blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 5
146
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 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
sequencelengths 1
16
| author_lines
sequencelengths 1
16
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2282802d840ac9a8360ada11458c6f5e421ac21b | 789bfae90cbb728db537b24eb9ab21c88bda2786 | /source/GameWonNotVisibleWaitStateClass.h | da89d3d3933f7e50b00594a9f1a91d6ffedc8428 | [
"MIT"
] | permissive | Izhido/bitsweeper | b89db2c2050cbc82ea60d31d2f31b041a1e913a3 | a37902c5b9ae9c25ee30694c2ba0974fd235090e | refs/heads/master | 2021-01-23T11:49:21.723909 | 2011-12-24T22:43:30 | 2011-12-24T22:43:30 | 34,614,275 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 455 | h | #ifndef GAMEWONNOTVISIBLEWAITSTATECLASS_H
#define GAMEWONNOTVISIBLEWAITSTATECLASS_H
#include "StateClass.h"
#define GAME_WON_NOT_VISIBLE_WAIT_STATE 33
class GameWonNotVisibleWaitStateClass
: public StateClass
{
public:
GameWonNotVisibleWaitStateClass();
void Start(class CommonDataClass* CommonData);
void Run(class CommonDataClass* CommonData);
void Draw(CommonDataClass* CommonData);
private:
int Count;
};
#endif
| [
"[email protected]@66f87ebb-1a6f-337b-3a26-6cadc16acdcf"
] | [
[
[
1,
25
]
]
] |
f62a2351c162461f4e8bebcc4711745aed708d97 | cd0987589d3815de1dea8529a7705caac479e7e9 | /webkit/WebKit/win/WebView.cpp | 4331147370abbdab49522ffd5b5dafe5514a162b | [
"BSD-2-Clause"
] | permissive | 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 | 209,901 | cpp | /*
* Copyright (C) 2006, 2007, 2008, 2009, 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 COMPUTER, INC. ``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 COMPUTER, INC. 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 "config.h"
#include "WebView.h"
#include "CFDictionaryPropertyBag.h"
#include "DOMCoreClasses.h"
#include "FullscreenVideoController.h"
#include "MarshallingHelpers.h"
#include "SoftLinking.h"
#include "WebBackForwardList.h"
#include "WebChromeClient.h"
#include "WebContextMenuClient.h"
#include "WebCoreTextRenderer.h"
#include "WebDatabaseManager.h"
#include "WebDocumentLoader.h"
#include "WebDownload.h"
#include "WebDragClient.h"
#include "WebEditorClient.h"
#include "WebElementPropertyBag.h"
#include "WebFrame.h"
#include "WebGeolocationControllerClient.h"
#include "WebGeolocationPosition.h"
#include "WebIconDatabase.h"
#include "WebInspector.h"
#include "WebInspectorClient.h"
#include "WebKit.h"
#include "WebKitDLL.h"
#include "WebKitLogging.h"
#include "WebKitStatisticsPrivate.h"
#include "WebKitSystemBits.h"
#include "WebMutableURLRequest.h"
#include "WebNotificationCenter.h"
#include "WebPlatformStrategies.h"
#include "WebPluginHalterClient.h"
#include "WebPreferences.h"
#include "WebScriptWorld.h"
#include "WindowsTouch.h"
#include <JavaScriptCore/APICast.h>
#include <JavaScriptCore/InitializeThreading.h>
#include <JavaScriptCore/JSLock.h>
#include <JavaScriptCore/JSValue.h>
#include <WebCore/AbstractDatabase.h>
#include <WebCore/AXObjectCache.h>
#include <WebCore/ApplicationCacheStorage.h>
#include <WebCore/BString.h>
#include <WebCore/BackForwardList.h>
#include <WebCore/BitmapInfo.h>
#include <WebCore/Cache.h>
#include <WebCore/Chrome.h>
#include <WebCore/ContextMenu.h>
#include <WebCore/ContextMenuController.h>
#include <WebCore/CookieStorageWin.h>
#include <WebCore/Cursor.h>
#include <WebCore/Document.h>
#include <WebCore/DragController.h>
#include <WebCore/DragData.h>
#include <WebCore/Editor.h>
#include <WebCore/EventHandler.h>
#include <WebCore/EventNames.h>
#include <WebCore/FileSystem.h>
#include <WebCore/FloatQuad.h>
#include <WebCore/FocusController.h>
#include <WebCore/FrameLoader.h>
#include <WebCore/FrameTree.h>
#include <WebCore/FrameView.h>
#include <WebCore/FrameWin.h>
#include <WebCore/GDIObjectCounter.h>
#include <WebCore/GraphicsContext.h>
#include <WebCore/HTMLMediaElement.h>
#include <WebCore/HTMLNames.h>
#include <WebCore/HistoryItem.h>
#include <WebCore/HitTestRequest.h>
#include <WebCore/HitTestResult.h>
#include <WebCore/IntRect.h>
#include <WebCore/JSElement.h>
#include <WebCore/KeyboardEvent.h>
#include <WebCore/Language.h>
#include <WebCore/Logging.h>
#include <WebCore/MIMETypeRegistry.h>
#include <WebCore/Page.h>
#include <WebCore/PageCache.h>
#include <WebCore/PageGroup.h>
#include <WebCore/PlatformKeyboardEvent.h>
#include <WebCore/PlatformMouseEvent.h>
#include <WebCore/PlatformWheelEvent.h>
#include <WebCore/PluginData.h>
#include <WebCore/PluginDatabase.h>
#include <WebCore/PluginView.h>
#include <WebCore/PopupMenu.h>
#include <WebCore/PopupMenuWin.h>
#include <WebCore/ProgressTracker.h>
#include <WebCore/RenderLayer.h>
#include <WebCore/RenderTheme.h>
#include <WebCore/RenderTreeAsText.h>
#include <WebCore/RenderView.h>
#include <WebCore/RenderWidget.h>
#include <WebCore/ResourceHandle.h>
#include <WebCore/ResourceHandleClient.h>
#include <WebCore/SchemeRegistry.h>
#include <WebCore/ScriptValue.h>
#include <WebCore/Scrollbar.h>
#include <WebCore/ScrollbarTheme.h>
#include <WebCore/SecurityOrigin.h>
#include <WebCore/SelectionController.h>
#include <WebCore/Settings.h>
#include <WebCore/SimpleFontData.h>
#include <WebCore/TypingCommand.h>
#include <WebCore/WindowMessageBroadcaster.h>
#include <wtf/Threading.h>
#if ENABLE(CLIENT_BASED_GEOLOCATION)
#include <WebCore/GeolocationController.h>
#include <WebCore/GeolocationError.h>
#endif
#if PLATFORM(CG)
#include <CoreGraphics/CGContext.h>
#endif
#if PLATFORM(CF)
#include <CoreFoundation/CoreFoundation.h>
#endif
#if USE(CFNETWORK)
#include <CFNetwork/CFURLCachePriv.h>
#include <CFNetwork/CFURLProtocolPriv.h>
#include <WebKitSystemInterface/WebKitSystemInterface.h>
#endif
#include <ShlObj.h>
#include <comutil.h>
#include <dimm.h>
#include <oleacc.h>
#include <tchar.h>
#include <windowsx.h>
#include <wtf/HashSet.h>
#include <wtf/text/CString.h>
// Soft link functions for gestures and panning feedback
SOFT_LINK_LIBRARY(USER32);
SOFT_LINK_OPTIONAL(USER32, GetGestureInfo, BOOL, WINAPI, (HGESTUREINFO, PGESTUREINFO));
SOFT_LINK_OPTIONAL(USER32, SetGestureConfig, BOOL, WINAPI, (HWND, DWORD, UINT, PGESTURECONFIG, UINT));
SOFT_LINK_OPTIONAL(USER32, CloseGestureInfoHandle, BOOL, WINAPI, (HGESTUREINFO));
SOFT_LINK_LIBRARY(Uxtheme);
SOFT_LINK_OPTIONAL(Uxtheme, BeginPanningFeedback, BOOL, WINAPI, (HWND));
SOFT_LINK_OPTIONAL(Uxtheme, EndPanningFeedback, BOOL, WINAPI, (HWND, BOOL));
SOFT_LINK_OPTIONAL(Uxtheme, UpdatePanningFeedback, BOOL, WINAPI, (HWND, LONG, LONG, BOOL));
using namespace WebCore;
using namespace std;
using JSC::JSLock;
static HMODULE accessibilityLib;
static HashSet<WebView*> pendingDeleteBackingStoreSet;
static String osVersion();
static String webKitVersion();
WebView* kit(Page* page)
{
return page ? static_cast<WebChromeClient*>(page->chrome()->client())->webView() : 0;
}
class PreferencesChangedOrRemovedObserver : public IWebNotificationObserver {
public:
static PreferencesChangedOrRemovedObserver* sharedInstance();
private:
PreferencesChangedOrRemovedObserver() {}
~PreferencesChangedOrRemovedObserver() {}
virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID, void**) { return E_FAIL; }
virtual ULONG STDMETHODCALLTYPE AddRef(void) { return 0; }
virtual ULONG STDMETHODCALLTYPE Release(void) { return 0; }
public:
// IWebNotificationObserver
virtual HRESULT STDMETHODCALLTYPE onNotify(
/* [in] */ IWebNotification* notification);
private:
HRESULT notifyPreferencesChanged(WebCacheModel);
HRESULT notifyPreferencesRemoved(WebCacheModel);
};
PreferencesChangedOrRemovedObserver* PreferencesChangedOrRemovedObserver::sharedInstance()
{
static PreferencesChangedOrRemovedObserver* shared = new PreferencesChangedOrRemovedObserver;
return shared;
}
HRESULT PreferencesChangedOrRemovedObserver::onNotify(IWebNotification* notification)
{
HRESULT hr = S_OK;
COMPtr<IUnknown> unkPrefs;
hr = notification->getObject(&unkPrefs);
if (FAILED(hr))
return hr;
COMPtr<IWebPreferences> preferences(Query, unkPrefs);
if (!preferences)
return E_NOINTERFACE;
WebCacheModel cacheModel;
hr = preferences->cacheModel(&cacheModel);
if (FAILED(hr))
return hr;
BSTR nameBSTR;
hr = notification->name(&nameBSTR);
if (FAILED(hr))
return hr;
BString name;
name.adoptBSTR(nameBSTR);
if (wcscmp(name, WebPreferences::webPreferencesChangedNotification()) == 0)
return notifyPreferencesChanged(cacheModel);
if (wcscmp(name, WebPreferences::webPreferencesRemovedNotification()) == 0)
return notifyPreferencesRemoved(cacheModel);
ASSERT_NOT_REACHED();
return E_FAIL;
}
HRESULT PreferencesChangedOrRemovedObserver::notifyPreferencesChanged(WebCacheModel cacheModel)
{
HRESULT hr = S_OK;
if (!WebView::didSetCacheModel() || cacheModel > WebView::cacheModel())
WebView::setCacheModel(cacheModel);
else if (cacheModel < WebView::cacheModel()) {
WebCacheModel sharedPreferencesCacheModel;
hr = WebPreferences::sharedStandardPreferences()->cacheModel(&sharedPreferencesCacheModel);
if (FAILED(hr))
return hr;
WebView::setCacheModel(max(sharedPreferencesCacheModel, WebView::maxCacheModelInAnyInstance()));
}
return hr;
}
HRESULT PreferencesChangedOrRemovedObserver::notifyPreferencesRemoved(WebCacheModel cacheModel)
{
HRESULT hr = S_OK;
if (cacheModel == WebView::cacheModel()) {
WebCacheModel sharedPreferencesCacheModel;
hr = WebPreferences::sharedStandardPreferences()->cacheModel(&sharedPreferencesCacheModel);
if (FAILED(hr))
return hr;
WebView::setCacheModel(max(sharedPreferencesCacheModel, WebView::maxCacheModelInAnyInstance()));
}
return hr;
}
const LPCWSTR kWebViewWindowClassName = L"WebViewWindowClass";
const int WM_XP_THEMECHANGED = 0x031A;
const int WM_VISTA_MOUSEHWHEEL = 0x020E;
static const int maxToolTipWidth = 250;
static const int delayBeforeDeletingBackingStoreMsec = 5000;
static ATOM registerWebView();
static void initializeStaticObservers();
static HRESULT updateSharedSettingsFromPreferencesIfNeeded(IWebPreferences*);
HRESULT createMatchEnumerator(Vector<IntRect>* rects, IEnumTextMatches** matches);
static bool continuousSpellCheckingEnabled;
static bool grammarCheckingEnabled;
static bool s_didSetCacheModel;
static WebCacheModel s_cacheModel = WebCacheModelDocumentViewer;
enum {
UpdateActiveStateTimer = 1,
DeleteBackingStoreTimer = 2,
};
// WebView ----------------------------------------------------------------
bool WebView::s_allowSiteSpecificHacks = false;
WebView::WebView()
: m_refCount(0)
#if !ASSERT_DISABLED
, m_deletionHasBegun(false)
#endif
, m_hostWindow(0)
, m_viewWindow(0)
, m_mainFrame(0)
, m_page(0)
, m_hasCustomDropTarget(false)
, m_useBackForwardList(true)
, m_userAgentOverridden(false)
, m_zoomMultiplier(1.0f)
, m_zoomsTextOnly(false)
, m_mouseActivated(false)
, m_dragData(0)
, m_currentCharacterCode(0)
, m_isBeingDestroyed(false)
, m_paintCount(0)
, m_hasSpellCheckerDocumentTag(false)
, m_smartInsertDeleteEnabled(false)
, m_didClose(false)
, m_inIMEComposition(0)
, m_toolTipHwnd(0)
, m_closeWindowTimer(0)
, m_topLevelParent(0)
, m_deleteBackingStoreTimerActive(false)
, m_transparent(false)
, m_selectTrailingWhitespaceEnabled(false)
, m_lastPanX(0)
, m_lastPanY(0)
, m_xOverpan(0)
, m_yOverpan(0)
#if USE(ACCELERATED_COMPOSITING)
, m_isAcceleratedCompositing(false)
#endif
, m_nextDisplayIsSynchronous(false)
, m_lastSetCursor(0)
{
JSC::initializeThreading();
WTF::initializeMainThread();
m_backingStoreSize.cx = m_backingStoreSize.cy = 0;
CoCreateInstance(CLSID_DragDropHelper, 0, CLSCTX_INPROC_SERVER, IID_IDropTargetHelper,(void**)&m_dropTargetHelper);
initializeStaticObservers();
WebPreferences* sharedPreferences = WebPreferences::sharedStandardPreferences();
BOOL enabled;
if (SUCCEEDED(sharedPreferences->continuousSpellCheckingEnabled(&enabled)))
continuousSpellCheckingEnabled = !!enabled;
if (SUCCEEDED(sharedPreferences->grammarCheckingEnabled(&enabled)))
grammarCheckingEnabled = !!enabled;
WebViewCount++;
gClassCount++;
gClassNameCount.add("WebView");
}
WebView::~WebView()
{
deleteBackingStore();
// the tooltip window needs to be explicitly destroyed since it isn't a WS_CHILD
if (::IsWindow(m_toolTipHwnd))
::DestroyWindow(m_toolTipHwnd);
ASSERT(!m_page);
ASSERT(!m_preferences);
ASSERT(!m_viewWindow);
WebViewCount--;
gClassCount--;
gClassNameCount.remove("WebView");
}
WebView* WebView::createInstance()
{
WebView* instance = new WebView();
instance->AddRef();
return instance;
}
void initializeStaticObservers()
{
static bool initialized;
if (initialized)
return;
initialized = true;
IWebNotificationCenter* notifyCenter = WebNotificationCenter::defaultCenterInternal();
notifyCenter->addObserver(PreferencesChangedOrRemovedObserver::sharedInstance(), WebPreferences::webPreferencesChangedNotification(), 0);
notifyCenter->addObserver(PreferencesChangedOrRemovedObserver::sharedInstance(), WebPreferences::webPreferencesRemovedNotification(), 0);
}
static HashSet<WebView*>& allWebViewsSet()
{
static HashSet<WebView*> allWebViewsSet;
return allWebViewsSet;
}
void WebView::addToAllWebViewsSet()
{
allWebViewsSet().add(this);
}
void WebView::removeFromAllWebViewsSet()
{
allWebViewsSet().remove(this);
}
void WebView::setCacheModel(WebCacheModel cacheModel)
{
#if USE(CFNETWORK)
if (s_didSetCacheModel && cacheModel == s_cacheModel)
return;
RetainPtr<CFURLCacheRef> cfurlCache(AdoptCF, CFURLCacheCopySharedURLCache());
RetainPtr<CFStringRef> cfurlCacheDirectory(AdoptCF, wkCopyFoundationCacheDirectory());
if (!cfurlCacheDirectory)
cfurlCacheDirectory.adoptCF(WebCore::localUserSpecificStorageDirectory().createCFString());
// As a fudge factor, use 1000 instead of 1024, in case the reported byte
// count doesn't align exactly to a megabyte boundary.
unsigned long long memSize = WebMemorySize() / 1024 / 1000;
unsigned long long diskFreeSize = WebVolumeFreeSize(cfurlCacheDirectory.get()) / 1024 / 1000;
unsigned cacheTotalCapacity = 0;
unsigned cacheMinDeadCapacity = 0;
unsigned cacheMaxDeadCapacity = 0;
double deadDecodedDataDeletionInterval = 0;
unsigned pageCacheCapacity = 0;
CFIndex cfurlCacheMemoryCapacity = 0;
CFIndex cfurlCacheDiskCapacity = 0;
switch (cacheModel) {
case WebCacheModelDocumentViewer: {
// Page cache capacity (in pages)
pageCacheCapacity = 0;
// Object cache capacities (in bytes)
if (memSize >= 2048)
cacheTotalCapacity = 96 * 1024 * 1024;
else if (memSize >= 1536)
cacheTotalCapacity = 64 * 1024 * 1024;
else if (memSize >= 1024)
cacheTotalCapacity = 32 * 1024 * 1024;
else if (memSize >= 512)
cacheTotalCapacity = 16 * 1024 * 1024;
cacheMinDeadCapacity = 0;
cacheMaxDeadCapacity = 0;
// Foundation memory cache capacity (in bytes)
cfurlCacheMemoryCapacity = 0;
// Foundation disk cache capacity (in bytes)
cfurlCacheDiskCapacity = CFURLCacheDiskCapacity(cfurlCache.get());
break;
}
case WebCacheModelDocumentBrowser: {
// Page cache capacity (in pages)
if (memSize >= 1024)
pageCacheCapacity = 3;
else if (memSize >= 512)
pageCacheCapacity = 2;
else if (memSize >= 256)
pageCacheCapacity = 1;
else
pageCacheCapacity = 0;
// Object cache capacities (in bytes)
if (memSize >= 2048)
cacheTotalCapacity = 96 * 1024 * 1024;
else if (memSize >= 1536)
cacheTotalCapacity = 64 * 1024 * 1024;
else if (memSize >= 1024)
cacheTotalCapacity = 32 * 1024 * 1024;
else if (memSize >= 512)
cacheTotalCapacity = 16 * 1024 * 1024;
cacheMinDeadCapacity = cacheTotalCapacity / 8;
cacheMaxDeadCapacity = cacheTotalCapacity / 4;
// Foundation memory cache capacity (in bytes)
if (memSize >= 2048)
cfurlCacheMemoryCapacity = 4 * 1024 * 1024;
else if (memSize >= 1024)
cfurlCacheMemoryCapacity = 2 * 1024 * 1024;
else if (memSize >= 512)
cfurlCacheMemoryCapacity = 1 * 1024 * 1024;
else
cfurlCacheMemoryCapacity = 512 * 1024;
// Foundation disk cache capacity (in bytes)
if (diskFreeSize >= 16384)
cfurlCacheDiskCapacity = 50 * 1024 * 1024;
else if (diskFreeSize >= 8192)
cfurlCacheDiskCapacity = 40 * 1024 * 1024;
else if (diskFreeSize >= 4096)
cfurlCacheDiskCapacity = 30 * 1024 * 1024;
else
cfurlCacheDiskCapacity = 20 * 1024 * 1024;
break;
}
case WebCacheModelPrimaryWebBrowser: {
// Page cache capacity (in pages)
// (Research indicates that value / page drops substantially after 3 pages.)
if (memSize >= 2048)
pageCacheCapacity = 5;
else if (memSize >= 1024)
pageCacheCapacity = 4;
else if (memSize >= 512)
pageCacheCapacity = 3;
else if (memSize >= 256)
pageCacheCapacity = 2;
else
pageCacheCapacity = 1;
// Object cache capacities (in bytes)
// (Testing indicates that value / MB depends heavily on content and
// browsing pattern. Even growth above 128MB can have substantial
// value / MB for some content / browsing patterns.)
if (memSize >= 2048)
cacheTotalCapacity = 128 * 1024 * 1024;
else if (memSize >= 1536)
cacheTotalCapacity = 96 * 1024 * 1024;
else if (memSize >= 1024)
cacheTotalCapacity = 64 * 1024 * 1024;
else if (memSize >= 512)
cacheTotalCapacity = 32 * 1024 * 1024;
cacheMinDeadCapacity = cacheTotalCapacity / 4;
cacheMaxDeadCapacity = cacheTotalCapacity / 2;
// This code is here to avoid a PLT regression. We can remove it if we
// can prove that the overall system gain would justify the regression.
cacheMaxDeadCapacity = max(24u, cacheMaxDeadCapacity);
deadDecodedDataDeletionInterval = 60;
// Foundation memory cache capacity (in bytes)
// (These values are small because WebCore does most caching itself.)
if (memSize >= 1024)
cfurlCacheMemoryCapacity = 4 * 1024 * 1024;
else if (memSize >= 512)
cfurlCacheMemoryCapacity = 2 * 1024 * 1024;
else if (memSize >= 256)
cfurlCacheMemoryCapacity = 1 * 1024 * 1024;
else
cfurlCacheMemoryCapacity = 512 * 1024;
// Foundation disk cache capacity (in bytes)
if (diskFreeSize >= 16384)
cfurlCacheDiskCapacity = 175 * 1024 * 1024;
else if (diskFreeSize >= 8192)
cfurlCacheDiskCapacity = 150 * 1024 * 1024;
else if (diskFreeSize >= 4096)
cfurlCacheDiskCapacity = 125 * 1024 * 1024;
else if (diskFreeSize >= 2048)
cfurlCacheDiskCapacity = 100 * 1024 * 1024;
else if (diskFreeSize >= 1024)
cfurlCacheDiskCapacity = 75 * 1024 * 1024;
else
cfurlCacheDiskCapacity = 50 * 1024 * 1024;
break;
}
default:
ASSERT_NOT_REACHED();
}
// Don't shrink a big disk cache, since that would cause churn.
cfurlCacheDiskCapacity = max(cfurlCacheDiskCapacity, CFURLCacheDiskCapacity(cfurlCache.get()));
cache()->setCapacities(cacheMinDeadCapacity, cacheMaxDeadCapacity, cacheTotalCapacity);
cache()->setDeadDecodedDataDeletionInterval(deadDecodedDataDeletionInterval);
pageCache()->setCapacity(pageCacheCapacity);
CFURLCacheSetMemoryCapacity(cfurlCache.get(), cfurlCacheMemoryCapacity);
CFURLCacheSetDiskCapacity(cfurlCache.get(), cfurlCacheDiskCapacity);
s_didSetCacheModel = true;
s_cacheModel = cacheModel;
return;
#endif
}
WebCacheModel WebView::cacheModel()
{
return s_cacheModel;
}
bool WebView::didSetCacheModel()
{
return s_didSetCacheModel;
}
WebCacheModel WebView::maxCacheModelInAnyInstance()
{
WebCacheModel cacheModel = WebCacheModelDocumentViewer;
HashSet<WebView*>::iterator end = allWebViewsSet().end();
for (HashSet<WebView*>::iterator it = allWebViewsSet().begin(); it != end; ++it) {
COMPtr<IWebPreferences> pref;
if (FAILED((*it)->preferences(&pref)))
continue;
WebCacheModel prefCacheModel = WebCacheModelDocumentViewer;
if (FAILED(pref->cacheModel(&prefCacheModel)))
continue;
cacheModel = max(cacheModel, prefCacheModel);
}
return cacheModel;
}
HRESULT STDMETHODCALLTYPE WebView::close()
{
if (m_didClose)
return S_OK;
m_didClose = true;
#if USE(ACCELERATED_COMPOSITING)
setAcceleratedCompositing(false);
#endif
WebNotificationCenter::defaultCenterInternal()->postNotificationName(_bstr_t(WebViewWillCloseNotification).GetBSTR(), static_cast<IWebView*>(this), 0);
if (m_uiDelegatePrivate)
m_uiDelegatePrivate->webViewClosing(this);
removeFromAllWebViewsSet();
if (m_page) {
if (Frame* frame = m_page->mainFrame())
frame->loader()->detachFromParent();
}
if (m_mouseOutTracker) {
m_mouseOutTracker->dwFlags = TME_CANCEL;
::TrackMouseEvent(m_mouseOutTracker.get());
m_mouseOutTracker.set(0);
}
revokeDragDrop();
if (m_viewWindow) {
// We can't check IsWindow(m_viewWindow) here, because that will return true even while
// we're already handling WM_DESTROY. So we check !isBeingDestroyed() instead.
if (!isBeingDestroyed())
DestroyWindow(m_viewWindow);
// Either we just destroyed m_viewWindow, or it's in the process of being destroyed. Either
// way, we clear it out to make sure we don't try to use it later.
m_viewWindow = 0;
}
setHostWindow(0);
setDownloadDelegate(0);
setEditingDelegate(0);
setFrameLoadDelegate(0);
setFrameLoadDelegatePrivate(0);
setHistoryDelegate(0);
setPolicyDelegate(0);
setResourceLoadDelegate(0);
setUIDelegate(0);
setFormDelegate(0);
setPluginHalterDelegate(0);
if (m_webInspector)
m_webInspector->webViewClosed();
delete m_page;
m_page = 0;
registerForIconNotification(false);
IWebNotificationCenter* notifyCenter = WebNotificationCenter::defaultCenterInternal();
notifyCenter->removeObserver(this, WebPreferences::webPreferencesChangedNotification(), static_cast<IWebPreferences*>(m_preferences.get()));
if (COMPtr<WebPreferences> preferences = m_preferences) {
BSTR identifier = 0;
preferences->identifier(&identifier);
m_preferences = 0;
preferences->didRemoveFromWebView();
// Make sure we release the reference, since WebPreferences::removeReferenceForIdentifier will check for last reference to WebPreferences
preferences = 0;
if (identifier) {
WebPreferences::removeReferenceForIdentifier(identifier);
SysFreeString(identifier);
}
}
deleteBackingStore();
return S_OK;
}
void WebView::repaint(const WebCore::IntRect& windowRect, bool contentChanged, bool immediate, bool repaintContentOnly)
{
#if USE(ACCELERATED_COMPOSITING)
if (isAcceleratedCompositing())
setRootLayerNeedsDisplay();
#endif
if (!repaintContentOnly) {
RECT rect = windowRect;
::InvalidateRect(m_viewWindow, &rect, false);
}
if (contentChanged)
addToDirtyRegion(windowRect);
if (immediate) {
if (repaintContentOnly)
updateBackingStore(core(topLevelFrame())->view());
else
::UpdateWindow(m_viewWindow);
}
}
void WebView::deleteBackingStore()
{
pendingDeleteBackingStoreSet.remove(this);
if (m_deleteBackingStoreTimerActive) {
KillTimer(m_viewWindow, DeleteBackingStoreTimer);
m_deleteBackingStoreTimerActive = false;
}
m_backingStoreBitmap.clear();
m_backingStoreDirtyRegion.clear();
#if USE(ACCELERATED_COMPOSITING)
if (m_layerRenderer)
m_layerRenderer->setBackingStoreDirty(false);
#endif
m_backingStoreSize.cx = m_backingStoreSize.cy = 0;
}
bool WebView::ensureBackingStore()
{
RECT windowRect;
::GetClientRect(m_viewWindow, &windowRect);
LONG width = windowRect.right - windowRect.left;
LONG height = windowRect.bottom - windowRect.top;
if (width > 0 && height > 0 && (width != m_backingStoreSize.cx || height != m_backingStoreSize.cy)) {
deleteBackingStore();
m_backingStoreSize.cx = width;
m_backingStoreSize.cy = height;
BitmapInfo bitmapInfo = BitmapInfo::createBottomUp(IntSize(m_backingStoreSize));
void* pixels = NULL;
m_backingStoreBitmap = RefCountedHBITMAP::create(::CreateDIBSection(0, &bitmapInfo, DIB_RGB_COLORS, &pixels, 0, 0));
return true;
}
return false;
}
void WebView::addToDirtyRegion(const IntRect& dirtyRect)
{
// FIXME: We want an assert here saying that the dirtyRect is inside the clienRect,
// but it was being hit during our layout tests, and is being investigated in
// http://webkit.org/b/29350.
HRGN newRegion = ::CreateRectRgn(dirtyRect.x(), dirtyRect.y(),
dirtyRect.right(), dirtyRect.bottom());
addToDirtyRegion(newRegion);
}
void WebView::addToDirtyRegion(HRGN newRegion)
{
LOCAL_GDI_COUNTER(0, __FUNCTION__);
if (m_backingStoreDirtyRegion) {
HRGN combinedRegion = ::CreateRectRgn(0,0,0,0);
::CombineRgn(combinedRegion, m_backingStoreDirtyRegion->handle(), newRegion, RGN_OR);
::DeleteObject(newRegion);
m_backingStoreDirtyRegion = RefCountedHRGN::create(combinedRegion);
} else
m_backingStoreDirtyRegion = RefCountedHRGN::create(newRegion);
#if USE(ACCELERATED_COMPOSITING)
if (m_layerRenderer)
m_layerRenderer->setBackingStoreDirty(true);
#endif
if (m_uiDelegatePrivate)
m_uiDelegatePrivate->webViewDidInvalidate(this);
}
void WebView::scrollBackingStore(FrameView* frameView, int dx, int dy, const IntRect& scrollViewRect, const IntRect& clipRect)
{
LOCAL_GDI_COUNTER(0, __FUNCTION__);
// If there's no backing store we don't need to update it
if (!m_backingStoreBitmap) {
if (m_uiDelegatePrivate)
m_uiDelegatePrivate->webViewScrolled(this);
return;
}
// Make a region to hold the invalidated scroll area.
HRGN updateRegion = ::CreateRectRgn(0, 0, 0, 0);
// Collect our device context info and select the bitmap to scroll.
HDC windowDC = ::GetDC(m_viewWindow);
HDC bitmapDC = ::CreateCompatibleDC(windowDC);
HGDIOBJ oldBitmap = ::SelectObject(bitmapDC, m_backingStoreBitmap->handle());
// Scroll the bitmap.
RECT scrollRectWin(scrollViewRect);
RECT clipRectWin(clipRect);
::ScrollDC(bitmapDC, dx, dy, &scrollRectWin, &clipRectWin, updateRegion, 0);
RECT regionBox;
::GetRgnBox(updateRegion, ®ionBox);
// Flush.
GdiFlush();
// Add the dirty region to the backing store's dirty region.
addToDirtyRegion(updateRegion);
if (m_uiDelegatePrivate)
m_uiDelegatePrivate->webViewScrolled(this);
// Update the backing store.
updateBackingStore(frameView, bitmapDC, false);
// Clean up.
::SelectObject(bitmapDC, oldBitmap);
::DeleteDC(bitmapDC);
::ReleaseDC(m_viewWindow, windowDC);
}
// This emulates the Mac smarts for painting rects intelligently. This is very
// important for us, since we double buffer based off dirty rects.
static void getUpdateRects(HRGN region, const IntRect& dirtyRect, Vector<IntRect>& rects)
{
ASSERT_ARG(region, region);
const int cRectThreshold = 10;
const float cWastedSpaceThreshold = 0.75f;
rects.clear();
DWORD regionDataSize = GetRegionData(region, sizeof(RGNDATA), NULL);
if (!regionDataSize) {
rects.append(dirtyRect);
return;
}
Vector<unsigned char> buffer(regionDataSize);
RGNDATA* regionData = reinterpret_cast<RGNDATA*>(buffer.data());
GetRegionData(region, regionDataSize, regionData);
if (regionData->rdh.nCount > cRectThreshold) {
rects.append(dirtyRect);
return;
}
double singlePixels = 0.0;
unsigned i;
RECT* rect;
for (i = 0, rect = reinterpret_cast<RECT*>(regionData->Buffer); i < regionData->rdh.nCount; i++, rect++)
singlePixels += (rect->right - rect->left) * (rect->bottom - rect->top);
double unionPixels = dirtyRect.width() * dirtyRect.height();
double wastedSpace = 1.0 - (singlePixels / unionPixels);
if (wastedSpace <= cWastedSpaceThreshold) {
rects.append(dirtyRect);
return;
}
for (i = 0, rect = reinterpret_cast<RECT*>(regionData->Buffer); i < regionData->rdh.nCount; i++, rect++)
rects.append(*rect);
}
void WebView::updateBackingStore(FrameView* frameView, HDC dc, bool backingStoreCompletelyDirty, WindowsToPaint windowsToPaint)
{
LOCAL_GDI_COUNTER(0, __FUNCTION__);
HDC windowDC = 0;
HDC bitmapDC = dc;
if (!dc) {
windowDC = ::GetDC(m_viewWindow);
bitmapDC = ::CreateCompatibleDC(windowDC);
::SelectObject(bitmapDC, m_backingStoreBitmap->handle());
}
if (m_backingStoreBitmap && (m_backingStoreDirtyRegion || backingStoreCompletelyDirty)) {
// Do a layout first so that everything we render to the backing store is always current.
if (Frame* coreFrame = core(m_mainFrame))
if (FrameView* view = coreFrame->view())
view->updateLayoutAndStyleIfNeededRecursive();
Vector<IntRect> paintRects;
if (!backingStoreCompletelyDirty && m_backingStoreDirtyRegion) {
RECT regionBox;
::GetRgnBox(m_backingStoreDirtyRegion->handle(), ®ionBox);
getUpdateRects(m_backingStoreDirtyRegion->handle(), regionBox, paintRects);
} else {
RECT clientRect;
::GetClientRect(m_viewWindow, &clientRect);
paintRects.append(clientRect);
}
for (unsigned i = 0; i < paintRects.size(); ++i)
paintIntoBackingStore(frameView, bitmapDC, paintRects[i], windowsToPaint);
if (m_uiDelegatePrivate)
m_uiDelegatePrivate->webViewPainted(this);
m_backingStoreDirtyRegion.clear();
#if USE(ACCELERATED_COMPOSITING)
if (m_layerRenderer)
m_layerRenderer->setBackingStoreDirty(false);
#endif
}
if (!dc) {
::DeleteDC(bitmapDC);
::ReleaseDC(m_viewWindow, windowDC);
}
GdiFlush();
}
void WebView::paint(HDC dc, LPARAM options)
{
LOCAL_GDI_COUNTER(0, __FUNCTION__);
Frame* coreFrame = core(m_mainFrame);
if (!coreFrame)
return;
FrameView* frameView = coreFrame->view();
RECT rcPaint;
HDC hdc;
OwnPtr<HRGN> region;
int regionType = NULLREGION;
PAINTSTRUCT ps;
WindowsToPaint windowsToPaint;
if (!dc) {
region.set(CreateRectRgn(0,0,0,0));
regionType = GetUpdateRgn(m_viewWindow, region.get(), false);
hdc = BeginPaint(m_viewWindow, &ps);
rcPaint = ps.rcPaint;
// We're painting to the screen, and our child windows can handle
// painting themselves to the screen.
windowsToPaint = PaintWebViewOnly;
} else {
hdc = dc;
::GetClientRect(m_viewWindow, &rcPaint);
if (options & PRF_ERASEBKGND)
::FillRect(hdc, &rcPaint, (HBRUSH)GetStockObject(WHITE_BRUSH));
// Since we aren't painting to the screen, we want to paint all our
// children into the HDC.
windowsToPaint = PaintWebViewAndChildren;
}
bool backingStoreCompletelyDirty = ensureBackingStore();
if (!m_backingStoreBitmap) {
if (!dc)
EndPaint(m_viewWindow, &ps);
return;
}
m_paintCount++;
HDC bitmapDC = ::CreateCompatibleDC(hdc);
HGDIOBJ oldBitmap = ::SelectObject(bitmapDC, m_backingStoreBitmap->handle());
// Update our backing store if needed.
updateBackingStore(frameView, bitmapDC, backingStoreCompletelyDirty, windowsToPaint);
#if USE(ACCELERATED_COMPOSITING)
if (!isAcceleratedCompositing()) {
#endif
// Now we blit the updated backing store
IntRect windowDirtyRect = rcPaint;
// Apply the same heuristic for this update region too.
Vector<IntRect> blitRects;
if (region && regionType == COMPLEXREGION)
getUpdateRects(region.get(), windowDirtyRect, blitRects);
else
blitRects.append(windowDirtyRect);
for (unsigned i = 0; i < blitRects.size(); ++i)
paintIntoWindow(bitmapDC, hdc, blitRects[i]);
#if USE(ACCELERATED_COMPOSITING)
} else
updateRootLayerContents();
#endif
::SelectObject(bitmapDC, oldBitmap);
::DeleteDC(bitmapDC);
if (!dc)
EndPaint(m_viewWindow, &ps);
m_paintCount--;
if (active())
cancelDeleteBackingStoreSoon();
else
deleteBackingStoreSoon();
}
void WebView::paintIntoBackingStore(FrameView* frameView, HDC bitmapDC, const IntRect& dirtyRect, WindowsToPaint windowsToPaint)
{
LOCAL_GDI_COUNTER(0, __FUNCTION__);
// FIXME: We want an assert here saying that the dirtyRect is inside the clienRect,
// but it was being hit during our layout tests, and is being investigated in
// http://webkit.org/b/29350.
RECT rect = dirtyRect;
#if FLASH_BACKING_STORE_REDRAW
HDC dc = ::GetDC(m_viewWindow);
OwnPtr<HBRUSH> yellowBrush(CreateSolidBrush(RGB(255, 255, 0)));
FillRect(dc, &rect, yellowBrush.get());
GdiFlush();
Sleep(50);
paintIntoWindow(bitmapDC, dc, dirtyRect);
::ReleaseDC(m_viewWindow, dc);
#endif
GraphicsContext gc(bitmapDC, m_transparent);
gc.setShouldIncludeChildWindows(windowsToPaint == PaintWebViewAndChildren);
gc.save();
if (m_transparent)
gc.clearRect(dirtyRect);
else
FillRect(bitmapDC, &rect, (HBRUSH)GetStockObject(WHITE_BRUSH));
COMPtr<IWebUIDelegatePrivate2> uiPrivate(Query, m_uiDelegate);
if (uiPrivate)
uiPrivate->drawBackground(this, reinterpret_cast<OLE_HANDLE>(bitmapDC), &rect);
if (frameView && frameView->frame() && frameView->frame()->contentRenderer()) {
gc.clip(dirtyRect);
frameView->paint(&gc, dirtyRect);
}
gc.restore();
}
void WebView::paintIntoWindow(HDC bitmapDC, HDC windowDC, const IntRect& dirtyRect)
{
LOCAL_GDI_COUNTER(0, __FUNCTION__);
#if FLASH_WINDOW_REDRAW
OwnPtr<HBRUSH> greenBrush = CreateSolidBrush(RGB(0, 255, 0));
RECT rect = dirtyRect;
FillRect(windowDC, &rect, greenBrush.get());
GdiFlush();
Sleep(50);
#endif
// Blit the dirty rect from the backing store into the same position
// in the destination DC.
BitBlt(windowDC, dirtyRect.x(), dirtyRect.y(), dirtyRect.width(), dirtyRect.height(), bitmapDC,
dirtyRect.x(), dirtyRect.y(), SRCCOPY);
}
void WebView::frameRect(RECT* rect)
{
::GetWindowRect(m_viewWindow, rect);
}
class WindowCloseTimer : public WebCore::SuspendableTimer {
public:
static WindowCloseTimer* create(WebView*);
private:
WindowCloseTimer(ScriptExecutionContext*, WebView*);
virtual void contextDestroyed();
virtual void fired();
WebView* m_webView;
};
WindowCloseTimer* WindowCloseTimer::create(WebView* webView)
{
ASSERT_ARG(webView, webView);
Frame* frame = core(webView->topLevelFrame());
ASSERT(frame);
if (!frame)
return 0;
Document* document = frame->document();
ASSERT(document);
if (!document)
return 0;
return new WindowCloseTimer(document, webView);
}
WindowCloseTimer::WindowCloseTimer(ScriptExecutionContext* context, WebView* webView)
: SuspendableTimer(context)
, m_webView(webView)
{
ASSERT_ARG(context, context);
ASSERT_ARG(webView, webView);
}
void WindowCloseTimer::contextDestroyed()
{
SuspendableTimer::contextDestroyed();
delete this;
}
void WindowCloseTimer::fired()
{
m_webView->closeWindowTimerFired();
}
void WebView::closeWindowSoon()
{
if (m_closeWindowTimer)
return;
m_closeWindowTimer = WindowCloseTimer::create(this);
if (!m_closeWindowTimer)
return;
m_closeWindowTimer->startOneShot(0);
AddRef();
}
void WebView::closeWindowTimerFired()
{
closeWindow();
Release();
}
void WebView::closeWindow()
{
if (m_hasSpellCheckerDocumentTag) {
if (m_editingDelegate)
m_editingDelegate->closeSpellDocument(this);
m_hasSpellCheckerDocumentTag = false;
}
COMPtr<IWebUIDelegate> ui;
if (SUCCEEDED(uiDelegate(&ui)))
ui->webViewClose(this);
}
bool WebView::canHandleRequest(const WebCore::ResourceRequest& request)
{
// On the mac there's an about url protocol implementation but CFNetwork doesn't have that.
if (equalIgnoringCase(String(request.url().protocol()), "about"))
return true;
#if USE(CFNETWORK)
if (CFURLProtocolCanHandleRequest(request.cfURLRequest()))
return true;
// FIXME: Mac WebKit calls _representationExistsForURLScheme here
return false;
#else
return true;
#endif
}
String WebView::standardUserAgentWithApplicationName(const String& applicationName)
{
return String::format("Mozilla/5.0 (Windows; U; %s; %s) AppleWebKit/%s (KHTML, like Gecko)%s%s", osVersion().latin1().data(), defaultLanguage().latin1().data(), webKitVersion().latin1().data(), (applicationName.length() ? " " : ""), applicationName.latin1().data());
}
Page* WebView::page()
{
return m_page;
}
bool WebView::handleContextMenuEvent(WPARAM wParam, LPARAM lParam)
{
// Translate the screen coordinates into window coordinates
POINT coords = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
if (coords.x == -1 || coords.y == -1) {
// The contextMenuController() holds onto the last context menu that was popped up on the
// page until a new one is created. We need to clear this menu before propagating the event
// through the DOM so that we can detect if we create a new menu for this event, since we
// won't create a new menu if the DOM swallows the event and the defaultEventHandler does
// not run.
m_page->contextMenuController()->clearContextMenu();
Frame* focusedFrame = m_page->focusController()->focusedOrMainFrame();
return focusedFrame->eventHandler()->sendContextMenuEventForKey();
} else {
if (!::ScreenToClient(m_viewWindow, &coords))
return false;
}
lParam = MAKELPARAM(coords.x, coords.y);
m_page->contextMenuController()->clearContextMenu();
IntPoint documentPoint(m_page->mainFrame()->view()->windowToContents(coords));
HitTestResult result = m_page->mainFrame()->eventHandler()->hitTestResultAtPoint(documentPoint, false);
Frame* targetFrame = result.innerNonSharedNode() ? result.innerNonSharedNode()->document()->frame() : m_page->focusController()->focusedOrMainFrame();
targetFrame->view()->setCursor(pointerCursor());
PlatformMouseEvent mouseEvent(m_viewWindow, WM_RBUTTONUP, wParam, lParam);
bool handledEvent = targetFrame->eventHandler()->sendContextMenuEvent(mouseEvent);
if (!handledEvent)
return false;
// Show the menu
ContextMenu* coreMenu = m_page->contextMenuController()->contextMenu();
if (!coreMenu)
return false;
Node* node = coreMenu->hitTestResult().innerNonSharedNode();
if (!node)
return false;
Frame* frame = node->document()->frame();
if (!frame)
return false;
FrameView* view = frame->view();
if (!view)
return false;
POINT point(view->contentsToWindow(coreMenu->hitTestResult().point()));
// Translate the point to screen coordinates
if (!::ClientToScreen(m_viewWindow, &point))
return false;
BOOL hasCustomMenus = false;
if (m_uiDelegate)
m_uiDelegate->hasCustomMenuImplementation(&hasCustomMenus);
if (hasCustomMenus)
m_uiDelegate->trackCustomPopupMenu((IWebView*)this, (OLE_HANDLE)(ULONG64)coreMenu->platformDescription(), &point);
else {
// Surprisingly, TPM_RIGHTBUTTON means that items are selectable with either the right OR left mouse button
UINT flags = TPM_RIGHTBUTTON | TPM_TOPALIGN | TPM_VERPOSANIMATION | TPM_HORIZONTAL
| TPM_LEFTALIGN | TPM_HORPOSANIMATION;
::TrackPopupMenuEx(coreMenu->platformDescription(), flags, point.x, point.y, m_viewWindow, 0);
}
return true;
}
bool WebView::onMeasureItem(WPARAM /*wParam*/, LPARAM lParam)
{
if (!m_uiDelegate)
return false;
BOOL hasCustomMenus = false;
m_uiDelegate->hasCustomMenuImplementation(&hasCustomMenus);
if (!hasCustomMenus)
return false;
m_uiDelegate->measureCustomMenuItem((IWebView*)this, (void*)lParam);
return true;
}
bool WebView::onDrawItem(WPARAM /*wParam*/, LPARAM lParam)
{
if (!m_uiDelegate)
return false;
BOOL hasCustomMenus = false;
m_uiDelegate->hasCustomMenuImplementation(&hasCustomMenus);
if (!hasCustomMenus)
return false;
m_uiDelegate->drawCustomMenuItem((IWebView*)this, (void*)lParam);
return true;
}
bool WebView::onInitMenuPopup(WPARAM wParam, LPARAM /*lParam*/)
{
if (!m_uiDelegate)
return false;
HMENU menu = (HMENU)wParam;
if (!menu)
return false;
BOOL hasCustomMenus = false;
m_uiDelegate->hasCustomMenuImplementation(&hasCustomMenus);
if (!hasCustomMenus)
return false;
m_uiDelegate->addCustomMenuDrawingData((IWebView*)this, (OLE_HANDLE)(ULONG64)menu);
return true;
}
bool WebView::onUninitMenuPopup(WPARAM wParam, LPARAM /*lParam*/)
{
if (!m_uiDelegate)
return false;
HMENU menu = (HMENU)wParam;
if (!menu)
return false;
BOOL hasCustomMenus = false;
m_uiDelegate->hasCustomMenuImplementation(&hasCustomMenus);
if (!hasCustomMenus)
return false;
m_uiDelegate->cleanUpCustomMenuDrawingData((IWebView*)this, (OLE_HANDLE)(ULONG64)menu);
return true;
}
void WebView::performContextMenuAction(WPARAM wParam, LPARAM lParam, bool byPosition)
{
ContextMenu* menu = m_page->contextMenuController()->contextMenu();
ASSERT(menu);
ContextMenuItem* item = byPosition ? menu->itemAtIndex((unsigned)wParam, (HMENU)lParam) : menu->itemWithAction((ContextMenuAction)wParam);
if (!item)
return;
m_page->contextMenuController()->contextMenuItemSelected(item);
delete item;
}
bool WebView::handleMouseEvent(UINT message, WPARAM wParam, LPARAM lParam)
{
static LONG globalClickCount;
static IntPoint globalPrevPoint;
static MouseButton globalPrevButton;
static LONG globalPrevMouseDownTime;
if (message == WM_CANCELMODE) {
m_page->mainFrame()->eventHandler()->lostMouseCapture();
return true;
}
// Create our event.
// On WM_MOUSELEAVE we need to create a mouseout event, so we force the position
// of the event to be at (MINSHORT, MINSHORT).
LPARAM position = (message == WM_MOUSELEAVE) ? ((MINSHORT << 16) | MINSHORT) : lParam;
PlatformMouseEvent mouseEvent(m_viewWindow, message, wParam, position, m_mouseActivated);
setMouseActivated(false);
bool insideThreshold = abs(globalPrevPoint.x() - mouseEvent.pos().x()) < ::GetSystemMetrics(SM_CXDOUBLECLK) &&
abs(globalPrevPoint.y() - mouseEvent.pos().y()) < ::GetSystemMetrics(SM_CYDOUBLECLK);
LONG messageTime = ::GetMessageTime();
bool handled = false;
if (message == WM_LBUTTONDOWN || message == WM_MBUTTONDOWN || message == WM_RBUTTONDOWN) {
// FIXME: I'm not sure if this is the "right" way to do this
// but without this call, we never become focused since we don't allow
// the default handling of mouse events.
SetFocus(m_viewWindow);
// Always start capturing events when the mouse goes down in our HWND.
::SetCapture(m_viewWindow);
if (((messageTime - globalPrevMouseDownTime) < (LONG)::GetDoubleClickTime()) &&
insideThreshold &&
mouseEvent.button() == globalPrevButton)
globalClickCount++;
else
// Reset the click count.
globalClickCount = 1;
globalPrevMouseDownTime = messageTime;
globalPrevButton = mouseEvent.button();
globalPrevPoint = mouseEvent.pos();
mouseEvent.setClickCount(globalClickCount);
handled = m_page->mainFrame()->eventHandler()->handleMousePressEvent(mouseEvent);
} else if (message == WM_LBUTTONDBLCLK || message == WM_MBUTTONDBLCLK || message == WM_RBUTTONDBLCLK) {
globalClickCount++;
mouseEvent.setClickCount(globalClickCount);
handled = m_page->mainFrame()->eventHandler()->handleMousePressEvent(mouseEvent);
} else if (message == WM_LBUTTONUP || message == WM_MBUTTONUP || message == WM_RBUTTONUP) {
// Record the global position and the button of the up.
globalPrevButton = mouseEvent.button();
globalPrevPoint = mouseEvent.pos();
mouseEvent.setClickCount(globalClickCount);
m_page->mainFrame()->eventHandler()->handleMouseReleaseEvent(mouseEvent);
::ReleaseCapture();
} else if (message == WM_MOUSELEAVE && m_mouseOutTracker) {
// Once WM_MOUSELEAVE is fired windows clears this tracker
// so there is no need to disable it ourselves.
m_mouseOutTracker.set(0);
m_page->mainFrame()->eventHandler()->mouseMoved(mouseEvent);
handled = true;
} else if (message == WM_MOUSEMOVE) {
if (!insideThreshold)
globalClickCount = 0;
mouseEvent.setClickCount(globalClickCount);
handled = m_page->mainFrame()->eventHandler()->mouseMoved(mouseEvent);
if (!m_mouseOutTracker) {
m_mouseOutTracker.set(new TRACKMOUSEEVENT);
m_mouseOutTracker->cbSize = sizeof(TRACKMOUSEEVENT);
m_mouseOutTracker->dwFlags = TME_LEAVE;
m_mouseOutTracker->hwndTrack = m_viewWindow;
::TrackMouseEvent(m_mouseOutTracker.get());
}
}
return handled;
}
bool WebView::gestureNotify(WPARAM wParam, LPARAM lParam)
{
GESTURENOTIFYSTRUCT* gn = reinterpret_cast<GESTURENOTIFYSTRUCT*>(lParam);
Frame* coreFrame = core(m_mainFrame);
if (!coreFrame)
return false;
ScrollView* view = coreFrame->view();
if (!view)
return false;
// If we don't have this function, we shouldn't be receiving this message
ASSERT(SetGestureConfigPtr());
bool hitScrollbar = false;
POINT gestureBeginPoint = {gn->ptsLocation.x, gn->ptsLocation.y};
HitTestRequest request(HitTestRequest::ReadOnly);
for (Frame* childFrame = m_page->mainFrame(); childFrame; childFrame = EventHandler::subframeForTargetNode(m_gestureTargetNode.get())) {
FrameView* frameView = childFrame->view();
if (!frameView)
break;
RenderView* renderView = childFrame->document()->renderView();
if (!renderView)
break;
RenderLayer* layer = renderView->layer();
if (!layer)
break;
HitTestResult result(frameView->screenToContents(gestureBeginPoint));
layer->hitTest(request, result);
m_gestureTargetNode = result.innerNode();
if (!hitScrollbar)
hitScrollbar = result.scrollbar();
}
if (!hitScrollbar) {
// The hit testing above won't detect if we've hit the main frame's vertical scrollbar. Check that manually now.
RECT webViewRect;
GetWindowRect(m_viewWindow, &webViewRect);
hitScrollbar = view->verticalScrollbar() && (gestureBeginPoint.x > (webViewRect.right - view->verticalScrollbar()->theme()->scrollbarThickness()));
}
bool canBeScrolled = false;
if (m_gestureTargetNode) {
for (RenderObject* renderer = m_gestureTargetNode->renderer(); renderer; renderer = renderer->parent()) {
if (renderer->isBox() && toRenderBox(renderer)->canBeScrolledAndHasScrollableArea()) {
canBeScrolled = true;
break;
}
}
}
// We always allow two-fingered panning with inertia and a gutter (which limits movement to one
// direction in most cases).
DWORD dwPanWant = GC_PAN | GC_PAN_WITH_INERTIA | GC_PAN_WITH_GUTTER;
// We never allow single-fingered horizontal panning. That gesture is reserved for creating text
// selections. This matches IE.
DWORD dwPanBlock = GC_PAN_WITH_SINGLE_FINGER_HORIZONTALLY;
if (hitScrollbar || !canBeScrolled) {
// The part of the page under the gesture can't be scrolled, or the gesture is on a scrollbar.
// Disallow single-fingered vertical panning in this case, too, so we'll fall back to the default
// behavior (which allows the scrollbar thumb to be dragged, text selections to be made, etc.).
dwPanBlock |= GC_PAN_WITH_SINGLE_FINGER_VERTICALLY;
} else {
// The part of the page the gesture is under can be scrolled, and we're not under a scrollbar.
// Allow single-fingered vertical panning in this case, so the user will be able to pan the page
// with one or two fingers.
dwPanWant |= GC_PAN_WITH_SINGLE_FINGER_VERTICALLY;
}
GESTURECONFIG gc = { GID_PAN, dwPanWant, dwPanBlock };
return SetGestureConfigPtr()(m_viewWindow, 0, 1, &gc, sizeof(GESTURECONFIG));
}
bool WebView::gesture(WPARAM wParam, LPARAM lParam)
{
// We want to bail out if we don't have either of these functions
if (!GetGestureInfoPtr() || !CloseGestureInfoHandlePtr())
return false;
HGESTUREINFO gestureHandle = reinterpret_cast<HGESTUREINFO>(lParam);
GESTUREINFO gi = {0};
gi.cbSize = sizeof(GESTUREINFO);
if (!GetGestureInfoPtr()(gestureHandle, reinterpret_cast<PGESTUREINFO>(&gi)))
return false;
switch (gi.dwID) {
case GID_BEGIN:
m_lastPanX = gi.ptsLocation.x;
m_lastPanY = gi.ptsLocation.y;
break;
case GID_END:
m_gestureTargetNode = 0;
break;
case GID_PAN: {
// Where are the fingers currently?
long currentX = gi.ptsLocation.x;
long currentY = gi.ptsLocation.y;
// How far did we pan in each direction?
long deltaX = currentX - m_lastPanX;
long deltaY = currentY - m_lastPanY;
// Calculate the overpan for window bounce
m_yOverpan -= m_lastPanY - currentY;
m_xOverpan -= m_lastPanX - currentX;
// Update our class variables with updated values
m_lastPanX = currentX;
m_lastPanY = currentY;
Frame* coreFrame = core(m_mainFrame);
if (!coreFrame) {
CloseGestureInfoHandlePtr()(gestureHandle);
return false;
}
if (!m_gestureTargetNode || !m_gestureTargetNode->renderer())
return false;
// We negate here since panning up moves the content up, but moves the scrollbar down.
m_gestureTargetNode->renderer()->enclosingLayer()->scrollByRecursively(-deltaX, -deltaY);
if (!(UpdatePanningFeedbackPtr() && BeginPanningFeedbackPtr() && EndPanningFeedbackPtr())) {
CloseGestureInfoHandlePtr()(gestureHandle);
return true;
}
if (gi.dwFlags & GF_BEGIN) {
BeginPanningFeedbackPtr()(m_viewWindow);
m_yOverpan = 0;
} else if (gi.dwFlags & GF_END) {
EndPanningFeedbackPtr()(m_viewWindow, true);
m_yOverpan = 0;
}
ScrollView* view = coreFrame->view();
if (!view) {
CloseGestureInfoHandlePtr()(gestureHandle);
return true;
}
Scrollbar* vertScrollbar = view->verticalScrollbar();
if (!vertScrollbar) {
CloseGestureInfoHandlePtr()(gestureHandle);
return true;
}
// FIXME: Support Horizontal Window Bounce. <https://webkit.org/b/28500>.
// FIXME: If the user starts panning down after a window bounce has started, the window doesn't bounce back
// until they release their finger. <https://webkit.org/b/28501>.
if (vertScrollbar->currentPos() == 0)
UpdatePanningFeedbackPtr()(m_viewWindow, 0, m_yOverpan, gi.dwFlags & GF_INERTIA);
else if (vertScrollbar->currentPos() >= vertScrollbar->maximum())
UpdatePanningFeedbackPtr()(m_viewWindow, 0, m_yOverpan, gi.dwFlags & GF_INERTIA);
CloseGestureInfoHandlePtr()(gestureHandle);
return true;
}
default:
break;
}
// If we get to this point, the gesture has not been handled. We forward
// the call to DefWindowProc by returning false, and we don't need to
// to call CloseGestureInfoHandle.
// http://msdn.microsoft.com/en-us/library/dd353228(VS.85).aspx
return false;
}
bool WebView::mouseWheel(WPARAM wParam, LPARAM lParam, bool isMouseHWheel)
{
// Ctrl+Mouse wheel doesn't ever go into WebCore. It is used to
// zoom instead (Mac zooms the whole Desktop, but Windows browsers trigger their
// own local zoom modes for Ctrl+wheel).
if (wParam & MK_CONTROL) {
short delta = short(HIWORD(wParam));
if (delta < 0)
makeTextSmaller(0);
else
makeTextLarger(0);
return true;
}
// FIXME: This doesn't fix https://bugs.webkit.org/show_bug.cgi?id=28217. This only fixes https://bugs.webkit.org/show_bug.cgi?id=28203.
HWND focusedWindow = GetFocus();
if (focusedWindow && focusedWindow != m_viewWindow) {
// Our focus is on a different hwnd, see if it's a PopupMenu and if so, set the focus back on us (which will hide the popup).
TCHAR className[256];
// Make sure truncation won't affect the comparison.
ASSERT(ARRAYSIZE(className) > _tcslen(PopupMenuWin::popupClassName()));
if (GetClassName(focusedWindow, className, ARRAYSIZE(className)) && !_tcscmp(className, PopupMenuWin::popupClassName())) {
// We don't let the WebView scroll here for two reasons - 1) To match Firefox behavior, 2) If we do scroll, we lose the
// focus ring around the select menu.
SetFocus(m_viewWindow);
return true;
}
}
PlatformWheelEvent wheelEvent(m_viewWindow, wParam, lParam, isMouseHWheel);
Frame* coreFrame = core(m_mainFrame);
if (!coreFrame)
return false;
return coreFrame->eventHandler()->handleWheelEvent(wheelEvent);
}
bool WebView::verticalScroll(WPARAM wParam, LPARAM /*lParam*/)
{
ScrollDirection direction;
ScrollGranularity granularity;
switch (LOWORD(wParam)) {
case SB_LINEDOWN:
granularity = ScrollByLine;
direction = ScrollDown;
break;
case SB_LINEUP:
granularity = ScrollByLine;
direction = ScrollUp;
break;
case SB_PAGEDOWN:
granularity = ScrollByDocument;
direction = ScrollDown;
break;
case SB_PAGEUP:
granularity = ScrollByDocument;
direction = ScrollUp;
break;
default:
return false;
break;
}
Frame* frame = m_page->focusController()->focusedOrMainFrame();
return frame->eventHandler()->scrollRecursively(direction, granularity);
}
bool WebView::horizontalScroll(WPARAM wParam, LPARAM /*lParam*/)
{
ScrollDirection direction;
ScrollGranularity granularity;
switch (LOWORD(wParam)) {
case SB_LINELEFT:
granularity = ScrollByLine;
direction = ScrollLeft;
break;
case SB_LINERIGHT:
granularity = ScrollByLine;
direction = ScrollRight;
break;
case SB_PAGELEFT:
granularity = ScrollByDocument;
direction = ScrollLeft;
break;
case SB_PAGERIGHT:
granularity = ScrollByDocument;
direction = ScrollRight;
break;
default:
return false;
}
Frame* frame = m_page->focusController()->focusedOrMainFrame();
return frame->eventHandler()->scrollRecursively(direction, granularity);
}
bool WebView::execCommand(WPARAM wParam, LPARAM /*lParam*/)
{
Frame* frame = m_page->focusController()->focusedOrMainFrame();
switch (LOWORD(wParam)) {
case SelectAll:
return frame->editor()->command("SelectAll").execute();
case Undo:
return frame->editor()->command("Undo").execute();
case Redo:
return frame->editor()->command("Redo").execute();
}
return false;
}
bool WebView::keyUp(WPARAM virtualKeyCode, LPARAM keyData, bool systemKeyDown)
{
PlatformKeyboardEvent keyEvent(m_viewWindow, virtualKeyCode, keyData, PlatformKeyboardEvent::KeyUp, systemKeyDown);
Frame* frame = m_page->focusController()->focusedOrMainFrame();
m_currentCharacterCode = 0;
return frame->eventHandler()->keyEvent(keyEvent);
}
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* WebView::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;
}
bool WebView::handleEditingKeyboardEvent(KeyboardEvent* evt)
{
Node* node = evt->target()->toNode();
ASSERT(node);
Frame* frame = node->document()->frame();
ASSERT(frame);
const PlatformKeyboardEvent* keyEvent = evt->keyEvent();
if (!keyEvent || keyEvent->isSystemKey()) // do not treat this as text input if it's a system key event
return false;
Editor::Command command = frame->editor()->command(interpretKeyEvent(evt));
if (keyEvent->type() == PlatformKeyboardEvent::RawKeyDown) {
// WebKit doesn't have enough information about mode to decide how commands that just insert text if executed via Editor should be treated,
// so we leave it upon WebCore to either handle them immediately (e.g. Tab that changes focus) or let a keypress event be generated
// (e.g. Tab that inserts a Tab character, or Enter).
return !command.isTextInsertion() && command.execute(evt);
}
if (command.execute(evt))
return true;
// Don't insert null or control characters as they can result in unexpected behaviour
if (evt->charCode() < ' ')
return false;
return frame->editor()->insertText(evt->keyEvent()->text(), evt);
}
bool WebView::keyDown(WPARAM virtualKeyCode, LPARAM keyData, bool systemKeyDown)
{
Frame* frame = m_page->focusController()->focusedOrMainFrame();
if (virtualKeyCode == VK_CAPITAL)
frame->eventHandler()->capsLockStateMayHaveChanged();
PlatformKeyboardEvent keyEvent(m_viewWindow, virtualKeyCode, keyData, PlatformKeyboardEvent::RawKeyDown, systemKeyDown);
bool handled = frame->eventHandler()->keyEvent(keyEvent);
// These events cannot be canceled, and we have no default handling for them.
// FIXME: match IE list more closely, see <http://msdn2.microsoft.com/en-us/library/ms536938.aspx>.
if (systemKeyDown && virtualKeyCode != VK_RETURN)
return false;
if (handled) {
// FIXME: remove WM_UNICHAR, too
MSG msg;
// WM_SYSCHAR events should not be removed, because access keys are implemented in WebCore in WM_SYSCHAR handler.
if (!systemKeyDown)
::PeekMessage(&msg, m_viewWindow, WM_CHAR, WM_CHAR, PM_REMOVE);
return true;
}
// We need to handle back/forward using either Backspace(+Shift) or Ctrl+Left/Right Arrow keys.
if ((virtualKeyCode == VK_BACK && keyEvent.shiftKey()) || (virtualKeyCode == VK_RIGHT && keyEvent.ctrlKey()))
return m_page->goForward();
if (virtualKeyCode == VK_BACK || (virtualKeyCode == VK_LEFT && keyEvent.ctrlKey()))
return m_page->goBack();
// Need to scroll the page if the arrow keys, pgup/dn, or home/end are hit.
ScrollDirection direction;
ScrollGranularity granularity;
switch (virtualKeyCode) {
case VK_LEFT:
granularity = ScrollByLine;
direction = ScrollLeft;
break;
case VK_RIGHT:
granularity = ScrollByLine;
direction = ScrollRight;
break;
case VK_UP:
granularity = ScrollByLine;
direction = ScrollUp;
break;
case VK_DOWN:
granularity = ScrollByLine;
direction = ScrollDown;
break;
case VK_HOME:
granularity = ScrollByDocument;
direction = ScrollUp;
break;
case VK_END:
granularity = ScrollByDocument;
direction = ScrollDown;
break;
case VK_PRIOR:
granularity = ScrollByPage;
direction = ScrollUp;
break;
case VK_NEXT:
granularity = ScrollByPage;
direction = ScrollDown;
break;
default:
return false;
}
return frame->eventHandler()->scrollRecursively(direction, granularity);
}
bool WebView::keyPress(WPARAM charCode, LPARAM keyData, bool systemKeyDown)
{
Frame* frame = m_page->focusController()->focusedOrMainFrame();
PlatformKeyboardEvent keyEvent(m_viewWindow, charCode, keyData, PlatformKeyboardEvent::Char, systemKeyDown);
// IE does not dispatch keypress event for WM_SYSCHAR.
if (systemKeyDown)
return frame->eventHandler()->handleAccessKey(keyEvent);
return frame->eventHandler()->keyEvent(keyEvent);
}
bool WebView::registerWebViewWindowClass()
{
static bool haveRegisteredWindowClass = false;
if (haveRegisteredWindowClass)
return true;
haveRegisteredWindowClass = true;
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_DBLCLKS;
wcex.lpfnWndProc = WebViewWndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 4; // 4 bytes for the IWebView pointer
wcex.hInstance = gInstance;
wcex.hIcon = 0;
wcex.hCursor = ::LoadCursor(0, IDC_ARROW);
wcex.hbrBackground = 0;
wcex.lpszMenuName = 0;
wcex.lpszClassName = kWebViewWindowClassName;
wcex.hIconSm = 0;
return !!RegisterClassEx(&wcex);
}
static HWND findTopLevelParent(HWND window)
{
if (!window)
return 0;
HWND current = window;
for (HWND parent = GetParent(current); current; current = parent, parent = GetParent(parent))
if (!parent || !(GetWindowLongPtr(current, GWL_STYLE) & (WS_POPUP | WS_CHILD)))
return current;
ASSERT_NOT_REACHED();
return 0;
}
LRESULT CALLBACK WebView::WebViewWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
LRESULT lResult = 0;
LONG_PTR longPtr = GetWindowLongPtr(hWnd, 0);
WebView* webView = reinterpret_cast<WebView*>(longPtr);
WebFrame* mainFrameImpl = webView ? webView->topLevelFrame() : 0;
if (!mainFrameImpl || webView->isBeingDestroyed())
return DefWindowProc(hWnd, message, wParam, lParam);
// hold a ref, since the WebView could go away in an event handler.
COMPtr<WebView> protector(webView);
ASSERT(webView);
// Windows Media Player has a modal message loop that will deliver messages
// to us at inappropriate times and we will crash if we handle them when
// they are delivered. We repost paint messages so that we eventually get
// a chance to paint once the modal loop has exited, but other messages
// aren't safe to repost, so we just drop them.
if (PluginView::isCallingPlugin()) {
if (message == WM_PAINT)
PostMessage(hWnd, message, wParam, lParam);
return 0;
}
bool handled = true;
switch (message) {
case WM_PAINT: {
webView->paint(0, 0);
break;
}
case WM_PRINTCLIENT:
webView->paint((HDC)wParam, lParam);
break;
case WM_DESTROY:
webView->setIsBeingDestroyed();
webView->close();
break;
case WM_GESTURENOTIFY:
handled = webView->gestureNotify(wParam, lParam);
break;
case WM_GESTURE:
handled = webView->gesture(wParam, lParam);
break;
case WM_MOUSEMOVE:
case WM_LBUTTONDOWN:
case WM_MBUTTONDOWN:
case WM_RBUTTONDOWN:
case WM_LBUTTONDBLCLK:
case WM_MBUTTONDBLCLK:
case WM_RBUTTONDBLCLK:
case WM_LBUTTONUP:
case WM_MBUTTONUP:
case WM_RBUTTONUP:
case WM_MOUSELEAVE:
case WM_CANCELMODE:
if (Frame* coreFrame = core(mainFrameImpl))
if (coreFrame->view()->didFirstLayout())
handled = webView->handleMouseEvent(message, wParam, lParam);
break;
case WM_MOUSEWHEEL:
case WM_VISTA_MOUSEHWHEEL:
if (Frame* coreFrame = core(mainFrameImpl))
if (coreFrame->view()->didFirstLayout())
handled = webView->mouseWheel(wParam, lParam, message == WM_VISTA_MOUSEHWHEEL);
break;
case WM_SYSKEYDOWN:
handled = webView->keyDown(wParam, lParam, true);
break;
case WM_KEYDOWN:
handled = webView->keyDown(wParam, lParam);
break;
case WM_SYSKEYUP:
handled = webView->keyUp(wParam, lParam, true);
break;
case WM_KEYUP:
handled = webView->keyUp(wParam, lParam);
break;
case WM_SYSCHAR:
handled = webView->keyPress(wParam, lParam, true);
break;
case WM_CHAR:
handled = webView->keyPress(wParam, lParam);
break;
// FIXME: We need to check WM_UNICHAR to support supplementary characters (that don't fit in 16 bits).
case WM_SIZE:
if (lParam != 0) {
webView->deleteBackingStore();
#if USE(ACCELERATED_COMPOSITING)
if (webView->isAcceleratedCompositing())
webView->resizeLayerRenderer();
#endif
if (Frame* coreFrame = core(mainFrameImpl))
coreFrame->view()->resize(LOWORD(lParam), HIWORD(lParam));
}
break;
case WM_SHOWWINDOW:
lResult = DefWindowProc(hWnd, message, wParam, lParam);
if (wParam == 0) {
// The window is being hidden (e.g., because we switched tabs).
// Null out our backing store.
webView->deleteBackingStore();
}
#if USE(ACCELERATED_COMPOSITING)
else if (webView->isAcceleratedCompositing())
webView->layerRendererBecameVisible();
#endif
break;
case WM_SETFOCUS: {
COMPtr<IWebUIDelegate> uiDelegate;
COMPtr<IWebUIDelegatePrivate> uiDelegatePrivate;
if (SUCCEEDED(webView->uiDelegate(&uiDelegate)) && uiDelegate
&& SUCCEEDED(uiDelegate->QueryInterface(IID_IWebUIDelegatePrivate, (void**) &uiDelegatePrivate)) && uiDelegatePrivate)
uiDelegatePrivate->webViewReceivedFocus(webView);
FocusController* focusController = webView->page()->focusController();
if (Frame* frame = focusController->focusedFrame()) {
// Send focus events unless the previously focused window is a
// child of ours (for example a plugin).
if (!IsChild(hWnd, reinterpret_cast<HWND>(wParam)))
focusController->setFocused(true);
} else
focusController->setFocused(true);
break;
}
case WM_KILLFOCUS: {
COMPtr<IWebUIDelegate> uiDelegate;
COMPtr<IWebUIDelegatePrivate> uiDelegatePrivate;
HWND newFocusWnd = reinterpret_cast<HWND>(wParam);
if (SUCCEEDED(webView->uiDelegate(&uiDelegate)) && uiDelegate
&& SUCCEEDED(uiDelegate->QueryInterface(IID_IWebUIDelegatePrivate, (void**) &uiDelegatePrivate)) && uiDelegatePrivate)
uiDelegatePrivate->webViewLostFocus(webView, (OLE_HANDLE)(ULONG64)newFocusWnd);
FocusController* focusController = webView->page()->focusController();
Frame* frame = focusController->focusedOrMainFrame();
webView->resetIME(frame);
// Send blur events unless we're losing focus to a child of ours.
if (!IsChild(hWnd, newFocusWnd))
focusController->setFocused(false);
// If we are pan-scrolling when we lose focus, stop the pan scrolling.
frame->eventHandler()->stopAutoscrollTimer();
break;
}
case WM_WINDOWPOSCHANGED:
if (reinterpret_cast<WINDOWPOS*>(lParam)->flags & SWP_SHOWWINDOW)
webView->updateActiveStateSoon();
handled = false;
break;
case WM_CUT:
webView->cut(0);
break;
case WM_COPY:
webView->copy(0);
break;
case WM_PASTE:
webView->paste(0);
break;
case WM_CLEAR:
webView->delete_(0);
break;
case WM_COMMAND:
if (HIWORD(wParam))
handled = webView->execCommand(wParam, lParam);
else // If the high word of wParam is 0, the message is from a menu
webView->performContextMenuAction(wParam, lParam, false);
break;
case WM_MENUCOMMAND:
webView->performContextMenuAction(wParam, lParam, true);
break;
case WM_CONTEXTMENU:
handled = webView->handleContextMenuEvent(wParam, lParam);
break;
case WM_INITMENUPOPUP:
handled = webView->onInitMenuPopup(wParam, lParam);
break;
case WM_MEASUREITEM:
handled = webView->onMeasureItem(wParam, lParam);
break;
case WM_DRAWITEM:
handled = webView->onDrawItem(wParam, lParam);
break;
case WM_UNINITMENUPOPUP:
handled = webView->onUninitMenuPopup(wParam, lParam);
break;
case WM_XP_THEMECHANGED:
if (Frame* coreFrame = core(mainFrameImpl)) {
webView->deleteBackingStore();
coreFrame->page()->theme()->themeChanged();
ScrollbarTheme::nativeTheme()->themeChanged();
RECT windowRect;
::GetClientRect(hWnd, &windowRect);
::InvalidateRect(hWnd, &windowRect, false);
#if USE(ACCELERATED_COMPOSITING)
if (webView->isAcceleratedCompositing())
webView->setRootLayerNeedsDisplay();
#endif
}
break;
case WM_MOUSEACTIVATE:
webView->setMouseActivated(true);
handled = false;
break;
case WM_GETDLGCODE: {
COMPtr<IWebUIDelegate> uiDelegate;
COMPtr<IWebUIDelegatePrivate> uiDelegatePrivate;
LONG_PTR dlgCode = 0;
UINT keyCode = 0;
if (lParam) {
LPMSG lpMsg = (LPMSG)lParam;
if (lpMsg->message == WM_KEYDOWN)
keyCode = (UINT) lpMsg->wParam;
}
if (SUCCEEDED(webView->uiDelegate(&uiDelegate)) && uiDelegate
&& SUCCEEDED(uiDelegate->QueryInterface(IID_IWebUIDelegatePrivate, (void**) &uiDelegatePrivate)) && uiDelegatePrivate
&& SUCCEEDED(uiDelegatePrivate->webViewGetDlgCode(webView, keyCode, &dlgCode)))
return dlgCode;
handled = false;
break;
}
case WM_GETOBJECT:
handled = webView->onGetObject(wParam, lParam, lResult);
break;
case WM_IME_STARTCOMPOSITION:
handled = webView->onIMEStartComposition();
break;
case WM_IME_REQUEST:
lResult = webView->onIMERequest(wParam, lParam);
break;
case WM_IME_COMPOSITION:
handled = webView->onIMEComposition(lParam);
break;
case WM_IME_ENDCOMPOSITION:
handled = webView->onIMEEndComposition();
break;
case WM_IME_CHAR:
handled = webView->onIMEChar(wParam, lParam);
break;
case WM_IME_NOTIFY:
handled = webView->onIMENotify(wParam, lParam, &lResult);
break;
case WM_IME_SELECT:
handled = webView->onIMESelect(wParam, lParam);
break;
case WM_IME_SETCONTEXT:
handled = webView->onIMESetContext(wParam, lParam);
break;
case WM_TIMER:
switch (wParam) {
case UpdateActiveStateTimer:
KillTimer(hWnd, UpdateActiveStateTimer);
webView->updateActiveState();
break;
case DeleteBackingStoreTimer:
webView->deleteBackingStore();
break;
}
break;
case WM_SETCURSOR:
handled = ::SetCursor(webView->m_lastSetCursor);
break;
case WM_VSCROLL:
handled = webView->verticalScroll(wParam, lParam);
break;
case WM_HSCROLL:
handled = webView->horizontalScroll(wParam, lParam);
break;
default:
handled = false;
break;
}
if (!handled)
lResult = DefWindowProc(hWnd, message, wParam, lParam);
// Let the client know whether we consider this message handled.
return (message == WM_KEYDOWN || message == WM_SYSKEYDOWN || message == WM_KEYUP || message == WM_SYSKEYUP) ? !handled : lResult;
}
bool WebView::developerExtrasEnabled() const
{
if (m_preferences->developerExtrasDisabledByOverride())
return false;
#ifdef NDEBUG
BOOL enabled;
return SUCCEEDED(m_preferences->developerExtrasEnabled(&enabled)) && enabled;
#else
return true;
#endif
}
static String osVersion()
{
String osVersion;
OSVERSIONINFO versionInfo = {0};
versionInfo.dwOSVersionInfoSize = sizeof(versionInfo);
GetVersionEx(&versionInfo);
if (versionInfo.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
if (versionInfo.dwMajorVersion == 4) {
if (versionInfo.dwMinorVersion == 0)
osVersion = "Windows 95";
else if (versionInfo.dwMinorVersion == 10)
osVersion = "Windows 98";
else if (versionInfo.dwMinorVersion == 90)
osVersion = "Windows 98; Win 9x 4.90";
}
} else if (versionInfo.dwPlatformId == VER_PLATFORM_WIN32_NT)
osVersion = String::format("Windows NT %d.%d", versionInfo.dwMajorVersion, versionInfo.dwMinorVersion);
if (!osVersion.length())
osVersion = String::format("Windows %d.%d", versionInfo.dwMajorVersion, versionInfo.dwMinorVersion);
return osVersion;
}
static String webKitVersion()
{
String versionStr = "420+";
void* data = 0;
struct LANGANDCODEPAGE {
WORD wLanguage;
WORD wCodePage;
} *lpTranslate;
TCHAR path[MAX_PATH];
GetModuleFileName(gInstance, path, ARRAYSIZE(path));
DWORD handle;
DWORD versionSize = GetFileVersionInfoSize(path, &handle);
if (!versionSize)
goto exit;
data = malloc(versionSize);
if (!data)
goto exit;
if (!GetFileVersionInfo(path, 0, versionSize, data))
goto exit;
UINT cbTranslate;
if (!VerQueryValue(data, TEXT("\\VarFileInfo\\Translation"), (LPVOID*)&lpTranslate, &cbTranslate))
goto exit;
TCHAR key[256];
_stprintf_s(key, ARRAYSIZE(key), TEXT("\\StringFileInfo\\%04x%04x\\ProductVersion"), lpTranslate[0].wLanguage, lpTranslate[0].wCodePage);
LPCTSTR productVersion;
UINT productVersionLength;
if (!VerQueryValue(data, (LPTSTR)(LPCTSTR)key, (void**)&productVersion, &productVersionLength))
goto exit;
versionStr = String(productVersion, productVersionLength);
exit:
if (data)
free(data);
return versionStr;
}
const String& WebView::userAgentForKURL(const KURL&)
{
if (m_userAgentOverridden)
return m_userAgentCustom;
if (!m_userAgentStandard.length())
m_userAgentStandard = WebView::standardUserAgentWithApplicationName(m_applicationName);
return m_userAgentStandard;
}
// IUnknown -------------------------------------------------------------------
HRESULT STDMETHODCALLTYPE WebView::QueryInterface(REFIID riid, void** ppvObject)
{
*ppvObject = 0;
if (IsEqualGUID(riid, CLSID_WebView))
*ppvObject = this;
else if (IsEqualGUID(riid, IID_IUnknown))
*ppvObject = static_cast<IWebView*>(this);
else if (IsEqualGUID(riid, IID_IWebView))
*ppvObject = static_cast<IWebView*>(this);
else if (IsEqualGUID(riid, IID_IWebViewPrivate))
*ppvObject = static_cast<IWebViewPrivate*>(this);
else if (IsEqualGUID(riid, IID_IWebIBActions))
*ppvObject = static_cast<IWebIBActions*>(this);
else if (IsEqualGUID(riid, IID_IWebViewCSS))
*ppvObject = static_cast<IWebViewCSS*>(this);
else if (IsEqualGUID(riid, IID_IWebViewEditing))
*ppvObject = static_cast<IWebViewEditing*>(this);
else if (IsEqualGUID(riid, IID_IWebViewUndoableEditing))
*ppvObject = static_cast<IWebViewUndoableEditing*>(this);
else if (IsEqualGUID(riid, IID_IWebViewEditingActions))
*ppvObject = static_cast<IWebViewEditingActions*>(this);
else if (IsEqualGUID(riid, IID_IWebNotificationObserver))
*ppvObject = static_cast<IWebNotificationObserver*>(this);
else if (IsEqualGUID(riid, IID_IDropTarget))
*ppvObject = static_cast<IDropTarget*>(this);
else
return E_NOINTERFACE;
AddRef();
return S_OK;
}
ULONG STDMETHODCALLTYPE WebView::AddRef(void)
{
ASSERT(!m_deletionHasBegun);
return ++m_refCount;
}
ULONG STDMETHODCALLTYPE WebView::Release(void)
{
ASSERT(!m_deletionHasBegun);
if (m_refCount == 1) {
// Call close() now so that clients don't have to. (It's harmless to call close() multiple
// times.) We do this here instead of in our destructor because close() can cause AddRef()
// and Release() to be called, and if that happened in our destructor we would be destroyed
// more than once.
close();
}
ULONG newRef = --m_refCount;
if (!newRef) {
#if !ASSERT_DISABLED
m_deletionHasBegun = true;
#endif
delete(this);
}
return newRef;
}
// IWebView --------------------------------------------------------------------
HRESULT STDMETHODCALLTYPE WebView::canShowMIMEType(
/* [in] */ BSTR mimeType,
/* [retval][out] */ BOOL* canShow)
{
String mimeTypeStr(mimeType, SysStringLen(mimeType));
if (!canShow)
return E_POINTER;
*canShow = MIMETypeRegistry::isSupportedImageMIMEType(mimeTypeStr) ||
MIMETypeRegistry::isSupportedNonImageMIMEType(mimeTypeStr) ||
(m_page && m_page->pluginData() && m_page->pluginData()->supportsMimeType(mimeTypeStr)) ||
shouldUseEmbeddedView(mimeTypeStr);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::canShowMIMETypeAsHTML(
/* [in] */ BSTR /*mimeType*/,
/* [retval][out] */ BOOL* canShow)
{
// FIXME
*canShow = TRUE;
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::MIMETypesShownAsHTML(
/* [retval][out] */ IEnumVARIANT** /*enumVariant*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebView::setMIMETypesShownAsHTML(
/* [size_is][in] */ BSTR* /*mimeTypes*/,
/* [in] */ int /*cMimeTypes*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebView::URLFromPasteboard(
/* [in] */ IDataObject* /*pasteboard*/,
/* [retval][out] */ BSTR* /*url*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebView::URLTitleFromPasteboard(
/* [in] */ IDataObject* /*pasteboard*/,
/* [retval][out] */ BSTR* /*urlTitle*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
static void WebKitSetApplicationCachePathIfNecessary()
{
static bool initialized = false;
if (initialized)
return;
String path = localUserSpecificStorageDirectory();
if (!path.isNull())
cacheStorage().setCacheDirectory(path);
initialized = true;
}
bool WebView::shouldInitializeTrackPointHack()
{
static bool shouldCreateScrollbars;
static bool hasRunTrackPointCheck;
if (hasRunTrackPointCheck)
return shouldCreateScrollbars;
hasRunTrackPointCheck = true;
const TCHAR trackPointKeys[][50] = { TEXT("Software\\Lenovo\\TrackPoint"),
TEXT("Software\\Lenovo\\UltraNav"),
TEXT("Software\\Alps\\Apoint\\TrackPoint"),
TEXT("Software\\Synaptics\\SynTPEnh\\UltraNavUSB"),
TEXT("Software\\Synaptics\\SynTPEnh\\UltraNavPS2") };
for (int i = 0; i < 5; ++i) {
HKEY trackPointKey;
int readKeyResult = ::RegOpenKeyEx(HKEY_CURRENT_USER, trackPointKeys[i], 0, KEY_READ, &trackPointKey);
::RegCloseKey(trackPointKey);
if (readKeyResult == ERROR_SUCCESS) {
shouldCreateScrollbars = true;
return shouldCreateScrollbars;
}
}
return shouldCreateScrollbars;
}
HRESULT STDMETHODCALLTYPE WebView::initWithFrame(
/* [in] */ RECT frame,
/* [in] */ BSTR frameName,
/* [in] */ BSTR groupName)
{
HRESULT hr = S_OK;
if (m_viewWindow)
return E_FAIL;
registerWebViewWindowClass();
m_viewWindow = CreateWindowEx(0, kWebViewWindowClassName, 0, WS_CHILD | WS_CLIPSIBLINGS | WS_CLIPCHILDREN,
frame.left, frame.top, frame.right - frame.left, frame.bottom - frame.top, m_hostWindow ? m_hostWindow : HWND_MESSAGE, 0, gInstance, 0);
ASSERT(::IsWindow(m_viewWindow));
if (shouldInitializeTrackPointHack()) {
// If we detected a registry key belonging to a TrackPoint driver, then create fake trackpoint
// scrollbars, so the WebView will receive WM_VSCROLL and WM_HSCROLL messages. We create one
// vertical scrollbar and one horizontal to allow for receiving both types of messages.
::CreateWindow(TEXT("SCROLLBAR"), TEXT("FAKETRACKPOINTHSCROLLBAR"), WS_CHILD | WS_VISIBLE | SBS_HORZ, 0, 0, 0, 0, m_viewWindow, 0, gInstance, 0);
::CreateWindow(TEXT("SCROLLBAR"), TEXT("FAKETRACKPOINTVSCROLLBAR"), WS_CHILD | WS_VISIBLE | SBS_VERT, 0, 0, 0, 0, m_viewWindow, 0, gInstance, 0);
}
hr = registerDragDrop();
if (FAILED(hr))
return hr;
WebPreferences* sharedPreferences = WebPreferences::sharedStandardPreferences();
sharedPreferences->willAddToWebView();
m_preferences = sharedPreferences;
InitializeLoggingChannelsIfNecessary();
#if ENABLE(DATABASE)
WebKitInitializeWebDatabasesIfNecessary();
#endif
WebKitSetApplicationCachePathIfNecessary();
WebPlatformStrategies::initialize();
#if USE(SAFARI_THEME)
BOOL shouldPaintNativeControls;
if (SUCCEEDED(m_preferences->shouldPaintNativeControls(&shouldPaintNativeControls)))
Settings::setShouldPaintNativeControls(shouldPaintNativeControls);
#endif
BOOL useHighResolutionTimer;
if (SUCCEEDED(m_preferences->shouldUseHighResolutionTimers(&useHighResolutionTimer)))
Settings::setShouldUseHighResolutionTimers(useHighResolutionTimer);
Page::PageClients pageClients;
pageClients.chromeClient = new WebChromeClient(this);
pageClients.contextMenuClient = new WebContextMenuClient(this);
pageClients.editorClient = new WebEditorClient(this);
pageClients.dragClient = new WebDragClient(this);
pageClients.inspectorClient = new WebInspectorClient(this);
pageClients.pluginHalterClient = new WebPluginHalterClient(this);
#if ENABLE(CLIENT_BASED_GEOLOCATION)
pageClients.geolocationControllerClient = new WebGeolocationControllerClient(this);
#endif
m_page = new Page(pageClients);
BSTR localStoragePath;
if (SUCCEEDED(m_preferences->localStorageDatabasePath(&localStoragePath))) {
m_page->settings()->setLocalStorageDatabasePath(String(localStoragePath, SysStringLen(localStoragePath)));
SysFreeString(localStoragePath);
}
if (m_uiDelegate) {
BSTR path;
if (SUCCEEDED(m_uiDelegate->ftpDirectoryTemplatePath(this, &path))) {
m_page->settings()->setFTPDirectoryTemplatePath(String(path, SysStringLen(path)));
SysFreeString(path);
}
}
WebFrame* webFrame = WebFrame::createInstance();
RefPtr<Frame> coreFrame = webFrame->init(this, m_page, 0);
m_mainFrame = webFrame;
webFrame->Release(); // The WebFrame is owned by the Frame, so release our reference to it.
coreFrame->tree()->setName(String(frameName, SysStringLen(frameName)));
coreFrame->init();
setGroupName(groupName);
addToAllWebViewsSet();
#pragma warning(suppress: 4244)
SetWindowLongPtr(m_viewWindow, 0, (LONG_PTR)this);
ShowWindow(m_viewWindow, SW_SHOW);
initializeToolTipWindow();
windowAncestryDidChange();
IWebNotificationCenter* notifyCenter = WebNotificationCenter::defaultCenterInternal();
notifyCenter->addObserver(this, WebPreferences::webPreferencesChangedNotification(), static_cast<IWebPreferences*>(m_preferences.get()));
m_preferences->postPreferencesChangesNotification();
setSmartInsertDeleteEnabled(TRUE);
return hr;
}
static bool initCommonControls()
{
static bool haveInitialized = false;
if (haveInitialized)
return true;
INITCOMMONCONTROLSEX init;
init.dwSize = sizeof(init);
init.dwICC = ICC_TREEVIEW_CLASSES;
haveInitialized = !!::InitCommonControlsEx(&init);
return haveInitialized;
}
void WebView::initializeToolTipWindow()
{
if (!initCommonControls())
return;
m_toolTipHwnd = CreateWindowEx(WS_EX_TRANSPARENT, TOOLTIPS_CLASS, 0, WS_POPUP | TTS_NOPREFIX | TTS_ALWAYSTIP,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
m_viewWindow, 0, 0, 0);
if (!m_toolTipHwnd)
return;
TOOLINFO info = {0};
info.cbSize = sizeof(info);
info.uFlags = TTF_IDISHWND | TTF_SUBCLASS ;
info.uId = reinterpret_cast<UINT_PTR>(m_viewWindow);
::SendMessage(m_toolTipHwnd, TTM_ADDTOOL, 0, reinterpret_cast<LPARAM>(&info));
::SendMessage(m_toolTipHwnd, TTM_SETMAXTIPWIDTH, 0, maxToolTipWidth);
::SetWindowPos(m_toolTipHwnd, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
}
void WebView::setToolTip(const String& toolTip)
{
if (!m_toolTipHwnd)
return;
if (toolTip == m_toolTip)
return;
m_toolTip = toolTip;
if (!m_toolTip.isEmpty()) {
TOOLINFO info = {0};
info.cbSize = sizeof(info);
info.uFlags = TTF_IDISHWND;
info.uId = reinterpret_cast<UINT_PTR>(m_viewWindow);
info.lpszText = const_cast<UChar*>(m_toolTip.charactersWithNullTermination());
::SendMessage(m_toolTipHwnd, TTM_UPDATETIPTEXT, 0, reinterpret_cast<LPARAM>(&info));
}
::SendMessage(m_toolTipHwnd, TTM_ACTIVATE, !m_toolTip.isEmpty(), 0);
}
HRESULT WebView::notifyDidAddIcon(IWebNotification* notification)
{
COMPtr<IPropertyBag> propertyBag;
HRESULT hr = notification->userInfo(&propertyBag);
if (FAILED(hr))
return hr;
if (!propertyBag)
return E_FAIL;
COMPtr<CFDictionaryPropertyBag> dictionaryPropertyBag;
hr = propertyBag->QueryInterface(&dictionaryPropertyBag);
if (FAILED(hr))
return hr;
CFDictionaryRef dictionary = dictionaryPropertyBag->dictionary();
if (!dictionary)
return E_FAIL;
CFTypeRef value = CFDictionaryGetValue(dictionary, WebIconDatabase::iconDatabaseNotificationUserInfoURLKey());
if (!value)
return E_FAIL;
if (CFGetTypeID(value) != CFStringGetTypeID())
return E_FAIL;
String mainFrameURL;
if (m_mainFrame)
mainFrameURL = m_mainFrame->url().string();
if (!mainFrameURL.isEmpty() && mainFrameURL == String((CFStringRef)value))
dispatchDidReceiveIconFromWebFrame(m_mainFrame);
return hr;
}
void WebView::registerForIconNotification(bool listen)
{
IWebNotificationCenter* nc = WebNotificationCenter::defaultCenterInternal();
if (listen)
nc->addObserver(this, WebIconDatabase::iconDatabaseDidAddIconNotification(), 0);
else
nc->removeObserver(this, WebIconDatabase::iconDatabaseDidAddIconNotification(), 0);
}
void WebView::dispatchDidReceiveIconFromWebFrame(WebFrame* frame)
{
registerForIconNotification(false);
if (m_frameLoadDelegate)
// FIXME: <rdar://problem/5491010> - Pass in the right HBITMAP.
m_frameLoadDelegate->didReceiveIcon(this, 0, frame);
}
HRESULT STDMETHODCALLTYPE WebView::setUIDelegate(
/* [in] */ IWebUIDelegate* d)
{
m_uiDelegate = d;
if (m_uiDelegatePrivate)
m_uiDelegatePrivate = 0;
if (d) {
if (FAILED(d->QueryInterface(IID_IWebUIDelegatePrivate, (void**)&m_uiDelegatePrivate)))
m_uiDelegatePrivate = 0;
}
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::uiDelegate(
/* [out][retval] */ IWebUIDelegate** d)
{
if (!m_uiDelegate)
return E_FAIL;
return m_uiDelegate.copyRefTo(d);
}
HRESULT STDMETHODCALLTYPE WebView::setResourceLoadDelegate(
/* [in] */ IWebResourceLoadDelegate* d)
{
m_resourceLoadDelegate = d;
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::resourceLoadDelegate(
/* [out][retval] */ IWebResourceLoadDelegate** d)
{
if (!m_resourceLoadDelegate)
return E_FAIL;
return m_resourceLoadDelegate.copyRefTo(d);
}
HRESULT STDMETHODCALLTYPE WebView::setDownloadDelegate(
/* [in] */ IWebDownloadDelegate* d)
{
m_downloadDelegate = d;
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::downloadDelegate(
/* [out][retval] */ IWebDownloadDelegate** d)
{
if (!m_downloadDelegate)
return E_FAIL;
return m_downloadDelegate.copyRefTo(d);
}
HRESULT STDMETHODCALLTYPE WebView::setFrameLoadDelegate(
/* [in] */ IWebFrameLoadDelegate* d)
{
m_frameLoadDelegate = d;
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::frameLoadDelegate(
/* [out][retval] */ IWebFrameLoadDelegate** d)
{
if (!m_frameLoadDelegate)
return E_FAIL;
return m_frameLoadDelegate.copyRefTo(d);
}
HRESULT STDMETHODCALLTYPE WebView::setPolicyDelegate(
/* [in] */ IWebPolicyDelegate* d)
{
m_policyDelegate = d;
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::policyDelegate(
/* [out][retval] */ IWebPolicyDelegate** d)
{
if (!m_policyDelegate)
return E_FAIL;
return m_policyDelegate.copyRefTo(d);
}
HRESULT STDMETHODCALLTYPE WebView::mainFrame(
/* [out][retval] */ IWebFrame** frame)
{
if (!frame) {
ASSERT_NOT_REACHED();
return E_POINTER;
}
*frame = m_mainFrame;
if (!m_mainFrame)
return E_FAIL;
m_mainFrame->AddRef();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::focusedFrame(
/* [out][retval] */ IWebFrame** frame)
{
if (!frame) {
ASSERT_NOT_REACHED();
return E_POINTER;
}
*frame = 0;
Frame* f = m_page->focusController()->focusedFrame();
if (!f)
return E_FAIL;
WebFrame* webFrame = kit(f);
if (!webFrame)
return E_FAIL;
return webFrame->QueryInterface(IID_IWebFrame, (void**) frame);
}
HRESULT STDMETHODCALLTYPE WebView::backForwardList(
/* [out][retval] */ IWebBackForwardList** list)
{
if (!m_useBackForwardList)
return E_FAIL;
*list = WebBackForwardList::createInstance(m_page->backForwardList());
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::setMaintainsBackForwardList(
/* [in] */ BOOL flag)
{
m_useBackForwardList = !!flag;
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::goBack(
/* [retval][out] */ BOOL* succeeded)
{
*succeeded = m_page->goBack();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::goForward(
/* [retval][out] */ BOOL* succeeded)
{
*succeeded = m_page->goForward();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::goToBackForwardItem(
/* [in] */ IWebHistoryItem* item,
/* [retval][out] */ BOOL* succeeded)
{
*succeeded = FALSE;
COMPtr<WebHistoryItem> webHistoryItem;
HRESULT hr = item->QueryInterface(&webHistoryItem);
if (FAILED(hr))
return hr;
m_page->goToItem(webHistoryItem->historyItem(), FrameLoadTypeIndexedBackForward);
*succeeded = TRUE;
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::setTextSizeMultiplier(
/* [in] */ float multiplier)
{
if (!m_mainFrame)
return E_FAIL;
setZoomMultiplier(multiplier, true);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::setPageSizeMultiplier(
/* [in] */ float multiplier)
{
if (!m_mainFrame)
return E_FAIL;
setZoomMultiplier(multiplier, false);
return S_OK;
}
void WebView::setZoomMultiplier(float multiplier, bool isTextOnly)
{
m_zoomMultiplier = multiplier;
m_zoomsTextOnly = isTextOnly;
if (Frame* coreFrame = core(m_mainFrame)) {
if (FrameView* view = coreFrame->view()) {
if (m_zoomsTextOnly)
view->setPageAndTextZoomFactors(1, multiplier);
else
view->setPageAndTextZoomFactors(multiplier, 1);
}
}
}
HRESULT STDMETHODCALLTYPE WebView::textSizeMultiplier(
/* [retval][out] */ float* multiplier)
{
*multiplier = zoomMultiplier(true);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::pageSizeMultiplier(
/* [retval][out] */ float* multiplier)
{
*multiplier = zoomMultiplier(false);
return S_OK;
}
float WebView::zoomMultiplier(bool isTextOnly)
{
if (isTextOnly != m_zoomsTextOnly)
return 1.0f;
return m_zoomMultiplier;
}
HRESULT STDMETHODCALLTYPE WebView::setApplicationNameForUserAgent(
/* [in] */ BSTR applicationName)
{
m_applicationName = String(applicationName, SysStringLen(applicationName));
m_userAgentStandard = String();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::applicationNameForUserAgent(
/* [retval][out] */ BSTR* applicationName)
{
*applicationName = SysAllocStringLen(m_applicationName.characters(), m_applicationName.length());
if (!*applicationName && m_applicationName.length())
return E_OUTOFMEMORY;
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::setCustomUserAgent(
/* [in] */ BSTR userAgentString)
{
m_userAgentOverridden = userAgentString;
m_userAgentCustom = String(userAgentString, SysStringLen(userAgentString));
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::customUserAgent(
/* [retval][out] */ BSTR* userAgentString)
{
*userAgentString = 0;
if (!m_userAgentOverridden)
return S_OK;
*userAgentString = SysAllocStringLen(m_userAgentCustom.characters(), m_userAgentCustom.length());
if (!*userAgentString && m_userAgentCustom.length())
return E_OUTOFMEMORY;
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::userAgentForURL(
/* [in] */ BSTR url,
/* [retval][out] */ BSTR* userAgent)
{
String userAgentString = userAgentForKURL(MarshallingHelpers::BSTRToKURL(url));
*userAgent = SysAllocStringLen(userAgentString.characters(), userAgentString.length());
if (!*userAgent && userAgentString.length())
return E_OUTOFMEMORY;
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::supportsTextEncoding(
/* [retval][out] */ BOOL* supports)
{
*supports = TRUE;
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::setCustomTextEncodingName(
/* [in] */ BSTR encodingName)
{
if (!m_mainFrame)
return E_FAIL;
HRESULT hr;
BSTR oldEncoding;
hr = customTextEncodingName(&oldEncoding);
if (FAILED(hr))
return hr;
if (oldEncoding != encodingName && (!oldEncoding || !encodingName || _tcscmp(oldEncoding, encodingName))) {
if (Frame* coreFrame = core(m_mainFrame))
coreFrame->loader()->reloadWithOverrideEncoding(String(encodingName, SysStringLen(encodingName)));
}
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::customTextEncodingName(
/* [retval][out] */ BSTR* encodingName)
{
HRESULT hr = S_OK;
COMPtr<IWebDataSource> dataSource;
COMPtr<WebDataSource> dataSourceImpl;
*encodingName = 0;
if (!m_mainFrame)
return E_FAIL;
if (FAILED(m_mainFrame->provisionalDataSource(&dataSource)) || !dataSource) {
hr = m_mainFrame->dataSource(&dataSource);
if (FAILED(hr) || !dataSource)
return hr;
}
hr = dataSource->QueryInterface(IID_WebDataSource, (void**)&dataSourceImpl);
if (FAILED(hr))
return hr;
BString str = dataSourceImpl->documentLoader()->overrideEncoding();
if (FAILED(hr))
return hr;
if (!*encodingName)
*encodingName = SysAllocStringLen(m_overrideEncoding.characters(), m_overrideEncoding.length());
if (!*encodingName && m_overrideEncoding.length())
return E_OUTOFMEMORY;
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::setMediaStyle(
/* [in] */ BSTR /*media*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebView::mediaStyle(
/* [retval][out] */ BSTR* /*media*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebView::stringByEvaluatingJavaScriptFromString(
/* [in] */ BSTR script, // assumes input does not have "JavaScript" at the begining.
/* [retval][out] */ BSTR* result)
{
if (!result) {
ASSERT_NOT_REACHED();
return E_POINTER;
}
*result = 0;
Frame* coreFrame = core(m_mainFrame);
if (!coreFrame)
return E_FAIL;
JSC::JSValue scriptExecutionResult = coreFrame->script()->executeScript(WTF::String(script), true).jsValue();
if (!scriptExecutionResult)
return E_FAIL;
else if (scriptExecutionResult.isString()) {
JSLock lock(JSC::SilenceAssertionsOnly);
JSC::ExecState* exec = coreFrame->script()->globalObject(mainThreadNormalWorld())->globalExec();
*result = BString(ustringToString(scriptExecutionResult.getString(exec)));
}
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::windowScriptObject(
/* [retval][out] */ IWebScriptObject** /*webScriptObject*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebView::setPreferences(
/* [in] */ IWebPreferences* prefs)
{
if (!prefs)
prefs = WebPreferences::sharedStandardPreferences();
if (m_preferences == prefs)
return S_OK;
COMPtr<WebPreferences> webPrefs(Query, prefs);
if (!webPrefs)
return E_NOINTERFACE;
webPrefs->willAddToWebView();
COMPtr<WebPreferences> oldPrefs = m_preferences;
IWebNotificationCenter* nc = WebNotificationCenter::defaultCenterInternal();
nc->removeObserver(this, WebPreferences::webPreferencesChangedNotification(), static_cast<IWebPreferences*>(m_preferences.get()));
BSTR identifier = 0;
oldPrefs->identifier(&identifier);
oldPrefs->didRemoveFromWebView();
oldPrefs = 0; // Make sure we release the reference, since WebPreferences::removeReferenceForIdentifier will check for last reference to WebPreferences
m_preferences = webPrefs;
if (identifier) {
WebPreferences::removeReferenceForIdentifier(identifier);
SysFreeString(identifier);
}
nc->addObserver(this, WebPreferences::webPreferencesChangedNotification(), static_cast<IWebPreferences*>(m_preferences.get()));
m_preferences->postPreferencesChangesNotification();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::preferences(
/* [retval][out] */ IWebPreferences** prefs)
{
if (!prefs)
return E_POINTER;
*prefs = m_preferences.get();
if (m_preferences)
m_preferences->AddRef();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::setPreferencesIdentifier(
/* [in] */ BSTR /*anIdentifier*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebView::preferencesIdentifier(
/* [retval][out] */ BSTR* /*anIdentifier*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
static void systemParameterChanged(WPARAM parameter)
{
#if PLATFORM(CG)
if (parameter == SPI_SETFONTSMOOTHING || parameter == SPI_SETFONTSMOOTHINGTYPE || parameter == SPI_SETFONTSMOOTHINGCONTRAST || parameter == SPI_SETFONTSMOOTHINGORIENTATION)
wkSystemFontSmoothingChanged();
#endif
}
void WebView::windowReceivedMessage(HWND, UINT message, WPARAM wParam, LPARAM)
{
switch (message) {
case WM_NCACTIVATE:
updateActiveStateSoon();
if (!wParam)
deleteBackingStoreSoon();
break;
case WM_SETTINGCHANGE:
systemParameterChanged(wParam);
break;
}
}
void WebView::updateActiveStateSoon() const
{
// This function is called while processing the WM_NCACTIVATE message.
// While processing WM_NCACTIVATE when we are being deactivated, GetActiveWindow() will
// still return our window. If we were to call updateActiveState() in that case, we would
// wrongly think that we are still the active window. To work around this, we update our
// active state after a 0-delay timer fires, at which point GetActiveWindow() will return
// the newly-activated window.
SetTimer(m_viewWindow, UpdateActiveStateTimer, 0, 0);
}
void WebView::deleteBackingStoreSoon()
{
if (pendingDeleteBackingStoreSet.size() > 2) {
Vector<WebView*> views;
HashSet<WebView*>::iterator end = pendingDeleteBackingStoreSet.end();
for (HashSet<WebView*>::iterator it = pendingDeleteBackingStoreSet.begin(); it != end; ++it)
views.append(*it);
for (int i = 0; i < views.size(); ++i)
views[i]->deleteBackingStore();
ASSERT(pendingDeleteBackingStoreSet.isEmpty());
}
pendingDeleteBackingStoreSet.add(this);
m_deleteBackingStoreTimerActive = true;
SetTimer(m_viewWindow, DeleteBackingStoreTimer, delayBeforeDeletingBackingStoreMsec, 0);
}
void WebView::cancelDeleteBackingStoreSoon()
{
if (!m_deleteBackingStoreTimerActive)
return;
pendingDeleteBackingStoreSet.remove(this);
m_deleteBackingStoreTimerActive = false;
KillTimer(m_viewWindow, DeleteBackingStoreTimer);
}
HRESULT STDMETHODCALLTYPE WebView::setHostWindow(
/* [in] */ OLE_HANDLE oleWindow)
{
HWND window = (HWND)(ULONG64)oleWindow;
if (m_viewWindow) {
if (window)
SetParent(m_viewWindow, window);
else if (!isBeingDestroyed()) {
// Turn the WebView into a message-only window so it will no longer be a child of the
// old host window and will be hidden from screen. We only do this when
// isBeingDestroyed() is false because doing this while handling WM_DESTROY can leave
// m_viewWindow in a weird state (see <http://webkit.org/b/29337>).
SetParent(m_viewWindow, HWND_MESSAGE);
}
}
m_hostWindow = window;
windowAncestryDidChange();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::hostWindow(
/* [retval][out] */ OLE_HANDLE* window)
{
*window = (OLE_HANDLE)(ULONG64)m_hostWindow;
return S_OK;
}
static Frame *incrementFrame(Frame *curr, bool forward, bool wrapFlag)
{
return forward
? curr->tree()->traverseNextWithWrap(wrapFlag)
: curr->tree()->traversePreviousWithWrap(wrapFlag);
}
HRESULT STDMETHODCALLTYPE WebView::searchFor(
/* [in] */ BSTR str,
/* [in] */ BOOL forward,
/* [in] */ BOOL caseFlag,
/* [in] */ BOOL wrapFlag,
/* [retval][out] */ BOOL* found)
{
if (!found)
return E_INVALIDARG;
if (!m_page || !m_page->mainFrame())
return E_UNEXPECTED;
if (!str || !SysStringLen(str))
return E_INVALIDARG;
*found = m_page->findString(String(str, SysStringLen(str)), caseFlag ? TextCaseSensitive : TextCaseInsensitive, forward ? FindDirectionForward : FindDirectionBackward, wrapFlag);
return S_OK;
}
bool WebView::active()
{
HWND activeWindow = GetActiveWindow();
return (activeWindow && m_topLevelParent == findTopLevelParent(activeWindow));
}
void WebView::updateActiveState()
{
m_page->focusController()->setActive(active());
}
HRESULT STDMETHODCALLTYPE WebView::updateFocusedAndActiveState()
{
updateActiveState();
bool active = m_page->focusController()->isActive();
Frame* mainFrame = m_page->mainFrame();
Frame* focusedFrame = m_page->focusController()->focusedOrMainFrame();
mainFrame->selection()->setFocused(active && mainFrame == focusedFrame);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::executeCoreCommandByName(BSTR bName, BSTR bValue)
{
String name(bName, SysStringLen(bName));
String value(bValue, SysStringLen(bValue));
m_page->focusController()->focusedOrMainFrame()->editor()->command(name).execute(value);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::clearMainFrameName()
{
m_page->mainFrame()->tree()->clearName();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::markAllMatchesForText(
BSTR str, BOOL caseSensitive, BOOL highlight, UINT limit, UINT* matches)
{
if (!matches)
return E_INVALIDARG;
if (!m_page || !m_page->mainFrame())
return E_UNEXPECTED;
if (!str || !SysStringLen(str))
return E_INVALIDARG;
*matches = m_page->markAllMatchesForText(String(str, SysStringLen(str)), caseSensitive ? TextCaseSensitive : TextCaseInsensitive, highlight, limit);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::unmarkAllTextMatches()
{
if (!m_page || !m_page->mainFrame())
return E_UNEXPECTED;
m_page->unmarkAllTextMatches();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::rectsForTextMatches(
IEnumTextMatches** pmatches)
{
Vector<IntRect> allRects;
WebCore::Frame* frame = m_page->mainFrame();
do {
if (Document* document = frame->document()) {
IntRect visibleRect = frame->view()->visibleContentRect();
Vector<IntRect> frameRects = document->markers()->renderedRectsForMarkers(DocumentMarker::TextMatch);
IntPoint frameOffset(-frame->view()->scrollOffset().width(), -frame->view()->scrollOffset().height());
frameOffset = frame->view()->convertToContainingWindow(frameOffset);
Vector<IntRect>::iterator end = frameRects.end();
for (Vector<IntRect>::iterator it = frameRects.begin(); it < end; it++) {
it->intersect(visibleRect);
it->move(frameOffset.x(), frameOffset.y());
allRects.append(*it);
}
}
frame = incrementFrame(frame, true, false);
} while (frame);
return createMatchEnumerator(&allRects, pmatches);
}
HRESULT STDMETHODCALLTYPE WebView::generateSelectionImage(BOOL forceWhiteText, OLE_HANDLE* hBitmap)
{
*hBitmap = 0;
WebCore::Frame* frame = m_page->focusController()->focusedOrMainFrame();
if (frame) {
HBITMAP bitmap = imageFromSelection(frame, forceWhiteText ? TRUE : FALSE);
*hBitmap = (OLE_HANDLE)(ULONG64)bitmap;
}
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::selectionRect(RECT* rc)
{
WebCore::Frame* frame = m_page->focusController()->focusedOrMainFrame();
if (frame) {
IntRect ir = enclosingIntRect(frame->selection()->bounds());
ir = frame->view()->convertToContainingWindow(ir);
ir.move(-frame->view()->scrollOffset().width(), -frame->view()->scrollOffset().height());
rc->left = ir.x();
rc->top = ir.y();
rc->bottom = rc->top + ir.height();
rc->right = rc->left + ir.width();
}
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::registerViewClass(
/* [in] */ IWebDocumentView* /*view*/,
/* [in] */ IWebDocumentRepresentation* /*representation*/,
/* [in] */ BSTR /*forMIMEType*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebView::setGroupName(
/* [in] */ BSTR groupName)
{
if (!m_page)
return S_OK;
m_page->setGroupName(String(groupName, SysStringLen(groupName)));
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::groupName(
/* [retval][out] */ BSTR* groupName)
{
*groupName = 0;
if (!m_page)
return S_OK;
String groupNameString = m_page->groupName();
*groupName = SysAllocStringLen(groupNameString.characters(), groupNameString.length());
if (!*groupName && groupNameString.length())
return E_OUTOFMEMORY;
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::estimatedProgress(
/* [retval][out] */ double* estimatedProgress)
{
*estimatedProgress = m_page->progress()->estimatedProgress();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::isLoading(
/* [retval][out] */ BOOL* isLoading)
{
COMPtr<IWebDataSource> dataSource;
COMPtr<IWebDataSource> provisionalDataSource;
if (!isLoading)
return E_POINTER;
*isLoading = FALSE;
if (!m_mainFrame)
return E_FAIL;
if (SUCCEEDED(m_mainFrame->dataSource(&dataSource)))
dataSource->isLoading(isLoading);
if (*isLoading)
return S_OK;
if (SUCCEEDED(m_mainFrame->provisionalDataSource(&provisionalDataSource)))
provisionalDataSource->isLoading(isLoading);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::elementAtPoint(
/* [in] */ LPPOINT point,
/* [retval][out] */ IPropertyBag** elementDictionary)
{
if (!elementDictionary) {
ASSERT_NOT_REACHED();
return E_POINTER;
}
*elementDictionary = 0;
Frame* frame = core(m_mainFrame);
if (!frame)
return E_FAIL;
IntPoint webCorePoint = IntPoint(point->x, point->y);
HitTestResult result = HitTestResult(webCorePoint);
if (frame->contentRenderer())
result = frame->eventHandler()->hitTestResultAtPoint(webCorePoint, false);
*elementDictionary = WebElementPropertyBag::createInstance(result);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::pasteboardTypesForSelection(
/* [retval][out] */ IEnumVARIANT** /*enumVariant*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebView::writeSelectionWithPasteboardTypes(
/* [size_is][in] */ BSTR* /*types*/,
/* [in] */ int /*cTypes*/,
/* [in] */ IDataObject* /*pasteboard*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebView::pasteboardTypesForElement(
/* [in] */ IPropertyBag* /*elementDictionary*/,
/* [retval][out] */ IEnumVARIANT** /*enumVariant*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebView::writeElement(
/* [in] */ IPropertyBag* /*elementDictionary*/,
/* [size_is][in] */ BSTR* /*withPasteboardTypes*/,
/* [in] */ int /*cWithPasteboardTypes*/,
/* [in] */ IDataObject* /*pasteboard*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebView::selectedText(
/* [out, retval] */ BSTR* text)
{
if (!text) {
ASSERT_NOT_REACHED();
return E_POINTER;
}
*text = 0;
Frame* focusedFrame = (m_page && m_page->focusController()) ? m_page->focusController()->focusedOrMainFrame() : 0;
if (!focusedFrame)
return E_FAIL;
String frameSelectedText = focusedFrame->editor()->selectedText();
*text = SysAllocStringLen(frameSelectedText.characters(), frameSelectedText.length());
if (!*text && frameSelectedText.length())
return E_OUTOFMEMORY;
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::centerSelectionInVisibleArea(
/* [in] */ IUnknown* /* sender */)
{
Frame* coreFrame = core(m_mainFrame);
if (!coreFrame)
return E_FAIL;
coreFrame->selection()->revealSelection(ScrollAlignment::alignCenterAlways);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::moveDragCaretToPoint(
/* [in] */ LPPOINT /*point*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebView::removeDragCaret( void)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebView::setDrawsBackground(
/* [in] */ BOOL /*drawsBackground*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebView::drawsBackground(
/* [retval][out] */ BOOL* /*drawsBackground*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebView::setMainFrameURL(
/* [in] */ BSTR /*urlString*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebView::mainFrameURL(
/* [retval][out] */ BSTR* urlString)
{
if (!urlString)
return E_POINTER;
if (!m_mainFrame)
return E_FAIL;
COMPtr<IWebDataSource> dataSource;
if (FAILED(m_mainFrame->provisionalDataSource(&dataSource))) {
if (FAILED(m_mainFrame->dataSource(&dataSource)))
return E_FAIL;
}
if (!dataSource) {
*urlString = 0;
return S_OK;
}
COMPtr<IWebMutableURLRequest> request;
if (FAILED(dataSource->request(&request)) || !request)
return E_FAIL;
if (FAILED(request->URL(urlString)))
return E_FAIL;
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::mainFrameDocument(
/* [retval][out] */ IDOMDocument** document)
{
if (document)
*document = 0;
if (!m_mainFrame)
return E_FAIL;
return m_mainFrame->DOMDocument(document);
}
HRESULT STDMETHODCALLTYPE WebView::mainFrameTitle(
/* [retval][out] */ BSTR* /*title*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebView::mainFrameIcon(
/* [retval][out] */ OLE_HANDLE* /*hBitmap*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebView::registerURLSchemeAsLocal(
/* [in] */ BSTR scheme)
{
if (!scheme)
return E_POINTER;
SchemeRegistry::registerURLSchemeAsLocal(String(scheme, ::SysStringLen(scheme)));
return S_OK;
}
// IWebIBActions ---------------------------------------------------------------
HRESULT STDMETHODCALLTYPE WebView::takeStringURLFrom(
/* [in] */ IUnknown* /*sender*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebView::stopLoading(
/* [in] */ IUnknown* /*sender*/)
{
if (!m_mainFrame)
return E_FAIL;
return m_mainFrame->stopLoading();
}
HRESULT STDMETHODCALLTYPE WebView::reload(
/* [in] */ IUnknown* /*sender*/)
{
if (!m_mainFrame)
return E_FAIL;
return m_mainFrame->reload();
}
HRESULT STDMETHODCALLTYPE WebView::canGoBack(
/* [in] */ IUnknown* /*sender*/,
/* [retval][out] */ BOOL* result)
{
*result = !!(m_page->backForwardList()->backItem() && !m_page->defersLoading());
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::goBack(
/* [in] */ IUnknown* /*sender*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebView::canGoForward(
/* [in] */ IUnknown* /*sender*/,
/* [retval][out] */ BOOL* result)
{
*result = !!(m_page->backForwardList()->forwardItem() && !m_page->defersLoading());
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::goForward(
/* [in] */ IUnknown* /*sender*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
// FIXME: This code should move into WebCore so it can be shared by all the WebKits.
#define MinimumZoomMultiplier 0.5f
#define MaximumZoomMultiplier 3.0f
#define ZoomMultiplierRatio 1.2f
HRESULT STDMETHODCALLTYPE WebView::canMakeTextLarger(
/* [in] */ IUnknown* /*sender*/,
/* [retval][out] */ BOOL* result)
{
bool canGrowMore = canZoomIn(m_zoomsTextOnly);
*result = canGrowMore ? TRUE : FALSE;
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::canZoomPageIn(
/* [in] */ IUnknown* /*sender*/,
/* [retval][out] */ BOOL* result)
{
bool canGrowMore = canZoomIn(false);
*result = canGrowMore ? TRUE : FALSE;
return S_OK;
}
bool WebView::canZoomIn(bool isTextOnly)
{
return zoomMultiplier(isTextOnly) * ZoomMultiplierRatio < MaximumZoomMultiplier;
}
HRESULT STDMETHODCALLTYPE WebView::makeTextLarger(
/* [in] */ IUnknown* /*sender*/)
{
return zoomIn(m_zoomsTextOnly);
}
HRESULT STDMETHODCALLTYPE WebView::zoomPageIn(
/* [in] */ IUnknown* /*sender*/)
{
return zoomIn(false);
}
HRESULT WebView::zoomIn(bool isTextOnly)
{
if (!canZoomIn(isTextOnly))
return E_FAIL;
setZoomMultiplier(zoomMultiplier(isTextOnly) * ZoomMultiplierRatio, isTextOnly);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::canMakeTextSmaller(
/* [in] */ IUnknown* /*sender*/,
/* [retval][out] */ BOOL* result)
{
bool canShrinkMore = canZoomOut(m_zoomsTextOnly);
*result = canShrinkMore ? TRUE : FALSE;
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::canZoomPageOut(
/* [in] */ IUnknown* /*sender*/,
/* [retval][out] */ BOOL* result)
{
bool canShrinkMore = canZoomOut(false);
*result = canShrinkMore ? TRUE : FALSE;
return S_OK;
}
bool WebView::canZoomOut(bool isTextOnly)
{
return zoomMultiplier(isTextOnly) / ZoomMultiplierRatio > MinimumZoomMultiplier;
}
HRESULT STDMETHODCALLTYPE WebView::makeTextSmaller(
/* [in] */ IUnknown* /*sender*/)
{
return zoomOut(m_zoomsTextOnly);
}
HRESULT STDMETHODCALLTYPE WebView::zoomPageOut(
/* [in] */ IUnknown* /*sender*/)
{
return zoomOut(false);
}
HRESULT WebView::zoomOut(bool isTextOnly)
{
if (!canZoomOut(isTextOnly))
return E_FAIL;
setZoomMultiplier(zoomMultiplier(isTextOnly) / ZoomMultiplierRatio, isTextOnly);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::canMakeTextStandardSize(
/* [in] */ IUnknown* /*sender*/,
/* [retval][out] */ BOOL* result)
{
// Since we always reset text zoom and page zoom together, this should continue to return an answer about text zoom even if its not enabled.
bool notAlreadyStandard = canResetZoom(true);
*result = notAlreadyStandard ? TRUE : FALSE;
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::canResetPageZoom(
/* [in] */ IUnknown* /*sender*/,
/* [retval][out] */ BOOL* result)
{
bool notAlreadyStandard = canResetZoom(false);
*result = notAlreadyStandard ? TRUE : FALSE;
return S_OK;
}
bool WebView::canResetZoom(bool isTextOnly)
{
return zoomMultiplier(isTextOnly) != 1.0f;
}
HRESULT STDMETHODCALLTYPE WebView::makeTextStandardSize(
/* [in] */ IUnknown* /*sender*/)
{
return resetZoom(true);
}
HRESULT STDMETHODCALLTYPE WebView::resetPageZoom(
/* [in] */ IUnknown* /*sender*/)
{
return resetZoom(false);
}
HRESULT WebView::resetZoom(bool isTextOnly)
{
if (!canResetZoom(isTextOnly))
return E_FAIL;
setZoomMultiplier(1.0f, isTextOnly);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::toggleContinuousSpellChecking(
/* [in] */ IUnknown* /*sender*/)
{
HRESULT hr;
BOOL enabled;
if (FAILED(hr = isContinuousSpellCheckingEnabled(&enabled)))
return hr;
return setContinuousSpellCheckingEnabled(enabled ? FALSE : TRUE);
}
HRESULT STDMETHODCALLTYPE WebView::toggleSmartInsertDelete(
/* [in] */ IUnknown* /*sender*/)
{
BOOL enabled = FALSE;
HRESULT hr = smartInsertDeleteEnabled(&enabled);
if (FAILED(hr))
return hr;
return setSmartInsertDeleteEnabled(enabled ? FALSE : TRUE);
}
HRESULT STDMETHODCALLTYPE WebView::toggleGrammarChecking(
/* [in] */ IUnknown* /*sender*/)
{
BOOL enabled;
HRESULT hr = isGrammarCheckingEnabled(&enabled);
if (FAILED(hr))
return hr;
return setGrammarCheckingEnabled(enabled ? FALSE : TRUE);
}
HRESULT STDMETHODCALLTYPE WebView::reloadFromOrigin(
/* [in] */ IUnknown* /*sender*/)
{
if (!m_mainFrame)
return E_FAIL;
return m_mainFrame->reloadFromOrigin();
}
// IWebViewCSS -----------------------------------------------------------------
HRESULT STDMETHODCALLTYPE WebView::computedStyleForElement(
/* [in] */ IDOMElement* /*element*/,
/* [in] */ BSTR /*pseudoElement*/,
/* [retval][out] */ IDOMCSSStyleDeclaration** /*style*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
// IWebViewEditing -------------------------------------------------------------
HRESULT STDMETHODCALLTYPE WebView::editableDOMRangeForPoint(
/* [in] */ LPPOINT /*point*/,
/* [retval][out] */ IDOMRange** /*range*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebView::setSelectedDOMRange(
/* [in] */ IDOMRange* /*range*/,
/* [in] */ WebSelectionAffinity /*affinity*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebView::selectedDOMRange(
/* [retval][out] */ IDOMRange** /*range*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebView::selectionAffinity(
/* [retval][out][retval][out] */ WebSelectionAffinity* /*affinity*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebView::setEditable(
/* [in] */ BOOL /*flag*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebView::isEditable(
/* [retval][out] */ BOOL* /*isEditable*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebView::setTypingStyle(
/* [in] */ IDOMCSSStyleDeclaration* /*style*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebView::typingStyle(
/* [retval][out] */ IDOMCSSStyleDeclaration** /*style*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebView::setSmartInsertDeleteEnabled(
/* [in] */ BOOL flag)
{
m_smartInsertDeleteEnabled = !!flag;
if (m_smartInsertDeleteEnabled)
setSelectTrailingWhitespaceEnabled(false);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::smartInsertDeleteEnabled(
/* [retval][out] */ BOOL* enabled)
{
*enabled = m_smartInsertDeleteEnabled ? TRUE : FALSE;
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::setSelectTrailingWhitespaceEnabled(
/* [in] */ BOOL flag)
{
m_selectTrailingWhitespaceEnabled = !!flag;
if (m_selectTrailingWhitespaceEnabled)
setSmartInsertDeleteEnabled(false);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::isSelectTrailingWhitespaceEnabled(
/* [retval][out] */ BOOL* enabled)
{
*enabled = m_selectTrailingWhitespaceEnabled ? TRUE : FALSE;
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::setContinuousSpellCheckingEnabled(
/* [in] */ BOOL flag)
{
if (continuousSpellCheckingEnabled != !!flag) {
continuousSpellCheckingEnabled = !!flag;
COMPtr<IWebPreferences> prefs;
if (SUCCEEDED(preferences(&prefs)))
prefs->setContinuousSpellCheckingEnabled(flag);
}
BOOL spellCheckingEnabled;
if (SUCCEEDED(isContinuousSpellCheckingEnabled(&spellCheckingEnabled)) && spellCheckingEnabled)
preflightSpellChecker();
else
m_mainFrame->unmarkAllMisspellings();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::isContinuousSpellCheckingEnabled(
/* [retval][out] */ BOOL* enabled)
{
*enabled = (continuousSpellCheckingEnabled && continuousCheckingAllowed()) ? TRUE : FALSE;
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::spellCheckerDocumentTag(
/* [retval][out] */ int* tag)
{
// we just use this as a flag to indicate that we've spell checked the document
// and need to close the spell checker out when the view closes.
*tag = 0;
m_hasSpellCheckerDocumentTag = true;
return S_OK;
}
static COMPtr<IWebEditingDelegate> spellingDelegateForTimer;
static void preflightSpellCheckerNow()
{
spellingDelegateForTimer->preflightChosenSpellServer();
spellingDelegateForTimer = 0;
}
static void CALLBACK preflightSpellCheckerTimerCallback(HWND, UINT, UINT_PTR id, DWORD)
{
::KillTimer(0, id);
preflightSpellCheckerNow();
}
void WebView::preflightSpellChecker()
{
// As AppKit does, we wish to delay tickling the shared spellchecker into existence on application launch.
if (!m_editingDelegate)
return;
BOOL exists;
spellingDelegateForTimer = m_editingDelegate;
if (SUCCEEDED(m_editingDelegate->sharedSpellCheckerExists(&exists)) && exists)
preflightSpellCheckerNow();
else
::SetTimer(0, 0, 2000, preflightSpellCheckerTimerCallback);
}
bool WebView::continuousCheckingAllowed()
{
static bool allowContinuousSpellChecking = true;
static bool readAllowContinuousSpellCheckingDefault = false;
if (!readAllowContinuousSpellCheckingDefault) {
COMPtr<IWebPreferences> prefs;
if (SUCCEEDED(preferences(&prefs))) {
BOOL allowed;
prefs->allowContinuousSpellChecking(&allowed);
allowContinuousSpellChecking = !!allowed;
}
readAllowContinuousSpellCheckingDefault = true;
}
return allowContinuousSpellChecking;
}
HRESULT STDMETHODCALLTYPE WebView::undoManager(
/* [retval][out] */ IWebUndoManager** /*manager*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebView::setEditingDelegate(
/* [in] */ IWebEditingDelegate* d)
{
m_editingDelegate = d;
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::editingDelegate(
/* [retval][out] */ IWebEditingDelegate** d)
{
if (!d) {
ASSERT_NOT_REACHED();
return E_POINTER;
}
*d = m_editingDelegate.get();
if (!*d)
return E_FAIL;
(*d)->AddRef();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::styleDeclarationWithText(
/* [in] */ BSTR /*text*/,
/* [retval][out] */ IDOMCSSStyleDeclaration** /*style*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebView::hasSelectedRange(
/* [retval][out] */ BOOL* hasSelectedRange)
{
*hasSelectedRange = m_page->mainFrame()->selection()->isRange();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::cutEnabled(
/* [retval][out] */ BOOL* enabled)
{
Editor* editor = m_page->focusController()->focusedOrMainFrame()->editor();
*enabled = editor->canCut() || editor->canDHTMLCut();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::copyEnabled(
/* [retval][out] */ BOOL* enabled)
{
Editor* editor = m_page->focusController()->focusedOrMainFrame()->editor();
*enabled = editor->canCopy() || editor->canDHTMLCopy();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::pasteEnabled(
/* [retval][out] */ BOOL* enabled)
{
Editor* editor = m_page->focusController()->focusedOrMainFrame()->editor();
*enabled = editor->canPaste() || editor->canDHTMLPaste();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::deleteEnabled(
/* [retval][out] */ BOOL* enabled)
{
*enabled = m_page->focusController()->focusedOrMainFrame()->editor()->canDelete();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::editingEnabled(
/* [retval][out] */ BOOL* enabled)
{
*enabled = m_page->focusController()->focusedOrMainFrame()->editor()->canEdit();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::isGrammarCheckingEnabled(
/* [retval][out] */ BOOL* enabled)
{
*enabled = grammarCheckingEnabled ? TRUE : FALSE;
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::setGrammarCheckingEnabled(
BOOL enabled)
{
if (!m_editingDelegate) {
LOG_ERROR("No NSSpellChecker");
return E_FAIL;
}
if (grammarCheckingEnabled == !!enabled)
return S_OK;
grammarCheckingEnabled = !!enabled;
COMPtr<IWebPreferences> prefs;
if (SUCCEEDED(preferences(&prefs)))
prefs->setGrammarCheckingEnabled(enabled);
m_editingDelegate->updateGrammar();
// We call _preflightSpellChecker when turning continuous spell checking on, but we don't need to do that here
// because grammar checking only occurs on code paths that already preflight spell checking appropriately.
BOOL grammarEnabled;
if (SUCCEEDED(isGrammarCheckingEnabled(&grammarEnabled)) && !grammarEnabled)
m_mainFrame->unmarkAllBadGrammar();
return S_OK;
}
// IWebViewUndoableEditing -----------------------------------------------------
HRESULT STDMETHODCALLTYPE WebView::replaceSelectionWithNode(
/* [in] */ IDOMNode* /*node*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebView::replaceSelectionWithText(
/* [in] */ BSTR text)
{
String textString(text, ::SysStringLen(text));
Position start = m_page->mainFrame()->selection()->selection().start();
m_page->focusController()->focusedOrMainFrame()->editor()->insertText(textString, 0);
m_page->mainFrame()->selection()->setBase(start);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::replaceSelectionWithMarkupString(
/* [in] */ BSTR /*markupString*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebView::replaceSelectionWithArchive(
/* [in] */ IWebArchive* /*archive*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebView::deleteSelection( void)
{
Editor* editor = m_page->focusController()->focusedOrMainFrame()->editor();
editor->deleteSelectionWithSmartDelete(editor->canSmartCopyOrDelete());
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::clearSelection( void)
{
m_page->focusController()->focusedOrMainFrame()->selection()->clear();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::applyStyle(
/* [in] */ IDOMCSSStyleDeclaration* /*style*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
// IWebViewEditingActions ------------------------------------------------------
HRESULT STDMETHODCALLTYPE WebView::copy(
/* [in] */ IUnknown* /*sender*/)
{
m_page->focusController()->focusedOrMainFrame()->editor()->command("Copy").execute();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::cut(
/* [in] */ IUnknown* /*sender*/)
{
m_page->focusController()->focusedOrMainFrame()->editor()->command("Cut").execute();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::paste(
/* [in] */ IUnknown* /*sender*/)
{
m_page->focusController()->focusedOrMainFrame()->editor()->command("Paste").execute();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::copyURL(
/* [in] */ BSTR url)
{
m_page->focusController()->focusedOrMainFrame()->editor()->copyURL(MarshallingHelpers::BSTRToKURL(url), "");
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::copyFont(
/* [in] */ IUnknown* /*sender*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebView::pasteFont(
/* [in] */ IUnknown* /*sender*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebView::delete_(
/* [in] */ IUnknown* /*sender*/)
{
m_page->focusController()->focusedOrMainFrame()->editor()->command("Delete").execute();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::pasteAsPlainText(
/* [in] */ IUnknown* /*sender*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebView::pasteAsRichText(
/* [in] */ IUnknown* /*sender*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebView::changeFont(
/* [in] */ IUnknown* /*sender*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebView::changeAttributes(
/* [in] */ IUnknown* /*sender*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebView::changeDocumentBackgroundColor(
/* [in] */ IUnknown* /*sender*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebView::changeColor(
/* [in] */ IUnknown* /*sender*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebView::alignCenter(
/* [in] */ IUnknown* /*sender*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebView::alignJustified(
/* [in] */ IUnknown* /*sender*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebView::alignLeft(
/* [in] */ IUnknown* /*sender*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebView::alignRight(
/* [in] */ IUnknown* /*sender*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebView::checkSpelling(
/* [in] */ IUnknown* /*sender*/)
{
if (!m_editingDelegate) {
LOG_ERROR("No NSSpellChecker");
return E_FAIL;
}
core(m_mainFrame)->editor()->advanceToNextMisspelling();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::showGuessPanel(
/* [in] */ IUnknown* /*sender*/)
{
if (!m_editingDelegate) {
LOG_ERROR("No NSSpellChecker");
return E_FAIL;
}
// Post-Tiger, this menu item is a show/hide toggle, to match AppKit. Leave Tiger behavior alone
// to match rest of OS X.
BOOL showing;
if (SUCCEEDED(m_editingDelegate->spellingUIIsShowing(&showing)) && showing) {
m_editingDelegate->showSpellingUI(FALSE);
}
core(m_mainFrame)->editor()->advanceToNextMisspelling(true);
m_editingDelegate->showSpellingUI(TRUE);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::performFindPanelAction(
/* [in] */ IUnknown* /*sender*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebView::startSpeaking(
/* [in] */ IUnknown* /*sender*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebView::stopSpeaking(
/* [in] */ IUnknown* /*sender*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
// IWebNotificationObserver -----------------------------------------------------------------
HRESULT STDMETHODCALLTYPE WebView::onNotify(
/* [in] */ IWebNotification* notification)
{
BSTR nameBSTR;
HRESULT hr = notification->name(&nameBSTR);
if (FAILED(hr))
return hr;
BString name;
name.adoptBSTR(nameBSTR);
if (!wcscmp(name, WebIconDatabase::iconDatabaseDidAddIconNotification()))
return notifyDidAddIcon(notification);
if (!wcscmp(name, WebPreferences::webPreferencesChangedNotification()))
return notifyPreferencesChanged(notification);
return hr;
}
HRESULT WebView::notifyPreferencesChanged(IWebNotification* notification)
{
HRESULT hr;
COMPtr<IUnknown> unkPrefs;
hr = notification->getObject(&unkPrefs);
if (FAILED(hr))
return hr;
COMPtr<IWebPreferences> preferences(Query, unkPrefs);
if (!preferences)
return E_NOINTERFACE;
ASSERT(preferences == m_preferences);
BSTR str;
int size;
BOOL enabled;
Settings* settings = m_page->settings();
hr = preferences->cursiveFontFamily(&str);
if (FAILED(hr))
return hr;
settings->setCursiveFontFamily(AtomicString(str, SysStringLen(str)));
SysFreeString(str);
hr = preferences->defaultFixedFontSize(&size);
if (FAILED(hr))
return hr;
settings->setDefaultFixedFontSize(size);
hr = preferences->defaultFontSize(&size);
if (FAILED(hr))
return hr;
settings->setDefaultFontSize(size);
hr = preferences->defaultTextEncodingName(&str);
if (FAILED(hr))
return hr;
settings->setDefaultTextEncodingName(String(str, SysStringLen(str)));
SysFreeString(str);
hr = preferences->fantasyFontFamily(&str);
if (FAILED(hr))
return hr;
settings->setFantasyFontFamily(AtomicString(str, SysStringLen(str)));
SysFreeString(str);
hr = preferences->fixedFontFamily(&str);
if (FAILED(hr))
return hr;
settings->setFixedFontFamily(AtomicString(str, SysStringLen(str)));
SysFreeString(str);
hr = preferences->isJavaEnabled(&enabled);
if (FAILED(hr))
return hr;
settings->setJavaEnabled(!!enabled);
hr = preferences->isJavaScriptEnabled(&enabled);
if (FAILED(hr))
return hr;
settings->setJavaScriptEnabled(!!enabled);
hr = preferences->javaScriptCanOpenWindowsAutomatically(&enabled);
if (FAILED(hr))
return hr;
settings->setJavaScriptCanOpenWindowsAutomatically(!!enabled);
hr = preferences->minimumFontSize(&size);
if (FAILED(hr))
return hr;
settings->setMinimumFontSize(size);
hr = preferences->minimumLogicalFontSize(&size);
if (FAILED(hr))
return hr;
settings->setMinimumLogicalFontSize(size);
hr = preferences->arePlugInsEnabled(&enabled);
if (FAILED(hr))
return hr;
settings->setPluginsEnabled(!!enabled);
hr = preferences->privateBrowsingEnabled(&enabled);
if (FAILED(hr))
return hr;
settings->setPrivateBrowsingEnabled(!!enabled);
hr = preferences->sansSerifFontFamily(&str);
if (FAILED(hr))
return hr;
settings->setSansSerifFontFamily(AtomicString(str, SysStringLen(str)));
SysFreeString(str);
hr = preferences->serifFontFamily(&str);
if (FAILED(hr))
return hr;
settings->setSerifFontFamily(AtomicString(str, SysStringLen(str)));
SysFreeString(str);
hr = preferences->standardFontFamily(&str);
if (FAILED(hr))
return hr;
settings->setStandardFontFamily(AtomicString(str, SysStringLen(str)));
SysFreeString(str);
hr = preferences->loadsImagesAutomatically(&enabled);
if (FAILED(hr))
return hr;
settings->setLoadsImagesAutomatically(!!enabled);
hr = preferences->userStyleSheetEnabled(&enabled);
if (FAILED(hr))
return hr;
if (enabled) {
hr = preferences->userStyleSheetLocation(&str);
if (FAILED(hr))
return hr;
RetainPtr<CFStringRef> urlString(AdoptCF, String(str, SysStringLen(str)).createCFString());
RetainPtr<CFURLRef> url(AdoptCF, CFURLCreateWithString(kCFAllocatorDefault, urlString.get(), 0));
// Check if the passed in string is a path and convert it to a URL.
// FIXME: This is a workaround for nightly builds until we can get Safari to pass
// in an URL here. See <rdar://problem/5478378>
if (!url) {
DWORD len = SysStringLen(str) + 1;
int result = WideCharToMultiByte(CP_UTF8, 0, str, len, 0, 0, 0, 0);
Vector<UInt8> utf8Path(result);
if (!WideCharToMultiByte(CP_UTF8, 0, str, len, (LPSTR)utf8Path.data(), result, 0, 0))
return E_FAIL;
url.adoptCF(CFURLCreateFromFileSystemRepresentation(0, utf8Path.data(), result - 1, false));
}
settings->setUserStyleSheetLocation(url.get());
SysFreeString(str);
} else {
settings->setUserStyleSheetLocation(KURL());
}
hr = preferences->shouldPrintBackgrounds(&enabled);
if (FAILED(hr))
return hr;
settings->setShouldPrintBackgrounds(!!enabled);
hr = preferences->textAreasAreResizable(&enabled);
if (FAILED(hr))
return hr;
settings->setTextAreasAreResizable(!!enabled);
WebKitEditableLinkBehavior behavior;
hr = preferences->editableLinkBehavior(&behavior);
if (FAILED(hr))
return hr;
settings->setEditableLinkBehavior((EditableLinkBehavior)behavior);
WebKitEditingBehavior editingBehavior;
hr = preferences->editingBehavior(&editingBehavior);
if (FAILED(hr))
return hr;
settings->setEditingBehaviorType((EditingBehaviorType)editingBehavior);
hr = preferences->usesPageCache(&enabled);
if (FAILED(hr))
return hr;
settings->setUsesPageCache(!!enabled);
hr = preferences->isDOMPasteAllowed(&enabled);
if (FAILED(hr))
return hr;
settings->setDOMPasteAllowed(!!enabled);
hr = preferences->shouldPaintCustomScrollbars(&enabled);
if (FAILED(hr))
return hr;
settings->setShouldPaintCustomScrollbars(!!enabled);
hr = preferences->zoomsTextOnly(&enabled);
if (FAILED(hr))
return hr;
if (m_zoomsTextOnly != !!enabled)
setZoomMultiplier(m_zoomMultiplier, enabled);
settings->setShowsURLsInToolTips(false);
settings->setForceFTPDirectoryListings(true);
settings->setDeveloperExtrasEnabled(developerExtrasEnabled());
settings->setNeedsSiteSpecificQuirks(s_allowSiteSpecificHacks);
FontSmoothingType smoothingType;
hr = preferences->fontSmoothing(&smoothingType);
if (FAILED(hr))
return hr;
settings->setFontRenderingMode(smoothingType != FontSmoothingTypeWindows ? NormalRenderingMode : AlternateRenderingMode);
COMPtr<IWebPreferencesPrivate> prefsPrivate(Query, preferences);
if (prefsPrivate) {
hr = prefsPrivate->authorAndUserStylesEnabled(&enabled);
if (FAILED(hr))
return hr;
settings->setAuthorAndUserStylesEnabled(enabled);
}
hr = prefsPrivate->inApplicationChromeMode(&enabled);
if (FAILED(hr))
return hr;
settings->setApplicationChromeMode(enabled);
hr = prefsPrivate->offlineWebApplicationCacheEnabled(&enabled);
if (FAILED(hr))
return hr;
settings->setOfflineWebApplicationCacheEnabled(enabled);
#if ENABLE(DATABASE)
hr = prefsPrivate->databasesEnabled(&enabled);
if (FAILED(hr))
return hr;
AbstractDatabase::setIsAvailable(enabled);
#endif
hr = prefsPrivate->localStorageEnabled(&enabled);
if (FAILED(hr))
return hr;
settings->setLocalStorageEnabled(enabled);
hr = prefsPrivate->experimentalNotificationsEnabled(&enabled);
if (FAILED(hr))
return hr;
settings->setExperimentalNotificationsEnabled(enabled);
hr = prefsPrivate->isWebSecurityEnabled(&enabled);
if (FAILED(hr))
return hr;
settings->setWebSecurityEnabled(!!enabled);
hr = prefsPrivate->allowUniversalAccessFromFileURLs(&enabled);
if (FAILED(hr))
return hr;
settings->setAllowUniversalAccessFromFileURLs(!!enabled);
hr = prefsPrivate->allowFileAccessFromFileURLs(&enabled);
if (FAILED(hr))
return hr;
settings->setAllowFileAccessFromFileURLs(!!enabled);
hr = prefsPrivate->javaScriptCanAccessClipboard(&enabled);
if (FAILED(hr))
return hr;
settings->setJavaScriptCanAccessClipboard(!!enabled);
hr = prefsPrivate->isXSSAuditorEnabled(&enabled);
if (FAILED(hr))
return hr;
settings->setXSSAuditorEnabled(!!enabled);
#if USE(SAFARI_THEME)
hr = prefsPrivate->shouldPaintNativeControls(&enabled);
if (FAILED(hr))
return hr;
settings->setShouldPaintNativeControls(!!enabled);
#endif
hr = prefsPrivate->shouldUseHighResolutionTimers(&enabled);
if (FAILED(hr))
return hr;
settings->setShouldUseHighResolutionTimers(enabled);
UINT runTime;
hr = prefsPrivate->pluginAllowedRunTime(&runTime);
if (FAILED(hr))
return hr;
settings->setPluginAllowedRunTime(runTime);
hr = prefsPrivate->isFrameFlatteningEnabled(&enabled);
if (FAILED(hr))
return hr;
settings->setFrameFlatteningEnabled(enabled);
#if USE(ACCELERATED_COMPOSITING)
hr = prefsPrivate->acceleratedCompositingEnabled(&enabled);
if (FAILED(hr))
return hr;
settings->setAcceleratedCompositingEnabled(enabled);
#endif
hr = prefsPrivate->showDebugBorders(&enabled);
if (FAILED(hr))
return hr;
settings->setShowDebugBorders(enabled);
hr = prefsPrivate->showRepaintCounter(&enabled);
if (FAILED(hr))
return hr;
settings->setShowRepaintCounter(enabled);
#if ENABLE(3D_CANVAS)
settings->setWebGLEnabled(true);
#endif // ENABLE(3D_CANVAS)
hr = prefsPrivate->isDNSPrefetchingEnabled(&enabled);
if (FAILED(hr))
return hr;
settings->setDNSPrefetchingEnabled(enabled);
hr = prefsPrivate->memoryInfoEnabled(&enabled);
if (FAILED(hr))
return hr;
settings->setMemoryInfoEnabled(enabled);
if (!m_closeWindowTimer)
m_mainFrame->invalidate(); // FIXME
hr = updateSharedSettingsFromPreferencesIfNeeded(preferences.get());
if (FAILED(hr))
return hr;
return S_OK;
}
HRESULT updateSharedSettingsFromPreferencesIfNeeded(IWebPreferences* preferences)
{
if (preferences != WebPreferences::sharedStandardPreferences())
return S_OK;
WebKitCookieStorageAcceptPolicy acceptPolicy;
HRESULT hr = preferences->cookieStorageAcceptPolicy(&acceptPolicy);
if (FAILED(hr))
return hr;
#if USE(CFNETWORK)
// Set cookie storage accept policy
if (CFHTTPCookieStorageRef cookieStorage = currentCookieStorage())
CFHTTPCookieStorageSetCookieAcceptPolicy(cookieStorage, acceptPolicy);
#endif
return S_OK;
}
// IWebViewPrivate ------------------------------------------------------------
HRESULT STDMETHODCALLTYPE WebView::MIMETypeForExtension(
/* [in] */ BSTR extension,
/* [retval][out] */ BSTR* mimeType)
{
if (!mimeType)
return E_POINTER;
String extensionStr(extension, SysStringLen(extension));
*mimeType = BString(MIMETypeRegistry::getMIMETypeForExtension(extensionStr)).release();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::setCustomDropTarget(
/* [in] */ IDropTarget* dt)
{
ASSERT(::IsWindow(m_viewWindow));
if (!dt)
return E_POINTER;
m_hasCustomDropTarget = true;
revokeDragDrop();
return ::RegisterDragDrop(m_viewWindow,dt);
}
HRESULT STDMETHODCALLTYPE WebView::removeCustomDropTarget()
{
if (!m_hasCustomDropTarget)
return S_OK;
m_hasCustomDropTarget = false;
revokeDragDrop();
return registerDragDrop();
}
HRESULT STDMETHODCALLTYPE WebView::setInViewSourceMode(
/* [in] */ BOOL flag)
{
if (!m_mainFrame)
return E_FAIL;
return m_mainFrame->setInViewSourceMode(flag);
}
HRESULT STDMETHODCALLTYPE WebView::inViewSourceMode(
/* [retval][out] */ BOOL* flag)
{
if (!m_mainFrame)
return E_FAIL;
return m_mainFrame->inViewSourceMode(flag);
}
HRESULT STDMETHODCALLTYPE WebView::viewWindow(
/* [retval][out] */ OLE_HANDLE *window)
{
*window = (OLE_HANDLE)(ULONG64)m_viewWindow;
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::setFormDelegate(
/* [in] */ IWebFormDelegate *formDelegate)
{
m_formDelegate = formDelegate;
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::formDelegate(
/* [retval][out] */ IWebFormDelegate **formDelegate)
{
if (!m_formDelegate)
return E_FAIL;
return m_formDelegate.copyRefTo(formDelegate);
}
HRESULT STDMETHODCALLTYPE WebView::setFrameLoadDelegatePrivate(
/* [in] */ IWebFrameLoadDelegatePrivate* d)
{
m_frameLoadDelegatePrivate = d;
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::frameLoadDelegatePrivate(
/* [out][retval] */ IWebFrameLoadDelegatePrivate** d)
{
if (!m_frameLoadDelegatePrivate)
return E_FAIL;
return m_frameLoadDelegatePrivate.copyRefTo(d);
}
HRESULT STDMETHODCALLTYPE WebView::scrollOffset(
/* [retval][out] */ LPPOINT offset)
{
if (!offset)
return E_POINTER;
IntSize offsetIntSize = m_page->mainFrame()->view()->scrollOffset();
offset->x = offsetIntSize.width();
offset->y = offsetIntSize.height();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::scrollBy(
/* [in] */ LPPOINT offset)
{
if (!offset)
return E_POINTER;
m_page->mainFrame()->view()->scrollBy(IntSize(offset->x, offset->y));
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::visibleContentRect(
/* [retval][out] */ LPRECT rect)
{
if (!rect)
return E_POINTER;
FloatRect visibleContent = m_page->mainFrame()->view()->visibleContentRect();
rect->left = (LONG) visibleContent.x();
rect->top = (LONG) visibleContent.y();
rect->right = (LONG) visibleContent.right();
rect->bottom = (LONG) visibleContent.bottom();
return S_OK;
}
static DWORD dragOperationToDragCursor(DragOperation op) {
DWORD res = DROPEFFECT_NONE;
if (op & DragOperationCopy)
res = DROPEFFECT_COPY;
else if (op & DragOperationLink)
res = DROPEFFECT_LINK;
else if (op & DragOperationMove)
res = DROPEFFECT_MOVE;
else if (op & DragOperationGeneric)
res = DROPEFFECT_MOVE; //This appears to be the Firefox behaviour
return res;
}
DragOperation WebView::keyStateToDragOperation(DWORD grfKeyState) const
{
if (!m_page)
return DragOperationNone;
// Conforms to Microsoft's key combinations as documented for
// IDropTarget::DragOver. Note, grfKeyState is the current
// state of the keyboard modifier keys on the keyboard. See:
// <http://msdn.microsoft.com/en-us/library/ms680129(VS.85).aspx>.
DragOperation operation = m_page->dragController()->sourceDragOperation();
if ((grfKeyState & (MK_CONTROL | MK_SHIFT)) == (MK_CONTROL | MK_SHIFT))
operation = DragOperationLink;
else if ((grfKeyState & MK_CONTROL) == MK_CONTROL)
operation = DragOperationCopy;
else if ((grfKeyState & MK_SHIFT) == MK_SHIFT)
operation = DragOperationGeneric;
return operation;
}
HRESULT STDMETHODCALLTYPE WebView::DragEnter(
IDataObject* pDataObject, DWORD grfKeyState, POINTL pt, DWORD* pdwEffect)
{
m_dragData = 0;
if (m_dropTargetHelper)
m_dropTargetHelper->DragEnter(m_viewWindow, pDataObject, (POINT*)&pt, *pdwEffect);
POINTL localpt = pt;
::ScreenToClient(m_viewWindow, (LPPOINT)&localpt);
DragData data(pDataObject, IntPoint(localpt.x, localpt.y),
IntPoint(pt.x, pt.y), keyStateToDragOperation(grfKeyState));
*pdwEffect = dragOperationToDragCursor(m_page->dragController()->dragEntered(&data));
m_lastDropEffect = *pdwEffect;
m_dragData = pDataObject;
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::DragOver(
DWORD grfKeyState, POINTL pt, DWORD* pdwEffect)
{
if (m_dropTargetHelper)
m_dropTargetHelper->DragOver((POINT*)&pt, *pdwEffect);
if (m_dragData) {
POINTL localpt = pt;
::ScreenToClient(m_viewWindow, (LPPOINT)&localpt);
DragData data(m_dragData.get(), IntPoint(localpt.x, localpt.y),
IntPoint(pt.x, pt.y), keyStateToDragOperation(grfKeyState));
*pdwEffect = dragOperationToDragCursor(m_page->dragController()->dragUpdated(&data));
} else
*pdwEffect = DROPEFFECT_NONE;
m_lastDropEffect = *pdwEffect;
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::DragLeave()
{
if (m_dropTargetHelper)
m_dropTargetHelper->DragLeave();
if (m_dragData) {
DragData data(m_dragData.get(), IntPoint(), IntPoint(),
DragOperationNone);
m_page->dragController()->dragExited(&data);
m_dragData = 0;
}
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::Drop(
IDataObject* pDataObject, DWORD grfKeyState, POINTL pt, DWORD* pdwEffect)
{
if (m_dropTargetHelper)
m_dropTargetHelper->Drop(pDataObject, (POINT*)&pt, *pdwEffect);
m_dragData = 0;
*pdwEffect = m_lastDropEffect;
POINTL localpt = pt;
::ScreenToClient(m_viewWindow, (LPPOINT)&localpt);
DragData data(pDataObject, IntPoint(localpt.x, localpt.y),
IntPoint(pt.x, pt.y), keyStateToDragOperation(grfKeyState));
m_page->dragController()->performDrag(&data);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::canHandleRequest(
IWebURLRequest *request,
BOOL *result)
{
COMPtr<WebMutableURLRequest> requestImpl;
HRESULT hr = request->QueryInterface(&requestImpl);
if (FAILED(hr))
return hr;
*result = !!canHandleRequest(requestImpl->resourceRequest());
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::standardUserAgentWithApplicationName(
BSTR applicationName,
BSTR* groupName)
{
if (!groupName) {
ASSERT_NOT_REACHED();
return E_POINTER;
}
*groupName;
if (!applicationName) {
ASSERT_NOT_REACHED();
return E_POINTER;
}
BString applicationNameBString(applicationName);
*groupName = BString(standardUserAgentWithApplicationName(String(applicationNameBString, SysStringLen(applicationNameBString)))).release();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::clearFocusNode()
{
if (m_page && m_page->focusController())
m_page->focusController()->setFocusedNode(0, 0);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::setInitialFocus(
/* [in] */ BOOL forward)
{
if (m_page && m_page->focusController()) {
Frame* frame = m_page->focusController()->focusedOrMainFrame();
frame->document()->setFocusedNode(0);
m_page->focusController()->setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, 0);
}
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::setTabKeyCyclesThroughElements(
/* [in] */ BOOL cycles)
{
if (m_page)
m_page->setTabKeyCyclesThroughElements(!!cycles);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::tabKeyCyclesThroughElements(
/* [retval][out] */ BOOL* result)
{
if (!result) {
ASSERT_NOT_REACHED();
return E_POINTER;
}
*result = m_page && m_page->tabKeyCyclesThroughElements() ? TRUE : FALSE;
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::setAllowSiteSpecificHacks(
/* [in] */ BOOL allow)
{
s_allowSiteSpecificHacks = !!allow;
// FIXME: This sets a global so it needs to call notifyPreferencesChanged
// on all WebView objects (not just itself).
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::addAdditionalPluginDirectory(
/* [in] */ BSTR directory)
{
PluginDatabase::installedPlugins()->addExtraPluginDirectory(String(directory, SysStringLen(directory)));
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::loadBackForwardListFromOtherView(
/* [in] */ IWebView* otherView)
{
if (!m_page)
return E_FAIL;
// It turns out the right combination of behavior is done with the back/forward load
// type. (See behavior matrix at the top of WebFramePrivate.) So we copy all the items
// in the back forward list, and go to the current one.
BackForwardList* backForwardList = m_page->backForwardList();
ASSERT(!backForwardList->currentItem()); // destination list should be empty
COMPtr<WebView> otherWebView;
if (FAILED(otherView->QueryInterface(&otherWebView)))
return E_FAIL;
BackForwardList* otherBackForwardList = otherWebView->m_page->backForwardList();
if (!otherBackForwardList->currentItem())
return S_OK; // empty back forward list, bail
HistoryItem* newItemToGoTo = 0;
int lastItemIndex = otherBackForwardList->forwardListCount();
for (int i = -otherBackForwardList->backListCount(); i <= lastItemIndex; ++i) {
if (!i) {
// If this item is showing , save away its current scroll and form state,
// since that might have changed since loading and it is normally not saved
// until we leave that page.
otherWebView->m_page->mainFrame()->loader()->history()->saveDocumentAndScrollState();
}
RefPtr<HistoryItem> newItem = otherBackForwardList->itemAtIndex(i)->copy();
if (!i)
newItemToGoTo = newItem.get();
backForwardList->addItem(newItem.release());
}
ASSERT(newItemToGoTo);
m_page->goToItem(newItemToGoTo, FrameLoadTypeIndexedBackForward);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::clearUndoRedoOperations()
{
if (Frame* frame = m_page->focusController()->focusedOrMainFrame())
frame->editor()->clearUndoRedoOperations();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::shouldClose(
/* [retval][out] */ BOOL* result)
{
if (!result) {
ASSERT_NOT_REACHED();
return E_POINTER;
}
*result = TRUE;
if (Frame* frame = m_page->mainFrame())
*result = frame->loader()->shouldClose();
return S_OK;
}
HRESULT WebView::registerDragDrop()
{
ASSERT(::IsWindow(m_viewWindow));
return ::RegisterDragDrop(m_viewWindow, this);
}
HRESULT WebView::revokeDragDrop()
{
if (!m_viewWindow)
return S_OK;
return ::RevokeDragDrop(m_viewWindow);
}
HRESULT WebView::setProhibitsMainFrameScrolling(BOOL b)
{
if (!m_page)
return E_FAIL;
m_page->mainFrame()->view()->setProhibitsScrolling(b);
return S_OK;
}
HRESULT WebView::setShouldApplyMacFontAscentHack(BOOL b)
{
SimpleFontData::setShouldApplyMacAscentHack(b);
return S_OK;
}
class IMMDict {
typedef HIMC (CALLBACK *getContextPtr)(HWND);
typedef BOOL (CALLBACK *releaseContextPtr)(HWND, HIMC);
typedef LONG (CALLBACK *getCompositionStringPtr)(HIMC, DWORD, LPVOID, DWORD);
typedef BOOL (CALLBACK *setCandidateWindowPtr)(HIMC, LPCANDIDATEFORM);
typedef BOOL (CALLBACK *setOpenStatusPtr)(HIMC, BOOL);
typedef BOOL (CALLBACK *notifyIMEPtr)(HIMC, DWORD, DWORD, DWORD);
typedef BOOL (CALLBACK *associateContextExPtr)(HWND, HIMC, DWORD);
public:
getContextPtr getContext;
releaseContextPtr releaseContext;
getCompositionStringPtr getCompositionString;
setCandidateWindowPtr setCandidateWindow;
setOpenStatusPtr setOpenStatus;
notifyIMEPtr notifyIME;
associateContextExPtr associateContextEx;
static const IMMDict& dict();
private:
IMMDict();
HMODULE m_instance;
};
const IMMDict& IMMDict::dict()
{
static IMMDict instance;
return instance;
}
IMMDict::IMMDict()
{
m_instance = ::LoadLibrary(TEXT("IMM32.DLL"));
getContext = reinterpret_cast<getContextPtr>(::GetProcAddress(m_instance, "ImmGetContext"));
ASSERT(getContext);
releaseContext = reinterpret_cast<releaseContextPtr>(::GetProcAddress(m_instance, "ImmReleaseContext"));
ASSERT(releaseContext);
getCompositionString = reinterpret_cast<getCompositionStringPtr>(::GetProcAddress(m_instance, "ImmGetCompositionStringW"));
ASSERT(getCompositionString);
setCandidateWindow = reinterpret_cast<setCandidateWindowPtr>(::GetProcAddress(m_instance, "ImmSetCandidateWindow"));
ASSERT(setCandidateWindow);
setOpenStatus = reinterpret_cast<setOpenStatusPtr>(::GetProcAddress(m_instance, "ImmSetOpenStatus"));
ASSERT(setOpenStatus);
notifyIME = reinterpret_cast<notifyIMEPtr>(::GetProcAddress(m_instance, "ImmNotifyIME"));
ASSERT(notifyIME);
associateContextEx = reinterpret_cast<associateContextExPtr>(::GetProcAddress(m_instance, "ImmAssociateContextEx"));
ASSERT(associateContextEx);
}
HIMC WebView::getIMMContext()
{
HIMC context = IMMDict::dict().getContext(m_viewWindow);
return context;
}
void WebView::releaseIMMContext(HIMC hIMC)
{
if (!hIMC)
return;
IMMDict::dict().releaseContext(m_viewWindow, hIMC);
}
void WebView::prepareCandidateWindow(Frame* targetFrame, HIMC hInputContext)
{
IntRect caret;
if (RefPtr<Range> range = targetFrame->selection()->selection().toNormalizedRange()) {
ExceptionCode ec = 0;
RefPtr<Range> tempRange = range->cloneRange(ec);
caret = targetFrame->editor()->firstRectForRange(tempRange.get());
}
caret = targetFrame->view()->contentsToWindow(caret);
CANDIDATEFORM form;
form.dwIndex = 0;
form.dwStyle = CFS_EXCLUDE;
form.ptCurrentPos.x = caret.x();
form.ptCurrentPos.y = caret.y() + caret.height();
form.rcArea.top = caret.y();
form.rcArea.bottom = caret.bottom();
form.rcArea.left = caret.x();
form.rcArea.right = caret.right();
IMMDict::dict().setCandidateWindow(hInputContext, &form);
}
void WebView::resetIME(Frame* targetFrame)
{
if (targetFrame)
targetFrame->editor()->confirmCompositionWithoutDisturbingSelection();
if (HIMC hInputContext = getIMMContext()) {
IMMDict::dict().notifyIME(hInputContext, NI_COMPOSITIONSTR, CPS_CANCEL, 0);
releaseIMMContext(hInputContext);
}
}
void WebView::updateSelectionForIME()
{
Frame* targetFrame = m_page->focusController()->focusedOrMainFrame();
if (!targetFrame || !targetFrame->editor()->hasComposition())
return;
if (targetFrame->editor()->ignoreCompositionSelectionChange())
return;
unsigned start;
unsigned end;
if (!targetFrame->editor()->getCompositionSelection(start, end))
resetIME(targetFrame);
}
void WebView::setInputMethodState(bool enabled)
{
IMMDict::dict().associateContextEx(m_viewWindow, 0, enabled ? IACE_DEFAULT : 0);
}
void WebView::selectionChanged()
{
updateSelectionForIME();
}
bool WebView::onIMEStartComposition()
{
LOG(TextInput, "onIMEStartComposition");
m_inIMEComposition++;
Frame* targetFrame = m_page->focusController()->focusedOrMainFrame();
if (!targetFrame)
return true;
HIMC hInputContext = getIMMContext();
prepareCandidateWindow(targetFrame, hInputContext);
releaseIMMContext(hInputContext);
return true;
}
static bool getCompositionString(HIMC hInputContext, DWORD type, String& result)
{
int compositionLength = IMMDict::dict().getCompositionString(hInputContext, type, 0, 0);
if (compositionLength <= 0)
return false;
Vector<UChar> compositionBuffer(compositionLength / 2);
compositionLength = IMMDict::dict().getCompositionString(hInputContext, type, (LPVOID)compositionBuffer.data(), compositionLength);
result = String(compositionBuffer.data(), compositionLength / 2);
ASSERT(!compositionLength || compositionBuffer[0]);
ASSERT(!compositionLength || compositionBuffer[compositionLength / 2 - 1]);
return true;
}
static void compositionToUnderlines(const Vector<DWORD>& clauses, const Vector<BYTE>& attributes, Vector<CompositionUnderline>& underlines)
{
if (clauses.isEmpty()) {
underlines.clear();
return;
}
const size_t numBoundaries = clauses.size() - 1;
underlines.resize(numBoundaries);
for (unsigned i = 0; i < numBoundaries; i++) {
underlines[i].startOffset = clauses[i];
underlines[i].endOffset = clauses[i + 1];
BYTE attribute = attributes[clauses[i]];
underlines[i].thick = attribute == ATTR_TARGET_CONVERTED || attribute == ATTR_TARGET_NOTCONVERTED;
underlines[i].color = Color(0,0,0);
}
}
#if !LOG_DISABLED
#define APPEND_ARGUMENT_NAME(name) \
if (lparam & name) { \
if (needsComma) \
result += ", "; \
result += #name; \
needsComma = true; \
}
static String imeCompositionArgumentNames(LPARAM lparam)
{
String result;
bool needsComma = false;
if (lparam & GCS_COMPATTR) {
result = "GCS_COMPATTR";
needsComma = true;
}
APPEND_ARGUMENT_NAME(GCS_COMPCLAUSE);
APPEND_ARGUMENT_NAME(GCS_COMPREADSTR);
APPEND_ARGUMENT_NAME(GCS_COMPREADATTR);
APPEND_ARGUMENT_NAME(GCS_COMPREADCLAUSE);
APPEND_ARGUMENT_NAME(GCS_COMPSTR);
APPEND_ARGUMENT_NAME(GCS_CURSORPOS);
APPEND_ARGUMENT_NAME(GCS_DELTASTART);
APPEND_ARGUMENT_NAME(GCS_RESULTCLAUSE);
APPEND_ARGUMENT_NAME(GCS_RESULTREADCLAUSE);
APPEND_ARGUMENT_NAME(GCS_RESULTREADSTR);
APPEND_ARGUMENT_NAME(GCS_RESULTSTR);
APPEND_ARGUMENT_NAME(CS_INSERTCHAR);
APPEND_ARGUMENT_NAME(CS_NOMOVECARET);
return result;
}
static String imeNotificationName(WPARAM wparam)
{
switch (wparam) {
case IMN_CHANGECANDIDATE:
return "IMN_CHANGECANDIDATE";
case IMN_CLOSECANDIDATE:
return "IMN_CLOSECANDIDATE";
case IMN_CLOSESTATUSWINDOW:
return "IMN_CLOSESTATUSWINDOW";
case IMN_GUIDELINE:
return "IMN_GUIDELINE";
case IMN_OPENCANDIDATE:
return "IMN_OPENCANDIDATE";
case IMN_OPENSTATUSWINDOW:
return "IMN_OPENSTATUSWINDOW";
case IMN_SETCANDIDATEPOS:
return "IMN_SETCANDIDATEPOS";
case IMN_SETCOMPOSITIONFONT:
return "IMN_SETCOMPOSITIONFONT";
case IMN_SETCOMPOSITIONWINDOW:
return "IMN_SETCOMPOSITIONWINDOW";
case IMN_SETCONVERSIONMODE:
return "IMN_SETCONVERSIONMODE";
case IMN_SETOPENSTATUS:
return "IMN_SETOPENSTATUS";
case IMN_SETSENTENCEMODE:
return "IMN_SETSENTENCEMODE";
case IMN_SETSTATUSWINDOWPOS:
return "IMN_SETSTATUSWINDOWPOS";
default:
return "Unknown (" + String::number(wparam) + ")";
}
}
static String imeRequestName(WPARAM wparam)
{
switch (wparam) {
case IMR_CANDIDATEWINDOW:
return "IMR_CANDIDATEWINDOW";
case IMR_COMPOSITIONFONT:
return "IMR_COMPOSITIONFONT";
case IMR_COMPOSITIONWINDOW:
return "IMR_COMPOSITIONWINDOW";
case IMR_CONFIRMRECONVERTSTRING:
return "IMR_CONFIRMRECONVERTSTRING";
case IMR_DOCUMENTFEED:
return "IMR_DOCUMENTFEED";
case IMR_QUERYCHARPOSITION:
return "IMR_QUERYCHARPOSITION";
case IMR_RECONVERTSTRING:
return "IMR_RECONVERTSTRING";
default:
return "Unknown (" + String::number(wparam) + ")";
}
}
#endif
bool WebView::onIMEComposition(LPARAM lparam)
{
LOG(TextInput, "onIMEComposition %s", imeCompositionArgumentNames(lparam).latin1().data());
HIMC hInputContext = getIMMContext();
if (!hInputContext)
return true;
Frame* targetFrame = m_page->focusController()->focusedOrMainFrame();
if (!targetFrame || !targetFrame->editor()->canEdit())
return true;
prepareCandidateWindow(targetFrame, hInputContext);
if (lparam & GCS_RESULTSTR || !lparam) {
String compositionString;
if (!getCompositionString(hInputContext, GCS_RESULTSTR, compositionString) && lparam)
return true;
targetFrame->editor()->confirmComposition(compositionString);
} else {
String compositionString;
if (!getCompositionString(hInputContext, GCS_COMPSTR, compositionString))
return true;
// Composition string attributes
int numAttributes = IMMDict::dict().getCompositionString(hInputContext, GCS_COMPATTR, 0, 0);
Vector<BYTE> attributes(numAttributes);
IMMDict::dict().getCompositionString(hInputContext, GCS_COMPATTR, attributes.data(), numAttributes);
// Get clauses
int numClauses = IMMDict::dict().getCompositionString(hInputContext, GCS_COMPCLAUSE, 0, 0);
Vector<DWORD> clauses(numClauses / sizeof(DWORD));
IMMDict::dict().getCompositionString(hInputContext, GCS_COMPCLAUSE, clauses.data(), numClauses);
Vector<CompositionUnderline> underlines;
compositionToUnderlines(clauses, attributes, underlines);
int cursorPosition = LOWORD(IMMDict::dict().getCompositionString(hInputContext, GCS_CURSORPOS, 0, 0));
targetFrame->editor()->setComposition(compositionString, underlines, cursorPosition, 0);
}
return true;
}
bool WebView::onIMEEndComposition()
{
LOG(TextInput, "onIMEEndComposition");
// If the composition hasn't been confirmed yet, it needs to be cancelled.
// This happens after deleting the last character from inline input hole.
Frame* targetFrame = m_page->focusController()->focusedOrMainFrame();
if (targetFrame && targetFrame->editor()->hasComposition())
targetFrame->editor()->confirmComposition(String());
if (m_inIMEComposition)
m_inIMEComposition--;
return true;
}
bool WebView::onIMEChar(WPARAM wparam, LPARAM lparam)
{
UNUSED_PARAM(wparam);
UNUSED_PARAM(lparam);
LOG(TextInput, "onIMEChar U+%04X %08X", wparam, lparam);
return true;
}
bool WebView::onIMENotify(WPARAM wparam, LPARAM, LRESULT*)
{
UNUSED_PARAM(wparam);
LOG(TextInput, "onIMENotify %s", imeNotificationName(wparam).latin1().data());
return false;
}
LRESULT WebView::onIMERequestCharPosition(Frame* targetFrame, IMECHARPOSITION* charPos)
{
if (charPos->dwCharPos && !targetFrame->editor()->hasComposition())
return 0;
IntRect caret;
if (RefPtr<Range> range = targetFrame->editor()->hasComposition() ? targetFrame->editor()->compositionRange() : targetFrame->selection()->selection().toNormalizedRange()) {
ExceptionCode ec = 0;
RefPtr<Range> tempRange = range->cloneRange(ec);
tempRange->setStart(tempRange->startContainer(ec), tempRange->startOffset(ec) + charPos->dwCharPos, ec);
caret = targetFrame->editor()->firstRectForRange(tempRange.get());
}
caret = targetFrame->view()->contentsToWindow(caret);
charPos->pt.x = caret.x();
charPos->pt.y = caret.y();
::ClientToScreen(m_viewWindow, &charPos->pt);
charPos->cLineHeight = caret.height();
::GetWindowRect(m_viewWindow, &charPos->rcDocument);
return true;
}
LRESULT WebView::onIMERequestReconvertString(Frame* targetFrame, RECONVERTSTRING* reconvertString)
{
RefPtr<Range> selectedRange = targetFrame->selection()->toNormalizedRange();
String text = selectedRange->text();
if (!reconvertString)
return sizeof(RECONVERTSTRING) + text.length() * sizeof(UChar);
unsigned totalSize = sizeof(RECONVERTSTRING) + text.length() * sizeof(UChar);
if (totalSize > reconvertString->dwSize)
return 0;
reconvertString->dwCompStrLen = text.length();
reconvertString->dwStrLen = text.length();
reconvertString->dwTargetStrLen = text.length();
reconvertString->dwStrOffset = sizeof(RECONVERTSTRING);
memcpy(reconvertString + 1, text.characters(), text.length() * sizeof(UChar));
return totalSize;
}
LRESULT WebView::onIMERequest(WPARAM request, LPARAM data)
{
LOG(TextInput, "onIMERequest %s", imeRequestName(request).latin1().data());
Frame* targetFrame = m_page->focusController()->focusedOrMainFrame();
if (!targetFrame || !targetFrame->editor()->canEdit())
return 0;
switch (request) {
case IMR_RECONVERTSTRING:
return onIMERequestReconvertString(targetFrame, (RECONVERTSTRING*)data);
case IMR_QUERYCHARPOSITION:
return onIMERequestCharPosition(targetFrame, (IMECHARPOSITION*)data);
}
return 0;
}
bool WebView::onIMESelect(WPARAM wparam, LPARAM lparam)
{
UNUSED_PARAM(wparam);
UNUSED_PARAM(lparam);
LOG(TextInput, "onIMESelect locale %ld %s", lparam, wparam ? "select" : "deselect");
return false;
}
bool WebView::onIMESetContext(WPARAM wparam, LPARAM)
{
LOG(TextInput, "onIMESetContext %s", wparam ? "active" : "inactive");
return false;
}
HRESULT STDMETHODCALLTYPE WebView::inspector(IWebInspector** inspector)
{
if (!m_webInspector)
m_webInspector.adoptRef(WebInspector::createInstance(this));
return m_webInspector.copyRefTo(inspector);
}
HRESULT STDMETHODCALLTYPE WebView::windowAncestryDidChange()
{
HWND newParent;
if (m_viewWindow)
newParent = findTopLevelParent(m_hostWindow);
else {
// There's no point in tracking active state changes of our parent window if we don't have
// a window ourselves.
newParent = 0;
}
if (newParent == m_topLevelParent)
return S_OK;
if (m_topLevelParent)
WindowMessageBroadcaster::removeListener(m_topLevelParent, this);
m_topLevelParent = newParent;
if (m_topLevelParent)
WindowMessageBroadcaster::addListener(m_topLevelParent, this);
updateActiveState();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::paintDocumentRectToContext(
/* [in] */ RECT rect,
/* [in] */ OLE_HANDLE deviceContext)
{
if (!deviceContext)
return E_POINTER;
if (!m_mainFrame)
return E_FAIL;
return m_mainFrame->paintDocumentRectToContext(rect, deviceContext);
}
HRESULT STDMETHODCALLTYPE WebView::paintScrollViewRectToContextAtPoint(
/* [in] */ RECT rect,
/* [in] */ POINT pt,
/* [in] */ OLE_HANDLE deviceContext)
{
if (!deviceContext)
return E_POINTER;
if (!m_mainFrame)
return E_FAIL;
return m_mainFrame->paintScrollViewRectToContextAtPoint(rect, pt, deviceContext);
}
HRESULT STDMETHODCALLTYPE WebView::reportException(
/* [in] */ JSContextRef context,
/* [in] */ JSValueRef exception)
{
if (!context || !exception)
return E_FAIL;
JSLock lock(JSC::SilenceAssertionsOnly);
JSC::ExecState* execState = toJS(context);
// Make sure the context has a DOMWindow global object, otherwise this context didn't originate from a WebView.
if (!toJSDOMWindow(execState->lexicalGlobalObject()))
return E_FAIL;
WebCore::reportException(execState, toJS(execState, exception));
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::elementFromJS(
/* [in] */ JSContextRef context,
/* [in] */ JSValueRef nodeObject,
/* [retval][out] */ IDOMElement **element)
{
if (!element)
return E_POINTER;
*element = 0;
if (!context)
return E_FAIL;
if (!nodeObject)
return E_FAIL;
JSLock lock(JSC::SilenceAssertionsOnly);
Element* elt = toElement(toJS(toJS(context), nodeObject));
if (!elt)
return E_FAIL;
*element = DOMElement::createInstance(elt);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::setCustomHTMLTokenizerTimeDelay(
/* [in] */ double timeDelay)
{
if (!m_page)
return E_FAIL;
m_page->setCustomHTMLTokenizerTimeDelay(timeDelay);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::setCustomHTMLTokenizerChunkSize(
/* [in] */ int chunkSize)
{
if (!m_page)
return E_FAIL;
m_page->setCustomHTMLTokenizerChunkSize(chunkSize);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::backingStore(
/* [out, retval] */ OLE_HANDLE* hBitmap)
{
if (!hBitmap)
return E_POINTER;
if (!m_backingStoreBitmap)
return E_FAIL;
*hBitmap = reinterpret_cast<OLE_HANDLE>(m_backingStoreBitmap->handle());
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::setTransparent(BOOL transparent)
{
if (m_transparent == !!transparent)
return S_OK;
m_transparent = transparent;
m_mainFrame->updateBackground();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::transparent(BOOL* transparent)
{
if (!transparent)
return E_POINTER;
*transparent = this->transparent() ? TRUE : FALSE;
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::setCookieEnabled(BOOL enable)
{
if (!m_page)
return E_FAIL;
m_page->setCookieEnabled(enable);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::cookieEnabled(BOOL* enabled)
{
if (!enabled)
return E_POINTER;
if (!m_page)
return E_FAIL;
*enabled = m_page->cookieEnabled();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::setMediaVolume(float volume)
{
if (!m_page)
return E_FAIL;
m_page->setMediaVolume(volume);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::mediaVolume(float* volume)
{
if (!volume)
return E_POINTER;
if (!m_page)
return E_FAIL;
*volume = m_page->mediaVolume();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::setDefersCallbacks(BOOL defersCallbacks)
{
if (!m_page)
return E_FAIL;
m_page->setDefersLoading(defersCallbacks);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::defersCallbacks(BOOL* defersCallbacks)
{
if (!defersCallbacks)
return E_POINTER;
if (!m_page)
return E_FAIL;
*defersCallbacks = m_page->defersLoading();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::globalHistoryItem(IWebHistoryItem** item)
{
if (!item)
return E_POINTER;
if (!m_page)
return E_FAIL;
if (!m_page->globalHistoryItem()) {
*item = 0;
return S_OK;
}
*item = WebHistoryItem::createInstance(m_page->globalHistoryItem());
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::setAlwaysUsesComplexTextCodePath(BOOL complex)
{
WebCoreSetAlwaysUsesComplexTextCodePath(complex);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::alwaysUsesComplexTextCodePath(BOOL* complex)
{
if (!complex)
return E_POINTER;
*complex = WebCoreAlwaysUsesComplexTextCodePath();
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::registerEmbeddedViewMIMEType(BSTR mimeType)
{
if (!mimeType)
return E_POINTER;
if (!m_embeddedViewMIMETypes)
m_embeddedViewMIMETypes.set(new HashSet<String>);
m_embeddedViewMIMETypes->add(String(mimeType, ::SysStringLen(mimeType)));
return S_OK;
}
bool WebView::shouldUseEmbeddedView(const WTF::String& mimeType) const
{
if (!m_embeddedViewMIMETypes)
return false;
return m_embeddedViewMIMETypes->contains(mimeType);
}
bool WebView::onGetObject(WPARAM wParam, LPARAM lParam, LRESULT& lResult) const
{
lResult = 0;
if (lParam != OBJID_CLIENT)
return false;
AXObjectCache::enableAccessibility();
// Get the accessible object for the top-level frame.
WebFrame* mainFrameImpl = topLevelFrame();
if (!mainFrameImpl)
return false;
COMPtr<IAccessible> accessible = mainFrameImpl->accessible();
if (!accessible)
return false;
if (!accessibilityLib) {
if (!(accessibilityLib = ::LoadLibrary(TEXT("oleacc.dll"))))
return false;
}
static LPFNLRESULTFROMOBJECT procPtr = reinterpret_cast<LPFNLRESULTFROMOBJECT>(::GetProcAddress(accessibilityLib, "LresultFromObject"));
if (!procPtr)
return false;
// LresultFromObject returns a reference to the accessible object, stored
// in an LRESULT. If this call is not successful, Windows will handle the
// request through DefWindowProc.
return SUCCEEDED(lResult = procPtr(__uuidof(IAccessible), wParam, accessible.get()));
}
STDMETHODIMP WebView::AccessibleObjectFromWindow(HWND hwnd, DWORD objectID, REFIID riid, void** ppObject)
{
ASSERT(accessibilityLib);
static LPFNACCESSIBLEOBJECTFROMWINDOW procPtr = reinterpret_cast<LPFNACCESSIBLEOBJECTFROMWINDOW>(::GetProcAddress(accessibilityLib, "AccessibleObjectFromWindow"));
if (!procPtr)
return E_FAIL;
return procPtr(hwnd, objectID, riid, ppObject);
}
HRESULT WebView::setMemoryCacheDelegateCallsEnabled(BOOL enabled)
{
m_page->setMemoryCacheClientCallsEnabled(enabled);
return S_OK;
}
HRESULT WebView::setJavaScriptURLsAreAllowed(BOOL areAllowed)
{
m_page->setJavaScriptURLsAreAllowed(areAllowed);
return S_OK;
}
HRESULT WebView::setCanStartPlugins(BOOL canStartPlugins)
{
m_page->setCanStartMedia(canStartPlugins);
return S_OK;
}
static String toString(BSTR bstr)
{
return String(bstr, SysStringLen(bstr));
}
static KURL toKURL(BSTR bstr)
{
return KURL(KURL(), toString(bstr));
}
void WebView::enterFullscreenForNode(Node* node)
{
if (!node->hasTagName(HTMLNames::videoTag))
return;
#if ENABLE(VIDEO)
HTMLMediaElement* videoElement = static_cast<HTMLMediaElement*>(node);
if (m_fullscreenController) {
if (m_fullscreenController->mediaElement() == videoElement) {
// The backend may just warn us that the underlaying plaftormMovie()
// has changed. Just force an update.
m_fullscreenController->setMediaElement(videoElement);
return; // No more to do.
}
// First exit Fullscreen for the old mediaElement.
m_fullscreenController->mediaElement()->exitFullscreen();
// This previous call has to trigger exitFullscreen,
// which has to clear m_fullscreenController.
ASSERT(!m_fullscreenController);
}
m_fullscreenController = new FullscreenVideoController;
m_fullscreenController->setMediaElement(videoElement);
m_fullscreenController->enterFullscreen();
#endif
}
void WebView::exitFullscreen()
{
#if ENABLE(VIDEO)
if (m_fullscreenController)
m_fullscreenController->exitFullscreen();
m_fullscreenController = 0;
#endif
}
static PassOwnPtr<Vector<String> > toStringVector(unsigned patternsCount, BSTR* patterns)
{
// Convert the patterns into a Vector.
if (patternsCount == 0)
return 0;
Vector<String>* patternsVector = new Vector<String>;
for (unsigned i = 0; i < patternsCount; ++i)
patternsVector->append(toString(patterns[i]));
return patternsVector;
}
HRESULT WebView::addUserScriptToGroup(BSTR groupName, IWebScriptWorld* iWorld, BSTR source, BSTR url,
unsigned whitelistCount, BSTR* whitelist,
unsigned blacklistCount, BSTR* blacklist,
WebUserScriptInjectionTime injectionTime)
{
COMPtr<WebScriptWorld> world(Query, iWorld);
if (!world)
return E_POINTER;
String group = toString(groupName);
if (group.isEmpty())
return E_INVALIDARG;
PageGroup* pageGroup = PageGroup::pageGroup(group);
ASSERT(pageGroup);
if (!pageGroup)
return E_FAIL;
pageGroup->addUserScriptToWorld(world->world(), toString(source), toKURL(url),
toStringVector(whitelistCount, whitelist), toStringVector(blacklistCount, blacklist),
injectionTime == WebInjectAtDocumentStart ? InjectAtDocumentStart : InjectAtDocumentEnd,
InjectInAllFrames);
return S_OK;
}
HRESULT WebView::addUserStyleSheetToGroup(BSTR groupName, IWebScriptWorld* iWorld, BSTR source, BSTR url,
unsigned whitelistCount, BSTR* whitelist,
unsigned blacklistCount, BSTR* blacklist)
{
COMPtr<WebScriptWorld> world(Query, iWorld);
if (!world)
return E_POINTER;
String group = toString(groupName);
if (group.isEmpty())
return E_INVALIDARG;
PageGroup* pageGroup = PageGroup::pageGroup(group);
ASSERT(pageGroup);
if (!pageGroup)
return E_FAIL;
pageGroup->addUserStyleSheetToWorld(world->world(), toString(source), toKURL(url),
toStringVector(whitelistCount, whitelist), toStringVector(blacklistCount, blacklist),
InjectInAllFrames);
return S_OK;
}
HRESULT WebView::removeUserScriptFromGroup(BSTR groupName, IWebScriptWorld* iWorld, BSTR url)
{
COMPtr<WebScriptWorld> world(Query, iWorld);
if (!world)
return E_POINTER;
String group = toString(groupName);
if (group.isEmpty())
return E_INVALIDARG;
PageGroup* pageGroup = PageGroup::pageGroup(group);
ASSERT(pageGroup);
if (!pageGroup)
return E_FAIL;
pageGroup->removeUserScriptFromWorld(world->world(), toKURL(url));
return S_OK;
}
HRESULT WebView::removeUserStyleSheetFromGroup(BSTR groupName, IWebScriptWorld* iWorld, BSTR url)
{
COMPtr<WebScriptWorld> world(Query, iWorld);
if (!world)
return E_POINTER;
String group = toString(groupName);
if (group.isEmpty())
return E_INVALIDARG;
PageGroup* pageGroup = PageGroup::pageGroup(group);
ASSERT(pageGroup);
if (!pageGroup)
return E_FAIL;
pageGroup->removeUserStyleSheetFromWorld(world->world(), toKURL(url));
return S_OK;
}
HRESULT WebView::removeUserScriptsFromGroup(BSTR groupName, IWebScriptWorld* iWorld)
{
COMPtr<WebScriptWorld> world(Query, iWorld);
if (!world)
return E_POINTER;
String group = toString(groupName);
if (group.isEmpty())
return E_INVALIDARG;
PageGroup* pageGroup = PageGroup::pageGroup(group);
ASSERT(pageGroup);
if (!pageGroup)
return E_FAIL;
pageGroup->removeUserScriptsFromWorld(world->world());
return S_OK;
}
HRESULT WebView::removeUserStyleSheetsFromGroup(BSTR groupName, IWebScriptWorld* iWorld)
{
COMPtr<WebScriptWorld> world(Query, iWorld);
if (!world)
return E_POINTER;
String group = toString(groupName);
if (group.isEmpty())
return E_INVALIDARG;
PageGroup* pageGroup = PageGroup::pageGroup(group);
ASSERT(pageGroup);
if (!pageGroup)
return E_FAIL;
pageGroup->removeUserStyleSheetsFromWorld(world->world());
return S_OK;
}
HRESULT WebView::removeAllUserContentFromGroup(BSTR groupName)
{
String group = toString(groupName);
if (group.isEmpty())
return E_INVALIDARG;
PageGroup* pageGroup = PageGroup::pageGroup(group);
ASSERT(pageGroup);
if (!pageGroup)
return E_FAIL;
pageGroup->removeAllUserContent();
return S_OK;
}
HRESULT WebView::invalidateBackingStore(const RECT* rect)
{
if (!IsWindow(m_viewWindow))
return S_OK;
RECT clientRect;
if (!GetClientRect(m_viewWindow, &clientRect))
return E_FAIL;
RECT rectToInvalidate;
if (!rect)
rectToInvalidate = clientRect;
else if (!IntersectRect(&rectToInvalidate, &clientRect, rect))
return S_OK;
repaint(rectToInvalidate, true);
return S_OK;
}
HRESULT WebView::addOriginAccessWhitelistEntry(BSTR sourceOrigin, BSTR destinationProtocol, BSTR destinationHost, BOOL allowDestinationSubdomains)
{
SecurityOrigin::addOriginAccessWhitelistEntry(*SecurityOrigin::createFromString(String(sourceOrigin, SysStringLen(sourceOrigin))), String(destinationProtocol, SysStringLen(destinationProtocol)), String(destinationHost, SysStringLen(destinationHost)), allowDestinationSubdomains);
return S_OK;
}
HRESULT WebView::removeOriginAccessWhitelistEntry(BSTR sourceOrigin, BSTR destinationProtocol, BSTR destinationHost, BOOL allowDestinationSubdomains)
{
SecurityOrigin::removeOriginAccessWhitelistEntry(*SecurityOrigin::createFromString(String(sourceOrigin, SysStringLen(sourceOrigin))), String(destinationProtocol, SysStringLen(destinationProtocol)), String(destinationHost, SysStringLen(destinationHost)), allowDestinationSubdomains);
return S_OK;
}
HRESULT WebView::resetOriginAccessWhitelists()
{
SecurityOrigin::resetOriginAccessWhitelists();
return S_OK;
}
HRESULT WebView::setHistoryDelegate(IWebHistoryDelegate* historyDelegate)
{
m_historyDelegate = historyDelegate;
return S_OK;
}
HRESULT WebView::historyDelegate(IWebHistoryDelegate** historyDelegate)
{
if (!historyDelegate)
return E_POINTER;
return m_historyDelegate.copyRefTo(historyDelegate);
}
HRESULT WebView::addVisitedLinks(BSTR* visitedURLs, unsigned visitedURLCount)
{
PageGroup& group = core(this)->group();
for (unsigned i = 0; i < visitedURLCount; ++i) {
BSTR url = visitedURLs[i];
unsigned length = SysStringLen(url);
group.addVisitedLink(url, length);
}
return S_OK;
}
void WebView::downloadURL(const KURL& url)
{
// It's the delegate's job to ref the WebDownload to keep it alive - otherwise it will be
// destroyed when this function returns.
COMPtr<WebDownload> download(AdoptCOM, WebDownload::createInstance(url, m_downloadDelegate.get()));
download->start();
}
#if USE(ACCELERATED_COMPOSITING)
void WebView::setRootChildLayer(WebCore::WKCACFLayer* layer)
{
setAcceleratedCompositing(layer ? true : false);
if (m_layerRenderer)
m_layerRenderer->setRootChildLayer(layer);
}
void WebView::setAcceleratedCompositing(bool accelerated)
{
if (m_isAcceleratedCompositing == accelerated || !WKCACFLayerRenderer::acceleratedCompositingAvailable())
return;
if (accelerated) {
m_layerRenderer = WKCACFLayerRenderer::create(this);
if (m_layerRenderer) {
m_isAcceleratedCompositing = true;
// Create the root layer
ASSERT(m_viewWindow);
m_layerRenderer->setHostWindow(m_viewWindow);
m_layerRenderer->createRenderer();
}
} else {
m_layerRenderer = 0;
m_isAcceleratedCompositing = false;
}
}
void releaseBackingStoreCallback(void* info, const void* data, size_t size)
{
// Release the backing store bitmap previously retained by updateRootLayerContents().
ASSERT(info);
if (info)
static_cast<RefCountedHBITMAP*>(info)->deref();
}
void WebView::updateRootLayerContents()
{
if (!m_backingStoreBitmap || !m_layerRenderer)
return;
// Get the backing store into a CGImage
BITMAP bitmap;
GetObject(m_backingStoreBitmap->handle(), sizeof(bitmap), &bitmap);
size_t bmSize = bitmap.bmWidthBytes * bitmap.bmHeight;
RetainPtr<CGDataProviderRef> cgData(AdoptCF,
CGDataProviderCreateWithData(static_cast<void*>(m_backingStoreBitmap.get()),
bitmap.bmBits, bmSize,
releaseBackingStoreCallback));
RetainPtr<CGColorSpaceRef> space(AdoptCF, CGColorSpaceCreateDeviceRGB());
RetainPtr<CGImageRef> backingStoreImage(AdoptCF, CGImageCreate(bitmap.bmWidth, bitmap.bmHeight,
8, bitmap.bmBitsPixel,
bitmap.bmWidthBytes, space.get(),
kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipFirst,
cgData.get(), 0, false,
kCGRenderingIntentDefault));
// Retain the backing store bitmap so that it is not deleted by deleteBackingStore()
// while still in use within CA. When CA is done with the bitmap, it will
// call releaseBackingStoreCallback(), which will release the backing store bitmap.
m_backingStoreBitmap->ref();
// Hand the CGImage to CACF for compositing
if (m_nextDisplayIsSynchronous) {
m_layerRenderer->setRootContentsAndDisplay(backingStoreImage.get());
m_nextDisplayIsSynchronous = false;
} else
m_layerRenderer->setRootContents(backingStoreImage.get());
// Set the frame and scroll position
Frame* coreFrame = core(m_mainFrame);
if (!coreFrame)
return;
FrameView* frameView = coreFrame->view();
m_layerRenderer->setScrollFrame(IntPoint(frameView->scrollX(), frameView->scrollY()), IntSize(frameView->layoutWidth(), frameView->layoutHeight()));
}
#endif
HRESULT STDMETHODCALLTYPE WebView::setPluginHalterDelegate(IWebPluginHalterDelegate* d)
{
m_pluginHalterDelegate = d;
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::pluginHalterDelegate(IWebPluginHalterDelegate** d)
{
if (!d)
return E_POINTER;
if (!m_pluginHalterDelegate)
return E_FAIL;
return m_pluginHalterDelegate.copyRefTo(d);
}
static PluginView* pluginViewForNode(IDOMNode* domNode)
{
COMPtr<DOMNode> webKitDOMNode(Query, domNode);
if (!webKitDOMNode)
return 0;
Node* node = webKitDOMNode->node();
if (!node)
return 0;
RenderObject* renderer = node->renderer();
if (!renderer || !renderer->isWidget())
return 0;
Widget* widget = toRenderWidget(renderer)->widget();
if (!widget || !widget->isPluginView())
return 0;
return static_cast<PluginView*>(widget);
}
HRESULT WebView::isNodeHaltedPlugin(IDOMNode* domNode, BOOL* result)
{
if (!domNode || !result)
return E_POINTER;
*result = FALSE;
PluginView* view = pluginViewForNode(domNode);
if (!view)
return E_FAIL;
*result = view->isHalted();
return S_OK;
}
HRESULT WebView::restartHaltedPluginForNode(IDOMNode* domNode)
{
if (!domNode)
return E_POINTER;
PluginView* view = pluginViewForNode(domNode);
if (!view)
return E_FAIL;
view->restart();
return S_OK;
}
HRESULT WebView::hasPluginForNodeBeenHalted(IDOMNode* domNode, BOOL* result)
{
if (!domNode || !result)
return E_POINTER;
*result = FALSE;
PluginView* view = pluginViewForNode(domNode);
if (!view)
return E_FAIL;
*result = view->hasBeenHalted();
return S_OK;
}
HRESULT WebView::setGeolocationProvider(IWebGeolocationProvider* locationProvider)
{
m_geolocationProvider = locationProvider;
return S_OK;
}
HRESULT WebView::geolocationProvider(IWebGeolocationProvider** locationProvider)
{
if (!locationProvider)
return E_POINTER;
if (!m_geolocationProvider)
return E_FAIL;
return m_geolocationProvider.copyRefTo(locationProvider);
}
HRESULT WebView::geolocationDidChangePosition(IWebGeolocationPosition* position)
{
#if ENABLE(CLIENT_BASED_GEOLOCATION)
if (!m_page)
return E_FAIL;
m_page->geolocationController()->positionChanged(core(position));
return S_OK;
#else
return E_NOTIMPL;
#endif
}
HRESULT WebView::geolocationDidFailWithError(IWebError* error)
{
#if ENABLE(CLIENT_BASED_GEOLOCATION)
if (!m_page)
return E_FAIL;
if (!error)
return E_POINTER;
BSTR descriptionBSTR;
if (FAILED(error->localizedDescription(&descriptionBSTR)))
return E_FAIL;
String descriptionString(descriptionBSTR, SysStringLen(descriptionBSTR));
SysFreeString(descriptionBSTR);
RefPtr<GeolocationError> geolocationError = GeolocationError::create(GeolocationError::PositionUnavailable, descriptionString);
m_page->geolocationController()->errorOccurred(geolocationError.get());
return S_OK;
#else
return E_NOTIMPL;
#endif
}
HRESULT WebView::setDomainRelaxationForbiddenForURLScheme(BOOL forbidden, BSTR scheme)
{
SecurityOrigin::setDomainRelaxationForbiddenForURLScheme(forbidden, String(scheme, SysStringLen(scheme)));
return S_OK;
}
HRESULT WebView::registerURLSchemeAsSecure(BSTR scheme)
{
SchemeRegistry::registerURLSchemeAsSecure(toString(scheme));
return S_OK;
}
HRESULT WebView::nextDisplayIsSynchronous()
{
m_nextDisplayIsSynchronous = true;
return S_OK;
}
#if USE(ACCELERATED_COMPOSITING)
bool WebView::shouldRender() const
{
Frame* coreFrame = core(m_mainFrame);
if (!coreFrame)
return true;
FrameView* frameView = coreFrame->view();
if (!frameView)
return true;
return !frameView->layoutPending();
}
#endif
class EnumTextMatches : public IEnumTextMatches
{
long m_ref;
UINT m_index;
Vector<IntRect> m_rects;
public:
EnumTextMatches(Vector<IntRect>* rects) : m_index(0), m_ref(1)
{
m_rects = *rects;
}
virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv)
{
if (IsEqualGUID(riid, IID_IUnknown) || IsEqualGUID(riid, IID_IEnumTextMatches)) {
*ppv = this;
AddRef();
}
return *ppv?S_OK:E_NOINTERFACE;
}
virtual ULONG STDMETHODCALLTYPE AddRef()
{
return m_ref++;
}
virtual ULONG STDMETHODCALLTYPE Release()
{
if (m_ref == 1) {
delete this;
return 0;
}
else
return m_ref--;
}
virtual HRESULT STDMETHODCALLTYPE Next(ULONG, RECT* rect, ULONG* pceltFetched)
{
if (m_index < m_rects.size()) {
if (pceltFetched)
*pceltFetched = 1;
*rect = m_rects[m_index];
m_index++;
return S_OK;
}
if (pceltFetched)
*pceltFetched = 0;
return S_FALSE;
}
virtual HRESULT STDMETHODCALLTYPE Skip(ULONG celt)
{
m_index += celt;
return S_OK;
}
virtual HRESULT STDMETHODCALLTYPE Reset(void)
{
m_index = 0;
return S_OK;
}
virtual HRESULT STDMETHODCALLTYPE Clone(IEnumTextMatches**)
{
return E_NOTIMPL;
}
};
HRESULT createMatchEnumerator(Vector<IntRect>* rects, IEnumTextMatches** matches)
{
*matches = new EnumTextMatches(rects);
return (*matches)?S_OK:E_OUTOFMEMORY;
}
Page* core(IWebView* iWebView)
{
Page* page = 0;
COMPtr<WebView> webView;
if (SUCCEEDED(iWebView->QueryInterface(&webView)) && webView)
page = webView->page();
return page;
}
| [
"[email protected]"
] | [
[
[
1,
6539
]
]
] |
76d82eec0a1e9ebd70cfeaff3fb5ac730c1393ff | faaac39c2cc373003406ab2ac4f5363de07a6aae | / zenithprime/src/controller/BattleBoard/BBControler.cpp | 4687e9edb7d2a0e539debdfd4d2afdb12fa37888 | [] | no_license | mgq812/zenithprime | 595625f2ec86879eb5d0df4613ba41a10e3158c0 | 3c8ff4a46fb8837e13773e45f23974943a467a6f | refs/heads/master | 2021-01-20T06:57:05.754430 | 2011-02-05T17:20:19 | 2011-02-05T17:20:19 | 32,297,284 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 712 | cpp | #include <iostream>
#include "BBControler.h"
BBControler::BBControler(BBModel* battleBoard1){
battleBoard = battleBoard1;
currentState = BBNullState::getState();
}
void BBControler::setState(BBState* nextState)
{
currentState = nextState;
}
void BBControler::LeftMouseClick(NxRaycastHit& hit){
currentState->LeftMouseClick(hit, this);
}
void BBControler::RightMouseClick(NxRaycastHit& hit){
currentState->RightMouseClick(hit, this);
}
void BBControler::MouseHover(NxRaycastHit& hit){
currentState->MouseHover(hit, this);
}
void BBControler::LeftMouseDrag(NxRaycastHit& hit){
currentState->LeftMouseDrag(hit, this);
}
BBModel* BBControler::getModel(){
return battleBoard;
} | [
"ElderGrimes@2c223db4-e1a0-a0c7-f360-d8b483a75394",
"MHSmith01@2c223db4-e1a0-a0c7-f360-d8b483a75394",
"mhsmith01@2c223db4-e1a0-a0c7-f360-d8b483a75394"
] | [
[
[
1,
4
],
[
12,
12
],
[
18,
19
],
[
26,
26
],
[
29,
29
]
],
[
[
5,
6
],
[
13,
17
],
[
20,
25
],
[
27,
28
]
],
[
[
7,
11
]
]
] |
0d47b9de3b4872584926b463c178093d59e9f59f | f13f46fbe8535a7573d0f399449c230a35cd2014 | /JelloMan/RotateGizmo.h | 6e36d496cfb5a5e294aaec4fdcd5cd4793d4f5d3 | [] | no_license | fangsunjian/jello-man | 354f1c86edc2af55045d8d2bcb58d9cf9b26c68a | 148170a4834a77a9e1549ad3bb746cb03470df8f | refs/heads/master | 2020-12-24T16:42:11.511756 | 2011-06-14T10:16:51 | 2011-06-14T10:16:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,257 | h | #pragma once
#include "Blox2D.h"
#include "Vector3.h"
#include "RenderContext.h"
#include "ITransformable.h"
#include "ILevelObject.h"
#include "ObjectSelecter.h"
#include "Axis.h"
class RotateGizmo
{
public:
// CONSTRUCTOR - DESTRUCTOR
RotateGizmo(ObjectSelecter* pObjectSelecter);
virtual ~RotateGizmo();
// GENERAL
void Show(ITransformable* pLevelObject, int id);
void Tick();
// DRAW
void Draw(const RenderContext* pRenderContext);
// SETTERS
void UseSnapping(bool bSnap)
{ m_bSnap = bSnap; }
void SetSnapSize(float snapSize)
{ m_SnapSize = snapSize; }
private:
static const int END_ELLIPSE_RADIUS = 5;
static const int AXIS_LENGTH = 100;
// DRAW
void DrawAxis(const Vector3& pos, Axis axis,
const Matrix& world, const Matrix& view, const Matrix& projection);
void DrawGizmo(const Vector3& pos);
// CONTROLS
void CheckControls();
// DATAMEMBERS
const RenderContext* m_pRenderContext;
bool m_bLockX;
bool m_bLockY;
bool m_bLockZ;
bool m_bSnap;
float m_SnapSize;
float m_Move;
D3D10_VIEWPORT m_ViewPort;
TextFormat* m_pAxisFont;
Vector3 m_vCenterPos;
ObjectSelecter* m_pObjectSelecter;
};
| [
"[email protected]",
"bastian.damman@0fb7bab5-1bf9-c5f3-09d9-7611b49293d6"
] | [
[
[
1,
5
],
[
10,
18
],
[
20,
20
],
[
23,
32
],
[
42,
46
],
[
50,
54
],
[
56,
57
],
[
60,
63
]
],
[
[
6,
9
],
[
19,
19
],
[
21,
22
],
[
33,
41
],
[
47,
49
],
[
55,
55
],
[
58,
59
]
]
] |
3daa7e410a170ec9b9d6ec5866cd0375684dbb56 | 9089a2927b27a193070b041a4c169de9b99eb444 | /logistics.h | 9097958d1008a7b05bb59ad2d0c41c407ac62dbd | [] | no_license | Alyanorno/Message-system | f58d9a3a8b40611daff1fb27a4ced1f15309b45b | 5aa6a238a6da45b4a784202d5614432a7531ef05 | refs/heads/master | 2020-06-06T21:09:43.922219 | 2011-12-17T12:46:11 | 2011-12-17T12:46:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,424 | h | #pragma once
#include <vector>
#include <string>
#include <typeinfo>
#include <map>
class Logistic
{
public:
Logistic();
~Logistic();
void Initialize();
struct Object
{
struct Id
{
Id( int _owner, int _id ) : owner(_owner), id(_id) {}
int owner, id;
};
std::vector< Id > ids;
};
std::vector< Object > objects;
struct Message
{
template< typename T >
Message( std::string _to, std::string _info, T& _message ) : to(_to), info(_info), received(false)
{ message = new T(_message); type = typeid(T).name(); }
Message( const Message& m ) : to(m.to), info(m.info), type(m.type), received(m.received)
{ message = m.message; }
~Message() {}
template< typename T >
T ReceiveMessage()
{
if( type != typeid(T).name() )
throw std::string( "Incorrect type" );
else if( received )
throw std::string( "Message already received" );
else if( message == 0 )
throw std::string( "Error null pointer!" );
received = true;
T* ptr = reinterpret_cast<T*>(message);
T t( *ptr );
delete message;
message = 0;
return t;
}
template< typename T >
bool IsMessageType() { return type == typeid(T).name(); }
std::string to;
std::string info;
private:
std::string type;
bool received;
void* message;
};
int MessageCount( std::string to )
{
if( recipients.count( to ) == 0 )
return 0;
else
return messages[ recipients[ to ] ].size();
}
Message GetMessage( std::string to )
{
if( recipients.count( to ) == 0 || messages[ recipients[ to ] ].size() == 0 )
throw std::string( "No messages to: " + to );
Message result( messages[ recipients[ to ] ].back() );
messages[ recipients[ to ] ].pop_back();
return result;
}
// Some very odd error where the compiler adds an A to GetMessage when you call GetMessage
// Temporary fix until i find out what the hell is going on
Message GetMessageA( std::string to )
{
return GetMessage( to );
}
void AddMessage( Message message )
{
if( recipients.count( message.to ) == 0 ) {
messages.push_back( std::vector< Message >() );
recipients.insert( std::pair<std::string,int>( message.to, messages.size() - 1 ) );
}
messages[ recipients[ message.to ] ].push_back( message );
}
private:
std::map< std::string, int > recipients;
std::vector< std::vector< Message > > messages;
};
| [
"[email protected]"
] | [
[
[
1,
92
]
]
] |
ed9b13eea31e4f4cda9438122288c1ea9622aea7 | b7c505dcef43c0675fd89d428e45f3c2850b124f | /Src/SimulatorQt/Util/qt/Win32/include/Qt/qatomic_powerpc.h | eba67d4b4de0838958a6bdae6b2bdc6c7a181749 | [
"BSD-2-Clause"
] | permissive | pranet/bhuman2009fork | 14e473bd6e5d30af9f1745311d689723bfc5cfdb | 82c1bd4485ae24043aa720a3aa7cb3e605b1a329 | refs/heads/master | 2021-01-15T17:55:37.058289 | 2010-02-28T13:52:56 | 2010-02-28T13:52:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 23,586 | h | /****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information ([email protected])
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at [email protected].
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QATOMIC_POWERPC_H
#define QATOMIC_POWERPC_H
QT_BEGIN_HEADER
QT_BEGIN_NAMESPACE
#define Q_ATOMIC_INT_REFERENCE_COUNTING_IS_ALWAYS_NATIVE
inline bool QBasicAtomicInt::isReferenceCountingNative()
{ return true; }
inline bool QBasicAtomicInt::isReferenceCountingWaitFree()
{ return false; }
#define Q_ATOMIC_INT_TEST_AND_SET_IS_ALWAYS_NATIVE
inline bool QBasicAtomicInt::isTestAndSetNative()
{ return true; }
inline bool QBasicAtomicInt::isTestAndSetWaitFree()
{ return false; }
#define Q_ATOMIC_INT_FETCH_AND_STORE_IS_ALWAYS_NATIVE
inline bool QBasicAtomicInt::isFetchAndStoreNative()
{ return true; }
inline bool QBasicAtomicInt::isFetchAndStoreWaitFree()
{ return false; }
#define Q_ATOMIC_INT_FETCH_AND_ADD_IS_ALWAYS_NATIVE
inline bool QBasicAtomicInt::isFetchAndAddNative()
{ return true; }
inline bool QBasicAtomicInt::isFetchAndAddWaitFree()
{ return false; }
#define Q_ATOMIC_POINTER_TEST_AND_SET_IS_ALWAYS_NATIVE
template <typename T>
Q_INLINE_TEMPLATE bool QBasicAtomicPointer<T>::isTestAndSetNative()
{ return true; }
template <typename T>
Q_INLINE_TEMPLATE bool QBasicAtomicPointer<T>::isTestAndSetWaitFree()
{ return false; }
#define Q_ATOMIC_POINTER_FETCH_AND_STORE_IS_ALWAYS_NATIVE
template <typename T>
Q_INLINE_TEMPLATE bool QBasicAtomicPointer<T>::isFetchAndStoreNative()
{ return true; }
template <typename T>
Q_INLINE_TEMPLATE bool QBasicAtomicPointer<T>::isFetchAndStoreWaitFree()
{ return false; }
#define Q_ATOMIC_POINTER_FETCH_AND_ADD_IS_ALWAYS_NATIVE
template <typename T>
Q_INLINE_TEMPLATE bool QBasicAtomicPointer<T>::isFetchAndAddNative()
{ return true; }
template <typename T>
Q_INLINE_TEMPLATE bool QBasicAtomicPointer<T>::isFetchAndAddWaitFree()
{ return false; }
QT_BEGIN_NAMESPACE
#if defined(Q_CC_GNU)
#if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 2) \
|| (!defined(__64BIT__) && !defined(__powerpc64__) && !defined(__ppc64__))
# define _Q_VALUE "0, %[_q_value]"
# define _Q_VALUE_MEMORY_OPERAND "+m" (_q_value)
# define _Q_VALUE_REGISTER_OPERAND [_q_value] "r" (&_q_value),
#else
// On 64-bit with gcc >= 4.2
# define _Q_VALUE "%y[_q_value]"
# define _Q_VALUE_MEMORY_OPERAND [_q_value] "+Z" (_q_value)
# define _Q_VALUE_REGISTER_OPERAND
#endif
inline bool QBasicAtomicInt::ref()
{
register int originalValue;
register int newValue;
asm volatile("lwarx %[originalValue]," _Q_VALUE "\n"
"addi %[newValue], %[originalValue], %[one]\n"
"stwcx. %[newValue]," _Q_VALUE "\n"
"bne- $-12\n"
: [originalValue] "=&b" (originalValue),
[newValue] "=&r" (newValue),
_Q_VALUE_MEMORY_OPERAND
: _Q_VALUE_REGISTER_OPERAND
[one] "i" (1)
: "cc", "memory");
return newValue != 0;
}
inline bool QBasicAtomicInt::deref()
{
register int originalValue;
register int newValue;
asm volatile("lwarx %[originalValue]," _Q_VALUE "\n"
"addi %[newValue], %[originalValue], %[minusOne]\n"
"stwcx. %[newValue]," _Q_VALUE "\n"
"bne- $-12\n"
: [originalValue] "=&b" (originalValue),
[newValue] "=&r" (newValue),
_Q_VALUE_MEMORY_OPERAND
: _Q_VALUE_REGISTER_OPERAND
[minusOne] "i" (-1)
: "cc", "memory");
return newValue != 0;
}
inline bool QBasicAtomicInt::testAndSetRelaxed(int expectedValue, int newValue)
{
register int result;
asm volatile("lwarx %[result]," _Q_VALUE "\n"
"xor. %[result], %[result], %[expectedValue]\n"
"bne $+12\n"
"stwcx. %[newValue]," _Q_VALUE "\n"
"bne- $-16\n"
: [result] "=&r" (result),
_Q_VALUE_MEMORY_OPERAND
: _Q_VALUE_REGISTER_OPERAND
[expectedValue] "r" (expectedValue),
[newValue] "r" (newValue)
: "cc", "memory");
return result == 0;
}
inline bool QBasicAtomicInt::testAndSetAcquire(int expectedValue, int newValue)
{
register int result;
asm volatile("lwarx %[result]," _Q_VALUE "\n"
"xor. %[result], %[result], %[expectedValue]\n"
"bne $+16\n"
"stwcx. %[newValue]," _Q_VALUE "\n"
"bne- $-16\n"
"isync\n"
: [result] "=&r" (result),
_Q_VALUE_MEMORY_OPERAND
: _Q_VALUE_REGISTER_OPERAND
[expectedValue] "r" (expectedValue),
[newValue] "r" (newValue)
: "cc", "memory");
return result == 0;
}
inline bool QBasicAtomicInt::testAndSetRelease(int expectedValue, int newValue)
{
register int result;
asm volatile("eieio\n"
"lwarx %[result]," _Q_VALUE "\n"
"xor. %[result], %[result], %[expectedValue]\n"
"bne $+12\n"
"stwcx. %[newValue]," _Q_VALUE "\n"
"bne- $-16\n"
: [result] "=&r" (result),
_Q_VALUE_MEMORY_OPERAND
: _Q_VALUE_REGISTER_OPERAND
[expectedValue] "r" (expectedValue),
[newValue] "r" (newValue)
: "cc", "memory");
return result == 0;
}
inline int QBasicAtomicInt::fetchAndStoreRelaxed(int newValue)
{
register int originalValue;
asm volatile("lwarx %[originalValue]," _Q_VALUE "\n"
"stwcx. %[newValue]," _Q_VALUE "\n"
"bne- $-8\n"
: [originalValue] "=&r" (originalValue),
_Q_VALUE_MEMORY_OPERAND
: _Q_VALUE_REGISTER_OPERAND
[newValue] "r" (newValue)
: "cc", "memory");
return originalValue;
}
inline int QBasicAtomicInt::fetchAndStoreAcquire(int newValue)
{
register int originalValue;
asm volatile("lwarx %[originalValue]," _Q_VALUE "\n"
"stwcx. %[newValue]," _Q_VALUE "\n"
"bne- $-8\n"
"isync\n"
: [originalValue] "=&r" (originalValue),
_Q_VALUE_MEMORY_OPERAND
: _Q_VALUE_REGISTER_OPERAND
[newValue] "r" (newValue)
: "cc", "memory");
return originalValue;
}
inline int QBasicAtomicInt::fetchAndStoreRelease(int newValue)
{
register int originalValue;
asm volatile("eieio\n"
"lwarx %[originalValue]," _Q_VALUE "\n"
"stwcx. %[newValue]," _Q_VALUE "\n"
"bne- $-8\n"
: [originalValue] "=&r" (originalValue),
_Q_VALUE_MEMORY_OPERAND
: _Q_VALUE_REGISTER_OPERAND
[newValue] "r" (newValue)
: "cc", "memory");
return originalValue;
}
inline int QBasicAtomicInt::fetchAndAddRelaxed(int valueToAdd)
{
register int originalValue;
register int newValue;
asm volatile("lwarx %[originalValue]," _Q_VALUE "\n"
"add %[newValue], %[originalValue], %[valueToAdd]\n"
"stwcx. %[newValue]," _Q_VALUE "\n"
"bne- $-12\n"
: [originalValue] "=&r" (originalValue),
[newValue] "=&r" (newValue),
_Q_VALUE_MEMORY_OPERAND
: _Q_VALUE_REGISTER_OPERAND
[valueToAdd] "r" (valueToAdd)
: "cc", "memory");
return originalValue;
}
inline int QBasicAtomicInt::fetchAndAddAcquire(int valueToAdd)
{
register int originalValue;
register int newValue;
asm volatile("lwarx %[originalValue]," _Q_VALUE "\n"
"add %[newValue], %[originalValue], %[valueToAdd]\n"
"stwcx. %[newValue]," _Q_VALUE "\n"
"bne- $-12\n"
"isync\n"
: [originalValue] "=&r" (originalValue),
[newValue] "=&r" (newValue),
_Q_VALUE_MEMORY_OPERAND
: _Q_VALUE_REGISTER_OPERAND
[valueToAdd] "r" (valueToAdd)
: "cc", "memory");
return originalValue;
}
inline int QBasicAtomicInt::fetchAndAddRelease(int valueToAdd)
{
register int originalValue;
register int newValue;
asm volatile("eieio\n"
"lwarx %[originalValue]," _Q_VALUE "\n"
"add %[newValue], %[originalValue], %[valueToAdd]\n"
"stwcx. %[newValue]," _Q_VALUE "\n"
"bne- $-12\n"
: [originalValue] "=&r" (originalValue),
[newValue] "=&r" (newValue),
_Q_VALUE_MEMORY_OPERAND
: _Q_VALUE_REGISTER_OPERAND
[valueToAdd] "r" (valueToAdd)
: "cc", "memory");
return originalValue;
}
#if defined(__64BIT__) || defined(__powerpc64__) || defined(__ppc64__)
# define LPARX "ldarx"
# define STPCX "stdcx."
#else
# define LPARX "lwarx"
# define STPCX "stwcx."
#endif
template <typename T>
Q_INLINE_TEMPLATE bool QBasicAtomicPointer<T>::testAndSetRelaxed(T *expectedValue, T *newValue)
{
register void *result;
asm volatile(LPARX" %[result]," _Q_VALUE "\n"
"xor. %[result], %[result], %[expectedValue]\n"
"bne $+12\n"
STPCX" %[newValue]," _Q_VALUE "\n"
"bne- $-16\n"
: [result] "=&r" (result),
_Q_VALUE_MEMORY_OPERAND
: _Q_VALUE_REGISTER_OPERAND
[expectedValue] "r" (expectedValue),
[newValue] "r" (newValue)
: "cc", "memory");
return result == 0;
}
template <typename T>
Q_INLINE_TEMPLATE bool QBasicAtomicPointer<T>::testAndSetAcquire(T *expectedValue, T *newValue)
{
register void *result;
asm volatile(LPARX" %[result]," _Q_VALUE "\n"
"xor. %[result], %[result], %[expectedValue]\n"
"bne $+16\n"
STPCX" %[newValue]," _Q_VALUE "\n"
"bne- $-16\n"
"isync\n"
: [result] "=&r" (result),
_Q_VALUE_MEMORY_OPERAND
: _Q_VALUE_REGISTER_OPERAND
[expectedValue] "r" (expectedValue),
[newValue] "r" (newValue)
: "cc", "memory");
return result == 0;
}
template <typename T>
Q_INLINE_TEMPLATE bool QBasicAtomicPointer<T>::testAndSetRelease(T *expectedValue, T *newValue)
{
register void *result;
asm volatile("eieio\n"
LPARX" %[result]," _Q_VALUE "\n"
"xor. %[result], %[result], %[expectedValue]\n"
"bne $+12\n"
STPCX" %[newValue]," _Q_VALUE "\n"
"bne- $-16\n"
: [result] "=&r" (result),
_Q_VALUE_MEMORY_OPERAND
: _Q_VALUE_REGISTER_OPERAND
[expectedValue] "r" (expectedValue),
[newValue] "r" (newValue)
: "cc", "memory");
return result == 0;
}
template <typename T>
Q_INLINE_TEMPLATE T *QBasicAtomicPointer<T>::fetchAndStoreRelaxed(T *newValue)
{
register T *originalValue;
asm volatile(LPARX" %[originalValue]," _Q_VALUE "\n"
STPCX" %[newValue]," _Q_VALUE "\n"
"bne- $-8\n"
: [originalValue] "=&r" (originalValue),
_Q_VALUE_MEMORY_OPERAND
: _Q_VALUE_REGISTER_OPERAND
[newValue] "r" (newValue)
: "cc", "memory");
return originalValue;
}
template <typename T>
Q_INLINE_TEMPLATE T *QBasicAtomicPointer<T>::fetchAndStoreAcquire(T *newValue)
{
register T *originalValue;
asm volatile(LPARX" %[originalValue]," _Q_VALUE "\n"
STPCX" %[newValue]," _Q_VALUE "\n"
"bne- $-8\n"
"isync\n"
: [originalValue] "=&r" (originalValue),
_Q_VALUE_MEMORY_OPERAND
: _Q_VALUE_REGISTER_OPERAND
[newValue] "r" (newValue)
: "cc", "memory");
return originalValue;
}
template <typename T>
Q_INLINE_TEMPLATE T *QBasicAtomicPointer<T>::fetchAndStoreRelease(T *newValue)
{
register T *originalValue;
asm volatile("eieio\n"
LPARX" %[originalValue]," _Q_VALUE "\n"
STPCX" %[newValue]," _Q_VALUE "\n"
"bne- $-8\n"
: [originalValue] "=&r" (originalValue),
_Q_VALUE_MEMORY_OPERAND
: _Q_VALUE_REGISTER_OPERAND
[newValue] "r" (newValue)
: "cc", "memory");
return originalValue;
}
template <typename T>
Q_INLINE_TEMPLATE T *QBasicAtomicPointer<T>::fetchAndAddRelaxed(qptrdiff valueToAdd)
{
register T *originalValue;
register T *newValue;
asm volatile(LPARX" %[originalValue]," _Q_VALUE "\n"
"add %[newValue], %[originalValue], %[valueToAdd]\n"
STPCX" %[newValue]," _Q_VALUE "\n"
"bne- $-12\n"
: [originalValue] "=&r" (originalValue),
[newValue] "=&r" (newValue),
_Q_VALUE_MEMORY_OPERAND
: _Q_VALUE_REGISTER_OPERAND
[valueToAdd] "r" (valueToAdd * sizeof(T))
: "cc", "memory");
return originalValue;
}
template <typename T>
Q_INLINE_TEMPLATE T *QBasicAtomicPointer<T>::fetchAndAddAcquire(qptrdiff valueToAdd)
{
register T *originalValue;
register T *newValue;
asm volatile(LPARX" %[originalValue]," _Q_VALUE "\n"
"add %[newValue], %[originalValue], %[valueToAdd]\n"
STPCX" %[newValue]," _Q_VALUE "\n"
"bne- $-12\n"
"isync\n"
: [originalValue] "=&r" (originalValue),
[newValue] "=&r" (newValue),
_Q_VALUE_MEMORY_OPERAND
: _Q_VALUE_REGISTER_OPERAND
[valueToAdd] "r" (valueToAdd * sizeof(T))
: "cc", "memory");
return originalValue;
}
template <typename T>
Q_INLINE_TEMPLATE T *QBasicAtomicPointer<T>::fetchAndAddRelease(qptrdiff valueToAdd)
{
register T *originalValue;
register T *newValue;
asm volatile("eieio\n"
LPARX" %[originalValue]," _Q_VALUE "\n"
"add %[newValue], %[originalValue], %[valueToAdd]\n"
STPCX" %[newValue]," _Q_VALUE "\n"
"bne- $-12\n"
: [originalValue] "=&r" (originalValue),
[newValue] "=&r" (newValue),
_Q_VALUE_MEMORY_OPERAND
: _Q_VALUE_REGISTER_OPERAND
[valueToAdd] "r" (valueToAdd * sizeof(T))
: "cc", "memory");
return originalValue;
}
#undef LPARX
#undef STPCX
#undef _Q_VALUE
#undef _Q_VALUE_MEMORY_OPERAND
#undef _Q_VALUE_REGISTER_OPERAND
#else
extern "C" {
int q_atomic_test_and_set_int(volatile int *ptr, int expectedValue, int newValue);
int q_atomic_test_and_set_acquire_int(volatile int *ptr, int expectedValue, int newValue);
int q_atomic_test_and_set_release_int(volatile int *ptr, int expectedValue, int newValue);
int q_atomic_test_and_set_ptr(volatile void *ptr, void *expectedValue, void *newValue);
int q_atomic_test_and_set_acquire_ptr(volatile void *ptr, void *expectedValue, void *newValue);
int q_atomic_test_and_set_release_ptr(volatile void *ptr, void *expectedValue, void *newValue);
int q_atomic_increment(volatile int *);
int q_atomic_decrement(volatile int *);
int q_atomic_set_int(volatile int *, int);
int q_atomic_fetch_and_store_acquire_int(volatile int *ptr, int newValue);
int q_atomic_fetch_and_store_release_int(volatile int *ptr, int newValue);
void *q_atomic_set_ptr(volatile void *, void *);
int q_atomic_fetch_and_store_acquire_ptr(volatile void *ptr, void *newValue);
int q_atomic_fetch_and_store_release_ptr(volatile void *ptr, void *newValue);
int q_atomic_fetch_and_add_int(volatile int *ptr, int valueToAdd);
int q_atomic_fetch_and_add_acquire_int(volatile int *ptr, int valueToAdd);
int q_atomic_fetch_and_add_release_int(volatile int *ptr, int valueToAdd);
void *q_atomic_fetch_and_add_ptr(volatile void *ptr, qptrdiff valueToAdd);
void *q_atomic_fetch_and_add_acquire_ptr(volatile void *ptr, qptrdiff valueToAdd);
void *q_atomic_fetch_and_add_release_ptr(volatile void *ptr, qptrdiff valueToAdd);
} // extern "C"
inline bool QBasicAtomicInt::ref()
{
return q_atomic_increment(&_q_value) != 0;
}
inline bool QBasicAtomicInt::deref()
{
return q_atomic_decrement(&_q_value) != 0;
}
inline bool QBasicAtomicInt::testAndSetRelaxed(int expectedValue, int newValue)
{
return q_atomic_test_and_set_int(&_q_value, expectedValue, newValue) != 0;
}
inline bool QBasicAtomicInt::testAndSetAcquire(int expectedValue, int newValue)
{
return q_atomic_test_and_set_acquire_int(&_q_value, expectedValue, newValue) != 0;
}
inline bool QBasicAtomicInt::testAndSetRelease(int expectedValue, int newValue)
{
return q_atomic_test_and_set_release_int(&_q_value, expectedValue, newValue) != 0;
}
inline int QBasicAtomicInt::fetchAndStoreRelaxed(int newValue)
{
return q_atomic_set_int(&_q_value, newValue);
}
inline int QBasicAtomicInt::fetchAndStoreAcquire(int newValue)
{
return q_atomic_fetch_and_store_acquire_int(&_q_value, newValue);
}
inline int QBasicAtomicInt::fetchAndStoreRelease(int newValue)
{
return q_atomic_fetch_and_store_release_int(&_q_value, newValue);
}
inline int QBasicAtomicInt::fetchAndAddRelaxed(int valueToAdd)
{
return q_atomic_fetch_and_add_int(&_q_value, valueToAdd);
}
inline int QBasicAtomicInt::fetchAndAddAcquire(int valueToAdd)
{
return q_atomic_fetch_and_add_acquire_int(&_q_value, valueToAdd);
}
inline int QBasicAtomicInt::fetchAndAddRelease(int valueToAdd)
{
return q_atomic_fetch_and_add_release_int(&_q_value, valueToAdd);
}
template <typename T>
Q_INLINE_TEMPLATE bool QBasicAtomicPointer<T>::testAndSetRelaxed(T *expectedValue, T *newValue)
{
return q_atomic_test_and_set_ptr(&_q_value, expectedValue, newValue) != 0;
}
template <typename T>
Q_INLINE_TEMPLATE bool QBasicAtomicPointer<T>::testAndSetAcquire(T *expectedValue, T *newValue)
{
return q_atomic_test_and_set_acquire_ptr(&_q_value, expectedValue, newValue) != 0;
}
template <typename T>
Q_INLINE_TEMPLATE bool QBasicAtomicPointer<T>::testAndSetRelease(T *expectedValue, T *newValue)
{
return q_atomic_test_and_set_release_ptr(&_q_value, expectedValue, newValue) != 0;
}
template <typename T>
Q_INLINE_TEMPLATE T *QBasicAtomicPointer<T>::fetchAndStoreRelaxed(T *newValue)
{
return reinterpret_cast<T *>(q_atomic_set_ptr(&_q_value, newValue));
}
template <typename T>
Q_INLINE_TEMPLATE T *QBasicAtomicPointer<T>::fetchAndStoreAcquire(T *newValue)
{
return reinterpret_cast<T *>(q_atomic_fetch_and_store_acquire_ptr(&_q_value, newValue));
}
template <typename T>
Q_INLINE_TEMPLATE T *QBasicAtomicPointer<T>::fetchAndStoreRelease(T *newValue)
{
return reinterpret_cast<T *>(q_atomic_fetch_and_store_release_ptr(&_q_value, newValue));
}
template <typename T>
Q_INLINE_TEMPLATE T *QBasicAtomicPointer<T>::fetchAndAddRelaxed(qptrdiff valueToAdd)
{
return reinterpret_cast<T *>(q_atomic_fetch_and_add_ptr(&_q_value, valueToAdd * sizeof(T)));
}
template <typename T>
Q_INLINE_TEMPLATE T *QBasicAtomicPointer<T>::fetchAndAddAcquire(qptrdiff valueToAdd)
{
return reinterpret_cast<T *>(q_atomic_fetch_and_add_acquire_ptr(&_q_value, valueToAdd * sizeof(T)));
}
template <typename T>
Q_INLINE_TEMPLATE T *QBasicAtomicPointer<T>::fetchAndAddRelease(qptrdiff valueToAdd)
{
return reinterpret_cast<T *>(q_atomic_fetch_and_add_release_ptr(&_q_value, valueToAdd * sizeof(T)));
}
#endif
inline bool QBasicAtomicInt::testAndSetOrdered(int expectedValue, int newValue)
{
return testAndSetAcquire(expectedValue, newValue);
}
inline int QBasicAtomicInt::fetchAndStoreOrdered(int newValue)
{
return fetchAndStoreAcquire(newValue);
}
inline int QBasicAtomicInt::fetchAndAddOrdered(int valueToAdd)
{
return fetchAndAddAcquire(valueToAdd);
}
template <typename T>
Q_INLINE_TEMPLATE bool QBasicAtomicPointer<T>::testAndSetOrdered(T *expectedValue, T *newValue)
{
return testAndSetAcquire(expectedValue, newValue);
}
template <typename T>
Q_INLINE_TEMPLATE T *QBasicAtomicPointer<T>::fetchAndStoreOrdered(T *newValue)
{
return fetchAndStoreAcquire(newValue);
}
template <typename T>
Q_INLINE_TEMPLATE T *QBasicAtomicPointer<T>::fetchAndAddOrdered(qptrdiff valueToAdd)
{
return fetchAndAddAcquire(valueToAdd);
}
QT_END_NAMESPACE
QT_END_HEADER
#endif // QATOMIC_POWERPC_H
| [
"alon@rogue.(none)"
] | [
[
[
1,
650
]
]
] |
786882edd461bae86af6cfa554d9bbaab4de9f7b | bfdfb7c406c318c877b7cbc43bc2dfd925185e50 | /stdlib/ffi/HSca_Random.cpp | e2b7246196b5e4f0ddc4ad7172d1ed1ab8403a08 | [
"MIT"
] | permissive | ysei/Hayat | 74cc1e281ae6772b2a05bbeccfcf430215cb435b | b32ed82a1c6222ef7f4bf0fc9dedfad81280c2c0 | refs/heads/master | 2020-12-11T09:07:35.606061 | 2011-08-01T12:38:39 | 2011-08-01T12:38:39 | null | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 2,198 | cpp | /* -*- coding: sjis-dos; -*- */
/*
* copyright 2010 FUKUZAWA Tadashi. All rights reserved.
*/
#include "HSca_Random.h"
static hyu32 seed = 0x23456789;
namespace Hayat {
void genRand(void)
{
/* taps: 32 31 29 1; 帰還多項式: x^32 + x^31 + x^29 + x + 1 */
for (int i = 32; i > 0; --i)
seed = (seed >> 1) ^ (-((hys32)(seed & 1)) & 0xd0000001u);
}
}
FFI_DEFINITION_START {
// M系列乱数: アルゴリズムは ガロアLFSR
// http://ja.wikipedia.org/wiki/線形帰還シフトレジスタ
// 周期は 2^32-1 、seedは 0 にはならない
// rand(x), rand(n,m) は、単に剰余を取っているだけなので、
// 小さい数値の方が微妙に頻度が高い。これはxやm-nが32bit近いと
// 影響が大きくなるはず。
// また、seedは0にならないので、その分少し偏っていると言えなくもない。
// 通常ゲームで使用する数値の範囲であれば、ほぼ問題とならないはず。
hys32 FFI_FUNC(srand) (Value selfVal, hys32 x)
{
FFI_DEBUG_ASSERT_CLASSMETHOD(selfVal);
HMD_ASSERTMSG(x != 0, M_M("srand(0) is not allowed")); // todo: exceptionにすべき
seed = (hyu32) x;
return x;
}
hys32 FFI_FUNC(seed) (Value selfVal)
{
FFI_DEBUG_ASSERT_CLASSMETHOD(selfVal);
return (hys32)seed;
}
DEEP_FFI_FUNC(rand)
{
Value selfVal = context->pop();
FFI_DEBUG_ASSERT_CLASSMETHOD(selfVal);
Hayat::genRand();
if (numArgs == 0) {
context->pushInt((hys32)seed);
return;
} else if (numArgs == 1) {
hys32 x = context->popInt();
HMD_ASSERT(x > 0); // todo: exception にすべき
context->pushInt((hys32)(seed % (hyu32)x));
return;
} else if (numArgs == 2) {
hys32 y = context->popInt();
hys32 x = context->popInt();
HMD_ASSERT(y >= x); // todo: exception にすべき
hys32 d = y - x + 1;
context->pushInt((hys32)(seed % (hyu32)d) + x);
return;
}
HMD_FATAL_ERROR("Random::rand(...) bad arguments error: numArgs = %d\n", numArgs);
}
} FFI_DEFINITION_END
| [
"[email protected]"
] | [
[
[
1,
73
]
]
] |
237accef9e67081ff8a2341566321bcacea4ed5e | 7dd2dbb15df45024e4c3f555da6d9ca6fc2c4d8b | /maelstrom/main.cpp | bdefee8a9122866d1284fd25c1988c40e77e6f68 | [] | no_license | wangscript/maelstrom-editor | c9f761e1f9e5f4e64d7e37834a7a63e04f57ae31 | 5bfab31bf444f44b9f8209f4deaed8715c305426 | refs/heads/master | 2021-01-10T01:37:00.619456 | 2011-11-21T23:17:08 | 2011-11-21T23:17:08 | 50,160,495 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 568 | cpp | #include <QtGui/QApplication>
#include <splashscreen.h>
#include <mainwindow.h>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QCoreApplication::setOrganizationName("Vortex");
QCoreApplication::setApplicationName("Maelstrom");
SplashScreen splash;
MainWindow mainWindow;
QObject::connect(&mainWindow, SIGNAL(initializeProgressChanged(QString)), &splash, SLOT(showMessage(QString)));
splash.show();
mainWindow.initialize();
mainWindow.show();
splash.close();
return a.exec();
}
| [
"[email protected]"
] | [
[
[
1,
24
]
]
] |
9ddda77bfd276737027ee5de3fb206a0c290ce84 | df238aa31eb8c74e2c208188109813272472beec | /BCGInclude/BCGPToolBar.h | e393d059fcf40640e19bd8268ea6bfe2c3bf0a7f | [] | 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 | 28,292 | h | //*******************************************************************************
// COPYRIGHT NOTES
// ---------------
// This is a part of the BCGControlBar Library
// Copyright (C) 1998-2008 BCGSoft Ltd.
// All rights reserved.
//
// This source code can be used, distributed or modified
// only under terms and conditions
// of the accompanying license agreement.
//*******************************************************************************
//
// bcgtoolbar.h : definition of CBCGPToolBar
//
// This code is based on the Microsoft Visual C++ sample file
// TOOLBAR.C from the OLDBARS example
//
#ifndef _TOOLBAR_H_
#define _TOOLBAR_H_
#ifndef __AFXTEMPL_H__
#include "afxtempl.h"
#endif
#include "BCGCBPro.h"
#include "BCGPToolbarDropTarget.h"
#include "BCGPToolbarDropSource.h"
#include "BCGPToolBarImages.h"
#include "BCGPToolbarButton.h"
#include "BCGPControlBarImpl.h"
#include "CmdUsageCount.h"
#include "BCGPCommandManager.h"
#include "BCGPVisualManager.h"
#include "BCGGlobals.h"
#include "BCGPBaseToolBar.h"
class CBCGPToolbarMenuButton;
class CCustomizeButton;
class CBCGPRegistry;
//-----------------------------------------------
// CBCGPToolbar LoadBitmap/LoadToolbar parameters:
//-----------------------------------------------
class BCGCBPRODLLEXPORT CBCGPToolBarParams
{
public:
CBCGPToolBarParams();
UINT m_uiColdResID; // Toolbar regular images
UINT m_uiHotResID; // Toolbar "hot" images
UINT m_uiDisabledResID; // Toolbar disabled images
UINT m_uiLargeColdResID; // Toolbar large regular images
UINT m_uiLargeHotResID; // Toolbar large "hot" images
UINT m_uiLargeDisabledResID; // Toolbar large disabled images
UINT m_uiMenuResID; // Menu images
UINT m_uiMenuDisabledResID; // Menu disabled images
};
//----------------------------------
// BCGPToolbar notification messages:
//----------------------------------
BCGCBPRODLLEXPORT extern UINT BCGM_TOOLBARMENU;
BCGCBPRODLLEXPORT extern UINT BCGM_CUSTOMIZETOOLBAR;
BCGCBPRODLLEXPORT extern UINT BCGM_CREATETOOLBAR;
BCGCBPRODLLEXPORT extern UINT BCGM_DELETETOOLBAR;
BCGCBPRODLLEXPORT extern UINT BCGM_CUSTOMIZEHELP;
BCGCBPRODLLEXPORT extern UINT BCGM_RESETTOOLBAR;
BCGCBPRODLLEXPORT extern UINT BCGM_RESETMENU;
BCGCBPRODLLEXPORT extern UINT BCGM_SHOWREGULARMENU;
BCGCBPRODLLEXPORT extern UINT BCGM_RESETCONTEXTMENU;
BCGCBPRODLLEXPORT extern UINT BCGM_RESETKEYBOARD;
BCGCBPRODLLEXPORT extern UINT BCGM_RESETRPROMPT;
extern const UINT uiAccTimerDelay;
extern const UINT uiAccNotifyEvent;
#define LINE_OFFSET 5
class BCGCBPRODLLEXPORT CBCGPToolBar : public CBCGPBaseToolBar
{
friend class CBCGPToolbarDropTarget;
friend class CBCGPToolbarsPage;
friend class CBCGPOptionsPage;
friend class CButtonsTextList;
friend class CBCGPCommandManager;
friend class CCustomizeButton;
friend class CBCGPCustomizeMenuButton;
friend class CBCGPToolTipCtrl;
DECLARE_SERIAL(CBCGPToolBar)
//--------------
// Construction:
//--------------
public:
CBCGPToolBar();
virtual BOOL Create(CWnd* pParentWnd,
DWORD dwStyle = dwDefaultToolbarStyle,
UINT nID = AFX_IDW_TOOLBAR);
virtual BOOL CreateEx(CWnd* pParentWnd, DWORD dwCtrlStyle = TBSTYLE_FLAT,
DWORD dwStyle = dwDefaultToolbarStyle,
CRect rcBorders = CRect(1, 1, 1, 1),
UINT nID = AFX_IDW_TOOLBAR);
//----------------------------------------------------------------
// Set toolbar buttons image resources.
// You should use SINGLE CBCGPToolBarImages for ALL your toolbars!
//----------------------------------------------------------------
static BOOL SetUserImages (CBCGPToolBarImages* pUserImages);
virtual void ResetImages (); // Reset all toolbar images exept user-derfined to the default
//------------------------------
// Clear all images except user:
//------------------------------
static void ResetAllImages();
//--------------------------------
// Dimension manipulation methods:
//--------------------------------
static void SetSizes (SIZE sizeButton, SIZE sizeImage);
static void SetMenuSizes (SIZE sizeButton, SIZE sizeImage);
static CSize GetMenuImageSize ();
static CSize GetMenuButtonSize ();
void SetLockedSizes (SIZE sizeButton, SIZE sizeImage);
void SetHeight (int cyHeight);
//-----------------
// Toolbar context:
//-----------------
virtual BOOL LoadBitmap (UINT uiResID, UINT uiColdResID = 0,
UINT uiMenuResID = 0, BOOL bLocked = FALSE,
UINT uiDisabledResID = 0, UINT uiMenuDisabledResID = 0);
virtual BOOL LoadToolBar (UINT uiResID, UINT uiColdResID = 0,
UINT uiMenuResID = 0, BOOL bLocked = FALSE,
UINT uiDisabledResID = 0, UINT uiMenuDisabledResID = 0,
UINT uiHotResID = 0);
virtual BOOL LoadBitmapEx (CBCGPToolBarParams& params, BOOL bLocked = FALSE);
virtual BOOL LoadToolBarEx (UINT uiToolbarResID, CBCGPToolBarParams& params,
BOOL bLocked = FALSE);
//----------------------------
// Toolbar buttons add/remove:
//----------------------------
virtual BOOL SetButtons(const UINT* lpIDArray, int nIDCount, BOOL bRemapImages = TRUE);
virtual int InsertButton (const CBCGPToolbarButton& button, INT_PTR iInsertAt = -1);
virtual int InsertSeparator (INT_PTR iInsertAt = -1);
int ReplaceButton (UINT uiCmd, const CBCGPToolbarButton& button, BOOL bAll = FALSE);
virtual BOOL RemoveButton (int iIndex);
virtual void RemoveAllButtons ();
static BOOL IsLastCommandFromButton (CBCGPToolbarButton* pButton);
static BOOL AddToolBarForImageCollection (UINT uiResID, UINT uiBmpResID = 0,
UINT uiColdResID = 0, UINT uiMenuResID = 0,
UINT uiDisabledResID = 0, UINT uiMenuDisabledResID = 0);
static void SetNonPermittedCommands (CList<UINT, UINT>& lstCommands);
static BOOL IsCommandPermitted (UINT uiCmd)
{
return m_lstUnpermittedCommands.Find (uiCmd) == NULL;
}
static void SetBasicCommands (CList<UINT, UINT>& lstCommands);
static void AddBasicCommand (UINT uiCmd);
static BOOL IsBasicCommand (UINT uiCmd)
{
return m_lstBasicCommands.Find (uiCmd) != NULL;
}
static const CList<UINT, UINT>& GetBasicCommands ()
{
return m_lstBasicCommands;
}
static BOOL IsCommandRarelyUsed (UINT uiCmd);
static void AddCommandUsage (UINT uiCommand);
static BOOL SetCommandUsageOptions (UINT nStartCount, UINT nMinUsagePercentage = 5);
virtual int GetRowHeight () const
{
if (m_bDrawTextLabels)
{
ASSERT (m_nMaxBtnHeight > 0);
return m_nMaxBtnHeight;
}
return max (globalData.GetTextHeight (m_dwStyle & CBRS_ORIENT_HORZ),
(m_bMenuMode ?
(m_sizeMenuButton.cy > 0 ?
m_sizeMenuButton.cy : m_sizeButton.cy) :
GetButtonSize ().cy));
}
virtual int GetColumnWidth () const
{
return m_bMenuMode ?
m_sizeMenuButton.cx > 0 ?
m_sizeMenuButton.cx : m_sizeButton.cx :
GetButtonSize ().cx;
}
virtual BOOL IsButtonExtraSizeAvailable () const
{
return TRUE;
}
static void SetHelpMode (BOOL bOn = TRUE);
virtual void Deactivate ();
virtual void RestoreFocus ();
void SetToolBarBtnText (UINT nBtnIndex,
LPCTSTR szText = NULL,
BOOL bShowText = TRUE,
BOOL bShowImage = TRUE);
virtual BOOL CanFocus () const {return FALSE;}
void EnableLargeIcons (BOOL bEnable);
static void SetLargeIcons (BOOL bLargeIcons = TRUE);
static BOOL IsLargeIcons ()
{
return m_bLargeIcons;
}
static void AutoGrayInactiveImages (BOOL bEnable = TRUE,
int nGrayPercentage = 0,
BOOL bRedrawAllToolbars = TRUE);
static BOOL IsAutoGrayInactiveImages ()
{
return m_bAutoGrayInactiveImages;
}
CSize GetButtonSize () const
{
CSize size = m_bLocked ?
(m_bLargeIconsAreEnbaled ? m_sizeCurButtonLocked : m_sizeButtonLocked) :
(m_bLargeIconsAreEnbaled ? m_sizeCurButton : m_sizeButton);
if (IsButtonExtraSizeAvailable ())
{
size += CBCGPVisualManager::GetInstance ()->GetButtonExtraBorder ();
}
return size;
}
CSize GetImageSize () const
{
return m_bLocked ?
m_bLargeIconsAreEnbaled ? m_sizeCurImageLocked : m_sizeImageLocked :
m_bLargeIconsAreEnbaled ? m_sizeCurImage : m_sizeImage;
}
CSize GetLockedImageSize () const
{
if (!m_bLocked)
{
ASSERT (FALSE);
return CSize (0, 0);
}
return m_sizeImageLocked;
}
BOOL IsButtonHighlighted (int iButton) const;
//------------
// Attributes:
//------------
public:
BOOL IsLocked () const
{
return m_bLocked;
}
UINT GetResourceID () const
{
return m_uiOriginalResID;
}
virtual BOOL IsResourceChanged () const
{
return m_bResourceWasChanged;
}
virtual BOOL IsFloating () const {return m_bFloating;}
static const CObList& GetAllToolbars ();
// standard control bar things
int CommandToIndex(UINT nIDFind, int iIndexFirst = 0) const;
UINT GetItemID(int nIndex) const;
virtual void GetItemRect(int nIndex, LPRECT lpRect) const;
virtual void GetInvalidateItemRect(int nIndex, LPRECT lpRect) const;
UINT GetButtonStyle(int nIndex) const;
virtual void SetButtonStyle(int nIndex, UINT nStyle);
int GetCount () const;
int ButtonToIndex(const CBCGPToolbarButton* pButton) const;
CBCGPToolbarButton* GetButton (int iIndex) const;
const CObList& GetAllButtons() const { return m_Buttons; }
const CObList& GetOrigButtons() const { return m_OrigButtons; }
const CObList& GetOrigResetButtons() const { return m_OrigResetButtons; }
void SetOrigButtons (const CObList& lstOrigButtons);
// Find all buttons specified by the given command ID from the all
// toolbars:
static int GetCommandButtons (UINT uiCmd, CObList& listButtons);
static BOOL SetCustomizeMode (BOOL bSet = TRUE);
static BOOL IsCustomizeMode ()
{
return m_bCustomizeMode;
}
static BOOL IsAltCustomizeMode ()
{
return m_bAltCustomizeMode;
}
BOOL IsUserDefined () const;
static CBCGPToolBar* FromHandlePermanent (HWND hwnd);
static CBCGPToolBarImages* GetImages ()
{
return &m_Images;
}
static CBCGPToolBarImages* GetColdImages ()
{
return &m_ColdImages;
}
static CBCGPToolBarImages* GetDisabledImages ()
{
return &m_DisabledImages;
}
static CBCGPToolBarImages* GetLargeImages ()
{
return &m_LargeImages;
}
static CBCGPToolBarImages* GetLargeColdImages ()
{
return &m_LargeColdImages;
}
static CBCGPToolBarImages* GetLargeDisabledImages ()
{
return &m_LargeDisabledImages;
}
static CBCGPToolBarImages* GetMenuImages ()
{
return &m_MenuImages;
}
static CBCGPToolBarImages* GetDisabledMenuImages ()
{
return &m_DisabledMenuImages;
}
static CBCGPToolBarImages* GetUserImages ()
{
return m_pUserImages;
}
CBCGPToolBarImages* GetLockedImages ()
{
if (!m_bLocked)
{
ASSERT (FALSE);
return NULL;
}
return &m_ImagesLocked;
}
CBCGPToolBarImages* GetLockedColdImages ()
{
if (!m_bLocked)
{
ASSERT (FALSE);
return NULL;
}
return &m_ColdImagesLocked;
}
CBCGPToolBarImages* GetLockedDisabledImages ()
{
if (!m_bLocked)
{
ASSERT (FALSE);
return NULL;
}
return &m_DisabledImagesLocked;
}
CBCGPToolBarImages* GetLockedMenuImages ()
{
if (!m_bLocked)
{
ASSERT (FALSE);
return NULL;
}
if (m_MenuImagesLocked.GetCount () > 0)
{
return &m_MenuImagesLocked;
}
if (m_ImagesLocked.GetCount () > 0)
{
return &m_ImagesLocked;
}
return NULL;
}
static int GetDefaultImage (UINT uiID)
{
int iImage;
if (m_DefaultImages.Lookup (uiID, iImage))
{
return iImage;
}
return -1;
}
int GetImagesOffset () const
{
return m_iImagesOffset;
}
CBCGPToolbarButton* GetHighlightedButton () const;
static void SetHotTextColor (COLORREF clrText);
static COLORREF GetHotTextColor ();
void SetHotBorder (BOOL bShowHotBorder)
{
m_bShowHotBorder = bShowHotBorder;
}
BOOL GetHotBorder () const
{
return m_bShowHotBorder;
}
void SetGrayDisabledButtons (BOOL bGrayDisabledButtons)
{
m_bGrayDisabledButtons = bGrayDisabledButtons;
}
BOOL GetGrayDisabledButtons () const
{
return m_bGrayDisabledButtons;
}
//------------------------------------------------------
// Enable/disable quick customization mode ("Alt+drag"):
//------------------------------------------------------
static void EnableQuickCustomization (BOOL bEnable = TRUE)
{
m_bAltCustomization = bEnable;
}
static void SetLook2000 (BOOL bLook2000 = TRUE);
static BOOL IsLook2000 ();
virtual void EnableDocking (DWORD dwAlignment);
void EnableCustomizeButton (BOOL bEnable, UINT uiCustomizeCmd, const CString& strCustomizeText, BOOL bQuickCustomize = TRUE);
void EnableCustomizeButton (BOOL bEnable, UINT uiCustomizeCmd, UINT uiCustomizeTextResId, BOOL bQuickCustomize = TRUE);
BOOL IsExistCustomizeButton()
{
if(m_pCustomizeBtn == NULL)
{
return FALSE;
}
return TRUE;
}
CCustomizeButton* GetCustomizeButton()
{
return m_pCustomizeBtn;
}
void EnableTextLabels (BOOL bEnable = TRUE);
virtual BOOL AllowChangeTextLabels () const
{
return TRUE;
}
BOOL AreTextLabels () const
{
return m_bTextLabels;
}
virtual BOOL OnBeforeRemoveButton (CBCGPToolbarButton* /*pButton*/, DROPEFFECT /*dropEffect*/)
{
return TRUE;
}
void SetMaskMode (BOOL bMasked)
{
m_bMasked = bMasked;
}
void SetPermament (BOOL bPermament = TRUE)
{
m_bPermament = bPermament;
}
BOOL GetIgnoreSetText () const
{
return m_bIgnoreSetText;
}
void SetIgnoreSetText (BOOL bValue)
{
m_bIgnoreSetText = bValue;
}
BOOL GetRouteCommandsViaFrame ()
{
return m_bRouteCommandsViaFrame;
}
void SetRouteCommandsViaFrame (BOOL bValue)
{
m_bRouteCommandsViaFrame = bValue;
}
BOOL IsAddRemoveQuickCustomize()
{
return m_bQuickCustomize;
}
BOOL IsBrother()
{
return m_bHasBrother;
}
CBCGPToolBar* GetBrotherToolbar()
{
return m_pBrotherToolBar;
}
void SetBrotherToolbar(CBCGPToolBar* pBrotherToolbar);
BOOL IsOneRowWithBrother();
void SetOneRowWithBrother();
void SetTwoRowsWithBrother();
BOOL CanHandleBrothers();
void EnableReflections(BOOL bEnable = TRUE)
{
m_bAllowReflections = bEnable;
}
static BOOL GetShowTooltips() {return m_bShowTooltips;} //JRG Modified 3/21/2000
static void SetShowTooltips(BOOL bValue) {m_bShowTooltips = bValue;} //JRG Modified 3/21/2000
HWND GetHwndLastFocus() const {return m_hwndLastFocus;};
static BOOL m_bDisableLabelsEdit;
public:
// for changing button info
void GetButtonInfo(int nIndex, UINT& nID, UINT& nStyle, int& iImage) const;
void SetButtonInfo(int nIndex, UINT nID, UINT nStyle, int iImage);
BOOL SetButtonText(int nIndex, LPCTSTR lpszText);
CString GetButtonText( int nIndex ) const;
void GetButtonText( int nIndex, CString& rString ) const;
// Save/load toolbar state + buttons:
void Serialize (CArchive& ar);
virtual BOOL LoadState (LPCTSTR lpszProfileName = NULL, int nIndex = -1, UINT uiID = (UINT) -1);
virtual BOOL SaveState (LPCTSTR lpszProfileName = NULL, int nIndex = -1, UINT uiID = (UINT) -1);
virtual BOOL RemoveStateFromRegistry (LPCTSTR lpszProfileName = NULL, int nIndex = -1, UINT uiID = (UINT) -1);
static BOOL LoadParameters (LPCTSTR lpszProfileName = NULL);
static BOOL SaveParameters (LPCTSTR lpszProfileName = NULL);
static BOOL LoadLargeIconsState (LPCTSTR lpszProfileName = NULL);
virtual BOOL CanBeRestored () const;
virtual BOOL CanBeClosed () const
{
return !m_bPermament;
}
virtual BOOL RestoreOriginalstate ();
virtual void OnReset () {}
static void ResetAll ();
virtual void AdjustLayout ();
virtual int HitTest(CPoint point);
virtual BOOL TranslateChar (UINT nChar);
virtual void OnUpdateCmdUI(CFrameWnd* pTarget, BOOL bDisableIfNoHndler);
virtual BOOL PrevMenu ();
virtual BOOL NextMenu ();
BOOL ProcessCommand (CBCGPToolbarButton* pButton);
CBCGPToolbarMenuButton* GetDroppedDownMenu (int* pIndex = NULL) const;
BOOL SetHot (CBCGPToolbarButton *pMenuButton);
virtual BOOL OnSetDefaultButtonText (CBCGPToolbarButton* pButton);
BOOL IsDragButton (const CBCGPToolbarButton* pButton) const
{
return pButton == m_pDragButton;
}
virtual void OnFillBackground (CDC* /*pDC*/) {}
virtual void OnGlobalFontsChanged ();
static BOOL m_bExtCharTranslation;
static double m_dblLargeImageRatio; // large image stretch ratio (default: * 2)
static void CBCGPToolBar::CleanUpImages ();
void CleanUpLockedImages ();
void AdjustSize ();
virtual BOOL OnUserToolTip (CBCGPToolbarButton* pButton, CString& strTTText) const;
// Implementation
public:
virtual ~CBCGPToolBar();
virtual CSize CalcFixedLayout(BOOL bStretch, BOOL bHorz);
virtual CSize CalcSize (BOOL bVertDock);
int WrapToolBar (int nWidth, int nHeight = 32767,
CDC* pDC = NULL,
int nColumnWidth = -1, int nRowHeight = -1);
virtual void OnChangeHot (int iHot);
virtual CSize StretchControlBar (int nLength, BOOL bVert);
CBCGPToolbarButton* InvalidateButton(int nIndex);
void UpdateButton(int nIndex);
virtual void OnChangeVisualManager ();
protected:
virtual CSize CalcLayout (DWORD dwMode, int nLength = -1);
void SizeToolBar (int nLength, BOOL bVert = FALSE);
public:
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected:
virtual int InsertButton (CBCGPToolbarButton* pButton, int iInsertAt = -1);
virtual BOOL DrawButton (CDC* pDC, CBCGPToolbarButton* pButton,
CBCGPToolBarImages* pImages, BOOL bHighlighted,
BOOL bDrawDisabledImages);
virtual void DrawDragMarker (CDC* pDC);
CBCGPToolBarImages* GetImageList (CBCGPToolBarImages& images, CBCGPToolBarImages& imagesLocked,
CBCGPToolBarImages& largeImages, CBCGPToolBarImages& largeImagesLocked) const;
void RebuildAccelerationKeys ();
virtual CWnd* GetCommandTarget () const
{
// determine target of command update
CFrameWnd* pTarget = (CFrameWnd*) GetOwner();
if (pTarget == NULL || (m_bRouteCommandsViaFrame && !pTarget->IsFrameWnd ()))
{
pTarget = BCGPGetParentFrame (this);
}
return pTarget;
}
void UpdateTooltips ();
virtual void OnAfterFloat ();
virtual void OnAfterDock (CBCGPBaseControlBar* /*pBar*/, LPCRECT /*lpRect*/, BCGP_DOCK_METHOD /*dockMethod*/);
virtual void OnBeforeChangeParent (CWnd* pWndNewParent, BOOL bDelay = FALSE);
protected:
friend class CBCGPWorkspace;
static CBCGPToolBar* m_pSelToolbar; // "Selected" toolbar in the customization mode
static CBCGPToolBarImages m_Images; // Shared toolbar images
static CBCGPToolBarImages m_ColdImages; // Shared toolbar "cold" images
static CBCGPToolBarImages m_DisabledImages; // Shared disabled images
static CBCGPToolBarImages m_LargeImages; // Shared toolbar large "hot" images
static CBCGPToolBarImages m_LargeColdImages; // Shared toolbar large "cold" images
static CBCGPToolBarImages m_LargeDisabledImages; // Shared disabled large images
static CBCGPToolBarImages m_MenuImages;
static CBCGPToolBarImages m_DisabledMenuImages;
static BOOL m_bAutoGrayInactiveImages;
static int m_nGrayImagePercentage;
static CBCGPToolBarImages* m_pUserImages; // Shared user-defined images
CBCGPToolBarImages m_ImagesLocked; // "Locked" toolbar images
CBCGPToolBarImages m_ColdImagesLocked; // "Locked" toolbar "cold" images
CBCGPToolBarImages m_DisabledImagesLocked; // "Locked" toolbar disabled images
CBCGPToolBarImages m_LargeImagesLocked; // "Locked" toolbar large images
CBCGPToolBarImages m_LargeColdImagesLocked; // "Locked" toolbar large "cold" images
CBCGPToolBarImages m_LargeDisabledImagesLocked; // "Locked" toolbar large disabled images
CBCGPToolBarImages m_MenuImagesLocked; // "Locked" toolbar menu images
CBCGPToolBarImages m_DisabledMenuImagesLocked; // "Locked" toolbar menu disabled images
BOOL m_bLocked;
BOOL m_bLargeIconsAreEnbaled;
CBCGPControlBarImpl m_Impl;
BOOL m_bMasked;
BOOL m_bPermament; // Can't be closed
BOOL m_bTextLabels; // Text labels below the image are available
BOOL m_bDrawTextLabels;
int m_nMaxBtnHeight;// Actual only if m_bTextLabels is TRUE
static CMap<UINT, UINT, int, int> m_DefaultImages;
static CSize m_sizeButton; // original size of button
static CSize m_sizeImage; // original size of glyph
static CSize m_sizeMenuButton; // size of button on the menu
static CSize m_sizeMenuImage; // size of image on the menu
static CSize m_sizeCurButton; // size of button
static CSize m_sizeCurImage; // size of glyph
CSize m_sizeButtonLocked; // original size of button of the locked toolbars
CSize m_sizeImageLocked; // original size of glyph of the locked toolbars
CSize m_sizeCurButtonLocked; // size of button
CSize m_sizeCurImageLocked; // size of glyph
int m_iButtonCapture; // index of button with capture (-1 => none)
int m_iHighlighted; // highlighted button index
int m_iSelected; // selected button index
int m_iHot;
CObList m_Buttons;
CObList m_OrigButtons; // Original (not customized) items
CObList m_OrigResetButtons; // Original (not customized) items after reset
BOOL m_bResourceWasChanged; // Resource was changed since last session
BOOL m_bLeaveFocus; // Don't remove selection in the focused bars.
BOOL m_bFloating;
CBCGPToolbarDropTarget m_DropTarget;
static CBCGPToolbarDropSource m_DropSource;
BOOL m_bNoDropTarget;
static BOOL m_bCustomizeMode;
static BOOL m_bAltCustomizeMode;
CToolTipCtrl* m_pToolTip;
int m_nTooltipsCount;
int m_iDragIndex;
CRect m_rectDrag;
CPen m_penDrag;
CBCGPToolbarButton* m_pDragButton;
CPoint m_ptStartDrag;
BOOL m_bIsDragCopy;
BOOL m_bStretchButton;
CRect m_rectTrack;
int m_iImagesOffset;
UINT m_uiOriginalResID; // Toolbar resource ID
BOOL m_bTracked;
CPoint m_ptLastMouse;
BOOL m_bMenuMode;
CWnd* m_pWndLastCapture;
HWND m_hwndLastFocus;
BOOL m_bDisableControlsIfNoHandler;
BOOL m_bRouteCommandsViaFrame;
BOOL m_bDisableCustomize;
CSize m_sizeLast;
static COLORREF m_clrTextHot;
static HHOOK m_hookMouseHelp; // Mouse hook for the help mode
static CBCGPToolBar* m_pLastHookedToolbar;
CMap<UINT, UINT&, CBCGPToolbarButton*, CBCGPToolbarButton*&> m_AcellKeys; // Keyborad acceleration keys
static BOOL m_bShowTooltips;
static BOOL m_bShowShortcutKeys;
static BOOL m_bLargeIcons;
static CList<UINT, UINT> m_lstUnpermittedCommands;
static CList<UINT, UINT> m_lstBasicCommands;
static CCmdUsageCount m_UsageCount;
BOOL m_bShowHotBorder;
BOOL m_bGrayDisabledButtons;
BOOL m_bIgnoreSetText;
int m_nMaxLen;
static BOOL m_bAltCustomization;
CCustomizeButton* m_pCustomizeBtn;
BOOL m_bQuickCustomize;
BOOL m_bHasBrother;
BOOL m_bElderBrother;
CBCGPToolBar* m_pBrotherToolBar;
BOOL m_bAllowReflections;
int m_iAccHotItem;
BOOL m_bRoundShape;
BOOL m_bInUpdateShadow;
virtual BOOL OnDrop(COleDataObject* pDataObject, DROPEFFECT dropEffect, CPoint point);
virtual DROPEFFECT OnDragEnter(COleDataObject* pDataObject, DWORD dwKeyState, CPoint point);
virtual void OnDragLeave();
virtual DROPEFFECT OnDragOver(COleDataObject* pDataObject, DWORD dwKeyState, CPoint point);
virtual void DoPaint(CDC* pDC);
virtual INT_PTR OnToolHitTest(CPoint point, TOOLINFO* pTI) const;
virtual BOOL PreTranslateMessage(MSG* pMsg);
virtual BOOL OnCommand(WPARAM wParam, LPARAM lParam);
virtual BOOL NotifyControlCommand (CBCGPToolbarButton* pButton,
BOOL bAccelerator,
int nNotifyCode,
WPARAM wParam,
LPARAM lParam);
virtual int FindDropIndex (const CPoint point, CRect& rectDrag) const;
virtual void AdjustLocations ();
virtual BOOL OnSendCommand (const CBCGPToolbarButton* /*pButton*/) { return FALSE; }
virtual BOOL AllowSelectDisabled () const { return FALSE; }
virtual BOOL AllowShowOnList () const { return TRUE; }
virtual BOOL AlwaysSaveSelection () const { return FALSE; }
virtual void DrawSeparator (CDC* pDC, const CRect& rect, BOOL bHorz);
virtual CBCGPToolbarButton* CreateDroppedButton (COleDataObject* pDataObject);
virtual BOOL OnKey (UINT /*nChar*/) { return FALSE; }
virtual void OnCustomizeMode (BOOL bSet);
virtual BOOL EnableContextMenuItems (CBCGPToolbarButton* pButton, CMenu* pPopup);
virtual BOOL IsPureMenuButton (CBCGPToolbarButton* /*pButton*/) const
{
return m_bMenuMode;
}
virtual void OnCalcSeparatorRect (CBCGPToolbarButton* pButton,
CRect& rectSeparator,
BOOL bHorz);
virtual void AddRemoveSeparator (const CBCGPToolbarButton* pButton,
const CPoint& ptStart, const CPoint& ptDrop);
virtual void ShowCommandMessageString (UINT uiCmdId);
static LRESULT CALLBACK BCGToolBarMouseProc (int nCode, WPARAM wParam, LPARAM lParam);
BOOL DropDownMenu (CBCGPToolbarButton* pButton);
virtual int CalcMaxButtonHeight ();
virtual BOOL AllowAltCustomization () const { return TRUE; }
virtual void OnAfterButtonDelete ();
void SetRoundedRgn ();
void RedrawCustomizeButton ();
void UpdateImagesColor ();
virtual BOOL OnSetAccData (long lVal);
void AccNotifyObjectFocusEvent (int iButtton);
// SmartUpdate methods:
virtual void SaveOriginalState (CBCGPRegistry& reg);
virtual BOOL LoadLastOriginalState (CBCGPRegistry& reg);
virtual BOOL SmartUpdate (const CObList& lstPrevButtons);
void SaveResetOriginalState (CBCGPRegistry& reg);
BOOL LoadResetOriginalState (CBCGPRegistry& reg);
BOOL RemoveResetStateButton (UINT uiCmdId);
int InsertResetStateButton (const CBCGPToolbarButton& button, int iInsertAt);
//{{AFX_MSG(CBCGPToolBar)
afx_msg void OnMouseMove(UINT nFlags, CPoint point);
afx_msg void OnCancelMode();
afx_msg void OnSysColorChange();
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
afx_msg void OnDestroy();
afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
afx_msg void OnToolbarAppearance();
afx_msg void OnToolbarDelete();
afx_msg void OnToolbarImage();
afx_msg void OnToolbarImageAndText();
afx_msg void OnToolbarStartGroup();
afx_msg void OnToolbarText();
afx_msg void OnLButtonUp(UINT nFlags, CPoint point);
afx_msg void OnWindowPosChanged(WINDOWPOS FAR* lpwndpos);
afx_msg HBRUSH OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor);
afx_msg BOOL OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message);
afx_msg void OnSize(UINT nType, int cx, int cy);
afx_msg void OnLButtonDblClk(UINT nFlags, CPoint point);
afx_msg void OnBcgbarresToolbarReset();
afx_msg void OnNcCalcSize(BOOL bCalcValidRects, NCCALCSIZE_PARAMS FAR* lpncsp);
afx_msg void OnNcPaint();
afx_msg void OnBcgbarresCopyImage();
afx_msg void OnSetFocus(CWnd* pOldWnd);
afx_msg void OnBcgbarresToolbarNewMenu();
afx_msg void OnWindowPosChanging(WINDOWPOS FAR* lpwndpos);
afx_msg BOOL OnEraseBkgnd(CDC* pDC);
afx_msg void OnKillFocus(CWnd* pNewWnd);
afx_msg void OnSettingChange(UINT uFlags, LPCTSTR lpszSection);
afx_msg void OnShowWindow(BOOL bShow, UINT nStatus);
afx_msg void OnRButtonDown(UINT nFlags, CPoint point);
//}}AFX_MSG
afx_msg void OnContextMenu(CWnd*, CPoint point);
afx_msg LRESULT OnMouseLeave(WPARAM,LPARAM);
afx_msg LRESULT OnHelpHitTest(WPARAM,LPARAM);
afx_msg LRESULT OnGetButtonCount(WPARAM,LPARAM);
afx_msg LRESULT OnGetItemRect(WPARAM,LPARAM);
afx_msg LRESULT OnGetButton(WPARAM,LPARAM);
afx_msg LRESULT OnGetButtonText(WPARAM,LPARAM);
afx_msg BOOL OnNeedTipText(UINT id, NMHDR* pNMH, LRESULT* pResult);
afx_msg LRESULT OnPromptReset(WPARAM, LPARAM);
afx_msg BCGNcHitTestType OnNcHitTest(CPoint point);
afx_msg LRESULT OnBCGUpdateToolTips(WPARAM, LPARAM);
afx_msg LRESULT OnBCGSetControlAero (WPARAM, LPARAM);
DECLARE_MESSAGE_MAP()
};
#endif //!_TOOLBAR_H_
| [
"myme5261314@ec588229-7da7-b333-41f6-0e1ebc3afda5"
] | [
[
[
1,
969
]
]
] |
d5c732652187c2ac56a4828fd0d454b9ff0abfb9 | e92a0b984f0798ef2bba9ad4199b431b4f5eb946 | /2009/simulateur/src/pc/webcam.cpp | 613b1bee68ddb0b5834dcd4cae901c85b812d01b | [] | no_license | AdamdbUT/mac-gyver | c09c1892080bf77c25cb4ca2a7ebaf7be3459032 | 32de5c0989710ccd671d46e0babb602e51bf8ff9 | refs/heads/master | 2021-01-23T15:53:19.383860 | 2010-06-21T13:33:38 | 2010-06-21T13:33:38 | 42,737,082 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,427 | cpp | #include "webcam.hpp"
webcam_t::webcam_t(const std::string& dev,size_t w,size_t h)
:m_width(w),m_height(h),m_image(image_t::yuv_format,0,0)
{
open(dev);
init();
}
webcam_t::~webcam_t()
{
deinit();
}
void webcam_t::start()
{
start_capturing();
m_image=image_t(image_t::yuv_format,m_width,m_height);
}
void webcam_t::stop()
{
stop_capturing();
}
size_t webcam_t::get_width()
{
return m_width;
}
size_t webcam_t::get_height()
{
return m_height;
}
void webcam_t::capture(image_t& img)
{
do_capture();
get_image(img);
}
void webcam_t::do_capture()
{
video_capture();
process_capture_to_image(m_image);
}
void webcam_t::get_image(image_t& img)
{
img=m_image;
}
const image_t& webcam_t::get_image2() const
{
return m_image;
}
int webcam_t::xioctl(int request,void *arg)
{
int r;
do
r=ioctl(m_fd,request,arg);
while(-1==r && EINTR==errno);
return r;
}
void webcam_t::open(const std::string& dev)
{
// open device
m_fd=::open(dev.c_str(),O_RDWR|O_NONBLOCK,0);
if(m_fd==-1)
{
printf("[video] Cannot open device '%s'\n",dev.c_str());
return;
}
}
bool webcam_t::init()
{
struct v4l2_capability cap;
struct v4l2_cropcap cropcap;
struct v4l2_crop crop;
struct v4l2_format fmt;
struct v4l2_input input;
struct v4l2_frmsizeenum frmsize;
struct v4l2_standard std;
// check the device is a video device, capable of read/write operations
if (xioctl(VIDIOC_QUERYCAP,&cap)==-1)
{
printf("[video] Error: device is not a valid V4L2 device or the request failed\n");
return false;
}
if(!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE))
{
printf("[video] Error: device has not video capture capability\n");
return false;
}
printf("[video] Available video inputs:\n");
memset(&input,0,sizeof(input));
while(ioctl(m_fd,VIDIOC_ENUMINPUT,&input)!=-1)
{
printf("[video] * %s[type=%s]\n",input.name,input.type==V4L2_INPUT_TYPE_CAMERA?"camera":"tuner");
input.index++;
}
printf("[video] Available frame sizes[experimental API call]:\n");
memset(&frmsize,0,sizeof(frmsize));
while(ioctl(m_fd,VIDIOC_ENUM_FRAMESIZES,&frmsize)!=-1)
{
if(frmsize.type==V4L2_FRMSIZE_TYPE_DISCRETE)
printf("[video] * %dx%d\n",frmsize.discrete.width,frmsize.discrete.height);
frmsize.index++;
}
printf("[video] Supported video standards:\n");
memset(&std,0,sizeof(std));
while(ioctl(m_fd,VIDIOC_ENUMSTD,&std)!=-1)
{
printf("[video] * %s[lines_per_frame=%d]\n",std.name,std.framelines);
std.index++;
}
bool read_write_supported=(cap.capabilities & V4L2_CAP_READWRITE);
m_read_write_supported=read_write_supported;
bool streaming_supported=(cap.capabilities & V4L2_CAP_STREAMING);
m_streaming_supported=streaming_supported;
bool asyncio_supported=(cap.capabilities & V4L2_CAP_ASYNCIO);
printf("[video] Device supports the following input mode:\n");
printf("[video] * read/write: %s\n",read_write_supported?"yes":"no");
printf("[video] * streaming: %s\n",streaming_supported?"yes":"no");
printf("[video] * asynchronous io: %s\n",asyncio_supported?"yes":"no");
if(!m_read_write_supported && !m_streaming_supported)
{
printf("[video] Error: device does not supported read !\n");
return false;
}
// note: we use a conservative choice: not interleave YUV but it would be better to do the best possible chocie using the enumeration
memset(&fmt,0,sizeof(fmt));
fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
fmt.fmt.pix.width = m_width;
fmt.fmt.pix.height = m_height;
fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_YUYV;
fmt.fmt.pix.field = V4L2_FIELD_NONE;
fmt.fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
if(xioctl(VIDIOC_S_FMT,&fmt)==-1)
{
printf("[video] Error: input format selection failed\n");
return false;
}
// if read write is not supported, setup mmap or user pointer
printf("[video] Trying read/write method...\n");
// try read/write method
{
if(read_write_supported)
{
m_video_buffer=new uint8_t[m_video_image_size];
if(m_video_buffer!=0)
{
printf("[video] Using read/write method\n");
m_capture_method=VIDEO_READ_WRITE;
goto Ltry_end;
}
else
printf("[video] Error: could not allocate video buffer\n");
}
}
// try user pointer method
{
struct v4l2_requestbuffers reqbuf;
printf("[video] Trying user pointer method...\n");
memset(&reqbuf,0,sizeof(reqbuf));
reqbuf.type=V4L2_BUF_TYPE_VIDEO_CAPTURE;
reqbuf.memory=V4L2_MEMORY_USERPTR;
if(ioctl(m_fd,VIDIOC_REQBUFS,&reqbuf)!=-1)
{
m_video_buffer=new uint8_t[m_video_image_size];
if(m_video_buffer!=0)
{
printf("[video] Using user pointer method\n");
m_capture_method=VIDEO_USERP;
goto Ltry_end;
}
else
printf("[video] Error: could not allocate video buffer\n");
}
}
// try memory mapping method
{
struct v4l2_requestbuffers reqbuf;
printf("[video] Trying memory map method...\n");
memset(&reqbuf,0,sizeof(reqbuf));
reqbuf.type=V4L2_BUF_TYPE_VIDEO_CAPTURE;
reqbuf.memory=V4L2_MEMORY_MMAP;
reqbuf.count=1;
if(ioctl(m_fd,VIDIOC_REQBUFS,&reqbuf)!=-1)
{
struct v4l2_buffer buffer;
memset(&buffer,0,sizeof (buffer));
buffer.type=reqbuf.type;
buffer.memory=V4L2_MEMORY_MMAP;
buffer.index=0;
if(ioctl(m_fd,VIDIOC_QUERYBUF,&buffer)!=-1)
{
m_mmap_buffer_length=buffer.length;
m_video_buffer=static_cast<uint8_t *>(
mmap(NULL,buffer.length,
PROT_READ|PROT_WRITE,
MAP_SHARED,
m_fd,buffer.m.offset));
if(m_video_buffer!=MAP_FAILED)
{
printf("[video] Using memory mapping method\n");
m_capture_method=VIDEO_MMAP;
goto Ltry_end;
}
else
printf("[video] Error: mmap failed\n");
}
else
printf("[video] Error: could not query mmap buffer\n");
}
}
// no method worked
printf("[video] Error: no useable read method found\n");
return false;
Ltry_end:
// setup cropping: reset if supported
memset(&cropcap,0,sizeof(cropcap));
cropcap.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
if(xioctl(VIDIOC_CROPCAP,&cropcap)==0)
{
crop.type=V4L2_BUF_TYPE_VIDEO_CAPTURE;
crop.c=cropcap.defrect; // reset to default
if(xioctl(VIDIOC_S_CROP,&crop)==-1)
{
printf("[video] Warning: cropping unsupported or cropping reseting failed, assume everything is well setuped\n");
}
}
else
{
printf("[video] Warning: cropping unsupported, assume everything is well setuped\n");
}
// select video input format
{
printf("[video] Supported formats:\n");
// enumerate formats
struct v4l2_fmtdesc fmt;
fmt.type=V4L2_BUF_TYPE_VIDEO_CAPTURE;
fmt.index=0;
while(xioctl(VIDIOC_ENUM_FMT,&fmt)!=-1)
{
printf("[video] * %s\n",fmt.description);
fmt.index++;
xioctl(VIDIOC_ENUM_FMT,&fmt);
}
}
/*
// note: we use a conservative choice: not interleave YUV but it would be better to do the best possible chocie using the enumeration
memset(&fmt,0,sizeof(fmt));
fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
fmt.fmt.pix.width = m_width;
fmt.fmt.pix.height = m_height;
fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_YUYV;
fmt.fmt.pix.field = V4L2_FIELD_NONE;
fmt.fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
if(xioctl(VIDIOC_S_FMT,&fmt)==-1)
{
printf("[video] Error: input format selection failed\n");
return false;
}
*/
printf("[video] Using input format: not interlaced, YUYV(I hope !) video capturing at %ux%u[bpl=%u]\n",
fmt.fmt.pix.width,fmt.fmt.pix.height,fmt.fmt.pix.bytesperline);
printf("[video] Driver set pixel format to %u(colorspace %u) and field to %u\n",
fmt.fmt.pix.pixelformat,fmt.fmt.pix.colorspace,fmt.fmt.pix.field);
m_width=fmt.fmt.pix.width;
m_height=fmt.fmt.pix.height;
m_video_bytes_per_line=fmt.fmt.pix.bytesperline;
m_video_pixel_format=fmt.fmt.pix.pixelformat;
m_video_colorspace=fmt.fmt.pix.colorspace;
return true;
}
bool webcam_t::enqueue_buffer()
{
struct v4l2_buffer buf;
memset(&buf,0,sizeof(buf));
buf.type=V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory=V4L2_MEMORY_MMAP;
buf.index=0;
if(xioctl(VIDIOC_QBUF,&buf)==-1)
{
printf("[video] Error: could not enqueue video buffer\n");
return false;
}
return true;
}
bool webcam_t::dequeue_buffer()
{
struct v4l2_buffer buf;
memset(&buf,0,sizeof(buf));
buf.type=V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory=V4L2_MEMORY_MMAP;
int res;
do
{
usleep(50);
res=xioctl(VIDIOC_DQBUF,&buf);
}
while(res==-1 && errno==EAGAIN);
if(res==-1)
{
printf("[video] Error: buffer dequeueing failed\n");
return false;
}
else
return true;
}
bool webcam_t::start_capturing()
{
switch(m_capture_method)
{
case VIDEO_READ_WRITE:
return true;
case VIDEO_MMAP:
{
if(!enqueue_buffer())
return false;
enum v4l2_buf_type type;
type=V4L2_BUF_TYPE_VIDEO_CAPTURE;
if(xioctl(VIDIOC_STREAMON,&type)==-1)
{
printf("[video] Error: could not start streaming\n");
return false;
}
if(!dequeue_buffer())
return false;
return true;
}
case VIDEO_USERP:
printf("[video] Error: start streaming for user pointer method unimplemented\n");
return false;
default:
printf("[video] Error: no capture used[internal error]{stac}\n");
return false;
}
}
void webcam_t::stop_capturing()
{
switch(m_capture_method)
{
case VIDEO_READ_WRITE:
break;
case VIDEO_MMAP:
case VIDEO_USERP:
{
enum v4l2_buf_type type;
type=V4L2_BUF_TYPE_VIDEO_CAPTURE;
if(xioctl(VIDIOC_STREAMOFF,&type)==-1)
printf("[video] Error: could not stop streaming\n");
}
break;
default:
printf("[video] Error: no capture used[internal error]{stoc}\n");
break;
}
}
bool webcam_t::video_get_integer_control(__u32 cid,int& v)
{
struct v4l2_control control;
memset(&control,0,sizeof(control));
control.id=cid;
if(ioctl(m_fd,VIDIOC_G_CTRL,&control)==-1)
return false;
else
{
v=control.value;
return true;
}
}
bool webcam_t::video_set_boolean_control(__u32 cid,bool b)
{
struct v4l2_control control;
memset (&control,0,sizeof(control));
control.id=cid;
control.value=b;
if(ioctl(m_fd,VIDIOC_S_CTRL,&control)==-1)
return false;
else
return true;
}
bool webcam_t::video_set_integer_control(__u32 cid,int v)
{
struct v4l2_control control;
memset (&control,0,sizeof(control));
control.id=cid;
control.value=v;
if(ioctl(m_fd,VIDIOC_S_CTRL,&control)==-1)
return false;
else
return true;
}
bool webcam_t::video_capture()
{
int brightness,contrast,saturation,hue,gamma;
if(!video_get_integer_control(V4L2_CID_BRIGHTNESS,brightness))
printf("[video] Warning: could not get brighness\n");
if(!video_get_integer_control(V4L2_CID_CONTRAST,contrast))
printf("[video] Warning: could not get contrast\n");
if(!video_get_integer_control(V4L2_CID_SATURATION,saturation))
printf("[video] Warning: could not get saturation\n");
if(!video_get_integer_control(V4L2_CID_HUE,hue))
printf("[video] Warning: could not get hue\n");
if(!video_get_integer_control(V4L2_CID_GAMMA,gamma))
printf("[video] Warning: could not get gamma adjust\n");
printf("[video] (capture) brightness=%d contrast=%d saturation=%d hue=%d gamma=%d\n",brightness,contrast,saturation,hue,gamma);
switch(m_capture_method)
{
case VIDEO_READ_WRITE:
printf("[video] Error: video capturing using read/write method unimplemented\n");
return false;
case VIDEO_USERP:
printf("[video] Error: video capturing using user pointer method unimplemented\n");
return false;
case VIDEO_MMAP:
{
if(!enqueue_buffer())
return false;
return dequeue_buffer();
}
default:
printf("[video] Error: no capture used[internal error]{vc}\n");
return false;
}
}
void webcam_t::deinit()
{
switch(m_capture_method)
{
case VIDEO_READ_WRITE:
case VIDEO_USERP:
delete[] m_video_buffer;
break;
case VIDEO_MMAP:
munmap(m_video_buffer,m_mmap_buffer_length);
break;
default:
printf("[video] Error: no capture used[internal error]{uvd}\n");
}
}
bool webcam_t::process_capture_to_image(image_t& img)
{
assert(img.fmt==image_t::yuv_format);
// mainly expand yuyv to yuv
// also take care of padding
if(m_video_pixel_format==V4L2_PIX_FMT_YUYV)
{
for(size_t y=0;y<m_height;y++)
{
// four bytes -> two pixels
for(size_t x=0;x<m_width;x+=2)
{
// equivalent of 2 bytes per pixel
uint8_t *ptr=m_video_buffer+(m_height-1-y)*m_video_bytes_per_line+x*2;
uint8_t Y1=ptr[0];
uint8_t U=ptr[1];
uint8_t V=ptr[3];
uint8_t Y2=ptr[2];
img.pixel(x,y)[0]=Y1;
img.pixel(x,y)[1]=U;
img.pixel(x,y)[2]=V;
img.pixel(x+1,y)[0]=Y2;
img.pixel(x+1,y)[1]=U;
img.pixel(x+1,y)[2]=V;
}
}
return true;
}
else
{
printf("[video] Error: video pixel format support unimplemented\n");
return false;
}
}
| [
"[email protected]"
] | [
[
[
1,
533
]
]
] |
cd17dc2d53d7e1aa1d390bc73e70677f8a78fae2 | 516b78edbad95d6fb76b6a51c5353eaeb81b56d6 | /engine2/src/util/math/Matrix.cpp | 9891cd616c881ace765c7175e93c1c2e4e187a61 | [] | no_license | BackupTheBerlios/lutaprakct | 73d9fb2898e0a1a019d8ea7870774dd68778793e | fee62fa093fa560e51a26598619b97926ea9cb6b | refs/heads/master | 2021-01-18T14:05:20.313781 | 2008-06-16T21:51:13 | 2008-06-16T21:51:13 | 40,252,766 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,650 | cpp |
#include "Matrix.h"
void identity(Matrix4f& mat){
mat.m[0] = 1.0;
mat.m[1] = 0;
mat.m[2] = 0;
mat.m[3] = 0;
mat.m[4] = 0;
mat.m[5] = 1.0;
mat.m[6] = 0;
mat.m[7] = 0;
mat.m[8] = 0;
mat.m[9] = 0;
mat.m[10] = 1.0;
mat.m[11] = 0;
mat.m[12] = 0;
mat.m[13] = 0;
mat.m[14] = 0;
mat.m[15] = 1.0;
}
void translate(Matrix4f& m, float x, float y, float z){
m.m[12] += x;
m.m[13] += y;
m.m[14] += z;
}
void scale(Matrix4f& m, float x, float y, float z){
m.m[0] *= x; m.m[5] *= y; m.m[10] *= z;
}
#define A(row,col) a.m[(col<<2)+row]
#define B(row,col) b.m[(col<<2)+row]
#define P(row,col) product.m[(col<<2)+row]
void multiply(Matrix4f& product, Matrix4f& a, Matrix4f& b){
for (int i = 0; i < 4; i++) {
float ai0=A(i,0), ai1=A(i,1), ai2=A(i,2), ai3=A(i,3);
P(i,0) = ai0 * B(0,0) + ai1 * B(1,0) + ai2 * B(2,0) + ai3 * B(3,0);
P(i,1) = ai0 * B(0,1) + ai1 * B(1,1) + ai2 * B(2,1) + ai3 * B(3,1);
P(i,2) = ai0 * B(0,2) + ai1 * B(1,2) + ai2 * B(2,2) + ai3 * B(3,2);
P(i,3) = ai0 * B(0,3) + ai1 * B(1,3) + ai2 * B(2,3) + ai3 * B(3,3);
}
}
#undef A
#undef B
#undef P
#define TRANSPOSE4(dst, src) \
{ \
for (int j = 0; j < 4; j++) \
{ \
for (int i = 0; i < 4; i++) \
{ \
dst.m[(j*4)+i] = src.m[(i*4)+j]; \
} \
} \
}
void transpose(Matrix4f& final, Matrix4f& m){
TRANSPOSE4(final, m)
}
| [
"gha"
] | [
[
[
1,
74
]
]
] |
8bb9d876f9574c74d879570318b1764d69a21fa3 | 85b0567a9928ad160159d30d585a9b6870735dc1 | /IFace/MainWindow.cpp | 91d371c875018aa4c6250ebe142b68ecc2df4056 | [] | no_license | bobrnor/IFace | 63d0e0b87dbb8f58a9d343a1304a97dc66dc70d4 | 1e9bb88346df28b6e14aa7d7f72b81334848bdcf | refs/heads/master | 2021-01-22T10:02:34.354097 | 2011-05-20T21:15:04 | 2011-05-20T21:15:04 | 1,436,014 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 36,184 | cpp | #include "MainWindow.h"
#include "ui_MainWindow.h"
#include <QDebug>
#include <QFileDialog>
#include <QStringList>
#include <QAction>
#include <QFile>
#include <QCloseEvent>
#include <QShortcut>
#include <QWidget>
#include <QColor>
#include <QVBoxLayout>
#include <QColorDialog>
#include <QPainter>
#include <QPixmap>
#include <QIcon>
#include <QMessageBox>
#include <QLibraryInfo>
#include <QProcess>
#include <QLocale>
#include <QRegExp>
#include <QTextCodec>
#include "GlobalState.h"
#include "CodeEditorWidget.h"
#include "CodeEditor.h"
#include "CommentsEditor.h"
QString MainWindow::m_qtAssistantEnPath = QLibraryInfo::location(QLibraryInfo::BinariesPath)
+ QDir::separator()
+ QLatin1String("assistant");
QString MainWindow::m_qtAssistantRuPath = QLibraryInfo::location(QLibraryInfo::BinariesPath)
+ QDir::separator()
+ QLatin1String("assistant");
MainWindow::MainWindow(QWidget *parent) : QWidget(parent), ui(new Ui::MainWindow) {
ui->setupUi(this);
m_currentProjectManager = NULL;
m_highlightToolBarAction = NULL;
m_highlightMenuAction = NULL;
m_hoveredAction = NULL;
m_lastHelpAction = NULL;
m_isLastHelpForMenu = false;
m_isInCompile = false;
m_needReopenHelp = false;
m_statusBar = new QStatusBar(this);
ui->topLayout->addWidget(m_statusBar);
m_menuBar = new MenuBar(this);
ui->topLayout->addWidget(m_menuBar);
ui->topLayout->addSpacing(0);
connect(m_menuBar, SIGNAL(hovered(QAction*)), this, SLOT(showStatusBarInfo(QAction*)));
connect(m_menuBar, SIGNAL(triggered(QAction*)), this, SLOT(hideStatusBarInfo()));
connect(m_menuBar, SIGNAL(leaveSignal()), this, SLOT(hideStatusBarInfo()));
m_lastEnHelpSource = m_lastRuHelpSource = "";
m_helpProcess = NULL;
// m_toolBar = new QToolBar(this);
// ui->topLayout->addWidget(m_toolBar);
initStatusBar();
initMenu();
//initToolBar();
initSplitters();
initProjectTree();
initCodeTabs();
initErrorTable();
initShortcuts();
initEventFilters();
showStartUpHelp();
updateColorIcons();
updateEnability();
}
MainWindow::~MainWindow() {
delete ui;
if (m_currentProjectManager != NULL) {
delete m_currentProjectManager;
}
if (m_menuBar != NULL) {
delete m_menuBar;
}
if (m_statusBar != NULL) {
delete m_statusBar;
}
for (int i = m_shortcutList.count() - 1; i >= 0; --i) {
QShortcut *shortcut = m_shortcutList.at(i);
m_shortcutList.removeAt(i);
delete shortcut;
}
}
void MainWindow::showStartUpHelp() {
if (!GlobalState::instance()->enHighFrequenceError().isEmpty()) {
QMessageBox *messageBox = new QMessageBox(tr("Last session hegh frequence error help"),
(GlobalState::instance()->langId()) ? GlobalState::instance()->ruHighFrequenceError() : GlobalState::instance()->enHighFrequenceError(),
QMessageBox::Information,
QMessageBox::Ok,
QMessageBox::NoButton,
QMessageBox::NoButton);
messageBox->exec();
delete messageBox;
}
}
void MainWindow::closeEvent(QCloseEvent *event) {
if (m_currentProjectManager != NULL) {
bool tryCloseResult = m_currentProjectManager->beginCloseProject();
if (tryCloseResult) {
m_currentProjectManager->endCloseProject();
event->accept();
}
else {
event->ignore();
}
}
else {
event->accept();
}
}
void MainWindow::initMenu() {
QMenu *fileMenu = createFileMenu();
QMenu *editMenu = createEditMenu();
QMenu *buildMenu = createBuildMenu();
QMenu *languageMenu = createLanguageMenu();
QMenu *helpMenu = createHelpMenu();
m_menuBar->addMenu(fileMenu);
m_menuBar->addMenu(editMenu);
m_menuBar->addMenu(buildMenu);
m_menuBar->addMenu(languageMenu);
m_menuBar->addMenu(helpMenu);
m_menuBar->setMaximumHeight(100);
}
void MainWindow::initSplitters() {
}
void MainWindow::initProjectTree() {
}
void MainWindow::initToolBar() {
m_toolBar->setIconSize(QSize(16, 16));
m_highlightToolBarAction = m_toolBar->addAction(tr("Highlight"), this, SLOT(highlightSelectedTextSlot()));
m_toolBar->addAction(tr("Change Highlight Color"), this, SLOT(changeTextHighlightColor()));
}
void MainWindow::initCodeTabs() {}
void MainWindow::initErrorTable() {}
QMenu *MainWindow::createFileMenu() {
QTranslator translator;
translator.load("iface_ru.qm", ".");
QMenu *menu = new QMenu(tr("&File"), m_menuBar);
QString translation = translator.translate("MainWindow", "&File");
m_ruEnRuMap["&File"] = translation;
m_ruEnRuMap[translation] = "&File";
QAction *action = menu->addAction(tr("Create project..."), this, SLOT(newProjectSlot()));
translation = translator.translate("MainWindow", "Create project...");
m_ruEnRuMap["Create project..."] = translation;
m_ruEnRuMap[translation] = "Create project...";
m_compiletRelatedActions.append(action);
action = menu->addAction(tr("Open project..."), this, SLOT(openProjectSlot()));
translation = translator.translate("MainWindow", "Open project...");
m_ruEnRuMap["Open project..."] = translation;
m_ruEnRuMap[translation] = "Open project...";
m_compiletRelatedActions.append(action);
menu->addSeparator();
QMenu *addMenu = new QMenu(tr("Add"), menu);
translation = translator.translate("MainWindow", "Add");
m_ruEnRuMap["Add"] = translation;
m_ruEnRuMap[translation] = "Add";
menu->addMenu(addMenu);
action = addMenu->addAction(tr("&New file..."), this, SLOT(newProjectFileSlot()));
translation = translator.translate("MainWindow", "&New file...");
m_ruEnRuMap["&New file..."] = translation;
m_ruEnRuMap[translation] = "&New file...";
action->setShortcut(QKeySequence("Ctrl+N"));
m_compiletRelatedActions.append(action);
m_projectRelatedActions.append(action);
action = addMenu->addAction(tr("Existing file..."), this, SLOT(openProjectFileSlot()));
translation = translator.translate("MainWindow", "Existing file...");
m_ruEnRuMap["Existing file..."] = translation;
m_ruEnRuMap[translation] = "Existing file...";
m_compiletRelatedActions.append(action);
m_projectRelatedActions.append(action);
menu->addSeparator();
action = menu->addAction(tr("&Save"), this, SLOT(saveCurrentFileSlot()));
translation = translator.translate("MainWindow", "&Save");
m_ruEnRuMap["&Save"] = translation;
m_ruEnRuMap[translation] = "&Save";
action->setShortcut(QKeySequence("Ctrl+S"));
m_compiletRelatedActions.append(action);
m_projectRelatedActions.append(action);
action = menu->addAction(tr("Save all"), this, SLOT(saveAllSlot()));
translation = translator.translate("MainWindow", "Save all");
m_ruEnRuMap["Save all"] = translation;
m_ruEnRuMap[translation] = "Save all";
action->setShortcut(QKeySequence("Ctrl+Shift+S"));
m_compiletRelatedActions.append(action);
m_projectRelatedActions.append(action);
menu->addSeparator();
m_lastProjectsMenu = menu->addMenu(tr("Last Projects"));
translation = translator.translate("MainWindow", "Last Projects");
m_ruEnRuMap["Last Projects"] = translation;
m_ruEnRuMap[translation] = "Last Projects";
updateLastProjectsMenu();
menu->addSeparator();
menu->addAction(tr("Exit"), this, SLOT(close()));
translation = translator.translate("MainWindow", "Exit");
m_ruEnRuMap["Exit"] = translation;
m_ruEnRuMap[translation] = "Exit";
return menu;
}
QMenu *MainWindow::createEditMenu() {
QTranslator translator;
translator.load("iface_ru.qm", ".");
QMenu *editMenu = new QMenu(tr("&Edit"), m_menuBar);
QString translation = translator.translate("MainWindow", "&Edit");
m_ruEnRuMap["&Edit"] = translation;
m_ruEnRuMap[translation] = "&Edit";
QAction *action = editMenu->addAction(tr("Cut"), this, SLOT(cut()));
translation = translator.translate("MainWindow", "Cut");
m_ruEnRuMap["Cut"] = translation;
m_ruEnRuMap[translation] = "Cut";
m_codeRelatedActions.append(action);
m_commentsRelatedActions.append(action);
m_projectRelatedActions.append(action);
action = editMenu->addAction(tr("Copy"), this, SLOT(copy()));
translation = translator.translate("MainWindow", "Copy");
m_ruEnRuMap["Copy"] = translation;
m_ruEnRuMap[translation] = "Copy";
m_codeRelatedActions.append(action);
m_commentsRelatedActions.append(action);
m_projectRelatedActions.append(action);
action = editMenu->addAction(tr("Paste"), this, SLOT(paste()));
translation = translator.translate("MainWindow", "Paste");
m_ruEnRuMap["Paste"] = translation;
m_ruEnRuMap[translation] = "Paste";
m_codeRelatedActions.append(action);
m_commentsRelatedActions.append(action);
m_projectRelatedActions.append(action);
editMenu->addSeparator();
m_highlightMenuAction = editMenu->addAction(tr("Highlight"), this, SLOT(highlightSelectedTextSlot()));
translation = translator.translate("MainWindow", "Highlight");
m_ruEnRuMap["Highlight"] = translation;
m_ruEnRuMap[translation] = "Highlight";
m_highlightMenuAction->setShortcut(QKeySequence("Ctrl+H"));
m_codeRelatedActions.append(m_highlightMenuAction);
m_projectRelatedActions.append(m_highlightMenuAction);
action = editMenu->addAction(tr("Change Highlight Color"), this, SLOT(changeTextHighlightColor()));
translation = translator.translate("MainWindow", "Change Highlight Color");
m_ruEnRuMap["Change Highlight Color"] = translation;
m_ruEnRuMap[translation] = "Change Highlight Color";
m_projectRelatedActions.append(action);
return editMenu;
}
QMenu *MainWindow::createBuildMenu() {
QTranslator translator;
translator.load("iface_ru.qm", ".");
QMenu *buildMenu = new QMenu(tr("&Build"), m_menuBar);
QString translation = translator.translate("MainWindow", "&Build");
m_ruEnRuMap["&Build"] = translation;
m_ruEnRuMap[translation] = "&Build";
QAction *action = buildMenu->addAction(tr("Compile"), this, SLOT(compile()));
translation = translator.translate("MainWindow", "Compile");
m_ruEnRuMap["Compile"] = translation;
m_ruEnRuMap[translation] = "Compile";
action->setShortcut(QKeySequence("F5"));
m_projectRelatedActions.append(action);
m_compiletRelatedActions.append(action);
return buildMenu;
}
QMenu *MainWindow::createLanguageMenu() {
QTranslator translator;
translator.load("iface_ru.qm", ".");
QMenu *langMenu = new QMenu(tr("&Language"), m_menuBar);
QString translation = translator.translate("MainWindow", "&Language");
m_ruEnRuMap["&Language"] = translation;
m_ruEnRuMap[translation] = "&Language";
langMenu->addAction(tr("Russian"), this, SLOT(ruLang()));
translation = translator.translate("MainWindow", "Russian");
m_ruEnRuMap["Russian"] = translation;
m_ruEnRuMap[translation] = "Russian";
langMenu->addAction(tr("English"), this, SLOT(enLang()));
translation = translator.translate("MainWindow", "English");
m_ruEnRuMap["English"] = translation;
m_ruEnRuMap[translation] = "English";
return langMenu;
}
QMenu *MainWindow::createHelpMenu() {
QTranslator translator;
translator.load("iface_ru.qm", ".");
QMenu *helpMenu = new QMenu(tr("&Help"), m_menuBar);
QString translation = translator.translate("MainWindow", "&Help");
m_ruEnRuMap["&Help"] = translation;
m_ruEnRuMap[translation] = "&Help";
helpMenu->addAction(tr("Help"), this, SLOT(showHelp()));
translation = translator.translate("MainWindow", "Help");
m_ruEnRuMap["Help"] = translation;
m_ruEnRuMap[translation] = "Help";
return helpMenu;
}
void MainWindow::updateLastProjectsMenu() {
m_lastProjectsMenu->clear();
foreach (QString path, GlobalState::instance()->lastProjects()) {
QString elidedString = fontMetrics().elidedText(path, Qt::ElideMiddle, 200);
QAction *action = m_lastProjectsMenu->addAction(elidedString, this, SLOT(openProjectFromLastSlot()));
action->setToolTip(path);
action->setStatusTip(path);
}
}
void MainWindow::initStatusBar() {
m_statusBar->setSizeGripEnabled(false);
}
void MainWindow::initShortcuts() {
QShortcut *shortcut = new QShortcut(this);
shortcut->setKey(QKeySequence("Ctrl+1"));
shortcut->setEnabled(true);
connect(shortcut, SIGNAL(activated()), this, SLOT(shortcutActivated()));
m_shortcutList.append(shortcut);
shortcut = new QShortcut(this);
shortcut->setKey(QKeySequence("Ctrl+2"));
shortcut->setEnabled(true);
connect(shortcut, SIGNAL(activated()), this, SLOT(shortcutActivated()));
m_shortcutList.append(shortcut);
shortcut = new QShortcut(this);
shortcut->setKey(QKeySequence("Ctrl+3"));
shortcut->setEnabled(true);
connect(shortcut, SIGNAL(activated()), this, SLOT(shortcutActivated()));
m_shortcutList.append(shortcut);
shortcut = new QShortcut(this);
shortcut->setKey(QKeySequence("Ctrl+4"));
shortcut->setEnabled(true);
connect(shortcut, SIGNAL(activated()), this, SLOT(shortcutActivated()));
m_shortcutList.append(shortcut);
shortcut = new QShortcut(this);
shortcut->setKey(QKeySequence("Ctrl+5"));
shortcut->setEnabled(true);
connect(shortcut, SIGNAL(activated()), this, SLOT(shortcutActivated()));
m_shortcutList.append(shortcut);
shortcut = new QShortcut(this);
shortcut->setKey(QKeySequence("F1"));
shortcut->setEnabled(true);
shortcut->setContext(Qt::ApplicationShortcut);
connect(shortcut, SIGNAL(activated()), this, SLOT(showContextHelp()));
m_shortcutList.append(shortcut);
}
void MainWindow::setupProjectEnvironment(ProjectManager *projectManager) {
if (projectManager != NULL) {
projectManager->assignTabWidget(ui->codeTabs);
projectManager->assignProjectTreeWidget(ui->projectTree);
projectManager->assignErrorWidget(ui->errorTable);
ProjectTreeHelper *treeHelper = projectManager->projectTreeHelper();
connect(treeHelper, SIGNAL(addNewFileToProjectSignal()),
this, SLOT(newProjectFileSlot()));
connect(treeHelper, SIGNAL(addExistingFileToProjectSignal()),
this, SLOT(openProjectFileSlot()));
connect(treeHelper, SIGNAL(removeFileFromProjectSignal(ProjectFile *)),
this, SLOT(removeProjectFileSlot(ProjectFile *)));
connect(projectManager, SIGNAL(compileEndSignal()), this, SLOT(compileEnd()));
}
updateEnability();
}
//-------------SLOTS------------------
void MainWindow::newProjectSlot() {
QFileDialog dialog(this);
dialog.setFileMode(QFileDialog::AnyFile);
dialog.setViewMode(QFileDialog::Detail);
dialog.setAcceptMode(QFileDialog::AcceptSave);
dialog.setConfirmOverwrite(true);
dialog.setWindowTitle(tr("Create project..."));
dialog.setOption(QFileDialog::DontUseNativeDialog, true);
QString fileName;
if (dialog.exec()) {
qDebug() << dialog.selectedFiles();
fileName = dialog.selectedFiles().at(0);
if (m_currentProjectManager != NULL) {
bool tryCloseResult = m_currentProjectManager->beginCloseProject();
if (tryCloseResult) {
m_currentProjectManager->endCloseProject();
delete m_currentProjectManager;
}
else {
return;
}
}
if (QFile::exists(fileName)) {
bool ok = QFile::remove(fileName);
Q_ASSERT(ok);
}
m_currentProjectManager = new ProjectManager(fileName);
setupProjectEnvironment(m_currentProjectManager);
// TODO: update all
updateLastProjectsMenu();
}
}
void MainWindow::newProjectFileSlot() {
Q_ASSERT(m_currentProjectManager != NULL);
QFileDialog dialog(this);
dialog.setFileMode(QFileDialog::AnyFile);
dialog.setViewMode(QFileDialog::Detail);
dialog.setAcceptMode(QFileDialog::AcceptSave);
dialog.setConfirmOverwrite(true);
dialog.setWindowTitle(tr("New file..."));
dialog.setOption(QFileDialog::DontUseNativeDialog, true);
QString fileName;
if (dialog.exec()) {
qDebug() << dialog.selectedFiles();
fileName = dialog.selectedFiles().at(0);
if (QFile::exists(fileName)) {
bool ok = QFile::remove(fileName);
Q_ASSERT(ok);
}
ProjectFile *projectFile = new ProjectFile(m_currentProjectManager->project(), fileName);
m_currentProjectManager->addProjectFile(projectFile);
// TODO: update all
}
}
void MainWindow::openProjectSlot() {
QFileDialog dialog(this);
dialog.setFileMode(QFileDialog::AnyFile);
dialog.setViewMode(QFileDialog::Detail);
dialog.setAcceptMode(QFileDialog::AcceptOpen);
dialog.setConfirmOverwrite(true);
dialog.setWindowTitle(tr("Open project..."));
dialog.setOption(QFileDialog::DontUseNativeDialog, true);
QString fileName;
if (dialog.exec()) {
qDebug() << dialog.selectedFiles();
fileName = dialog.selectedFiles().at(0);
if (m_currentProjectManager != NULL) {
bool tryCloseResult = m_currentProjectManager->beginCloseProject();
if (tryCloseResult) {
m_currentProjectManager->endCloseProject();
delete m_currentProjectManager;
}
else {
return;
}
}
m_currentProjectManager = new ProjectManager(fileName);
setupProjectEnvironment(m_currentProjectManager);
// TODO: update all
updateLastProjectsMenu();
}
}
void MainWindow::openProjectFromLastSlot() {
if (sender() != NULL) {
QAction *action = static_cast<QAction *>(sender());
QString path = action->toolTip();
if (!path.isEmpty()) {
if (m_currentProjectManager != NULL) {
bool tryCloseResult = m_currentProjectManager->beginCloseProject();
if (tryCloseResult) {
m_currentProjectManager->endCloseProject();
delete m_currentProjectManager;
}
else {
return;
}
}
if (QFile::exists(path)) {
m_currentProjectManager = new ProjectManager(path);
setupProjectEnvironment(m_currentProjectManager);
// TODO: update all
updateLastProjectsMenu();
}
else {
QMessageBox *messageBox = new QMessageBox(tr("File not found"),
tr("Selected project not found."),
QMessageBox::Critical,
QMessageBox::Ok,
QMessageBox::NoButton,
QMessageBox::NoButton);
messageBox->exec();
delete messageBox;
}
}
}
}
void MainWindow::openProjectFileSlot() {
Q_ASSERT(m_currentProjectManager != NULL);
QFileDialog dialog(this);
dialog.setFileMode(QFileDialog::AnyFile);
dialog.setViewMode(QFileDialog::Detail);
dialog.setAcceptMode(QFileDialog::AcceptOpen);
dialog.setConfirmOverwrite(true);
dialog.setWindowTitle(tr("Existing file..."));
dialog.setOption(QFileDialog::DontUseNativeDialog, true);
QString fileName;
if (dialog.exec()) {
qDebug() << dialog.selectedFiles();
fileName = dialog.selectedFiles().at(0);
ProjectFile *projectFile = new ProjectFile(m_currentProjectManager->project(), fileName);
m_currentProjectManager->addProjectFile(projectFile);
// TODO: update all
}
}
void MainWindow::removeProjectFileSlot(ProjectFile *file) {
if (m_currentProjectManager != NULL && file != NULL) {
m_currentProjectManager->removeProjectFile(file);
}
}
void MainWindow::saveCurrentFileSlot() {
if (m_currentProjectManager != NULL) {
m_currentProjectManager->saveCurrentlyOpenProjectFile();
}
}
void MainWindow::saveAllSlot() {
if (m_currentProjectManager != NULL) {
m_currentProjectManager->saveAll();
}
}
void MainWindow::compile() {
if (m_currentProjectManager != NULL) {
m_currentProjectManager->compile();
m_isInCompile = true;
m_statusBar->showMessage(tr("Compilig..."));
updateEnability();
}
}
void MainWindow::compileEnd() {
QMessageBox *messageBox = new QMessageBox(tr("Compiling"),
tr("Compiling is done."),
QMessageBox::Information,
QMessageBox::Ok,
QMessageBox::NoButton,
QMessageBox::NoButton);
messageBox->exec();
delete messageBox;
m_isInCompile = false;
m_statusBar->showMessage("");
updateEnability();
}
void MainWindow::setFocusToMenu() {
if (m_menuBar != NULL) {
m_menuBar->setFocus(Qt::ShortcutFocusReason);
}
}
void MainWindow::shortcutActivated() {
if (sender() != NULL) {
QShortcut *shortcut = static_cast<QShortcut *>(sender());
QString key = shortcut->key();
if (key == "Ctrl+1") {
//setFocusToMenu();
}
else if (key == "Ctrl+2") {
if (m_currentProjectManager != NULL) {
m_currentProjectManager->setFocusToProjectTree();
}
}
else if (key == "Ctrl+3") {
if (m_currentProjectManager != NULL) {
m_currentProjectManager->setFocusToCode();
}
}
else if (key == "Ctrl+4") {
if (m_currentProjectManager != NULL) {
m_currentProjectManager->setFocusToComments();
}
}
else if (key == "Ctrl+5") {
if (m_currentProjectManager != NULL) {
m_currentProjectManager->setFocusToErros();
}
}
}
}
void MainWindow::initEventFilters() {
m_menuBar->installEventFilter(this);
ui->errorTable->installEventFilter(this);
ui->codeAndErrorsWidget->installEventFilter(this);
ui->projectTree->installEventFilter(this);
GlobalState::instance()->setEventFilter(this);
}
bool MainWindow::eventFilter(QObject *object, QEvent *event) {
static int i = 0;
if (event->type() == QEvent::FocusIn) {
if (object->isWidgetType()) {
QPalette p(palette());
QWidget *widget = NULL;
if (object->inherits("QMenuBar") || object->inherits("QMenu") || object->inherits("QAction")) {
widget = ui->line;
p.setColor(QPalette::Dark, Qt::red);
p.setColor(QPalette::Light, Qt::red);
p.setColor(QPalette::Mid, Qt::red);
}
else {
m_isInCode = object->inherits("CodeEditor");
m_isInComments = object->inherits("CommentsEditor");
updateEnability();
if (!m_isInCode && !m_isInComments) {
widget = static_cast<QWidget *>(object);
p.setColor(QPalette::Window, Qt::red);
}
}
if (widget != NULL) {
widget->setPalette(p);
}
}
}
else if (event->type() == QEvent::FocusOut) {
if (object->isWidgetType()) {
QPalette p(palette());
QWidget *widget = NULL;
if (object->inherits("QMenuBar") || object->inherits("QMenu") || object->inherits("QAction")) {
widget = ui->line;
}
else {
widget = static_cast<QWidget *>(object);
}
widget->setPalette(p);
}
}
else if (event->type() == QEvent::LanguageChange) {
qDebug() << __FUNCSIG__;
i++;
if (i == 4) {
ui->retranslateUi(this);
retranslate();
i = 0;
}
}
return QWidget::eventFilter(object, event);
}
void MainWindow::changeTextHighlightColor() {
QColor color = QColorDialog::getColor(GlobalState::instance()->textHighlightColor(), this);
GlobalState::instance()->setTextHighlightColor(color);
updateColorIcons();
}
void MainWindow::highlightSelectedTextSlot() {
if (m_currentProjectManager != NULL && m_currentProjectManager->tabsHelper() != NULL) {
TabsHelper *tabsHelper = m_currentProjectManager->tabsHelper();
if (tabsHelper->tabWidget() != NULL && tabsHelper->tabWidget()->currentWidget() != NULL) {
CodeEditorWidget *widget = static_cast<CodeEditorWidget *>(tabsHelper->tabWidget()->currentWidget());
CodeEditor *editor = widget->codeEditor();
editor->highlightCurrentSelection(GlobalState::instance()->textHighlightColor());
m_currentProjectManager->setFocusToCode();
}
}
}
QIcon MainWindow::makeIconForColor(const QColor &color) {
QPixmap pixmap(32, 32);
QPainter painter(&pixmap);
painter.setPen(color);
painter.drawRect(2, 2, 28, 28);
painter.fillRect(2, 2, 28, 28, color);
painter.end();
QIcon icon(pixmap);
return icon;
}
void MainWindow::updateColorIcons() {
QIcon icon = makeIconForColor(GlobalState::instance()->textHighlightColor());
if (m_highlightToolBarAction != NULL) {
m_highlightToolBarAction->setIcon(icon);
}
if (m_highlightMenuAction != NULL) {
m_highlightMenuAction->setIcon(icon);
}
}
void MainWindow::showStatusBarInfo(QAction *action) {
QString statusTipText = action->statusTip();
if (statusTipText.isEmpty()) {
statusTipText = action->text();
}
m_statusBar->showMessage(statusTipText.replace("&", ""));
m_hoveredAction = action;
}
void MainWindow::hideStatusBarInfo() {
m_statusBar->showMessage("");
m_hoveredAction = NULL;
}
void MainWindow::updateEnability() {
bool projectOpen = m_currentProjectManager != NULL;
foreach (QAction *action, m_projectRelatedActions) {
action->setEnabled(projectOpen);
}
if (projectOpen) {
foreach (QAction *action, m_compiletRelatedActions) {
action->setEnabled(!m_isInCompile);
}
foreach (QAction *action, m_codeRelatedActions) {
action->setEnabled(m_isInCode);
}
if (m_isInComments) {
foreach (QAction *action, m_commentsRelatedActions) {
action->setEnabled(m_isInComments);
}
}
}
}
void MainWindow::paste() {
if (m_currentProjectManager != NULL && m_currentProjectManager->tabsHelper() != NULL) {
TabsHelper *tabsHelper = m_currentProjectManager->tabsHelper();
if (tabsHelper->tabWidget() != NULL && tabsHelper->tabWidget()->currentWidget() != NULL) {
CodeEditorWidget *widget = static_cast<CodeEditorWidget *>(tabsHelper->tabWidget()->currentWidget());
if (m_isInCode) {
CodeEditor *editor = widget->codeEditor();
editor->paste();
m_currentProjectManager->setFocusToCode();
}
else if (m_isInComments) {
CommentsEditor *editor = widget->commentsArea();
editor->paste();
m_currentProjectManager->setFocusToComments();
}
}
}
}
void MainWindow::cut() {
if (m_currentProjectManager != NULL && m_currentProjectManager->tabsHelper() != NULL) {
TabsHelper *tabsHelper = m_currentProjectManager->tabsHelper();
if (tabsHelper->tabWidget() != NULL && tabsHelper->tabWidget()->currentWidget() != NULL) {
CodeEditorWidget *widget = static_cast<CodeEditorWidget *>(tabsHelper->tabWidget()->currentWidget());
if (m_isInCode) {
CodeEditor *editor = widget->codeEditor();
editor->cut();
m_currentProjectManager->setFocusToCode();
}
else if (m_isInComments) {
CommentsEditor *editor = widget->commentsArea();
editor->cut();
m_currentProjectManager->setFocusToComments();
}
}
}
}
void MainWindow::copy() {
if (m_currentProjectManager != NULL && m_currentProjectManager->tabsHelper() != NULL) {
TabsHelper *tabsHelper = m_currentProjectManager->tabsHelper();
if (tabsHelper->tabWidget() != NULL && tabsHelper->tabWidget()->currentWidget() != NULL) {
CodeEditorWidget *widget = static_cast<CodeEditorWidget *>(tabsHelper->tabWidget()->currentWidget());
if (m_isInCode) {
CodeEditor *editor = widget->codeEditor();
editor->copy();
m_currentProjectManager->setFocusToCode();
}
else if (m_isInComments) {
CommentsEditor *editor = widget->commentsArea();
editor->copy();
m_currentProjectManager->setFocusToComments();
}
}
}
}
void MainWindow::enLang() {
GlobalState::instance()->translator()->load("iface_en.qm", ".");
GlobalState::instance()->setLangId(0);
qApp->installTranslator(GlobalState::instance()->translator());
qApp->removeTranslator(GlobalState::instance()->qtTranslator());
//ui->retranslateUi(this);
}
void MainWindow::ruLang() {
GlobalState::instance()->translator()->load("iface_ru.qm", ".");
GlobalState::instance()->setLangId(1);
qApp->installTranslator(GlobalState::instance()->qtTranslator());
qApp->installTranslator(GlobalState::instance()->translator());
//ui->retranslateUi(this);
}
void MainWindow::retranslate() {
qDebug() << __FUNCSIG__;
m_menuBar->clear();
initMenu();
updateColorIcons();
updateEnability();
if (m_currentProjectManager != NULL) {
m_currentProjectManager->retranslate();
}
if (m_helpProcess != NULL && m_helpProcess->state() != QProcess::NotRunning) {
m_needReopenHelp = true;
reopenHelp();
}
}
void MainWindow::showRuSource(QString source) {
if (m_helpProcess == NULL || m_helpProcess->state() == QProcess::NotRunning || m_needReopenHelp) {
if (m_helpProcess != NULL) {
delete m_helpProcess;
}
m_helpProcess = new QProcess();
QString app = (GlobalState::instance()->langId()) ? m_qtAssistantRuPath : m_qtAssistantEnPath;
QLatin1String qhc("C:/Documents and Settings/Administrator/gitProjs/IFace/help/help.qhc");
QStringList args;
args << QLatin1String("-collectionFile")
<< qhc
<< QLatin1String("-enableRemoteControl");
m_helpProcess->start(app, args);
if (!m_helpProcess->waitForStarted()) {
QMessageBox::critical(0, QObject::tr("Simple Text Viewer"),
QObject::tr("Unable to launch Qt Assistant (%1)").arg(app));
}
m_needReopenHelp = false;
}
//m_lastHelpSource = source;
QString helpPath = "qthelp://mycompany.com.iface.1_0/doc/ru/";
QByteArray ba;
ba.append("setCurrentFilter iface_ru; ");
ba.append("setSource " + helpPath + source + "\n");
m_helpProcess->write(ba);
}
void MainWindow::showEnSource(QString source) {
if (m_helpProcess == NULL || m_helpProcess->state() == QProcess::NotRunning || m_needReopenHelp) {
if (m_helpProcess != NULL) {
delete m_helpProcess;
}
m_helpProcess = new QProcess();
QString app = (GlobalState::instance()->langId()) ? m_qtAssistantRuPath : m_qtAssistantEnPath;
QLatin1String qhc("C:/Documents and Settings/Administrator/gitProjs/IFace/help/help.qhc");
QStringList args;
args << QLatin1String("-collectionFile")
<< qhc
<< QLatin1String("-enableRemoteControl");
m_helpProcess->start(app, args);
if (!m_helpProcess->waitForStarted()) {
QMessageBox::critical(0, QObject::tr("Simple Text Viewer"),
QObject::tr("Unable to launch Qt Assistant (%1)").arg(app));
}
m_needReopenHelp = false;
}
//m_lastHelpSource = source;
QString helpPath = "qthelp://mycompany.com.iface.1_0/doc/en/";
QByteArray ba;
ba.append("setCurrentFilter iface_en; ");
ba.append("setSource " + helpPath + source + "\n");
m_helpProcess->write(ba);
}
void MainWindow::reopenHelp() {
if (GlobalState::instance()->langId()) {
showRuSource(m_lastRuHelpSource);
}
else {
showEnSource(m_lastEnHelpSource);
}
}
void MainWindow::showHelp() {
m_lastEnHelpSource = m_lastRuHelpSource = "keywords.html";
if (GlobalState::instance()->langId()) {
showRuSource("keywords.html");
}
else {
showEnSource("keywords.html");
}
}
void MainWindow::showContextHelp() {
qDebug() << __FUNCSIG__;
if (this->focusWidget() != NULL) {
QWidget *widgetInFocus = focusWidget();
QWidget *widgetUnderCursor = qApp->widgetAt(QCursor::pos());
if (QString(widgetUnderCursor->metaObject()->className()).trimmed() == "QWidget") {
widgetUnderCursor = widgetUnderCursor->parentWidget();
}
if (widgetInFocus != NULL) {
qDebug() << "Widget in focus: " << widgetInFocus->metaObject()->className();
}
if (widgetUnderCursor != NULL) {
qDebug() << "Widget under cursor: " << widgetUnderCursor->metaObject()->className();
}
if ((widgetUnderCursor->inherits("MenuBar") || widgetUnderCursor->inherits("QMenu"))
&& m_hoveredAction != NULL) {
m_isLastHelpForMenu = true;
m_lastHelpAction = m_hoveredAction;
loadMenuHelp();
}
else if (widgetInFocus->inherits("QTableView")) {
m_isLastHelpForMenu = false;
loadErrorHelp();
}
else if (widgetInFocus->inherits("CodeEditor")) {
m_isLastHelpForMenu = false;
loadKeywordHelp();
}
else if (widgetInFocus->inherits("CommentsEditor") || widgetUnderCursor->inherits("CommentsEditor")) {
m_isLastHelpForMenu = false;
loadCommentsHelp();
}
else if (widgetUnderCursor->inherits("LeftArea")) {
m_isLastHelpForMenu = false;
loadBreakpointsHelp();
}
else if (widgetUnderCursor->inherits("CodeEditor")) {
m_isLastHelpForMenu = false;
loadEditorHelp();
}
}
}
void MainWindow::loadMenuHelp() {
static QRegExp rx1("(\\W|\\d)");
QString ru;
QString en;
if (GlobalState::instance()->langId()) {
ru = m_hoveredAction->text();
en = m_ruEnRuMap.value(ru, "");
ru.replace(rx1, "");
ru = trasliterate(ru);
en.replace(rx1, "");
en = en.toLower();
}
else {
en = m_hoveredAction->text();
ru = m_ruEnRuMap.value(en, "");
ru.replace(rx1, "");
ru = trasliterate(ru);
en.replace(rx1, "");
en = en.toLower();
}
m_lastEnHelpSource = en + ".html";
m_lastRuHelpSource = ru + ".html";
if (GlobalState::instance()->langId()) {
showRuSource(m_lastRuHelpSource);
}
else {
showEnSource(m_lastEnHelpSource);
}
}
void MainWindow::loadKeywordHelp() {
QWidget *widget = m_currentProjectManager->tabsHelper()->tabWidget()->currentWidget();
if (widget != NULL) {
CodeEditorWidget *codeEditorWidget = static_cast<CodeEditorWidget *>(widget);
CodeEditor *codeEditor = codeEditorWidget->codeEditor();
QString word = codeEditor->wordUnderCursor();
qDebug() << "Word under cursor: " << word;
if (!word.isEmpty()) {
m_lastEnHelpSource = m_lastRuHelpSource = word + ".html";
if (GlobalState::instance()->langId()) {
showRuSource(m_lastRuHelpSource);
}
else {
showEnSource(m_lastEnHelpSource);
}
}
}
}
void MainWindow::loadEditorHelp() {
m_lastEnHelpSource = m_lastRuHelpSource = "editor.html";
if (GlobalState::instance()->langId()) {
showRuSource(m_lastRuHelpSource);
}
else {
showEnSource(m_lastEnHelpSource);
}
}
void MainWindow::loadBreakpointsHelp() {
m_lastEnHelpSource = m_lastRuHelpSource = "breakpoints.html";
if (GlobalState::instance()->langId()) {
showRuSource(m_lastRuHelpSource);
}
else {
showEnSource(m_lastEnHelpSource);
}
}
void MainWindow::loadCommentsHelp() {
m_lastEnHelpSource = m_lastRuHelpSource = "comments.html";
if (GlobalState::instance()->langId()) {
showRuSource(m_lastRuHelpSource);
}
else {
showEnSource(m_lastEnHelpSource);
}
}
void MainWindow::loadErrorHelp() {
static QRegExp rx1("(\\W|\\d)");
static QRegExp rx2("(\\[.*\\]$)");
static QRegExp rx3("(^[^:]*: )");
if (m_currentProjectManager != NULL && m_currentProjectManager->errorTableHelper() != NULL) {
ErrorTableHelper *errorHelper = m_currentProjectManager->errorTableHelper();
CompileError enError = errorHelper->currentEnError();
QString source = enError.errorPattern();
source.replace("<", "");
source.replace(">", "");
source.replace(rx2, "");
source.replace(rx3, "");
source.replace(rx1, "");
source = trasliterate(source);
source = source.toLower() + ".html";
m_lastEnHelpSource = source;
CompileError ruError = errorHelper->currentRuError();
source = ruError.errorPattern();
source.replace("<", "");
source.replace(">", "");
source.replace(rx2, "");
source.replace(rx3, "");
source.replace(rx1, "");
source = trasliterate(source);
source = source.toLower() + ".html";
m_lastRuHelpSource = source;
if (GlobalState::instance()->langId()) {
showRuSource(m_lastRuHelpSource);
}
else {
showEnSource(m_lastEnHelpSource);
}
}
}
QString MainWindow::trasliterate(QString rusText) {
QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
QHash<QString, QString> dict;
QString eng;
eng = "abcdefghijklmnopqrstuvwxyz1234567890";
dict["а"] = "a";
dict["б"] = "b";
dict["в"] = "v";
dict["г"] = "g";
dict["д"] = "d";
dict["е"] = "e";
dict["ё"] = "io";
dict["ж"] = "j";
dict["з"] = "z";
dict["и"] = "i";
dict["й"] = "j";
dict["к"] = "k";
dict["л"] = "l";
dict["м"] = "m";
dict["н"] = "n";
dict["о"] = "o";
dict["п"] = "p";
dict["р"] = "r";
dict["с"] = "s";
dict["т"] = "t";
dict["у"] = "u";
dict["ф"] = "f";
dict["х"] = "h";
dict["ц"] = "c";
dict["ч"] = "ch";
dict["ш"] = "sch";
dict["щ"] = "sch";
dict["ы"] = "i";
dict["э"] = "e";
dict["ю"] = "yu";
dict["я"] = "ja";
QString res;
foreach (QChar ch, rusText.toLower())
res += dict.contains(ch) ? dict[ch] : eng.contains(ch) ? ch : QString("");
setlocale(LC_ALL, "rus");
QTextCodec::setCodecForCStrings(QTextCodec::codecForName("cp1251"));
QTextCodec::setCodecForLocale(QTextCodec::codecForName("cp1251"));
return res;
} | [
"[email protected]"
] | [
[
[
1,
1286
]
]
] |
bbfde0c67ec58de1d8aca6488f35eb543d336797 | 463c3b62132d215e245a097a921859ecb498f723 | /lib/dlib/memory_manager/memory_manager_kernel_1.h | 91db8286dbdc46c6a0e04c1b099f88c796a3b68e | [
"LicenseRef-scancode-unknown-license-reference",
"BSL-1.0"
] | permissive | athulan/cppagent | 58f078cee55b68c08297acdf04a5424c2308cfdc | 9027ec4e32647e10c38276e12bcfed526a7e27dd | refs/heads/master | 2021-01-18T23:34:34.691846 | 2009-05-05T00:19:54 | 2009-05-05T00:19:54 | 197,038 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 8,047 | h | // Copyright (C) 2004 Davis E. King ([email protected])
// License: Boost Software License See LICENSE.txt for the full license.
#ifndef DLIB_MEMORY_MANAGER_KERNEl_1_
#define DLIB_MEMORY_MANAGER_KERNEl_1_
#include "../algs.h"
#include "memory_manager_kernel_abstract.h"
#include "../assert.h"
#include <new>
namespace dlib
{
template <
typename T,
unsigned long max_pool_size
>
class memory_manager_kernel_1
{
/*!
INITIAL VALUE
allocations == 0
next == 0
pool_size == 0
REQUIREMENTS ON max_pool_size
max_pool_size is the maximum number of nodes we will keep in our linked list at once.
So you can put any value in for this argument.
CONVENTION
This memory manager implementation allocates T objects one at a time when there are
allocation requests. Then when there is a deallocate request the returning T object
is place into a list of free blocks if that list has less than max_pool_size
blocks in it. subsequent allocation requests will be serviced by drawing from the
free list whenever it isn't empty.
allocations == get_number_of_allocations()
- if (next != 0) then
- next == the next pointer to return from allocate()
and next == pointer to the first node in a linked list. each node
is one item in the memory pool.
- the last node in the linked list has next set to 0
- pool_size == the number of nodes in the linked list
- pool_size <= max_pool_size
- else
- we need to call new to get the next pointer to return from allocate()
!*/
union node
{
node* next;
char item[sizeof(T)];
};
public:
typedef T type;
template <typename U>
struct rebind {
typedef memory_manager_kernel_1<U,max_pool_size> other;
};
memory_manager_kernel_1(
) :
allocations(0),
next(0),
pool_size(0)
{
}
virtual ~memory_manager_kernel_1(
)
{
while (next != 0)
{
node* temp = next;
next = next->next;
::operator delete ( reinterpret_cast<void*>(temp));
}
}
unsigned long get_number_of_allocations (
) const { return allocations; }
T* allocate_array (
unsigned long size
)
{
T* temp = new T[size];
++allocations;
return temp;
}
void deallocate_array (
T* item
)
{
--allocations;
delete [] item;
}
T* allocate (
)
{
T* temp;
if (next != 0)
{
temp = reinterpret_cast<T*>(next);
node* n = next->next;
try
{
// construct this new T object with placement new.
new (reinterpret_cast<void*>(temp))T();
}
catch (...)
{
next->next = n;
throw;
}
next = n;
--pool_size;
}
else
{
temp = reinterpret_cast<T*>(::operator new(sizeof(node)));
try
{
// construct this new T object with placement new.
new (reinterpret_cast<void*>(temp))T();
}
catch (...)
{
// construction of the new object threw so delete the block of memory
::operator delete ( reinterpret_cast<void*>(temp));
throw;
}
}
++allocations;
return temp;
}
void deallocate (
T* item
)
{
--allocations;
item->~T();
if (pool_size >= max_pool_size)
{
::operator delete ( reinterpret_cast<void*>(item));
return;
}
// add this memory chunk into our linked list.
node* temp = reinterpret_cast<node*>(item);
temp->next = next;
next = temp;
++pool_size;
}
void swap (
memory_manager_kernel_1& item
)
{
exchange(allocations,item.allocations);
exchange(next,item.next);
exchange(pool_size,item.pool_size);
}
private:
// data members
unsigned long allocations;
node* next;
unsigned long pool_size;
// restricted functions
memory_manager_kernel_1(memory_manager_kernel_1&); // copy constructor
memory_manager_kernel_1& operator=(memory_manager_kernel_1&); // assignment operator
};
// ----------------------------------------------------------------------------------------
template <
typename T
>
class memory_manager_kernel_1<T,0>
{
/*!
INITIAL VALUE
allocations == 0
CONVENTION
This memory manager just calls new and delete directly so it doesn't
really do anything.
allocations == get_number_of_allocations()
!*/
public:
typedef T type;
template <typename U>
struct rebind {
typedef memory_manager_kernel_1<U,0> other;
};
memory_manager_kernel_1(
) :
allocations(0)
{
}
virtual ~memory_manager_kernel_1(
)
{
}
unsigned long get_number_of_allocations (
) const { return allocations; }
T* allocate_array (
unsigned long size
)
{
T* temp = new T[size];
++allocations;
return temp;
}
void deallocate_array (
T* item
)
{
--allocations;
delete [] item;
}
T* allocate (
)
{
T* temp = new T;
++allocations;
return temp;
}
void deallocate (
T* item
)
{
delete item;
--allocations;
}
void swap (
memory_manager_kernel_1& item
)
{
exchange(allocations,item.allocations);
}
private:
// data members
unsigned long allocations;
// restricted functions
memory_manager_kernel_1(memory_manager_kernel_1&); // copy constructor
memory_manager_kernel_1& operator=(memory_manager_kernel_1&); // assignment operator
};
// ----------------------------------------------------------------------------------------
template <
typename T,
unsigned long max_pool_size
>
inline void swap (
memory_manager_kernel_1<T,max_pool_size>& a,
memory_manager_kernel_1<T,max_pool_size>& b
) { a.swap(b); }
// ----------------------------------------------------------------------------------------
}
#endif // DLIB_MEMORY_MANAGER_KERNEl_1_
| [
"jimmy@DGJ3X3B1.(none)"
] | [
[
[
1,
305
]
]
] |
4c01cb30ae2c3af8368b61f7d9a2c1b629c51792 | 580738f96494d426d6e5973c5b3493026caf8b6a | /Include/Vcl/rtlconsts.hpp | 6a0acb6bc67c228464eceedb098611960150392f | [] | no_license | bravesoftdz/cbuilder-vcl | 6b460b4d535d17c309560352479b437d99383d4b | 7b91ef1602681e094a6a7769ebb65ffd6f291c59 | refs/heads/master | 2021-01-10T14:21:03.726693 | 2010-01-11T11:23:45 | 2010-01-11T11:23:45 | 48,485,606 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 17,196 | hpp | // Borland C++ Builder
// Copyright (c) 1995, 2002 by Borland Software Corporation
// All rights reserved
// (DO NOT EDIT: machine generated header) 'RTLConsts.pas' rev: 6.00
#ifndef RTLConstsHPP
#define RTLConstsHPP
#pragma delphiheader begin
#pragma option push -w-
#pragma option push -Vx
#include <SysInit.hpp> // Pascal unit
#include <System.hpp> // Pascal unit
//-- user supplied -----------------------------------------------------------
namespace Rtlconsts
{
//-- type declarations -------------------------------------------------------
//-- var, const, procedure ---------------------------------------------------
extern PACKAGE System::ResourceString _SAncestorNotFound;
#define Rtlconsts_SAncestorNotFound System::LoadResourceString(&Rtlconsts::_SAncestorNotFound)
extern PACKAGE System::ResourceString _SAssignError;
#define Rtlconsts_SAssignError System::LoadResourceString(&Rtlconsts::_SAssignError)
extern PACKAGE System::ResourceString _SBitsIndexError;
#define Rtlconsts_SBitsIndexError System::LoadResourceString(&Rtlconsts::_SBitsIndexError)
extern PACKAGE System::ResourceString _SBucketListLocked;
#define Rtlconsts_SBucketListLocked System::LoadResourceString(&Rtlconsts::_SBucketListLocked)
extern PACKAGE System::ResourceString _SCantWriteResourceStreamError;
#define Rtlconsts_SCantWriteResourceStreamError System::LoadResourceString(&Rtlconsts::_SCantWriteResourceStreamError)
extern PACKAGE System::ResourceString _SCharExpected;
#define Rtlconsts_SCharExpected System::LoadResourceString(&Rtlconsts::_SCharExpected)
extern PACKAGE System::ResourceString _SCheckSynchronizeError;
#define Rtlconsts_SCheckSynchronizeError System::LoadResourceString(&Rtlconsts::_SCheckSynchronizeError)
extern PACKAGE System::ResourceString _SClassNotFound;
#define Rtlconsts_SClassNotFound System::LoadResourceString(&Rtlconsts::_SClassNotFound)
extern PACKAGE System::ResourceString _SDelimiterQuoteCharError;
#define Rtlconsts_SDelimiterQuoteCharError System::LoadResourceString(&Rtlconsts::_SDelimiterQuoteCharError)
extern PACKAGE System::ResourceString _SDuplicateClass;
#define Rtlconsts_SDuplicateClass System::LoadResourceString(&Rtlconsts::_SDuplicateClass)
extern PACKAGE System::ResourceString _SDuplicateItem;
#define Rtlconsts_SDuplicateItem System::LoadResourceString(&Rtlconsts::_SDuplicateItem)
extern PACKAGE System::ResourceString _SDuplicateName;
#define Rtlconsts_SDuplicateName System::LoadResourceString(&Rtlconsts::_SDuplicateName)
extern PACKAGE System::ResourceString _SDuplicateString;
#define Rtlconsts_SDuplicateString System::LoadResourceString(&Rtlconsts::_SDuplicateString)
extern PACKAGE System::ResourceString _SFCreateError;
#define Rtlconsts_SFCreateError System::LoadResourceString(&Rtlconsts::_SFCreateError)
extern PACKAGE System::ResourceString _SFixedColTooBig;
#define Rtlconsts_SFixedColTooBig System::LoadResourceString(&Rtlconsts::_SFixedColTooBig)
extern PACKAGE System::ResourceString _SFixedRowTooBig;
#define Rtlconsts_SFixedRowTooBig System::LoadResourceString(&Rtlconsts::_SFixedRowTooBig)
extern PACKAGE System::ResourceString _SFOpenError;
#define Rtlconsts_SFOpenError System::LoadResourceString(&Rtlconsts::_SFOpenError)
extern PACKAGE System::ResourceString _SGridTooLarge;
#define Rtlconsts_SGridTooLarge System::LoadResourceString(&Rtlconsts::_SGridTooLarge)
extern PACKAGE System::ResourceString _SIdentifierExpected;
#define Rtlconsts_SIdentifierExpected System::LoadResourceString(&Rtlconsts::_SIdentifierExpected)
extern PACKAGE System::ResourceString _SIndexOutOfRange;
#define Rtlconsts_SIndexOutOfRange System::LoadResourceString(&Rtlconsts::_SIndexOutOfRange)
extern PACKAGE System::ResourceString _SIniFileWriteError;
#define Rtlconsts_SIniFileWriteError System::LoadResourceString(&Rtlconsts::_SIniFileWriteError)
extern PACKAGE System::ResourceString _SInvalidActionCreation;
#define Rtlconsts_SInvalidActionCreation System::LoadResourceString(&Rtlconsts::_SInvalidActionCreation)
extern PACKAGE System::ResourceString _SInvalidActionEnumeration;
#define Rtlconsts_SInvalidActionEnumeration System::LoadResourceString(&Rtlconsts::_SInvalidActionEnumeration)
extern PACKAGE System::ResourceString _SInvalidActionRegistration;
#define Rtlconsts_SInvalidActionRegistration System::LoadResourceString(&Rtlconsts::_SInvalidActionRegistration)
extern PACKAGE System::ResourceString _SInvalidActionUnregistration;
#define Rtlconsts_SInvalidActionUnregistration System::LoadResourceString(&Rtlconsts::_SInvalidActionUnregistration)
extern PACKAGE System::ResourceString _SInvalidBinary;
#define Rtlconsts_SInvalidBinary System::LoadResourceString(&Rtlconsts::_SInvalidBinary)
extern PACKAGE System::ResourceString _SInvalidDate;
#define Rtlconsts_SInvalidDate System::LoadResourceString(&Rtlconsts::_SInvalidDate)
extern PACKAGE System::ResourceString _SInvalidDateTime;
#define Rtlconsts_SInvalidDateTime System::LoadResourceString(&Rtlconsts::_SInvalidDateTime)
extern PACKAGE System::ResourceString _SInvalidFileName;
#define Rtlconsts_SInvalidFileName System::LoadResourceString(&Rtlconsts::_SInvalidFileName)
extern PACKAGE System::ResourceString _SInvalidImage;
#define Rtlconsts_SInvalidImage System::LoadResourceString(&Rtlconsts::_SInvalidImage)
extern PACKAGE System::ResourceString _SInvalidInteger;
#define Rtlconsts_SInvalidInteger System::LoadResourceString(&Rtlconsts::_SInvalidInteger)
extern PACKAGE System::ResourceString _SInvalidMask;
#define Rtlconsts_SInvalidMask System::LoadResourceString(&Rtlconsts::_SInvalidMask)
extern PACKAGE System::ResourceString _SInvalidName;
#define Rtlconsts_SInvalidName System::LoadResourceString(&Rtlconsts::_SInvalidName)
extern PACKAGE System::ResourceString _SInvalidProperty;
#define Rtlconsts_SInvalidProperty System::LoadResourceString(&Rtlconsts::_SInvalidProperty)
extern PACKAGE System::ResourceString _SInvalidPropertyElement;
#define Rtlconsts_SInvalidPropertyElement System::LoadResourceString(&Rtlconsts::_SInvalidPropertyElement)
extern PACKAGE System::ResourceString _SInvalidPropertyPath;
#define Rtlconsts_SInvalidPropertyPath System::LoadResourceString(&Rtlconsts::_SInvalidPropertyPath)
extern PACKAGE System::ResourceString _SInvalidPropertyType;
#define Rtlconsts_SInvalidPropertyType System::LoadResourceString(&Rtlconsts::_SInvalidPropertyType)
extern PACKAGE System::ResourceString _SInvalidPropertyValue;
#define Rtlconsts_SInvalidPropertyValue System::LoadResourceString(&Rtlconsts::_SInvalidPropertyValue)
extern PACKAGE System::ResourceString _SInvalidRegType;
#define Rtlconsts_SInvalidRegType System::LoadResourceString(&Rtlconsts::_SInvalidRegType)
extern PACKAGE System::ResourceString _SInvalidString;
#define Rtlconsts_SInvalidString System::LoadResourceString(&Rtlconsts::_SInvalidString)
extern PACKAGE System::ResourceString _SInvalidStringGridOp;
#define Rtlconsts_SInvalidStringGridOp System::LoadResourceString(&Rtlconsts::_SInvalidStringGridOp)
extern PACKAGE System::ResourceString _SInvalidTime;
#define Rtlconsts_SInvalidTime System::LoadResourceString(&Rtlconsts::_SInvalidTime)
extern PACKAGE System::ResourceString _SItemNotFound;
#define Rtlconsts_SItemNotFound System::LoadResourceString(&Rtlconsts::_SItemNotFound)
extern PACKAGE System::ResourceString _SLineTooLong;
#define Rtlconsts_SLineTooLong System::LoadResourceString(&Rtlconsts::_SLineTooLong)
extern PACKAGE System::ResourceString _SListCapacityError;
#define Rtlconsts_SListCapacityError System::LoadResourceString(&Rtlconsts::_SListCapacityError)
extern PACKAGE System::ResourceString _SListCountError;
#define Rtlconsts_SListCountError System::LoadResourceString(&Rtlconsts::_SListCountError)
extern PACKAGE System::ResourceString _SListIndexError;
#define Rtlconsts_SListIndexError System::LoadResourceString(&Rtlconsts::_SListIndexError)
extern PACKAGE System::ResourceString _SMaskErr;
#define Rtlconsts_SMaskErr System::LoadResourceString(&Rtlconsts::_SMaskErr)
extern PACKAGE System::ResourceString _SMaskEditErr;
#define Rtlconsts_SMaskEditErr System::LoadResourceString(&Rtlconsts::_SMaskEditErr)
extern PACKAGE System::ResourceString _SMemoryStreamError;
#define Rtlconsts_SMemoryStreamError System::LoadResourceString(&Rtlconsts::_SMemoryStreamError)
extern PACKAGE System::ResourceString _SNoComSupport;
#define Rtlconsts_SNoComSupport System::LoadResourceString(&Rtlconsts::_SNoComSupport)
extern PACKAGE System::ResourceString _SNotPrinting;
#define Rtlconsts_SNotPrinting System::LoadResourceString(&Rtlconsts::_SNotPrinting)
extern PACKAGE System::ResourceString _SNumberExpected;
#define Rtlconsts_SNumberExpected System::LoadResourceString(&Rtlconsts::_SNumberExpected)
extern PACKAGE System::ResourceString _SParseError;
#define Rtlconsts_SParseError System::LoadResourceString(&Rtlconsts::_SParseError)
extern PACKAGE System::ResourceString _SComponentNameTooLong;
#define Rtlconsts_SComponentNameTooLong System::LoadResourceString(&Rtlconsts::_SComponentNameTooLong)
extern PACKAGE System::ResourceString _SPropertyException;
#define Rtlconsts_SPropertyException System::LoadResourceString(&Rtlconsts::_SPropertyException)
extern PACKAGE System::ResourceString _SPrinting;
#define Rtlconsts_SPrinting System::LoadResourceString(&Rtlconsts::_SPrinting)
extern PACKAGE System::ResourceString _SReadError;
#define Rtlconsts_SReadError System::LoadResourceString(&Rtlconsts::_SReadError)
extern PACKAGE System::ResourceString _SReadOnlyProperty;
#define Rtlconsts_SReadOnlyProperty System::LoadResourceString(&Rtlconsts::_SReadOnlyProperty)
extern PACKAGE System::ResourceString _SRegCreateFailed;
#define Rtlconsts_SRegCreateFailed System::LoadResourceString(&Rtlconsts::_SRegCreateFailed)
extern PACKAGE System::ResourceString _SRegGetDataFailed;
#define Rtlconsts_SRegGetDataFailed System::LoadResourceString(&Rtlconsts::_SRegGetDataFailed)
extern PACKAGE System::ResourceString _SRegisterError;
#define Rtlconsts_SRegisterError System::LoadResourceString(&Rtlconsts::_SRegisterError)
extern PACKAGE System::ResourceString _SRegSetDataFailed;
#define Rtlconsts_SRegSetDataFailed System::LoadResourceString(&Rtlconsts::_SRegSetDataFailed)
extern PACKAGE System::ResourceString _SResNotFound;
#define Rtlconsts_SResNotFound System::LoadResourceString(&Rtlconsts::_SResNotFound)
extern PACKAGE System::ResourceString _SSeekNotImplemented;
#define Rtlconsts_SSeekNotImplemented System::LoadResourceString(&Rtlconsts::_SSeekNotImplemented)
extern PACKAGE System::ResourceString _SSortedListError;
#define Rtlconsts_SSortedListError System::LoadResourceString(&Rtlconsts::_SSortedListError)
extern PACKAGE System::ResourceString _SStringExpected;
#define Rtlconsts_SStringExpected System::LoadResourceString(&Rtlconsts::_SStringExpected)
extern PACKAGE System::ResourceString _SSymbolExpected;
#define Rtlconsts_SSymbolExpected System::LoadResourceString(&Rtlconsts::_SSymbolExpected)
extern PACKAGE System::ResourceString _STimeEncodeError;
#define Rtlconsts_STimeEncodeError System::LoadResourceString(&Rtlconsts::_STimeEncodeError)
extern PACKAGE System::ResourceString _STooManyDeleted;
#define Rtlconsts_STooManyDeleted System::LoadResourceString(&Rtlconsts::_STooManyDeleted)
extern PACKAGE System::ResourceString _SUnknownGroup;
#define Rtlconsts_SUnknownGroup System::LoadResourceString(&Rtlconsts::_SUnknownGroup)
extern PACKAGE System::ResourceString _SUnknownProperty;
#define Rtlconsts_SUnknownProperty System::LoadResourceString(&Rtlconsts::_SUnknownProperty)
extern PACKAGE System::ResourceString _SWriteError;
#define Rtlconsts_SWriteError System::LoadResourceString(&Rtlconsts::_SWriteError)
extern PACKAGE System::ResourceString _SStreamSetSize;
#define Rtlconsts_SStreamSetSize System::LoadResourceString(&Rtlconsts::_SStreamSetSize)
extern PACKAGE System::ResourceString _SThreadCreateError;
#define Rtlconsts_SThreadCreateError System::LoadResourceString(&Rtlconsts::_SThreadCreateError)
extern PACKAGE System::ResourceString _SThreadError;
#define Rtlconsts_SThreadError System::LoadResourceString(&Rtlconsts::_SThreadError)
extern PACKAGE System::ResourceString _SInvalidDateDay;
#define Rtlconsts_SInvalidDateDay System::LoadResourceString(&Rtlconsts::_SInvalidDateDay)
extern PACKAGE System::ResourceString _SInvalidDateWeek;
#define Rtlconsts_SInvalidDateWeek System::LoadResourceString(&Rtlconsts::_SInvalidDateWeek)
extern PACKAGE System::ResourceString _SInvalidDateMonthWeek;
#define Rtlconsts_SInvalidDateMonthWeek System::LoadResourceString(&Rtlconsts::_SInvalidDateMonthWeek)
extern PACKAGE System::ResourceString _SInvalidDayOfWeekInMonth;
#define Rtlconsts_SInvalidDayOfWeekInMonth System::LoadResourceString(&Rtlconsts::_SInvalidDayOfWeekInMonth)
extern PACKAGE System::ResourceString _SInvalidJulianDate;
#define Rtlconsts_SInvalidJulianDate System::LoadResourceString(&Rtlconsts::_SInvalidJulianDate)
extern PACKAGE System::ResourceString _SMissingDateTimeField;
#define Rtlconsts_SMissingDateTimeField System::LoadResourceString(&Rtlconsts::_SMissingDateTimeField)
extern PACKAGE System::ResourceString _SConvIncompatibleTypes2;
#define Rtlconsts_SConvIncompatibleTypes2 System::LoadResourceString(&Rtlconsts::_SConvIncompatibleTypes2)
extern PACKAGE System::ResourceString _SConvIncompatibleTypes3;
#define Rtlconsts_SConvIncompatibleTypes3 System::LoadResourceString(&Rtlconsts::_SConvIncompatibleTypes3)
extern PACKAGE System::ResourceString _SConvIncompatibleTypes4;
#define Rtlconsts_SConvIncompatibleTypes4 System::LoadResourceString(&Rtlconsts::_SConvIncompatibleTypes4)
extern PACKAGE System::ResourceString _SConvUnknownType;
#define Rtlconsts_SConvUnknownType System::LoadResourceString(&Rtlconsts::_SConvUnknownType)
extern PACKAGE System::ResourceString _SConvDuplicateType;
#define Rtlconsts_SConvDuplicateType System::LoadResourceString(&Rtlconsts::_SConvDuplicateType)
extern PACKAGE System::ResourceString _SConvUnknownFamily;
#define Rtlconsts_SConvUnknownFamily System::LoadResourceString(&Rtlconsts::_SConvUnknownFamily)
extern PACKAGE System::ResourceString _SConvDuplicateFamily;
#define Rtlconsts_SConvDuplicateFamily System::LoadResourceString(&Rtlconsts::_SConvDuplicateFamily)
extern PACKAGE System::ResourceString _SConvUnknownDescription;
#define Rtlconsts_SConvUnknownDescription System::LoadResourceString(&Rtlconsts::_SConvUnknownDescription)
extern PACKAGE System::ResourceString _SConvIllegalType;
#define Rtlconsts_SConvIllegalType System::LoadResourceString(&Rtlconsts::_SConvIllegalType)
extern PACKAGE System::ResourceString _SConvIllegalFamily;
#define Rtlconsts_SConvIllegalFamily System::LoadResourceString(&Rtlconsts::_SConvIllegalFamily)
extern PACKAGE System::ResourceString _SConvFactorZero;
#define Rtlconsts_SConvFactorZero System::LoadResourceString(&Rtlconsts::_SConvFactorZero)
extern PACKAGE System::ResourceString _SConvStrParseError;
#define Rtlconsts_SConvStrParseError System::LoadResourceString(&Rtlconsts::_SConvStrParseError)
extern PACKAGE System::ResourceString _SFailedToCallConstructor;
#define Rtlconsts_SFailedToCallConstructor System::LoadResourceString(&Rtlconsts::_SFailedToCallConstructor)
extern PACKAGE System::ResourceString _sWindowsSocketError;
#define Rtlconsts_sWindowsSocketError System::LoadResourceString(&Rtlconsts::_sWindowsSocketError)
extern PACKAGE System::ResourceString _sAsyncSocketError;
#define Rtlconsts_sAsyncSocketError System::LoadResourceString(&Rtlconsts::_sAsyncSocketError)
extern PACKAGE System::ResourceString _sNoAddress;
#define Rtlconsts_sNoAddress System::LoadResourceString(&Rtlconsts::_sNoAddress)
extern PACKAGE System::ResourceString _sCannotListenOnOpen;
#define Rtlconsts_sCannotListenOnOpen System::LoadResourceString(&Rtlconsts::_sCannotListenOnOpen)
extern PACKAGE System::ResourceString _sCannotCreateSocket;
#define Rtlconsts_sCannotCreateSocket System::LoadResourceString(&Rtlconsts::_sCannotCreateSocket)
extern PACKAGE System::ResourceString _sSocketAlreadyOpen;
#define Rtlconsts_sSocketAlreadyOpen System::LoadResourceString(&Rtlconsts::_sSocketAlreadyOpen)
extern PACKAGE System::ResourceString _sCantChangeWhileActive;
#define Rtlconsts_sCantChangeWhileActive System::LoadResourceString(&Rtlconsts::_sCantChangeWhileActive)
extern PACKAGE System::ResourceString _sSocketMustBeBlocking;
#define Rtlconsts_sSocketMustBeBlocking System::LoadResourceString(&Rtlconsts::_sSocketMustBeBlocking)
extern PACKAGE System::ResourceString _sSocketIOError;
#define Rtlconsts_sSocketIOError System::LoadResourceString(&Rtlconsts::_sSocketIOError)
extern PACKAGE System::ResourceString _sSocketRead;
#define Rtlconsts_sSocketRead System::LoadResourceString(&Rtlconsts::_sSocketRead)
extern PACKAGE System::ResourceString _sSocketWrite;
#define Rtlconsts_sSocketWrite System::LoadResourceString(&Rtlconsts::_sSocketWrite)
} /* namespace Rtlconsts */
using namespace Rtlconsts;
#pragma option pop // -w-
#pragma option pop // -Vx
#pragma delphiheader end.
//-- end unit ----------------------------------------------------------------
#endif // RTLConsts
| [
"bitscode@7bd08ab0-fa70-11de-930f-d36749347e7b"
] | [
[
[
1,
242
]
]
] |
bfe5a94f785d42e66fa6216a716647eaab9b916f | 0841b965ef16edab738c260e2bb46dec5a44857d | /gadgets/skinnedgadgets/skinnedscreen.cpp | 407a33d9572c6facab8cb828c0d35cfa51705e68 | [] | no_license | ant512/WoopsiExtras | b73e399ebb3bd7685587e7e8b6051d336989354a | 45ea469a22827b737a361b5a5f73cbeffe2974c3 | refs/heads/master | 2021-01-08T22:13:16.196976 | 2010-09-03T08:28:31 | 2010-09-03T08:28:31 | 242,157,454 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,425 | cpp | #include "skinnedscreendepthbutton.h"
#include "skinnedscreenflipbutton.h"
#include "skinnedscreentitle.h"
#include "skinnedscreen.h"
using namespace WoopsiUI;
SkinnedScreen::SkinnedScreen(const char* title, u32 flags, u32 screenFlags, const ScreenSkin* skin) : Screen(title, flags, skin->style) {
_screenTitle = NULL;
_depthButton = NULL;
_flipButton = NULL;
_skin = skin;
// Parse skin information
_titleHeight = _skin->titleBar.bitmap.height;
_flags.borderless = _skin->screen.borderless;
_flags.permeable = _skin->screen.permeable;
_screenFlags.showFlipButton = _skin->flipButton.visible;
_screenFlags.showDepthButton = _skin->depthButton.visible;
setBorderless(!_flags.borderless);
}
void SkinnedScreen::setBorderless(bool isBorderless) {
if (isBorderless != _flags.borderless) {
if (isBorderless) {
// Remove borders
_screenTitle->close();
if (_depthButton != NULL) _depthButton->close();
if (_flipButton != NULL) _flipButton->close();
_screenTitle = NULL;
_depthButton = NULL;
_flipButton = NULL;
_flags.borderless = true;
} else {
// Add borders
// Calculate button positions
u16 flipX = _width - _skin->flipButton.bitmap.width;
u16 depthX = _width - _skin->depthButton.bitmap.width;
if (_skin->depthButton.visible) {
flipX -= _skin->depthButton.bitmap.width;
}
_screenTitle = new SkinnedScreenTitle(this, _skin);
_screenTitle->addGadgetEventHandler(this);
insertGadget(_screenTitle);
// Create depth button
if (_screenFlags.showDepthButton) {
_depthButton = new SkinnedScreenDepthButton(depthX, 0, _skin);
_depthButton->addGadgetEventHandler(this);
addGadget(_depthButton);
}
// Create flip button
if (_screenFlags.showFlipButton) {
_flipButton = new SkinnedScreenFlipButton(flipX, 0, _skin);
_flipButton->addGadgetEventHandler(this);
addGadget(_flipButton);
}
_flags.borderless = false;
}
invalidateVisibleRectCache();
redraw();
}
}
void SkinnedScreen::handleReleaseEvent(const GadgetEventArgs& e) {
if (e.getSource() != NULL) {
// Process decoration gadgets only
if (e.getSource() == _flipButton) {
// Flip screens
flipScreens();
} else if (e.getSource() == _depthButton) {
// Depth swap to bottom of stack
lowerToBottom();
blur();
} else if (e.getSource() == _screenTitle) {
release(e.getX(), e.getY());
}
}
}
void SkinnedScreen::handleClickEvent(const GadgetEventArgs& e) {
if (e.getSource() != NULL) {
if (e.getSource() == _screenTitle) {
setDragging(e.getX(), e.getY());
}
}
}
void SkinnedScreen::handleDragEvent(const GadgetEventArgs& e) {
if (e.getSource() != NULL) {
if (e.getSource() == _screenTitle) {
drag(e.getX(), e.getY(), e.getVX(), e.getVY());
}
}
}
void SkinnedScreen::handleReleaseOutsideEvent(const GadgetEventArgs& e) {
if (e.getSource() != NULL) {
if (e.getSource() == _screenTitle) {
release(e.getX(), e.getY());
}
}
}
void SkinnedScreen::showFlipButton() {
if ((!_flags.borderless) && (!_screenFlags.showFlipButton)) {
_screenFlags.showFlipButton = true;
// Calculate button position
u16 flipX = _width - _skin->flipButton.bitmap.width;
// Recreate flip button
_flipButton = new SkinnedScreenFlipButton(flipX, 0, _skin);
_flipButton->addGadgetEventHandler(this);
addGadget(_flipButton);
_flipButton->redraw();
}
}
void SkinnedScreen::showDepthButton() {
if ((!_flags.borderless) && (!_screenFlags.showDepthButton)) {
_screenFlags.showDepthButton = true;
// Calculate button position
u16 depthX = _width - _skin->depthButton.bitmap.width;
// Recreate depth button
_depthButton = new SkinnedScreenDepthButton(depthX, 0, _skin);
_depthButton->addGadgetEventHandler(this);
addGadget(_depthButton);
_depthButton->redraw();
}
}
void SkinnedScreen::hideFlipButton() {
if ((!_flags.borderless) && (_screenFlags.showFlipButton)) {
_screenFlags.showFlipButton = false;
// Delete flip button
_flipButton->close();
_flipButton = NULL;
}
}
void SkinnedScreen::hideDepthButton() {
if ((!_flags.borderless) && (_screenFlags.showDepthButton)) {
_screenFlags.showDepthButton = false;
// Delete close button
_depthButton->close();
_depthButton = NULL;
}
}
| [
"devnull@localhost"
] | [
[
[
1,
173
]
]
] |
2c30acff282b1bcc2cc851aef4be999258c25984 | 74c8da5b29163992a08a376c7819785998afb588 | /NetAnimal/Game/Hunter/NewGameNeedle/GameNeedleComponent/include/RotationComponent.h | 0d2f1db1765459acfbcd8012fddcde4cb613840e | [] | no_license | dbabox/aomi | dbfb46c1c9417a8078ec9a516cc9c90fe3773b78 | 4cffc8e59368e82aed997fe0f4dcbd7df626d1d0 | refs/heads/master | 2021-01-13T14:05:10.813348 | 2011-06-07T09:36:41 | 2011-06-07T09:36:41 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 1,465 | h | #ifndef __Orz_RotationComponent__
#define __Orz_RotationComponent__
#include "CRotationInterface.h"
namespace Ogre
{
class SceneNode;
}
namespace Orz
{
class CRotationInterface;
class _UpdateInOgreRenderingQueued;
class RotationComponent: public Component//Ðýת×é¼þ
{
friend class _UpdateInOgreRenderingQueued;
public :
RotationComponent(void);
virtual ~RotationComponent(void);
private:
ComponentInterface * _queryInterface(const TypeInfo & info);
boost::scoped_ptr<CRotationInterface> _rotationInterface;
void _play2(std::pair<float, float> & startAllDegree, TimeType allTime);
bool update(TimeType interval);
float interpolation(float value);
float time2Degree(TimeType time);
void setAngle(float degree);
float getAngle(void) const;
static std::pair<float, float> getStartAll(float start, float end);
void reset(float angle);
void _play(float allDegree, TimeType allTime);
void play(float startDegree, float allDegree, TimeType allTime);
private:
bool init(Ogre::SceneNode * node, CRotationInterface::DIRECTION direction, float offset);
bool _implUpdate(TimeType interval);
float _startDegree;
float _endDegree;
TimeType _allTime;
TimeType _curTime;
float _angle;
float _curAngle;
float _offsetAngle;
Ogre::SceneNode * _node;
int _direction;
boost::scoped_ptr<_UpdateInOgreRenderingQueued> _update;
};
}
#endif | [
"[email protected]"
] | [
[
[
1,
73
]
]
] |
263b830fc2e3bd225a169340b9519b811572772e | ee065463a247fda9a1927e978143186204fefa23 | /Src/Application/QtExtensions/QDoubleSpinBoxWrapper.h | 07064ac2a13722a13519ba6203af5e5d4623d929 | [] | no_license | ptrefall/hinsimviz | 32e9a679170eda9e552d69db6578369a3065f863 | 9caaacd39bf04bbe13ee1288d8578ece7949518f | refs/heads/master | 2021-01-22T09:03:52.503587 | 2010-09-26T17:29:20 | 2010-09-26T17:29:20 | 32,448,374 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,178 | h | #pragma once
#include "IWrapper.h"
#include <ClanLib/core.h>
#include <QtGui/QDoubleSpinBox>
#include <Depends/Entity/Property.h>
class ObjectQtWrapper;
class QDoubleSpinBoxWrapper : public IWrapper
{
public:
QDoubleSpinBoxWrapper(ObjectQtWrapper *qObj, Engine::Entity::Property<double> property);
QDoubleSpinBoxWrapper(ObjectQtWrapper *qObj, Engine::Entity::Property<float> property);
virtual ~QDoubleSpinBoxWrapper();
QDoubleSpinBox *getQDoubleSpinBox() const { return spinbox; }
Engine::Entity::Property<double> getDProperty() { return dProperty; }
Engine::Entity::Property<float> getFProperty() { return fProperty; }
private:
void OnDPropertyChanged(const double &oldValue, const double &newValue);
void OnFPropertyChanged(const float &oldValue, const float &newValue);
CL_Slot slotDPropertyChanged;
CL_Slot slotFPropertyChanged;
QDoubleSpinBox *spinbox;
Engine::Entity::Property<double> dProperty;
Engine::Entity::Property<float> fProperty;
ObjectQtWrapper *qObj;
bool slotChanged;
bool propChanged;
public slots:
virtual void slotDValueChanged(double value);
virtual void slotFValueChanged(double value);
};
| [
"[email protected]@28a56cb3-1e7c-bc60-7718-65c159e1d2df"
] | [
[
[
1,
38
]
]
] |
04c2384ffaa7c8649336354dc5c3221d3b050e3e | ed6f03c2780226a28113ba535d3e438ee5d70266 | /src/eljpalette.cpp | 25a4b4dd2c3406603065c45af8e0184f8d422d38 | [] | no_license | snmsts/wxc | f06c0306d0ff55f0634e5a372b3a71f56325c647 | 19663c56e4ae2c79ccf647d687a9a1d42ca8cb61 | refs/heads/master | 2021-01-01T05:41:20.607789 | 2009-04-08T09:12:08 | 2009-04-08T09:12:08 | 170,876 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,675 | cpp | #include "wrapper.h"
extern "C"
{
EWXWEXPORT(void*,wxPalette_CreateDefault)()
{
return (void*)new wxPalette();
}
EWXWEXPORT(void*,wxPalette_CreateRGB)(int n,void* red,void* green,void* blue)
{
return (void*)new wxPalette(n, (unsigned char*)red, (unsigned char*)green, (unsigned char*)blue);
}
EWXWEXPORT(void,wxPalette_Delete)(void* self)
{
delete (wxPalette*)self;
}
EWXWEXPORT(int,wxPalette_GetPixel)(void* self,wxUint8 red,wxUint8 green,wxUint8 blue)
{
return ((wxPalette*)self)->GetPixel(red,green,blue);
}
EWXWEXPORT(bool,wxPalette_GetRGB)(wxPalette* self,int pixel,void* red,void* green,void* blue)
{
return self->GetRGB(pixel, (unsigned char*)red, (unsigned char*)green, (unsigned char*)blue);
}
EWXWEXPORT(bool,wxPalette_IsOk)(wxPalette* self)
{
return self->IsOk();
}
EWXWEXPORT(void,wxPalette_Assign)(void* self,void* palette)
{
*((wxPalette*)self) = *((wxPalette*)palette);
}
EWXWEXPORT(bool,wxPalette_IsEqual)(wxPalette* self,wxPalette* palette)
{
#if (wxVERSION_NUMBER <= 2800)
return *self == *palette;
#else
wxPalette* pal1 = self;
wxPalette* pal2 = palette;
if (pal1->GetColoursCount() == pal2->GetColoursCount()){
bool equal = true;
unsigned char red1 = 0;
unsigned char red2 = 0;
unsigned char green1 = 0;
unsigned char green2 = 0;
unsigned char blue1 = 0;
unsigned char blue2 = 0;
for(int x = 0; x<(pal1->GetColoursCount()); x++){
pal1->GetRGB(x, &red1, &green1, &blue1);
pal2->GetRGB(x, &red2, &green2, &blue2);
equal = equal && (red1==red2 && green1==green2 && blue1==blue2);
}
return equal;
} else {
return false;
}
#endif
}
}
| [
"[email protected]"
] | [
[
[
1,
68
]
]
] |
efbb71fbdbc5b005d2249afd916c6e520ae95803 | e7c45d18fa1e4285e5227e5984e07c47f8867d1d | /Common/Scd/ScdLib/DBGMNGR.CPP | e0e2fc200543e39246ac24a467c2e8f0f1b53114 | [] | no_license | abcweizhuo/Test3 | 0f3379e528a543c0d43aad09489b2444a2e0f86d | 128a4edcf9a93d36a45e5585b70dee75e4502db4 | refs/heads/master | 2021-01-17T01:59:39.357645 | 2008-08-20T00:00:29 | 2008-08-20T00:00:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,070 | cpp | //================== SysCAD - Copyright Kenwalt (Pty) Ltd ===================
// $Nokeywords: $
//===========================================================================
// SysCAD Copyright Kenwalt (Pty) Ltd 1992,1994
#include "stdafx.h"
#define __DBGMNGR_CPP
#include <sys\stat.h>
//#include <afxmt.h>
#include "dbgmngr.h"
#include "gpfuncs.h"
#include "crtdbg.h"
#include "errorlog.h"
#include "scdver.h"
#if DBGMANAGER
//#pragma warning (disable : 4073) // initializers put in library initialization area
//#pragma init_seg(lib) // Force Early Construction and Late Destruction
//
//CCriticalSection DbgMngrLock;
LONG DbgMngrLock=-1;
//#pragma init_seg(user) // Restore Normal Construction and Destruction
// =========================================================================
// initialize static data members in cpp for only ONE copy ( if in header MULTIPLE copies )
pCDbgMngr CDbgMngr::pFirst = NULL;
pCGenSexn CGenSexn::pFirstGen = NULL;
long CDbgMngr::LastFileTime = 0;
long CDbgMngr::IndexCnt = 0;
flag CDbgMngr::bStarted = 0;
Strng CDbgMngr::DbgMngrFilename(" ");//("c:\\syscad71\\SCD_Dmf.Ini"); // specifies the DbgMngrFile to be used
//Strng CDbgMngr::DbgMngrFilename; // specifies the DbgMngrFile to be used
//--------------------------------------------------------------------------
CSubSexn::CSubSexn ( pchar subSection)
{
pNxt = NULL;
subStrng = subSection;
fValue = 0;
fStrng = "";
};
//--------------------------------------------------------------------------
CSubSexn::~CSubSexn ()
{
delete pNxt;
};
//--------------------------------------------------------------------------
/*#F:If the sub section is already present in the list then nothing is added, otherwise
the sub section name is added to the list, which corresponds to the respective general section name.*/
flag CSubSexn::Add (pchar subSection )
{
pCSubSexn looking = this; // pFirstSub;
flag flag = 1;
pCSubSexn last = NULL;
while ( looking) //->pNxt ) //!= NULL )
{
if ( looking->subStrng.XStrICmp ( subSection ) == 0 ) // if sub section exists EXIT
{ // case insensitive comparison like file
flag = 0;
break;
};
last = looking;
looking = looking->pNxt;
}
if (flag) // it exited because the last term was reached
last->pNxt = new CSubSexn (subSection) ;
return 1;
};
//=======================================================================================
/*#f:this constructs the CGenSexn instance, and at the same time it also
constructs the included CSbSexn pointer*/
CGenSexn::CGenSexn(pchar general, pchar subSection )
{
pNxt = NULL;
pSubSexns = new CSubSexn( subSection );
genStrng = general;
};
//--------------------------------------------------------------------------
CGenSexn::~CGenSexn()
{
delete pSubSexns;
delete pNxt;
};
//--------------------------------------------------------------------------
/*#F: If the general section already exists then only a new sub section is added
to the list, otherwise a new general section is also added to the list */
flag CGenSexn::Add (pchar generalSection, pchar subSection)
{
pCGenSexn p = pFirstGen;
flag flag = 1;
pCGenSexn last = NULL;
while(p)
{
if ( p->genStrng.XStrICmp (generalSection) == 0) // matches with existing
{ // case insensitive
p->pSubSexns->Add ( subSection );
flag = 0;
break;
}
last = p;
p = p->pNxt; //get next
}
if (flag) // exited the loop without finding a like minded friend
{
CGenSexn*pn = new CGenSexn ( generalSection, subSection );
CGenSexn*p=pFirstGen, *p1=NULL;
while (p && ((_stricmp(p->genStrng(), generalSection)<0)))
{
p1=p;
p=p->pNxt;
}
if (p1)
{
pn->pNxt=p1->pNxt;
p1->pNxt=pn;
}
else
{
pn->pNxt=pFirstGen;
pFirstGen=pn;
}
//last->pNxt = new CGenSexn ( generalSection, subSection );
};
return 1;
};
//--------------------------------------------------------------------------
/*#F: The index value returned by the list box can be used to retrieve
the required general section */
pCGenSexn CGenSexn::GetByIndex ( int index )
{
pCGenSexn p = pFirstGen;
int count = 0;
while(p && ( count < index ) )
{
count++;
p = p->pNxt; //get next
}
return p;
};
//--------------------------------------------------------------------------
/*#F: This will initially determine whether the file actually exists, if so the
value and groups associated with the line will be put into the "fValue" and
fStrng variables in the associated CSubSexn, if no such line
exists or the file does not exist then the default values are retrieved. */
void CGenSexn::ReadFromFile ( pCSubSexn currentSubSexn )
{
struct _stat buffer;
int r = _stat( CDbgMngr::DbgMngrFilename(), &buffer );
if(!r)// file exists
{
char Buff[1024];
GetPrivateProfileString(genStrng(), currentSubSexn->subStrng(), "xXxX", &Buff[0], sizeof(Buff), CDbgMngr::DbgMngrFilename());
if (strcmp(Buff, "xXxX")!=0) // line exists in file
{
Strng s = Buff;// used only to break out tokens from Buff
s.Trim(" ");
Strng entireLine = s;
int decider = 0;
decider = entireLine.Find(','); // line only consists of a value
if ( decider == -1 )
currentSubSexn->fStrng = "xXxX";
else
currentSubSexn->fStrng = entireLine.Right ( entireLine.Length() - (decider + 1) );// all except the value & comma
Strng Tok; // used to manipulate token
Tok = s.StrTok(",",True);
Tok.Trim(" ");// isolate the value
currentSubSexn->fValue = atol(Tok.Str());// returns 0 if this cannot be done
}
else //line does not exist in file
{
currentSubSexn->fValue = 0;
currentSubSexn->fStrng = "xXxX";
};
}
else
{ // dbg file does not exist ( -1)
currentSubSexn->fValue = 0;
currentSubSexn->fStrng = "xXxX";
}
};
//--------------------------------------------------------------------------
/*#F: This will open the file anew and write the required value and groups
associated with the line to the file. If the default value for groups are
retrieved, then no groups are written to the file*/
void CGenSexn::WriteToFile ( pCSubSexn currentSubSexn )
{
Strng actuallyWritten;
if (strcmp(currentSubSexn->fStrng(), "xXxX") !=0) // groups != default val
{
actuallyWritten.Set("%ld",currentSubSexn->fValue);
actuallyWritten += ",";
actuallyWritten += currentSubSexn->fStrng();
}
else
actuallyWritten.Set("%ld",currentSubSexn->fValue);
// to posn the equals and values in a column 30 characters from start of subSexnname
int remainder = 30 - currentSubSexn->subStrng.Length ();
currentSubSexn->subStrng.RPad(remainder); // pad the remainder with spaces
WritePrivateProfileString (genStrng(), currentSubSexn->subStrng(), actuallyWritten(), CDbgMngr::DbgMngrFilename() );
};
//=======================================================================================
/*#F: The Constructor appends the CDbgMngr object to end of linked list, records
the object's "Group Name" and loads any items, from the file, which are listed after
this group name.
#x: if pGroup does not correlate with one of the Group names in the DbgMngrFile -
eg SYSCAD.DMF in syscad71 directory, it will not be ignored.*/
CDbgMngr::CDbgMngr(pchar pSection, pchar pGroup)
{
sSection = pSection;//assign sexn name to member function for later reference
sGroup = pGroup; //assign group name to member function for later reference
ASSERT(pSection); //cannot be empty string
ASSERT(pGroup); //cannot be empty string
ASSERT(sSection.Length()>0); //cannot be empty string
ASSERT(sGroup.Length()>0); //cannot be empty string
Items.Clear();// ensure that linked list assigned to sGroup is clear of all items
pNxt=NULL;
bOn=0;
bOnPgm=0;
//add to CDbgMngr list...
StartupLock.Lock();
CDbgMngr*p=pFirst, *p1=NULL;
while (p &&
((_stricmp(p->sSection(), pSection)<0) ||
((_stricmp(p->sSection(), pSection)==0) && (_stricmp(p->sGroup(), pGroup)<0))))
{
p1=p;
p=p->pNxt;
}
if (p1)
{
pNxt=p1->pNxt;
p1->pNxt=this;
}
else
{
pNxt=pFirst;
pFirst=this;
}
StartupLock.Unlock();
//if(pFirst)// if a list exists
// {
// pCDbgMngr p = pFirst;
// while(p->pNxt) // cycle through list until p is linked to NULL
// p = p->pNxt;
// p->pNxt = this; // assign the previous CDbgMngr's pointer to the current CDbgMngr
// }
//else
// pFirst = this;
Load();
//add to Sections/sub-section list...
if (CGenSexn::pFirstGen)
CGenSexn::pFirstGen->Add(pSection, pGroup);
else
CGenSexn::pFirstGen = new CGenSexn(pSection, pGroup);
if (0)
{
dbgpln("DbgMngr @%8x Nxt %8x : %s:%s", this, pNxt,sSection(), sGroup());
pCDbgMngr p = pFirst;
while(p)
{
dbgpln(" @%8x %8x: %s:%s",p, p->pNxt, p->sSection(), p->sGroup());
p = p->pNxt;
}
}
};
//--------------------------------------------------------------------------
/*#F: The Destructor .*/
CDbgMngr::~CDbgMngr()
{
if (0)
{
dbgpln("~DbgMngr @%8x %8x: %s:%s",this, pNxt, sSection(), sGroup());
pCDbgMngr p = pFirst;
while(p)
{
dbgpln(" @%8x %8x: %s:%s",p, p->pNxt, p->sSection(), p->sGroup());
p = p->pNxt;
}
}
Items.Clear();// ensure that linked list assigned to sGroup is clear of all items
// append dbgmngr in list or create list
StartupLock.Lock();
ASSERT(pFirst!=NULL);
if (pFirst==this) // Unlink this Object
pFirst=pNxt;
else
{
pCDbgMngr p = pFirst;
while(p && (p->pNxt!=this))
p = p->pNxt;
if (p)
p->pNxt=pNxt;
else
DoBreak();
//while(p && _CrtIsValidPointer(p, sizeof(CDbgMngr), True) && (p->pNxt!=this))
// p = p->pNxt;
//if (p && _CrtIsValidPointer(p, sizeof(CDbgMngr), True))
// p->pNxt=pNxt;
}
StartupLock.Unlock();
}
//--------------------------------------------------------------------------
void CDbgMngr::StartUp()
{
bStarted=1;
LoadAll();
};
//--------------------------------------------------------------------------
void CDbgMngr::ShutDown()
{
bStarted=0;
delete CGenSexn::pFirstGen;
CGenSexn::pFirstGen=NULL;
};
//--------------------------------------------------------------------------
/*#f:Places debugging-enabled Items in a linked list, provided that the file and group name
exists and the group is enabled to produce debug information ( bOn != 0)*/
void CDbgMngr::Load()
{
if (!bStarted)
return;
struct _stat buffer;
int r = _stat( DbgMngrFilename(), &buffer );
if(!r)
{
bOn=0;
Items.Clear();
char Buff[1024]; // preferred method but GetPrivateProfileString !convert char Buff(*)[1024] to char*
// thus needing &Buff[0] ie point to 1st char of limited array of char ie sim to a pointer
// note type casting (char *)&Buff would also have worke
//thus independent of ctual size
GetPrivateProfileString(sSection(), sGroup(), "xXxX", &Buff[0], sizeof(Buff), DbgMngrFilename());
if (strcmp(Buff, "xXxX")!=0)
{
Strng s = Buff;// used only to break out tokens from Buff
s.Trim(" ");
Strng Tok; // used to manipulate token
Tok = s.StrTok(",",True);
Tok.Trim(" ");// trim any trailing spaces from token
// should have isolated bOn
bOn = atol(Tok.Length()> 0 ? Tok.Str() : "0");// 0 if this cannot be done
Tok = s.StrTok(",");// break out next token up to nxt ','
if (bOn)
while( Tok.Length()>0)
{
Tok.Trim(" ");// trim off any leading/trailing spaces
Strng inWaiting = Tok;
pchar t = Tok();//.Buff;
t[1]='\0';// separate the yes/no from rest of sentence
if(!(strcmp(t,"0")))
{
Tok = s.StrTok(",");// break out next token up to nxt ','
continue;// dont add to list of items if switched off
}
else
Items.Append(inWaiting());// append whole token is not preceded by digit
Tok = s.StrTok(",");// break out next token up to nxt ','
}
}
//if (bOn)
// dbgpln("CDbgMngr %s:%s", sSection()!=NULL ? sSection() : "?", sGroup()!=NULL ? sGroup() : "?");
}
else
{ // file does not exist ( -1)
} // therefore do nothing
}
//--------------------------------------------------------------------------
/*#F: Only when the DbgMngrFile is updated or modified, does it cycle through the linked
list of CDbgMngrs, loading each in turn*/
void CDbgMngr::LoadAll()
{
if (!bStarted)
return;
//SetRootDirectory("c:\\syscad71");
#if BLDDEPENDENTFILES
Strng NewDbgMngrFilename(MakeDbgFileName("Ini"));
#else
Strng NewDbgMngrFilename(TemporaryFiles(), "Scd_Dbg.ini");
#endif
flag ForceLoad=_stricmp(NewDbgMngrFilename(), DbgMngrFilename())!=0;
struct _stat FileTime; //if used an unallocated pointer memory would be unstable
long CurrentFileTime = 0;
if ((_stat( DbgMngrFilename(), &FileTime )) == 0) // if file info obtained ie file exists
CurrentFileTime = FileTime.st_mtime;
if (CurrentFileTime != LastFileTime || ForceLoad) // if file recently updated DO
{
if (ForceLoad)
DbgMngrFilename=NewDbgMngrFilename;
StartupLock.Lock();
pCDbgMngr pArb;
if(pFirst)
{
pFirst->Load();
pArb=pFirst->pNxt;
while(pArb)
{
pArb->Load();
pArb= pArb->pNxt;
};
};
StartupLock.Unlock();
LastFileTime = CurrentFileTime;
};
};
//--------------------------------------------------------------------------
/*#F: When the size of the Dbg-File is greater than MaxFileSize( in KiloBytes )
then it is deleted. PercentRemaining - determines how much of the most
recent data sent to the debug file, remains after the deletion.
This an interger value specifing the percentage that is to be saved
from 0 - 50, the default is 0 ie a complete deletion. A number greater than 50 becomes 50 %.*/
void CDbgMngr::ChkFileSize(long MaxFileSize, long PercentRemaining)
{
if (!dbgtestfileopen())
return;
if (!bStarted)
return;
if (PercentRemaining < 0)
PercentRemaining = 0;
if (PercentRemaining > 50)
PercentRemaining = 50;
float percentage = (float)PercentRemaining / 100;
long actualFileSize = MaxFileSize * 1024;
long remainder = 0;
//SetRootDirectory("c:\\syscad71");
//struct _stat dbg_stats;
// Strng test = TemporaryFiles();
// if (test.Length()>0)
// if (test[test.Length()-1] != '\\')
// test += "\\";
// test += "Scd_Dbg.Txt";
// //dbgopen(test());
// int r = _stat( test(), &dbg_stats );
// long qwerty = dbg_stats.st_size;
// if (r==0 && dbg_stats.st_size >= actualFileSize)
long filesize=GetFileSize(dbgfile(), NULL);
// long qwerty = dbg_stats.st_size;
if (filesize >= actualFileSize)
{
float rem = percentage * actualFileSize;
remainder = (long)rem;
dbgfiletrunc(remainder);
LogNote("DbgMngr", 0, "Debug file truncated");
}
};
#endif
//--------------------------------------------------------------------------
| [
"[email protected]",
"[email protected]"
] | [
[
[
1,
128
],
[
130,
261
],
[
264,
424
],
[
426,
426
],
[
428,
428
],
[
430,
501
]
],
[
[
129,
129
],
[
262,
263
],
[
425,
425
],
[
427,
427
],
[
429,
429
]
]
] |
5fc486adfb6799b079019f10d31c299f4d023d02 | e52b0e0e87fbeb76edd0f11a7e1b03d25027932e | /src/Input.cpp | 9314c20a7d2fa3762d121601086953138d4345e1 | [] | no_license | zerotri/Maxwell_Game_old | d9aaa4c38ee1b99fe9ddb6f777737229dc6eebeb | da7a02ff25697777efe285973e5cecba14154b6c | refs/heads/master | 2021-01-25T05:22:45.278629 | 2008-02-07T03:11:01 | 2008-02-07T03:11:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,106 | cpp | #include "Input.h"
#define INPUT_LOOP_ITERATOR(funcname, ...)\
for(;vInputIterator!= vInputHandlers.end();vInputIterator++)\
{\
if((*vInputIterator)==NULL)\
continue;\
(*vInputIterator)->funcname(__VA_ARGS__);\
}
Input::Input()
{
vInputHandlers.reserve(8);
msgCount = 0;
}
Input::~Input()
{
std::vector<InputHandler*>::iterator vInputIterator = vInputHandlers.begin();
INPUT_LOOP_ITERATOR(Destroy);
vInputHandlers.clear();
}
void Input::Query()
{
if(!api)
return;
InputEvent evt;
evt.type = InputEvent::Evt_None;
std::vector<InputHandler*>::iterator vInputIterator;
while(api->Input_GetEvent(&evt))
{
msgCount++;
vInputIterator = vInputHandlers.begin();
switch(evt.type)
{
case InputEvent::Evt_KeyPress:
INPUT_LOOP_ITERATOR(onKeyPress,
evt.key.keyboard_key,
evt.key.keyboard_flag,
evt.key.keyboard_char);
break;
case InputEvent::Evt_KeyRelease:
INPUT_LOOP_ITERATOR(onKeyRelease,
evt.key.keyboard_key,
evt.key.keyboard_flag,
evt.key.keyboard_char);
break;
case InputEvent::Evt_MousePress:
INPUT_LOOP_ITERATOR(onMousePress,
evt.mouse.button,
evt.mouse.x,
evt.mouse.y);
break;
case InputEvent::Evt_MouseRelease:
INPUT_LOOP_ITERATOR(onMouseRelease,
evt.mouse.button,
evt.mouse.x,
evt.mouse.y);
break;
case InputEvent::Evt_MouseWheel:
INPUT_LOOP_ITERATOR(onMouseWheel,
evt.mouse.degrees,
evt.mouse.x,
evt.mouse.y);
break;
case InputEvent::Evt_MouseMove:
INPUT_LOOP_ITERATOR(onMouseMove,
evt.mouse.x,
evt.mouse.y);
break;
default:
break;
}
}
}
bool Input::GetKeyState(unsigned char key)
{
return api->Input_GetKeyState(key);
}
void Input::AddInputHandler(InputHandler* newInput)
{
if(newInput == NULL)
return;
vInputHandlers.push_back(newInput);
}
int Input::GetMsgCount()
{
return msgCount;
}
void Input::SetAPI(API_Base* _api)
{
api = _api;
}
| [
"[email protected]"
] | [
[
[
1,
92
]
]
] |
6eda48e5acc4c4bf37a63ae3599242100004951b | 2b32433353652d705e5558e7c2d5de8b9fbf8fc3 | /tp7/BIN/9372/Длинная арифметика/Теория/3/long_src/fhtmul.cpp | 596dfb500b8c1399d3934b2b62ab877c6aeb2283 | [] | no_license | smarthaert/d-edit | 70865143db2946dd29a4ff52cb36e85d18965be3 | 41d069236748c6e77a5a457280846a300d38e080 | refs/heads/master | 2020-04-23T12:21:51.180517 | 2011-01-30T00:37:18 | 2011-01-30T00:37:18 | 35,532,200 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,402 | cpp | #include <cmath>
#include "general.h"
#include "BigInt.h"
real MaxError;
real *LongNum1=NULL, *LongNum2=NULL;
extern void FHT_F(real*, ulong);
extern void FHT_T(real*, ulong);
extern void CreateSineTable(ulong);
void CarryNormalize(real *Convolution, ulong Len, BigInt &C) {
real inv = 0.5 / Len;
real RawPyramid, Pyramid, PyramidError, Carry = 0;
ulong x;
ushort *c = C.Coef;
if ( Len > C.SizeMax ) Len=C.SizeMax;
MaxError = 0;
for (x = 0; x < Len; x++) {
RawPyramid = Convolution[x] * inv + Carry;
Pyramid = floor(RawPyramid + 0.5);
PyramidError = fabs(RawPyramid - Pyramid);
if (PyramidError > MaxError)
MaxError = PyramidError;
Carry = floor(Pyramid / BASE);
c[x] = (short)(Pyramid - Carry * BASE);
}
do { x--; } while (c[x]==0);
C.Size = x+1;
}
void FHTConvolution(real *LongNum1, const real *LongNum2, ulong Len) {
ulong Step=2, Step2=Step*2;
ulong x,y;
LongNum1[0] = LongNum1[0] * 2.0 * LongNum2[0];
LongNum1[1] = LongNum1[1] * 2.0 * LongNum2[1];
while (Step < Len) {
for (x=Step,y=Step2-1;x<Step2;x+=2,y-=2) {
real h1p,h1m,h2p,h2m;
real s1,d1;
h1p=LongNum1[x];
h1m=LongNum1[y];
s1=h1p+h1m;
d1=h1p-h1m;
h2p=LongNum2[x];
h2m=LongNum2[y];
LongNum1[x]=(h2p*s1+h2m*d1);
LongNum1[y]=(h2m*s1-h2p*d1);
}
Step*=2;
Step2*=2;
}
}
void FastMul(const BigInt &A,const BigInt &B, BigInt &C) {
ulong Len = 2;
while ( Len < A.Size + B.Size ) Len *=2;
if ( Len < 40 ) {
BigInt Atmp(A), Btmp(B);
Mul(Atmp,Btmp,C);
return;
}
ulong x;
const ushort *a=A.Coef, *b=B.Coef;
for (x = 0; x < A.Size; x++) LongNum1[x] = a[x];
for (; x < Len; x++) LongNum1[x] = 0.0;
FHT_F(LongNum1,Len);
if (a == b) {
FHTConvolution(LongNum1,LongNum1,Len);
} else {
for (x = 0; x < B.Size; x++) LongNum2[x] = b[x];
for (; x < Len; x++) LongNum2[x] = 0.0;
FHT_F(LongNum2,Len);
FHTConvolution(LongNum1,LongNum2,Len);
}
FHT_T(LongNum1,Len);
CarryNormalize(LongNum1, Len, C);
}
void FastMulInit(ulong Len) {
ulong MaxLen;
if ((Len & -Len) == Len)
MaxLen = Len;
else {
MaxLen = 2;
while (MaxLen < Len) MaxLen*=2;
}
LongNum1 = new real[MaxLen];
LongNum2 = new real[MaxLen];
CreateSineTable(MaxLen);
}
void FastMulDeInit() {
delete LongNum1;
delete LongNum2;
}
| [
"[email protected]"
] | [
[
[
1,
121
]
]
] |
4d16c5f362de4dc663d07211834d7962a799a1e9 | 2b0e9ad72bb37219446e14c3e69bfda6d226218a | /tests/unit/Test_Threading/SyncManyToOne.cpp | 49ce99a852b62e08afa9ef0778337c97e0ef547f | [
"MIT"
] | permissive | svn2github/cpp-events | 5a672372e564f14ffd776e7d8f6fcb5a37eb307a | 572af0c42ceb7cbd3ee27d9c6e65412896e88c85 | refs/heads/master | 2020-05-17T01:15:05.179670 | 2011-07-28T15:33:46 | 2011-07-28T15:33:46 | 30,379,625 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,593 | cpp | // Copyright (c) 2010 Nickolas Pohilets
//
// This file is a part of the unit test suit for the CppEvents library.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include <Cpp/Events.hpp>
#include <Cpp/Threading/Thread.hpp>
#include <Cpp/Utils/Random.hpp>
#include <gtest/gtest.h>
namespace UnitTests {
namespace Threading {
namespace SyncManyToOne {
//------------------------------------------------------------------------------
class EventSender;
//------------------------------------------------------------------------------
class EventHandler
{
public:
Cpp::ConnectionScope scope;
void onEvent(EventSender * sender);
};
//------------------------------------------------------------------------------
class EventSender
{
public:
EventSender()
{
connectionCount_ = 0;
callbackCounter_ = 0;
}
Cpp::EventRef<> theEvent() { return theEvent_; }
void recieverCallback()
{
--callbackCounter_;
}
void connect(EventHandler * handler)
{
++connectionCount_;
handler->scope.connect(this->theEvent(), handler, &EventHandler::onEvent, this);
}
void disconnect(EventHandler * handler)
{
bool ok = handler->scope.disconnectOne(this->theEvent());
if(ok) --connectionCount_;
}
void fire()
{
callbackCounter_ = connectionCount_;
theEvent_.fire();
ASSERT_EQ(0, callbackCounter_);
}
private:
Cpp::Event<> theEvent_;
int connectionCount_;
int callbackCounter_;
};
//------------------------------------------------------------------------------
void EventHandler::onEvent(EventSender * sender)
{
sender->recieverCallback();
}
//------------------------------------------------------------------------------
class SenderThread : public Cpp::Thread
{
public:
void start(EventHandler * handler, unsigned long z, unsigned long w, bool isMain)
{
handler_ = handler;
isMain_ = isMain;
m_z = z; m_w = w;
Thread::start();
}
protected:
virtual void run()
{
Cpp::Events::ThreadInit threadInit;
EventSender sender;
Cpp::WikiRandom rnd(m_z, m_w);
for(int i=0; i<100; ++i)
{
if(isMain_)
{
std::cout << i << "% " << std::flush;
if((i % 10) == 9) std::cout << std::endl;
}
for(int j=0; j<500; ++j)
{
unsigned long k = rnd.generate() % 10;
if(k < 4) // 0,1,2,3
sender.connect(handler_);
else if(k < 7) // 4,5,6
sender.disconnect(handler_);
else // 7,8,9
sender.fire();
}
}
}
private:
EventHandler * handler_;
bool isMain_;
unsigned long m_z;
unsigned long m_w;
};
//------------------------------------------------------------------------------
/*
This test check synchronization in the ConnectionScope class.
*/
TEST(Test_Threading, SyncManyToOne)
{
static int const threadCount = 4;
SenderThread threads[threadCount];
EventHandler handler;
std::cout << "Running test in " << threadCount << " threads." << std::endl;
std::cout << "This may take up to several minutes, please wait..." << std::endl;
Cpp::WikiRandom rnd(1234, 5678);
unsigned long prevX = rnd.generate();
for(int i=0; i<threadCount; ++i)
{
unsigned long x = rnd.generate();
threads[i].start(&handler, prevX, x, (i==0));
prevX = x;
}
for(int i=0; i<threadCount; ++i)
{
threads[i].join();
}
std::cout << "Done!" << std::endl;
}
//------------------------------------------------------------------------------
} //namespace SyncManyToOne
} //namespace Threading
} //namespace UnitTests
| [
"pohilets@67599820-88c8-11de-9c77-2f49170b69f2"
] | [
[
[
1,
170
]
]
] |
a2bdfa42dabd10f74856e5a1543494f3e02e219f | 968aa9bac548662b49af4e2b873b61873ba6f680 | /imgtools/romtools/rofsbuild/fatimagegenerator.h | a627d9d52e5621dae8f8dec9d6a054788e3b0a89 | [] | no_license | anagovitsyn/oss.FCL.sftools.dev.build | b3401a1ee3fb3c8f3d5caae6e5018ad7851963f3 | f458a4ce83f74d603362fe6b71eaa647ccc62fee | refs/heads/master | 2021-12-11T09:37:34.633852 | 2010-12-01T08:05:36 | 2010-12-01T08:05:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,997 | h | /*
* Copyright (c) 2010 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".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description:
*
*/
#ifndef __FAT_IMAGE_GENERATER_HEADER__
#define __FAT_IMAGE_GENERATER_HEADER__
#include "fatdefines.h"
#include <iostream>
#include <list>
#include <fstream>
using namespace std ;
const unsigned int KBufferedIOBytes = 0x800000 ; // 8M
const unsigned int KMaxClusterBytes = 0x8000; // 32K
enum TSupportedFatType {
EFatUnknown = 0,
EFat16 = 1,
EFat32 = 2
};
class TFSNode;
class TFatCluster;
typedef list<TFatCluster*> PFatClusterList ;
typedef list<TFatCluster*>::iterator Interator ;
class TFatImgGenerator
{
public :
//The constructor ,
//a TFatImgGenerator is created and initialized,
//if the parameters breaks the FAT specification,
// then iType is set to EFatUnknown and thus
// IsValid return false
TFatImgGenerator(TSupportedFatType aType , ConfigurableFatAttributes& aAttr );
~TFatImgGenerator();
inline bool IsValid() const { return (EFatUnknown != iType);}
//Create the FAT image,
//If FAT image is not valid, or error accurs, return false
bool Execute(TFSNode* aRootDir , const char* aOutputFile);
protected :
void InitAsFat16(TUint32 aTotalSectors, TUint16 aBytsPerSec);
void InitAsFat32(TUint32 aTotalSectors, TUint16 aBytsPerSec);
bool PrepareClusters(TUint& aNextClusIndex,TFSNode* aNode);
TSupportedFatType iType ;
char* iFatTable ;
TUint iFatTableBytes ;
TUint iTotalClusters ;
TUint iBytsPerClus ;
TFATBootSector iBootSector ;
TFAT32BSExt iFat32Ext ;
TFATHeader iFatHeader ;
PFatClusterList iDataClusters ;
};
#endif
| [
"none@none",
"[email protected]"
] | [
[
[
1,
54
],
[
57,
70
]
],
[
[
55,
56
]
]
] |
6c03ce187fe10a885c1fd7e1b9ca8b95dfe45ccd | 7a310d01d1a4361fd06b40a74a2afc8ddc23b4d3 | /src/DonutSecurityZone.cpp | 1a814fdd70081f355f7b2be6545d1585bdd22bf4 | [] | 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 | 846 | cpp | /**
* @file DonutSecurityZone.cpp
* @brief クッキーの扱いに関するコマンドメッセージをハンドリングするクラス
*/
#include "stdafx.h"
#include "DonutSecurityZone.h"
#if defined USE_ATLDBGMEM
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
void CDonutSecurityZone::OnCookieAllowAll(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/)
{
SetGlobalCookiePref(0);
}
void CDonutSecurityZone::OnCookieAllowSameOrigin(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/)
{
SetGlobalCookiePref(1);
}
void CDonutSecurityZone::OnCookieDenyAll(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/)
{
SetGlobalCookiePref(2);
}
void CDonutSecurityZone::OnCookieCustom(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/)
{
SetGlobalCookiePref(3);
} | [
"[email protected]"
] | [
[
[
1,
33
]
]
] |
61ee548eed40d4c87de68abe1875456d32906803 | 25233569ca21bf93b0d54ca99027938d65dc09d5 | /SystemInfo.cpp | 8ca19dba40ca69c87f91ea0b21d8ec90ca1ca362 | [] | no_license | jugg/litestep-module-label | 6ede7ff5c80c25e1dc611d02ba5dc13559914ddc | a75ef94a56d68c2a928bde5bab60318e609b9a10 | refs/heads/master | 2021-01-18T09:20:42.000147 | 2004-10-07T12:28:00 | 2004-10-07T12:28:00 | null | 0 | 0 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 37,319 | cpp | #include "common.h"
#include <stdio.h>
#include "processor.h"
#include "SystemInfo.h"
#include "Label.h"
const int unitsDefault = 0;
const int unitsKB = 1;
const int unitsMB = 2;
const int unitsGB = 3;
const int unitsPercent = 4;
// enum Bus
#define BusType char
#define ISA 0
#define SMBus 1
#define VIA686Bus 2
#define DirectIO 3
// enum SMB
#define SMBType char
#define smtSMBIntel 0
#define smtSMBAMD 1
#define smtSMBALi 2
#define smtSMBNForce 3
#define smtSMBSIS 4
// enum Sensor Types
#define SensorType char
#define stUnknown 0
#define stTemperature 1
#define stVoltage 2
#define stFan 3
#define stMhz 4
#define stPercentage 5
typedef struct {
SensorType iType; // type of sensor
int Count; // number of sensor for that type
} SharedIndex;
typedef struct {
SensorType ssType; // type of sensor
unsigned char ssName[12]; // name of sensor
char sspadding1[3]; // padding of 3 byte
double ssCurrent; // current value
double ssLow; // lowest readout
double ssHigh; // highest readout
long ssCount; // total number of readout
char sspadding2[4]; // padding of 4 byte
long double ssTotal; // total amout of all readouts
char sspadding3[6]; // padding of 6 byte
double ssAlarm1; // temp & fan: high alarm; voltage: % off;
double ssAlarm2; // temp: low alarm
} SharedSensor;
typedef struct {
short siSMB_Base; // SMBus base address
BusType siSMB_Type; // SMBus/Isa bus used to access chip
SMBType siSMB_Code; // SMBus sub type, Intel, AMD or ALi
char siSMB_Addr; // Address of sensor chip on SMBus
unsigned char siSMB_Name[41]; // Nice name for SMBus
short siISA_Base; // ISA base address of sensor chip on ISA
int siChipType; // Chip nr, connects with Chipinfo.ini
char siVoltageSubType; // Subvoltage option selected
} SharedInfo;
typedef struct {
double sdVersion; // version number (example: 51090)
SharedIndex sdIndex[10]; // Sensor index
SharedSensor sdSensor[100]; // sensor info
SharedInfo sdInfo; // misc. info
unsigned char sdStart[41]; // start time
unsigned char sdCurrent[41]; // current time
unsigned char sdPath[256]; // MBM path
} mbmSharedData;
SystemInfo::SystemInfo()
{
WSADATA wd;
WSAStartup(0x0101, &wd);
usingCPU = false;
am = getLocaleInfo(LOCALE_S1159);
pm = getLocaleInfo(LOCALE_S2359);
shortWeekdays[0] = getLocaleInfo(LOCALE_SABBREVDAYNAME7);
shortWeekdays[1] = getLocaleInfo(LOCALE_SABBREVDAYNAME1);
shortWeekdays[2] = getLocaleInfo(LOCALE_SABBREVDAYNAME2);
shortWeekdays[3] = getLocaleInfo(LOCALE_SABBREVDAYNAME3);
shortWeekdays[4] = getLocaleInfo(LOCALE_SABBREVDAYNAME4);
shortWeekdays[5] = getLocaleInfo(LOCALE_SABBREVDAYNAME5);
shortWeekdays[6] = getLocaleInfo(LOCALE_SABBREVDAYNAME6);
weekdays[0] = getLocaleInfo(LOCALE_SDAYNAME7);
weekdays[1] = getLocaleInfo(LOCALE_SDAYNAME1);
weekdays[2] = getLocaleInfo(LOCALE_SDAYNAME2);
weekdays[3] = getLocaleInfo(LOCALE_SDAYNAME3);
weekdays[4] = getLocaleInfo(LOCALE_SDAYNAME4);
weekdays[5] = getLocaleInfo(LOCALE_SDAYNAME5);
weekdays[6] = getLocaleInfo(LOCALE_SDAYNAME6);
shortMonths[0] = getLocaleInfo(LOCALE_SABBREVMONTHNAME1);
shortMonths[1] = getLocaleInfo(LOCALE_SABBREVMONTHNAME2);
shortMonths[2] = getLocaleInfo(LOCALE_SABBREVMONTHNAME3);
shortMonths[3] = getLocaleInfo(LOCALE_SABBREVMONTHNAME4);
shortMonths[4] = getLocaleInfo(LOCALE_SABBREVMONTHNAME5);
shortMonths[5] = getLocaleInfo(LOCALE_SABBREVMONTHNAME6);
shortMonths[6] = getLocaleInfo(LOCALE_SABBREVMONTHNAME7);
shortMonths[7] = getLocaleInfo(LOCALE_SABBREVMONTHNAME8);
shortMonths[8] = getLocaleInfo(LOCALE_SABBREVMONTHNAME9);
shortMonths[9] = getLocaleInfo(LOCALE_SABBREVMONTHNAME10);
shortMonths[10] = getLocaleInfo(LOCALE_SABBREVMONTHNAME11);
shortMonths[11] = getLocaleInfo(LOCALE_SABBREVMONTHNAME12);
months[0] = getLocaleInfo(LOCALE_SMONTHNAME1);
months[1] = getLocaleInfo(LOCALE_SMONTHNAME2);
months[2] = getLocaleInfo(LOCALE_SMONTHNAME3);
months[3] = getLocaleInfo(LOCALE_SMONTHNAME4);
months[4] = getLocaleInfo(LOCALE_SMONTHNAME5);
months[5] = getLocaleInfo(LOCALE_SMONTHNAME6);
months[6] = getLocaleInfo(LOCALE_SMONTHNAME7);
months[7] = getLocaleInfo(LOCALE_SMONTHNAME8);
months[8] = getLocaleInfo(LOCALE_SMONTHNAME9);
months[9] = getLocaleInfo(LOCALE_SMONTHNAME10);
months[10] = getLocaleInfo(LOCALE_SMONTHNAME11);
months[11] = getLocaleInfo(LOCALE_SMONTHNAME12);
}
SystemInfo::~SystemInfo()
{
if(usingCPU)
endProcessorStatistics();
WSACleanup();
delete[] am;
delete[] pm;
int i;
for(i = 0; i < 7; i++)
{
delete[] shortWeekdays[i];
delete[] weekdays[i];
}
for(i = 0; i < 12; i++)
{
delete[] shortMonths[i];
delete[] months[i];
}
}
string SystemInfo::processLabelText(const string &text, Label *label, boolean *dynamic)
{
string output;
int length = text.length();
int i = 0;
if(dynamic) *dynamic = false;
while(i < length)
{
if(text[i] == '[')
{
i++;
if(i < length && text[i] == '[')
{
output.append(1, '[');
i++;
continue;
}
output.append(process(text, i, length, label, dynamic));
if(i >= length || text[i++] != ']')
{
output = "[syntax error]";
break;
}
/*
string code;
while(i < length && text[i] != ']')
{
code.append(1, text[i]);
i++;
}
int index = 0;
output.append(process(code, index, code.length(), dynamic));
*/
// if(i < length) i++;
continue;
}
else if(text[i] == ']')
{
i++;
if(i < length && text[i] == ']')
{
output.append(1, ']');
i++;
continue;
}
}
else if(text[i] == '\\')
{
char ch;
i++;
if(i < length && text[i] == 'n')
{
ch = '\n';
}
else
{
ch = text[i];
}
output.append(1, ch);
i++;
continue;
}
output.append(1, text[i++]);
}
return output;
}
string SystemInfo::evaluateFunction(const string &functionName, const vector<string> &arguments, Label *label, boolean *dynamic = 0)
{
string name = lowerCase(functionName);
if(name == "activetask")
return getActiveTask(dynamic);
else if(name == "battery")
return getBattery(dynamic);
else if(name == "computername")
return getComputerName(dynamic);
else if(name == "cpu")
return getCPU(dynamic);
else if(name == "date")
return getDate(arguments, dynamic);
else if(name == "diskavailable" && arguments.size() >= 1)
return getDiskAvailable(arguments, dynamic);
else if(name == "diskinuse" && arguments.size() >= 1)
return getDiskInUse(arguments, dynamic);
else if(name == "disktotal" && arguments.size() >= 1)
return getDiskTotal(arguments, dynamic);
else if(name == "hostname")
return getHostName(dynamic);
else if(name == "ip")
return getIP(arguments, dynamic);
else if(name == "itime")
return getInternetTime(dynamic);
else if(name == "lsvar" && arguments.size() >= 1)
return getLSVar(arguments[0], dynamic);
else if(name == "mbmtemperature")
return getMBMData(stTemperature, arguments, dynamic, label->bUseFahrenheit);
else if(name == "mbmcpuusage")
return getMBMData(stPercentage, arguments, dynamic, label->bUseFahrenheit);
else if(name == "mbmfanspeed")
return getMBMData(stFan, arguments, dynamic, label->bUseFahrenheit);
else if(name == "mbmvoltage")
return getMBMData(stVoltage, arguments, dynamic, label->bUseFahrenheit);
else if(name == "memavailable")
return getMemAvailable(arguments, dynamic);
else if(name == "meminuse")
return getMemInUse(arguments, dynamic);
else if(name == "memtotal")
return getMemTotal(arguments, dynamic);
else if(name == "os")
return getOS(dynamic);
else if(name == "powersource")
return getPowerSource(arguments, dynamic);
else if(name == "randomline" && arguments.size() >= 1)
return getRandomLine(arguments[0], dynamic);
else if(name == "swapavailable")
return getSwapAvailable(arguments, dynamic);
else if(name == "swapinuse")
return getSwapInUse(arguments, dynamic);
else if(name == "swaptotal")
return getSwapTotal(arguments, dynamic);
else if(name == "time")
return getTime(arguments, dynamic);
else if(name == "uptime")
return getUptime(arguments, dynamic);
else if(name == "username")
return getUserName(dynamic);
else if(name == "winampsong")
return getWinampSong(dynamic);
else if(name == "winamptime")
return getWinampTime(dynamic);
else if(name == "winampremaintime")
return getWinampRemainTime(dynamic);
else if(name == "winamptotaltime")
return getWinampTotalTime(dynamic);
else if(name == "winampstatus")
return getWinampStatus(dynamic);
else if(name == "windowtitle" && arguments.size() >= 1)
return getWindowTitle(arguments[0], dynamic);
else if(name == "hideifempty" && arguments.size() >= 1)
return hideIfEmpty(arguments[0], label, dynamic);
else if(name == "after" && arguments.size() == 2)
return after(arguments[0], arguments[1]);
else if(name == "afterlast" && arguments.size() == 2)
return afterLast(arguments[0], arguments[1]);
else if(name == "before" && arguments.size() == 2)
return before(arguments[0], arguments[1]);
else if(name == "beforelast" && arguments.size() == 2)
return beforeLast(arguments[0], arguments[1]);
else if(name == "between" && arguments.size() == 3)
return between(arguments[0], arguments[1], arguments[2]);
else if(name == "capitalize" && arguments.size() == 1)
return capitalize(arguments[0]);
else if(name == "lowercase" && arguments.size() == 1)
return lowerCase(arguments[0]);
else if(name == "trim" && arguments.size() == 1)
return trim(arguments[0]);
else if(name == "uppercase" && arguments.size() == 1)
return upperCase(arguments[0]);
else if(name == "kb") // units hack
return "1";
else if(name == "mb")
return "2";
else if(name == "gb")
return "3";
else if(name == "%")
return "4";
else if(name == "semicolon") // hack to avoid escaping ;'s
return ";";
*dynamic = false;
return "[?]";
}
string SystemInfo::process(const string &text, int &i, int length, Label *label, boolean *dynamic = 0)
{
// skip whitespace
while(i < length && isspace(text[i]))
i++;
// is it a string literal?
if(i < length && (text[i] == '\"' || text[i] == '\''))
{
string literalValue;
char quoteChar = text[i++];
while(i < length && text[i] != quoteChar)
literalValue.append(1, text[i++]);
if(i < length) i++;
return literalValue;
}
else if(i < length && isdigit(text[i])) // is it a numeric constant?
{
string number;
while(i < length && isdigit(text[i]))
number.append(1, text[i++]);
return number;
}
else // otherwise its a name
{
string name;
vector<string> arguments;
// retrieve name
while(i < length && (isalnum(text[i]) || text[i] == '-' || text[i] == '%'))
name.append(1, text[i++]);
// skip whitespace
while(i < length && isspace(text[i]))
i++;
// has argument list?
if(i < length && text[i] == '(')
{
// process each argument
do
{
i++;
// call recursively to handle
arguments.push_back(process(text, i, length, label, dynamic));
// skip whitespace
while(i < length && isspace(text[i]))
i++;
}
while(i < length && text[i] == ',');
// must be a closing parenthesis
if(i >= length || text[i++] != ')')
return "[error]";
}
// get it
return evaluateFunction(name, arguments, label, dynamic);
}
}
string SystemInfo::getActiveTask(boolean *dynamic)
{
char buffer[256] = { 0 };
HWND activeTask = GetForegroundWindow();
if(IsAppWindow(activeTask))
GetWindowText(activeTask, buffer, 256);
if(dynamic) *dynamic = true;
return string(buffer);
}
string SystemInfo::getComputerName(boolean *dynamic)
{
char buffer[32];
unsigned long bufferLen = 32;
GetComputerName(buffer, &bufferLen);
return string(buffer);
}
string SystemInfo::getCPU(boolean *dynamic)
{
if(!usingCPU)
{
startProcessorStatistics();
usingCPU = true;
}
char buffer[16];
StringCchPrintf(buffer, 16, "%d%%", getProcessorUsage());
if(dynamic) *dynamic = true;
return string(buffer);
}
string SystemInfo::getDate(const vector<string> &arguments, boolean *dynamic)
{
if(dynamic) *dynamic = true;
SYSTEMTIME st;
getLocalizedTime(&st, arguments.size() >= 2 ? arguments[1] : "");
if(arguments.size() >= 1)
{
// SYSTEMTIME st;
// GetLocalTime(&st);
return formatDateTime(arguments[0], st, 0);
}
else
{
char buffer[64];
GetDateFormat(LOCALE_USER_DEFAULT, DATE_LONGDATE, &st, 0, buffer, 64);
return string(buffer);
}
}
string SystemInfo::getInternetTime(boolean *dynamic)
{
if(dynamic) *dynamic = true;
SYSTEMTIME st;
GetSystemTime(&st);
int seconds = ((((st.wHour + 1) % 24) * 60) + st.wMinute) * 60 + st.wSecond;
int beats = (1000 * seconds) / 86400;
char output[8];
StringCchPrintf(output, 8, "@%03d", beats);
return string(output);
}
string SystemInfo::getDiskAvailable(const vector<string> &arguments, boolean *dynamic)
{
largeInt freeBytes;
largeInt totalBytes;
int units = unitsDefault;
if(arguments.size() >= 2)
units = atoi(arguments[1].c_str());
getDiskFreeSpace(arguments[0], freeBytes, totalBytes);
if(dynamic) *dynamic = true;
return formatByteSize(freeBytes, totalBytes, units);
}
string SystemInfo::getDiskInUse(const vector<string> &arguments, boolean *dynamic)
{
largeInt freeBytes;
largeInt totalBytes;
int units = unitsDefault;
if(arguments.size() >= 2)
units = atoi(arguments[1].c_str());
getDiskFreeSpace(arguments[0], freeBytes, totalBytes);
if(dynamic) *dynamic = true;
return formatByteSize(totalBytes - freeBytes, totalBytes, units);
}
string SystemInfo::getDiskTotal(const vector<string> &arguments, boolean *dynamic)
{
largeInt freeBytes;
largeInt totalBytes;
int units = unitsDefault;
if(arguments.size() >= 2)
units = atoi(arguments[1].c_str());
getDiskFreeSpace(arguments[0], freeBytes, totalBytes);
if(dynamic) *dynamic = true;
return formatByteSize(totalBytes, totalBytes, units);
}
string SystemInfo::getHostName(boolean *dynamic)
{
char hostName[256];
gethostname(hostName, 256);
hostent *hostInfo = gethostbyname(hostName);
if(hostInfo)
return string(hostInfo->h_name);
return "";
}
string SystemInfo::getIP(const vector<string> &arguments, boolean *dynamic)
{
char hostName[256];
gethostname(hostName, 256);
hostent *hostInfo = gethostbyname(hostName);
if(!hostInfo)
return "";
int numIPs = 0;
while(hostInfo->h_addr_list[numIPs])
numIPs++;
if(numIPs == 0)
return "";
int n = 0;
int value = 0;
if(arguments.size() >= 1)
n = atoi(arguments[0].c_str()) - 1;
if(n < 0) n = 0;
if(n >= numIPs) n = numIPs - 1;
return string(inet_ntoa(*((in_addr *) hostInfo->h_addr_list[n])));
}
string SystemInfo::getLSVar(const string &name, boolean *dynamic)
{
// LSGetVariable pops up an error box if the variable
// is undefined; making it useless. I'm just gonna
// use VarExpansion for better backwards compatability
if(dynamic) *dynamic = true;
if(GetRCBool(name.c_str(), TRUE))
{
TCHAR strVarRef[64];
StringCchPrintf(strVarRef, 64, "$%s$", name.c_str());
TCHAR strResult[256];
VarExpansion(strResult, strVarRef);
return string(strResult);
}
else
{
return "";
}
}
string SystemInfo::getMemAvailable(const vector<string> &arguments, boolean *dynamic)
{
int units = unitsDefault;
if(arguments.size() >= 1)
units = atoi(arguments[0].c_str());
MEMORYSTATUS ms;
ms.dwLength = sizeof(MEMORYSTATUS);
GlobalMemoryStatus(&ms);
if(dynamic) *dynamic = true;
return formatByteSize(ms.dwAvailPhys, ms.dwTotalPhys, units);
}
string SystemInfo::getMemInUse(const vector<string> &arguments, boolean *dynamic)
{
int units = unitsDefault;
if(arguments.size() >= 1)
units = atoi(arguments[0].c_str());
MEMORYSTATUS ms;
ms.dwLength = sizeof(MEMORYSTATUS);
GlobalMemoryStatus(&ms);
if(dynamic) *dynamic = true;
return formatByteSize(ms.dwTotalPhys - ms.dwAvailPhys, ms.dwTotalPhys, units);
}
string SystemInfo::getMemTotal(const vector<string> &arguments, boolean *dynamic)
{
int units = unitsDefault;
if(arguments.size() >= 1)
units = atoi(arguments[0].c_str());
MEMORYSTATUS ms;
ms.dwLength = sizeof(MEMORYSTATUS);
GlobalMemoryStatus(&ms);
if(dynamic) *dynamic = true;
return formatByteSize(ms.dwTotalPhys, ms.dwTotalPhys, units);
}
string SystemInfo::getOS(boolean *dynamic)
{
if(IsOS(OS_ME))
return "Windows ME";
if(IsOS(OS_98))
return "Windows 98";
if(IsOS(OS_95))
return "Windows 95";
if(IsOS(OS_XP))
return "Windows XP";
if(IsOS(OS_2K))
return "Windows 2000";
if(IsOS(OS_NT4))
return "Windows NT4";
return "unknown OS";
}
string SystemInfo::getRandomLine(const string &file, boolean *dynamic)
{
FILE *fp = fopen(file.c_str(), "r");
int lineCount = 0;
char lineBuffer[1024];
if(fp)
{
while(fgets(lineBuffer, 1024, fp))
{
if(lineBuffer[0] != '\n' && lineBuffer[0] != 0)
lineCount++;
}
srand(GetTickCount());
int line = rand() % lineCount;
lineCount = 0;
fseek(fp, 0, SEEK_SET);
while(fgets(lineBuffer, 1024, fp))
{
if(lineBuffer[0] != '\n' && lineBuffer[0] != 0)
{
if(lineCount == line)
{
int length = strlen(lineBuffer);
if(lineBuffer[length - 1] == '\n') lineBuffer[length - 1] = 0;
fclose(fp);
return string(lineBuffer);
}
lineCount++;
}
}
fclose(fp);
return "[error]";
}
return "[Could not open file!]";
}
string SystemInfo::getSwapAvailable(const vector<string> &arguments, boolean *dynamic)
{
int units = unitsDefault;
if(arguments.size() >= 1)
units = atoi(arguments[0].c_str());
MEMORYSTATUS ms;
ms.dwLength = sizeof(MEMORYSTATUS);
GlobalMemoryStatus(&ms);
if(dynamic) *dynamic = true;
return formatByteSize(ms.dwAvailPageFile, ms.dwTotalPageFile, units);
}
string SystemInfo::getSwapInUse(const vector<string> &arguments, boolean *dynamic)
{
int units = unitsDefault;
if(arguments.size() >= 1)
units = atoi(arguments[0].c_str());
MEMORYSTATUS ms;
ms.dwLength = sizeof(MEMORYSTATUS);
GlobalMemoryStatus(&ms);
if(dynamic) *dynamic = true;
return formatByteSize(ms.dwTotalPageFile - ms.dwAvailPageFile, ms.dwTotalPageFile, units);
}
string SystemInfo::getSwapTotal(const vector<string> &arguments, boolean *dynamic)
{
int units = unitsDefault;
if(arguments.size() >= 1)
units = atoi(arguments[0].c_str());
MEMORYSTATUS ms;
ms.dwLength = sizeof(MEMORYSTATUS);
GlobalMemoryStatus(&ms);
if(dynamic) *dynamic = true;
return formatByteSize(ms.dwTotalPageFile, ms.dwTotalPageFile, units);
}
string SystemInfo::getTime(const vector<string> &arguments, boolean *dynamic)
{
if(dynamic) *dynamic = true;
SYSTEMTIME st;
getLocalizedTime(&st, arguments.size() >= 2 ? arguments[1] : "");
if(arguments.size() >= 1)
{
// SYSTEMTIME st;
// GetLocalTime(&st);
return formatDateTime(arguments[0], st, 0);
}
else
{
char buffer[64];
GetTimeFormat(LOCALE_USER_DEFAULT, TIME_NOSECONDS, &st, 0, buffer, 64);
return string(buffer);
}
}
string SystemInfo::getUptime(const vector<string> &arguments, boolean *dynamic)
{
if(dynamic) *dynamic = true;
unsigned int ms = GetTickCount();
unsigned int seconds = ms / 1000;
ms %= 1000;
unsigned int minutes = seconds / 60;
seconds %= 60;
unsigned int hours = minutes / 60;
minutes %= 60;
unsigned int days = hours / 24;
hours %= 24;
SYSTEMTIME st;
st.wMonth = -1;
st.wDay = days;
st.wDayOfWeek = -1;
st.wYear = 0;
st.wHour = hours;
st.wMinute = minutes;
st.wSecond = seconds;
st.wMilliseconds = ms;
string format = (arguments.size() >= 1) ? arguments[0] : "d days hh:nn:ss";
return formatDateTime(format, st, 1);
}
string SystemInfo::getUserName(boolean *dynamic)
{
char buffer[32];
unsigned long bufferLen = 32;
GetUserName(buffer, &bufferLen);
return string(buffer);
}
string SystemInfo::getWinampSong(boolean *dynamic)
{
if(dynamic) *dynamic = true;
HWND hWinamp = FindWindow("Winamp v1.x", 0);
if(!hWinamp) return "";
char buffer[256];
GetWindowText(hWinamp, buffer, 256);
if(strstr(buffer, " - Winamp") == 0)
return "";
return trim(between(string(buffer), ".", "-"));
}
string SystemInfo::getWinampTime(boolean *dynamic)
{
if(dynamic) *dynamic = true;
HWND hWinamp = FindWindow("Winamp v1.x", 0);
if(!hWinamp) return "0:00";
int seconds = SendMessage(hWinamp, WM_USER, 0, 105) / 1000;
int minutes = seconds / 60;
seconds %= 60;
char buffer[32];
StringCchPrintf(buffer, 32, "%d:%02d", minutes, seconds);
return string(buffer);
}
string SystemInfo::getWinampRemainTime(boolean *dynamic)
{
if(dynamic) *dynamic = true;
HWND hWinamp = FindWindow("Winamp v1.x", 0);
if(!hWinamp) return "0:00";
int seconds = SendMessage(hWinamp, WM_USER, 1, 105) - SendMessage(hWinamp, WM_USER, 0, 105) / 1000;
int minutes = seconds / 60;
seconds %= 60;
char buffer[32];
StringCchPrintf(buffer, 32, "%d:%02d", minutes, seconds);
return string(buffer);
}
string SystemInfo::getWinampTotalTime(boolean *dynamic)
{
if(dynamic) *dynamic = true;
HWND hWinamp = FindWindow("Winamp v1.x", 0);
if(!hWinamp) return "0:00";
int seconds = SendMessage(hWinamp, WM_USER, 1, 105);
int minutes = seconds / 60;
seconds %= 60;
char buffer[32];
StringCchPrintf(buffer, 32, "%d:%02d", minutes, seconds);
return string(buffer);
}
string SystemInfo::getWinampStatus(boolean *dynamic)
{
if(dynamic) *dynamic = true;
HWND hWinamp = FindWindow("Winamp v1.x", 0);
if(!hWinamp) return "";
int status = SendMessage(hWinamp, WM_USER, 0, 104);
if(status == 1) {
return "Playing";
}
else if(status == 3) {
return "Paused";
}
else {
return "Stopped";
}
}
string SystemInfo::getWindowTitle(const string &windowClass, boolean *dynamic)
{
if(dynamic) *dynamic = true;
HWND hWnd = FindWindow(windowClass.c_str(), 0);
if(!hWnd) return "";
char buffer[256];
GetWindowText(hWnd, buffer, 256);
return string(buffer);
}
string SystemInfo::getPowerSource(const vector<string> &arguments, boolean *dynamic)
{
if(dynamic) *dynamic = 1;
SYSTEM_POWER_STATUS sps;
GetSystemPowerStatus(&sps);
if(sps.ACLineStatus == 0)
{
if(arguments.size() >= 2)
return arguments[1];
else
return "Battery";
}
else
{
if(arguments.size() >= 1)
return arguments[0];
else
return "AC";
}
}
string SystemInfo::getBattery(boolean *dynamic)
{
if(dynamic) *dynamic = 1;
SYSTEM_POWER_STATUS sps;
GetSystemPowerStatus(&sps);
if(sps.BatteryLifePercent > 100)
sps.BatteryLifePercent = 0;
char output[8];
StringCchPrintf(output, 8, "%d%%", sps.BatteryLifePercent);
return string(output);
}
// -----------------------------------
// MotherBoard Monitor 5 (MBM5) info
// -----------------------------------
/*
sensortype: the type of sensor it should return (temp, voltage, fan, etc)
arguments: # of sensor (you can have more than one temp sensor)
dynamic: if this is a dynamic variable which can change over time
bUseFahrenheit: if we should return the values in Fahrenheit
*/
string SystemInfo::getMBMData (const SensorType sensortype, const vector<string> &arguments, boolean *dynamic, boolean &bUseFahrenheit)
{
if(dynamic) *dynamic = 1; //this is always a dynamic variable
int n = 0;
double value = 0;
mbmSharedData *pSharedData = NULL;
char output[16];
if(arguments.size() >= 1)
n = atoi(arguments[0].c_str()) - 1;
if(n < 0) n = 0; //n has now the # of the sensor we´re looking for
HANDLE hSharedData=OpenFileMapping(FILE_MAP_READ, FALSE, "$M$B$M$5$S$D$");
if (hSharedData==0)
return "0";
if(hSharedData != INVALID_HANDLE_VALUE)
{ pSharedData = (mbmSharedData *) MapViewOfFile(hSharedData,
FILE_MAP_READ, 0, 0, 0);
if(!pSharedData) {
CloseHandle (hSharedData);
UnmapViewOfFile(pSharedData);
return "0";
}
}
//this only works with newer versions of MBM
if (pSharedData->sdVersion < 51090) {
return "Please update your version of MBM";
}
int totalSensorCount = 0;
for (int i=0;i<5;i++)
totalSensorCount += pSharedData->sdIndex[i].Count;
for (int j=0;j<totalSensorCount;j++)
{
if (pSharedData->sdSensor[j].ssType == sensortype) //is this the type of sensor we´re looking for?
{
if (n == 0) //have we found our sensor?
{
switch (sensortype)
{
case stTemperature:
value = pSharedData->sdSensor[j].ssCurrent;
if (bUseFahrenheit) {
value = value * 9 / 5 + 32;
}
StringCbPrintf (output, 15, "%.0f", value);
break;
case stVoltage:
case stFan:
value = pSharedData->sdSensor[j].ssCurrent;
StringCbPrintf (output, 15, "%.2f", value);
break;
}
UnmapViewOfFile(pSharedData);
CloseHandle (hSharedData);
return string(output);
}
else //no we haven´t found it yet: same type, but wrong number
{
n--;
}
}
}
UnmapViewOfFile(pSharedData);
CloseHandle (hSharedData);
return "0";
}
string SystemInfo::hideIfEmpty(const string &s, Label *label, boolean *dynamic)
{
if(label)
{
if(s.empty() && label->isVisible())
label->hide();
else if(!s.empty() && !label->isVisible())
label->show();
}
return s;
}
string SystemInfo::after(const string &s, const string &search)
{
int i = s.find(search);
i = (i < 0) ? 0 : i + search.length();
return s.substr(i, s.length() - i);
}
string SystemInfo::afterLast(const string &s, const string &search)
{
int i = s.rfind(search);
i = (i < 0) ? 0 : i + search.length();
return s.substr(i, s.length() - i);
}
string SystemInfo::before(const string &s, const string &search)
{
int i = s.find(search);
i = (i < 0) ? s.length() : i;
return s.substr(0, i);
}
string SystemInfo::beforeLast(const string &s, const string &search)
{
int i = s.rfind(search);
i = (i < 0) ? s.length() : i;
return s.substr(0, i);
}
string SystemInfo::between(const string &s, const string &left, const string &right)
{
int start = s.find(left);
start = (start < 0) ? 0 : start + left.length();
int end = s.rfind(right);
end = (end < 0) ? s.length() - 1 : end - right.length();
return (start > end) ? "" : s.substr(start, end - start + 1);
}
string SystemInfo::capitalize(const string &s)
{
string result;
int length = s.length();
int i = 0;
while(i < length)
result.append(1, (i == 0) ? toupper(s[i++]) : tolower(s[i++]));
return result;
}
string SystemInfo::lowerCase(const string &s)
{
string result;
int length = s.length();
int i = 0;
while(i < length)
result.append(1, tolower(s[i++]));
return result;
}
string SystemInfo::trim(const string &s)
{
int start = 0;
int end = s.length() - 1;
while(start <= end && isspace(s[start]))
start++;
while(start <= end && isspace(s[end]))
end--;
return s.substr(start, end - start + 1);
}
string SystemInfo::upperCase(const string &s)
{
string result;
int length = s.length();
int i = 0;
while(i < length)
result.append(1, toupper(s[i++]));
return result;
}
void SystemInfo::getDiskFreeSpace(const string &drive, largeInt &freeBytes, largeInt &totalBytes)
{
static BOOL (WINAPI *pfnGetDiskFreeSpaceEx)(LPCSTR, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER);
static BOOL fChecked = FALSE;
if(!fChecked)
{
pfnGetDiskFreeSpaceEx = (BOOL (WINAPI *)(LPCSTR, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER)) GetProcAddress(
GetModuleHandle("KERNEL32.DLL"), "GetDiskFreeSpaceExA");
fChecked = TRUE;
}
if(pfnGetDiskFreeSpaceEx)
{
largeInt dummy;
pfnGetDiskFreeSpaceEx(drive.c_str(),
(PULARGE_INTEGER) &freeBytes,
(PULARGE_INTEGER) &totalBytes,
(PULARGE_INTEGER) &dummy);
}
else
{
DWORD sectorsPerCluster;
DWORD bytesPerSector;
DWORD freeClusters;
DWORD totalClusters;
GetDiskFreeSpace(drive.c_str(),
§orsPerCluster,
&bytesPerSector,
&freeClusters,
&totalClusters);
largeInt bytesPerCluster = (largeInt) bytesPerSector * (largeInt) sectorsPerCluster;
freeBytes = (largeInt) freeClusters * bytesPerCluster;
totalBytes = (largeInt) totalClusters * bytesPerCluster;
}
}
static const char *units[] = {
"bytes", "KB", "MB", "GB", "TB", "PB", "EB"
};
string SystemInfo::formatByteSize(largeInt byteSize, largeInt total, int unit)
{
char buffer[32];
if(unit == unitsPercent) {
StringCchPrintf(buffer, 32, "%d", (byteSize * 100) / total);
return string(buffer);
}
/* if(unit == unitsKB) {
sprintf(buffer, "%lf", (double) (__int64) byteSize / 1024.0);
return string(buffer);
}
else if(unit == unitsMB) {
sprintf(buffer, "%lf", (double) (__int64) byteSize / (1024.0 * 1024.0));
return string(buffer);
}
else if(unit == unitsGB) {
sprintf(buffer, "%lf", (double) (__int64) byteSize / (1024.0 * 1024.0 * 1024.0));
return string(buffer);
}
else if(unit == unitsPercent) {
sprintf(buffer, "%d", (byteSize * 100) / total);
return string(buffer);
} */
largeInt i = 0;
boolean addUnits = true;
if(unit == unitsKB) {
i = 1;
addUnits = false;
}
else if(unit == unitsMB) {
i = 2;
addUnits = false;
}
else if(unit == unitsGB) {
i = 3;
addUnits = false;
}
else {
if(byteSize & 0xF000000000000000) i++;
if(byteSize & 0xFFFC000000000000) i++;
if(byteSize & 0xFFFFFF0000000000) i++;
if(byteSize & 0xFFFFFFFFC0000000) i++;
if(byteSize & 0xFFFFFFFFFFF00000) i++;
if(byteSize & 0xFFFFFFFFFFFFFC00) i++;
}
largeInt divisor = 1 << (i * 10);
largeInt quotient = byteSize / divisor;
largeInt remainder = ((byteSize % divisor) * 100) / divisor;
if(quotient > 9 && quotient < 100)
remainder = remainder / 10;
else if(quotient >= 100)
remainder = 0;
if(remainder > 0)
StringCchPrintf(buffer, 32, "%d.%02d", (int) quotient, (int) remainder);
else
StringCchPrintf(buffer, 32, "%d", (int) quotient);
if(addUnits) {
StringCchCat(buffer, 32, " ");
StringCchCat(buffer, 32, units[i]);
}
return string(buffer);
}
static inline int isSequenceChar(int ch)
{
return (ch == 'd' || ch == 'm' || ch == 'y' || ch == 'h' || ch == 'i' || ch == 'n' || ch == 's');
}
string SystemInfo::formatDateTime(const string &format, const SYSTEMTIME &st, int span)
{
const char *formatPtr = format.c_str();
string output;
int lastChar = 0;
int sequenceChar = 0;
int count = 0;
int ch = *formatPtr++;
while(ch || sequenceChar)
{
if(sequenceChar)
{
if(ch == sequenceChar)
{
count++;
}
else if(isalpha(ch))
{
output.append(count, sequenceChar);
output.append(1, ch);
sequenceChar = 0;
count = 0;
}
else
{
switch(sequenceChar)
{
case 'd':
{
switch(count)
{
case 1:
{
char temp[8];
StringCchPrintf(temp, 8, "%d", st.wDay);
output.append(temp);
break;
}
case 2:
{
char temp[8];
StringCchPrintf(temp, 8, "%02d", st.wDay);
output.append(temp);
break;
}
case 3:
{
if(st.wDayOfWeek < 7)
output.append(shortWeekdays[st.wDayOfWeek]);
break;
}
case 4:
{
if(st.wDayOfWeek < 7)
output.append(weekdays[st.wDayOfWeek]);
break;
}
default:
{
output.append(count, sequenceChar);
break;
}
}
break;
}
case 'm':
{
if(span) break;
switch(count)
{
case 1:
{
char temp[8];
StringCchPrintf(temp, 8, "%d", st.wMonth);
output.append(temp);
break;
}
case 2:
{
char temp[8];
StringCchPrintf(temp, 8, "%02d", st.wMonth);
output.append(temp);
break;
}
case 3:
{
if(st.wMonth > 0 && st.wMonth < 13)
output.append(shortMonths[st.wMonth - 1]);
break;
}
case 4:
{
if(st.wMonth > 0 && st.wMonth < 13)
output.append(months[st.wMonth - 1]);
break;
}
default:
{
output.append(count, sequenceChar);
break;
}
}
break;
}
case 'y':
{
if(span) break;
if(count == 2 || count == 4)
{
char temp[8];
StringCchPrintf(temp, 8, "%04d", st.wYear);
output.append((count == 2) ? temp + 2 : temp);
}
else
{
output.append(count, sequenceChar);
}
break;
}
case 'h':
{
if(count == 1 || count == 2)
{
char temp[8];
int hour = span ? st.wHour : (st.wHour == 0) ? 12 : (st.wHour > 12) ? st.wHour - 12 : st.wHour;
StringCchPrintf(temp, 8, (count == 1) ? "%d" : "%02d", hour);
output.append(temp);
}
else
{
output.append(count, sequenceChar);
}
break;
}
case 'i':
{
if(count == 1 || count == 2)
{
char temp[8];
StringCchPrintf(temp, 8, (count == 1) ? "%d" : "%02d", st.wHour);
output.append(temp);
}
else
{
output.append(count, sequenceChar);
}
break;
}
case 'n':
{
if(count == 1 || count == 2)
{
char temp[8];
StringCchPrintf(temp, 8, (count == 1) ? "%d" : "%02d", st.wMinute);
output.append(temp);
}
else
{
output.append(count, sequenceChar);
}
break;
}
case 's':
{
if(count == 1 || count == 2)
{
char temp[8];
StringCchPrintf(temp, 8, (count == 1) ? "%d" : "%02d", st.wSecond);
output.append(temp);
}
else
{
output.append(count, sequenceChar);
}
break;
}
default:
{
output.append(count, sequenceChar);
break;
}
}
if(ch) output.append(1, ch);
sequenceChar = 0;
count = 0;
}
}
else
{
if(isSequenceChar(ch) && !isalpha(lastChar))
{
sequenceChar = ch;
count = 1;
}
else if(ch == 'a' && !isalpha(lastChar))
{
const char *p = formatPtr - 1;
// special case: am/pm
if(strncmp(p, "am/pm", 5) == 0)
{
output.append((st.wHour >= 12) ? pm : am);
formatPtr = formatPtr + 4;
}
else
{
output.append(1, ch);
}
}
else
{
output.append(1, ch);
}
}
lastChar = ch;
if(ch) ch = *formatPtr++;
}
return output;
}
void SystemInfo::getLocalizedTime(SYSTEMTIME *pst, const string &timezone)
{
string temp = lowerCase(timezone);
const char *s = temp.c_str();
if(s[0] == 'u' && s[1] == 't' && s[2] == 'c')
{
s = s + 3;
GetSystemTime(pst);
}
else
{
GetLocalTime(pst);
}
while(s[0] == ' ')
s++;
int dHour = 0;
int dMinute = 0;
int sign = 1;
if(s[0] == '+')
{
sign = 1;
s++;
}
else if(s[0] == '-')
{
sign = -1;
s++;
}
while(s[0] >= '0' && s[0] <= '9')
{
dHour = (dHour * 10) + (s[0] - '0');
s++;
}
if(s[0] == ':')
{
s++;
while(s[0] >= '0' && s[0] <= '9')
{
dMinute = (dMinute * 10) + (s[0] - '0');
s++;
}
}
largeInt base;
largeInt delta = (largeInt) (sign * ((dHour * 60) + dMinute)) * 600000000;
SystemTimeToFileTime(pst, (LPFILETIME) &base);
base = base + delta;
FileTimeToSystemTime((LPFILETIME) &base, pst);
}
char *SystemInfo::getLocaleInfo(LCTYPE type)
{
int len = GetLocaleInfo(LOCALE_USER_DEFAULT, type, 0, 0);
char *buffer = new char[len];
GetLocaleInfo(LOCALE_USER_DEFAULT, type, buffer, len);
return buffer;
}
SystemInfo *systemInfo;
| [
"[email protected]"
] | [
[
[
1,
1577
]
]
] |
4e1dfb2464d8abfe5f86eed4cc738eff96f74fb2 | 5fb9b06a4bf002fc851502717a020362b7d9d042 | /developertools/GumpEditor/entity/GumpBorder.cpp | 843749a315cf8e8c91ba0c7132b89cbd321ce595 | [] | no_license | bravesoftdz/iris-svn | 8f30b28773cf55ecf8951b982370854536d78870 | c03438fcf59d9c788f6cb66b6cb9cf7235fbcbd4 | refs/heads/master | 2021-12-05T18:32:54.525624 | 2006-08-21T13:10:54 | 2006-08-21T13:10:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,066 | cpp | #include "StdAfx.h"
#include "GumpEditor.h"
#include "StdGrfx.h"
#include ".\gumpBorder.h"
#include "GumpEditorDoc.h"
CGumpBorder::CGumpBorder(CGumpPtr pGump) : CGumpPicture(NULL)
{
SetGump(pGump);
SetTitle("border");
SetType("border");
CString strName;
strName.Format("border_%x", pGump ? pGump->GetGumpID() : 0);
SetName(strName);
//AddPropertyPage( &m_page );
}
CGumpBorder::~CGumpBorder(void)
{
}
CDiagramEntity* CGumpBorder::Clone()
{
CGumpBorder* obj = new CGumpBorder(m_pGumpB[LT]);
obj->Copy( this );
return obj;
}
void CGumpBorder::Draw( CDC* dc, CRect rect )
{
if (!m_pGumpB[LT]) {
CGumpEntity::Draw(dc,rect);
return;
}
double zoom = GetZoom();
int img_x[4],img_y[4];
img_x[0] = rect.left;
img_x[1] = max(rect.left, rect.left + m_sizeGumpB[LT].cx * zoom);
img_x[2] = min(rect.right, rect.right - m_sizeGumpB[RT].cx * zoom);
img_x[3] = rect.right;
img_y[0] = rect.top;
img_y[1] = max(rect.top, rect.top + m_sizeGumpB[LT].cy * zoom);
img_y[2] = min(rect.bottom, rect.bottom - m_sizeGumpB[LB].cy * zoom);
img_y[3] = rect.bottom;
if (m_pGumpB[LT]) m_pGumpB[LT]->DrawGump(dc, CPoint(img_x[0],img_y[0]), zoom);
if (m_pGumpB[RT]) m_pGumpB[RT]->DrawGump(dc, CPoint(img_x[2],img_y[0]), zoom);
if (m_pGumpB[LB]) m_pGumpB[LB]->DrawGump(dc, CPoint(img_x[0],img_y[2]), zoom);
if (m_pGumpB[RB]) m_pGumpB[RB]->DrawGump(dc, CPoint(img_x[2],img_y[2]), zoom);
if (m_pGumpB[TOP]) m_pGumpB[TOP]->DrawGump(dc, CRect(img_x[1],img_y[0],img_x[2],img_y[1]), zoom);
if (m_pGumpB[LC]) m_pGumpB[LC]->DrawGump(dc, CRect(img_x[0],img_y[1],img_x[1],img_y[2]), zoom);
if (m_pGumpB[RC]) m_pGumpB[RC]->DrawGump(dc, CRect(img_x[2],img_y[1],img_x[3],img_y[2]), zoom);
if (m_pGumpB[BOTTOM]) m_pGumpB[BOTTOM]->DrawGump(dc, CRect(img_x[1],img_y[2],img_x[2],img_y[3]), zoom);
if (m_pGumpB[CENTER]) m_pGumpB[CENTER]->DrawGump(dc, CRect(img_x[1],img_y[1],img_x[2],img_y[2]), zoom);
}
CGumpEntity* CGumpBorder::CreateFromNode( XML::Node* node )
{
CGumpBorder* obj = new CGumpBorder(NULL);
if (!obj->FromString( node ))
{
delete obj;
obj = NULL;
}
return obj;
}
int CGumpBorder::GetGumpID(void) const
{
return m_pGumpB[LT] ? m_pGumpB[LT]->GetGumpID() : -1;
}
void CGumpBorder::SetGump(CGumpPtr pGump, bool bUpdateRect)
{
// ASSERT(pGump);
for (int i = 0; i < NUM_PART; i++) {
m_pGumpB[i] = NULL;
m_sizeGumpB[i].SetSize(0,0);
}
if (!pGump) return;
int iGumpID = pGump->GetGumpID();
int iWidth = 0, iHeight = 0;
CGumpEditorDoc* pDoc = GfxGetGumpDocument();
m_pGumpB[LT] = pGump;
m_sizeGumpB[LT] = pGump->GetDimensions();
for (int i = 1; i < NUM_PART; i++) {
m_pGumpB[i] = pDoc->GetGump(iGumpID+i);
if (!m_pGumpB[i]) continue;
m_sizeGumpB[i] = m_pGumpB[i]->GetDimensions();
if (i < LC) iWidth += m_sizeGumpB[i].cx;
if (i % LC == 0) iHeight += m_sizeGumpB[i].cy;
}
if (!bUpdateRect) return;
CRect rect = GetRect();
SetRect(rect.left,rect.top,rect.left+iWidth,rect.top+iHeight);
}
| [
"sience@a725d9c3-d2eb-0310-b856-fa980ef11a19"
] | [
[
[
1,
114
]
]
] |
28ab3899dd503523f98a7e93fcf65beea259afa0 | 3414945a21f778f467500c2ba0ae743fd6653565 | /src/gdx-cpp/graphics/Texture.cpp | 6a667588854d1b9053832e26d4336ff2e7b0f503 | [
"Apache-2.0"
] | permissive | fredmen/libgdx-cpp | 945fdd6ec9837230a19d65cc560f210627747600 | 3447a8fa2a4f5435a6f9fe8a6405327877c263b2 | refs/heads/master | 2021-01-16T00:17:10.413392 | 2011-09-30T12:44:25 | 2011-09-30T12:44:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,191 | cpp |
/*
Copyright 2011 Aevum Software aevum @ aevumlab.com
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.
@author Victor Vicente de Carvalho [email protected]
@author Ozires Bortolon de Faria [email protected]
*/
#include "Texture.hpp"
#include "gdx-cpp/Gdx.hpp"
#include "gdx-cpp/graphics/Pixmap.hpp"
#include "gdx-cpp/math/MathUtils.hpp"
#include "GL10.hpp"
#include "gdx-cpp/graphics/glutils/MipMapGenerator.hpp"
#include "gdx-cpp/assets/AssetLoaderParameters.hpp"
#include "gdx-cpp/assets/loaders/TextureParameter.hpp"
#include "gdx-cpp/graphics/glutils/PixmapTextureData.hpp"
#include <list>
#include <sstream>
#include "glutils/FileTextureData.hpp"
#include <stdexcept>
using namespace gdx_cpp::graphics;
using namespace gdx_cpp;
const Texture::TextureWrap Texture::TextureWrap::ClampToEdge = Texture::TextureWrap(GL10::GL_CLAMP_TO_EDGE);
const Texture::TextureWrap Texture::TextureWrap::Repeat = Texture::TextureWrap(GL10::GL_REPEAT);
const Texture::TextureFilter Texture::TextureFilter::Nearest = Texture::TextureFilter(GL10::GL_NEAREST);
const Texture::TextureFilter Texture::TextureFilter::Linear = Texture::TextureFilter(GL10::GL_LINEAR);
const Texture::TextureFilter Texture::TextureFilter::MipMap = Texture::TextureFilter(GL10::GL_LINEAR_MIPMAP_LINEAR);
const Texture::TextureFilter Texture::TextureFilter::MipMapNearestNearest = Texture::TextureFilter(GL10::GL_NEAREST_MIPMAP_NEAREST);
const Texture::TextureFilter Texture::TextureFilter::MipMapLinearNearest = Texture::TextureFilter(GL10::GL_LINEAR_MIPMAP_NEAREST);
const Texture::TextureFilter Texture::TextureFilter::MipMapNearestLinear = Texture::TextureFilter(GL10::GL_NEAREST_MIPMAP_LINEAR);
const Texture::TextureFilter Texture::TextureFilter::MipMapLinearLinear = Texture::TextureFilter(GL10::GL_LINEAR_MIPMAP_LINEAR);
Texture::managedTextureMap Texture::managedTextures;
int Texture::buffer = 0;
assets::AssetManager* Texture::assetManager = 0;
Texture::ptr Texture::fromFile(const gdx_cpp::files::FileHandle::ptr file,
const gdx_cpp::graphics::Pixmap::Format* format,
bool useMipMaps)
{
ptr newTex = ptr(new Texture);
newTex->initialize(file, format, useMipMaps);
return newTex;
}
void Texture::create (TextureData::ptr data) {
this->glHandle = 0;
this->enforcePotImages = true;
this->useHWMipMap = true;
this->assetManager = 0;
glHandle = createGLHandle();
load(data);
if (data->isManaged()) {
addManagedTexture(gdx_cpp::Gdx::app, shared_from_this());
}
}
int Texture::createGLHandle () {
Gdx::gl->glGenTextures(1, &buffer);
return buffer;
}
void Texture::load (const TextureData::ptr& data) {
if (this->data != NULL && data->isManaged() != this->data->isManaged()) {
Gdx::app->error("Texture.cpp", "New data must have the same managed status as the old data");
}
this->data = data;
if (data->getType() == TextureData::TextureDataType::Pixmap) {
Pixmap::ptr pixmap = data->getPixmap();
uploadImageData(pixmap);
if (data->disposePixmap()) pixmap->dispose();
setFilter(minFilter, magFilter);
setWrap(uWrap, vWrap);
}
if (data->getType() == TextureData::TextureDataType::Compressed) {
Gdx::gl->glBindTexture(GL10::GL_TEXTURE_2D, glHandle);
data->uploadCompressedData();
setFilter(minFilter, magFilter);
setWrap(uWrap, vWrap);
}
}
void Texture::uploadImageData (const gdx_cpp::graphics::Pixmap::ptr& pixmap) {
if (enforcePotImages && Gdx::gl20 == NULL
&& (! gdx_cpp::math::utils::isPowerOfTwo(data->getWidth()) || !gdx_cpp::math::utils::isPowerOfTwo(data->getHeight())))
{
throw std::runtime_error("Texture.cpp: texture width and height must be powers of two");
}
bool disposePixmap = false;
Pixmap::ptr tmp = pixmap;
if (*data->getFormat() != pixmap->getFormat()) {
tmp = Pixmap::newFromPixmap(*pixmap);
tmp->drawPixmap(*pixmap, 0, 0, 0, 0, pixmap->getWidth(), pixmap->getHeight());
disposePixmap = true;
}
Gdx::gl->glBindTexture(GL10::GL_TEXTURE_2D, glHandle);
if (data->useMipMaps()) {
glutils::MipMapGenerator::generateMipMap(tmp, tmp->getWidth(), tmp->getHeight(), disposePixmap);
} else {
Gdx::gl->glTexImage2D(GL10::GL_TEXTURE_2D, 0, tmp->getGLInternalFormat(), tmp->getWidth(), tmp->getHeight(), 0,
tmp->getGLFormat(), tmp->getGLType(), tmp->getPixels());
if (disposePixmap) tmp->dispose();
}
}
void Texture::reload () {
if (!data->isManaged()) {
gdx_cpp::Gdx::app->error(__FILE__, "Tried to reload unmanaged Texture");
}
createGLHandle();
load(data);
}
void Texture::bind () {
Gdx::gl->glBindTexture(GL10::GL_TEXTURE_2D, glHandle);
}
void Texture::bind (int unit) {
Gdx::gl->glActiveTexture(GL10::GL_TEXTURE0 + unit);
Gdx::gl->glBindTexture(GL10::GL_TEXTURE_2D, glHandle);
}
void Texture::draw (Pixmap& pixmap,int x,int y) {
if (data->isManaged()){
gdx_cpp::Gdx::app->error(__FILE__ , "can't draw to a managed texture");
}
Gdx::gl->glBindTexture(GL10::GL_TEXTURE_2D, glHandle);
Gdx::gl->glTexSubImage2D(GL10::GL_TEXTURE_2D, 0, x, y, pixmap.getWidth(), pixmap.getHeight(), pixmap.getGLFormat(),
pixmap.getGLType(), (const unsigned char*) pixmap.getPixels());
}
int Texture::getWidth () const {
return data->getWidth();
}
int Texture::getHeight () const {
return data->getHeight();
}
const gdx_cpp::graphics::Texture::TextureFilter& Texture::getMinFilter () const {
return minFilter;
}
const gdx_cpp::graphics::Texture::TextureFilter& Texture::getMagFilter () const {
return magFilter;
}
const gdx_cpp::graphics::Texture::TextureWrap& Texture::getUWrap () const {
return uWrap;
}
const gdx_cpp::graphics::Texture::TextureWrap& Texture::getVWrap () const {
return vWrap;
}
TextureData::ptr Texture::getTextureData () {
return data;
}
bool Texture::isManaged () {
return data->isManaged();
}
int Texture::getTextureObjectHandle () {
return glHandle;
}
void Texture::setWrap (const gdx_cpp::graphics::Texture::TextureWrap& u, const gdx_cpp::graphics::Texture::TextureWrap& v) {
this->uWrap = u;
this->vWrap = v;
bind();
Gdx::gl->glTexParameterf(GL10::GL_TEXTURE_2D, GL10::GL_TEXTURE_WRAP_S, u.getGLEnum());
Gdx::gl->glTexParameterf(GL10::GL_TEXTURE_2D, GL10::GL_TEXTURE_WRAP_T, v.getGLEnum());
}
void Texture::setFilter (const gdx_cpp::graphics::Texture::TextureFilter& minFilter, const gdx_cpp::graphics::Texture::TextureFilter& magFilter) {
this->minFilter = minFilter;
this->magFilter = magFilter;
bind();
Gdx::gl->glTexParameterf(GL10::GL_TEXTURE_2D, GL10::GL_TEXTURE_MIN_FILTER, minFilter.getGLEnum());
Gdx::gl->glTexParameterf(GL10::GL_TEXTURE_2D, GL10::GL_TEXTURE_MAG_FILTER, magFilter.getGLEnum());
}
void Texture::dispose () {
buffer = glHandle;
Gdx::gl->glDeleteTextures(1, &buffer);
if (data->isManaged()) {
if (managedTextures.count(Gdx::app))
managedTextures[Gdx::app].remove(shared_from_this());
}
}
void Texture::setEnforcePotImages (bool enforcePotImages) {
Texture::enforcePotImages = enforcePotImages;
}
void Texture::addManagedTexture (gdx_cpp::Application* app,const Texture::ptr texture) {
managedTextures[app].push_back(texture);
}
void Texture::clearAllTextures (gdx_cpp::Application* app) {
managedTextures.erase(app);
}
const assets::AssetType& Texture::getAssetType()
{
return assets::AssetType::Texture;
}
void Texture::invalidateAllTextures (gdx_cpp::Application* app) {
textureList& managedTexureList = managedTextures[app];
if (assetManager == NULL) {
textureList::iterator it = managedTexureList.begin();
textureList::iterator end = managedTexureList.end();
for (; it != end; it++) {
(*it)->reload();
}
} else {
// textureList t(managedTexureList);
//
// managedTexureList.clear();
//
// textureList::iterator it = t.begin();
// textureList::iterator end = t.end();
//
// std::string filename;
//
// for (; it != end; ++it) {
// if (!assetManager->getAssetFileName((Asset&) *it, filename)) {
// (*it)->reload();
// } else {
// assets::loaders::TextureParameter::ptr params;
// params->format = (*it)->getTextureData()->getFormat();
// params->genMipMaps = (*it)->getTextureData()->useMipMaps();
// params->texture = *it;
// (*it)->glHandle = Texture::createGLHandle();
// assetManager->remove(filename);
// assetManager->preload(filename, assets::AssetType::Texture, params);
// }
// managedTexureList.push_back(*it);
// }
}
}
void Texture::setAssetManager (gdx_cpp::assets::AssetManager* manager) {
Texture::assetManager = manager;
}
std::string Texture::getManagedStatus () {
std::stringstream builder;
builder << "Managed textures/app: { ";
managedTextureMap::iterator it = managedTextures.begin();
managedTextureMap::iterator end = managedTextures.end();
for(; it != end; it++) {
builder << it->second.size() << " ";
}
builder << "}";
return builder.str();
}
Texture::Texture(const TextureData::ptr data)
:
minFilter(TextureFilter::Nearest)
,magFilter(TextureFilter::Nearest)
,uWrap(TextureWrap::ClampToEdge)
,vWrap(TextureWrap::ClampToEdge)
{
create(data);
}
Texture::Texture(int width, int height, const Pixmap::Format& format, Pixmap::PixmapType pixType)
:
minFilter(TextureFilter::Nearest)
,magFilter(TextureFilter::Nearest)
,uWrap(TextureWrap::ClampToEdge)
,vWrap(TextureWrap::ClampToEdge)
{
Pixmap::ptr pixmap = Pixmap::newFromRect(width, height, format, pixType);
glutils::PixmapTextureData::ptr ptd(new glutils::PixmapTextureData(pixmap, NULL, false, true));
create(ptd);
}
Texture::Texture(Pixmap::ptr pixmap, const Pixmap::Format& format, bool useMipMaps)
:
minFilter(TextureFilter::Nearest)
,magFilter(TextureFilter::Nearest)
,uWrap(TextureWrap::ClampToEdge)
,vWrap(TextureWrap::ClampToEdge)
{
create(glutils::PixmapTextureData::ptr(new glutils::PixmapTextureData(pixmap, &format, useMipMaps, false)));
}
Texture::Texture()
:
minFilter(TextureFilter::Nearest)
,magFilter(TextureFilter::Nearest)
,uWrap(TextureWrap::ClampToEdge)
,vWrap(TextureWrap::ClampToEdge)
{
}
Texture::Texture(const Pixmap::ptr pixmap, bool useMipMaps)
:
minFilter(TextureFilter::Nearest)
,magFilter(TextureFilter::Nearest)
,uWrap(TextureWrap::ClampToEdge)
,vWrap(TextureWrap::ClampToEdge)
{
create(glutils::PixmapTextureData::ptr(new glutils::PixmapTextureData(pixmap, NULL , useMipMaps, false)));
}
void Texture::initialize(const gdx_cpp::files::FileHandle::ptr file, const Pixmap::Format* format, bool useMipMaps)
{
this->glHandle = 0;
this->enforcePotImages = true;
this->useHWMipMap = true;
this->assetManager = 0;
create(TextureData::ptr(Gdx::graphics->resolveTextureData(file, null_shared_ptr(), format, useMipMaps)));
} | [
"[email protected]",
"[email protected]"
] | [
[
[
1,
354
],
[
356,
357
]
],
[
[
355,
355
]
]
] |
7975d28b2400dbb06ab65864824d2dffa83821ae | 2cb90fce964b78852ab83c27d81d3be5c3394281 | /src/edoo/Hora.cpp | 7d6e0660e116c70a9882fc8f9485a7c058b4d554 | [] | no_license | pauek/edoo | d103b9250170f56cc48cd2688d8e4d7ec8a25397 | 17c66e5ecb379131d98c5e98a4bb4f9662810448 | refs/heads/master | 2016-09-06T05:44:32.325766 | 2011-04-25T18:53:22 | 2011-04-25T18:53:22 | 1,397,972 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,788 | cpp |
#include "Hora.h"
Hora::Hora() {
_hores = 0; _minuts = 0; _segons = 0;
}
Hora::Hora(int h, int m, int s) {
_hores = h; _minuts = m; _segons = s;
_ajusta();
}
Hora::Hora(int segons) {
_hores = 0; _minuts = 0; _segons = segons;
_ajusta();
}
Hora::Hora(const Hora &h) {
_hores = h._hores;
_minuts = h._minuts;
_segons = h._segons;
}
int Hora::hores() const { return _hores; }
int Hora::minuts() const { return _minuts; }
int Hora::segons() const { return _segons; }
int Hora::total_segons() const {
return (_hores * 60 + _minuts) * 60 + _segons;
}
// '_ajusta' posa la hora a valors correctes
// però preserva la quantitat de segons:
//
// 13:27:90 -> 13:28:30 (0)
// 13:00:125 -> 13:02:05 (0)
// 25:05:-40 -> 01:04:20 (1)
// 00:00:-30 -> 23:59:30 (-1)
// etc.
//
// Retorna el número de dies que hi havia
//
int Hora::_ajusta() {
const int UN_DIA = 24 * 60 * 60;
// Ajuntem les parts (T: Total)
int T = total_segons();
// traiem els dies
int dies = T / UN_DIA;
T = T % UN_DIA;
if (T < 0) {
T += UN_DIA;
// el dia que hem afegit a 'total' el trec de dies.
dies = dies - 1;
}
// Dividim en parts
_hores = T / 3600;
T = T % 3600;
_minuts = T / 60;
T = T % 60;
_segons = T;
return dies;
}
int Hora::avansa(int seg) {
_segons += seg;
return _ajusta();
}
Hora Hora::operator+(int segons) const {
Hora resultat;
resultat.avansa(segons);
return resultat;
}
Hora Hora::operator-(int segons) const {
return operator+(-segons);
}
void Hora::operator+=(int segons) { avansa( segons); }
void Hora::operator-=(int segons) { avansa(-segons); }
bool Hora::operator==(const Hora &h) const {
return total_segons() == h.total_segons();
}
bool Hora::operator!=(const Hora& h) const {
return !operator==(h);
}
bool Hora::operator<(const Hora &h) const { return total_segons() < h.total_segons(); }
bool Hora::operator<=(const Hora &h) const { return total_segons() <= h.total_segons(); }
bool Hora::operator>(const Hora &h) const { return total_segons() > h.total_segons(); }
bool Hora::operator>=(const Hora &h) const { return total_segons() >= h.total_segons(); }
void Hora::llegeix(istream& i) {
char c;
i >> _hores >> c >> _minuts >> c >> _segons;
}
void Hora::escriu(ostream& o) const {
if (_hores < 10) cout << 0;
o << _hores << ':';
if (_minuts < 10) cout << 0;
o << _minuts << ':';
if (_segons < 10) cout << 0;
o << _segons;
}
istream& operator>>(istream &is, Hora &h) {
h.llegeix(is);
return is;
}
ostream& operator<<(ostream &os, const Hora &h) {
h.escriu(os);
return os;
}
| [
"[email protected]"
] | [
[
[
1,
122
]
]
] |
2866d5791062f5b77c7e9978ae8eb6230003f9a9 | 4b116281b895732989336f45dc65e95deb69917b | /Code Base/GSP410-Project2/Quadrant.h | 861ece5a1bffb1b6f372b3ce0d0e4c4d446fbd2f | [] | no_license | Pavani565/gsp410-spaceshooter | 1f192ca16b41e8afdcc25645f950508a6f9a92c6 | c299b03d285e676874f72aa062d76b186918b146 | refs/heads/master | 2021-01-10T00:59:18.499288 | 2011-12-12T16:59:51 | 2011-12-12T16:59:51 | 33,170,205 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,599 | h | //Will Zepeda
//GSP-410
//Quadrant.h
//Class that holds all data a quadrant needs to init, update, and pass
//to renderer
#pragma once
#include "Structures.h"
#include "Sector.h"
#include "Unit.h"
#include "EnemyUnit.h"
#include "FriendlyUnit.h"
#include "Star.h"
#include "Station.h"
//MAKE INTO SINGLETON DESIGN
//needs to have firing mechanism that:
// uses mouse x and y to determine who was clicked
// needs attack function that calcs distances and whatnot
//
const int quadSize = 8;
class Quadrant
{
private:
CEnemyUnit mEnemies[3];
CStar mStars[7];
CFriendlyUnit mFriendly;
CStation mStation;
Sector mQuad[quadSize][quadSize];
QuadData mQuadData;
public:
//For passing to Render - Kevin
CRenderable* m_Drawables[12];
int m_NumberOfDrawables;
Quadrant();
//kevin's algorithm/code that i put into a function
void makeDrawableList();
CFriendlyUnit GetFriendlyUnit(void);
////////////////////////////////////////////////////////////////////////////
//Class : LoadQuad
//Param1 : QuadData struct that consists of three ints that make up
// : the number of enemies, stars, and stations each quandrant should have
//Job : fills private data of current quadrant based on QuadData.
// : makes list of renderables and deletes renderable if it gets destroyed
//Return : void
void LoadQuad(QuadData);
////////////////////////////////////////////////////////////////////////////
//Class : getSector
//Param1 : int, row number
//Param2 : int, column number
//Job : returns address of sector specified by
// : uses those ints as indeces for a specific sector in mQuad.
//Return : address of sector.
Sector& getSector(int);
////////////////////////////////////////////////////////////////////////////
//Class : getEmptySector
//Param1 : void
//Job : generates two random ints withing range of quadSize.
// : uses those ints as indeces for a specific sector in mQuad.
// : checks to see if that sector's mOccupiedType is EMPTY.
//Return : address of empty sector.
Sector& getEmptySector();
/******************************************************************/
/** these functions call friendly's blaster, missiles, and shield functions **/
void addBlasterEnergy1();
void addBlasterEnergy10();
void subBlasterEnergy1();
void subBlasterEnergy10();
void addShieldEnergy1();
void addShieldEnergy10();
void subShieldEnergy1();
void subShieldEnergy10();
//returns false if blasters failed
bool fireBlasters();
//returns false if missile failed
bool fireMissiles(Command);
//returns false if ship doesn't have enough fuel to move
bool moveFriendly(Command);
void dockFriendly(Command);
void moveEnemy();
////////////////////////////////////////////////////////////////////////////
//Class : destroyedEnemies
//Param1 : void
//Job : Call after fireBlasters and fireMissiles
// : Calculates how many enemies, if any, were destroyed
//Return : int, returns how many enemies were destroyed.
int destroyedEnemies();
////////////////////////////////////////////////////////////////////////////
//Class : destoryedStations
//Param1 : void
//Job : Call after moveFriendly and fireMissiles
// : Calculates how many stations, if any, were destroyed
//Return : int, returns how many stations were destroyed.
int destroyedStations();
/******************************************************************/
};
| [
"[email protected]@7eab73fc-b600-5548-9ef9-911d97763ba7",
"[email protected]@7eab73fc-b600-5548-9ef9-911d97763ba7",
"[email protected]@7eab73fc-b600-5548-9ef9-911d97763ba7"
] | [
[
[
1,
11
],
[
14,
14
],
[
17,
28
],
[
30,
30
],
[
32,
35
],
[
37,
37
],
[
41,
44
],
[
46,
117
]
],
[
[
12,
13
],
[
29,
29
],
[
31,
31
],
[
36,
36
],
[
38,
40
],
[
45,
45
]
],
[
[
15,
16
]
]
] |
b01ab371fb9d9959e50c35dd477af116a617c0b4 | 7a310d01d1a4361fd06b40a74a2afc8ddc23b4d3 | /src/Thumbnail.h | f41620cfd7af3e9d02a0e5a9a20281767cf28b70 | [] | 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 | 11,643 | h | /**
* @file Thumbnail.h
* @brief サムネール表示.
* @note
* +++ 本家unDonut R5で実装 R10βで破棄されたルーチンを復活.
* +++ タブ数が多いとダイアログでるまでにかなり待ち時間発生する.... スレッドに分けるべきなんだろうなあ.
*/
#ifndef __THUMBNAIL_H_
#define __THUMBNAIL_H_
#define USE_THUMBNAIL
#include "resource.h"
//#include "MtlWin.h"
class CThumbnailDlg : public CDialogImpl<CThumbnailDlg> /*, public CMessageFilter*/ {
public:
enum {
IDD = IDD_DIALOG_THUMBNAIL,
};
private:
enum {
PIC_WIDTH = 200,
PIC_HEIGHT = 200,
SPACE = 2,
m_nMinWidth = 20,
m_nMinHeight = 50,
m_nDefWidth = 550,
m_nDefHeight = 520
};
CListViewCtrl m_List;
CImageList m_ImageList;
HWND m_hParent;
CRect m_rcDialog;
CRect m_rcDialogInit;
int m_nPictWidth;
int m_nPictHeight;
BYTE/*BOOL*/ m_bInit;
BYTE/*BOOL*/ m_bCenter;
BYTE/*BOOL*/ m_bSavePos;
CContainedWindow m_wndList;
public:
CThumbnailDlg()
: m_wndList(this, 1)
, m_bCenter(FALSE)
, m_bInit(FALSE)
#if 1 //+++
, m_hParent(0)
, m_bSavePos(0)
, m_nPictWidth(0)
, m_nPictHeight(0)
#endif
{
}
BEGIN_MSG_MAP(CThumbnailDlg)
MESSAGE_HANDLER( WM_INITDIALOG , OnInitDialog )
MESSAGE_HANDLER( WM_ACTIVATE , OnActivate )
MESSAGE_HANDLER( WM_SIZE , OnSize )
MESSAGE_HANDLER( WM_DESTROY , OnDestroy )
NOTIFY_HANDLER( IDC_LIST_THUMBNAIL , NM_DBLCLK, OnDblClk )
NOTIFY_HANDLER( IDC_LIST_THUMBNAIL , NM_RDBLCLK, OnRDblClk )
NOTIFY_HANDLER( IDC_LIST_THUMBNAIL , NM_RCLICK, OnRClick )
COMMAND_ID_HANDLER( IDOK , OnCloseCmd )
COMMAND_ID_HANDLER( IDCANCEL , OnCloseCmd )
ALT_MSG_MAP(1)
MESSAGE_HANDLER( WM_KEYDOWN , OnKeyDown )
END_MSG_MAP()
int DoModal(HWND hWndParent, LPARAM dwInitParam = NULL)
{
m_hParent = (HWND) dwInitParam;
return CDialogImpl<CThumbnailDlg>::DoModal(hWndParent, dwInitParam);
}
private:
LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL & /*bHandled*/)
{
GetDefaultSize(m_rcDialog);
//::MoveWindow(m_hWnd, rc.left, rc.top, rc.Width(), rc.Height(), TRUE);
m_List = GetDlgItem(IDC_LIST_THUMBNAIL);
m_ImageList.Create(m_nPictWidth, m_nPictHeight, ILC_COLOR24, 8, 8);
MtlForEachMDIChild( m_hParent, _Function_EnumChild_MakeThumbnail(m_ImageList, m_nPictWidth, m_nPictHeight) );
m_List.SetImageList(m_ImageList.m_hImageList, LVSIL_NORMAL);
MtlForEachMDIChild( m_hParent, _Function_EnumChild_MakeListView(m_List) );
MoveWindow(m_rcDialog, TRUE);
m_wndList.SubclassWindow(m_List.m_hWnd);
return TRUE;
}
void GetDefaultSize(CRect &rc)
{
CIniFileI pr( g_szIniFileName, _T("Thumbnail") );
//画像サイズ取得
DWORD dwWidth = pr.GetValue( _T("PicWidth" ) );
DWORD dwHeight = pr.GetValue( _T("PicHeight") );
m_nPictWidth = (dwWidth > 0) ? dwWidth : PIC_WIDTH;
m_nPictHeight = (dwHeight> 0) ? dwHeight : PIC_HEIGHT;
//位置を取得
DWORD dwSave = pr.GetValue( _T("SavePosition") );
if (dwSave) {
DWORD dwLeft = pr.GetValue( _T("Left" ) );
DWORD dwTop = pr.GetValue( _T("Top" ) );
DWORD dwRight = pr.GetValue( _T("Right" ) );
DWORD dwBottom= pr.GetValue( _T("Bottom") );
if (dwRight == 0 || dwBottom == 0) {
dwRight = dwLeft + m_nDefWidth;
dwBottom = dwTop + m_nDefHeight;
m_bCenter = TRUE;
}
rc.SetRect(dwLeft, dwTop, dwRight, dwBottom);
} else { //+++ ブラウザ側メインウィンドウのクライアント領域の位置&サイズになるように修正.
CRect rcInit;
if (m_hParent)
::GetWindowRect(m_hParent, &rcInit);
if (m_hParent && rcInit.Width() > 0 && rcInit.Height() > 0) {
rc = rcInit;
if (rc.Width() < m_nPictWidth+32)
rc.right = rc.left + m_nPictWidth+32;
if (rc.Height() < m_nPictHeight+32)
rc.bottom = rc.top + m_nPictHeight+32;
m_bCenter = false;
} else {
m_bCenter = TRUE;
rc.SetRect(0, 0, m_nDefWidth, m_nDefHeight);
}
}
pr.Close();
m_bSavePos = dwSave != 0; //? TRUE : FALSE;
}
LRESULT OnDestroy(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL & /*bHandled*/)
{
if (m_bSavePos) {
CRect rc;
GetWindowRect(&rc);
CIniFileO pr( g_szIniFileName, _T("Thumbnail") );
pr.SetValue( rc.left , _T("Left" ) );
pr.SetValue( rc.top , _T("Top" ) );
pr.SetValue( rc.right , _T("Right" ) );
pr.SetValue( rc.bottom, _T("Bottom") );
pr.Close();
}
return 0;
}
BYTE PreTranslateMessage(MSG *pMsg)
{
return 0;
}
LRESULT OnActivate(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL & /*bHandled*/)
{
return 0;
}
LRESULT OnSize(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL & /*bHandled*/)
{
if (!m_bInit) {
MoveWindow(m_rcDialog, TRUE);
if (m_bCenter)
CenterWindow( GetParent() );
m_bInit = TRUE;
}
CRect rc;
GetClientRect(&rc);
rc.DeflateRect(SPACE, SPACE);
m_List.MoveWindow(&rc, TRUE);
return 0;
}
LRESULT OnKeyDown(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL & /*bHandled*/)
{
int nVirtKey = (int) wParam;
#if 1 //+++
int index = 0;
switch (nVirtKey) {
case VK_LEFT:
case VK_UP:
{
int n = m_List.GetItemCount();
if (n <= 0)
break;
index = m_List.GetSelectedIndex();
index = (n + index - 1) % n;
//if (index > 0)
m_List.SelectItem(index);
#if 0 //def WIN64
unsigned w = m_List.GetColumnWidth();
unsigned n = m_List.GetSelectedColumn();
if (w)
n = (w + n - 1) % w;
m_List.SetSelectedColumn(n);
#endif
}
break;
case VK_RIGHT:
case VK_DOWN:
{
int n = m_List.GetItemCount();
if (n <= 0)
break;
index = m_List.GetSelectedIndex();
index = (index + 1) % n;
m_List.SelectItem(index);
#if 0 //def WIN64
unsigned w = m_List.GetColumnWidth();
unsigned n = m_List.GetSelectedColumn();
if (w)
n = (n + 1) % w;
m_List.SetSelectedColumn(n);
#endif
}
break;
//case VK_MBUTTON:
// index = m_List.GetSelectedIndex();
// break;
case VK_DELETE:
{
index = m_List.GetSelectedIndex();
DoItemClose(m_List.GetSelectedIndex());
}
break;
default:
break;
}
#else
if (nVirtKey == 'W' || nVirtKey == 'w') {
if (::GetKeyState(VK_CONTROL) < 0)
EndDialog(0);
}
#endif
return 0;
}
LRESULT OnCloseCmd(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL & /*bHandled*/)
{
//DestroyWindow();
EndDialog(wID);
return 0;
}
//+++
LRESULT OnRClick(int idCtrl, LPNMHDR pnmh, BOOL &bHandled)
{
LPNMLISTVIEW plv = (LPNMLISTVIEW) pnmh;
int index = plv->iItem;
::SetForegroundWindow(m_hWnd);
CMenu/*Handle*/ menu0;
menu0.LoadMenu(IDR_THUMBNAIL_MENU);
if (menu0.m_hMenu == NULL)
return 0;
CMenuHandle menu = menu0.GetSubMenu(0);
if (menu.m_hMenu == NULL)
return 0;
// ポップアップメニューを開く.
POINT pt;
::GetCursorPos(&pt);
HRESULT hr = menu.TrackPopupMenu(TPM_LEFTALIGN | TPM_LEFTBUTTON | TPM_RIGHTBUTTON| TPM_RETURNCMD, pt.x, pt.y, m_hWnd, NULL);
switch (hr) {
case ID_FILE_OPEN: DoItemOpen(index); break;
case ID_FILE_CLOSE: DoItemClose(index); break;
case ID_WINDOW_CLOSE_EXCEPT: DoItemCloseExcept(index); break;
case ID_WINDOW_CLOSE_ALL: DoItemCloseAll(); break;
case ID_LEFT_CLOSE: DoItemCloseLeft(index); break;
case ID_RIGHT_CLOSE: DoItemCloseRight(index); break;
default: ;
}
return 0;
}
LRESULT OnDblClk(int idCtrl, LPNMHDR pnmh, BOOL &bHandled)
{
LPNMLISTVIEW plv = (LPNMLISTVIEW) pnmh;
return DoItemOpen(plv->iItem);
}
LRESULT OnRDblClk(int idCtrl, LPNMHDR pnmh, BOOL &bHandled)
{
// LPNMLISTVIEW plv = (LPNMLISTVIEW) pnmh;
// return DoItemClose(plv->iItem);
return 0;
}
LRESULT DoItemOpen(int index)
{
HWND hWnd = (HWND) m_List.GetItemData(index);
::SendMessage(m_hParent, WM_MDIACTIVATE, (WPARAM) hWnd, 0);
EndDialog(index);
return 0;
}
LRESULT DoItemClose(int index)
{
HWND hWnd = (HWND) m_List.GetItemData(index);
m_List.DeleteItem(index);
::SendMessage(hWnd, WM_CLOSE, 0, 0);
int n = m_List.GetItemCount();
if (n > 0) {
if (index < 0)
index = 0;
if (index >= n)
index = n-1;
m_List.SelectItem(index);
//hWnd = (HWND) m_List.GetItemData(index);
//::SendMessage(m_hParent, WM_MDIACTIVATE, (WPARAM) hWnd, 0);
} else {
EndDialog(index);
}
return 0;
}
LRESULT DoItemCloseExcept(int index)
{
DoItemCloseRight(index);
DoItemCloseLeft(index);
return 0;
}
LRESULT DoItemCloseAll()
{
DoItemCloseRight(0);
DoItemClose(0);
return 0;
}
LRESULT DoItemCloseLeft(int index)
{
int n = m_List.GetItemCount();
if (n <= 1)
return 0;
while (index > 0) {
HWND hWnd = (HWND) m_List.GetItemData(0);
m_List.DeleteItem(0);
::SendMessage(hWnd, WM_CLOSE, 0, 0);
--index;
}
return 0;
}
LRESULT DoItemCloseRight(int index)
{
int n = m_List.GetItemCount();
if (n <= 1)
return 0;
for (int i = n; --i > index;) {
HWND hWnd = (HWND) m_List.GetItemData(i);
m_List.DeleteItem(i);
::SendMessage(hWnd, WM_CLOSE, 0, 0);
}
return 0;
}
struct _Function_EnumChild_MakeListView {
CListViewCtrl & m_ListView;
public:
_Function_EnumChild_MakeListView(CListViewCtrl &List)
: m_ListView(List)
{
}
void operator ()(HWND hWnd)
{
CString strTitle = MtlGetWindowText(hWnd);
int index = m_ListView.GetItemCount();
m_ListView.InsertItem(LVIF_IMAGE | LVIF_TEXT, index, strTitle, 0, 0, index, 0);
m_ListView.SetItemData(index, (LPARAM) hWnd);
}
};
struct _Function_EnumChild_MakeThumbnail {
CImageList& m_ImgList;
int m_nWidth;
int m_nHeight;
public:
_Function_EnumChild_MakeThumbnail(CImageList &ImgList, int PictWidth, int PictHeight)
: m_ImgList(ImgList)
, m_nWidth(PictWidth)
, m_nHeight(PictHeight)
{
}
bool CreateOnHGlobal(IStream** ppIStream)
{
HRESULT hr;
if(ppIStream == NULL)
return false;
hr = ::CreateStreamOnHGlobal(NULL,TRUE,ppIStream);
if(SUCCEEDED(hr) && *ppIStream)
return true;
*ppIStream = NULL;
return false;
}
void operator ()(HWND hWnd);
//+++ 未使用.
bool SaveBitmap(HDC hDC, HBITMAP hBmp, int index)
{
//+++ 200x200固定だったのをメンバー変数をみるように修正.
BYTE dat[54];
unsigned size = m_nWidth * m_nHeight * 3;
std::vector<BYTE> pixs( size );
CString str;
str.Format(_T("test%02d.bmp"), index);
FILE* fp = _tfopen(str, _T("wb"));
if (fp == NULL)
return NULL;
FILE* fpdat = _tfopen(_T("test.dat"), _T("rb"));
if (fpdat == NULL) {
fclose(fp);
return NULL;
}
LPBITMAPFILEHEADER pbf = (BITMAPFILEHEADER *) dat;
LPBITMAPINFOHEADER pbi = (BITMAPINFOHEADER *) ( dat + sizeof (BITMAPFILEHEADER) );
fread(dat, 1, 54, fpdat);
::GetDIBits(hDC, hBmp, 0, m_nHeight, &pixs[0], (BITMAPINFO *) pbi, DIB_RGB_COLORS);
fwrite(dat , 1, 54 , fp);
fwrite(&pixs[0], 1, size, fp);
fclose(fpdat);
fclose(fp);
return true;
}
};
};
#endif //__THUMBNAIL_H_
| [
"[email protected]"
] | [
[
[
1,
488
]
]
] |
9d0d2d43f145e09c5b64dca843e0f68245fe3cf3 | 2c1e5a69ca68fe185cc04c5904aa104b0ba42e32 | /src/game/cui.cpp | 1094deecb32c48bca1f9624186ac1c537dbbfc67 | [] | no_license | dogtwelve/newsiderpg | e3f8284a7cd9938156ef8d683dca7bcbd928c593 | 303566a034dca3e66cf0f29cf9eaea1d54d63e4a | refs/heads/master | 2021-01-10T13:03:31.986204 | 2010-06-27T05:36:33 | 2010-06-27T05:36:33 | 46,550,247 | 0 | 1 | null | null | null | null | UHC | C++ | false | false | 73,618 | cpp | #include "Defines.h"
#include "../common/Engine.h"
#include "../common/Image.h"
#include "../common/Stream.h"
#include "../common/Graphics.h"
#include "ASprite.h"
#include "../wipi/Small_Font.h"
#include "cui.h"
#include "ENTITY.h"
#include "Command_Def.h"
#include "USER_Map.h"
#include "Module_Move.h"
#include "UI_GameLoft.h"
#include "UI_Splash.h"
#include "UI_Menu.h"
#include "cEntity.h"
#include "DEF.h"
#include "GAME.h"
#include "cGAME.h"
#include "..\Config\version.h"
//GuanHao. IGP
#include "..\igp_wipi\wipiigp.h"
//USER_MAP.hpp
#include "macro.h"
//#include ".\NetSource\Common\cKRConvert.h"
#include "cKRConvert.h"
//#include "maincharacter.h"
extern cGame* g_pGame;
//MainMenu* mainUI;//mainUI
//MainGame* gameUI;//gameUI
//void cUI::pursuit_object_auto(int _id , int _map_kind , boolean bID)
//{
// int temp = 0;
// char _map_kindA = -32;
// char _map_kindB = -32;
// char _map_kindC = -32;
// char _index_ID = 0;
// char _index_posX = 0;
// char _index_posY = 0;
// char _index_charposY = 0;
//
// if(_map_kind == MAP_WORLD)
// {
// _map_kindB = (byte)MAP_TOWN;
// _map_kindC = (byte)MAP_SQUARE;
// }
// else if(_map_kind == MAP_TOWN)
// {
// _index_ID = (byte)39;
// _map_kindA = (byte)MAP_WORLD;
// _map_kindC = (byte)MAP_SQUARE;
// _index_posX = (byte)5;
// _index_posY = (byte)22;
// }
// else if(_map_kind == MAP_SQUARE)
// {
// _index_ID = (byte)78;
// _map_kindA = (byte)MAP_WORLD;
// _map_kindB = (byte)MAP_TOWN;
// _index_posY = (byte)20;
// }
//
// if(g_pGame->m_map_kind == _map_kind)
// {
// if(!bID)
// {
// temp = g_pGame->getEntityNumber(_id);
// _index_charposY -= (byte)34;
// }
// else
// {
// temp = g_pGame->getEntityGameID(_id);
// }
//
// if(temp != -1)
// {
// if(bID)
// {
// g_pGame->getEntity(temp)->m_flags = 0;
// }
// g_pGame->pursuit_object(g_pGame->getEntity(temp)->m_posX ,g_pGame->getEntity(temp)->m_posY + _index_charposY);
// }
//
// }
// else if(g_pGame->m_map_kind == _map_kindA)
// {
// temp = g_pGame->getEntityGameID(_index_ID);
// if(temp != -1)
// {
// g_pGame->getEntity(temp)->m_flags = 0;
// g_pGame->pursuit_object(g_pGame->getEntity(temp)->m_posX - _index_posX ,g_pGame->getEntity(temp)->m_posY + _index_posY);
// }
// }
// else if(g_pGame->m_map_kind == _map_kindB)
// {
// temp = g_pGame->getEntityGameID(21);
// if(temp != -1)
// {
// g_pGame->getEntity(temp)->m_flags = 0;
// g_pGame->pursuit_object(g_pGame->getEntity(temp)->m_posX + 5 ,g_pGame->getEntity(temp)->m_posY + 22);
// }
// }
// else if(g_pGame->m_map_kind == _map_kindC)
// {
// temp = g_pGame->getEntityGameID(27);
// if(temp != -1)
// {
// g_pGame->getEntity(temp)->m_flags = 0;
// g_pGame->pursuit_object(g_pGame->getEntity(temp)->m_posX ,g_pGame->getEntity(temp)->m_posY - 15);
// }
//
// }
//}
//================================================================
/// INIT GAME CHEAT
//================================================================
void cUI::init_Cheat( )
{
Cheat_Data = NULL;
Cheat_Input = NULL;
Cheat_Data = GL_NEW int[CHEAT_MAX_COUNT];
Cheat_Input = GL_NEW int[CHEAT_MAX_COUNT];
Cheat_Data[0] = CHEAT_DATA1;
Cheat_Data[1] = CHEAT_DATA2;
Cheat_Data[2] = CHEAT_DATA3;
Cheat_Data[3] = CHEAT_DATA4;
Cheat_Data[4] = CHEAT_DATA5;
Cheat_Data[5] = CHEAT_DATA6;
Cheat_Data[6] = CHEAT_DATA7;
Cheat_Data[7] = CHEAT_DATA8;
cheat_samecount = 0;
cheat_intputcount = 0;
// g_pGame->m_SetDebuglevel = 6;
cheat_money = 0;
//g_pGame->Init_Bank();
}
//================================================================
/// DRAW CHEAT
//================================================================
void cUI::Draw_Cheat( )
{
}
//================================================================
/// PROCESS KEY CHEAT
//================================================================
void cUI::key_Cheat( )
{
}
#define EVENING_TIME 1080//CLOCK::k_minute * 18
#define MONING_TIME 420//CLOCK::k_minute * 7
#define NIGHT_ALPHA 150
void cUI::draw_Start_Channel()
{
/////////////////
int _time = g_pGame->getClock();
//if( _time > 1080 || _time < MONING_TIME) // #define EVENING_TIME 1080//CLOCK::k_minute * 18
{
_time = (_time < MONING_TIME) ? (MONING_TIME - _time) : (_time - EVENING_TIME);
_time = _time - (_time % 10);
if(_time > NIGHT_ALPHA)
{
_time = NIGHT_ALPHA;
}
if(_time < 1)
{
return;
}
g->SetChannel(CHANNEL_NIGHT);
//MEMSET(g->m_buffPixel, _time, SCREEN_WIDTH * SCREEN_HEIGHT);
MEMSET(g_pGame->backbuffpix, _time, SCREEN_WIDTH * SCREEN_HEIGHT);
//g->SetOpacity(_time);
//g->SetColor(0x000000);//ADD
//
//g->EnableBlackAlphaEffect(_time , 0);
//int x = g_pGame->getEntity(GAMESPRITE_MAIN_CHAR)->m_OFFposX;
//int y = g_pGame->getEntity(GAMESPRITE_MAIN_CHAR)->m_OFFposY;
//g->SetChannel(1);
////g->FillRect(0,0,SCREEN_WIDTH,SCREEN_HEIGHT);
//g_pGame->load_spriteArray[0]->PaintFrame(g, 0, x, y, 0, 0, 0);
//g->SetChannel(0);
//g->SetARGBColor(0xFFFFFFFF);//ADD
}
}
void cUI::draw_End_Channel()
{
//if( (g->GetChannel()&CHANNEL_NIGHT ) != CHANNEL_NIGHT)
//{
// //g->SetARGBColor(0xb1000000);
// //g->FillRect(0,0,240,320);
// //g->SetARGBColor(0xff000000);
// return;
//}
//
//int x = g_pGame->getEntity(GAMESPRITE_MAIN_CHAR)->m_OFFposX;
//int y = g_pGame->getEntity(GAMESPRITE_MAIN_CHAR)->m_OFFposY;
//
//g_pGame->load_spriteArray[0]->PaintFrame(g, 0, x, y, 0, 0, 0);
//g->UnSetChannel(CHANNEL_NIGHT);
//g->EnableBlackAlphaEffect(0 , 0);
}
void cUI::process_USER_Openning( int message )
{
if( message == MESSAGE_INIT)
{
TIME_PAUSE_OFF();
//g_pGame->Stop_FireWork();//485
game_sub_state = GAME_STATE_MAP;
m_lastTileX = -1;
m_lastTileY = -1;
m_oldLevelX = -1;
m_oldLevelY = -1;
g_pGame->m_mapX = 0;
g_pGame->m_mapY = -10;
g_pGame->ResetCinematic( 0 );
g_pGame->StartCinematic ( 0 );
g_pGame->Text_freeText( TEXT_INDEX_GAME );
//// g_pGame->Text_loadTextPack( PACK_TEXT, TEXT_OPENING, TEXT_INDEX_GAME );
// STRCPY( g_pGame->mascot_currentText, GET_STRING( OPENING_SYNOP_1, TEXT_INDEX_GAME ));
SPRITE_INIT_PAGE();
menu_strscroll_count = 0;
mascot_hide();
softkey_init(SOFTKEY_SYMBOL_MENU,SOFTKEY_SYMBOL_EMPTY);
}
else if( message == MESSAGE_UPDATE)
{
g_pGame->UpdateCinematic();
int _direct = 0;
if ( !g_pGame->IsCinematicActive() || KEY_PRESSED(GAME_KEY_POUND) )
{
// g_pGame->EndCinematic(ANIMATION_OPENING);
g_pGame->goto_map( STATE_DRAW_HOUSE );
m_StateStory = STORY_OPENNING_END;
}
//DBGPRINTF("game_sub_state = %d",game_sub_state);
}
else if( message == MESSAGE_PAINT)
{
g->SetColor(0x000000);
g->FillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
g_pGame->drawViewTop();
SET_STRING_COLOR(0xFFFFFF);
if ( SPRITE_DRAW_PAGE(g, g_pGame->mascot_currentText, SCREEN_HALF_WIDTH, 145, SCREEN_WIDTH-70, SCREEN_HEIGHT-170, menu_strscroll_count, CGraphics::HCENTER ) )
{
menu_strscroll_count++;
}
// else
// {
// menu_strscroll_count = 0;
// }
// OPENNIG_IMOTICON->PaintFrame( g, FRAME_IMOTICON_SKIP , SCREEN_WIDTH, SCREEN_HEIGHT-5, 0,0,0 ) ;
}
else if( message == MESSAGE_EXIT)
{
g_pGame->Text_freeText( TEXT_INDEX_GAME );
SOUND_STOP( );
FREE_GAMERES();
}
}
void cUI::process_USER_House( int message )
{
// if( message == MESSAGE_INIT)
// {
//
// TIME_PAUSE_OFF();
//
// //g_pGame->Stop_FireWork();//485
// game_sub_state = GAME_STATE_MAP;
//
// m_lastTileX = -1;
// m_lastTileY = -1;
// m_oldLevelX = -1;
// m_oldLevelY = -1;
//
// Set_Camera_Position(g_pGame->getEntity(GAMESPRITE_MAIN_CHAR) );
//
// // if ( m_StateStory == STORY_OPENNING_END )
// // {
// // g_pGame->ResetCinematic(0);
// // g_pGame->StartCinematic ( 0 );
// // }
//
// b_show_Entity = true;
//
// g_pGame->Text_freeText( TEXT_INDEX_GAME );
// g_pGame->Text_loadTextPack( PACK_TEXT, TEXT_OPENING, TEXT_INDEX_GAME );
//
//#ifdef hasShine
// g_pGame->InitShine();
//#endif
// mascot_hide();
//
// // SET_STRING_COLOR(0x000000);
//
// softkey_init(SOFTKEY_SYMBOL_MENU,SOFTKEY_SYMBOL_EMPTY);
//
// }
// else if( message == MESSAGE_UPDATE)
// {
//
// g_pGame->UpdateCinematic();
//
// if ( g_pGame->getEntity(GAMESPRITE_MAIN_CHAR) != NULL)
// {
// int _direct = 0;
//
// if ( g_pGame->IsCinematicActive() )
// {
// if ( !g_pGame->IsCinematicRunning() )
// {
// mascot_Keyupdate();
// }
// }
// else
// {
// if ( b_show_Entity )
// {
// m_StateStory = STORYL_HOUSEOPENNING_END;
// // m_StateStory = STORYL_HOUSEBUG_END;
// Update_Entity_ShowLayer( );
// b_show_Entity = false;
// }
//
// _direct = Set_KeyEvent();
// Update_Entity( );
// }
//
// g_pGame->getEntity(GAMESPRITE_MAIN_CHAR)->set_direct(_direct);
//
// set_move( g_pGame->getEntity(GAMESPRITE_MAIN_CHAR) , 0 );
//
// if ( !g_pGame->IsCinematicActive() )
// {
// Set_FollowEntity( g_pGame->getEntity(GAMESPRITE_MAIN_CHAR) , g_pGame->getEntity(GAMESPRITE_CHICK) );
// }
//
// Set_Camera_Position(g_pGame->getEntity(GAMESPRITE_MAIN_CHAR) );
//
// //update_Zone();
// }
//
// //DBGPRINTF("game_sub_state = %d",game_sub_state);
// }
// else if( message == MESSAGE_PAINT)
// {
// draw_Start_Channel();
// g_pGame->updateAndDrawViewTop();
// draw_End_Channel();
// g_pGame->drawClock ();
//
// //popup_paint();
//
// mascot_paint();
//
// }
// else if( message == MESSAGE_EXIT)
// {
//
// // SAFE_DEL(Boy_Object);
//
// g_pGame->Text_freeText( TEXT_INDEX_GAME );
//
// // g_pGame->Text_freeText( TEXT_INDEX_MAP );
//
// SOUND_STOP( );
//
// FREE_GAMERES();
//
// }
}
void cUI::process_USER_Map1( int message )
{
// if( message == MESSAGE_INIT)
// {
// TIME_PAUSE_OFF();
//
// game_sub_state = GAME_STATE_MAP;
//
// m_lastTileX = -1;
// m_lastTileY = -1;
// m_oldLevelX = -1;
// m_oldLevelY = -1;
//
// // g_pGame->getEntity(GAMESPRITE_MAIN_CHAR)->m_posX = 100;
// // g_pGame->getEntity(GAMESPRITE_MAIN_CHAR)->m_posY = 140;
//
// Set_Camera_Position(g_pGame->getEntity(GAMESPRITE_MAIN_CHAR) );
//
// softkey_init(SOFTKEY_SYMBOL_MENU,SOFTKEY_SYMBOL_EMPTY);
//
// FISHING_EFF->SetCurrentAnimation(0,ANIM_FISHING_EFF_UI_2, true);
// FISHING_EFF->SetCurrentAnimation(1,ANIM_FISHING_EFF_EFF, false);
//
// while( !FISHING_EFF->Is_animDone(1) )
// {
// FISHING_EFF->UpdateAnimation(1);
// }
//
// for(int i = 0 ; i < FISH_BALL_EA ; i++)
// {
// f_ballPos[FISH_BALL_EA + i] = -1;
// }
// //////////////
// //vel = FISH_BALL_MIN_SPEED + ( 40 / 40 ) * (FISH_BALL_MAX_SPEED-FISH_BALL_MIN_SPEED);
// //f_firePos = 47 + 8; // RND(0,3); 47
// //f_firePos -= f_firePos%vel;
// //set_Ball();
//
//
//
// }
// else if( message == MESSAGE_UPDATE)
// {
//// mascot_Keyupdate();
// popup_update();
//
//// g_pGame->UpdateCinematic();
//
// if ( g_pGame->getEntity(GAMESPRITE_MAIN_CHAR) != NULL)
// {
// int _direct = 0;
//
// if ( g_pGame->IsCinematicActive() )
// {
// if ( !g_pGame->IsCinematicRunning() )
// {
// if( KEY_PRESSED(GAME_KEY_ALL_ACTION))
// {
// g_pGame->ResumeCinematics();
// }
// }
// }
// else
// {
//
// _direct = Set_KeyEvent();
// }
// if( fish_Catch <= 0)
// {
//
// g_pGame->getEntity(GAMESPRITE_MAIN_CHAR)->set_direct(_direct);
//
// set_move( g_pGame->getEntity(GAMESPRITE_MAIN_CHAR) , 0 );
// }
//
// if ( !g_pGame->IsCinematicActive() )
// {
// Set_FollowEntity( g_pGame->getEntity(GAMESPRITE_MAIN_CHAR) , g_pGame->getEntity(GAMESPRITE_CHICK) );
// }
//
// Set_Camera_Position(g_pGame->getEntity(GAMESPRITE_MAIN_CHAR) );
//
// //update_Zone();
//
// Update_Entity( );
//
// if(sp_BFishing == 1)
// {
// if(KEY_PRESSED(GAME_KEY_1))
// {
// sp_BFishing = 2;
//
// int setAniNumber = ANIM_MAINCHARACTER_FISHING_BASIC_DOWN ;//+ g_pGame->getEntity(GAMESPRITE_MAIN_CHAR)->m_dirBefore-1;
// g_pGame->getEntity(GAMESPRITE_MAIN_CHAR)->setAnim(CHARSLOT::k_slot_boby,setAniNumber);
// CHAR_PAUSE_OFF();
// }
// else if(KEY_PRESSED(GAME_KEY_2))
// {
// sp_BFishing = 3;
//
// int setAniNumber = ANIM_MAINCHARACTER_NET_BASIC_DOWN ;//+ g_pGame->getEntity(GAMESPRITE_MAIN_CHAR)->m_dirBefore-1;
//
// g_pGame->getEntity(GAMESPRITE_MAIN_CHAR)->setAnim(CHARSLOT::k_slot_boby,setAniNumber);
// CHAR_PAUSE_OFF();
// }
// else if(KEY_PRESSED(GAME_KEY_3))
// {
// sp_BFishing = 0;
// CHAR_PAUSE_OFF();
// SET_FLAG(g_pGame->m_CharAbility, CHAR_RAPID_FOOD);
//
// }
// else if(KEY_PRESSED(GAME_KEY_4))
// {
// sp_BFishing = 0;
// CHAR_PAUSE_OFF();
// }
// //if( KEY_PRESSED(GAME_KEY_ALL_UP) )
// //{
//
// //}
// //else if( KEY_PRESSED(GAME_KEY_ALL_DOWN) )
// //{
//
// //}
// //else if( KEY_PRESSED(GAME_KEY_MENU_ALL_ACTION) )
// //{
// // sp_BFishing = 2;
//
// // int setAniNumber = ANIM_MAINCHARACTER_FISHING_BASIC_DOWN ;//+ g_pGame->getEntity(GAMESPRITE_MAIN_CHAR)->m_dirBefore-1;
//
// // g_pGame->getEntity(GAMESPRITE_MAIN_CHAR)->setAnim(CHARSLOT::k_slot_boby,setAniNumber);
// // g_pGame->m_chrMove_pause = false;
// //}
//
// }
// else if(sp_BFishing == 2 || sp_BFishing == 3)
// {
// if ( ! (g_pGame->m_colMap_water > 0) )
// {
// sp_BFishing = 0;
// }
// }
// else if(sp_BFishing == 4)
// {
// if ( ! (g_pGame->m_colMap_water > 0) )
// {
// sp_BFishing = 0;
// }
// if( !g_pGame->getEntity(17)->isAnimOver(0) )
// {
// switch(g_pGame->getEntity(GAMESPRITE_MAIN_CHAR)->getCurrentAnim(CHARSLOT::k_slot_boby))
// {
// case ANIM_MAINCHARACTER_NET_BASIC_DOWN:
// case ANIM_MAINCHARACTER_NET_BASIC_DOWN+4:
// g_pGame->getEntity(17)->m_posY += 4;
// break;
// case ANIM_MAINCHARACTER_NET_BASIC_UP:
// case ANIM_MAINCHARACTER_NET_BASIC_UP+4:
// g_pGame->getEntity(17)->m_posY -= 4;
// break;
// case ANIM_MAINCHARACTER_NET_BASIC_RIGHT:
// case ANIM_MAINCHARACTER_NET_BASIC_RIGHT+4:
// g_pGame->getEntity(17)->m_posX += 4;
// break;
// case ANIM_MAINCHARACTER_NET_BASIC_LEFT:
// case ANIM_MAINCHARACTER_NET_BASIC_LEFT+4:
// g_pGame->getEntity(17)->m_posX -= 4;
// break;
// }
// }
// else
// {
// sp_BFishing = 5;
//
// //g_pGame->getEntity(17)->setAniLoop(0,false);
// }
// if(g_pGame->getEntity(17)->m_OFFposX < 0 || g_pGame->getEntity(17)->m_OFFposX > SCREEN_WIDTH
// || g_pGame->getEntity(17)->m_OFFposY < 0 || g_pGame->getEntity(17)->m_OFFposY > SCREEN_HEIGHT )
// {
// sp_BFishing = 5;
// g_pGame->s_cUI->fish_Catch = -1;
// }
//
//
// }
//
//
// if (sp_BFishing == 0 && g_pGame->m_colMap_water > 0 )
// {
// if( KEY_PRESSED(GAME_KEY_MENU_ALL_ACTION) )
// {
// sp_BFishing = 1;
// CHAR_PAUSE_ON();
// }
// }
// else if(sp_BFishing == 3 && g_pGame->m_colMap_water > 0 )
// {
// if(KEY_PRESSED_OR_HELD(GAME_KEY_MENU_ALL_ACTION))
// {
//
//
// }
//
// if(KEY_RELEASE(GAME_KEY_MENU_ALL_ACTION) )
// {
// CHAR_PAUSE_ON();
// sp_BFishing = 4;
//
// g_pGame->getEntity(17)->unsetSpriteFlag(ETCSLOT::k_slot_boby , FLAG_DONTDRAW);
//
// g_pGame->getEntity(17)->m_posX = g_pGame->getEntity(GAMESPRITE_MAIN_CHAR)->m_posX;
// g_pGame->getEntity(17)->m_posY = g_pGame->getEntity(GAMESPRITE_MAIN_CHAR)->m_posY;
//
// switch(g_pGame->getEntity(GAMESPRITE_MAIN_CHAR)->getCurrentAnim(CHARSLOT::k_slot_boby))
// {
// case ANIM_MAINCHARACTER_NET_BASIC_DOWN:
// case ANIM_MAINCHARACTER_NET_BASIC_DOWN+4:
// g_pGame->getEntity(17)->m_posY += 25;
// break;
// case ANIM_MAINCHARACTER_NET_BASIC_UP:
// case ANIM_MAINCHARACTER_NET_BASIC_UP+4:
// g_pGame->getEntity(17)->m_posY -= 25;
// break;
// case ANIM_MAINCHARACTER_NET_BASIC_RIGHT:
// case ANIM_MAINCHARACTER_NET_BASIC_RIGHT+4:
// g_pGame->getEntity(17)->m_posX += 25;
// break;
// case ANIM_MAINCHARACTER_NET_BASIC_LEFT:
// case ANIM_MAINCHARACTER_NET_BASIC_LEFT+4:
// g_pGame->getEntity(17)->m_posX -= 25;
// }
// VIBRATE(500);
// g_pGame->getEntity(17)->setAniLoop(0,false);
// g_pGame->getEntity(17)->setAnim(0,0);
// }
// }
//
// FISHING_EFF->UpdateAnimation(0);
// if( !FISHING_EFF->Is_animDone(1) )
// {
// FISHING_EFF->UpdateAnimation(1);
// }
//
// }
//
//
// }
// else if( message == MESSAGE_PAINT)
// {
//
// draw_Start_Channel();
//
// g_pGame->updateAndDrawViewTop();
//
// //g->EnableGrayEffect();
//
// draw_End_Channel();
//
//
//
// if(sp_BFishing == 1)
// {
// //g->SetARGBColor(0xB4000000);
// //g->SetARGBColor(0xff000000);
//
// g->SetColor(0x8c6d00);
// g->DrawRect(SCREEN_HALF_WIDTH-50,SCREEN_HALF_HEIGHT - 60,100,120);
// g->SetColor(0xffc600);
// g->FillRect(SCREEN_HALF_WIDTH-50 + 1,SCREEN_HALF_HEIGHT - 60 + 1,100 - 1,120 - 1);
//
// //g->SetARGBColor(0xffffffff);
// DRAW_KORSTR(g,"1 . NET", SCREEN_HALF_WIDTH-40, SCREEN_HALF_HEIGHT - 50, Graphics::TOP | Graphics::LEFT, 0xffffff);
// DRAW_KORSTR(g,"2 . casting net", SCREEN_HALF_WIDTH-40, SCREEN_HALF_HEIGHT - 50 + 20, Graphics::TOP | Graphics::LEFT, 0xffffff);
// DRAW_KORSTR(g,"3 . Rapid Walk", SCREEN_HALF_WIDTH-40, SCREEN_HALF_HEIGHT - 50 + 40, Graphics::TOP | Graphics::LEFT, 0xffffff);
// DRAW_KORSTR(g,"4 . EXIT", SCREEN_HALF_WIDTH-40, SCREEN_HALF_HEIGHT - 50 + 60, Graphics::TOP | Graphics::LEFT, 0xffffff);
// }
//
//
// if ( fish_Catch > 0 && g_pGame->m_colMap_water > 0 )
// {
//
//
// int x = g_pGame->getEntity(GAMESPRITE_MAIN_CHAR)->m_OFFposX;
// int y = g_pGame->getEntity(GAMESPRITE_MAIN_CHAR)->m_OFFposY - 50;
// if(x < 60)
// {
// x += (60-x);
// }
// else if(x > SCREEN_WIDTH-60)
// {
// x -= (60 - (SCREEN_WIDTH - x));
// }
//
// //drawFishing(x,y);
//
// fish_Game(x,y);
//
//
// }
// else if(fish_Catch == -1)
// {
// fish_Catch = 0;
// sp_BFishing = 3;
// g_pGame->getEntity(17)->setSpriteFlag(ETCSLOT::k_slot_boby , FLAG_DONTDRAW);
// CHAR_PAUSE_OFF();
// }
//
// g_pGame->Draw_MainUI();
//
// g_pGame->drawClock ();
//
// softkey_paint(false);
//
//
// }
// else if( message == MESSAGE_EXIT)
// {
//
// // SAFE_DEL(Boy_Object);
//
// SOUND_STOP( );
//
// FREE_GAMERES();
//
// }
}
void cUI::process_USER_Chapter( int message )
{
//if( message == MESSAGE_INIT)
//{
//
// TIME_PAUSE_OFF();
// //g_pGame->Stop_FireWork();//485
// //game_sub_state = GAME_STATE_MAP;
// m_lastTileX = -1;
// m_lastTileY = -1;
// m_oldLevelX = -1;
// m_oldLevelY = -1;
// Set_Camera_Position(g_pGame->getEntity(GAMESPRITE_MAIN_CHAR) );
//// g_pGame->SaveLoad_MapRecord(0, false );
// g_pGame->Get_UserMapRecord( 0 );
//
//// if ( m_StateStory == STORY_OPENNING_END )
//// {
//// g_pGame->ResetCinematic(0);
//// g_pGame->StartCinematic ( 0 );
//// }
//// g_pGame->Text_freeText( TEXT_INDEX_GAME );
//// g_pGame->Text_loadTextPack( PACK_TEXT, TEXT_OPENING, TEXT_INDEX_GAME );
//// g_pGame->InitShine();
// build_state_mode = BUILD_MODE_INIT;
// mascot_hide();
//// SET_STRING_COLOR(0x000000);
// softkey_init(SOFTKEY_SYMBOL_MENU,SOFTKEY_SYMBOL_EMPTY);
//}
//else if( message == MESSAGE_UPDATE)
//{
// g_pGame->UpdateCinematic();
// if ( build_state_mode == BUILD_MODE_INIT )
// {
// int _direct = 0;
// _direct = Set_KeyEvent();
// Update_Entity( );
// g_pGame->getEntity(GAMESPRITE_MAIN_CHAR)->set_direct(_direct);
// set_move( g_pGame->getEntity(GAMESPRITE_MAIN_CHAR) , 0 );
//
// Set_FollowEntity( g_pGame->getEntity(GAMESPRITE_MAIN_CHAR) , g_pGame->getEntity(GAMESPRITE_CHICK) );
//
// Set_Camera_Position( g_pGame->getEntity(GAMESPRITE_MAIN_CHAR) );
// if ( KEY_PRESSED(GAME_KEY_MENU_PRE_ACTION) )
// {
// build_state_mode = BUILD_MODE_MENU;
// build_staet_type = 0;
// }
// }
// else if ( build_state_mode == BUILD_MODE_MENU )
// {
// if( KEY_PRESSED(GAME_KEY_ALL_UP) )
// {
// build_staet_type++;
// if ( build_staet_type > 8 )
// {
// build_staet_type = 0;
// }
// }
// else if( KEY_PRESSED(GAME_KEY_ALL_DOWN) )
// {
// build_staet_type--;
// if ( build_staet_type < 0 )
// {
// build_staet_type = 8;
// }
// }
// else if ( KEY_PRESSED(GAME_KEY_MENU_ALL_ACTION) )
// {
// build_state_mode = BUILD_MODE_ACTIVE;
// build_posX = (g_pGame->getEntity(GAMESPRITE_MAIN_CHAR)->m_posX);
// build_posY = (g_pGame->getEntity(GAMESPRITE_MAIN_CHAR)->m_posY);
// }
// else if ( KEY_PRESSED(GAME_KEY_MENU_PRE_ACTION) )
// {
// build_state_mode = BUILD_MODE_INIT;
// }
// }
// else if ( build_state_mode == BUILD_MODE_ACTIVE )
// {
// if( KEY_PRESSED(GAME_KEY_ALL_LEFT) )
// {
// build_posX -= TILE_W;
// }
// else if( KEY_PRESSED(GAME_KEY_ALL_RIGHT) )
// {
// build_posX += TILE_W;
// }
// else if( KEY_PRESSED(GAME_KEY_ALL_UP) )
// {
// build_posY -= TILE_H;
// }
// else if( KEY_PRESSED(GAME_KEY_ALL_DOWN) )
// {
// build_posY += TILE_H;
// }
// if ( build_posX < 0 ) build_posX = 0;
// else if ( build_posX > (g_pGame->m_tileMapW*16) ) build_posX = (g_pGame->m_tileMapW*16);
// if ( build_posY < 0 ) build_posY = 0;
// else if ( build_posY > (g_pGame->m_tileMapH*16) ) build_posY = (g_pGame->m_tileMapH*16);
// Set_Camera_Position( build_posX, build_posY );
// if ( KEY_PRESSED(GAME_KEY_MENU_PRE_ACTION) )
// {
// build_state_mode = BUILD_MODE_INIT;
// }
// else if ( KEY_PRESSED(GAME_KEY_MENU_ALL_ACTION) )
// {
// if ( ENTITY::k_max > g_pGame->m_actorsMax_count )
// {
// short* params= GL_NEW short[ACTOR_MAPOBJECT_MAX];
// params[ACTOR_GTSID] = GAMESPRITE_BUILDING;
// params[ACTOR_GAMEID] = 0; //STATE
// params[ACTOR_POSX] = build_posX;//<<4;//TILE_W;
// params[ACTOR_POSY] = build_posY;//<<4;//TILE_H;
// params[ACTOR_ANIID] = build_staet_type;
// params[ACTOR_FLAGS] = 0;
// params[ACTOR_COUNT] = g_pGame->m_actorsNew_count;
// g_pGame->Add_UserEntity( params, true ) ;
// // SAFE_DEL(g_pGame->getEntity(g_pGame->m_actorsMax_count));
// // g_pGame->getEntity(g_pGame->m_actorsMax_count) = GL_NEW cEntity( params[ACTOR_GTSID], 1 );
// // g_pGame->getEntity(g_pGame->m_actorsMax_count++)->init(params[ACTOR_FLAGS], params[ACTOR_POSX], params[ACTOR_POSY], params, ACTOR_MAPOBJECT_MAX);
// // g_pGame->m_actorsNew_count ++;
// SAFE_DEL_ARRAY(params);
// }
// else
// {
// build_state_mode = BUILD_MODE_INIT;
// }
// }
//
//
// }
//}
//else if( message == MESSAGE_PAINT)
//{
// g_pGame->updateAndDrawViewTop();
//
// if ( build_state_mode == BUILD_MODE_MENU )
// {
// g->SetColor(0x8c6d00);
// g->DrawRect(SCREEN_HALF_WIDTH-50,SCREEN_HALF_HEIGHT - 60,100,120);
// g->SetColor(0xffc600);
// g->FillRect(SCREEN_HALF_WIDTH-50 + 1,SCREEN_HALF_HEIGHT - 60 + 1,100 - 1,120 - 1);
//
// RES_BUILD->PaintFrame( g, build_staet_type , SCREEN_HALF_WIDTH , SCREEN_HALF_HEIGHT+20, 0, 0, 0);
// }
// else if ( build_state_mode == BUILD_MODE_ACTIVE )
// {
//// si->m_posX = (m_posX - ox) + x;
//// si->m_posY = (m_posY - oy) + y;
// RES_BUILD->PaintFrame( g, build_staet_type , build_posX-g_pGame->m_mapX, build_posY-g_pGame->m_mapY, 0, 0, 0);
// // Set_Camera_Position( build_posX*20, build_posY*20 );
// }
//// g_pGame->drawClock ();
//// draw_Channel();
// //popup_paint();
//// mascot_paint();
//}
//else if( message == MESSAGE_EXIT)
//{
//// SAFE_DEL(Boy_Object);
//// g_pGame->Text_freeText( TEXT_INDEX_GAME );
//// g_pGame->Text_freeText( TEXT_INDEX_MAP );
// SOUND_STOP( );
// FREE_GAMERES();
//}
}
void cUI::draw_Interface()
{
int pos_x = 0;
int pos_y = 0;
Draw_Number(g_pGame->COMMON_SPRITE_NUMBER,10,pos_y,15,0,DIRECT_LEFT,4);
}
void cUI::fish_Game(int _x , int _y)
{
int i;
for(i = 0 ; i < 2 ; i++)
{
f_ballPos[i] += f_ballVel[i];
if(f_ballPos[i] < 0)
{
f_ballVel[i] = vel/(2-i);
}
else if(f_ballPos[i] > 47<<1 )
{
f_ballVel[i] = -vel/(2-i);
}
}
if( KEY_PRESSED(GAME_KEY_ALL_ACTION) )
{
if(isInFireZone(1))
{
// FISHING_EFF->ClearAnimation(1,false);
f_ballVel[1] = 0;
f_ballVel[0] = 0;
// FONT_EFF->SetCurrentAnimation(0,ANIM_FONT_EFFECT_GOOD_1 + g_pGame->random(0,1), true);
isFire = 1;
}
else
{
f_ballVel[0] = 0;
f_ballVel[1] = 0;
// FONT_EFF->SetCurrentAnimation(0,ANIM_FONT_EFFECT_BAD_1 + g_pGame->random(0,1), true);
isFire = 2;
}
}
if( !(isFire == 2 || (isFire == 1 /*&& FISHING_EFF->Is_animDone(1)*/) ) )
{
// FISHING_EFF->PaintFrame(g, FRAME_FISHING_EFF_BG, _x , _y, 0, 0, 0);
// FISHING_EFF->PaintFrame(g, FRAME_FISHING_EFF_FIRE, _x - 47 + f_ballPos[0] , _y, 0, 0, 0);
//if(f_ballVel[1] != 0)
if( isFire == 0 )
{
// FISHING_EFF->PaintFrame(g, FRAME_FISHING_EFF_ARROW_LEFT, _x - 47 + f_ballPos[1] , _y , 0, 0, 0);
}
// if( !FISHING_EFF->Is_animDone(1) )
{
//FISHING_EFF->PaintAnimation(g, 1, _x - 47 + f_ballPos[0] , _y, 0, 0, 0);
}
//FISHING_EFF->PaintAnimation(g, 0, _x, _y, 0, 0, 0);
}
// if(!FONT_EFF->Is_animDone(0))
{
// FONT_EFF->UpdateAnimation(0);
// FONT_EFF->PaintAnimation(g, 0, _x , _y - 30 , 0, 0, 0);
setBall_cnt++;
if(setBall_cnt > 25)
{
fish_Catch = 0;
// FONT_EFF->setAnimStop(0);
if(sp_BFishing == 5)
{
g_pGame->getEntity(17)->setSpriteFlag(ETCSLOT::k_slot_boby , FLAG_DONTDRAW);
sp_BFishing = 3;
CHAR_PAUSE_OFF();
}
}
}
}
void cUI::fish_Game1(int _x , int _y)
{
int i;
//#define FISH_BALL_EA 3
//f_firePos //
//f_ballPos[2*FISH_BALL_EA]
//f_ballVel[FISH_BALL_EA]
//set_ball()
isFire = -1;
if( KEY_PRESSED(GAME_KEY_UP))
{
// isFire = FRAME_FISHING_EFF_ARROW_UP;
}
else if( KEY_PRESSED(GAME_KEY_DOWN) )
{
// isFire = FRAME_FISHING_EFF_ARROW_DOWN;
}
else if( KEY_PRESSED(GAME_KEY_LEFT) )
{
// isFire = FRAME_FISHING_EFF_ARROW_LEFT;
}
else if( KEY_PRESSED(GAME_KEY_RIGHT) )
{
// isFire = FRAME_FISHING_EFF_ARROW_RIGHT;
}
////////////////////////
for(i = 0 ; i < FISH_BALL_EA ; i++)
{
if( f_ballPos[FISH_BALL_EA + i] > -1 )
{
f_ballPos[i] += vel; //f_ballVel[i];
//f_ballPos[1 + i*2] += f_ballVel[i];
if(f_ballPos[i] == vel * (8 + (10 - vel)* (2 - (vel/5)) ) ) // (12 + 10 - vel)
{
set_Ball();
}
if(f_ballPos[i] > 94)
{
f_ballVel[i] = 0;
f_ballPos[FISH_BALL_EA + i] = -1;
}
if(isFire > -1 && f_ballVel[i] != 0 && isInFireZone(i) )
{
if(isFire == f_ballPos[FISH_BALL_EA + i])
{
f_ballVel[i] = 0;
// FISHING_EFF->ClearAnimation(1,false);
}
}
}
}
// FISHING_EFF->PaintFrame(g, FRAME_FISHING_EFF_BG, _x - 47 + f_firePos , _y, 0, 0, 0);
// FISHING_EFF->PaintFrame(g, FRAME_FISHING_EFF_FIRE, _x - 47 + f_firePos , _y, 0, 0, 0);
for(i = 0 ; i < FISH_BALL_EA ; i++)
{
if(f_ballVel[i] != 0)
{
FISHING_EFF->PaintFrame(g, f_ballPos[FISH_BALL_EA + i], _x - 47 + f_ballPos[i] , _y , 0, 0, 0);
}
}
// if( !FISHING_EFF->Is_animDone(1) )
{
// FISHING_EFF->PaintAnimation(g, 1, _x - 47 + f_firePos , _y, 0, 0, 0);
}
// FISHING_EFF->PaintAnimation(g, 0, _x, _y, 0, 0, 0);
}
void cUI::set_init_Ball()
{
vel = FISH_BALL_MIN_SPEED + ( fish_Catch / 40 ) * (FISH_BALL_MAX_SPEED-FISH_BALL_MIN_SPEED);
f_firePos = 47 + 8; // RND(0,3); 47
f_firePos -= f_firePos%vel;
setBall_cnt = 0;
set_Ball();
/////aaa
f_ballPos[0] = 47;
f_ballVel[0]= -vel;
f_ballVel[1]= vel;
isFire = 0;
}
void cUI::set_Ball()
{
int i;
setBall_cnt++;
if(setBall_cnt > 5)
{
fish_Catch = 0;
return;
}
for(i = 0 ; i < FISH_BALL_EA ; i++)
{
if( f_ballPos[FISH_BALL_EA + i] == -1)
{
f_ballPos[i] = 0;
// f_ballPos[FISH_BALL_EA + i] = FRAME_FISHING_EFF_ARROW_LEFT+ RND(0,3) ;
f_ballVel[i] = vel;
break;
}
}
}
bool cUI::isInFireZone(int index)
{
bool _temp = false;
//if( f_ballPos[index] >= f_firePos - (FISH_BALL_SIZEW>>1) && f_ballPos[index] <= f_firePos + (FISH_BALL_SIZEW>>1))
if(f_ballPos[index] >= f_ballPos[0] - (FISH_BALL_SIZEW>>1) - ABS(f_ballVel[1]) && f_ballPos[index] <= f_ballPos[0] + (FISH_BALL_SIZEW>>1) + ABS(f_ballVel[1]) )
{
_temp = true;
}
return _temp;
}
void cUI::Set_Chage_map( int _collnum )
{
switch(_collnum)
{
case COL_TILES::k_door0:
if ( g_pGame->m_map_kind == WORLD_MAP1 )
{
g_pGame->goto_map( STATE_DRAW_HOUSE );
}
else if ( g_pGame->m_map_kind == HOUSE_MYHOME )
{
g_pGame->goto_map( STATE_DRAW_MAP1 );
}
else if ( g_pGame->m_map_kind == CHAPTER_1 )
{
g_pGame->goto_map( STATE_DRAW_MAP1 );
}
// pushState(STATE_DRAW_MAP,true);
// g_pGame->hero_mosX = 380*TILE_W/20;
// g_pGame->hero_mosY = 500*TILE_W/20;
break;
case COL_TILES::k_door1:
if ( g_pGame->m_map_kind == WORLD_MAP1 )
{
g_pGame->goto_map( STATE_DRAW_CHAPTER );
}
// g_pGame->m_map_kind = MAP_WORLD;
// pushState(STATE_DRAW_MAP,true);
// g_pGame->hero_mosX = 716*TILE_W/20;
// g_pGame->hero_mosY = 491*TILE_W/20;
// g_pGame->goto_map( STATE_DRAW_HOUSE );
break;
}
}
void cUI::update_Zone()
{
for(int i = ZONES::k_start ; i < ZONES::k_max ; i++)
{
if(g_pGame->collideWithZone(i))
{
switch(i)
{
case ZONES::k_door_0:
if ( g_pGame->m_map_kind == WORLD_MAP1 )
{
g_pGame->goto_map( STATE_DRAW_HOUSE );
}
else if ( g_pGame->m_map_kind == HOUSE_MYHOME )
{
g_pGame->goto_map( STATE_DRAW_MAP1 );
}
// pushState(STATE_DRAW_MAP,true);
// g_pGame->hero_mosX = 380*TILE_W/20;
// g_pGame->hero_mosY = 500*TILE_W/20;
break;
case ZONES::k_door_1:
if ( g_pGame->m_map_kind == WORLD_MAP1 )
{
g_pGame->goto_map( STATE_DRAW_CHAPTER );
}
// g_pGame->m_map_kind = MAP_WORLD;
// pushState(STATE_DRAW_MAP,true);
// g_pGame->hero_mosX = 716*TILE_W/20;
// g_pGame->hero_mosY = 491*TILE_W/20;
// g_pGame->goto_map( STATE_DRAW_HOUSE );
break;
}
}
}// End for(int i = ZONES::k_start ; i < ZONES::k_max ; i++){
}
//Module_Move.hpp
//int m_CameraX;
//int m_CameraY;
// Auto move variable
int auto_move;
cUI::cUI()
{
moveState = MOVESTATE_WALK ;
stackA = -1;
stackCnt = 0;
stackB = -1;
// change_active = false;
// change_size = 0;
// change_direct = 0;
// change_Maxsize = 0;
// change_count = 0;
// change_replay = 0;
// displayResetInfo = false;
// player = GL_NEW cXPlayerMenus(g_pGame,g_pGame->jFont);
//if(player)
//{
// //MC_knlCreateSharedBuf( (const M_Char *)"pXPlayer", sizeof(cXPlayerMenus*) );
// //player = new cXPlayerMenus( instance_, cKFont_ );
// //minh_dang *(cXPlayerMenus**)MC_GETDPTR((void*)MC_knlGetSharedBuf((const M_Char *)"pXPlayer")) = player;
// g_pGame->Xplayer_share_buff = (void *)player ;
//}
}
cUI::~cUI()
{
// SAFE_DEL_ARRAY(menu_List);
SAFE_DEL_ARRAY(menu_str);
// SAFE_DEL_ARRAY_OBJ(npc_Object,npc_Object_length);
// SAFE_DEL_ARRAY(Draw_Order);
// SAFE_DEL_ARRAY(temp_Order);
SAFE_DEL_ARRAY(str_version);
// cXPlayerMenus *vPtr = cXPlayerMenus::getInstance();
// SAFE_DEL(vPtr);
// SAFE_DEL(g_pGame->Xplayer_share_buff);
//MC_knlDestroySharedBuf( (void*)MC_knlGetSharedBuf() );
}
int cUI::check_move( cEntity* _obj, int _posX, int _posY )
{
if(g_pGame->m_mapCol != NULL)
{
int rect[4];
int temp_move_col;
g_pGame->getCollisionRect(rect , _obj );
temp_move_col = g_pGame->canDropObject(rect,_posX,_posY);
return temp_move_col;
}
return COL_TILES::k_oob_null;
}
void cUI::set_move( cEntity* _obj , int _auto_move)
{
// if(g_pGame->m_chrMove_pause) return;
// int _moveX = 0, _moveY = 0;
// int move_vel = (moveState == MOVESTATE_RUN)? 3:0 ;
// int _col_tile = 0;
//
//
//
// if( moveState == MOVESTATE_STOP )
// {
// move_vel = -1;
// }
// else if ( g_pGame->m_colMap_water > 0 )
// {
// g_pGame->m_colMap_count++;
// if ( g_pGame->m_colMap_count % (g_pGame->m_colMap_water+2) == 0)
// {
// g_pGame->m_colMap_count = 0;
// move_vel = -1 ;
// }
// else
// {
// move_vel = -2 ;
// }
// }
// if( (g_pGame->m_CharAbility & CHAR_RAPID_FOOD) != 0)
// {
// move_vel += 1;
// }
//
// switch ( _obj->m_dir )
// {
// case DIRECT_LEFT: _moveX = -BOY_MOVE-move_vel; break;
// case DIRECT_RIGHT: _moveX = BOY_MOVE+move_vel; break;
// case DIRECT_UP: _moveY = -BOY_MOVE-move_vel; break;
// case DIRECT_DOWN: _moveY = BOY_MOVE+move_vel; break;
// }
//
//
// if ( _obj->m_posX+_moveX < MOVE_LIMITE_STARTX || _obj->m_posX + _moveX > MOVE_LIMITE_ENDX )
// {
// _moveX = 0;
// }
// else if ( _obj->m_posY+_moveY < MOVE_LIMITE_STARTY || _obj->m_posY+_moveY > MOVE_LIMITE_ENDY )
// {
// _moveY = 0;
// }
//
// _obj->m_posX += _moveX;
// _obj->m_posY += _moveY;
//
// _col_tile = check_move( _obj, _obj->m_posX, _obj->m_posY );
//
// g_pGame->m_colMap_water = 0;
//
// if( _col_tile != COL_TILES::k_oob_null)
// {
// if( _col_tile > COL_TILES::k_can_move && _col_tile < COL_TILES::k_door0 )
// {
// // check direction
// _obj->m_posX -= _moveX;
// _obj->m_posY -= _moveY;
//
// g_pGame->m_colMap_hold = false;
//
// if( _col_tile == COL_TILES::k_cant_move_stop )
// {
// g_pGame->m_colMap_hold = true;
// }
// else
// {
// if(_auto_move == 0)
// {
// int tempx = 0;
// int tempy = 0;
// int _coltemp = 0;
//
// _auto_move ++;
//
// if(_moveX != 0)
// {
// for(int _i = 1 ; _i < 100 ; _i++)
// {
// _coltemp = check_move( _obj, _obj->m_posX+_moveX, _obj->m_posY+_moveY+(2*_i));
// //if(check_move( _obj, _obj->m_posX+_moveX, _obj->m_posY+_moveY+(2*_i) ) == COL_TILES::k_can_move)
// if( _coltemp == COL_TILES::k_can_move || (_coltemp >= COL_TILES::k_door0 && _coltemp <= COL_TILES::k_door3) )
// {
// _obj->m_dir = DIRECT_DOWN ;
// break;
// }
//
// tempy = ((_obj->m_posY+_moveY-(2*_i)) < 0 )?0:(_obj->m_posY+_moveY-(2*_i));
//
// _coltemp = check_move( _obj,_obj->m_posX+_moveX, tempy );
// //if( check_move( _obj,_obj->m_posX+_moveX, tempy ) == COL_TILES::k_can_move )
// if( _coltemp == COL_TILES::k_can_move || (_coltemp >= COL_TILES::k_door0 && _coltemp <= COL_TILES::k_door3) )
// {
// _obj->m_dir = DIRECT_UP ;
// break;
// }
// }
// }
// else if(_moveY != 0)
// {
// for(int _i = 1 ; _i < 100 ; _i++)
// {
// _coltemp = check_move( _obj, _obj->m_posX + _moveX + (2*_i), _obj->m_posY + _moveY );
// //if(check_move( _obj, _obj->m_posX + _moveX + (2*_i), _obj->m_posY + _moveY ) == COL_TILES::k_can_move)
// if( _coltemp == COL_TILES::k_can_move || (_coltemp >= COL_TILES::k_door0 && _coltemp <= COL_TILES::k_door3) )
// {
// _obj->m_dir = DIRECT_RIGHT ;
// break;
// }
//
// tempx = ((_obj->m_posX+_moveX-(2*_i))< 0 )?0:(_obj->m_posX+_moveX-(2*_i));
// _coltemp = check_move( _obj, tempx ,_obj->m_posY + _moveY );
// //if(check_move( _obj, tempx ,_obj->m_posY + _moveY ) == COL_TILES::k_can_move)
// if( _coltemp == COL_TILES::k_can_move || (_coltemp >= COL_TILES::k_door0 && _coltemp <= COL_TILES::k_door3) )
// {
// _obj->m_dir = DIRECT_LEFT ;
// break;
// }
// }
// }
// set_move(_obj , _auto_move);
// }
// }
// }
// else if ( _col_tile >= COL_TILES::k_door0 && _col_tile <= COL_TILES::k_door3 )
// {
//
// _obj->setFlag(DFLAGS::HIDE_LAYER);
// Set_Chage_map( _col_tile );
// //return;
// }
// else if ( _col_tile >= COL_TILES::k_water1 )
// {
// g_pGame->m_colMap_water = _col_tile;
//
// //_obj->m_renderer[CHARSLOT::k_slot_etc]->m_posOffY = -((_col_tile-COL_TILES::k_water1)*2);
//
// moveState = MOVESTATE_WALK;
// }
//
// if(g_pGame->m_colMap_water > 0)
// {
// _obj->setSpriteLayer(CHARSLOT::k_slot_etc, LAYER::k_inactive);
// }
// else
// {
// _obj->setSpriteLayer(CHARSLOT::k_slot_etc, LAYER::k_hide);
// }
// }
//
//// if ( g_pGame->m_colMap_hold )
//// {
//// _obj->m_dir = DIRECT_NULL;
//// }
//
// //if(moveState == MOVESTATE_WALK )//g_pGame->getEntity(GAMESPRITE_MAIN_CHAR).isAnimOver(CHARSLOT::k_slot_etc))
// //{
// // switch ( _obj->m_dir )
// // {
// // case DIRECT_LEFT:
// // g_pGame->getEntity(ENTITY::k_main_character)->setAnim(CHARSLOT::k_slot_etc,BOY_GAME_FACE_LEFT_BLINK_EYE_ANI_INDEX);
// // break;
// // case DIRECT_RIGHT:
// // g_pGame->getEntity(ENTITY::k_main_character)->setAnim(CHARSLOT::k_slot_etc,BOY_GAME_FACE_RIGHT_BLINK_EYE_ANI_INDEX);
// // break;
// // case DIRECT_DOWN:
// // g_pGame->getEntity(ENTITY::k_main_character)->setAnim(CHARSLOT::k_slot_etc,BOY_GAME_FACE_DOWN_BLINK_EYE_ANI_INDEX);
// // break;
// // case DIRECT_UP:
// // g_pGame->getEntity(ENTITY::k_main_character)->setAnim(CHARSLOT::k_slot_etc,ANIM_EMPTY);
// // break;
// // }
// //}
// //else
// //{
// // g_pGame->getEntity(ENTITY::k_main_character)->setAnim(CHARSLOT::k_slot_etc,ANIM_EMPTY);
// //}
//
//
// if ( g_pGame->getEntity(GAMESPRITE_MAIN_CHAR)->isAnimOver(CHARSLOT::k_slot_boby) || (_obj->m_dirBefore != _obj->m_dir) )
// {
// int setAniNumber = 0;
// switch ( _obj->m_dir )
// {
// case DIRECT_LEFT:
//
// if(moveState == MOVESTATE_WALK)
// {
// setAniNumber = ANIM_MAINCHARACTER_WALK_LEFT;
//
// if(sp_BFishing == 2 && g_pGame->m_colMap_water > 0)
// {
// setAniNumber += ANIM_MAINCHARACTER_FISHING_BASIC_LEFT;
// _obj->setAnim(CHARSLOT::k_slot_etc,ANIM_MAINCHARACTER_FISHINGEFFECT_LEFT_2);
// }
// else if(sp_BFishing == 3)
// {
// setAniNumber += ANIM_MAINCHARACTER_NET_BASIC_LEFT;
// }
//
// }
// else if(moveState == MOVESTATE_RUN)
// {
// setAniNumber = ANIM_MAINCHARACTER_RUN_LEFT;
// // g_pGame->getEntity(GAMESPRITE_MAIN_CHAR)->setAnim(CHARSLOT::k_slot_effect,BOY_GAME_SMOG_LEFT_ANI_INDEX);
// }
//
// break;
// case DIRECT_RIGHT:
//
// if(moveState == MOVESTATE_WALK)
// {
// setAniNumber = ANIM_MAINCHARACTER_WALK_RIGHT;
//
// if(sp_BFishing == 2 && g_pGame->m_colMap_water > 0)
// {
// setAniNumber += ANIM_MAINCHARACTER_FISHING_BASIC_LEFT;
// _obj->setAnim(CHARSLOT::k_slot_etc,ANIM_MAINCHARACTER_FISHINGEFFECT_RIGHT_2);
// }
// else if(sp_BFishing == 3)
// {
// setAniNumber += ANIM_MAINCHARACTER_NET_BASIC_LEFT;
// }
// }
// else if(moveState == MOVESTATE_RUN)
// {
// setAniNumber = ANIM_MAINCHARACTER_RUN_RIGHT;
// // g_pGame->getEntity(GAMESPRITE_MAIN_CHAR)->setAnim(CHARSLOT::k_slot_effect,BOY_GAME_SMOG_RIGHT_ANI_INDEX);
// }
// break;
//
// case DIRECT_UP:
// if(moveState == MOVESTATE_WALK)
// {
// setAniNumber = ANIM_MAINCHARACTER_WALK_UP ;
//
// if(sp_BFishing == 2 && g_pGame->m_colMap_water > 0)
// {
// setAniNumber += ANIM_MAINCHARACTER_FISHING_BASIC_LEFT;
// _obj->setAnim(CHARSLOT::k_slot_etc,ANIM_MAINCHARACTER_FISHINGEFFECT_UP_2);
// }
// else if(sp_BFishing == 3)
// {
// setAniNumber += ANIM_MAINCHARACTER_NET_BASIC_LEFT;
// }
// }
// else if(moveState == MOVESTATE_RUN)
// {
// setAniNumber = ANIM_MAINCHARACTER_RUN_UP;
// // g_pGame->getEntity(GAMESPRITE_MAIN_CHAR)->setAnim(CHARSLOT::k_slot_effect,BOY_GAME_SMOG_UP_ANI_INDEX);
// }
//
// break;
//
// case DIRECT_DOWN:
// if(moveState == MOVESTATE_WALK)
// {
// setAniNumber = ANIM_MAINCHARACTER_WALK_DOWN ;
//
// //_obj->m_renderer[CHARSLOT::k_slot_etc]->m_nCrtModule = ANIM_MAINCHARACTER_FISHINGEFFECT_DOWN_2;
// if(sp_BFishing == 2 && g_pGame->m_colMap_water > 0)
// {
// setAniNumber += ANIM_MAINCHARACTER_FISHING_BASIC_LEFT;
// _obj->setAnim(CHARSLOT::k_slot_etc,ANIM_MAINCHARACTER_FISHINGEFFECT_DOWN_2);
// }
// else if(sp_BFishing == 3)
// {
// setAniNumber += ANIM_MAINCHARACTER_NET_BASIC_LEFT;
// }
// }
// else if(moveState == MOVESTATE_RUN)
// {
// setAniNumber = ANIM_MAINCHARACTER_RUN_DOWN;
// // g_pGame->getEntity(GAMESPRITE_MAIN_CHAR)->setAnim(CHARSLOT::k_slot_effect,BOY_GAME_SMOG_DOWN_ANI_INDEX);
// }
// break;
// }
//
// if(_obj->m_dir != DIRECT_NULL)
// {
// g_pGame->getEntity(GAMESPRITE_MAIN_CHAR)->setAnim(CHARSLOT::k_slot_boby,setAniNumber);
// }
// }
//
//
// if(moveState == MOVESTATE_STOP)
// {
// int setAniNumber = 0;
// switch ( _obj->m_dir )
// {
// case DIRECT_LEFT:
// setAniNumber = ANIM_MAINCHARACTER_STOP_LEFT;
// // g_pGame->getEntity(ENTITY::k_main_character)->setAnim(CHARSLOT::k_slot_effect,BOY_GAME_SMOG_RIGHT_ANI_INDEX);
// break;
// case DIRECT_RIGHT:
// setAniNumber = ANIM_MAINCHARACTER_STOP_RIGHT;
// // g_pGame->getEntity(ENTITY::k_main_character)->setAnim(CHARSLOT::k_slot_effect,BOY_GAME_SMOG_LEFT_ANI_INDEX);
// break;
// case DIRECT_UP:
// setAniNumber = ANIM_MAINCHARACTER_STOP_UP;
// // g_pGame->getEntity(ENTITY::k_main_character)->setAnim(CHARSLOT::k_slot_effect,BOY_GAME_SMOG_DOWN_ANI_INDEX);
// break;
// case DIRECT_DOWN:
// setAniNumber = ANIM_MAINCHARACTER_STOP_DOWN;
// // g_pGame->getEntity(ENTITY::k_main_character)->setAnim(CHARSLOT::k_slot_effect,BOY_GAME_SMOG_UP_ANI_INDEX);
// break;
// }
// g_pGame->getEntity(GAMESPRITE_MAIN_CHAR)->setAnim(CHARSLOT::k_slot_boby,setAniNumber);
//
// }
//
//
// if ( _obj->m_dir == DIRECT_NULL )
// {
// int setAniNumber = 0;
//
// if(_obj->m_dirBefore != 0)
// {
// setAniNumber = ANIM_MAINCHARACTER_BASIC_LEFT + _obj->m_dirBefore -1;
//
// if(sp_BFishing == 2)
// {
// setAniNumber += ANIM_MAINCHARACTER_FISHING_BASIC_LEFT;
// }
// else if(sp_BFishing == 3)
// {
// setAniNumber += ANIM_MAINCHARACTER_NET_BASIC_LEFT;
// }
// _obj->setAnim(CHARSLOT::k_slot_boby,setAniNumber);
// }
// _obj->m_renderer[CHARSLOT::k_slot_etc]->m_nCrtModule = ANIM_MAINCHARACTER_FISHINGEFFECT_BASIC_2;
//
// }
//
// _obj->m_dirBefore = _obj->m_dir;
}
int cUI::Set_Keypressed_Direct( )
{
int _direct = DIRECT_NULL;
if(KEY_PRESSED_OR_HELD(GAME_KEY_ALL_LEFT)) //_OR_HELD
{
_direct = DIRECT_LEFT;
}
else if(KEY_PRESSED_OR_HELD(GAME_KEY_ALL_RIGHT))
{
_direct = DIRECT_RIGHT;
}
else if(KEY_PRESSED_OR_HELD(GAME_KEY_ALL_UP))
{
_direct = DIRECT_UP;
}
else if(KEY_PRESSED_OR_HELD(GAME_KEY_ALL_DOWN))
{
_direct = DIRECT_DOWN;
}
else if(KEY_PRESSED_OR_HELD(GAME_KEY_ALL_ACTION))
{
_direct = DIRECT_CENTER;
}
else if(KEY_PRESSED_OR_HELD(GAME_KEY_ALL_1))
{
_direct = DIRECT_1;
}
//DBG("Set_Keypressed_Direct====="+_direct);
return _direct;
}
int cUI::Set_Keyrepeate_Direct( )
{
int _direct = DIRECT_NULL;
if(KEY_HELD(GAME_KEY_ALL_LEFT))
{
_direct = DIRECT_LEFT;
}
if(KEY_HELD(GAME_KEY_ALL_RIGHT))
{
_direct = DIRECT_RIGHT;
}
if(KEY_HELD(GAME_KEY_ALL_UP))
{
_direct = DIRECT_UP;
}
if(KEY_HELD(GAME_KEY_ALL_DOWN))
{
_direct = DIRECT_DOWN;
}
if(KEY_HELD(GAME_KEY_ALL_ACTION))
{
_direct = DIRECT_CENTER;
}
if(KEY_HELD(GAME_KEY_ALL_1))
{
_direct = DIRECT_1;
}
// DBG("Set_Keyrepeate_Direct====="+_direct);
return _direct;
}
static int moveState = MOVESTATE_WALK;
static int stackA = -1;
static int stackCnt = 0;
static int stackB = -1;
int cUI::Set_KeyEvent()
{
int temp_pressed = Set_Keypressed_Direct();
int temp_repeate = Set_Keyrepeate_Direct();
//DBGPRINTF("111temp_pressed = %d",temp_pressed);
//DBGPRINTF("222temp_repeate = %d",temp_repeate);
if(moveState == MOVESTATE_WALK)
{
if(temp_pressed > DIRECT_NULL)
{
if(stackA <= DIRECT_NULL) //
{
stackA = temp_pressed;
stackCnt = 0;
}
else if(stackA == temp_repeate && stackCnt > 6 )
{
moveState = MOVESTATE_RUN;
stackB = temp_repeate;
stackCnt = 0;
return temp_repeate;
}
//else //
//{
// stackA = -1;
//}
stackCnt++;
}
else
{
stackA = -1;
stackCnt = 0;
}
// DBGPRINTF("3333 stackCnt = %d",stackCnt);
// if(stackCnt > 7)
// {
// stackA = -1;
// stackCnt = 0;
// }
return temp_pressed;
}
else if(moveState == MOVESTATE_RUN )
{
// DBGPRINTF("5555 stackCnt = %d",stackCnt);
if(temp_pressed == DIRECT_NULL)
{
moveState = MOVESTATE_STOP;
stackA = -1;
}
if(temp_repeate == DIRECT_NULL) return stackB;
boolean bRunStop = false;
switch(stackB)
{
case DIRECT_LEFT:
if(temp_repeate == DIRECT_RIGHT)
{
//Stop
bRunStop = true;
}
else
{
stackB = temp_repeate;
}
break;
case DIRECT_RIGHT:
if(temp_repeate == DIRECT_LEFT)
{
//Stop
bRunStop = true;
}
else
{
stackB = temp_repeate;
}
break;
case DIRECT_UP:
if(temp_repeate == DIRECT_DOWN)
{
//Stop
bRunStop = true;
}
else
{
stackB = temp_repeate;
}
break;
case DIRECT_DOWN:
if(temp_repeate == DIRECT_UP)
{
//Stop
bRunStop = true;
}
else
{
stackB = temp_repeate;
}
break;
}
if(bRunStop)
{
moveState = MOVESTATE_STOP;
stackA = -1;
//g_pGame->getEntity(GAMESPRITE_MAIN_CHAR).setAnim(CHARSLOT::k_slot_effect,BOY_GAME_SMOG_UP_ANI_INDEX);
}
return stackB;
}
else if(moveState == MOVESTATE_STOP)
{
stackCnt++;
if(stackCnt > 0)//5)
{
stackCnt = 0;
moveState = MOVESTATE_WALK;
// g_pGame->getEntity(GAMESPRITE_MAIN_CHAR)->setAnim(CHARSLOT::k_slot_effect,BOY_GAME_NONE_ANI_INDEX);
}
return stackB;
}
return DIRECT_NULL;
}
void cUI::Set_FollowEntity( cEntity* _obj , cEntity* _target )
{
int _gapX,_gapY;
int _ABSgapX,_ABSgapY;
int _Maxgap;
int _movestate = 0;
int _Direct;
int _ActiveRun ;
int _ActiveWalk ;
_gapX = _obj->m_posX - _target->m_posX;
_gapY = _obj->m_posY - _target->m_posY;
_ABSgapX = ABS(_gapX);
_ABSgapY = ABS(_gapY);
if ( _ABSgapX > (_ABSgapY+5) )
{
_Direct = ( _gapX < 0 )?DIRECT_LEFT:DIRECT_RIGHT;
}
else
{
_Direct = ( _gapY < 0 )?DIRECT_UP:DIRECT_DOWN;
}
_Maxgap = MAX(_ABSgapX,_ABSgapY);
if ( _Direct == DIRECT_DOWN || _Direct == DIRECT_UP )
{
_ActiveRun = 10;
_ActiveWalk = 5;
}
else
{
_ActiveRun = 30;
_ActiveWalk = 20;
}
if ( _Maxgap > _ActiveRun )
{
_movestate = MOVESTATE_RUN;
}
else if ( _Maxgap > _ActiveWalk )
{
_movestate = MOVESTATE_WALK;
}
else
{
_movestate = MOVESTATE_STAND;
}
if ( g_pGame->m_colMap_water > 0 )
{
_movestate = MOVESTATE_STAND;
}
Set_Entity( _target ,_Direct , _movestate );
if ( _movestate != MOVESTATE_STAND )
{
int _col_tile = check_move( _target, _target->m_posX, _target->m_posY );
if( _col_tile != COL_TILES::k_oob_null)
{
if(_col_tile > COL_TILES::k_can_move )
{
int _moveX = 0, _moveY = 0;
int move_vel = (_movestate == MOVESTATE_RUN)? (OBJECT_MOVE+2):OBJECT_MOVE ;
switch ( _target->m_dir )
{
case DIRECT_LEFT: _moveX = -(move_vel); break;
case DIRECT_RIGHT: _moveX = (move_vel); break;
case DIRECT_UP: _moveY = -(move_vel); break;
case DIRECT_DOWN: _moveY = (move_vel); break;
}
// check direction
_target->m_posX -= _moveX;
_target->m_posY -= _moveY;
if ( _ABSgapX > (_ABSgapY+5) )
{
_Direct = ( _gapY < 0 )?DIRECT_UP:DIRECT_DOWN;
}
else
{
_Direct = ( _gapX < 0 )?DIRECT_LEFT:DIRECT_RIGHT;
}
//_target->m_dir = _Direct;
Set_Entity( _target, _Direct, _movestate );
}
}
}
}
void cUI::Set_Entity( cEntity* _target , int _direct , int _movestate)
{
/*int _AniNumber = 0 ;
int _moveX = 0, _moveY = 0;
int move_vel = (_movestate == MOVESTATE_RUN)? (OBJECT_MOVE+2):OBJECT_MOVE ;
_target->m_dir = _direct;
switch ( _target->m_dir )
{
case DIRECT_LEFT: _moveX = -(move_vel); break;
case DIRECT_RIGHT: _moveX = (move_vel); break;
case DIRECT_UP: _moveY = -(move_vel); break;
case DIRECT_DOWN: _moveY = (move_vel); break;
}
if ( _movestate != MOVESTATE_STAND )
{
switch ( _target->m_dir )
{
case DIRECT_LEFT:
_target->m_posX += _moveX;
_AniNumber = ANIM_CHICK_BASIC_LEFT;
break;
case DIRECT_RIGHT:
_target->m_posX += _moveX;
_AniNumber = ANIM_CHICK_BASIC_RIGHT;
break;
case DIRECT_UP:
_target->m_posY += _moveY;
_AniNumber = ANIM_CHICK_BASIC_UP;
break;
case DIRECT_DOWN:
_target->m_posY += _moveY;
_AniNumber = ANIM_CHICK_BASIC_DOWN;
break;
}
if ( _movestate != MOVESTATE_STAND )
{
_AniNumber += ANIM_CHICK_WALK_LEFT;
}
_target->setAnim( CHARSLOT::k_slot_boby,_AniNumber );
}*/
}
void cUI::Set_Camera_Position( cEntity* _obj )
{
int _cameraGapX = 0;
int _cameraGapY = 0;
_cameraGapX = SCR_W >> 1;
_cameraGapY = (SCR_H >> 1);
g_pGame->m_mapX = _obj->m_posX - _cameraGapX;
g_pGame->m_mapY = _obj->m_posY - _cameraGapY;
SET_NUMBER_SMALL(g_pGame->m_mapX , SV_X);
SET_NUMBER_SMALL(g_pGame->m_mapY , SV_Y);
SET_NUMBER_LARGE(g_pGame->m_mapX , g_pGame->m_tileMapW*TILE_W-SCR_W);
SET_NUMBER_LARGE(g_pGame->m_mapY , g_pGame->m_tileMapH*TILE_H-SCR_H);
}
void cUI::Set_Camera_Position( int _x , int _y )
{
int _cameraGapX = 0;
int _cameraGapY = 0;
_cameraGapX = SCR_W >> 1;
_cameraGapY = (SCR_H >> 1);
g_pGame->m_mapX = _x - _cameraGapX;
g_pGame->m_mapY = _y - _cameraGapY;
SET_NUMBER_SMALL(g_pGame->m_mapX , SV_X);
SET_NUMBER_SMALL(g_pGame->m_mapY , SV_Y);
SET_NUMBER_LARGE(g_pGame->m_mapX , g_pGame->m_tileMapW*TILE_W-SCR_W);
SET_NUMBER_LARGE(g_pGame->m_mapY , g_pGame->m_tileMapH*TILE_H-SCR_H);
}
void cUI::Update_Entity( )
{
// for (int i = 0; i < ENTITY::k_max; i++)
for (int i = 0; i < g_pGame->m_actorsMax_count; i++)
{
if ( g_pGame->getEntity(i) != NULL && !((g_pGame->getEntity(i)->m_flags & DFLAGS::HIDE_LAYER) != 0))
{
g_pGame->getEntity(i)->update();
}
}
}
void cUI::Update_Entity_ShowLayer ( )
{
// for (int i = 0; i < ENTITY::k_max; i++)
for (int i = 0; i < g_pGame->m_actorsMax_count; i++)
{
if ( g_pGame->getEntity(i) != NULL && ((g_pGame->getEntity(i)->m_flags & DFLAGS::HIDE_LAYER) != 0))
{
g_pGame->getEntity(i)->unsetFlag(DFLAGS::HIDE_LAYER);
}
}
}
void cUI::Entity_Update( cEntity* _obj, int _moveX, int _moveY )
{
}
//*****************************************************************************************************************************************
//*S*************************************************************** MENU 테스트 **************************************************************
//*****************************************************************************************************************************************
void cUI::process_Main_Test(int message)
{
}
//*****************************************************************************************************************************************
//*E*************************************************************** MENU 테스트 **************************************************************
//*****************************************************************************************************************************************
//*****************************************************************************************************************************************
//*S*************************************************************** GAME 테스트 **************************************************************
//*****************************************************************************************************************************************
void cUI::process_UI_Test(int message)
{
}
//*****************************************************************************************************************************************
//*E*************************************************************** GAME 테스트 **************************************************************
//*****************************************************************************************************************************************
//***************************************************************************
//** STATE_GAMELOFT (Implementation)
//**
//** Any variable declaration should go into UI_GameWG.h
//***************************************************************************
void cUI::process_UI_GameWG( int message )
{
// if( message == MESSAGE_INIT)
// {
//
// g->SetClip(0, 0, SCREEN_WIDTH, OS_SCREEN_H);
// GAMELOFT_SPRITE_LOGO->SetCurrentAnimation(0,0, false);
// GAMELOFT_SPRITE_2588->SetCurrentAnimation(0,0, false);
// //g->SetARGBColor(0X33000000);
//
// //GAMELOFT_SPRITE_LOGO -> ScaleImage(10, 7);
//
// //GAMELOFT_SPRITE_2588 -> ScaleImage(10, 6);
//
// //g_pGame->SetStoreType(STORE_SLOT1);
//
// //g_pGame->SetRecordDataArray(RECORD_USERINFO_NAME ,);
//
// //g_pGame->SaveLoadRecord(false);
//
// }
// else if( message == MESSAGE_UPDATE)
// {
//
// //#ifdef EVALUATION
// // pushState( STATE_LOAD_COMMON, true );
// //#else
//
// if ( !GAMELOFT_SPRITE_LOGO->Is_animDone(0) )
// {
// GAMELOFT_SPRITE_LOGO->UpdateAnimation(0);
// }
// else if ( !GAMELOFT_SPRITE_2588->Is_animDone(0) )
// {
// GAMELOFT_SPRITE_2588->UpdateAnimation(0);
// }
// else
// {
//
//
// //#ifdef VIEW_GAMERATING
// // pushState( STATE_GAMEGRADE, false );
// //#else
// pushState( STATE_LOAD_COMMON, true );
// //pushState( STATE_SELECTSOUND, false );
// //#endif
// // g_pGame->m_map_kind = HOUSE_MYHOME;
// // pushState(STATE_DRAW_HOUSE,true);
//
// // g_pGame->m_map_kind = WORLD_MAP1;
// // pushState(STATE_DRAW_MAP1,true);
//
// // g_pGame->goto_map( STATE_DRAW_HOUSE );
//
// // g_pGame->goto_map( STATE_DRAW_MAP1 );
//
// }
//
// //#endif//EVALUATION
// }
//
// else if( message == MESSAGE_PAINT)
// {
// g->SetColor(0xFFFFFF);
// g->FillRect(0, 0, SCREEN_WIDTH, OS_SCREEN_H);
//#ifdef EVALUATION
// return;
//#endif
// if ( !GAMELOFT_SPRITE_LOGO->Is_animDone(0) )
// {
//
//
//
// GAMELOFT_SPRITE_LOGO->PaintAnimation(g, 0, SCREEN_HALF_WIDTH, SCREEN_HALF_HEIGHT, 0, 0, 0);
//
// //g->SetARGBColor(0X88FFFFff);
// //GAMELOFT_SPRITE_2588->PaintAnimation(g, 0, SCREEN_HALF_WIDTH, SCREEN_HALF_HEIGHT, 0, 0, 0);
// //g->SetARGBColor(0xFFFFFFFF);//ADD
// //int arc1 = 90;
//
// //int s_superEffectX = (180 - 90) * 70 / 90;
// //g->SetARGBColor(0X11FFFF00);
// ////g->SetColor(0x000000);
// ////g->FillRect(0,0,240,320);
// //
// //g->FillArc(100 - s_superEffectX / 2 - 10,
// // 160 - 30 - 70 / 2 - 10,
// // s_superEffectX, 70, arc1, 180);
// //g->SetARGBColor(0xFFFFFFFF);//ADD
//
//
// }else{
// GAMELOFT_SPRITE_2588->PaintAnimation(g, 0, SCREEN_HALF_WIDTH, SCREEN_HALF_HEIGHT, 0, 0, 0);
//
// }
//
//
//
// }
//
// else if( message == MESSAGE_EXIT)
// {
// //SAFE_DEL(GAMELOFT_SPRITE_LOGO);
// //SAFE_DEL(GAMELOFT_SPRITE_2588);
//
// //SAFE_DEL(g_pGame->load_spriteArray);
//
// //GAMELOFT_SPRITE_LOGO->StopScaleImage();
// //GAMELOFT_SPRITE_2588->StopScaleImage();
// g->SetARGBColor(0xFFFFFFFF);
//
// //g_pGame->load_reset();
//
// }
}
//***************************************************************************
//** STATE_SELECTSOUND (Implementation)
//**
//** Any variable declaration should go into UI_SelectLSound.h
//** GameWG, NYC. November 13, 2007
//***************************************************************************
void cUI::process_UI_SelectSound( int message )
{
#ifdef EVALUATION
if( message == MESSAGE_INIT)
{
g_pGame->m_sndVol = 2;
menu_strscroll_count = 0;
g_pGame->Text_loadTextPack (PACK_TEXT, TEXT_MAIN,4);
if(g_pGame->have_save_file)
{
g_pGame->m_speed = GET_BYTE_DBDATA( RECORD_SPEED );
g_pGame->m_vibrateOn = GET_BYTE_DBDATA( RECORD_VIBRATION );
}
}
else if( message == MESSAGE_UPDATE)
{
if( KEY_PRESSED(GAME_KEY_SOFTKEY_RIGHT) )
{
g_pGame->m_sndVol = GET_BYTE_DBDATA( RECORD_SOUND );
if( g_pGame->m_sndVol < 1 )
{
g_pGame->m_sndVol = 2;
}
pushState( STATE_SPLASH, false );
}
}
else if( message == MESSAGE_PAINT)
{
g->SetColor(0);
g->FillRect(0,0,240,320);
SPRITE_INIT_PAGE();
SET_STRING_OUT_LINE(false);
SET_STRING_COLOR(0xffffff);
if(SPRITE_DRAW_PAGE(g, GET_STRING(MAIN_TEXT_INFO_IGP1 ,4), 5 , 10+(260>>1), 230, 235,
menu_strscroll_count , Graphics::LEFT ) > 0 )
{
menu_strscroll_count++;
}
else
{
menu_strscroll_count = 0;
}
DRAW_KORSTR(g,GET_STRING(MAIN_TEXT_INFO_IGP2, 4), 236, 286, Graphics::BOTTOM | Graphics::RIGHT, 0xffffff);
}
else if( message == MESSAGE_EXIT)
{
}
#else
if( message == MESSAGE_INIT)
{
//softkey_init( SOFTKEY_SYMBOL_EMPTY, SOFTKEY_SYMBOL_OK);
//SAVE_DATA ( false );
//select_point = 0;
select_point = 1;
//GuanHao. save
if(g_pGame->have_save_file)
{
g_pGame->m_speed = GET_BYTE_DBDATA(g_pGame->record_buffData, RECORD_SPEED );
}
g_pGame->m_vibrateOn = GET_BYTE_DBDATA(g_pGame->record_buffData, RECORD_VIBRATION );
}
else if( message == MESSAGE_UPDATE)//485
{
//if( KEY_PRESSED(GAME_KEY_ALL_UP) || KEY_PRESSED(GAME_KEY_ALL_DOWN) )
if( KEY_PRESSED(GAME_KEY_ALL_LEFT) || KEY_PRESSED(GAME_KEY_ALL_RIGHT) )
{
select_point = ((select_point==0)?1:0);
}
else if( KEY_PRESSED(GAME_KEY_ALL_ACTION))
{
if ( select_point == 0 )
{
g_pGame->m_sndVol = GET_BYTE_DBDATA(g_pGame->record_buffData, RECORD_SOUND );
if( g_pGame->m_sndVol < 1 )
{
g_pGame->m_sndVol = 2;
}
}
else
{
g_pGame->m_sndVol = 0;
}
pushState( STATE_SPLASH, false );
}
}
else if( message == MESSAGE_PAINT)
{
g->SetColor(0x000000);
g->FillRect(0,0,SCREEN_WIDTH,SCREEN_HEIGHT);
//DRAW_KORSTR( g, GET_STRING(COMMON_ENABLE_SOUND_QUESTION ,TEXT_INDEX_COMMON) , SCREEN_HALF_WIDTH, SCREEN_HALF_HEIGHT, Graphics::TOP|Graphics::HCENTER , 0xffffff );
if ( select_point == 0 )
{
// DRAW_KORSTR_LINE( g, GET_STRING(COMMON_YES ,TEXT_INDEX_COMMON) , SCREEN_HALF_WIDTH-30, SCREEN_HALF_HEIGHT+45, Graphics::TOP|Graphics::HCENTER , 0xffffff, 0x000000 );
// DRAW_KORSTR( g, GET_STRING(COMMON_NO ,TEXT_INDEX_COMMON) , SCREEN_HALF_WIDTH+30, SCREEN_HALF_HEIGHT+45, Graphics::TOP|Graphics::HCENTER , 0xffffff);
}
else
{
// DRAW_KORSTR( g, GET_STRING(COMMON_YES ,TEXT_INDEX_COMMON) , SCREEN_HALF_WIDTH-30, SCREEN_HALF_HEIGHT+45, Graphics::TOP|Graphics::HCENTER , 0xffffff );
// DRAW_KORSTR_LINE( g, GET_STRING(COMMON_NO ,TEXT_INDEX_COMMON) , SCREEN_HALF_WIDTH+30, SCREEN_HALF_HEIGHT+45, Graphics::TOP|Graphics::HCENTER , 0xffffff, 0x000000 );
}
//softkey_paint();
}
else if( message == MESSAGE_EXIT)
{
}
#endif
}
//================================================================
/// PROCESS GAMEGRADE
//================================================================
void cUI::process_UI_GameGrade( int message )
{
if( message == MESSAGE_INIT)
{
img_Gamegrade = g_pGame->create_Image ( GAMEGRADE_IMG );
game_counter = 0;
}
else if( message == MESSAGE_UPDATE)
{
if( (game_counter > GRAD_PASS_TIME) )
{
pushState( STATE_LOAD_COMMON, true );
// pushState( STATE_SELECTSOUND, false );
}
}
else if( message == MESSAGE_PAINT)
{
g->SetColor(0x000000);
g->FillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
g->DrawImage(img_Gamegrade, SCREEN_HALF_WIDTH, SCREEN_HALF_HEIGHT, Graphics::HCENTER | Graphics::VCENTER);
}
else if( message == MESSAGE_EXIT)
{
//img_Gamegrade = null;
SAFE_DEL(img_Gamegrade);
}
}
//================================================================
/// PROCESS Splash
//================================================================
void cUI::process_UI_Splash( int message )
{
if( message == MESSAGE_INIT)
{
//#ifdef LGT_VERSION
// //GuanHao. save
// if(g_pGame->have_save_file)
// {
// g_pGame->m_speed = GET_BYTE_DBDATA( RECORD_SPEED );
// }
// g_pGame->m_vibrateOn = GET_BYTE_DBDATA( RECORD_VIBRATION );
// g_pGame->m_sndVol = GET_BYTE_DBDATA( RECORD_SOUND );
//#endif
img_splash = g_pGame->create_Image ( SPLASH_IMG );
img_GgeMark = g_pGame->create_Image ( AGEMARK_IMG );
//g_pGame->setVol( INTRO_SOUND_01 , (g_pGame->m_sndVol) );
//SOUND_PLAY(INTRO_SOUND_01,true);
// g_pGame->init_popup( );
}
else if( message == MESSAGE_UPDATE)
{
if((ANY_KEY_PRESS() && !KEY_PRESSED(GAME_KEY_VOL_UP) && !KEY_PRESSED(GAME_KEY_VOL_DOWN)))
{
//SOUND_STOP();
pushState(STATE_MENU_MAIN,false);
}
}
else if( message == MESSAGE_PAINT)
{
g->DrawImage(img_splash, SCREEN_HALF_WIDTH, 0, Graphics::HCENTER | Graphics::TOP);
g->DrawImage(img_GgeMark, SCREEN_WIDTH, 0, Graphics::RIGHT | Graphics::TOP);
////if(game_counter%10 <= 5)
//// Splash_Sprite->PaintFrame(g, SPLASH_RES_PRESSANYKEY_FRM_INDEX, SCREEN_HALF_WIDTH, /*256*/SCREEN_HALF_HEIGHT+35, 0, 0, 0);
//char tem[40];
//SPRINTF(tem, "%s%s", "ver ",VERSION);
//
//DRAW_KORSTR_LINE(g, tem , 3, 4, Graphics::TOP|Graphics::LEFT , 0x000000 ,0xffffff);
}
else if( message == MESSAGE_EXIT)
{
SAFE_DEL(img_splash);
//img_splash = NULL;
SAFE_DEL(img_GgeMark);
//Splash_Sprite->ClearCompressedImageData();
////Splash_Sprite = NULL;
//SAFE_DEL(Splash_Sprite);
//SOUND_STOP();
}
}
//================================================================
/// PROCESS MENU
//================================================================
void cUI::process_UI_Menu( int message )
{
if( message == MESSAGE_INIT)
{
// g_pGame->Text_freeText( TEXT_INDEX_MENU );
// g_pGame->Text_loadTextPack( PACK_TEXT, TEXT_MENU, TEXT_INDEX_MENU );
// title_frame = MENU_RES_MENU_FRM_INDEX;
// title_posX = TOP_MENU_POSX;
// title_posY = TOP_MENU_POSY;
//data_save = (g_pGame->GetRecordDataByte(RECORD_SAVE1)==1)?true:false ;
//g_pGame->showIGPNew = (g_pGame->GetRecordDataByte(RECORD_IGP_NEW)==0)?true:false ;
img_GgeMark = g_pGame->create_Image ( RATING_MARK_IMG );
//img_New = g_pGame->create_Image ( IMG_NEW );
select_point = 0;
g_pGame->SetStoreType(STORE_SLOT1);
g_pGame->SaveLoadRecord(false);
//g_pGame->GetRecordDataArray( RECORD_USERINFO_NAME ,(char*)g_pGame->textField_Name, 16);
}
else if( message == MESSAGE_UPDATE)
{
update_KeyMenu( );
//Process_Menu( );
}
else if( message == MESSAGE_PAINT)
{
g->SetColor(0xffffff);
g->FillRect(0,0,240,320);
draw_Menu( );
}
else if( message == MESSAGE_EXIT)
{
SAFE_DEL(img_GgeMark);
g_pGame->Text_freeText( TEXT_INDEX_MENU );
//FREE_GAMERES();
}
}
void cUI::update_KeyMenu()
{
//if(g_pGame->_cText)
//{
// if( g_pGame->update_Key_textField() == 1)
// {
// g_pGame->SetStoreType(STORE_SLOT1);
// g_pGame->SetRecordDataArray(RECORD_USERINFO_NAME ,GET_STRING( MENU_STORY_MODE+3 ,TEXT_INDEX_MENU) , 16);
// g_pGame->SaveLoadRecord(true);
// }
//}
//else
//{
// if(KEY_PRESSED(GAME_KEY_ALL_UP) )
// {
// select_point = (select_point+7-1)%7;
// }
// else if(KEY_PRESSED(GAME_KEY_ALL_DOWN) )
// {
// select_point = (select_point+1)%7;
// }
// else if(KEY_PRESSED(GAME_KEY_ALL_ACTION) || softkey_update() == SOFTKEY_RIGHT )
// {
// if(select_point == 0)
// {
// g_pGame->set_textField( AUTOMATA_KR );
// }
// }
//}
}
void cUI::draw_Menu()
{
int i = 0;
/*if(g_pGame->_cText)
{
DRAW_KORSTR_LINE(g, GET_STRING( MENU_STORY_MODE ,TEXT_INDEX_MENU) , SCREEN_HALF_WIDTH , 50 , Graphics::TOP|Graphics::HCENTER , 0xff0000 ,0xffffff);
byte _bUTF16_[16]={0};
byte _bUTF8_[32]={0};
char* str = g_pGame->m_pStrArray->getStr();
g_pGame->getText(&str);
int iLen_ = STRLEN(str);
iLen_ = ConvertKSC5601toUTF16( (byte*)str, iLen_, _bUTF16_ );
iLen_ = ConvertUTF16toUTF8( _bUTF16_, _bUTF8_, iLen_, CONVUTF_8 );
DRAW_KORSTR_LINE(g, (char*)_bUTF8_ , SCREEN_HALF_WIDTH , 120, Graphics::TOP|Graphics::HCENTER , 0xff0000 ,0xffffff);
g_pGame->m_pStrArray->releaseStr(str);
}
else
{
for(i = 0 ; i < 7 ;i++)
{
if(select_point == i)
{
DRAW_KORSTR_LINE(g, GET_STRING( MENU_STORY_MODE+i ,TEXT_INDEX_MENU) , SCREEN_HALF_WIDTH , 50 + i*20, Graphics::TOP|Graphics::HCENTER , 0xff0000 ,0xffffff);
}
else
{
DRAW_KORSTR_LINE(g, GET_STRING( MENU_STORY_MODE+i ,TEXT_INDEX_MENU) , SCREEN_HALF_WIDTH , 50 + i*20, Graphics::TOP|Graphics::HCENTER , 0x000000 ,0xffffff);
}
}
DRAW_KORSTR_LINE(g, g_pGame->textField_Name , SCREEN_HALF_WIDTH , 50 + i*20, Graphics::TOP|Graphics::HCENTER , 0x00ff00 ,0xffffff);
}*/
}
////////////////////////////////
//UI_Net.hpp
//================================================================
/// PROCESS ENDING
//================================================================
//void cUI::process_UI_Net( INT_TYPE message )
//{
// cXPlayerMenus::getInstance()->paint(g);
//}
////////////////////////////////////////////////////
void cUI::Set_Net_NextState( byte _state )
{
g_pGame->state = _state;
switch (g_pGame->state )
{
case cGame::CAUTION_POPUP :
case cGame::MENU:
case cGame::REPLAY:
sel_point = 0;
g_pGame->jFont->isInitalizedPage = false;
softkey_init(SOFTKEY_SYMBOL_BACK,SOFTKEY_SYMBOL_OK);
break;
case cGame::ALREADY_REPLAY:
case cGame::NEEDLESS_REPLAY:
g_pGame->jFont->isInitalizedPage = false;
softkey_init(SOFTKEY_SYMBOL_EMPTY,SOFTKEY_SYMBOL_OK);
break;
}
}
void cUI::getKeyrelease()//SangHo - Key 이벤트 임시구현
{
if (keyLife) return;
if (keyCodeRelease) keyCodePress=keyCodeRelease=0;
}
void cUI::getKeypress()//SangHo - Key 이벤트 임시구현
{
keyCodeCui = keyCodePress;
keyLife = false;
}
void cUI::keyProcess()
{
//612. +
bool _bSelect = false ;
switch (g_pGame->state)
{
case cGame::MENU:
//612. +
if(KEY_PRESSED(GAME_KEY_UP))
{
sel_point--;
if ( sel_point < 0)
{
sel_point = NET_MENU_MAX;
}
}
else if(KEY_PRESSED(GAME_KEY_DOWN))
{
sel_point++;
if ( sel_point > NET_MENU_MAX)
{
sel_point = 0;
}
}
else if(KEY_PRESSED(GAME_KEY_CLICK)|| softkey_update() == SOFTKEY_RIGHT )
{
_bSelect = true;
}
else if(KEY_PRESSED( GAME_KEY_CLEAR ) || softkey_update() == SOFTKEY_LEFT )//SOFTKEY_RIGHT)
{
pushState(STATE_MENU_MAIN,true);
}
if(KEY_PRESSED(GAME_KEY_1))
{
//612. *
/*g_pGame->jFont->isInitalizedPage = false;
g_pGame->state = cGame::CAUTION_POPUP;*/
sel_point = 0;
_bSelect = true;
}
else if(KEY_PRESSED(GAME_KEY_2))
{
//612. *
////GLWipiNetModule.makeCharge(g_pGame->application.s_game, g_pGame->jFont);//Chen Shoutian, to do
//g_pGame->state = cGame::CHARGE;
sel_point = 1;
_bSelect = true;
}
else if(KEY_PRESSED(GAME_KEY_3))
{
////GLWipiNetModule.makeDownload(g_pGame->application.s_game, g_pGame->jFont, "");//Chen Shoutian, to do
// it will be downloaded files that the prefix is "MUSIC"...
// //GLWipiNetModule.makeDownload(this, g_pGame->jFont, "MUSIC");
//g_pGame->state = cGame::DOWNLOAD;
sel_point = 2;
_bSelect = true;
}
else if(KEY_PRESSED(GAME_KEY_4))
{
// g_pGame->menu_Pointer = 4;
//pushState(STATE_MENU_MAIN,true);
sel_point = 3;
_bSelect = true;
}
break;
case cGame::CAUTION_POPUP:
//if(KEY_PRESSED(GAME_KEY_1))
//{
// // wipiNetwork = new WipiNetwork(this, g_pGame->jFont, new int[9]);
// ////GLWipiNetModule.makeRanking(g_pGame->application.s_game, g_pGame->jFont, scoreArray);//Chen Shoutian, to do
// g_pGame->state = cGame::RANKING;
//}
//else if(KEY_PRESSED(GAME_KEY_2))
//{
// g_pGame->state = cGame::MENU;
//}
//break;
if(KEY_PRESSED(GAME_KEY_1))
{
sel_point = 0;
_bSelect = true;
}
else if(KEY_PRESSED(GAME_KEY_2))
{
sel_point = 1;
Set_Net_NextState(cGame::MENU);
}
if(KEY_PRESSED(GAME_KEY_UP)||KEY_PRESSED(GAME_KEY_DOWN))
{
sel_point = (sel_point==0)?1:0;
}
else if(KEY_PRESSED(GAME_KEY_CLICK) || softkey_update() == SOFTKEY_RIGHT)
{
_bSelect = true;
}
else if(KEY_PRESSED(GAME_KEY_CLEAR) || softkey_update() == SOFTKEY_LEFT )//SOFTKEY_RIGHT)//fixed bug 1454551
{
Set_Net_NextState(cGame::MENU);
}
if ( _bSelect )
{
if(sel_point == 0)
{
//GLWipiNetModule.score_sending = XPlayer.SCORE_TYPE_POINTS; //SCORE_TYPE_POINTS = 1; SCORE_TYPE_TIME = 2;
//GLWipiNetModule.makeRanking(cGame.application.s_game, cGame.jFont, scoreArray);
Set_Net_NextState(cGame::RANKING);
}
else if(sel_point == 1)
{
Set_Net_NextState(cGame::MENU);
}
_bSelect = false;
}
break;
case cGame::REPLAY:
break;
case cGame::ALREADY_REPLAY:
case cGame::NEEDLESS_REPLAY:
if(KEY_PRESSED(GAME_KEY_CLICK) || softkey_update() == SOFTKEY_RIGHT )
{
sel_point = 2;
Set_Net_NextState(cGame::MENU);
}
break;
case cGame::RANKING:
case cGame::CHARGE:
case cGame::DOWNLOAD:
// wipiNetwork.keyPressed(pressedKey);
////GLWipiNetModule.instance.keyPressed(g_pGame->game_keyNet);//Chen Shoutian, to do
break;
}
//612. *
//g_pGame->game_keyNet = 0;
//g_pGame->game_netKeyPressed = 0;
}
void cUI::logicProcess()
{
switch (g_pGame->state)
{
//612. -
//case cGame::MENU:
//break;
case cGame::RANKING:
case cGame::CHARGE:
case cGame::DOWNLOAD:
// wipiNetwork.logicProcess();
//WipiNetwork.instance.logicProcess();//Chen Shoutian,to do
break;
}
// repaint();
}
//612. +
////////////////////////////////////////////////////
/// SET GGI (NET)
////////////////////////////////////////////////////
int cUI::Set_GGI() // APPEND 2008-02-21 (Seungho.Han)
{
int _ggi_index = 0;
int _size_index = 0;
int _company_index = COMPANY_KTF;
if ( SCREEN_WIDTH <= GGI_SIZE_120 )
{
_size_index = 0;
}
else if ( SCREEN_WIDTH <= GGI_SIZE_176 )
{
_size_index = 1;
}
else if ( SCREEN_WIDTH <= GGI_SIZE_240 )
{
_size_index = 2;
}
else if ( SCREEN_WIDTH <= GGI_SIZE_320 )
{
_size_index = 3;
}
if ( _company_index == COMPANY_SKT )
{
_ggi_index = _size_index+GGI_SKT;
}
else if ( _company_index == COMPANY_KTF )
{
_size_index--;
if ( _size_index < 0 )
{
_size_index = 0;
}
_ggi_index = _size_index+GGI_KTF;
}
else// if ( _company_index == COMPANY_LGT )
{
_ggi_index = _size_index+GGI_LGT;
}
return _ggi_index;
}
//GuanHao. reset
void cUI::resetGame(bool autoOpen)
{
}
//GuanHao. IGP. draw
//void cUI::process_UI_IGP(int message)
//{
//
// //return;
//
// if( message == MESSAGE_INIT)
// {
//
// }
// else if( message == MESSAGE_UPDATE)
// {
// if(g_pGame->m_pIgp->Update())
// pushState(STATE_MENU_MAIN,true);
// }
// else if( message == MESSAGE_PAINT)
// {
// g_pGame->m_pIgp->Draw();
// }
// else if( message == MESSAGE_EXIT)
// {
// }
//}
| [
"[email protected]"
] | [
[
[
1,
3088
]
]
] |
d6321d194475e8d055e0d44afce00465ff0178af | 709cd826da3ae55945fd7036ecf872ee7cdbd82a | /Term/WildMagic2/Source/Curves/WmlSingleCurve2.cpp | dd4764ed008ddbb321b940e7ce77ec8f1365c0f1 | [] | 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 | 2,693 | 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 "WmlSingleCurve2.h"
#include "WmlIntegrate1.h"
using namespace Wml;
//----------------------------------------------------------------------------
template <class Real>
SingleCurve2<Real>::SingleCurve2 (Real fTMin, Real fTMax)
:
Curve2<Real>(fTMin,fTMax)
{
}
//----------------------------------------------------------------------------
template <class Real>
Real SingleCurve2<Real>::GetSpeedWithData (Real fTime, void* pvData)
{
return ((Curve2<Real>*)pvData)->GetSpeed(fTime);
}
//----------------------------------------------------------------------------
template <class Real>
Real SingleCurve2<Real>::GetLength (Real fT0, Real fT1) const
{
assert( m_fTMin <= fT0 && fT0 <= m_fTMax );
assert( m_fTMin <= fT1 && fT1 <= m_fTMax );
assert( fT0 <= fT1 );
return Integrate1<Real>::RombergIntegral(fT0,fT1,GetSpeedWithData,
(void*)this);
}
//----------------------------------------------------------------------------
template <class Real>
Real SingleCurve2<Real>::GetTime (Real fLength, int iIterations,
Real fTolerance) const
{
if ( fLength <= (Real)0.0 )
return m_fTMin;
if ( fLength >= GetTotalLength() )
return m_fTMax;
// initial guess for Newton's method
Real fRatio = fLength/GetTotalLength();
Real fOmRatio = ((Real)1.0) - fRatio;
Real fTime = fOmRatio*m_fTMin + fRatio*m_fTMax;
for (int i = 0; i < iIterations; i++)
{
Real fDifference = GetLength(m_fTMin,fTime) - fLength;
if ( Math<Real>::FAbs(fDifference) < fTolerance )
return fTime;
fTime -= fDifference/GetSpeed(fTime);
}
// Newton's method failed. If this happens, increase iterations or
// tolerance or integration accuracy.
return Math<Real>::MAX_REAL;
}
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
// explicit instantiation
//----------------------------------------------------------------------------
namespace Wml
{
template class WML_ITEM SingleCurve2<float>;
template class WML_ITEM SingleCurve2<double>;
}
//----------------------------------------------------------------------------
| [
"[email protected]"
] | [
[
[
1,
78
]
]
] |
75ac511c80a4ad558c39977b77d5445aeaa112c7 | 382b459563be90227848e5125f0d37f83c1e2a4f | /Schedule/src/type.cpp | 3c08b6a0920ec34d7be9dbe2bee239782e96b3c2 | [] | no_license | Maciej-Poleski/SchoolTools | 516c9758dfa153440a816a96e3f05c7f290daf6c | e55099f77eb0f65b75a871d577cc4054221b9802 | refs/heads/master | 2023-07-02T09:07:31.185410 | 2010-07-11T20:56:59 | 2010-07-11T20:56:59 | 392,391,718 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 32 | cpp | #include "../include/type.h"
| [
"[email protected]"
] | [
[
[
1,
2
]
]
] |
6426a06097c68862b7de72dff9aea11caa68da4e | 0bce46a5dd859d82824f4b74c4adecd7b4bc2387 | /sourcecode/level.cpp | 4955744e6a2668fd2ab903c2f21e7da2f9b245e2 | [] | no_license | xflash/moon-invaders | a08e00ddb590fa3bd395e65bb793a67166a27eb1 | 8124f4787a8b1b201e85c17010620488f51827a4 | refs/heads/master | 2021-01-25T08:38:05.896106 | 2009-02-19T09:41:38 | 2009-02-19T09:41:38 | 32,315,985 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,157 | cpp | #include "level.h"
#include "player.h"
#include "invader.h"
void NextLevel(void)
{
float spd;
int cnt;
word life;
float space;
if(NoInvaders() && player.life>0)
{
player.level++;
if(player.money+player.level/2<=160)
player.money+=player.level/2;
else
player.money=160;
cnt=player.level*2;
spd=0.20f+(float)player.level*0.04f;
life=3+(word)((float)player.level*1.1f);
if(player.level>50)
life=(word)((float)life*((float)player.level)/50.0f);
space=48;
switch(player.level%4)
{
case 0: // 'boss' - quarter as many guys with double HP
life*=10;
cnt/=10;
space*=3; // widen them out
spd*=0.8f;
break;
case 1: // normal - normal guys, normal speed, normal HP
break;
case 2: // speed - half as many guys, move twice as fast, half HP
life/=2;
spd*=1.5f;
space=48; // tighten them up
cnt/=2;
break;
case 3: // horde - 3/4 speed, twice as many guys with half HP
life/=2;
spd*=0.75f;
space=36; // tighten up
cnt*=2;
break;
}
if(cnt>255)
cnt=255;
InvaderWave(cnt,life,spd,space);
}
}
| [
"rcoqueugniot@19f3d9c2-fe69-11dd-a3ef-1f8437fb274a"
] | [
[
[
1,
55
]
]
] |
8c54759f77f45ccfcd59affa338329700dd189c5 | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/os/ossrv/stdlibs/apps/libdl/src/tdlserver.cpp | 1c0db2755fe4704a809d00dd0327bb57e8014fb0 | [] | 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,649 | cpp | /*
* Copyright (c) 2006-2008 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:
*
*/
/**
* @file
*
* tdl test server implementation
*/
#include "tdlserver.h"
#include "tdl.h"
_LIT(KServerName, "tdl");
CTestDlByNameServer* CTestDlByNameServer::NewL()
{
CTestDlByNameServer *server = new(ELeave) CTestDlByNameServer();
CleanupStack::PushL(server);
server->ConstructL(KServerName);
CleanupStack::Pop(server);
return server;
}
LOCAL_C void MainL()
{
// Leave the hooks in for platform security
#if (defined __DATA_CAGING__)
RProcess().DataCaging(RProcess::EDataCagingOn);
RProcess().SecureApi(RProcess::ESecureApiOn);
#endif
CActiveScheduler* sched=NULL;
sched=new(ELeave) CActiveScheduler;
CActiveScheduler::Install(sched);
CTestDlByNameServer* server = NULL;
// Create the CTestServer derived server
TRAPD(err, server = CTestDlByNameServer::NewL());
if(!err)
{
// Sync with the client and enter the active scheduler
RProcess::Rendezvous(KErrNone);
sched->Start();
}
delete server;
delete sched;
}
/**
* Server entry point
* @return Standard Epoc error code on exit
*/
TInt E32Main()
{
__UHEAP_MARK;
CTrapCleanup* cleanup = CTrapCleanup::New();
if(cleanup == NULL)
{
return KErrNoMemory;
}
TRAP_IGNORE(MainL());
delete cleanup;
__UHEAP_MARKEND;
return KErrNone;
}
CTestStep* CTestDlByNameServer::CreateTestStep(const TDesC& aStepName)
{
CTestStep* testStep = NULL;
if(aStepName == KDlSymLkupWithHandle)
testStep = new CTestDlByName(aStepName);
else if(aStepName == KDlSymLkupWithRTLD_DEFAULT)
testStep = new CTestDlByName(aStepName);
else if(aStepName == KDlLoadByVar)
testStep = new CTestDlByName(aStepName);
else if(aStepName == KDlLoadWithInvalidArg)
testStep = new CTestDlByName(aStepName);
else if(aStepName == KDlMutexOnOpenHandle)
testStep = new CTestDlByName(aStepName);
else if(aStepName == KOpenNonStdDllOrdinalLookup)
testStep = new CTestDlByName(aStepName);
else if(aStepName == KOpenNonStdDllSymbolicLookup)
testStep = new CTestDlByName(aStepName);
else if(aStepName == KOpenNonStdDllSymbolicLookupWithRTLD_DEFAULT)
testStep = new CTestDlByName(aStepName);
return testStep;
}
| [
"none@none"
] | [
[
[
1,
106
]
]
] |
589264f701d272a5ec51c487e0a30fe29f3cf639 | 4ab592fb354f75b42181d5375d485031960aaa7d | /src/core/graphics.cpp | 0ae0a82b28f587c09b876b9b4518b99a891e8a2f | [] | no_license | CBE7F1F65/cca610e2e115c51cef211fafb0f66662 | 806ced886ed61762220b43300cb993ead00949dc | b3cdff63d689e2b1748e9cd93cedd7e8389a7057 | refs/heads/master | 2020-12-24T14:55:56.999923 | 2010-07-23T04:24:59 | 2010-07-23T04:24:59 | 32,192,699 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 45,158 | cpp | /*
** Haaf's Game Engine 1.8
** Copyright (C) 2003-2007, Relish Games
** hge.relishgames.com
**
** Core functions implementation: graphics
*/
/************************************************************************/
/* Part of this file is modified by h5nc ([email protected]) */
/* Changes of adjusting from d3d8 to d3d9 will not be marked in detail */
/************************************************************************/
#include "hge_impl.h"
#ifdef __WIN32
#include <d3d9.h>
#include <d3dx9.h>
#else
#ifdef __PSP
#include <pspkernel.h>
#include <pspdisplay.h>
#include <pspdebug.h>
#include <pspctrl.h>
#include <pspgu.h>
#include <pspgum.h>
#include <psprtc.h>
#include "../src/psp/PSP_graphics.h"
static unsigned int __attribute__((aligned(16))) gulist[262144];
#define SLICE_SIZE_F 64.0f
#endif // __PSP
#endif
void CALL HGE_Impl::Gfx_Clear(DWORD color)
{
/************************************************************************/
/* TODO */
/************************************************************************/
if(pCurTarget)
{
#ifdef __WIN32
if(pCurTarget->pDepth)
pD3DDevice->Clear( 0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, color, 1.0f, 0 );
else
pD3DDevice->Clear( 0, NULL, D3DCLEAR_TARGET, color, 1.0f, 0 );
#endif
}
else
{
#ifdef __WIN32
if(bZBuffer)
pD3DDevice->Clear( 0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, color, 1.0f, 0 );
else
pD3DDevice->Clear( 0, NULL, D3DCLEAR_TARGET, color, 1.0f, 0 );
#else
#ifdef __PSP
sceGuDisable(GU_SCISSOR_TEST);
sceGuClearColor(color);
sceGuClear(GU_COLOR_BUFFER_BIT);
sceGuEnable(GU_SCISSOR_TEST);
#endif // __PSP
#endif
}
}
void CALL HGE_Impl::Gfx_SetClipping(int x, int y, int w, int h)
{
int scr_width = 0;
int scr_height = 0;
if(!pCurTarget) {
scr_width=pHGE->System_GetStateInt(HGE_SCREENWIDTH);
scr_height=pHGE->System_GetStateInt(HGE_SCREENHEIGHT);
}
else {
#ifdef __WIN32
scr_width=Texture_GetWidth((HTEXTURE)((DWORD)pCurTarget->pTex));
scr_height=Texture_GetHeight((HTEXTURE)((DWORD)pCurTarget->pTex));
#endif // __WIN32
}
#ifdef __WIN32
D3DVIEWPORT9 vp;
if(!w) {
vp.X=0;
vp.Y=0;
vp.Width=scr_width;
vp.Height=scr_height;
}
else
{
if(x<0) { w+=x; x=0; }
if(y<0) { h+=y; y=0; }
if(x+w > scr_width) w=scr_width-x;
if(y+h > scr_height) h=scr_height-y;
vp.X=x;
vp.Y=y;
vp.Width=w;
vp.Height=h;
}
vp.MinZ=0.0f;
vp.MaxZ=1.0f;
_render_batch();
pD3DDevice->SetViewport(&vp);
D3DXMATRIX tmp;
Math_MatrixScaling(&matProj, 1.0f, -1.0f, 1.0f);
Math_MatrixTranslation(&tmp, -0.5f, +0.5f, 0.0f);
Math_MatrixMultiply(&matProj, &matProj, &tmp);
Math_MatrixOrthoOffCenterLH(&tmp, (float)vp.X, (float)(vp.X+vp.Width), -((float)(vp.Y+vp.Height)), -((float)vp.Y), vp.MinZ, vp.MaxZ);
Math_MatrixMultiply(&matProj, &matProj, &tmp);
pD3DDevice->SetTransform(D3DTS_PROJECTION, &matProj);
#else
#ifdef __PSP
if (!w)
{
w = scr_width;
h = scr_height;
}
sceGuEnable(GU_SCISSOR_TEST);
sceGuScissor(x,y,x+w,y+h);
#endif // __PSP
#endif
}
/************************************************************************/
/* These functions are added by h5nc ([email protected]) */
/************************************************************************/
void CALL HGE_Impl::Gfx_SetTransform(float x, float y, float dx, float dy, float rot, float hscale, float vscale)
{
D3DXMATRIX tmp;
if(vscale==0.0f) Math_MatrixIdentity(&matView);
else
{
Math_MatrixTranslation(&matView, -x, -y, 0.0f);
Math_MatrixScaling(&tmp, hscale, vscale, 1.0f);
Math_MatrixMultiply(&matView, &matView, &tmp);
Math_MatrixRotationZ(&tmp, -rot);
Math_MatrixMultiply(&matView, &matView, &tmp);
Math_MatrixTranslation(&tmp, x+dx, y+dy, 0.0f);
Math_MatrixMultiply(&matView, &matView, &tmp);
}
_render_batch();
Gfx_SetTransform(D3DTS_VIEW, &matView);
}
void CALL HGE_Impl::Gfx_SetTransform(D3DTRANSFORMSTATETYPE State, const D3DMATRIX * pMatrix)
{
#ifdef __WIN32
pD3DDevice->SetTransform(State, pMatrix);
#else
sceGumMatrixMode((int)State);
sceGumLoadIdentity();
sceGumMultMatrix((ScePspFMatrix4*)pMatrix);
#endif
}
D3DMATRIX CALL HGE_Impl::Gfx_GetTransform(D3DTRANSFORMSTATETYPE State)
{
D3DMATRIX mat;
#ifdef __WIN32
pD3DDevice->GetTransform(State, &mat);
#else
sceGumMatrixMode((int)State);
sceGumStoreMatrix((ScePspFMatrix4*)&mat);
#endif
return mat;
}
void CALL HGE_Impl::Gfx_SetTextureInfo(int _nTexInfo, hgeTextureInfo * _texInfo)
{
nTexInfo = _nTexInfo;
texInfo = _texInfo;
}
bool CALL HGE_Impl::Gfx_BeginScene(HTARGET targ)
{
#ifdef __WIN32
LPDIRECT3DSURFACE9 pSurf=0, pDepth=0;
CRenderTargetList *target=(CRenderTargetList *)targ;
D3DDISPLAYMODE Mode;
HRESULT hr = pD3DDevice->TestCooperativeLevel();
if (hr == D3DERR_DEVICELOST) return false;
else if (hr == D3DERR_DEVICENOTRESET)
{
if(bWindowed)
{
if(FAILED(pD3D->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &Mode)) || Mode.Format==D3DFMT_UNKNOWN)
{
_PostError("Can't determine desktop video mode");
return false;
}
d3dppW.BackBufferFormat = Mode.Format;
if(_format_id(Mode.Format) < 4) nScreenBPP=16;
else nScreenBPP=32;
}
if(!_GfxRestore()) return false;
}
if(VertArray)
{
_PostError("Gfx_BeginScene: Scene is already being rendered");
return false;
}
if(target != pCurTarget)
{
if(target)
{
target->pTex->GetSurfaceLevel(0, &pSurf);
pDepth=target->pDepth;
}
else
{
pSurf=pScreenSurf;
pDepth=pScreenDepth;
}
//+1st -3rd
if(FAILED(pD3DDevice->SetRenderTarget(0, pSurf)))
{
if(target) pSurf->Release();
_PostError("Gfx_BeginScene: Can't set render target");
return false;
}
if(target)
{
pSurf->Release();
if(target->pDepth)
pD3DDevice->SetRenderState( D3DRS_ZENABLE, D3DZB_TRUE );
else
pD3DDevice->SetRenderState( D3DRS_ZENABLE, D3DZB_FALSE );
/************************************************************************/
/* This line is deleted by h5nc ([email protected]) */
/************************************************************************/
// _SetProjectionMatrix(target->width, target->height);
}
else
{
if(bZBuffer) pD3DDevice->SetRenderState( D3DRS_ZENABLE, D3DZB_TRUE );
else pD3DDevice->SetRenderState( D3DRS_ZENABLE, D3DZB_FALSE );
_SetProjectionMatrix(nScreenWidth, nScreenHeight);
}
/************************************************************************/
/* These 3 lines are deleted by h5nc ([email protected]) */
/************************************************************************/
// pD3DDevice->SetTransform(D3DTS_PROJECTION, &matProj);
// D3DXMatrixIdentity(&matView);
// pD3DDevice->SetTransform(D3DTS_VIEW, &matView);
pCurTarget=target;
}
pD3DDevice->BeginScene();
pVB->Lock( 0, 0, (void**)&VertArray, 0 );
#else
/************************************************************************/
/* TODO */
/************************************************************************/
#ifdef __PSP
sceGuStart(GU_DIRECT, gulist);
matProj.m[0][0] = SCREEN_HEIGHT/SCREEN_WIDTH;
matProj.m[0][1] = 0.0f;
matProj.m[0][2] = 0.0f;
matProj.m[0][3] = 0.0f;
matProj.m[1][0] = 0.0f;
matProj.m[1][1] = -1.0f;
matProj.m[1][2] = 0.0f;
matProj.m[1][3] = 0.0f;
matProj.m[2][0] = 0.0f;
matProj.m[2][1] = 0.0f;
matProj.m[2][2] = -1.0f;
matProj.m[2][3] = -1.0f;
matProj.m[3][0] = -SCREEN_HEIGHT/2;
matProj.m[3][1] = SCREEN_HEIGHT/2;
matProj.m[3][2] = SCREEN_HEIGHT/2;
matProj.m[3][3] = SCREEN_HEIGHT/2;
sceGumMatrixMode(GU_PROJECTION);
sceGumLoadIdentity();
sceGumMultMatrix((ScePspFMatrix4*)&matProj);
sceGumMatrixMode(GU_VIEW);
sceGumLoadIdentity();
#endif // __PSP
#endif //__WIN32
return true;
}
#ifdef __PSP
#include <malloc.h>
int __freemem()
{
void *ptrs[480];
int mem, x, i;
void *ptr;
for (x = 0; x < 480; x++)
{
ptr = malloc(51200);
if (!ptr) break;
ptrs[x] = ptr;
}
mem = x * 51200;
for (i = 0; i < x; i++)
free(ptrs[i]);
return mem;
}
#endif // __PSP
void CALL HGE_Impl::Gfx_EndScene()
{
_render_batch(true);
#ifdef __WIN32
pD3DDevice->EndScene();
if(!pCurTarget) pD3DDevice->Present( NULL, NULL, NULL, NULL );
#else
/************************************************************************/
/* TODO */
/************************************************************************/
#ifdef __PSP
sceGuFinish();
sceGuSync(0,0);
pspDebugScreenSetXY(0, 0);
int freemem = __freemem();
pspDebugScreenPrintf("%f %d(%.2fM)", Timer_GetFPS(), freemem, freemem*1.0f/(1024*1024));
sceGuSwapBuffers();
#endif // __PSP
#endif
}
#ifdef __PSP
DWORD _ARGBtoABGR(DWORD color)
{
BYTE r = GETR(color);
BYTE b = GETB(color);
color = SETB(color, r);
color = SETR(color, b);
return color;
}
#endif // __PSP
void CALL HGE_Impl::Gfx_RenderPoint(float x, float y, float z, DWORD color)
{
#ifdef __WIN32
if(VertArray)
{
if(CurPrimType!=HGEPRIM_POINTS || nPrim>=VERTEX_BUFFER_SIZE/HGEPRIM_POINTS || CurTexture || CurBlendMode!=BLEND_DEFAULT)
{
_render_batch();
CurPrimType=HGEPRIM_POINTS;
if(CurBlendMode != BLEND_DEFAULT) _SetBlendMode(BLEND_DEFAULT);
if(CurTexture) { pD3DDevice->SetTexture(0, 0); CurTexture=0; }
}
int i=nPrim*HGEPRIM_POINTS;
VertArray[i].x = x;
VertArray[i].y = y;
VertArray[i].z = z;
VertArray[i].col = color;
VertArray[i].tx = VertArray[i].ty = 0.0f;
nPrim++;
}
#else
#ifdef __PSP
struct pspVertex* vertices = (struct pspVertex*)sceGuGetMemory(1 * sizeof(struct pspVertex));
if (!vertices)
{
return;
}
vertices[0].color = color;
vertices[0].x = x;
vertices[0].y = y;
sceGuDisable(GU_TEXTURE_2D);
sceGuShadeModel(GU_FLAT);
sceGuShadeModel(GU_SMOOTH);
sceGuAmbientColor(0xffffffff);
sceGumDrawArray(GU_POINTS, GU_COLOR_8888|GU_VERTEX_32BITF|GU_TRANSFORM_3D, 1*1, 0, vertices);
sceGuEnable(GU_TEXTURE_2D);
#endif // __PSP
#endif // __WIN32
}
void CALL HGE_Impl::Gfx_RenderLine(float x1, float y1, float x2, float y2, DWORD color, float z)
{
#ifdef __WIN32
if(VertArray)
{
if(CurPrimType!=HGEPRIM_LINES || nPrim>=VERTEX_BUFFER_SIZE/HGEPRIM_LINES || CurTexture || CurBlendMode!=BLEND_DEFAULT)
{
_render_batch();
CurPrimType=HGEPRIM_LINES;
if(CurBlendMode != BLEND_DEFAULT) _SetBlendMode(BLEND_DEFAULT);
if(CurTexture) { pD3DDevice->SetTexture(0, 0); CurTexture=0; }
}
int i=nPrim*HGEPRIM_LINES;
VertArray[i].x = x1; VertArray[i+1].x = x2;
VertArray[i].y = y1; VertArray[i+1].y = y2;
VertArray[i].z = VertArray[i+1].z = z;
VertArray[i].col = VertArray[i+1].col = color;
VertArray[i].tx = VertArray[i+1].tx =
VertArray[i].ty = VertArray[i+1].ty = 0.0f;
nPrim++;
}
#else
#ifdef __PSP
struct pspVertex* vertices = (struct pspVertex*)sceGuGetMemory(2 * sizeof(struct pspVertex));
if (!vertices)
{
return;
}
vertices[0].color = color;
vertices[0].x = x1;
vertices[0].y = y1;
vertices[0].z = z;
vertices[1].color = color;
vertices[1].x = x2;
vertices[1].y = y2;
vertices[1].z = z;
sceGuDisable(GU_TEXTURE_2D);
sceGuShadeModel(GU_FLAT);
sceGuShadeModel(GU_SMOOTH);
sceGuAmbientColor(0xffffffff);
sceGumDrawArray(GU_LINES, GU_COLOR_8888|GU_VERTEX_32BITF|GU_TRANSFORM_3D, 1*2, 0, vertices);
sceGuEnable(GU_TEXTURE_2D);
#endif // __PSP
#endif // __WIN32
}
/************************************************************************/
/* These 2 functions are added by h5nc ([email protected]) for later use */
/************************************************************************/
/*
void CALL HGE_Impl::Gfx_3DRenderStart()
{
if(VertArray)
{
_render_batch();
}
pD3DDevice->SetRenderState(D3DRS_LIGHTING, TRUE);
if (!(CurBlendMode & BLEND_ZWRITE))
{
pD3DDevice->SetRenderState(D3DRS_ZWRITEENABLE, TRUE);
}
}
void CALL HGE_Impl::Gfx_3DRenderEnd()
{
pD3DDevice->SetStreamSource( 0, pVB, 0, sizeof(hgeVertex));
pD3DDevice->SetIndices( pIB );
if (!(CurBlendMode & BLEND_ZWRITE))
{
pD3DDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
}
pD3DDevice->SetFVF(D3DFVF_HGEVERTEX);
pD3DDevice->SetRenderState( D3DRS_LIGHTING, FALSE );
}
*/
void CALL HGE_Impl::Gfx_RenderTriple(const hgeTriple *triple)
{
#ifdef __WIN32
if(VertArray)
{
HTEXTURE tex = triple->tex;
Texture_LoadTextureWhenNeeded(&tex);
DWORD ttex = Texture_GetTexture(tex);
if(CurPrimType!=HGEPRIM_TRIPLES || nPrim>=VERTEX_BUFFER_SIZE/HGEPRIM_TRIPLES || CurTexture!=ttex || CurBlendMode!=triple->blend)
{
_render_batch();
CurPrimType=HGEPRIM_TRIPLES;
if(CurBlendMode != triple->blend) _SetBlendMode(triple->blend);
/*
if (!ttex)
{
return;
}*/
if(ttex != CurTexture) {
pD3DDevice->SetTexture( 0, (LPDIRECT3DTEXTURE9)ttex );
CurTexture = ttex;
}
}
memcpy(&VertArray[nPrim*HGEPRIM_TRIPLES], triple->v, sizeof(hgeVertex)*HGEPRIM_TRIPLES);
nPrim++;
}
#endif
}
void CALL HGE_Impl::Gfx_RenderQuad(const hgeQuad *quad)
{
#ifdef __WIN32
if(VertArray)
{
HTEXTURE tex = quad->tex;
Texture_LoadTextureWhenNeeded(&tex);
DWORD ttex = Texture_GetTexture(tex);
if(CurPrimType!=HGEPRIM_QUADS || nPrim>=VERTEX_BUFFER_SIZE/HGEPRIM_QUADS || CurTexture!=ttex || CurBlendMode!=quad->blend)
{
_render_batch();
CurPrimType=HGEPRIM_QUADS;
if(CurBlendMode != quad->blend) _SetBlendMode(quad->blend);
/*
if (!ttex)
{
return;
}*/
if(ttex != CurTexture)
{
pD3DDevice->SetTexture( 0, (LPDIRECT3DTEXTURE9)ttex );
CurTexture = ttex;
}
}
memcpy(&VertArray[nPrim*HGEPRIM_QUADS], quad->v, sizeof(hgeVertex)*HGEPRIM_QUADS);
nPrim++;
}
#else
#ifdef __PSP
struct pspVertexUV *vertices;
int i;
HTEXTURE tex = quad->tex;
Texture_LoadTextureWhenNeeded(&tex);
Image * pTex = (Image *)Texture_GetTexture(tex);
if(pTex == 0 || pTex->textureWidth == 0 || pTex->textureHeight ==0 || !pTex->data)
{
return;
}
sceGuTexMode(GU_PSM_8888, 0, 0, GU_TRUE);
if((DWORD)pTex != CurTexture)
{
CurTexture = (DWORD)pTex;
sceGuTexImage(0, pTex->textureWidth, pTex->textureHeight, pTex->textureWidth, pTex->data);
sceKernelDcacheWritebackAll();
}
// sceKernelDcacheWritebackAll();
if (CurBlendMode != quad->blend)
{
_SetBlendMode(quad->blend);
}
vertices = (struct pspVertexUV*)sceGuGetMemory(4 * sizeof(struct pspVertexUV));
if (!vertices)
{
return;
}
for (i=0; i<4; i++)
{
int j = i;
if (i > 1)
{
j = 5-i;
}
vertices[i].u = quad->v[j].tx;
vertices[i].v = quad->v[j].ty;
vertices[i].x = quad->v[j].x;
vertices[i].y = quad->v[j].y;
vertices[i].z = quad->v[j].z;
vertices[i].color = _ARGBtoABGR(quad->v[j].col);
}
sceGumDrawArray(GU_TRIANGLE_STRIP,GU_TEXTURE_32BITF|GU_COLOR_8888|GU_VERTEX_32BITF|GU_TRANSFORM_3D, 4, 0, vertices);
#endif // __PSP
#endif
}
hgeVertex* CALL HGE_Impl::Gfx_StartBatch(int prim_type, HTEXTURE tex, int blend, int *max_prim)
{
#ifdef __WIN32
if(VertArray)
{
_render_batch();
CurPrimType=prim_type;
if(CurBlendMode != blend) _SetBlendMode(blend);
Texture_LoadTextureWhenNeeded(&tex);
DWORD ttex = Texture_GetTexture(tex);
if(ttex != CurTexture)
{
pD3DDevice->SetTexture( 0, (LPDIRECT3DTEXTURE9)ttex );
CurTexture = ttex;
}
*max_prim=VERTEX_BUFFER_SIZE / prim_type;
return VertArray;
}
else return NULL;
#else
return NULL;
#endif
}
void CALL HGE_Impl::Gfx_FinishBatch(int nprim)
{
nPrim=nprim;
}
HTARGET CALL HGE_Impl::Target_Create(int width, int height, bool zbuffer)
{
#ifdef __WIN32
CRenderTargetList *pTarget;
D3DSURFACE_DESC TDesc;
pTarget = new CRenderTargetList;
pTarget->pTex=0;
pTarget->pDepth=0;
/************************************************************************/
/* This parameter in comment is changed by h5nc ([email protected]) */
/************************************************************************/
if(FAILED(D3DXCreateTexture(pD3DDevice, width, height, 1, D3DUSAGE_RENDERTARGET,
/*d3dpp->BackBufferFormat*/D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &pTarget->pTex)))
{
_PostError("Can't create render target texture");
delete pTarget;
return 0;
}
pTarget->pTex->GetLevelDesc(0, &TDesc);
pTarget->width=TDesc.Width;
pTarget->height=TDesc.Height;
if(zbuffer)
{
//+5th +6th
if(FAILED(pD3DDevice->CreateDepthStencilSurface(pTarget->width, pTarget->height,
D3DFMT_D16, D3DMULTISAMPLE_NONE, 0, TRUE, &pTarget->pDepth, NULL)))
{
pTarget->pTex->Release();
_PostError("Can't create render target depth buffer");
delete pTarget;
return 0;
}
}
pTarget->next=pTargets;
pTargets=pTarget;
return (HTARGET)pTarget;
#else
return NULL;
#endif
}
void CALL HGE_Impl::Target_Free(HTARGET target)
{
#ifdef __WIN32
CRenderTargetList *pTarget=pTargets, *pPrevTarget=NULL;
while(pTarget)
{
if((CRenderTargetList *)target == pTarget)
{
if(pPrevTarget)
pPrevTarget->next = pTarget->next;
else
pTargets = pTarget->next;
if(pTarget->pTex) pTarget->pTex->Release();
if(pTarget->pDepth) pTarget->pDepth->Release();
delete pTarget;
return;
}
pPrevTarget=pTarget;
pTarget=pTarget->next;
}
#endif
}
HTEXTURE CALL HGE_Impl::Target_GetTexture(HTARGET target)
{
#ifdef __WIN32
CRenderTargetList *targ=(CRenderTargetList *)target;
if(target) return (HTEXTURE)((DWORD)targ->pTex);
else return NULL;
#else
return NULL;
#endif
}
HTEXTURE CALL HGE_Impl::Texture_Create(int width, int height)
{
#ifdef __WIN32
LPDIRECT3DTEXTURE9 pTex;
if( FAILED( D3DXCreateTexture( pD3DDevice, width, height,
1, // Mip levels
0, // Usage
D3DFMT_A8R8G8B8, // Format
D3DPOOL_MANAGED, // Memory pool
&pTex ) ) )
{
_PostError("Can't create texture");
return NULL;
}
return (HTEXTURE)((DWORD)pTex);
#else
/************************************************************************/
/* TODO */
/************************************************************************/
return NULL;
#endif
}
HTEXTURE CALL HGE_Impl::Texture_Load(const char *filename, DWORD size, bool bMipmap)
{
void *data;
DWORD _size;
#ifdef __WIN32
D3DFORMAT fmt1, fmt2;
LPDIRECT3DTEXTURE9 pTex;
D3DXIMAGE_INFO info;
#endif
CTextureList *texItem;
if(size) { data=(void *)filename; _size=size; }
else
{
data=pHGE->Resource_Load(filename, &_size);
if(!data) return NULL;
}
#ifdef __WIN32
if(*(DWORD*)data == 0x20534444) // Compressed DDS format magic number
{
fmt1=D3DFMT_UNKNOWN;
fmt2=D3DFMT_A8R8G8B8;
}
else
{
fmt1=D3DFMT_A8R8G8B8;
fmt2=D3DFMT_UNKNOWN;
}
// if( FAILED( D3DXCreateTextureFromFileInMemory( pD3DDevice, data, _size, &pTex ) ) ) pTex=NULL;
if( FAILED( D3DXCreateTextureFromFileInMemoryEx( pD3DDevice, data, _size,
D3DX_DEFAULT, D3DX_DEFAULT,
bMipmap ? 0:1, // Mip levels
0, // Usage
fmt1, // Format
D3DPOOL_MANAGED, // Memory pool
D3DX_FILTER_NONE, // Filter
D3DX_DEFAULT, // Mip filter
0, // Color key
&info, NULL,
&pTex ) ) )
if( FAILED( D3DXCreateTextureFromFileInMemoryEx( pD3DDevice, data, _size,
D3DX_DEFAULT, D3DX_DEFAULT,
bMipmap ? 0:1, // Mip levels
0, // Usage
fmt2, // Format
D3DPOOL_MANAGED, // Memory pool
D3DX_FILTER_NONE, // Filter
D3DX_DEFAULT, // Mip filter
0, // Color key
&info, NULL,
&pTex ) ) )
{
_PostError("Can't create texture");
if(!size) Resource_Free(data);
return NULL;
}
#else
/************************************************************************/
/* TODO */
/************************************************************************/
Image * pTex = loadImageFromMemory((BYTE *)data, _size);
#endif
if(!size) Resource_Free(data);
if (!pTex)
{
return NULL;
}
texItem=new CTextureList;
texItem->tex=(HTEXTURE)((DWORD)pTex);
#ifdef __WIN32
texItem->width=info.Width;
texItem->height=info.Height;
#else
texItem->width=pTex->textureWidth;
texItem->height=pTex->textureHeight;
#endif
texItem->next=textures;
textures=texItem;
return (HTEXTURE)((DWORD)pTex);
}
void CALL HGE_Impl::Texture_Free(HTEXTURE tex)
{
DWORD ttex = Texture_GetTexture(tex);
#ifdef __WIN32
LPDIRECT3DTEXTURE9 pTex=(LPDIRECT3DTEXTURE9)ttex;
#else
#ifdef __PSP
Image * pTex = (Image *)ttex;
#endif // __PSP
#endif
CTextureList *texItem=textures, *texPrev=0;
while(texItem)
{
if(texItem->tex.tex==tex.tex)
{
if(texPrev) texPrev->next=texItem->next;
else textures=texItem->next;
delete texItem;
break;
}
texPrev=texItem;
texItem=texItem->next;
}
#ifdef __WIN32
if(pTex != NULL) pTex->Release();
#else
#ifdef __PSP
if (pTex)
{
freeImage(pTex);
}
#endif // __PSP
#endif
}
DWORD CALL HGE_Impl::Texture_GetTexture(HTEXTURE tex)
{
return tex.GetTexture(nTexInfo, texInfo);
}
int CALL HGE_Impl::Texture_GetWidth(HTEXTURE tex, bool bOriginal)
{
DWORD ttex = Texture_GetTexture(tex);
if (!ttex)
{
return tex.GetTextureWidthByInfo(nTexInfo, texInfo);
}
#ifdef __WIN32
D3DSURFACE_DESC TDesc;
LPDIRECT3DTEXTURE9 pTex=(LPDIRECT3DTEXTURE9)ttex;
#endif
CTextureList *texItem=textures;
if(bOriginal)
{
while(texItem)
{
if(texItem->tex.tex==tex.tex) return texItem->width;
texItem=texItem->next;
}
return 0;
}
#ifdef __WIN32
else
{
if(FAILED(pTex->GetLevelDesc(0, &TDesc))) return 0;
else return TDesc.Width;
}
#else
Image * pTex = (Image *)ttex;
return pTex->textureWidth;
#endif
}
int CALL HGE_Impl::Texture_GetHeight(HTEXTURE tex, bool bOriginal)
{
DWORD ttex = Texture_GetTexture(tex);
if (!ttex)
{
return tex.GetTextureHeightByInfo(nTexInfo, texInfo);
}
#ifdef __WIN32
D3DSURFACE_DESC TDesc;
LPDIRECT3DTEXTURE9 pTex=(LPDIRECT3DTEXTURE9)ttex;
#endif
CTextureList *texItem=textures;
if(bOriginal)
{
while(texItem)
{
if(texItem->tex.tex==tex.tex) return texItem->height;
texItem=texItem->next;
}
return 0;
}
#ifdef __WIN32
else
{
if(FAILED(pTex->GetLevelDesc(0, &TDesc))) return 0;
else return TDesc.Height;
}
#else
Image * pTex = (Image *)ttex;
return pTex->textureHeight;
#endif
}
DWORD * CALL HGE_Impl::Texture_Lock(HTEXTURE tex, bool bReadOnly, int left, int top, int width, int height)
{
#ifdef __WIN32
Texture_LoadTextureWhenNeeded(&tex);
DWORD ttex = Texture_GetTexture(tex);
LPDIRECT3DTEXTURE9 pTex=(LPDIRECT3DTEXTURE9)ttex;
D3DSURFACE_DESC TDesc;
D3DLOCKED_RECT TRect;
RECT region, *prec;
int flags;
pTex->GetLevelDesc(0, &TDesc);
if(TDesc.Format!=D3DFMT_A8R8G8B8 && TDesc.Format!=D3DFMT_X8R8G8B8) return 0;
if(width && height)
{
region.left=left;
region.top=top;
region.right=left+width;
region.bottom=top+height;
prec=®ion;
}
else prec=0;
if(bReadOnly) flags=D3DLOCK_READONLY;
else flags=0;
if(FAILED(pTex->LockRect(0, &TRect, prec, flags)))
{
_PostError("Can't lock texture");
return NULL;
}
return (DWORD *)TRect.pBits;
#else
return NULL;
#endif
}
void CALL HGE_Impl::Texture_Unlock(HTEXTURE tex)
{
#ifdef __WIN32
DWORD ttex = Texture_GetTexture(tex);
LPDIRECT3DTEXTURE9 pTex=(LPDIRECT3DTEXTURE9)ttex;
pTex->UnlockRect(0);
#endif
}
bool CALL HGE_Impl::Texture_Save(HTEXTURE tex, const char * filename, DWORD filetype)
{
#ifdef __WIN32
DWORD ttex = Texture_GetTexture(tex);
LPDIRECT3DTEXTURE9 pTex=(LPDIRECT3DTEXTURE9)ttex;
if (!pTex)
{
return false;
}
HRESULT hr = D3DXSaveTextureToFile(filename, (D3DXIMAGE_FILEFORMAT)filetype, pTex, NULL);
if (FAILED(hr))
{
return false;
}
#endif
return true;
}
bool CALL HGE_Impl::Texture_LoadTextureWhenNeeded(HTEXTURE * tex)
{
if (procLoadTextureFunc)
{
Texture_SetTextureToLoad(tex);
bool bret = procLoadTextureFunc();
Texture_SetTextureToLoad(NULL);
return bret;
}
return false;
}
void CALL HGE_Impl::Texture_SetTextureToLoad(HTEXTURE * tex)
{
textoload = tex;
}
HTEXTURE * CALL HGE_Impl::Texture_GetTextureToLoad()
{
return textoload;
}
//////// Implementation ////////
void HGE_Impl::_render_batch(bool bEndScene)
{
#ifdef __WIN32
if(VertArray)
{
pVB->Unlock();
if(nPrim)
{
switch(CurPrimType)
{
case HGEPRIM_QUADS:
//+2nd
pD3DDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, nPrim<<2, 0, nPrim<<1);
break;
case HGEPRIM_TRIPLES:
pD3DDevice->DrawPrimitive(D3DPT_TRIANGLELIST, 0, nPrim);
break;
case HGEPRIM_LINES:
pD3DDevice->DrawPrimitive(D3DPT_LINELIST, 0, nPrim);
break;
case HGEPRIM_POINTS:
pD3DDevice->DrawPrimitive(D3DPT_POINTLIST, 0, nPrim);
break;
}
nPrim=0;
}
if(bEndScene) VertArray = 0;
else pVB->Lock( 0, 0, (void**)&VertArray, 0 );
}
#endif
}
void HGE_Impl::_SetBlendMode(int blend)
{
#ifdef __WIN32
if((blend & BLEND_ALPHABLEND) != (CurBlendMode & BLEND_ALPHABLEND))
{
if(blend & BLEND_ALPHABLEND) pD3DDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
else pD3DDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE);
}
if((blend & BLEND_ZWRITE) != (CurBlendMode & BLEND_ZWRITE))
{
if(blend & BLEND_ZWRITE) pD3DDevice->SetRenderState(D3DRS_ZWRITEENABLE, TRUE);
else pD3DDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
}
if((blend & BLEND_COLORADD) != (CurBlendMode & BLEND_COLORADD))
{
if(blend & BLEND_COLORADD) pD3DDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_ADD);
else pD3DDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE);
}
#else
#ifdef __PSP
int toblend;
switch (blend)
{
case BLEND_ALPHAADD:
toblend = GU_TFX_ADD;
default:
toblend = GU_TFX_MODULATE;
break;
}
sceGuTexFunc(toblend, GU_TCC_RGBA);
#endif // __PSP
#endif
CurBlendMode = blend;
}
void HGE_Impl::_SetProjectionMatrix(int width, int height)
{
D3DXMATRIX tmp;
Math_MatrixScaling(&matProj, 1.0f, -1.0f, 1.0f);
Math_MatrixTranslation(&tmp, -0.5f, height+0.5f, 0.0f);
Math_MatrixMultiply(&matProj, &matProj, &tmp);
Math_MatrixOrthoOffCenterLH(&tmp, 0, (float)width, 0, (float)height, 0.0f, 1.0f);
Math_MatrixMultiply(&matProj, &matProj, &tmp);
}
#ifdef __PSP
static unsigned int staticOffset = 0;
static unsigned int getMemorySize(unsigned int width, unsigned int height, unsigned int psm)
{
switch (psm)
{
case GU_PSM_T4:
return (width * height) >> 1;
case GU_PSM_T8:
return width * height;
case GU_PSM_5650:
case GU_PSM_5551:
case GU_PSM_4444:
case GU_PSM_T16:
return 2 * width * height;
case GU_PSM_8888:
case GU_PSM_T32:
return 4 * width * height;
default:
return 0;
}
}
void* getStaticVramBuffer(unsigned int width, unsigned int height, unsigned int psm)
{
unsigned int memSize = getMemorySize(width,height,psm);
void* result = (void*)staticOffset;
staticOffset += memSize;
return result;
}
void* getStaticVramTexture(unsigned int width, unsigned int height, unsigned int psm)
{
void* result = getStaticVramBuffer(width,height,psm);
return (void*)(((unsigned int)result) + ((unsigned int)sceGeEdramGetAddr()));
}
#endif // __PSP
bool HGE_Impl::_GfxInit()
{
#ifdef __WIN32
static const char *szFormats[]={"UNKNOWN", "R5G6B5", "X1R5G5B5", "A1R5G5B5", "X8R8G8B8", "A8R8G8B8"};
D3DADAPTER_IDENTIFIER9 AdID;
D3DDISPLAYMODE Mode;
D3DFORMAT Format=D3DFMT_UNKNOWN;
UINT nModes, i;
// Init D3D
/************************************************************************/
/* This parameter is changed by h5nc ([email protected]) */
/************************************************************************/
pD3D=Direct3DCreate9(D3D_SDK_VERSION/* 120 */); // D3D_SDK_VERSION
if(pD3D==NULL)
{
_PostError("Can't create D3D interface");
return false;
}
// Get adapter info
//change 2nd
pD3D->GetAdapterIdentifier(D3DADAPTER_DEFAULT, D3DADAPTER_DEFAULT, &AdID);
System_Log("D3D Driver: %s",AdID.Driver);
System_Log("Description: %s",AdID.Description);
System_Log("Version: %d.%d.%d.%d",
HIWORD(AdID.DriverVersion.HighPart),
LOWORD(AdID.DriverVersion.HighPart),
HIWORD(AdID.DriverVersion.LowPart),
LOWORD(AdID.DriverVersion.LowPart));
// Set up Windowed presentation parameters
if(FAILED(pD3D->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &Mode)) || Mode.Format==D3DFMT_UNKNOWN)
{
_PostError("Can't determine desktop video mode");
if(bWindowed) return false;
}
ZeroMemory(&d3dppW, sizeof(d3dppW));
d3dppW.BackBufferWidth = nScreenWidth;
d3dppW.BackBufferHeight = nScreenHeight;
d3dppW.BackBufferFormat = Mode.Format;
d3dppW.BackBufferCount = 1;
d3dppW.MultiSampleType = D3DMULTISAMPLE_NONE;
d3dppW.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
d3dppW.hDeviceWindow = hwnd;
d3dppW.Windowed = TRUE;
/************************************************************************/
/* This parameter is changed by h5nc ([email protected]) */
/************************************************************************/
d3dppW.SwapEffect = D3DSWAPEFFECT_DISCARD;
if(bZBuffer)
{
d3dppW.EnableAutoDepthStencil = TRUE;
d3dppW.AutoDepthStencilFormat = D3DFMT_D16;
}
/************************************************************************/
/* The following blocks are modified by h5nc ([email protected]) */
/************************************************************************/
if(nScreenBPP == 32)
{
nModes=pD3D->GetAdapterModeCount(D3DADAPTER_DEFAULT, D3DFMT_X8R8G8B8);
for(i=0;i<nModes;i++)
{
pD3D->EnumAdapterModes(D3DADAPTER_DEFAULT, D3DFMT_X8R8G8B8, i, &Mode);
if(Mode.Width != (UINT)nScreenWidth || Mode.Height != (UINT)nScreenHeight) continue;
if(_format_id(Mode.Format) > _format_id(Format)) Format=Mode.Format;
}
}
else
{
D3DFORMAT tempFormat = D3DFMT_X1R5G5B5;
nModes = pD3D->GetAdapterModeCount(D3DADAPTER_DEFAULT, D3DFMT_X1R5G5B5);
if(!nModes)
{
nModes = pD3D->GetAdapterModeCount(D3DADAPTER_DEFAULT, D3DFMT_R5G6B5);
tempFormat = D3DFMT_R5G6B5;
}
for(i=0; i<nModes; i++)
{
pD3D->EnumAdapterModes(D3DADAPTER_DEFAULT, tempFormat, i, &Mode);
if(Mode.Width != (UINT)nScreenWidth || Mode.Height != (UINT)nScreenHeight) continue;
if(_format_id(Mode.Format) > _format_id(Format)) Format=Mode.Format;
}
}
ZeroMemory(&d3dppFS, sizeof(d3dppFS));
d3dppFS.BackBufferWidth = nScreenWidth;
d3dppFS.BackBufferHeight = nScreenHeight;
d3dppFS.BackBufferFormat = Format;
d3dppFS.BackBufferCount = 1;
d3dppFS.MultiSampleType = D3DMULTISAMPLE_NONE;
d3dppFS.hDeviceWindow = hwnd;
d3dppFS.Windowed = FALSE;
/************************************************************************/
/* This parameter is changed by h5nc ([email protected]) */
/************************************************************************/
d3dppFS.SwapEffect = D3DSWAPEFFECT_DISCARD;
d3dppFS.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT;
if(nHGEFPS==HGEFPS_VSYNC) d3dppFS.PresentationInterval = D3DPRESENT_INTERVAL_ONE;
else d3dppFS.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
if(bZBuffer)
{
d3dppFS.EnableAutoDepthStencil = TRUE;
d3dppFS.AutoDepthStencilFormat = D3DFMT_D16;
}
d3dpp = bWindowed ? &d3dppW : &d3dppFS;
if(_format_id(d3dpp->BackBufferFormat) < 4) nScreenBPP=16;
else nScreenBPP=32;
/************************************************************************/
/* These blocks are added by h5nc ([email protected]) */
/************************************************************************/
// Get D3D caps
D3DCAPS9 d3dcaps;
if(FAILED(pD3D->GetDeviceCaps(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, &d3dcaps)))
{
_PostError("Can't get D3DCAPS");
return false;
}
DWORD d3dvp = D3DCREATE_HARDWARE_VERTEXPROCESSING;
if ((d3dcaps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT) == 0 || d3dcaps.VertexShaderVersion < D3DVS_VERSION(1,1))
{
d3dvp = D3DCREATE_SOFTWARE_VERTEXPROCESSING;
}
// Create D3D Device
/************************************************************************/
/* This parameter is changed by h5nc ([email protected]) */
/************************************************************************/
if( FAILED( pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hwnd,
/*D3DCREATE_SOFTWARE_VERTEXPROCESSING,*/
d3dvp,
d3dpp, &pD3DDevice ) ) )
{
_PostError("Can't create D3D device");
return false;
}
Gfx_SetTextureInfo(0);
#endif
#ifdef __PSP
#define BUF_WIDTH (512)
// Setup GU
//pspDebugScreenInit();
// Setup GU
void * m_drawbuf = getStaticVramBuffer(BUF_WIDTH,SCREEN_HEIGHT,GU_PSM_8888);
void * m_displaybuf = getStaticVramBuffer(BUF_WIDTH,SCREEN_HEIGHT,GU_PSM_8888);
void * m_zbuf = getStaticVramBuffer(BUF_WIDTH,SCREEN_HEIGHT,GU_PSM_4444);
// setup GU
sceGuInit();
sceGuStart(GU_DIRECT, gulist);
sceGuDrawBuffer(GU_PSM_8888,m_drawbuf,BUF_WIDTH);
sceGuDispBuffer(SCREEN_WIDTH,SCREEN_HEIGHT,m_displaybuf,BUF_WIDTH);
sceGuDepthBuffer(m_zbuf,BUF_WIDTH);
sceGuOffset(2048 - (SCREEN_WIDTH/2), 2048 - (SCREEN_HEIGHT/2));
sceGuViewport(2048, 2048, SCREEN_WIDTH, SCREEN_HEIGHT);
// Scissoring
sceGuEnable(GU_SCISSOR_TEST);
sceGuScissor(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
// Backface culling
sceGuFrontFace(GU_CCW);
sceGuDisable(GU_CULL_FACE); // no culling in 2D
// Depth test
sceGuDisable(GU_DEPTH_TEST);
sceGuDepthMask(GU_TRUE); // disable z-writes
// Color keying
sceGuDisable(GU_COLOR_TEST);
sceGuDisable(GU_ALPHA_TEST);
sceGuDisable(GU_CLIP_PLANES);
// Texturing
sceGuEnable(GU_TEXTURE_2D);
sceGuShadeModel(GU_SMOOTH);
sceGuTexWrap(GU_REPEAT, GU_REPEAT);
sceGuTexFilter(GU_LINEAR,GU_LINEAR);
//sceGuTexFunc(GU_TFX_REPLACE, GU_TCC_RGBA);
sceGuTexEnvColor(0xFFFFFFFF);
sceGuColor(0xFFFFFFFF);
sceGuAmbientColor(0xFFFFFFFF);
sceGuTexOffset(0.0f, 0.0f);
sceGuTexScale(1.0f, 1.0f);
// Blending
sceGuEnable(GU_BLEND);
sceGuBlendFunc(GU_ADD, GU_SRC_ALPHA, GU_ONE_MINUS_SRC_ALPHA, 0, 0);
sceGuTexFunc(GU_TFX_MODULATE,GU_TCC_RGBA);
sceGuTexFilter(GU_LINEAR,GU_LINEAR);
sceGuDisable(GU_DITHER);
// Projection
matProj.m[0][0] = SCREEN_HEIGHT/SCREEN_WIDTH;
matProj.m[0][1] = 0.0f;
matProj.m[0][2] = 0.0f;
matProj.m[0][3] = 0.0f;
matProj.m[1][0] = 0.0f;
matProj.m[1][1] = -1.0f;
matProj.m[1][2] = 0.0f;
matProj.m[1][3] = 0.0f;
matProj.m[2][0] = 0.0f;
matProj.m[2][1] = 0.0f;
matProj.m[2][2] = -1.0f;
matProj.m[2][3] = -1.0f;
matProj.m[3][0] = -SCREEN_HEIGHT/2;
matProj.m[3][1] = SCREEN_HEIGHT/2;
matProj.m[3][2] = SCREEN_HEIGHT/2;
matProj.m[3][3] = SCREEN_HEIGHT/2;
sceGumMatrixMode(GU_PROJECTION);
sceGumLoadIdentity();
sceGumMultMatrix((ScePspFMatrix4*)&matProj);
sceGumMatrixMode(GU_VIEW);
sceGumLoadIdentity();
sceGumMatrixMode(GU_MODEL);
sceGumLoadIdentity();
sceGuClearColor( 0x0 );
sceGuClear(GU_COLOR_BUFFER_BIT|GU_FAST_CLEAR_BIT);
sceGuFinish();
sceGuSync(0,0);
sceDisplayWaitVblankStart();
sceGuDisplay(1);
#endif // __PSP
_AdjustWindow();
#ifdef __WIN32
System_Log("Mode: %d x %d x %s\n",nScreenWidth,nScreenHeight,szFormats[_format_id(Format)]);
#endif
// Create vertex batch buffer
VertArray=0;
textures=0;
// Init all stuff that can be lost
_SetProjectionMatrix(nScreenWidth, nScreenHeight);
Math_MatrixIdentity(&matView);
if(!_init_lost()) return false;
Gfx_Clear(0);
return true;
}
#ifdef __WIN32
int HGE_Impl::_format_id(D3DFORMAT fmt)
{
switch(fmt) {
case D3DFMT_R5G6B5: return 1;
case D3DFMT_X1R5G5B5: return 2;
case D3DFMT_A1R5G5B5: return 3;
case D3DFMT_X8R8G8B8: return 4;
case D3DFMT_A8R8G8B8: return 5;
default: return 0;
}
}
#endif
void HGE_Impl::_AdjustWindow()
{
#ifdef __WIN32
RECT *rc;
LONG style;
if(bWindowed) {rc=&rectW; style=styleW; }
else {rc=&rectFS; style=styleFS; }
SetWindowLong(hwnd, GWL_STYLE, style);
style=GetWindowLong(hwnd, GWL_EXSTYLE);
if(bWindowed)
{
SetWindowLong(hwnd, GWL_EXSTYLE, style & (~WS_EX_TOPMOST));
SetWindowPos(hwnd, HWND_NOTOPMOST, rc->left, rc->top, rc->right-rc->left, rc->bottom-rc->top, SWP_FRAMECHANGED);
}
else
{
SetWindowLong(hwnd, GWL_EXSTYLE, style | WS_EX_TOPMOST);
SetWindowPos(hwnd, HWND_TOPMOST, rc->left, rc->top, rc->right-rc->left, rc->bottom-rc->top, SWP_FRAMECHANGED);
}
#endif
}
void HGE_Impl::_Resize(int width, int height)
{
if(hwndParent)
{
//if(procFocusLostFunc) procFocusLostFunc();
#ifdef __WIN32
d3dppW.BackBufferWidth=width;
d3dppW.BackBufferHeight=height;
#endif
nScreenWidth=width;
nScreenHeight=height;
_SetProjectionMatrix(nScreenWidth, nScreenHeight);
_GfxRestore();
//if(procFocusGainFunc) procFocusGainFunc();
}
}
void HGE_Impl::_GfxDone()
{
CRenderTargetList *target=pTargets, *next_target;
while(textures) Texture_Free(textures->tex);
#ifdef __WIN32
if(pScreenSurf) { pScreenSurf->Release(); pScreenSurf=0; }
if(pScreenDepth) { pScreenDepth->Release(); pScreenDepth=0; }
#endif
while(target)
{
#ifdef __WIN32
if(target->pTex) target->pTex->Release();
if(target->pDepth) target->pDepth->Release();
#endif
next_target=target->next;
delete target;
target=next_target;
}
pTargets=0;
#ifdef __WIN32
if(pIB)
{
//-2nd
pD3DDevice->SetIndices(NULL);
pIB->Release();
pIB = NULL;
}
if(pVB)
{
if(VertArray) { pVB->Unlock(); VertArray=0; }
//+2nd
pD3DDevice->SetStreamSource( 0, pVB, 0, sizeof(hgeVertex) );
pVB->Release();
pVB = NULL;
}
if(pD3DDevice) { pD3DDevice->Release(); pD3DDevice=0; }
if(pD3D) { pD3D->Release(); pD3D=0; }
#else
#ifdef __PSP
sceGuTerm();
#endif // __PSP
#endif
}
bool HGE_Impl::_GfxRestore()
{
#ifdef __WIN32
CRenderTargetList *target=pTargets;
//if(!pD3DDevice) return false;
//if(pD3DDevice->TestCooperativeLevel() == D3DERR_DEVICELOST) return;
if(pScreenSurf) pScreenSurf->Release();
if(pScreenDepth) pScreenDepth->Release();
while(target)
{
if(target->pTex) target->pTex->Release();
if(target->pDepth) target->pDepth->Release();
target=target->next;
}
/************************************************************************/
/* Blocks marked with "Yuki" are originally her codes */
/* h5nc ([email protected]) copied these codes under her permission */
/************************************************************************/
/* add by Yuki */
// begin
CFontList * listIterator = fontList;
while (listIterator)
{
if (listIterator->font) ((ID3DXFont *)(listIterator->font))->OnLostDevice();
listIterator = listIterator->next;
}
// end
if(pIB)
{
pD3DDevice->SetIndices(NULL);
pIB->Release();
pIB = NULL;
}
if(pVB)
{
//+2nd
pD3DDevice->SetStreamSource( 0, pVB, 0, sizeof(hgeVertex) );
pVB->Release();
pVB = NULL;
}
pD3DDevice->Reset(d3dpp);
if(!_init_lost()) return false;
/************************************************************************/
/* Blocks marked with "Yuki" are originally her codes */
/* h5nc ([email protected]) copied these codes under her permission */
/************************************************************************/
/* add by Yuki */
// begin
listIterator = fontList;
while (listIterator)
{
if (listIterator->font) ((ID3DXFont *)(listIterator->font))->OnResetDevice();
listIterator = listIterator->next;
}
// end
if(procGfxRestoreFunc) return procGfxRestoreFunc();
#endif
return true;
}
bool HGE_Impl::_init_lost()
{
#ifdef __WIN32
CRenderTargetList *target=pTargets;
// Store render target
pScreenSurf=0;
pScreenDepth=0;
pD3DDevice->GetRenderTarget(0, &pScreenSurf);
pD3DDevice->GetDepthStencilSurface(&pScreenDepth);
while(target)
{
if(target->pTex)
D3DXCreateTexture(pD3DDevice, target->width, target->height, 1, D3DUSAGE_RENDERTARGET,
/*d3dpp->BackBufferFormat*/D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &target->pTex);
if(target->pDepth)
pD3DDevice->CreateDepthStencilSurface(target->width, target->height,
D3DFMT_D16, D3DMULTISAMPLE_NONE, 0, TRUE, &target->pDepth, NULL);
target=target->next;
}
// Create Vertex buffer
if( FAILED (pD3DDevice->CreateVertexBuffer(VERTEX_BUFFER_SIZE*sizeof(hgeVertex),
D3DUSAGE_WRITEONLY,
D3DFVF_HGEVERTEX,
D3DPOOL_DEFAULT, &pVB, NULL)))
{
_PostError("Can't create D3D vertex buffer");
return false;
}
// pD3DDevice->SetVertexShader( D3DFVF_HGEVERTEX );
pD3DDevice->SetFVF( D3DFVF_HGEVERTEX );
pD3DDevice->SetStreamSource( 0, pVB, 0, sizeof(hgeVertex) );
// Create and setup Index buffer
if( FAILED( pD3DDevice->CreateIndexBuffer(VERTEX_BUFFER_SIZE*6/4*sizeof(WORD),
D3DUSAGE_WRITEONLY,
D3DFMT_INDEX16,
D3DPOOL_DEFAULT, &pIB, NULL) ) )
{
_PostError("Can't create D3D index buffer");
return false;
}
WORD *pIndices, n=0;
if( FAILED( pIB->Lock( 0, 0, (void**)&pIndices, 0 ) ) )
{
_PostError("Can't lock D3D index buffer");
return false;
}
for(int i=0; i<VERTEX_BUFFER_SIZE/4; i++) {
*pIndices++=n;
*pIndices++=n+1;
*pIndices++=n+2;
*pIndices++=n+2;
*pIndices++=n+3;
*pIndices++=n;
n+=4;
}
pIB->Unlock();
pD3DDevice->SetIndices(pIB);
// Set common render states
//pD3DDevice->SetRenderState( D3DRS_LASTPIXEL, FALSE );
pD3DDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE );
pD3DDevice->SetRenderState( D3DRS_LIGHTING, FALSE );
pD3DDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, TRUE );
pD3DDevice->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_SRCALPHA );
pD3DDevice->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA );
pD3DDevice->SetRenderState( D3DRS_ALPHATESTENABLE, TRUE );
pD3DDevice->SetRenderState( D3DRS_ALPHAREF, 0x01 );
pD3DDevice->SetRenderState( D3DRS_ALPHAFUNC, D3DCMP_GREATEREQUAL );
pD3DDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_MODULATE );
pD3DDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
pD3DDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );
pD3DDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_MODULATE );
pD3DDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE );
pD3DDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE );
// pD3DDevice->SetTextureStageState(0, D3DTSS_MIPFILTER, D3DTEXF_POINT);
pD3DDevice->SetSamplerState(0, D3DSAMP_MIPFILTER, D3DTEXF_POINT);
if(bTextureFilter)
{
// pD3DDevice->SetTextureStageState(0,D3DTSS_MAGFILTER,D3DTEXF_LINEAR);
// pD3DDevice->SetTextureStageState(0,D3DTSS_MINFILTER,D3DTEXF_LINEAR);
pD3DDevice->SetSamplerState(0,D3DSAMP_MAGFILTER,D3DTEXF_LINEAR);
pD3DDevice->SetSamplerState(0,D3DSAMP_MINFILTER,D3DTEXF_LINEAR);
}
else
{
// pD3DDevice->SetTextureStageState(0,D3DTSS_MAGFILTER,D3DTEXF_POINT);
// pD3DDevice->SetTextureStageState(0,D3DTSS_MINFILTER,D3DTEXF_POINT);
pD3DDevice->SetSamplerState(0,D3DSAMP_MAGFILTER,D3DTEXF_POINT);
pD3DDevice->SetSamplerState(0,D3DSAMP_MINFILTER,D3DTEXF_POINT);
}
nPrim=0;
CurPrimType=HGEPRIM_QUADS;
CurBlendMode = BLEND_DEFAULT;
CurTexture = NULL;
pD3DDevice->SetTransform(D3DTS_VIEW, &matView);
pD3DDevice->SetTransform(D3DTS_PROJECTION, &matProj);
#endif
/************************************************************************/
/* TODO */
/************************************************************************/
return true;
}
| [
"CBE7F1F65@4a173d03-4959-223b-e14c-e2eaa5fc8a8b"
] | [
[
[
1,
1757
]
]
] |
9fcfcecf622131052de86621cbb2c78f74572d09 | 6fa6532d530904ba3704da72327072c24adfc587 | /SCoder/SCoder/coders/lsbsoundcoder.cpp | 17ca1f855e7f380717468a147e70a67b28cfc335 | [] | no_license | photoguns/code-hnure | 277b1c0a249dae75c66e615986fb1477e6e0f938 | 92d6ab861a9de3f409c5af0a46ed78c2aaf13c17 | refs/heads/master | 2020-05-20T08:56:07.927168 | 2009-05-29T16:49:34 | 2009-05-29T16:49:34 | 35,911,792 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,630 | cpp | ////////////////////////////////////////////////////////////////////////////////
#include "lsbsoundcoder.h"
#include <cassert>
////////////////////////////////////////////////////////////////////////////////
LSBSoundCoder::LSBSoundCoder()
{
}
////////////////////////////////////////////////////////////////////////////////
LSBSoundCoder::~LSBSoundCoder()
{
}
////////////////////////////////////////////////////////////////////////////////
std::string LSBSoundCoder::GetMessage( const Container* _container, const Key* _key )
{
// Must be a BMP container
if ( _container->IsWaveContainer() )
{
// Get container
const WAVContainer* container =
static_cast<const WAVContainer*>(_container);
// Setup Wave container
SetupContainer(container);
// Get message length first
unsigned long messageLength = GetMessageLength();
// Get message text
return GetMessageText(messageLength);
}
// Error, not a Wave container
return "";
}
////////////////////////////////////////////////////////////////////////////////
void LSBSoundCoder::SetMessage( Container* _container, const std::string& _message,
const Key* _key )
{
// Must be BMP container
if ( _container->IsWaveContainer() )
{
// Get container
const WAVContainer* container =
static_cast<const WAVContainer*>(_container);
// Setup Wave container
SetupContainer(container);
//Hide message length first
SetMessageLength( _message.length() );
// Hide message text
SetMessageText(_message);
}
}
////////////////////////////////////////////////////////////////////////////////
void LSBSoundCoder::SetupContainer( const WAVContainer* _container )
{
// Set current container
SetContainer(_container);
m_CurrSamplePosition = 0;
}
////////////////////////////////////////////////////////////////////////////////
const WAVContainer* LSBSoundCoder::GetContainer() const
{
return static_cast<const WAVContainer*>(m_Container);
}
////////////////////////////////////////////////////////////////////////////////
WAVContainer* LSBSoundCoder::GetContainer()
{
return m_Container;
}
////////////////////////////////////////////////////////////////////////////////
void LSBSoundCoder::SetContainer( const WAVContainer* _container )
{
m_Container = const_cast<WAVContainer*>(_container);
}
////////////////////////////////////////////////////////////////////////////////
unsigned long LSBSoundCoder::GetMessageLength()
{
// Binary message size
SizeTBitset messageLength;
// Read message length
for (size_t bitsRead = 0; bitsRead < bitsInSizeT; ++bitsRead)
{
// Bit
bool bit;
// If no space left to read bits - break
if ( !GetBit(&bit) )
{
assert(0&&"Can not get bit in GetMessageLength()");
break;
}
// Save bit
messageLength[bitsRead] = bit;
}
// Return message length
return messageLength.to_ulong();
}
////////////////////////////////////////////////////////////////////////////////
void LSBSoundCoder::SetMessageLength( size_t _length )
{
// Prepare message length for hiding - convert it to binary
SizeTBitset length(_length);
// Write all the bits
for (size_t bitsWritten = 0; bitsWritten < bitsInSizeT; ++bitsWritten)
{
// If no space left to write bits - break
if ( !SetBit( length[bitsWritten] ) )
{
assert(0&&"Can not set bit in SetMessageLength()");
break;
}
}
}
////////////////////////////////////////////////////////////////////////////////
std::string LSBSoundCoder::GetMessageText( size_t _length )
{
// Binary message
BinaryString message;
size_t bitsInMessage = _length * bitsInChar;
// Read message
for (size_t bitsRead = 0; bitsRead < bitsInMessage; ++bitsRead )
{
// Add new char to message to write bits in
if (bitsRead % bitsInChar == 0)
message.push_back( CharBitset() );
// Bit
bool bit;
// If no space left to read bits - break
if ( !GetBit(&bit) )
{
assert(0&&"Can not get bit in GetMessageText()");
break;
}
// Save bit
message.back()[bitsRead % bitsInChar] = bit;
}
// Result string
std::string str;
// Convert from binary to char
for (size_t i = 0; i < message.size(); ++i)
str += static_cast<char>( message[i].to_ulong() );
return str;
}
////////////////////////////////////////////////////////////////////////////////
void LSBSoundCoder::SetMessageText( const std::string& _message )
{
// Prepare message for hiding - convert it to binary
BinaryString message;
// Convert message to binary
for (size_t byteN = 0; byteN < _message.length(); ++byteN)
// Save each letter
message.push_back(_message[byteN]);
// Get container dimensions
const size_t bitsInMessage = _message.size() * bitsInChar;
// Hide message
for (size_t bitsWritten = 0; bitsWritten < bitsInMessage; ++bitsWritten)
{
// If no space left to write bits - break
if ( !SetBit( message[bitsWritten / bitsInChar]
[bitsWritten % bitsInChar] ) )
{
assert(0&&"Can not set bit in SetMessageText()");
break;
}
}
}
////////////////////////////////////////////////////////////////////////////////
bool LSBSoundCoder::GetBit( bool* _bit )
{
// Check borders
if ( JumpToNextSample() )
{
// Get sample
short sample = m_Container->GetSample(m_CurrSamplePosition);
// Get sample's LSB
if (sample % 2)
*_bit = true;
else
*_bit = false;
// Bit has been read
return true;
}
else
// Bit has not been read
return false;
}
////////////////////////////////////////////////////////////////////////////////
bool LSBSoundCoder::SetBit( bool _bit )
{
// Check borders
if ( JumpToNextSample() )
{
// Get sample
short sample = m_Container->GetSample(m_CurrSamplePosition);
// Reset LSB
sample &= 254;
// Set LSB
sample |= static_cast<short>(_bit);
// Save sample
SetCurrSample(sample);
// Bit has been written
return true;
}
else
// Bit has not been written
return false;
}
////////////////////////////////////////////////////////////////////////////////
bool LSBSoundCoder::JumpToNextSample()
{
++m_CurrSamplePosition;
return m_CurrSamplePosition < m_Container->Size();
}
////////////////////////////////////////////////////////////////////////////////
short LSBSoundCoder::GetCurrSample() const
{
return m_Container->GetSample(m_CurrSamplePosition);
}
////////////////////////////////////////////////////////////////////////////////
void LSBSoundCoder::SetCurrSample( short _sample )
{
m_Container->SetSample(m_CurrSamplePosition, _sample);
}
////////////////////////////////////////////////////////////////////////////////
| [
"[email protected]@8592428e-0b6d-11de-9036-69e38a880166"
] | [
[
[
1,
319
]
]
] |
639f4ca27acb23506ae51f7ce030de0884cb27f6 | bc748fecef580023b06779a36ba37f0b6375e16b | /code/source/powerups/PowerupReverse.cpp | 61913d6a53cb54c13b1f780fa2faba072c218d19 | [] | no_license | Zilor/tetricycle | 9c89e6c4b3a144873295ba642390ecc83049b965 | 0d34bbb1c4dc248db0586bf0a4ab24d0ce7a997c | refs/heads/master | 2016-09-06T07:52:04.401928 | 2010-10-21T00:23:23 | 2010-10-21T00:23:23 | 34,345,077 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,091 | cpp | /*
* TetriCycle
* Copyright (C) 2009, 2010 Cale Scholl
*
* This file is part of TetriCycle.
*
* TetriCycle 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.
*
* TetriCycle 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 TetriCycle. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file PowerupReverse.cpp
* @author Cale Scholl / calvinss4
*/
#include "PowerupReverse.h"
#include "Player.h" // for Player
#include "libwiigui/gui.h" // for GuiImageData
extern Player *g_players; ///< the player instances
PowerupId PowerupReverse::powerupId;
Powerup *PowerupReverse::instance = new PowerupReverse();
GuiImageData *PowerupReverse::imageData =
new GuiImageData(powerup_reverse_png);
string PowerupReverse::helpText[2] =
{"Reverse", "Reverses the direction in which the "
"target player's tetris cylinder rotates."};
void PowerupReverse::StartEffect(u8 player)
{
g_players[player].gameData.powerupData.isReverse = true;
}
/// Allow more than one PowerupReverse to be in effect at the same time.
/**
* This function assumes this powerup has already been removed from the powerup
* effect queue. If another PowerupReverse is in the queue then allow that one
* to stop the effect.
*/
void PowerupReverse::StopEffect(u8 player)
{
for (int i = 0; i < MAX_POWERUP_EFFECTS; ++i)
{
Powerup *powerup = g_players[player].gameData.powerupEffects[i];
if (powerup && powerup->GetPowerupId() == powerupId)
{
return;
}
}
g_players[player].gameData.powerupData.isReverse = false;
} | [
"CaleScholl@ee772953-8931-6355-c94c-fe2f9a27bad4"
] | [
[
[
1,
65
]
]
] |
19c0e49baf1a47891bab7f36d5d144b13404d43f | c95a83e1a741b8c0eb810dd018d91060e5872dd8 | /libs/STLPort-4.0/stlport/stl/_string_hash.h | 228c7268ad0269e1843e88c84ffe427e7921efdd | [
"LicenseRef-scancode-stlport-4.5"
] | permissive | 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,942 | h | /*
* Copyright (c) 1997-1999
* Silicon Graphics Computer Systems, Inc.
*
* Copyright (c) 1999
* Boris Fomitchev
*
* This material is provided "as is", with absolutely no warranty expressed
* or implied. Any use is at your own risk.
*
* Permission to use or copy this software for any purpose is hereby granted
* without fee, provided the above notices are retained on all copies.
* Permission to modify the code and to distribute modified code is granted,
* provided the above notices are retained, and a notice that the code was
* modified is included with the above copyright notice.
*
*/
#ifndef __SGI_STL_STRING_HASH_H
# define __SGI_STL_STRING_HASH_H
#ifndef __SGI_STL_HASH_FUN_H
# include <stl/_hash_fun.h>
#endif
__STL_BEGIN_NAMESPACE
template <class _CharT, class _Traits, class _Alloc>
__STL_INLINE_LOOP size_t
__stl_string_hash(const basic_string<_CharT,_Traits,_Alloc>& __s) {
unsigned long __h = 0;
typedef typename basic_string<_CharT,_Traits,_Alloc>::const_pointer const_ptr;
size_t __len = __s.size();
const _CharT* __data = __s.data();
for ( size_t __i = 0; __i < __len; ++__i)
__h = 5*__h + __data[__i];
return size_t(__h);
}
#ifdef __STL_CLASS_PARTIAL_SPECIALIZATION
template <class _CharT, class _Traits, class _Alloc>
struct hash<basic_string<_CharT,_Traits,_Alloc> > {
size_t operator()(const basic_string<_CharT,_Traits,_Alloc>& __s) const
{ return __stl_string_hash(__s); }
};
#else
__STL_TEMPLATE_NULL struct __STL_CLASS_DECLSPEC hash<string> {
size_t operator()(const string& __s) const
{ return __stl_string_hash(__s); }
};
# if defined (__STL_HAS_WCHAR_T)
__STL_TEMPLATE_NULL struct __STL_CLASS_DECLSPEC hash<wstring> {
size_t operator()(const wstring& __s) const
{ return __stl_string_hash(__s); }
};
# endif
#endif /* __STL_CLASS_PARTIAL_SPECIALIZATION */
__STL_END_NAMESPACE
#endif
| [
"[email protected]"
] | [
[
[
1,
66
]
]
] |
68ad66c47f6d1d3f49d12df7302c285a3597476d | ac559231a41a5833220a1319456073365f13d484 | /src/old/server-jaus/cxutils/networking/tcpserver.h | 8c58b78198546358c94ab94cb0b1df2714125ea6 | [] | no_license | mtboswell/mtboswell-auvc2 | 6521002ca12f9f7e1ec5df781ed03419129b8f56 | 02bb0dd47936967a7b9fa7d091398812f441c1dc | refs/heads/master | 2020-04-01T23:02:15.282160 | 2011-07-17T16:48:34 | 2011-07-17T16:48:34 | 32,832,956 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,919 | h | ////////////////////////////////////////////////////////////////////////////////////
///
/// \file tcpserver.h
/// \brief This file contains software for the TcpServer. These
/// sockets are created by the TcpListenSocket and are used to handle
/// TCP connections from clients (TcpClientSocket).
///
/// <br>Author(s): Daniel Barber
/// <br>Created: 22 June 2007
/// <br>Copyright (c) 2009
/// <br>Applied Cognition and Training in Immersive Virtual Environments
/// <br>(ACTIVE) Laboratory
/// <br>Institute for Simulation and Training (IST)
/// <br>University of Central Florida (UCF)
/// <br>All rights reserved.
/// <br>Email: [email protected]
/// <br>Web: http://active.ist.ucf.edu
///
/// 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 ACTIVE LAB, IST, UCF, 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 ACTIVE LAB''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 UCF BE LIABLE FOR ANY
/// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
/// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
/// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
/// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
/// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
/// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
///
////////////////////////////////////////////////////////////////////////////////////
#ifndef __CXUTILS_TCP_SERVER_SOCKET_H
#define __CXUTILS_TCP_SERVER_SOCKET_H
#include "cxutils/networking/socket.h"
#include "cxutils/networking/tcplistensocket.h"
namespace CxUtils
{
////////////////////////////////////////////////////////////////////////////////////
///
/// \class TcpServer
/// \brief Socket created by TcpListenSocket which maintains a connection to
/// a TCP client. Capable of sending/receiving packet data from/to client.
///
/// TCP Connections are bi-directional (you can send and receive on the socket).
///
////////////////////////////////////////////////////////////////////////////////////
class CX_UTILS_DLL TcpServer : public Socket
{
friend class TcpListenSocket;
public:
TcpServer();
virtual ~TcpServer();
int InitializeSocket(const TcpListenSocket& socket);
inline IP4Address GetClientAddress() const { return mClientAddress; }
private:
virtual int SendFromBuffer(const char* buffer,
const unsigned int length) const;
virtual int RecvToBuffer(char* buffer,
const unsigned int length,
const long int timeOutMilliseconds = 0,
IPAddress* ipAddress = NULL,
unsigned short* port = NULL) const;
IP4Address mClientAddress; ///< IP address of connected client.
};
}
#endif
/* End of File */
| [
"[email protected]"
] | [
[
[
1,
80
]
]
] |
ade47a0e15611d2138c61d98c2e2e63be6a1e980 | dc9d65f711d3507da390eefb57c7519c97e81c64 | /plugins/filetransfer/ftid.cpp | 8d740888c43a3a85e8635a1a37306c9e844a9e6b | [] | no_license | xjohncz/saje | 40cd6d3a11b07c7e4b0f205762aacbe7528e4906 | 7c8a6c1cfab57feacc2dd657c70380b38330e3ef | refs/heads/master | 2021-01-20T08:46:49.601271 | 2011-04-20T03:18:10 | 2011-04-20T03:18:10 | 35,888,997 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 333 | cpp | #include "ftid.h"
FTId::FTId()
{
}
bool FTId::operator==(const FTId &other) const {
return id == other.id && contact == other.contact && incoming == other.incoming;
}
bool FTId::operator<(const FTId &other) const {
return id < other.id || contact < other.contact || (incoming ? 1 : 0) < (other.incoming ? 1 : 0);
}
| [
"sje397@200c22c1-0253-0410-a7cc-2773c7d12e9d"
] | [
[
[
1,
13
]
]
] |
d5fe1a23693b36c29bfae388c4cda8489be5ce55 | dba70d101eb0e52373a825372e4413ed7600d84d | /Demo/Demo_Beginning/Beginning.cpp | 82459d3c385430436915d6acd50b23071066d505 | [] | no_license | nustxujun/simplerenderer | 2aa269199f3bab5dc56069caa8162258e71f0f96 | 466a43a1e4f6e36e7d03722d0d5355395872ad86 | refs/heads/master | 2021-03-12T22:38:06.759909 | 2010-10-02T03:30:26 | 2010-10-02T03:30:26 | 32,198,944 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,658 | cpp | #include "Beginning.h"
int WINAPI WinMain ( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
App app;
app.start();
return 0;
}
void App::init(Renderer& renderer, const AppParam& param)
{
Matrix4X4 view, projection,world;
MatrixUtil::getViewSpace(view,Vector3(0,0,-3),Vector3(0,0,0),Vector3(0,1,0));
renderer.setMatrix(TS_VIEW,view);
MatrixUtil::getPerspectiveProjectionSpace(projection,3.14159265 / 4,param.width / param.height,0.1,10);
renderer.setMatrix(TS_PROJECTION,projection);
renderer.setMatrix(TS_WORLD,world);
VertexDeclaration vd2;
vd2.addElement(VET_FLOAT3,VES_POSITION);
vd2.addElement(VET_COLOUR,VES_DIFFUSE);
vd2.addElement(VET_FLOAT2,VES_TEXTURE_COORDINATES);
struct vertexFormat
{
float x,y,z;
int color;
float u,v;
};
vertexFormat vertexData[] =
{
-1.0f,-1.0f,0.0f,0x50ff0000,1.0f,1.0f,
-1.0f,1.0f,0.0f,0x5000ff00,1.0f,0.0f,
1.0f,-1.0f,0.f,0x500000ff,0.0f,1.0f,
1.0f,-1.0f,0.f,0x50ff00ff,0.0f,1.0f,
-1.0f,1.0f,0.0f,0x5000ff00,1.0f,0.0f,
1.0f,1.0f,0.0f,0x500000ff,0.0f,0.0f,
};
mVB = renderer.createVertexBuffer(6,vd2);
mVB->fill(0,6,vertexData);
}
void App::destroy(Renderer& renderer, const AppParam& param)
{}
void App::renderOneFrame(Renderer& renderer, const AppParam& param)
{
renderer.clearColour(Colour(0,0,0));
renderer.clearDepth(1.0f);
Matrix4X4 world;
static float i = 0;
i += 0.1f;
float r = sin(i);
world = world * r;
world.m[3][3] = 1;
renderer.setMatrix(RCP::TS_WORLD,world);
renderer.setVertexBuffer(mVB);
renderer.draw(PT_TRIANGLESTRIP,0,2);
}
| [
"[email protected]@c2606ca0-2ebb-fda8-717c-293879e69bc3"
] | [
[
[
1,
67
]
]
] |
aa5b7baf68b76c896d781645d22a863fd4673e04 | fd3f2268460656e395652b11ae1a5b358bfe0a59 | /srchybrid/StatisticsDlg.h | b9fcdca8a6689e16ad6285bea7f8fcacc1f808e2 | [] | 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 | ISO-8859-16 | C++ | false | false | 8,310 | h | //this file is part of eMule
//Copyright (C)2002-2008 Merkur ( strEmail.Format("%s@%s", "devteam", "emule-project.net") / http://www.emule-project.net )
//
//This program is free software; you can redistribute it and/or
//modify it under the terms of the GNU General Public License
//as published by the Free Software Foundation; either
//version 2 of the License, or (at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program; if not, write to the Free Software
//Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#pragma once
#include "ResizableLib\ResizableDialog.h"
#include "StatisticsTree.h"
#include "SplitterControl.h"
#include "OScopeCtrl.h"
// NOTE: Do not set specific 'Nr. of sub client versions' per client type, current code contains too much hardcoded
// references to deal with that.
#define MAX_CLIENTS_WITH_SUB_VERSION 4 // eMule, eDHyb, eD, aMule
#define MAX_SUB_CLIENT_VERSIONS 8
class CStatisticsDlg : public CResizableDialog
{
DECLARE_DYNAMIC(CStatisticsDlg)
public:
CStatisticsDlg(CWnd* pParent = NULL); // standard constructor
~CStatisticsDlg();
enum { IDD = IDD_STATISTICS };
void Localize();
//Xman
/*
void SetCurrentRate(float uploadrate, float downloadrate);
*/
//Xman end
void ShowInterval();
// -khaos--+++> Optional force update parameter.
void ShowStatistics(bool forceUpdate = false);
// <-----khaos-
void SetARange(bool SetDownload,int maxValue);
void RepaintMeters();
//Xman
// Maella -Accurate measure of bandwidth: eDonkey data + control, network adapter-
void Process();
// Maelle end
void UpdateConnectionsGraph();
void DoTreeMenu();
void CreateMyTree();
// -khaos--+++> New class for our humble little tree.
CStatisticsTree stattree;
// <-----khaos-
private:
COScopeCtrl m_DownloadOMeter,m_UploadOMeter,m_Statistics;
TOOLINFO tt;
//Xman
// Maella -Accurate measure of bandwidth: eDonkey data + control, network adapter-
//enum Curve {CURRENT = 0, MINUTE = 1, SESSION = 2, OVERALL = 3, ADAPTER = 4};
//Xman had to change it for filled graphs
enum Curve {ADAPTER = 0, OVERALL = 1, MINUTE = 2, SESSION = 3, CURRENT = 4};
#define NUMBEROFLINES 4
//Xman
/*
double m_dPlotDataMore[4];
*/
//Xman end
uint32 m_ilastMaxConnReached;
uint32 cli_lastCount[MAX_CLIENTS_WITH_SUB_VERSION];
CImageList imagelistStatTree;
HTREEITEM h_transfer, trans[3]; // Transfer Header and Items
HTREEITEM h_upload, h_up_session, up_S[6], h_up_total, up_T[2]; // Uploads Session and Total Items and Headers
HTREEITEM hup_scb, up_scb[7], hup_spb, up_spb[3], hup_ssb, up_ssb[2]; // Session Uploaded Byte Breakdowns
HTREEITEM hup_tcb, up_tcb[7], hup_tpb, up_tpb[3], hup_tsb, up_tsb[2]; // Total Uploaded Byte Breakdowns
//Xman
/*
HTREEITEM hup_soh, up_soh[4], hup_toh, up_toh[4]; // Upline Overhead
*/
HTREEITEM hup_soh, up_soh[5 /*Xman +1 count obfuscation data*/], hup_toh, up_toh[4]; // Upline Overhead
//Xman end
HTREEITEM up_ssessions[4], up_tsessions[4]; // Breakdown of Upload Sessions
HTREEITEM h_download, h_down_session, down_S[8], h_down_total, down_T[6]; // Downloads Session and Total Items and Headers
HTREEITEM hdown_scb, down_scb[8], hdown_spb, down_spb[3]; // Session Downloaded Byte Breakdowns
HTREEITEM hdown_tcb, down_tcb[8], hdown_tpb, down_tpb[3]; // Total Downloaded Byte Breakdowns
//Xman
/*
HTREEITEM hdown_soh, down_soh[4], hdown_toh, down_toh[4]; // Downline Overhead
HTREEITEM down_ssessions[4], down_tsessions[4], down_sources[22]; // Breakdown of Download Sessions and Sources
*/
HTREEITEM hdown_soh, down_soh[5 /*Xman +1 count obfuscation data*/], hdown_toh, down_toh[4]; // Downline Overhead
HTREEITEM down_ssessions[4], down_tsessions[4], down_sources[23 /*+1 Xman Xtreme Mod: Count failed tcp-connections */]; // Breakdown of Download Sessions and Sources
//Xman end
HTREEITEM h_connection, h_conn_session, h_conn_total; // Connection Section Headers
HTREEITEM hconn_sg, conn_sg[5], hconn_su, conn_su[4], hconn_sd, conn_sd[4]; // Connection Session Section Headers and Items
HTREEITEM hconn_tg, conn_tg[4], hconn_tu, conn_tu[3], hconn_td, conn_td[3]; // Connection Total Section Headers and Items
//Xman
/*
HTREEITEM h_clients, cligen[6], hclisoft, clisoft[8];
*/
HTREEITEM h_clients, cligen[9/*6*Official+1*Leecher+1*Mods+1*Country*/], hclisoft, clisoft[8]; //Xman Anti-Leecher //Xman extended stats
//Xman end
HTREEITEM cli_versions[MAX_CLIENTS_WITH_SUB_VERSION*MAX_SUB_CLIENT_VERSIONS];
HTREEITEM cli_other[MAX_SUB_CLIENT_VERSIONS/2];
HTREEITEM hclinet, clinet[4]; // Clients Section
HTREEITEM hcliport, cliport[2]; // Clients Section
HTREEITEM hclifirewalled, clifirewalled[2]; // Clients Section
HTREEITEM h_servers, srv[6], srv_w[3], hsrv_records, srv_r[3]; // Servers Section
HTREEITEM h_shared, shar[4], hshar_records, shar_r[4]; // Shared Section
// The time/projections section. Yes, it's huge.
HTREEITEM h_time, tvitime[2], htime_s, tvitime_s[4], tvitime_st[2], htime_t, tvitime_t[3], tvitime_tt[2];
HTREEITEM htime_aap, time_aaph[3], time_aap_hup[3], time_aap_hdown[3];
HTREEITEM time_aap_up_hd[3][3], time_aap_down_hd[3][2];
HTREEITEM time_aap_up[3][3], time_aap_up_dc[3][7], time_aap_up_dp[3][3];
HTREEITEM time_aap_up_ds[3][2], time_aap_up_s[3][2], time_aap_up_oh[3][4];
HTREEITEM time_aap_down[3][7], time_aap_down_dc[3][8], time_aap_down_dp[3][3];
HTREEITEM time_aap_down_s[3][2], time_aap_down_oh[3][4];
HTREEITEM h_total_downloads;
HTREEITEM h_total_num_of_dls;
HTREEITEM h_total_size_of_dls;
HTREEITEM h_total_size_dld;
HTREEITEM h_total_size_left_to_dl;
HTREEITEM h_total_size_left_on_drive;
HTREEITEM h_total_size_needed;
void SetupLegend( int ResIdx, int ElmtIdx, int legendNr);
void SetStatsRanges(int min, int max);
//Xman
// Maella -Accurate measure of bandwidth: eDonkey data + control, network adapter-
/*
int m_oldcx;
int m_oldcy;
*/
void ShowGraphs();
uint16 m_intervalGraph; // refresh counter for graphs
uint16 m_intervalStat; // refresh counter for statistic
// Maella end
#ifdef _DEBUG
HTREEITEM h_debug,h_blocks,debug1,debug2,debug3,debug4,debug5;
CMap<const unsigned char *,const unsigned char *,HTREEITEM *,HTREEITEM *> blockFiles;
#endif
HTREEITEM h_allocs;
HTREEITEM h_allocSizes[32];
protected:
void SetAllIcons();
virtual BOOL OnInitDialog();
virtual void OnSize(UINT nType,int cx,int cy);
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//MORPH START - Added by SiRoB, Splitting Bar [OČ]
CSplitterControl m_wndSplitterstat; //bzubzusplitstat
CSplitterControl m_wndSplitterstat_HL; //bzubzusplitstat
CSplitterControl m_wndSplitterstat_HR; //bzubzusplitstat
void DoResize_V(int delta);
void DoResize_HL(int delta);
void DoResize_HR(int delta);
void initCSize();
virtual LRESULT DefWindowProc(UINT message, WPARAM wParam, LPARAM lParam);
//MORPH END - Added by SiRoB, Splitting Bar [OČ]
virtual BOOL PreTranslateMessage(MSG* pMsg);
bool m_bTreepaneHidden;
CToolTipCtrl* m_TimeToolTips;
DECLARE_MESSAGE_MAP()
afx_msg void OnSysColorChange();
afx_msg void OnShowWindow(BOOL bShow, UINT nStatus);
afx_msg void OnMenuButtonClicked();
afx_msg void OnStnDblclickScopeD();
afx_msg void OnStnDblclickScopeU();
afx_msg void OnStnDblclickStatsscope();
afx_msg LRESULT OnOscopePositionMsg(WPARAM wParam, LPARAM lParam);
afx_msg BOOL OnHelpInfo(HELPINFO* pHelpInfo);
afx_msg HBRUSH OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor);
//Xman
// Maella -Network Adapter Feedback Control-
public:
int GetARange(bool SetDownload) const {return m_lastRange[(SetDownload==false)?0:1];}
private:
int m_lastRange[2];
// Maella end
// ==> Design Settings [eWombat/Stulle] - Max
protected:
CBrush m_brMyBrush;
COLORREF crStatsColor;
public:
void OnBackcolor();
// <== Design Settings [eWombat/Stulle] - Max
};
| [
"Mike.Ken.S@dd569cc8-ff36-11de-bbca-1111db1fd05b"
] | [
[
[
1,
206
]
]
] |
02393b63692c4c76922fff24fbbae0304fb95cbb | ee2e06bda0a5a2c70a0b9bebdd4c45846f440208 | /word/CppUTest/tests/AllTests.cpp | ead0a1e432ad5726e82fa3a67896e1b81ee65413 | [] | no_license | RobinLiu/Test | 0f53a376e6753ece70ba038573450f9c0fb053e5 | 360eca350691edd17744a2ea1b16c79e1a9ad117 | refs/heads/master | 2021-01-01T19:46:55.684640 | 2011-07-06T13:53:07 | 2011-07-06T13:53:07 | 1,617,721 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,794 | cpp | /*
* Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde
* 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 <organization> 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 EARLIER MENTIONED AUTHORS ``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 <copyright holder> 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 "CppUTest/CommandLineTestRunner.h"
int main(int ac, char** av)
{
return CommandLineTestRunner::RunAllTests(ac, av);
}
#include "AllTests.h"
| [
"RobinofChina@43938a50-64aa-11de-9867-89bd1bae666e"
] | [
[
[
1,
36
]
]
] |
a93bec93f32ccadcf99d427fb28423f3bc5a84db | 8258620cb8eca7519a58dadde63e84f65d99cc80 | /sandbox/dani/open_GL_examples/robot/robot.cpp | df5c7c7f4148aea5c8f584dca47f79caf1ddf214 | [] | no_license | danieleferro/3morduc | bfdf4c296243dcd7c5ba5984bc899001bf74732b | a27901ae90065ded879f5dd119b2f44a2933c6da | refs/heads/master | 2016-09-06T06:02:39.202421 | 2011-03-23T08:51:56 | 2011-03-23T08:51:56 | 32,210,720 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,281 | cpp | #include "robot.h"
void PaintCylinder(GLfloat radius,GLfloat height);
void PaintDisk(GLfloat radius);
Robot::Robot(float x, float y, float theta)
{
radius = y;
this->x = x;
this->y = y;
this->theta = theta;
}
void Robot::Place(GLfloat new_x, GLfloat new_y,
GLfloat new_theta)
{
this->x = new_x;
this->y = new_y;
this->theta = new_theta;
}
void Robot::DrawRobot()
{
GLfloat reflectance_black[] = { 0.2f, 0.2f, 0.2f};
GLfloat reflectance_white[] = { 0.8f, 0.8f, 0.8f};
GLfloat cosine, sine;
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
// set robot height
glTranslatef(0.0f, -12.0f, 0.0f);
// set robot reflectance (it is black)
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, reflectance_black);
// set robot position
glTranslatef(this->x, 0.0f, this->y);
glRotatef(-(this->theta) * 180 / M_PI, 0.0f, 1.0f, 0.0f);
// compute theta's cosine and sine value
cosine = cos(this->theta);
sine = sin(this->theta);
// translate on z axis
glTranslatef(0.0f,0.08f,0.0f);
glScalef(radius, radius, radius);
// draw robot
PaintCylinder(1.0f, 0.1);
PaintDisk(-1.0f);
glTranslatef(0.0f, 0.1f, 0.0f);
PaintDisk(1.0f);
glTranslatef(0.0f, 0.6f, 0.0f);
PaintCylinder(1.0f, 0.1f);
PaintDisk(-1.0f);
glTranslatef(0.0f, 0.1f, 0.0f);
PaintDisk(1.0f);
glTranslatef(0.8f, 0.0f, 0.0f);
glColor3f(0.5f, 0.5f, 0.5f);
PaintCylinder(0.2f, 0.3f);
glTranslatef(0.0f, 0.3f, 0.0f);
PaintDisk(0.2f);
glTranslatef(0,0.401,0);
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, reflectance_white);
PaintDisk(0.1f);
glTranslatef(0,-0.701,0);
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, reflectance_black);
glTranslatef(-0.8f, 0.0f, 0.0f);
glColor3f(0.1f, 0.1f, 0.1f);
glTranslatef(0.0f ,0.6f, 0.0f);
PaintCylinder(1.0f, 0.1f);
PaintDisk(-1.0f);
glTranslatef(0.0f, 0.1f, 0.0f);
PaintDisk(1.0f);
glTranslatef(0.0f, -1.5f, 0.0f);
glTranslatef(0.0f, 0.0f, 0.8f);
PaintCylinder(0.1f, 1.5f);
glTranslatef(0.0f, 0.0f, -1.60f);
PaintCylinder(0.1f, 1.5f);
glTranslatef(-0.8f, 0.0f, 0.8f);
PaintCylinder(0.1f, 1.5f);
glTranslatef(0.8f, 0.0f, 0.0f);
glScalef(1/radius, 1/radius, 1/radius);
glPopMatrix();
}
void PaintDisk(GLfloat radius)
{
glBegin(GL_POLYGON);
float pos = -1;
if (radius <= 0)
pos = pos*pos;
glNormal3f(0,pos,0);
// glVertex3f(0,0,0);
for (int k = 0; k <= 360; k++)
glVertex3f(radius * cos(M_PI/180*k), 0, radius * sin(M_PI/180*k*pos));
glEnd();
}
void PaintCylinder(GLfloat radius, GLfloat height)
{
GLfloat c[361], s[361];
glBegin(GL_QUAD_STRIP);
for (int k=0;k<=360;k++) {
c[k]=cos(M_PI/180*k);
s[k]=sin(M_PI/180*k);
glNormal3f(c[k], s[k], 0);
glVertex3f(radius * c[k], 0, radius * s[k]);
glVertex3f(radius * c[k], height, radius * s[k]);
}
for (int k=0; k<=360; k++) {
glNormal3f(c[k], s[k], 0);
glVertex3f(radius*c[k], height, radius*s[k]);
}
glEnd();
}
GLfloat Robot::GetX()
{
return this->x;
}
GLfloat Robot::GetY() {
return this->y;
}
GLfloat Robot::GetTheta() {
return this->theta;
}
| [
"loris.fichera@9b93cbac-0697-c522-f574-8d8975c4cc90",
"daniele.ferro86@9b93cbac-0697-c522-f574-8d8975c4cc90"
] | [
[
[
1,
5
],
[
7,
7
],
[
9,
13
],
[
16,
23
],
[
25,
26
],
[
28,
29
],
[
36,
36
],
[
38,
40
],
[
42,
49
],
[
52,
66
],
[
68,
72
],
[
74,
75
],
[
77,
78
],
[
80,
95
],
[
99,
148
],
[
150,
150
],
[
152,
152
],
[
155,
155
],
[
157,
157
],
[
160,
160
],
[
162,
162
]
],
[
[
6,
6
],
[
8,
8
],
[
14,
15
],
[
24,
24
],
[
27,
27
],
[
30,
35
],
[
37,
37
],
[
41,
41
],
[
50,
51
],
[
67,
67
],
[
73,
73
],
[
76,
76
],
[
79,
79
],
[
96,
98
],
[
149,
149
],
[
151,
151
],
[
153,
154
],
[
156,
156
],
[
158,
159
],
[
161,
161
],
[
163,
164
]
]
] |
565f158c094984434566f5bbefe138e1a7f20f50 | 1960e1ee431d2cfd2f8ed5715a1112f665b258e3 | /src/com/coconnectionpoint.cpp | be228713aa3dec0cef04c0e16888b657d4231d6c | [] | no_license | BackupTheBerlios/bvr20983 | c26a1379b0a62e1c09d1428525f3b4940d5bb1a7 | b32e92c866c294637785862e0ff9c491705c62a5 | refs/heads/master | 2021-01-01T16:12:42.021350 | 2009-11-01T22:38:40 | 2009-11-01T22:38:40 | 39,518,214 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,941 | cpp | /*
* $Id$
*
* Connection point object that manages IUnknown pointers.
* This is a stand-alone object created from the implementation of IConnectionPointContainer.
*
* Copyright (C) 2008 Dorothea Wachmann
*
* 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
* (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, see http://www.gnu.org/licenses/.
*/
#include "os.h"
#include "com/coconnectionpoint.h"
#include "com/coenum.h"
#include "com/codispatch.h"
#include "util/logstream.h"
#include "util/comlogstream.h"
namespace bvr20983
{
namespace COM
{
/*
* COConnectionPoint::COConnectionPoint
*
* Parameters (Constructor):
* pObj PCConnObject of the object we're in. We can
* query this for the IConnectionPointContainer
* interface we might need.
* riid REFIID of the interface we're supporting
*/
COConnectionPoint::COConnectionPoint(IUnknown* pObj,REFGUID typelibGUID, REFIID riid)
: m_typelibGUID(typelibGUID),
m_iid(riid)
{ m_cRef = 1;
m_cConn = 0;
m_pObj = pObj;
m_pITypeInfo = NULL;
for( UINT i=0; i < CCONNMAX; i++)
m_gpUnknown[i].SetIID(m_iid);
CODispatch::LoadTypeInfo(m_typelibGUID,m_iid,&m_pITypeInfo);
} // of COConnectionPoint::COConnectionPoint()
/**
* COConnectionPoint::~COConnectionPoint
*
*/
COConnectionPoint::~COConnectionPoint()
{ RELEASE_INTERFACE(m_pITypeInfo);
} // of COConnectionPoint::~COConnectionPoint()
/*
* COConnectionPoint::QueryInterface
* COConnectionPoint::AddRef
* COConnectionPoint::Release
*
* Purpose:
* Non-delegating IUnknown members for COConnectionPoint.
*/
STDMETHODIMP COConnectionPoint::QueryInterface(REFIID riid, LPVOID *ppv)
{ HRESULT result = E_NOINTERFACE;
*ppv=NULL;
if( IID_IUnknown==riid || IID_IConnectionPoint==riid )
*ppv=(LPVOID)this;
else
LOGGER_DEBUG<<_T("COConnectionPoint::QueryInterface(")<<riid<<_T(") unknown interface ")<<endl;
if( NULL!=*ppv )
{ ((LPUNKNOWN)*ppv)->AddRef();
result = NOERROR;
} // of if
return result;
}
/**
*
*/
STDMETHODIMP_(ULONG) COConnectionPoint::AddRef()
{ return ++m_cRef; }
/**
*
*/
STDMETHODIMP_(ULONG) COConnectionPoint::Release()
{ ULONG result = --m_cRef;
if( result<=0 )
delete this;
return result;
}
/*
* COConnectionPoint::GetConnectionInterface
*
* Purpose:
* Returns the IID of the outgoing interface supported through
* this connection point.
*
* Parameters:
* pIID IID * in which to store the IID.
*/
STDMETHODIMP COConnectionPoint::GetConnectionInterface(IID *pIID)
{ HRESULT result = E_POINTER;
if( NULL!=pIID )
{ *pIID=m_iid;
LOGGER_DEBUG<<_T("COConnectionPoint::GetConnectionInterface(")<<m_iid<<_T(")")<<endl;
result = NOERROR;
} // of if
return result;
}
/*
* COConnectionPoint::GetConnectionPointContainer
*
* Purpose:
* Returns a pointer to the IConnectionPointContainer that
* is manageing this connection point.
*
* Parameters:
* ppCPC IConnectionPointContainer ** in which to return
* the pointer after calling AddRef.
*/
STDMETHODIMP COConnectionPoint::GetConnectionPointContainer(IConnectionPointContainer **ppCPC)
{ return m_pObj->QueryInterface(IID_IConnectionPointContainer, (void **)ppCPC); }
/*
* COConnectionPoint::Advise
*
* Purpose:
* Provides this connection point with a notification sink to
* call whenever the appropriate outgoing function/event occurs.
*
* Parameters:
* pUnkSink LPUNKNOWN to the sink to notify. The connection
* point must QueryInterface on this pointer to obtain
* the proper interface to call. The connection
* point must also insure that any pointer held has
* a reference count (QueryInterface will do it).
* pdwCookie DWORD * in which to store the connection key for
* later calls to Unadvise.
*/
STDMETHODIMP COConnectionPoint::Advise(LPUNKNOWN pUnkSink, DWORD *pdwCookie)
{ IUnknown* pSink=NULL;
*pdwCookie=0;
//Check if we're already full of sink pointers
if( CCONNMAX==m_cConn )
return CONNECT_E_ADVISELIMIT;
/*
* Verify that the sink has the interface it's supposed
* to. We don't have to know what it is because we have
* m_iid to describe it. If this works, then we neatly
* have a pointer with an AddRef that we can stow away.
*/
if( FAILED(pUnkSink->QueryInterface(m_iid, (PPVOID)&pSink)) )
return CONNECT_E_CANNOTCONNECT;
/*
* We got the sink, now store it in our array. We'll look for
* the first entry that is NULL, indicating a free spot.
*/
for( UINT i=0;i<CCONNMAX;i++ )
if( m_gpUnknown[i].IsNULL() )
{ m_gpUnknown[i] = pUnkSink;
*pdwCookie = m_gpUnknown[i].GetCookie();
LOGGER_DEBUG<<_T("COConnectionPoint::Advise(dwCookie=0x")<<hex<<*pdwCookie<<_T(" i=)")<<dec<<i<<endl;
break;
} // of if
m_cConn++;
LOGGER_DEBUG<<_T("COConnectionPoint::Advise() m_cConn=")<<m_cConn<<endl;
return NOERROR;
} // of COConnectionPoint::Advise()
/*
* COConnectionPoint::Unadvise
*
* Purpose:
* Terminates the connection to the notification sink identified
* with dwCookie (that was returned from Advise). The connection
* point has to Release any held pointers for that sink.
*
* Parameters:
* dwCookie DWORD connection key from Advise.
*/
STDMETHODIMP COConnectionPoint::Unadvise(DWORD dwCookie)
{ HRESULT result = CONNECT_E_NOCONNECTION;
if( 0==dwCookie )
result = E_INVALIDARG;
else
for( UINT i=0;i<CCONNMAX;i++ )
if( dwCookie==m_gpUnknown[i].GetCookie() )
{ m_gpUnknown[i].Release();
m_cConn--;
result = NOERROR;
break;
} // of if
LOGGER_DEBUG<<_T("COConnectionPoint::Unadvise(dwCookie=")<<dwCookie<<_T(") m_cConn=")<<m_cConn<<endl;
return result;
} // of COConnectionPoint::Unadvise()
/*
* COConnectionPoint::EnumConnections
*
* Purpose:
* Creates and returns an enumerator object with the
* IEnumConnections interface that will enumerate the IUnknown
* pointers of each connected sink.
*
* this member is potentially called from a different thread
*
* Parameters:
* ppEnum LPENUMCONNECTIONS in which to store the
* IEnumConnections pointer.
*/
STDMETHODIMP COConnectionPoint::EnumConnections(LPENUMCONNECTIONS *ppEnum)
{ HRESULT result=OLE_E_NOCONNECTION;
LPCONNECTDATA pCD=NULL;
UINT i, j;
COEnumConnections* pEnum=NULL;
if( NULL==ppEnum )
result = E_POINTER;
else
{
*ppEnum=NULL;
if( 0!=m_cConn )
{ pCD=new CONNECTDATA[(UINT)m_cConn];
if( NULL==pCD )
result = E_OUTOFMEMORY;
else
{ COMPtr<IUnknown> pUnk[CCONNMAX];
::memset(pCD,0,sizeof(*pCD)*m_cConn);
for( i=0,j=0;i<CCONNMAX;i++ )
if( !m_gpUnknown[i].IsNULL() )
{ LOGGER_DEBUG<<_T("COConnectionPoint::EnumConnections(): m_gpUnknown[")<<dec<<i<<_T("]=")<<m_gpUnknown[i].GetCookie()<<endl;
pUnk[j] = m_gpUnknown[i];
pCD[j].pUnk = pUnk[j];
pCD[j].dwCookie = m_gpUnknown[i].GetCookie();
j++;
} // of if
/*
* If creation works, it makes a copy pCD, so we can
* always delete it regardless of the outcome.
*/
if( pCD!=NULL )
{ pEnum=new COEnumConnections(IID_IEnumConnections,m_cConn, pCD);
delete[] pCD;
} // of if
if( NULL!=pEnum )
{ *ppEnum = pEnum;
result = S_OK;
} // of if
else
result = E_OUTOFMEMORY;
} // of else
} // of if
} // of else
LOGGER_DEBUG<<_T("COConnectionPoint::EnumConnections()")<<endl;
return result;
} // of COConnectionPoint::EnumConnections()
} // of namespace COM
} // of namespace bvr20983
/*==========================END-OF-FILE===================================*/
| [
"dwachmann@01137330-e44e-0410-aa50-acf51430b3d2"
] | [
[
[
1,
312
]
]
] |
f030f21a8f3e3d0d9e83d8dcedfd50d783239674 | bf7d05c055c5686e4ded30f9705a28a396520d48 | /Meta/MetaFCO.h | 9c1a1752783b26c407681bf236833a4dfbd7d6ee | [] | no_license | ghemingway/mgalib | f32438d5abdbeb5739c298e401a0513f91c8d6d0 | c8cf8507a7fe73efe1da19abcdb77b52e75e2de0 | refs/heads/master | 2020-12-24T15:40:33.538434 | 2011-02-04T16:38:09 | 2011-02-04T16:38:09 | 32,185,568 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,146 | h | #ifndef __META_METAFCO_H__
#define __META_METAFCO_H__
/*** Included Header Files ***/
#include "MetaBase.h"
/*** Namespace Declaration ***/
namespace MGA {
/*** Class Predefinitions ***/
class MetaAttribute;
class MetaRole;
class MetaFolder;
// --------------------------- MetaFCO --------------------------- //
class MetaFCO : public MetaBase
{
protected:
friend class MetaBase;
MetaFCO(CoreObject &coreObject, MetaProject* const &metaProject) : ::MetaBase(coreObject, metaProject) { }
public:
virtual ~MetaFCO() { }
virtual const Result_t GetDefinedIn(MetaBase* &metaBase) const throw(); //!<
virtual const Result_t GetDefinedAttributes(std::list<MetaAttribute*> &attribList) const throw(); //!<
virtual const Result_t GetDefinedAttributeByName(const std::string &name, const bool &inScope, MetaAttribute* &attrib) const throw();
virtual const Result_t GetUsedInRoles(std::list<MetaRole*> &rolesList) const throw(); //!<
virtual const Result_t GetUsedInFolders(std::list<MetaFolder*> &folderList) const throw(); //!<
virtual const Result_t GetAttributes(std::list<MetaAttribute*> &attribList) const throw(); //!<
virtual const Result_t GetAttributeByName(const std::string &name, MetaAttribute* &attrib) const throw(); //!<
virtual const Result_t GetAttributeByRef(const Uuid &uuid, MetaAttribute* &attrib) const throw(); //!<
virtual const Result_t CreateAttribute(MetaAttribute* &metaAttribute) throw(); //!<
virtual const Result_t AddAttribute(MetaAttribute* &attrib) throw(); //!<
virtual const Result_t GetAliasingEnabled(bool &value) const throw(); //!<
virtual const Result_t SetAliasingEnabled(const bool &value) throw(); //!<
};
// --------------------------- MetaAtom --------------------------- //
class MetaAtom : public MetaFCO
{
private:
friend class MetaBase;
MetaAtom(CoreObject &coreObject, MetaProject* const &metaProject) : ::MetaFCO(coreObject, metaProject) { }
public:
virtual ~MetaAtom() { }
};
/*** End of MGA Namespace ***/
}
#endif // __META_METAFCO_H__
| [
"graham.hemingway@8932de9b-a0df-7518-fb39-9aee4a96b462"
] | [
[
[
1,
65
]
]
] |
670c4d2ed5ad07d082b59bea8a28734c316573f6 | 65da00cc6f20a83dd89098bb22f8f93c2ff7419b | /HabuGraphics/LPad/Source/Main.cpp | 3ff9b54a415035c9e9e5fd17b92ad3fd92be5ef3 | [] | no_license | skevy/CSC-350-Assignment-5 | 8b7c42257972d71e3d0cd3e9566e88a1fdcce73c | 8091a56694f4b5b8de7e278b64448d4f491aaef5 | refs/heads/master | 2021-01-23T11:49:35.653361 | 2011-04-20T02:20:06 | 2011-04-20T02:20:06 | 1,638,578 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,202 | cpp | //***************************************************************************//
// HabuGraphics Pad
// Written By Jeremy M Miller (Author of HabuGraphics Engine)
// Description: This is test platform for my OpenGL based graphics engine
// Version 0.01.103004
//
// Copyright (c) 2005-2010 Jeremy M Miller. All rights reserved.
// This source code module, and all information, data, and algorithms
// associated with it, are part of BlueHabu technology (tm).
// PROPRIETARY AND CONFIDENTIAL
//***************************************************************************//
//***************************************************************************//
#include "App.hpp"
//***************************************************************************//
//***************************************************************************//
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPreviousInstance, char* cpCmdLine, int nCmdShow)
{
App::Instance(hInstance);
if(App::Instance()->Initialize(cpCmdLine))
App::Instance()->Run();
App::Instance()->End();
return 0;
}
//***************************************************************************// | [
"[email protected]"
] | [
[
[
1,
28
]
]
] |
4d0c97591fee8446add8c6ea254a8e1cf9003ff4 | 4061b5e48204bf0ee878440a602d84c1d6623396 | /boilerplates/class.hpp | d24bdbf72c01bd9da0bdd1b1724be2cee244e520 | [] | no_license | m0tive/boil | 9863dabf39eedf34e932dea2f5c502da2c32cc6c | 115bb5cb15fed9805be56b3b395e25136ad52fc5 | refs/heads/master | 2020-04-05T09:19:57.514860 | 2010-12-01T22:50:11 | 2010-12-01T22:50:11 | 1,130,227 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 858 | hpp | // File Info {{{
//------------------------------------------------------------------------------
/// \file @[email protected]
/// \date @DATE@
/// \author @AUTHOR@
/// \brief
/// \note Copyright (C) @YEAR@ - All Rights Reserved
//}}}---------------------------------------------------------------------------
// Include catch {{{
#ifdef _MSC_VER
#pragma once
#endif
#ifndef _@NAMESPACE@_@CLASS@_hpp_
#define _@NAMESPACE@_@CLASS@_hpp_
// }}}
//#include "@NAMESPACE@/Defs.h"
//------------------------------------------------------------------------------
namespace @NAMESPACE@
{
/// \brief
class @CLASS@
{
public:
//---------------------------------------
/// \details Default constructor
@CLASS@();
//---------------------------------------
/// \details Destructor
~@CLASS@();
};
}
#endif
| [
"[email protected]",
"[email protected]"
] | [
[
[
1,
18
],
[
23,
40
]
],
[
[
19,
22
]
]
] |
119efb31aca8e2447318ac50f1c3466688d78cc3 | e59eeaca030f1fdf12cb79de0e646fafdaab2c64 | /stdafx.cpp | 4a590d3a2a524f75d872aa34bcef79f0bd5e7c43 | [] | no_license | jcccf/hepth | 5215c5056845efb06601ad20ea975587bfa8463d | 093ad00ec8e833be8b8a7501245be09489887371 | refs/heads/master | 2021-01-22T09:54:57.305488 | 2010-12-05T04:16:15 | 2010-12-05T04:16:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 292 | cpp | // stdafx.cpp : source file that includes just the standard includes
// hepth.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]"
] | [
[
[
1,
8
]
]
] |
679a78ead474d38baad794758485473d01d4287f | 7acbb1c1941bd6edae0a4217eb5d3513929324c0 | /GLibrary-CPP/sources/GPushButton.h | a4229f9b48b85e1cc726317d6117a3f7c6e1d891 | [] | no_license | hungconcon/geofreylibrary | a5bfc96e0602298b5a7b53d4afe7395a993498f1 | 3abf3e1c31a245a79fa26b4bcf2e6e86fa258e4d | refs/heads/master | 2021-01-10T10:11:51.535513 | 2009-11-30T15:29:34 | 2009-11-30T15:29:34 | 46,771,895 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 364 | h |
#ifndef __GPUSHBUTTON_H__
# define __GPUSHBUTTON_H__
#include "GWidget.h"
#include "GExport.h"
class GEXPORTED GPushButton : public GWidget
{
public:
GPushButton(GWidget *Parent);
GPushButton(const GString &Text, GWidget *Parent);
~GPushButton(void);
void SetText(const GString &Text);
private:
GWidget *_parent;
};
#endif | [
"mvoirgard@34e8d5ee-a372-11de-889f-a79cef5dd62c",
"[email protected]"
] | [
[
[
1,
5
],
[
7,
7
],
[
9,
10
],
[
13,
18
],
[
20,
22
]
],
[
[
6,
6
],
[
8,
8
],
[
11,
12
],
[
19,
19
]
]
] |
4e46afceffeaea922af56d5cafb74e916ce3ef90 | 9756190964e5121271a44aba29a5649b6f95f506 | /SimpleParam/Param/src/MainWindow/CrossParamControl.cpp | fb464e02e985ef18646144af7bff98c9c3dd0ebd | [] | no_license | feengg/Parameterization | 40f71bedd1adc7d2ccbbc45cc0c3bf0e1d0b1103 | f8d2f26ff83d6f53ac8a6abb4c38d9b59db1d507 | refs/heads/master | 2020-03-23T05:18:25.675256 | 2011-01-21T15:19:08 | 2011-01-21T15:19:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,946 | cpp | #include "CrossParamControl.h"
#include "../Param/CrossParameter.h"
#include "../Param/Parameter.h"
#include "../Param/ParamDrawer.h"
#include "../ModelMesh/MeshModel.h"
#include <fstream>
CrossParamControl::CrossParamControl(QGLViewer* _gl_viewer_1, QGLViewer* _gl_viewer_2, QWidget* parent)
: QWidget(parent)
{
m_gl_viewer_1 = _gl_viewer_1;
m_gl_viewer_2 = _gl_viewer_2;
m_surface_1_group = CreateSurface1Group(this);
m_surface_2_group = CreateSurface2Group(this);
m_cross_param_group = CreateCrossParamGroup(this);
m_texture_setting_group = CreateTextureGroup(this);
m_visualization_group = CreateVisualizationGroup(this);
m_corresponding_group = CreateCorrespondingGroup(this);
CreateMainLayout();
}
QGroupBox* CrossParamControl::CreateSurface1Group(QWidget* parent /* = 0 */)
{
QGroupBox* surface_1_group = new QGroupBox(parent);
surface_1_group->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed);
surface_1_group->setTitle(tr("Surface 1 Setting"));
/// child widgets
QPushButton* load_surface_1_mesh = new QPushButton(surface_1_group);
load_surface_1_mesh->setText(tr("Load Surface 1 Mesh"));
QPushButton* load_surface_1_patch = new QPushButton(surface_1_group);
load_surface_1_patch->setText(tr("Load Surface 1 Patch"));
// QPushButton* optimize_ambiguity_patch = new QPushButton(surface_1_group);
// optimize_ambiguity_patch->setText(tr("Optimize Ambiguity Patch"));
QPushButton* parameter_1 = new QPushButton(surface_1_group);
parameter_1->setText(tr("Parameter"));
/// layout
QVBoxLayout* surface_1_layout = new QVBoxLayout(surface_1_group);
surface_1_layout->addWidget(load_surface_1_mesh);
surface_1_layout->addWidget(load_surface_1_patch);
// surface_1_layout->addWidget(optimize_ambiguity_patch);
surface_1_layout->addWidget(parameter_1);
/// connections
connect(load_surface_1_mesh, SIGNAL(clicked()), m_gl_viewer_1, SLOT(loadMeshModel()));
connect(load_surface_1_patch, SIGNAL(clicked()), m_gl_viewer_1, SLOT(loadQuadFile()));
// connect(optimize_ambiguity_patch, SIGNAL(clicked()), m_gl_viewer_1, SLOT(OptimizeAmbiguityPatch()));
connect(parameter_1, SIGNAL(clicked()), m_gl_viewer_1, SLOT(SolveParameter()));
return surface_1_group;
}
QGroupBox* CrossParamControl::CreateSurface2Group(QWidget* parent /* = 0 */)
{
QGroupBox* surface_2_group = new QGroupBox(parent);
surface_2_group->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed);
surface_2_group->setTitle(tr("Surface 2 Setting"));
/// child widgets
QPushButton* load_surface_2_mesh = new QPushButton(surface_2_group);
load_surface_2_mesh->setText(tr("Load Surface 2 Mesh"));
QPushButton* load_surface_2_patch = new QPushButton(surface_2_group);
load_surface_2_patch->setText(tr("Load Surface 2 Patch"));
QPushButton* parameter_2 = new QPushButton(surface_2_group);
parameter_2->setText(tr("Parameter"));
QPushButton* save_face_tex = new QPushButton(surface_2_group);
save_face_tex->setText(tr("Save face tex coord"));
QPushButton* load_face_tex = new QPushButton(surface_2_group);
load_face_tex->setText(tr("Load face tex coord"));
/// layout
QVBoxLayout* surface_2_layout = new QVBoxLayout(surface_2_group);
surface_2_layout->setSpacing(10);
surface_2_layout->addWidget(load_surface_2_mesh);
surface_2_layout->addWidget(load_surface_2_patch);
surface_2_layout->addWidget(parameter_2);
surface_2_layout->addWidget(save_face_tex);
surface_2_layout->addWidget(load_face_tex);
/// connections
connect(load_surface_2_mesh, SIGNAL(clicked()), m_gl_viewer_2, SLOT(loadMeshModel()));
connect(load_surface_2_patch, SIGNAL(clicked()), m_gl_viewer_2, SLOT(loadQuadFile()));
connect(parameter_2, SIGNAL(clicked()), m_gl_viewer_2, SLOT(SolveParameter()));
connect(save_face_tex, SIGNAL(clicked()), m_gl_viewer_2, SLOT(SaveFaceTexCoord()));
connect(load_face_tex, SIGNAL(clicked()), m_gl_viewer_2, SLOT(LoadFaceTexCoord()));
return surface_2_group;
}
QGroupBox* CrossParamControl::CreateCrossParamGroup(QWidget* parent /* = 0 */)
{
QGroupBox* cross_param_group = new QGroupBox(parent);
cross_param_group->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed);
cross_param_group->setTitle(tr("Cross Parameterization"));
/// child widgets
QPushButton* compute_cross_parameter = new QPushButton(cross_param_group);
compute_cross_parameter->setText(tr("Compute Cross Parameter"));
QPushButton* optimizer = new QPushButton(cross_param_group);
optimizer->setText(tr("Cross Parameter Optimize"));
/// layout
QVBoxLayout* cross_parameter_layout = new QVBoxLayout(cross_param_group);
cross_parameter_layout->addWidget(compute_cross_parameter);
cross_parameter_layout->addWidget(optimizer);
/// connections
connect(compute_cross_parameter, SIGNAL(clicked()), this, SLOT(ComputeCrossParam()));
connect(optimizer, SIGNAL(clicked()), this, SLOT(OptimizeCrossParam()));
return cross_param_group;
}
QGroupBox* CrossParamControl::CreateTextureGroup(QWidget* parent /* = 0 */)
{
QGroupBox* texture_group = new QGroupBox(parent);
texture_group->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed);
texture_group->setTitle(tr("Texture"));
/// child widgets
QRadioButton* square_texture = new QRadioButton(texture_group);
QRadioButton* line_texture = new QRadioButton(texture_group);
QRadioButton* boundary_texture = new QRadioButton(texture_group);
square_texture->setText(tr("Square"));
line_texture->setText(tr("Line"));
boundary_texture->setText(tr("Boundary"));
square_texture->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
line_texture->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
boundary_texture->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
QVBoxLayout* texture_layout = new QVBoxLayout(texture_group);
texture_layout->addWidget(square_texture);
texture_layout->addWidget(line_texture);
texture_layout->addWidget(boundary_texture);
/// connections
connect(square_texture, SIGNAL(clicked()), m_gl_viewer_1, SLOT(CreateSquareTexture()));
connect(square_texture, SIGNAL(clicked()), m_gl_viewer_2, SLOT(CreateSquareTexture()));
connect(line_texture, SIGNAL(clicked()), m_gl_viewer_1, SLOT(CreateLineTexture()));
connect(line_texture, SIGNAL(clicked()), m_gl_viewer_2, SLOT(CreateLineTexture()));
connect(boundary_texture, SIGNAL(clicked()), m_gl_viewer_1, SLOT(CreateBoundaryTexture()));
connect(boundary_texture, SIGNAL(clicked()), m_gl_viewer_2, SLOT(CreateBoundaryTexture()));
square_texture->setChecked(true);
return texture_group;
}
QGroupBox* CrossParamControl::CreateVisualizationGroup(QWidget* parent /* = 0 */)
{
QGroupBox* visual_group = new QGroupBox(parent);
visual_group->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed);
visual_group->setTitle(tr("Visulzation"));
/// child widgets
// QRadioButton* patch_layout = new QRadioButton(visual_group);
QCheckBox* patch_conner = new QCheckBox(visual_group);
QCheckBox* patch_edge = new QCheckBox(visual_group);
QCheckBox* patch_face = new QCheckBox(visual_group);
QCheckBox* outrange_vert = new QCheckBox(visual_group);
QCheckBox* select_patch = new QCheckBox(visual_group);
QCheckBox* flipped_triangle = new QCheckBox(visual_group);
QCheckBox* corresponding = new QCheckBox(visual_group);
QCheckBox* uncorresponding_vert = new QCheckBox(visual_group);
patch_conner->setText(tr("Patch Conner"));
patch_edge ->setText(tr("Patch Edge"));
patch_face ->setText(tr("Patch Face"));
outrange_vert->setText(tr("Out Range Vertex"));
select_patch->setText(tr("Selected Patch"));
flipped_triangle ->setText("Flipped Triangle");
corresponding->setText("Corresponding");
uncorresponding_vert->setText("UnCorresponding Vert");
patch_conner->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
patch_edge->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
patch_face->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
outrange_vert->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
select_patch->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
flipped_triangle->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
corresponding->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
uncorresponding_vert->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
QVBoxLayout* visual_layout = new QVBoxLayout(visual_group);
visual_layout->addWidget(patch_conner);
visual_layout->addWidget(patch_edge);
visual_layout->addWidget(patch_face);
visual_layout->addWidget(outrange_vert);
visual_layout->addWidget(select_patch);
visual_layout->addWidget(flipped_triangle);
visual_layout->addWidget(corresponding);
visual_layout->addWidget(uncorresponding_vert);
/// connects
connect(patch_conner, SIGNAL(toggled(bool)), this, SLOT(SetPatchConnerDisplay(bool)));
connect(patch_edge, SIGNAL(toggled(bool)), this, SLOT(SetPatchEdgeDisplay(bool)));
connect(patch_face, SIGNAL(toggled(bool)), this, SLOT(SetPatchFaceDisplay(bool)));
connect(outrange_vert, SIGNAL(toggled(bool)), this, SLOT(SetOutRangeVertDisplay(bool)));
connect(select_patch, SIGNAL(toggled(bool)), this, SLOT(SetSelectedPatchDisplay(bool)));
connect(flipped_triangle, SIGNAL(toggled(bool)), this, SLOT(SetFlippedTriangleDisplay(bool)));
connect(corresponding, SIGNAL(toggled(bool)), this, SLOT(SetCorrespondingDisplay(bool)));
connect(uncorresponding_vert, SIGNAL(toggled(bool)), this, SLOT(SetUnCorrespondingDisplay(bool)));
return visual_group;
}
QGroupBox* CrossParamControl::CreateOptimizerGroup(QWidget* parent /* = 0 */)
{
QGroupBox* optimizer_group = new QGroupBox(parent);
optimizer_group->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed);
optimizer_group->setTitle("Cross Parameter Optimizer");
QPushButton* optimizer = new QPushButton(optimizer_group);
return optimizer_group;
}
QGroupBox* CrossParamControl::CreateCorrespondingGroup(QWidget* parent /* = 0 */)
{
QGroupBox* corresponding_group = new QGroupBox(parent);
corresponding_group->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed);
corresponding_group->setTitle("Corresponding");
QPushButton* load_corresponding = new QPushButton(tr("Load Corresponding"));
QPushButton* corresponding = new QPushButton(tr("Corresponding"));
QPushButton* select_patch = new QPushButton(tr("Select Patch"));
connect(load_corresponding, SIGNAL(clicked()), this, SLOT(LoadCorrespondingFile()));
connect(select_patch, SIGNAL(clicked()), m_gl_viewer_1, SLOT(SetParamDrawerSelectPatchMode()));
connect(corresponding, SIGNAL(clicked()), m_gl_viewer_1, SLOT(SetParamDrawerSelectVertMode()));
connect(corresponding, SIGNAL(clicked()), m_gl_viewer_2, SLOT(SetParamDrawerCorrespondMode()));
/// layout
QVBoxLayout* corresponding_layout = new QVBoxLayout(corresponding_group);
corresponding_layout->addWidget(load_corresponding);
corresponding_layout->addWidget(corresponding);
corresponding_layout->addWidget(select_patch);
return corresponding_group;
}
void CrossParamControl::LoadCorrespondingFile()
{
std::string prev_file_path;
ifstream fin ("open_file_path.txt");
if(!fin.fail()){
fin >> prev_file_path;
}
fin.close();
QString fileName = QFileDialog::getOpenFileName(
this,
tr("Open Corresponding File"),
tr(prev_file_path.c_str()),
tr("Corr file(*.corr);;"
"All files(*)"));
std::string f = std::string((const char *) fileName.toLocal8Bit());
if(f.size() != 0)
{
p_cross_parameter = p_cross_parameter = boost::shared_ptr<PARAM::CrossParameter> (new
PARAM::CrossParameter(*(m_gl_viewer_1->p_param), *(m_gl_viewer_2->p_param)));
p_cross_parameter->LoadCorrespondingFile(f);
std::string file_path, file_title, file_ext;
Utility util;
util.ResolveFileName(f, file_path, file_title, file_ext);
ofstream fout("open_file_path.txt");
if(!fout.fail()){
fout << file_path << std::endl;
}
fout.close();
}
}
void CrossParamControl::FindCorrespondingOnA()
{
int vid = m_gl_viewer_2->p_param_drawer->GetSelectedVertID();
if(vid == -1) return;
if(m_gl_viewer_2->p_param == NULL) return;
if(m_gl_viewer_1->p_param_drawer == NULL) return;
if(p_cross_parameter == NULL) return;
int chart_id = m_gl_viewer_2->p_param->GetVertexChartID(vid);
PARAM::ParamCoord param_coord = m_gl_viewer_2->p_param->GetVertexParamCoord(vid);
PARAM::ChartParamCoord chart_param_coord(param_coord, chart_id);
PARAM::SurfaceCoord surface_coord;
p_cross_parameter->GetSurfaceCoordOnA(chart_param_coord, surface_coord);
m_gl_viewer_1->p_param_drawer->SetSelectedVertCoord(surface_coord);
m_gl_viewer_1->updateGL();
}
void CrossParamControl::FindCorrespondingOnB()
{
// int vid = m_gl_viewer_1->p_param_drawer->GetSelectedVertID();
PARAM::SurfaceCoord surf_coord = m_gl_viewer_1->p_param_drawer->GetSelectedSurfaceCorod();
if(surf_coord.face_index == -1) return;
if(m_gl_viewer_1->p_param == NULL) return;
if(m_gl_viewer_2->p_param_drawer == NULL) return;
if(p_cross_parameter == NULL) return;
int fid = surf_coord.face_index;
PARAM::Barycentrc baryc = surf_coord.barycentric;
const PolyIndexArray& fIndex1 = m_gl_viewer_1->p_mesh->m_Kernel.GetFaceInfo().GetIndex();
const PolyIndexArray& fIndex2 = m_gl_viewer_2->p_mesh->m_Kernel.GetFaceInfo().GetIndex();
const CoordArray& vCoord2 = m_gl_viewer_2->p_mesh->m_Kernel.GetVertexInfo().GetCoord();
const IndexArray& face1 = fIndex1[fid];
std::vector<PARAM::SurfaceCoord> face_vert_sf_vec(3);
std::vector<Coord> face_vert_coord_vec(3);
for(int i=0; i<3; ++i)
{
int vid = face1[i];
PARAM::SurfaceCoord surf_coord = p_cross_parameter->m_corresponding_AB[vid];
int _fid = surf_coord.face_index;
if(_fid == -1) { std::cerr <<" Fid == -1" << std::endl; return;}
PARAM::Barycentrc _baryc = surf_coord.barycentric;
const IndexArray& face2 = fIndex2[_fid];
face_vert_coord_vec[i] = vCoord2[face2[0]]*_baryc[0] + vCoord2[face2[1]]*_baryc[1] + vCoord2[face2[2]]*_baryc[2];
// int chart_id = m_gl_viewer_1->p_param->GetVertexChartID(vid);
// PARAM::ParamCoord param_coord = m_gl_viewer_1->p_param->GetVertexParamCoord(vid);
//std::cout << "Surface A --- chart id : " << chart_id << ", param_coord " << param_coord.s_coord <<" " << param_coord.t_coord << std::endl;
// PARAM::ChartParamCoord chart_param_coord(param_coord, chart_id);
face_vert_sf_vec[i]= p_cross_parameter->m_corresponding_AB[vid];
}
Coord corr_coord = face_vert_coord_vec[0]*baryc[0] + face_vert_coord_vec[1]*baryc[1] + face_vert_coord_vec[2]*baryc[2];
// p_cross_parameter->GetSurfaceCoordOnB(chart_param_coord, surface_coord);
// m_gl_viewer_2->p_param_drawer->SetSelectedVertCoord(surface_coord);
m_gl_viewer_2->p_param_drawer->SetSelectedVertCoord(corr_coord);
int vid_2 = m_gl_viewer_2->p_param_drawer->GetSelectedVertID();
// std::cout << "Surface B --- chart id : " << chart_id << ", param_coord " << param_coord.s_coord <<" "<<param_coord.t_coord << std::endl;
m_gl_viewer_2->updateGL();
}
void CrossParamControl::ComputeCrossParam()
{
if(m_gl_viewer_1 == 0 || m_gl_viewer_2 == 0) return;
if(m_gl_viewer_1->p_param == 0 || m_gl_viewer_2->p_param == 0) return;
p_cross_parameter->FindCorrespondingAB();
// p_cross_parameter->FindCorrespondingBA();
// p_cross_parameter->VertTextureTransferBA();
//
// const std::vector<TexCoord>& vert_tex_array_B = p_cross_parameter->GetTransferedVertTexArrayB();
//
// boost::shared_ptr<MeshModel> p_mesh_B = m_gl_viewer_2->p_mesh;
// p_mesh_B->m_Kernel.GetVertexInfo().GetTexCoord() = vert_tex_array_B;
// p_mesh_B->m_Kernel.GetFaceInfo().GetTexIndex() = (p_mesh_B->m_Kernel.GetFaceInfo().GetIndex());
// p_cross_parameter->FaceTextureTransferBA();
//
// const std::vector<TexCoordArray>& face_tex_array_B = p_cross_parameter->GetTransferedFaceTexArrayB();
//
// boost::shared_ptr<MeshModel> p_mesh_B = m_gl_viewer_2->p_mesh;
// p_mesh_B->m_Kernel.GetFaceInfo().GetTexCoord() = face_tex_array_B;
m_gl_viewer_2->p_param_drawer->SetUnCorrespondingVertArray(p_cross_parameter->GetUnCorrespondingVertArrayOnB());
}
void CrossParamControl::OptimizeCrossParam()
{
// if(p_cross_param == NULL) return;
// boost::shared_ptr<PARAM::CrossParamHarmonicOptimizer> p_cp_optimizer(new
// PARAM::CrossParamHarmonicOptimizer(*p_cross_param.get()));
//
// p_cp_optimizer->Optimize();
}
void CrossParamControl::SetPatchConnerDisplay(bool toggled)
{
if(m_gl_viewer_1 && m_gl_viewer_1->p_param_drawer) {
m_gl_viewer_1->p_param_drawer->SetDrawPatchConner(toggled);
m_gl_viewer_1->updateGL();
}
if(m_gl_viewer_2 && m_gl_viewer_2->p_param_drawer) {
m_gl_viewer_2->p_param_drawer->SetDrawPatchConner(toggled);
m_gl_viewer_2->updateGL();
}
}
void CrossParamControl::SetPatchEdgeDisplay(bool toggled)
{
if(m_gl_viewer_1 && m_gl_viewer_1->p_param_drawer){
m_gl_viewer_1->p_param_drawer->SetDrawPatchEdge(toggled);
m_gl_viewer_1->updateGL();
}
if(m_gl_viewer_2 && m_gl_viewer_2->p_param_drawer){
m_gl_viewer_2->p_param_drawer->SetDrawPatchEdge(toggled);
m_gl_viewer_2->updateGL();
}
}
void CrossParamControl::SetPatchFaceDisplay(bool toggled)
{
if(m_gl_viewer_1 && m_gl_viewer_1->p_param_drawer){
m_gl_viewer_1->p_param_drawer->SetDrawPatchFace(toggled);
m_gl_viewer_1->updateGL();
}
if(m_gl_viewer_2 && m_gl_viewer_2->p_param_drawer){
m_gl_viewer_2->p_param_drawer->SetDrawPatchFace(toggled);
m_gl_viewer_2->updateGL();
}
}
void CrossParamControl::SetOutRangeVertDisplay(bool toggled)
{
if(m_gl_viewer_1 && m_gl_viewer_1->p_param_drawer){
m_gl_viewer_1->p_param_drawer->SetDrawOutRangeVertices(toggled);
m_gl_viewer_1->updateGL();
}
if(m_gl_viewer_2 && m_gl_viewer_2->p_param_drawer){
m_gl_viewer_2->p_param_drawer->SetDrawOutRangeVertices(toggled);
m_gl_viewer_2->updateGL();
}
}
void CrossParamControl::SetSelectedPatchDisplay(bool toggled)
{
if(m_gl_viewer_1 && m_gl_viewer_1->p_param_drawer){
m_gl_viewer_1->p_param_drawer->SetDrawSelectedPatch(toggled);
m_gl_viewer_1->updateGL();
}
}
void CrossParamControl::SetFlippedTriangleDisplay(bool toggled)
{
if(m_gl_viewer_1 && m_gl_viewer_1->p_param_drawer){
m_gl_viewer_1->p_param_drawer->SetDrawFlipFace(toggled);
m_gl_viewer_1->updateGL();
}
}
void CrossParamControl::SetCorrespondingDisplay(bool toggled)
{
if(m_gl_viewer_1 && m_gl_viewer_1->p_param_drawer){
m_gl_viewer_1->p_param_drawer->SetDrawSelectedVertex(toggled);
m_gl_viewer_1->updateGL();
}
if(m_gl_viewer_2 && m_gl_viewer_2->p_param_drawer){
m_gl_viewer_2->p_param_drawer->SetDrawSelectedVertex(toggled);
m_gl_viewer_2->updateGL();
}
}
void CrossParamControl::SetUnCorrespondingDisplay(bool toggled)
{
if(m_gl_viewer_1 && m_gl_viewer_1->p_param_drawer){
m_gl_viewer_1->p_param_drawer->SetDrawUnCorresponding(toggled);
m_gl_viewer_1->updateGL();
}
if(m_gl_viewer_2 && m_gl_viewer_2->p_param_drawer){
m_gl_viewer_2->p_param_drawer->SetDrawUnCorresponding(toggled);
m_gl_viewer_2->updateGL();
}
}
void CrossParamControl::CreateMainLayout()
{
QGroupBox* main_group = new QGroupBox(this);
main_group->setFixedWidth(200);
main_group->setTitle(tr("Cross Parameterization"));
QVBoxLayout* main_group_layout = new QVBoxLayout(main_group);
main_group_layout->setMargin(3);
main_group_layout->setSpacing(30);
main_group_layout->addWidget(m_surface_1_group);
main_group_layout->addWidget(m_surface_2_group);
main_group_layout->addWidget(m_corresponding_group);
main_group_layout->addWidget(m_cross_param_group);
main_group_layout->addWidget(m_texture_setting_group);
main_group_layout->addWidget(m_visualization_group);
main_group_layout->addStretch(1);
}
| [
"[email protected]"
] | [
[
[
1,
491
]
]
] |
c27b9a6d6b9fdea59879e5ea73b83b7a7f4a6b4a | 5e61787e7adba6ed1c2b5e40d38098ebdf9bdee8 | /sans/models/c_models/models.hh | 54f7bc56f52a434ae3eef87ec23be5d2a2354f70 | [] | no_license | mcvine/sansmodels | 4dcba43d18c930488b0e69e8afb04139e89e7b21 | 618928810ee7ae58ec35bbb839eba2a0117c4611 | refs/heads/master | 2021-01-22T13:12:22.721492 | 2011-09-30T14:01:06 | 2011-09-30T14:01:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 26,426 | hh | /**
This software was developed by the University of Tennessee as part of the
Distributed Data Analysis of Neutron Scattering Experiments (DANSE)
project funded by the US National Science Foundation.
If you use DANSE applications to do scientific research that leads to
publication, we ask that you acknowledge the use of the software with the
following sentence:
"This work benefited from DANSE software developed under NSF award DMR-0520547."
copyright 2008, University of Tennessee
*/
#ifndef MODEL_CLASS_H
#define MODEL_CLASS_H
#include <vector>
#include "parameters.hh"
extern "C" {
#include "cylinder.h"
#include "parallelepiped.h"
#include "lamellarPS.h"
#include "lamellar.h"
#include "fuzzysphere.h"
}
using namespace std;
class CylinderModel{
public:
// Model parameters
Parameter radius;
Parameter scale;
Parameter length;
Parameter sldCyl;
Parameter sldSolv;
Parameter background;
Parameter cyl_theta;
Parameter cyl_phi;
// Constructor
CylinderModel();
// Operators to get I(Q)
double operator()(double q);
double operator()(double qx, double qy);
double calculate_ER();
double evaluate_rphi(double q, double phi);
};
class BarBellModel{
public:
// Model parameters
Parameter scale;
Parameter rad_bar;
Parameter len_bar;
Parameter rad_bell;
Parameter sld_barbell;
Parameter sld_solv;
Parameter background;
Parameter theta;
Parameter phi;
// Constructor
BarBellModel();
// Operators to get I(Q)
double operator()(double q);
double operator()(double qx, double qy);
double calculate_ER();
double evaluate_rphi(double q, double phi);
};
class CappedCylinderModel{
public:
// Model parameters
Parameter scale;
Parameter rad_cyl;
Parameter len_cyl;
Parameter rad_cap;
Parameter sld_capcyl;
Parameter sld_solv;
Parameter background;
Parameter theta;
Parameter phi;
// Constructor
CappedCylinderModel();
// Operators to get I(Q)
double operator()(double q);
double operator()(double qx, double qy);
double calculate_ER();
double evaluate_rphi(double q, double phi);
};
class ParallelepipedModel{
public:
// Model parameters
Parameter scale;
Parameter short_a;
Parameter short_b;
Parameter long_c;
Parameter sldPipe;
Parameter sldSolv;
Parameter background;
Parameter parallel_theta;
Parameter parallel_phi;
Parameter parallel_psi;
// Constructor
ParallelepipedModel();
// Operators to get I(Q)
double operator()(double q);
double operator()(double qx, double qy);
double calculate_ER();
double evaluate_rphi(double q, double phi);
};
class CSParallelepipedModel{
public:
// Model parameters
Parameter scale;
Parameter shortA;
Parameter midB;
Parameter longC;
Parameter rimA;
Parameter rimB;
Parameter rimC;
Parameter sld_rimA;
Parameter sld_rimB;
Parameter sld_rimC;
Parameter sld_pcore;
Parameter sld_solv;
Parameter background;
Parameter parallel_theta;
Parameter parallel_phi;
Parameter parallel_psi;
// Constructor
CSParallelepipedModel();
// Operators to get I(Q)
double operator()(double q);
double operator()(double qx, double qy);
double calculate_ER();
double evaluate_rphi(double q, double phi);
};
class OnionModel{
public:
// Model parameters
Parameter n_shells;
Parameter scale;
Parameter rad_core0;
Parameter sld_core0;
Parameter sld_solv;
Parameter background;
Parameter sld_out_shell1;
Parameter sld_out_shell2;
Parameter sld_out_shell3;
Parameter sld_out_shell4;
Parameter sld_out_shell5;
Parameter sld_out_shell6;
Parameter sld_out_shell7;
Parameter sld_out_shell8;
Parameter sld_out_shell9;
Parameter sld_out_shell10;
Parameter sld_in_shell1;
Parameter sld_in_shell2;
Parameter sld_in_shell3;
Parameter sld_in_shell4;
Parameter sld_in_shell5;
Parameter sld_in_shell6;
Parameter sld_in_shell7;
Parameter sld_in_shell8;
Parameter sld_in_shell9;
Parameter sld_in_shell10;
Parameter A_shell1;
Parameter A_shell2;
Parameter A_shell3;
Parameter A_shell4;
Parameter A_shell5;
Parameter A_shell6;
Parameter A_shell7;
Parameter A_shell8;
Parameter A_shell9;
Parameter A_shell10;
Parameter thick_shell1;
Parameter thick_shell2;
Parameter thick_shell3;
Parameter thick_shell4;
Parameter thick_shell5;
Parameter thick_shell6;
Parameter thick_shell7;
Parameter thick_shell8;
Parameter thick_shell9;
Parameter thick_shell10;
Parameter func_shell1;
Parameter func_shell2;
Parameter func_shell3;
Parameter func_shell4;
Parameter func_shell5;
Parameter func_shell6;
Parameter func_shell7;
Parameter func_shell8;
Parameter func_shell9;
Parameter func_shell10;
// Constructor
OnionModel();
// Operators to get I(Q)
double operator()(double q);
double operator()(double qx, double qy);
double calculate_ER();
double evaluate_rphi(double q, double phi);
};
class RPAModel{
public:
// Model parameters
Parameter lcase_n;
Parameter ba;
Parameter bb;
Parameter bc;
Parameter bd;
Parameter Kab;
Parameter Kac;
Parameter Kad;
Parameter Kbc;
Parameter Kbd;
Parameter Kcd;
Parameter scale;
Parameter background;
Parameter Na;
Parameter Phia;
Parameter va;
Parameter La;
Parameter Nb;
Parameter Phib;
Parameter vb;
Parameter Lb;
Parameter Nc;
Parameter Phic;
Parameter vc;
Parameter Lc;
Parameter Nd;
Parameter Phid;
Parameter vd;
Parameter Ld;
// Constructor
RPAModel();
// Operators to get I(Q)
double operator()(double q);
double operator()(double qx, double qy);
double calculate_ER();
double evaluate_rphi(double q, double phi);
};
class ReflModel{
public:
// Model parameters
Parameter n_layers;
Parameter scale;
Parameter thick_inter0;
Parameter func_inter0;
Parameter sld_bottom0;
Parameter sld_medium;
Parameter background;
Parameter sld_flat1;
Parameter sld_flat2;
Parameter sld_flat3;
Parameter sld_flat4;
Parameter sld_flat5;
Parameter sld_flat6;
Parameter sld_flat7;
Parameter sld_flat8;
Parameter sld_flat9;
Parameter sld_flat10;
Parameter thick_inter1;
Parameter thick_inter2;
Parameter thick_inter3;
Parameter thick_inter4;
Parameter thick_inter5;
Parameter thick_inter6;
Parameter thick_inter7;
Parameter thick_inter8;
Parameter thick_inter9;
Parameter thick_inter10;
Parameter thick_flat1;
Parameter thick_flat2;
Parameter thick_flat3;
Parameter thick_flat4;
Parameter thick_flat5;
Parameter thick_flat6;
Parameter thick_flat7;
Parameter thick_flat8;
Parameter thick_flat9;
Parameter thick_flat10;
Parameter func_inter1;
Parameter func_inter2;
Parameter func_inter3;
Parameter func_inter4;
Parameter func_inter5;
Parameter func_inter6;
Parameter func_inter7;
Parameter func_inter8;
Parameter func_inter9;
Parameter func_inter10;
// Constructor
ReflModel();
// Operators to get I(Q)
double operator()(double q);
double operator()(double qx, double qy);
double calculate_ER();
double evaluate_rphi(double q, double phi);
};
class ReflAdvModel{
public:
// Model parameters
Parameter n_layers;
Parameter scale;
Parameter thick_inter0;
Parameter func_inter0;
Parameter sld_bottom0;
Parameter sld_medium;
Parameter background;
Parameter sld_flat1;
Parameter sld_flat2;
Parameter sld_flat3;
Parameter sld_flat4;
Parameter sld_flat5;
Parameter sld_flat6;
Parameter sld_flat7;
Parameter sld_flat8;
Parameter sld_flat9;
Parameter sld_flat10;
Parameter thick_inter1;
Parameter thick_inter2;
Parameter thick_inter3;
Parameter thick_inter4;
Parameter thick_inter5;
Parameter thick_inter6;
Parameter thick_inter7;
Parameter thick_inter8;
Parameter thick_inter9;
Parameter thick_inter10;
Parameter thick_flat1;
Parameter thick_flat2;
Parameter thick_flat3;
Parameter thick_flat4;
Parameter thick_flat5;
Parameter thick_flat6;
Parameter thick_flat7;
Parameter thick_flat8;
Parameter thick_flat9;
Parameter thick_flat10;
Parameter func_inter1;
Parameter func_inter2;
Parameter func_inter3;
Parameter func_inter4;
Parameter func_inter5;
Parameter func_inter6;
Parameter func_inter7;
Parameter func_inter8;
Parameter func_inter9;
Parameter func_inter10;
Parameter sldIM_flat1;
Parameter sldIM_flat2;
Parameter sldIM_flat3;
Parameter sldIM_flat4;
Parameter sldIM_flat5;
Parameter sldIM_flat6;
Parameter sldIM_flat7;
Parameter sldIM_flat8;
Parameter sldIM_flat9;
Parameter sldIM_flat10;
Parameter nu_inter1;
Parameter nu_inter2;
Parameter nu_inter3;
Parameter nu_inter4;
Parameter nu_inter5;
Parameter nu_inter6;
Parameter nu_inter7;
Parameter nu_inter8;
Parameter nu_inter9;
Parameter nu_inter10;
Parameter sldIM_sub0;
Parameter sldIM_medium;
Parameter npts_inter;
Parameter nu_inter0;
// Constructor
ReflAdvModel();
// Operators to get I(Q)
double operator()(double q);
double operator()(double qx, double qy);
double calculate_ER();
double evaluate_rphi(double q, double phi);
};
class SphereModel{
public:
// Model parameters
Parameter radius;
Parameter scale;
Parameter sldSph;
Parameter sldSolv;
Parameter background;
// Constructor
SphereModel();
// Operators to get I(Q)
double operator()(double q);
double operator()(double qx, double qy);
double calculate_ER();
double evaluate_rphi(double q, double phi);
};
class SphereSLDModel{
public:
// Model parameters
Parameter n_shells;
Parameter scale;
Parameter thick_inter0;
Parameter func_inter0;
Parameter sld_core0;
Parameter sld_solv;
Parameter background;
Parameter sld_flat1;
Parameter sld_flat2;
Parameter sld_flat3;
Parameter sld_flat4;
Parameter sld_flat5;
Parameter sld_flat6;
Parameter sld_flat7;
Parameter sld_flat8;
Parameter sld_flat9;
Parameter sld_flat10;
Parameter thick_inter1;
Parameter thick_inter2;
Parameter thick_inter3;
Parameter thick_inter4;
Parameter thick_inter5;
Parameter thick_inter6;
Parameter thick_inter7;
Parameter thick_inter8;
Parameter thick_inter9;
Parameter thick_inter10;
Parameter thick_flat1;
Parameter thick_flat2;
Parameter thick_flat3;
Parameter thick_flat4;
Parameter thick_flat5;
Parameter thick_flat6;
Parameter thick_flat7;
Parameter thick_flat8;
Parameter thick_flat9;
Parameter thick_flat10;
Parameter func_inter1;
Parameter func_inter2;
Parameter func_inter3;
Parameter func_inter4;
Parameter func_inter5;
Parameter func_inter6;
Parameter func_inter7;
Parameter func_inter8;
Parameter func_inter9;
Parameter func_inter10;
Parameter nu_inter1;
Parameter nu_inter2;
Parameter nu_inter3;
Parameter nu_inter4;
Parameter nu_inter5;
Parameter nu_inter6;
Parameter nu_inter7;
Parameter nu_inter8;
Parameter nu_inter9;
Parameter nu_inter10;
Parameter npts_inter;
Parameter nu_inter0;
Parameter rad_core0;
// Constructor
SphereSLDModel();
// Operators to get I(Q)
double operator()(double q);
double operator()(double qx, double qy);
double calculate_ER();
double evaluate_rphi(double q, double phi);
};
class SCCrystalModel{
public:
// Model parameters
Parameter scale;
Parameter dnn;
Parameter d_factor;
Parameter radius;
Parameter sldSph;
Parameter sldSolv;
Parameter background;
Parameter theta;
Parameter phi;
Parameter psi;
// Constructor
SCCrystalModel();
// Operators to get I(Q)
double operator()(double q);
double operator()(double qx, double qy);
double calculate_ER();
double evaluate_rphi(double q, double phi);
};
class PearlNecklaceModel{
public:
// Model parameters
Parameter scale;
Parameter radius;
Parameter edge_separation;
Parameter thick_string;
Parameter num_pearls;
Parameter sld_pearl;
Parameter sld_string;
Parameter sld_solv;
Parameter background;
// Constructor
PearlNecklaceModel();
// Operators to get I(Q)
double operator()(double q);
double operator()(double qx, double qy);
double calculate_ER();
double evaluate_rphi(double q, double phi);
};
class FCCrystalModel{
public:
// Model parameters
Parameter scale;
Parameter dnn;
Parameter d_factor;
Parameter radius;
Parameter sldSph;
Parameter sldSolv;
Parameter background;
Parameter theta;
Parameter phi;
Parameter psi;
// Constructor
FCCrystalModel();
// Operators to get I(Q)
double operator()(double q);
double operator()(double qx, double qy);
double calculate_ER();
double evaluate_rphi(double q, double phi);
};
class BCCrystalModel{
public:
// Model parameters
Parameter scale;
Parameter dnn;
Parameter d_factor;
Parameter radius;
Parameter sldSph;
Parameter sldSolv;
Parameter background;
Parameter theta;
Parameter phi;
Parameter psi;
// Constructor
BCCrystalModel();
// Operators to get I(Q)
double operator()(double q);
double operator()(double qx, double qy);
double calculate_ER();
double evaluate_rphi(double q, double phi);
};
class FuzzySphereModel{
public:
// Model parameters
Parameter radius;
Parameter scale;
Parameter fuzziness;
Parameter sldSph;
Parameter sldSolv;
Parameter background;
// Constructor
FuzzySphereModel();
// Operators to get I(Q)
double operator()(double q);
double operator()(double qx, double qy);
double calculate_ER();
double evaluate_rphi(double q, double phi);
};
class HardsphereStructure{
public:
// Model parameters
Parameter effect_radius;
Parameter volfraction;
// Constructor
HardsphereStructure();
// Operators to get I(Q)
double operator()(double q);
double operator()(double qx, double qy);
double calculate_ER();
double evaluate_rphi(double q, double phi);
};
class StickyHSStructure{
public:
// Model parameters
Parameter effect_radius;
Parameter volfraction;
Parameter perturb;
Parameter stickiness;
// Constructor
StickyHSStructure();
// Operators to get I(Q)
double operator()(double q);
double operator()(double qx, double qy);
double calculate_ER();
double evaluate_rphi(double q, double phi);
};
class SquareWellStructure{
public:
// Model parameters
Parameter effect_radius;
Parameter volfraction;
Parameter welldepth;
Parameter wellwidth;
// Constructor
SquareWellStructure();
// Operators to get I(Q)
double operator()(double q);
double operator()(double qx, double qy);
double calculate_ER();
double evaluate_rphi(double q, double phi);
};
class HayterMSAStructure{
public:
// Model parameters
Parameter effect_radius;
Parameter charge;
Parameter volfraction;
Parameter temperature;
Parameter saltconc;
Parameter dielectconst;
// Constructor
HayterMSAStructure();
// Operators to get I(Q)
double operator()(double q);
double operator()(double qx, double qy);
double calculate_ER();
double evaluate_rphi(double q, double phi);
};
class DiamEllipFunc{
public:
// Model parameters
Parameter radius_a;
Parameter radius_b;
// Constructor
DiamEllipFunc();
// Operators to get I(Q)
double operator()(double q);
double operator()(double qx, double qy);
double calculate_ER();
double evaluate_rphi(double q, double phi);
};
class DiamCylFunc{
public:
// Model parameters
Parameter radius;
Parameter length;
// Constructor
DiamCylFunc();
// Operators to get I(Q)
double operator()(double q);
double operator()(double qx, double qy);
double calculate_ER();
double evaluate_rphi(double q, double phi);
};
class SLDCalFunc{
public:
// Model parameters
Parameter fun_type;
Parameter npts_inter;
Parameter shell_num;
Parameter nu_inter;
Parameter sld_left;
Parameter sld_right;
// Constructor
SLDCalFunc();
// Operators to get SLD
double operator()(double q);
double operator()(double qx, double qy);
double calculate_ER();
double evaluate_rphi(double q, double phi);
};
class CoreShellModel{
public:
// Model parameters
Parameter radius;
Parameter scale;
Parameter thickness;
Parameter core_sld;
Parameter shell_sld;
Parameter solvent_sld;
Parameter background;
// Constructor
CoreShellModel();
// Operators to get I(Q)
double operator()(double q);
double operator()(double qx, double qy);
double calculate_ER();
double evaluate_rphi(double q, double phi);
};
class CoreFourShellModel{
public:
// Model parameters
Parameter scale;
Parameter rad_core0;
Parameter sld_core0;
Parameter thick_shell1;
Parameter sld_shell1;
Parameter thick_shell2;
Parameter sld_shell2;
Parameter thick_shell3;
Parameter sld_shell3;
Parameter thick_shell4;
Parameter sld_shell4;
Parameter sld_solv;
Parameter background;
// Constructor
CoreFourShellModel();
// Operators to get I(Q)
double operator()(double q);
double operator()(double qx, double qy);
double calculate_ER();
double evaluate_rphi(double q, double phi);
};
class CoreShellCylinderModel{
public:
// Model parameters
Parameter radius;
Parameter scale;
Parameter thickness;
Parameter length;
Parameter core_sld;
Parameter shell_sld;
Parameter solvent_sld;
Parameter background;
Parameter axis_theta;
Parameter axis_phi;
// Constructor
CoreShellCylinderModel();
// Operators to get I(Q)
double operator()(double q);
double operator()(double qx, double qy);
double calculate_ER();
double evaluate_rphi(double q, double phi);
};
class EllipsoidModel{
public:
// Model parameters
Parameter radius_a;
Parameter scale;
Parameter radius_b;
Parameter sldEll;
Parameter sldSolv;
Parameter background;
Parameter axis_theta;
Parameter axis_phi;
// Constructor
EllipsoidModel();
// Operators to get I(Q)
double operator()(double q);
double operator()(double qx, double qy);
double calculate_ER();
double evaluate_rphi(double q, double phi);
};
class EllipticalCylinderModel{
public:
// Model parameters
Parameter r_minor;
Parameter scale;
Parameter r_ratio;
Parameter length;
Parameter sldCyl;
Parameter sldSolv;
Parameter background;
Parameter cyl_theta;
Parameter cyl_phi;
Parameter cyl_psi;
// Constructor
EllipticalCylinderModel();
// Operators to get I(Q)
double operator()(double q);
double operator()(double qx, double qy);
double calculate_ER();
double evaluate_rphi(double q, double phi);
};
class TriaxialEllipsoidModel{
public:
// Model parameters
Parameter scale;
Parameter semi_axisA;
Parameter semi_axisB;
Parameter semi_axisC;
Parameter sldEll;
Parameter sldSolv;
Parameter background;
Parameter axis_theta;
Parameter axis_phi;
Parameter axis_psi;
// Constructor
TriaxialEllipsoidModel();
// Operators to get I(Q)
double operator()(double q);
double operator()(double qx, double qy);
double calculate_ER();
double evaluate_rphi(double q, double phi);
};
class FlexibleCylinderModel{
public:
// Model parameters
Parameter scale;
Parameter length;
Parameter kuhn_length;
Parameter radius;
Parameter sldCyl;
Parameter sldSolv;
Parameter background;
// Constructor
FlexibleCylinderModel();
// Operators to get I(Q)
double operator()(double q);
double operator()(double qx, double qy);
double calculate_ER();
double evaluate_rphi(double q, double phi);
};
class FlexCylEllipXModel{
public:
// Model parameters
Parameter scale;
Parameter length;
Parameter kuhn_length;
Parameter radius;
Parameter axis_ratio;
Parameter sldCyl;
Parameter sldSolv;
Parameter background;
// Constructor
FlexCylEllipXModel();
// Operators to get I(Q)
double operator()(double q);
double operator()(double qx, double qy);
double calculate_ER();
double evaluate_rphi(double q, double phi);
};
class StackedDisksModel{
public:
// Model parameters
Parameter scale;
Parameter core_thick;
Parameter radius;
Parameter layer_thick;
Parameter core_sld;
Parameter layer_sld;
Parameter solvent_sld;
Parameter n_stacking;
Parameter sigma_d;
Parameter background;
Parameter axis_theta;
Parameter axis_phi;
// Constructor
StackedDisksModel();
// Operators to get I(Q)
double operator()(double q);
double operator()(double qx, double qy);
double calculate_ER();
double evaluate_rphi(double q, double phi);
};
class LamellarModel{
public:
// Model parameters
Parameter scale;
Parameter bi_thick;
Parameter sld_bi;
Parameter sld_sol;
Parameter background;
// Constructor
LamellarModel();
// Operators to get I(Q)
double operator()(double q);
double operator()(double qx, double qy);
double calculate_ER();
double evaluate_rphi(double q, double phi);
};
class LamellarFFHGModel{
public:
// Model parameters
Parameter scale;
Parameter t_length;
Parameter h_thickness;
Parameter sld_tail;
Parameter sld_head;
Parameter sld_solvent;
Parameter background;
// Constructor
LamellarFFHGModel();
// Operators to get I(Q)
double operator()(double q);
double operator()(double qx, double qy);
double calculate_ER();
double evaluate_rphi(double q, double phi);
};
class LamellarPSModel{
public:
// Model parameters
Parameter scale;
Parameter spacing;
Parameter delta;
Parameter sld_bi;
Parameter sld_sol;
Parameter n_plates;
Parameter caille;
Parameter background;
// Constructor
LamellarPSModel();
// Operators to get I(Q)
double operator()(double q);
double operator()(double qx, double qy);
double calculate_ER();
double evaluate_rphi(double q, double phi);
};
class LamellarPSHGModel{
public:
// Model parameters
Parameter scale;
Parameter spacing;
Parameter deltaT;
Parameter deltaH;
Parameter sld_tail;
Parameter sld_head;
Parameter sld_solvent;
Parameter n_plates;
Parameter caille;
Parameter background;
// Constructor
LamellarPSHGModel();
// Operators to get I(Q)
double operator()(double q);
double operator()(double qx, double qy);
double calculate_ER();
double evaluate_rphi(double q, double phi);
};
class LamellarPCrystalModel{
public:
// Model parameters
Parameter scale;
Parameter thickness;
Parameter Nlayers;
Parameter spacing;
Parameter pd_spacing;
Parameter sld_layer;
Parameter sld_solvent;
Parameter background;
// Constructor
LamellarPCrystalModel();
// Operators to get I(Q)
double operator()(double q);
double operator()(double qx, double qy);
double calculate_ER();
double evaluate_rphi(double q, double phi);
};
class CoreShellEllipsoidModel{
public:
// Model parameters
Parameter scale;
Parameter equat_core;
Parameter polar_core;
Parameter equat_shell;
Parameter polar_shell;
Parameter sld_core;
Parameter sld_shell;
Parameter sld_solvent;
Parameter background;
Parameter axis_theta;
Parameter axis_phi;
// Constructor
CoreShellEllipsoidModel();
// Operators to get I(Q)
double operator()(double q);
double operator()(double qx, double qy);
double calculate_ER();
double evaluate_rphi(double q, double phi);
};
class HollowCylinderModel{
public:
// Model parameters
Parameter scale;
Parameter core_radius;
Parameter radius;
Parameter length;
Parameter sldCyl;
Parameter sldSolv;
Parameter background;
Parameter axis_theta;
Parameter axis_phi;
//Constructor
HollowCylinderModel();
//Operators to get I(Q)
double operator()(double q);
double operator()(double qx , double qy);
double calculate_ER();
double evaluate_rphi(double q, double phi);
};
class MultiShellModel{
public:
// Model parameters
Parameter scale;
Parameter core_radius;
Parameter s_thickness;
Parameter w_thickness;
Parameter core_sld;
Parameter shell_sld;
Parameter n_pairs;
Parameter background;
//Constructor
MultiShellModel();
//Operators to get I(Q)
double operator()(double q);
double operator()(double qx , double qy);
double calculate_ER();
double evaluate_rphi(double q, double phi);
};
class VesicleModel{
public:
// Model parameters
Parameter scale;
Parameter radius;
Parameter thickness;
Parameter core_sld;
Parameter shell_sld;
Parameter background;
//Constructor
VesicleModel();
//Operators to get I(Q)
double operator()(double q);
double operator()(double qx , double qy);
double calculate_ER();
double evaluate_rphi(double q, double phi);
};
class BinaryHSModel{
public:
// Model parameters
Parameter l_radius;
Parameter s_radius;
Parameter vol_frac_ls;
Parameter vol_frac_ss;
Parameter ls_sld;
Parameter ss_sld;
Parameter solvent_sld;
Parameter background;
//Constructor
BinaryHSModel();
//Operators to get I(Q)
double operator()(double q);
double operator()(double qx , double qy);
double calculate_ER();
double evaluate_rphi(double q, double phi);
};
class BinaryHSPSF11Model{
public:
// Model parameters
Parameter l_radius;
Parameter s_radius;
Parameter vol_frac_ls;
Parameter vol_frac_ss;
Parameter ls_sld;
Parameter ss_sld;
Parameter solvent_sld;
Parameter background;
//Constructor
BinaryHSPSF11Model();
//Operators to get I(Q)
double operator()(double q);
double operator()(double qx , double qy);
double calculate_ER();
double evaluate_rphi(double q, double phi);
};
class Poly_GaussCoil{
public:
// Model parameters
Parameter rg;
Parameter scale;
Parameter poly_m;
Parameter background;
// Constructor
Poly_GaussCoil();
// Operators to get I(Q)
double operator()(double q);
double operator()(double qx, double qy);
double calculate_ER();
double evaluate_rphi(double q, double phi);
};
class FractalModel{
public:
// Model parameters
Parameter radius;
Parameter scale;
Parameter fractal_dim;
Parameter cor_length;
Parameter sldBlock;
Parameter sldSolv;
Parameter background;
// Constructor
FractalModel();
// Operators to get I(Q)
double operator()(double q);
double operator()(double qx, double qy);
double calculate_ER();
double evaluate_rphi(double q, double phi);
};
#endif
| [
[
[
1,
20
],
[
25,
34
],
[
37,
46
],
[
48,
50
],
[
438,
442
],
[
445,
452
],
[
454,
456
],
[
783,
799
],
[
801,
803
],
[
831,
850
],
[
852,
860
],
[
863,
872
],
[
874,
883
],
[
886,
896
],
[
898,
899
],
[
1279,
1279
]
],
[
[
21,
21
],
[
98,
101
],
[
107,
109
],
[
111,
117
],
[
119,
122
],
[
900,
906
],
[
909,
911
],
[
914,
919
],
[
921,
930
],
[
933,
933
],
[
935,
940
],
[
942,
944
],
[
967,
970
],
[
972,
972
],
[
974,
976
],
[
979,
981
],
[
983,
988
],
[
990,
996
],
[
1000,
1000
],
[
1002,
1007
],
[
1009,
1022
],
[
1024,
1029
],
[
1031,
1042
],
[
1045,
1047
],
[
1049,
1054
],
[
1056,
1071
],
[
1073,
1078
],
[
1080,
1082
],
[
1131,
1135
],
[
1137,
1137
],
[
1140,
1142
],
[
1144,
1145
],
[
1147,
1149
],
[
1151,
1164
],
[
1166,
1167
],
[
1169,
1171
],
[
1173,
1179
],
[
1181,
1184
],
[
1186,
1187
],
[
1189,
1191
],
[
1193,
1206
],
[
1208,
1209
],
[
1211,
1213
],
[
1215,
1228
],
[
1230,
1231
],
[
1233,
1235
],
[
1237,
1239
]
],
[
[
22,
24
],
[
35,
36
],
[
47,
47
],
[
51,
97
],
[
102,
106
],
[
110,
110
],
[
118,
118
],
[
123,
437
],
[
443,
444
],
[
453,
453
],
[
457,
782
],
[
800,
800
],
[
804,
830
],
[
851,
851
],
[
861,
862
],
[
873,
873
],
[
884,
885
],
[
897,
897
],
[
907,
908
],
[
912,
913
],
[
920,
920
],
[
931,
932
],
[
934,
934
],
[
941,
941
],
[
945,
966
],
[
971,
971
],
[
973,
973
],
[
977,
978
],
[
982,
982
],
[
989,
989
],
[
997,
999
],
[
1001,
1001
],
[
1008,
1008
],
[
1023,
1023
],
[
1030,
1030
],
[
1043,
1044
],
[
1048,
1048
],
[
1055,
1055
],
[
1072,
1072
],
[
1079,
1079
],
[
1083,
1130
],
[
1136,
1136
],
[
1138,
1139
],
[
1143,
1143
],
[
1146,
1146
],
[
1150,
1150
],
[
1165,
1165
],
[
1168,
1168
],
[
1172,
1172
],
[
1180,
1180
],
[
1185,
1185
],
[
1188,
1188
],
[
1192,
1192
],
[
1207,
1207
],
[
1210,
1210
],
[
1214,
1214
],
[
1229,
1229
],
[
1232,
1232
],
[
1236,
1236
],
[
1240,
1278
]
]
] |
|
17e7d1ddfd988c2429e2b27285acb233bf3d2ea6 | 21dd1ece27a68047f93bac2bdf9e6603827b1990 | /CppUTest/src/CppUTest/Extensions/OrderedTest.cpp | 4b5331ee6c810c2b3fd8de04d3b8f4a6773502d9 | [] | no_license | LupusDei/8LU-DSP | c626ce817b6b178c226c437537426f25597958a5 | 65860326bb89a36ff71871b046642b7dd45d5607 | refs/heads/master | 2021-01-17T21:51:19.971505 | 2010-09-24T15:08:01 | 2010-09-24T15:08:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,242 | cpp | /*
* Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde
* 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 <organization> 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 EARLIER MENTIONED AUTHORS ``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 <copyright holder> 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 "CppUTest/TestHarness.h"
#include "CppUTest/TestRegistry.h"
#include "CppUTest/Extensions/OrderedTest.h"
OrderedTest* OrderedTest::_orderedTestsHead = 0;
OrderedTest::OrderedTest() : _nextOrderedTest(0)
{
}
OrderedTest::~OrderedTest()
{
}
int OrderedTest::getLevel()
{
return _level;
}
void OrderedTest::setLevel(int level)
{
_level = level;
}
void OrderedTest::setOrderedTestHead(OrderedTest* test)
{
_orderedTestsHead = test;
}
OrderedTest* OrderedTest::getOrderedTestHead()
{
return _orderedTestsHead;
}
bool OrderedTest::firstOrderedTest()
{
return (getOrderedTestHead() == 0);
}
OrderedTest* OrderedTest::addOrderedTest(OrderedTest* test)
{
Utest::addTest(test);
_nextOrderedTest = test;
return this;
}
void OrderedTest::addOrderedTestToHead(OrderedTest* test)
{
TestRegistry *reg = TestRegistry::getCurrentRegistry();
if (reg->getFirstTest()->isNull() || getOrderedTestHead() == reg->getFirstTest())
reg->addTest(test);
else
reg->getTestWithNext(getOrderedTestHead())->addTest(test);
test->_nextOrderedTest = getOrderedTestHead();
setOrderedTestHead(test);
}
OrderedTest* OrderedTest::getNextOrderedTest()
{
return _nextOrderedTest;
}
OrderedTestInstaller::OrderedTestInstaller(OrderedTest* test, const char* groupName, const char* testName, const char* fileName, int lineNumber, int level)
{
test->setTestName(testName);
test->setGroupName(groupName);
test->setFileName(fileName);
test->setLineNumber(lineNumber);
test->setLevel(level);
if (OrderedTest::firstOrderedTest()) OrderedTest::addOrderedTestToHead(test);
else addOrderedTestInOrder(test);
}
void OrderedTestInstaller::addOrderedTestInOrder(OrderedTest* test)
{
if (test->getLevel() < OrderedTest::getOrderedTestHead()->getLevel())
OrderedTest::addOrderedTestToHead(test);
else
addOrderedTestInOrderNotAtHeadPosition(test);
}
void OrderedTestInstaller::addOrderedTestInOrderNotAtHeadPosition(OrderedTest* test)
{
OrderedTest* current = OrderedTest::getOrderedTestHead();
while (current->getNextOrderedTest()) {
if (current->getNextOrderedTest()->getLevel() > test->getLevel()) {
test->addOrderedTest(current->getNextOrderedTest());
current->addOrderedTest(test);
return;
}
current = current->getNextOrderedTest();
}
test->addOrderedTest(current->getNextOrderedTest());
current->addOrderedTest(test);
}
OrderedTestInstaller::~OrderedTestInstaller()
{
}
| [
"[email protected]"
] | [
[
[
1,
130
]
]
] |
8930696700514c1402bd95951223561c0e97f835 | fd518ed0226c6a044d5e168ab50a0e4a37f8efa9 | /iAuthor/AmpSdk/wmvgen/src/Common/dshowutil.cpp | 98ee6f3f43858988b5b47920aab75be271472798 | [] | no_license | shilinxu/iprojects | e2e2394df9882afaacfb9852332f83cbef6a8c93 | 79bc8e45596577948c45cf2afcff331bc71ab026 | refs/heads/master | 2020-05-17T19:15:43.197685 | 2010-04-02T15:58:11 | 2010-04-02T15:58:11 | 41,959,151 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,837 | cpp | //------------------------------------------------------------------------------
// File: DShowUtil.cpp
//
// Desc: DirectShow sample code - utility functions.
//
// Copyright (c) 2000-2001 Microsoft Corporation. All rights reserved.
//------------------------------------------------------------------------------
#include "stdafx.h"
#include <atlbase.h>
#include <dshow.h>
//#include <mtype.h>
//#include <wxdebug.h>
//#include <reftime.h>
#include "dshowutil.h"
// general purpose function to delete a heap allocated AM_MEDIA_TYPE structure
// which is useful when calling IEnumMediaTypes::Next as the interface
// implementation allocates the structures which you must later delete
// the format block may also be a pointer to an interface to release
void WINAPI DeleteMediaType(AM_MEDIA_TYPE *pmt)
{
// allow NULL pointers for coding simplicity
if (pmt == NULL) {
return;
}
FreeMediaType(*pmt);
CoTaskMemFree((PVOID)pmt);
}
// this also comes in useful when using the IEnumMediaTypes interface so
// that you can copy a media type, you can do nearly the same by creating
// a CMediaType object but as soon as it goes out of scope the destructor
// will delete the memory it allocated (this takes a copy of the memory)
AM_MEDIA_TYPE * WINAPI CreateMediaType(AM_MEDIA_TYPE const *pSrc)
{
_ASSERT(pSrc);
// Allocate a block of memory for the media type
AM_MEDIA_TYPE *pMediaType =
(AM_MEDIA_TYPE *)CoTaskMemAlloc(sizeof(AM_MEDIA_TYPE));
if (pMediaType == NULL) {
return NULL;
}
// Copy the variable length format block
HRESULT hr = CopyMediaType(pMediaType,pSrc);
if (FAILED(hr)) {
CoTaskMemFree((PVOID)pMediaType);
return NULL;
}
return pMediaType;
}
HRESULT WINAPI CopyMediaType(AM_MEDIA_TYPE *pmtTarget, const AM_MEDIA_TYPE *pmtSource)
{
// We'll leak if we copy onto one that already exists - there's one
// case we can check like that - copying to itself.
_ASSERT(pmtSource != pmtTarget);
*pmtTarget = *pmtSource;
if (pmtSource->cbFormat != 0) {
_ASSERT(pmtSource->pbFormat != NULL);
pmtTarget->pbFormat = (PBYTE)CoTaskMemAlloc(pmtSource->cbFormat);
if (pmtTarget->pbFormat == NULL) {
pmtTarget->cbFormat = 0;
return E_OUTOFMEMORY;
} else {
CopyMemory((PVOID)pmtTarget->pbFormat, (PVOID)pmtSource->pbFormat,
pmtTarget->cbFormat);
}
}
if (pmtTarget->pUnk != NULL) {
pmtTarget->pUnk->AddRef();
}
return S_OK;
}
// Free an existing media type (ie free resources it holds)
void WINAPI FreeMediaType(AM_MEDIA_TYPE& mt)
{
if (mt.cbFormat != 0) {
CoTaskMemFree((PVOID)mt.pbFormat);
// Strictly unnecessary but tidier
mt.cbFormat = 0;
mt.pbFormat = NULL;
}
if (mt.pUnk != NULL) {
mt.pUnk->Release();
mt.pUnk = NULL;
}
}
HRESULT FindRenderer(IGraphBuilder *pGB, const GUID *mediatype, IBaseFilter **ppFilter)
{
HRESULT hr;
IEnumFilters *pEnum = NULL;
IBaseFilter *pFilter = NULL;
IPin *pPin;
ULONG ulFetched, ulInPins, ulOutPins;
BOOL bFound=FALSE;
// Verify graph builder interface
if (!pGB)
return E_NOINTERFACE;
// Verify that a media type was passed
if (!mediatype)
return E_POINTER;
// Clear the filter pointer in case there is no match
if (ppFilter)
*ppFilter = NULL;
// Get filter enumerator
hr = pGB->EnumFilters(&pEnum);
if (FAILED(hr))
return hr;
pEnum->Reset();
// Enumerate all filters in the graph
while(!bFound && (pEnum->Next(1, &pFilter, &ulFetched) == S_OK))
{
#ifdef DEBUG
// Read filter name for debugging purposes
FILTER_INFO FilterInfo;
TCHAR szName[256];
hr = pFilter->QueryFilterInfo(&FilterInfo);
if (SUCCEEDED(hr))
{
// Show filter name in debugger
#ifdef UNICODE
lstrcpy(szName, FilterInfo.achName);
#else
WideCharToMultiByte(CP_ACP, 0, FilterInfo.achName, -1, szName, 256, 0, 0);
#endif
FilterInfo.pGraph->Release();
}
#endif
// Find a filter with one input and no output pins
hr = CountFilterPins(pFilter, &ulInPins, &ulOutPins);
if (FAILED(hr))
break;
if ((ulInPins == 1) && (ulOutPins == 0))
{
// Get the first pin on the filter
pPin=0;
pPin = GetInPin(pFilter, 0);
// Read this pin's major media type
AM_MEDIA_TYPE type={0};
hr = pPin->ConnectionMediaType(&type);
if (FAILED(hr))
break;
// Is this pin's media type the requested type?
// If so, then this is the renderer for which we are searching.
// Copy the interface pointer and return.
if (type.majortype == *mediatype)
{
// Found our filter
*ppFilter = pFilter;
bFound = TRUE;;
}
// This is not the renderer, so release the interface.
else
pFilter->Release();
// Delete memory allocated by ConnectionMediaType()
FreeMediaType(type);
}
else
{
// No match, so release the interface
pFilter->Release();
}
}
pEnum->Release();
return hr;
}
HRESULT FindAudioRenderer(IGraphBuilder *pGB, IBaseFilter **ppFilter)
{
return FindRenderer(pGB, &MEDIATYPE_Audio, ppFilter);
}
HRESULT FindVideoRenderer(IGraphBuilder *pGB, IBaseFilter **ppFilter)
{
return FindRenderer(pGB, &MEDIATYPE_Video, ppFilter);
}
HRESULT CountFilterPins(IBaseFilter *pFilter, ULONG *pulInPins, ULONG *pulOutPins)
{
HRESULT hr=S_OK;
IEnumPins *pEnum=0;
ULONG ulFound;
IPin *pPin;
// Verify input
if (!pFilter || !pulInPins || !pulOutPins)
return E_POINTER;
// Clear number of pins found
*pulInPins = 0;
*pulOutPins = 0;
// Get pin enumerator
hr = pFilter->EnumPins(&pEnum);
if(FAILED(hr))
return hr;
pEnum->Reset();
// Count every pin on the filter
while(S_OK == pEnum->Next(1, &pPin, &ulFound))
{
PIN_DIRECTION pindir = (PIN_DIRECTION)3;
hr = pPin->QueryDirection(&pindir);
if(pindir == PINDIR_INPUT)
(*pulInPins)++;
else
(*pulOutPins)++;
pPin->Release();
}
pEnum->Release();
return hr;
}
HRESULT CountTotalFilterPins(IBaseFilter *pFilter, ULONG *pulPins)
{
HRESULT hr;
IEnumPins *pEnum=0;
ULONG ulFound;
IPin *pPin;
// Verify input
if (!pFilter || !pulPins)
return E_POINTER;
// Clear number of pins found
*pulPins = 0;
// Get pin enumerator
hr = pFilter->EnumPins(&pEnum);
if(FAILED(hr))
return hr;
// Count every pin on the filter, ignoring direction
while(S_OK == pEnum->Next(1, &pPin, &ulFound))
{
(*pulPins)++;
pPin->Release();
}
pEnum->Release();
return hr;
}
HRESULT GetPin( IBaseFilter * pFilter, PIN_DIRECTION dirrequired, int iNum, IPin **ppPin)
{
CComPtr< IEnumPins > pEnum;
*ppPin = NULL;
HRESULT hr = pFilter->EnumPins(&pEnum);
if(FAILED(hr))
return hr;
ULONG ulFound;
IPin *pPin;
hr = E_FAIL;
while(S_OK == pEnum->Next(1, &pPin, &ulFound))
{
PIN_DIRECTION pindir = (PIN_DIRECTION)3;
pPin->QueryDirection(&pindir);
if(pindir == dirrequired)
{
if(iNum == 0)
{
*ppPin = pPin;
// Found requested pin, so clear error
hr = S_OK;
break;
}
iNum--;
}
pPin->Release();
}
return hr;
}
IPin * GetInPin( IBaseFilter * pFilter, int Num )
{
CComPtr< IPin > pComPin;
GetPin(pFilter, PINDIR_INPUT, Num, &pComPin);
return pComPin;
}
IPin * GetOutPin( IBaseFilter * pFilter, int Num )
{
CComPtr< IPin > pComPin;
GetPin(pFilter, PINDIR_OUTPUT, Num, &pComPin);
return pComPin;
}
HRESULT FindOtherSplitterPin(IPin *pPinIn, GUID guid, int nStream, IPin **ppSplitPin)
{
if (!ppSplitPin)
return E_POINTER;
CComPtr< IPin > pPinOut;
pPinOut = pPinIn;
while(pPinOut)
{
PIN_INFO ThisPinInfo;
pPinOut->QueryPinInfo(&ThisPinInfo);
if(ThisPinInfo.pFilter) ThisPinInfo.pFilter->Release();
pPinOut = NULL;
CComPtr< IEnumPins > pEnumPins;
ThisPinInfo.pFilter->EnumPins(&pEnumPins);
if(!pEnumPins)
{
return NULL;
}
// look at every pin on the current filter...
//
ULONG Fetched = 0;
while(1)
{
CComPtr< IPin > pPin;
Fetched = 0;
_ASSERT(!pPin); // is it out of scope?
pEnumPins->Next(1, &pPin, &Fetched);
if(!Fetched)
{
break;
}
PIN_INFO pi;
pPin->QueryPinInfo(&pi);
if(pi.pFilter) pi.pFilter->Release();
// if it's an input pin...
//
if(pi.dir == PINDIR_INPUT)
{
// continue searching upstream from this pin
//
pPin->ConnectedTo(&pPinOut);
// a pin that supports the required media type is the
// splitter pin we are looking for! We are done
//
}
else
{
CComPtr< IEnumMediaTypes > pMediaEnum;
pPin->EnumMediaTypes(&pMediaEnum);
if(pMediaEnum)
{
Fetched = 0;
AM_MEDIA_TYPE *pMediaType;
pMediaEnum->Next(1, &pMediaType, &Fetched);
if(Fetched)
{
if(pMediaType->majortype == guid)
{
if(nStream-- == 0)
{
DeleteMediaType(pMediaType);
*ppSplitPin = pPin;
(*ppSplitPin)->AddRef();
return S_OK;
}
}
DeleteMediaType(pMediaType);
}
}
}
// go try the next pin
} // while
}
_ASSERT(FALSE);
return E_FAIL;
}
HRESULT SeekNextFrame( IMediaSeeking * pSeeking, double FPS, long Frame )
{
// try seeking by frames first
//
HRESULT hr = pSeeking->SetTimeFormat(&TIME_FORMAT_FRAME);
REFERENCE_TIME Pos = 0;
if(!FAILED(hr))
{
pSeeking->GetCurrentPosition(&Pos);
Pos++;
}
else
{
// couldn't seek by frames, use Frame and FPS to calculate time
//
Pos = REFERENCE_TIME(double( Frame * UNITS ) / FPS);
// add a half-frame to seek to middle of the frame
//
Pos += REFERENCE_TIME(double( UNITS ) * 0.5 / FPS);
}
hr = pSeeking->SetPositions(&Pos, AM_SEEKING_AbsolutePositioning,
NULL, AM_SEEKING_NoPositioning);
return hr;
}
#ifdef DEBUG
// for debugging purposes
//const INT iMAXLEVELS = 5; // Maximum debug categories
//extern DWORD m_Levels[iMAXLEVELS]; // Debug level per category
#endif
void TurnOnDebugDllDebugging( )
{
/*
#ifdef DEBUG
for(int i = 0 ; i < iMAXLEVELS ; i++)
{
m_Levels[i] = 1;
}
#endif
*/
}
void DbgPrint( char * pText )
{
//DbgLog(( LOG_TRACE, 1, "%s", pText ));
}
void ErrPrint( char * pText )
{
#ifdef DEBUG
printf(pText);
#endif
return;
}
// Adds a DirectShow filter graph to the Running Object Table,
// allowing GraphEdit to "spy" on a remote filter graph.
HRESULT AddGraphToRot(IUnknown *pUnkGraph, DWORD *pdwRegister)
{
IMoniker * pMoniker;
IRunningObjectTable *pROT;
WCHAR wsz[128];
HRESULT hr;
if (FAILED(GetRunningObjectTable(0, &pROT)))
return E_FAIL;
wsprintfW(wsz, L"FilterGraph %08x pid %08x", (DWORD_PTR)pUnkGraph,
GetCurrentProcessId());
hr = CreateItemMoniker(L"!", wsz, &pMoniker);
if (SUCCEEDED(hr))
{
hr = pROT->Register(0, pUnkGraph, pMoniker, pdwRegister);
pMoniker->Release();
}
pROT->Release();
return hr;
}
// Removes a filter graph from the Running Object Table
void RemoveGraphFromRot(DWORD pdwRegister)
{
IRunningObjectTable *pROT;
if (SUCCEEDED(GetRunningObjectTable(0, &pROT)))
{
pROT->Revoke(pdwRegister);
pROT->Release();
}
}
void ShowFilenameByCLSID(REFCLSID clsid, TCHAR *szFilename)
{
USES_CONVERSION;
HRESULT hr;
LPOLESTR strCLSID;
// Convert binary CLSID to a readable version
hr = StringFromCLSID(clsid, &strCLSID);
if(SUCCEEDED(hr))
{
TCHAR szKey[512];
//CString strQuery(strCLSID);
// Create key name for reading filename registry
wsprintf(szKey, _T("Software\\Classes\\CLSID\\%s\\InprocServer32\0"),
W2T(strCLSID));
// Free memory associated with strCLSID (allocated in StringFromCLSID)
CoTaskMemFree(strCLSID);
HKEY hkeyFilter=0;
DWORD dwSize=MAX_PATH;
BYTE szFile[MAX_PATH];
int rc=0;
// Open the CLSID key that contains information about the filter
rc = RegOpenKey(HKEY_LOCAL_MACHINE, szKey, &hkeyFilter);
if (rc == ERROR_SUCCESS)
{
rc = RegQueryValueEx(hkeyFilter, NULL, // Read (Default) value
NULL, NULL, szFile, &dwSize);
if (rc == ERROR_SUCCESS)
wsprintf(szFilename, _T("%s"), szFile);
else
wsprintf(szFilename, _T("<Unknown>\0"));
rc = RegCloseKey(hkeyFilter);
}
}
}
HRESULT GetFileDurationString(IMediaSeeking *pMS, TCHAR *szDuration)
{
HRESULT hr;
if (!pMS)
return E_NOINTERFACE;
if (!szDuration)
return E_POINTER;
// Initialize the display in case we can't read the duration
wsprintf(szDuration, _T("<00:00.000>"));
// Is media time supported for this file?
if (S_OK != pMS->IsFormatSupported(&TIME_FORMAT_MEDIA_TIME))
return E_NOINTERFACE;
// Read the time format to restore later
GUID guidOriginalFormat;
hr = pMS->GetTimeFormat(&guidOriginalFormat);
if (FAILED(hr))
return hr;
// Ensure media time format for easy display
hr = pMS->SetTimeFormat(&TIME_FORMAT_MEDIA_TIME);
if (FAILED(hr))
return hr;
// Read the file's duration
LONGLONG llDuration;
hr = pMS->GetDuration(&llDuration);
if (FAILED(hr))
return hr;
// Return to the original format
if (guidOriginalFormat != TIME_FORMAT_MEDIA_TIME)
{
hr = pMS->SetTimeFormat(&guidOriginalFormat);
if (FAILED(hr))
return hr;
}
// Convert the LONGLONG duration into human-readable format
unsigned long nTotalMS = (unsigned long) llDuration / 10000; // 100ns -> ms
int nMS = nTotalMS % 1000;
int nSeconds = nTotalMS / 1000;
int nMinutes = nSeconds / 60;
nSeconds %= 60;
// Update the string
wsprintf(szDuration, _T("%02dm:%02d.%03ds\0"), nMinutes, nSeconds, nMS);
return hr;
}
BOOL SupportsPropertyPage(IBaseFilter *pFilter)
{
HRESULT hr;
ISpecifyPropertyPages *pSpecify;
// Discover if this filter contains a property page
hr = pFilter->QueryInterface(IID_ISpecifyPropertyPages, (void **)&pSpecify);
if (SUCCEEDED(hr))
{
pSpecify->Release();
return TRUE;
}
else
return FALSE;
}
HRESULT ShowFilterPropertyPage(IBaseFilter *pFilter, HWND hwndParent)
{
HRESULT hr;
ISpecifyPropertyPages *pSpecify=0;
if (!pFilter)
return E_NOINTERFACE;
// Discover if this filter contains a property page
hr = pFilter->QueryInterface(IID_ISpecifyPropertyPages, (void **)&pSpecify);
if (SUCCEEDED(hr))
{
do
{
FILTER_INFO FilterInfo;
hr = pFilter->QueryFilterInfo(&FilterInfo);
if (FAILED(hr))
break;
CAUUID caGUID;
hr = pSpecify->GetPages(&caGUID);
if (FAILED(hr))
break;
pSpecify->Release();
// Display the filter's property page
OleCreatePropertyFrame(
hwndParent, // Parent window
0, // x (Reserved)
0, // y (Reserved)
FilterInfo.achName, // Caption for the dialog box
1, // Number of filters
(IUnknown **)&pFilter, // Pointer to the filter
caGUID.cElems, // Number of property pages
caGUID.pElems, // Pointer to property page CLSIDs
0, // Locale identifier
0, // Reserved
NULL // Reserved
);
CoTaskMemFree(caGUID.pElems);
FilterInfo.pGraph->Release();
} while(0);
}
pFilter->Release();
return hr;
}
//
// Some hardware decoders and video renderers support stepping media
// frame by frame with the IVideoFrameStep interface. See the interface
// documentation for more details on frame stepping.
//
BOOL CanFrameStep(IGraphBuilder *pGB)
{
HRESULT hr;
IVideoFrameStep* pFS;
hr = pGB->QueryInterface(__uuidof(IVideoFrameStep), (PVOID *)&pFS);
if (FAILED(hr))
return FALSE;
// Check if this decoder can step
hr = pFS->CanStep(0L, NULL);
pFS->Release();
if (hr == S_OK)
return TRUE;
else
return FALSE;
}
| [
"[email protected]"
] | [
[
[
1,
711
]
]
] |
f12e85f46a29784ab528dae9c1ead5f9d53932f5 | 3414945a21f778f467500c2ba0ae743fd6653565 | /src/gdx-cpp/graphics/g2d/BitmapFontCache.cpp | 518d183a3c7a3ba162d3ef5241dd377d4509d7d6 | [
"Apache-2.0"
] | permissive | fredmen/libgdx-cpp | 945fdd6ec9837230a19d65cc560f210627747600 | 3447a8fa2a4f5435a6f9fe8a6405327877c263b2 | refs/heads/master | 2021-01-16T00:17:10.413392 | 2011-09-30T12:44:25 | 2011-09-30T12:44:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,030 | cpp |
/*
Copyright 2011 Aevum Software aevum @ aevumlab.com
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.
@author Victor Vicente de Carvalho [email protected]
@author Ozires Bortolon de Faria [email protected]
*/
#include "BitmapFontCache.hpp"
using namespace gdx_cpp::graphics::g2d;
void BitmapFontCache::setPosition (float x,float y) {
translate(x - this.x, y - this.y);
}
void BitmapFontCache::translate (float xAmount,float yAmount) {
if (xAmount == 0 && yAmount == 0) return;
if (integer) {
xAmount = (int)xAmount;
yAmount = (int)yAmount;
}
x += xAmount;
y += yAmount;
float[] vertices = this.vertices;
for (int i = 0, n = idx; i < n; i += 5) {
vertices[i] += xAmount;
vertices[i + 1] += yAmount;
}
}
void BitmapFontCache::setColor (const gdx_cpp::graphics::Color& tint) {
final float color = tint.toFloatBits();
if (color == this.color) return;
this.color = color;
float[] vertices = this.vertices;
for (int i = 2, n = idx; i < n; i += 5)
vertices[i] = color;
}
void BitmapFontCache::setColor (float r,float g,float b,float a) {
int intBits = ((int)(255 * a) << 24) | ((int)(255 * b) << 16) | ((int)(255 * g) << 8) | ((int)(255 * r));
float color = NumberUtils.intBitsToFloat((intBits & 0xfeffffff));
if (color == this.color) return;
this.color = color;
float[] vertices = this.vertices;
for (int i = 2, n = idx; i < n; i += 5)
vertices[i] = color;
}
void BitmapFontCache::draw (const SpriteBatch& spriteBatch) {
spriteBatch.draw(font.getRegion().getTexture(), vertices, 0, idx);
}
void BitmapFontCache::draw (const SpriteBatch& spriteBatch,float alphaModulation) {
Color color = getColor();
float oldAlpha = color.a;
color.a *= alphaModulation;
setColor(color);
draw(spriteBatch);
color.a = oldAlpha;
setColor(color);
}
gdx_cpp::graphics::Color& BitmapFontCache::getColor () {
float floatBits = color;
int intBits = NumberUtils.floatToRawIntBits(color);
Color color = tmpColor;
color.r = (intBits & 0xff) / 255f;
color.g = ((intBits >>> 8) & 0xff) / 255f;
color.b = ((intBits >>> 16) & 0xff) / 255f;
color.a = ((intBits >>> 24) & 0xff) / 255f;
return color;
}
void BitmapFontCache::reset (int glyphCount) {
x = 0;
y = 0;
idx = 0;
int vertexCount = glyphCount * 20;
if (vertices == null || vertices.length < vertexCount) vertices = new float[vertexCount];
}
float BitmapFontCache::addToCache (const CharSequence& str,float x,float y,int start,int end) {
float startX = x;
BitmapFont font = this.font;
Glyph lastGlyph = null;
if (font.data.scaleX == 1 && font.data.scaleY == 1) {
while (start < end) {
lastGlyph = font.data.getGlyph(str.charAt(start++));
if (lastGlyph != null) {
addGlyph(lastGlyph, x + lastGlyph.xoffset, y + lastGlyph.yoffset, lastGlyph.width, lastGlyph.height);
x += lastGlyph.xadvance;
break;
}
}
while (start < end) {
char ch = str.charAt(start++);
Glyph g = font.data.getGlyph(ch);
if (g != null) {
x += lastGlyph.getKerning(ch);
lastGlyph = g;
addGlyph(lastGlyph, x + g.xoffset, y + g.yoffset, g.width, g.height);
x += g.xadvance;
}
}
} else {
float scaleX = font.data.scaleX, scaleY = font.data.scaleY;
while (start < end) {
lastGlyph = font.data.getGlyph(str.charAt(start++));
if (lastGlyph != null) {
addGlyph(lastGlyph, //
x + lastGlyph.xoffset * scaleX, //
y + lastGlyph.yoffset * scaleY, //
lastGlyph.width * scaleX, //
lastGlyph.height * scaleY);
x += lastGlyph.xadvance * scaleX;
break;
}
}
while (start < end) {
char ch = str.charAt(start++);
Glyph g = font.data.getGlyph(ch);
if (g != null) {
x += lastGlyph.getKerning(ch) * scaleX;
lastGlyph = g;
addGlyph(lastGlyph, //
x + g.xoffset * scaleX, //
y + g.yoffset * scaleY, //
g.width * scaleX, //
g.height * scaleY);
x += g.xadvance * scaleX;
}
}
}
return x - startX;
}
void BitmapFontCache::addGlyph (const gdx_cpp::graphics::g2d::BitmapFont::Glyph& glyph,float x,float y,float width,float height) {
final float x2 = x + width;
final float y2 = y + height;
final float u = glyph.u;
final float u2 = glyph.u2;
final float v = glyph.v;
final float v2 = glyph.v2;
final float[] vertices = this.vertices;
if (!integer) {
vertices[idx++] = x;
vertices[idx++] = y;
vertices[idx++] = color;
vertices[idx++] = u;
vertices[idx++] = v;
vertices[idx++] = x;
vertices[idx++] = y2;
vertices[idx++] = color;
vertices[idx++] = u;
vertices[idx++] = v2;
vertices[idx++] = x2;
vertices[idx++] = y2;
vertices[idx++] = color;
vertices[idx++] = u2;
vertices[idx++] = v2;
vertices[idx++] = x2;
vertices[idx++] = y;
vertices[idx++] = color;
vertices[idx++] = u2;
vertices[idx++] = v;
} else {
vertices[idx++] = (int)x;
vertices[idx++] = (int)y;
vertices[idx++] = color;
vertices[idx++] = u;
vertices[idx++] = v;
vertices[idx++] = (int)x;
vertices[idx++] = (int)y2;
vertices[idx++] = color;
vertices[idx++] = u;
vertices[idx++] = v2;
vertices[idx++] = (int)x2;
vertices[idx++] = (int)y2;
vertices[idx++] = color;
vertices[idx++] = u2;
vertices[idx++] = v2;
vertices[idx++] = (int)x2;
vertices[idx++] = (int)y;
vertices[idx++] = color;
vertices[idx++] = u2;
vertices[idx++] = v;
}
}
gdx_cpp::graphics::g2d::BitmapFont::TextBounds& BitmapFontCache::setText (const CharSequence& str,float x,float y) {
return setText(str, x, y, 0, str.length());
}
gdx_cpp::graphics::g2d::BitmapFont::TextBounds& BitmapFontCache::setText (const CharSequence& str,float x,float y,int start,int end) {
reset(end - start);
y += font.data.ascent;
textBounds.width = addToCache(str, x, y, start, end);
textBounds.height = font.data.capHeight;
return textBounds;
}
gdx_cpp::graphics::g2d::BitmapFont::TextBounds& BitmapFontCache::setMultiLineText (const CharSequence& str,float x,float y) {
return setMultiLineText(str, x, y, 0, HAlignment.LEFT);
}
gdx_cpp::graphics::g2d::BitmapFont::TextBounds& BitmapFontCache::setMultiLineText (const CharSequence& str,float x,float y,float alignmentWidth,const gdx_cpp::graphics::g2d::BitmapFont::HAlignment& alignment) {
BitmapFont font = this.font;
int length = str.length();
reset(length);
y += font.data.ascent;
float down = font.data.down;
float maxWidth = 0;
float startY = y;
int start = 0;
int numLines = 0;
while (start < length) {
int lineEnd = BitmapFont.indexOf(str, '\n', start);
float xOffset = 0;
if (alignment != HAlignment.LEFT) {
float lineWidth = font.getBounds(str, start, lineEnd).width;
xOffset = alignmentWidth - lineWidth;
if (alignment == HAlignment.CENTER) xOffset /= 2;
}
float lineWidth = addToCache(str, x + xOffset, y, start, lineEnd);
maxWidth = Math.max(maxWidth, lineWidth);
start = lineEnd + 1;
y += down;
numLines++;
}
textBounds.width = maxWidth;
textBounds.height = font.data.capHeight + (numLines - 1) * font.data.lineHeight;
return textBounds;
}
gdx_cpp::graphics::g2d::BitmapFont::TextBounds& BitmapFontCache::setWrappedText (const CharSequence& str,float x,float y,float wrapWidth) {
return setWrappedText(str, x, y, wrapWidth, HAlignment.LEFT);
}
gdx_cpp::graphics::g2d::BitmapFont::TextBounds& BitmapFontCache::setWrappedText (const CharSequence& str,float x,float y,float wrapWidth,const gdx_cpp::graphics::g2d::BitmapFont::HAlignment& alignment) {
BitmapFont font = this.font;
int length = str.length();
reset(length);
y += font.data.ascent;
float down = font.data.down;
float maxWidth = 0;
int start = 0;
int numLines = 0;
while (start < length) {
int lineEnd = start + font.computeVisibleGlyphs(str, start, BitmapFont.indexOf(str, '\n', start), wrapWidth);
if (lineEnd < length) {
while (lineEnd > start) {
char ch = str.charAt(lineEnd);
if (ch == ' ' || ch == '\n') break;
lineEnd--;
}
}
if (lineEnd == start) lineEnd++;
float xOffset = 0;
if (alignment != HAlignment.LEFT) {
float lineWidth = font.getBounds(str, start, lineEnd).width;
xOffset = wrapWidth - lineWidth;
if (alignment == HAlignment.CENTER) xOffset /= 2;
}
float lineWidth = addToCache(str, x + xOffset, y, start, lineEnd);
maxWidth = Math.max(maxWidth, lineWidth);
start = lineEnd + 1;
y += down;
numLines++;
}
textBounds.width = maxWidth;
textBounds.height = font.data.capHeight + (numLines - 1) * font.data.lineHeight;
return textBounds;
}
gdx_cpp::graphics::g2d::BitmapFont::TextBounds& BitmapFontCache::getBounds () {
return textBounds;
}
float BitmapFontCache::getX () {
return x;
}
float BitmapFontCache::getY () {
return y;
}
BitmapFont& BitmapFontCache::getFont () {
return font;
}
void BitmapFontCache::dispose () {
font.dispose();
}
void BitmapFontCache::setUseIntegerPositions (bool use) {
this.integer = use;
}
bool BitmapFontCache::usesIntegerPositions () {
return integer;
}
| [
"[email protected]"
] | [
[
[
1,
330
]
]
] |
9d30df56dd0865093da01edb500a846b683d36db | b8fe0ddfa6869de08ba9cd434e3cf11e57d59085 | /NxOgre/build/source/NxOgreMemoryResource.cpp | 4b23fa93ff26000dbf9d9c371e334e5dc7f30574 | [] | no_license | juanjmostazo/ouan-tests | c89933891ed4f6ad48f48d03df1f22ba0f3ff392 | eaa73fb482b264d555071f3726510ed73bef22ea | refs/heads/master | 2021-01-10T20:18:35.918470 | 2010-06-20T15:45:00 | 2010-06-20T15:45:00 | 38,101,212 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 10,564 | cpp | /** File: NxOgreMemoryResource.cpp
Created on: 17-Nov-08
Author: Robin Southern "betajaen"
© Copyright, 2008-2009 by Robin Southern, http://www.nxogre.org
This file is part of NxOgre.
NxOgre 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.
NxOgre 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 NxOgre. If not, see <http://www.gnu.org/licenses/>.
*/
#include "NxOgreStable.h"
#include "NxOgreMemoryResource.h"
namespace NxOgre
{
MemoryResource::MemoryResource(const ArchiveResourceIdentifier& ari, Archive* archive)
:Resource(ari, archive), mStart(0), mEnd(0), mPointer(0)
{
}
MemoryResource::~MemoryResource(void)
{
if (mStart)
NxOgre_Unallocate(mStart);
}
Enums::ResourceStatus MemoryResource::getStatus(void) const
{
return mStatus;
}
Enums::ResourceDirectionality MemoryResource::getDirectionality(void) const
{
return mDirectionality;
}
void MemoryResource::open(void)
{
if (mStatus == Enums::ResourceStatus_Opened)
close();
mStatus = Enums::ResourceStatus_Opening;
mDirectionality = Enums::ResourceDirectionality_Unknown;
mAccess = Enums::ResourceAccess_ReadAndWrite;
mStart = (char*) NxOgre_Allocate(16, Classes::_char);
mEnd = mStart + 16;
mPointer = mStart;
mStatus = Enums::ResourceStatus_Opened;
}
void MemoryResource::close(void)
{
mStatus = Enums::ResourceStatus_Closing;
mDirectionality = Enums::ResourceDirectionality_Unknown;
if (mStart)
NxOgre_Unallocate(mStart);
mStart = mEnd = mPointer = 0;
mStatus = Enums::ResourceStatus_Closed;
}
Enums::ResourceAccess MemoryResource::getAccess(void) const
{
return mAccess;
}
size_t MemoryResource::getSize(void) const
{
return (mEnd - mStart);
}
bool MemoryResource::seek(size_t to)
{
if (mStatus == Enums::ResourceStatus_Opened && mDirectionality == Enums::ResourceDirectionality_Omidirectional)
{
if (to > size_t(mEnd - mStart))
return false;
mPointer = mStart + to;
return true;
}
return false;
}
bool MemoryResource::seekBeginning(void)
{
if (mStatus == Enums::ResourceStatus_Opened && mDirectionality == Enums::ResourceDirectionality_Omidirectional)
{
mPointer = mStart;
return true;
}
return false;
}
bool MemoryResource::seekEnd(void)
{
if (mStatus == Enums::ResourceStatus_Opened && mDirectionality == Enums::ResourceDirectionality_Omidirectional)
{
mPointer = mEnd - 1;
return true;
}
return false;
}
bool MemoryResource::atBeginning(void) const
{
return (mPointer == mStart);
}
bool MemoryResource::atEnd(void) const
{
return (mPointer >= mEnd - 1);
}
size_t MemoryResource::at(void) const
{
return (mPointer - mStart);
}
bool MemoryResource::write(const void* src, size_t src_size)
{
if (mStatus != Enums::ResourceStatus_Opened)
return false;
if (mStatus != mAccess != Enums::ResourceAccess_ReadOnly)
return false;
size_t current_size = (mEnd - mStart);
char* pointer_willbe = mPointer + src_size;
if (pointer_willbe > mStart + current_size)
{
mStatus = Enums::ResourceStatus_Maintenance;
size_t new_buffer_size = (current_size * 2) + 1;
char* new_buffer = (char*) NxOgre_Allocate(new_buffer_size, Classes::_char);
if (mStart)
Memory::copy(new_buffer, mStart, current_size);
NxOgre_Unallocate(mStart);
size_t pointer_pos = mPointer - mStart;
mStart = new_buffer;
mEnd = mStart + new_buffer_size;
mPointer = mStart + pointer_pos;
mStatus = Enums::ResourceStatus_Maintenance;
}
Memory::copy(mPointer, src, src_size);
mPointer += src_size;
return true;
}
bool MemoryResource::writeNull(void)
{
return write(&NULL_BYTE, sizeof(char));
}
bool MemoryResource::writeBool(bool bool_value)
{
return write(&bool_value, sizeof(bool));
}
bool MemoryResource::writeBool(bool* bool_array, size_t length)
{
return write(&bool_array, sizeof(bool) * length);
}
bool MemoryResource::writeUChar(unsigned char char_value)
{
return write(&char_value, sizeof(unsigned char));
}
bool MemoryResource::writeUChar(unsigned char* char_array, size_t length)
{
return write(&char_array, sizeof(unsigned char) * length);
}
bool MemoryResource::writeChar(char char_value)
{
return write(&char_value, sizeof(char));
}
bool MemoryResource::writeChar(char* char_array, size_t length)
{
return write(char_array, sizeof(char) * length);
}
bool MemoryResource::writeUShort(unsigned short u_short_value)
{
return write(&u_short_value, sizeof(unsigned short));
}
bool MemoryResource::writeUShort(unsigned short* u_short_array, size_t length)
{
return write(u_short_array, sizeof(unsigned short) * length);
}
bool MemoryResource::writeShort(short short_value)
{
return write(&short_value, sizeof(short));
}
bool MemoryResource::writeShort(short* short_array, size_t length)
{
return write(short_array, sizeof(short_array) * length);
}
bool MemoryResource::writeUInt(unsigned int u_int_value)
{
return write(&u_int_value, sizeof(unsigned int));
}
bool MemoryResource::writeUInt(unsigned int* u_int_array, size_t length)
{
return write(u_int_array, sizeof(unsigned int) * length);
}
bool MemoryResource::writeInt(int int_value)
{
return write(&int_value, sizeof(int));
}
bool MemoryResource::writeInt(int* int_array, size_t length)
{
return write(int_array, sizeof(int) * length);
}
bool MemoryResource::writeFloat(float float_value)
{
return write(&float_value, sizeof(float));
}
bool MemoryResource::writeFloat(float* float_array, size_t length)
{
return write(float_array, sizeof(float) * length);
}
bool MemoryResource::writeDouble(double double_value)
{
return write(&double_value, sizeof(double));
}
bool MemoryResource::writeDouble(double* double_array, size_t length)
{
return write(double_array, sizeof(double) * length);
}
bool MemoryResource::writeReal(NxOgreRealType real_value)
{
return write(&real_value, sizeof(NxOgreRealType));
}
bool MemoryResource::writeReal(NxOgreRealType* real_array, size_t length)
{
return write(real_array, sizeof(NxOgreRealType) * length);
}
bool MemoryResource::writeLong(long long_value)
{
return write(&long_value, sizeof(long));
}
bool MemoryResource::writeLong(long* long_array, size_t length)
{
return write(long_array, sizeof(long) * length);
}
bool MemoryResource::readBool(void)
{
bool t;
Memory::copy(&t, mPointer, sizeof(bool));
mPointer += sizeof(bool);
return t;
}
void MemoryResource::readBoolArray(bool* t, size_t length)
{
Memory::copy(t, mPointer, length);
mPointer += length;
}
unsigned char MemoryResource::readUChar(void)
{
unsigned char t;
Memory::copy(&t, mPointer, sizeof(unsigned char));
mPointer += sizeof(unsigned char);
return t;
}
void MemoryResource::readUCharArray(unsigned char* t, size_t length)
{
Memory::copy(t, mPointer, length);
mPointer += length;
}
char MemoryResource::readChar(void)
{
char t;
Memory::copy(&t, mPointer, sizeof(char));
mPointer += sizeof(char);
return t;
}
void MemoryResource::readCharArray(char* t, size_t length)
{
Memory::copy(t, mPointer, length);
mPointer += length;
}
unsigned short MemoryResource::readUShort(void)
{
unsigned short t;
Memory::copy(&t, mPointer, sizeof(unsigned short));
mPointer += sizeof(unsigned short);
return t;
}
void MemoryResource::readUShortArray(unsigned short* t, size_t length)
{
Memory::copy(t, mPointer, length);
mPointer += length;
}
short MemoryResource::readShort(void)
{
short t;
Memory::copy(&t, mPointer, sizeof(short));
mPointer += sizeof(short);
return t;
}
void MemoryResource::readShortArray(short* t, size_t length)
{
Memory::copy(t, mPointer, length);
mPointer += length;
}
unsigned int MemoryResource::readUInt(void)
{
unsigned int t;
Memory::copy(&t, mPointer, sizeof(unsigned int));
mPointer += sizeof(unsigned int);
return t;
}
void MemoryResource::readUIntArray(unsigned int* t, size_t length)
{
Memory::copy(t, mPointer, length);
mPointer += length;
}
int MemoryResource::readInt(void)
{
int t;
Memory::copy(&t, mPointer, sizeof(int));
mPointer += sizeof(int);
return t;
}
void MemoryResource::readIntArray(int* t, size_t length)
{
Memory::copy(t, mPointer, length);
mPointer += length;
}
float MemoryResource::readFloat(void)
{
float t;
Memory::copy(&t, mPointer, sizeof(float));
mPointer += sizeof(float);
return t;
}
void MemoryResource::readFloatArray(float* t, size_t length)
{
Memory::copy(t, mPointer, length);
mPointer += length;
}
double MemoryResource::readDouble(void)
{
double t;
Memory::copy(&t, mPointer, sizeof(double));
mPointer += sizeof(double);
return t;
}
void MemoryResource::readDouble(double* t, size_t length)
{
Memory::copy(t, mPointer, length);
mPointer += length;
}
Real MemoryResource::readReal(void)
{
NxOgreRealType t;
Memory::copy(&t, mPointer, sizeof(NxOgreRealType));
mPointer += sizeof(NxOgreRealType);
return t;
}
void MemoryResource::readRealArray(NxOgreRealType* t, size_t length)
{
Memory::copy(t, mPointer, length);
mPointer += length;
}
long MemoryResource::readLong(void)
{
long t;
Memory::copy(&t, mPointer, sizeof(long));
mPointer += sizeof(long);
return t;
}
void MemoryResource::readLongArray(long* t, size_t length)
{
Memory::copy(t, mPointer, length);
mPointer += length;
}
void MemoryResource::flush()
{
// No code required.
}
} // namespace NxOgre
| [
"ithiliel@6899d1ce-2719-11df-8847-f3d5e5ef3dde"
] | [
[
[
1,
454
]
]
] |
780fde75f7c2726547ced2ac0c7823680a9ab2e7 | 222bc22cb0330b694d2c3b0f4b866d726fd29c72 | /src/nv38box/Math/WmlGVector.h | 73150877eee39370f494f94af36adb215d35e6ed | [
"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 | UTF-8 | C++ | false | false | 2,441 | h | // 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.
#ifndef WMLGVECTOR_H
#define WMLGVECTOR_H
#include "WmlMath.h"
namespace Wml
{
template<class Real>
class WML_ITEM GVector
{
public:
// construction
GVector(int iSize = 0);
GVector(int iSize, const Real* afTuple);
GVector(const GVector& rkV);
~GVector();
// coordinate access
void SetSize(int iSize);
int GetSize() const;
operator const Real*() const;
operator Real*();
Real operator[](int i) const;
Real& operator[](int i);
// assignment
GVector& operator=(const GVector& rkV);
// comparison
bool operator==(const GVector& rkV) const;
bool operator!=(const GVector& rkV) const;
bool operator<(const GVector& rkV) const;
bool operator<=(const GVector& rkV) const;
bool operator>(const GVector& rkV) const;
bool operator>=(const GVector& rkV) const;
// arithmetic operations
GVector operator+(const GVector& rkV) const;
GVector operator-(const GVector& rkV) const;
GVector operator*(Real fScalar) const;
GVector operator/(Real fScalar) const;
GVector operator-() const;
// arithmetic updates
GVector& operator+=(const GVector& rkV);
GVector& operator-=(const GVector& rkV);
GVector& operator*=(Real fScalar);
GVector& operator/=(Real fScalar);
// vector operations
Real Length() const;
Real SquaredLength() const;
Real Dot(const GVector& rkV) const;
Real Normalize();
protected:
// support for comparisons
int CompareArrays(const GVector& rkV) const;
int m_iSize;
Real* m_afTuple;
};
template<class Real>
WML_ITEM GVector<Real> operator*(Real fScalar, const GVector<Real>& rkV);
typedef GVector<float> GVectorf;
typedef GVector<double> GVectord;
}
#endif
| [
"[email protected]"
] | [
[
[
1,
81
]
]
] |
b2c6a8f746a5f840cc8319341a7ea5dba042aa60 | dda0d7bb4153bcd98ad5e32e4eac22dc974b8c9d | /tests/crash_report_api_test.cpp | 34df857afef7fbda6e6561eba4140ac9b1bc9d10 | [
"BSD-3-Clause"
] | permissive | systembugtj/crash-report | abd45ceedc08419a3465414ad9b3b6a5d6c6729a | 205b087e79eb8ed7a9b6a7c9f4ac580707e9cb7e | refs/heads/master | 2021-01-19T07:08:04.878028 | 2011-04-05T04:03:54 | 2011-04-05T04:03:54 | 35,228,814 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 28,636 | cpp | /*************************************************************************************
This file is a part of CrashRpt library.
Copyright (c) 2003, Michael Carruth
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 author 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 "stdafx.h"
#include "Tests.h"
#include "crash_report_helper.h"
#include "base/Utility.h"
#include "base/strconv.h"
REGISTER_TEST_SUITE( CrashRptAPITests , "CrashRpt API function tests");
REGISTER_TEST(Test_crInstall_null);
void Test_crInstall_null()
{
// Test crInstall with NULL info - should fail
int nInstallResult = crInstallW(NULL);
TEST_ASSERT(nInstallResult!=0);
int nInstallResult2 = crInstallA(NULL);
TEST_ASSERT(nInstallResult2!=0);
__TEST_CLEANUP__;
}
REGISTER_TEST(Test_crInstall_wrong_cb);
void Test_crInstall_wrong_cb()
{
// Test crInstall with wrong size parameter - should fail
CR_INSTALL_INFO info;
memset(&info, 0, sizeof(CR_INSTALL_INFO));
info.size = 1000;
int nInstallResult = crInstall(&info);
TEST_ASSERT(nInstallResult!=0);
__TEST_CLEANUP__;
}
REGISTER_TEST(Test_crInstall_missing_app_ver);
void Test_crInstall_missing_app_ver()
{
// Test crInstall with with missing app version
// As this console app has missing EXE product version - should fail
CR_INSTALL_INFO info;
memset(&info, 0, sizeof(CR_INSTALL_INFO));
info.size = sizeof(CR_INSTALL_INFO);
int nInstallResult = crInstall(&info);
TEST_ASSERT(nInstallResult!=0);
__TEST_CLEANUP__;
}
REGISTER_TEST(Test_crInstallW_zero_info);
void Test_crInstallW_zero_info()
{
// Test crInstallW with zero info
CR_INSTALL_INFOW infoW;
memset(&infoW, 0, sizeof(CR_INSTALL_INFOW));
infoW.size = sizeof(CR_INSTALL_INFOW);
infoW.application_version = L"1.0.0"; // Specify app version, otherwise it will fail.
int nInstallResult = crInstallW(&infoW);
TEST_ASSERT(nInstallResult==0);
__TEST_CLEANUP__
crUninstall();
}
REGISTER_TEST(Test_crInstallA_zero_info);
void Test_crInstallA_zero_info()
{
// Test crInstallA with zero info
CR_INSTALL_INFOA infoA;
memset(&infoA, 0, sizeof(CR_INSTALL_INFOA));
infoA.size = sizeof(CR_INSTALL_INFOA);
infoA.application_version = "1.0.0"; // Specify app version, otherwise it will fail.
int nInstallResult = crInstallA(&infoA);
TEST_ASSERT(nInstallResult==0);
__TEST_CLEANUP__
crUninstall();
}
REGISTER_TEST(Test_crInstallA_twice);
void Test_crInstallA_twice()
{
// Call crInstallA two times - the second one should fail
CR_INSTALL_INFOA infoA;
memset(&infoA, 0, sizeof(CR_INSTALL_INFOA));
infoA.size = sizeof(CR_INSTALL_INFOA);
infoA.application_version = "1.0.0"; // Specify app version, otherwise it will fail.
int nInstallResult = crInstallA(&infoA);
TEST_ASSERT(nInstallResult==0);
int nInstallResult2 = crInstallA(&infoA);
TEST_ASSERT(nInstallResult2!=0);
__TEST_CLEANUP__
crUninstall();
}
#ifndef CRASHRPT_LIB
// Test the case when crash_report.dll and crash_sender.exe are located in
// a different folder (not the same where process executable is located).
// This test also checks that crInstall and crUninstall function names
// are undecorated.
REGISTER_TEST(Test_crInstall_in_different_folder);
void Test_crInstall_in_different_folder()
{
CString sAppDataFolder;
CString sExeFolder;
CString sTmpFolder;
HMODULE hCrashRpt = NULL;
// Create a temporary folder
Utility::GetSpecialFolder(CSIDL_APPDATA, sAppDataFolder);
sTmpFolder = sAppDataFolder+_T("\\CrashRpt");
BOOL bCreate = Utility::CreateFolder(sTmpFolder);
TEST_ASSERT(bCreate);
// Copy crash_report.dll and crash_sender.exe into that folder
sExeFolder = Utility::GetModulePath(NULL);
#ifdef _DEBUG
BOOL bCopy = CopyFile(sExeFolder+_T("\\crash_reportd.dll"), sTmpFolder+_T("\\crash_reportd.dll"), TRUE);
TEST_ASSERT(bCopy);
BOOL bCopy2 = CopyFile(sExeFolder+_T("\\crash_senderd.exe"), sTmpFolder+_T("\\crash_senderd.exe"), TRUE);
TEST_ASSERT(bCopy2);
#else
BOOL bCopy = CopyFile(sExeFolder+_T("\\crash_report.dll"), sTmpFolder+_T("\\crash_report.dll"), TRUE);
TEST_ASSERT(bCopy);
BOOL bCopy2 = CopyFile(sExeFolder+_T("\\crash_sender.exe"), sTmpFolder+_T("\\crash_sender.exe"), TRUE);
TEST_ASSERT(bCopy2);
#endif
BOOL bCopy3 = CopyFile(sExeFolder+_T("\\crashrpt_lang.ini"), sTmpFolder+_T("\\crashrpt_lang.ini"), TRUE);
TEST_ASSERT(bCopy3);
// Load crash_report.dll dynamically
#ifdef _DEBUG
hCrashRpt = LoadLibrary(sTmpFolder+_T("\\crash_reportd.dll"));
TEST_ASSERT(hCrashRpt!=NULL);
#else
hCrashRpt = LoadLibrary(sTmpFolder+_T("\\crash_report.dll"));
TEST_ASSERT(hCrashRpt!=NULL);
#endif
// Install crash handler
CR_INSTALL_INFO infoW;
memset(&infoW, 0, sizeof(CR_INSTALL_INFOW));
infoW.size = sizeof(CR_INSTALL_INFOW);
infoW.application_name = L"My& app Name & '"; // Use appname with restricted XML characters
infoW.application_version = L"1.0.0"; // Specify app version, otherwise it will fail.
typedef int (WINAPI *PFNCRINSTALLW)(PCR_INSTALL_INFOW);
PFNCRINSTALLW pfncrInstallW = (PFNCRINSTALLW)GetProcAddress(hCrashRpt, "crInstallW");
TEST_ASSERT(pfncrInstallW!=NULL);
typedef int (WINAPI *PFNCRUNINSTALL)();
PFNCRUNINSTALL pfncrUninstall = (PFNCRUNINSTALL)GetProcAddress(hCrashRpt, "crUninstall");
TEST_ASSERT(pfncrUninstall!=NULL);
// Install should succeed
int nInstallResult = pfncrInstallW(&infoW);
TEST_ASSERT(nInstallResult==0);
__TEST_CLEANUP__
crUninstall();
FreeLibrary(hCrashRpt);
// Delete temporary folder
Utility::RecycleFile(sTmpFolder, TRUE);
}
#endif //!CRASHRPT_LIB
REGISTER_TEST(Test_crUninstall);
void Test_crUninstall()
{
// Call crUninstall - should fail, because crInstall should be called first
int nUninstallResult = crUninstall();
TEST_ASSERT(nUninstallResult!=0);
// And another time...
int nUninstallResult2 = crUninstall();
TEST_ASSERT(nUninstallResult2!=0);
__TEST_CLEANUP__;
}
REGISTER_TEST(Test_crAddFileA);
void Test_crAddFileA()
{
strconv_t strconv;
CString sFileName;
// Should fail, because crInstall() should be called first
int nResult = crAddFileA("a.txt", "invalid file");
TEST_ASSERT(nResult!=0);
// Install crash handler
CR_INSTALL_INFOA infoA;
memset(&infoA, 0, sizeof(CR_INSTALL_INFOA));
infoA.size = sizeof(CR_INSTALL_INFOA);
infoA.application_version = "1.0.0"; // Specify app version, otherwise it will fail.
int nInstallResult = crInstallA(&infoA);
TEST_ASSERT(nInstallResult==0);
// Add not existing file, crAddFileA should fail
int nResult2 = crAddFileA("a.txt", "invalid file");
TEST_ASSERT(nResult2!=0);
if(g_bRunningFromUNICODEFolder==FALSE)
{
// Add existing file, crAddFileA should succeed
sFileName = Utility::GetModulePath(NULL)+_T("\\dummy.ini");
const char* szFileName = strconv.t2a(sFileName);
int nResult3 = crAddFileA(szFileName, "Dummy INI File");
TEST_ASSERT(nResult3==0);
}
__TEST_CLEANUP__;
// Uninstall
crUninstall();
}
REGISTER_TEST(Test_crAddFileW);
void Test_crAddFileW()
{
strconv_t strconv;
CString sFileName;
// Should fail, because crInstall() should be called first
int nResult = crAddFileW(L"a.txt", L"invalid file");
TEST_ASSERT(nResult!=0);
// Install crash handler
CR_INSTALL_INFOW infoW;
memset(&infoW, 0, sizeof(CR_INSTALL_INFOW));
infoW.size = sizeof(CR_INSTALL_INFOW);
infoW.application_version = L"1.0.0"; // Specify app version, otherwise it will fail.
int nInstallResult = crInstallW(&infoW);
TEST_ASSERT(nInstallResult==0);
// Add not existing file, crAddFileA should fail
int nResult2 = crAddFileW(L"a.txt", L"invalid file");
TEST_ASSERT(nResult2!=0);
// Add existing file, crAddFileA should succeed
sFileName = Utility::GetModulePath(NULL)+_T("\\dummy.ini");
const wchar_t* szFileName = strconv.t2w(sFileName);
int nResult3 = crAddFileW(szFileName, L"Dummy INI File");
TEST_ASSERT(nResult3==0);
__TEST_CLEANUP__;
// Uninstall
crUninstall();
}
REGISTER_TEST(Test_crAddPropertyA);
void Test_crAddPropertyA()
{
// Should fail, because crInstall() should be called first
int nResult = crAddPropertyA("VideoAdapter", "nVidia GeForce GTS 250");
TEST_ASSERT(nResult!=0);
// Install crash handler
CR_INSTALL_INFOA infoA;
memset(&infoA, 0, sizeof(CR_INSTALL_INFOA));
infoA.size = sizeof(CR_INSTALL_INFOA);
infoA.application_version = "1.0.0"; // Specify app version, otherwise it will fail.
int nInstallResult = crInstallA(&infoA);
TEST_ASSERT(nInstallResult==0);
// Should fail, because property name is empty
int nResult2 = crAddPropertyA("", "nVidia GeForce GTS 250");
TEST_ASSERT(nResult2!=0);
// Should succeed
int nResult3 = crAddPropertyA("VideoAdapter", "nVidia GeForce GTS 250");
TEST_ASSERT(nResult3==0);
__TEST_CLEANUP__;
// Uninstall
crUninstall();
}
REGISTER_TEST(Test_crAddPropertyW);
void Test_crAddPropertyW()
{
// Should fail, because crInstall() should be called first
int nResult = crAddPropertyW(L"VideoAdapter", L"nVidia GeForce GTS 250");
TEST_ASSERT(nResult!=0);
// Install crash handler
CR_INSTALL_INFOW infoW;
memset(&infoW, 0, sizeof(CR_INSTALL_INFOW));
infoW.size = sizeof(CR_INSTALL_INFOW);
infoW.application_version = L"1.0.0"; // Specify app version, otherwise it will fail.
int nInstallResult = crInstallW(&infoW);
TEST_ASSERT(nInstallResult==0);
// Should fail, because property name is empty
int nResult2 = crAddPropertyW(L"", L"nVidia GeForce GTS 250");
TEST_ASSERT(nResult2!=0);
// Should succeed
int nResult3 = crAddPropertyW(L"VideoAdapter", L"nVidia GeForce GTS 250");
TEST_ASSERT(nResult3==0);
__TEST_CLEANUP__;
// Uninstall
crUninstall();
}
REGISTER_TEST(Test_crAddScreenshot);
void Test_crAddScreenshot()
{
// Should fail, because crInstall() should be called first
int nResult = crAddScreenshot(CR_AS_VIRTUAL_SCREEN);
TEST_ASSERT(nResult!=0);
// Install crash handler
CR_INSTALL_INFOW infoW;
memset(&infoW, 0, sizeof(CR_INSTALL_INFOW));
infoW.size = sizeof(CR_INSTALL_INFOW);
infoW.application_version = L"1.0.0"; // Specify app version, otherwise it will fail.
int nInstallResult = crInstallW(&infoW);
TEST_ASSERT(nInstallResult==0);
// Should succeed
int nResult2 = crAddScreenshot(CR_AS_VIRTUAL_SCREEN);
TEST_ASSERT(nResult2==0);
// Call twice - should succeed
int nResult3 = crAddScreenshot(CR_AS_MAIN_WINDOW);
TEST_ASSERT(nResult3==0);
__TEST_CLEANUP__;
// Uninstall
crUninstall();
}
REGISTER_TEST(Test_crAddScreenshot2);
void Test_crAddScreenshot2()
{
// Should fail, because crInstall() should be called first
int nResult = crAddScreenshot2(CR_AS_VIRTUAL_SCREEN, 95);
TEST_ASSERT(nResult!=0);
// Install crash handler
CR_INSTALL_INFOW infoW;
memset(&infoW, 0, sizeof(CR_INSTALL_INFOW));
infoW.size = sizeof(CR_INSTALL_INFOW);
infoW.application_version = L"1.0.0"; // Specify app version, otherwise it will fail.
int nInstallResult = crInstallW(&infoW);
TEST_ASSERT(nInstallResult==0);
// Should succeed
int nResult2 = crAddScreenshot2(CR_AS_VIRTUAL_SCREEN, 50);
TEST_ASSERT(nResult2==0);
// Call twice - should succeed
int nResult3 = crAddScreenshot2(CR_AS_MAIN_WINDOW, 60);
TEST_ASSERT(nResult3==0);
// Call with invalid JPEG quality - should fail
int nResult4 = crAddScreenshot2(CR_AS_MAIN_WINDOW, -60);
TEST_ASSERT(nResult4!=0);
// Call with invalid JPEG quality - should fail
int nResult5 = crAddScreenshot2(CR_AS_MAIN_WINDOW, 160);
TEST_ASSERT(nResult5!=0);
__TEST_CLEANUP__;
// Uninstall
crUninstall();
}
REGISTER_TEST(Test_crAddRegKeyA);
void Test_crAddRegKeyA()
{
// Should fail, because crInstall() should be called first
int nResult = crAddRegKeyA("HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows", "regkey.xml", 0);
TEST_ASSERT(nResult!=0);
// Install crash handler
CR_INSTALL_INFOA infoA;
memset(&infoA, 0, sizeof(CR_INSTALL_INFOA));
infoA.size = sizeof(CR_INSTALL_INFOA);
infoA.application_version = "1.0.0"; // Specify app version, otherwise it will fail.
int nInstallResult = crInstallA(&infoA);
TEST_ASSERT(nInstallResult==0);
// Should fail, because registry key name is NULL
int nResult2 = crAddRegKeyA(NULL, "regkey.xml", 0);
TEST_ASSERT(nResult2!=0);
// Should fail, because registry key name is empty
int nResult3 = crAddRegKeyA("", "regkey.xml", 0);
TEST_ASSERT(nResult3!=0);
// Should succeed
int nResult4 = crAddRegKeyA("HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows", "regkey.xml", 0);
TEST_ASSERT(nResult4==0);
// Should fail, because registry key doesn't exist
int nResult5 = crAddRegKeyA("HKEY_LOCAL_MACHINE\\Softweeere\\", "regkey.xml", 0);
TEST_ASSERT(nResult5!=0);
// Should fail, because registry key is a parent key
int nResult6 = crAddRegKeyA("HKEY_LOCAL_MACHINE\\", "regkey.xml", 0);
TEST_ASSERT(nResult6!=0);
__TEST_CLEANUP__;
// Uninstall
crUninstall();
}
REGISTER_TEST(Test_crAddRegKeyW);
void Test_crAddRegKeyW()
{
// Should fail, because crInstall() should be called first
int nResult = crAddRegKeyW(L"HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows", L"regkey.xml", 0);
TEST_ASSERT(nResult!=0);
// Install crash handler
CR_INSTALL_INFOW infoW;
memset(&infoW, 0, sizeof(CR_INSTALL_INFOW));
infoW.size = sizeof(CR_INSTALL_INFOW);
infoW.application_version = L"1.0.0"; // Specify app version, otherwise it will fail.
int nInstallResult = crInstallW(&infoW);
TEST_ASSERT(nInstallResult==0);
// Should fail, because registry key name is NULL
int nResult2 = crAddRegKeyW(NULL, L"regkey.xml", 0);
TEST_ASSERT(nResult2!=0);
// Should fail, because registry key name is empty
int nResult3 = crAddRegKeyW(L"", L"regkey.xml", 0);
TEST_ASSERT(nResult3!=0);
// Should succeed
int nResult4 = crAddRegKeyW(L"HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows", L"regkey.xml", 0);
TEST_ASSERT(nResult4==0);
// Should fail, because registry key doesn't exist
int nResult5 = crAddRegKeyW(L"HKEY_LOCAL_MACHINE\\Softweeere\\", L"regkey.xml", 0);
TEST_ASSERT(nResult5!=0);
// Should fail, because registry key is a parent key
int nResult6 = crAddRegKeyW(L"HKEY_LOCAL_MACHINE\\", L"regkey.xml", 0);
TEST_ASSERT(nResult6!=0);
__TEST_CLEANUP__;
// Uninstall
crUninstall();
}
REGISTER_TEST(Test_crGetLastErrorMsgA);
void Test_crGetLastErrorMsgA()
{
// Get error message before Install
char szErrMsg[256] = "";
int nResult = crGetLastErrorMsgA(szErrMsg, 256);
TEST_ASSERT(nResult>0);
// Install crash handler
CR_INSTALL_INFOA infoA;
memset(&infoA, 0, sizeof(CR_INSTALL_INFOA));
infoA.size = sizeof(CR_INSTALL_INFOA);
infoA.application_version = "1.0.0"; // Specify app version, otherwise it will fail.
int nInstallResult = crInstallA(&infoA);
TEST_ASSERT(nInstallResult==0);
// Get error message
char szErrMsg2[256] = "";
int nResult2 = crGetLastErrorMsgA(szErrMsg2, 256);
TEST_ASSERT(nResult2>0);
// Get error message to NULL buffer - must fail
int nResult3 = crGetLastErrorMsgA(NULL, 256);
TEST_ASSERT(nResult3<0);
// Get error message to a buffer, but zero length - must fail
char szErrMsg3[256] = "";
int nResult4 = crGetLastErrorMsgA(szErrMsg3, 0);
TEST_ASSERT(nResult4<0);
// Get error message to a single-char buffer, must trunkate message and succeed
char szErrMsg5[1] = "";
int nResult5 = crGetLastErrorMsgA(szErrMsg5, 1);
TEST_ASSERT(nResult5==0);
// Get error message to a small buffer, must trunkate message and succeed
char szErrMsg6[2] = "";
int nResult6 = crGetLastErrorMsgA(szErrMsg6, 2);
TEST_ASSERT(nResult6>0);
__TEST_CLEANUP__;
// Uninstall
crUninstall();
}
REGISTER_TEST(Test_crGetLastErrorMsgW);
void Test_crGetLastErrorMsgW()
{
// Get error message before Install
WCHAR szErrMsg[256] = L"";
int nResult = crGetLastErrorMsgW(szErrMsg, 256);
TEST_ASSERT(nResult>0);
// Install crash handler
CR_INSTALL_INFOW infoW;
memset(&infoW, 0, sizeof(CR_INSTALL_INFOW));
infoW.size = sizeof(CR_INSTALL_INFOW);
infoW.application_version = L"1.0.0"; // Specify app version, otherwise it will fail.
int nInstallResult = crInstallW(&infoW);
TEST_ASSERT(nInstallResult==0);
// Get error message
WCHAR szErrMsg2[256] = L"";
int nResult2 = crGetLastErrorMsgW(szErrMsg2, 256);
TEST_ASSERT(nResult2>0);
// Get error message to NULL buffer - must fail
int nResult3 = crGetLastErrorMsgW(NULL, 256);
TEST_ASSERT(nResult3<0);
// Get error message to a buffer, but zero length - must fail
WCHAR szErrMsg3[256] = L"";
int nResult4 = crGetLastErrorMsgW(szErrMsg3, 0);
TEST_ASSERT(nResult4<0);
// Get error message to a single-char buffer, must trunkate message and succeed
WCHAR szErrMsg5[1] = L"";
int nResult5 = crGetLastErrorMsgW(szErrMsg5, 1);
TEST_ASSERT(nResult5==0);
// Get error message to a small buffer, must trunkate message and succeed
WCHAR szErrMsg6[2] = L"";
int nResult6 = crGetLastErrorMsgW(szErrMsg6, 2);
TEST_ASSERT(nResult6>0);
__TEST_CLEANUP__;
// Uninstall
crUninstall();
}
REGISTER_TEST(Test_CrAutoInstallHelper);
void Test_CrAutoInstallHelper()
{
crash_report::CrAutoInstallHelper helper;
helper.set_application_version(_T("1.0.0"));
TEST_ASSERT(helper.Install()==0);
__TEST_CLEANUP__;
}
REGISTER_TEST(Test_CrThreadAutoInstallHelper);
DWORD WINAPI ThreadProc1(LPVOID lpParam)
{
// Install thread exception handlers
crash_report::CrThreadAutoInstallHelper cr_thread_install(0);
int* pnResult = (int*)lpParam;
*pnResult = cr_thread_install.result();
return 0;
}
void Test_CrThreadAutoInstallHelper()
{
// Install crash handler for the main thread
crash_report::CrAutoInstallHelper helper;
helper.set_application_version(_T("1.0.0"));
TEST_ASSERT(helper.Install()==0);
// Run a worker thread
int nResult = -1;
HANDLE hThread = CreateThread(NULL, 0, ThreadProc1, &nResult, 0, NULL);
// Wait until thread exits
WaitForSingleObject(hThread, INFINITE);
TEST_ASSERT(nResult==0);
__TEST_CLEANUP__;
}
REGISTER_TEST(Test_crEmulateCrash);
void Test_crEmulateCrash()
{
CString sAppDataFolder;
CString sExeFolder;
CString sTmpFolder;
// Test it with invalid argument - should fail
int nResult = crEmulateCrash((UINT)-1);
TEST_ASSERT(nResult!=0);
// Test it with invalid argument - should fail
int nResult2 = crEmulateCrash(CR_THROW+1);
TEST_ASSERT(nResult2!=0);
__TEST_CLEANUP__;
crUninstall();
// Delete tmp folder
Utility::RecycleFile(sTmpFolder, TRUE);
}
REGISTER_TEST(Test_crInstallToCurrentThread);
DWORD WINAPI ThreadProc2(LPVOID /*lpParam*/)
{
// Uninstall before install - should fail
int nUnResult = crUninstallFromCurrentThread();
TEST_ASSERT(nUnResult!=0);
// Install thread exception handlers - should succeed
int nResult = crInstallToCurrentThread();
TEST_ASSERT(nResult==0);
// Install thread exception handlers the second time - should fail
int nResult2 = crInstallToCurrentThread();
TEST_ASSERT(nResult2!=0);
__TEST_CLEANUP__;
// Uninstall - should succeed
crUninstallFromCurrentThread();
return 0;
}
void Test_crInstallToCurrentThread()
{
// Call before install - must fail
int nResult = crInstallToCurrentThread();
TEST_ASSERT(nResult!=0);
// Call before install - must fail
int nResult2 = crInstallToCurrentThread2(0);
TEST_ASSERT(nResult2!=0);
// Install crash handler for the main thread
CR_INSTALL_INFO info;
memset(&info, 0, sizeof(CR_INSTALL_INFO));
info.size = sizeof(CR_INSTALL_INFO);
info.application_version = _T("1.0.0"); // Specify app version, otherwise it will fail.
int nInstResult = crInstall(&info);
TEST_ASSERT(nInstResult==0);
// Call in the main thread - must fail
int nResult3 = crInstallToCurrentThread2(0);
TEST_ASSERT(nResult3!=0);
// Run a worker thread
HANDLE hThread = CreateThread(NULL, 0, ThreadProc2, NULL, 0, NULL);
// Wait until thread exits
WaitForSingleObject(hThread, INFINITE);
__TEST_CLEANUP__;
// Uninstall should succeed
crUninstall();
}
// This test runs several threads and installs/uninstalls exception handlers in
// them concurrently.
REGISTER_TEST(Test_crInstallToCurrentThread_concurrent);
DWORD WINAPI ThreadProc3(LPVOID /*lpParam*/)
{
int i;
for(i=0; i<100; i++)
{
// Install thread exception handlers - should succeed
int nResult = crInstallToCurrentThread();
TEST_ASSERT(nResult==0);
Sleep(10);
// Uninstall - should succeed
int nUnResult2 = crUninstallFromCurrentThread();
TEST_ASSERT(nUnResult2==0);
}
__TEST_CLEANUP__;
crUninstallFromCurrentThread();
return 0;
}
void Test_crInstallToCurrentThread_concurrent()
{
// Install crash handler for the main thread
CR_INSTALL_INFO info;
memset(&info, 0, sizeof(CR_INSTALL_INFO));
info.size = sizeof(CR_INSTALL_INFO);
info.application_version = _T("1.0.0"); // Specify app version, otherwise it will fail.
int nInstResult = crInstall(&info);
TEST_ASSERT(nInstResult==0);
// Run a worker thread
HANDLE hThread = CreateThread(NULL, 0, ThreadProc3, NULL, 0, NULL);
// Run another worker thread
HANDLE hThread2 = CreateThread(NULL, 0, ThreadProc3, NULL, 0, NULL);
// Run the third worker thread
HANDLE hThread3 = CreateThread(NULL, 0, ThreadProc3, NULL, 0, NULL);
// Wait until threads exit
WaitForSingleObject(hThread, INFINITE);
WaitForSingleObject(hThread2, INFINITE);
WaitForSingleObject(hThread3, INFINITE);
__TEST_CLEANUP__;
// Uninstall
crUninstall();
}
REGISTER_TEST(Test_crGenerateErrorReport);
void Test_crGenerateErrorReport()
{
CString sAppDataFolder;
CString sExeFolder;
CString sTmpFolder;
// Create a temporary folder
Utility::GetSpecialFolder(CSIDL_APPDATA, sAppDataFolder);
sTmpFolder = sAppDataFolder+_T("\\CrashRpt");
BOOL bCreate = Utility::CreateFolder(sTmpFolder);
TEST_ASSERT(bCreate);
// Install crash handler for the main thread
CR_INSTALL_INFO info;
memset(&info, 0, sizeof(CR_INSTALL_INFO));
info.size = sizeof(CR_INSTALL_INFO);
info.application_version = _T("1.0.0"); // Specify app version, otherwise it will fail.
info.flags = CR_INST_NO_GUI|CR_INST_DONT_SEND_REPORT;
info.save_dir = sTmpFolder;
int nInstResult = crInstall(&info);
TEST_ASSERT(nInstResult==0);
// Call with NULL parameter - should fail
int nResult = crGenerateErrorReport(NULL);
TEST_ASSERT(nResult!=0);
// Call with valid parameter - should succeed
CR_EXCEPTION_INFO exc;
memset(&exc, 0, sizeof(CR_EXCEPTION_INFO));
exc.cb = sizeof(CR_EXCEPTION_INFO);
int nResult2 = crGenerateErrorReport(&exc);
TEST_ASSERT(nResult2==0);
// Check that a folder with crash report files exists
WIN32_FIND_DATA fd;
HANDLE hFind = FindFirstFile(sTmpFolder+_T("\\*"), &fd);
FindClose(hFind);
TEST_ASSERT(hFind!=INVALID_HANDLE_VALUE && hFind!=NULL);
__TEST_CLEANUP__;
// Uninstall
crUninstall();
// Delete tmp folder
Utility::RecycleFile(sTmpFolder, TRUE);
}
#ifndef CRASHRPT_LIB
// Test that API function names are undecorated
REGISTER_TEST(Test_undecorated_func_names);
void Test_undecorated_func_names()
{
HMODULE hCrashRpt = NULL;
// Load crash_report.dll dynamically
#ifdef _DEBUG
hCrashRpt = LoadLibrary(_T("crash_reportd.dll"));
#else
hCrashRpt = LoadLibrary(_T("crash_report.dll"));
#endif
TEST_ASSERT(hCrashRpt!=NULL);
typedef int (WINAPI *PFNCRINSTALLA)(PCR_INSTALL_INFOA);
PFNCRINSTALLA pfncrInstallA = (PFNCRINSTALLA)GetProcAddress(hCrashRpt, "crInstallA");
TEST_ASSERT(pfncrInstallA!=NULL);
typedef int (WINAPI *PFNCRINSTALLW)(PCR_INSTALL_INFOW);
PFNCRINSTALLW pfncrInstallW = (PFNCRINSTALLW)GetProcAddress(hCrashRpt, "crInstallW");
TEST_ASSERT(pfncrInstallW!=NULL);
typedef int (WINAPI *PFNCRUNINSTALL)();
PFNCRUNINSTALL pfncrUninstall = (PFNCRUNINSTALL)GetProcAddress(hCrashRpt, "crUninstall");
TEST_ASSERT(pfncrUninstall!=NULL);
typedef int (WINAPI *PFNCRINSTALLTOCURRENTTHREAD)();
PFNCRINSTALLTOCURRENTTHREAD pfncrInstallToCurrentThread =
(PFNCRINSTALLTOCURRENTTHREAD)GetProcAddress(hCrashRpt, "crInstallToCurrentThread");
TEST_ASSERT(pfncrInstallToCurrentThread!=NULL);
typedef int (WINAPI *PFNCRINSTALLTOCURRENTTHREAD2)();
PFNCRINSTALLTOCURRENTTHREAD2 pfncrInstallToCurrentThread2 =
(PFNCRINSTALLTOCURRENTTHREAD2)GetProcAddress(hCrashRpt, "crInstallToCurrentThread2");
TEST_ASSERT(pfncrInstallToCurrentThread2!=NULL);
typedef int (WINAPI *PFNCRUNINSTALLFROMCURRENTTHREAD)();
PFNCRUNINSTALLFROMCURRENTTHREAD pfncrUninstallFromCurrentThread =
(PFNCRINSTALLTOCURRENTTHREAD)GetProcAddress(hCrashRpt, "crUninstallFromCurrentThread");
TEST_ASSERT(pfncrUninstallFromCurrentThread!=NULL);
typedef int (WINAPI *PFNCRADDFILEW)(const wchar_t*, const wchar_t*);
PFNCRADDFILEW pfncrAddFileW =
(PFNCRADDFILEW)GetProcAddress(hCrashRpt, "crAddFileW");
TEST_ASSERT(pfncrAddFileW!=NULL);
typedef int (WINAPI *PFNCRADDFILEA)(const char*, const char*);
PFNCRADDFILEA pfncrAddFileA =
(PFNCRADDFILEA)GetProcAddress(hCrashRpt, "crAddFileA");
TEST_ASSERT(pfncrAddFileA!=NULL);
typedef int (WINAPI *PFNCRADDFILE2W)(const wchar_t*, const wchar_t*);
PFNCRADDFILE2W pfncrAddFile2W =
(PFNCRADDFILE2W)GetProcAddress(hCrashRpt, "crAddFile2W");
TEST_ASSERT(pfncrAddFile2W!=NULL);
typedef int (WINAPI *PFNCRADDFILE2A)(const char*, const char*);
PFNCRADDFILE2A pfncrAddFile2A =
(PFNCRADDFILE2A)GetProcAddress(hCrashRpt, "crAddFile2A");
TEST_ASSERT(pfncrAddFile2A!=NULL);
typedef int (WINAPI *PFNCRADDSCREENSHOT)(DWORD);
PFNCRADDSCREENSHOT pfncrAddScreenshot =
(PFNCRADDSCREENSHOT)GetProcAddress(hCrashRpt, "crAddScreenshot");
TEST_ASSERT(pfncrAddScreenshot!=NULL);
typedef int (WINAPI *PFNCRADDSCREENSHOT2)(DWORD, int);
PFNCRADDSCREENSHOT2 pfncrAddScreenshot2 =
(PFNCRADDSCREENSHOT2)GetProcAddress(hCrashRpt, "crAddScreenshot2");
TEST_ASSERT(pfncrAddScreenshot2!=NULL);
__TEST_CLEANUP__
FreeLibrary(hCrashRpt);
}
#endif //!CRASHRPT_LIB | [
"[email protected]@9307afbf-8b4c-5d34-949b-c69a0924eb0b"
] | [
[
[
1,
933
]
]
] |
f4ffb9b22d2f864df9a93681aa294fc7f0cd8786 | 0c5fd443401312fafae18ea6a9d17bac9ee61474 | /code/engine/EventSystem/Core/ThreadingPolicy.cpp | 332923eeadf74fe8d8ef27b7b9d93cb4c57b1d1e | [] | no_license | nurF/Brute-Force-Game-Engine | fcfebc997d6ab487508a5706b849e9d7bc66792d | b930472429ec6d6f691230e36076cd2c868d853d | refs/heads/master | 2021-01-18T09:29:44.038036 | 2011-12-02T17:31:59 | 2011-12-02T17:31:59 | 2,877,061 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,462 | cpp | /* ___ _________ ____ __
/ _ )/ __/ ___/____/ __/___ ___ _/_/___ ___
/ _ / _// (_ //___/ _/ / _ | _ `/ // _ | -_)
/____/_/ \___/ /___//_//_|_, /_//_//_|__/
/___/
This file is part of the Brute-Force Game Engine, BFG-Engine
For the latest info, see http://www.brute-force-games.com
Copyright (c) 2011 Brute-Force Games GbR
The BFG-Engine 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.
The BFG-Engine 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 the BFG-Engine. If not, see <http://www.gnu.org/licenses/>.
*/
#include <EventSystem/Core/ThreadingPolicy.h>
#include <Base/NameCurrentThread.h>
#include <EventSystem/Core/EventLoop.h>
namespace EventSystem {
void eventEntryHelper(IEventLoop* loop)
{
loop->entry();
}
void eventEntryHelperNamed(const std::string& name, IEventLoop* loop)
{
BFG::nameCurrentThread(name);
loop->entry();
}
} //namespace EventSystem
| [
"[email protected]"
] | [
[
[
1,
46
]
]
] |
e7a8dbb7760185d454dc4c950454a43184d0c0cb | 30e4267e1a7fe172118bf26252aa2eb92b97a460 | /code/pkg_Example/Modules/MFCExtTempl/Module.cpp | 3ca6e4250de4c2a73a21aebe504950a2796d3e51 | [
"Apache-2.0"
] | permissive | thinkhy/x3c_extension | f299103002715365160c274314f02171ca9d9d97 | 8a31deb466df5d487561db0fbacb753a0873a19c | refs/heads/master | 2020-04-22T22:02:44.934037 | 2011-01-07T06:20:28 | 2011-01-07T06:20:28 | 1,234,211 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 235 | cpp | #include "stdafx.h"
#include <afxdllx.h>
#include <XModuleMacro.h>
#include <XModuleImpl.h>
#include "Cx_Example2.h"
XBEGIN_DEFINE_MODULE()
XDEFINE_CLASSMAP_ENTRY(CLSID_Example, Cx_Example2)
XEND_DEFINE_MODULE_MFCEXTDLL()
| [
"rhcad1@71899303-b18e-48b3-b26e-8aaddbe541a3"
] | [
[
[
1,
10
]
]
] |
541bf84d759bea49f83bd0b6241d335b75a476c0 | 3da0b0276bc8c3d7d1bcdbabfb0e763a38d3a24c | /zju.finished/1246.cpp | f80cdd411d5781ce34b50a2087b603f768aeb253 | [] | no_license | usherfu/zoj | 4af6de9798bcb0ffa9dbb7f773b903f630e06617 | 8bb41d209b54292d6f596c5be55babd781610a52 | refs/heads/master | 2021-05-28T11:21:55.965737 | 2009-12-15T07:58:33 | 2009-12-15T07:58:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,400 | cpp | #include<iostream>
#include<vector>
using namespace std;
// Wrong Answer
struct Node {
int c, e; // c是系数, e是指数
bool operator<(const Node&rhs)const{
return e>rhs.e;
}
};
char buf[100];
void output(vector<Node> &pro){
if(pro.size() == 0){
printf("0\n");
return;
}
for(int i=0; i<pro.size(); i++){
if(i) printf("+");
if(pro[i].e >= 2){
if(pro[i].c > 1){
printf("%d*",pro[i].c);
}
printf("n^%d", pro[i].e);
}else if(pro[i].e == 1){
if(pro[i].c > 1){
printf("%d*",pro[i].c);
}
printf("n");
} else {// e == 0
printf("%d", pro[i].c);
}
}
printf("\n");
}
void update_e(vector<Node> &v){
for(int i=0; i<v.size(); i++){
v[i].e++;
}
}
void update_c(int t, vector<Node> &v){
for(int i=0; i<v.size(); i++){
v[i].c *= t;
}
}
void combine(vector<Node> &r){
vector<Node> v;
Node one;
scanf("%s", buf);
while(buf[0] != 'E'){
if(strcmp(buf, "LOOP") == 0){
scanf("%s", buf);
v.clear();
if(buf[0] == 'n'){ // affect e
combine(v);
update_e(v);
} else { // affect c
int t = atoi(buf);
combine(v);
update_c(t, v);
}
while(v.size()){
r.push_back(v.back());
v.pop_back();
}
} else { // OP
scanf("%s", buf);
one.c = atoi(buf);
one.e = 0;
r.push_back(one);
}
scanf("%s", buf);
}
sort(r.begin(), r.end());
int i=0, s=0;
for( ; s<r.size(); s++){
if(r[s].c == 0) continue;
if(i == 0 || r[s].e != r[i-1].e){
r[i++] = r[s];
} else {
r[i-1].c += r[s].c;
}
}
while(r.size() > i){
r.pop_back();
}
}
int main(){
int tst=0, tstnum;
vector<Node> pro;
scanf("%d", &tstnum);
while(tst++ < tstnum){
scanf("%s", buf);
printf("Program #%d\nRuntime = ", tst);
pro.clear();
combine(pro);
output(pro);
printf("\n");
}
return 0;
}
| [
"[email protected]"
] | [
[
[
1,
102
]
]
] |
ea035d6da3139c9da5e67be2c80593c95bd81f20 | 51c71b06d7fa1aa97df4ffe6782e9a4924480a33 | /Calibration/CameraManager.h | 6cddff60f90c8ae6db411269c89cf6c4b2b6c5b4 | [] | no_license | alonf01/open-light | 9eb8d185979cfa16797f9d2201cf192b3e91f270 | 685f974fcd7cc29b6bec00fa17804c5f2b7a83c3 | refs/heads/master | 2020-05-30T15:24:08.579565 | 2010-12-14T00:56:32 | 2010-12-14T00:56:32 | 35,759,673 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,195 | h | ////////////////////////////////////////////////////////////////////////////////////////////////////
// file: Calibration\CameraManager.h
//
// summary: Abstracted Camera SDK Interface Class.
// Virtual class that defines the interfaces for managing camera SDKs
//
// Brett Jones & Rajinder Sodhi 2010
////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma once
#include "Common.h"
#include "Camera.h"
#include "CameraConfigParams.h"
////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary> Virtual class that defines the interfaces for managing camera SDKs. </summary>
////////////////////////////////////////////////////////////////////////////////////////////////////
class CameraManager
{
public:
////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary> Initialises this object. </summary>
////////////////////////////////////////////////////////////////////////////////////////////////////
virtual void Init(CameraConfigParams* camParams) = 0;
////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary> Clean up all resources. </summary>
////////////////////////////////////////////////////////////////////////////////////////////////////
virtual void CleanUp() = 0;
////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary> Gets the valid cameras list. </summary>
///
/// <returns> null if it fails, else the cameras. </returns>
////////////////////////////////////////////////////////////////////////////////////////////////////
std::vector<Camera*> GetCameras()
{ return mCameras; };
protected:
/// <summary> A list of all cameras. </summary>
std::vector<Camera*> mCameras;
/// <summary> Did the SDK load correctly. </summary>
bool mIsLoaded;
/// <summary> Camera configuration parameters </summary>
CameraConfigParams* mCamParams;
};
| [
"b.jonessoda@8a600b9a-ddf7-11de-b878-c5ec750a8c44"
] | [
[
[
1,
49
]
]
] |
0e2db0a4be21b3e9e9d381ca7f0321f0f1dcb8b0 | 15e150276fe80a4a50c77826fad0270d87ffc706 | /ukol2/src/main.cpp | 897cefd0be9a203942a53614ae4040e9de137ebb | [] | no_license | dk1844/fit-par-batoh-ws2010 | 50c23b29ba86b3a45946858968d190550e488e87 | cb4b229c636019a533127ff01e05adcf5eed3154 | refs/heads/master | 2021-03-12T19:22:53.479227 | 2010-12-15T20:21:24 | 2010-12-15T20:21:24 | 32,389,454 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 26,700 | cpp | /*
* File: main.cpp
* Author: Daniel Kavan
*
* Created on 30. září 2010, 18:29
*
*
*
* **PERKS**
*
* * the current value of a bag used to be calculated when expanding (just as volume is).
* This has been changed, bc. we can save the time for computing value for variations of contents that are cut by the BB algorithm
* * Old way, how we stored nodes in stack was implemented using int data type.
* We change it to bit representation -> we use char instead of int and use every bit of char to
* signify, if the item is presented or not
* We save a lot of memory -> int: 4bytes/item
* char(with bit rep.) 1bit/item
*/
#include <cstdlib>
#include <stack>
#include "NodeStack.h"
#include <vector>
#include <iostream> // I/O
#include <fstream> // file I/O
#include <iomanip> // format manipulation
#include <string>
#include <stdio.h>
#include <string.h>
#include <sstream>
#include "mpi.h"
#include "Node.h"
#include "NodeStack.h"
#define LENGTH 5000
#define STACKTYPE NodeStack::BEHAVIOR_STACK
#define CHECK_MSG_AMOUNT 100
//tags
#define MSG_INIT_WORK 100 //INIT: init prace
#define MSG_INIT_NO_WORK 103 //INIT: Neni prace, malo vstupnich dat
#define MSG_WORK_REQUEST 200 //REQ: zadost o praci
#define MSG_WORK_SENT 202 //ANS: posilam cast zasobniku (praci)
#define MSG_WORK_NOWORK 203 //ANS: neni prace
#define MSG_TOKEN_WHITE 300 //: pesek a dal TBD
#define MSG_TOKEN_BLACK 301
#define MSG_FINISH 400 //: Ukoncuji
#define MSG_MY_BEST 401 //: "Send me your best"
#define MSG_TERMINATE 401 //
using namespace std;
// global variables
NodeStack stack1;
int process_rank = 0;
int processes = 5;
char message[LENGTH];
int donator_next;
MPI_Status status;
Node best; // containing the right-now best leaf node.
float bestValue = 0;
int locals_received_count = 0;
int bufS = LENGTH;
bool im_done_too;
//declare vectors for input data
vector<float> volumes;
vector<float> values;
float bagSize;
int items_count;
int citac = 0; //
bool finished = false;
bool p0_token_already_sent = false;
//this falg will be used to hadle ADUV
bool data_given_to_next = false;
bool waiting_for_data = false;
bool token_received = false;
int max_data_requests = 0;
int no_failed_data_req = 0;
bool printDebug = false;
//stack<Node> stack1;
/**
* Print the content of a vecor
* @param vect1 pointer to a vector
* @param name optional title
*/
template<class T> void printVector(vector<T> * vect1, char * name = "") {
if (name != "") {
cout << "Vector \"" << name << "\" content:" << endl;
} else {
cout << "Vector content:" << endl;
}
for (int b = 0; b < (* vect1).size(); b++) {
cout << (*vect1)[b] << " ";
}
cout << endl;
}
bool unpackMessage(char * buffer, int buffS) {
string msgTemp;
string serial;
int bufferSize = buffS;
serial.clear();
serial = buffer;
string tmp;
int emprTagPosition = 0;
int endTagPosition = 0;
Node akt;
//start of file... we check, if the & is present here and remove it
tmp = serial.substr(0, 1);
//todo, handle, if there is no end tag
endTagPosition = serial.find("&&");
serial = serial.substr(1, serial.length());
if (tmp.compare("&") != 0 || endTagPosition == -1) {
// message doesnt contains valid data
return false;
} else {
//remove first &
while (endTagPosition != emprTagPosition) {
emprTagPosition = serial.find("&");
endTagPosition = serial.find("&&");
msgTemp = serial.substr(0, emprTagPosition + 1);
serial = serial.substr(emprTagPosition + 1, serial.length());
akt.deserialize(msgTemp.c_str(), bufferSize);
stack1.push(akt);
}
}
return true;
}
void generateMessage(char * buffer, int bufferSize) {
char message[bufferSize];
stringstream sstr;
Node akt = stack1.top();
//get maximum number of nodes to send
//this value will be between number of items and half of the nodes in stack
int noItems = akt.getItemsCount();
int halfOfStack = stack1.size() / 2;
int itemsAdded = 0;
int itemsToBeAdded = 0;
int msgLenght = 0;
int msgBuffer = 0;
// generally, we will send same number of nodes as items count
//if there is not enough nodes in stack, we will send on hlaf of stack
if (halfOfStack < noItems) {
itemsToBeAdded = halfOfStack;
} else {
itemsToBeAdded = noItems;
}
sstr.clear();
sstr.flush();
//cout << "P" << process_rank << ": generating message: halfOfStack:" << halfOfStack << " :itemsToBeAdded: " << itemsToBeAdded << endl;
//insert number of Nodes in message
//sstr << "&&" << stack1.size() << "&";
for (int i = 0; i <= itemsToBeAdded; i++) {
akt = stack1.top();
akt.serialize(message, msgBuffer);
//if my msg is smaller than free space in buffer, add it
// -2 is saving space for last &&, which is signalizeing end of buffer
if (msgBuffer + 1 < bufferSize - msgLenght - 2) {
sstr << "&" << message;
stack1.pop();
msgLenght += strlen(message) + 1;
} else {
//cout << "P" << process_rank << ": Buffer is small:" << bufferSize << ":msgBuffer: " << msgBuffer << ": msgLength " << msgLenght << endl;
break;
}
}
sstr << "&&";
//cout << "P" << process_rank << ": messageGenerated:" << buffer << endl;
string res = sstr.str();
bufferSize = res.length();
strcpy(buffer, res.c_str());
}
/**
* Loads data from filename into vectors volume and value
* @param filename name of the file loading
* @param volume vector containing floats with volumes
* @param value vector containing floats with values
*/
void loadDataFromFile(char * filename, int * items_cnt, vector<float> * volume, vector<float> * value, float * bagSize, int pid) {
ifstream fp_in; // declarations of stream fp_in
fp_in.open(filename, ios::in); // open the streams
//cout << fp_in << endl;
if (!fp_in) {
cerr << "P" << pid << ":File could not be opened" << endl;
MPI_Finalize();
exit(1);
}
int count;
float float_val;
// get number of intems
fp_in >> count; // input from file pointer or standard input
if (!fp_in.good()) {
cerr << "Wrong format" << endl;
MPI_Finalize();
exit(1);
}
(*items_cnt) = count;
//get size of back
fp_in >> float_val; // input from file pointer or standard input
if (!fp_in.good()) {
cerr << "Wrong format" << endl;
MPI_Finalize();
exit(1);
}
(*bagSize) = float_val;
(*volume).resize(count);
(*value).resize(count);
if (printDebug) cout << "P" << pid << ": Loading data: (2x" << count << " values)." << endl;
for (int i = 0; i < count; i++) {
fp_in >> float_val;
if (!fp_in.good()) {
cerr << "Wrong format inside" << endl;
MPI_Finalize();
exit(1);
}
(*volume)[i] = float_val;
fp_in >> float_val;
if (!fp_in.good()) {
cerr << "Wrong format inside" << endl;
MPI_Finalize();
exit(1);
}
(*value)[i] = float_val;
}
float dummy;
fp_in >> dummy;
if (!fp_in.eof()) {
cerr << "WARNING: file should have ended, skipping the rest.." << endl;
// MPI_Finalize();
// exit(1);
}
fp_in.close(); // close the streams
}
/**
*
* @param bestValue pointer to value of best actual solution
* @param root - node, which will be solved
* @param best - best node we found
* @param bagSize - pointer to bagSize
* @param volumes - pointer to volumes vector
* @param values - pointer to values vector
* @param stack1 - pointer to stack 0 we will add new nodes using this
* @param items_count - # of items
*/
void procedeNode(float * bestValue, Node root, Node * best, float * bagSize, vector<float> * volumes, vector<float> * values, NodeStack * stack1, int items_count) {
if (root.isExpandable()) {
Node a;
Node b;
root.expand(&a, &b, volumes);
// predmet nepridan, takze a je urcite perspektivni.
(*stack1).push(a);
//b se jeste vejde?
if (b.getCurrentVolume() > (*bagSize)) {
} else {
(*stack1).push(b);
}
} else {
//je akt lepsim resenim?
float aktValue = root.calculateValue(values);
if ((*bestValue) <= aktValue) { //if equal, doent matter, just making sure, when e.g. the bag is too small and the solution si the bag with <0,0, .. ,0,0>
(*best) = root;
(*bestValue) = aktValue;
}
}
}
/**
* Stack division for all processes
* @param volumes vector of volumes
* @param stack1 the stack
* @param bagSize size of the bag
* @param processes !important # processes to divide into
* @return true if succesfully divided (ready for parallel), false for too little data for this many processors => serial job.
*/
bool initDivide(vector<float> * volumes, NodeStack * stack1, float bagSize, int processes) {
//bool initDivide(vector<float> * volumes, stack<Node> * stack1, float bagSize, int processes) {
if (processes == 1) return false;
while ((*stack1).size() < processes && !(*stack1).empty()) {
Node akt = (*stack1).top();
(*stack1).pop(); //remove top
if (akt.isExpandable()) {
Node a, b;
akt.expand(&a, &b, volumes);
(*stack1).push(a);
if (b.getCurrentVolume() > bagSize) {
if (printDebug) cout << "DEBUG=pre0: Volume of " << b.getCurrentVolume() << " would be too much, cutting BB-branch" << endl;
} else {
(*stack1).push(b);
}
} else {
if (printDebug) cout << "P0:Data too small -> serial job." << endl;
return false; //only p0 solving!
}
}
return true; //parallel ok
}
void receiveMessage() {
//blocking receive
bool check_next_message = true;
Node thisProot(items_count);
while (check_next_message) {
MPI_Recv(message, LENGTH, MPI_CHAR, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
switch (status.MPI_TAG) {
case MSG_WORK_REQUEST: // zadost o praci, prijmout a dopovedet
// zaslat rozdeleny zasobnik a nebo odmitnuti MSG_WORK_NOWORK
if (printDebug) cout << "P" << process_rank << ": WORK_REQUEST_RECEIVED from P" << status.MPI_SOURCE << endl;
//if my stack is empty or if it has only one value, send no_work_request
if (stack1.size() < 2) {
//if(!stack1.empty()){
MPI_Send(message, strlen(message) + 1, MPI_CHAR, status.MPI_SOURCE, MSG_WORK_NOWORK, MPI_COMM_WORLD);
} else {
// Node akt = stack1.top();
// stack1.pop(); //remove top
// akt.serialize(message, bufS);
generateMessage(message, bufS);
MPI_Send(message, strlen(message) + 1, MPI_CHAR, status.MPI_SOURCE, MSG_WORK_SENT, MPI_COMM_WORLD);
if (process_rank > status.MPI_SOURCE) {
data_given_to_next = true;
}
}
break;
case MSG_WORK_SENT: // prisel rozdeleny zasobnik, prijmout
// deserializovat a spustit vypocet
if (printDebug) cout << "P" << process_rank << ":Data received from P" << status.MPI_SOURCE << ": message:" << message << endl;
unpackMessage(message, bufS);
//put my root to stack
//thisProot.deserialize(message, bufS);
//put my root to stack
//stack1.push(thisProot);
//I have new data so I can start calculation again
waiting_for_data = false;
//erase counter of unseccessful tries for data
no_failed_data_req = 0;
break;
case MSG_WORK_NOWORK: // odmitnuti zadosti o praci
// zkusit jiny proces
// a nebo se prepnout do pasivniho stavu a cekat na token
if (printDebug) cout << "P" << process_rank << ":NO WORK Received from from P" << status.MPI_SOURCE << ":" << " Request for work sent to P" << donator_next << endl;
//there is only limited unsuccessful requests for work
if (max_data_requests >= no_failed_data_req) {
MPI_Send(message, strlen(message) + 1, MPI_CHAR, donator_next, MSG_WORK_REQUEST, MPI_COMM_WORLD);
waiting_for_data = true;
no_failed_data_req++;
//calculation of next donator
donator_next = (donator_next + 1) % processes;
//prohibit to ask myself for work
if (donator_next == process_rank) {
donator_next = (donator_next + 1) % processes;
}
} else {
if (printDebug) cout << "P" << process_rank << ": I cannot ask for other work... waiting" << endl;
}
break;
case MSG_TOKEN_WHITE:
case MSG_TOKEN_BLACK: //ukoncovaci token, prijmout a nasledne preposlat
// - bily nebo cerny v zavislosti na stavu procesu
int msgToSend;
if (process_rank != 0) {
//MPI_Recv(&message, LENGTH, MPI_CHAR, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
//if i sent data to another proces, I need to send black token and reset data_given flG
if (data_given_to_next) {
msgToSend = MSG_TOKEN_BLACK;
data_given_to_next = false;
} else {
//If iam white I dont care about token value and send it to next P
msgToSend = status.MPI_TAG;
}
if (printDebug) cout << "P" << process_rank << ": TOKEN SENT:" << msgToSend << endl;
MPI_Send(message, strlen(message) + 1, MPI_CHAR, (process_rank + 1) % processes, msgToSend, MPI_COMM_WORLD);
} else {
//this is zero, received token and..
//MPI_Recv(&message, LENGTH, MPI_CHAR, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
//is it over?
if (status.MPI_TAG == MSG_TOKEN_WHITE) {
//its over.
// I can quit calculation loop
finished = true;
} else {
//someone was black. do yet another round.
MPI_Send(message, strlen(message) + 1, MPI_CHAR, (process_rank + 1) % processes, MSG_TOKEN_WHITE, MPI_COMM_WORLD);
}
}
break;
case MSG_FINISH: //konec vypoctu - proces 0 pomoci tokenu zjistil, ze jiz nikdo nema praci
//a rozeslal zpravu ukoncujici vypocet
//mam-li reseni, odeslu procesu 0
//nasledne ukoncim spoji cinnost
//jestlize se meri cas, nezapomen zavolat koncovou barieru MPI_Barrier (MPI_COMM_WORLD)
if (process_rank != 0) {
cout << "P" << process_rank << ":" << "LOCAL best value is: " << bestValue << "." << endl;
//best.print(process_rank);
} else {
cerr << "P" << process_rank << ":" << "P0 should never receive MSG_FINISH!" << endl;
}
//best mam.
best.serialize(message, bufS);
if (printDebug) cout << "P" << process_rank << ":" << " sending my best to P0!" << endl;
MPI_Send(message, strlen(message) + 1, MPI_CHAR, 0, MSG_MY_BEST, MPI_COMM_WORLD);
MPI_Barrier(MPI_COMM_WORLD);
MPI_Finalize();
exit(0);
break;
case MSG_MY_BEST:
if (process_rank == 0) {
// receive and try to figure out, who's the best..
if (printDebug) cout << "P" << process_rank << ":FINALE received: " << message << " from P" << status.MPI_SOURCE << endl;
Node akt;
akt.deserialize(message, bufS);
//is akt better than my best?
if (akt.calculateValue(&values) > bestValue) {
best = akt;
bestValue = best.calculateValue(&values);
//cout << "P0: best changed to " << bestValue << endl;
if (printDebug) best.print(process_rank);
}
} else {
cerr << "P" << process_rank << ":" << "Pnot0 should never receive MSG_MY_BEST!" << endl;
}
locals_received_count++;
//did everything call home?
if (locals_received_count == processes - 1) {
finished = true;
}
break;
default:
cerr << "unrecognized message type" << endl;
break;
}
//if I dont need to wait for the data, I can return to counting
if (waiting_for_data == false) {
check_next_message = false;
}
//if im P0 and calculation is over, so ia dont care about waiting for data
if (process_rank == 0 && finished == true) {
check_next_message = false;
}
}
}
bool checkInput(int * argc, char *** argv) {
//this is how to use it :)
//cout << (* argc) << endl;
//cout << (* argv)[0] ;
int ac = (*argc);
bool isDebug = false;
if (ac < 2 || ac > 3) {
cerr << "Incorrect number of arguments!" << endl;
cerr << "USAGE : " << (*argv)[0] << " <filename> [--debug]" << endl;
exit(1);
MPI_Finalize();
}
if (ac == 3) {
isDebug = (strcmp((*argv)[2], "--debug") == 0); // match?
if (!isDebug) {
cerr << "Incorrect argments!" << endl;
cerr << "USAGE : " << (*argv)[0] << " <filename> [--debug]" << endl;
exit(2);
MPI_Finalize();
}
}
return isDebug;
}
int main(int argc, char** argv) {
/**/
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &process_rank);
MPI_Comm_size(MPI_COMM_WORLD, &processes);
//check arguments
printDebug = checkInput(&argc, &argv);
double t1 = 0;
sprintf(message, "There are %d processes.\n", processes); //==message
if (process_rank == 0) {
printf("P%d:%s", process_rank, message); //P0 saying how many processes there are
MPI_Barrier(MPI_COMM_WORLD);
t1 = MPI_Wtime();
}
donator_next = (process_rank + 1) % processes;
max_data_requests = processes / 2;
stack1.setBehavior(STACKTYPE);
if (process_rank == 0) {
stack1.printStackBehavior();
}
//load source date from file
loadDataFromFile(argv[1], &items_count, &volumes, &values, &bagSize, process_rank);
//whether to run parallel
bool isParallel;
Node thisProot(items_count);
if (process_rank == 0) {
// try to divide
stack1.push(thisProot);
stack1.setBehavior(NodeStack::BEHAVIOR_QUEUE);
printf("for init division purposes:");
stack1.printStackBehavior();
isParallel = initDivide(&volumes, &stack1, bagSize, processes);
stack1.setBehavior(NodeStack::BEHAVIOR_STACK);
stack1.printStackBehavior();
}
if (process_rank == 0) {
if (isParallel) {
if (printDebug) cout << "P0:processes expanded to #" << stack1.size() << endl;
for (int i = 1; i < processes; i++) {
Node akt = stack1.top();
stack1.pop(); //remove top
int bufS = LENGTH;
akt.serialize(message, bufS);
MPI_Send(message, strlen(message) + 1, MPI_CHAR, i, MSG_INIT_WORK, MPI_COMM_WORLD);
}
} else {
if (processes != 1) {
//not parallel
for (int i = 1; i < processes; i++) {
MPI_Send(message, strlen(message) + 1, MPI_CHAR, i, MSG_INIT_NO_WORK, MPI_COMM_WORLD);
}
}
}
} else {
//procesor not 0 - Pi is waiting for work from P0
MPI_Barrier(MPI_COMM_WORLD);
MPI_Recv(message, LENGTH, MPI_CHAR, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
if (status.MPI_TAG == MSG_INIT_WORK) {
if (printDebug) cout << "P" << process_rank << ": received: " << message << endl;
if (printDebug) cout << "P" << process_rank << ": Starting calculation" << endl;
//data recieved from P0, I can start with calculation
isParallel = true;
int BS = LENGTH;
//take data from message
thisProot.deserialize(message, BS);
//put my root to stack
stack1.push(thisProot);
} else if (status.MPI_TAG == MSG_INIT_NO_WORK) {
//there is no work for me, i can go to the pub and take some beers...
isParallel = false;
cout << "P" << process_rank << ": serial job = i'm done." << endl;
MPI_Finalize();
return 0;
} else {
//unexpected message
cerr << "P" << process_rank << ": init msg error" << endl;
}
}
//init done.
//controls for paralel program
int flag;
//PID of next donator of data. Need to be init after creating of proceses
if (printDebug) cout << "P" << process_rank << ": My next donator:" << donator_next << endl;
if (isParallel) { /**/
while (!finished) //ukoncime jen, kdyz bude stack prazdny a finished true.
{
//work...
if (!stack1.empty()) {
Node akt = stack1.top();
stack1.pop(); //remove top
procedeNode(&bestValue, akt, &best, &bagSize, &volumes, &values, &stack1, items_count);
} else {
// if iam p0, and i havent sent token yet, do it now.
if (process_rank == 0 && p0_token_already_sent == false) {
MPI_Send(message, strlen(message) + 1, MPI_CHAR, (process_rank + 1) % processes, MSG_TOKEN_WHITE, MPI_COMM_WORLD);
p0_token_already_sent = true;
if (printDebug) cout << "P" << process_rank << ":" << " Token sent to " << donator_next << endl;
}
//iam out of work... so I send request to another process
if (printDebug) cout << "P" << process_rank << ":" << " Request for work sent to P" << donator_next << endl;
MPI_Send(message, strlen(message) + 1, MPI_CHAR, donator_next, MSG_WORK_REQUEST, MPI_COMM_WORLD);
waiting_for_data = true;
no_failed_data_req++;
//calculation of next donator
donator_next = (donator_next + 1) % processes;
//prohibit to ask myself for work
if (donator_next == process_rank) {
donator_next = (donator_next + 1) % processes;
}
receiveMessage();
citac = 0;
}
citac++; //inc. couter when we reach check_msg_amount, we will check for messages
if ((citac % CHECK_MSG_AMOUNT) == 0) {
//if there is message in queue, receive it
//cout << "P" << process_rank << ": Couter full, im going to check messages" << endl;
MPI_Iprobe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &flag, &status);
if (flag) {
receiveMessage();
}
//protection against overflow of int during long calculations
citac = 0;
}
}
//finished flag is true. I send finish message to all procesess
for (int i = 1; i < processes; i++) {
MPI_Send(message, strlen(message) + 1, MPI_CHAR, i, MSG_FINISH, MPI_COMM_WORLD);
if (printDebug) cout << "P" << process_rank << ":" << " FINISH MESSAGE TO: " << "P" << i << endl;
}
//isParallel part done
} else {
//it a serial job
cout << "P" << process_rank << ":" << "Performing a serial job." << endl;
//work!
while (!stack1.empty()) {
Node akt = stack1.top();
stack1.pop(); //remove top
procedeNode(&bestValue, akt, &best, &bagSize, &volumes, &values, &stack1, items_count);
}
}
//all threads are finished with work and the winner is known:
//I will return with P0 into messageReceive cycle and keep it here using waiting_for_data and finished
//until all data are collected
if (isParallel) {
waiting_for_data = true;
finished = false;
receiveMessage();
}
cout << "P" << process_rank << ":" << "solution with the value of " << best.calculateValue(&values) << " is:" << endl;
best.print(process_rank);
//no one (expcept P0) should get here!
if (process_rank != 0) {
cerr << "P" << process_rank << ":" << "noone should reach the endpoint!" << endl;
}
MPI_Barrier(MPI_COMM_WORLD);
double t2 = MPI_Wtime();
cout << "Spotrebovany cas je: " << t2 - t1 << endl;
MPI_Finalize();
return 0;
}
| [
"dk1844@a7112e55-00eb-d1e0-63ed-7a5e4b87212c",
"mvcelicka@a7112e55-00eb-d1e0-63ed-7a5e4b87212c"
] | [
[
[
1,
32
],
[
34,
57
],
[
60,
64
],
[
75,
75
],
[
77,
77
],
[
91,
114
],
[
126,
126
],
[
129,
129
],
[
132,
132
],
[
137,
137
],
[
142,
142
],
[
145,
145
],
[
152,
152
],
[
166,
167
],
[
179,
179
],
[
181,
181
],
[
185,
185
],
[
188,
188
],
[
193,
193
],
[
201,
201
],
[
203,
208
],
[
210,
215
],
[
217,
298
],
[
300,
350
],
[
354,
355
],
[
358,
360
],
[
362,
363
],
[
365,
403
],
[
405,
406
],
[
408,
410
],
[
412,
419
],
[
426,
426
],
[
433,
433
],
[
443,
443
],
[
449,
449
],
[
451,
486
],
[
488,
490
],
[
492,
492
],
[
494,
504
],
[
506,
507
],
[
511,
511
],
[
515,
515
],
[
517,
545
],
[
549,
555
],
[
557,
560
],
[
562,
563
],
[
565,
571
],
[
573,
617
],
[
619,
625
],
[
627,
628
],
[
630,
630
],
[
633,
633
],
[
635,
635
],
[
637,
642
],
[
644,
650
],
[
652,
654
],
[
656,
656
],
[
658,
661
],
[
664,
664
],
[
666,
668
],
[
670,
684
],
[
695,
695
],
[
697,
697
],
[
699,
715
],
[
718,
731
],
[
735,
737
]
],
[
[
33,
33
],
[
58,
59
],
[
65,
74
],
[
76,
76
],
[
78,
90
],
[
115,
125
],
[
127,
128
],
[
130,
131
],
[
133,
136
],
[
138,
141
],
[
143,
144
],
[
146,
151
],
[
153,
165
],
[
168,
178
],
[
180,
180
],
[
182,
184
],
[
186,
187
],
[
189,
192
],
[
194,
200
],
[
202,
202
],
[
209,
209
],
[
216,
216
],
[
299,
299
],
[
351,
353
],
[
356,
357
],
[
361,
361
],
[
364,
364
],
[
404,
404
],
[
407,
407
],
[
411,
411
],
[
420,
425
],
[
427,
432
],
[
434,
442
],
[
444,
448
],
[
450,
450
],
[
487,
487
],
[
491,
491
],
[
493,
493
],
[
505,
505
],
[
508,
510
],
[
512,
514
],
[
516,
516
],
[
546,
548
],
[
556,
556
],
[
561,
561
],
[
564,
564
],
[
572,
572
],
[
618,
618
],
[
626,
626
],
[
629,
629
],
[
631,
632
],
[
634,
634
],
[
636,
636
],
[
643,
643
],
[
651,
651
],
[
655,
655
],
[
657,
657
],
[
662,
663
],
[
665,
665
],
[
669,
669
],
[
685,
694
],
[
696,
696
],
[
698,
698
],
[
716,
717
],
[
732,
734
]
]
] |
fe238f47f319c6bdabaee832aa5bdf8ba57530f4 | 1960e1ee431d2cfd2f8ed5715a1112f665b258e3 | /src/com/covariant.cpp | f83a6a431b6faaa852186fffe7fa1a29788989a8 | [] | no_license | BackupTheBerlios/bvr20983 | c26a1379b0a62e1c09d1428525f3b4940d5bb1a7 | b32e92c866c294637785862e0ff9c491705c62a5 | refs/heads/master | 2021-01-01T16:12:42.021350 | 2009-11-01T22:38:40 | 2009-11-01T22:38:40 | 39,518,214 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,751 | cpp | /*
* $Id$
*
* COM VARIANT and PROPVARIANT Helper.
*
* Copyright (C) 2008 Dorothea Wachmann
*
* 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
* (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, see http://www.gnu.org/licenses/.
*/
#include "os.h"
#include "com/covariant.h"
#include "util/logstream.h"
#include "util/comlogstream.h"
using namespace bvr20983;
namespace bvr20983
{
namespace COM
{
/**
*
*/
COVariant::COVariant()
{ ::VariantInit(&m_value); }
/**
*
*/
COVariant::COVariant(const VARIANT& value)
{ ::VariantInit(&m_value);
*this = value;
}
/**
*
*/
COVariant::COVariant(const COVariant& value)
{ ::VariantInit(&m_value);
*this = value;
}
/**
*
*/
COVariant::COVariant(LPCTSTR value,UINT len)
{ ::VariantInit(&m_value);
V_VT(&m_value) = VT_BSTR;
TCHAR n = _T('\0');
LPTSTR v = NULL;
if( NULL!=value && len>0 && len<=::_tcslen(value) )
{ v = const_cast<LPTSTR>(value);
n = v[len];
v[len] = _T('\0');
} // of if
V_BSTR(&m_value) = ::SysAllocString(value);
if( NULL!=v )
v[len] = n;
}
/**
*
*/
COVariant::COVariant(const TString& value)
{ ::VariantInit(&m_value);
V_VT(&m_value) = VT_BSTR;
V_BSTR(&m_value) = ::SysAllocString(value.c_str());
}
/**
*
*/
COVariant::COVariant(bool value)
{ ::VariantInit(&m_value);
V_VT(&m_value) = VT_BOOL;
V_BOOL(&m_value) = value ? VARIANT_TRUE : VARIANT_FALSE;
}
/**
*
*/
COVariant::~COVariant()
{ ::VariantClear(&m_value); }
/**
*
*/
COVariant& COVariant::operator=(const VARIANT& value)
{ ::VariantClear(&m_value);
::VariantCopy(&m_value,const_cast<VARIANT*>(&value));
return *this;
} // of COVariant::operator=()
/**
*
*/
COVariant& COVariant::operator=(const COVariant& value)
{ ::VariantClear(&m_value);
::VariantCopy(&m_value,const_cast<VARIANT*>(&value.m_value));
return *this;
} // of COVariant::operator=()
/**
*
*/
HRESULT COVariant::ChangeType(VARTYPE vt,const COVariant& value)
{ const VARIANT* v = value;
::VariantClear(&m_value);
return ::VariantChangeType(&m_value, const_cast<VARIANT*>(v), 0, vt);
} // of COVariant::ChangeType()
/**
*
*/
HRESULT COVariant::ChangeType(VARTYPE vt)
{ return ::VariantChangeType(&m_value,&m_value, 0, vt);
} // of COVariant::ChangeType()
/**
*
*/
COPropVariant::COPropVariant()
{ ::PropVariantInit(&m_value); }
/**
*
*/
COPropVariant::COPropVariant(const PROPVARIANT& value)
{ ::PropVariantInit(&m_value);
*this = value;
}
/**
*
*/
COPropVariant::COPropVariant(const COPropVariant& value)
{ ::PropVariantInit(&m_value);
*this = value;
}
/**
*
*/
COPropVariant::~COPropVariant()
{ ::PropVariantClear(&m_value); }
/**
*
*/
COPropVariant& COPropVariant::operator=(const PROPVARIANT& value)
{ ::PropVariantClear(&m_value);
::PropVariantCopy(&m_value,&value);
return *this;
} // of COPropVariant::operator=()
/**
*
*/
COPropVariant& COPropVariant::operator=(const COPropVariant& value)
{ ::PropVariantClear(&m_value);
::PropVariantCopy(&m_value,&value.m_value);
return *this;
} // of COPropVariant::operator=()
/**
*
*/
COPropVariant& COPropVariant::operator=(const VARIANT& value)
{ ::PropVariantClear(&m_value);
m_value.vt = value.vt & VT_TYPEMASK;
switch( m_value.vt )
{
case VT_EMPTY:
case VT_NULL:
break;
case VT_I1:
m_value.cVal = value.cVal;
break;
case VT_UI1:
m_value.bVal = value.bVal;
break;
case VT_I2:
m_value.iVal = value.iVal;
break;
case VT_UI2:
m_value.uiVal = value.uiVal;
break;
case VT_I4:
m_value.lVal = value.lVal;
break;
case VT_UI4:
m_value.ulVal = value.ulVal;
break;
case VT_INT:
m_value.intVal = value.intVal;
break;
case VT_UINT:
m_value.uintVal = value.uintVal;
break;
case VT_R4:
m_value.fltVal = value.fltVal;
break;
case VT_R8:
m_value.dblVal = value.dblVal;
break;
case VT_CY:
m_value.cyVal = value.cyVal;
break;
case VT_DATE:
m_value.date = value.date;
break;
case VT_BSTR:
m_value.bstrVal = ::SysAllocString(value.bstrVal);
break;
case VT_DISPATCH:
m_value.pdispVal = value.pdispVal;
ADDREF_INTERFACE(m_value.pdispVal);
break;
case VT_ERROR:
m_value.scode = value.scode;
break;
case VT_BOOL:
m_value.boolVal = value.boolVal;
break;
case VT_VARIANT:
break;
case VT_UNKNOWN:
m_value.punkVal = value.punkVal;
ADDREF_INTERFACE(m_value.punkVal);
break;
case VT_DECIMAL:
m_value.pdecVal = value.pdecVal;
break;
case VT_RECORD:
break;
default:
break;
} // of switch
return *this;
} // of COPropVariant::operator=()
/**
*
*/
COPropVariant& COPropVariant::operator=(const COVariant& value)
{ const VARIANT& v = value;
*this = v;
return *this;
} // of COPropVariant::operator=()
/**
*
*/
bool COPropVariant::GetBool(bool& b) const
{ bool result = false;
if( m_value.vt==VT_BOOL || m_value.vt==VT_BSTR )
{ result = true;
b = (m_value.vt==VT_BOOL && m_value.boolVal==VARIANT_TRUE)
||
(m_value.vt==VT_BSTR && _tcsicmp(_T("true"),m_value.bstrVal)==0)
;
} // of if
return result;
}
/**
*
*/
bool COPropVariant::GetString(TString s) const
{ bool result = false;
if( m_value.vt==VT_BSTR )
{ s = m_value.bstrVal;
result = true;
}
return result;
}
/**
*
*/
bool COPropVariant::GetString(BSTR* s) const
{ bool result = false;
if( m_value.vt==VT_BSTR && NULL!=s )
{ *s = ::SysAllocString(m_value.bstrVal);
result = true;
}
return result;
}
/**
*
*/
bool COPropVariant::GetULong(ULONG& v) const
{ bool result = false;
if( m_value.vt==VT_UI4 )
{ v = m_value.ulVal;
result = true;
}
return result;
}
} // of namespace COM
} // of namespace bvr20983
/*==========================END-OF-FILE===================================*/
| [
"dwachmann@01137330-e44e-0410-aa50-acf51430b3d2"
] | [
[
[
1,
349
]
]
] |
c4c368f4661ead1bf5c8446e550071a41ecc3585 | bdb1e38df8bf74ac0df4209a77ddea841045349e | /CapsuleSortor/Version 1.0 -2.0/CapsuleSortor-10-11-12/CapsuleSortor-10-11-12/ToolSrc/TImgRowIter.h | bbd1ded1e34a79eda95a651b05e3506a01a51bd1 | [] | no_license | Strongc/my001project | e0754f23c7818df964289dc07890e29144393432 | 07d6e31b9d4708d2ef691d9bedccbb818ea6b121 | refs/heads/master | 2021-01-19T07:02:29.673281 | 2010-12-17T03:10:52 | 2010-12-17T03:10:52 | 49,062,858 | 0 | 1 | null | 2016-01-05T11:53:07 | 2016-01-05T11:53:07 | null | UTF-8 | C++ | false | false | 1,946 | h | // Image row Iterator class
#ifndef TIMGROWITER_H
#define TIMGROWITER_H
#include "PixelType.h"
template<class T>
class TImgRowIter
{
private:
struct current
{
T* p; // Pointer to start of row y
int x; // x coordinate of start of row
int y; // y coordinate of current row
int bytes; // Number of bytes to offset to next row
};
public:
TImgRowIter ()
{ m_cur.p = 0; m_cur.x = 0; m_cur.y = 0; m_cur.bytes = 0;}
TImgRowIter (T* p, int bytes, int x, int y)
{ m_cur.p = p; m_cur.bytes = bytes; m_cur.x = x; m_cur.y = y;}
T* Base()
{
return m_cur.p;
}
TImgRowIter& operator++ ()
{
m_cur.p = reinterpret_cast<T*>
(reinterpret_cast<PixelMem*>(m_cur.p) + m_cur.bytes);
m_cur.y++;
return *this;
}
TImgRowIter operator++ (int)
{
TImgRowIter t = *this;
m_cur.p = reinterpret_cast<T*>
(reinterpret_cast<PixelMem*>(m_cur.p) + m_cur.bytes);
m_cur.y++;
return t;
}
TImgRowIter& operator-- ()
{
m_cur.p = reinterpret_cast<T*>
(reinterpret_cast<PixelMem*>(m_cur.p) - m_cur.bytes);
m_cur.y--;
return *this;
}
TImgRowIter operator-- (int)
{
TImgRowIter t = *this;
m_cur.p = reinterpret_cast<T*>
(reinterpret_cast<PixelMem*>(m_cur.p) - m_cur.bytes);
m_cur.y--;
return t;
}
TImgRowIter& operator+= (int s)
{
m_cur.p = reinterpret_cast<T*>
(reinterpret_cast<PixelMem*>(m_cur.p) + s*m_cur.bytes);
m_cur.y += s;
return *this;
}
TImgRowIter& operator-= (int s)
{
m_cur.p = reinterpret_cast<T*>
(reinterpret_cast<PixelMem*>(m_cur.p) - s*m_cur.bytes);
m_cur.y -= s;
return *this;
}
bool operator== (const TImgRowIter& i) const
{ return (m_cur.p == i.m_cur.p);}
bool operator!= (const TImgRowIter& i) const
{ return (m_cur.p != i.m_cur.p);}
// Default copy constructor and assignment operators ok.
private:
current m_cur;
};
#endif //TIMGROWITER_H | [
"vincen.cn@66f52ff4-a261-11de-b161-9f508301ba8e"
] | [
[
[
1,
88
]
]
] |
4844a45aacea4cc15b8e54e8f579b31c327bc5a3 | 9df2486e5d0489f83cc7dcfb3ccc43374ab2500c | /src/objects/ball.cpp | 53d789f9839f81d115284e29da1a872c7c7ac20d | [] | no_license | renardchien/Eta-Chronicles | 27ad4ffb68385ecaafae4f12b0db67c096f62ad1 | d77d54184ec916baeb1ab7cc00ac44005d4f5624 | refs/heads/master | 2021-01-10T19:28:28.394781 | 2011-09-05T14:40:38 | 2011-09-05T14:40:38 | 1,914,623 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 11,715 | cpp | /***************************************************************************
* ball.cpp - ball class
*
* Copyright (C) 2006 - 2009 Florian Richter
***************************************************************************/
/*
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
(at your option) any later version.
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 "../objects/ball.h"
#include "../core/game_core.h"
#include "../enemies/enemy.h"
#include "../objects/goldpiece.h"
#include "../enemies/gee.h"
#include "../enemies/spika.h"
#include "../player/player.h"
#include "../video/animation.h"
#include "../level/level.h"
#include "../gui/hud.h"
#include "../core/sprite_manager.h"
namespace SMC
{
/* *** *** *** *** *** *** cBall *** *** *** *** *** *** *** *** *** *** *** */
cBall :: cBall( float x, float y, const cSprite *origin_object /* = NULL */, ball_effect btype /* = FIREBALL_DEFAULT */ )
: cMovingSprite( NULL, x, y )
{
m_sprite_array = ARRAY_ACTIVE;
m_type = TYPE_BALL;
m_pos_z = 0.095f;
m_spawned = 1;
m_player_range = 2000;
m_massive_type = MASS_MASSIVE;
m_glim_mod = 1;
m_glim_counter = 0.0f;
m_fire_counter = 0.0f;
m_life_left = 0;
if( btype == FIREBALL_DEFAULT || btype == FIREBALL_EXPLOSION )
{
Set_Image( pVideo->Get_Surface( "animation/fireball/1.png" ) );
m_ball_type = FIREBALL_DEFAULT;
}
else if( btype == ICEBALL_DEFAULT || btype == ICEBALL_EXPLOSION )
{
Set_Image( pVideo->Get_Surface( "animation/iceball/1.png" ) );
m_ball_type = ICEBALL_DEFAULT;
}
else
{
printf( "Warning : Ball unknown type %d\n", btype );
cMovingSprite::Destroy();
return;
}
if( origin_object )
{
m_origin_array = origin_object->m_sprite_array;
m_origin_type = origin_object->m_type;
if( m_origin_type == TYPE_PLAYER )
{
if( m_ball_type == FIREBALL_DEFAULT || m_ball_type == ICEBALL_DEFAULT )
{
pPlayer->shoot_counter = speedfactor_fps;
}
}
}
// if origin not set
else
{
printf( "Warning : Ball origin not set\n" );
m_origin_array = ARRAY_UNDEFINED;
m_origin_type = TYPE_UNDEFINED;
}
}
cBall :: ~cBall( void )
{
// always destroy
if( !m_auto_destroy )
{
cBall::Destroy();
}
}
void cBall :: Destroy_Ball( bool with_sound /* = 0 */ )
{
Set_Velocity(0,0);
if( with_sound )
{
if( m_ball_type == FIREBALL_DEFAULT )
{
pAudio->Play_Sound( "item/fireball_explode.wav" );
}
}
Destroy();
}
void cBall :: Destroy( void )
{
if( m_auto_destroy )
{
return;
}
if( m_ball_type == FIREBALL_DEFAULT )
{
pAnimation_Manager->Add( new cAnimation_Fireball( m_pos_x + m_col_rect.m_w / 2, m_pos_y + m_col_rect.m_h / 2 ) );
}
else if( m_ball_type == ICEBALL_DEFAULT )
{
// create animation
cParticle_Emitter *anim = new cParticle_Emitter();
Generate_Particles( anim );
anim->Set_Quota( 15 );
// add animation
pAnimation_Manager->Add( anim );
}
cMovingSprite::Destroy();
}
void cBall :: Update( void )
{
if( !m_valid_update )
{
return;
}
// right
if( m_velx > 0.0f )
{
Set_Velocity(20,0);
m_rot_z += pFramerate->m_speed_factor * 40;
}
// left
else
{
Set_Velocity(-20,0);
m_rot_z -= pFramerate->m_speed_factor * 40;
}
// if ball is out of Player Range
if( !Is_In_Player_Range() )
{
Destroy();
}
// glim animation
if( m_glim_mod )
{
m_glim_counter += pFramerate->m_speed_factor * 0.1f;
//m_glim_counter += pFramerate->m_speed_factor * 0.0f;
if( m_glim_counter > 1.0f )
{
m_glim_counter = 1.0f;
//m_glim_counter = 0.0f;
m_glim_mod = 0;
}
}
else
{
m_glim_counter -= pFramerate->m_speed_factor * 0.1f;
//m_glim_counter -= pFramerate->m_speed_factor * 0.0f;
if( m_glim_counter < 0.0f )
{
m_glim_counter = 0.0f;
m_glim_mod = 1;
}
}
// generate fire particle animation
m_fire_counter += pFramerate->m_speed_factor;
while( m_fire_counter > 1 )
{
Generate_Particles();
m_fire_counter -= 1;
}
}
void cBall :: Draw( cSurface_Request *request /* = NULL */ )
{
if( !m_valid_draw )
{
return;
}
// don't draw if leveleditor mode
if( editor_level_enabled )
{
return;
}
if( m_ball_type == FIREBALL_DEFAULT )
{
Set_Color_Combine( m_glim_counter, m_glim_counter / 1.2f, m_glim_counter / 2, GL_ADD );
}
else if( m_ball_type == ICEBALL_DEFAULT )
{
Set_Color_Combine( m_glim_counter / 2.5f, m_glim_counter / 2.5f, m_glim_counter / 1.7f, GL_ADD );
}
cMovingSprite::Draw( request );
}
void cBall :: Generate_Particles( cParticle_Emitter *anim /* = NULL */ ) const
{
bool create_anim = 0;
if( !anim )
{
create_anim = 1;
// create animation
anim = new cParticle_Emitter();
}
anim->Set_Emitter_Rect( m_col_rect );
anim->Set_Image( pVideo->Get_Surface( "animation/particles/light.png" ) );
anim->Set_Pos_Z( m_pos_z + 0.0001f );
if( m_ball_type == FIREBALL_DEFAULT )
{
anim->Set_Time_to_Live( 0.2f );
anim->Set_Color( Color( static_cast<Uint8>(250), 140, 90 ) );
}
else if( m_ball_type == ICEBALL_DEFAULT )
{
anim->Set_Time_to_Live( 0.5f );
anim->Set_Color( Color( static_cast<Uint8>(90), 90, 255 ) );
}
anim->Set_Blending( BLEND_ADD );
anim->Set_Speed( 0.35f, 0.3f );
anim->Set_Scale( 0.4f, 0.2f );
if( create_anim )
{
// add animation
pAnimation_Manager->Add( anim );
}
}
Col_Valid_Type cBall :: Validate_Collision( cSprite *obj )
{
// basic validation checking
Col_Valid_Type basic_valid = Validate_Collision_Ghost( obj );
// found valid collision
if( basic_valid != COL_VTYPE_NOT_POSSIBLE )
{
return basic_valid;
}
switch( obj->m_type )
{
case TYPE_PLAYER:
{
if( m_origin_type != TYPE_PLAYER )
{
return COL_VTYPE_INTERNAL;
}
return COL_VTYPE_NOT_VALID;
}
case TYPE_BALL:
{
return COL_VTYPE_NOT_VALID;
}
default:
{
break;
}
}
if( obj->m_massive_type == MASS_MASSIVE )
{
if( obj->m_sprite_array == ARRAY_ENEMY && m_origin_array == ARRAY_ENEMY )
{
return COL_VTYPE_NOT_VALID;
}
return COL_VTYPE_BLOCKING;
}
else if( obj->m_massive_type == MASS_HALFMASSIVE )
{
// if moving downwards and the object is on bottom
if( m_vely >= 0.0f && Is_On_Top( obj ) )
{
return COL_VTYPE_BLOCKING;
}
}
return COL_VTYPE_NOT_VALID;
}
void cBall :: Handle_Collision( cObjectCollision *collision )
{
// already destroyed
if( m_auto_destroy )
{
return;
}
cMovingSprite::Handle_Collision( collision );
}
void cBall :: Handle_Collision_Player( cObjectCollision *collision )
{
// velocity hit
if( collision->direction == DIR_LEFT )
{
if( pPlayer->m_velx > 0.0f )
{
pPlayer->m_velx *= 0.3f;
}
}
else if( collision->direction == DIR_RIGHT )
{
if( pPlayer->m_velx < 0.0f )
{
pPlayer->m_velx *= 0.3f;
}
}
else if( collision->direction == DIR_UP )
{
if( pPlayer->m_vely > 0.0f )
{
pPlayer->m_vely *= 0.2f;
}
}
else if( collision->direction == DIR_DOWN )
{
if( pPlayer->m_vely < 0.0f )
{
pPlayer->m_vely *= 0.4f;
}
}
pAudio->Play_Sound( "item/fireball_repelled.wav" );
Destroy();
}
void cBall :: Handle_Collision_Enemy( cObjectCollision *collision )
{
cEnemy *enemy = static_cast<cEnemy *>(pActive_Sprite_Manager->Get_Pointer( collision->number ));
// if enemy is not destroyable
if( ( m_ball_type == FIREBALL_DEFAULT && enemy->m_fire_resistant ) || ( m_ball_type == ICEBALL_DEFAULT && enemy->m_ice_resistance >= 1 ) )
{
pAudio->Play_Sound( "item/fireball_repelled.wav" );
}
// destroy enemy
else
{
// enemy rect particle animation
for( unsigned int w = 0; w < enemy->m_col_rect.m_w; w += 15 )
{
for( unsigned int h = 0; h < enemy->m_col_rect.m_h; h += 15 )
{
// animation
cParticle_Emitter *anim = new cParticle_Emitter();
anim->Set_Pos( enemy->m_pos_x + w, enemy->m_pos_y + h );
anim->Set_Image( pVideo->Get_Surface( "animation/particles/light.png" ) );
anim->Set_Time_to_Live( 0.2f, 0.4f );
Color anim_color, anim_color_rand;
if( m_ball_type == FIREBALL_DEFAULT )
{
anim_color = Color( static_cast<Uint8>(250), 170, 150 );
anim_color_rand = Color( static_cast<Uint8>( rand() % 5 ), rand() % 85, rand() % 25, 0 );
}
else
{
anim_color = Color( static_cast<Uint8>(150), 150, 240 );
anim_color_rand = Color( static_cast<Uint8>( rand() % 80 ), rand() % 80, rand() % 10, 0 );
}
anim->Set_Color( anim_color, anim_color_rand );
anim->Set_Fading_Alpha( 1 );
anim->Set_Fading_Size( 1 );
anim->Set_Speed( 0.5f, 2.2f );
anim->Set_Blending( BLEND_DRIVE );
// add animation
pAnimation_Manager->Add( anim );
}
}
// play enemy kill sound
pAudio->Play_Sound( enemy->m_kill_sound );
if( m_ball_type == FIREBALL_DEFAULT )
{
enemy->set_life_left(1);
enemy->return_life_left();
//if (m_life_left < 1)
if (enemy->return_life_left() < 0)
{
// get points
pHud_Points->Add_Points( enemy->m_kill_points, m_pos_x, m_pos_y, "", static_cast<Uint8>(255), 1 );
// create goldpiece
cMovingSprite *goldpiece = new cFGoldpiece( enemy->m_col_rect.m_x, enemy->m_col_rect.m_y + enemy->m_col_rect.m_h, collision->direction );
// set optimal position
goldpiece->Col_Move( -( ( goldpiece->m_col_rect.m_w - enemy->m_col_rect.m_w ) / 2 ), -( goldpiece->m_col_pos.m_y + goldpiece->m_col_rect.m_h ), 1, 1 );
// add goldpiece
pActive_Sprite_Manager->Add( goldpiece );
enemy->Set_Active( 0 );
enemy->DownGrade( 1 );
pPlayer->Add_Kill_Multiplier();
}
}
else if( m_ball_type == ICEBALL_DEFAULT )
{
enemy->Freeze();
}
}
Destroy();
}
void cBall :: Handle_Collision_Massive( cObjectCollision *collision )
{
if( collision->direction == DIR_DOWN )
{
// if directly hitting the ground
if( m_velx < 0.1f && m_velx > -0.1f )
{
Destroy_Ball( 1 );
return;
}
if( m_ball_type == FIREBALL_DEFAULT )
{
m_vely = 0.0f;
// create animation
cAnimation_Fireball *anim = new cAnimation_Fireball( m_pos_x + m_col_rect.m_w / 2, m_pos_y + m_col_rect.m_h / 2 );
anim->Set_Fading_Speed( 3.0f );
pAnimation_Manager->Add( anim );
}
else if( m_ball_type == ICEBALL_DEFAULT )
{
m_vely = -5.0f;
// create animation
cParticle_Emitter *anim = new cParticle_Emitter();
anim->Set_Pos( m_pos_x + m_col_rect.m_w / 2, m_pos_y + m_col_rect.m_h / 2 );
anim->Set_Image( pVideo->Get_Surface( "animation/particles/cloud.png" ) );
anim->Set_Direction_Range( 0, 180 );
anim->Set_Quota( 3 );
anim->Set_Time_to_Live( 0.8f );
anim->Set_Pos_Z( m_pos_z + 0.0001f );
anim->Set_Color( Color( static_cast<Uint8>(50), 50, 250 ) );
anim->Set_Blending( BLEND_ADD );
anim->Set_Speed( 0.5f, 0.4f );
anim->Set_Scale( 0.3f, 0.4f );
// add animation
pAnimation_Manager->Add( anim );
}
}
// other directions
else
{
Destroy_Ball( 1 );
}
}
void cBall :: Handle_out_of_Level( ObjectDirection dir )
{
// ignore top
if( dir == DIR_TOP )
{
return;
}
Destroy_Ball( 1 );
}
/* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */
} // namespace SMC
| [
"[email protected]"
] | [
[
[
1,
500
]
]
] |
5c5a007bc9d6ba555b5723dcfc2f16bfed463e4a | dadae22098e24c412a8d8d4133c8f009a8a529c9 | /tp2/src/vector3.h | 84655c0c8c6251af6385eed27f8f6cf66edfb5fe | [] | no_license | maoueh/PHS4700 | 9fe2bdf96576975b0d81e816c242a8f9d9975fbc | 2c2710fcc5dbe4cd496f7329379ac28af33dc44d | refs/heads/master | 2021-01-22T22:44:17.232771 | 2009-10-06T18:49:30 | 2009-10-06T18:49:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,019 | h | #ifndef VECTOR3_H
#define VECTOR3_H
#include "common.h"
template <class Real>
class Vector3
{
public:
static const Vector3 ZERO;
static const Vector3 UNIT_X;
static const Vector3 UNIT_Y;
static const Vector3 UNIT_Z;
inline Vector3();
inline Vector3(Real x, Real y, Real z);
inline explicit Vector3(Real* coordinates); // Takes a three element <Real> array
inline explicit Vector3(Real scalar);
inline Vector3(const Vector3& other);
inline Real x() const;
inline Real& x();
inline Real y() const;
inline Real& y();
inline Real z() const;
inline Real& z();
inline void set(Real scalar);
inline void set(Real x, Real y, Real z);
inline void set(Real* coordinates); // Takes a three element <Real> array
inline void set2(Real* coordinates); // Takes a two element <Real> array
inline void assignTo(Real* values); // Assign the array received with the components of the vector
inline Vector3& operator= (const Vector3& rightSide);
inline operator const Real* () const;
inline operator Real* ();
inline Real operator[] (INT index) const;
inline Real& operator[] (INT index);
inline BOOL operator== (const Vector3& rightSide) const;
inline BOOL operator!= (const Vector3& rightSide) const;
inline Vector3& operator+= (const Vector3& rightSide);
inline Vector3& operator-= (const Vector3& rightSide);
inline Vector3& operator*= (Real scalar);
inline Vector3& operator/= (Real scalar);
inline Vector3 operator- () const;
inline Vector3 operator+ (const Vector3& rightSide) const;
inline Vector3 operator- (const Vector3& rightSide) const;
inline Vector3 operator* (Real scalar) const;
inline Vector3 operator/ (Real scalar) const;
// Be careful : the length is not squarred, use magnitude for the squarred value
inline Real length() const;
inline Real magnitude() const;
inline Vector3 normalize() const;
inline static Real scalarProduct(Vector3& leftSide, const Vector3& rightSide); // Same as dotProduct
inline static Real dotProduct(Vector3& leftSide, const Vector3& rightSide); // Same as scalarProduct
inline static Vector3 vectorProduct(Vector3& leftSide, const Vector3& rightSide); // Same as crossProduct
inline static Vector3 crossProduct(Vector3& leftSide, const Vector3& rightSide); // Same as vectorProduct
inline static Real distance(Vector3& leftSide, const Vector3& rightSide);
Real components[3];
};
template <class Real>
Vector3<Real> operator* (Real scalar, const Vector3<Real>& rightSide);
template <class Real>
Vector3<Real> operator/ (Real scalar, const Vector3<Real>& rightSide);
template <class Real>
ostream& operator<< (ostream& outputStream, const Vector3<Real>& vector);
#include "vector3.inl"
typedef Vector3<FLOAT> Vector3f;
typedef Vector3<DOUBLE> Vector3d;
#endif
| [
"[email protected]"
] | [
[
[
1,
86
]
]
] |
e18b1f0514d43e32f06333a3f63a6ee873fecebf | 7c51155f60ff037d1b8d6eea1797c7d17e1d95c2 | /eJVM-Final/Loader.cpp | cd46caf56640c41401b60e86a154d69e7e5d081c | [] | no_license | BackupTheBerlios/ejvm | 7258cd180256970d57399d0c153d00257dbb127c | 626602de9ed55a825efeefd70970c36bcef0588d | refs/heads/master | 2020-06-11T19:47:07.882834 | 2006-07-10T16:39:59 | 2006-07-10T16:39:59 | 39,960,044 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,207 | cpp | #include "Loader.h"
#include "Heap.h"
#include <stdio.h>
#include <sys/stat.h>
//#include <unistd.h>
Loader * Loader::loaderInstance = NULL;
//--------------------------------------------------------------
Loader * Loader::getInstance()
{
if(loaderInstance == NULL)
loaderInstance = new Loader;
return loaderInstance;
}
//-----------------------------------------------------
void Loader::deleteLoader()
{
delete loaderInstance;
loaderInstance =NULL;
}
//---------------------------------------------------------
Loader::Loader()
{
}
//----------------------------------------------------------
byte * Loader::makeArrayInCPP(char * fileName)
{
struct stat len;
FILE *stream;
void * classFile;
if((stream = fopen(fileName, "rb")) == NULL)
{
cout<<"File Not Found"<<endl;
exit(1);
}
stat(fileName,&len);
int size = len.st_size;
classFile = new byte[size];
size_t bytesRead =fread(classFile,1,(size_t)size,stream);
cout<<bytesRead<<" bytes read\n";
fclose(stream);
/*char ch;
unsigned long length = 0;
ifstream fin(fileName, ios::in | ios::binary);
if(!fin)
{
cout<<"Cannot open the file";
return NULL;
}
//Calaculate the file length
while(fin.get(ch))
length++;
fin.close();
//now read the file
fin.open(fileName, ios::in | ios::binary);
byte * pData=new byte[length];
fin.read((char *)pData,length);
//see how many bytes have beed read
cout<<fin.gcount()<<" bytes read\n";
fin.close();
/* char file2[80]="/Khaled/eclipseWork/hello/OPS2.class";
ofstream fout(file2, ios::out | ios::binary);
fout.write((char *)pData,length);
//see how many bytes have beed written
cout<<fin.gcount()<<" bytes written\n";
fout.close();*/
//return pData ;
return (byte *)classFile;
}
//---------------------------------------------------------------------------------------------
ClassData * Loader::getClassData(const char * className)
{
///////////////////////////class name must be without .class
/**
* psudoCode:
* if(!(classData=lookupdClassData(className)))
* u1[] classFile = classFiel2bytes(className);
* classData = Heap->createClassData(classFile);
* return classData;
*/
// char path[80]="/Khaled/eclipseWork/testPrototype1/";
char path[80]="";
Heap * heap= Heap::getInstance();
ClassData * cdata =NULL;
byte * classFile = NULL;
cdata = heap->lookupClassData(className);
if(cdata == NULL)//Class not loaded
{
//prepare the path of the class file
strcat(path,className);
strcat(path,".class");
//put the class file in array of bytes
classFile=this->makeArrayInCPP(path);//*********************************************************************************DONT forget to uncomment
//create classdata on the heap
cdata = heap->createClassData(className,classFile); //*************************************************dont forget to modify it to take array of bytes or u1
//after checking that there are no errors during parsing, insert in the hash
heap->addToHash(cdata);
}
delete [] classFile;
return cdata;
}
| [
"ahmed_seddiq"
] | [
[
[
1,
126
]
]
] |
dfb169746018e4ce98a388dbbd86f5b88a0cc7ed | 5dfa2f8acf81eb653df4a35a76d6be973b10a62c | /trunk/Community_Core_Vision/addons/ofxNCore/src/Modules/ofxNCoreVision.h | 8975a1eeebdc587963ac98a5e3e29b66f7fa7cbd | [] | no_license | guozanhua/ccv-multicam | d69534ff8592f7984a5eadc83ed8b20b9d3df949 | 31206f0de7f73b3d43f2a910fdcdffb7ed1bf2c2 | refs/heads/master | 2021-01-22T14:24:52.321877 | 2011-08-31T14:18:44 | 2011-08-31T14:18:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,935 | h |
/*
* ofxNCoreVision.h
* NUI Group Community Core Vision
*
* Created by NUI Group Dev Team A on 2/1/09.
* Updated by Anatoly Churikov on 12/03/11
* Copyright 2011 NUI Group. All rights reserved.
*
*/
#ifndef _ofxNCoreVision_H
#define _ofxNCoreVision_H
//Main
#include "ofMain.h"
//Addons
#ifdef TARGET_WIN32
#include "ofxMultiplexer.h"
#include "ofxDSVL.h"
#endif
#include "ofxOpenCv.h"
#include "ofxDirList.h"
#include "ofxVectorMath.h"
#include "ofxNetwork.h"
#include "ofxOsc.h"
#include "ofxThread.h"
#include "ofxXmlSettings.h"
#include "ofxFiducialTracker.h"
#include "ofxDShow.h"
// Our Addon
#include "ofxNCore.h"
// height and width of the source/tracked draw window
#define MAIN_WINDOW_HEIGHT 240.0f
#define MAIN_WINDOW_WIDTH 320.0f
class ofxNCoreVision : public ofxGuiListener
{
// ofxGUI setup stuff
enum
{
propertiesPanel,
propertiesPanel_flipV,
propertiesPanel_flipH,
propertiesPanel_settings,
propertiesPanel_pressure,
optionPanel,
optionPanel_tuio_osc,
optionPanel_tuio_tcp,
optionPanel_bin_tcp,
calibrationPanel,
calibrationPanel_calibrate,
calibrationPanel_warp,
sourcePanel,
sourcePanel_recording,
TemplatePanel,
TemplatePanel_minArea,
TemplatePanel_maxArea,
backgroundPanel,
backgroundPanel_remove,
backgroundPanel_dynamic,
backgroundPanel_learn_rate,
smoothPanel,
smoothPanel_use,
smoothPanel_smooth,
amplifyPanel,
amplifyPanel_use,
amplifyPanel_amp,
highpassPanel,
highpassPanel_use,
highpassPanel_blur,
highpassPanel_noise,
trackedPanel,
trackedPanel_darkblobs,
trackedPanel_use,
trackedPanel_threshold,
trackedPanel_min_movement,
trackedPanel_min_blob_size,
trackedPanel_max_blob_size,
trackedPanel_normalizing_on,
trackedPanel_low_normalizing,
trackedPanel_high_normalizing,
trackedPanel_outlines,
trackedPanel_ids,
trackingPanel, //Panel for selecting what to track-Fingers, Objects or Fiducials
trackingPanel_trackFingers,
trackingPanel_trackObjects,
trackingPanel_trackFiducials,
savePanel,
kParameter_SaveXml,
kParameter_File,
kParameter_LoadTemplateXml,
kParameter_SaveTemplateXml,
};
public:
ofxNCoreVision(bool debug)
{
ofAddListener(ofEvents.mousePressed, this, &ofxNCoreVision::_mousePressed);
ofAddListener(ofEvents.mouseDragged, this, &ofxNCoreVision::_mouseDragged);
ofAddListener(ofEvents.mouseReleased, this, &ofxNCoreVision::_mouseReleased);
ofAddListener(ofEvents.keyPressed, this, &ofxNCoreVision::_keyPressed);
ofAddListener(ofEvents.keyReleased, this, &ofxNCoreVision::_keyReleased);
ofAddListener(ofEvents.setup, this, &ofxNCoreVision::_setup);
ofAddListener(ofEvents.update, this, &ofxNCoreVision::_update);
ofAddListener(ofEvents.draw, this, &ofxNCoreVision::_draw);
ofAddListener(ofEvents.exit, this, &ofxNCoreVision::_exit);
#ifdef TARGET_WIN32
multiplexer = NULL;
dsvl = NULL;
#endif
debugMode = debug;
vidGrabber = NULL;
vidPlayer = NULL;
//initialize filter
filter = NULL;
filter_fiducial = NULL;
//fps and dsp calculation
frames = 0;
fps = 0;
lastFPSlog = 0;
differenceTime = 0;
//bools
bCalibration= 0;
bFullscreen = 0;
bcamera = 0;
bShowLabels = 1;
bMiniMode = 0;
bDrawOutlines = 1;
bGPUMode = 0;
bTUIOMode = 0;
bFidMode = 0;
showConfiguration = 0;
//camera
camRate = 30;
camWidth = 320;
camHeight = 240;
//ints/floats
backgroundLearnRate = .01;
MIN_BLOB_SIZE = 2;
MAX_BLOB_SIZE = 100;
contourFinder.bTrackFingers=false;
contourFinder.bTrackObjects=false;
contourFinder.bTrackFiducials=false;
//if auto tracker is defined then the tracker automagically comes up
//on startup..
#ifdef STANDALONE
bStandaloneMode = true;
#else
bStandaloneMode = false;
#endif
}
~ofxNCoreVision()
{
// AlexP
// C++ guarantees that operator delete checks its argument for null-ness
delete filter; filter = NULL;
delete filter_fiducial; filter_fiducial = NULL;
delete vidGrabber; vidGrabber = NULL;
delete vidPlayer; vidPlayer = NULL;
#ifdef TARGET_WIN32
delete multiplexer; multiplexer = NULL;
delete dsvl; dsvl = NULL;
#endif
}
/****************************************************************
* Public functions
****************************************************************/
ofxNCoreVision* Instance();
//Basic Events called every frame
void _setup(ofEventArgs &e);
void _update(ofEventArgs &e);
void _draw(ofEventArgs &e);
void _exit(ofEventArgs &e);
//Mouse Events
void _mousePressed(ofMouseEventArgs &e);
void _mouseDragged(ofMouseEventArgs &e);
void _mouseReleased(ofMouseEventArgs &e);
//Key Events
void _keyPressed(ofKeyEventArgs &e);
void _keyReleased(ofKeyEventArgs &e);
//GUI
void setupControls();
void handleGui(int parameterId, int task, void* data, int length);
ofxGui* controls;
//image processing stuff
void initDevice();
void getPixels();
void grabFrameToCPU();
void grabFrameToGPU(GLuint target);
//drawing
void drawFingerOutlines();
void drawMiniMode();
void drawFullMode();
void drawFiducials();
//Load/save settings
void loadXMLSettings();
void saveSettings();
//Getters
std::map<int, Blob> getBlobs();
std::map<int, Blob> getObjects();
/***************************************************************
* Video Capture Devices
***************************************************************/
#ifdef TARGET_WIN32
ofxMultiplexer* multiplexer;
ofxDSVL* dsvl;
ofxDShow* show;
#endif
ofVideoGrabber* vidGrabber;
ofVideoPlayer* vidPlayer;
/****************************************************************
* Variables in config.xml Settings file
*****************************************************************/
int deviceID;
int frameseq;
int threshold;
int wobbleThreshold;
int camRate;
unsigned int camWidth;
unsigned int camHeight;
int winWidth;
int winHeight;
int MIN_BLOB_SIZE;
int MAX_BLOB_SIZE;
float backgroundLearnRate;
bool showConfiguration;
bool bcamera;
bool bMiniMode;
bool bShowInterface;
bool bShowPressure;
bool bDrawOutlines;
bool bTUIOMode;
bool bFullscreen;
bool bCalibration;
bool bShowLabels;
bool bNewFrame;
//filters
bool bAutoBackground;
//modes
bool bGPUMode;
//Area slider variables
int minTempArea;
int maxTempArea;
//For the fiducial mode drawing
bool bFidMode;
//auto ~ standalone/non-addon
bool bStandaloneMode;
/*****************************************************
* Fiducial Finder
*******************************************************/
ofxFiducialTracker fidfinder;
float fiducialDrawFactor_Width; //To draw the Fiducials in the right place we have to scale from camWidth to filter->camWidth
float fiducialDrawFactor_Height;
Filters* filter_fiducial;
CPUImageFilter processedImg_fiducial;
/****************************************************
*End config.xml variables
*****************************************************/
//Debug mode variables
bool debugMode;
//FPS variables
int frames;
int fps;
float lastFPSlog;
int differenceTime;
//Fonts
ofTrueTypeFont verdana;
ofTrueTypeFont sidebarTXT;
ofTrueTypeFont bigvideo;
//Images
ofImage background;
//Blob Tracker
BlobTracker tracker;
//Template Utilities
TemplateUtils templates;
//Template Registration
ofRectangle rect;
ofRectangle minRect;
ofRectangle maxRect;
//Object Selection bools
bool isSelecting;
//Area sliders
/****************************************************************
* Private Stuff
****************************************************************/
string videoFileName;
int maxBlobs;
// The variable which will check the initilisation of camera
//to avoid multiple initialisation
bool cameraInited;
//Calibration
Calibration calib;
//Blob Finder
ContourFinder contourFinder;
//Image filters
Filters* filter;
CPUImageFilter processedImg;
ofxCvColorImage sourceImg;
//XML Settings Vars
ofxXmlSettings XML;
string message;
//Communication
TUIO myTUIO;
string tmpLocalHost;
int tmpPort;
int tmpFlashPort;
//Logging
char dateStr [9];
char timeStr [9];
time_t rawtime;
struct tm * timeinfo;
char fileName [80];
FILE * stream ;
};
#endif
| [
"[email protected]@da66ed7f-4d6a-8cb4-a557-1474cfe16edc"
] | [
[
[
1,
371
]
]
] |
f96d224a609663652b63ea4ec818d9bdaf6350b2 | 0531b270535a46f315ead3524e60fb70fd6055da | /Source/libkwl/Bot_Hybrid.cpp | c4fe0cc47da8d1eb9668bee57e08aceb609e00b2 | [] | no_license | jannispl/kwlbot | e7588283d395ea6d54f6a82d45f2f0577f66fde1 | a5c1ea65c38067747893eeccdae726faeedec0d5 | refs/heads/master | 2021-01-01T19:10:16.324535 | 2010-12-12T22:58:24 | 2010-12-12T22:58:24 | 33,863,720 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,466 | cpp | /*
kwlbot IRC bot
File: Bot_Hybrid.cpp
Purpose: Class which represents an IRC bot
IRCD-Hybrid service implementation
*/
#include "StdInc.h"
#include "Bot.h"
#include "WildcardMatch.h"
#include "IrcMessages.h"
#include <algorithm>
// Shortcut to call an event
#define CALL_EVENT_NOARG(what) \
for (CPool<CEventManager *>::iterator eventManagerIterator = m_pParentCore->GetEventManagers()->begin(); eventManagerIterator != m_pParentCore->GetEventManagers()->end(); ++eventManagerIterator) \
{ \
(*eventManagerIterator)->what(this); \
} \
m_pParentCore->GetScriptEventManager()->what(this)
#define CALL_EVENT(what, ...) \
for (CPool<CEventManager *>::iterator eventManagerIterator = m_pParentCore->GetEventManagers()->begin(); eventManagerIterator != m_pParentCore->GetEventManagers()->end(); ++eventManagerIterator) \
{ \
(*eventManagerIterator)->what(this, __VA_ARGS__); \
} \
m_pParentCore->GetScriptEventManager()->what(this, __VA_ARGS__)
#if defined(SERVICE) && IRCD == HYBRID
// TODO: IRCD-Hybrid implementation
/*
ircd-hybrid protocol notes
use SJOIN instead of JOIN: (DONE)
send_cmd(NULL, "SJOIN %ld %s + :%s", (long int) chantime, channel, user);
SJOIN 1284766570 #home + :LOLBOT
nick introduction:
NICK MaVe 1 1284766547 +i ~MaVe xdsl-89-0-34-142.netcologne.de hades.arpa :...
channel introduction:
:hades.arpa SJOIN 1284766548 #home +nt :@MaVe
*/
#endif
| [
"[email protected]@f9c66ffb-4930-c197-0f80-100fa691f586"
] | [
[
[
1,
50
]
]
] |
3abf2c640aef51e11e5993b4ac472208fec87ba0 | 5ff30d64df43c7438bbbcfda528b09bb8fec9e6b | /kgraphics/math/Triangle.cpp | 24da26db6ca54d635ebc0d4c7e15eef5a35578d4 | [] | no_license | lvtx/gamekernel | c80cdb4655f6d4930a7d035a5448b469ac9ae924 | a84d9c268590a294a298a4c825d2dfe35e6eca21 | refs/heads/master | 2016-09-06T18:11:42.702216 | 2011-09-27T07:22:08 | 2011-09-27T07:22:08 | 38,255,025 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 22,998 | cpp | #include <stdafx.h>
#include <kgraphics/math/Triangle.h>
#include <kgraphics/math/Vector3.h>
#include <kgraphics/math/Vector2.h>
#include <kgraphics/math/Ray3.h>
#include <kgraphics/math/math.h>
#include <kgraphics/math/Plane.h>
namespace gfx {
// helper functions
inline bool AdjustQ( const Vector3& P0, const Vector3& P1,
const Vector3& P2, const Vector3& Q0,
const Vector3& Q1, const Vector3& Q2,
float testQ0, float testQ1, float testQ2,
const Vector3& normalP );
inline bool TestLineOverlap( const Vector3& P0, const Vector3& P1,
const Vector3& P2, const Vector3& Q0,
const Vector3& Q1, const Vector3& Q2 );
inline bool CoplanarTriangleIntersect( const Vector3& P0,
const Vector3& P1, const Vector3& P2,
const Vector3& Q0, const Vector3& Q1,
const Vector3& Q2, const Vector3& planeNormal );
inline bool EdgeTest( const Vector2& edgePoint, const Vector2& edgeVector,
float n, const Vector2& P0, const Vector2& P1, const Vector2& P2 );
//-------------------------------------------------------------------------------
// @ ::IsPointInTriangle()
//-------------------------------------------------------------------------------
// Returns true if point on triangle plane lies inside triangle (3D version)
// Assumes triangle is not degenerate
//-------------------------------------------------------------------------------
bool IsPointInTriangle( const Vector3& point, const Vector3& P0,
const Vector3& P1, const Vector3& P2 )
{
Vector3 v0 = P1 - P0;
Vector3 v1 = P2 - P1;
Vector3 n = v0.Cross(v1);
Vector3 wTest = v0.Cross(point - P0);
if ( wTest.Dot(n) < 0.0f )
{
return false;
}
wTest = v1.Cross(point - P1);
if ( wTest.Dot(n) < 0.0f )
{
return false;
}
Vector3 v2 = P0 - P2;
wTest = v2.Cross(point - P2);
if ( wTest.Dot(n) < 0.0f )
{
return false;
}
return true;
}
//-------------------------------------------------------------------------------
// @ ::BarycentricCoordinates()
//-------------------------------------------------------------------------------
// Returns barycentric coordinates for point inside triangle (3D version)
// Assumes triangle is not degenerate
//-------------------------------------------------------------------------------
void BarycentricCoordinates( float &r, float &s, float& t,
const Vector3& point, const Vector3& P0,
const Vector3& P1, const Vector3& P2 )
{
// get difference vectors
Vector3 u = P1 - P0;
Vector3 v = P2 - P0;
Vector3 w = point - P0;
// compute cross product to get area of parallelograms
Vector3 a = u.Cross(w);
Vector3 b = v.Cross(w);
Vector3 c = u.Cross(v);
// compute barycentric coordinates as ratios of areas
float denom = 1.0f/c.Length();
s = b.Length()*denom;
t = a.Length()*denom;
r = 1.0f - s - t;
}
//-------------------------------------------------------------------------------
// @ ::TriangleIntersect()
//-------------------------------------------------------------------------------
// Returns true if triangles P0P1P2 and Q0Q1Q2 intersect
// Assumes triangle is not degenerate
//
// This is not the algorithm presented in the text. Instead, it is based on a
// recent article by Guigue and Devillers in the July 2003 issue Journal of
// Graphics Tools. As it is faster than the ERIT algorithm, under ordinary
// circumstances it would have been discussed in the text, but it arrived too late.
//
// More information and the original source code can be found at
// http://www.acm.org/jgt/papers/GuigueDevillers03/
//
// A nearly identical algorithm was in the same issue of JGT, by Shen Heng and
// Tang. See http://www.acm.org/jgt/papers/ShenHengTang03/ for source code.
//
// Yes, this is complicated. Did you think testing triangles would be easy?
//-------------------------------------------------------------------------------
bool TriangleIntersect( const Vector3& P0, const Vector3& P1,
const Vector3& P2, const Vector3& Q0,
const Vector3& Q1, const Vector3& Q2 )
{
// test P against Q's plane
Vector3 normalQ = (Q1-Q0).Cross(Q2-Q0);
float testP0 = normalQ.Dot( P0 - Q0 );
float testP1 = normalQ.Dot( P1 - Q0 );
float testP2 = normalQ.Dot( P2 - Q0 );
// P doesn't intersect Q's plane
if (testP0*testP1 > kEpsilon && testP0*testP2 > kEpsilon )
return false;
// test Q against P's plane
Vector3 normalP = (P1-P0).Cross(P2-P0);
float testQ0 = normalP.Dot( Q0 - P0 );
float testQ1 = normalP.Dot( Q1 - P0 );
float testQ2 = normalP.Dot( Q2 - P0 );
// Q doesn't intersect P's plane
if (testQ0*testQ1 > kEpsilon && testQ0*testQ2 > kEpsilon )
return false;
// now we rearrange P's vertices such that the lone vertex (the one that lies
// in its own half-space of Q) is first. We also permute the other
// triangle's vertices so that P0 will "see" them in counterclockwise order
// Once reordered, we pass the vertices down to a helper function which will
// reorder Q's vertices, and then test
// P0 in Q's positive half-space
if (testP0 > kEpsilon)
{
// P1 in Q's positive half-space (so P2 is lone vertex)
if (testP1 > kEpsilon)
return AdjustQ(P2, P0, P1, Q0, Q2, Q1, testQ0, testQ2, testQ1, normalP);
// P2 in Q's positive half-space (so P1 is lone vertex)
else if (testP2 > kEpsilon)
return AdjustQ(P1, P2, P0, Q0, Q2, Q1, testQ0, testQ2, testQ1, normalP);
// P0 is lone vertex
else
return AdjustQ(P0, P1, P2, Q0, Q1, Q2, testQ0, testQ1, testQ2, normalP);
}
// P0 in Q's negative half-space
else if (testP0 < -kEpsilon)
{
// P1 in Q's negative half-space (so P2 is lone vertex)
if (testP1 < -kEpsilon)
return AdjustQ(P2, P0, P1, Q0, Q1, Q2, testQ0, testQ1, testQ2, normalP);
// P2 in Q's negative half-space (so P1 is lone vertex)
else if (testP2 < -kEpsilon)
return AdjustQ(P1, P2, P0, Q0, Q1, Q2, testQ0, testQ1, testQ2, normalP);
// P0 is lone vertex
else
return AdjustQ(P0, P1, P2, Q0, Q2, Q1, testQ0, testQ2, testQ1, normalP);
}
// P0 on Q's plane
else
{
// P1 in Q's negative half-space
if (testP1 < -kEpsilon)
{
// P2 in Q's negative half-space (P0 is lone vertex)
if (testP2 < -kEpsilon)
return AdjustQ(P0, P1, P2, Q0, Q1, Q2, testQ0, testQ1, testQ2, normalP);
// P2 in positive half-space or on plane (P1 is lone vertex)
else
return AdjustQ(P1, P2, P0, Q0, Q2, Q1, testQ0, testQ2, testQ1, normalP);
}
// P1 in Q's positive half-space
else if (testP1 > kEpsilon)
{
// P2 in Q's positive half-space (P0 is lone vertex)
if (testP2 > kEpsilon)
return AdjustQ(P0, P1, P2, Q0, Q2, Q1, testQ0, testQ2, testQ1, normalP);
// P2 in negative half-space or on plane (P1 is lone vertex)
else
return AdjustQ(P1, P2, P0, Q0, Q1, Q2, testQ0, testQ1, testQ2, normalP);
}
// P1 lies on Q's plane too
else
{
// P2 in Q's positive half-space (P2 is lone vertex)
if (testP2 > kEpsilon)
return AdjustQ(P2, P0, P1, Q0, Q1, Q2, testQ0, testQ1, testQ2, normalP);
// P2 in Q's negative half-space (P2 is lone vertex)
// note different ordering for Q vertices
else if (testP2 < -kEpsilon)
return AdjustQ(P2, P0, P1, Q0, Q2, Q1, testQ0, testQ2, testQ1, normalP);
// all three points lie on Q's plane, default to 2D test
else
return CoplanarTriangleIntersect(P0, P1, P2, Q0, Q1, Q2, normalP);
}
}
}
//-------------------------------------------------------------------------------
// @ ::AdjustQ()
//-------------------------------------------------------------------------------
// Helper for TriangleIntersect()
//
// Now we rearrange Q's vertices such that the lone vertex (the one that lies
// in its own half-space of P) is first. We also permute the other
// triangle's vertices so that Q0 will "see" them in counterclockwise order
//
// Once reordered, we pass the vertices down to a helper function which will
// actually test for intersection on the common line between the two planes
//-------------------------------------------------------------------------------
inline bool
AdjustQ( const Vector3& P0, const Vector3& P1,
const Vector3& P2, const Vector3& Q0,
const Vector3& Q1, const Vector3& Q2,
float testQ0, float testQ1, float testQ2,
const Vector3& normalP )
{
// Q0 in P's positive half-space
if (testQ0 > kEpsilon)
{
// Q1 in P's positive half-space (so Q2 is lone vertex)
if (testQ1 > kEpsilon)
return TestLineOverlap(P0, P2, P1, Q2, Q0, Q1);
// Q2 in P's positive half-space (so Q1 is lone vertex)
else if (testQ2 > kEpsilon)
return TestLineOverlap(P0, P2, P1, Q1, Q2, Q0);
// Q0 is lone vertex
else
return TestLineOverlap(P0, P1, P2, Q0, Q1, Q2);
}
// Q0 in P's negative half-space
else if (testQ0 < -kEpsilon)
{
// Q1 in P's negative half-space (so Q2 is lone vertex)
if (testQ1 < -kEpsilon)
return TestLineOverlap(P0, P1, P2, Q2, Q0, Q1);
// Q2 in P's negative half-space (so Q1 is lone vertex)
else if (testQ2 < -kEpsilon)
return TestLineOverlap(P0, P1, P2, Q1, Q2, Q0);
// Q0 is lone vertex
else
return TestLineOverlap(P0, P2, P1, Q0, Q1, Q2);
}
// Q0 on P's plane
else
{
// Q1 in P's negative half-space
if (testQ1 < -kEpsilon)
{
// Q2 in P's negative half-space (Q0 is lone vertex)
if (testQ2 < -kEpsilon)
return TestLineOverlap(P0, P1, P2, Q0, Q1, Q2);
// Q2 in positive half-space or on plane (P1 is lone vertex)
else
return TestLineOverlap(P0, P2, P1, Q1, Q2, Q0);
}
// Q1 in P's positive half-space
else if (testQ1 > kEpsilon)
{
// Q2 in P's positive half-space (Q0 is lone vertex)
if (testQ2 > kEpsilon)
return TestLineOverlap(P0, P2, P1, Q0, Q1, Q2);
// Q2 in negative half-space or on plane (P1 is lone vertex)
else
return TestLineOverlap(P0, P1, P2, Q1, Q2, Q0);
}
// Q1 lies on P's plane too
else
{
// Q2 in P's positive half-space (Q2 is lone vertex)
if (testQ2 > kEpsilon)
return TestLineOverlap(P0, P1, P2, Q2, Q0, Q1);
// Q2 in P's negative half-space (Q2 is lone vertex)
// note different ordering for Q vertices
else if (testQ2 < -kEpsilon)
return TestLineOverlap(P0, P2, P1, Q2, Q0, Q1);
// all three points lie on P's plane, default to 2D test
else
return CoplanarTriangleIntersect(P0, P1, P2, Q0, Q1, Q2, normalP);
}
}
}
//-------------------------------------------------------------------------------
// @ ::TestLineOverlap()
//-------------------------------------------------------------------------------
// Helper for TriangleIntersect()
//
// This tests whether the rearranged triangles overlap, by checking the intervals
// where their edges cross the common line between the two planes. If the
// interval for P is [i,j] and Q is [k,l], then there is intersection if the
// intervals overlap. Previous algorithms computed these intervals directly,
// this tests implictly by using two "plane tests."
//-------------------------------------------------------------------------------
inline bool
TestLineOverlap( const Vector3& P0, const Vector3& P1,
const Vector3& P2, const Vector3& Q0,
const Vector3& Q1, const Vector3& Q2 )
{
// get "plane normal"
Vector3 normal = (P1-P0).Cross(Q0-P0);
// fails test, no intersection
if ( normal.Dot( Q1 - P0 ) > kEpsilon )
return false;
// get "plane normal"
normal = (P2-P0).Cross(Q2-P0);
// fails test, no intersection
if ( normal.Dot( Q0 - P0 ) > kEpsilon )
return false;
// intersection!
return true;
}
//-------------------------------------------------------------------------------
// @ ::CoplanarTriangleIntersect()
//-------------------------------------------------------------------------------
// Helper for TriangleIntersect()
//
// This projects the two triangles down to 2D, maintaining the largest area by
// dropping the dimension where the normal points the farthest.
//-------------------------------------------------------------------------------
inline bool CoplanarTriangleIntersect( const Vector3& P0,
const Vector3& P1, const Vector3& P2,
const Vector3& Q0, const Vector3& Q1,
const Vector3& Q2, const Vector3& planeNormal )
{
Vector3 absNormal( Abs(planeNormal.x), Abs(planeNormal.y),
Abs(planeNormal.z) );
Vector2 projP0, projP1, projP2;
Vector2 projQ0, projQ1, projQ2;
// if x is direction of largest magnitude
if ( absNormal.x > absNormal.y && absNormal.x >= absNormal.z )
{
projP0.Set( P0.y, P0.z );
projP1.Set( P1.y, P1.z );
projP2.Set( P2.y, P2.z );
projQ0.Set( Q0.y, Q0.z );
projQ1.Set( Q1.y, Q1.z );
projQ2.Set( Q2.y, Q2.z );
}
// if y is direction of largest magnitude
else if ( absNormal.y > absNormal.x && absNormal.y >= absNormal.z )
{
projP0.Set( P0.x, P0.z );
projP1.Set( P1.x, P1.z );
projP2.Set( P2.x, P2.z );
projQ0.Set( Q0.x, Q0.z );
projQ1.Set( Q1.x, Q1.z );
projQ2.Set( Q2.x, Q2.z );
}
// z is the direction of largest magnitude
else
{
projP0.Set( P0.x, P0.y );
projP1.Set( P1.x, P1.y );
projP2.Set( P2.x, P2.y );
projQ0.Set( Q0.x, Q0.y );
projQ1.Set( Q1.x, Q1.y );
projQ2.Set( Q2.x, Q2.y );
}
return TriangleIntersect( projP0, projP1, projP2, projQ0, projQ1, projQ2 );
}
//-------------------------------------------------------------------------------
// @ ::TriangleIntersect()
//-------------------------------------------------------------------------------
// Returns true if ray intersects triangle
//-------------------------------------------------------------------------------
bool
TriangleIntersect( float& t, const Vector3& P0, const Vector3& P1,
const Vector3& P2, const Ray3& ray )
{
// test ray direction against triangle
Vector3 e1 = P1 - P0;
Vector3 e2 = P2 - P0;
Vector3 p = ray.GetDirection().Cross(e2);
float a = e1.Dot(p);
// if result zero, no intersection or infinite intersections
// (ray parallel to triangle plane)
if ( IsZero(a) )
return false;
// compute denominator
float f = 1.0f/a;
// compute barycentric coordinates
Vector3 s = ray.GetOrigin() - P0;
float u = f*s.Dot(p);
// ray falls outside triangle
if (u < 0.0f || u > 1.0f)
return false;
Vector3 q = s.Cross(e1);
float v = f*ray.GetDirection().Dot(q);
// ray falls outside triangle
if (v < 0.0f || u+v > 1.0f)
return false;
// compute line parameter
t = f*e2.Dot(q);
return (t >= 0.0f);
}
//-------------------------------------------------------------------------------
// @ ::TriangleClassify()
//-------------------------------------------------------------------------------
// Returns signed distance between plane and triangle
//-------------------------------------------------------------------------------
float
TriangleClassify( const Vector3& P0, const Vector3& P1,
const Vector3& P2, const Plane& plane )
{
float test0 = plane.Test( P0 );
float test1 = plane.Test( P1 );
// if two points lie on opposite sides of plane, intersect
if (test0*test1 < 0.0f)
return 0.0f;
float test2 = plane.Test( P2 );
// if two points lie on opposite sides of plane, intersect
if (test0*test2 < 0.0f)
return 0.0f;
if (test1*test2 < 0.0f)
return 0.0f;
// no intersection, return signed distance
if ( test0 < 0.0f )
{
if ( test0 < test1 )
{
if ( test1 < test2 )
return test2;
else
return test1;
}
else if (test0 < test2)
{
return test2;
}
else
{
return test0;
}
}
else
{
if ( test0 > test1 )
{
if ( test1 > test2 )
return test2;
else
return test1;
}
else if (test0 > test2)
{
return test2;
}
else
{
return test0;
}
}
}
//-------------------------------------------------------------------------------
// @ ::IsPointInTriangle()
//-------------------------------------------------------------------------------
// Returns true if point lies inside triangle (2D version)
// Assumes triangle is not degenerate
//-------------------------------------------------------------------------------
bool IsPointInTriangle( const Vector2& point, const Vector2& P0,
const Vector2& P1, const Vector2& P2 )
{
Vector2 v0 = P1 - P0;
Vector2 v1 = P2 - P1;
float n = v0.PerpDot(v1);
float wTest = v0.PerpDot(point - P0);
if ( wTest*n < 0.0f )
{
return false;
}
wTest = v1.PerpDot(point - P1);
if ( wTest*n < 0.0f )
{
return false;
}
Vector2 v2 = P0 - P2;
wTest = v2.PerpDot(point - P2);
if ( wTest*n < 0.0f )
{
return false;
}
return true;
} // End of IsPointInTriangle()
//-------------------------------------------------------------------------------
// @ ::BarycentricCoordinates()
//-------------------------------------------------------------------------------
// Returns barycentric coordinates for point inside triangle (2D version)
// Assumes triangle is not degenerate
//-------------------------------------------------------------------------------
void BarycentricCoordinates( float &r, float &s, float& t,
const Vector2& point, const Vector2& P0,
const Vector2& P1, const Vector2& P2 )
{
// get difference vectors
Vector2 u = P1 - P0;
Vector2 v = P2 - P0;
Vector2 w = point - P0;
// compute perpendicular dot product to get area of parallelograms
float a = u.PerpDot(w);
float b = v.PerpDot(w);
float c = u.PerpDot(v);
// compute barycentric coordinates as ratios of areas
float denom = 1.0f/c;
s = b*denom;
t = a*denom;
r = 1.0f - s - t;
} // End of BarycentricCoordinates()
//-------------------------------------------------------------------------------
// @ ::TriangleIntersect()
//-------------------------------------------------------------------------------
// Returns true if triangles P0P1P2 and Q0Q1Q2 intersect (2D version)
// Assumes triangle is not degenerate
//
// Uses principle of separating planes again: if all three points of one triangle
// lie outside one edge of the other, then they are disjoint
//
// This could probably be made faster.
// See // http://www.acm.org/jgt/papers/GuigueDevillers03/ for another possible
// implementation.
//-------------------------------------------------------------------------------
bool TriangleIntersect( const Vector2& P0, const Vector2& P1,
const Vector2& P2, const Vector2& Q0,
const Vector2& Q1, const Vector2& Q2 )
{
// test Q against P
Vector2 v0 = P1 - P0;
Vector2 v1 = P2 - P1;
float n = v0.PerpDot(v1);
// test against edge 0
if (EdgeTest( P0, v0, n, Q0, Q1, Q2 ))
return false;
// test against edge 1
if (EdgeTest( P1, v1, n, Q0, Q1, Q2 ))
return false;
// test against edge 2
Vector2 v2 = P0 - P2;
if (EdgeTest( P2, v2, n, Q0, Q1, Q2 ))
return false;
// test P against Q
v0 = Q1 - Q0;
v1 = Q2 - Q1;
n = v0.PerpDot(v1);
// test against edge 0
if (EdgeTest( Q0, v0, n, P0, P1, P2 ))
return false;
// test against edge 1
if (EdgeTest( Q1, v1, n, P0, P1, P2 ))
return false;
// test against edge 2
v2 = Q0 - Q2;
if (EdgeTest( Q2, v2, n, P0, P1, P2 ))
return false;
return true;
}
//-------------------------------------------------------------------------------
// @ ::EdgeTest()
//-------------------------------------------------------------------------------
// Helper function for 2D TriangleIntersect()
//
// Given an edge vector and origin, triangle "normal" value, and three points,
// determine if all three points lie outside the edge
//-------------------------------------------------------------------------------
inline bool
EdgeTest( const Vector2& edgePoint, const Vector2& edgeVector, float n,
const Vector2& P0, const Vector2& P1, const Vector2& P2 )
{
// test each point against the edge in turn
float wTest = edgeVector.PerpDot(P0 - edgePoint);
if ( wTest*n > 0.0f )
{
return false;
}
wTest = edgeVector.PerpDot(P1 - edgePoint);
if ( wTest*n > 0.0f )
{
return false;
}
wTest = edgeVector.PerpDot(P2 - edgePoint);
if ( wTest*n > 0.0f )
{
return false;
}
return true;
}
} // namespace gfx
| [
"keedongpark@keedongpark"
] | [
[
[
1,
654
]
]
] |
a9b6834c4cca4e00533b4b336756980d474671a2 | 5e0422794380a8f3bf06d0c37ac2354f4b91fefb | /fastnet/session_acceptor_factory.h | e639226a3da3e67ab926f99d49afc284e198cd16 | [] | no_license | OrAlien/fastnetwork | 1d8fb757b855b1f23cc844cda4d8dc7a568bc38e | 792d28d8b5829c227aebe8378f60db17de4d6f14 | refs/heads/master | 2021-05-28T20:30:24.031458 | 2010-06-02T14:30:04 | 2010-06-02T14:30:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 444 | h | #pragma once
#include "session_type.h"
#include "datagram_acceptor.h"
namespace fastnet
{
class session_acceptor_factory
{
public:
session_acceptor_factory(void);
~session_acceptor_factory(void);
public:
static session_acceptor * new_session_acceptor( transport_type type ) {
switch( type ) {
case UDP:
return new fastnet::udp::datagram_acceptor();
break;
default:
return NULL;
}
}
};
} | [
"everwanna@8b0bd7a0-72c1-11de-90d8-1fdda9445408"
] | [
[
[
1,
27
]
]
] |
4ab30d7265f94b61bc150ff596d3dc4955bb3840 | 2f77d5232a073a28266f5a5aa614160acba05ce6 | /01.DevelopLibrary/SaveSmsTest/InfoCenterOfSmartPhone/NewSmsWnd.h | 49fb8b168df1d67cc2eaa47cce53d0c3e39e222a | [] | no_license | radtek/mobilelzz | 87f2d0b53f7fd414e62c8b2d960e87ae359c81b4 | 402276f7c225dd0b0fae825013b29d0244114e7d | refs/heads/master | 2020-12-24T21:21:30.860184 | 2011-03-26T02:19:47 | 2011-03-26T02:19:47 | 58,142,323 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,117 | h |
#ifndef __NewSmsWnd_h__
#define __NewSmsWnd_h__
//此代码演示了:
// 创建和初始化应用程序
// 创建和初始化窗体
// 按钮控件的使用及其命令消息的处理
// 单行文本编辑器
// 文字按钮工具条
// 响应屏幕旋转的消息以及处理旋转后ToolBarText的位置
#define MZ_IDC_SEND_SMS_BTN 101
#define IDC_PPM_OK 102
#define IDC_PPM_CANCEL 103
#define MZ_IDC_RECIEVERS_EDIT 104
#define MZ_IDC_SMS_MSG_EDIT 105
#define MZ_IDC_CONTACTORS_BTN 106
#define PROGRESS_TIMER_ID 111
#define BUTTON_WIDTH_V 150
#define BUTTON_WIDTH_H 150
#define BUTTON_HEIGHT_VH 65
// 从 CMzWndEx 派生的主窗口类
class CMyEdit: public UiEdit
{
public:
virtual ~CMyEdit()
{
ReleaseCapture();
}
};
class CNewSmsWnd: public CMzWndEx
{
MZ_DECLARE_DYNAMIC(CNewSmsWnd);
public:
CNewSmsWnd()
{
m_lCurProgress = 0;
m_SmsMsgEdit = new CMyEdit;
}
virtual ~CNewSmsWnd(){
MzAccClose();
}
static DWORD WINAPI ProxyRun(LPVOID lp);
void Run();
void UpdateData( MyListItemData* pRecivers,long lReciversCount );
// 按钮
UiButton m_SendSmsBtn;
UiButton m_ContactorsBtn;
MzPopupProgress m_progress;
long m_lCurProgress;
// 文本
UiEditControl m_Recievers;
CMyEdit* m_SmsMsgEdit;
DWORD m_accMsg;
protected:
// 窗口的初始化
virtual BOOL OnInitDialog();
// 重载命令消息的处理函数
virtual void OnMzCommand(WPARAM wParam, LPARAM lParam);
LRESULT MzDefWndProc(UINT message, WPARAM wParam, LPARAM lParam);
// 转屏后如果需要调整窗口的位置,重载此函数响应 WM_SETTINGCHANGE 消息
virtual void OnSettingChange(DWORD wFlag, LPCTSTR pszSectionName);
bool SendSMS(IN LPCTSTR lpNumber,IN LPCTSTR lpszMessage);
bool SendSMS_Wrapper(IN CMzString& Number);
void OnTimer(UINT_PTR nIDEvent);
// HRESULT smsInsert( wchar_t **pwcNo, long lCnt, wchar_t *pContent );
HRESULT smsInsert( wchar_t *pwcNo, wchar_t *pContent );
};
#endif //__NewSmsWnd_h__ | [
"[email protected]"
] | [
[
[
1,
98
]
]
] |
50a8197b7cf43e63150fec2e95eef7597fd27560 | 3af6c2119743037b41eee8a46244ade56a2ac3e3 | /Cpp/Box2D/Joints/Box2dDistanceJointRef.h | a308a83c9bca1c0fea6be7e32cdb62e885dd583c | [
"MIT"
] | permissive | TheProjecter/tgb-box2d-integration | 16f848a8deb89d4ecbd4061712c385c19225b1b7 | 85cbc6e45f563dafc0b05e75a8f08338e1a5941a | refs/heads/master | 2021-01-10T19:20:19.741374 | 2009-05-02T12:35:20 | 2009-05-02T12:35:20 | 42,947,643 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,955 | h | //=============================================================================
// Box2dDistanceJointRef.h
//=============================================================================
/*
TGB-Box2D-Integration (http://code.google.com/p/tgb-box2d-integration/)
Copyright (c) 2009 Michael Woerister
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef _BOX2D_DISTANCE_JOINT_REF_H_
#define _BOX2D_DISTANCE_JOINT_REF_H_
#include "./Box2dJointRef.h"
//=============================================================================
// class Box2dDistanceJointRef
//=============================================================================
class Box2dDistanceJointRef : public Box2dJointRef {
public:
DECLARE_CONOBJECT(Box2dDistanceJointRef);
private:
typedef Box2dJointRef Parent;
b2DistanceJoint * joint() const
{
return static_cast<b2DistanceJoint*>( this->getJoint() );
}
};
#endif
| [
"michaelwoerister@f3bf45be-f2fd-11dd-89c5-9df526a60542"
] | [
[
[
1,
48
]
]
] |
4713f34527b8a7c9db89ea6fd27ff8a3baa91310 | d8ee6216089aa884589ca9175d3bc191dcc1ea12 | /PostEffectProgram/Include/Utilities.h | 0d3779288c6cd7486a9803645a5d6d4b812f5226 | [] | no_license | OtterOrder/posteffectprogram | a15035eb96a107ec220f834baeb4c4db2573fd56 | ff713b71ba72984e74fc62e9a1f7b1fb8fb43198 | refs/heads/master | 2016-09-05T09:06:20.138050 | 2009-06-30T07:21:43 | 2009-06-30T07:21:43 | 32,115,407 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,343 | h | #pragma once
#include "Types.h"
//------------------------------------------------------------------------------------------------------------------------------
#define SAFE_DELETE(p) \
{ \
if (p) \
{ \
delete p; \
p = NULL; \
} \
}
//------------------------------------------------------------------------------------------------------------------------------
#define SAFE_RELEASE(p) \
{ \
if (p) \
{ \
p->Release(); \
p = NULL; \
} \
}
//------------------------------------------------------------------------------------------------------------------------------
#define SAFE_NEW(p, type) \
{ \
if (!p) \
{ \
p = new type; \
} \
}
//------------------------------------------------------------------------------------------------------------------------------
#include <vector>
#define DefineVectorIterator(type, name) typedef std::vector< type* >::iterator name
//------------------------------------------------------------------------------------------------------------------------------
bool Warning(bool _test, cStr _str);
#define WarningReturn(test, msg) \
{ \
if (Warning(test, msg)) \
{ \
return; \
} \
}
#define getDevice Renderer::GetDevice()
| [
"alban.chagnoleau@7ea0d518-2368-11de-96a1-5542d1fc8aa6",
"germain.mazac@7ea0d518-2368-11de-96a1-5542d1fc8aa6"
] | [
[
[
1,
49
]
],
[
[
50,
51
]
]
] |
863ba5110999dd640e651d29173e5808566a94a0 | 9a48be80edc7692df4918c0222a1640545384dbb | /Libraries/Boost1.40/libs/spirit/test/qi/and_predicate.cpp | ddd2d13e52c4180cb1751b620833557cb90d6d0a | [
"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 | 839 | cpp | /*=============================================================================
Copyright (c) 2001-2007 Joel de Guzman
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#include <boost/detail/lightweight_test.hpp>
#include <boost/spirit/include/qi_operator.hpp>
#include <boost/spirit/include/qi_numeric.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <iostream>
#include "test.hpp"
int
main()
{
using spirit_test::test;
using namespace boost::spirit;
{
BOOST_TEST((test("1234", &int_, false)));
BOOST_TEST((!test("abcd", &int_)));
}
return boost::report_errors();
}
| [
"metrix@Blended.(none)"
] | [
[
[
1,
27
]
]
] |
b514de08b0aebada84f35c618b1c8eb84f2d4b3c | ce262ae496ab3eeebfcbb337da86d34eb689c07b | /SEFoundation/SESceneGraph/SEUnculledObject.h | 963feb8c98ae624bffe0b6cd85644551c5a5bcdb | [] | 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 | 1,561 | 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_UnculledObject_H
#define Swing_UnculledObject_H
#include "SEFoundationLIB.h"
#include "SEPlatforms.h"
#include "SESystem.h"
namespace Swing
{
class SEEffect;
class SESpatial;
//----------------------------------------------------------------------------
// Description:
// Author:Sun Che
// Date:20080707
//----------------------------------------------------------------------------
class SE_FOUNDATION_API SEUnculledObject
{
public:
SESpatial* Object;
SEEffect* GlobalEffect;
inline bool IsRenderable(void) const;
};
#include "SEUnculledObject.inl"
}
#endif
| [
"[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac"
] | [
[
[
1,
52
]
]
] |
65eec260070d9ff4c9027baaca08d9fecf5ae6e3 | 93176e72508a8b04769ee55bece71095d814ec38 | /Utilities/otbliblas/include/liblas/external/property_tree/detail/xml_parser_write.hpp | 88c98fa8021efd707850e584e4614e5d94021632 | [
"MIT",
"BSL-1.0"
] | permissive | inglada/OTB | a0171a19be1428c0f3654c48fe5c35442934cf13 | 8b6d8a7df9d54c2b13189e00ba8fcb070e78e916 | refs/heads/master | 2021-01-19T09:23:47.919676 | 2011-06-29T17:29:21 | 2011-06-29T17:29:21 | 1,982,100 | 4 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 7,480 | hpp | // ----------------------------------------------------------------------------
// Copyright (C) 2002-2006 Marcin Kalicinski
//
// 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)
//
// For more information, see www.boost.org
// ----------------------------------------------------------------------------
#ifndef BOOST_PROPERTY_TREE_DETAIL_XML_PARSER_WRITE_HPP_INCLUDED
#define BOOST_PROPERTY_TREE_DETAIL_XML_PARSER_WRITE_HPP_INCLUDED
#include <liblas/external/property_tree/ptree.hpp>
#include <liblas/external/property_tree/detail/xml_parser_utils.hpp>
#include <string>
#include <ostream>
#include <iomanip>
namespace liblas { namespace property_tree { namespace xml_parser
{
template<class Ch>
void write_xml_indent(std::basic_ostream<Ch> &stream,
int indent,
const xml_writer_settings<Ch> & settings
)
{
stream << std::basic_string<Ch>(indent * settings.indent_count, settings.indent_char);
}
template<class Ch>
void write_xml_comment(std::basic_ostream<Ch> &stream,
const std::basic_string<Ch> &s,
int indent,
bool separate_line,
const xml_writer_settings<Ch> & settings
)
{
typedef typename std::basic_string<Ch> Str;
if (separate_line)
write_xml_indent(stream,indent,settings);
stream << Ch('<') << Ch('!') << Ch('-') << Ch('-');
stream << s;
stream << Ch('-') << Ch('-') << Ch('>');
if (separate_line)
stream << Ch('\n');
}
template<class Ch>
void write_xml_text(std::basic_ostream<Ch> &stream,
const std::basic_string<Ch> &s,
int indent,
bool separate_line,
const xml_writer_settings<Ch> & settings
)
{
if (separate_line)
write_xml_indent(stream,indent,settings);
stream << encode_char_entities(s);
if (separate_line)
stream << Ch('\n');
}
template<class Ptree>
void write_xml_element(std::basic_ostream<typename Ptree::key_type::value_type> &stream,
const std::basic_string<typename Ptree::key_type::value_type> &key,
const Ptree &pt,
int indent,
const xml_writer_settings<typename Ptree::key_type::value_type> & settings)
{
typedef typename Ptree::key_type::value_type Ch;
typedef typename std::basic_string<Ch> Str;
typedef typename Ptree::const_iterator It;
bool want_pretty = settings.indent_count > 0;
// Find if elements present
bool has_elements = false;
bool has_attrs_only = pt.data().empty();
for (It it = pt.begin(), end = pt.end(); it != end; ++it)
{
if (it->first != xmlattr<Ch>() )
{
has_attrs_only = false;
if (it->first != xmltext<Ch>())
{
has_elements = true;
break;
}
}
}
// Write element
if (pt.data().empty() && pt.empty()) // Empty key
{
if (indent >= 0)
{
write_xml_indent(stream,indent,settings);
stream << Ch('<') << key <<
Ch('/') << Ch('>');
if (want_pretty)
stream << Ch('\n');
}
}
else // Nonempty key
{
// Write opening tag, attributes and data
if (indent >= 0)
{
// Write opening brace and key
write_xml_indent(stream,indent,settings);
stream << Ch('<') << key;
// Write attributes
if (::boost::optional<const Ptree &> attribs = pt.get_child_optional(xmlattr<Ch>()))
for (It it = attribs.get().begin(); it != attribs.get().end(); ++it)
stream << Ch(' ') << it->first << Ch('=') <<
Ch('"') << it->second.template get_value<std::basic_string<Ch> >() << Ch('"');
if ( has_attrs_only )
{
// Write closing brace
stream << Ch('/') << Ch('>');
if (want_pretty)
stream << Ch('\n');
}
else
{
// Write closing brace
stream << Ch('>');
// Break line if needed and if we want pretty-printing
if (has_elements && want_pretty)
stream << Ch('\n');
}
}
// Write data text, if present
if (!pt.data().empty())
write_xml_text(stream,
pt.template get_value<std::basic_string<Ch> >(),
indent + 1, has_elements && want_pretty, settings);
// Write elements, comments and texts
for (It it = pt.begin(); it != pt.end(); ++it)
{
if (it->first == xmlattr<Ch>())
continue;
else if (it->first == xmlcomment<Ch>())
write_xml_comment(stream,
it->second.template get_value<std::basic_string<Ch> >(),
indent + 1, want_pretty, settings);
else if (it->first == xmltext<Ch>())
write_xml_text(stream,
it->second.template get_value<std::basic_string<Ch> >(),
indent + 1, has_elements && want_pretty, settings);
else
write_xml_element(stream, it->first, it->second,
indent + 1, settings);
}
// Write closing tag
if (indent >= 0 && !has_attrs_only)
{
if (has_elements)
write_xml_indent(stream,indent,settings);
stream << Ch('<') << Ch('/') << key << Ch('>');
if (want_pretty)
stream << Ch('\n');
}
}
}
template<class Ptree>
void write_xml_internal(std::basic_ostream<typename Ptree::key_type::value_type> &stream,
const Ptree &pt,
const std::string &filename,
const xml_writer_settings<typename Ptree::key_type::value_type> & settings)
{
typedef typename Ptree::key_type::value_type Ch;
typedef typename std::basic_string<Ch> Str;
stream << detail::widen<Ch>("<?xml version=\"1.0\" encoding=\"")
<< settings.encoding
<< detail::widen<Ch>("\"?>\n");
write_xml_element(stream, Str(), pt, -1, settings);
if (!stream)
BOOST_PROPERTY_TREE_THROW(xml_parser_error("write error", filename, 0));
}
} } }
#endif
| [
"[email protected]"
] | [
[
[
1,
194
]
]
] |
730620c5a528cdb20916def16462ee67a45f779b | fc4946d917dc2ea50798a03981b0274e403eb9b7 | /gentleman/gentleman/WindowsAPICodePack/WindowsAPICodePack/DirectX/DirectX/DirectWrite/DWriteFontFace.h | e048433200ec00132f7cb87e6b8f10bb7b60c5e1 | [] | no_license | midnite8177/phever | f9a55a545322c9aff0c7d0c45be3d3ddd6088c97 | 45529e80ebf707e7299887165821ca360aa1907d | refs/heads/master | 2020-05-16T21:59:24.201346 | 2010-07-12T23:51:53 | 2010-07-12T23:51:53 | 34,965,829 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 6,914 | h | //Copyright (c) Microsoft Corporation. All rights reserved.
#pragma once
#include "DirectUnknown.h"
#include "DWriteStructs.h"
#ifdef GetGlyphIndices // make sure the ::GetGlyphIndices function is undefined
#undef GetGlyphIndices
#endif
using namespace Microsoft::WindowsAPICodePack::DirectX;
namespace Microsoft { namespace WindowsAPICodePack { namespace DirectX { namespace DirectWrite {
/// <summary>
/// Represents an absolute reference to a font face.
/// It contains font face type, appropriate file references and face identification data.
/// Various font data such as metrics, names and glyph outlines is obtained from FontFace.
/// </summary>
public ref class FontFace : public DirectUnknown
{
public:
/// <summary>
/// The file format type of a font face.
/// </summary>
property FontFaceType FaceType
{
FontFaceType get();
}
/// <summary>
/// The zero-based index of the font face in its font file or files. If the font files contain a single face,
/// the return value is zero.
/// </summary>
property UINT32 Index
{
UINT32 get();
}
/// <summary>
/// The algorithmic style simulation flags of a font face.
/// </summary>
property FontSimulations Simulations
{
FontSimulations get();
}
/// <summary>
/// Determines whether the font is a symbol font.
/// </summary>
property Boolean IsSymbolFont
{
Boolean get();
}
/// <summary>
/// Obtains design units and common metrics for the font face.
/// These metrics are applicable to all the glyphs within a fontface and are used by applications for layout calculations.
/// </summary>
property FontMetrics Metrics
{
FontMetrics get();
}
/// <summary>
/// The number of glyphs in the font face.
/// </summary>
property UINT16 GlyphCount
{
UINT16 get();
}
/// <summary>
/// Obtains ideal glyph metrics in font design units. Design glyphs metrics are used for glyph positioning.
/// </summary>
/// <param name="glyphIndices">An array of glyph indices to compute the metrics for.</param>
/// <param name="isSideways">Indicates whether the font is being used in a sideways run.
/// This can affect the glyph metrics if the font has oblique simulation
/// because sideways oblique simulation differs from non-sideways oblique simulation.</param>
/// <returns>
/// Array of <see cref="GlyphMetrics"/> structures filled by this function.
/// The metrics returned by this function are in font design units.
/// </returns>
array<GlyphMetrics>^ GetDesignGlyphMetrics(
array<UINT16>^ glyphIndices,
BOOL isSideways);
/// <summary>
/// Obtains ideal glyph metrics in font design units. Design glyphs metrics are used for glyph positioning.
/// This function assume Sideways is false.
/// </summary>
/// <param name="glyphIndices">An array of glyph indices to compute the metrics for.</param>
/// <returns>
/// Array of <see cref="GlyphMetrics"/> structures filled by this function.
/// The metrics returned by this function are in font design units.
/// </returns>
array<GlyphMetrics>^ GetDesignGlyphMetrics(array<UINT16>^ glyphIndices);
/// <summary>
/// Returns the nominal mapping of UCS4 Unicode code points to glyph indices as defined by the font 'CMAP' table.
/// Note that this mapping is primarily provided for line layout engines built on top of the physical font API.
/// Because of OpenType glyph substitution and line layout character substitution, the nominal conversion does not always correspond
/// to how a Unicode string will map to glyph indices when rendering using a particular font face.
/// Also, note that Unicode Variant Selectors provide for alternate mappings for character to glyph.
/// This call will always return the default variant.
/// </summary>
/// <param name="codePoints">An array of USC4 code points to obtain nominal glyph indices from.</param>
/// <returns>
/// Array of nominal glyph indices filled by this function.
/// </returns>
array<UINT16>^ GetGlyphIndices(array<UINT32>^ codePoints);
/// <summary>
/// Returns the nominal mapping of UCS4 Unicode code points to glyph indices as defined by the font 'CMAP' table.
/// Note that this mapping is primarily provided for line layout engines built on top of the physical font API.
/// Because of OpenType glyph substitution and line layout character substitution, the nominal conversion does not always correspond
/// to how a Unicode string will map to glyph indices when rendering using a particular font face.
/// Also, note that Unicode Variant Selectors provide for alternate mappings for character to glyph.
/// This call will always return the default variant.
/// </summary>
/// <param name="chars">An array of characters to obtain nominal glyph indices from.</param>
/// <returns>
/// Array of nominal glyph indices filled by this function.
/// </returns>
array<UINT16>^ GetGlyphIndices(array<System::Char>^ chars);
/// <summary>
/// Returns the nominal mapping of UCS4 Unicode code points to glyph indices as defined by the font 'CMAP' table.
/// Note that this mapping is primarily provided for line layout engines built on top of the physical font API.
/// Because of OpenType glyph substitution and line layout character substitution, the nominal conversion does not always correspond
/// to how a Unicode string will map to glyph indices when rendering using a particular font face.
/// Also, note that Unicode Variant Selectors provide for alternate mappings for character to glyph.
/// This call will always return the default variant.
/// </summary>
/// <param name="textString">The string to obtain nominal glyph indices for its characters.</param>
/// <returns>
/// Array of nominal glyph indices filled by this function.
/// </returns>
array<UINT16>^ GetGlyphIndices(System::String^ textString);
internal:
FontFace()
{ }
FontFace(IDWriteFontFace* pNativeIDWriteFontFace) : DirectUnknown(pNativeIDWriteFontFace)
{ }
};
} } } } | [
"lucemia@9e708c16-f4dd-11de-aa3c-59de0406b4f5"
] | [
[
[
1,
152
]
]
] |
ed8f37c99553bb0505396e868ff227d371fda7e9 | fc4946d917dc2ea50798a03981b0274e403eb9b7 | /gentleman/gentleman/WindowsAPICodePack/WindowsAPICodePack/DirectX/DirectX/Direct2D/D2DGeometrySink.cpp | c39f2354ca73fb4e94feafe5e73122bb978ad1fc | [] | no_license | midnite8177/phever | f9a55a545322c9aff0c7d0c45be3d3ddd6088c97 | 45529e80ebf707e7299887165821ca360aa1907d | refs/heads/master | 2020-05-16T21:59:24.201346 | 2010-07-12T23:51:53 | 2010-07-12T23:51:53 | 34,965,829 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 6,293 | cpp | // Copyright (c) Microsoft Corporation. All rights reserved.
//+----------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// File name:
// GeometrySink.cpp
//
// Description:
// Implements native geometry sink wrapper interfaces that call into a
// wrapper implementation of a managed interface supplied by the caller.
//
//-----------------------------------------------------------------------------
#include "stdafx.h"
#include "D2DGeometrySink.h"
namespace Microsoft { namespace WindowsAPICodePack { namespace DirectX { namespace Direct2D1 {
#define STANDARD_PROLOGUE \
if (SUCCEEDED(m_hr)) \
{ \
try \
{
#define STANDARD_CATCH_BLOCKS \
catch(System::Exception^) \
{ \
m_hr = E_FAIL; \
} \
#define STANDARD_EPILOGUE \
} \
STANDARD_CATCH_BLOCKS \
} \
GeometrySinkCallback::GeometrySinkCallback(
ISimplifiedGeometrySink ^sink
) : m_hr(S_OK),
m_sink(sink),
m_cRef(1)
{
}
STDMETHODIMP
GeometrySinkCallback::QueryInterface(
__in REFIID riid,
__out void **ppv
)
{
if (ppv == NULL)
{
return E_INVALIDARG;
}
void *pv = NULL;
if (riid == __uuidof(IUnknown))
{
pv = static_cast<IUnknown *>(this);
}
else if (riid == __uuidof(ID2D1SimplifiedGeometrySink))
{
pv = static_cast<ID2D1SimplifiedGeometrySink *>(this);
}
else if (riid == __uuidof(ID2D1GeometrySink))
{
pv = static_cast<ID2D1GeometrySink *>(this);
}
if (pv == NULL)
{
return E_NOINTERFACE;
}
AddRef();
*ppv = pv;
return S_OK;
}
STDMETHODIMP_(ULONG)
GeometrySinkCallback::AddRef()
{
return InterlockedIncrement(&m_cRef);
}
STDMETHODIMP_(ULONG)
GeometrySinkCallback::Release()
{
LONG cRef = InterlockedDecrement(&m_cRef);
if (cRef == 0)
{
delete this;
}
return cRef;
}
STDMETHODIMP_(void)
GeometrySinkCallback::SetFillMode(
D2D1_FILL_MODE fillMode
)
{
STANDARD_PROLOGUE
m_sink->SetFillMode(static_cast<FillMode>(fillMode));
STANDARD_EPILOGUE
}
STDMETHODIMP_(void)
GeometrySinkCallback::SetSegmentFlags(
D2D1_PATH_SEGMENT vertexFlags
)
{
STANDARD_PROLOGUE
m_sink->SetSegmentFlags(static_cast<PathSegment>(vertexFlags));
STANDARD_EPILOGUE
}
STDMETHODIMP_(void)
GeometrySinkCallback::BeginFigure(
__in CONST D2D1_POINT_2F startPoint,
D2D1_FIGURE_BEGIN figureBegin
)
{
STANDARD_PROLOGUE
Point2F copystartPoint;
copystartPoint.CopyFrom(startPoint);
m_sink->BeginFigure(copystartPoint, static_cast<FigureBegin>(figureBegin));
STANDARD_EPILOGUE
}
STDMETHODIMP_(void)
GeometrySinkCallback::AddLines(
__in_ecount(pointsLength) CONST D2D1_POINT_2F *points,
UINT pointsLength
)
{
STANDARD_PROLOGUE
cli::array<Point2F> ^arrayCopy = GetArray<Point2F>(points, pointsLength);
m_sink->AddLines(arrayCopy);
STANDARD_EPILOGUE
}
STDMETHODIMP_(void)
GeometrySinkCallback::AddBeziers(
__in_ecount(aBeziersLength) CONST D2D1_BEZIER_SEGMENT *aBeziers,
UINT aBeziersLength
)
{
STANDARD_PROLOGUE
cli::array<BezierSegment> ^arrayCopy = GetArray<BezierSegment>(aBeziers, aBeziersLength);
m_sink->AddBeziers(arrayCopy);
STANDARD_EPILOGUE
}
STDMETHODIMP_(void)
GeometrySinkCallback::EndFigure(
D2D1_FIGURE_END figureEnd
)
{
STANDARD_PROLOGUE
m_sink->EndFigure(static_cast<FigureEnd>(figureEnd));
STANDARD_EPILOGUE
}
STDMETHODIMP
GeometrySinkCallback::Close()
{
STANDARD_PROLOGUE
//
// We always call Close, even if we are in an error state. The managed interior
// implementation might need to close stuff and might have an independent error to
// report.
//
m_sink->Close();
STANDARD_EPILOGUE
return m_hr;
}
STDMETHODIMP_(void)
GeometrySinkCallback::AddLine(
__in D2D1_POINT_2F vertex
)
{
STANDARD_PROLOGUE
Point2F point2F;
point2F.CopyFrom(vertex);
ISimplifiedGeometrySink^ sink = m_sink;
safe_cast<IGeometrySink^>(sink)->AddLine(point2F);
STANDARD_EPILOGUE
}
STDMETHODIMP_(void)
GeometrySinkCallback::AddBezier(
__in CONST D2D1_BEZIER_SEGMENT *pBezier
)
{
STANDARD_PROLOGUE
BezierSegment bezierSegment;
bezierSegment.CopyFrom(*pBezier);
ISimplifiedGeometrySink^ sink = m_sink;
safe_cast<IGeometrySink^>(sink)->AddBezier(bezierSegment);
STANDARD_EPILOGUE
}
STDMETHODIMP_(void)
GeometrySinkCallback::AddQuadraticBezier(
__in CONST D2D1_QUADRATIC_BEZIER_SEGMENT *pBezier
)
{
STANDARD_PROLOGUE
QuadraticBezierSegment quadraticBezierSegment;
quadraticBezierSegment.CopyFrom(*pBezier);
ISimplifiedGeometrySink^ sink = m_sink;
safe_cast<IGeometrySink^>(sink)->AddQuadraticBezier(quadraticBezierSegment);
STANDARD_EPILOGUE
}
STDMETHODIMP_(void)
GeometrySinkCallback::AddQuadraticBeziers(
__in_ecount(aBeziersLength) CONST D2D1_QUADRATIC_BEZIER_SEGMENT *aBeziers,
UINT aBeziersLength
)
{
STANDARD_PROLOGUE
cli::array<QuadraticBezierSegment> ^arrayCopy = GetArray<QuadraticBezierSegment>(aBeziers, aBeziersLength);
ISimplifiedGeometrySink^ sink = m_sink;
safe_cast<IGeometrySink^>(sink)->AddQuadraticBeziers(arrayCopy);
STANDARD_EPILOGUE
}
STDMETHODIMP_(void)
GeometrySinkCallback::AddArc(
__in CONST D2D1_ARC_SEGMENT *pArc
)
{
STANDARD_PROLOGUE
ArcSegment arcSegment;
arcSegment.CopyFrom(*pArc);
ISimplifiedGeometrySink^ sink = m_sink;
safe_cast<IGeometrySink^>(sink)->AddArc(arcSegment);
STANDARD_EPILOGUE
}
GeometrySinkCallback::~GeometrySinkCallback()
{
}
} } } }
| [
"lucemia@9e708c16-f4dd-11de-aa3c-59de0406b4f5"
] | [
[
[
1,
295
]
]
] |
dff79c1d12983decadbd4b22c5d96490d61f72a4 | d9a78f212155bb978f5ac27d30eb0489bca87c3f | /PB/src/PbLib/GeneratedFiles/Release/moc_PBLauncher.cpp | 3efeec80f733ee1f8ddb649831896ff8f5947823 | [] | no_license | marchon/pokerbridge | 1ed4a6a521f8644dcd0b6ec66a1ac46879b8473c | 97d42ef318bf08f3bc0c0cb1d95bd31eb2a3a8a9 | refs/heads/master | 2021-01-10T07:15:26.496252 | 2010-05-17T20:01:29 | 2010-05-17T20:01:29 | 36,398,892 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,888 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'PBLauncher.h'
**
** Created: Fri 2. Apr 21:30:26 2010
** by: The Qt Meta Object Compiler version 61 (Qt 4.5.2)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "stdafx.h"
#include "..\..\PBLauncher.h"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'PBLauncher.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 61
#error "This file was generated using the moc from 4.5.2. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
static const uint qt_meta_data_PBLauncher[] = {
// content:
2, // revision
0, // classname
0, 0, // classinfo
0, 0, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0 // eod
};
static const char qt_meta_stringdata_PBLauncher[] = {
"PBLauncher\0"
};
const QMetaObject PBLauncher::staticMetaObject = {
{ &QObject::staticMetaObject, qt_meta_stringdata_PBLauncher,
qt_meta_data_PBLauncher, 0 }
};
const QMetaObject *PBLauncher::metaObject() const
{
return &staticMetaObject;
}
void *PBLauncher::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_PBLauncher))
return static_cast<void*>(const_cast< PBLauncher*>(this));
return QObject::qt_metacast(_clname);
}
int PBLauncher::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QObject::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
return _id;
}
QT_END_MOC_NAMESPACE
| [
"[email protected]"
] | [
[
[
1,
64
]
]
] |
9fd774810bd05411c2e32fcdea146e8f6c886f52 | 08b064b3fb246f720b8d9727d690ca8c3b96d100 | /Nordwind/game/object/Mobile.cpp | 8704ea1b23e034d26bd828cebe4d4bc0f432a128 | [] | no_license | michalxl/nordwind | e901d2d211b5db70e7b04700458cfbf8a4f68134 | 271bce7f872678a74c7020863bef9f7a7f4854af | refs/heads/master | 2021-01-10T06:37:41.935726 | 2011-01-03T00:09:06 | 2011-01-03T00:09:06 | 43,566,147 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,949 | cpp | /*
* Mobile.cpp
*
* Created on: 25.12.2009
* Author: idstein
*/
#include "Mobile.hpp"
#include <qpainter.h>
using namespace game;
// West = 0, Right = 1, East = 2, Down = 3, South = 4, Left = 5, North = 6, Up = 7
const quint8 Mobile::sDirectionMap[8] = { 3, 2, 1, 0, 1, 2, 3, 4 };
// we need to mirror the output texture on West, Right and East
const bool Mobile::sDirectionFlip[8] = { true, true, true, false, false, false,
false, false };
//IndexFile& Animations::getAnimFile(Body& _body) const {
// if(!mFileMapping.contains( _body ))
// return _body;
// qint8 file = mFileMapping[_body].second;
// if(!mAnimFiles.contains(file))
// return *this;
// _body = mFileMapping[_body].first;
// return file;
//}
//Animations& Animations::loadBodyDef( QString _fileName ) {
// // Format is:
// // oldbody {newbody, newbody, newbody} newhue
// QRegExp pattern("^\\s*(\\d+)\\s+\\{([^\\}]+)\\}\\s+(\\d+)\\s*$");
// QRegExp splitPattern("\\s*,\\s*");
//
// QFile file(_fileName);
// QTextStream stream(&file);
// Q_ASSERT_X(stream.device()->open(QIODevice::ReadOnly), __PRETTY_FUNCTION__, _fileName.toAscii().constData());
// bool ok = false;
// quint32 iLine = 0;
// while (!stream.atEnd()) {
// QString line = stream.readLine();
// ++iLine;
// if (!line.startsWith("//") && line.contains(pattern)) {
// // Parse the list of new ids
// QStringList newIds = pattern.cap(2).split(splitPattern);
// Body oldBody = pattern.cap(1).toUInt(&ok);
// if(!ok)
// oldBody = pattern.cap(1).toUInt( &ok, 16 );
// if(!ok) {
// qDebug() << "Incorrect body in" << file.fileName() << " at line" << iLine;
// continue;
// }
// ID hue = pattern.cap(3).toUInt();
// if (newIds.size() > 0) {
// mFallback.insert(oldBody, QPair<Body, ID>( newIds[0].toUInt(), hue ));
// }
// }
// }
// return *this;
//}
//Animations& Animations::loadMobTypesTxt(QString path) {
// QFile file(path);
//
// if (!file.open(QFile::ReadOnly)) {
// qDebug() << "Unable to open mobile type data from " << file.fileName();
// return;
// }
//
// // Format is:
// // body type(string) flags
// QTextStream stream(&file);
// quint32 iLine = 0;
// while (!stream.atEnd()) {
// QString line = stream.readLine().trimmed();
// ++iLine;
// if (!line.startsWith("//")) {
// QStringList parts = line.split(QRegExp("\\s+"));
//
// // 3 parts required
// if (parts.size() == 3) {
// bool ok = false;
// ushort body = parts[0].toUInt( &ok );
// if(!ok) {
// body = parts[0].toUInt( &ok, 16 );
// }
// if(!ok) {
// qDebug() << "Incorrect body in" << file.fileName() << " at line" << iLine;
// continue;
// }
//
// quint16 flags = parts[2].toUShort(&ok); // Parse flags
// if(!ok) {
// qDebug() << "Incorrect flag in " << file.fileName() << " at line" << iLine;
// continue;
// }
//
// // Parse the body type
// eAnimationType type;
// if (parts[1] == "HUMAN") {
// type = eAnim_human;
// } else if (parts[1] == "ANIMAL") {
// type = eAnim_animal;
// } else if (parts[1] == "MONSTER") {
// type = eAnim_monster;
// } else if (parts[1] == "EQUIPMENT") {
// type = eAnim_equipment;
// } else {
// qDebug() << "Unknown type in" << file.fileName() << " at line" << iLine;
// continue;
// }
// m_mobTypes.insert( (quint32)body, QPair<eAnimationType, quint16>(type, flags) );
// }
// }
// }
//}
//Animations& Animations::getFallback( Body& _body, Action& _action, Direction& _direction, Hue&_hue ) {
// Q_UNUSED(_action);
// Q_UNUSED(_direction);
// if(mFallback.contains(_body)) {
// _hue = Client::getInstance()->resources()->hues()->getHue( mFallback[_body].second, _hue->isPartialHue() );
// _body = mFallback[_body].first;
// }
// return *this;
//}
// Anim2
// 200 monsters � 110 actions
// x animals � 65 actions
// Anim3
// 300 animals � 65 actions
// 100 monsters � 110 actions
// x equipement � 175 actions
// Anim4
// 200 animals � 65 actions
// 200 monsters � 110 actions
// x equipement ``a 175 actions
ID Mobile::id() const {
ID result = 0;
if (mID < 200)
result = mID * 110;
else if (mID < 400)
result = (mID - 200) * 65 + 22000;
else
result = (mID - 400) * 175 + 35000;
result += mAction * 5 + sDirectionMap[mDirection & 7];
return result;
}
ID Mobile::body() const {
return mID;
}
Mobile::Action Mobile::action() const {
return mAction;
}
Mobile::Direction Mobile::direction() const {
return mDirection;
}
QRectF Mobile::boundingRect() const {
return mBase.frameRect();
}
Mobile::Mobile(const Serial &serial, QObject *parent, const ID &body, const Direction &direction, Action action)
: Dynamic(serial,parent),
Object(body),
QGraphicsPixmapItem(),
mAction(action),
mDirection(direction),
mBase(QString("animations:%1").arg(id()),"anim",this) {
if(!mBase.isValid())
qDebug() << "Invalid animation";
mBase.setCacheMode(QMovie::CacheAll);
connect(&mBase,SIGNAL(frameChanged(int)),SLOT(onFrameChanged(int)));
mBase.start();
}
/*void Mobile::paint( QPainter* painter, const QStyleOptionGraphicsItem* _option, QWidget* _widget ) {
Q_UNUSED(_option);
Q_UNUSED(_widget);
QRect rect = mBase.frameRect();
if(sDirectionFlip[mDirection])
painter->setTransform(QTransform(-1.0f,0.0f,
0.0f,1.0f,
rect.width(),0.0f));
painter->drawPixmap(rect.topLeft(),mBase.currentPixmap());
}*/
void Mobile::onFrameChanged(int frameNumber) {
Q_UNUSED(frameNumber);
setPixmap(mBase.currentPixmap());
setOffset(mBase.frameRect().topLeft());
//update();
}
| [
"paulidstein@ae180d36-aaa7-11de-892d-7b2b76e7707e"
] | [
[
[
1,
196
]
]
] |
2908dc23a2baadd5086c72465c78e9883024ca40 | 43626054205d6048ec98c76db5641ce8e42b8237 | /source/CMainMenuState.h | c5931f8c319de82bbdf62d77dad5067129fd04e4 | [] | no_license | Wazoobi/whitewings | b700da98b855a64442ad7b7c4b0be23427b0ee23 | a53fdb832cfb1ce8605209c9af47f36b01c44727 | refs/heads/master | 2021-01-10T19:33:22.924792 | 2009-08-05T18:30:07 | 2009-08-05T18:30:07 | 32,119,981 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,391 | h | //////////////////////////////////////////////////////////////////////////
// File Name : "CMainMenuState.h"
//
// Author : Juno Madden (JM)
//
// Purpose : To encapsulate all code for the main menu.
//////////////////////////////////////////////////////////////////////////
#pragma once
#include "IGameState.h"
#include "CGame.h"
#include "SGD Wrappers/CSGD_Direct3D.h"
#include "SGD Wrappers/CSGD_TextureManager.h"
#include "SGD Wrappers/CSGD_DirectInput.h"
class CMainMenuState : public IGameState
{
CSGD_Direct3D *m_pD3D;
CSGD_TextureManager *m_pTM;
CSGD_DirectInput *m_pDI;
CGame *pGame;
int m_nImageID;
int m_nBackgroundID;
int FontID;
int currentSelection;
CMainMenuState(void);
~CMainMenuState(void);
CMainMenuState(const CMainMenuState&);
CMainMenuState& operator=(const CMainMenuState&);
public:
//////////////////////////////////////////////////////////////////////////
// Function : Get Instance
//
// Purpose : Grants global access to the singleton.
//////////////////////////////////////////////////////////////////////////
static CMainMenuState* GetInstance(void);
//////////////////////////////////////////////////////////////////////////
// Function : Enter
//
// Purpose : Enters into the state.
//////////////////////////////////////////////////////////////////////////
void Enter(void);
//////////////////////////////////////////////////////////////////////////
// Function : Exit
//
// Purpose : Leaves the state.
//////////////////////////////////////////////////////////////////////////
void Exit(void);
//////////////////////////////////////////////////////////////////////////
// Function : Input
//
// Purpose : Takes in input.
//////////////////////////////////////////////////////////////////////////
bool Input(void);
//////////////////////////////////////////////////////////////////////////
// Function : Updates
//
// Purpose : Updates data members based on time.
//////////////////////////////////////////////////////////////////////////
void Update(float fElapsedTime);
//////////////////////////////////////////////////////////////////////////
// Function : Render
//
// Purpose : Draws to the screen.
//////////////////////////////////////////////////////////////////////////
void Render(void);
}; | [
"Juno05@1cfc0206-7002-11de-8585-3f51e31374b7",
"gameatronMC@1cfc0206-7002-11de-8585-3f51e31374b7"
] | [
[
[
1,
26
],
[
28,
80
]
],
[
[
27,
27
]
]
] |
79d790d6fa18c010da6124756cb9e5f76dd70b0c | 77aa13a51685597585abf89b5ad30f9ef4011bde | /dep/src/boost/boost/exception/detail/object_hex_dump.hpp | cc4037bc8c86e83b832e69bd174335c10dc5aa9b | [] | 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 | 1,245 | hpp | //Copyright (c) 2006-2008 Emil Dotchevski and Reverge Studios, Inc.
//Distributed under the Boost Software License, Version 1.0. (See accompanying
//file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef UUID_6F463AC838DF11DDA3E6909F56D89593
#define UUID_6F463AC838DF11DDA3E6909F56D89593
#include <boost/exception/detail/type_info.hpp>
#include <iomanip>
#include <ios>
#include <string>
#include <sstream>
namespace
boost
{
namespace
exception_detail
{
template <class T>
inline
std::string
object_hex_dump( T const & x, size_t max_size=16 )
{
std::ostringstream s;
s << "type: " << type_name<T>() << ", size: " << sizeof(T) << ", dump: ";
size_t n=sizeof(T)>max_size?max_size:sizeof(T);
s.fill('0');
s.width(2);
unsigned char const * b=reinterpret_cast<unsigned char const *>(&x);
s << std::setw(2) << std::hex << (unsigned int)*b;
for( unsigned char const * e=b+n; ++b!=e; )
s << " " << std::setw(2) << std::hex << (unsigned int)*b;
return s.str();
}
}
}
#endif
| [
"pepsi1x1@a6a5f009-272a-4b40-a74d-5f9816a51f88"
] | [
[
[
1,
40
]
]
] |
454d5601cb51ac0caf4e120fa75bf3385f505d13 | 9426ad6e612863451ad7aac2ad8c8dd100a37a98 | /ULLib/src/ULListCtrl.cpp | ab65db73504612ad0c15c2f1e0d60683a9df0a4f | [] | no_license | piroxiljin/ullib | 61f7bd176c6088d42fd5aa38a4ba5d4825becd35 | 7072af667b6d91a3afd2f64310c6e1f3f6a055b1 | refs/heads/master | 2020-12-28T19:46:57.920199 | 2010-02-17T01:43:44 | 2010-02-17T01:43:44 | 57,068,293 | 0 | 0 | null | 2016-04-25T19:05:41 | 2016-04-25T19:05:41 | null | WINDOWS-1251 | C++ | false | false | 4,508 | cpp | ///\file ULListCtrl.cpp
///\brief фаил реализации класса лист контрола
#include "..\..\ULLib\Include\ULListCtrl.h"
#include "..\..\ULLib\Include\ULRes.h"
namespace ULWnds
{
namespace ULControls
{
CULListCtrl::CULListCtrl():
ULWnds::CULSubClass()
{
}
BOOL CULListCtrl::Create(HWND hParentWnd,UINT uID,int x,int y,
int cx,int cy,DWORD dwStyle,DWORD dwStyleEx)
{
m_hParentWnd=hParentWnd;
m_hWnd = CreateWindowEx(dwStyleEx,WC_LISTVIEW,
NULL,
dwStyle,
x, y, cx, cy,
hParentWnd,(HMENU)(LONG_PTR)uID,
ULOther::ULGetResourceHandle(),
NULL);
return CULSubClass::Attach(m_hWnd);
}
int CULListCtrl::InsertColumn(int nCol,LPCTSTR lpszColumnHeading,int nFormat,int nWidth,int nSubItem)
{
LVCOLUMN lvc;
lvc.mask=LVCF_TEXT|LVCF_WIDTH|LVCF_SUBITEM|LVCF_FMT;
lvc.pszText=(LPTSTR)lpszColumnHeading;
lvc.cchTextMax=static_cast<int>(_tcslen(lpszColumnHeading)+1);
lvc.fmt=nFormat;
lvc.cx=nWidth;
lvc.iSubItem=nSubItem;
return (int)SendMessage(LVM_INSERTCOLUMN,(WPARAM)nCol,(LPARAM)&lvc);
}
BOOL CULListCtrl::SetColumnWidth(int nCol,int cx)
{
return (BOOL)SendMessage(LVM_SETCOLUMNWIDTH,(WPARAM)nCol,(LPARAM)cx);
}
int CULListCtrl::GetColumnWidth(int nCol)
{
return (int)SendMessage(LVM_GETCOLUMNWIDTH,(WPARAM)nCol);
}
int CULListCtrl::InsertItem(int nItem,LPCTSTR lpszItem)
{
LVITEM lvi;
lvi.mask=LVIF_TEXT;
lvi.iItem=nItem;
lvi.iSubItem=0;
lvi.pszText=(LPTSTR)lpszItem;
lvi.cchTextMax=static_cast<int>(_tcslen(lpszItem)+1);
return (int)SendMessage(LVM_INSERTITEM,0,(LPARAM)&lvi);
}
BOOL CULListCtrl::SetItemText(int nItem,int nSubItem,LPCTSTR lpszText)
{
LVITEM lvi;
lvi.mask=LVIF_TEXT;
lvi.iItem=nItem;
lvi.iSubItem=nSubItem;
lvi.pszText=(LPTSTR)lpszText;
lvi.cchTextMax=static_cast<int>(_tcslen(lpszText)+1);
return (BOOL)SendMessage(LVM_SETITEM,0,(LPARAM)&lvi);
}
BOOL CULListCtrl::GetItemText(int nItem,int nSubItem,LPTSTR lpszText,int nLen)
{
LVITEM lvi;
lvi.mask=LVIF_TEXT;
lvi.iItem=nItem;
lvi.iSubItem=nSubItem;
lvi.pszText=(LPTSTR)lpszText;
lvi.cchTextMax=nLen;
return (BOOL)SendMessage(LVM_GETITEM,0,(LPARAM)&lvi);
}
int CULListCtrl::GetItemCount()
{
return (int)SendMessage(LVM_GETITEMCOUNT);
}
DWORD CULListCtrl::SetExtendedStyle(DWORD dwNewStyle)
{
return (DWORD)SendMessage(LVM_SETEXTENDEDLISTVIEWSTYLE,(WPARAM)dwNewStyle,(LPARAM)dwNewStyle);
}
BOOL CULListCtrl::DeleteAllItems()
{
return (BOOL)SendMessage(LVM_DELETEALLITEMS);
}
BOOL CULListCtrl::GetColumn(int nCol,LPLVCOLUMN pCol)
{
return (BOOL)SendMessage(LVM_GETCOLUMN,(WPARAM)nCol,(LPARAM)pCol);
}
BOOL CULListCtrl::GetItemRect(int nItem,LPRECT lpRect,UINT nCode)
{
lpRect->left = nCode;
return (BOOL)SendMessage(LVM_GETITEMRECT, (WPARAM)nItem,(LPARAM)lpRect);
}
BOOL CULListCtrl::GetSubItemRect(int iItem, int iSubItem, int nArea, RECT* lpRect)
{
lpRect->top = iSubItem;
lpRect->left = nArea;
return (BOOL)SendMessage(LVM_GETSUBITEMRECT,iItem, (LPARAM)lpRect);
}
int CULListCtrl::GetSubItemCount()
{
HWND hwndHeader=(HWND)SendMessage(LVM_GETHEADER);
if(!hwndHeader)
return -1;
return (int)::SendMessage(hwndHeader,HDM_GETITEMCOUNT,0,0);
}
int CULListCtrl::HitTest(LPLVHITTESTINFO pInfo)
{
return(int)SendMessage(LVM_HITTEST,0,(LPARAM)pInfo);
}
int CULListCtrl::SubItemHitTest(LPLVHITTESTINFO pInfo)
{
return(int)SendMessage(LVM_SUBITEMHITTEST,0,(LPARAM)pInfo);
}
BOOL CULListCtrl::SetItemData(int nItem,DWORD_PTR dwData)
{
LVITEM it={0};
it.mask=LVIF_PARAM;
it.iItem=nItem;
it.lParam=dwData;
return (BOOL)SendMessage(LVM_SETITEM,0,(LPARAM)&it);
}
DWORD_PTR CULListCtrl::GetItemData(int nItem)
{
LVITEM it={0};
it.mask=LVIF_PARAM;
it.iItem=nItem;
SendMessage(LVM_GETITEM,0,(LPARAM)&it);
return it.lParam;
}
int CULListCtrl::GetFirstSelectedItemPosition()
{
return (int)SendMessage(LVM_GETNEXTITEM,(WPARAM)-1,(LPARAM)LVNI_SELECTED);
}
int CULListCtrl::GetNextSelectedItemPosition(int pos)
{
return (int)SendMessage(LVM_GETNEXTITEM,(WPARAM)pos,(LPARAM)LVNI_SELECTED);
}
BOOL CULListCtrl::DeleteItem(int nItem)
{
return (BOOL)SendMessage(LVM_DELETEITEM,(WPARAM)nItem);
}
}
}
| [
"UncleLab@a8b69a72-a546-0410-9fb4-5106a01aa11f"
] | [
[
[
1,
168
]
]
] |
56337df185682398662943d942bbf62d579a1254 | c95a83e1a741b8c0eb810dd018d91060e5872dd8 | /Game/ObjectDLL/ObjectShared/GameServerShell.cpp | bbd894ac5f403146767aa7b5a8ebf430b33b72b7 | [] | 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 | 151,432 | cpp | // ----------------------------------------------------------------------- //
//
// MODULE : GameServerShell.cpp
//
// PURPOSE : The game's server shell - Implementation
//
// CREATED : 9/17/97
//
// (c) 1997-2002 Monolith Productions, Inc. All Rights Reserved
//
// ----------------------------------------------------------------------- //
#include "stdafx.h"
#include "GameServerShell.h"
#include "PlayerObj.h"
#include "iltserver.h"
#include "MsgIDs.h"
#include "CommandIDs.h"
#include "ServerUtilities.h"
#include "Trigger.h"
#include "Sparam.h"
#include "ObjectMsgs.h"
#include <stdio.h>
#include "AssertMgr.h"
#include "WorldProperties.h"
#include "GameBase.h"
#include "MusicMgr.h"
#include "Camera.h"
#include "ServerSpecialFX.h"
#include "AI.h"
#include "AIGoalAbstract.h"
#include "GadgetTarget.h"
#include "DecisionObject.h"
#include "DebugLineSystem.h"
#include "AIVolumeMgr.h"
#include "AIInformationVolumeMgr.h"
#include "AINodeMgr.h"
#include "GameStartPoint.h"
#include "AIStimulusMgr.h"
#include "AICentralKnowledgeMgr.h"
#include "ServerTrackedNodeMgr.h"
#include "GlobalServerMgr.h"
#include "iserverdir.h"
#include "ObjectTemplateMgr.h"
#include "LiteObjectMgr.h"
#include "GameBaseLite.h"
#include "ServerMissionMgr.h"
#include "SinglePlayerMissionMgr.h"
#include "CoopMissionMgr.h"
#include "DeathMatchMissionMgr.h"
#include "TeamDeathMatchMissionMgr.h"
#include "DoomsDayMissionMgr.h"
#include "ServerSaveLoadMgr.h"
#include "CharacterMgr.h"
#include "ServerAssetMgr.h"
#include "VersionMgr.h"
#include "CRC32.h"
#include "PlayerButes.h"
#include "CVarTrack.h"
#include "ParsedMsg.h"
#include "ScmdServer.h"
#include "BanIPMgr.h"
#include <time.h>
#define MAX_CLIENT_NAME_LENGTH 100
#define CLIENT_PING_UPDATE_RATE 3.0f
#define UPDATENAME_INTERVAL 10.0f
#define GAME_VERSION 1
// simple macro to clean up code and reduce typing overhead
#define GET_PLAYER(hSender) (CPlayerObj*)g_pLTServer->GetClientUserData(hSender)
//#define _DEGUG
// debug output messages to sever console
#ifdef _DEGUG
enum EDebugOutput {eAlways = 0, eSomeTimes = 1, eRarely = 2};
// if true all server messages will be output to console
LTBOOL g_debugOutputMessages(LTFALSE);
EDebugOutput g_debugOutputLevel(eRarely);
#define DEBUG_CONSOLE_OUTPUT(output, level) \
if (g_debugOutputMessages && level >= g_debugOutputLevel) \
g_pLTServer->CPrint(output)
#else
#define DEBUG_CONSOLE_OUTPUT(output, level)
#endif // _DEBUG
extern CAIInformationVolumeMgr* g_pAIInformationVolumeMgr;
// Stuff to create a GameServerShell.
//SETUP_SERVERSHELL()
CVarTrack g_CanShowDimsTrack;
CVarTrack g_ShowDimsTrack;
CVarTrack g_ShowTimingTrack;
CVarTrack g_ShowTriggersTrack;
CVarTrack g_ShowTriggersFilter;
CVarTrack g_ShowVolumesTrack;
CVarTrack g_ShowInfoVolumesTrack;
CVarTrack g_ShowNodesTrack;
CVarTrack g_ClearLinesTrack;
CVarTrack g_DamageScale;
CVarTrack g_HealScale;
CVarTrack g_StairStepHeight;
CVarTrack g_NetAudioTaunts;
CVarTrack g_vtAIHitPtsPlayerIncreasePercent;
CVarTrack g_vtAIArmorPtsPlayerIncreasePercent;
CVarTrack g_vtRespawnWaitTime;
CVarTrack g_vtMultiplayerRespawnWaitTime;
CVarTrack g_vtDoomsdayRespawnWaitTime;
CGameServerShell* g_pGameServerShell = LTNULL;
// ----------------------------------------------------------------------- //
// Helpers for world time conversion.
// ----------------------------------------------------------------------- //
inline float TODSecondsToHours(float time)
{
return (float)(time / 3600.0);
}
inline float TODHoursToSeconds(float time)
{
return (float)(time * 3600.0);
}
ClientData::ClientData( )
{
m_hClient = NULL;
m_nLastClientUpdateTime = GetTickCount( );
}
LTRESULT CGameServerShell::OnServerInitialized()
{
g_pGameServerShell = this;
//////////////////////////////////////////////////////////////////////////////
// Set up all the stuff that everything relies on
// Redirect our asserts as specified by the assert convar
CAssertMgr::Enable();
// Set up the LT subsystem pointers
g_pModelLT = g_pLTServer->GetModelLT();
g_pTransLT = g_pLTServer->GetTransformLT();
g_pPhysicsLT = g_pLTServer->Physics();
g_pLTBase = static_cast<ILTCSBase*>(g_pLTServer);
// Set up global console trackers...
g_CanShowDimsTrack.Init(g_pLTServer, "CanShowDims", LTNULL, 0.0f);
g_ShowDimsTrack.Init(g_pLTServer, "ShowDims", LTNULL, 0.0f);
g_ShowTimingTrack.Init(g_pLTServer, "ShowTiming", "0", 0.0f);
g_ShowTriggersTrack.Init(g_pLTServer, "ShowTriggers", "0", 0.0f);
g_ShowTriggersFilter.Init(g_pLTServer, "FilterTriggerMsgs", "", 0.0f);
g_ShowVolumesTrack.Init(g_pLTServer, "ShowAIVolumes", "0", 0.0f);
g_ShowInfoVolumesTrack.Init(g_pLTServer, "ShowAIInfoVolumes", "0", 0.0f);
g_ShowNodesTrack.Init(g_pLTServer, "ShowAINodes", "0", 0.0f);
g_ClearLinesTrack.Init(g_pLTServer, "ClearLines", LTNULL, 0.0f);
g_DamageScale.Init(g_pLTServer, "DamageScale", LTNULL, 1.0f);
g_HealScale.Init(g_pLTServer, "HealScale", LTNULL, 1.0f);
g_NetAudioTaunts.Init(g_pLTServer,"NetAudioTaunts",LTNULL,1.0f);
g_vtAIHitPtsPlayerIncreasePercent.Init( g_pLTServer, "AIHitPointsPlayerIncreasePercent", LTNULL, 0.25f );
g_vtAIArmorPtsPlayerIncreasePercent.Init( g_pLTServer, "AIArmorPointsPlayerIncreasePercent", LTNULL, 0.25f );
g_StairStepHeight.Init(g_pLTServer, STAIR_STEP_HEIGHT_CVAR, LTNULL, DEFAULT_STAIRSTEP_HEIGHT);
g_vtRespawnWaitTime.Init( g_pLTServer, "RespawnWaitTime", NULL, 1.0f);
g_vtMultiplayerRespawnWaitTime.Init( g_pLTServer, "RespawnMultiWaitTime", NULL, 30.0f);
g_vtDoomsdayRespawnWaitTime.Init( g_pLTServer, "RespawnDoomsdayWaitTime", NULL, 15.0f);
// Make sure we are using autodeactivation...
g_pLTServer->RunGameConString("autodeactivate 1.0");
g_pPhysicsLT->SetStairHeight( g_StairStepHeight.GetFloat() );
//////////////////////////////////////////////////////////////////////////////
// Do all the stuff that used to be in the ctor for the server
ClearClientList();
SetUpdateGameServ();
m_SunVec[0] = m_SunVec[1] = m_SunVec[2] = 0;
if( !InitGameType())
return LT_ERROR;
// Create the AI class factory.
if ( 0 == m_pAIClassFactory )
{
m_pAIClassFactory = debug_new( CAIClassFactory );
ASSERT( 0 != m_pAIClassFactory );
}
SetLGFlags( LOAD_NEW_GAME );
m_hSwitchWorldVar = LTNULL;
m_bFirstUpdate = LTTRUE;
m_TODSeconds = TODHoursToSeconds(12.0f);
m_TODCounter = 0.0f;
m_ClientPingSendCounter = 0.0f;
m_iPrevRamp = 0;
m_sWorld.Empty( );
// Initialize all the globals...
if ( m_pGlobalMgr == 0 )
{
m_pGlobalMgr = debug_new( CGlobalServerMgr );
ASSERT( 0 != m_pGlobalMgr );
}
m_pGlobalMgr->Init();
if ( m_pAIStimulusMgr == 0 )
{
m_pAIStimulusMgr = debug_new( CAIStimulusMgr );
ASSERT( 0 != m_pAIStimulusMgr );
}
if ( m_pAICentralKnowledgeMgr == 0 )
{
m_pAICentralKnowledgeMgr = debug_new( CAICentralKnowledgeMgr );
ASSERT( 0 != m_pAICentralKnowledgeMgr );
}
if ( m_pCharacterMgr == 0 )
{
m_pCharacterMgr = debug_new( CCharacterMgr );
ASSERT( 0 != m_pCharacterMgr );
}
if( m_pServerTrackedNodeMgr == 0 )
{
m_pServerTrackedNodeMgr = debug_new( CServerTrackedNodeMgr );
ASSERT( 0 != m_pServerTrackedNodeMgr );
}
m_bShowMultiplayerSummary = LTFALSE;
m_bStartNextMultiplayerLevel = LTFALSE;
m_fSummaryEndTime = 0.0f;
if( !m_pServerSaveLoadMgr )
{
m_pServerSaveLoadMgr = debug_new( CServerSaveLoadMgr );
if( !m_pServerSaveLoadMgr )
{
return LT_ERROR;
}
}
if( !m_pServerSaveLoadMgr->Init( m_ServerGameOptions.m_sProfileName.c_str( ), IsMultiplayerGame( )))
{
return LT_ERROR;
}
m_bPreCacheAssets = m_ServerGameOptions.m_bPreCacheAssets;
m_nPauseCount = 0;
m_bClientPaused = false;
m_eSwitchingWorldsState = eSwitchingWorldsStateNone;
m_nCShellCRC = CRC32::CalcRezFileCRC("cshell.dll");
m_eMinMusicMood = CMusicMgr::eMoodRoutine;
// Use max on LAN games
float fMinBandwidth = ( m_ServerGameOptions.m_bLANOnly ) ? k_fMaxBandwidth : 0.0f;
if( m_ServerGameOptions.m_nBandwidthServer < eBandwidth_Custom)
{
WriteConsoleFloat("BandwidthTargetServer",
LTCLAMP(((float)g_BandwidthServer[m_ServerGameOptions.m_nBandwidthServer] * 1024.0f), fMinBandwidth, k_fMaxBandwidth) );
}
else
{
WriteConsoleFloat("BandwidthTargetServer",
LTCLAMP(((float)m_ServerGameOptions.m_nBandwidthServerCustom * 1024.0f), fMinBandwidth, k_fMaxBandwidth) );
}
// Initialize the scmd handler.
if( !ScmdServer::Instance( ).Init( ))
return LT_ERROR;
// Initialize the BanIPMgr.
if( !BanIPMgr::Instance( ).Init( ))
return LT_ERROR;
// Do any game specific initialization.
switch( m_ServerGameOptions.m_eGameType )
{
// Single player and coop use the same weapon files...
case eGameTypeSingle:
case eGameTypeCooperative:
{
g_pWeaponMgr->LoadOverrideButes( WEAPON_DEFAULT_FILE );
}
break;
case eGameTypeDeathmatch:
case eGameTypeTeamDeathmatch:
case eGameTypeDoomsDay:
{
g_pWeaponMgr->LoadOverrideButes( WEAPON_DEFAULT_MULTI_FILE );
ApplyWeaponRestrictions( );
}
break;
}
// Seed the random number generator so GetRandom() isn't the same each game.
// IMPORTANT: reseeding the random number generator should not happen all the time
// as it can lead to GetRandom() not acting as random as you might think.
srand(time(NULL));
return LT_OK;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::OnServerTerm()
//
// PURPOSE: Server is shutting down...
//
// ----------------------------------------------------------------------- //
void CGameServerShell::OnServerTerm()
{
CAssertMgr::Disable();
}
LTBOOL g_bInfiniteAmmo = LTFALSE;
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::CGameServerShell()
//
// PURPOSE: Initialize
//
// ----------------------------------------------------------------------- //
CGameServerShell::CGameServerShell() :
m_pAIStimulusMgr( 0 )
, m_pAICentralKnowledgeMgr( 0 )
, m_pAIClassFactory( 0 )
, m_pServerTrackedNodeMgr( 0 )
, m_pGlobalMgr( 0 )
, m_pServerDir( 0 )
, m_pCharacterMgr( 0 )
, m_bCachedLevelFiles( false )
{
m_aCurMessageSourceAddr[0] = 0;
m_aCurMessageSourceAddr[1] = 0;
m_aCurMessageSourceAddr[2] = 0;
m_aCurMessageSourceAddr[3] = 0;
m_nCurMessageSourcePort = 0;
m_bPreCacheAssets = false;
// Create the object template mgr
m_pObjectTemplates = debug_new( CObjectTemplateMgr );
// Create the lite object mgr
m_pLiteObjectMgr = debug_new( CLiteObjectMgr );
// Note : ctor stuff is now all handled by ::OnServerInitialized
m_pServerMissionMgr = NULL;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::~CGameServerShell()
//
// PURPOSE: Deallocate
//
// ----------------------------------------------------------------------- //
CGameServerShell::~CGameServerShell()
{
if ( m_pServerTrackedNodeMgr != 0 )
{
debug_delete( m_pServerTrackedNodeMgr );
m_pServerTrackedNodeMgr = 0;
}
if ( m_pAIStimulusMgr != 0 )
{
debug_delete( m_pAIStimulusMgr );
m_pAIStimulusMgr = 0;
}
if ( m_pAICentralKnowledgeMgr != 0 )
{
debug_delete( m_pAICentralKnowledgeMgr );
m_pAICentralKnowledgeMgr = 0;
}
if ( m_pCharacterMgr != 0 )
{
debug_delete( m_pCharacterMgr );
m_pCharacterMgr = 0;
}
// Delete the AI class factory LAST.
if ( m_pAIClassFactory != 0 )
{
debug_delete( m_pAIClassFactory );
m_pAIClassFactory = 0;
}
// Clean up the Pointer to the GlobalMemmoryMgr as we want to clean up the
//
if ( m_pGlobalMgr != 0 )
{
debug_delete( m_pGlobalMgr );
m_pGlobalMgr = 0;
}
// Get rid of the serverdir, if we have one
if( m_pServerDir )
{
delete m_pServerDir;
m_pServerDir = 0;
}
// Get rid of the object template mgr
debug_delete( m_pObjectTemplates );
m_pObjectTemplates = 0;
// Get rid of the lite object mgr
debug_delete( m_pLiteObjectMgr );
m_pLiteObjectMgr = 0;
// Toss the server missionmgr.
if( m_pServerMissionMgr )
{
debug_delete( m_pServerMissionMgr );
m_pServerMissionMgr = NULL;
}
if( m_pServerSaveLoadMgr )
{
debug_delete( m_pServerSaveLoadMgr );
m_pServerSaveLoadMgr = NULL;
}
// Remove all remaining clients from our list of clients.
ClientDataList::iterator iter = m_ClientDataList.begin( );
for( ; iter != m_ClientDataList.end( ); iter++ )
{
ClientData* pClientData = *iter;
debug_delete( pClientData );
}
m_ClientDataList.clear( );
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::OnAddClient()
//
// PURPOSE: Called when a client connects to a server
//
// ----------------------------------------------------------------------- //
void CGameServerShell::OnAddClient(HCLIENT hClient)
{
DEBUG_CONSOLE_OUTPUT("Add Client", eRarely);
// Add this client to our list of clients.
ClientData* pClientData = debug_new( ClientData );
pClientData->m_hClient = hClient;
pClientData->m_nLastClientUpdateTime = GetTickCount( );
m_ClientDataList.push_back( pClientData );
// Check if the client is banned.
if( !BanIPMgr::Instance( ).OnAddClient( hClient ))
{
g_pLTServer->KickClient( hClient );
}
// Tell serverapp about it.
ServerAppAddClient( hClient );
// Tell the client about the pause state.
CAutoMessage cMsg;
uint32 nFlags = g_pLTServer->GetServerFlags();
bool bInPauseState = (( nFlags & SS_PAUSED ) != 0 );
cMsg.Writeuint8( MID_GAME_PAUSE );
cMsg.Writebool( bInPauseState );
g_pLTServer->SendToClient( cMsg.Read(), hClient, MESSAGE_GUARANTEED );
cMsg.Reset( );
cMsg.Writeuint8( MID_SWITCHINGWORLDSSTATE );
cMsg.Writeuint8( m_eSwitchingWorldsState );
g_pLTServer->SendToClient( cMsg.Read(), hClient, MESSAGE_GUARANTEED);
uint32 dwClientId = g_pLTServer->GetClientID( hClient );
if( IsTeamGameType() )
{
// tell the player about the current teams
CTeamMgr::Instance().UpdateClient( hClient );
}
// Tell the new Client about all the players already
// on the server...
// Don't just broadcast the list. That would send messages to clients that aren't fully connected yet.
CPlayerObj::PlayerObjList::const_iterator iter = CPlayerObj::GetPlayerObjList( ).begin( );
while( iter != CPlayerObj::GetPlayerObjList( ).end( ))
{
CPlayerObj* pOldPlayer = *iter;
// Make sure the player has a client and has spawned at least once
if( pOldPlayer && pOldPlayer->GetClient( ) && pOldPlayer->RespawnCalled())
{
SendPlayerInfoMsgToClients(hClient, pOldPlayer, MID_PI_EXIST);
}
iter++;
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::OnRemoveClient()
//
// PURPOSE: Called when a client disconnects from a server
//
// ----------------------------------------------------------------------- //
void CGameServerShell::OnRemoveClient(HCLIENT hClient)
{
if (IsMultiplayerGame( ))
{
// Send a message to all clients, letting them know this user is leaving the world
uint32 nClientID = g_pLTServer->GetClientID(hClient);
CAutoMessage cMsg;
cMsg.Writeuint8(MID_PLAYER_REMOVED);
cMsg.Writeuint32(nClientID);
g_pLTServer->SendToClient(cMsg.Read(), LTNULL, MESSAGE_GUARANTEED);
if (IsTeamGameType())
{
CTeamMgr::Instance().RemovePlayer( nClientID );
}
}
// Clear our client data...
CPlayerObj* pPlayer = GET_PLAYER(hClient);
if (pPlayer)
{
pPlayer->SetClient(LTNULL);
}
// Tell server app about it.
ServerAppRemoveClient( hClient );
// Tell the scmd about it.
ScmdServer::Instance( ).OnRemoveClient( hClient );
// Remove this client from our list of clients.
ClientDataList::iterator iter = m_ClientDataList.begin( );
for( ; iter != m_ClientDataList.end( ); iter++ )
{
ClientData* pClientData = *iter;
if( pClientData->m_hClient == hClient )
{
m_ClientDataList.erase( iter );
debug_delete( pClientData );
break;
}
}
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CreateClientName
// ROUTINE: GetIpStringFromClientName
// ROUTINE: GetClientGivenPlayerNameFromClientName
//
// PURPOSE: Creates a clientname based on the ip and client given player name.
//
// --------------------------------------------------------------------------- //
static void CreateClientName( HCLIENT hClient, char const* pszClientGivenPlayerName, char* pszClientName,
int nSize )
{
uint8 aTcpIp[4];
uint16 nPort;
g_pLTServer->GetClientAddr( hClient, aTcpIp, &nPort );
_snprintf( pszClientName, nSize, "%d.%d.%d.%d:%d#%s", aTcpIp[0], aTcpIp[1], aTcpIp[2], aTcpIp[3], nPort,
pszClientGivenPlayerName );
pszClientName[nSize-1] = 0;
}
static void GetIpStringFromClientName( char const* pszClientName, char* pszIpString, int nSize )
{
CString sCopy = pszClientName;
int nSeperator = sCopy.Find( "#" );
if( nSeperator == -1 )
{
pszIpString[0] = 0;
return;
}
strncpy( pszIpString, sCopy.Left( nSeperator ), nSize );
pszIpString[nSize-1] = 0;
}
static void GetClientGivenPlayerNameFromClientName( char const* pszClientName,
char* pszClientGivenPlayerName, int nSize )
{
CString sCopy = pszClientName;
int nSeperator = sCopy.Find( "#" );
strncpy( pszClientGivenPlayerName, sCopy.Mid( nSeperator + 1 ), nSize );
pszClientGivenPlayerName[nSize-1] = 0;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::OnClientEnterWorld()
//
// PURPOSE: Add a client
//
// ----------------------------------------------------------------------- //
LPBASECLASS CGameServerShell::OnClientEnterWorld(HCLIENT hClient)
{
if (!hClient) return LTNULL;
DEBUG_CONSOLE_OUTPUT("Client Enter World", eRarely);
CPlayerObj* pPlayer = LTNULL;
ModelId ePlayerModelId = eModelIdInvalid;
g_pPhysicsLT->SetStairHeight( g_StairStepHeight.GetFloat() );
// This will be filled in with clientdata for mp games.
NetClientData ncd;
memset( &ncd, 0, sizeof( ncd ));
char const* pszClientName = NULL;
// Must have client data for mp game.
if( IsMultiplayerGame( ))
{
// Make sure the NetClientData is valid.
int nNcdSize = sizeof( ncd );
if( !g_pLTServer->GetClientData( hClient, ( uint8* )&ncd, nNcdSize ) || nNcdSize != sizeof( NetClientData ))
{
return NULL;
}
pszClientName = ncd.m_szPlayerGuid;
ePlayerModelId = (ModelId)ncd.m_ePlayerModelId;
// Check if the modelid is valid.
if( ePlayerModelId == eModelIdInvalid ||
ePlayerModelId >= g_pModelButeMgr->GetNumModels( ))
{
return NULL;
}
}
else
{
pszClientName = "singleplayer";
}
// Set our clientname from the netclientdata.
g_pLTServer->SetClientName( hClient, pszClientName, strlen( pszClientName ) + 1 );
// See if we can use a player from one of the clientrefs.
pPlayer = PickClientRefPlayer( hClient );
// If we found a player, then respawn, otherwise create a new player.
if( !pPlayer )
{
pPlayer = CreatePlayer( hClient, ePlayerModelId );
if( !pPlayer )
{
ASSERT( !"CGameServerShell::OnClientEnterWorld: Could not create player." );
return NULL;
}
}
RespawnPlayer( pPlayer, hClient );
// Add this client to our local list...
AddClientToList(hClient);
SetUpdateGameServ();
if (IsMultiplayerGame( ))
{
SendMultiPlayerDataToClient(hClient);
SendObjectivesDataToClient( hClient );
// Tell the player about our ncd.
pPlayer->SetNetClientData( ncd );
uint32 nClientID = g_pLTServer->GetClientID( hClient );
char const* pszNetUniqueName = pPlayer->GetNetUniqueName( );
CAutoMessage cMsg;
cMsg.Writeuint8( MID_PLAYER_CONNECTED );
cMsg.WriteString( pszNetUniqueName );
cMsg.Writeuint32( nClientID );
g_pLTServer->SendToClient( cMsg.Read(), hClient, MESSAGE_GUARANTEED );
}
else
{
// Let the client know if any objectives have been added before they actually entered the world...
SendObjectivesDataToClient( hClient );
}
// All done...
return pPlayer;
}
// ----------------------------------------------------------------------- //
// Sends a game data message to the specified client.
// ----------------------------------------------------------------------- //
void CGameServerShell::SendMultiPlayerDataToClient(HCLIENT hClient)
{
if( !hClient )
return;
CAutoMessage cMsg;
cMsg.Writeuint8(MID_MULTIPLAYER_DATA);
cMsg.Writeuint8((uint8)GetGameType());
if (IsMultiplayerGame( ))
{
// Get our ip address and port...
char sBuf[32];
int nBufSize = 30;
WORD wPort = 0;
g_pLTServer->GetTcpIpAddress(sBuf, nBufSize, wPort);
cMsg.WriteString(sBuf);
cMsg.Writeuint32((uint32) wPort);
}
g_pLTServer->SendToClient(cMsg.Read(), hClient, MESSAGE_GUARANTEED);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::SendObjectivesDataToClient()
//
// PURPOSE: Sends all current objective data to the client...
//
// ----------------------------------------------------------------------- //
void CGameServerShell::SendObjectivesDataToClient( HCLIENT hClient )
{
if( !hClient )
return;
CAutoMessage cMsg;
cMsg.Writeuint8( MID_OBJECTIVES_DATA );
int nNumObj = m_Objectives.m_IDArray.size();
//send total number of objectives
cMsg.Writeuint8((uint8)nNumObj);
//send list of general objectives
for (uint8 i = 0; i < m_Objectives.m_IDArray.size(); i++)
{
cMsg.Writeuint32((uint32)m_Objectives.m_IDArray[i]);
}
//send total number of optional objectives
nNumObj = m_OptionalObjectives.m_IDArray.size();
cMsg.Writeuint8((uint8)nNumObj);
//send list of optional objectives
for (i = 0; i < m_OptionalObjectives.m_IDArray.size(); i++)
{
cMsg.Writeuint32((uint32)m_OptionalObjectives.m_IDArray[i]);
}
//send total number of completed objectives
nNumObj = m_CompletedObjectives.m_IDArray.size();
cMsg.Writeuint8((uint8)nNumObj);
//send list of general completed objectives
for (i = 0; i < m_CompletedObjectives.m_IDArray.size(); i++)
{
cMsg.Writeuint32((uint32)m_CompletedObjectives.m_IDArray[i]);
}
//send total number of mission parameters
nNumObj = m_Parameters.m_IDArray.size();
cMsg.Writeuint8((uint8)nNumObj);
//send list of mission parameters
for (i = 0; i < m_Parameters.m_IDArray.size(); i++)
{
cMsg.Writeuint32((uint32)m_Parameters.m_IDArray[i]);
}
g_pLTServer->SendToClient(cMsg.Read(), hClient, MESSAGE_GUARANTEED);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::OnClientExitWorld()
//
// PURPOSE: remove a client
//
// ----------------------------------------------------------------------- //
void CGameServerShell::OnClientExitWorld(HCLIENT hClient)
{
// Remove this client from our local list...
RemoveClientFromList(hClient);
SetUpdateGameServ();
// Remove the player object...
CPlayerObj* pPlayer = (CPlayerObj*)g_pLTServer->GetClientUserData(hClient);
if (pPlayer)
{
// Clear our client pointer.
pPlayer->SetClient( NULL );
g_pLTServer->RemoveObject(pPlayer->m_hObject);
g_pLTServer->SetClientUserData(hClient, LTNULL);
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::PreStartWorld()
//
// PURPOSE: Handle pre start world
//
// ----------------------------------------------------------------------- //
void CGameServerShell::PreStartWorld(bool bSwitchingWorlds)
{
// Make sure the client doesn't hold a pause on us.
ClientPauseGame( false );
// No commands yet...
m_CmdMgr.Clear();
m_pCharacterMgr->PreStartWorld(m_nLastLGFlags);
m_pAIStimulusMgr->Term();
m_pAIStimulusMgr->Init();
m_pAICentralKnowledgeMgr->Term();
m_pAICentralKnowledgeMgr->Init();
// Tell the server app.
ServerAppPreStartWorld( );
// Make sure we reset any necessary globals...
Camera::ClearActiveCameras();
// Clear the object template mgr
m_pObjectTemplates->Clear();
// Clear the lite object mgr
m_pLiteObjectMgr->PreStartWorld(bSwitchingWorlds);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::PostStartWorld()
//
// PURPOSE: Handle post switch world
//
// ----------------------------------------------------------------------- //
void CGameServerShell::PostStartWorld()
{
m_pCharacterMgr->PostStartWorld(m_nLastLGFlags);
// Load any commands we might have for this level...
if( g_pCommandButeMgr )
g_pCommandButeMgr->PostStartWorld( m_nLastLGFlags );
// Tell the server app.
ServerAppPostStartWorld( );
// Start the switching worlds state machine.
StartSwitchingWorlds( );
// Give the lite objects a chance to do post-start world stuff
GetLiteObjectMgr()->PostStartWorld();
//Clear the mission failed flag (and unpause if it had paused us)
g_pServerMissionMgr->SetMissionFailed(false);
// Set the min music mood for the current level.
m_eMinMusicMood = CMusicMgr::eMoodRoutine;
HCONVAR hMinMusicMood = g_pLTServer->GetGameConVar("MinMusicMood");
if( hMinMusicMood )
{
const char* pVal = g_pLTServer->GetVarValueString(hMinMusicMood);
if (pVal && pVal[0] != 0)
{
for( int iMood=0; iMood < CMusicMgr::kNumMoods; ++iMood )
{
if( stricmp( s_aszMusicMoods[iMood], pVal ) == 0 )
{
m_eMinMusicMood = (CMusicMgr::Mood)iMood;
break;
}
}
}
}
}
void CGameServerShell::SendPlayerInfoMsgToClients(HCLIENT hClients, CPlayerObj *pPlayer, uint8 nInfoType)
{
HCLIENT hClient = pPlayer->GetClient();
if (!hClient) return;
uint32 nClientID = g_pLTServer->GetClientID(hClient);
bool bIsAdmin = false;
if( ScmdServer::Instance( ).GetAdminControl( ) == ScmdServer::kAdminControlClient &&
hClient == ScmdServer::Instance( ).GetAdminClient( ))
{
bIsAdmin = true;
}
CAutoMessage cMsg;
cMsg.Writeuint8(MID_PLAYER_INFO);
cMsg.WriteString(pPlayer->GetNetUniqueName());
cMsg.Writeuint32(nClientID);
cMsg.WriteObject(pPlayer->m_hObject);
cMsg.Writeuint8((uint8)pPlayer->GetModelId());
cMsg.Writeuint8(pPlayer->GetTeamID( ));
cMsg.Writebool( bIsAdmin );
cMsg.Writeuint8(nInfoType);
g_pLTServer->SendToClient(cMsg.Read(), hClients, MESSAGE_GUARANTEED);
pPlayer->GetPlayerScore()->UpdateClients(hClients);
}
void CGameServerShell::ProcessHandshake(HCLIENT hClient, ILTMessage_Read *pMsg)
{
// Get the player
CPlayerObj *pPlayer = GetPlayerFromClientList(hClient);
if (!pPlayer)
{
// Uh... Who are you again?
g_pLTServer->KickClient(hClient);
return;
}
//host doesn't need to provide user password
bool bIsHost = g_pLTServer->GetClientInfoFlags(hClient) & CIF_LOCAL;
// Get the player's GUID.
char szClientName[MAX_CLIENT_NAME_LENGTH] = "";
g_pLTServer->GetClientName( hClient, szClientName, ARRAY_LEN( szClientName ));
if( !szClientName[0] )
{
g_pLTServer->KickClient( hClient );
return;
}
int nHandshakeSub = (int)pMsg->Readuint8();
switch (nHandshakeSub)
{
case MID_HANDSHAKE_HELLO :
{
// Check the client's version
int nHandshakeVer = (int)pMsg->Readuint16();
if (nHandshakeVer != GAME_HANDSHAKE_VER)
{
// If they got here, they ignored our different version number. Boot 'em!
g_pLTServer->KickClient(hClient);
// Jump out of the handshake
return;
}
// Read in the client's sooper-secret key
uint32 nClientKey = pMsg->Readuint32();
// Write out a password message, encrypted with their key
// Note : A key from them that null encrypts our key doesn't really effect
// anything.. I mean, they DID send the key, and they're the ones that need
// to use our key anyway..
CAutoMessage cResponse;
cResponse.Writeuint8(MID_HANDSHAKE);
cResponse.Writeuint8(MID_HANDSHAKE_PASSWORD);
cResponse.Writeuint32( GAME_HANDSHAKE_PASSWORD );
cResponse.Writebool((!bIsHost && m_ServerGameOptions.m_bUsePassword));
g_pLTServer->SendToClient(cResponse.Read(), hClient, MESSAGE_GUARANTEED);
}
break;
case MID_HANDSHAKE_LETMEIN :
{
// Get the client's password
uint32 nClientPassword = pMsg->Readuint32();
uint32 nXORMask = GAME_HANDSHAKE_MASK;
nClientPassword ^= nXORMask;
uint32 nClientName = GAME_HANDSHAKE_PASSWORD;
// Validate
if (nClientName != nClientPassword)
{
// They're a fake!!
g_pLTServer->KickClient(hClient);
return;
}
// Read in their weapons file CRC
uint32 nWeaponCRC = g_pWeaponMgr->GetFileCRC();
nWeaponCRC ^= nXORMask;
uint32 nClientCRC = pMsg->Readuint32();
#ifndef _DEBUG
if (nWeaponCRC != nClientCRC)
{
// They're cheating!!
g_pLTServer->KickClient(hClient);
return;
}
#endif
// Read in their client file CRC
uint32 nCShellCRC = m_nCShellCRC;
nCShellCRC ^= nXORMask;
nClientCRC = pMsg->Readuint32();
#ifndef _DEBUG
if (nCShellCRC != nClientCRC)
{
// They're cheating!!
g_pLTServer->KickClient(hClient);
return;
}
#endif
// CRC the modelbutes.txt
static uint32 nModelButesCRC = CRC32::CalcRezFileCRC( g_pModelButeMgr->GetAttributeFile( ));
uint32 nModelButesMaskedCRC = nModelButesCRC ^ nXORMask;
uint32 nClientModelButesCRC = pMsg->Readuint32();
#ifndef _DEBUG
if( nClientModelButesCRC != nModelButesMaskedCRC )
{
// They're cheating!!
g_pLTServer->KickClient(hClient);
return;
}
#endif
// CRC the surface.txt
static uint32 nSurfaceCRC = CRC32::CalcRezFileCRC( g_pSurfaceMgr->GetAttributeFile( ));
uint32 nSurfaceMaskedCRC = nSurfaceCRC ^ nXORMask;
uint32 nClientSurfaceCRC = pMsg->Readuint32();
#ifndef _DEBUG
if( nClientSurfaceCRC != nSurfaceMaskedCRC )
{
// They're cheating!!
g_pLTServer->KickClient(hClient);
return;
}
#endif
// CRC the damagefx.txt
static uint32 nDamageFxCRC = CRC32::CalcRezFileCRC( "attributes\\damagefx.txt" );
uint32 nDamageFxMaskedCRC = nDamageFxCRC ^ nXORMask;
uint32 nClientDamageFxCRC = pMsg->Readuint32();
#ifndef _DEBUG
if( nClientDamageFxCRC != nDamageFxMaskedCRC )
{
// They're cheating!!
g_pLTServer->KickClient(hClient);
return;
}
#endif
uint32 nHashedPassword = pMsg->Readuint32();
uint32 nServerHashedPassword = str_Hash(m_ServerGameOptions.m_sPassword.c_str( ));
// Validate
if (!bIsHost && m_ServerGameOptions.m_bUsePassword && nHashedPassword != nServerHashedPassword)
{
// They don't know the password
// Tell the client...
CAutoMessage cMsg;
cMsg.Writeuint8(MID_HANDSHAKE);
cMsg.Writeuint8((uint8)MID_HANDSHAKE_WRONGPASS);
g_pLTServer->SendToClient(cMsg.Read(), hClient, MESSAGE_GUARANTEED);
//and boot 'em
//jrg - 9/4/02 in this particular case we let the client disconnect itself so that it can handle
// an incorrect password a little more smoothly
// g_pLTServer->KickClient(hClient);
return;
}
// Tell the client they passed the test...
CAutoMessage cMsg;
cMsg.Writeuint8(MID_HANDSHAKE);
cMsg.Writeuint8((uint8)MID_HANDSHAKE_DONE);
g_pLTServer->SendToClient(cMsg.Read(), hClient, MESSAGE_GUARANTEED);
// Unlock the player
pPlayer->FinishHandshake();
// Spawn them in..
RespawnPlayer(pPlayer, hClient);
}
break;
default :
{
// Hmm.. They sent over an invalid handshake message. They're naughty.
g_pLTServer->KickClient(hClient);
return;
}
}
}
/***************************************************************************/
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::OnMessage()
//
// PURPOSE: Routes messages to a specific handler in an effort to reduce
// ungodly sized switch cases.
//
// ----------------------------------------------------------------------- //
void CGameServerShell::OnMessage(HCLIENT hSender, ILTMessage_Read *pMsg)
{
if( !pMsg )
return;
// Let the server missionmgr handle its messages.
if( g_pServerMissionMgr )
{
if( g_pServerMissionMgr->OnMessage( hSender, *pMsg ))
return;
}
// Let the server saveloadmgr handle its messages.
if( g_pServerSaveLoadMgr )
{
if( g_pServerSaveLoadMgr->OnMessage( hSender, *pMsg ))
return;
}
// Let the scmd check if it needs this message.
if( ScmdServer::Instance( ).OnMessage( hSender, *pMsg ))
{
return;
}
// Update our clientupdate time if mp.
if( IsMultiplayerGame( ) && !( g_pLTServer->GetClientInfoFlags( hSender ) & CIF_LOCAL ))
{
ClientData* pClientData = GetClientData( hSender );
if( pClientData )
{
pClientData->m_nLastClientUpdateTime = GetTickCount( );
}
}
pMsg->SeekTo(0);
uint8 messageID = pMsg->Readuint8();
switch (messageID)
{
case MID_PLAYER_UPDATE: HandlePlayerUpdate (hSender, pMsg); break;
case MID_WEAPON_FIRE: HandleWeaponFire (hSender, pMsg); break;
case MID_WEAPON_RELOAD: HandleWeaponReload (hSender, pMsg); break;
case MID_WEAPON_SOUND: HandleWeaponSound (hSender, pMsg); break;
case MID_WEAPON_SOUND_LOOP: HandleWeaponSoundLoop (hSender, pMsg); break;
case MID_WEAPON_CHANGE: HandleWeaponChange (hSender, pMsg); break;
case MID_PLAYER_ACTIVATE: HandlePlayerActivate (hSender, pMsg); break;
case MID_PLAYER_CLIENTMSG: HandlePlayerClientMsg (hSender, pMsg); break;
case MID_FRAG_SELF: HandleFragSelf (hSender, pMsg); break;
case MID_PLAYER_RESPAWN: HandlePlayerRespawn (hSender, pMsg); break;
case MID_PLAYER_CANCELREVIVE: HandlePlayerCancelRevive (hSender, pMsg); break;
case MID_CLIENT_LOADED: HandleClientLoaded (hSender, pMsg); break;
case MID_PLAYER_MESSAGE: HandlePlayerMessage (hSender, pMsg); break;
case MID_PLAYER_CHEAT: HandlePlayerCheat (hSender, pMsg); break;
case MID_PLAYER_SKILLS: HandlePlayerSkills (hSender, pMsg); break;
case MID_PLAYER_TELEPORT: HandlePlayerTeleport (hSender, pMsg); break;
case MID_GAME_PAUSE: HandleGamePause (hSender, pMsg); break;
case MID_GAME_UNPAUSE: HandleGameUnpause (hSender, pMsg); break;
case MID_CONSOLE_TRIGGER: HandleConsoleTrigger (hSender, pMsg); break;
case MID_CONSOLE_COMMAND: HandleConsoleCommand (hSender, pMsg); break;
case MID_DIFFICULTY: HandleDifficulty (hSender, pMsg); break;
case MID_STIMULUS: HandleStimulus (hSender, pMsg); break;
case MID_RENDER_STIMULUS: HandleRenderStimulus (hSender, pMsg); break;
case MID_OBJECT_ALPHA: HandleObjectAlpha (hSender, pMsg); break;
case MID_ADD_GOAL: HandleAddGoal (hSender, pMsg); break;
case MID_REMOVE_GOAL: HandleRemoveGoal (hSender, pMsg); break;
case MID_GADGETTARGET: HandleGadgetTarget (hSender, pMsg); break;
case MID_SEARCH: HandleSearch (hSender, pMsg); break;
case MID_DECISION: HandleDecision (hSender, pMsg); break;
case MID_PLAYER_TAUNT: HandlePlayerTaunt (hSender, pMsg); break;
case MID_MULTIPLAYER_UPDATE: HandleMultiplayerUpdate (hSender, pMsg); break;
case MID_PLAYER_MULTIPLAYER_INIT: HandleMultiplayerInit (hSender, pMsg); break;
case MID_PLAYER_INFOCHANGE: HandleMultiplayerPlayerUpdate (hSender, pMsg); break;
case MID_HANDSHAKE: HandleHandshake (hSender, pMsg); break;
case MID_PLAYER_GHOSTMESSAGE: HandlePlayerGhostMessage (hSender, pMsg); break;
case MID_PLAYER_CHATMODE: HandlePlayerChatMode (hSender, pMsg); break;
case MID_CLEAR_PROGRESSIVE_DAMAGE: HandleClearProgressiveDamage (hSender, pMsg); break;
case MID_PROJECTILE: HandleProjectileMessage (hSender, pMsg); break;
case MID_SAVE_GAME: HandleSaveGame (hSender, pMsg); break;
case MID_OBJECT_MESSAGE: HandleObjectMessage (hSender, pMsg); break;
case MID_PERFORMANCE: HandlePerformanceMessage (hSender, pMsg); break;
default: HandleDefault (hSender, pMsg); break;
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::Handle ()
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
void CGameServerShell::HandlePlayerUpdate (HCLIENT hSender, ILTMessage_Read *pMsg)
{
// Update the player...
CPlayerObj* pPlayer = GET_PLAYER(hSender);
if (pPlayer)
{
if (pPlayer->ClientUpdate(pMsg))
{
// Merged player position and update messages.
pPlayer->HandlePlayerPositionMessage(pMsg);
}
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::Handle ()
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
void CGameServerShell::HandleWeaponFire (HCLIENT hSender, ILTMessage_Read *pMsg)
{
CPlayerObj* pPlayer = GET_PLAYER(hSender);
if (pPlayer)
{
pPlayer->HandleWeaponFireMessage (pMsg);
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::HandleWeaponReload
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
void CGameServerShell::HandleWeaponReload(HCLIENT hSender, ILTMessage_Read *pMsg)
{
CPlayerObj *pPlayer = GET_PLAYER( hSender );
if( pPlayer )
{
uint8 nAmmoId = pMsg->Readuint8();
pPlayer->DoWeaponReload( nAmmoId );
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::Handle ()
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
void CGameServerShell::HandleWeaponSound (HCLIENT hSender, ILTMessage_Read *pMsg)
{
CPlayerObj* pPlayer = GET_PLAYER(hSender);
if (pPlayer)
{
pPlayer->HandleWeaponSoundMessage (pMsg);
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::HandleWeaponSoundLoop
//
// PURPOSE: Relays message to specific player to handle
//
// ----------------------------------------------------------------------- //
void CGameServerShell::HandleWeaponSoundLoop( HCLIENT hSender, ILTMessage_Read *pMsg )
{
CPlayerObj *pPlayer = GET_PLAYER( hSender );
if( pPlayer )
{
pPlayer->HandleWeaponSoundLoopMessage( pMsg );
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::HandleWeaponChange ()
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
void CGameServerShell::HandleWeaponChange (HCLIENT hSender, ILTMessage_Read *pMsg)
{
CPlayerObj* pPlayer = GET_PLAYER(hSender);
if (pPlayer)
{
uint8 nWeaponId = pMsg->Readuint8();
uint8 nAmmoId = pMsg->Readuint8();
pPlayer->DoWeaponChange(nWeaponId,nAmmoId);
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::HandlePlayerActivate ()
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
void CGameServerShell::HandlePlayerActivate (HCLIENT hSender, ILTMessage_Read *pMsg)
{
CPlayerObj* pPlayer = GET_PLAYER(hSender);
if (pPlayer)
{
pPlayer->HandleActivateMessage(pMsg);
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::HandlePlayerClientMsg ()
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
void CGameServerShell::HandlePlayerClientMsg (HCLIENT hSender, ILTMessage_Read *pMsg)
{
CPlayerObj* pPlayer = GET_PLAYER(hSender);
if (pPlayer)
{
pPlayer->HandleClientMsg(pMsg);
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::HandlePlayerTeleport ()
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
void CGameServerShell::HandlePlayerTeleport (HCLIENT hSender, ILTMessage_Read *pMsg)
{
CPlayerObj* pPlayer = GET_PLAYER(hSender);
if (pPlayer)
{
pPlayer->HandleTeleportMsg(pMsg);
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::HandleFragSelf ()
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
void CGameServerShell::HandleFragSelf (HCLIENT hSender, ILTMessage_Read *pMsg)
{
CPlayerObj* pPlayer = GET_PLAYER(hSender);
if (pPlayer)
{
LPBASECLASS pClass = g_pLTServer->HandleToObject(pPlayer->m_hObject);
if (pClass)
{
DamageStruct damage;
damage.eType = DT_EXPLODE;
damage.fDamage = damage.kInfiniteDamage;
damage.hDamager = pPlayer->m_hObject;
damage.vDir.Init(0, 1, 0);
damage.DoDamage(pClass, pPlayer->m_hObject);
}
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::HandlePlayerRespawn ()
//
// PURPOSE: when the player dies he is responed back into the world in
// one of two states. the first state is PS_ALIVE where the
// player can participate in the match. the second state is
// PS_GHOST where the player has no interaction with the
// in-game world and basically acts as a spectator.
//
// ----------------------------------------------------------------------- //
void CGameServerShell::HandlePlayerRespawn (HCLIENT hSender, ILTMessage_Read *pMsg)
{
CPlayerObj* pPlayer = GET_PLAYER(hSender);
// don't respawn player if he is alive (may cause problems for end of match spawns)
if (pPlayer && pPlayer->CanRespawn( ))
{
pPlayer->Respawn( );
pPlayer->ResetAfterDeath( );
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::HandlePlayerCancelRevive
//
// PURPOSE: In certain gametypes, the player can be revived while
// waiting to respawn. If they don't wish to be revived,
// they can cancel revive by hitting the fire or activate
// while the timer is counting down.
//
// ----------------------------------------------------------------------- //
void CGameServerShell::HandlePlayerCancelRevive( HCLIENT hSender, ILTMessage_Read *pMsg )
{
CPlayerObj* pPlayer = GET_PLAYER(hSender);
// don't respawn player if he is alive (may cause problems for end of match spawns)
if (pPlayer && pPlayer->CanRespawn( ))
{
pPlayer->CancelRevive( );
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::HandleClientLoaded()
//
// PURPOSE: Sent from the client in response to a server message of
// MID_CLIENT_LOADED. Client sends this when it is fully
// loaded and in the play state.
//
// ----------------------------------------------------------------------- //
void CGameServerShell::HandleClientLoaded( HCLIENT hSender, ILTMessage_Read *pMsg )
{
CPlayerObj* pPlayer = GET_PLAYER(hSender);
ASSERT( pPlayer && "No player associated with client!" );
if( pPlayer )
{
pPlayer->SetClientLoaded( true );
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::HandlePlayerTaunt ()
//
// PURPOSE: when we get an audio taunt from a player we first check to
// see if we have audio taunts turned off here on the server.
// if not we forward the taunt to the clients
//
// ----------------------------------------------------------------------- //
void CGameServerShell::HandlePlayerTaunt (HCLIENT hSender, ILTMessage_Read *pMsg)
{
CPlayerObj* pPlayer = GET_PLAYER(hSender);
if (pPlayer && g_NetAudioTaunts.GetFloat() > 0.0f)
{
uint32 nTauntID = pMsg->Readuint32();
CAutoMessage cTauntMsg;
cTauntMsg.Writeuint8(MID_SFX_MESSAGE);
cTauntMsg.Writeuint8(SFX_CHARACTER_ID);
cTauntMsg.WriteObject(pPlayer->m_hObject);
cTauntMsg.Writeuint8(CFX_TAUNT_MSG);
cTauntMsg.Writeuint32(nTauntID);
cTauntMsg.Writeuint8(pPlayer->GetTeamID());
g_pLTServer->SendToClient(cTauntMsg.Read(), LTNULL, 0);
// retrieve the string they sent
char szString[256];
szString[0] = 0;
pMsg->ReadString(szString, sizeof(szString));
// So it shows up in GameSrv..
if(szString[0] && !(g_pLTServer->GetClientInfoFlags(hSender) & CIF_LOCAL))
{
g_pLTServer->CPrint(szString);
}
uint32 clientID = g_pLTServer->GetClientID(hSender);
// now send the string to all clients
CAutoMessage cStringMsg;
cStringMsg.Writeuint8(MID_PLAYER_MESSAGE);
cStringMsg.WriteString(szString);
cStringMsg.Writeuint32(clientID);
cStringMsg.Writeuint8(pPlayer->GetTeamID());
g_pLTServer->SendToClient(cStringMsg.Read(), LTNULL, 0);
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::HandleMultiplayerUpdate ()
//
// PURPOSE: send all of the player states to everyone on the server. this
// is basically just a state update.
//
// ----------------------------------------------------------------------- //
void CGameServerShell::HandleMultiplayerUpdate (HCLIENT hSender, ILTMessage_Read *pMsg)
{
CPlayerObj* pPlayer = GET_PLAYER(hSender);
if (pPlayer)
{
// Tell the new Client about all the clients already
// on the server...
for (int i = 0; i < MAX_CLIENTS; i++)
{
CPlayerObj* pCurPlayer = GetPlayerFromClientList(m_aClients[i]);
if (pCurPlayer)
{
SendPlayerInfoMsgToClients(pPlayer->GetClient(), pCurPlayer, MID_PI_UPDATE);
}
}
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::HandleMultiplayerServerDir ()
//
// PURPOSE: Handle messages sent through the server directory interface
//
// ----------------------------------------------------------------------- //
void CGameServerShell::HandleMultiplayerServerDir (HCLIENT hSender, ILTMessage_Read *pMsg)
{
// Only handle this message if we actually have a server directory
if (!m_pServerDir)
return;
uint8 aNumericAddr[4];
char aSourceAddr[16];
uint16 nSourcePort;
// Get the address and port of where this came from
if (!hSender)
{
GetCurMessageSource(aNumericAddr, &nSourcePort);
}
else
{
g_pLTServer->GetClientAddr(hSender, aNumericAddr, &nSourcePort);
}
// Convert the address portion
sprintf(aSourceAddr, "%d.%d.%d.%d",
(uint32)aNumericAddr[0],
(uint32)aNumericAddr[1],
(uint32)aNumericAddr[2],
(uint32)aNumericAddr[3]);
// Let the server directory handle it
m_pServerDir->HandleNetMessage(*CLTMsgRef_Read(pMsg->SubMsg(pMsg->Tell())), aSourceAddr, nSourcePort);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::HandleMultiplayerInit ()
//
// PURPOSE: initializes a clients player object when they join a server
// and informs all other clients that someone has joined.
//
// ----------------------------------------------------------------------- //
void CGameServerShell::HandleMultiplayerInit (HCLIENT hSender, ILTMessage_Read *pMsg)
{
CPlayerObj* pNewPlayer = GET_PLAYER(hSender);
if( !pNewPlayer )
return;
// try and init player from message
if( !pNewPlayer->MultiplayerInit( pMsg ))
return;
// Tell our client about us so that it knows what team we're on
if( IsTeamGameType( ))
{
SendPlayerInfoMsgToClients( hSender, pNewPlayer, MID_PI_UPDATE );
}
// Don't just broadcast the list. That would send messages to clients that aren't fully connected yet.
CPlayerObj::PlayerObjList::const_iterator iter = CPlayerObj::GetPlayerObjList( ).begin( );
while( iter != CPlayerObj::GetPlayerObjList( ).end( ))
{
CPlayerObj* pOldPlayer = *iter;
if( pOldPlayer )
{
// Make sure the player has a client.
if( pOldPlayer->GetClient( ) && pOldPlayer->RespawnCalled() )
{
// Send a message to each existing clients, letting them know a new client has joined the game...
SendPlayerInfoMsgToClients(pOldPlayer->GetClient( ), pNewPlayer, MID_PI_JOIN);
// Tell the new Client about each client already on the server...
if (pNewPlayer != pOldPlayer) // avoid telling the client about himself (shouldn't be necessary)
{
SendPlayerInfoMsgToClients(pNewPlayer->GetClient(), pOldPlayer, MID_PI_EXIST);
}
else
{
ASSERT( !"CGameServerShell::HandleMultiplayerInit() : new player already respawned?" );
}
}
}
else
{
ASSERT( !"CGameServerShell::HandleMultiplayerInit() : Invalid playerobj entry." );
}
iter++;
}
// Resend all the line systems.
LineSystem::ResendAll( );
// now get the new player into the world
pNewPlayer->Respawn(m_nLastLGFlags);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::HandleMultiplayerPlayerUpdate ()
//
// PURPOSE: updates a clients player info and informs all other clients of the changes.
//
// ----------------------------------------------------------------------- //
void CGameServerShell::HandleMultiplayerPlayerUpdate (HCLIENT hSender, ILTMessage_Read *pMsg)
{
CPlayerObj* pPlayer = GET_PLAYER(hSender);
if( !pPlayer )
return;
// try and update player from message
if( !pPlayer->MultiplayerUpdate( pMsg ))
return;
// Send a message to all clients, letting them know a
// new client has joined the game...
SendPlayerInfoMsgToClients(LTNULL, pPlayer, MID_PI_UPDATE);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::HandleHandshake ()
//
// PURPOSE: the handshack process is a way to get the client and server
// agree upon a communiction protocol. in cases like "Denile
// Of Service" (DOS) attacks the client will be droped if they
// dont respond with in a fixed amount of time.
//
// ----------------------------------------------------------------------- //
void CGameServerShell::HandleHandshake (HCLIENT hSender, ILTMessage_Read *pMsg)
{
ProcessHandshake(hSender, pMsg);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::HandlePlayerMessage ()
//
// PURPOSE: this handler is called when a player sends out a text message
// which routes it to the rest of the player
//
// ----------------------------------------------------------------------- //
void CGameServerShell::HandlePlayerMessage (HCLIENT hSender, ILTMessage_Read *pMsg)
{
// retrieve the string they sent
char szString[256];
szString[0] = 0;
pMsg->ReadString(szString, sizeof(szString));
bool bTeamMsg = pMsg->Readbool();
uint8 nTeam = INVALID_TEAM;
CPlayerObj* pPlayer = GET_PLAYER(hSender);
if (IsTeamGameType() && bTeamMsg && pPlayer)
nTeam = pPlayer->GetTeamID();
// So it shows up in GameSrv..
if(szString[0] && !(g_pLTServer->GetClientInfoFlags(hSender) & CIF_LOCAL))
{
if( !pPlayer )
return;
char szMsg[256] = {0};
sprintf( szMsg, "%s: %s", pPlayer->GetNetUniqueName(), szString );
g_pLTServer->CPrint( szMsg );
}
uint32 clientID = g_pLTServer->GetClientID(hSender);
// now send the string to all clients
CAutoMessage cMsg;
cMsg.Writeuint8(MID_PLAYER_MESSAGE);
cMsg.WriteString(szString);
cMsg.Writeuint32(clientID);
cMsg.Writeuint8(nTeam);
g_pLTServer->SendToClient(cMsg.Read(), LTNULL, MESSAGE_GUARANTEED);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::HandlePlayerGhostMessage ()
//
// PURPOSE: this handler is called when a player sends out a text message
// which only routes it to other spectators
//
// ----------------------------------------------------------------------- //
void CGameServerShell::HandlePlayerGhostMessage (HCLIENT hSender, ILTMessage_Read *pMsg)
{
CPlayerObj* pPlayer = GET_PLAYER(hSender);
if( !pPlayer )
return;
//do nothing if player isn't a ghost
if (pPlayer->GetState() != PS_GHOST) return;
// retrieve the string they sent
char szString[100];
szString[0] = 0;
pMsg->ReadString(szString, sizeof(szString));
// So it shows up in GameSrv..
if(szString[0] && !(g_pLTServer->GetClientInfoFlags(hSender) & CIF_LOCAL))
{
char szMsg[256] = {0};
sprintf( szMsg, "%s: %s", pPlayer->GetNetUniqueName(), szString );
g_pLTServer->CPrint( szMsg );
}
uint32 clientID = g_pLTServer->GetClientID(hSender);
// now send the string to all clients on the same team
for (int i = 0; i < MAX_CLIENTS; i++)
{
CPlayerObj* pCurPlayer = GetPlayerFromClientList(m_aClients[i]);
if (pCurPlayer && pCurPlayer->GetState() == PS_GHOST)
{
CAutoMessage cMsg;
cMsg.Writeuint8(MID_PLAYER_GHOSTMESSAGE);
cMsg.WriteString(szString);
g_pLTServer->SendToClient(cMsg.Read(), pCurPlayer->GetClient(), MESSAGE_GUARANTEED);
}
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::HandlePlayerChatMode ()
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
void CGameServerShell::HandlePlayerChatMode (HCLIENT hSender, ILTMessage_Read *pMsg)
{
CPlayerObj* pPlayer = GET_PLAYER(hSender);
if (pPlayer)
{
LTBOOL bChatting = (LTBOOL)pMsg->Readuint8();
pPlayer->SetChatting(bChatting);
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::HandlePlayerCheat ()
//
// PURPOSE: this handler is called when the player enters a cheat code
// into the console. it checks some validity issues and then
// routes the cheat to the appropriat handler
//
// ----------------------------------------------------------------------- //
void CGameServerShell::HandlePlayerCheat (HCLIENT hSender, ILTMessage_Read *pMsg)
{
#ifdef _DEMO
return; // No cheats in demo mode
#endif
// get a pointer to the sender's player object
CPlayerObj* pPlayer = GET_PLAYER(hSender);
if (!pPlayer) return;
// retrieve message data
CheatCode nCheatCode = (CheatCode) pMsg->Readuint8();
uint32 nData = pMsg->Readuint32();
// now deal with the specific cheat code
if (nCheatCode <= CHEAT_NONE || nCheatCode >= CHEAT_MAX) return; // wont the default case catch these?
#ifdef _FINAL
if (IsMultiplayerGame( )) // No cheats in multiplayer - oh yeah?! :{
{
switch (nCheatCode) // why always send the data? it was easier to cut & paste
{
case CHEAT_NEXTMISSION: CheatNextMission(pPlayer, nData); break;
case CHEAT_BOOT: CheatBootPlayer (pPlayer, nData); break;
}
return;
}
#endif
switch (nCheatCode) // why always send the data? it was easier to cut & paste
{
case CHEAT_GOD: CheatGod (pPlayer, nData); break;
case CHEAT_AMMO: CheatAmmo (pPlayer, nData); break;
case CHEAT_ARMOR: CheatArmor (pPlayer, nData); break;
case CHEAT_HEALTH: CheatHealth (pPlayer, nData); break;
case CHEAT_CLIP: CheatClip (pPlayer, nData); break;
case CHEAT_INVISIBLE: CheatInvisible (pPlayer, nData); break;
case CHEAT_TELEPORT: CheatTeleport (pPlayer, nData); break;
case CHEAT_FULL_WEAPONS: CheatWeapons (pPlayer, nData); break;
case CHEAT_TEARS: CheatTears (pPlayer, nData); break;
case CHEAT_REMOVEAI: CheatRemoveAI (pPlayer, nData); break;
case CHEAT_SNOWMOBILE: CheatSnowmobile (pPlayer, nData); break;
case CHEAT_MODSQUAD: CheatModSquad (pPlayer, nData); break;
case CHEAT_FULL_GEAR: CheatFullGear (pPlayer, nData); break;
case CHEAT_EXITLEVEL: CheatExitLevel (pPlayer, nData); break;
case CHEAT_NEXTMISSION: CheatNextMission(pPlayer, nData); break;
case CHEAT_BOOT: CheatBootPlayer (pPlayer, nData); break;
case CHEAT_GIMMEGUN: CheatGimmeGun (pPlayer, nData); break;
case CHEAT_GIMMEMOD: CheatGimmeMod (pPlayer, nData); break;
case CHEAT_GIMMEGEAR: CheatGimmeGear (pPlayer, nData); break;
case CHEAT_GIMMEAMMO: CheatGimmeAmmo (pPlayer, nData); break;
case CHEAT_SKILLZ: CheatSkillz (pPlayer, nData); break;
case CHEAT_BODYGOLFING: CheatBodyGolfing(pPlayer, nData); break;
default: CheatDefault (pPlayer, nData); break; // good way to catch bugs, we hate those default cheaters
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::HandleGamePause ()
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
void CGameServerShell::HandleGamePause (HCLIENT hSender, ILTMessage_Read *pMsg)
{
ClientPauseGame( true );
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::HandleGameUnpause ()
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
void CGameServerShell::HandleGameUnpause (HCLIENT hSender, ILTMessage_Read *pMsg)
{
ClientPauseGame( false );
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::HandleConsoleTrigger ()
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
void CGameServerShell::HandleConsoleTrigger (HCLIENT hSender, ILTMessage_Read *pMsg)
{
CPlayerObj* pPlayer = GET_PLAYER(hSender);
if (!pPlayer)
{
return;
}
// Read the message data...
HSTRING hstrObjName = pMsg->ReadHString();
HSTRING hstrCommand = pMsg->ReadHString();
const char* pName = LTNULL;
const char* pCommand = LTNULL;
if (hstrObjName)
{
pName = g_pLTServer->GetStringData(hstrObjName);
}
if (hstrCommand)
{
pCommand = g_pLTServer->GetStringData(hstrCommand);
}
// Special case if we're supposed to list objects of a certain type...
if (_strnicmp(pCommand, "LIST", 4) == 0)
{
ConParse parse;
parse.Init(pCommand);
LTBOOL bNoObjects = LTTRUE;
if (g_pCommonLT->Parse(&parse) == LT_OK)
{
if (parse.m_nArgs > 1)
{
g_pLTServer->CPrint("Listing objects of type '%s'", parse.m_Args[1]);
LTVector vPos;
HCLASS hClass = g_pLTServer->GetClass(parse.m_Args[1]);
// Get the names of all the objects of the specified class...
HOBJECT hObj = g_pLTServer->GetNextObject(LTNULL);
while (hObj)
{
if (g_pLTServer->IsKindOf(g_pLTServer->GetObjectClass(hObj), hClass))
{
g_pLTServer->GetObjectPos( hObj, &vPos );
g_pLTServer->CPrint("%s (active) Pos<%.3f,%.3f,%.3f>", GetObjectName(hObj),
VEC_EXPAND( vPos ));
bNoObjects = LTFALSE;
}
hObj = g_pLTServer->GetNextObject(hObj);
}
hObj = g_pLTServer->GetNextInactiveObject(LTNULL);
while (hObj)
{
if (g_pLTServer->IsKindOf(g_pLTServer->GetObjectClass(hObj), hClass))
{
g_pLTServer->GetObjectPos( hObj, &vPos );
g_pLTServer->CPrint("%s (inactive) Pos<%.3f,%.3f,%.3f>", GetObjectName(hObj),
VEC_EXPAND( vPos ));
bNoObjects = LTFALSE;
}
hObj = g_pLTServer->GetNextInactiveObject(hObj);
}
CLiteObjectMgr::TObjectList aLiteObjects;
g_pGameServerShell->GetLiteObjectMgr()->GetObjectsOfClass(hClass, &aLiteObjects);
CLiteObjectMgr::TObjectList::iterator iCurObj = aLiteObjects.begin();
for (; iCurObj != aLiteObjects.end(); ++iCurObj)
{
g_pLTServer->CPrint("%s %s", (*iCurObj)->GetName(), (*iCurObj)->IsActive() ? "(active)" : "(inactive)");
}
bNoObjects |= !aLiteObjects.empty();
if (bNoObjects)
{
g_pLTServer->CPrint("No objects of type '%s' exist (NOTE: object type IS case-sensitive)", parse.m_Args[1]);
}
}
}
}
// Send the message to all appropriate objects...
else if (SendTriggerMsgToObjects(pPlayer, hstrObjName, hstrCommand))
{
g_pLTServer->CPrint("Sent '%s' Msg '%s'", pName ? pName : "Invalid Object!", pCommand ? pCommand : "Empty Message!!!");
}
else
{
g_pLTServer->CPrint("Failed to Send '%s' Msg '%s'!", pName ? pName : "Invalid Object!", pCommand ? pCommand : "Empty Message!!!");
}
if (hstrObjName)
{
g_pLTServer->FreeString(hstrObjName);
}
if (hstrCommand)
{
g_pLTServer->FreeString(hstrCommand);
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::HandleConsoleCommand ()
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
void CGameServerShell::HandleConsoleCommand (HCLIENT hSender, ILTMessage_Read *pMsg)
{
HSTRING hCommand = pMsg->ReadHString();
if (!hCommand) return;
if (m_CmdMgr.Process(g_pLTServer->GetStringData(hCommand), (ILTBaseClass*)NULL, (ILTBaseClass*)NULL))
{
g_pLTServer->CPrint("Sent Command '%s'", g_pLTServer->GetStringData(hCommand));
}
if (hCommand)
{
g_pLTServer->FreeString(hCommand);
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::HandleDifficulty ()
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
void CGameServerShell::HandleDifficulty (HCLIENT hSender, ILTMessage_Read *pMsg)
{
if (!IsDifficultyGameType()) return;
bool bIsHost = g_pLTServer->GetClientInfoFlags(hSender) & CIF_LOCAL;
if (!bIsHost) return;
m_eDifficulty = (GameDifficulty)pMsg->Readuint8();
g_pLTServer->CPrint("Difficulty:%d",(int)m_eDifficulty);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::HandleStimulus()
//
// PURPOSE: Handle a stimulus message by placing one in the world.
//
// ----------------------------------------------------------------------- //
void CGameServerShell::HandleStimulus(HCLIENT hSender, ILTMessage_Read *pMsg)
{
uint8 cArgs = pMsg->Readuint8();
char szStimType[64];
pMsg->ReadString(szStimType, 64);
EnumAIStimulusType eStimType = CAIStimulusMgr::StimulusFromString(szStimType);
float fMultiplier = (cArgs == 2) ? pMsg->Readfloat() : 1.f;
// Place stimulus at the location of the player.
LTVector vPos;
CPlayerObj *pPlayer = g_pCharacterMgr->FindPlayer();
g_pLTServer->GetObjectPos(pPlayer->m_hObject, &vPos);
g_pAIStimulusMgr->RegisterStimulus(eStimType, pPlayer->m_hObject, vPos, fMultiplier);
g_pLTServer->CPrint("Stimulus: %s at (%.2f, %.2f, %.2f) x%.2f", szStimType, vPos.x, vPos.y, vPos.z, fMultiplier);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::HandleRenderStimulus()
//
// PURPOSE: Handle a render stimulus message by toggling stimulus rendering.
//
// ----------------------------------------------------------------------- //
void CGameServerShell::HandleRenderStimulus(HCLIENT hSender, ILTMessage_Read *pMsg)
{
LTBOOL bRender = (LTBOOL)pMsg->Readuint8();
g_pAIStimulusMgr->RenderStimulus(bRender);
g_pLTServer->CPrint("Stimulus Rendering: %d", bRender);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::HandleObjectAlpha()
//
// PURPOSE: Handle an object alpha message by setting the alpha for the object.
//
// ----------------------------------------------------------------------- //
void CGameServerShell::HandleObjectAlpha(HCLIENT hSender, ILTMessage_Read *pMsg)
{
char szName[64];
pMsg->ReadString(szName, 64);
LTFLOAT fAlpha = pMsg->Readfloat();
HOBJECT hObject;
if ( LT_OK == FindNamedObject(szName, hObject) )
{
g_pLTServer->SetObjectColor(hObject, 0.f, 0.f, 0.f, fAlpha);
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::HandleAddGoal()
//
// PURPOSE: Handle an add goal message by adding a goal to an AI.
//
// ----------------------------------------------------------------------- //
void CGameServerShell::HandleAddGoal(HCLIENT hSender, ILTMessage_Read *pMsg)
{
HOBJECT hAI;
char szAIName[32];
pMsg->ReadString(szAIName, 32);
if ( LT_OK == FindNamedObject(szAIName, hAI) )
{
char szGoalType[64];
pMsg->ReadString(szGoalType, 64);
char szMsg[128];
sprintf(szMsg, "AddGoal %s", szGoalType);
char szNameValuePair[64];
uint32 cNameValuePairs = pMsg->Readuint32();
for(uint32 iNameValuePair=0; iNameValuePair < cNameValuePairs; ++iNameValuePair)
{
pMsg->ReadString(szNameValuePair, 64);
strcat(szMsg, " ");
strcat(szMsg, szNameValuePair);
}
CAI* pAI = (CAI*)g_pLTServer->HandleToObject(hAI);
SendTriggerMsgToObject(pAI, hAI, LTFALSE, szMsg);
}
else {
g_pLTServer->CPrint("Could not find AI named: %s", szAIName);
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::HandleRemoveGoal()
//
// PURPOSE: Handle a remove goal message by removing a goal from an AI.
//
// ----------------------------------------------------------------------- //
void CGameServerShell::HandleRemoveGoal(HCLIENT hSender, ILTMessage_Read *pMsg)
{
HOBJECT hAI;
char szAIName[32];
pMsg->ReadString(szAIName, 32);
if ( LT_OK == FindNamedObject(szAIName, hAI) )
{
char szGoalType[64];
pMsg->ReadString(szGoalType, 64);
char szMsg[128];
sprintf(szMsg, "RemoveGoal %s", szGoalType);
CAI* pAI = (CAI*)g_pLTServer->HandleToObject(hAI);
SendTriggerMsgToObject(pAI, hAI, LTFALSE, szMsg);
}
else {
g_pLTServer->CPrint("Could not find AI named: %s", szAIName);
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::HandleGadgetTarget
//
// PURPOSE: Send a stopped message to the target.
//
// ----------------------------------------------------------------------- //
void CGameServerShell::HandleGadgetTarget( HCLIENT hSender, ILTMessage_Read *pMsg )
{
HOBJECT hTarget = pMsg->ReadObject( );
LTFLOAT fTime = pMsg->Readfloat( );
if( hTarget )
{
char szMsg[32] = {0};
sprintf( szMsg, "Stopped %f", fTime );
GadgetTarget *pGadgetTarget = (GadgetTarget*)g_pLTServer->HandleToObject( hTarget );
if( pGadgetTarget )
{
CPlayerObj* pPlayerObj = GET_PLAYER(hSender);
SendTriggerMsgToObject( pPlayerObj, hTarget, LTFALSE, szMsg );
}
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::HandleSearch
//
// PURPOSE: Send an update message to the target.
//
// ----------------------------------------------------------------------- //
void CGameServerShell::HandleSearch( HCLIENT hSender, ILTMessage_Read *pMsg )
{
HOBJECT hTarget = pMsg->ReadObject( );
LTFLOAT fTime = pMsg->Readfloat( );
if( hTarget )
{
char szMsg[32] = {0};
sprintf( szMsg, "update %f", fTime );
CPlayerObj* pPlayer = GET_PLAYER(hSender);
if( pPlayer )
{
SendTriggerMsgToObject( pPlayer, hTarget, LTFALSE, szMsg );
}
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::HandleDecision()
//
// PURPOSE: Handle Decision object choices
//
// ----------------------------------------------------------------------- //
void CGameServerShell::HandleDecision(HCLIENT hSender, ILTMessage_Read *pMsg)
{
HOBJECT hObj = pMsg->ReadObject();
uint8 nChoice = pMsg->Readuint8();
DecisionObject *pDecisionObject = (DecisionObject*)g_pLTServer->HandleToObject( hObj );
if( pDecisionObject )
{
pDecisionObject->HandleChoose(nChoice);
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::HandleClearDamage
//
// PURPOSE: Clear the specified damage for the client
//
// ----------------------------------------------------------------------- //
void CGameServerShell::HandleClearProgressiveDamage( HCLIENT hSender, ILTMessage_Read *pMsg )
{
CPlayerObj* pPlayer = GET_PLAYER(hSender);
if( pPlayer )
{
CDestructible *pDamage = pPlayer->GetDestructible();
DamageFlags nDmgFlags = pMsg->Readuint64();
pDamage->ClearProgressiveDamage( nDmgFlags );
}
}
// ----------------------------------------------------------------------- //
//
// FUNCTION: CGameServerShell::HandleProjectileMessage
//
// PURPOSE: Handles messages from the client to projectiles
//
// ----------------------------------------------------------------------- //
void CGameServerShell::HandleProjectileMessage( HCLIENT hSender, ILTMessage_Read *pMsg )
{
LTRESULT ltResult;
CPlayerObj* pPlayer = GET_PLAYER( hSender );
if ( pPlayer )
{
ltResult = g_pLTServer->SendToObject(
pMsg,
LTNULL,
g_pLTServer->ObjectToHandle( pPlayer ),
MESSAGE_GUARANTEED
);
ASSERT( LT_OK == ltResult );
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::HandleDefault ()
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
void CGameServerShell::HandleDefault (HCLIENT hSender, ILTMessage_Read *pMsg)
{
// unhandled message?
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::Cheat ()
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
void CGameServerShell::CheatGod (CPlayerObj* pPlayer, uint32 nData)
{
if (!pPlayer) return; // yeah, this is redundant but hell, cheats aren't called every frame
pPlayer->ToggleGodMode ();
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::Cheat ()
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
void CGameServerShell::CheatAmmo (CPlayerObj* pPlayer, uint32 nData)
{
if (!pPlayer) return;
pPlayer->FullAmmoCheat ();
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::Cheat ()
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
void CGameServerShell::CheatArmor (CPlayerObj* pPlayer, uint32 nData)
{
if (!pPlayer) return;
pPlayer->RepairArmorCheat ();
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::Cheat ()
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
void CGameServerShell::CheatHealth (CPlayerObj* pPlayer, uint32 nData)
{
if (!pPlayer) return;
pPlayer->HealCheat ();
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::CheatClip()
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
void CGameServerShell::CheatClip (CPlayerObj* pPlayer, uint32 nData)
{
if (!pPlayer) return;
pPlayer->SetSpectatorMode(nData);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::CheatInvisible()
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
void CGameServerShell::CheatInvisible(CPlayerObj* pPlayer, uint32 nData)
{
if (!pPlayer) return;
pPlayer->SetInvisibleMode(nData);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::Cheat ()
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
void CGameServerShell::CheatTeleport (CPlayerObj* pPlayer, uint32 nData)
{
if (!pPlayer) return;
pPlayer->Respawn ();
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::Cheat ()
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
void CGameServerShell::CheatWeapons (CPlayerObj* pPlayer, uint32 nData)
{
if (!pPlayer) return;
pPlayer->FullWeaponCheat ();
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::Cheat ()
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
void CGameServerShell::CheatTears (CPlayerObj* pPlayer, uint32 nData)
{
if (!pPlayer) return;
if ((g_bInfiniteAmmo = !g_bInfiniteAmmo)) pPlayer->FullWeaponCheat();
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::Cheat ()
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
void CGameServerShell::CheatSkillz (CPlayerObj* pPlayer, uint32 nData)
{
if (!pPlayer) return;
pPlayer->SkillsCheat();
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::Cheat ()
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
void CGameServerShell::CheatRemoveAI (CPlayerObj* pPlayer, uint32 nData)
{
HandleCheatRemoveAI(nData);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::Cheat ()
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
void CGameServerShell::CheatSnowmobile (CPlayerObj* pPlayer, uint32 nData)
{
if (!g_pLTServer) return; // if this is true you are really screwed
g_pLTServer->RunGameConString("spawnobject PlayerVehicle (VehicleType Snowmobile)");
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::Cheat ()
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
void CGameServerShell::CheatModSquad (CPlayerObj* pPlayer, uint32 nData)
{
if (!pPlayer) return;
pPlayer->FullModsCheat();
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::Cheat ()
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
void CGameServerShell::CheatFullGear (CPlayerObj* pPlayer, uint32 nData)
{
if (!pPlayer) return;
pPlayer->FullGearCheat();
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::CheatExitLevel()
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
void CGameServerShell::CheatExitLevel(CPlayerObj* pPlayer, uint32 nData)
{
if (!pPlayer) return;
bool bIsHost = g_pLTServer->GetClientInfoFlags(pPlayer->GetClient()) & CIF_LOCAL;
if (!bIsHost) return;
g_pServerMissionMgr->ExitLevelSwitch( );
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::CheatNextMission()
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
void CGameServerShell::CheatNextMission(CPlayerObj* pPlayer, uint32 nData)
{
if (!pPlayer) return;
bool bIsHost = g_pLTServer->GetClientInfoFlags(pPlayer->GetClient()) & CIF_LOCAL;
if (!bIsHost) return;
g_pServerMissionMgr->NextMission( );
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::CheatBootPlayer()
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
void CGameServerShell::CheatBootPlayer(CPlayerObj* pPlayer, uint32 nData)
{
if (!pPlayer || !IsMultiplayerGame() ) return;
bool bIsHost = g_pLTServer->GetClientInfoFlags(pPlayer->GetClient()) & CIF_LOCAL;
if (!bIsHost) return;
//don't boot yourself
uint32 clientID = g_pLTServer->GetClientID(pPlayer->GetClient());
if (clientID == nData) return;
HCLIENT hClient = GetClientFromID(nData);
if (hClient) g_pLTServer->KickClient(hClient);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::CheatGimmeGun()
//
// PURPOSE:
//
// -----------------------------------------------------------------------
void CGameServerShell::CheatGimmeGun( CPlayerObj *pPlayer, uint32 nData )
{
if( !pPlayer )
return;
pPlayer->GimmeGunCheat( nData );
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::CheatGimmeMod()
//
// PURPOSE:
//
// -----------------------------------------------------------------------
void CGameServerShell::CheatGimmeMod( CPlayerObj *pPlayer, uint32 nData )
{
if( !pPlayer )
return;
pPlayer->GimmeModCheat( nData );
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::CheatGimmeGear()
//
// PURPOSE:
//
// -----------------------------------------------------------------------
void CGameServerShell::CheatGimmeGear( CPlayerObj *pPlayer, uint32 nData )
{
if( !pPlayer )
return;
pPlayer->GimmeGearCheat( nData );
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::CheatGimmeAmmo()
//
// PURPOSE:
//
// -----------------------------------------------------------------------
void CGameServerShell::CheatGimmeAmmo( CPlayerObj *pPlayer, uint32 nData )
{
if( !pPlayer )
return;
pPlayer->GimmeAmmoCheat( nData );
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::CheatBodyGolfing ()
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
void CGameServerShell::CheatBodyGolfing (CPlayerObj* pPlayer, uint32 nData)
{
if (!pPlayer) return;
extern CVarTrack g_vtBodyExplosionVelMultiplier;
extern float g_kfDefaultBodyExplosionVelocity;
// Toggle the value of g_vtBodyExplosionVelMultiplier
if (!g_vtBodyExplosionVelMultiplier.IsInitted())
{
g_vtBodyExplosionVelMultiplier.Init(g_pLTServer, "BodyExplosionMult", NULL, g_kfDefaultBodyExplosionVelocity);
}
if (g_vtBodyExplosionVelMultiplier.GetFloat() < 10.0f)
{
g_vtBodyExplosionVelMultiplier.SetFloat(10.0f);
}
else
{
// Set back to default...
g_vtBodyExplosionVelMultiplier.SetFloat(g_kfDefaultBodyExplosionVelocity);
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::Cheat ()
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
void CGameServerShell::CheatDefault (CPlayerObj* pPlayer, uint32 nData)
{
// some how i don't think we are in kansas any more toto
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::FindStartPoint()
//
// PURPOSE: Find a good start point.
//
// ----------------------------------------------------------------------- //
GameStartPoint* CGameServerShell::FindStartPoint(CPlayerObj* pPlayer)
{
// We need at least one start point...
if( GameStartPoint::GetStartPointList().size() == 0 )
{
return LTNULL;
}
// Build a list of unlocked start points...
GameStartPoint* pStartPt = LTNULL;
GameStartPoint::StartPointList lstValidStartPts;
bool bStartPointsOnly = pPlayer ? !pPlayer->UsedStartPoint() : true;
GameStartPoint::StartPointList::const_iterator iter = GameStartPoint::GetStartPointList().begin();
while( iter != GameStartPoint::GetStartPointList().end() )
{
pStartPt = *iter;
if( !pStartPt->IsLocked() )
{
if( (bStartPointsOnly && pStartPt->IsStartPoint()) || (!bStartPointsOnly && pStartPt->IsSpawnPoint()) )
{
lstValidStartPts.push_back( pStartPt );
}
}
++iter;
}
// Sort the list based on last time used...
std::sort(lstValidStartPts.begin(),lstValidStartPts.end(),GameStartPointLesser() );
pStartPt = LTNULL;
int nCount = lstValidStartPts.size();
// Get the index into the valid list based on game type...
if( nCount > 1 )
{
int nIndex = 0;
switch( GetGameType() )
{
case eGameTypeSingle:
{
nIndex = 0;
}
break;
case eGameTypeCooperative:
{
nIndex = nCount+1;
int nRetries = nCount;
LTBOOL bSafe = LTFALSE;
while (nRetries && !bSafe)
{
if (nIndex > nCount)
{
nIndex = GetRandom(0, nCount-1);
}
else
{
nIndex = (nIndex+1)%nCount;
}
pStartPt = lstValidStartPts[ nIndex ];
LTVector testPos;
g_pLTServer->GetObjectPos(pStartPt->m_hObject, &testPos);
bSafe = !IsPositionOccupied(testPos,pPlayer);
nRetries--;
}
}
break;
case eGameTypeDeathmatch:
{
nIndex = GetRandom(0,1);
bool bSafe = false;
while (nIndex < nCount && !bSafe)
{
pStartPt = lstValidStartPts[ nIndex ];
LTVector testPos;
g_pLTServer->GetObjectPos(pStartPt->m_hObject, &testPos);
bSafe = !IsPositionOccupied(testPos,pPlayer);
if (!bSafe)
{
g_pLTServer->CPrint("CGameServerShell::FindStartPoint(): option %d occupied",nIndex);
nIndex++;
}
}
if (!bSafe)
nIndex = 0;
}
break;
case eGameTypeTeamDeathmatch:
case eGameTypeDoomsDay:
{
// Try and get an available team start point...
nIndex = 0;
bool bSafe = false;
if( pPlayer )
{
while( nIndex < nCount && !bSafe )
{
pStartPt = lstValidStartPts[ nIndex ];
LTVector vPos;
g_pLTServer->GetObjectPos( pStartPt->m_hObject, &vPos );
bSafe = !IsPositionOccupied( vPos, pPlayer ) && (pStartPt->GetTeamID() == pPlayer->GetTeamID());
if( !bSafe )
{
++nIndex;
}
}
if( !bSafe )
{
// No available team start point so just get the first team start point...
nIndex = 0;
while( nIndex < nCount && !bSafe )
{
pStartPt = lstValidStartPts[ nIndex ];
bSafe = (pStartPt->GetTeamID() == pPlayer->GetTeamID());
if( !bSafe )
{
++nIndex;
}
}
}
}
if( !bSafe )
{
g_pLTServer->CPrint( "No Team start point for team (%i)!", pPlayer ? pPlayer->GetTeamID() : INVALID_TEAM );
nIndex = GetRandom(0,1);
bool bSafe = false;
while (nIndex < nCount && !bSafe)
{
pStartPt = lstValidStartPts[ nIndex ];
LTVector testPos;
g_pLTServer->GetObjectPos(pStartPt->m_hObject, &testPos);
bSafe = !IsPositionOccupied(testPos,pPlayer);
if (!bSafe)
{
g_pLTServer->CPrint("CGameServerShell::FindStartPoint(): option %d occupied",nIndex);
nIndex++;
}
}
if (!bSafe)
nIndex = 0;
}
}
break;
default : break;
}
pStartPt = lstValidStartPts[ nIndex ];
}
else
{
// We know there is at least one valid start point.
pStartPt = GameStartPoint::GetStartPointList()[ 0 ];
}
if (pStartPt)
{
pStartPt->SetLastUse(g_pLTServer->GetTime());
if( pPlayer )
pPlayer->SetUsedStartPoint( true );
}
return pStartPt;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::RespawnPlayer()
//
// PURPOSE: Respawn the player object
//
// ----------------------------------------------------------------------- //
void CGameServerShell::RespawnPlayer(CPlayerObj* pPlayer, HCLIENT hClient)
{
if (!pPlayer || !hClient) return;
// Player object meet client, client meet player object...
pPlayer->SetClient(hClient);
g_pLTServer->SetClientUserData(hClient, (void *)pPlayer);
// If this is a multiplayer game wait until MULTIPLAYER_INIT message
// to respawn the player...
if (!IsMultiplayerGame( ))
{
pPlayer->Respawn(m_nLastLGFlags);
// Tell the client to init us!
SendEmptyClientMsg(MID_PLAYER_SINGLEPLAYER_INIT, hClient, MESSAGE_GUARANTEED);
// Unlock the player since we're in single player mode
pPlayer->FinishHandshake();
}
else if (!pPlayer->HasDoneHandshake())
{
// Start a handshake with the client
CAutoMessage cMsg;
cMsg.Writeuint8(MID_HANDSHAKE);
cMsg.Writeuint8(MID_HANDSHAKE_HELLO);
cMsg.Writeuint16(GAME_HANDSHAKE_VER);
g_pLTServer->SendToClient(cMsg.Read(), hClient, MESSAGE_GUARANTEED);
}
else
{
// Tell the client to init us!
SendEmptyClientMsg(MID_PLAYER_MULTIPLAYER_INIT, hClient, MESSAGE_GUARANTEED);
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::HandleCheatRemoveAI()
//
// PURPOSE: Handle the remove ai cheat
//
// ----------------------------------------------------------------------- //
void CGameServerShell::HandleCheatRemoveAI(uint32 nData)
{
HOBJECT hObj = g_pLTServer->GetNextObject(LTNULL);
HCLASS hClass = g_pLTServer->GetClass("CAI");
// Remove all the ai objects...
LTBOOL bRemove = LTFALSE;
HOBJECT hRemoveObj = LTNULL;
while (hObj)
{
if (g_pLTServer->IsKindOf(g_pLTServer->GetObjectClass(hObj), hClass))
{
hRemoveObj = hObj;
}
hObj = g_pLTServer->GetNextObject(hObj);
if (hRemoveObj)
{
LPBASECLASS pClass = g_pLTServer->HandleToObject(hRemoveObj);
if (pClass)
{
DamageStruct damage;
damage.eType = DT_EXPLODE;
damage.fDamage = damage.kInfiniteDamage;
damage.hDamager = hRemoveObj;
damage.DoDamage(pClass, hRemoveObj);
}
hRemoveObj = LTNULL;
}
}
hObj = g_pLTServer->GetNextInactiveObject(LTNULL);
hRemoveObj = LTNULL;
while (hObj)
{
if (g_pLTServer->IsKindOf(g_pLTServer->GetObjectClass(hObj), hClass))
{
hRemoveObj = hObj;
}
hObj = g_pLTServer->GetNextInactiveObject(hObj);
if (hRemoveObj)
{
LPBASECLASS pClass = g_pLTServer->HandleToObject(hRemoveObj);
if (pClass)
{
DamageStruct damage;
damage.eType = DT_EXPLODE;
damage.fDamage = damage.kInfiniteDamage;
damage.hDamager = hRemoveObj;
damage.DoDamage(pClass, hRemoveObj);
}
hRemoveObj = LTNULL;
}
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::ReportError()
//
// PURPOSE: Tell the client about a server error
//
// ----------------------------------------------------------------------- //
void CGameServerShell::ReportError(HCLIENT hSender, uint8 nErrorType)
{
CAutoMessage cMsg;
cMsg.Writeuint8(MID_SERVER_ERROR);
cMsg.Writeuint8((uint8)nErrorType);
g_pLTServer->SendToClient(cMsg.Read(), hSender, MESSAGE_GUARANTEED);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::CacheFiles()
//
// PURPOSE: Cache files that are used often
//
// ----------------------------------------------------------------------- //
void CGameServerShell::CacheFiles()
{
if (m_bPreCacheAssets)
{
#ifndef _FINAL
g_pLTServer->CPrint("Caching files...");
#endif
CacheLevelSpecificFiles();
#ifndef _FINAL
g_pLTServer->CPrint("Done caching files...");
#endif
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::CacheLevelSpecificFiles()
//
// PURPOSE: Cache files specific to the current level...
//
// ----------------------------------------------------------------------- //
void CGameServerShell::CacheLevelSpecificFiles()
{
const char* pCurLevelName = GetCurLevel();
if (m_bCachedLevelFiles || !pCurLevelName || !(*pCurLevelName)) return;
char pTempCurLevel[MAX_PATH + 1];
LTStrCpy(pTempCurLevel, pCurLevelName, sizeof(pTempCurLevel));
// Chop off any suffix...
char *pDot = strchr(pTempCurLevel, '.');
if (pDot)
{
*pDot = '\0';
}
// The asset file should be in with the world files...
char fname[MAX_PATH + 1];
LTSNPrintF(fname, sizeof(fname), "%s.txt", pTempCurLevel);
// Have the asset mgr handle the loading of the assets...
CServerAssetMgr assetMgr;
if (!assetMgr.Init(fname))
{
#ifndef _FINAL
g_pLTServer->CPrint("CServerAssetMgr::Init() falied for file: %s", fname);
#endif
}
// Reset so we don't try and cache again until the next level is loaded...
m_bCachedLevelFiles = true;
}
void CGameServerShell::UpdateClientPingTimes()
{
float ping;
uint32 clientID;
HCLIENT hClient;
m_ClientPingSendCounter += g_pLTServer->GetFrameTime();
if(m_ClientPingSendCounter > CLIENT_PING_UPDATE_RATE)
{
CAutoMessage cMsg;
cMsg.Writeuint8(MID_PINGTIMES);
hClient = LTNULL;
while(hClient = g_pLTServer->GetNextClient(hClient))
{
clientID = g_pLTServer->GetClientID(hClient);
g_pLTServer->GetClientPing(hClient, ping);
cMsg.Writeuint16((uint16)clientID);
cMsg.Writeuint16((uint16)(ping + 0.5f));
}
cMsg.Writeuint16(0xFFFF);
g_pLTServer->SendToClient(cMsg.Read(), LTNULL, 0);
m_ClientPingSendCounter = 0.0f;
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::SetSwitchingWorldsState
//
// PURPOSE: Sets the switching worlds state and tells it to the clients.
//
// ----------------------------------------------------------------------- //
void CGameServerShell::SetSwitchingWorldsState( SwitchingWorldsState eSwitchingWorldsState )
{
if( m_eSwitchingWorldsState == eSwitchingWorldsState )
return;
m_eSwitchingWorldsState = eSwitchingWorldsState;
CAutoMessage cMsg;
cMsg.Writeuint8( MID_SWITCHINGWORLDSSTATE );
cMsg.Writeuint8( eSwitchingWorldsState );
g_pLTServer->SendToClient( cMsg.Read(), NULL, MESSAGE_GUARANTEED);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::StartSwitchingWorlds
//
// PURPOSE: Finish our switch world process.
//
// ----------------------------------------------------------------------- //
void CGameServerShell::StartSwitchingWorlds( )
{
// Pause the game until all the clients are in. There is an unpause
// in FinishSwitchingWorlds.
PauseGame( true );
SetSwitchingWorldsState( eSwitchingWorldsStatePlayerHookup );
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::FinishSwitchingWorlds
//
// PURPOSE: Finish our switch world process.
//
// ----------------------------------------------------------------------- //
void CGameServerShell::FinishSwitchingWorlds( )
{
// Remove our pause we put on in StartSwitchingWorlds.
PauseGame( false );
// Done switching worlds.
SetSwitchingWorldsState( eSwitchingWorldsStateFinished );
g_pServerMissionMgr->LevelStarted();
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::UpdateSwitchingWorlds
//
// PURPOSE: Update our switch world state machine.
//
// ----------------------------------------------------------------------- //
void CGameServerShell::UpdateSwitchingWorlds( )
{
switch( m_eSwitchingWorldsState )
{
case eSwitchingWorldsStateNone:
{
return;
}
break;
// Waiting for clients from the previous level to
// get hooked up to players in this level.
case eSwitchingWorldsStatePlayerHookup:
{
// Loop through the clients that don't have players bound to them. If they
// match any of the clientrefs, we have to wait until they get their
// OnClientEnterWorld called. If none of the clients match a clientref, then
// we're done with the switchworld.
HCLIENT hNextClient = g_pLTServer->GetNextClient( LTNULL );
bool bWaitLonger = false;
while( hNextClient )
{
// Copy the current client and advance to the next. Makes body of loop easier.
HCLIENT hClient = hNextClient;
hNextClient = g_pLTServer->GetNextClient( hClient );
// Check the client's connection.
if( ClientConnectionInTrouble( hClient ))
{
// Kick the client if they are too slow to play.
g_pLTServer->KickClient( hClient );
continue;
}
// Check if this client has already been hooked up to a player. If so, skip it.
CPlayerObj* pUsedPlayer = ( CPlayerObj* )g_pLTServer->GetClientUserData( hClient );
if( pUsedPlayer )
{
// If the player hasn't respawned we need to wait until they do...
if( pUsedPlayer->RespawnCalled() )
{
continue;
}
bWaitLonger = true;
break;
}
// If there are no clientrefs, then we didn't come from a previous
// level with players. This guy is just joining and
// we need to wait longer for him to finish handshaking.
HCLIENTREF hNextClientRef = g_pLTServer->GetNextClientRef(LTNULL);
if (!hNextClientRef)
{
bWaitLonger = true;
break;
}
// See if this client will match any clientrefs. If so, then we have to wait
// for the OnClientEnterWorld before we can finish the switch world.
pUsedPlayer = PickClientRefPlayer( hClient );
if( pUsedPlayer )
{
bWaitLonger = true;
break;
}
}
// See if we found didn't find a player.
if( bWaitLonger )
return;
// Do an autosave if we aren't loading from a save game.
if( m_nLastLGFlags != LOAD_RESTORE_GAME )
{
// No more unclaimed clientrefs. Now do the autosave.
if( !g_pServerSaveLoadMgr->CanSaveGame( ) )
{
// Can't save, so skip the autosave state.
SetSwitchingWorldsState( eSwitchingWorldsStateWaitForClient );
return;
}
// Do an autosave.
g_pServerSaveLoadMgr->AutoSave( g_pServerMissionMgr->GetCurrentMission( ),
g_pServerMissionMgr->GetCurrentLevel( ));
SetSwitchingWorldsState( eSwitchingWorldsStateAutoSave );
}
else
{
// Wait for player loaded.
SetSwitchingWorldsState( eSwitchingWorldsStateWaitForClient );
}
return;
}
break;
// Wait for the autosave to finish.
case eSwitchingWorldsStateAutoSave:
{
// See if we're done with the autosave.
if( g_pServerSaveLoadMgr->GetSaveDataState( ) == eSaveDataStateNone )
{
// Wait for player loaded.
SetSwitchingWorldsState( eSwitchingWorldsStateWaitForClient );
return;
}
}
break;
// Wait for at least one player to be loaded.
case eSwitchingWorldsStateWaitForClient:
{
// Iterate over all the players and see if any of them have finished loading.
CPlayerObj::PlayerObjList::const_iterator iter = CPlayerObj::GetPlayerObjList( ).begin( );
while( iter != CPlayerObj::GetPlayerObjList( ).end( ))
{
CPlayerObj* pPlayerObj = *iter;
if( pPlayerObj->IsClientLoaded( ))
{
FinishSwitchingWorlds( );
return;
}
iter++;
}
}
break;
case eSwitchingWorldsStateFinished:
{
return;
}
break;
default:
{
ASSERT( !"CGameServerShell::UpdateSwitchingWorlds: Invalid switching worlds state." );
return;
}
break;
}
return;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::Update
//
// PURPOSE: Update servier stuff periodically
//
// ----------------------------------------------------------------------- //
void CGameServerShell::Update(LTFLOAT timeElapsed)
{
// Check for first update...
if (m_bFirstUpdate)
{
m_bFirstUpdate = LTFALSE;
FirstUpdate();
}
// Update the switching worlds state machine.
UpdateSwitchingWorlds();
// Update the lite objects
if ((g_pLTServer->GetServerFlags() & SS_PAUSED) == 0)
GetLiteObjectMgr()->Update();
g_pMusicMgr->Update();
// Update the command mgr...
m_CmdMgr.Update();
// Update the AI's senses.
g_pAIStimulusMgr->Update();
// See if we should show our bounding box...
if (g_CanShowDimsTrack.GetFloat())
{
if (g_ShowDimsTrack.GetFloat())
{
UpdateBoundingBoxes();
}
else
{
RemoveBoundingBoxes();
}
}
// Should the stair height change...
if( g_StairStepHeight.GetFloat() != DEFAULT_STAIRSTEP_HEIGHT )
{
g_pPhysicsLT->SetStairHeight( g_StairStepHeight.GetFloat() );
}
#ifndef _FINAL
if( g_pAIVolumeMgr )
{
g_pAIVolumeMgr->UpdateDebugRendering( g_ShowVolumesTrack.GetFloat() );
}
if( g_pAIInformationVolumeMgr )
{
g_pAIInformationVolumeMgr->UpdateDebugRendering( g_ShowInfoVolumesTrack.GetFloat() );
}
if( g_pAINodeMgr )
{
g_pAINodeMgr->UpdateDebugRendering( g_ShowNodesTrack.GetFloat() );
}
#endif
if( g_ClearLinesTrack.GetFloat() > 0.0f )
{
LineSystem::RemoveAll();
g_ClearLinesTrack.SetFloat(0.0f);
}
// Did the server want to say something?
const char *pSay = m_SayTrack.GetStr("");
if(pSay && pSay[0] != 0)
{
char fullMsg[512];
sprintf(fullMsg, "HOST: %s", pSay);
CAutoMessage cMsg;
cMsg.Writeuint8(MID_PLAYER_MESSAGE);
cMsg.WriteString(fullMsg);
cMsg.Writeuint32(-1);
cMsg.Writeuint8(INVALID_TEAM);
g_pLTServer->SendToClient(cMsg.Read(), LTNULL, MESSAGE_GUARANTEED);
m_SayTrack.SetStr("");
}
g_pServerMissionMgr->Update( );
g_pServerSaveLoadMgr->Update( );
if( IsMultiplayerGame( ))
{
// Update multiplayer stuff...
UpdateMultiplayer();
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::FirstUpdate
//
// PURPOSE: Do the first update
//
// ----------------------------------------------------------------------- //
void CGameServerShell::FirstUpdate()
{
m_SayTrack.Init(g_pLTServer, "Say", "", 0.0f);
m_ShowTimeTrack.Init(g_pLTServer, "ShowTime", LTNULL, 0.0f);
m_WorldTimeTrack.Init(g_pLTServer, "WorldTime", "-1", 0.0f);
m_WorldTimeSpeedTrack.Init(g_pLTServer, "WorldTimeSpeed", "-1", 0.0f);
// Init some console vars...
extern CVarTrack g_vtAIDamageAdjustEasy;
extern CVarTrack g_vtAIDamageAdjustNormal;
extern CVarTrack g_vtAIDamageAdjustHard;
extern CVarTrack g_vtAIDamageAdjustVeryHard;
extern CVarTrack g_vtAIDamageIncreasePerPlayer;
extern CVarTrack g_vtPlayerDamageDecreasePerPlayer;
float fVal = 0.0f;
if( !g_vtAIDamageAdjustEasy.IsInitted() )
{
fVal = g_pServerButeMgr->GetPlayerAttributeFloat(PLAYER_BUTE_AIDAMAGEADJUSTEASY);
g_vtAIDamageAdjustEasy.Init( g_pLTServer, "AIDamageAdjustEasy", LTNULL, fVal );
}
if( !g_vtAIDamageAdjustNormal.IsInitted() )
{
fVal = g_pServerButeMgr->GetPlayerAttributeFloat(PLAYER_BUTE_AIDAMAGEADJUSTNORM);
g_vtAIDamageAdjustNormal.Init( g_pLTServer, "AIDamageAdjustNormal", LTNULL, fVal );
}
if( !g_vtAIDamageAdjustHard.IsInitted() )
{
fVal = g_pServerButeMgr->GetPlayerAttributeFloat(PLAYER_BUTE_AIDAMAGEADJUSTHARD);
g_vtAIDamageAdjustHard.Init( g_pLTServer, "AIDamageAdjustHard", LTNULL, fVal );
}
if( !g_vtAIDamageAdjustVeryHard.IsInitted() )
{
fVal = g_pServerButeMgr->GetPlayerAttributeFloat(PLAYER_BUTE_AIDAMAGEADJUSTVERYHARD);
g_vtAIDamageAdjustVeryHard.Init( g_pLTServer, "AIDamageAdjustVeryHard", LTNULL, fVal );
}
if( !g_vtAIDamageIncreasePerPlayer.IsInitted() )
{
fVal = g_pServerButeMgr->GetPlayerAttributeFloat(PLAYER_BUTE_AIDAMAGEADJUSTPERPLAYER);
g_vtAIDamageIncreasePerPlayer.Init( g_pLTServer, "AIDamageIncreasePerPlayer", LTNULL, fVal );
}
if( !g_vtPlayerDamageDecreasePerPlayer.IsInitted() )
{
fVal = g_pServerButeMgr->GetPlayerAttributeFloat(PLAYER_BUTE_PLAYERDAMAGEDECREASE);
g_vtPlayerDamageDecreasePerPlayer.Init( g_pLTServer, "PlayerDamageDecreasePerPlayer", LTNULL, fVal );
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::UpdateGameServer
//
// PURPOSE: Updates a stand-alone server with game info if necessary
//
// ----------------------------------------------------------------------- //
LTBOOL CGameServerShell::UpdateGameServer()
{
// Check if we need to update...
if (!m_bUpdateGameServ)
{
return(LTFALSE);
}
m_bUpdateGameServ = LTFALSE;
// Make sure we are actually being hosted via GameServ...
if( !m_ServerGameOptions.m_bDedicated )
{
return(LTFALSE);
}
ServerAppShellUpdate( );
// All done...
return(LTTRUE);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::AddClientToList
//
// PURPOSE: Adds the given client handle to our local list
//
// ----------------------------------------------------------------------- //
LTBOOL CGameServerShell::AddClientToList(HCLIENT hClient)
{
// Sanity checks...
if (!hClient) return(LTFALSE);
// Make sure this client isn't already in our list...
if (IsClientInList(hClient))
{
return(LTTRUE);
}
// Add this client handle to our array...
for (int i = 0; i < MAX_CLIENTS; i++)
{
if (m_aClients[i] == LTNULL)
{
m_aClients[i] = hClient;
return(LTTRUE);
}
}
// If we get here, there wasn't any space left in the array...
return(LTFALSE);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::RemoveClientFromList
//
// PURPOSE: Adds the given client handle to our local list
//
// ----------------------------------------------------------------------- //
LTBOOL CGameServerShell::RemoveClientFromList(HCLIENT hClient)
{
// Sanity checks...
if (!hClient) return(LTFALSE);
// Remove this client handle from our array...
for (int i = 0; i < MAX_CLIENTS; i++)
{
if (m_aClients[i] == hClient)
{
m_aClients[i] = LTNULL;
return(LTTRUE);
}
}
// If we get here, we didn't find the given client handle in the array...
return(LTFALSE);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::IsClientInList
//
// PURPOSE: Determines if the given client handle is in our list
//
// ----------------------------------------------------------------------- //
LTBOOL CGameServerShell::IsClientInList(HCLIENT hClient)
{
// Sanity checks...
if (!hClient) return(LTFALSE);
// Look for this client handle in our array...
for (int i = 0; i < MAX_CLIENTS; i++)
{
if (m_aClients[i] == hClient)
{
return(LTTRUE);
}
}
// If we get here, we didn't find the given client handle in the array...
return(LTFALSE);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::GetPlayerFromClientList
//
// PURPOSE: Adds the given client handle to our local list
//
// ----------------------------------------------------------------------- //
CPlayerObj* CGameServerShell::GetPlayerFromClientList(HCLIENT hClient)
{
// Sanity checks...
if (!hClient) return(LTNULL);
// Remove this client handle from our array...
for (int i = 0; i < MAX_CLIENTS; i++)
{
if (m_aClients[i] == hClient)
{
CPlayerObj* pPlayer = (CPlayerObj*)g_pLTServer->GetClientUserData(hClient);
return(pPlayer);
}
}
// If we get here, we didn't find the given client handle in the array...
return(LTNULL);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::GetClientFromID
//
// PURPOSE: Get the handle to a client based on an id
//
// ----------------------------------------------------------------------- //
HCLIENT CGameServerShell::GetClientFromID(uint32 nID)
{
for (int i = 0; i < MAX_CLIENTS; i++)
{
uint32 clientID = g_pLTServer->GetClientID(m_aClients[i]);
if (clientID == nID)
{
return (m_aClients[i]);
}
}
// If we get here, we didn't find the given client handle in the array...
return(LTNULL);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::InitGameType
//
// PURPOSE: Setup game type.
//
// ----------------------------------------------------------------------- //
bool CGameServerShell::InitGameType()
{
ServerGameOptions** ppServerGameOptions;
uint32 dwLen = sizeof( ServerGameOptions* );
g_pLTServer->GetGameInfo((void**)&ppServerGameOptions, &dwLen);
if( ppServerGameOptions && *ppServerGameOptions )
{
m_ServerGameOptions = **ppServerGameOptions;
}
// Toss any old missionmgr.
if( m_pServerMissionMgr )
{
debug_delete( m_pServerMissionMgr );
m_pServerMissionMgr = NULL;
}
// Reseed random number generator if necessary...
if (m_ServerGameOptions.m_bPerformanceTest)
{
srand(123); // Same as client, doesn't really matter...
}
switch( m_ServerGameOptions.m_eGameType )
{
case eGameTypeSingle:
m_pServerMissionMgr = debug_new( CSinglePlayerMissionMgr );
break;
case eGameTypeCooperative:
m_pServerMissionMgr = debug_new( CCoopMissionMgr );
break;
case eGameTypeDeathmatch:
m_pServerMissionMgr = debug_new( CDeathMatchMissionMgr );
break;
case eGameTypeTeamDeathmatch:
m_pServerMissionMgr = debug_new( CTeamDeathMatchMissionMgr );
break;
case eGameTypeDoomsDay:
m_pServerMissionMgr = debug_new( CDoomsDayMissionMgr );
break;
default:
ASSERT( !"CGameServerShell::InitGameType: Invalid game type." );
break;
}
if( !m_pServerMissionMgr )
return false;
if( !m_pServerMissionMgr->Init( ))
return false;
return true;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::UpdateBoundingBoxes()
//
// PURPOSE: Update object bounding boxes
//
// ----------------------------------------------------------------------- //
void CGameServerShell::UpdateBoundingBoxes()
{
HOBJECT hObj = g_pLTServer->GetNextObject(LTNULL);
HCLASS hClass = g_pLTServer->GetClass("GameBase");
// Active objects...
while (hObj)
{
if (g_pLTServer->IsKindOf(g_pLTServer->GetObjectClass(hObj), hClass))
{
GameBase* pObj = (GameBase*)g_pLTServer->HandleToObject(hObj);
if (pObj)
{
pObj->UpdateBoundingBox();
}
}
hObj = g_pLTServer->GetNextObject(hObj);
}
// Inactive objects...
hObj = g_pLTServer->GetNextInactiveObject(LTNULL);
while (hObj)
{
if (g_pLTServer->IsKindOf(g_pLTServer->GetObjectClass(hObj), hClass))
{
GameBase* pObj = (GameBase*)g_pLTServer->HandleToObject(hObj);
if (pObj)
{
pObj->UpdateBoundingBox();
}
}
hObj = g_pLTServer->GetNextInactiveObject(hObj);
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::RemoveBoundingBoxes()
//
// PURPOSE: Remove object bounding boxes
//
// ----------------------------------------------------------------------- //
void CGameServerShell::RemoveBoundingBoxes()
{
HOBJECT hObj = g_pLTServer->GetNextObject(LTNULL);
HCLASS hClass = g_pLTServer->GetClass("GameBase");
// Active objects...
while (hObj)
{
if (g_pLTServer->IsKindOf(g_pLTServer->GetObjectClass(hObj), hClass))
{
GameBase* pObj = (GameBase*)g_pLTServer->HandleToObject(hObj);
if (pObj)
{
pObj->RemoveBoundingBox();
}
}
hObj = g_pLTServer->GetNextObject(hObj);
}
// Inactive objects...
hObj = g_pLTServer->GetNextInactiveObject(LTNULL);
while (hObj)
{
if (g_pLTServer->IsKindOf(g_pLTServer->GetObjectClass(hObj), hClass))
{
GameBase* pObj = (GameBase*)g_pLTServer->HandleToObject(hObj);
if (pObj)
{
pObj->RemoveBoundingBox();
}
}
hObj = g_pLTServer->GetNextInactiveObject(hObj);
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::UpdateMultiplayer
//
// PURPOSE: Determine if it is time to change levels
//
// ----------------------------------------------------------------------- //
void CGameServerShell::UpdateMultiplayer()
{
if (!IsMultiplayerGame( )) return;
// Update client ping times
UpdateClientPingTimes();
// Update game server info...
UpdateGameServer();
if (m_bShowMultiplayerSummary)
{
LTBOOL bReady = LTTRUE;
if (m_fSummaryEndTime > g_pLTServer->GetTime())
{
for (int i = 0; i < MAX_CLIENTS && bReady; i++)
{
CPlayerObj* pPlayer = GetPlayerFromClientList(m_aClients[i]);
if (pPlayer)
{
if (!pPlayer->IsReadyToExit())
{
bReady = LTFALSE;
break;
}
}
}
}
if (bReady)
{
m_bStartNextMultiplayerLevel = LTTRUE;
}
return;
}
// Check if any client has not talked to us in a very long time. If so, it may
// mean there is a bug in the networking code that refuses to kick clients not responding.
// Because this bug is rare, it's difficult to track in the networking. This is just a bit
// of fullproofing. The autoboottime is in seconds, so we need to convert it to ms.
uint32 nCurrentTime = GetTickCount( );
uint32 nAutoBootTime = ( uint32 )( GetConsoleFloat( "AutoBootTime", 5.0f * 60.0f ) * 1000.0f + 0.5f );
ClientDataList::const_iterator iter = m_ClientDataList.begin( );
for( ; iter != m_ClientDataList.end( ); iter++ )
{
ClientData* pClientData = *iter;
// Skip the host.
if( g_pLTServer->GetClientInfoFlags( pClientData->m_hClient ) & CIF_LOCAL )
continue;
// Get the time since the ping. Account for wrapping.
uint32 nDeltaTime = ( nCurrentTime > pClientData->m_nLastClientUpdateTime ) ?
( nCurrentTime - pClientData->m_nLastClientUpdateTime ) :
( nCurrentTime + ~( pClientData->m_nLastClientUpdateTime - 1 ));
// Check if they haven't talked in a while.
if( nDeltaTime >= nAutoBootTime )
{
g_pLTServer->CPrint( "Booting innactive client." );
g_pLTServer->KickClient( pClientData->m_hClient );
}
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::StartNextMultiplayerLevel
//
// PURPOSE: Start the next multiplayer level
//
// ----------------------------------------------------------------------- //
bool CGameServerShell::StartNextMultiplayerLevel()
{
m_bShowMultiplayerSummary = LTFALSE;
return g_pServerMissionMgr->NextMission( );
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::ServerAppMessageFn
//
// PURPOSE: Server app message function
//
// ----------------------------------------------------------------------- //
LTRESULT CGameServerShell::ServerAppMessageFn( ILTMessage_Read& msg )
{
// Let the scmd check if it needs this message.
if( ScmdServer::Instance( ).OnMessage( NULL, msg ))
{
return LT_OK;
}
msg.SeekTo(0);
switch( msg.Readuint8( ))
{
case SERVERSHELL_INIT:
{
if( !OnServerShellInit( ))
return LT_ERROR;
}
break;
case SERVERSHELL_NEXTWORLD:
{
if( !StartNextMultiplayerLevel( ))
return LT_ERROR;
}
break;
case SERVERSHELL_SETWORLD:
{
// Read in the world index. Go back one, since StartNextMultiplayerLevel
// will preincrement the curlevel.
int nNewMission;
nNewMission = msg.Readuint32( );
if( !g_pServerMissionMgr->SwitchToCampaignIndex( nNewMission ))
return LT_ERROR;
}
break;
case SERVERSHELL_MESSAGE:
{
char szMsg[256] = {0};
msg.ReadString( szMsg, ARRAY_LEN( szMsg ));
g_pLTServer->RunGameConString( szMsg );
}
break;
case SERVERSHELL_MISSIONFAILED:
{
// We have a failed mission from the server app...
// Wait for client responses to begin the auto load.
g_pServerSaveLoadMgr->WaitForAutoLoadResponses();
}
break;
// Invalid message.
default:
{
ASSERT( FALSE );
return LT_ERROR;
}
break;
}
return LT_OK;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::OnServerShellInit
//
// PURPOSE: Initializes the server servershell from serverapp.
//
// ----------------------------------------------------------------------- //
bool CGameServerShell::OnServerShellInit( )
{
// Initialize the server game. Need to do this first to init servermissionmgr.
CAutoMessage cMsg;
cMsg.Writeuint8( MID_START_GAME );
CLTMsgRef_Read msgRead = cMsg.Read( );
if( !g_pServerMissionMgr->OnMessage( NULL, *msgRead ))
return false;
// First we'll tell the serverapp about the missions in the campaign.
CAutoMessage cLevelsMsg;
cLevelsMsg.Writeuint8( SERVERAPP_INIT );
char const* pszFirstMission = NULL;
Campaign& campaign = g_pServerMissionMgr->GetCampaign( );
cLevelsMsg.Writeuint8( campaign.size( ));
char fname[_MAX_FNAME] = "";
for( Campaign::iterator iter = campaign.begin( ); iter != campaign.end( ); iter++ )
{
// Get the mission in the campaign.
int nMission = *iter;
MISSION* pMission = g_pMissionButeMgr->GetMission( nMission );
if( !pMission )
continue;
// Use the first level of the mission as the name of the mission.
LEVEL& level = pMission->aLevels[0];
if( !pszFirstMission )
{
pszFirstMission = level.szLevel;
}
_splitpath( level.szLevel, NULL, NULL, fname, NULL );
cLevelsMsg.WriteString( fname );
}
// Send the message to the server app.
CLTMsgRef_Read msgRefReadLevels = cLevelsMsg.Read( );
g_pLTServer->SendToServerApp( *msgRefReadLevels );
// Start the first level.
CAutoMessage cMsgStartLevel;
cMsgStartLevel.Writeuint8( MID_START_LEVEL );
cMsgStartLevel.WriteString( pszFirstMission );
CLTMsgRef_Read msgReadStartLevel = cMsgStartLevel.Read( );
if( !g_pServerMissionMgr->OnMessage( NULL, *msgReadStartLevel ))
return false;
return true;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::PauseGame
//
// PURPOSE: Pause/unpause the game. bForce overrides the counted pauses.
//
// ----------------------------------------------------------------------- //
void CGameServerShell::PauseGame( bool bPause, bool bForce )
{
// Reset the pause count if forced.
if( bForce )
{
m_nPauseCount = 0;
}
PauseGame( bPause );
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::PauseGame
//
// PURPOSE: Pause/unpause the game using reference counts.
//
// ----------------------------------------------------------------------- //
void CGameServerShell::PauseGame( bool bPause )
{
if( bPause )
m_nPauseCount++;
else
m_nPauseCount--;
// Make sure we don't go negative.
m_nPauseCount = Max( 0, m_nPauseCount );
//determine what state we are in
bool bInPauseState = (m_nPauseCount > 0);
//if we are not paused, forget whether the client had paused us
if (!bInPauseState)
m_bClientPaused = false;
//alright, we have changed pause state, so let us notify the server and its objects
uint32 nFlags = g_pLTServer->GetServerFlags();
if( bInPauseState )
nFlags |= SS_PAUSED;
else
nFlags &= ~SS_PAUSED;
g_pLTServer->SetServerFlags (nFlags);
//handle setting of the paused flag
HOBJECT hObj = g_pLTServer->GetNextObject(LTNULL);
while (hObj)
{
g_pLTServer->Common()->SetObjectFlags(hObj, OFT_Flags, bInPauseState ? FLAG_PAUSED : 0, FLAG_PAUSED);
hObj = g_pLTServer->GetNextObject(hObj);
}
hObj = g_pLTServer->GetNextInactiveObject(LTNULL);
while (hObj)
{
g_pLTServer->Common()->SetObjectFlags(hObj, OFT_Flags, bInPauseState ? FLAG_PAUSED : 0, FLAG_PAUSED);
hObj = g_pLTServer->GetNextInactiveObject(hObj);
}
CAutoMessage cMsg;
cMsg.Writeuint8( MID_GAME_PAUSE );
cMsg.Writebool( bInPauseState );
g_pLTServer->SendToClient( cMsg.Read(), NULL, MESSAGE_GUARANTEED );
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::IsPaused( )
//
// PURPOSE: Check if server is paused.
//
// ----------------------------------------------------------------------- //
bool CGameServerShell::IsPaused( )
{
uint32 nFlags = g_pLTServer->GetServerFlags();
bool bInPauseState = (( nFlags & SS_PAUSED ) != 0 );
return bInPauseState;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::ClientPauseGame( )
//
// PURPOSE: Modifies the client's pause on the game.
//
// ----------------------------------------------------------------------- //
void CGameServerShell::ClientPauseGame( bool bPause )
{
if( bPause )
{
if( m_bClientPaused )
return;
m_bClientPaused = true;
PauseGame( true );
}
else
{
if( m_bClientPaused )
{
m_bClientPaused = false;
PauseGame( false );
}
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::HandleConsoleCmdMsg()
//
// PURPOSE: Handle console cmd messages
//
// ----------------------------------------------------------------------- //
void CGameServerShell::HandleConsoleCmdMsg(HCLIENT hSender, ILTMessage_Read *pMsg)
{
HSTRING hCommand = pMsg->ReadHString();
if (!hCommand) return;
if (m_CmdMgr.Process(g_pLTServer->GetStringData(hCommand), (ILTBaseClass*)NULL, (ILTBaseClass*)NULL))
{
g_pLTServer->CPrint("Sent Command '%s'", g_pLTServer->GetStringData(hCommand));
}
if (hCommand)
{
g_pLTServer->FreeString(hCommand);
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::HandlePlayerSkills()
//
// PURPOSE: Handle the player skills request
//
// ----------------------------------------------------------------------- //
void CGameServerShell::HandlePlayerSkills(HCLIENT hSender, ILTMessage_Read *pMsg)
{
if (!hSender) return;
CPlayerObj* pPlayer = (CPlayerObj*)g_pLTServer->GetClientUserData(hSender);
if (!pPlayer) return;
pPlayer->HandleSkillUpdate(pMsg);
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::HandleSaveData
//
// PURPOSE: Handle savegame command from client.
//
// --------------------------------------------------------------------------- //
void CGameServerShell::HandleSaveGame( HCLIENT hSender, ILTMessage_Read* pMsg )
{
if( !pMsg )
return;
// Ignore save requests from non-local clients.
if( !( g_pLTServer->GetClientInfoFlags( hSender ) & CIF_LOCAL ))
return;
int nSlot = pMsg->Readuint8( );
// Check if this is a quicksave.
if( nSlot == 0 )
{
g_pServerSaveLoadMgr->QuickSave( g_pServerMissionMgr->GetCurrentMission( ),
g_pServerMissionMgr->GetCurrentLevel( ));
}
else
{
// Get the savegame name.
char szSaveName[MAX_PATH];
pMsg->ReadString( szSaveName, ARRAY_LEN( szSaveName ));
g_pServerSaveLoadMgr->SaveGameSlot( nSlot, szSaveName );
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::HandleObjectMessage
//
// PURPOSE: Handles generic message from the client to a specific object
//
// ----------------------------------------------------------------------- //
void CGameServerShell::HandleObjectMessage(HCLIENT hSender, ILTMessage_Read* pMsg)
{
// Sanity check
if(!pMsg)
return;
// Grab the object and make sure it exists
HOBJECT hObj = pMsg->ReadObject();
if(!hObj)
return;
// Cast it
GameBase *pObj = (GameBase *)g_pLTServer->HandleToObject(hObj);
if(!pObj)
return;
// Check for the player object
CPlayerObj* pPlayer = GET_PLAYER(hSender);
if(!pPlayer)
{
return;
}
// Call the object's objectmessagefn and forward the message
pObj->ObjectMessageFn(pPlayer->m_hObject, CLTMsgRef_Read(pMsg->SubMsg( pMsg->Tell( ))));
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::HandlePerformanceMessage ()
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
void CGameServerShell::HandlePerformanceMessage (HCLIENT hSender, ILTMessage_Read *pMsg)
{
//Ignore for multiplayer if not host?
uint8 nEnvironmentalDetail = pMsg->Readuint8();
m_bPreCacheAssets = pMsg->Readbool();
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::Save
//
// PURPOSE: Save the global world info
//
// ----------------------------------------------------------------------- //
void CGameServerShell::Save(ILTMessage_Write *pMsg, uint32 dwSaveFlags)
{
_ASSERT(pMsg);
if (!pMsg) return;
SAVE_DWORD(g_pVersionMgr->GetSaveVersion());
// Important: This has to be first, since it's taking the place of engine object behavior
m_pLiteObjectMgr->Save(pMsg);
m_pCharacterMgr->Save(pMsg);
m_CmdMgr.Save(pMsg);
m_pAIStimulusMgr->Save(pMsg);
m_pAICentralKnowledgeMgr->Save(pMsg);
m_pObjectTemplates->Save( pMsg );
//save difficulty
pMsg->Writeuint8(m_eDifficulty);
//save min music mood.
SAVE_DWORD(m_eMinMusicMood);
g_pServerMissionMgr->Save( *pMsg, dwSaveFlags );
g_pKeyMgr->Save( pMsg, dwSaveFlags );
{ // BL 09/28/00 need to save/load these because they don't
// get set by worldproperties in a load situation
SAVE_DWORD(m_nTimeRamps);
SAVE_DWORD(m_iPrevRamp);
for ( uint32 iTimeRamp = 0 ; iTimeRamp < MAX_TIME_RAMPS ; iTimeRamp++ )
{
SAVE_FLOAT(m_TimeRamps[iTimeRamp].m_Time);
SAVE_VECTOR(m_TimeRamps[iTimeRamp].m_Color);
SAVE_HSTRING(m_TimeRamps[iTimeRamp].m_hTarget);
SAVE_HSTRING(m_TimeRamps[iTimeRamp].m_hMessage);
}
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::Load
//
// PURPOSE: Load the global world info
//
// ----------------------------------------------------------------------- //
void CGameServerShell::Load(ILTMessage_Read *pMsg, uint32 dwLoadFlags)
{
_ASSERT(pMsg);
if (!pMsg) return;
// This old version didn't save the version number at the top. We need
// to use an engine value to determine the version.
uint32 nSaveFileVersion = 0;
g_pLTServer->GetSaveFileVersion( nSaveFileVersion );
if( nSaveFileVersion > 2001 )
{
uint32 nSaveVersion;
LOAD_DWORD(nSaveVersion);
g_pVersionMgr->SetCurrentSaveVersion( nSaveVersion );
}
// Important: This has to be first, since it's taking the place of engine object behavior
m_pLiteObjectMgr->Load(pMsg);
m_pCharacterMgr->Load(pMsg);
m_CmdMgr.Load(pMsg);
m_pAIStimulusMgr->Load(pMsg);
m_pAICentralKnowledgeMgr->Load(pMsg);
m_pObjectTemplates->Load( pMsg );
//load difficulty
m_eDifficulty = (GameDifficulty)pMsg->Readuint8();
g_pLTServer->CPrint("Difficulty:%d",(int)m_eDifficulty);
//load min music mood.
LOAD_DWORD_CAST(m_eMinMusicMood, CMusicMgr::Mood);
g_pServerMissionMgr->Load( *pMsg, dwLoadFlags );
g_pKeyMgr->Load( pMsg, dwLoadFlags );
{ // BL 09/28/00 need to save/load these because they don't
// get set by worldproperties in a load situation
LOAD_DWORD(m_nTimeRamps);
LOAD_DWORD(m_iPrevRamp);
for ( uint32 iTimeRamp = 0 ; iTimeRamp < MAX_TIME_RAMPS ; iTimeRamp++ )
{
LOAD_FLOAT(m_TimeRamps[iTimeRamp].m_Time);
LOAD_VECTOR(m_TimeRamps[iTimeRamp].m_Color);
LOAD_HSTRING(m_TimeRamps[iTimeRamp].m_hTarget);
LOAD_HSTRING(m_TimeRamps[iTimeRamp].m_hMessage);
}
}
if( nSaveFileVersion == 2001 )
{
uint32 nSaveVersion;
LOAD_DWORD(nSaveVersion);
g_pVersionMgr->SetCurrentSaveVersion( nSaveVersion );
HSTRING hDummy = NULL;
LOAD_HSTRING(hDummy);
g_pLTServer->FreeString( hDummy );
hDummy = NULL;
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::GetTimeRamp
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
TimeRamp* CGameServerShell::GetTimeRamp(uint32 i)
{
if(i >= MAX_TIME_RAMPS)
{
ASSERT(FALSE);
return NULL;
}
return &m_TimeRamps[i];
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::ShowMultiplayerSummary
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
void CGameServerShell::ShowMultiplayerSummary()
{
m_bShowMultiplayerSummary = LTTRUE;
int endString = 0;
for (int i = 0; i < MAX_CLIENTS; i++)
{
CPlayerObj* pPlayer = GetPlayerFromClientList(m_aClients[i]);
if (pPlayer)
{
pPlayer->ReadyToExit(LTFALSE);
}
}
m_fSummaryEndTime = g_pServerButeMgr->GetSummaryDelay() + g_pLTServer->GetTime();
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::ProcessPacket
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
LTRESULT CGameServerShell::ProcessPacket(ILTMessage_Read *pMsg, uint8 senderAddr[4], uint16 senderPort)
{
if (pMsg->Size() >= 16)
{
// Skip the engine-side portion of the message header
CLTMsgRef_Read cSubMsg(pMsg->SubMsg(8));
// Remember what address this came from
SetCurMessageSource(senderAddr, senderPort);
cSubMsg->SeekTo(0);
uint8 messageID = cSubMsg->Readuint8();
switch (messageID)
{
case MID_MULTIPLAYER_SERVERDIR: HandleMultiplayerServerDir (NULL, cSubMsg); break;
default:
break;
}
}
return(LT_OK);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::GetFirstNetPlayer
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
CPlayerObj* CGameServerShell::GetFirstNetPlayer()
{
m_nGetPlayerIndex = 0;
CPlayerObj* pPlayer = GetPlayerFromClientList(m_aClients[m_nGetPlayerIndex]);
while (!pPlayer && m_nGetPlayerIndex < MAX_CLIENTS-1)
{
m_nGetPlayerIndex++;
pPlayer = GetPlayerFromClientList(m_aClients[m_nGetPlayerIndex]);
}
return(pPlayer);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::GetNextNetPlayer
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
CPlayerObj* CGameServerShell::GetNextNetPlayer()
{
CPlayerObj* pPlayer = NULL;
while (!pPlayer && m_nGetPlayerIndex < MAX_CLIENTS-1)
{
m_nGetPlayerIndex++;
pPlayer = GetPlayerFromClientList(m_aClients[m_nGetPlayerIndex]);
}
return(pPlayer);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::GetPlayerPing
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
uint32 CGameServerShell::GetPlayerPing(CPlayerObj* pPlayer)
{
if (!pPlayer) return(0);
float ping = 0.0f;
HCLIENT hClient = pPlayer->GetClient();
if (!hClient) return(0);
uint32 clientID = g_pLTServer->GetClientID(hClient);
g_pLTServer->GetClientPing(hClient, ping);
return((uint16)(ping + 0.5f));
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::ClientConnectionInTrouble
//
// PURPOSE: Checks if client connection is in trouble.
//
// --------------------------------------------------------------------------- //
bool CGameServerShell::ClientConnectionInTrouble( HCLIENT hClient )
{
// Check inputs.
if( hClient == NULL )
{
ASSERT( !"CGameServerShell::ClientConnectionInTrouble: Invalid inputs." );
return false;
}
// If the player's ping is larger than the max allowed, drop him.
float fClientPing = 0.0f;
if( g_pLTServer->GetClientPing( hClient, fClientPing ) != LT_OK )
{
ASSERT( !"CGameServerShell::ClientConnectionInTrouble: Bad client handle." );
return false;
}
// Check if client is under limit.
float fMaxClientPing = GetConsoleFloat( "MaxClientPing", 30000.0f );
if( fClientPing < fMaxClientPing )
return false;
// Client connection is in trouble.
return true;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::GetHostName
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
char const* CGameServerShell::GetHostName()
{
return(m_ServerGameOptions.GetSessionName());
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::GetCurLevel
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
char const* CGameServerShell::GetCurLevel()
{
return(m_sWorld);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::SetCurLevel
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
void CGameServerShell::SetCurLevel( char const* pszWorldName )
{
m_sWorld = pszWorldName;
// [KLS 5/13/02] If we're changing the current level, then we need to allow for
// caching of the level specific files for this new level...
// (see the CacheLevelSpecificFiles() function)
m_bCachedLevelFiles = false;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::GetNumPlayers
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
int CGameServerShell::GetNumPlayers()
{
CPlayerObj* pPlr = GetFirstNetPlayer();
int nCount = 0;
while (pPlr)
{
nCount++;
pPlr = GetNextNetPlayer();
}
return(nCount);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::IsPositionOccupied
//
// PURPOSE: Check for any other player object's at this position
//
// ----------------------------------------------------------------------- //
LTBOOL CGameServerShell::IsPositionOccupied(LTVector & vPos, CPlayerObj* pPlayer)
{
ObjArray <HOBJECT, MAX_OBJECT_ARRAY_SIZE> objArray;
g_pLTServer->FindNamedObjects(DEFAULT_PLAYERNAME, objArray);
int numObjects = objArray.NumObjects();
if (!numObjects) return LTFALSE;
HOBJECT hPlayerObj = LTNULL;
if (pPlayer)
{
hPlayerObj = pPlayer->m_hObject;
}
for (int i = 0; i < numObjects; i++)
{
HOBJECT hObject = objArray.GetObject(i);
if (hObject != hPlayerObj)
{
LTVector vObjPos, vDims;
g_pLTServer->GetObjectPos(hObject, &vObjPos);
g_pPhysicsLT->GetObjectDims(hObject, &vDims);
// Increase the size of the dims to account for the players
// dims overlapping...
vDims *= 2.0f;
if (vObjPos.x - vDims.x < vPos.x && vPos.x < vObjPos.x + vDims.x &&
vObjPos.y - vDims.y < vPos.y && vPos.y < vObjPos.y + vDims.y &&
vObjPos.z - vDims.z < vPos.z && vPos.z < vObjPos.z + vDims.z)
{
return LTTRUE;
}
}
}
return LTFALSE;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::ServerAppAddClient
//
// PURPOSE: The server app is the dedicated server application and is
// usefull when running a dedicated server. on a regular server
// SendToServerApp returns LT_NOTFOUND and nothing actually
// gets sent. inorder for SendToServerApp to return LT_OK we
// need to call CreateServer to get a ServerInterface* and
// register a ServerAppHandler to it.
//
// ----------------------------------------------------------------------- //
void CGameServerShell::ServerAppAddClient( HCLIENT hClient )
{
// Write out the player information.
CAutoMessage cMsg;
cMsg.Writeuint8( SERVERAPP_ADDCLIENT );
cMsg.Writeuint16( g_pLTServer->GetClientID( hClient ));
// Send to the server app.
CLTMsgRef_Read msgRefRead = cMsg.Read( );
g_pLTServer->SendToServerApp( *msgRefRead );
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::ServerAppRemoveClient
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
void CGameServerShell::ServerAppRemoveClient( HCLIENT hClient )
{
// Write out the player information.
CAutoMessage cMsg;
cMsg.Writeuint8( SERVERAPP_REMOVECLIENT );
cMsg.Writeuint16( g_pLTServer->GetClientID( hClient ));
// Send to the server app.
CLTMsgRef_Read msgRefRead = cMsg.Read( );
g_pLTServer->SendToServerApp( *msgRefRead );
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::ServerAppShellUpdate
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
void CGameServerShell::ServerAppShellUpdate( )
{
int i;
// Write the message id.
CAutoMessage cMsg;
cMsg.Writeuint8( SERVERAPP_SHELLUPDATE );
// Add info for each player.
for (i = 0; i < MAX_CLIENTS; i++)
{
CPlayerObj* pPlayer = GetPlayerFromClientList(m_aClients[i]);
if( !pPlayer )
continue;
HCLIENT hClient = pPlayer->GetClient();
if( !hClient )
continue;
cMsg.Writeuint16( g_pLTServer->GetClientID( hClient ));
cMsg.WriteString( pPlayer->GetNetUniqueName( ));
cMsg.Writeint16( pPlayer->GetPlayerScore()->GetFrags( ));
cMsg.Writeint16( pPlayer->GetPlayerScore()->GetTags( ));
cMsg.Writeint16( pPlayer->GetPlayerScore()->GetScore( ));
}
// Signal end of player list.
cMsg.Writeuint16(( uint16 )-1 );
// Send to the server app.
CLTMsgRef_Read msgRefRead = cMsg.Read( );
g_pLTServer->SendToServerApp( *msgRefRead );
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::ServerAppPreStartWorld
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
void CGameServerShell::ServerAppPreStartWorld( )
{
CAutoMessage cMsg;
cMsg.Writeuint8( SERVERAPP_PRELOADWORLD );
// Send to the server app.
CLTMsgRef_Read msgRefRead = cMsg.Read( );
g_pLTServer->SendToServerApp( *msgRefRead );
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::ServerAppPostStartWorld
//
// PURPOSE:
//
// ----------------------------------------------------------------------- //
void CGameServerShell::ServerAppPostStartWorld( )
{
CAutoMessage cMsg;
cMsg.Writeuint8( SERVERAPP_POSTLOADWORLD );
cMsg.Writeuint16(( int )g_pServerMissionMgr->GetCurrentCampaignIndex( ));
char fname[_MAX_FNAME] = "";
_splitpath( GetCurLevel( ), NULL, NULL, fname, NULL );
cMsg.WriteString( fname );
// Send to the server app.
CLTMsgRef_Read msgRefRead = cMsg.Read( );
g_pLTServer->SendToServerApp( *msgRefRead );
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::SetServerDir
//
// PURPOSE: Change the server directory object
//
// --------------------------------------------------------------------------- //
void CGameServerShell::SetServerDir(IServerDirectory *pDir)
{
if( m_pServerDir )
{
// No leaking, please...
delete m_pServerDir;
}
m_pServerDir = pDir;
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::SetCurMessageSource
//
// PURPOSE: Set the source address of the message which is currently being processed
//
// --------------------------------------------------------------------------- //
void CGameServerShell::SetCurMessageSource(const uint8 aAddr[4], uint16 nPort)
{
m_aCurMessageSourceAddr[0] = aAddr[0];
m_aCurMessageSourceAddr[1] = aAddr[1];
m_aCurMessageSourceAddr[2] = aAddr[2];
m_aCurMessageSourceAddr[3] = aAddr[3];
m_nCurMessageSourcePort = nPort;
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::GetCurMessageSource
//
// PURPOSE: Get the source address of the message which is currently being processed
//
// --------------------------------------------------------------------------- //
void CGameServerShell::GetCurMessageSource(uint8 aAddr[4], uint16 *pPort)
{
aAddr[0] = m_aCurMessageSourceAddr[0];
aAddr[1] = m_aCurMessageSourceAddr[1];
aAddr[2] = m_aCurMessageSourceAddr[2];
aAddr[3] = m_aCurMessageSourceAddr[3];
*pPort = m_nCurMessageSourcePort;
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::MatchClientNameToPlayer
//
// PURPOSE: Matches a client name to a clientref and returns the
// playerobj of the clientref. If it can't match the client
// to the player, it returns null.
//
// --------------------------------------------------------------------------- //
CPlayerObj* CGameServerShell::MatchClientNameToPlayer( char const* pszClientName )
{
// Check inputs.
if( !pszClientName )
{
ASSERT( !"CGameServerShell::MatchClientToPlayer: Invalid inputs." );
return NULL;
}
char szClientRefName[MAX_CLIENT_NAME_LENGTH] = "";
// Search through all the clientrefs to find the one we were using when the player
// got saved. This is done by matching our IP addresses together.
HCLIENTREF hNextClientRef = g_pLTServer->GetNextClientRef(LTNULL);
while (hNextClientRef)
{
// Copy the current clientref and advance to the next. Makes body of loop easier.
HCLIENTREF hClientRef = hNextClientRef;
hNextClientRef = g_pLTServer->GetNextClientRef(hClientRef);
// Get the player associated with this clientref.
HOBJECT hObject = g_pLTServer->GetClientRefObject( hClientRef );
CPlayerObj* pPlayer = dynamic_cast< CPlayerObj* >( g_pLTServer->HandleToObject( hObject ));
if( !pPlayer )
continue;
// Get the clientname from the clientref and compare it to the input clientname.
g_pLTServer->GetClientRefName( hClientRef, szClientRefName, ARRAY_LEN( szClientRefName ));
if( _stricmp( pszClientName, szClientRefName ) != 0 )
continue;
// Found a matching player.
return pPlayer;
}
// No player found.
return NULL;
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::FindFreePlayerFromClientRefs
//
// PURPOSE: Look through all the clientrefs and see if there is any
// that doesn't match a different client.
//
// --------------------------------------------------------------------------- //
CPlayerObj* CGameServerShell::FindFreePlayerFromClientRefs( )
{
char szClientName[MAX_CLIENT_NAME_LENGTH] = "";
// Iterate through the clientrefs. Check if the clientref's playerobj
// doesn't match a client that doesn't have a playerobj associated with it yet.
HCLIENTREF hNextClientRef = g_pLTServer->GetNextClientRef(LTNULL);
while( hNextClientRef )
{
// Copy the current clientref and advance to the next. Makes body of loop easier.
HCLIENTREF hClientRef = hNextClientRef;
hNextClientRef = g_pLTServer->GetNextClientRef( hClientRef );
// Get the player associated with this clientref.
HOBJECT hObject = g_pLTServer->GetClientRefObject( hClientRef );
CPlayerObj* pPlayerRef = dynamic_cast< CPlayerObj* >( g_pLTServer->HandleToObject( hObject ));
if( !pPlayerRef )
continue;
// Loop through the other clients and see if they match this clientref.
HCLIENT hNextClient = g_pLTServer->GetNextClient( LTNULL );
bool bMatched = false;
while( hNextClient )
{
// Copy the current client and advance to the next. Makes body of loop easier.
HCLIENT hOtherClient = hNextClient;
hNextClient = g_pLTServer->GetNextClient( hOtherClient );
// Check if this client has already been hooked up to a player. If so, skip it.
CPlayerObj* pUsedPlayer = ( CPlayerObj* )g_pLTServer->GetClientUserData( hOtherClient );
if( pUsedPlayer )
continue;
// Get the client name.
g_pLTServer->GetClientName( hOtherClient, szClientName, ARRAY_LEN( szClientName ));
// If this client doesn't match any clientrefs, then skip it.
CPlayerObj* pClientMatch = MatchClientNameToPlayer( szClientName );
if( !pClientMatch )
continue;
// Check if this client matches a different clientref. If so, skip it.
if( pClientMatch != pPlayerRef )
continue;
// This client matches this clientref. Stop looking and go to the next clientref.
bMatched = true;
break;
}
// If no client matched this clientref, then we can take it.
if( !bMatched )
{
// No client matched this clientref, we can use it.
if( pPlayerRef )
return pPlayerRef;
}
}
// Didn't find any free clientref players.
return NULL;
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::PickClientRefPlayer
//
// PURPOSE: Find the clientref for this client based on the set clientname.
//
// --------------------------------------------------------------------------- //
CPlayerObj* CGameServerShell::PickClientRefPlayer( HCLIENT hClient )
{
// Check inputs.
if( !hClient )
{
ASSERT( !"CGameServerShell::FindPlayerFromClientRefs: Invalid inputs." );
return NULL;
}
// Get the clientname. Must be set before entering this function.
char szClientName[MAX_CLIENT_NAME_LENGTH] = "";
g_pLTServer->GetClientName( hClient, szClientName, ARRAY_LEN( szClientName ));
if( !szClientName[0] )
{
// If we've got a client without a name, they're not ready yet...
return NULL;
}
// See if we have a direct match between our client and a player.
CPlayerObj* pPlayer = MatchClientNameToPlayer( szClientName );
if( !pPlayer )
return NULL;
return pPlayer;
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::ProcessObjectiveMessage
//
// PURPOSE: Process the objectives and fill out the info if supplied...
//
// --------------------------------------------------------------------------- //
bool CGameServerShell::ProcessObjectiveMessage( const CParsedMsg &cMsg, ObjectiveMsgInfo *pInfo )
{
static CParsedMsg::CToken s_cTok_Objective("Objective");
static CParsedMsg::CToken s_cTok_Option("Option");
static CParsedMsg::CToken s_cTok_Parameter("Parameter");
static CParsedMsg::CToken s_cTok_Add("Add");
static CParsedMsg::CToken s_cTok_Remove("Remove");
static CParsedMsg::CToken s_cTok_RemoveAll("RemoveAll");
static CParsedMsg::CToken s_cTok_Completed("Completed");
if (cMsg.GetArgCount() < 2)
return false;
uint8 nType = 0;
if( cMsg.GetArg(0) == s_cTok_Objective )
{
nType = IC_OBJECTIVE_ID;
}
else if( cMsg.GetArg(0) == s_cTok_Option )
{
nType = IC_OPTION_ID;
}
else if( cMsg.GetArg(0) == s_cTok_Parameter )
{
nType = IC_PARAMETER_ID;
}
else
{
return false;
}
uint8 nRequest = ITEM_ADD_ID;
if (cMsg.GetArg(1) == s_cTok_Add)
{
nRequest = ITEM_ADD_ID;
}
else if (cMsg.GetArg(1) == s_cTok_Remove)
{
nRequest = ITEM_REMOVE_ID;
}
else if (cMsg.GetArg(1) == s_cTok_RemoveAll)
{
nRequest = ITEM_CLEAR_ID;
}
else if ((cMsg.GetArg(1) == s_cTok_Completed) && (nType != IC_PARAMETER_ID))
{
nRequest = ITEM_COMPLETE_ID;
}
else
{
return false;
}
uint32 dwId = 0;
if (nRequest != ITEM_CLEAR_ID)
{
if (cMsg.GetArgCount() < 3) return false;
dwId = (uint32) atol(cMsg.GetArg(2));
}
switch (nRequest)
{
case ITEM_ADD_ID:
{
if (nType == IC_OPTION_ID)
{
m_OptionalObjectives.Add(dwId);
}
else if (nType == IC_PARAMETER_ID)
{
m_Parameters.Add(dwId);
}
else
{
m_Objectives.Add(dwId);
}
}
break;
case ITEM_REMOVE_ID:
{
m_Objectives.Remove(dwId);
m_OptionalObjectives.Remove(dwId);
m_CompletedObjectives.Remove(dwId);
m_Parameters.Remove(dwId);
}
break;
case ITEM_COMPLETE_ID:
{
m_Objectives.Remove(dwId);
m_OptionalObjectives.Remove(dwId);
m_CompletedObjectives.Add(dwId);
}
break;
case ITEM_CLEAR_ID:
{
m_Objectives.Clear();
m_OptionalObjectives.Clear();
m_CompletedObjectives.Clear();
m_Parameters.Clear();
}
break;
}
if( pInfo )
{
pInfo->m_nType = nType;
pInfo->m_nRequest = nRequest;
pInfo->m_dwId = dwId;
}
return true;
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::ResetObjectives
//
// PURPOSE: Clear out all of our objectives...
//
// --------------------------------------------------------------------------- //
void CGameServerShell::ResetObjectives()
{
m_Objectives.Clear();
m_OptionalObjectives.Clear();
m_CompletedObjectives.Clear();
m_Parameters.Clear();
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::SaveObjectives
//
// PURPOSE: Save all of our objectives...
//
// --------------------------------------------------------------------------- //
void CGameServerShell::SaveObjectives( ILTMessage_Write *pMsg, uint32 dwSaveFlags )
{
m_Objectives.Save( pMsg );
m_OptionalObjectives.Save( pMsg );
m_CompletedObjectives.Save( pMsg );
m_Parameters.Save( pMsg );
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::LoadObjectives
//
// PURPOSE: Load all of our objectives...
//
// --------------------------------------------------------------------------- //
void CGameServerShell::LoadObjectives( ILTMessage_Read *pMsg, uint32 dwLoadFlags )
{
m_Objectives.Load( pMsg );
m_OptionalObjectives.Load( pMsg );
m_CompletedObjectives.Load( pMsg );
m_Parameters.Load( pMsg );
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::ApplyWeaponRestrictions
//
// PURPOSE: Apply the server game option weapon restrictions.
//
// ----------------------------------------------------------------------- //
void CGameServerShell::ApplyWeaponRestrictions( )
{
StringSet::iterator iter = m_ServerGameOptions.m_setRestrictedWeapons.begin( );
while( iter != m_ServerGameOptions.m_setRestrictedWeapons.end( ))
{
std::string const& sValue = *iter;
iter++;
WEAPON* pWeapon = ( WEAPON* )g_pWeaponMgr->GetWeapon( sValue.c_str( ));
if( !pWeapon )
continue;
if( pWeapon->bCanServerRestrict )
pWeapon->bServerRestricted = true;
}
iter = m_ServerGameOptions.m_setRestrictedAmmo.begin( );
while( iter != m_ServerGameOptions.m_setRestrictedAmmo.end( ))
{
std::string const& sValue = *iter;
iter++;
AMMO* pAmmo = ( AMMO* )g_pWeaponMgr->GetAmmo( sValue.c_str( ));
if( !pAmmo )
continue;
if( pAmmo->bCanServerRestrict )
pAmmo->bServerRestricted = true;
}
iter = m_ServerGameOptions.m_setRestrictedGear.begin( );
while( iter != m_ServerGameOptions.m_setRestrictedGear.end( ))
{
std::string const& sValue = *iter;
iter++;
GEAR* pGear = ( GEAR* )g_pWeaponMgr->GetGear( sValue.c_str( ));
if( !pGear )
continue;
if( pGear->bCanServerRestrict )
pGear->bServerRestricted = true;
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::SetLGFlags
//
// PURPOSE: Set the load game flags for...
//
// ----------------------------------------------------------------------- //
void CGameServerShell::SetLGFlags( uint8 nLGFlags )
{
m_nLastLGFlags = nLGFlags;
if( g_pVersionMgr )
g_pVersionMgr->SetLGFlags( m_nLastLGFlags );
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CGameServerShell::GetClientData
//
// PURPOSE: Gets the clientdata given a HCLIENT.
//
// ----------------------------------------------------------------------- //
ClientData* CGameServerShell::GetClientData( HCLIENT hClient )
{
// Remove this client from our list of clients.
ClientDataList::iterator iter = m_ClientDataList.begin( );
for( ; iter != m_ClientDataList.end( ); iter++ )
{
ClientData* pClientData = *iter;
if( pClientData->m_hClient == hClient )
{
return pClientData;
}
}
return NULL;
} | [
"[email protected]"
] | [
[
[
1,
5491
]
]
] |
fee9c65bacbb1fc28e0022e45e88f7000a43d738 | 9ad9345e116ead00be7b3bd147a0f43144a2e402 | /Integration_WAH_&_Extraction/SMDataExtraction/SMPreprocessing/DiscretizeData.cpp | 8691ae95bfeeb0c6424a551b4c60c49266287e88 | [] | no_license | asankaf/scalable-data-mining-framework | e46999670a2317ee8d7814a4bd21f62d8f9f5c8f | 811fddd97f52a203fdacd14c5753c3923d3a6498 | refs/heads/master | 2020-04-02T08:14:39.589079 | 2010-07-18T16:44:56 | 2010-07-18T16:44:56 | 33,870,353 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,933 | cpp | #include "StdAfx.h"
#include "DiscretizeData.h"
#include "AttributeType.h"
DiscretizeData::DiscretizeData(void)
{
}
DiscretizeData::~DiscretizeData(void)
{
delete this->_ctsDs;
}
EncodedIntAttribute* DiscretizeData::DiscretizeCtsAttribute(EncodedDoubleAttribute* _ctsAtt)
{
EncodedDoubleAttribute* doubleAtt = _ctsAtt;
EncodedIntAttribute* intAtt = new EncodedIntAttribute();
intAtt->setSignBitSet(doubleAtt->signBitSet());
intAtt->setAttID(doubleAtt->attributeID());
intAtt->setAttName(doubleAtt->attributeName());
intAtt->setAttType(ATT_TYPE::SIGNEDINT_VAL);
long int maxVal = (long int)doubleAtt->maxAttVal();
long int minVal = (long int)doubleAtt->minAttVal();
intAtt->setMaxVal(maxVal);
intAtt->setMinVal(minVal);
long int* vals = new long int[this->_rowCount];
for (int i = 0 ; i < this->_rowCount ; i++)
{
long int val = (long int)(doubleAtt->decodeTheTuple(i+1));
vals[i] = val;
}
int no_v_bitStreams = 0;
if (maxVal == 0)
{
no_v_bitStreams = 1;
}
else no_v_bitStreams = (int)ceil(log10((double)maxVal)/log10(2.0));
intAtt->setNoOfVBitStreams(no_v_bitStreams,this->_rowCount);
dynamic_bitset<> *convertdBitArray = new dynamic_bitset<>[this->_rowCount];
for (int j=0 ; j < this->_rowCount ; j++)
{
dynamic_bitset<> bitSet(no_v_bitStreams,(unsigned long)abs(vals[j]));
convertdBitArray[j] = bitSet;
}
delete vals;
BitStreamInfo **bitStreams = new BitStreamInfo*[no_v_bitStreams];
for (int k = 0 ; k < no_v_bitStreams ; k++)
{
BitStreamInfo* temp_bitStream = new VBitStream();
dynamic_bitset<> temp_bitSet(this->_rowCount);
for (int l = 0 ; l < this->_rowCount ; l++)
{
bool val = convertdBitArray[l][k];
temp_bitSet[l] = val;
}
temp_bitStream->convert(temp_bitSet);
temp_bitStream->setBitStreamAllocAttID(doubleAtt->attributeID());
temp_bitStream->setBitStreamAllocAttName(doubleAtt->attributeName());
bitStreams[k] = temp_bitStream;
}
vector<BitStreamInfo*> bitStream(bitStreams,bitStreams+no_v_bitStreams);
intAtt->setVBitStreams(bitStream);
return intAtt;
}
void DiscretizeData::DiscretizeAllCtsAttributes()
{
vector<EncodedAttributeInfo*> encodedAtts;
vector<EncodedIntAttribute*> encodedDisctretedIntAtts;
encodedAtts.resize(this->_ctsDs->noOfAttributes());
for (int i = 0 ; i < this->_ctsDs->noOfAttributes() ; i++)
{
EncodedAttributeInfo* att = this->_ctsDs->codedAttributes()[i];
int attType = (int)att->attributeType();
if (attType == 1)
{
EncodedIntAttribute* convertedIntAtt = DiscretizeCtsAttribute(static_cast<EncodedDoubleAttribute*>(att));
delete att;
encodedAtts[i] = convertedIntAtt;
encodedDisctretedIntAtts.push_back(convertedIntAtt);
}
else encodedAtts[i] = att;
}
this->_ctsDs->CodedAtts(encodedAtts);
this->_ctsDs->discretizeCtsAtts(encodedDisctretedIntAtts);
}
void DiscretizeData::DiscretizeSelectedCtsAtts( vector<int> zeroBasedAttIDs )
{
vector<EncodedAttributeInfo*> encodedAtts;
vector<EncodedIntAttribute*> encodedDisctretedIntAtts;
encodedAtts.resize(this->_ctsDs->noOfAttributes());
std::sort(zeroBasedAttIDs.begin(),zeroBasedAttIDs.end());
int selectAttCounter = 0;
for (int i = 0 ; i < this->_ctsDs->noOfAttributes() ; i++)
{
EncodedAttributeInfo* att = this->_ctsDs->codedAttributes()[i];
if (selectAttCounter < zeroBasedAttIDs.size() && i == zeroBasedAttIDs[selectAttCounter])
{
int attType = (int)att->attributeType();
if (attType == 1)
{
EncodedIntAttribute* convertedIntAtt = DiscretizeCtsAttribute(static_cast<EncodedDoubleAttribute*>(att));
delete att;
encodedAtts[i] = convertedIntAtt;
encodedDisctretedIntAtts.push_back(convertedIntAtt);
}
selectAttCounter++;
}
else encodedAtts[i] = att;
}
this->_ctsDs->CodedAtts(encodedAtts);
this->_ctsDs->discretizeCtsAtts(encodedDisctretedIntAtts);
}
| [
"jaadds@c7f6ba40-6498-11de-987a-95e5a5a5d5f1",
"[email protected]@c7f6ba40-6498-11de-987a-95e5a5a5d5f1"
] | [
[
[
1,
2
],
[
4,
10
],
[
12,
13
],
[
15,
15
],
[
17,
17
],
[
19,
20
],
[
22,
49
],
[
51,
66
],
[
69,
70
]
],
[
[
3,
3
],
[
11,
11
],
[
14,
14
],
[
16,
16
],
[
18,
18
],
[
21,
21
],
[
50,
50
],
[
67,
68
],
[
71,
122
]
]
] |
e68d92f1a4cbb9925d5bf153840c56f08279d1b8 | 33f59b1ba6b12c2dd3080b24830331c37bba9fe2 | /Depend/Foundation/NumericalAnalysis/Wm4Eigen.cpp | 01fdafce526b70bc34093341268138ffe6c98724 | [] | no_license | daleaddink/flagship3d | 4835c223fe1b6429c12e325770c14679c42ae3c6 | 6cce5b1ff7e7a2d5d0df7aa0594a70d795c7979a | refs/heads/master | 2021-01-15T16:29:12.196094 | 2009-11-01T10:18:11 | 2009-11-01T10:18:11 | 37,734,654 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,211 | cpp | // Geometric Tools, Inc.
// http://www.geometrictools.com
// Copyright (c) 1998-2006. All Rights Reserved
//
// The Wild Magic Version 4 Foundation Library source code is supplied
// under the terms of the license agreement
// http://www.geometrictools.com/License/Wm4FoundationLicense.pdf
// and may not be copied or disclosed except in accordance with the terms
// of that agreement.
#include "Wm4FoundationPCH.h"
#include "Wm4Eigen.h"
namespace Wm4
{
//----------------------------------------------------------------------------
template <class Real>
Eigen<Real>::Eigen (int iSize)
:
m_kMat(iSize,iSize)
{
assert(iSize >= 2);
m_iSize = iSize;
m_afDiag = WM4_NEW Real[m_iSize];
m_afSubd = WM4_NEW Real[m_iSize];
m_bIsRotation = false;
}
//----------------------------------------------------------------------------
template <class Real>
Eigen<Real>::Eigen (const Matrix2<Real>& rkM)
:
m_kMat(2,2,(const Real*)rkM)
{
m_iSize = 2;
m_afDiag = WM4_NEW Real[m_iSize];
m_afSubd = WM4_NEW Real[m_iSize];
m_bIsRotation = false;
}
//----------------------------------------------------------------------------
template <class Real>
Eigen<Real>::Eigen (const Matrix3<Real>& rkM)
:
m_kMat(3,3,(const Real*)rkM)
{
m_iSize = 3;
m_afDiag = WM4_NEW Real[m_iSize];
m_afSubd = WM4_NEW Real[m_iSize];
m_bIsRotation = false;
}
//----------------------------------------------------------------------------
template <class Real>
Eigen<Real>::Eigen (const GMatrix<Real>& rkM)
:
m_kMat(rkM)
{
m_iSize = rkM.GetRows();
assert(m_iSize >= 2 && (rkM.GetColumns() == m_iSize));
m_afDiag = WM4_NEW Real[m_iSize];
m_afSubd = WM4_NEW Real[m_iSize];
m_bIsRotation = false;
}
//----------------------------------------------------------------------------
template <class Real>
Eigen<Real>::~Eigen ()
{
WM4_DELETE[] m_afSubd;
WM4_DELETE[] m_afDiag;
}
//----------------------------------------------------------------------------
template <class Real>
Real& Eigen<Real>::operator() (int iRow, int iCol)
{
return m_kMat[iRow][iCol];
}
//----------------------------------------------------------------------------
template <class Real>
Eigen<Real>& Eigen<Real>::operator= (const Matrix2<Real>& rkM)
{
m_kMat.SetMatrix(2,2,(const Real*)rkM);
m_iSize = 2;
WM4_DELETE[] m_afDiag;
WM4_DELETE[] m_afSubd;
m_afDiag = WM4_NEW Real[m_iSize];
m_afSubd = WM4_NEW Real[m_iSize];
return *this;
}
//----------------------------------------------------------------------------
template <class Real>
Eigen<Real>& Eigen<Real>::operator= (const Matrix3<Real>& rkM)
{
m_kMat.SetMatrix(3,3,(const Real*)rkM);
m_iSize = 3;
WM4_DELETE[] m_afDiag;
WM4_DELETE[] m_afSubd;
m_afDiag = WM4_NEW Real[m_iSize];
m_afSubd = WM4_NEW Real[m_iSize];
return *this;
}
//----------------------------------------------------------------------------
template <class Real>
Eigen<Real>& Eigen<Real>::operator= (const GMatrix<Real>& rkM)
{
m_kMat = rkM;
return *this;
}
//----------------------------------------------------------------------------
template <class Real>
Real Eigen<Real>::GetEigenvalue (int i) const
{
return m_afDiag[i];
}
//----------------------------------------------------------------------------
template <class Real>
const Real* Eigen<Real>::GetEigenvalues () const
{
return m_afDiag;
}
//----------------------------------------------------------------------------
template <class Real>
void Eigen<Real>::GetEigenvector (int i, Vector2<Real>& rkV) const
{
assert(m_iSize == 2);
if (m_iSize == 2)
{
for (int iRow = 0; iRow < m_iSize; iRow++)
{
rkV[iRow] = m_kMat[iRow][i];
}
}
else
{
rkV = Vector2<Real>::ZERO;
}
}
//----------------------------------------------------------------------------
template <class Real>
void Eigen<Real>::GetEigenvector (int i, Vector3<Real>& rkV) const
{
assert(m_iSize == 3);
if (m_iSize == 3)
{
for (int iRow = 0; iRow < m_iSize; iRow++)
{
rkV[iRow] = m_kMat[iRow][i];
}
}
else
{
rkV = Vector3<Real>::ZERO;
}
}
//----------------------------------------------------------------------------
template <class Real>
GVector<Real> Eigen<Real>::GetEigenvector (int i) const
{
return m_kMat.GetColumn(i);
}
//----------------------------------------------------------------------------
template <class Real>
const GMatrix<Real>& Eigen<Real>::GetEigenvectors () const
{
return m_kMat;
}
//----------------------------------------------------------------------------
template <class Real>
void Eigen<Real>::Tridiagonal2 ()
{
// matrix is already tridiagonal
m_afDiag[0] = m_kMat[0][0];
m_afDiag[1] = m_kMat[1][1];
m_afSubd[0] = m_kMat[0][1];
m_afSubd[1] = (Real)0.0;
m_kMat[0][0] = (Real)1.0;
m_kMat[0][1] = (Real)0.0;
m_kMat[1][0] = (Real)0.0;
m_kMat[1][1] = (Real)1.0;
m_bIsRotation = true;
}
//----------------------------------------------------------------------------
template <class Real>
void Eigen<Real>::Tridiagonal3 ()
{
Real fM00 = m_kMat[0][0];
Real fM01 = m_kMat[0][1];
Real fM02 = m_kMat[0][2];
Real fM11 = m_kMat[1][1];
Real fM12 = m_kMat[1][2];
Real fM22 = m_kMat[2][2];
m_afDiag[0] = fM00;
m_afSubd[2] = (Real)0.0;
if (Math<Real>::FAbs(fM02) > Math<Real>::ZERO_TOLERANCE)
{
Real fLength = Math<Real>::Sqrt(fM01*fM01+fM02*fM02);
Real fInvLength = ((Real)1.0)/fLength;
fM01 *= fInvLength;
fM02 *= fInvLength;
Real fQ = ((Real)2.0)*fM01*fM12+fM02*(fM22-fM11);
m_afDiag[1] = fM11+fM02*fQ;
m_afDiag[2] = fM22-fM02*fQ;
m_afSubd[0] = fLength;
m_afSubd[1] = fM12-fM01*fQ;
m_kMat[0][0] = (Real)1.0;
m_kMat[0][1] = (Real)0.0;
m_kMat[0][2] = (Real)0.0;
m_kMat[1][0] = (Real)0.0;
m_kMat[1][1] = fM01;
m_kMat[1][2] = fM02;
m_kMat[2][0] = (Real)0.0;
m_kMat[2][1] = fM02;
m_kMat[2][2] = -fM01;
m_bIsRotation = false;
}
else
{
m_afDiag[1] = fM11;
m_afDiag[2] = fM22;
m_afSubd[0] = fM01;
m_afSubd[1] = fM12;
m_kMat[0][0] = (Real)1.0;
m_kMat[0][1] = (Real)0.0;
m_kMat[0][2] = (Real)0.0;
m_kMat[1][0] = (Real)0.0;
m_kMat[1][1] = (Real)1.0;
m_kMat[1][2] = (Real)0.0;
m_kMat[2][0] = (Real)0.0;
m_kMat[2][1] = (Real)0.0;
m_kMat[2][2] = (Real)1.0;
m_bIsRotation = true;
}
}
//----------------------------------------------------------------------------
template <class Real>
void Eigen<Real>::TridiagonalN ()
{
int i0, i1, i2, i3;
for (i0 = m_iSize-1, i3 = m_iSize-2; i0 >= 1; i0--, i3--)
{
Real fH = (Real)0.0, fScale = (Real)0.0;
if (i3 > 0)
{
for (i2 = 0; i2 <= i3; i2++)
{
fScale += Math<Real>::FAbs(m_kMat[i0][i2]);
}
if (fScale == (Real)0.0)
{
m_afSubd[i0] = m_kMat[i0][i3];
}
else
{
Real fInvScale = ((Real)1.0)/fScale;
for (i2 = 0; i2 <= i3; i2++)
{
m_kMat[i0][i2] *= fInvScale;
fH += m_kMat[i0][i2]*m_kMat[i0][i2];
}
Real fF = m_kMat[i0][i3];
Real fG = Math<Real>::Sqrt(fH);
if (fF > (Real)0.0)
{
fG = -fG;
}
m_afSubd[i0] = fScale*fG;
fH -= fF*fG;
m_kMat[i0][i3] = fF-fG;
fF = (Real)0.0;
Real fInvH = ((Real)1.0)/fH;
for (i1 = 0; i1 <= i3; i1++)
{
m_kMat[i1][i0] = m_kMat[i0][i1]*fInvH;
fG = (Real)0.0;
for (i2 = 0; i2 <= i1; i2++)
{
fG += m_kMat[i1][i2]*m_kMat[i0][i2];
}
for (i2 = i1+1; i2 <= i3; i2++)
{
fG += m_kMat[i2][i1]*m_kMat[i0][i2];
}
m_afSubd[i1] = fG*fInvH;
fF += m_afSubd[i1]*m_kMat[i0][i1];
}
Real fHalfFdivH = ((Real)0.5)*fF*fInvH;
for (i1 = 0; i1 <= i3; i1++)
{
fF = m_kMat[i0][i1];
fG = m_afSubd[i1] - fHalfFdivH*fF;
m_afSubd[i1] = fG;
for (i2 = 0; i2 <= i1; i2++)
{
m_kMat[i1][i2] -= fF*m_afSubd[i2] +
fG*m_kMat[i0][i2];
}
}
}
}
else
{
m_afSubd[i0] = m_kMat[i0][i3];
}
m_afDiag[i0] = fH;
}
m_afDiag[0] = (Real)0.0;
m_afSubd[0] = (Real)0.0;
for (i0 = 0, i3 = -1; i0 <= m_iSize-1; i0++, i3++)
{
if (m_afDiag[i0] != (Real)0.0)
{
for (i1 = 0; i1 <= i3; i1++)
{
Real fSum = (Real)0.0;
for (i2 = 0; i2 <= i3; i2++)
{
fSum += m_kMat[i0][i2]*m_kMat[i2][i1];
}
for (i2 = 0; i2 <= i3; i2++)
{
m_kMat[i2][i1] -= fSum*m_kMat[i2][i0];
}
}
}
m_afDiag[i0] = m_kMat[i0][i0];
m_kMat[i0][i0] = (Real)1.0;
for (i1 = 0; i1 <= i3; i1++)
{
m_kMat[i1][i0] = (Real)0.0;
m_kMat[i0][i1] = (Real)0.0;
}
}
// re-ordering if Eigen::QLAlgorithm is used subsequently
for (i0 = 1, i3 = 0; i0 < m_iSize; i0++, i3++)
{
m_afSubd[i3] = m_afSubd[i0];
}
m_afSubd[m_iSize-1] = (Real)0.0;
m_bIsRotation = ((m_iSize % 2) == 0);
}
//----------------------------------------------------------------------------
template <class Real>
bool Eigen<Real>::QLAlgorithm ()
{
const int iMaxIter = 32;
for (int i0 = 0; i0 < m_iSize; i0++)
{
int i1;
for (i1 = 0; i1 < iMaxIter; i1++)
{
int i2;
for (i2 = i0; i2 <= m_iSize-2; i2++)
{
Real fTmp = Math<Real>::FAbs(m_afDiag[i2]) +
Math<Real>::FAbs(m_afDiag[i2+1]);
if (Math<Real>::FAbs(m_afSubd[i2]) + fTmp == fTmp)
{
break;
}
}
if (i2 == i0)
{
break;
}
Real fG = (m_afDiag[i0+1] - m_afDiag[i0])/(((Real)2.0) *
m_afSubd[i0]);
Real fR = Math<Real>::Sqrt(fG*fG+(Real)1.0);
if ( fG < (Real)0.0 )
{
fG = m_afDiag[i2]-m_afDiag[i0]+m_afSubd[i0]/(fG-fR);
}
else
{
fG = m_afDiag[i2]-m_afDiag[i0]+m_afSubd[i0]/(fG+fR);
}
Real fSin = (Real)1.0, fCos = (Real)1.0, fP = (Real)0.0;
for (int i3 = i2-1; i3 >= i0; i3--)
{
Real fF = fSin*m_afSubd[i3];
Real fB = fCos*m_afSubd[i3];
if (Math<Real>::FAbs(fF) >= Math<Real>::FAbs(fG))
{
fCos = fG/fF;
fR = Math<Real>::Sqrt(fCos*fCos+(Real)1.0);
m_afSubd[i3+1] = fF*fR;
fSin = ((Real)1.0)/fR;
fCos *= fSin;
}
else
{
fSin = fF/fG;
fR = Math<Real>::Sqrt(fSin*fSin+(Real)1.0);
m_afSubd[i3+1] = fG*fR;
fCos = ((Real)1.0)/fR;
fSin *= fCos;
}
fG = m_afDiag[i3+1]-fP;
fR = (m_afDiag[i3]-fG)*fSin+((Real)2.0)*fB*fCos;
fP = fSin*fR;
m_afDiag[i3+1] = fG+fP;
fG = fCos*fR-fB;
for (int i4 = 0; i4 < m_iSize; i4++)
{
fF = m_kMat[i4][i3+1];
m_kMat[i4][i3+1] = fSin*m_kMat[i4][i3]+fCos*fF;
m_kMat[i4][i3] = fCos*m_kMat[i4][i3]-fSin*fF;
}
}
m_afDiag[i0] -= fP;
m_afSubd[i0] = fG;
m_afSubd[i2] = (Real)0.0;
}
if (i1 == iMaxIter)
{
return false;
}
}
return true;
}
//----------------------------------------------------------------------------
template <class Real>
void Eigen<Real>::DecreasingSort ()
{
// sort eigenvalues in decreasing order, e[0] >= ... >= e[iSize-1]
for (int i0 = 0, i1; i0 <= m_iSize-2; i0++)
{
// locate maximum eigenvalue
i1 = i0;
Real fMax = m_afDiag[i1];
int i2;
for (i2 = i0+1; i2 < m_iSize; i2++)
{
if (m_afDiag[i2] > fMax)
{
i1 = i2;
fMax = m_afDiag[i1];
}
}
if (i1 != i0)
{
// swap eigenvalues
m_afDiag[i1] = m_afDiag[i0];
m_afDiag[i0] = fMax;
// swap eigenvectors
for (i2 = 0; i2 < m_iSize; i2++)
{
Real fTmp = m_kMat[i2][i0];
m_kMat[i2][i0] = m_kMat[i2][i1];
m_kMat[i2][i1] = fTmp;
m_bIsRotation = !m_bIsRotation;
}
}
}
}
//----------------------------------------------------------------------------
template <class Real>
void Eigen<Real>::IncreasingSort ()
{
// sort eigenvalues in increasing order, e[0] <= ... <= e[iSize-1]
for (int i0 = 0, i1; i0 <= m_iSize-2; i0++)
{
// locate minimum eigenvalue
i1 = i0;
Real fMin = m_afDiag[i1];
int i2;
for (i2 = i0+1; i2 < m_iSize; i2++)
{
if (m_afDiag[i2] < fMin)
{
i1 = i2;
fMin = m_afDiag[i1];
}
}
if (i1 != i0)
{
// swap eigenvalues
m_afDiag[i1] = m_afDiag[i0];
m_afDiag[i0] = fMin;
// swap eigenvectors
for (i2 = 0; i2 < m_iSize; i2++)
{
Real fTmp = m_kMat[i2][i0];
m_kMat[i2][i0] = m_kMat[i2][i1];
m_kMat[i2][i1] = fTmp;
m_bIsRotation = !m_bIsRotation;
}
}
}
}
//----------------------------------------------------------------------------
template <class Real>
void Eigen<Real>::GuaranteeRotation ()
{
if (!m_bIsRotation)
{
// change sign on the first column
for (int iRow = 0; iRow < m_iSize; iRow++)
{
m_kMat[iRow][0] = -m_kMat[iRow][0];
}
}
}
//----------------------------------------------------------------------------
template <class Real>
void Eigen<Real>::EigenStuff2 ()
{
Tridiagonal2();
QLAlgorithm();
GuaranteeRotation();
}
//----------------------------------------------------------------------------
template <class Real>
void Eigen<Real>::EigenStuff3 ()
{
Tridiagonal3();
QLAlgorithm();
GuaranteeRotation();
}
//----------------------------------------------------------------------------
template <class Real>
void Eigen<Real>::EigenStuffN ()
{
TridiagonalN();
QLAlgorithm();
GuaranteeRotation();
}
//----------------------------------------------------------------------------
template <class Real>
void Eigen<Real>::EigenStuff ()
{
switch (m_iSize)
{
case 2: Tridiagonal2(); break;
case 3: Tridiagonal3(); break;
default: TridiagonalN(); break;
}
QLAlgorithm();
GuaranteeRotation();
}
//----------------------------------------------------------------------------
template <class Real>
void Eigen<Real>::DecrSortEigenStuff2 ()
{
Tridiagonal2();
QLAlgorithm();
DecreasingSort();
GuaranteeRotation();
}
//----------------------------------------------------------------------------
template <class Real>
void Eigen<Real>::DecrSortEigenStuff3 ()
{
Tridiagonal3();
QLAlgorithm();
DecreasingSort();
GuaranteeRotation();
}
//----------------------------------------------------------------------------
template <class Real>
void Eigen<Real>::DecrSortEigenStuffN ()
{
TridiagonalN();
QLAlgorithm();
DecreasingSort();
GuaranteeRotation();
}
//----------------------------------------------------------------------------
template <class Real>
void Eigen<Real>::DecrSortEigenStuff ()
{
switch (m_iSize)
{
case 2: Tridiagonal2(); break;
case 3: Tridiagonal3(); break;
default: TridiagonalN(); break;
}
QLAlgorithm();
DecreasingSort();
GuaranteeRotation();
}
//----------------------------------------------------------------------------
template <class Real>
void Eigen<Real>::IncrSortEigenStuff2 ()
{
Tridiagonal2();
QLAlgorithm();
IncreasingSort();
GuaranteeRotation();
}
//----------------------------------------------------------------------------
template <class Real>
void Eigen<Real>::IncrSortEigenStuff3 ()
{
Tridiagonal3();
QLAlgorithm();
IncreasingSort();
GuaranteeRotation();
}
//----------------------------------------------------------------------------
template <class Real>
void Eigen<Real>::IncrSortEigenStuffN ()
{
TridiagonalN();
QLAlgorithm();
IncreasingSort();
GuaranteeRotation();
}
//----------------------------------------------------------------------------
template <class Real>
void Eigen<Real>::IncrSortEigenStuff ()
{
switch (m_iSize)
{
case 2: Tridiagonal2(); break;
case 3: Tridiagonal3(); break;
default: TridiagonalN(); break;
}
QLAlgorithm();
IncreasingSort();
GuaranteeRotation();
}
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
// explicit instantiation
//----------------------------------------------------------------------------
template WM4_FOUNDATION_ITEM
class Eigen<float>;
template WM4_FOUNDATION_ITEM
class Eigen<double>;
//----------------------------------------------------------------------------
}
| [
"yf.flagship@e79fdf7c-a9d8-11de-b950-3d5b5f4ea0aa"
] | [
[
[
1,
647
]
]
] |
e7ab8494ea3d7b8e7de724560f616775658e8ff0 | 9773c3304eecc308671bcfa16b5390c81ef3b23a | /MDI AIPI V.6.92 2003 ( Correct Save Fired Rules, AM =-1, g_currentLine)/AIPI/Aipi_Tokenizer.h | f34edeca9ae103aa5ffb3e13c3cd860e7f9d3150 | [] | no_license | 15831944/AiPI-1 | 2d09d6e6bd3fa104d0175cf562bb7826e1ac5ec4 | 9350aea6ac4c7870b43d0a9f992a1908a3c1c4a8 | refs/heads/master | 2021-12-02T20:34:03.136125 | 2011-10-27T00:07:54 | 2011-10-27T00:07:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,001 | h | // Aipi_Tokenizer.h: interface for the CAipi_Tokenizer class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_AIPI_TOKENIZER_H__FE42D69B_22B3_4936_A9B0_946C2F6734A6__INCLUDED_)
#define AFX_AIPI_TOKENIZER_H__FE42D69B_22B3_4936_A9B0_946C2F6734A6__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "Aipi_Init.h"
class CAipi_Tokenizer
{
public:
CAipi_Tokenizer();
virtual ~CAipi_Tokenizer();
inline CAipi_Tokenizer( int index, long pos1, long pos2, int line, double iform, tstring token, int categ)
{
m_Index = index;
m_Pos1 = pos1;
m_Pos2 = pos2;
m_Line = line;
m_IntForm = iform;
m_Token = token;
m_Category = categ;
}
inline void CAipi_Tokenizer::setIndex(int index)
{
m_Index = index;
}
inline void CAipi_Tokenizer::setPos1(long pos1)
{
m_Pos1 = pos1;
}
inline void CAipi_Tokenizer::setPos2(long pos2)
{
m_Pos2 = pos2;
}
inline void CAipi_Tokenizer::setLine(int line)
{
m_Line = line;
}
inline void CAipi_Tokenizer::setToken(tstring token)
{
m_Token = token;
}
inline void CAipi_Tokenizer::setIntForm(double iform)
{
m_IntForm = iform;
}
inline void CAipi_Tokenizer::setCategory(int categ)
{
m_Category = categ;
}
inline long CAipi_Tokenizer::getIndex()
{
return m_Index;
}
inline long CAipi_Tokenizer::getPos1()
{
return m_Pos1;
}
inline long CAipi_Tokenizer::getPos2()
{
return m_Pos2;
}
inline int CAipi_Tokenizer::getLine()
{
return m_Line;
}
inline tstring CAipi_Tokenizer::getToken()
{
return m_Token;
}
inline double CAipi_Tokenizer::getIntForm()
{
return m_IntForm;
}
inline int CAipi_Tokenizer::getCategory()
{
return m_Category;
}
public:
CAipi_Tokenizer* CAipi_Tokenizer::v_addTokenIndex(int index, long pos1, long pos2, int line, double iform, tstring token, int categ );
CAipi_Tokenizer* CAipi_Tokenizer::v_addToken(long pos1, long pos2, int line, double iform, tstring token, int categ );
long v_getIntFormByIndex( int index);
long v_getPos1ByIndex( int index);
long v_getPos2ByIndex( int index);
int v_getLineByIndex( int index);
int v_getCategoryByIndex(int index);
tstring v_getTokenByIndex(int index);
tstring v_lastToken();
tstring v_previousLastToken();
void v_clearTokenizer();
void v_printTokenizer();
//unsigned int v_previousToken(unsigned int pos);
long v_lastPosition();
long v_stepback_1Pos();
long v_stepback_2Pos();
long v_stepback_3Pos();
long v_sizeTokenizer();
double v_lastIntFormToken();
long v_previousLastIntFormToken();
public:
int m_Index;
long m_Pos1;
long m_Pos2;
int m_Line;
double m_IntForm;
int m_Category;
tstring m_Token;
};
#endif // !defined(AFX_AIPI_TOKENIZER_H__FE42D69B_22B3_4936_A9B0_946C2F6734A6__INCLUDED_)
| [
"[email protected]"
] | [
[
[
1,
155
]
]
] |
8e0f4fbb4b260fd71a371e7fe725b9777befe3cf | fcdddf0f27e52ece3f594c14fd47d1123f4ac863 | /terralib/src/qwt/qwt_plot_axis.cpp | c44c2caf3f01b5d51c15fe5ee92e1d948bf3670c | [] | no_license | radtek/terra-printer | 32a2568b1e92cb5a0495c651d7048db6b2bbc8e5 | 959241e52562128d196ccb806b51fda17d7342ae | refs/heads/master | 2020-06-11T01:49:15.043478 | 2011-12-12T13:31:19 | 2011-12-12T13:31:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,373 | cpp | /* -*- mode: C++ ; c-file-style: "stroustrup" -*- *****************************
* Qwt Widget Library
* Copyright (C) 1997 Josef Wilgen
* Copyright (C) 2002 Uwe Rathmann
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the Qwt License, Version 1.0
*****************************************************************************/
#include "qwt_plot.h"
#include "qwt_math.h"
#include "qwt_scale_widget.h"
#include "qwt_scale_div.h"
#include "qwt_scale_engine.h"
class QwtPlot::AxisData
{
public:
bool isEnabled;
bool doAutoScale;
double minValue;
double maxValue;
double stepSize;
int maxMajor;
int maxMinor;
QwtScaleDiv scaleDiv;
QwtScaleEngine *scaleEngine;
QwtScaleWidget *scaleWidget;
};
//! Initialize axes
void QwtPlot::initAxesData()
{
int axisId;
for( axisId = 0; axisId < axisCnt; axisId++)
d_axisData[axisId] = new AxisData;
d_axisData[yLeft]->scaleWidget =
new QwtScaleWidget(QwtScaleDraw::LeftScale, this);
d_axisData[yRight]->scaleWidget =
new QwtScaleWidget(QwtScaleDraw::RightScale, this);
d_axisData[xTop]->scaleWidget =
new QwtScaleWidget(QwtScaleDraw::TopScale, this);
d_axisData[xBottom]->scaleWidget =
new QwtScaleWidget(QwtScaleDraw::BottomScale, this);
QFont fscl(fontInfo().family(), 10);
QFont fttl(fontInfo().family(), 12, QFont::Bold);
for(axisId = 0; axisId < axisCnt; axisId++)
{
AxisData &d = *d_axisData[axisId];
d.scaleWidget->setFont(fscl);
d.scaleWidget->setBaselineDist(2);
QwtText text;
text.setFont(fttl);
d.scaleWidget->setTitle(text);
d.doAutoScale = true;
d.minValue = 0.0;
d.maxValue = 1000.0;
d.stepSize = 0.0;
d.maxMinor = 5;
d.maxMajor = 8;
d.scaleEngine = new QwtLinearScaleEngine;
d.scaleDiv.invalidate();
}
d_axisData[yLeft]->isEnabled = true;
d_axisData[yRight]->isEnabled = false;
d_axisData[xBottom]->isEnabled = true;
d_axisData[xTop]->isEnabled = false;
}
void QwtPlot::deleteAxesData()
{
for( int axisId = 0; axisId < axisCnt; axisId++)
{
delete d_axisData[axisId]->scaleEngine;
delete d_axisData[axisId];
d_axisData[axisId] = NULL;
}
}
/*!
\return specified axis, or NULL if axisId is invalid.
\param axisId axis index
*/
const QwtScaleWidget *QwtPlot::axisWidget(int axisId) const
{
if (axisValid(axisId))
return d_axisData[axisId]->scaleWidget;
return NULL;
}
/*!
\return specified axis, or NULL if axisId is invalid.
\param axisId axis index
*/
QwtScaleWidget *QwtPlot::axisWidget(int axisId)
{
if (axisValid(axisId))
return d_axisData[axisId]->scaleWidget;
return NULL;
}
void QwtPlot::setAxisScaleEngine(int axisId, QwtScaleEngine *scaleEngine)
{
if (axisValid(axisId) && scaleEngine != NULL )
{
AxisData &d = *d_axisData[axisId];
delete d.scaleEngine;
d.scaleEngine = scaleEngine;
d.scaleDiv.invalidate();
autoRefresh();
}
}
QwtScaleEngine *QwtPlot::axisScaleEngine(int axisId)
{
if (axisValid(axisId))
return d_axisData[axisId]->scaleEngine;
else
return NULL;
}
const QwtScaleEngine *QwtPlot::axisScaleEngine(int axisId) const
{
if (axisValid(axisId))
return d_axisData[axisId]->scaleEngine;
else
return NULL;
}
/*!
\return \c true if autoscaling is enabled
\param axisId axis index
*/
bool QwtPlot::axisAutoScale(int axisId) const
{
if (axisValid(axisId))
return d_axisData[axisId]->doAutoScale;
else
return false;
}
/*!
\return \c true if a specified axis is enabled
\param axisId axis index
*/
bool QwtPlot::axisEnabled(int axisId) const
{
if (axisValid(axisId))
return d_axisData[axisId]->isEnabled;
else
return false;
}
/*!
\return the font of the scale labels for a specified axis
\param axisId axis index
*/
QFont QwtPlot::axisFont(int axisId) const
{
if (axisValid(axisId))
return axisWidget(axisId)->font();
else
return QFont();
}
/*!
\return the maximum number of major ticks for a specified axis
\param axisId axis index
*/
int QwtPlot::axisMaxMajor(int axisId) const
{
if (axisValid(axisId))
return d_axisData[axisId]->maxMajor;
else
return 0;
}
/*!
\return the maximum number of minor ticks for a specified axis
\param axisId axis index
*/
int QwtPlot::axisMaxMinor(int axisId) const
{
if (axisValid(axisId))
return d_axisData[axisId]->maxMinor;
else
return 0;
}
/*!
\returns the scale division of a specified axis
\param axisId axis index
\sa QwtScaleDiv
*/
const QwtScaleDiv *QwtPlot::axisScaleDiv(int axisId) const
{
if (!axisValid(axisId))
return NULL;
return &d_axisData[axisId]->scaleDiv;
}
/*!
\returns the scale division of a specified axis
\param axisId axis index
\sa QwtScaleDiv
*/
QwtScaleDiv *QwtPlot::axisScaleDiv(int axisId)
{
if (!axisValid(axisId))
return NULL;
return &d_axisData[axisId]->scaleDiv;
}
/*!
\returns the scale draw of a specified axis
\param axisId axis index
\return specified scaleDraw for axis, or NULL if axis is invalid.
\sa QwtScaleDraw
*/
const QwtScaleDraw *QwtPlot::axisScaleDraw(int axisId) const
{
if (!axisValid(axisId))
return NULL;
return axisWidget(axisId)->scaleDraw();
}
/*!
\returns the scale draw of a specified axis
\param axisId axis index
\return specified scaleDraw for axis, or NULL if axis is invalid.
\sa QwtScaleDraw
*/
QwtScaleDraw *QwtPlot::axisScaleDraw(int axisId)
{
if (!axisValid(axisId))
return NULL;
return axisWidget(axisId)->scaleDraw();
}
/*!
\return the title of a specified axis
\param axisId axis index
*/
QwtText QwtPlot::axisTitle(int axisId) const
{
if (axisValid(axisId))
return axisWidget(axisId)->title();
else
return QwtText();
}
/*!
\brief Enable or disable a specified axis
When an axis is disabled, this only means that it is not
visible on the screen. Curves, markers and can be attached
to disabled axes, and transformation of screen coordinates
into values works as normal.
Only xBottom and yLeft are enabled by default.
\param axisId axis index
\param tf \c true (enabled) or \c false (disabled)
*/
void QwtPlot::enableAxis(int axisId, bool tf)
{
if (axisValid(axisId) && tf != d_axisData[axisId]->isEnabled)
{
d_axisData[axisId]->isEnabled = tf;
updateLayout();
}
}
/*!
Transform the x or y coordinate of a position in the
drawing region into a value.
\param axisId axis index
\param pos position
\warning The position can be an x or a y coordinate,
depending on the specified axis.
*/
double QwtPlot::invTransform(int axisId, int pos) const
{
if (axisValid(axisId))
return(canvasMap(axisId).invTransform(pos));
else
return 0.0;
}
/*!
\brief Transform a value into a coordinate in the plotting region
\param axisId axis index
\param value value
\return X or y coordinate in the plotting region corresponding
to the value.
*/
int QwtPlot::transform(int axisId, double value) const
{
if (axisValid(axisId))
return(canvasMap(axisId).transform(value));
else
return 0;
}
/*!
\brief Change the font of an axis
\param axisId axis index
\param f font
\warning This function changes the font of the tick labels,
not of the axis title.
*/
void QwtPlot::setAxisFont(int axisId, const QFont &f)
{
if (axisValid(axisId))
axisWidget(axisId)->setFont(f);
}
/*!
\brief Enable autoscaling for a specified axis
This member function is used to switch back to autoscaling mode
after a fixed scale has been set. Autoscaling is enabled by default.
\param axisId axis index
\sa QwtPlot::setAxisScale(), QwtPlot::setAxisScaleDiv()
*/
void QwtPlot::setAxisAutoScale(int axisId)
{
if (axisValid(axisId) && !d_axisData[axisId]->doAutoScale )
{
d_axisData[axisId]->doAutoScale = true;
autoRefresh();
}
}
/*!
\brief Disable autoscaling and specify a fixed scale for a selected axis.
\param axisId axis index
\param min
\param max minimum and maximum of the scale
\param stepSize Major step size. If <code>step == 0</code>, the step size is
calculated automatically using the maxMajor setting.
\sa QwtPlot::setAxisMaxMajor(), QwtPlot::setAxisAutoScale()
*/
void QwtPlot::setAxisScale(int axisId, double min, double max, double stepSize)
{
if (axisValid(axisId))
{
AxisData &d = *d_axisData[axisId];
d.doAutoScale = false;
d.scaleDiv.invalidate();
d.minValue = min;
d.maxValue = max;
d.stepSize = stepSize;
autoRefresh();
}
}
/*!
\brief Disable autoscaling and specify a fixed scale for a selected axis.
\param axisId axis index
\param scaleDiv Scale division
\sa QwtPlot::setAxisScale(), QwtPlot::setAxisAutoScale()
*/
void QwtPlot::setAxisScaleDiv(int axisId, const QwtScaleDiv &scaleDiv)
{
if (axisValid(axisId))
{
AxisData &d = *d_axisData[axisId];
d.doAutoScale = false;
d.scaleDiv = scaleDiv;
autoRefresh();
}
}
/*!
\brief Set a scale draw
\param axisId axis index
\param scaleDraw object responsible for drawing scales.
By passing scaleDraw it is possible to extend QwtScaleDraw
functionality and let it take place in QwtPlot. Please note
that scaleDraw has to be created with new and will be deleted
by the corresponding QwtScale member ( like a child object ).
\sa QwtScaleDraw, QwtScale
\warning The attributes of scaleDraw will be overwritten by those of the
previous QwtScaleDraw.
*/
void QwtPlot::setAxisScaleDraw(int axisId, QwtScaleDraw *scaleDraw)
{
if (axisValid(axisId))
{
axisWidget(axisId)->setScaleDraw(scaleDraw);
autoRefresh();
}
}
/*!
Change the alignment of the tick labels
\param axisId axis index
\param alignment Or'd Qt::AlignmentFlags <see qnamespace.h>
\sa QwtScaleDraw::setLabelAlignment()
*/
#if QT_VERSION < 0x040000
void QwtPlot::setAxisLabelAlignment(int axisId, int alignment)
#else
void QwtPlot::setAxisLabelAlignment(int axisId, Qt::Alignment alignment)
#endif
{
if (axisValid(axisId))
axisWidget(axisId)->setLabelAlignment(alignment);
}
/*!
Rotate all tick labels
\param axisId axis index
\param rotation Angle in degrees. When changing the label rotation,
the label alignment might be adjusted too.
\sa QwtScaleDraw::setLabelRotation(), QwtPlot::setAxisLabelAlignment
*/
void QwtPlot::setAxisLabelRotation(int axisId, double rotation)
{
if (axisValid(axisId))
axisWidget(axisId)->setLabelRotation(rotation);
}
/*!
\brief Set the maximum number of minor scale intervals for a specified axis
\param axisId axis index
\param maxMinor maximum number of minor steps
\sa QwtAutoScale::setMaxMinor
*/
void QwtPlot::setAxisMaxMinor(int axisId, int maxMinor)
{
if (axisValid(axisId))
{
if ( maxMinor < 0 )
maxMinor = 0;
if ( maxMinor > 100 )
maxMinor = 100;
AxisData &d = *d_axisData[axisId];
if ( maxMinor != d.maxMinor )
{
d.maxMinor = maxMinor;
d.scaleDiv.invalidate();
autoRefresh();
}
}
}
/*!
\brief Set the maximum number of major scale intervals for a specified axis
\param axisId axis index
\param maxMajor maximum number of major steps
\sa QwtAutoScale::setMaxMajor
*/
void QwtPlot::setAxisMaxMajor(int axisId, int maxMajor)
{
if (axisValid(axisId))
{
if ( maxMajor < 1 )
maxMajor = 1;
if ( maxMajor > 1000 )
maxMajor = 10000;
AxisData &d = *d_axisData[axisId];
if ( maxMajor != d.maxMinor )
{
d.maxMajor = maxMajor;
d.scaleDiv.invalidate();
autoRefresh();
}
}
}
/*!
\brief Change the title of a specified axis
\param axisId axis index
\param title axis title
*/
void QwtPlot::setAxisTitle(int axisId, const QString &title)
{
if (axisValid(axisId))
axisWidget(axisId)->setTitle(title);
}
/*!
\brief Change the title of a specified axis
\param axisId axis index
\param title axis title
*/
void QwtPlot::setAxisTitle(int axisId, const QwtText &title)
{
if (axisValid(axisId))
axisWidget(axisId)->setTitle(title);
}
//! Rebuild the scales and maps
void QwtPlot::updateAxes()
{
// Find bounding interval of the item data
// for all axes, where autoscaling is enabled
QwtDoubleInterval intv[axisCnt];
const QwtPlotItemList& itmList = itemList();
QwtPlotItemIterator it;
for ( it = itmList.begin(); it != itmList.end(); ++it )
{
const QwtPlotItem *item = *it;
if ( !item->testItemAttribute(QwtPlotItem::AutoScale) )
continue;
if ( axisAutoScale(item->xAxis()) || axisAutoScale(item->yAxis()) )
{
const QwtDoubleRect rect = item->boundingRect();
intv[item->xAxis()] |= QwtDoubleInterval(rect.left(), rect.right());
intv[item->yAxis()] |= QwtDoubleInterval(rect.top(), rect.bottom());
}
}
// Adjust scales
for (int axisId = 0; axisId < axisCnt; axisId++)
{
AxisData &d = *d_axisData[axisId];
double minValue = d.minValue;
double maxValue = d.maxValue;
double stepSize = d.stepSize;
if ( d.doAutoScale && intv[axisId].isValid() )
{
d.scaleDiv.invalidate();
minValue = intv[axisId].minValue();
maxValue = intv[axisId].maxValue();
d.scaleEngine->autoScale(d.maxMajor,
minValue, maxValue, stepSize);
}
if ( !d.scaleDiv.isValid() )
{
d.scaleDiv = d.scaleEngine->divideScale(
minValue, maxValue,
d.maxMajor, d.maxMinor, stepSize);
}
QwtScaleWidget *scaleWidget = axisWidget(axisId);
scaleWidget->setScaleDiv(
d.scaleEngine->transformation(), d.scaleDiv);
int startDist, endDist;
scaleWidget->getBorderDistHint(startDist, endDist);
scaleWidget->setBorderDist(startDist, endDist);
}
for ( it = itmList.begin(); it != itmList.end(); ++it )
{
QwtPlotItem *item = *it;
item->updateScaleDiv( *axisScaleDiv(item->xAxis()),
*axisScaleDiv(item->yAxis()));
}
}
| [
"[email protected]@58180da6-ba8b-8960-36a5-00cc02a3ddec"
] | [
[
[
1,
603
]
]
] |
2a1d860354172ab1d91f73e964986481b5ca0635 | 7f30cb109e574560873a5eb8bb398c027f85eeee | /src/appData.h | b01b8bfee3216b439599bbea13e7c7eb5e9b3bd3 | [] | no_license | svn2github/MITO | e8fd0e0b6eebf26f2382f62660c06726419a9043 | 71d1269d7666151df52d6b5a98765676d992349a | refs/heads/master | 2021-01-10T03:13:55.083371 | 2011-10-14T15:40:14 | 2011-10-14T15:40:14 | 47,415,786 | 1 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 3,291 | h | /**
* \file appData.h
* \brief File per la gestione dei dati
* \author ICAR-CNR Napoli
*/
#ifndef _appData_h_
#define _appData_h_
#include <string>
using namespace std;
class wxArrayString;
/**
* \class appData
* \brief Classe astratta responsabile della gestione dei dati
*/
class appData {
protected:
/**
* \var int _idData
* \brief Identificatore del dato
*/
unsigned int _idData;
/**
* \var string _name
* \brief Nome del dato
*/
string _name;
public:
/** Costruttore */
appData();
/** Distruttore */
virtual ~appData();
/**
* \fn unsigned int getIdData()
* \brief Restituisce il valore della variabile _idData
* \return Valore della variabile _idData
*/
inline unsigned int getIdData() {
return _idData;
}
/**
* \fn void setIdData(unsigned int idData)
* \brief Assegna l'idData
* \param idData Identificativo del dato
*/
inline void setIdData(unsigned int idData) {
_idData = idData;
}
/**
* \fn string getName()
* \brief Restituisce il nome associato al dato
* \return Valore della variabile _name
*/
inline string getName() {
return _name;
}
/**
* \fn void setName(string name)
* \brief Assegna un nome al dato
* \param name Nome del dato
*/
inline void setName(string name) {
_name = name;
}
/**
* \fn virtual bool open(string fileName, bool read) = 0
* \brief Metodo virtuale puro: restituisce true se il file è aperto correttamente
* \param fileName Nome del file o della directory
* \param read indica se leggere l'immagine o sono l'header
* \return true se l'operazione è andata a buon fine
*/
virtual bool open(string fileName, bool read) = 0;
/**
* \fn virtual bool open(wxArrayString *pPaths, bool read) = 0
* \brief Metodo virtuale puro: restituisce true se il file è aperto correttamente
* \param pPaths Percorsi
* \param read indica se leggere l'immagine o sono l'header
* \return true se l'operazione è andata a buon fine
*/
virtual bool open(wxArrayString *pPaths, bool read) = 0;
/**
* \fn virtual int getHeaderLength() = 0
* \brief Metodo virtuale puro: restituisce la dimensione dell'header
* \return Dimensione dell'header
*/
virtual int getHeaderLength() = 0;
/**
* \fn virtual string getHeaderKey(int index) = 0
* \brief Metodo virtuale puro: restituisce una chiave dell'header
* \param index Indice del tag
* \return Chiave
*/
virtual string getHeaderKey(int index) = 0;
/**
* \fn virtual string getHeaderValue(int index) = 0
* \brief Metodo virtuale puro: restituisce il valore di un tag dell'header
* \param index Indice del tag
* \return Tag
*/
virtual string getHeaderValue(int index) = 0;
/**
* \fn virtual string getHeaderEntry(int index) = 0
* \brief Metodo virtuale puro: restituisce un entry dell'header
* \param index Indice dell'entry
* \return Entry
*/
virtual string getHeaderEntry(int index) = 0;
/**
* \fn virtual int getHeaderEntriesLength() = 0
* \brief Metodo virtuale puro: restituisce la dimensione degli entry dell'header
* \return Dimensione entry
*/
virtual int getHeaderEntriesLength() = 0;
};
#endif _appData_h_ | [
"kg_dexterp37@fde90bc1-0431-4138-8110-3f8199bc04de"
] | [
[
[
1,
136
]
]
] |
a246fd49e88dee57a6e5bbdce0c3d153d308aecd | 0b55a33f4df7593378f58b60faff6bac01ec27f3 | /Konstruct/Common/Utility/kpuRegistry.cpp | 505213c7f4d20e22c912d925a1472646159f5b80 | [] | no_license | RonOHara-GG/dimgame | 8d149ffac1b1176432a3cae4643ba2d07011dd8e | bbde89435683244133dca9743d652dabb9edf1a4 | refs/heads/master | 2021-01-10T21:05:40.480392 | 2010-09-01T20:46:40 | 2010-09-01T20:46:40 | 32,113,739 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,297 | cpp | #include "StdAfx.h"
#include "Common\Utility\kpuRegistry.h"
char kpuRegistry::sm_szBaseKey[512];
kpuRegistry::kpuRegistry(void)
{
}
kpuRegistry::~kpuRegistry(void)
{
}
void kpuRegistry::SetBaseKey(const char* szKey)
{
memcpy(sm_szBaseKey, szKey, sizeof(sm_szBaseKey));
}
bool kpuRegistry::GetNubmerValue(const char* szKey, u32& unVal)
{
HKEY hKey;
DWORD dwDispAndSize;
long lVal = RegCreateKeyEx(HKEY_CURRENT_USER, sm_szBaseKey, 0, 0, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, 0, &hKey, &dwDispAndSize);
if( lVal != ERROR_SUCCESS )
return false;
dwDispAndSize = sizeof(DWORD);
lVal = RegQueryValueEx(hKey, szKey, 0, 0, (BYTE*)&unVal, &dwDispAndSize);
RegCloseKey(hKey);
if( lVal != ERROR_SUCCESS )
return false;
return true;
}
bool kpuRegistry::GetStringValue(const char* szKey, char* szValue, int nValueLength)
{
HKEY hKey;
DWORD dwDispAndSize;
long lVal = RegCreateKeyEx(HKEY_CURRENT_USER, sm_szBaseKey, 0, 0, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, 0, &hKey, &dwDispAndSize);
if( lVal != ERROR_SUCCESS )
return false;
dwDispAndSize = (DWORD)nValueLength;
lVal = RegQueryValueEx(hKey, szKey, 0, 0, (BYTE*)szValue, &dwDispAndSize);
RegCloseKey(hKey);
if( lVal != ERROR_SUCCESS )
return false;
return true;
}
| [
"acid1789@0c57dbdb-4d19-7b8c-568b-3fe73d88484e"
] | [
[
[
1,
51
]
]
] |
a9d152e5d853b8ce552feeb45a2f5ea33b647c35 | ea12fed4c32e9c7992956419eb3e2bace91f063a | /zombie/code/zombie/ngrass/src/nvegetation/nvegetationnode_cmds.cc | 9b672c99145646733a433e26ca61755a55fdb73b | [] | no_license | ugozapad/TheZombieEngine | 832492930df28c28cd349673f79f3609b1fe7190 | 8e8c3e6225c2ed93e07287356def9fbdeacf3d6a | refs/heads/master | 2020-04-30T11:35:36.258363 | 2011-02-24T14:18:43 | 2011-02-24T14:18:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 873 | cc | #include "precompiled/pchngrass.h"
//------------------------------------------------------------------------------
// nvegetationnode_cmds.cc
// (C) 2004 Conjurer Services, S.A.
//------------------------------------------------------------------------------
#include "nvegetation/nvegetationnode.h"
#include "nvegetation/nvegetationnode.h"
#include "kernel/npersistserver.h"
//---------------------------------------------------------------------------
/**
*/
NSCRIPT_INITCMDS_BEGIN( nVegetationNode )
NSCRIPT_INITCMDS_END()
//---------------------------------------------------------------------------
/**
*/
bool
nVegetationNode::SaveCmds(nPersistServer * ps)
{
if (nGeometryNode::SaveCmds(ps))
{
return true;
}
return false;
}
//---------------------------------------------------------------------------
| [
"magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91"
] | [
[
[
1,
31
]
]
] |
8c8dc0891f703038ea9d6b7fd07f4281e82c8830 | 55196303f36aa20da255031a8f115b6af83e7d11 | /private/bikini/flash/player.cpp | b9075f14bf68b660c2987bd2ccad067cfeb3acce | [] | no_license | Heartbroken/bikini | 3f5447647d39587ffe15a7ae5badab3300d2a2ff | fe74f51a3a5d281c671d303632ff38be84d23dd7 | refs/heads/master | 2021-01-10T19:48:40.851837 | 2010-05-25T19:58:52 | 2010-05-25T19:58:52 | 37,190,932 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,468 | cpp | /*---------------------------------------------------------------------------------------------*//*
Binary Kinematics 3 - C++ Game Programming Library
Copyright (C) 2008-2010 Viktor Reutskyy
[email protected]
*//*---------------------------------------------------------------------------------------------*/
#include "header.hpp"
namespace bk { /*--------------------------------------------------------------------------------*/
namespace flash { /*-----------------------------------------------------------------------------*/
extern void build_line_mesh(const short2 _points[], uint _count, real _width, array_<short2> &_mesh);
bk::loader default_loader;
null_sensor default_sensor;
static const uint small_mesh_size = 100;
// gameswf callbacks
struct player::_private : gameswf::render_handler
{
// loading ------------------------------------------------------------------------------------
static loader *loader_p;
static inline s32 read(handle _buffer, s32 _length, handle _ID) { return (s32)loader_p->read((uint)_ID, _buffer, _length); }
static inline s32 write(pointer _buffer, s32 _length, handle _ID) { assert(0); return 0; }
static inline s32 seek(s32 _offset, handle _ID) { return (s32)loader_p->seek((uint)_ID, _offset, 0); }
static inline s32 seek_to_end(handle _ID) { return (s32)loader_p->seek((uint)_ID, 0, 2); }
static inline s32 tell(pointer _ID) { return (s32)loader_p->seek((uint)_ID, 0, 1); }
static inline bool get_eof(handle _ID) { return false; }
static inline s32 close(handle _ID) { loader_p->close((uint)_ID); return 0; }
static tu_file* open(const char* _path)
{
uint l_alength = strlen(_path) + 1;
uint l_wlength = MultiByteToWideChar(CP_UTF8, 0, _path, (s32)l_alength, 0, 0);
wchar* l_path = (wchar*)_malloca(l_wlength * sizeof(wchar));
MultiByteToWideChar(CP_UTF8, 0, _path, (s32)l_alength, l_path, (s32)l_wlength);
uint l_ID = loader_p->open(l_path);
return new tu_file((handle)l_ID, &read, &write, &seek, &seek_to_end, &tell, &get_eof, &close);
}
// log ----------------------------------------------------------------------------------------
static void log(bool _error, const char* _message)
{
if (_error) std::cerr << _message;
else std::cout << _message;
}
// fscommand ----------------------------------------------------------------------------------
static void fscommand(gameswf::character* _movie, const char* _command, const char* _arg)
{
std::cout << "command: '" << _command << "' arg: '" << _arg << "'\n";
}
// rendering ----------------------------------------------------------------------------------
// gameswf types
typedef gameswf::bitmap_info bitmap_info;
typedef gameswf::mesh_info mesh_info;
typedef gameswf::video_handler video_handler;
typedef gameswf::rgba rgba;
typedef gameswf::matrix matrix;
typedef gameswf::cxform cxform;
typedef gameswf::rect rect;
// state variables
static renderer *renderer_p;
// bitmap
struct bitmap : bitmap_info
{
uint texture_ID;
inline bitmap()
:
texture_ID(bad_ID)
{}
inline bitmap(sint _w, sint _h, u8* _data)
{
texture_ID = renderer_p->create_texture(video::tf::a8, _data, (uint)_w, (uint)_h, (uint)_h);
}
inline bitmap(image::rgb* _data)
{
texture_ID = renderer_p->create_texture(video::tf::b8g8r8, _data->m_data, (uint)_data->m_width, (uint)_data->m_height, (uint)_data->m_pitch);
}
inline bitmap(image::rgba* _data)
{
texture_ID = renderer_p->create_texture(video::tf::a8b8g8r8, _data->m_data, (uint)_data->m_width, (uint)_data->m_height, (uint)_data->m_pitch);
}
~bitmap()
{
if (renderer_p) renderer_p->destroy_texture(texture_ID);
}
};
// mesh
struct mesh : mesh_info
{
uint mesh_ID;
inline mesh()
:
mesh_ID(bad_ID)
{}
inline mesh(pointer _coords, uint _vertex_count)
{
mesh_ID = renderer_p ? renderer_p->create_mesh((short2*)_coords, _vertex_count) : bad_ID;
}
~mesh()
{
if (renderer_p) renderer_p->destroy_mesh(mesh_ID);
}
};
// overrides
// Your handler should return these with a ref-count of 0. (@@ is that the right policy?)
bitmap_info* create_bitmap_info_empty() // used when DO_NOT_LOAD_BITMAPS is set
{
return new bitmap;
}
bitmap_info* create_bitmap_info_alpha(s32 _w, s32 _h, u8* _data)
{
return new bitmap(_w, _h, _data);
}
bitmap_info* create_bitmap_info_rgb(image::rgb* _data)
{
return new bitmap(_data);
}
bitmap_info* create_bitmap_info_rgba(image::rgba* _data)
{
return new bitmap(_data);
}
video_handler* create_video_handler()
{
return 0;
}
// <viktor.reutskyy>
mesh_info* create_mesh_info_tristrip(pointer _coords, s32 _vertex_count)
{
if (_vertex_count <= small_mesh_size) return 0;
return new mesh(_coords, _vertex_count);
}
mesh_info* create_mesh_info_linestrip(pointer _coords, s32 _vertex_count, f32 _width)
{
static array_<short2> l_mesh; l_mesh.resize(0);
build_line_mesh((short2*)_coords, _vertex_count, _width, l_mesh);
if (l_mesh.size() <= small_mesh_size) return 0;
return new mesh(&l_mesh[0], l_mesh.size());
}
// Bracket the displaying of a frame from a movie.
// Fill the background color, and set up default
// transforms, etc.
void begin_display(rgba _background_color, s32 _viewport_x0, s32 _viewport_y0, s32 _viewport_width, s32 _viewport_height, f32 _x0, f32 _x1, f32 _y0, f32 _y1)
{
color l_background(_background_color.m_r, _background_color.m_g, _background_color.m_b, _background_color.m_a);
bk::rect l_viewport((sint)_x0, (sint)_y0, (sint)(_x1 - _x0), (sint)(_y1 - _y0));
m_renderer.begin_render(l_background, l_viewport);
}
void end_display()
{
m_renderer.end_render();
}
// Geometric and color transforms for mesh and line_strip rendering.
void set_matrix(const matrix &_m)
{
xform l_xform(_m.m_[0][0], _m.m_[0][1], _m.m_[0][2],
_m.m_[1][0], _m.m_[1][1], _m.m_[1][2]);
m_renderer.set_xform(l_xform);
}
void set_cxform(const cxform &_cx)
{
//m_cxform = _cx;
}
// Draw triangles using the current fill-style 0.
// Clears the style list after rendering.
//
// coords is a list of (x,y) coordinate pairs, in
// triangle-strip order. The type of the array should
// be Sint16[vertex_count*2]
void draw_mesh_strip(pointer _coords, s32 _vertex_count)
{
m_renderer.draw_tristrip((short2*)_coords, (uint)_vertex_count);
}
// As above, but coords is in triangle list order.
void draw_triangle_list(pointer _coords, s32 _vertex_count)
{
}
// Draw a line-strip using the current line style.
// Clear the style list after rendering.
//
// Coords is a list of (x,y) coordinate pairs, in
// sequence. Each coord is a 16-bit signed integer.
void draw_line_strip(pointer _coords, s32 _vertex_count)
{
static array_<short2> l_mesh; l_mesh.resize(0);
build_line_mesh((short2*)_coords, _vertex_count, m_line_width, l_mesh);
if (!l_mesh.empty())
m_renderer.draw_tristrip(&l_mesh[0], l_mesh.size());
}
// Draw mesh
void draw_mesh(const mesh_info *_mesh)
{
m_renderer.draw_mesh(static_cast<const mesh*>(_mesh)->mesh_ID);
}
// Set line and fill styles for mesh & line_strip
// rendering.
void fill_style_disable(s32 _fill_side)
{
m_renderer.set_texture(bad_ID, xform());
}
void fill_style_color(s32 _fill_side, const rgba &_color)
{
color l_color(_color.m_r, _color.m_g, _color.m_b, _color.m_a);
m_renderer.set_color(l_color);
m_renderer.set_texture(bad_ID, xform());
}
void fill_style_bitmap(s32 _fill_side, bitmap_info *_bi_p, const matrix &_m, bitmap_wrap_mode _wm)
{
bitmap &l_bitmap = *(bitmap*)_bi_p;
xform l_txform(_m.m_[0][0], _m.m_[0][1], _m.m_[0][2], _m.m_[1][0], _m.m_[1][1], _m.m_[1][2]);
m_renderer.set_texture(l_bitmap.texture_ID, l_txform);
m_renderer.set_color(white);
}
void line_style_disable()
{
}
void line_style_color(rgba _color)
{
color l_color(_color.m_r, _color.m_g, _color.m_b, _color.m_a);
m_renderer.set_color(l_color);
m_renderer.set_texture(bad_ID, xform());
}
void line_style_width(f32 _width)
{
m_line_width = (real)_width;
}
// Special function to draw a rectangular bitmap;
// intended for textured glyph rendering. Ignores
// current transforms.
void draw_bitmap(const matrix &_m, bitmap_info *_bi_p, const rect &_coords, const rect &_uv_coords, rgba _color)
{
}
void set_antialiased(bool _enable)
{
}
void begin_submit_mask()
{
}
void end_submit_mask()
{
}
void disable_mask()
{
}
// Mouse cursor handling.
void set_cursor(cursor_type _cursor)
{
}
bool is_visible(const rect &_bound)
{
return true;
}
void open()
{
}
// members
sensor &m_sensor;
loader &m_loader;
renderer &m_renderer;
gameswf::player &m_player;
real m_line_width;
_private(renderer &_renderer, sensor &_sensor, loader &_loader)
:
m_renderer(_renderer), m_sensor(_sensor), m_loader(_loader),
m_player(* new gameswf::player())
{
m_player.add_ref();
gameswf::register_file_opener_callback(&_private::open);
m_sensor.set_hittest(hittest(*this, &_private::do_hittest));
}
~_private()
{
stop();
m_player.drop_ref();
delete &m_renderer;
delete &m_sensor;
delete &m_loader;
}
void set_handlers()
{
loader_p = &m_loader;
renderer_p = &m_renderer;
gameswf::set_render_handler(this);
gameswf::register_log_callback(log);
gameswf::register_fscommand_callback(fscommand);
}
void reset_handlers()
{
loader_p = 0;
renderer_p = 0;
gameswf::set_render_handler(0);
gameswf::register_log_callback(0);
gameswf::register_fscommand_callback(0);
}
bool play(const achar* _path)
{
set_handlers();
smart_ptr<gameswf::root> l_movie = m_player.load_file(_path);
//l_movie->set_display_viewport(0, 0, 800, 600);
reset_handlers();
if (l_movie == 0) return false;
l_movie->add_ref();
return true;
}
bool pause(bool _yes)
{
if (m_player.get_root() == 0) return false;
set_handlers();
m_player.get_root()->set_play_state(_yes ? gameswf::character::PLAY : gameswf::character::STOP);
reset_handlers();
return true;
}
bool stop()
{
if (m_player.get_root() == 0) return false;
set_handlers();
m_player.get_root()->drop_ref();
reset_handlers();
return true;
}
bool update(real _dt)
{
set_handlers();
short2 l_point; bool l_button;
m_sensor.mouse_state(l_point, l_button);
m_player.get_root()->notify_mouse_state(l_point.x, l_point.y, l_button ? 1 : 0);
m_player.get_root()->advance(_dt);
reset_handlers();
return true;
}
bool render()
{
set_handlers();
m_player.get_root()->display();
reset_handlers();
return true;
}
bool do_hittest(const short2 &_point)
{
if (m_player.get_root() == 0) return false;
return m_player.get_root()->get_root_movie()->get_topmost_mouse_entity(PIXELS_TO_TWIPS(_point.x), PIXELS_TO_TWIPS(_point.y)) != 0;
}
};
player::loader *player::_private::loader_p = 0;
player::renderer *player::_private::renderer_p = 0;
// player
player::player()
:
m_private(0)
{}
player::~player()
{}
bool player::create(renderer &_renderer, sensor &_sensor, loader &_loader)
{
m_private = new _private(_renderer, _sensor, _loader);
return true;
}
bool player::update(real _dt)
{
return m_private->update(_dt);
}
bool player::render() const
{
return m_private->render();
}
void player::destroy()
{
delete m_private;
m_private = 0;
}
bool player::play(const astring &_path)
{
return m_private->play(_path.c_str());
}
bool player::play(const wstring &_path)
{
uint l_wlength = _path.length() + 1;
uint l_alength = WideCharToMultiByte(CP_UTF8, 0, _path.c_str(), (s32)l_wlength, 0, 0, 0, 0);
achar* l_path = (achar*)_malloca(l_alength * sizeof(achar));
WideCharToMultiByte(CP_UTF8, 0, _path.c_str(), (int)l_wlength, l_path, (int)l_alength, 0, 0);
return m_private->play(l_path);
}
bool player::pause(bool _yes)
{
return m_private->pause(_yes);
}
bool player::stop()
{
return m_private->stop();
}
} /* namespace flash ----------------------------------------------------------------------------*/
} /* namespace bk -------------------------------------------------------------------------------*/
| [
"viktor.reutskyy@68c2588f-494f-0410-aecb-65da31d84587"
] | [
[
[
1,
436
]
]
] |
d364600903f9e490be95830aefaac5adb5e71cfd | be3d7c318d79cd33d306aba58a1159147cac91fd | /modules/wgd_models/src/modelx.cpp | 27d9b13ea71396e3fe73bb02b8e7a9632bf8a8b9 | [] | no_license | knicos/Cadence | 827149b53bb3e92fe532b0ad4234b7d0de11ca43 | 7e1e1cf1bae664f77afce63407b61c7b2b0a4fff | refs/heads/master | 2020-05-29T13:19:07.595099 | 2011-10-31T13:05:48 | 2011-10-31T13:05:48 | 1,238,039 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,861 | cpp | #include <wgd/modelx.h>
#include <vector>
#include <wgd/bone.h>
#include <wgd/mesh.h>
#include <wgd/material.h>
#include <wgd/colour.h>
#include <wgd/vertex.h>
#include <wgd/animationset.h>
using namespace wgd;
using namespace cadence;
using namespace cadence::token;
static const cadence::token::Char<1> semi(';');
static const cadence::token::Char<1> comma(',');
bool ModelX::validate(File *file){
if(file->parse(Keyword("xof"))){
file->seek(5);
bool valid = file->parse(Keyword("txt 0032"));
if(!valid) Warning(0, "Invalid .x file");
file->seek(0, Stream::BEG);
return valid;
}
return false;
}
void ModelX::load(){
std::cout << "Loading Model " << file()->filename() << "\n";
file()->open(File::READ);
file()->seek(16);
//main loop
while(!file()->eof()){
parseJunk();
if(file()->eof()) break;
if(parse(Keyword("template"))) skipBlock();
else if(parse(Keyword("Frame"))) readFrame(createBone(ix::root));
else if(parse(Keyword("Mesh"))) readMesh(Null);
else if(parse(Keyword("AnimationSet"))) readAnimationSet();
else if(parse(AlphaNumericX())) skipBlock();
else Error(0, "ModelX: Some crazy error of doom");
}
file()->close();
}
void ModelX::skipBlock(){
startBlock();
endBlock();
}
OID ModelX::startBlock(){
token::AlphaNumericX name;
parse(WhiteSpace());
parseValue(name);
parse(WhiteSpace());
parse(Char<1>('{'));
return (name.value)? OID(name.value) : Null;
}
void ModelX::endBlock(){
int count=1;
while(count>0 && !file()->eof()) {
if(parse(Char<1>('{'))) count++;
else if(parse(Char<1>('}'))) count--;
else file()->seek(1);
}
}
OID ModelX::readInline(){
AlphaNumericX s;
parseJunk();
parseValue(s);
parse(Block<-1>('}'));
return (s.value)? OID(s.value) : Null;
}
void ModelX::readFrame(Bone *parent){
OID name = startBlock();
Bone *cBone;
ALIGNVS float tMatrix[16] ALIGNED;
//create bone
cBone = createBone(name);
parent->addChild(name);
while(!file()->eof()){
parseJunk();
if(parse(Keyword("FrameTransformMatrix"))){
startBlock();
readMatrix(tMatrix);
cBone->tMatrix(tMatrix);
endBlock();
} else if(parse(Keyword("Frame"))) readFrame(cBone);
else if(parse(Keyword("Mesh"))) readMesh(name);
else if(parse(Char<1>('{'))) readInline(); //Mesh reference - ignore for now (and probably forever)
else break;
}
endBlock();
}
void ModelX::readMatrix(float* m){
token::Float f;
for(int i=0; i<16; i++){
parseJunk();
parseValue(f);
m[i] = f.value;
parse(Char<1>(','));
parse(WhiteSpace());
}
}
vector3d ModelX::readVector(int n){ return parseVector(n, semi); }
void ModelX::readMesh(const OID& boneName){
int nVertices=0;
vector3d *vertices = NULL;
vector3d *normals = NULL;
vector2d *uvs = NULL;
int nFaces=0;
int *faces = NULL;
int *matList = NULL;
OID *materials = NULL;
int *duplication = NULL;
int weights = 0;
MeshSkin *skin = NULL;
//The actual parsing...
OID name = startBlock();
nVertices = readVertices(vertices);
nFaces = readFaces(faces, duplication);
//sub blocks
while(!file()->eof()){
parseJunk();
if(parse(Keyword("MeshNormals"))) readNormals(normals);
else if(parse(Keyword("MeshTextureCoords"))) readTexCoords(uvs);
else if(parse(Keyword("MeshMaterialList"))) readMaterials(nFaces, matList, materials, duplication);
else if(parse(Keyword("XSkinMeshHeader"))) {
weights = readSkinHeader(skin);
skin = new MeshSkin[weights * nVertices];
memset(skin, 0, weights * nVertices * sizeof(MeshSkin));
}else if(parse(Keyword("SkinWeights"))) readSkin(skin, weights);
else if(parse(Keyword("VertexDuplicationIndices"))) skipBlock();
else break;
}
//Process mesh (divide it into sub meshes per material - also fo any flipping stuff)
processMesh(boneName, nFaces, faces, vertices, normals, uvs, matList, materials, weights, skin);
endBlock();
}
int ModelX::readVertices(vector3d *& vertices){
token::Integer<10> tint;
parseJunk();
int nVertices=0;
//if(!parseValue(tint)) return 0;
if(!tint.parse(*file())) return 0;
nVertices = (int)tint.value;
parse(semi);
vertices = new vector3d[nVertices];
for(int i=0; i<nVertices; i++){
vertices[i] = readVector();
parse(comma);
}
parse(semi);
return nVertices;
}
int ModelX::readFaces(int *& faces, int *& duplication){
token::Integer<10> tint;
std::vector<int> tfaces;
std::vector<int> tduplication;
int nFaces, sides;
int f[2] = {-1, -1};
parseJunk();
//char a = file()->peek(); //no idea
//char b = file()->peek(1);
if(!parseValue(tint)) return 0;
nFaces = (int)tint.value;
parse(semi);
for(int i=0; i<nFaces; i++){
parseJunk();
parseValue(tint); parse(semi);
sides = (int)tint.value;
for(int j = 0; j<sides; j++){
parseJunk();
parseValue(tint); parse(comma);
if(j<2) f[j] = (int)tint.value;
else {
tfaces.push_back(f[0]);
tfaces.push_back(f[1]);
tfaces.push_back((int)tint.value);
f[1] = (int)tint.value;
}
// Record if there are extra faces added to fix material list
if(j>2) {
tduplication.push_back(i);
}
}
parse(semi);
parse(comma);
}
parse(semi);
//return data
faces = new int[tfaces.size()];
memcpy(faces, &tfaces[0], tfaces.size() * sizeof(int));
//material duplication
tduplication.push_back(-1);
duplication = new int[tduplication.size()];
memcpy(duplication, &tduplication[0], tduplication.size() * sizeof(int));
//return number of triangles
return tfaces.size() / 3;
}
int ModelX::readNormals(wgd::vector3d *& normals){
token::Integer<10> tint;
startBlock();
parseJunk();
int nNormals=0;
parseValue(tint); parse(semi); nNormals = (int)tint.value;
normals = new vector3d[nNormals];
for(int i=0; i<nNormals; i++){
normals[i] = readVector();
parse(comma);
}
parse(semi);
endBlock();
return nNormals;
}
int ModelX::readTexCoords(wgd::vector2d *& uvs){
token::Integer<10> tint;
startBlock();
parseJunk();
int nUVs=0;
parseValue(tint); parse(semi); nUVs = (int)tint.value;
uvs = new vector2d[nUVs];
for(int i=0; i<nUVs; i++){
uvs[i] = readVector(2);
parse(comma);
}
parse(semi);
endBlock();
return nUVs;
}
int ModelX::readMaterials(int count, int *&matID, OID *& material, int *& duplication){
//count=number of triangles (may be different from faces), duplication=indices to be duplicated
//This one is slightly different
token::Integer<10> tint;
startBlock();
parseJunk();
int nFaces=0;
int nMaterials=0;
parseValue(tint); parse(semi); nMaterials = (int)tint.value;
parseJunk();
parseValue(tint); parse(semi); nFaces = (int)tint.value;
int index=0, dix=0;
matID = new int[count];
for(int i=0; i<nFaces; i++){
parseJunk();
parseValue(tint); parse(comma);
matID[index++] = (int)tint.value;
//duplicated indices
while(duplication[dix]==i) {
matID[index++] = (int)tint.value;
dix++;
}
}
parse(semi);
parse(semi); //coz blender is crap
//Materials defined here
material = new OID[nMaterials];
for(int i=0; i<nMaterials; i++){
parseJunk();
if(parse(Keyword("Material"))) material[i] = readMaterial();
else if(parse(Char<1>('{'))) material[i] = readInline();
}
endBlock();
return nMaterials;
}
OID ModelX::readMaterial(){
token::Float tfloat;
vector3d v;
OID name = startBlock();
//Create the material resource
Material *mat = createMaterial(name);
//diffuse (ambient)
parseJunk();
v = readVector(4);
if(mat->get(ix::diffuse)==Null) mat->diffuse(colour(v.x, v.y, v.z, v.w));
if(mat->get(ix::ambient)==Null) mat->ambient(colour(v.x/3.0f, v.y/3.0f, v.z/3.0f, 1.0));
parse(semi);
//Shininess
parseJunk();
parseValue(tfloat);
if(mat->get(ix::shininess)==Null) {
mat->shininess(tfloat.value);
//Blender bug - this value is between 0-2 rather than 0-128:
if(tfloat.value > 0.0 && tfloat.value < 1.0) mat->shininess(tfloat.value * 64.0f);
}
parse(semi);
//specular
parseJunk();
v = readVector();
if(mat->get(ix::specular)==Null) mat->specular(colour(v.x, v.y, v.z, 1.0));
parse(semi);
//emmissive
parseJunk();
v = readVector();
if(mat->get(ix::emission)==Null) mat->emission(colour(v.x, v.y, v.z, 1.0));
parse(semi);
//Texture
parseJunk();
if(parse(Keyword("TextureFilename"))){
startBlock();
parseJunk();
//read string (append to directory(file()->localFile(), buf); and save)
Block<-1> texFile('"', '"');
parseValue(texFile);
//create texture
if(mat->texture()==NULL || mat->texture()->file()==NULL){
char tdir[128];
directory((const char*)file()->filename(), tdir);
dstring tf(tdir); tf + texFile.value;
if(mat->texture()==NULL) mat->texture(new Texture);
mat->texture()->file(new LocalFile((const char*)tf));
}
endBlock();
}
endBlock();
return name;
}
int ModelX::readSkinHeader(wgd::MeshSkin *&){
startBlock();
parseJunk();
Integer<10> wpv;
parseValue(wpv);
endBlock();
return (int)wpv.value;
}
int ModelX::readSkin(wgd::MeshSkin *&skin, int weights){
Block<-1> boneName('"', '"');
Integer<10> count;
Integer<10> tint;
Float tfloat;
startBlock();
parseJunk();
parseValue(boneName); parse(semi);
Bone *bone = createBone(boneName.value);
parseJunk();
parseValue(count); parse(semi);
int *index = new int[(int)count.value];
for(int i=0; i<(int)count.value; i++){
parseJunk();
parseValue(tint);
parse(comma);
index[i] = (int)tint.value;
}
parse(semi);
for(int i=0; i<(int)count.value; i++){
parseJunk();
parseValue(tfloat);
parse(comma);
for(int j=0; j<weights; j++){
if(skin[index[i] * weights + j].weight==0.0){
skin[index[i] * weights + j].weight = tfloat.value;
skin[index[i] * weights + j].bone = bone;
break;
}
}
}
parse(semi);
ALIGNVS float mat[16] ALIGNED;
readMatrix(mat);
bone->sMatrix(mat);
endBlock();
return (int) count.value;
}
void ModelX::processMesh(const OID& boneName, int nfaces, int *f, wgd::vector3d *v, wgd::vector3d *n, wgd::vector2d *uv, int *m, OID *mat, int w, MeshSkin *skin){
int offset=0;
while(offset < nfaces){
//see how many faces in this material
int num = 0, cmat = m[offset];
for(int i=offset; i<=nfaces; i++){
if(m[i]!=cmat || i==nfaces) { num = i-offset; break; }
}
//create mesh
if(num>0){
//copy vertex data
MeshSkin *s=0;
vertex_t *vx = new vertex_t[num * 3];
if(w) s = new MeshSkin[num * 3 * w];
for(int i=0; i<num * 3; i++){
int ix = f[i + offset*3];
vx[i].position.x = v[ix].x;
vx[i].position.y = v[ix].y;
vx[i].position.z = v[ix].z;
if(n){
vx[i].normal.x = n[ix].x;
vx[i].normal.y = n[ix].y;
vx[i].normal.z = n[ix].z;
}
if(uv){
vx[i].texcoords[0].u = uv[ix].x;
vx[i].texcoords[0].v = 1.0f - uv[ix].y;
}
if(w){
for(int j=0; j<w; j++){
s[i*w + j].bone = skin[ix*w + j].bone;
s[i*w + j].weight = skin[ix*w + j].weight;
//check for non-skin
if(j==0 && s[i*w].weight==0.0){
s[i*w].weight = 1.0;
if(boneName==Null) s[i*w].bone = createBone(ix::root);
else s[i*w].bone = createBone(boneName);
}
}
}
}
//Save mesh to the model
Mesh *m = createMesh();
m->vertices(num * 3, vx);
m->skin(w, s);
//std::cout << "CMAT = " << cmat << "\n";
OID mate = mat[cmat];
m->material(mate);
if(boneName!=Null) m->bone(boneName);
offset += num;
}
}
}
void ModelX::readAnimationSet(){
OID name = startBlock();
//create animation set
AnimationSet *set = createAnimation(name);
while(!file()->eof()){
parseJunk();
if(parse(Keyword("Animation"))) readAnimation(set);
else break;
}
endBlock();
}
void ModelX::readAnimation(AnimationSet *set){
OID name = startBlock();
OID boneName;
//get bone it applies to
parseJunk();
if(parse(Char<1>('{'))) boneName = readInline();
if(boneName==Null){
Error(0, "ModelX: No frame defined for animation");
endBlock();
return;
}
int bID = createBone(boneName)->bid();
//Read Keyframes
while(!file()->eof()){
parseJunk();
if(parse(Keyword("AnimationKey"))) readAnimationKey(set, bID);
else break;
}
endBlock();
}
void ModelX::readAnimationKey(AnimationSet*set, int bone){
token::Integer<10> tint;
int type, keys, frame, size;
vector3d v;
startBlock();
//type
parseJunk(); parseValue(tint); parse(semi);
type = (int)tint.value;
//Invalid type
if(type==4){
Error(0, "ModelX: Cannot use matrix keys for animation");
endBlock();
return;
}
//number of keyframes
parseJunk(); parseValue(tint); parse(semi);
keys = (int)tint.value;
for(int i=0; i<keys; i++){
//keyframe
parseJunk(); parseValue(tint); parse(semi);
frame = (int)tint.value;
//num values
parseJunk(); parseValue(tint); parse(semi);
size = (int)tint.value;
//data
v = parseVector(size, comma);
parse(semi); parse(semi); parse(comma);
switch(type){
// Note: quaternions are in a strange order - see version 2
case 0: set->keyOrientation(bone, frame, quaternion(v.y, v.z, v.w, -v.x)); break; //Rotation Keys
case 1: set->keyScale(bone, frame, v); break; //Scale keys
case 2: set->keyPosition(bone, frame, v); break; //position keys
}
}
parse(semi);
endBlock();
}
| [
"[email protected]"
] | [
[
[
1,
610
]
]
] |
07ca197fc4059be0305fa804ffccd350ae45cdc0 | 40920d4672465672653eb2c3c6f0c233a2b09a29 | /imgpack/uImagePlaner.cpp | 515b764ae628964b683fc64883b6e37770fe6253 | [] | no_license | Letractively/imgpack | 70c6786724b80bedbbe9c52813931fc2f4b8bdba | f0504c829d21f6d20e891f7b5208cb40cb5e1c8f | refs/heads/master | 2021-01-10T16:55:16.212558 | 2011-11-14T20:25:32 | 2011-11-14T20:25:32 | 46,196,516 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,033 | cpp | // ImagePacker by DAS ( [email protected] )
#include <algorithm>
#include "uImagePlaner.h"
///////////////////////////////////////////////////////////////////////////
void uImagePlaner::add(int x, int y, const std::string imgName)
{
uImageRect img;
img.sizeX = x;
img.sizeY = y;
img.name = imgName;
rectList.push_back(img);
if((x > startTextureSize) || (y > startTextureSize))
startTextureSize = getTextureSize( (x > y) ? x : y );
if((x > 1024) || (y > 1024))
maxTextureSize = 2048;
// if((x > 2048) && (y > 2048))
// ERROR
}
///////////////////////////////////////////////////////////////////////////
int uImagePlaner::getTextureSize(int imgSize)
{
int i = 1;
while(i < imgSize)
i *= 2;
return i;
}
///////////////////////////////////////////////////////////////////////////
int uImagePlaner::fillRect(int minX, int maxX, int minY, int maxY, uImageRectList::iterator start)
{
start--;
int rectW = maxX - minX;
int rectH = maxY - minY;
if(rectH < calcList[0].sizeY) return maxY;
if(rectW < calcList[0].sizeX) return maxY;
for(uImageRectList::iterator i = start; i != calcList.begin(); i--)
if((!i->done) && (i->sizeY <= rectH) && (i->sizeX <= rectW)) {
i->done = true;
i->rectMinX = minX;
i->rectMinY = minY;
i->rectMaxX = minX + i->sizeX;
i->rectMaxY = minY + i->sizeY;
fillRect(i->rectMaxX, maxX, minY, i->rectMaxY, i);
fillRect(minX, maxX, i->rectMaxY, maxY, i);
return i->rectMaxY;
}
if(start == calcList.begin())
if((!start->done) && (start->sizeY <= rectH) && (start->sizeX <= rectW)) {
start->done = true;
start->rectMinX = minX;
start->rectMinY = minY;
start->rectMaxX = minX + start->sizeX;
start->rectMaxY = minY + start->sizeY;
}
return -1;
}
///////////////////////////////////////////////////////////////////////////
bool uImagePlaner::isDone()
{
for(uImageRectList::iterator i = calcList.begin(); i != calcList.end(); i++)
if(i->done)
return true;
return false;
}
///////////////////////////////////////////////////////////////////////////
void uImagePlaner::calc()
{
int sizeXY = 0;
for(uImageRectList::iterator i = rectList.begin(); i != rectList.end(); i++)
sizeXY += i->sizeX * i->sizeY;
int x = startTextureSize;
int y = startTextureSize;
while(true) {
if(((x * y) >= sizeXY) || ((x == maxTextureSize) && (y == maxTextureSize))) {
calcList = rectList;
std::sort(calcList.begin(), calcList.end());
fillRect(0, x, 0, y, calcList.end());
if(isDone()) {
outSizeX = x;
outSizeY = y;
return;
}
}
y = x = x * 2;
if(x > maxTextureSize)
x = maxTextureSize;
if(y > maxTextureSize)
y = maxTextureSize;
}
/*
outSizeX = MAX_TEXTURE_SIZE;
outSizeY = MAX_TEXTURE_SIZE;
calcList = rectList;
std::sort(calcList.begin(), calcList.end());
fillRect(0, MAX_TEXTURE_SIZE, 0, MAX_TEXTURE_SIZE, calcList.end());
*/
}
| [
"[email protected]"
] | [
[
[
1,
135
]
]
] |
fdbe7526bdfa0578c9635aaa7e952d341ef12360 | a2ba072a87ab830f5343022ed11b4ac365f58ef0 | / urt-bumpy-q3map2 --username [email protected]/libs/jpeg6/jdsample.cpp | a15e252c7a8c5684fc21824f95cb38e9cd94f2b1 | [] | no_license | Garey27/urt-bumpy-q3map2 | 7d0849fc8eb333d9007213b641138e8517aa092a | fcc567a04facada74f60306c01e68f410cb5a111 | refs/heads/master | 2021-01-10T17:24:51.991794 | 2010-06-22T13:19:24 | 2010-06-22T13:19:24 | 43,057,943 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,813 | cpp | /*
* jdsample.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 upsampling routines.
*
* Upsampling input data is counted in "row groups". A row group
* is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
* sample rows of each component. Upsampling will normally produce
* max_v_samp_factor pixel rows from each row group (but this could vary
* if the upsampler is applying a scale factor of its own).
*
* An excellent reference for image resampling is
* Digital Image Warping, George Wolberg, 1990.
* Pub. by IEEE Computer Society Press, Los Alamitos, CA. ISBN 0-8186-8944-7.
*/
#define JPEG_INTERNALS
#include "jinclude.h"
#include "radiant_jpeglib.h"
/* Pointer to routine to upsample a single component */
typedef JMETHOD(void, upsample1_ptr,
(j_decompress_ptr cinfo, jpeg_component_info * compptr,
JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));
/* Private subobject */
typedef struct {
struct jpeg_upsampler pub; /* public fields */
/* Color conversion buffer. When using separate upsampling and color
* conversion steps, this buffer holds one upsampled row group until it
* has been color converted and output.
* Note: we do not allocate any storage for component(s) which are full-size,
* ie do not need rescaling. The corresponding entry of color_buf[] is
* simply set to point to the input data array, thereby avoiding copying.
*/
JSAMPARRAY color_buf[MAX_COMPONENTS];
/* Per-component upsampling method pointers */
upsample1_ptr methods[MAX_COMPONENTS];
int next_row_out; /* counts rows emitted from color_buf */
JDIMENSION rows_to_go; /* counts rows remaining in image */
/* Height of an input row group for each component. */
int rowgroup_height[MAX_COMPONENTS];
/* These arrays save pixel expansion factors so that int_expand need not
* recompute them each time. They are unused for other upsampling methods.
*/
UINT8 h_expand[MAX_COMPONENTS];
UINT8 v_expand[MAX_COMPONENTS];
} my_upsampler;
typedef my_upsampler * my_upsample_ptr;
/*
* Initialize for an upsampling pass.
*/
METHODDEF void
start_pass_upsample (j_decompress_ptr cinfo)
{
my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
/* Mark the conversion buffer empty */
upsample->next_row_out = cinfo->max_v_samp_factor;
/* Initialize total-height counter for detecting bottom of image */
upsample->rows_to_go = cinfo->output_height;
}
/*
* Control routine to do upsampling (and color conversion).
*
* In this version we upsample each component independently.
* We upsample one row group into the conversion buffer, then apply
* color conversion a row at a time.
*/
METHODDEF void
sep_upsample (j_decompress_ptr cinfo,
JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
JDIMENSION in_row_groups_avail,
JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
JDIMENSION out_rows_avail)
{
my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
int ci;
jpeg_component_info * compptr;
JDIMENSION num_rows;
/* Fill the conversion buffer, if it's empty */
if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
ci++, compptr++) {
/* Invoke per-component upsample method. Notice we pass a POINTER
* to color_buf[ci], so that fullsize_upsample can change it.
*/
(*upsample->methods[ci]) (cinfo, compptr,
input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
upsample->color_buf + ci);
}
upsample->next_row_out = 0;
}
/* Color-convert and emit rows */
/* How many we have in the buffer: */
num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
/* Not more than the distance to the end of the image. Need this test
* in case the image height is not a multiple of max_v_samp_factor:
*/
if (num_rows > upsample->rows_to_go)
num_rows = upsample->rows_to_go;
/* And not more than what the client can accept: */
out_rows_avail -= *out_row_ctr;
if (num_rows > out_rows_avail)
num_rows = out_rows_avail;
(*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
(JDIMENSION) upsample->next_row_out,
output_buf + *out_row_ctr,
(int) num_rows);
/* Adjust counts */
*out_row_ctr += num_rows;
upsample->rows_to_go -= num_rows;
upsample->next_row_out += num_rows;
/* When the buffer is emptied, declare this input row group consumed */
if (upsample->next_row_out >= cinfo->max_v_samp_factor)
(*in_row_group_ctr)++;
}
/*
* These are the routines invoked by sep_upsample to upsample pixel values
* of a single component. One row group is processed per call.
*/
/*
* For full-size components, we just make color_buf[ci] point at the
* input buffer, and thus avoid copying any data. Note that this is
* safe only because sep_upsample doesn't declare the input row group
* "consumed" until we are done color converting and emitting it.
*/
METHODDEF void
fullsize_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
{
*output_data_ptr = input_data;
}
/*
* This is a no-op version used for "uninteresting" components.
* These components will not be referenced by color conversion.
*/
METHODDEF void
noop_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
{
*output_data_ptr = NULL; /* safety check */
}
/*
* This version handles any integral sampling ratios.
* This is not used for typical JPEG files, so it need not be fast.
* Nor, for that matter, is it particularly accurate: the algorithm is
* simple replication of the input pixel onto the corresponding output
* pixels. The hi-falutin sampling literature refers to this as a
* "box filter". A box filter tends to introduce visible artifacts,
* so if you are actually going to use 3:1 or 4:1 sampling ratios
* you would be well advised to improve this code.
*/
METHODDEF void
int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
{
my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
JSAMPARRAY output_data = *output_data_ptr;
register JSAMPROW inptr, outptr;
register JSAMPLE invalue;
register int h;
JSAMPROW outend;
int h_expand, v_expand;
int inrow, outrow;
h_expand = upsample->h_expand[compptr->component_index];
v_expand = upsample->v_expand[compptr->component_index];
inrow = outrow = 0;
while (outrow < cinfo->max_v_samp_factor) {
/* Generate one output row with proper horizontal expansion */
inptr = input_data[inrow];
outptr = output_data[outrow];
outend = outptr + cinfo->output_width;
while (outptr < outend) {
invalue = *inptr++; /* don't need GETJSAMPLE() here */
for (h = h_expand; h > 0; h--) {
*outptr++ = invalue;
}
}
/* Generate any additional output rows by duplicating the first one */
if (v_expand > 1) {
jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
v_expand-1, cinfo->output_width);
}
inrow++;
outrow += v_expand;
}
}
/*
* Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
* It's still a box filter.
*/
METHODDEF void
h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
{
JSAMPARRAY output_data = *output_data_ptr;
register JSAMPROW inptr, outptr;
register JSAMPLE invalue;
JSAMPROW outend;
int inrow;
for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
inptr = input_data[inrow];
outptr = output_data[inrow];
outend = outptr + cinfo->output_width;
while (outptr < outend) {
invalue = *inptr++; /* don't need GETJSAMPLE() here */
*outptr++ = invalue;
*outptr++ = invalue;
}
}
}
/*
* Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
* It's still a box filter.
*/
METHODDEF void
h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
{
JSAMPARRAY output_data = *output_data_ptr;
register JSAMPROW inptr, outptr;
register JSAMPLE invalue;
JSAMPROW outend;
int inrow, outrow;
inrow = outrow = 0;
while (outrow < cinfo->max_v_samp_factor) {
inptr = input_data[inrow];
outptr = output_data[outrow];
outend = outptr + cinfo->output_width;
while (outptr < outend) {
invalue = *inptr++; /* don't need GETJSAMPLE() here */
*outptr++ = invalue;
*outptr++ = invalue;
}
jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
1, cinfo->output_width);
inrow++;
outrow += 2;
}
}
/*
* Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
*
* The upsampling algorithm is linear interpolation between pixel centers,
* also known as a "triangle filter". This is a good compromise between
* speed and visual quality. The centers of the output pixels are 1/4 and 3/4
* of the way between input pixel centers.
*
* A note about the "bias" calculations: when rounding fractional values to
* integer, we do not want to always round 0.5 up to the next integer.
* If we did that, we'd introduce a noticeable bias towards larger values.
* Instead, this code is arranged so that 0.5 will be rounded up or down at
* alternate pixel locations (a simple ordered dither pattern).
*/
METHODDEF void
h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
{
JSAMPARRAY output_data = *output_data_ptr;
register JSAMPROW inptr, outptr;
register int invalue;
register JDIMENSION colctr;
int inrow;
for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
inptr = input_data[inrow];
outptr = output_data[inrow];
/* Special case for first column */
invalue = GETJSAMPLE(*inptr++);
*outptr++ = (JSAMPLE) invalue;
*outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
/* General case: 3/4 * nearer pixel + 1/4 * further pixel */
invalue = GETJSAMPLE(*inptr++) * 3;
*outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
*outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
}
/* Special case for last column */
invalue = GETJSAMPLE(*inptr);
*outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
*outptr++ = (JSAMPLE) invalue;
}
}
/*
* Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
* Again a triangle filter; see comments for h2v1 case, above.
*
* It is OK for us to reference the adjacent input rows because we demanded
* context from the main buffer controller (see initialization code).
*/
METHODDEF void
h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
{
JSAMPARRAY output_data = *output_data_ptr;
register JSAMPROW inptr0, inptr1, outptr;
#if BITS_IN_JSAMPLE == 8
register int thiscolsum, lastcolsum, nextcolsum;
#else
register INT32 thiscolsum, lastcolsum, nextcolsum;
#endif
register JDIMENSION colctr;
int inrow, outrow, v;
inrow = outrow = 0;
while (outrow < cinfo->max_v_samp_factor) {
for (v = 0; v < 2; v++) {
/* inptr0 points to nearest input row, inptr1 points to next nearest */
inptr0 = input_data[inrow];
if (v == 0) /* next nearest is row above */
inptr1 = input_data[inrow-1];
else /* next nearest is row below */
inptr1 = input_data[inrow+1];
outptr = output_data[outrow++];
/* Special case for first column */
thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
*outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4);
*outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
lastcolsum = thiscolsum; thiscolsum = nextcolsum;
for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
/* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
/* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
*outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
*outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
lastcolsum = thiscolsum; thiscolsum = nextcolsum;
}
/* Special case for last column */
*outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
*outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4);
}
inrow++;
}
}
/*
* Module initialization routine for upsampling.
*/
GLOBAL void
jinit_upsampler (j_decompress_ptr cinfo)
{
my_upsample_ptr upsample;
int ci;
jpeg_component_info * compptr;
boolean need_buffer, do_fancy;
int h_in_group, v_in_group, h_out_group, v_out_group;
upsample = (my_upsample_ptr)
(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
SIZEOF(my_upsampler));
cinfo->upsample = (struct jpeg_upsampler *) upsample;
upsample->pub.start_pass = start_pass_upsample;
upsample->pub.upsample = sep_upsample;
upsample->pub.need_context_rows = FALSE; /* until we find out differently */
if (cinfo->CCIR601_sampling) /* this isn't supported */
ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
/* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
* so don't ask for it.
*/
do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
/* Verify we can handle the sampling factors, select per-component methods,
* and create storage as needed.
*/
for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
ci++, compptr++) {
/* Compute size of an "input group" after IDCT scaling. This many samples
* are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
*/
h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
cinfo->min_DCT_scaled_size;
v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
cinfo->min_DCT_scaled_size;
h_out_group = cinfo->max_h_samp_factor;
v_out_group = cinfo->max_v_samp_factor;
upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
need_buffer = TRUE;
if (! compptr->component_needed) {
/* Don't bother to upsample an uninteresting component. */
upsample->methods[ci] = noop_upsample;
need_buffer = FALSE;
} else if (h_in_group == h_out_group && v_in_group == v_out_group) {
/* Fullsize components can be processed without any work. */
upsample->methods[ci] = fullsize_upsample;
need_buffer = FALSE;
} else if (h_in_group * 2 == h_out_group &&
v_in_group == v_out_group) {
/* Special cases for 2h1v upsampling */
if (do_fancy && compptr->downsampled_width > 2)
upsample->methods[ci] = h2v1_fancy_upsample;
else
upsample->methods[ci] = h2v1_upsample;
} else if (h_in_group * 2 == h_out_group &&
v_in_group * 2 == v_out_group) {
/* Special cases for 2h2v upsampling */
if (do_fancy && compptr->downsampled_width > 2) {
upsample->methods[ci] = h2v2_fancy_upsample;
upsample->pub.need_context_rows = TRUE;
} else
upsample->methods[ci] = h2v2_upsample;
} else if ((h_out_group % h_in_group) == 0 &&
(v_out_group % v_in_group) == 0) {
/* Generic integral-factors upsampling method */
upsample->methods[ci] = int_upsample;
upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
} else
ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
if (need_buffer) {
upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
((j_common_ptr) cinfo, JPOOL_IMAGE,
(JDIMENSION) jround_up((long) cinfo->output_width,
(long) cinfo->max_h_samp_factor),
(JDIMENSION) cinfo->max_v_samp_factor);
}
}
}
| [
"[email protected]"
] | [
[
[
1,
956
]
]
] |
93cdd62be27168d09ec73c5e809390e2520bc36b | 893d8c9628e99dfe4412c400e626ad6fd08da6ee | /rtgen_client.cpp | e6afced7b408aa476b406815d56afc9d2949dff7 | [] | no_license | herzi/distrrtgen | 3db54ace872076c3cd609d0dbbad4fea9dbcc815 | 5cad3a168eedb11ab0288e0748294630d078c10e | refs/heads/master | 2021-01-13T02:31:21.060660 | 2007-12-19T18:56:48 | 2007-12-19T18:56:48 | 5,073 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,638 | cpp | // rtgen_client.cpp : Defines the entry point for the console application.
//
#ifdef _WIN32
#pragma warning(disable : 4786)
#endif
#include "config.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <time.h>
#include <stdio.h>
#include "ServerConnector.h"
#include "RainbowTableGenerator.h"
#include "WU_mgr.h"
#ifndef WIN32
#include <pwd.h>
#include <sys/types.h>
#include <errno.h>
#include <sys/stat.h> // For mkdir()
#include <sys/resource.h> //renice main thread
#define CPU_INFO_FILENAME "/proc/cpuinfo"
#endif
#define MAX_PART_SIZE 8000000 //size of PART file
#define CLIENT_WAIT_TIME_SECONDS 600 // Wait 10 min and try again
#define VERSION "3.0 LX"
enum TALKATIVE
{
TK_ALL = 0,
TK_WARNINGS,
TK_ERRORS
};
int main(int argc, char* argv[])
{
std::string sUsername;
std::string sPassword;
double nFrequency;
std::string sHostname;
std::string sHomedir;
int nNumProcessors = 0;
int nClientID;
int nTalkative = TK_ALL;
if(argc > 1)
{
if(strcmp(argv[1], "-q") == 0)
{
nTalkative = TK_WARNINGS;
}
else if(strcmp(argv[1], "-Q") == 0)
{
nTalkative = TK_ERRORS;
}
}
// with which MACRO I have been compiled with..
#ifdef _FAST_HASH_
if(nTalkative <= TK_ALL)
std::cout << "Compiled with Fast and thread safe Hashroutines" << std::endl;
#endif
#ifdef _FAST_MD5_
if(nTalkative <= TK_ALL)
std::cout << "Compiled with Fast and thread unsafe MD5 Hashroutine" << std::endl;
#endif
// First load the client identification information
std::ostringstream sClientInfo;
#ifndef WIN32
struct passwd *userinfo;
userinfo = getpwuid(getuid());
sHomedir = userinfo->pw_dir;
sClientInfo << sHomedir << "/.distrrtgen/";
#endif
sClientInfo << ".client";
std::fstream fClientInfo(sClientInfo.str().c_str(), std::fstream::in);
if(fClientInfo.is_open() == false) nClientID = 0;
else
{
fClientInfo >> nClientID;
fClientInfo.close();
}
// Then load the client configuration
std::ostringstream sConf;
#ifndef WIN32
sConf << sHomedir << "/.distrrtgen/";
#endif
sConf << "distrrtgen.conf";
std::fstream fConfig(sConf.str().c_str(), std::ifstream::in);
if(fConfig.is_open() == false)
{
std::cout << sConf.str() << " could not be opened - " << strerror(errno) << std::endl;
return 1;
}
// std::string sUsername, sPassword;
if( !(fConfig >> sUsername) )
{
std::cout << "Missing username line, check version of " << sConf.str() << std::endl;
return 1;
}
if( !(fConfig >> sPassword) )
{
std::cout << "Missing password line, check version of " << sConf.str() << std::endl;
return 1;
}
if( !(fConfig >> sHostname) )
{
std::cout << "Missing hostname line, check version of " << sConf.str() << std::endl;
return 1;
}
fConfig.close();
sUsername = sUsername.substr(9);
sPassword = sPassword.substr(9);
sHostname = sHostname.substr(9);
if(sUsername == "")
{
std::cout << "No username configured in " << sConf.str() << std::endl;
return 1;
}
if(sPassword == "")
{
std::cout << "No password configured in " << sConf.str() << std::endl;
return 1;
}
if(sHostname == "")
{
std::cout << "No Hostname configured in " << sConf.str() << std::endl;
return 1;
}
wu_mgr *WUFile = new wu_mgr();
//WUFile->read("test.xml");
//if(sProcessors.substr(7).length() > 0) // Check if processor count is manually configured
//{
// nNumProcessors = atoi(sProcessors.substr(7).c_str());
//}
// If numprocessors is 0, RainbowTableGenerator.cpp will try to detect it itself
// Try to catch cpu Frequency from /proc/cpuinfo
#ifndef WIN32
const char* cpuprefix = "cpu MHz";
const char* cpunumber = "processor";
FILE* F;
char cpuline[300+1];
char* pos;
int ok = 0;
nNumProcessors = 0;
// open cpuinfo system file
F = fopen(CPU_INFO_FILENAME,"r");
if (!F) return 0;
//read lines
while (!feof(F))
{
fgets (cpuline, sizeof(cpuline), F);
//test if it's a processor id line
/* deprecated
if (!strncmp(cpuline, cpunumber, strlen(cpunumber)))
{
}
*/
// test if it's the frequency line
if (!strncmp(cpuline, cpuprefix, strlen(cpuprefix)))
{
// Yes, grep the frequency
pos = strrchr (cpuline, ':') +2;
if (!pos) break;
if (pos[strlen(pos)-1] == '\n') pos[strlen(pos)-1] = '\0';
strcpy (cpuline, pos);
strcat (cpuline,"e6");
nFrequency = atof (cpuline)/1000000;
ok = 1;
//break; //bug : http://www.freerainbowtables.com/phpBB3/viewtopic.php?f=4&p=916&sid=53804aa79a7bc4bb06cff38481889cf7#p909
}
}
nNumProcessors = sysconf(_SC_NPROCESSORS_ONLN);
if(nTalkative <= TK_ALL)
std::cout << nNumProcessors <<" processor(s) found." << std::endl;
if (ok == 1)
{
if(nTalkative <= TK_ALL)
std::cout << "CPU frequency has been found : " << nFrequency << " MHz" << std::endl;
}
else
{
if(nTalkative <= TK_ALL)
std::cout << "Unable to get cpu frequency from /proc/cpuinfo." << std::endl;
exit(-1);
}
#endif
ServerConnector *Con = new ServerConnector();
//Con->Connect(); //deprecated
Con->Login(sUsername, sPassword, sHostname, nClientID, nFrequency);
// Check to see if there is something to resume from
stWorkInfo stWork;
std::ostringstream sResumeFile;
#ifndef WIN32
sResumeFile << sHomedir << "/.distrrtgen/";
#endif
sResumeFile << ".resume";
FILE *file = fopen(sResumeFile.str().c_str(), "rb");
if(file != NULL)
{
// Bingo.. There is a resume file.
fread(&stWork, sizeof(unsigned int), 6, file);
char buf[8096];
memset(buf, 0x00, sizeof(buf));
fread(&buf[0], sizeof(buf), 1, file);
fclose(file);
char szCharset[8096], szHR[8096];
strcpy(&szCharset[0], &buf[0]);
stWork.sCharset.assign(szCharset);
const char *pHR = strchr(&buf[0], 0x00);
pHR++;
strcpy(&szHR[0], pHR);
stWork.sHashRoutine.assign(szHR);
pHR = strchr(pHR, 0x00);
pHR++;
strcpy(&szHR[0], pHR);
stWork.sSalt.assign(szHR);
//before continuing, test if part file is <8MB sized
const char * cFileName;
std::string sFileName;
std::stringstream szFileName;
szFileName << sHomedir << "/.distrrtgen/" << stWork.nPartID << ".part"; // Store it in the users home directory
sFileName = szFileName.str();
cFileName = sFileName.c_str();
FILE *partfile = fopen(cFileName,"rb");
long size;
if(partfile != NULL)
{
fseek(partfile,0,SEEK_END);
size=ftell(partfile);
rewind(partfile);
fclose(partfile);
if(nTalkative <= TK_ALL)
std::cout << "Part file size (in bytes) : " << size << std::endl;
if (size != MAX_PART_SIZE)
{
if(nTalkative <= TK_ALL)
std::cout << "Deleting " << cFileName << std::endl;
if( remove(cFileName) != 0 )
{
if(nTalkative <= TK_ALL)
std::cout << "Error deleting file, please manually delete it." << std::endl;
exit(-1);
}
else
if(nTalkative <= TK_ALL)
std::cout << "File successfully deleted." << std::endl;
}
}
else
{
if(nTalkative <= TK_ALL)
std::cout << "No unfinished part file." << std::endl;
}
if (size==MAX_PART_SIZE)
{
if(nTalkative <= TK_ALL)
std::cout << "File already completed... try uploading" << std::endl;
//ServerConnector *Con = new ServerConnector();
while(1)
{
try
{
Con->Connect(); //deprecated
if(!Con->Login(sUsername, sPassword, sHostname, nClientID, nFrequency))
exit(0);
int nResult = Con->SendFinishedWork(stWork.nPartID, szFileName.str(), sUsername, sPassword);
Con->Disconnect(); // Deprecated against XML/HTTP (destroy Con object)
switch(nResult)
{
case TRANSFER_OK:
if(nTalkative <= TK_ALL)
std::cout << "Data delivered!" << std::endl;
remove(szFileName.str().c_str());
stWork.sCharset = ""; // Blank out the charset to indicate the work is complete
unlink(sResumeFile.str().c_str());
break;
case TRANSFER_NOTREGISTERED:
if(nTalkative <= TK_ALL)
std::cout << "Data was not accepted by the server. Dismissing" << std::endl;
remove(szFileName.str().c_str());
stWork.sCharset = ""; //We let the charset is order to retry
unlink(sResumeFile.str().c_str()); //We remove the part but not the resume file, to restart
break;
case TRANSFER_GENERAL_ERROR:
if(nTalkative <= TK_ALL)
std::cout << "Could not transfer data to server. Retrying in " << CLIENT_WAIT_TIME_SECONDS / 60 << " minutes" << std::endl;
Sleep(CLIENT_WAIT_TIME_SECONDS * 1000);
continue;
}
break;
}
catch(SocketException *ex)
{
std::cout << "Error connecting to server: " << ex->GetErrorMessage() << ". Retrying in " << CLIENT_WAIT_TIME_SECONDS / 60 << " minutes" << std::endl;
delete ex;
Sleep(CLIENT_WAIT_TIME_SECONDS * 1000);
}
catch(ConnectionException *ex)
{
if(ex->GetErrorLevel() >= nTalkative)
std::cout << ex->GetErrorMessage() << ". Retrying in " << CLIENT_WAIT_TIME_SECONDS / 60 << " minutes" << std::endl;
delete ex;
Sleep(CLIENT_WAIT_TIME_SECONDS * 1000);
}
}
//remove(szFileName.str().c_str());
//stWork.sCharset = ""; // Blank out the charset to indicate the work is complete
/*std::ostringstream sResumeFile;
#ifndef WIN32
sResumeFile << sHomedir << "/.distrrtgen/";
#endif
sResumeFile << ".resume";*/
//unlink(sResumeFile.str().c_str());
}
else
{
// We delete the old part file
/*char * cDeleteFile;
sprintf(cDeleteFile, "/bin/rm -f %s", cFileName);
system(cDeleteFile);*/
if(nTalkative <= TK_ALL)
std::cout << "Delete Part file and restart interrupted computations..." << std::endl;
remove(szFileName.str().c_str());
}
}
try
{
if(nTalkative <= TK_ALL)
std::cout << "Initializing DistrRTgen " << VERSION << std::endl;
CRainbowTableGenerator *pGenerator = new CRainbowTableGenerator(nNumProcessors);
if(nTalkative <= TK_ALL)
std::cout << "Generating using " << pGenerator->GetProcessorCount() << " processor(s)..." << std::endl;
//CServerConnector *Con = new ServerConnector();
while(1)
{
//renice main thread to 0.
setpriority(PRIO_PROCESS, 0, 0);
try
{
if(nClientID == 0) // This client doesn't have an ID.
{ // We connect to the server and register ourself
//ServerConnector *Con = new ServerConnector();
if(nTalkative <= TK_ALL)
std::cout << "Connecting to server to perform first time registration...";
//Con->Connect(); //useless
if(nTalkative <= TK_ALL)
{
std::cout << "OK" << std::endl;
std::cout << "Performing logon...";
}
nClientID = Con->Login(sUsername, sPassword, sHostname, nClientID, nFrequency);
if(nTalkative <= TK_ALL)
std::cout << "client num : " << nClientID << std::endl;
std::fstream fClient(sClientInfo.str().c_str(), std::fstream::out);
if(fClient.is_open() == false)
{
std::cout << "Could not open " << sClientInfo.str() << " for writing" << std::endl;
nClientID = 0;
}
else
{
fClient << nClientID;
fClient.close();
}
Con->Disconnect();
}
// If there is no work to do, request some!
if(stWork.sCharset == "")
{
if(nTalkative <= TK_ALL)
std::cout << "Connecting to server...";
Con->Connect();
if(nTalkative <= TK_ALL)
{
std::cout << "OK" << std::endl;
std::cout << "Performing logon...";
}
Con->Login(sUsername, sPassword, sHostname, nClientID, nFrequency);
if(nTalkative <= TK_ALL)
{
std::cout << "OK" << std::endl;
std::cout << "Requesting work...";
}
Con->RequestWork(&stWork, sUsername, sPassword, sHostname, nClientID, nFrequency);
if(nTalkative <= TK_ALL)
std::cout << "work received !" << std::endl;
FILE *fileResume = fopen(sResumeFile.str().c_str(), "wb");
if(fileResume == NULL)
{
std::cout << "Unable to open " << sResumeFile.str() << " for writing" << std::endl;
return 1;
}
fwrite(&stWork, sizeof(unsigned int), 6, fileResume); // Write the 6 unsigned ints
fwrite(stWork.sCharset.c_str(), stWork.sCharset.length(), 1, fileResume);
fputc(0x00, fileResume);
fwrite(stWork.sHashRoutine.c_str(), stWork.sHashRoutine.length(), 1, fileResume);
fclose(fileResume);
Con->Disconnect();
}
std::stringstream szFileName;
#ifdef WIN32
szFileName << stWork.nPartID << ".part";
#else
szFileName << sHomedir << "/.distrrtgen/" << stWork.nPartID << ".part"; // Store it in the users home directory
#endif
// do the work
int nReturn;
if(nTalkative <= TK_ALL)
std::cout << "Starting multithreaded rainbowtable generator..." << std::endl;
#ifndef WIN32
if(nTalkative >= TK_WARNINGS)
std::freopen("/dev/null", "w", stdout);
#endif
if((nReturn = pGenerator->CalculateTable(szFileName.str(), stWork.nChainCount, stWork.sHashRoutine, stWork.sCharset, stWork.nMinLetters, stWork.nMaxLetters, stWork.nOffset, stWork.nChainLength, stWork.sSalt)) != 0)
{
if(nTalkative >= TK_WARNINGS)
std::freopen("/dev/stdout", "w", stdout);
std::cout << "Error id " << nReturn << " received while generating table";
return nReturn;
}
#ifndef WIN32
if(nTalkative >= TK_WARNINGS)
std::freopen("/dev/stdout", "w", stdout);
#endif
if(nTalkative <= TK_ALL)
std::cout << "Calculations of part " << stWork.nPartID << " completed. Sending data..." << std::endl;
while(1)
{
try
{
Con->Connect();
Con->Login(sUsername, sPassword, sHostname, nClientID, nFrequency);
int nResult = Con->SendFinishedWork(stWork.nPartID, szFileName.str(), sUsername, sPassword);
Con->Disconnect();
switch(nResult)
{
case TRANSFER_OK:
if(nTalkative <= TK_ALL)
std::cout << "Data delivered!" << std::endl;
remove(szFileName.str().c_str());
stWork.sCharset = ""; // Blank out the charset to indicate the work is complete
unlink(sResumeFile.str().c_str());
break;
case TRANSFER_NOTREGISTERED:
if(nTalkative <= TK_ALL)
std::cout << "Data was not accepted by the server. Dismissing" << std::endl;
remove(szFileName.str().c_str());
stWork.sCharset = ""; // Blank out the charset to indicate the work is complete
unlink(sResumeFile.str().c_str());
break;
case TRANSFER_GENERAL_ERROR:
if(nTalkative <= TK_ALL)
std::cout << "Could not transfer data to server. Retrying in " << CLIENT_WAIT_TIME_SECONDS / 60 << " minutes" << std::endl;
Sleep(CLIENT_WAIT_TIME_SECONDS * 1000);
continue;
}
break;
}
catch(SocketException *ex)
{
std::cout << "Error connecting to server: " << ex->GetErrorMessage() << ". Retrying in " << CLIENT_WAIT_TIME_SECONDS / 60 << " minutes" << std::endl;
delete ex;
Sleep(CLIENT_WAIT_TIME_SECONDS * 1000);
}
catch(ConnectionException *ex)
{
if(ex->GetErrorLevel() >= nTalkative)
std::cout << ex->GetErrorMessage() << ". Retrying in " << CLIENT_WAIT_TIME_SECONDS / 60 << " minutes" << std::endl;
delete ex;
Sleep(CLIENT_WAIT_TIME_SECONDS * 1000);
}
}
//remove(szFileName.str().c_str());
//stWork.sCharset = ""; // Blank out the charset to indicate the work is complete
//unlink(sResumeFile.str().c_str());
}
catch(SocketException *ex)
{
if(nTalkative <= TK_WARNINGS)
std::cout << "Could not connect to server: " << ex->GetErrorMessage() << ". Retrying in " << CLIENT_WAIT_TIME_SECONDS / 60 << " minutes" << std::endl;
delete ex;
Sleep(CLIENT_WAIT_TIME_SECONDS * 1000);
}
catch(ConnectionException *ex)
{
if(ex->GetErrorLevel() >= nTalkative)
std::cout << ex->GetErrorMessage() << ". Retrying in " << CLIENT_WAIT_TIME_SECONDS / 60 << " minutes" << std::endl;
delete ex;
Sleep(CLIENT_WAIT_TIME_SECONDS * 1000);
}
}
}
catch (...)
{
if(nTalkative <= TK_ERRORS)
std::cerr << "Unhandled exception :(" << std::endl;
}
return 0;
}
| [
"alexis.dagues@14c93cb0-9641-0410-902e-89133d47d5d8"
] | [
[
[
1,
523
]
]
] |
a9f04decadb9d8ef50e3d511b80a876995d2745b | d2fc16640fb0156afb6528e744867e2be4eec02c | /src/ScriptProcs/ScriptDrawing.cpp | b66748442315314311081652269802117a8c8f2e | [] | no_license | wlschmidt/lcdmiscellany | 8cd93b5403f9c62a127ddd00c8c5dd577cf72e2f | 6623ca05cd978d91580673e6d183f2242bb8eb24 | refs/heads/master | 2021-01-19T02:30:05.104179 | 2011-11-02T21:52:07 | 2011-11-02T21:52:07 | 48,021,331 | 1 | 1 | null | 2016-07-23T09:08:48 | 2015-12-15T05:20:15 | C++ | UTF-8 | C++ | false | false | 7,701 | cpp | #include "ScriptDrawing.h"
#include "../Screen.h"
#include "../ScriptObjects/ScriptFont.h"
#include "../Unicode.h"
#include "../malloc.h"
#include "../vm.h"
void ClearScreen(ScriptValue &s, ScriptValue *args) {
activeScreen->Clear();
}
void DrawPixel(ScriptValue &s, ScriptValue *args) {
activeScreen->ColorPixel(args[0].i32, args[1].i32, activeScreen->drawColor);
}
void InvertPixel(ScriptValue &s, ScriptValue *args) {
activeScreen->TogglePixel(args[0].i32, args[1].i32);
}
void ClearPixel(ScriptValue &s, ScriptValue *args) {
activeScreen->ColorPixel(args[0].i32, args[1].i32, activeScreen->bgColor);
}
void DrawLine(ScriptValue &s, ScriptValue *args) {
activeScreen->DrawLine(args[0].i32, args[1].i32, args[2].i32, args[3].i32);
}
void InvertLine(ScriptValue &s, ScriptValue *args) {
activeScreen->InvertLine(args[0].i32, args[1].i32, args[2].i32, args[3].i32);
}
void ClearLine(ScriptValue &s, ScriptValue *args) {
activeScreen->ClearLine(args[0].i32, args[1].i32, args[2].i32, args[3].i32);
}
void ClearRect(ScriptValue &s, ScriptValue *args) {
activeScreen->ClearRect(args[0].i32, args[1].i32, args[2].i32, args[3].i32);
}
void InvertRect(ScriptValue &s, ScriptValue *args) {
activeScreen->InvertRect(args[0].i32, args[1].i32, args[2].i32, args[3].i32);
}
void DrawRect(ScriptValue &s, ScriptValue *args) {
activeScreen->DrawRect(args[0].i32, args[1].i32, args[2].i32, args[3].i32);
}
void ColorRect(ScriptValue &s, ScriptValue *args) {
RECT r = {
args[0].i32,
args[1].i32,
args[2].i32,
args[3].i32,
};
activeScreen->FillRect(r, *(Color4*)&args[4].i32);
}
void ColorLine(ScriptValue &s, ScriptValue *args) {
if (args[0].type != SCRIPT_LIST) return;
int numVals = args[0].listVal->numVals;
ScriptValue *vals = args[0].listVal->vals;
if (numVals < 5) return;
Color4 color;
color.val = (int) CoerceIntNoRelease(vals[0]);
int lx = (int) CoerceIntNoRelease(vals[1]);
int ly = (int) CoerceIntNoRelease(vals[2]);
for (int i = 4; i < numVals; i+=2) {
int x = (int) CoerceIntNoRelease(vals[i-1]);
int y = (int) CoerceIntNoRelease(vals[i]);
activeScreen->ColorLine(lx, ly, x, y, color);
lx = x;
ly = y;
}
}
void XorRect(ScriptValue &s, ScriptValue *args) {
Color4 c;
c.val = args[4].i32;
activeScreen->XorRect(args[0].i32, args[1].i32, args[2].i32, args[3].i32, c);
}
void TextSize(ScriptValue &s, ScriptValue *args) {
int height;
if (CreateListValue(s, 2)) {
int width = activeScreen->GetTextWidth(args[0].stringVal->value, args[0].stringVal->len, &height);
s.listVal->PushBack(width);
s.listVal->PushBack(height);
}
}
void DrawClippedText(ScriptValue &s, ScriptValue *args) {
RECT r = {args[1].i32, args[2].i32, args[3].i32, args[4].i32};
activeScreen->DisplayText(args[1].i32, args[2].i32, args[0].stringVal->value, args[0].stringVal->len, 0, 0, &r, args[5].i32);
}
void DisplayText(ScriptValue &s, ScriptValue *args) {
activeScreen->DisplayText(args[1].i32, args[2].i32, args[0].stringVal->value, args[0].stringVal->len, args[3].i32, args[4].i32);
int junk;
CreateIntValue(s, activeScreen->GetTextWidth(args[0].stringVal->value, args[0].stringVal->len, &junk));
}
void DisplayTextCentered(ScriptValue &s, ScriptValue *args) {
int width = activeScreen->DisplayTextCentered(args[1].i32, args[2].i32, args[0].stringVal->value, args[0].stringVal->len, args[3].i32, args[4].i32);
CreateIntValue(s, width);
}
void Redraw(StringValue *dev);
void RedrawNow(StringValue *dev);
void DisplayTextRight(ScriptValue &s, ScriptValue *args) {
int width = activeScreen->DisplayTextRight(args[1].i32, args[2].i32, args[0].stringVal->value, args[0].stringVal->len, args[3].i32, args[4].i32);
CreateIntValue(s, width);
}
void NeedRedraw(ScriptValue &s, ScriptValue *args) {
StringValue * string = 0;
if (args[1].stringVal->value[0])
string = args[1].stringVal;
if (args[0].intVal==-1)
RedrawNow(string);
else
Redraw(string);
}
int *FormatText(unsigned char *s, int len, int width, int &count) {
int wordLen = 0;
int lineLen = 0;
int line = 0;
int wordChars = 0;
int lineChars = 0;
int pos = 0;
int maxLines = 1+len /10;
int *breaks = (int*)malloc(sizeof(int)*maxLines);
DynamicFont *f = GetNewFontMetrics(activeScreen->activeNewFont);
int bold = 0;
while (pos < len) {
int l;
unsigned int c = NextUnicodeChar(s+pos, &l);
if (c==2) {
wordChars++;
bold ^= 1;
pos ++;
continue;
}
BitImage *b;
if (c == '\r') {
c = '\n';
if (pos < len-1 && s[pos+1] == '\n') {
pos++;
}
}
if (c == '\n') {
pos ++;
wordChars = 0;
lineChars = 0;
wordLen = 0;
lineLen = 0;
/*if (line == maxLines) {
if (!srealloc(breaks, maxLines * 2 * sizeof(int))) continue;
maxLines *= 2;
}
breaks[line] = pos;
line ++;
//*/
continue;
}
CharData *d = GetCharData(f, c, b, bold);
if (c == ' ' || c == '\t') {
if (d) {
if (c == ' ')
lineLen += d->width + wordLen;
else
lineLen += d->width - (lineLen % d->width);
}
lineChars += wordChars + l;
wordLen = 0;
wordChars = 0;
pos+=l;
}
else {
int charLen;
if (d) {
charLen = d->width;
}
else {
charLen = 0;
}
if (c == '(' || c == '[' || c == '{') {
lineLen += wordLen;
lineChars += wordChars;
wordChars = 0;
wordLen = 0;
}
if (wordLen + charLen + lineLen <= width || (!wordLen && !lineLen)) {
if (c == '\\' || c == '>' || c == '<' || c == ')' || c == ']' || c == '}' || c == '/' || c == ',' || c == '+' || c == '.' || c == '?' || c == '&' || c == '=') {
lineLen += charLen + wordLen;
lineChars += wordChars + l;
wordChars = 0;
wordLen = 0;
pos += l;
}
else {
wordChars += l;
wordLen += charLen;
pos += l;
}
}
else {
if (line == maxLines) {
if (!srealloc(breaks, maxLines * 2 * sizeof(int))) continue;
maxLines *= 2;
}
if (lineChars) {
breaks[line] = pos-wordChars;
}
else {
breaks[line] = pos;
wordLen = 0;
wordChars = 0;
}
lineLen = 0;
lineChars = 0;
line ++;
}
}
}
count = line;
return breaks;
}
void FormatText(ScriptValue &s, ScriptValue *args) {
int count;
int *breaks = FormatText(args[0].stringVal->value, args[0].stringVal->len, args[1].i32, count);
if (AllocateStringValue(s, args[0].stringVal->len + count)) {
int out = 0;
int i = 0;
for (int p=0; p<args[0].stringVal->len; p++) {
if (i < args[0].stringVal->len && breaks[i] == p) {
s.stringVal->value[out++] = '\n';
i++;
}
if (args[0].stringVal->value[p] != '\r' || args[0].stringVal->value[p+1] == '\n') {
s.stringVal->value[out++] = args[0].stringVal->value[p];
}
else {
s.stringVal->value[out++] = '\n';
}
}
}
free(breaks);
}
void SetBgColor(ScriptValue &s, ScriptValue *args) {
CreateIntValue(s, activeScreen->bgColor.val);
activeScreen->bgColor.val = args[0].i32;
}
void SetDrawColor(ScriptValue &s, ScriptValue *args) {
CreateIntValue(s, activeScreen->drawColor.val);
activeScreen->drawColor.val = args[0].i32;
}
void MyRGB(ScriptValue &s, ScriptValue *args) {
Color4 c = {args[2].i32, args[1].i32, args[0].i32, 0xFF};
CreateIntValue(s, c.val);
}
void MyRGBA(ScriptValue &s, ScriptValue *args) {
Color4 c = {args[2].i32, args[1].i32, args[0].i32, args[3].i32};
CreateIntValue(s, c.val);
}
void GetHDC(ScriptValue &s, ScriptValue *args) {
CreateIntValue(s, (__int64)activeScreen->hDC);
}
| [
"mattmenke@88352c64-7129-11de-90d8-1fdda9445408"
] | [
[
[
1,
279
]
]
] |