blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
5
146
content_id
stringlengths
40
40
detected_licenses
listlengths
0
7
license_type
stringclasses
2 values
repo_name
stringlengths
6
79
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
4 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.07k
426M
star_events_count
int64
0
27
fork_events_count
int64
0
12
gha_license_id
stringclasses
3 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
6 values
src_encoding
stringclasses
26 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
1 class
length_bytes
int64
20
6.28M
extension
stringclasses
20 values
content
stringlengths
20
6.28M
authors
listlengths
1
16
author_lines
listlengths
1
16
8e8740e1900b8a3f36df7935e3e3487b60561c0f
01fadae9f2a6d3f19bc843841a7faa9c40fc4a20
/CG/code_CG/Clipping.cpp
1aa11224da592456bec1e864e7f005daf2cbebcf
[]
no_license
passzenith/passzenithproject
9999da29ac8df269c41d280137113e1e2638542d
67dd08f4c3a046889319170a89b45478bfd662d2
refs/heads/master
2020-12-24T14:36:46.389657
2010-09-05T02:34:42
2010-09-05T02:34:42
32,310,266
0
0
null
null
null
null
UTF-8
C++
false
false
1,696
cpp
#include <GL/glut.h> void init (void) { glClearColor (1.0, 1.0, 1.0, 0.0); glLineWidth(2.0); glMatrixMode (GL_PROJECTION); glLoadIdentity (); gluOrtho2D (0.0, 300.0, 0.0, 300.0); } void myDisplay (void) { glClear (GL_COLOR_BUFFER_BIT); glBegin (GL_TRIANGLES); // Center Triangle glColor3f (1.0, 0.0, 0.0); glVertex2i (150,210); glVertex2i (210, 90); glVertex2i ( 90, 90); glEnd ( ); glBegin (GL_TRIANGLES); // Top-right Triangle glColor3f (0.0, 0.0, 1.0); glVertex2i (250,280); glVertex2i (330,240); glVertex2i (250,200); glEnd ( ); glBegin (GL_TRIANGLES); // Bottom-left Triangle glColor3f (0.0, 1.0, 0.0); glVertex2i ( 30, 50); glVertex2i ( 30,-50); glVertex2i (-30, 0); glEnd ( ); glBegin (GL_LINES); // Top-left Line glColor3f (0.0, 1.0, 1.0); glVertex2i ( 50,250); glVertex2i (-50,350); glEnd ( ); glBegin (GL_LINES); // Bottom-right Line glColor3f (1.0, 0.0, 1.0); glVertex2i (150,-50); glVertex2i (350, 90); glEnd ( ); glBegin (GL_QUADS); // Center-left Quads glColor3f (1.0, 1.0, 0.0); glVertex2i ( 50,200); glVertex2i ( 50,100); glVertex2i (-50,100); glVertex2i (-50,200); glEnd ( ); glFlush ( ); } int main (int argc, char** argv) { glutInit (&argc, argv); glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB); glutInitWindowPosition (50, 100); glutInitWindowSize (300, 300); glutCreateWindow ("Clipped Objects"); init ( ); glutDisplayFunc (myDisplay); glutMainLoop ( ); return 0; }
[ "passzenith@00fadc5f-a3f2-dbaa-0561-d91942954633" ]
[ [ [ 1, 73 ] ] ]
dde332f6332b1e81dce1faf3ca7968ff2b9fa526
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/Dependencies/Xerces/include/xercesc/parsers/DOMBuilderImpl.hpp
e04a178c3f9ea7fbe8aa871b71aa132581ed0d15
[]
no_license
svn2github/ngene
b2cddacf7ec035aa681d5b8989feab3383dac012
61850134a354816161859fe86c2907c8e73dc113
refs/heads/master
2023-09-03T12:34:18.944872
2011-07-27T19:26:04
2011-07-27T19:26:04
78,163,390
2
0
null
null
null
null
UTF-8
C++
false
false
37,848
hpp
/* * Copyright 2002,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id: DOMBuilderImpl.hpp 191708 2005-06-21 19:02:15Z cargilld $ * */ #if !defined(DOMBUILDERIMPL_HPP) #define DOMBUILDERIMPL_HPP #include <xercesc/parsers/AbstractDOMParser.hpp> #include <xercesc/dom/DOMBuilder.hpp> #include <xercesc/util/XercesDefs.hpp> XERCES_CPP_NAMESPACE_BEGIN class XMLEntityResolver; class XMLResourceIdentifier; /** * Introduced in DOM Level 3 * * DOMBuilderImpl provides an implementation of a DOMBuilder interface. * A DOMBuilder instance is obtained from the DOMImplementationLS interface * by invoking its createDOMBuilder method. */ class PARSERS_EXPORT DOMBuilderImpl : public AbstractDOMParser, public DOMBuilder { public : // ----------------------------------------------------------------------- // Constructors and Detructor // ----------------------------------------------------------------------- /** @name Constructors and Destructor */ //@{ /** Construct a DOMBuilderImpl, with an optional validator * * Constructor with an instance of validator class to use for * validation. If you don't provide a validator, a default one will * be created for you in the scanner. * * @param gramPool Pointer to the grammar pool instance from * external application. * The parser does NOT own it. * * @param valToAdopt Pointer to the validator instance to use. The * parser is responsible for freeing the memory. */ DOMBuilderImpl ( XMLValidator* const valToAdopt = 0 , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager , XMLGrammarPool* const gramPool = 0 ); /** * Destructor */ virtual ~DOMBuilderImpl(); //@} // ----------------------------------------------------------------------- // Implementation of DOMBuilder interface // ----------------------------------------------------------------------- // ----------------------------------------------------------------------- // Getter methods // ----------------------------------------------------------------------- /** @name Getter methods */ //@{ /** * <p><b>"Experimental - subject to change"</b></p> * * Get a pointer to the error handler * * This method returns the installed error handler. If no handler * has been installed, then it will be a zero pointer. * * @return The pointer to the installed error handler object. */ DOMErrorHandler* getErrorHandler(); /** * <p><b>"Experimental - subject to change"</b></p> * * Get a const pointer to the error handler * * This method returns the installed error handler. If no handler * has been installed, then it will be a zero pointer. * * @return A const pointer to the installed error handler object. */ const DOMErrorHandler* getErrorHandler() const; /** * <p><b>"Experimental - subject to change"</b></p> * * Get a pointer to the entity resolver * * This method returns the installed entity resolver. If no resolver * has been installed, then it will be a zero pointer. * * @return The pointer to the installed entity resolver object. */ DOMEntityResolver* getEntityResolver(); /** * Get a pointer to the entity resolver * * This method returns the installed entity resolver. If no resolver * has been installed, then it will be a zero pointer. * * @return The pointer to the installed entity resolver object. */ XMLEntityResolver* getXMLEntityResolver(); /** * Get a const pointer to the entity resolver * * This method returns the installed entity resolver. If no resolver * has been installed, then it will be a zero pointer. * * @return A const pointer to the installed entity resolver object. */ const XMLEntityResolver* getXMLEntityResolver() const; /** * <p><b>"Experimental - subject to change"</b></p> * * Get a const pointer to the entity resolver * * This method returns the installed entity resolver. If no resolver * has been installed, then it will be a zero pointer. * * @return A const pointer to the installed entity resolver object. */ const DOMEntityResolver* getEntityResolver() const; /** * <p><b>"Experimental - subject to change"</b></p> * * Get a pointer to the application filter * * This method returns the installed application filter. If no filter * has been installed, then it will be a zero pointer. * * @return The pointer to the installed application filter. */ DOMBuilderFilter* getFilter(); /** * <p><b>"Experimental - subject to change"</b></p> * * Get a const pointer to the application filter * * This method returns the installed application filter. If no filter * has been installed, then it will be a zero pointer. * * @return A const pointer to the installed application filter */ const DOMBuilderFilter* getFilter() const; //@} // ----------------------------------------------------------------------- // Setter methods // ----------------------------------------------------------------------- /** @name Setter methods */ //@{ /** * <p><b>"Experimental - subject to change"</b></p> * * Set the error handler * * This method allows applications to install their own error handler * to trap error and warning messages. * * <i>Any previously set handler is merely dropped, since the parser * does not own them.</i> * * @param handler A const pointer to the user supplied error * handler. * * @see #getErrorHandler */ void setErrorHandler(DOMErrorHandler* const handler); /** * <p><b>"Experimental - subject to change"</b></p> * * Set the entity resolver * * This method allows applications to install their own entity * resolver. By installing an entity resolver, the applications * can trap and potentially redirect references to external * entities. * * <i>Any previously set entity resolver is merely dropped, since the parser * does not own them. If both setEntityResolver and setXMLEntityResolver * are called, then the last one is used.</i> * * @param handler A const pointer to the user supplied entity * resolver. * * @see #getEntityResolver */ void setEntityResolver(DOMEntityResolver* const handler); /** * Set the entity resolver * * This method allows applications to install their own entity * resolver. By installing an entity resolver, the applications * can trap and potentially redirect references to external * entities. * * <i>Any previously set entity resolver is merely dropped, since the parser * does not own them. If both setEntityResolver and setXMLEntityResolver * are called, then the last one is used.</i> * * @param handler A const pointer to the user supplied entity * resolver. * * @see #getXMLEntityResolver */ void setXMLEntityResolver(XMLEntityResolver* const handler); /** * <p><b>"Experimental - subject to change"</b></p> * * Set the application filter * * When the application provides a filter, the parser will call out to * the filter at the completion of the construction of each Element node. * The filter implementation can choose to remove the element from the * document being constructed (unless the element is the document element) * or to terminate the parse early. If the document is being validated * when it's loaded the validation happens before the filter is called. * * <i>Any previously set filter is merely dropped, since the parser * does not own them.</i> * * @param filter A const pointer to the user supplied application * filter. * * @see #getFilter */ void setFilter(DOMBuilderFilter* const filter); //@} // ----------------------------------------------------------------------- // Feature methods // ----------------------------------------------------------------------- /** @name Feature methods */ //@{ /** * <p><b>"Experimental - subject to change"</b></p> * * Set the state of a feature * * It is possible for a DOMBuilder to recognize a feature name but to be * unable to set its value. * * @param name The feature name. * @param state The requested state of the feature (true or false). * @exception DOMException * NOT_SUPPORTED_ERR: Raised when the DOMBuilder recognizes the * feature name but cannot set the requested value. * <br>NOT_FOUND_ERR: Raised when the DOMBuilder does not recognize * the feature name. * * @see #getFeature * @see #canSetFeature */ void setFeature(const XMLCh* const name, const bool state); /** * <p><b>"Experimental - subject to change"</b></p> * * Look up the value of a feature. * * @param name The feature name. * @return The current state of the feature (true or false) * @exception DOMException * NOT_FOUND_ERR: Raised when the DOMBuilder does not recognize * the feature name. * * @see #setFeature * @see #canSetFeature */ bool getFeature(const XMLCh* const name) const; /** * <p><b>"Experimental - subject to change"</b></p> * * Query whether setting a feature to a specific value is supported. * * @param name The feature name. * @param state The requested state of the feature (true or false). * @return <code>true</code> if the feature could be successfully set * to the specified value, or <code>false</code> if the feature * is not recognized or the requested value is not supported. The * value of the feature itself is not changed. * * @see #getFeature * @see #setFeature */ bool canSetFeature(const XMLCh* const name, const bool state) const; //@} // ----------------------------------------------------------------------- // Parsing methods // ----------------------------------------------------------------------- /** @name Parsing methods */ //@{ /** * <p><b>"Experimental - subject to change"</b></p> * * Parse via an input source object * * This method invokes the parsing process on the XML file specified * by the DOMInputSource parameter. This API is borrowed from the * SAX Parser interface. * * @param source A const reference to the DOMInputSource object which * points to the XML file to be parsed. * @return If the DOMBuilder is a synchronous DOMBuilder the newly created * and populated Document is returned. If the DOMBuilder is * asynchronous then <code>null</code> is returned since the * document object is not yet parsed when this method returns. * @exception SAXException Any SAX exception, possibly * wrapping another exception. * @exception XMLException An exception from the parser or client * handler code. * @exception DOMException A DOM exception as per DOM spec. * * @see DOMInputSource#DOMInputSource * @see #setEntityResolver * @see #setErrorHandler */ DOMDocument* parse(const DOMInputSource& source); /** * <p><b>"Experimental - subject to change"</b></p> * * Parse via a file path or URL * * This method invokes the parsing process on the XML file specified by * the Unicode string parameter 'systemId'. * * @param systemId A const XMLCh pointer to the Unicode string which * contains the path to the XML file to be parsed. * @return If the DOMBuilder is a synchronous DOMBuilder the newly created * and populated Document is returned. If the DOMBuilder is * asynchronous then <code>null</code> is returned since the * document object is not yet parsed when this method returns. * @exception SAXException Any SAX exception, possibly * wrapping another exception. * @exception XMLException An exception from the parser or client * handler code. * @exception DOM_DOMException A DOM exception as per DOM spec. * * @see #parse(DOMInputSource,...) */ DOMDocument* parseURI(const XMLCh* const systemId); /** * <p><b>"Experimental - subject to change"</b></p> * * Parse via a file path or URL (in the local code page) * * This method invokes the parsing process on the XML file specified by * the native char* string parameter 'systemId'. * * @param systemId A const char pointer to a native string which * contains the path to the XML file to be parsed. * @return If the DOMBuilder is a synchronous DOMBuilder the newly created * and populated Document is returned. If the DOMBuilder is * asynchronous then <code>null</code> is returned since the * document object is not yet parsed when this method returns. * @exception SAXException Any SAX exception, possibly * wrapping another exception. * @exception XMLException An exception from the parser or client * handler code. * @exception DOM_DOMException A DOM exception as per DOM spec. * * @see #parse(DOMInputSource,...) */ DOMDocument* parseURI(const char* const systemId); /** * <p><b>"Experimental - subject to change"</b></p> * * Parse via an input source object * * This method invokes the parsing process on the XML file specified * by the DOMInputSource parameter, and inserts the content into an * existing document at the position specified with the contextNode * and action arguments. When parsing the input stream the context node * is used for resolving unbound namespace prefixes. * * @param source A const reference to the DOMInputSource object which * points to the XML file to be parsed. * @param contextNode The node that is used as the context for the data * that is being parsed. This node must be a Document * node, a DocumentFragment node, or a node of a type * that is allowed as a child of an element, e.g. it * can not be an attribute node. * @param action This parameter describes which action should be taken * between the new set of node being inserted and the * existing children of the context node. * @exception DOMException * NOT_SUPPORTED_ERR: Raised when the DOMBuilder doesn't support * this method. * <br>NO_MODIFICATION_ALLOWED_ERR: Raised if the context node is * readonly. */ virtual void parseWithContext ( const DOMInputSource& source , DOMNode* const contextNode , const short action ); // ----------------------------------------------------------------------- // Non-standard Extension // ----------------------------------------------------------------------- /** @name Non-standard Extension */ //@{ /** * Query the current value of a property in a DOMBuilder. * * The builder owns the returned pointer. The memory allocated for * the returned pointer will be destroyed when the builder is deleted. * * To ensure assessiblity of the returned information after the builder * is deleted, callers need to copy and store the returned information * somewhere else; otherwise you may get unexpected result. Since the returned * pointer is a generic void pointer, see * http://xml.apache.org/xerces-c/program-dom.html#DOMBuilderProperties to learn * exactly what type of property value each property returns for replication. * * @param name The unique identifier (URI) of the property being set. * @return The current value of the property. The pointer spans the same * life-time as the parser. A null pointer is returned if nothing * was specified externally. * @exception DOMException * <br>NOT_FOUND_ERR: Raised when the DOMBuilder does not recognize * the requested property. */ virtual void* getProperty(const XMLCh* const name) const; /** * Set the value of any property in a DOMBuilder. * See http://xml.apache.org/xerces-c/program-dom.html#DOMBuilderProperties for * the list of supported properties. * * It takes a void pointer as the property value. Application is required to initialize this void * pointer to a correct type. See http://xml.apache.org/xerces-c/program-dom.html#DOMBuilderProperties * to learn exactly what type of property value each property expects for processing. * Passing a void pointer that was initialized with a wrong type will lead to unexpected result. * If the same property is set more than once, the last one takes effect. * * @param name The unique identifier (URI) of the property being set. * @param value The requested value for the property. * See http://xml.apache.org/xerces-c/program-dom.html#DOMBuilderProperties to learn * exactly what type of property value each property expects for processing. * Passing a void pointer that was initialized with a wrong type will lead * to unexpected result. * @exception DOMException * <br>NOT_FOUND_ERR: Raised when the DOMBuilder does not recognize * the requested property. */ virtual void setProperty(const XMLCh* const name, void* value); /** * Called to indicate that this DOMBuilder is no longer in use * and that the implementation may relinquish any resources associated with it. * */ virtual void release(); /** Reset the documents vector pool and release all the associated memory * back to the system. * * When parsing a document using a DOM parser, all memory allocated * for a DOM tree is associated to the DOM document. * * If you do multiple parse using the same DOM parser instance, then * multiple DOM documents will be generated and saved in a vector pool. * All these documents (and thus all the allocated memory) * won't be deleted until the parser instance is destroyed. * * If you don't need these DOM documents anymore and don't want to * destroy the DOM parser instance at this moment, then you can call this method * to reset the document vector pool and release all the allocated memory * back to the system. * * It is an error to call this method if you are in the middle of a * parse (e.g. in the mid of a progressive parse). * * @exception IOException An exception from the parser if this function * is called when a parse is in progress. * */ virtual void resetDocumentPool(); /** * Preparse schema grammar (XML Schema, DTD, etc.) via an input source * object. * * This method invokes the preparsing process on a schema grammar XML * file specified by the DOMInputSource parameter. If the 'toCache' flag * is enabled, the parser will cache the grammars for re-use. If a grammar * key is found in the pool, no caching of any grammar will take place. * * <p><b>"Experimental - subject to change"</b></p> * * @param source A const reference to the DOMInputSource object which * points to the schema grammar file to be preparsed. * @param grammarType The grammar type (Schema or DTD). * @param toCache If <code>true</code>, we cache the preparsed grammar, * otherwise, no chaching. Default is <code>false</code>. * @return The preparsed schema grammar object (SchemaGrammar or * DTDGrammar). That grammar object is owned by the parser. * * @exception SAXException Any SAX exception, possibly * wrapping another exception. * @exception XMLException An exception from the parser or client * handler code. * @exception DOMException A DOM exception as per DOM spec. * * @see DOMInputSource#DOMInputSource */ virtual Grammar* loadGrammar(const DOMInputSource& source, const short grammarType, const bool toCache = false); /** * Preparse schema grammar (XML Schema, DTD, etc.) via a file path or URL * * This method invokes the preparsing process on a schema grammar XML * file specified by the file path parameter. If the 'toCache' flag * is enabled, the parser will cache the grammars for re-use. If a grammar * key is found in the pool, no caching of any grammar will take place. * * <p><b>"Experimental - subject to change"</b></p> * * @param systemId A const XMLCh pointer to the Unicode string which * contains the path to the XML grammar file to be * preparsed. * @param grammarType The grammar type (Schema or DTD). * @param toCache If <code>true</code>, we cache the preparsed grammar, * otherwise, no chaching. Default is <code>false</code>. * @return The preparsed schema grammar object (SchemaGrammar or * DTDGrammar). That grammar object is owned by the parser. * * @exception SAXException Any SAX exception, possibly * wrapping another exception. * @exception XMLException An exception from the parser or client * handler code. * @exception DOMException A DOM exception as per DOM spec. */ virtual Grammar* loadGrammar(const XMLCh* const systemId, const short grammarType, const bool toCache = false); /** * Preparse schema grammar (XML Schema, DTD, etc.) via a file path or URL * * This method invokes the preparsing process on a schema grammar XML * file specified by the file path parameter. If the 'toCache' flag * is enabled, the parser will cache the grammars for re-use. If a grammar * key is found in the pool, no caching of any grammar will take place. * * <p><b>"Experimental - subject to change"</b></p> * * @param systemId A const char pointer to a native string which contains * the path to the XML grammar file to be preparsed. * @param grammarType The grammar type (Schema or DTD). * @param toCache If <code>true</code>, we cache the preparsed grammar, * otherwise, no chaching. Default is <code>false</code>. * @return The preparsed schema grammar object (SchemaGrammar or * DTDGrammar). That grammar object is owned by the parser. * * @exception SAXException Any SAX exception, possibly * wrapping another exception. * @exception XMLException An exception from the parser or client * handler code. * @exception DOMException A DOM exception as per DOM spec. */ virtual Grammar* loadGrammar(const char* const systemId, const short grammarType, const bool toCache = false); /** * Retrieve the grammar that is associated with the specified namespace key * * @param nameSpaceKey Namespace key * @return Grammar associated with the Namespace key. */ virtual Grammar* getGrammar(const XMLCh* const nameSpaceKey) const; /** * Retrieve the grammar where the root element is declared. * * @return Grammar where root element declared */ virtual Grammar* getRootGrammar() const; /** * Returns the string corresponding to a URI id from the URI string pool. * * @param uriId id of the string in the URI string pool. * @return URI string corresponding to the URI id. */ virtual const XMLCh* getURIText(unsigned int uriId) const; /** * Clear the cached grammar pool */ virtual void resetCachedGrammarPool(); /** * Returns the current src offset within the input source. * To be used only while parsing is in progress. * * @return offset within the input source */ virtual unsigned int getSrcOffset() const; //@} // ----------------------------------------------------------------------- // Implementation of the XMLErrorReporter interface. // ----------------------------------------------------------------------- /** @name Implementation of the XMLErrorReporter interface. */ //@{ /** Handle errors reported from the parser * * This method is used to report back errors found while parsing the * XML file. This method is also borrowed from the SAX specification. * It calls the corresponding user installed Error Handler method: * 'fatal', 'error', 'warning' depending on the severity of the error. * This classification is defined by the XML specification. * * @param errCode An integer code for the error. * @param msgDomain A const pointer to an Unicode string representing * the message domain to use. * @param errType An enumeration classifying the severity of the error. * @param errorText A const pointer to an Unicode string representing * the text of the error message. * @param systemId A const pointer to an Unicode string representing * the system id of the XML file where this error * was discovered. * @param publicId A const pointer to an Unicode string representing * the public id of the XML file where this error * was discovered. * @param lineNum The line number where the error occurred. * @param colNum The column number where the error occurred. * @see DOMErrorHandler */ virtual void error ( const unsigned int errCode , const XMLCh* const msgDomain , const XMLErrorReporter::ErrTypes errType , const XMLCh* const errorText , const XMLCh* const systemId , const XMLCh* const publicId , const XMLSSize_t lineNum , const XMLSSize_t colNum ); /** Reset any error data before a new parse * * This method allows the user installed Error Handler callback to * 'reset' itself. * * <b><font color="#FF0000">This method is a no-op for this DOM * implementation.</font></b> */ virtual void resetErrors(); //@} // ----------------------------------------------------------------------- // Implementation of the XMLEntityHandler interface. // ----------------------------------------------------------------------- /** @name Implementation of the XMLEntityHandler interface. */ //@{ /** Handle an end of input source event * * This method is used to indicate the end of parsing of an external * entity file. * * <b><font color="#FF0000">This method is a no-op for this DOM * implementation.</font></b> * * @param inputSource A const reference to the InputSource object * which points to the XML file being parsed. * @see InputSource */ virtual void endInputSource(const InputSource& inputSource); /** Expand a system id * * This method allows an installed XMLEntityHandler to further * process any system id's of enternal entities encountered in * the XML file being parsed, such as redirection etc. * * <b><font color="#FF0000">This method always returns 'false' * for this DOM implementation.</font></b> * * @param systemId A const pointer to an Unicode string representing * the system id scanned by the parser. * @param toFill A pointer to a buffer in which the application * processed system id is stored. * @return 'true', if any processing is done, 'false' otherwise. */ virtual bool expandSystemId ( const XMLCh* const systemId , XMLBuffer& toFill ); /** Reset any entity handler information * * This method allows the installed XMLEntityHandler to reset * itself. * * <b><font color="#FF0000">This method is a no-op for this DOM * implementation.</font></b> */ virtual void resetEntities(); /** Resolve a public/system id * * This method allows a user installed entity handler to further * process any pointers to external entities. The applications can * implement 'redirection' via this callback. This method is also * borrowed from the SAX specification. * * @deprecated This method is no longer called (the other resolveEntity one is). * * @param publicId A const pointer to a Unicode string representing the * public id of the entity just parsed. * @param systemId A const pointer to a Unicode string representing the * system id of the entity just parsed. * @param baseURI A const pointer to a Unicode string representing the * base URI of the entity just parsed, * or <code>null</code> if there is no base URI. * @return The value returned by the user installed resolveEntity * method or NULL otherwise to indicate no processing was done. * The returned InputSource is owned by the DOMBuilder which is * responsible to clean up the memory. * @see DOMEntityResolver * @see XMLEntityHandler */ virtual InputSource* resolveEntity ( const XMLCh* const publicId , const XMLCh* const systemId , const XMLCh* const baseURI = 0 ); /** Resolve a public/system id * * This method allows a user installed entity handler to further * process any pointers to external entities. The applications can * implement 'redirection' via this callback. * * @param resourceIdentifier An object containing the type of * resource to be resolved and the associated data members * corresponding to this type. * @return The value returned by the user installed resolveEntity * method or NULL otherwise to indicate no processing was done. * The returned InputSource is owned by the parser which is * responsible to clean up the memory. * @see XMLEntityHandler * @see XMLEntityResolver */ virtual InputSource* resolveEntity ( XMLResourceIdentifier* resourceIdentifier ); /** Handle a 'start input source' event * * This method is used to indicate the start of parsing an external * entity file. * * <b><font color="#FF0000">This method is a no-op for this DOM parse * implementation.</font></b> * * @param inputSource A const reference to the InputSource object * which points to the external entity * being parsed. */ virtual void startInputSource(const InputSource& inputSource); //@} private : // ----------------------------------------------------------------------- // Initialize/Cleanup methods // ----------------------------------------------------------------------- void resetParse(); // ----------------------------------------------------------------------- // Private data members // // fEntityResolver // The installed DOM entity resolver, if any. Null if none. // // fErrorHandler // The installed DOM error handler, if any. Null if none. // // fFilter // The installed application filter, if any. Null if none. // // fCharsetOverridesXMLEncoding // Indicates if the "charset-overrides-xml-encoding" is set or not // // fUserAdoptsDocument // The DOMDocument ownership has been transferred to application // If set to true, the parser does not own the document anymore // and thus will not release its memory. //----------------------------------------------------------------------- bool fAutoValidation; bool fValidation; DOMEntityResolver* fEntityResolver; XMLEntityResolver* fXMLEntityResolver; DOMErrorHandler* fErrorHandler; DOMBuilderFilter* fFilter; bool fCharsetOverridesXMLEncoding; bool fUserAdoptsDocument; // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- DOMBuilderImpl(const DOMBuilderImpl &); DOMBuilderImpl & operator = (const DOMBuilderImpl &); }; // --------------------------------------------------------------------------- // DOMBuilderImpl: Handlers for the XMLEntityHandler interface // --------------------------------------------------------------------------- inline void DOMBuilderImpl::endInputSource(const InputSource&) { // The DOM entity resolver doesn't handle this } inline bool DOMBuilderImpl::expandSystemId(const XMLCh* const, XMLBuffer&) { // The DOM entity resolver doesn't handle this return false; } inline void DOMBuilderImpl::resetEntities() { // Nothing to do on this one } inline void DOMBuilderImpl::startInputSource(const InputSource&) { // The DOM entity resolver doesn't handle this } // --------------------------------------------------------------------------- // DOMBuilderImpl: Getter methods // --------------------------------------------------------------------------- inline DOMErrorHandler* DOMBuilderImpl::getErrorHandler() { return fErrorHandler; } inline const DOMErrorHandler* DOMBuilderImpl::getErrorHandler() const { return fErrorHandler; } inline DOMEntityResolver* DOMBuilderImpl::getEntityResolver() { return fEntityResolver; } inline const DOMEntityResolver* DOMBuilderImpl::getEntityResolver() const { return fEntityResolver; } inline XMLEntityResolver* DOMBuilderImpl::getXMLEntityResolver() { return fXMLEntityResolver; } inline const XMLEntityResolver* DOMBuilderImpl::getXMLEntityResolver() const { return fXMLEntityResolver; } inline DOMBuilderFilter* DOMBuilderImpl::getFilter() { return fFilter; } inline const DOMBuilderFilter* DOMBuilderImpl::getFilter() const { return fFilter; } XERCES_CPP_NAMESPACE_END #endif
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 953 ] ] ]
b8e70aa6425a255cf6a4d9561f88e05f7145fa85
74c8da5b29163992a08a376c7819785998afb588
/NetAnimal/Game/wheel/WheelAnimal2Controller/include/WheelAnimalUI.h
9b70d3300b3b470d568ded61f1016a451a44275a
[]
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
UTF-8
C++
false
false
2,179
h
#ifndef __Orz_WheelAnimalUI_h__ #define __Orz_WheelAnimalUI_h__ #include "DanListener.h" #include "WheelAnimalControllerConfig.h" #include "WheelUIInterface.h" #include "WheelEnum.h" #include <orz/Toolkit_Base/FSMLogic.h> namespace Orz { class Bonus; class Banker; class Time; class List; class WinBg; class Logo; //class Dan; class TVUI; class Light; /*class Dan2;*/ class _OrzWheelAnimal2ControllerExport WheelAnimalUI: public WheelUIInterface/*, public DanListener*/, public Singleton<WheelAnimalUI> { public: virtual void setTheTime(int second); virtual void setLogoShow(bool show); virtual void setStartVisible(bool visible); virtual void setEndUIVisible(bool visible); virtual void runWinner(void); virtual void update(TimeType interval); virtual void addBottom(void); WheelAnimalUI(void); virtual ~WheelAnimalUI(void); bool updateLight(TimeType i); void clearLight(void); void x3(void); void x2(void); void setWinnerShow(bool show); void setGold(int gold ); void showTVUI(bool show); void addTVUI(WheelEnum::AnimalItem item); /* virtual void updateUIData(int p0, int p1, int p2, int p3, int p4, int p5, int p6, int p7, int p8); virtual void uploadPassword(int password); virtual void setMenuDataVisible(bool visible); virtual void menuResult(bool result); virtual void writeMenuXY(int x, int y, unsigned long n); void setSetupVisible(bool show); void setupResult(bool ret); void bao_zhang_ma(const std::string & n); void setDanData(int i, int data);*/ private: // typedef std::map<std::pair<WheelEnum::AnimalType, WheelEnum::LIGHT_COLOR>, int> UIMap; // UIMap _uiMap; boost::scoped_ptr<Time> _time; boost::scoped_ptr<Logo> _logo; boost::scoped_ptr<List> _list; boost::scoped_ptr<Banker> _banker; boost::scoped_ptr<Bonus> _bonus; boost::scoped_ptr<TVUI> _TVUI; boost::scoped_ptr<WinBg> _winBg; /*boost::scoped_ptr<Dan> _dan; boost::scoped_ptr<Dan2> _dan2;*/ boost::scoped_ptr<Light> _light;/* */ }; typedef boost::shared_ptr< WheelAnimalUI> WheelAnimalUIPtr; } #endif
[ [ [ 1, 84 ] ] ]
08ec2338e1d1b337f67d1bf9ef49e60fc1e272e2
9a48be80edc7692df4918c0222a1640545384dbb
/Libraries/Boost1.40/libs/interprocess/example/doc_anonymous_shared_memory.cpp
4ab8ac90db41cea2350283f52aebb68501acc8fb
[ "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
1,226
cpp
////////////////////////////////////////////////////////////////////////////// // // (C) Copyright Ion Gaztanaga 2006-2007. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/interprocess for documentation. // ////////////////////////////////////////////////////////////////////////////// #include <boost/interprocess/detail/config_begin.hpp> //[doc_anonymous_shared_memory #include <boost/interprocess/anonymous_shared_memory.hpp> #include <boost/interprocess/mapped_region.hpp> #include <iostream> #include <cstring> int main () { using namespace boost::interprocess; try{ //Create an anonymous shared memory segment with size 1000 mapped_region region(anonymous_shared_memory(1000)); //Write all the memory to 1 std::memset(region.get_address(), 1, region.get_size()); //The segment is unmapped when "region" goes out of scope } catch(interprocess_exception &ex){ std::cout << ex.what() << std::endl; return 1; } return 0; } //] #include <boost/interprocess/detail/config_end.hpp>
[ "metrix@Blended.(none)" ]
[ [ [ 1, 36 ] ] ]
e0f19f90685c342e8a43fac798172e92c73d5423
c7a66fcf27ae7c2dc41dc557b5c8eee4dd81d9d2
/trunk/cln/viewmodes.cpp
51d0c9581976dbfefcb3e67fefa34fb77e8a48b2
[]
no_license
BackupTheBerlios/mimplugins-svn
1c142eb7186055dfa8deb747529fb99d5fbf201b
18dd487e64a0c3f9d4595ea43e64bc5c80aa765d
refs/heads/master
2021-01-04T14:06:28.579672
2008-01-13T00:12:59
2008-01-13T00:12:59
40,820,556
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
50,832
cpp
/* MirandaPluginInfo IM: the free IM client for Microsoft* Windows* Copyright 2000-2003 Miranda ICQ/IM project, all portions of this codebase are copyrighted to the people listed in contributors.txt. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. contact list view modes (CLVM) $Id: viewmodes.cpp 2873 2006-05-16 20:53:43Z ghazan $ */ #include "commonheaders.h" #include "m_variables.h" #define TIMERID_VIEWMODEEXPIRE 100 extern CLIST_INTERFACE *pcli; extern int _DebugPopup(HANDLE hContact, const char *fmt, ...); extern struct CluiData g_CluiData; extern HIMAGELIST hCListImages; typedef int (__cdecl *pfnEnumCallback)(char *szName); static HWND clvmHwnd = 0; static int clvm_curItem = 0; HMENU hViewModeMenu = 0; static HWND hwndSelector = 0; static HIMAGELIST himlViewModes = 0; static HANDLE hInfoItem = 0; static int nullImage; static DWORD stickyStatusMask = 0; static char g_szModename[2048]; static int g_ViewModeOptDlg = FALSE; static UINT _page1Controls[] = {IDC_STATIC1, IDC_STATIC2, IDC_STATIC3, IDC_STATIC5, IDC_STATIC4, IDC_STATIC8, IDC_ADDVIEWMODE, IDC_DELETEVIEWMODE, IDC_NEWVIEMODE, IDC_GROUPS, IDC_PROTOCOLS, IDC_VIEWMODES, IDC_STATUSMODES, IDC_STATIC12, IDC_STATIC13, IDC_STATIC14, IDC_PROTOGROUPOP, IDC_GROUPSTATUSOP, IDC_AUTOCLEAR, IDC_AUTOCLEARVAL, IDC_AUTOCLEARSPIN, IDC_STATIC15, IDC_STATIC16, 0}; static UINT _page2Controls[] = {IDC_CLIST, IDC_STATIC9, IDC_STATIC8, IDC_CLEARALL, IDC_CURVIEWMODE2, 0}; void ApplyViewMode(const char *name); /* * enumerate all view modes, call the callback function with the mode name * useful for filling lists, menus and so on.. */ int CLVM_EnumProc(const char *szSetting, LPARAM lParam) { pfnEnumCallback EnumCallback = (pfnEnumCallback)lParam; if (szSetting == NULL) return(1); EnumCallback((char *)szSetting); return(1); } void CLVM_EnumModes(pfnEnumCallback EnumCallback) { DBCONTACTENUMSETTINGS dbces; dbces.pfnEnumProc = CLVM_EnumProc; dbces.szModule = CLVM_MODULE; dbces.ofsSettings=0; dbces.lParam = (LPARAM)EnumCallback; CallService(MS_DB_CONTACT_ENUMSETTINGS,0,(LPARAM)&dbces); } int FillModes(char *szsetting) { if(szsetting[0] == 'ö') return 1; SendDlgItemMessageA(clvmHwnd, IDC_VIEWMODES, LB_INSERTSTRING, -1, (LPARAM)szsetting); return 1; } static void ShowPage(HWND hwnd, int page) { int i = 0; switch(page) { case 0: while(_page1Controls[i] != 0) ShowWindow(GetDlgItem(hwnd, _page1Controls[i++]), SW_SHOW); i = 0; while(_page2Controls[i] != 0) ShowWindow(GetDlgItem(hwnd, _page2Controls[i++]), SW_HIDE); break; case 1: while(_page1Controls[i] != 0) ShowWindow(GetDlgItem(hwnd, _page1Controls[i++]), SW_HIDE); i = 0; while(_page2Controls[i] != 0) ShowWindow(GetDlgItem(hwnd, _page2Controls[i++]), SW_SHOW); break; } } static int UpdateClistItem(HANDLE hContact, DWORD mask) { int i; for(i = ID_STATUS_OFFLINE; i <= ID_STATUS_OUTTOLUNCH; i++) SendDlgItemMessage(clvmHwnd, IDC_CLIST, CLM_SETEXTRAIMAGE, (WPARAM)hContact, MAKELONG(i - ID_STATUS_OFFLINE, (1 << (i - ID_STATUS_OFFLINE)) & mask ? i - ID_STATUS_OFFLINE : nullImage)); return 0; } static DWORD GetMaskForItem(HANDLE hItem) { int i; DWORD dwMask = 0; for(i = 0; i <= ID_STATUS_OUTTOLUNCH - ID_STATUS_OFFLINE; i++) dwMask |= (SendDlgItemMessage(clvmHwnd, IDC_CLIST, CLM_GETEXTRAIMAGE, (WPARAM)hItem, i) == nullImage ? 0 : 1 << i); return dwMask; } static void UpdateStickies() { HANDLE hContact = (HANDLE)CallService(MS_DB_CONTACT_FINDFIRST, 0, 0); HANDLE hItem; DWORD localMask; int i; while(hContact) { hItem = (HANDLE)SendDlgItemMessage(clvmHwnd, IDC_CLIST, CLM_FINDCONTACT, (WPARAM)hContact, 0); if(hItem) SendDlgItemMessage(clvmHwnd, IDC_CLIST, CLM_SETCHECKMARK, (WPARAM)hItem, DBGetContactSettingByte(hContact, "CLVM", g_szModename, 0) ? 1 : 0); localMask = HIWORD(DBGetContactSettingDword(hContact, "CLVM", g_szModename, 0)); UpdateClistItem(hItem, (localMask == 0 || localMask == stickyStatusMask) ? stickyStatusMask : localMask); hContact = (HANDLE)CallService(MS_DB_CONTACT_FINDNEXT, (WPARAM)hContact, 0); } { HANDLE hItem; for(i = ID_STATUS_OFFLINE; i <= ID_STATUS_OUTTOLUNCH; i++) SendDlgItemMessage(clvmHwnd, IDC_CLIST, CLM_SETEXTRAIMAGE, (WPARAM)hInfoItem, MAKELONG(i - ID_STATUS_OFFLINE, (1 << (i - ID_STATUS_OFFLINE)) & stickyStatusMask ? i - ID_STATUS_OFFLINE : ID_STATUS_OUTTOLUNCH - ID_STATUS_OFFLINE + 1)); hItem=(HANDLE)SendDlgItemMessage(clvmHwnd, IDC_CLIST, CLM_GETNEXTITEM,CLGN_ROOT,0); hItem=(HANDLE)SendDlgItemMessage(clvmHwnd, IDC_CLIST,CLM_GETNEXTITEM,CLGN_NEXTGROUP, (LPARAM)hItem); while(hItem) { for(i = ID_STATUS_OFFLINE; i <= ID_STATUS_OUTTOLUNCH; i++) SendDlgItemMessage(clvmHwnd, IDC_CLIST, CLM_SETEXTRAIMAGE, (WPARAM)hItem, MAKELONG(i - ID_STATUS_OFFLINE, nullImage)); hItem=(HANDLE)SendDlgItemMessage(clvmHwnd, IDC_CLIST,CLM_GETNEXTITEM,CLGN_NEXTGROUP,(LPARAM)hItem); } ShowPage(clvmHwnd, 0); } } static int FillDialog(HWND hwnd) { LVCOLUMN lvc = {0}; HWND hwndList = GetDlgItem(hwnd, IDC_PROTOCOLS); LVITEMA item = {0}; int protoCount = 0, i, newItem; PROTOCOLDESCRIPTOR **protos = 0; CLVM_EnumModes(FillModes); ListView_SetExtendedListViewStyle(GetDlgItem(hwnd, IDC_PROTOCOLS), LVS_EX_CHECKBOXES); lvc.mask = LVCF_FMT; lvc.fmt = LVCFMT_IMAGE | LVCFMT_LEFT; ListView_InsertColumn(GetDlgItem(hwnd, IDC_PROTOCOLS), 0, &lvc); // fill protocols... CallService(MS_PROTO_ENUMPROTOCOLS, (WPARAM)&protoCount, (LPARAM)&protos); item.mask = LVIF_TEXT; item.iItem = 1000; for(i = 0; i < protoCount; i++) { if(protos[i]->type != PROTOTYPE_PROTOCOL) continue; item.pszText = protos[i]->szName; newItem = SendMessageA(hwndList, LVM_INSERTITEMA, 0, (LPARAM)&item); } ListView_SetColumnWidth(hwndList, 0, LVSCW_AUTOSIZE); ListView_Arrange(hwndList, LVA_ALIGNLEFT | LVA_ALIGNTOP); // fill groups { LVITEM item = {0}; char buf[20]; DBVARIANT dbv = {0}; hwndList = GetDlgItem(hwnd, IDC_GROUPS); ListView_SetExtendedListViewStyle(hwndList, LVS_EX_CHECKBOXES); lvc.mask = LVCF_FMT; lvc.fmt = LVCFMT_IMAGE | LVCFMT_LEFT; ListView_InsertColumn(hwndList, 0, &lvc); item.mask = LVIF_TEXT; item.iItem = 1000; item.pszText = TranslateT("Ungrouped contacts"); newItem = SendMessage(hwndList, LVM_INSERTITEM, 0, (LPARAM)&item); for(i = 0;;i++) { mir_snprintf(buf, 20, "%d", i); if(DBGetContactSettingTString(NULL, "CListGroups", buf, &dbv)) break; item.pszText = &dbv.ptszVal[1]; newItem = SendMessage(hwndList, LVM_INSERTITEM, 0, (LPARAM)&item); DBFreeVariant(&dbv); } ListView_SetColumnWidth(hwndList, 0, LVSCW_AUTOSIZE); ListView_Arrange(hwndList, LVA_ALIGNLEFT | LVA_ALIGNTOP); } hwndList = GetDlgItem(hwnd, IDC_STATUSMODES); ListView_SetExtendedListViewStyle(hwndList, LVS_EX_CHECKBOXES); lvc.mask = LVCF_FMT; lvc.fmt = LVCFMT_IMAGE | LVCFMT_LEFT; ListView_InsertColumn(hwndList, 0, &lvc); for(i = ID_STATUS_OFFLINE; i <= ID_STATUS_OUTTOLUNCH; i++) { item.pszText = Translate((char *)CallService(MS_CLIST_GETSTATUSMODEDESCRIPTION, (WPARAM)i, 0)); item.iItem = i - ID_STATUS_OFFLINE; newItem = SendMessageA(hwndList, LVM_INSERTITEMA, 0, (LPARAM)&item); } ListView_SetColumnWidth(hwndList, 0, LVSCW_AUTOSIZE); ListView_Arrange(hwndList, LVA_ALIGNLEFT | LVA_ALIGNTOP); SendDlgItemMessageA(hwnd, IDC_PROTOGROUPOP, CB_INSERTSTRING, -1, (LPARAM)Translate("And")); SendDlgItemMessageA(hwnd, IDC_PROTOGROUPOP, CB_INSERTSTRING, -1, (LPARAM)Translate("Or")); SendDlgItemMessageA(hwnd, IDC_GROUPSTATUSOP, CB_INSERTSTRING, -1, (LPARAM)Translate("And")); SendDlgItemMessageA(hwnd, IDC_GROUPSTATUSOP, CB_INSERTSTRING, -1, (LPARAM)Translate("Or")); return 0; } static void SetAllChildIcons(HWND hwndList,HANDLE hFirstItem,int iColumn,int iImage) { int typeOfFirst,iOldIcon; HANDLE hItem,hChildItem; typeOfFirst=SendMessage(hwndList,CLM_GETITEMTYPE,(WPARAM)hFirstItem,0); //check groups if(typeOfFirst==CLCIT_GROUP) hItem=hFirstItem; else hItem=(HANDLE)SendMessage(hwndList,CLM_GETNEXTITEM,CLGN_NEXTGROUP,(LPARAM)hFirstItem); while(hItem) { hChildItem=(HANDLE)SendMessage(hwndList,CLM_GETNEXTITEM,CLGN_CHILD,(LPARAM)hItem); if(hChildItem) SetAllChildIcons(hwndList,hChildItem,iColumn,iImage); hItem=(HANDLE)SendMessage(hwndList,CLM_GETNEXTITEM,CLGN_NEXTGROUP,(LPARAM)hItem); } //check contacts if(typeOfFirst==CLCIT_CONTACT) hItem=hFirstItem; else hItem=(HANDLE)SendMessage(hwndList,CLM_GETNEXTITEM,CLGN_NEXTCONTACT,(LPARAM)hFirstItem); while(hItem) { iOldIcon=SendMessage(hwndList,CLM_GETEXTRAIMAGE,(WPARAM)hItem,iColumn); if(iOldIcon!=0xFF && iOldIcon!=iImage) SendMessage(hwndList,CLM_SETEXTRAIMAGE,(WPARAM)hItem,MAKELPARAM(iColumn,iImage)); hItem=(HANDLE)SendMessage(hwndList,CLM_GETNEXTITEM,CLGN_NEXTCONTACT,(LPARAM)hItem); } } static void SetIconsForColumn(HWND hwndList,HANDLE hItem,HANDLE hItemAll,int iColumn,int iImage) { int itemType; itemType=SendMessage(hwndList,CLM_GETITEMTYPE,(WPARAM)hItem,0); if(itemType==CLCIT_CONTACT) { int oldiImage = SendMessage(hwndList,CLM_GETEXTRAIMAGE,(WPARAM)hItem,iColumn); if (oldiImage!=0xFF&&oldiImage!=iImage) SendMessage(hwndList,CLM_SETEXTRAIMAGE,(WPARAM)hItem,MAKELPARAM(iColumn,iImage)); } else if(itemType==CLCIT_INFO) { int oldiImage = SendMessage(hwndList,CLM_GETEXTRAIMAGE,(WPARAM)hItem,iColumn); if (oldiImage!=0xFF&&oldiImage!=iImage) SendMessage(hwndList,CLM_SETEXTRAIMAGE,(WPARAM)hItem,MAKELPARAM(iColumn,iImage)); if(hItem == hItemAll) SetAllChildIcons(hwndList,hItem,iColumn,iImage); else SendMessage(hwndList,CLM_SETEXTRAIMAGE,(WPARAM)hItem,MAKELPARAM(iColumn,iImage)); //hItemUnknown } else if(itemType==CLCIT_GROUP) { int oldiImage = SendMessage(hwndList,CLM_GETEXTRAIMAGE,(WPARAM)hItem,iColumn); if (oldiImage!=0xFF&&oldiImage!=iImage) SendMessage(hwndList,CLM_SETEXTRAIMAGE,(WPARAM)hItem,MAKELPARAM(iColumn,iImage)); hItem=(HANDLE)SendMessage(hwndList,CLM_GETNEXTITEM,CLGN_CHILD,(LPARAM)hItem); if(hItem) SetAllChildIcons(hwndList,hItem,iColumn,iImage); } } void SaveViewMode(const char *name, const TCHAR *szGroupFilter, const char *szProtoFilter, DWORD statusMask, DWORD stickyStatusMask, unsigned int options, unsigned int stickies, unsigned int operators) { char szSetting[512]; mir_snprintf(szSetting, 512, "%c%s_PF", 246, name); DBWriteContactSettingString(NULL, CLVM_MODULE, szSetting, szProtoFilter); mir_snprintf(szSetting, 512, "%c%s_GF", 246, name); DBWriteContactSettingTString(NULL, CLVM_MODULE, szSetting, szGroupFilter); mir_snprintf(szSetting, 512, "%c%s_SM", 246, name); DBWriteContactSettingDword(NULL, CLVM_MODULE, szSetting, statusMask); mir_snprintf(szSetting, 512, "%c%s_SSM", 246, name); DBWriteContactSettingDword(NULL, CLVM_MODULE, szSetting, stickyStatusMask); mir_snprintf(szSetting, 512, "%c%s_OPT", 246, name); DBWriteContactSettingDword(NULL, CLVM_MODULE, szSetting, options); DBWriteContactSettingDword(NULL, CLVM_MODULE, name, MAKELONG((unsigned short)operators, (unsigned short)stickies)); } /* * saves the state of the filter definitions for the current item */ void SaveState() { TCHAR newGroupFilter[2048] = _T("|"); char newProtoFilter[2048] = "|"; int i, iLen; HWND hwndList; char *szModeName = NULL; DWORD statusMask = 0; HANDLE hContact, hItem; DWORD operators = 0; if(clvm_curItem == -1) return; { LVITEMA item = {0}; char szTemp[256]; hwndList = GetDlgItem(clvmHwnd, IDC_PROTOCOLS); for(i = 0; i < ListView_GetItemCount(hwndList); i++) { if(ListView_GetCheckState(hwndList, i)) { item.mask = LVIF_TEXT; item.pszText = szTemp; item.cchTextMax = 255; item.iItem = i; SendMessageA(hwndList, LVM_GETITEMA, 0, (LPARAM)&item); strncat(newProtoFilter, szTemp, 2048); strncat(newProtoFilter, "|", 2048); newProtoFilter[2047] = 0; } } } { LVITEM item = {0}; TCHAR szTemp[256]; hwndList = GetDlgItem(clvmHwnd, IDC_GROUPS); operators |= ListView_GetCheckState(hwndList, 0) ? CLVM_INCLUDED_UNGROUPED : 0; for(i = 0; i < ListView_GetItemCount(hwndList); i++) { if(ListView_GetCheckState(hwndList, i)) { item.mask = LVIF_TEXT; item.pszText = szTemp; item.cchTextMax = 255; item.iItem = i; SendMessage(hwndList, LVM_GETITEM, 0, (LPARAM)&item); _tcsncat(newGroupFilter, szTemp, 2048); _tcsncat(newGroupFilter, _T("|"), 2048); newGroupFilter[2047] = 0; } } } hwndList = GetDlgItem(clvmHwnd, IDC_STATUSMODES); for(i = ID_STATUS_OFFLINE; i <= ID_STATUS_OUTTOLUNCH; i++) { if(ListView_GetCheckState(hwndList, i - ID_STATUS_OFFLINE)) statusMask |= (1 << (i - ID_STATUS_OFFLINE)); } iLen = SendMessageA(GetDlgItem(clvmHwnd, IDC_VIEWMODES), LB_GETTEXTLEN, clvm_curItem, 0); if(iLen) { unsigned int stickies = 0; DWORD dwGlobalMask, dwLocalMask; szModeName = malloc(iLen + 1); if(szModeName) { DWORD options; //char *vastring = NULL; //int len = GetWindowTextLengthA(GetDlgItem(clvmHwnd, IDC_VARIABLES)) + 1; //vastring = (char *)malloc(len); //if(vastring) // GetDlgItemTextA(clvmHwnd, IDC_VARIABLES, vastring, len); SendDlgItemMessageA(clvmHwnd, IDC_VIEWMODES, LB_GETTEXT, clvm_curItem, (LPARAM)szModeName); dwGlobalMask = GetMaskForItem(hInfoItem); hContact = (HANDLE)CallService(MS_DB_CONTACT_FINDFIRST, 0, 0); while(hContact) { hItem = (HANDLE)SendDlgItemMessage(clvmHwnd, IDC_CLIST, CLM_FINDCONTACT, (WPARAM)hContact, 0); if(hItem) { if(SendDlgItemMessage(clvmHwnd, IDC_CLIST, CLM_GETCHECKMARK, (WPARAM)hItem, 0)) { dwLocalMask = GetMaskForItem(hItem); DBWriteContactSettingDword(hContact, "CLVM", szModeName, MAKELONG(1, (unsigned short)dwLocalMask)); stickies++; } else { if(DBGetContactSettingDword(hContact, "CLVM", szModeName, 0)) DBWriteContactSettingDword(hContact, "CLVM", szModeName, 0); } } hContact = (HANDLE)CallService(MS_DB_CONTACT_FINDNEXT, (WPARAM)hContact, 0); } operators |= ((SendDlgItemMessage(clvmHwnd, IDC_PROTOGROUPOP, CB_GETCURSEL, 0, 0) == 1 ? CLVM_PROTOGROUP_OP : 0) | (SendDlgItemMessage(clvmHwnd, IDC_GROUPSTATUSOP, CB_GETCURSEL, 0, 0) == 1 ? CLVM_GROUPSTATUS_OP : 0) | (IsDlgButtonChecked(clvmHwnd, IDC_AUTOCLEAR) ? CLVM_AUTOCLEAR : 0)); options = SendDlgItemMessage(clvmHwnd, IDC_AUTOCLEARSPIN, UDM_GETPOS, 0, 0); SaveViewMode(szModeName, newGroupFilter, newProtoFilter, statusMask, dwGlobalMask, options, stickies, operators); //free(vastring); free(szModeName); } } EnableWindow(GetDlgItem(clvmHwnd, IDC_APPLY), FALSE); } /* * updates the filter list boxes with the data taken from the filtering string */ void UpdateFilters() { DBVARIANT dbv_pf = {0}; DBVARIANT dbv_gf = {0}; char szSetting[128]; char *szBuf = NULL; int iLen; DWORD statusMask = 0, localMask = 0; DWORD dwFlags; DWORD opt; char szTemp[100]; if(clvm_curItem == LB_ERR) return; iLen = SendDlgItemMessageA(clvmHwnd, IDC_VIEWMODES, LB_GETTEXTLEN, clvm_curItem, 0); if(iLen == 0) return; szBuf = (char *)malloc(iLen + 1); SendDlgItemMessageA(clvmHwnd, IDC_VIEWMODES, LB_GETTEXT, clvm_curItem, (LPARAM)szBuf); strncpy(g_szModename, szBuf, sizeof(g_szModename)); g_szModename[sizeof(g_szModename) - 1] = 0; mir_snprintf(szTemp, 100, Translate("Current view mode: %s"), g_szModename); SetDlgItemTextA(clvmHwnd, IDC_CURVIEWMODE2, szTemp); mir_snprintf(szSetting, 128, "%c%s_PF", 246, szBuf); if(DBGetContactSetting(NULL, CLVM_MODULE, szSetting, &dbv_pf)) goto cleanup; mir_snprintf(szSetting, 128, "%c%s_GF", 246, szBuf); if(DBGetContactSettingTString(NULL, CLVM_MODULE, szSetting, &dbv_gf)) goto cleanup; mir_snprintf(szSetting, 128, "%c%s_OPT", 246, szBuf); if((opt = DBGetContactSettingDword(NULL, CLVM_MODULE, szSetting, -1)) != -1) { SendDlgItemMessage(clvmHwnd, IDC_AUTOCLEARSPIN, UDM_SETPOS, 0, MAKELONG(LOWORD(opt), 0)); } mir_snprintf(szSetting, 128, "%c%s_SM", 246, szBuf); statusMask = DBGetContactSettingDword(NULL, CLVM_MODULE, szSetting, -1); mir_snprintf(szSetting, 128, "%c%s_SSM", 246, szBuf); stickyStatusMask = DBGetContactSettingDword(NULL, CLVM_MODULE, szSetting, -1); dwFlags = DBGetContactSettingDword(NULL, CLVM_MODULE, szBuf, 0); { LVITEMA item = {0}; char szTemp[256]; char szMask[256]; int i; HWND hwndList = GetDlgItem(clvmHwnd, IDC_PROTOCOLS); item.mask = LVIF_TEXT; item.pszText = szTemp; item.cchTextMax = 255; for(i = 0; i < ListView_GetItemCount(hwndList); i++) { item.iItem = i; SendMessageA(hwndList, LVM_GETITEMA, 0, (LPARAM)&item); mir_snprintf(szMask, 256, "%s|", szTemp); if(dbv_pf.pszVal && strstr(dbv_pf.pszVal, szMask)) ListView_SetCheckState(hwndList, i, TRUE) else ListView_SetCheckState(hwndList, i, FALSE); } } { LVITEM item = {0}; TCHAR szTemp[256]; TCHAR szMask[256]; int i; HWND hwndList = GetDlgItem(clvmHwnd, IDC_GROUPS); item.mask = LVIF_TEXT; item.pszText = szTemp; item.cchTextMax = 255; ListView_SetCheckState(hwndList, 0, dwFlags & CLVM_INCLUDED_UNGROUPED ? TRUE : FALSE); for(i = 1; i < ListView_GetItemCount(hwndList); i++) { item.iItem = i; SendMessage(hwndList, LVM_GETITEM, 0, (LPARAM)&item); _sntprintf(szMask, 256, _T("%s|"), szTemp); if(dbv_gf.ptszVal && _tcsstr(dbv_gf.ptszVal, szMask)) ListView_SetCheckState(hwndList, i, TRUE) else ListView_SetCheckState(hwndList, i, FALSE); } } { HWND hwndList = GetDlgItem(clvmHwnd, IDC_STATUSMODES); int i; for(i = ID_STATUS_OFFLINE; i <= ID_STATUS_OUTTOLUNCH; i++) { if((1 << (i - ID_STATUS_OFFLINE)) & statusMask) ListView_SetCheckState(hwndList, i - ID_STATUS_OFFLINE, TRUE) else ListView_SetCheckState(hwndList, i - ID_STATUS_OFFLINE, FALSE); } } SendDlgItemMessage(clvmHwnd, IDC_PROTOGROUPOP, CB_SETCURSEL, dwFlags & CLVM_PROTOGROUP_OP ? 1 : 0, 0); SendDlgItemMessage(clvmHwnd, IDC_GROUPSTATUSOP, CB_SETCURSEL, dwFlags & CLVM_GROUPSTATUS_OP ? 1 : 0, 0); CheckDlgButton(clvmHwnd, IDC_AUTOCLEAR, dwFlags & CLVM_AUTOCLEAR ? 1 : 0); UpdateStickies(); ShowPage(clvmHwnd, 0); cleanup: DBFreeVariant(&dbv_pf); DBFreeVariant(&dbv_gf); free(szBuf); } BOOL CALLBACK DlgProcViewModesSetup(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) { clvmHwnd = hwndDlg; switch(msg) { case WM_INITDIALOG: { int i = 0; TCITEMA tci; RECT rcClient; CLCINFOITEM cii = {0}; HICON hIcon; himlViewModes = ImageList_Create(16, 16, ILC_MASK | (IsWinVerXPPlus() ? ILC_COLOR32 : ILC_COLOR16), 12, 0); for(i = ID_STATUS_OFFLINE; i <= ID_STATUS_OUTTOLUNCH; i++) ImageList_AddIcon(himlViewModes, LoadSkinnedProtoIcon(NULL, i)); hIcon = LoadImage(g_hInst, MAKEINTRESOURCE(IDI_MINIMIZE), IMAGE_ICON, 16, 16, 0); nullImage = ImageList_AddIcon(himlViewModes, hIcon); DestroyIcon(hIcon); GetClientRect(hwndDlg, &rcClient); tci.mask = TCIF_PARAM|TCIF_TEXT; tci.lParam = 0; tci.pszText = Translate("Sticky contacts"); SendMessageA(GetDlgItem(hwndDlg, IDC_TAB), TCM_INSERTITEMA, (WPARAM)0, (LPARAM)&tci); tci.pszText = Translate("Filtering"); SendMessageA(GetDlgItem(hwndDlg, IDC_TAB), TCM_INSERTITEMA, (WPARAM)0, (LPARAM)&tci); TabCtrl_SetCurSel(GetDlgItem(hwndDlg, IDC_TAB), 0); TranslateDialogDefault(hwndDlg); FillDialog(hwndDlg); EnableWindow(GetDlgItem(hwndDlg, IDC_ADDVIEWMODE), FALSE); SendDlgItemMessage(hwndDlg, IDC_CLIST, CLM_SETEXTRAIMAGELIST, 0, (LPARAM)himlViewModes); SendDlgItemMessage(hwndDlg, IDC_CLIST, CLM_SETEXTRACOLUMNS, ID_STATUS_OUTTOLUNCH - ID_STATUS_OFFLINE, 0); cii.cbSize = sizeof(cii); cii.hParentGroup = 0; cii.pszText = _T("*** All contacts ***"); hInfoItem = (HANDLE)SendDlgItemMessage(hwndDlg, IDC_CLIST, CLM_ADDINFOITEM, 0, (LPARAM)&cii); SendDlgItemMessage(hwndDlg, IDC_CLIST, CLM_SETHIDEEMPTYGROUPS, 1, 0); if(SendDlgItemMessage(hwndDlg, IDC_VIEWMODES, LB_SETCURSEL, 0, 0) != LB_ERR) { clvm_curItem = 0; UpdateFilters(); } else clvm_curItem = -1; g_ViewModeOptDlg = TRUE; i = 0; while(_page2Controls[i] != 0) ShowWindow(GetDlgItem(hwndDlg, _page2Controls[i++]), SW_HIDE); ShowWindow(hwndDlg, SW_SHOWNORMAL); EnableWindow(GetDlgItem(hwndDlg, IDC_APPLY), FALSE); //EnableWindow(GetDlgItem(hwndDlg, IDC_VARIABLES), FALSE); //EnableWindow(GetDlgItem(hwndDlg, IDC_VARIABLES), ServiceExists(MS_VARS_FORMATSTRING)); SendDlgItemMessage(hwndDlg, IDC_AUTOCLEARSPIN, UDM_SETRANGE, 0, MAKELONG(1000, 0)); SetWindowText(hwndDlg, TranslateT("Configure view modes")); return TRUE; } case WM_COMMAND: switch(LOWORD(wParam)) { case IDC_PROTOGROUPOP: case IDC_GROUPSTATUSOP: if (HIWORD(wParam) == CBN_SELCHANGE) EnableWindow(GetDlgItem(hwndDlg, IDC_APPLY), TRUE); break; case IDC_AUTOCLEAR: EnableWindow(GetDlgItem(hwndDlg, IDC_APPLY), TRUE); break; case IDC_AUTOCLEARVAL: if(HIWORD(wParam) == EN_CHANGE && GetFocus() == (HWND)lParam) EnableWindow(GetDlgItem(hwndDlg, IDC_APPLY), TRUE); break; case IDC_DELETEVIEWMODE: { if(MessageBoxA(0, Translate("Really delete this view mode? This cannot be undone"), Translate("Delete a view mode"), MB_YESNO | MB_ICONQUESTION) == IDYES) { char szSetting[256]; int iLen = SendDlgItemMessage(hwndDlg, IDC_VIEWMODES, LB_GETTEXTLEN, SendDlgItemMessage(hwndDlg, IDC_VIEWMODES, LB_GETCURSEL, 0, 0), 0); if(iLen) { char *szBuf = malloc(iLen + 1); if(szBuf) { HANDLE hContact; SendDlgItemMessageA(hwndDlg, IDC_VIEWMODES, LB_GETTEXT, SendDlgItemMessage(hwndDlg, IDC_VIEWMODES, LB_GETCURSEL, 0, 0), (LPARAM)szBuf); mir_snprintf(szSetting, 256, "%c%s_PF", 246, szBuf); DBDeleteContactSetting(NULL, CLVM_MODULE, szSetting); mir_snprintf(szSetting, 256, "%c%s_GF", 246, szBuf); DBDeleteContactSetting(NULL, CLVM_MODULE, szSetting); mir_snprintf(szSetting, 256, "%c%s_SM", 246, szBuf); DBDeleteContactSetting(NULL, CLVM_MODULE, szSetting); mir_snprintf(szSetting, 256, "%c%s_VA", 246, szBuf); DBDeleteContactSetting(NULL, CLVM_MODULE, szSetting); mir_snprintf(szSetting, 256, "%c%s_SSM", 246, szBuf); DBDeleteContactSetting(NULL, CLVM_MODULE, szSetting); DBDeleteContactSetting(NULL, CLVM_MODULE, szBuf); if(!strcmp(g_CluiData.current_viewmode, szBuf) && lstrlenA(szBuf) == lstrlenA(g_CluiData.current_viewmode)) { g_CluiData.bFilterEffective = 0; pcli->pfnClcBroadcast(CLM_AUTOREBUILD, 0, 0); SetWindowTextA(hwndSelector, Translate("No view mode")); } hContact = (HANDLE)CallService(MS_DB_CONTACT_FINDFIRST, 0, 0); while(hContact) { if(DBGetContactSettingDword(hContact, "CLVM", szBuf, -1) != -1) DBWriteContactSettingDword(hContact, "CLVM", szBuf, 0); hContact = (HANDLE)CallService(MS_DB_CONTACT_FINDNEXT, (WPARAM)hContact, 0); } SendDlgItemMessage(hwndDlg, IDC_VIEWMODES, LB_DELETESTRING, SendDlgItemMessage(hwndDlg, IDC_VIEWMODES, LB_GETCURSEL, 0, 0), 0); if(SendDlgItemMessage(hwndDlg, IDC_VIEWMODES, LB_SETCURSEL, 0, 0) != LB_ERR) { clvm_curItem = 0; UpdateFilters(); } else clvm_curItem = -1; free(szBuf); } } } break; } case IDC_ADDVIEWMODE: { char szBuf[256]; szBuf[0] = 0; GetDlgItemTextA(hwndDlg, IDC_NEWVIEMODE, szBuf, 256); szBuf[255] = 0; if(lstrlenA(szBuf) > 2) { if(DBGetContactSettingDword(NULL, CLVM_MODULE, szBuf, -1) != -1) MessageBox(0, TranslateT("A view mode with this name does alredy exist"), TranslateT("Duplicate name"), MB_OK); else { int iNewItem = SendDlgItemMessageA(hwndDlg, IDC_VIEWMODES, LB_INSERTSTRING, -1, (LPARAM)szBuf); if(iNewItem != LB_ERR) { SendDlgItemMessage(hwndDlg, IDC_VIEWMODES, LB_SETCURSEL, (WPARAM)iNewItem, 0); SaveViewMode(szBuf, _T(""), "", -1, -1, 0, 0, 0); clvm_curItem = iNewItem; UpdateStickies(); SendDlgItemMessage(hwndDlg, IDC_PROTOGROUPOP, CB_SETCURSEL, 0, 0); SendDlgItemMessage(hwndDlg, IDC_GROUPSTATUSOP, CB_SETCURSEL, 0, 0); } } SetDlgItemTextA(hwndDlg, IDC_NEWVIEMODE, ""); } EnableWindow(GetDlgItem(hwndDlg, IDC_ADDVIEWMODE), FALSE); break; } case IDC_CLEARALL: { HANDLE hItem; HANDLE hContact = (HANDLE)CallService(MS_DB_CONTACT_FINDFIRST, 0, 0); while(hContact) { hItem = (HANDLE)SendDlgItemMessage(hwndDlg, IDC_CLIST, CLM_FINDCONTACT, (WPARAM)hContact, 0); if(hItem) SendDlgItemMessage(hwndDlg, IDC_CLIST, CLM_SETCHECKMARK, (WPARAM)hItem, 0); hContact = (HANDLE)CallService(MS_DB_CONTACT_FINDNEXT, (WPARAM)hContact, 0); } } case IDOK: case IDC_APPLY: SaveState(); if(g_CluiData.bFilterEffective) ApplyViewMode(g_CluiData.current_viewmode); if(LOWORD(wParam) == IDOK) DestroyWindow(hwndDlg); break; case IDCANCEL: DestroyWindow(hwndDlg); break; } if(LOWORD(wParam) == IDC_NEWVIEMODE && HIWORD(wParam) == EN_CHANGE) EnableWindow(GetDlgItem(hwndDlg, IDC_ADDVIEWMODE), TRUE); if(LOWORD(wParam) == IDC_VIEWMODES && HIWORD(wParam) == LBN_SELCHANGE) { SaveState(); clvm_curItem = SendDlgItemMessage(hwndDlg, IDC_VIEWMODES, LB_GETCURSEL, 0, 0); UpdateFilters(); //EnableWindow(GetDlgItem(hwndDlg, IDC_APPLY), TRUE); //SendMessage(GetParent(hwndDlg), PSM_CHANGED, 0, 0); } break; case WM_NOTIFY: { switch (((LPNMHDR) lParam)->idFrom) { case IDC_GROUPS: case IDC_STATUSMODES: case IDC_PROTOCOLS: case IDC_CLIST: if (((LPNMHDR) lParam)->code == NM_CLICK || ((LPNMHDR) lParam)->code == CLN_CHECKCHANGED) EnableWindow(GetDlgItem(hwndDlg, IDC_APPLY), TRUE); switch (((LPNMHDR)lParam)->code) { case CLN_NEWCONTACT: case CLN_LISTREBUILT: //SetAllContactIcons(GetDlgItem(hwndDlg,IDC_CLIST)); //fall through /* case CLN_CONTACTMOVED: SetListGroupIcons(GetDlgItem(hwndDlg,IDC_LIST),(HANDLE)SendDlgItemMessage(hwndDlg,IDC_LIST,CLM_GETNEXTITEM,CLGN_ROOT,0),hItemAll,NULL); break; case CLN_OPTIONSCHANGED: ResetListOptions(GetDlgItem(hwndDlg,IDC_LIST)); break; case CLN_CHECKCHANGED: { HANDLE hItem; NMCLISTCONTROL *nm=(NMCLISTCONTROL*)lParam; int typeOfItem = SendDlgItemMessage(hwndDlg, IDC_LIST, CLM_GETITEMTYPE,(WPARAM)nm->hItem, 0); break; }*/ case NM_CLICK: { HANDLE hItem; NMCLISTCONTROL *nm=(NMCLISTCONTROL*)lParam; DWORD hitFlags; int iImage; if(nm->iColumn==-1) break; hItem = (HANDLE)SendDlgItemMessage(hwndDlg,IDC_CLIST,CLM_HITTEST,(WPARAM)&hitFlags,MAKELPARAM(nm->pt.x,nm->pt.y)); if(hItem==NULL) break; if(!(hitFlags&CLCHT_ONITEMEXTRA)) break; iImage = SendDlgItemMessage(hwndDlg,IDC_CLIST,CLM_GETEXTRAIMAGE,(WPARAM)hItem,MAKELPARAM(nm->iColumn,0)); if(iImage == nullImage) iImage = nm->iColumn; else if(iImage!=0xFF) iImage = nullImage; SetIconsForColumn(GetDlgItem(hwndDlg,IDC_CLIST),hItem,hInfoItem,nm->iColumn,iImage); //SetListGroupIcons(GetDlgItem(hwndDlg,IDC_CLIST),(HANDLE)SendDlgItemMessage(hwndDlg,IDC_LIST,CLM_GETNEXTITEM,CLGN_ROOT,0),hInfoItem,NULL); break; } } break; case IDC_TAB: if (((LPNMHDR) lParam)->code == TCN_SELCHANGE) { int id = TabCtrl_GetCurSel(GetDlgItem(hwndDlg, IDC_TAB)); if(id == 0) ShowPage(hwndDlg, 0); else ShowPage(hwndDlg, 1); break; } } break; } case WM_DESTROY: ImageList_RemoveAll(himlViewModes); ImageList_Destroy(himlViewModes); g_ViewModeOptDlg = FALSE; break; } return FALSE; } static int menuCounter = 0; static int FillMenuCallback(char *szSetting) { if(szSetting[0] == (char)246) return 1; AppendMenuA(hViewModeMenu, MF_STRING, menuCounter++, szSetting); return 1; } void BuildViewModeMenu() { if(hViewModeMenu) DestroyMenu(hViewModeMenu); menuCounter = 100; hViewModeMenu = CreatePopupMenu(); CLVM_EnumModes(FillMenuCallback); } static UINT _buttons[] = {IDC_RESETMODES, IDC_SELECTMODE, IDC_CONFIGUREMODES, 0}; LRESULT CALLBACK ViewModeFrameWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch(msg) { case WM_CREATE: { HWND hwndButton; hwndSelector = CreateWindowExA(0, "CLCButtonClass", "", BS_PUSHBUTTON | WS_VISIBLE | WS_CHILD | WS_TABSTOP, 0, 0, 20, 20, hwnd, (HMENU) IDC_SELECTMODE, g_hInst, NULL); SendMessage(hwndSelector, BUTTONADDTOOLTIP, (WPARAM)Translate("Select a view mode"), 0); hwndButton = CreateWindowExA(0, "CLCButtonClass", "", BS_PUSHBUTTON | WS_VISIBLE | WS_CHILD | WS_TABSTOP, 0, 0, 20, 20, hwnd, (HMENU) IDC_CONFIGUREMODES, g_hInst, NULL); SendMessage(hwndButton, BUTTONADDTOOLTIP, (WPARAM)Translate("Setup view modes"), 0); hwndButton = CreateWindowExA(0, "CLCButtonClass", "", BS_PUSHBUTTON | WS_VISIBLE | WS_CHILD | WS_TABSTOP, 0, 0, 20, 20, hwnd, (HMENU) IDC_RESETMODES, g_hInst, NULL); SendMessage(hwndButton, BUTTONADDTOOLTIP, (WPARAM)Translate("Clear view mode and return to default display"), 0); SendMessage(hwnd, WM_USER + 100, 0, 0); return FALSE; } case WM_SIZE: { if(IsWindowVisible(hwnd)) { RECT rcCLVMFrame; HDWP PosBatch = BeginDeferWindowPos(3); GetClientRect(hwnd, &rcCLVMFrame); PosBatch = DeferWindowPos(PosBatch, GetDlgItem(hwnd, IDC_RESETMODES), 0, rcCLVMFrame.right - 23, 1, 22, 20, SWP_NOZORDER); PosBatch = DeferWindowPos(PosBatch, GetDlgItem(hwnd, IDC_CONFIGUREMODES), 0, rcCLVMFrame.right - 45, 1, 22, 20, SWP_NOZORDER); PosBatch = DeferWindowPos(PosBatch, GetDlgItem(hwnd, IDC_SELECTMODE), 0, 1, 1, rcCLVMFrame.right - 46, 20, SWP_NOZORDER); EndDeferWindowPos(PosBatch); } break; } case WM_USER + 100: if(g_CluiData.IcoLib_Avail) { SendMessage(GetDlgItem(hwnd, IDC_RESETMODES), BM_SETIMAGE, IMAGE_ICON, (LPARAM)CallService(MS_SKIN2_GETICON, 0, (LPARAM)"CLN_CLVM_reset")); SendMessage(GetDlgItem(hwnd, IDC_CONFIGUREMODES), BM_SETIMAGE, IMAGE_ICON, (LPARAM)CallService(MS_SKIN2_GETICON, 0, (LPARAM)"CLN_CLVM_options")); SendMessage(GetDlgItem(hwnd, IDC_SELECTMODE), BM_SETIMAGE, IMAGE_ICON, (LPARAM)CallService(MS_SKIN2_GETICON, 0, (LPARAM)"CLN_CLVM_select")); } else { SendMessage(GetDlgItem(hwnd, IDC_RESETMODES), BM_SETIMAGE, IMAGE_ICON, (LPARAM)LoadImage(g_hInst, MAKEINTRESOURCE(IDI_DELETE), IMAGE_ICON, 16, 16, 0)); SendMessage(GetDlgItem(hwnd, IDC_CONFIGUREMODES), BM_SETIMAGE, IMAGE_ICON, (LPARAM)LoadImage(g_hInst, MAKEINTRESOURCE(IDI_CLVM_OPTIONS), IMAGE_ICON, 16, 16, 0)); SendMessage(GetDlgItem(hwnd, IDC_SELECTMODE), BM_SETIMAGE, IMAGE_ICON, (LPARAM)LoadImage(g_hInst, MAKEINTRESOURCE(IDI_CLVM_SELECT), IMAGE_ICON, 16, 16, 0)); } { int bSkinned = DBGetContactSettingByte(NULL, "CLCExt", "bskinned", 0); int i = 0; while(_buttons[i] != 0) { SendMessage(GetDlgItem(hwnd, _buttons[i]), BM_SETSKINNED, 0, bSkinned); if(bSkinned) { SendDlgItemMessage(hwnd, _buttons[i], BUTTONSETASFLATBTN, 0, 0); SendDlgItemMessage(hwnd, _buttons[i], BUTTONSETASFLATBTN + 10, 0, 0); } else { SendDlgItemMessage(hwnd, _buttons[i], BUTTONSETASFLATBTN, 0, 1); SendDlgItemMessage(hwnd, _buttons[i], BUTTONSETASFLATBTN + 10, 0, 1); } i++; } } if(g_CluiData.bFilterEffective) SetWindowTextA(GetDlgItem(hwnd, IDC_SELECTMODE), g_CluiData.current_viewmode); else SetWindowTextA(GetDlgItem(hwnd, IDC_SELECTMODE), "No view mode"); break; case WM_ERASEBKGND: { break; return TRUE; } case WM_PAINT: { PAINTSTRUCT ps; HDC hdc = BeginPaint(hwnd, &ps); RECT rc; //HDC hdc = (HDC)wParam; HDC hdcMem = CreateCompatibleDC(hdc); HBITMAP hbm, hbmold; GetClientRect(hwnd, &rc); hbm = CreateCompatibleBitmap(hdc, rc.right, rc.bottom); hbmold = SelectObject(hdcMem, hbm); if(g_CluiData.bWallpaperMode) SkinDrawBg(hwnd, hdcMem); else FillRect(hdcMem, &rc, GetSysColorBrush(COLOR_3DFACE)); BitBlt(hdc, 0, 0, rc.right, rc.bottom, hdcMem, 0, 0, SRCCOPY); SelectObject(hdcMem, hbmold); DeleteObject(hbm); DeleteDC(hdcMem); //InvalidateRect(GetDlgItem(hwnd, IDC_RESETMODES), NULL, FALSE); //InvalidateRect(GetDlgItem(hwnd, IDC_CONFIGUREMODES), NULL, FALSE); //InvalidateRect(GetDlgItem(hwnd, IDC_SELECTMODE), NULL, FALSE); EndPaint(hwnd, &ps); return 0; } case WM_TIMER: { switch(wParam) { case TIMERID_VIEWMODEEXPIRE: { POINT pt; RECT rcCLUI; GetWindowRect(pcli->hwndContactList, &rcCLUI); GetCursorPos(&pt); if(PtInRect(&rcCLUI, pt)) break; KillTimer(hwnd, wParam); if(!g_CluiData.old_viewmode[0]) SendMessage(hwnd, WM_COMMAND, IDC_RESETMODES, 0); else ApplyViewMode((const char *)g_CluiData.old_viewmode); break; } } break; } case WM_COMMAND: { switch(LOWORD(wParam)) { case IDC_SELECTMODE: { RECT rc; POINT pt; int selection; MENUITEMINFOA mii = {0}; char szTemp[256]; BuildViewModeMenu(); //GetWindowRect(GetDlgItem(hwnd, IDC_SELECTMODE), &rc); GetWindowRect((HWND)lParam, &rc); pt.x = rc.left; pt.y = rc.bottom; selection = TrackPopupMenu(hViewModeMenu,TPM_RETURNCMD|TPM_TOPALIGN|TPM_LEFTALIGN|TPM_RIGHTBUTTON, pt.x, pt.y, 0, hwnd, NULL); if(selection) { mii.cbSize = sizeof(mii); mii.fMask = MIIM_STRING; mii.dwTypeData = szTemp; mii.cch = 256; GetMenuItemInfoA(hViewModeMenu, selection, FALSE, &mii); ApplyViewMode(szTemp); } break; } case IDC_RESETMODES: g_CluiData.bFilterEffective = 0; pcli->pfnClcBroadcast(CLM_AUTOREBUILD, 0, 0); SetWindowTextA(GetDlgItem(hwnd, IDC_SELECTMODE), Translate("No view mode")); CallService(MS_CLIST_SETHIDEOFFLINE, (WPARAM)g_CluiData.boldHideOffline, 0); g_CluiData.boldHideOffline = (BYTE)-1; SetButtonStates(pcli->hwndContactList); g_CluiData.current_viewmode[0] = 0; g_CluiData.old_viewmode[0] = 0; break; case IDC_CONFIGUREMODES: { if(!g_ViewModeOptDlg) CreateDialogParam(g_hInst, MAKEINTRESOURCE(IDD_OPT_VIEWMODES), 0, DlgProcViewModesSetup, 0); break; } } break; } default: return DefWindowProc(hwnd, msg, wParam, lParam); } return TRUE; } static HWND hCLVMFrame; HWND g_hwndViewModeFrame; void CreateViewModeFrame() { CLISTFrame frame = {0}; WNDCLASS wndclass = {0}; wndclass.style = 0; wndclass.lpfnWndProc = ViewModeFrameWndProc; wndclass.cbClsExtra = 0; wndclass.cbWndExtra = 0; wndclass.hInstance = g_hInst; wndclass.hIcon = 0; wndclass.hCursor = LoadCursor(NULL, IDC_ARROW); wndclass.hbrBackground = (HBRUSH) (COLOR_3DFACE); wndclass.lpszMenuName = 0; wndclass.lpszClassName = _T("CLVMFrameWindow"); RegisterClass(&wndclass); frame.cbSize = sizeof(frame); frame.name = "View modes"; frame.hIcon = 0; frame.height = 20; frame.TBname = "View modes"; frame.Flags=F_VISIBLE|F_NOBORDER|F_SHOWTBTIP; frame.align = alTop; frame.hWnd = CreateWindowEx(0, _T("CLVMFrameWindow"), _T("CLVM"), WS_VISIBLE | WS_CHILD | WS_TABSTOP | WS_CLIPCHILDREN, 0, 0, 20, 20, pcli->hwndContactList, (HMENU) 0, g_hInst, NULL); g_hwndViewModeFrame = frame.hWnd; hCLVMFrame = (HWND)CallService(MS_CLIST_FRAMES_ADDFRAME,(WPARAM)&frame,(LPARAM)0); CallService(MS_CLIST_FRAMES_UPDATEFRAME, (WPARAM)hCLVMFrame, FU_FMPOS); } const char *MakeVariablesString(const char *src, const char *UIN); void ApplyViewMode(const char *name) { char szSetting[256]; DBVARIANT dbv = {0}; g_CluiData.bFilterEffective = 0; mir_snprintf(szSetting, 256, "%c%s_PF", 246, name); if(!DBGetContactSetting(NULL, CLVM_MODULE, szSetting, &dbv)) { if(lstrlenA(dbv.pszVal) >= 2) { strncpy(g_CluiData.protoFilter, dbv.pszVal, sizeof(g_CluiData.protoFilter)); g_CluiData.protoFilter[sizeof(g_CluiData.protoFilter) - 1] = 0; g_CluiData.bFilterEffective |= CLVM_FILTER_PROTOS; } mir_free(dbv.pszVal); } mir_snprintf(szSetting, 256, "%c%s_GF", 246, name); if(!DBGetContactSettingTString(NULL, CLVM_MODULE, szSetting, &dbv)) { if(lstrlen(dbv.ptszVal) >= 2) { _tcsncpy(g_CluiData.groupFilter, dbv.ptszVal, safe_sizeof(g_CluiData.groupFilter)); g_CluiData.groupFilter[safe_sizeof(g_CluiData.groupFilter) - 1] = 0; g_CluiData.bFilterEffective |= CLVM_FILTER_GROUPS; } mir_free(dbv.ptszVal); } mir_snprintf(szSetting, 256, "%c%s_SM", 246, name); g_CluiData.statusMaskFilter = DBGetContactSettingDword(NULL, CLVM_MODULE, szSetting, -1); if(g_CluiData.statusMaskFilter >= 1) g_CluiData.bFilterEffective |= CLVM_FILTER_STATUS; mir_snprintf(szSetting, 256, "%c%s_SSM", 246, name); g_CluiData.stickyMaskFilter = DBGetContactSettingDword(NULL, CLVM_MODULE, szSetting, -1); if(g_CluiData.stickyMaskFilter != -1) g_CluiData.bFilterEffective |= CLVM_FILTER_STICKYSTATUS; /* mir_snprintf(szSetting, 256, "%c%s_VA", 246, name); if(!DBGetContactSetting(NULL, CLVM_MODULE, szSetting, &dbv)) { strncpy(g_CluiData.varFilter, dbv.pszVal, sizeof(g_CluiData.varFilter)); g_CluiData.varFilter[sizeof(g_CluiData.varFilter) - 1] = 0; if(lstrlenA(g_CluiData.varFilter) > 10 && ServiceExists(MS_VARS_FORMATSTRING)) g_CluiData.bFilterEffective |= CLVM_FILTER_VARIABLES; mir_free(dbv.ptszVal); if(g_CluiData.bFilterEffective & CLVM_FILTER_VARIABLES) { HANDLE hContact = (HANDLE)CallService(MS_DB_CONTACT_FINDFIRST, 0, 0); char UIN[256]; char *id, *szProto; const char *varstring; char *temp; FORMATINFO fi; while(hContact) { szProto = (char *)CallService(MS_PROTO_GETCONTACTBASEPROTO, (WPARAM)hContact, 0); if(szProto) { id = (char*) CallProtoService(szProto, PS_GETCAPS, PFLAG_UNIQUEIDSETTING, 0); if(id) { if(!DBGetContactSetting(hContact, szProto, id, &dbv)) { if(dbv.type == DBVT_ASCIIZ) { mir_snprintf(UIN, 256, "<%s:%s>", szProto, dbv.pszVal); } else { mir_snprintf(UIN, 256, "<%s:%d>", szProto, dbv.dVal); } varstring = MakeVariablesString(g_CluiData.varFilter, UIN); ZeroMemory(&fi, sizeof(fi)); fi.cbSize = sizeof(fi); fi.szFormat = varstring; fi.szSource = ""; fi.hContact = 0; temp = (char *)CallService(MS_VARS_FORMATSTRING, (WPARAM)&fi, 0); if(temp && atol(temp) > 0) _DebugPopup(hContact, "%s, %d, %d, %d", temp, temp, fi.pCount, fi.eCount); variables_free(temp); DBFreeVariant(&dbv); } } } hContact = (HANDLE)CallService(MS_DB_CONTACT_FINDNEXT, (WPARAM)hContact, 0); } } }*/ g_CluiData.filterFlags = DBGetContactSettingDword(NULL, CLVM_MODULE, name, 0); KillTimer(g_hwndViewModeFrame, TIMERID_VIEWMODEEXPIRE); if(g_CluiData.filterFlags & CLVM_AUTOCLEAR) { DWORD timerexpire; mir_snprintf(szSetting, 256, "%c%s_OPT", 246, name); timerexpire = LOWORD(DBGetContactSettingDword(NULL, CLVM_MODULE, szSetting, 0)); strncpy(g_CluiData.old_viewmode, g_CluiData.current_viewmode, 256); g_CluiData.old_viewmode[255] = 0; SetTimer(g_hwndViewModeFrame, TIMERID_VIEWMODEEXPIRE, timerexpire * 1000, NULL); } strncpy(g_CluiData.current_viewmode, name, 256); g_CluiData.current_viewmode[255] = 0; if(HIWORD(g_CluiData.filterFlags) > 0) g_CluiData.bFilterEffective |= CLVM_STICKY_CONTACTS; if(g_CluiData.boldHideOffline == (BYTE)-1) g_CluiData.boldHideOffline = DBGetContactSettingByte(NULL, "CList", "HideOffline", 0); CallService(MS_CLIST_SETHIDEOFFLINE, 0, 0); SetWindowTextA(hwndSelector, name); pcli->pfnClcBroadcast(CLM_AUTOREBUILD, 0, 0); SetButtonStates(pcli->hwndContactList); }
[ "silvercircle@9e22c628-c204-0410-9d24-ab429885713d" ]
[ [ [ 1, 1147 ] ] ]
2f88fbe7e63d3b031e2e40b28d81f7f41c4a0834
e109ae97b8a43dbf4f4a42a40f8c8da0641237a5
/Main.cpp
8abc60411ced308c839a6d383590388ec7c5f0b8
[]
no_license
mtturner/strategoo-code
8346d48e7b5c038d53843a5195fecd1dc0a4fec9
6bdd46fdbd8cc77eca1afdd0bc9e1d293e59e882
refs/heads/master
2016-09-06T15:57:20.713674
2011-05-06T03:36:15
2011-05-06T03:36:15
32,553,378
1
0
null
null
null
null
UTF-8
C++
false
false
1,610
cpp
/****************************************************** Main.cpp This is Main for the application. ******************************************************/ #include "SDL.h" #include "Game.h" int main(int argc, char* args[]) { //controller object and event structure Game controller; //enumeration of all game states enum GameStates {STATE_INTRO, STATE_LOGIN, STATE_STARTMENU, STATE_SETPIECE, STATE_PLAYGAME, STATE_MENU, STATE_STATISTICS, STATE_EXIT}; //initialize SDL and load images if(!controller.initialize()) { return 1; } //set initial game state to intro controller.setState(STATE_INTRO); //main game loop while(controller.getState() != STATE_EXIT) { //state machine switch(controller.getState()) { case STATE_INTRO: if(!controller.doIntro()) { return 1; } break; case STATE_LOGIN: if(!controller.login()) { return 1; } break; case STATE_STARTMENU: if(!controller.doStartMenu()) { return 1; } break; case STATE_SETPIECE: if(!controller.doSetPiece()) { return 1; } break; case STATE_PLAYGAME: if(!controller.doPlayGame()) { return 1; } break; case STATE_MENU: if(!controller.doInGameMenu()) { return 1; } break; case STATE_STATISTICS: if(!controller.doStatistics()) { return 1; } break; case STATE_EXIT: break; } } //clean up SDL and dynamically allocated memory controller.cleanUp(); return 0; }
[ "cakeeater07@28384a92-424b-c9e9-0b9a-6d5e880deeca", "[email protected]@28384a92-424b-c9e9-0b9a-6d5e880deeca" ]
[ [ [ 1, 99 ] ], [ [ 100, 100 ] ] ]
49798ad708899a2d90a03e458609d9e82a69aba1
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/mw/classicui/uifw/apps/S60_SDK5.0/bctestpane/inc/bctestpaneappUi.h
1993cfe1bcccfb2c142598b9e0ac4d83c6209387
[]
no_license
SymbianSource/oss.FCL.sftools.ana.compatanamdw
a6a8abf9ef7ad71021d43b7f2b2076b504d4445e
1169475bbf82ebb763de36686d144336fcf9d93b
refs/heads/master
2020-12-24T12:29:44.646072
2010-11-11T14:03:20
2010-11-11T14:03:20
72,994,432
0
0
null
null
null
null
UTF-8
C++
false
false
1,287
h
/* * Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: AppUi * */ #ifndef C_BCTESTPANEAPPUI_H #define C_BCTESTPANEAPPUI_H #include <aknviewappui.h> class CBCTestPaneView; class CBCTestUtil; /** * Application UI class */ class CBCTestPaneAppUi : public CAknViewAppUi { public: // Constructors and destructor /** * ctor */ CBCTestPaneAppUi(); /** * symbian 2nd ctor */ void ConstructL(); /** * dtor */ virtual ~CBCTestPaneAppUi(); private: /** * From CEikAppUi */ void HandleCommandL( TInt aCommand ); private: // data /** * pointor to the view. * own */ CBCTestPaneView* iView; /** * pointor to BCTesting framework. * Own */ CBCTestUtil* iTestUtil; }; #endif // C_BCTESTPANEAPPUI_H
[ "none@none" ]
[ [ [ 1, 73 ] ] ]
aee38f2f1d9268352a361604483954dc151a2454
cd61c8405fae2fa91760ef796a5f7963fa7dbd37
/Sauron/SonarUnitTests/SonarReadingsLogParser.h
2832a349764ae1a2b959113e9dfd365f662963e3
[]
no_license
rafaelhdr/tccsauron
b61ec89bc9266601140114a37d024376a0366d38
027ecc2ab3579db1214d8a404d7d5fa6b1a64439
refs/heads/master
2016-09-05T23:05:57.117805
2009-12-14T09:41:58
2009-12-14T09:41:58
32,693,544
0
0
null
null
null
null
ISO-8859-1
C++
false
false
1,752
h
#pragma once #include "SonarModel.h" #include "SonarReading.h" #include "CustomTypes.h" #include <cassert> #include <string> #include <fstream> #include <sstream> #include <vector> struct LogLine { std::vector<sauron::SonarReading> readings; sauron::Pose pose; }; class SonarReadingsLogParser { public: SonarReadingsLogParser(std::string logfilename) : m_log(logfilename.c_str()){ if(!m_log.is_open()) { throw std::invalid_argument("O arquivo " + logfilename + " nao existe"); } parse(); } void addAllReadingsOfOneSonar(int sonarIndex, sauron::SonarModel& sonar) const { for(std::vector<LogLine>::const_iterator it = m_readings.begin(); it != m_readings.end(); it++) { sonar.addReading(it->readings.at(sonarIndex), it->pose); } } std::ifstream m_log; std::vector<LogLine> m_readings; void parse() { while(!m_log.eof()) { std::string sonarLine, poseLine; // a primeira linha contém a leitura dos sonares std::getline(m_log, sonarLine); // ignora linhas que comecem com '#' if(sonarLine.length() > 0 && sonarLine.at(0) != '#') { if(!m_log.eof()) { std::getline(m_log, poseLine); std::stringstream ss; ss << sonarLine; LogLine logLine; sauron::reading_t sonarReading; while(!ss.eof()) { ss >> sonarReading; if(!ss.fail()) logLine.readings.push_back(sauron::SonarReading(sonarReading)); } // a segunda tem a posição do robô sauron::pose_t x, y, th; ss.clear(); ss.str(poseLine); ss >> x >> y >> th; logLine.pose.X() = x; logLine.pose.Y() = y; logLine.pose.setTheta(th); m_readings.push_back(logLine); } } } } };
[ "budsbd@8373e73c-ebb0-11dd-9ba5-89a75009fd5d" ]
[ [ [ 1, 72 ] ] ]
71b1d021d58e6b7092b5c11a526581a4535a28b3
03f06dde16b4b08989eefa144ebc2c7cc21e95ad
/tags/0.21/WinProf/WinProfDoc.h
2a10a00ef4a1ab3557970991fa91d74378a018db
[]
no_license
BackupTheBerlios/winprof-svn
c3d557c72d7bc0306cb6bd7fd5ac189e5c277251
21ab1356cf6d16723f688734c995c7743bbde852
refs/heads/master
2021-01-25T05:35:44.550759
2005-06-23T11:51:27
2005-06-23T11:51:27
40,824,500
0
0
null
null
null
null
UTF-8
C++
false
false
657
h
// WinProf++Doc.h : interface of the CWinProfDoc class // #pragma once class CWinProfDoc : public CDocument { protected: // create from serialization only CWinProfDoc(); DECLARE_DYNCREATE(CWinProfDoc) // Attributes public: // Operations public: // Overrides public: virtual BOOL OnNewDocument(); virtual void Serialize(CArchive& ar); // Implementation public: virtual ~CWinProfDoc(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // Generated message map functions protected: DECLARE_MESSAGE_MAP() public: CString m_ExeFileName; };
[ "landau@f5a2dbeb-61f3-0310-bb71-ba092b21bc01" ]
[ [ [ 1, 41 ] ] ]
d4bb5a92b0e4024d8d1ffd3f2c63b7d620f6403a
89d2197ed4531892f005d7ee3804774202b1cb8d
/GWEN/include/Gwen/Controls/ScrollBar.h
840487a3dd08e8a24ed0e14a1a00495b3f65f8a2
[ "MIT", "Zlib" ]
permissive
hpidcock/gbsfml
ef8172b6c62b1c17d71d59aec9a7ff2da0131d23
e3aa990dff8c6b95aef92bab3e94affb978409f2
refs/heads/master
2020-05-30T15:01:19.182234
2010-09-29T06:53:53
2010-09-29T06:53:53
35,650,825
0
0
null
null
null
null
UTF-8
C++
false
false
2,045
h
/* GWEN Copyright (c) 2010 Facepunch Studios See license in Gwen.h */ #pragma once #include "Gwen/Controls/Base.h" #include "Gwen/Controls/Button.h" #include "Gwen/Gwen.h" #include "Gwen/Skin.h" #include "Gwen/Controls/Dragger.h" #include "Gwen/Controls/ScrollBarBar.h" #include "Gwen/Controls/ScrollBarButton.h" #define SCROLL_BUTTON_UP 0 #define SCROLL_BUTTON_LEFT 0 #define SCROLL_BUTTON_DOWN 1 #define SCROLL_BUTTON_RIGHT 1 #define NUDGE_DIST 10 namespace Gwen { namespace Controls { class GWEN_EXPORT BaseScrollBar : public Base { public: GWEN_CONTROL( BaseScrollBar, Base ); virtual void Layout(Skin::Base* skin); virtual void Render(Skin::Base* skin); virtual void SetBarSize(int size) = 0; virtual int GetBarSize() = 0; virtual int GetBarPos() = 0; virtual void OnBarMoved( Controls::Base* control); virtual void OnMouseClickLeft( int x, int y, bool bDown ){} virtual void ScrollToLeft(){} virtual void ScrollToRight(){} virtual void ScrollToTop(){} virtual void ScrollToBottom(){} virtual float GetNudgeAmount() { return m_fNudgeAmount / m_fContentSize; } virtual void SetNudgeAmount( float nudge ) { m_fNudgeAmount = nudge; } virtual void BarMovedNotification(); virtual float CalculateScrolledAmount() { return 0; } virtual int CalculateBarSize() { return 0; } virtual void SetScrolledAmount(float amount, bool forceUpdate); virtual void SetContentSize(float size); virtual void SetViewableContentSize(float size); virtual int GetButtonSize() { return 0; } virtual float GetScrolledAmount() { return m_fScrolledAmount; } Gwen::Event::Caller onBarMoved; protected: ControlsInternal::ScrollBarButton* m_ScrollButton[2]; ControlsInternal::ScrollBarBar * m_Bar; bool m_bDepressed; float m_fScrolledAmount; float m_fContentSize; float m_fViewableContentSize; float m_fNudgeAmount; }; } }
[ "haza55@5bf3a77f-ad06-ad18-b9fb-7d0f6dabd793" ]
[ [ [ 1, 78 ] ] ]
b4a7417577c3dadee9dd2fdbe460fe42700b02a2
7442395e399e1f544f8a08da82ac3659d0d7abf3
/src/reset.cpp
2dea4778e89c2acf8c58055e94512c03b35f75d8
[ "Apache-2.0" ]
permissive
MartinMReed/xenimus-calc-cplusplus
be7d848ddcf76320a90b971100e6e9344873e5b9
33f891c81ec03c35f43a8cb3e5f2b37a32088827
refs/heads/master
2016-09-06T11:30:58.601115
2006-06-22T16:38:00
2006-06-22T16:38:00
12,097,390
1
0
null
null
null
null
UTF-8
C++
false
false
2,650
cpp
/************************************************************************/ /** CPlusPlus Stat Calculator /** Xenimus Open Source Group /** /** Additons to this file: /** -[insert name] /** --[insert additions descriptions] /** /** -Halloween (10/16/05) /** --Adjusted +bases to account for Xenimus 1.83 update /** /** -Halloween (08/25/05) /** --Reset the saveIn input /** /** Original copy by: /** Halloween (06/15/05) /** /** All previous names must stay included when making additions. /************************************************************************/ #include "stdafx.h" #include "calc.h" #include "calcDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif //------------------------------------------------------- // CLEAR / RESET //------------------------------------------------------- void CCalcDlg::Onreset() { //unckeck all regular shrines m_strengthShrine.SetCheck( FALSE ); m_agilityShrine.SetCheck( FALSE ); m_constitutionShrine.SetCheck( FALSE ); m_intelligenceShrine.SetCheck( FALSE ); m_wisdomShrine.SetCheck( FALSE ); m_ghShrine.SetCheck( FALSE ); //unckeck all jeloc shrines m_sixthJeloc.SetCheck( FALSE );; m_strengthJeloc.SetCheck( FALSE ); m_agilityJeloc.SetCheck( FALSE ); m_constitutionJeloc.SetCheck( FALSE ); m_intelligenceJeloc.SetCheck( FALSE ); m_wisdomJeloc.SetCheck( FALSE ); //disable all jeloc shrines m_sixthJeloc.EnableWindow( FALSE ); m_strengthJeloc.EnableWindow( FALSE ); m_agilityJeloc.EnableWindow( FALSE ); m_constitutionJeloc.EnableWindow( FALSE ); m_intelligenceJeloc.EnableWindow( FALSE ); m_wisdomJeloc.EnableWindow( FALSE ); selectAllShrines = FALSE; JELOC = FALSE; selectAllJeloc = FALSE; //reset everything to its initial values classNumber = 0; lvl = 1; statArray[0] = 10; shrineArray[0] = 0; // Str statArray[1] = 10; shrineArray[1] = 0; // Agil statArray[2] = 10; shrineArray[2] = 0; // Cons statArray[3] = 10; shrineArray[3] = 0; // Intel statArray[4] = 10; shrineArray[4] = 0; // Wis hpBaseArray[0] = 8; mpBaseArray[0] = 8; // Helm hpBaseArray[1] = 0; mpBaseArray[1] = 0; // Armor hpBaseArray[2] = 0; mpBaseArray[2] = 0; // Glove hpBaseArray[3] = 8; mpBaseArray[3] = 8; // Weap hpBaseArray[4] = 36; mpBaseArray[4] = 30; // Ring hpBaseArray[5] = 0; mpBaseArray[5] = 0; // human m_hphuman.SetCheck( 0 ); m_mphuman.SetCheck( 0 ); m_neutralButton.SetCheck( TRUE ); m_fullButton.SetCheck( FALSE ); m_saveIn.SetWindowText( "Character Name" ); CCalcDlg::redo(); }
[ [ [ 1, 92 ] ] ]
ff543b0363a546a3defa66487048283767e01985
6477cf9ac119fe17d2c410ff3d8da60656179e3b
/Projects/zNotepad/myam.h
902f3a203e5392f6ee7bdfc0f05eded75a2e1db1
[]
no_license
crutchwalkfactory/motocakerteam
1cce9f850d2c84faebfc87d0adbfdd23472d9f08
0747624a575fb41db53506379692973e5998f8fe
refs/heads/master
2021-01-10T12:41:59.321840
2010-12-13T18:19:27
2010-12-13T18:19:27
46,494,539
0
0
null
null
null
null
UTF-8
C++
false
false
4,312
h
/* * Unofficial EZX Native Software Development Kit * Copyright (C) 2007 Y.S Hsiao <ysakaed at gmail dot com> * * 2007-08-02 by Y.S Hsiao (intoxicated) * * 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.1 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. * * Further, this software is distributed without any warranty that it is * free of the rightful claim of any third person regarding infringement * or the like. Any license provided herein, whether implied or * otherwise, applies only to this software file. Patent licenses, if * any, provided herein do not apply to combinations of this program with * other software, or any other product whatsoever. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if !defined(__ZSMS_H__) #define __ZSMS_H__ #include <qobject.h> #include <qdatetime.h> class ZSMS_OutgoingMsg; class ZSMS_IncomingMsg; class ZSMS_MsgRecordID; class MSGAPI_INCOME_SMS_S; class MSGAPI_MSG_RECORD_ID; class MSGAPI_OUTGO_SMS_S; class ZSMS : public QObject { Q_OBJECT public: ZSMS( QObject * parent = 0, const char * name = 0 ); virtual ~ZSMS(); int tmp[1024]; void composeMsg(ZSMS_OutgoingMsg const&); // compose window // void indOfIncomingMsg(ZSMS_IncomingMsg const&, ZSMS_MsgRecordID const&); void sendMsgWithResult(unsigned int*, ZSMS_OutgoingMsg const&); void enableInterceptCheck(bool); void rspnsOfSendMsgWithResult(unsigned int, int); void notifyInterceptCheckResult(ZSMS_MsgRecordID const&, bool); void gotoMessagingCenterHomeScreen(); // go to the message menu void sendMsg(ZSMS_OutgoingMsg const&); // send out message }; class ZSMS_OutgoingMsg { public: ZSMS_OutgoingMsg(QString const& , QString const& ); // Number, Content ZSMS_OutgoingMsg(ZSMS_OutgoingMsg const&); ~ZSMS_OutgoingMsg(); int tmp[1024]; QString getAddress(void); QString getMsgBody(void); }; class ZSMSPrivate : QObject { Q_OBJECT public: ZSMSPrivate(ZSMS*, QObject*, char const*); ~ZSMSPrivate(); void vfnShowMsg(MSGAPI_INCOME_SMS_S const&, MSGAPI_MSG_RECORD_ID const&); void vfnIndOfIncomingMsg(MSGAPI_INCOME_SMS_S const&, MSGAPI_MSG_RECORD_ID const&); void vfnRspnsOfSaveToDraft(unsigned int, int, MSGAPI_MSG_RECORD_ID const&); void vfnRspnsOfSendMsgWithResult(unsigned int, int); void vfnRspnsOfGetLatestSmsInDraft(unsigned int, int, MSGAPI_OUTGO_SMS_S const&, MSGAPI_MSG_RECORD_ID const&); }; class ZSMS_IncomingMsg { public: ZSMS_IncomingMsg(ZSMS_IncomingMsg const&); ZSMS_IncomingMsg(); ~ZSMS_IncomingMsg(); QString getAddress(void); QString getMsgBody(void); QDateTime getSentTime(void); bool isNull(void); bool isValid(void); }; class ZSMS_MsgRecordID { public: ZSMS_MsgRecordID(ZSMS_MsgRecordID const&); ZSMS_MsgRecordID(); ~ZSMS_MsgRecordID(); }; class ZSMSTypeConv { public: ZSMSTypeConv(void); ZSMS_IncomingMsg toZsmsIncomingMsg(MSGAPI_INCOME_SMS_S const&); ZSMS_MsgRecordID toZsmsMsgRecordID(MSGAPI_MSG_RECORD_ID const&); ZSMS_OutgoingMsg toZsmsOutgoingMsg(MSGAPI_OUTGO_SMS_S const&); MSGAPI_MSG_RECORD_ID toMsgapiMsgRecordID(ZSMS_MsgRecordID const&); MSGAPI_INCOME_SMS_S toMsgapiIncomeSms(ZSMS_IncomingMsg const&); ZSMS_OutgoingMsg toMsgapiOutgoSms(ZSMS_OutgoingMsg const&); }; #endif /* !defined(__ZSMS_H_) */
[ [ [ 1, 121 ] ] ]
905eb1b9127daea598db284c8294dfb41ae87beb
de98f880e307627d5ce93dcad1397bd4813751dd
/3libs/ut/include/OXShellNamespaceNavigator.h
dad88a2a4ece2f6a558a03add1437a8d0d61f317
[]
no_license
weimingtom/sls
7d44391bc0c6ae66f83ddcb6381db9ae97ee0dd8
d0d1de9c05ecf8bb6e4eda8a260c7a2f711615dd
refs/heads/master
2021-01-10T22:20:55.638757
2011-03-19T06:23:49
2011-03-19T06:23:49
44,464,621
2
0
null
null
null
null
ISO-8859-1
C++
false
false
30,279
h
// ========================================================================== // Class Specification : COXShellNamespaceNavigator // ========================================================================== // Header file : OXShellNamespaceNavigator.h // Version: 9.3 // This software along with its related components, documentation and files ("The Libraries") // is © 1994-2007 The Code Project (1612916 Ontario Limited) and use of The Libraries is // governed by a software license agreement ("Agreement"). Copies of the Agreement are // available at The Code Project (www.codeproject.com), as part of the package you downloaded // to obtain this file, or directly from our office. For a copy of the license governing // this software, you may contact us at [email protected], or by calling 416-849-8900. // ////////////////////////////////////////////////////////////////////////// /* DESCRIPTION COXShellNamespaceNavigator class is a helper class designed to simplify the process of navigating through Shell Namespace. This class represents a set of functions that can be especially useful while enumerating Shell Namespace items. Primarily it was designed as a helper class for COXShellFolderTree class (tree control that is automatically populated with Shell Namespace folders) but COXShellNamespaceNavigator class methods can be used independently in order to surf the Shell. Although this class simplify a lot of things you still have to have good understanding of the Shell Namespace objects and interfaces it implements. Refer to the SDK documentation that can be found on MSDN disc in the following section: "Platform, SDK, and DDK Documentation" "Platform SDK" "User Interface Services" "Shell and Common Controls" "Windows Shell API" "Shell Namespace" Specifically take look at the section that explains Item Identifiers and Pointers to Item Identifier Lists (IDLs) and interfaces that COXShellNamespaceNavigator class exploits in its methods: IShellFolder IEnumIDList IContextMenu These are crucial elements of Shell Namespace that you should be familiar with in order to fully understand the methods and ideas used in the COXShellNamespaceNavigator class. Below you will find some brief definition of the objects this class operates on. A namespace is a collection of symbols, such as database keys or file and directory names. The shell uses a single hierarchical namespace to organize all objects of interest to the user, including files, storage devices, printers, network resources, and anything else that can be viewed using Microsoft® Windows® Explorer. The root of this unified namespace is the desktop. In many ways, the shell namespace is analogous to a file system's directory structure. However, the namespace contains more types of objects than just files and directories. Folders and File Objects A folder is a collection of items in the shell namespace. A folder is analogous to a file system directory, and many folders are, in fact, directories. However, there are also other types of folders, such as remote computers, storage devices, the Desktop folder, the Control Panel, the Printers folder, and the Fonts folder. A folder can contain other folders as well as items called file objects. Because there are many kinds of folders and file objects, each folder is an OLE component object model (COM) object that can enumerate its contents and carry out other actions. More precisely, each folder implements the IShellFolder interface. Using IShellFolder functions, an application can navigate throughout the entire shell namespace. The following COXShellNamespaceNavigator function can be used in order to retrieve a pointer to the IShellFolder interface of the specified folder: LPSHELLFOLDER GetShellFolder(CString sFolderFullPath) const; Item Identifiers and Pointers to Item Identifier Lists (IDLs) Objects in the shell namespace are assigned item identifiers and item identifier lists. An item identifier uniquely identifies an item within its parent folder. An item identifier list uniquely identifies an item within the shell namespace by tracing a path to the item from a known point, usually the desktop (so called fully qualified IDL). A pointer to an item identifier list (PIDL) is used throughout the shell to identify an item. If you have the IShellFolder interface of Shell Namespace item's parent folder then it can be uniquely identified using IDL relative to partent folder (which actually consist only of one Item Identifier. We call such IDL as relative IDL). The following COXShellNamespaceNavigator function can be used in order to retrieve IDL for the specified folder: BOOL GetShellFolderFullIDL(CString sFolderFullPath, LPITEMIDLIST* ppidlFull) const; BOOL GetShellFolderRelativeIDL(const LPSHELLFOLDER lpParentFolder, CString sFolderRelativePath, LPITEMIDLIST* ppidlRelative) const; Item Enumeration A folder's IShellFolder interface can be used to determine the folder's contents by using the IShellFolder::EnumObjects method. We provide the following set of functions that you can use in order to enumerate the contents of given folder: Object enumeration is done in three steps: 1) BOOL InitObjectsEnumerator( const LPSHELLFOLDER lpFolder, const LPITEMIDLIST lpParentFullIDL, DWORD dwFlags=SHCONTF_FOLDERS|SHCONTF_NONFOLDERS|SHCONTF_INCLUDEHIDDEN); is called that specifies the IShellInterface of the folder which objects will be enumerated, this folder fully qualified IDL and attributes of enumerated objects 2) If InitObjectsEnumerator() returns success then you can call LPNAMESPACEOBJECT EnumerateObjectNext(BOOL& bLastReached); function which returns pointer to NAMESPACEOBJECT structure that provide extended description of the object. Parameter bLastReached will be set to FALSE if the last folder object has been reached 3) After all objects has been enumerated you MUST call BOOL ReleaseObjectsEnumerator(); function in order to reset internal COXShellNamespaceNavigator variables. Display Names Because item identifiers are binary data structures, each item in a shell folder also has a display name, which is a string that can be shown to the user. You can use the following functions: CString GetDisplayName(const LPSHELLFOLDER lpParentFolder, const LPITEMIDLIST lpRelativeIDL) const; CString GetFullPath(const LPITEMIDLIST lpFullIDL); Object Attributes and Interfaces Every file object and folder has attributes that determine, among other things, what actions can be carried out on it. To obtain the attributes of a file object or folder, your application can use the IShellFolder::GetAttributesOf method. We provide the following functions that simplify the process of retrieving of Shell Namespace item context menu and invoking any command from this menu on this item: HMENU GetObjectContextMenu(const LPSHELLFOLDER lpParentFolder, const LPITEMIDLIST lpRelativeIDL, DWORD dwFlags) const; BOOL InvokeCommand(const LPSHELLFOLDER lpParentFolder, const LPITEMIDLIST lpRelativeIDL, UINT nCmdID, DWORD dwFlags) const; Also we provide set of helper functions that simplifies process of working with Shell Namespace elements. The following functions can be used in order to copy, concatenate and enumerate PIDLs: LPITEMIDLIST ConcatenatePIDLs(LPCITEMIDLIST pidl1, LPCITEMIDLIST pidl2) const; LPITEMIDLIST CopyPIDL(LPCITEMIDLIST pidlSource) const; UINT GetIDLSize(LPCITEMIDLIST pidl) const; LPITEMIDLIST GetNextIDLItem(LPCITEMIDLIST pidl) const; Every item in shell namespace has image associated with it. Shell keeps one image list for all items' images. In order to retrieve it use the following function: HIMAGELIST GetShellImageList(BOOL bSmallIcon=TRUE) const; Also we provide specific NAMESPACEOBJECT structure that fully desribes any Shell Namespace item (including PIDLs, pointer to IShellFolder, display name and image index, for details refer to the documentation). NAMESPACEOBJECT is used as return value of some of the COXShellNamespaceNavigator functions but you can retrieve it explicitly using following function: LPNAMESPACEOBJECT GetNameSpaceObject(const LPSHELLFOLDER lpsfParent, const LPITEMIDLIST lpRelativeIDL, const LPITEMIDLIST lpFullIDL) const; The best way to learn how to use COXShellNamespaceNavigator class is to take look at the implementation of COXShellFolderTree class which represents standard tree control which is automatically populated with Shell Namespace folders. Dependencies: #include "OXShellFolderTree.h" Source code files: "OXShellNamespaceNavigator.cpp" */ #if !defined(_OXSHELLNAMESPACENAVIGATOR_H_) #define _OXSHELLNAMESPACENAVIGATOR_H_ #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 #include "OXDllExt.h" // OXShellNamespaceNavigator.h : header file // #ifndef _SHLOBJ_H_ #include <shlobj.h> #define _SHLOBJ_H_ #endif // _SHLOBJ_H_ #ifndef __AFXTEMPL_H__ #include <afxtempl.h> #define __AFXTEMPL_H__ #endif // __AFXTEMPL_H__ #include "UTB64Bit.h" // shell commands static const int IDCMD_DELETE=18; static const int IDCMD_RENAME=19; static const int IDCMD_PROPERTIES=20; static const int IDCMD_CUT=25; static const int IDCMD_COPY=26; static const int IDCMD_PASTE=27; ///////////////////////////////////////////////////////////////////////////// // Shell Namespaceobject descriptor // // lpsfParent - pointer to item's parent IShellFolder interface // lpRelativeIDL - item IDL relative to its parent folder // lpFullIDL - item IDL relative to Desktop folder // dwFlags - item attributes. Can be combination of the // following: // // SFGAO_CANDELETE The specified file objects or // folders can be deleted. // SFGAO_CANLINK It is possible to create // shortcuts for the specified file // objects or folders (same value // as the DROPEFFECT_LINK flag). // SFGAO_CANMOVE The specified file objects or // folders can be moved (same value // as the DROPEFFECT_MOVE flag). // SFGAO_CANRENAME The specified file objects or // folders can be renamed. // SFGAO_CAPABILITYMASK Mask for the capability flags. // SFGAO_DROPTARGET The specified file objects or // folders are drop targets. // SFGAO_HASPROPSHEET The specified file objects or // folders have property sheets. // SFGAO_GHOSTED The specified file objects or // folders should be displayed // using a ghosted icon. // SFGAO_LINK The specified file objects are // shortcuts. // SFGAO_READONLY The specified file objects or // folders are read-only. // SFGAO_SHARE The specified folders are shared. // SFGAO_HASSUBFOLDER The specified folders have // subfolders (and are, therefore, // expandable in the left pane of // Windows Explorer). // SFGAO_COMPRESSED The specified items are // compressed. // SFGAO_FILESYSTEM The specified folders or file // objects are part of the file // system (that is, they are files, // directories, or root directories). // SFGAO_FILESYSANCESTOR The specified folders contain // one or more file system // folders. // SFGAO_FOLDER The specified items are folders. // SFGAO_NEWCONTENT The objects contain new content. // SFGAO_NONENUMERATED The items are nonenumerated items. // SFGAO_REMOVABLE The specified file objects or // folders are on removable media. // SFGAO_VALIDATE Validate cached information. // The shell will validate that the // object still exist and will not // used cached information when // retrieving the attributes. // This is similar to doing a // refresh of the folder. // szDisplayName - item's display name // nImage - item's image (normal) // nImageSelected - item's image (normal) when it is in // selected state // nImageSmall - item's image (small) // nImageSelectedSmall - item's image (small) when it is in // selected state // typedef struct tagNAMESPACEOBJECT { LPSHELLFOLDER lpsfParent; LPITEMIDLIST lpRelativeIDL; LPITEMIDLIST lpFullIDL; DWORD dwFlags; TCHAR szDisplayName[MAX_PATH]; int nImage; int nImageSelected; int nImageSmall; int nImageSelectedSmall; } NAMESPACEOBJECT, *LPNAMESPACEOBJECT; // ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // COXShellNamespaceNavigator window class OX_CLASS_DECL COXShellNamespaceNavigator { // Construction public: // --- In: // --- Out: // --- Returns: // --- Effect : Constructs the object COXShellNamespaceNavigator(); // Attributes public: protected: // pointer to the window to which all Shell error notification will // be forwarded (if any Shell error happens message box with // notification will be displayed). If it is NULL then Shell error // notification will be surpassed CWnd* m_pOwnerWnd; //////////////////////////////////////////////////////////////////////// // set of variables used to enumeratwe parent folder contents // (subfolders and items). Object enumeration is done in three steps: // // 1) BOOL InitObjectsEnumerator( const LPSHELLFOLDER lpFolder, // const LPITEMIDLIST lpParentFullIDL, // const DWORD dwFlags=SHCONTF_FOLDERS|SHCONTF_NONFOLDERS|SHCONTF_INCLUDEHIDDEN); // is called that specifies the IShellInterface of the folder which // objects will be enumerated, this folder fully qualified IDL and // attributes of enumerated objects // // 2) If InitObjectsEnumerator() returns success then you can call // // LPNAMESPACEOBJECT EnumerateObjectNext(BOOL& bLastReached); // // function which returns pointer to NAMESPACEOBJECT structure // that provide extended description of the object. Parameter // bLastReached will be set to FALSE if the last folder object // has been reached // // 3) After all objects has been enumerated you MUST call // // BOOL ReleaseObjectsEnumerator(); // // function in order to reset internal COXShellNamespaceNavigator // variables. // LPENUMIDLIST m_lpeidl; BOOL m_bEnumeratorInitialized; LPSHELLFOLDER m_lpEnumerateFolder; LPITEMIDLIST m_lpEnumerateParentFullIDL; //////////////////////////////////////////////////////////////////////// mutable CMap<DWORD_PTR,DWORD_PTR,DWORD_PTR,DWORD_PTR> m_mapObjectsToFree; mutable CMap<DWORD_PTR,DWORD_PTR,DWORD_PTR,DWORD_PTR> m_mapIShellFolderToRelease; BOOL m_bAutoCleanUp; // Operations public: // --- In: lParam1 - pointer to NAMESPACEOBJECT for the // first object to compare // lParam2 - pointer to NAMESPACEOBJECT for the // second object to compare // lParamSort - additional data (unused at the moment) // --- Out: // --- Returns: Less than zero - The first item should precede // the second // Greater than zero - The first item should follow // the second // Zero - The two items are the same // --- Effect : Static callback function that can be used in fast // sorting routines that operate on Shell Namespace // objects static int CALLBACK CompareObjectsProc(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort); // --- In: pWnd - pointer to CWnd object // --- Out: // --- Returns: // --- Effect : Sets the window to which all Shell error notification // will be forwarded (if any Shell error happens message // box with notification will be displayed). If it is NULL // then Shell error notification will be surpassed. inline void SetOwnerWnd(CWnd* pWnd) { m_pOwnerWnd=pWnd; } // --- In: bSmallIcon - flag that specifies whether image with // small or normal images will be retrieved // --- Out: // --- Returns: Handle of the corresponding image list if succeed // or NULL otherwise // --- Effect : Retrieves Shell image list HIMAGELIST GetShellImageList(BOOL bSmallIcon=TRUE) const; // --- In: sFolderFullPath - full folder path // --- Out: // --- Returns: pointer to IShellFolder interface of the corresponding // folder if succeed or NULL otherwise // --- Effect : Retrieves IShellFolder interface for specified folder LPSHELLFOLDER GetShellFolder(CString sFolderFullPath) const; // --- In: lpParentFolder - pointer to IShellFolder interface // of the parent folder // lpRelativeIDL - folder IDL relative to its // parent folder // --- Out: // --- Returns: pointer to IShellFolder interface of the corresponding // folder if succeed or NULL otherwise // --- Effect : Retrieves IShellFolder interface for specified folder LPSHELLFOLDER GetShellFolder(const LPSHELLFOLDER lpParentFolder, const LPITEMIDLIST lpRelativeIDL) const; // --- In: pidlFull - pointer to fully qualified IDL that uniquely // identifies the folder which IShellFolder // interface is being requested // --- Out: // --- Returns: pointer to IShellFolder interface of the corresponding // folder if succeed or NULL otherwise // --- Effect : Retrieves IShellFolder interface for specified folder LPSHELLFOLDER GetShellFolder(LPCITEMIDLIST pidlFull) const; // --- In: pidlFull - pointer to fully qualified IDL that uniquely // identifies the folder which parent folder // interface has been requested // --- Out: lppRelativeIDL - pointer to a pointer to relative IDL that // will be filled with relative IDL for the // folder specified by its full IDL pidlFull. // --- Returns: pointer to IShellFolder interface of the parent // folder if succeed or NULL otherwise // --- Effect : Retrieves IShellFolder interface of the parent folder and // relative to this parent folder relative IDL LPSHELLFOLDER GetParentShellFolder(LPCITEMIDLIST pidlFull, LPITEMIDLIST* lppRelativeIDL) const; // --- In: sFolderFullPath - full folder path // --- Out: ppidlFull - pointer to pointer to fully // qualified IDL that will be filled // with specified folder IDL // --- Returns: TRUE if specified folder fully qualified IDL was // successfully retrieved or FALSE otherwise // --- Effect : Retrieves fully qualified IDL for specified folder BOOL GetShellFolderFullIDL(CString sFolderFullPath, LPITEMIDLIST* ppidlFull) const; // --- In: lpParentFolder - pointer to IShellFolder interface // of the parent folder // sFolderRelativePath - folder path relative to its // parent folder // --- Out: ppidlRelative - pointer to pointer to relative // IDL that will be filled with // specified folder IDL relative to // its parent folder // --- Returns: TRUE if specified folder relative IDL was // successfully retrieved or FALSE otherwise // --- Effect : Retrieves relative IDL for specified folder BOOL GetShellFolderRelativeIDL(const LPSHELLFOLDER lpParentFolder, CString sFolderRelativePath, LPITEMIDLIST* ppidlRelative) const; // --- In: lpParentFolder - pointer to IShellFolder interface // of the folder which items will be // enumerated // lpParentFullIDL - fully qualified IDL of the folder // wich items will be enumerated // dwFlags - determines the type of items // included in an enumeration. // // SHCONTF_FOLDERS Include items that // are folders in the // enumeration. // SHCONTF_NONFOLDERS Include items that // are not folders in // the enumeration. // SHCONTF_INCLUDEHIDDEN Include hidden items // in the enumeration. // --- Out: // --- Returns: TRUE if initialization suceeded or FALSE otherwise // --- Effect : Initialize the process of enumerating folder items. // In order to enumerate items call EnumerateObjectNext() // function. After all items has been enumerated // you MUST call ReleaseObjectsEnumerator() function. BOOL InitObjectsEnumerator(const LPSHELLFOLDER lpParentFolder, const LPITEMIDLIST lpParentFullIDL, DWORD dwFlags=SHCONTF_FOLDERS|SHCONTF_NONFOLDERS|SHCONTF_INCLUDEHIDDEN); // --- In: // --- Out: bLastReached - flag will be set to TRUE if the // last item in the enumeration // queue has been reached // --- Returns: pointer to NAMESPACEOBJECT structure if suceeded or // NULL otherwise // --- Effect : Enumerates folder items. Before calling this function // the process of enumeration MUST be initialized calling // InitObjectsEnumerator() function. After all items has // been enumerated you MUST call ReleaseObjectsEnumerator() // function. LPNAMESPACEOBJECT EnumerateObjectNext(BOOL& bLastReached); // --- In: // --- Out: // --- Returns: TRUE if internal enumeration objects were released // successfully or FALSE otherwise. // --- Effect : Releases all internal enumeration objects. After all // items has been enumerated this function MUST be called. BOOL ReleaseObjectsEnumerator(); // --- In: lpsfParent - pointer to IShellFolder interface // of parent folder // lpRelativeIDL - relative IDL to its parent folder // lpFullIDL - fully qualified IDL // --- Out: // --- Returns: pointer to NAMESPACEOBJECT structure if suceeded or // NULL otherwise // --- Effect : Creates NAMESPACEOBJECT structure for Shell // Namespace item. LPNAMESPACEOBJECT GetNameSpaceObject(const LPSHELLFOLDER lpsfParent, const LPITEMIDLIST lpRelativeIDL, const LPITEMIDLIST lpFullIDL) const; // --- In: lpParentFolder - pointer to IShellFolder interface // of the item's parent folder // lpRelativeIDL - relative IDL to its parent folder // --- Out: // --- Returns: Display name of the specified Shell Namespace item // --- Effect : Retrieves the display name of the specified Shell // Namespace item CString GetDisplayName(const LPSHELLFOLDER lpParentFolder, const LPITEMIDLIST lpRelativeIDL) const; // --- In: lpFullIDL - fully qualified IDL of the // specified Shell Namespace item // --- Out: // --- Returns: Full path of the specified Shell Namespace item // --- Effect : Retrieves the Full path of the specified Shell // Namespace item inline CString GetFullPath(const LPITEMIDLIST lpFullIDL) const { TCHAR pchPath[MAX_PATH]; if(SHGetPathFromIDList(lpFullIDL,pchPath)) return pchPath; else return _T(""); } // --- In: lpParentFolder - pointer to IShellFolder interface // of the item's parent folder // lpRelativeIDL - relative IDL to its parent folder // dwFlags - optional flags specifying how the // context menu can be changed. Can be // any combination of the following // values: // // CMF_CANRENAME This flag is set if the calling // application supports renaming // of items. A context menu // extension or drag-and-drop // handler should ignore this flag. // A namespace extension should add // a rename item to the menu if // applicable. // CMF_DEFAULTONLY This flag is set when the user // is activating the default action, // typically by double-clicking. // This flag provides a hint for // the context menu extension to // add nothing if it does not // modify the default item in the // menu. A context menu extension // or drag-and-drop handler should // not add any menu items if this // value is specified. A namespace // extension should add only the // default item (if any). // CMF_EXPLORE This flag is set when Windows // Explorer's tree window is // present. Context menu handlers // should ignore this value. // CMF_INCLUDESTATIC This flag is set when a static // menu is being constructed. Only // the browser should use this flag. // All other context menu // extensions should ignore this // flag. // CMF_NODEFAULT This flag is set if no item in // the menu should be the default // item. A context menu extension // or drag-and-drop handler should // ignore this flag. A namespace // extension should not set any of // the menu items to the default. // CMF_NORMAL Indicates normal operation. // A context menu extension, // namespace extension, or // drag-and-drop handler can add // all menu items. // CMF_NOVERBS This flag is set for items // displayed in the "Send To:" menu. // Context menu handlers should // ignore this value. // CMF_VERBSONLY This flag is set if the context // menu is for a shortcut object. // Context menu handlers should // ignore this value. // // --- Out: // --- Returns: Handle to popup menu for corresponding Shell Namespace // item if suceeded or FALSE otherwise // --- Effect : Retrieves handle to popup menu for corresponding // Shell Namespace item HMENU GetObjectContextMenu(const LPSHELLFOLDER lpParentFolder, const LPITEMIDLIST lpRelativeIDL, DWORD dwFlags) const; // --- In: lpParentFolder - pointer to IShellFolder interface // of the item's parent folder // lpRelativeIDL - relative IDL to its parent folder // nCmdID - command ID to be invoked // dwFlags - the same as in GetObjectContextMenu() // function // --- Out: // --- Returns: TRUE if command was successfully invoked or FALSE // otherwise // --- Effect : Invokes menu command from the context menu that was // previously retrieved by calling GetObjectContextMenu() // function BOOL InvokeCommand(const LPSHELLFOLDER lpParentFolder, const LPITEMIDLIST lpRelativeIDL, UINT nCmdID, DWORD dwFlags) const; // --- In: lpParentFolder - pointer to IShellFolder interface // of the item's parent folder // lpRelativeIDL - relative IDL to its parent folder // --- Out: // --- Returns: TRUE if default command was successfully invoked or FALSE // otherwise // --- Effect : Invokes default menu command from the context menu BOOL InvokeDefaultCommand(const LPSHELLFOLDER lpParentFolder, const LPITEMIDLIST lpRelativeIDL) const; // --- In: lpParentFolder - pointer to IShellFolder interface // of the item's parent folder // lpRelativeIDL - relative IDL to its parent folder // lppNewRelativeIDL- pointer to new relative IDL that will be // allocated in result of changing the name. // In this case the old relative IDL will be // automatically freed // lpszNewName - new object's name // --- Out: // --- Returns: TRUE if the object was successfully renamed (in this case old // lpRelativeIDL will be automatically freed and the new one // allocated in lpNewRelativeIDL) or FALSE otherwise // --- Effect : Renames the specified Shell Name space object BOOL RenameShellObject(const LPSHELLFOLDER lpParentFolder, const LPITEMIDLIST lpRelativeIDL, LPITEMIDLIST* lppNewRelativeIDL, LPCTSTR lpszNewName) const; //////////////////////////////////////////////////////////////////////// // set of helper functions // // --- In: pidl1 - IDL // pidl2 - IDL // --- Out: // --- Returns: pidl1 + pidl2 // --- Effect : Concatenates two IDLs. Usually you would call this // function in order to concatenate item's parent fully // qualified IDL and item's relative IDL LPITEMIDLIST ConcatenatePIDLs(LPCITEMIDLIST pidl1, LPCITEMIDLIST pidl2) const; // --- In: pidlSource - IDL // --- Out: // --- Returns: Copy of pidlSource // --- Effect : Copies the specified IDL. LPITEMIDLIST CopyPIDL(LPCITEMIDLIST pidlSource) const; // --- In: pidl - IDL // --- Out: // --- Returns: Size in bytes of the specified IDL // --- Effect : Retrieves the size of specified IDL. UINT GetIDLSize(LPCITEMIDLIST pidl) const; // --- In: pidl - IDL // --- Out: // --- Returns: next IDL item in IDL or NULL if the end has been reached // --- Effect : Retrieves next IDL item in IDL. LPITEMIDLIST GetNextIDLItem(LPCITEMIDLIST pidl) const; // //////////////////////////////////////////////////////////////////////// CString GetSpecialFolderPath(int nFolder, CWnd* pWndOwner=NULL) const; void FreeShellObject(void* pVoid) const; // Implementation public: // --- In: // --- Out: // --- Returns: // --- Effect : Object's destructor virtual ~COXShellNamespaceNavigator(); protected: private: LPMALLOC m_pMalloc; }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Developer Studio will insert additional declarations immediately before the previous line. #endif // !defined(_OXSHELLNAMESPACENAVIGATOR_H_)
[ [ [ 1, 785 ] ] ]
1420b9b8750c26f5f19d8f463a995845031f2602
7b4c786d4258ce4421b1e7bcca9011d4eeb50083
/_代码统计专用文件夹/C++Primer中文版(第4版)/第十四章 重载操作符与转换/20090221_代码14.2_输入和输出操作符_1_Sales_item输出操作符.cpp
e33fb62097d7c8880372f6882eeaa84f2c9e2000
[]
no_license
lzq123218/guoyishi-works
dbfa42a3e2d3bd4a984a5681e4335814657551ef
4e78c8f2e902589c3f06387374024225f52e5a92
refs/heads/master
2021-12-04T11:11:32.639076
2011-05-30T14:12:43
2011-05-30T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
166
cpp
ostream& operator<<(ostream& out, const Sales_item& s) { out << s.isbn << "\t" << s.units_sold << "\t" << s.revenue << "\t" << s.avg_price(); return out; }
[ "baicaibang@70501136-4834-11de-8855-c187e5f49513" ]
[ [ [ 1, 7 ] ] ]
3502db19c71ee13d89eb8613476a7f41af554b06
a65530d88102191a0ff7062a982c00c1408dc4ed
/GlobalTypes/Helper.h
2ebe21956fd432ab7f89c0e36fcbd9fb9061fcab
[]
no_license
willer2009/CompilerWS2012
329e7cf3c76798f67bbdf04624be9e76d8a69d1a
e95e092cd12adf6d0a3c38ae3e5661a7effdb0b0
refs/heads/master
2021-01-19T17:42:14.696270
2011-11-20T15:08:21
2011-11-20T15:08:21
2,809,660
0
0
null
null
null
null
UTF-8
C++
false
false
1,319
h
#include <ctype.h> class Helper { public: int getLength(const char* array) { int length; for(length = 0; array[length] != '\0'; length++); return length; } static void copy(char* destination, const char* source, int length) { for(int i = 0; i < length; i++) { destination[i] = source[i]; } } static bool compare(const char* first, const char* second) { int i; for(i = 0; first[i] != '\0' && second[i] != '\0'; i++) { if (first[i] != second[i]) return false; } if (first[i] != second[i]) return false; return true; } static bool compare(const char* first, const char* second, int length) { for(int i = 0; i < length; i++) { if (first[i] != second[i]) return false; } return true; } static bool compareCaseInsensitive(const char* first, const char* second) { int i; for(i = 0; first[i] != '\0' && second[i] != '\0'; i++) { if (tolower(first[i]) != tolower(second[i])) return false; } if (tolower(first[i]) != tolower(second[i])) return false; return true; } static bool compareCaseInsensitive(const char* first, const char* second, int length) { for(int i = 0; i < length; i++) { if (tolower(first[i]) != tolower(second[i])) return false; } return true; } };
[ [ [ 1, 48 ] ] ]
07ce9fc0eb1079992a2058c171a3f624a310c7a4
a92598d0a8a2e92b424915d2944212f2f13e7506
/PtRPG/libs/cocos2dx/include/CCTextureCache.h
bca2c2173bf5c6f5b7cf278c42f310c8d39ee8b3
[ "MIT" ]
permissive
peteo/RPG_Learn
0cc4facd639bd01d837ac56cf37a07fe22c59211
325fd1802b14e055732278f3d2d33a9577608c39
refs/heads/master
2021-01-23T11:07:05.050645
2011-12-12T08:47:27
2011-12-12T08:47:27
2,299,148
2
0
null
null
null
null
UTF-8
C++
false
false
7,731
h
/**************************************************************************** Copyright (c) 2010-2011 cocos2d-x.org Copyright (c) 2008-2010 Ricardo Quesada Copyright (c) 2011 Zynga Inc. http://www.cocos2d-x.org 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 __CCTEXTURE_CACHE_H__ #define __CCTEXTURE_CACHE_H__ #include <string> #include "CCObject.h" #include "CCMutableDictionary.h" #include "CCTexture2D.h" #if CC_ENABLE_CACHE_TEXTTURE_DATA #include "CCImage.h" #include <list> #endif namespace cocos2d { class CCAsyncObject; class CCLock; class CCImage; typedef void (*fpAsyncCallback)(CCTexture2D*, void*); /** @brief Singleton that handles the loading of textures * Once the texture is loaded, the next time it will return * a reference of the previously loaded texture reducing GPU & CPU memory */ class CC_DLL CCTextureCache : public CCObject { protected: CCMutableDictionary<std::string, CCTexture2D*> * m_pTextures; CCLock *m_pDictLock; CCLock *m_pContextLock; private: // @todo void addImageWithAsyncObject(CCAsyncObject* async); public: CCTextureCache(); virtual ~CCTextureCache(); char * description(void); /** Retruns ths shared instance of the cache */ static CCTextureCache * sharedTextureCache(); /** purges the cache. It releases the retained instance. @since v0.99.0 */ static void purgeSharedTextureCache(); /** Returns a Texture2D object given an file image * If the file image was not previously loaded, it will create a new CCTexture2D * object and it will return it. It will use the filename as a key. * Otherwise it will return a reference of a previosly loaded image. * Supported image extensions: .png, .bmp, .tiff, .jpeg, .pvr, .gif */ CCTexture2D* addImage(const char* fileimage); /* Returns a Texture2D object given a file image * If the file image was not previously loaded, it will create a new CCTexture2D object and it will return it. * Otherwise it will load a texture in a new thread, and when the image is loaded, the callback will be called with the Texture2D as a parameter. * The callback will be called from the main thread, so it is safe to create any cocos2d object from the callback. * Supported image extensions: .png, .jpg * @since v0.8 */ // @todo void addImageAsync(const char* filename, CCObject*target, fpAsyncCallback func); /* Returns a Texture2D object given an CGImageRef image * If the image was not previously loaded, it will create a new CCTexture2D object and it will return it. * Otherwise it will return a reference of a previously loaded image * The "key" parameter will be used as the "key" for the cache. * If "key" is nil, then a new texture will be created each time. * @since v0.8 */ // @todo CGImageRef CCTexture2D* addCGImage(CGImageRef image, string & key); /** Returns a Texture2D object given an UIImage image * If the image was not previously loaded, it will create a new CCTexture2D object and it will return it. * Otherwise it will return a reference of a previously loaded image * The "key" parameter will be used as the "key" for the cache. * If "key" is nil, then a new texture will be created each time. */ CCTexture2D* addUIImage(CCImage *image, const char *key); /** Returns an already created texture. Returns nil if the texture doesn't exist. @since v0.99.5 */ CCTexture2D* textureForKey(const char* key); /** Purges the dictionary of loaded textures. * Call this method if you receive the "Memory Warning" * In the short term: it will free some resources preventing your app from being killed * In the medium term: it will allocate more resources * In the long term: it will be the same */ void removeAllTextures(); /** Removes unused textures * Textures that have a retain count of 1 will be deleted * It is convinient to call this method after when starting a new Scene * @since v0.8 */ void removeUnusedTextures(); /** Deletes a texture from the cache given a texture */ void removeTexture(CCTexture2D* texture); /** Deletes a texture from the cache given a its key name @since v0.99.4 */ void removeTextureForKey(const char *textureKeyName); /** Output to CCLOG the current contents of this CCTextureCache * This will attempt to calculate the size of each texture, and the total texture memory in use * * @since v1.0 */ void dumpCachedTextureInfo(); #ifdef CC_SUPPORT_PVRTC /** Returns a Texture2D object given an PVRTC RAW filename * If the file image was not previously loaded, it will create a new CCTexture2D * object and it will return it. Otherwise it will return a reference of a previosly loaded image * * It can only load square images: width == height, and it must be a power of 2 (128,256,512...) * bpp can only be 2 or 4. 2 means more compression but lower quality. * hasAlpha: whether or not the image contains alpha channel */ CCTexture2D* addPVRTCImage(const char* fileimage, int bpp, bool hasAlpha, int width); #endif // CC_SUPPORT_PVRTC /** Returns a Texture2D object given an PVR filename * If the file image was not previously loaded, it will create a new CCTexture2D * object and it will return it. Otherwise it will return a reference of a previosly loaded image */ CCTexture2D* addPVRImage(const char* filename); /** Reload all textures It's only useful when the value of CC_ENABLE_CACHE_TEXTTURE_DATA is 1 */ static void reloadAllTextures(); }; #if CC_ENABLE_CACHE_TEXTTURE_DATA class VolatileTexture { typedef enum { kInvalid = 0, kImageFile, kImageData, kString, }ccCachedImageType; public: VolatileTexture(CCTexture2D *t); ~VolatileTexture(); static void addImageTexture(CCTexture2D *tt, const char* imageFileName, CCImage::EImageFormat format); static void addStringTexture(CCTexture2D *tt, const char* text, CCSize dimensions, CCTextAlignment alignment, const char *fontName, float fontSize); static void addDataTexture(CCTexture2D *tt, void* data, CCTexture2DPixelFormat pixelFormat, CCSize contentSize); static void removeTexture(CCTexture2D *t); static void reloadAllTextures(); public: static std::list<VolatileTexture*> textures; static bool isReloading; protected: CCTexture2D *texture; ccCachedImageType m_eCashedImageType; void *m_pTextureData; CCSize m_TextureSize; CCTexture2DPixelFormat m_PixelFormat; std::string m_strFileName; CCImage::EImageFormat m_FmtImage; CCSize m_size; CCTextAlignment m_alignment; std::string m_strFontName; std::string m_strText; float m_fFontSize; }; #endif }//namespace cocos2d #endif //__CCTEXTURE_CACHE_H__
[ [ [ 1, 219 ] ] ]
4f64a87fe62d3f4b8a5ac3695a9e3b2e8d4b2a50
ab41c2c63e554350ca5b93e41d7321ca127d8d3a
/glm/virtrev.hpp
ec368e44ceef02efc04ece83f9e5345a97d4deb6
[]
no_license
burner/e3rt
2dc3bac2b7face3b1606ee1430e7ecfd4523bf2e
775470cc9b912a8c1199dd1069d7e7d4fc997a52
refs/heads/master
2021-01-11T08:08:00.665300
2010-04-26T11:42:42
2010-04-26T11:42:42
337,021
3
0
null
null
null
null
UTF-8
C++
false
false
1,119
hpp
/////////////////////////////////////////////////////////////////////////////////////////////////// // OpenGL Mathematics Copyright (c) 2005 - 2008 G-Truc Creation (www.g-truc.net) // Virtrev SDK copyright matrem (matrem84.free.fr) /////////////////////////////////////////////////////////////////////////////////////////////////// // Created : 2008-05-29 // Updated : 2008-10-06 // Licence : This source is under MIT License // File : glm/virtrev.h /////////////////////////////////////////////////////////////////////////////////////////////////// // Note: // Virtrev SDK extensions /////////////////////////////////////////////////////////////////////////////////////////////////// #ifndef glm_virtrev #define glm_virtrev #define GLM_VIRTREV_GLOBAL 1 #if(defined(GLM_DEPENDENCE) && ( \ (GLM_DEPENDENCE & GLM_DEPENDENCE_GLEW) || \ (GLM_DEPENDENCE & GLM_DEPENDENCE_GLEE) || \ (GLM_DEPENDENCE & GLM_DEPENDENCE_GL))) #include "./virtrev/gl.hpp" #endif #include "./virtrev/address.hpp" #include "./virtrev/equal_operator.hpp" #include "./virtrev/xstream.hpp" #endif//glm_virtrev
[ [ [ 1, 29 ] ] ]
74014584a389ee37bc2cce4a13bf843ab2ef4558
737638e4d2496de8656a23e093f40ef74eca6ca8
/dialog.main.h
e4d41cc9930f30c5d6835fab2982bbdb6d659782
[]
no_license
ianperez/x-com-reloaded
edbd06f3d78b833a21b0b0effed5a887d93f071f
e581b56479233943ae8c7c572eca2a51abb36f2d
refs/heads/master
2021-01-21T23:16:50.031442
2010-12-18T05:52:45
2010-12-18T05:52:45
32,757,272
0
0
null
null
null
null
UTF-8
C++
false
false
1,118
h
#pragma once #include "uidialog.h" #include "font.h" #include "point.h" #include "saveinfo.h" #include <map> namespace ufo { using namespace std; class SaveLoadBase : public UIDialog { Palette m_prev; SmallFont m_font; Sint16 m_headerStringId; map<Uint8, SaveInfo> m_saves; public: SaveLoadBase(Sint16 headerStringId); void onCreate(); void onDestroy(); void onOpen(); void draw(Surface& surface); }; class SaveDialog : public SaveLoadBase { public: SaveDialog() : SaveLoadBase(791) { } }; class LoadDialog : public SaveLoadBase { public: LoadDialog() : SaveLoadBase(790) { } }; class LanguageDialog : public UIDialog { public: LanguageDialog(); void onCreate(); void onOpen(); }; class MainMenuDialog : public UIDialog { public: MainMenuDialog(); void onCreate(); void onOpen(); void draw(Surface& surface); }; class DifficultyDialog : public UIDialog { public: DifficultyDialog(); void onCreate(); void onOpen(); void draw(Surface& surface); }; }
[ "ianrobertperez@687bc148-feef-c4d9-3bcb-ab45cd3def04", "[email protected]@687bc148-feef-c4d9-3bcb-ab45cd3def04" ]
[ [ [ 1, 45 ], [ 56, 66 ], [ 70, 77 ], [ 79, 79 ] ], [ [ 46, 55 ], [ 67, 69 ], [ 78, 78 ] ] ]
0aed80a3cf30c21d64209e4a66120b6bf45b7480
0f8559dad8e89d112362f9770a4551149d4e738f
/Wall_Destruction/Havok/Source/Physics/Collide/Util/Welding/hkpWeldingUtility.inl
3b033fac76d80b21bafadcb01a7022a678d1a4df
[]
no_license
TheProjecter/olafurabertaymsc
9360ad4c988d921e55b8cef9b8dcf1959e92d814
456d4d87699342c5459534a7992f04669e75d2e1
refs/heads/master
2021-01-10T15:15:49.289873
2010-09-20T12:58:48
2010-09-20T12:58:48
45,933,002
0
0
null
null
null
null
UTF-8
C++
false
false
4,748
inl
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ hkpWeldingUtility::SectorType hkpWeldingUtility::getSector(const hkVector4& triangleNormal, const hkVector4& collisionNormal, int edgeBitcode ) { // Calculate the cosine for the angle between the triangle's normal and the collision normal // Note: this is the projection of the collision normal onto the triangle's normal and will be compared against // the current edge's cosine values. hkReal cosAngle = triangleNormal.dot3(collisionNormal); if ( cosAngle >= m_sinCosTable[edgeBitcode].m_cosAccept0 ) { return hkpWeldingUtility::ACCEPT_0; } else if ( cosAngle >= m_sinCosTable[edgeBitcode].m_cosSnap0 ) { return hkpWeldingUtility::SNAP_0; } else if ( cosAngle >= m_sinCosTable[edgeBitcode].m_cosSnap1 ) { return hkpWeldingUtility::REJECT; } else if ( cosAngle >= m_sinCosTable[edgeBitcode].m_cosAccept1 ) { return hkpWeldingUtility::SNAP_1; } return hkpWeldingUtility::ACCEPT_1; } hkBool hkpWeldingUtility::shouldSnapOneSided(hkpWeldingUtility::WeldingType weldingType, const hkVector4& triangleNormal, const hkVector4& collisionNormal, int edgeBitcode ) { hkReal cosAngle = triangleNormal.dot3(collisionNormal); hkReal* sinCosTableEntry = &m_sinCosTable[edgeBitcode].m_cosAccept0; return (weldingType == hkpWeldingUtility::WELDING_TYPE_ANTICLOCKWISE) ? cosAngle < sinCosTableEntry[weldingType] : cosAngle > sinCosTableEntry[weldingType]; } void hkpWeldingUtility::calcSnapVector( const hkVector4& triangleNormal, const hkVector4& edge, int edgeBitcode, SectorType sector, hkVector4& snapVectorOut ) { hkVector4 orthNormalEdge; orthNormalEdge.setCross(edge, triangleNormal); // rebuild the 'to-be-snapped-to' accept vector by accessing the float values directly via the sector id (either SNAP_0 or SNAP_1) hkReal* sinCosTableEntry = &m_sinCosTable[edgeBitcode].m_cosAccept0; hkVector4 hVec0; hVec0.setMul4( sinCosTableEntry[sector+0], triangleNormal ); hkVector4 hVec1; hVec1.setMul4( sinCosTableEntry[sector+1], orthNormalEdge ); snapVectorOut.setAdd4(hVec0, hVec1); snapVectorOut.normalize3(); } void hkpWeldingUtility::calcSnapVectorOneSided( const hkVector4& triangleNormal, const hkVector4& edge, int edgeBitcode, hkpWeldingUtility::WeldingType weldingType, hkVector4& snapVectorOut ) { calcSnapVector(triangleNormal, edge, edgeBitcode, (SectorType) weldingType, snapVectorOut ); } void hkpWeldingUtility::snapCollisionNormal(const hkVector4& triangleNormal, const hkVector4& edge, int edgeBitcode, SectorType sector, hkVector4& collisionNormalInOut ) { HK_ASSERT( 0xf02345ef, sector == SNAP_0 || sector == SNAP_1 ); // // rebuild the original snap vector from the triangle normal and the sector information // hkVector4 snapVector; calcSnapVector( triangleNormal, edge, edgeBitcode, sector, snapVector ); // // get the projection values of the collision normal onto the snap vector and the edge vector // hkSimdReal dot0 = snapVector.dot3(collisionNormalInOut); hkSimdReal dot1 = edge.dot3(collisionNormalInOut); // // build a new 'snapped' collision normal from the above reconstructed snap vector and the edge vector by using the above // calculated projection values // { hkVector4 hVec0; hVec0.setMul4(dot0, snapVector); hkVector4 hVec1; hVec1.setMul4(dot1, edge); collisionNormalInOut.setAdd4(hVec0, hVec1); collisionNormalInOut.normalize3(); } HK_ASSERT2( 0xf0f3eaad, hkMath::equal( collisionNormalInOut.lengthSquared3(), 1.0f, 0.01f), "CollisionNormal is not normalized" ); return; } /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20091222) * * Confidential Information of Havok. (C) Copyright 1999-2009 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at www.havok.com/tryhavok. * */
[ [ [ 1, 110 ] ] ]
98e089ec8007513b45f28c12a74fa9b43981e22b
e52b0e0e87fbeb76edd0f11a7e1b03d25027932e
/include/lua/LuaPlus.h
69227bb1458f935a85098445f46b420cda9a5b9e
[]
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,047
h
/////////////////////////////////////////////////////////////////////////////// // This source file is part of the LuaPlus source distribution and is Copyright // 2001-2004 by Joshua C. Jensen ([email protected]). // // The latest version may be obtained from http://wwhiz.com/LuaPlus/. // // The code presented in this file may be used in any environment it is // acceptable to use Lua. /////////////////////////////////////////////////////////////////////////////// #ifdef _MSC_VER #pragma once #endif // _MSC_VER #ifndef LUAPLUS_H #define LUAPLUS_H #include <stdarg.h> #include <string.h> #ifdef _MSC_VER #pragma warning(disable: 4505) #pragma warning(disable: 4127) #endif // _MSC_VER #include "LuaLink.h" struct lua_TObject; struct lua_TObjectBuffer; extern "C" { #include "include/lua.h" #include "include/lauxlib.h" #include "LuaPlusAddons.h" } // extern "C" #define LUAPLUS_ENABLE_INLINES #ifdef LUAPLUS_ENABLE_INLINES #define LUAPLUS_INLINE inline #else // !LUAPLUS_ENABLE_INLINES #define LUAPLUS_INLINE #endif // LUAPLUS_ENABLE_INLINES /////////////////////////////////////////////////////////////////////////////// // namespace LuaPlus /////////////////////////////////////////////////////////////////////////////// namespace LuaPlus { class LuaException { public: LuaException(const char* message) : m_message(message) {} ~LuaException() {} const char* GetMessage() const { return m_message; } protected: const char* m_message; }; //#define luaplus_assert(e) /* empty */ #define luaplus_assert(e) if (!(e)) throw LuaException(#e) #define luaplus_throw(e) throw LuaException(e) class LuaStateOutFile; class LuaState; class LuaStackObject; } // namespace LuaPlus #include "LuaStackObject.h" #include "LuaObject.h" #include "LuaState.h" #include "LuaTableIterator.h" #include "LuaObject.inl" #include "LuaStateOutFile.h" #include "LuaHelper.h" #include "LuaAutoBlock.h" #include "LuaStackTableIterator.h" #endif // LUAPLUS_H
[ [ [ 1, 81 ] ] ]
abf522d32d74648f7c9f479450d09bed5710d1b4
f55665c5faa3d79d0d6fe91fcfeb8daa5adf84d0
/Depend/MyGUI/Tools/SkinEditor/SettingsWindow.h
3ea9dbe9738f184a8efa53c5cfd819acf0a8ce0f
[]
no_license
lxinhcn/starworld
79ed06ca49d4064307ae73156574932d6185dbab
86eb0fb8bd268994454b0cfe6419ffef3fc0fc80
refs/heads/master
2021-01-10T07:43:51.858394
2010-09-15T02:38:48
2010-09-15T02:38:48
47,859,019
2
1
null
null
null
null
UTF-8
C++
false
false
1,157
h
/*! @file @author Georgiy Evmenov @date 09/2008 */ #ifndef __SETTINGS_WINDOW_H__ #define __SETTINGS_WINDOW_H__ #include "BaseLayout/BaseLayout.h" #include "Dialog.h" #include "OpenSaveFileDialog.h" namespace tools { class SettingsWindow : public Dialog { public: SettingsWindow(); virtual ~SettingsWindow(); void loadSettings(); void saveSettings(); protected: virtual void onDoModal(); virtual void onEndModal(); private: void notifyOkSettings(MyGUI::Widget* _sender); void notifyCancel(MyGUI::Widget* _sender); void notifyWindowButtonPressed(MyGUI::Window* _sender, const std::string& _name); void notifyClickResourcePathAdd(MyGUI::Widget* _sender); void notifyClickResourcePathDelete(MyGUI::Widget* _sender); void notifyEndDialogOpenSaveFile(Dialog* _sender, bool _result); private: MyGUI::Button* mButtonOkSettings; MyGUI::Button* mButtonCancel; MyGUI::Button* mResourcePathAdd; MyGUI::Button* mResourcePathDelete; MyGUI::List* mResourcePaths; OpenSaveFileDialog* mOpenSaveFileDialog; }; } // namespace tools #endif // __SETTINGS_WINDOW_H__
[ "albertclass@a94d7126-06ea-11de-b17c-0f1ef23b492c" ]
[ [ [ 1, 51 ] ] ]
240e0e566f417cf752e0f88621ce7987ea0b1e0c
867f5533667cce30d0743d5bea6b0c083c073386
/jingxian-downloader/wxCURL/include/wxCURL/ftptool.h
393e883b441b0cbae7721e9ca77ddad750e7960f
[]
no_license
mei-rune/jingxian-project
32804e0fa82f3f9a38f79e9a99c4645b9256e889
47bc7a2cb51fa0d85279f46207f6d7bea57f9e19
refs/heads/master
2022-08-12T18:43:37.139637
2009-12-11T09:30:04
2009-12-11T09:30:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,495
h
/* * ftptool.h * wxCURL * * Created by Casey O'Donnell on Fri Aug 13 2004. * Copyright (c) 2004 Casey O'Donnell. All rights reserved. * * Licence: wxWidgets Licence */ #ifndef _WXCURLFTPTOOL_H__INCLUDED_ #define _WXCURLFTPTOOL_H__INCLUDED_ #if defined(__GNUG__) && !defined(__APPLE__) #pragma interface "wxcurl/ftptool.h" #endif #include "wxcurl/ftp.h" class wxCurlFTPTool; class WXDLLIMPEXP_CURL wxCurlFTPFs { friend class wxCurlFTPTool; public: wxCurlFTPFs(); wxCurlFTPFs(const wxString& szName , const bool& bIsDir , const bool& bIsFile , const time_t& tLastModified , const long& iContentLength ); ~wxCurlFTPFs(); bool IsDirectory() const { return m_bIsDir; } bool IsFile() const { return m_bIsFile; } wxString GetName() const { return m_szName; } wxDateTime GetLastModified() const { return m_dtLastModified; } long GetContentLength() const { return m_iContentLength; } wxString GetFileSuffix() const { return m_szName.AfterLast('.'); } protected: wxString m_szName; bool m_bIsDir; bool m_bIsFile; wxDateTime m_dtLastModified; long m_iContentLength; }; WX_DECLARE_OBJARRAY(wxCurlFTPFs, wxArrayFTPFs); // ftptool.h: interface for the wxCurlFTPTool class. // ////////////////////////////////////////////////////////////////////// class WXDLLIMPEXP_CURL wxCurlFTPTool : public wxCurlFTP { public: wxCurlFTPTool(const wxString& szURL = wxEmptyString, const wxString& szUserName = wxEmptyString, const wxString& szPassword = wxEmptyString, wxEvtHandler* pEvtHandler = NULL, const bool& bSendUpdateEvents = false, const bool& bSendBeginEndEvents = false); virtual ~wxCurlFTPTool(); // More Complex Action Methods - These All Make Calls To: curl_easy_perform() // These routines have more 'intelligence' than simple FTP calls. bool GetFTPFs(wxArrayFTPFs& fs, const wxString& szRemoteLoc = wxEmptyString); bool Exists(const wxString& szRemoteLoc = wxEmptyString); bool IsDirectory(const wxString& szRemoteLoc = wxEmptyString); bool HasDirectory(const wxString& szRemoteLoc = wxEmptyString) { return IsDirectory(szRemoteLoc); } wxDateTime GetLastModified(const wxString& szRemoteLoc = wxEmptyString); long GetContentLength(const wxString& szRemoteLoc = wxEmptyString); wxString GetFileSuffix(const wxString& szRemoteLoc = wxEmptyString); protected: private: }; #endif // _WXCURLFTPTOOL_H__INCLUDED_
[ "runner.mei@0dd8077a-353d-11de-b438-597f59cd7555" ]
[ [ [ 1, 86 ] ] ]
d827e9b5f50e7cdb3f8c5fe120614f523c6a9aed
5a05acb4caae7d8eb6ab4731dcda528e2696b093
/ThirdParty/luabind/luabind/detail/format_signature.hpp
18ca2e94eaf51554e60de4e5a2e7bb832c43d0d2
[]
no_license
andreparker/spiralengine
aea8b22491aaae4c14f1cdb20f5407a4fb725922
36a4942045f49a7255004ec968b188f8088758f4
refs/heads/master
2021-01-22T12:12:39.066832
2010-05-07T00:02:31
2010-05-07T00:02:31
33,547,546
0
0
null
null
null
null
UTF-8
C++
false
false
3,357
hpp
// Copyright Daniel Wallin 2008. Use, modification and distribution is // subject to 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 LUABIND_FORMAT_SIGNATURE_081014_HPP # define LUABIND_FORMAT_SIGNATURE_081014_HPP # include <luabind/config.hpp> # include <luabind/lua_include.hpp> # include <boost/mpl/begin_end.hpp> # include <boost/mpl/next.hpp> # include <boost/mpl/size.hpp> namespace luabind { class object; class argument; } // namespace luabind namespace luabind { namespace detail { LUABIND_API std::string get_class_name( lua_State* L, LUABIND_TYPE_INFO i ); template <class T> struct type_to_string { static void get( lua_State* L ) { lua_pushstring( L, get_class_name( L, LUABIND_TYPEID( T ) ).c_str() ); } }; template <class T> struct type_to_string<T*> { static void get( lua_State* L ) { type_to_string<T>::get( L ); lua_pushstring( L, "*" ); lua_concat( L, 2 ); } }; template <class T> struct type_to_string<T&> { static void get( lua_State* L ) { type_to_string<T>::get( L ); lua_pushstring( L, "&" ); lua_concat( L, 2 ); } }; template <class T> struct type_to_string<T const> { static void get( lua_State* L ) { type_to_string<T>::get( L ); lua_pushstring( L, " const" ); lua_concat( L, 2 ); } }; # define LUABIND_TYPE_TO_STRING(x) \ template <> \ struct type_to_string<x> \ { \ static void get(lua_State* L) \ { \ lua_pushstring(L, #x); \ } \ }; # define LUABIND_INTEGRAL_TYPE_TO_STRING(x) \ LUABIND_TYPE_TO_STRING(x) \ LUABIND_TYPE_TO_STRING(unsigned x) LUABIND_INTEGRAL_TYPE_TO_STRING( char ) LUABIND_INTEGRAL_TYPE_TO_STRING( short ) LUABIND_INTEGRAL_TYPE_TO_STRING( int ) LUABIND_INTEGRAL_TYPE_TO_STRING( long ) LUABIND_TYPE_TO_STRING( void ) LUABIND_TYPE_TO_STRING( bool ) LUABIND_TYPE_TO_STRING( std::string ) LUABIND_TYPE_TO_STRING( lua_State ) LUABIND_TYPE_TO_STRING( luabind::object ) LUABIND_TYPE_TO_STRING( luabind::argument ) # undef LUABIND_INTEGRAL_TYPE_TO_STRING # undef LUABIND_TYPE_TO_STRING template <class End> void format_signature_aux( lua_State*, bool, End, End ) {} template <class Iter, class End> void format_signature_aux( lua_State* L, bool first, Iter, End end ) { if ( !first ) lua_pushstring( L, "," ); type_to_string<typename Iter::type>::get( L ); format_signature_aux( L, false, typename mpl::next<Iter>::type(), end ); } template <class Signature> void format_signature( lua_State* L, char const* function, Signature ) { typedef typename mpl::begin<Signature>::type first; type_to_string<typename first::type>::get( L ); lua_pushstring( L, " " ); lua_pushstring( L, function ); lua_pushstring( L, "(" ); format_signature_aux( L , true , typename mpl::next<first>::type() , typename mpl::end<Signature>::type() ); lua_pushstring( L, ")" ); lua_concat( L, mpl::size<Signature>() * 2 + 2 ); } } } // namespace luabind::detail #endif // LUABIND_FORMAT_SIGNATURE_081014_HPP
[ "DreLnBrown@e933ee44-1dc6-11de-9e56-bf19dc6c588e" ]
[ [ [ 1, 141 ] ] ]
a0c53f661b6104a3622658290f4357ec23a39899
f6c641b102ebbffb48e93dd554a0b7eb7e639be7
/Source/Base/Base Graphics Library/Texture2D.cpp
f7e8514dc3ae7c229a99bf542fde63a9fc273988
[]
no_license
ZAsprose/rtrt-on-gpu
e3ca4921a3429cbc72e0cee8afd946200b83573d
4949e373c273f963467658ca25d39244da7fb4e6
refs/heads/master
2021-01-10T14:42:45.293509
2010-08-25T18:37:19
2010-08-25T18:37:19
53,016,647
0
0
null
null
null
null
UTF-8
C++
false
false
4,191
cpp
/* ----------------------------------------------------------------------------- | B A S E G R A P H I C S L I B R A R Y | ----------------------------------------------------------------------------- Copyright (c) 2009 - 2010 Denis Bogolepov ( denisbogol @ gmail.com ) This library 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 library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include <logger.h> #include "Texture2D.hpp" namespace graphics { /************************************************************************/ /* CONSTRUCTOR AND DESTRUCTOR */ /************************************************************************/ Texture2D :: Texture2D ( GLenum unit, TextureData2D * data, GLenum target ) { fUnit = unit; fTarget = target; Data = data; glGenTextures ( 1, &fHandle ); EZLOGGERSTREAM << "Texture 2D was created\n"; EZLOGGERVAR ( fHandle ); } /************************************************************************/ Texture2D :: ~Texture2D ( void ) { delete Data; glDeleteTextures ( 1, &fHandle ); EZLOGGERSTREAM << "Texture 2D was deleted\n"; EZLOGGERVAR ( fHandle ); } /************************************************************************/ /* PUBLIC METHODS */ /************************************************************************/ void Texture2D :: Setup ( void ) { EZLOGGERSTREAM << "Setting texture data to OpenGL...\n"; EZLOGGERVAR ( fHandle ); EZLOGGERVAR ( fUnit ); if ( NULL != Data ) { Bind ( ); WrapMode.Setup ( fTarget ); FilterMode.Setup ( fTarget ); Data->Upload ( fTarget ); } else { EZLOGGERSTREAM << "ERROR: Texture data is empty\n"; } } /************************************************************************/ void Texture2D :: Update ( void ) { if ( NULL != Data ) { Bind ( ); Data->Upload ( fTarget ); } else { EZLOGGERSTREAM << "ERROR: Texture data is empty\n"; } } /************************************************************************/ void Texture2D :: Bind ( void ) { glActiveTexture ( GL_TEXTURE0 + fUnit ); glBindTexture ( fTarget, fHandle ); } /************************************************************************/ void Texture2D :: Unbind ( void ) { glActiveTexture ( GL_TEXTURE0 + fUnit ); glBindTexture ( fTarget, NULL ); } /************************************************************************/ GLenum Texture2D :: Unit ( void ) const { return fUnit; } /************************************************************************/ GLenum Texture2D :: Target ( void ) const { return fTarget; } /************************************************************************/ GLuint Texture2D :: Handle ( void ) const { return fHandle; } }
[ [ [ 1, 143 ] ] ]
ce656ec9e974945e5c870422c7fdf253fb3e1cd5
8e884f5b3617ff81a593273fb23286b4d789f548
/MakeDef/PCL_Set.hxx
ec3c4fb449451a0133c51e9d8ad094dc862499d2
[]
no_license
mau4x/PCL-1
76716e6af3f1e616ca99ac790ef6c5e8c36a8d46
b440c2ce3f3016c0c6f2ecdea9643f1a9bae19cc
refs/heads/master
2020-04-06T21:48:35.864329
2011-08-12T21:38:54
2011-08-12T21:38:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,430
hxx
#ifndef __PCL_SET_H__ #define __PCL_SET_H__ #ifndef __PCL_H__ # error Do not include this file directly. Include "PCL.h" instead #endif ///! //*!===========================================================================! //*! PCL stands for Portable Class Library and is designed for development //*! of applications portable between different environments, //*! first of all between MS Windows and GNU Linux. //*! //*! CopyFree Pulse Computer Consulting, 2001 - 2011 //*! //*! CopyFree License Agreement: //*! 1.You may do with this code WHATEVER YOU LIKE. //*! 2.In NO CASE Pulse Computer Consulting is responsible for your results. //*! //*! E-mail: [email protected], [email protected] //*!===========================================================================! ///! ///! ///! Virtual Set ///! static const uint VSetClassCode = VIRTUALCODE(false); class VSet { public: ///! ///! Public Methods ///! public: // General Management virtual uint Length() const =0; // 0 for empty set virtual void SetLength(uint NewLength) =0; // 0 to make set empty virtual void SetAll(bool NewValue) =0; virtual void Copy(const VSet &SourceSet) =0; virtual void SetValue(uint Member, bool NewValue) =0; virtual bool Value(uint Member) const =0; // Set Logics virtual void Not(void) =0; virtual void And(const VSet &Set) =0; virtual void Or(const VSet &Set) =0; virtual void Xor(const VSet &Set) =0; virtual bool IsEqual(const VSet &Set) const =0; virtual bool IsEmpty(void) const =0; ///! ///! Public Operators ///! public: virtual bool operator [](uint Member) const =0; // .Value() {Same as Pascal's 'in'} // Assignments virtual const VSet& operator =(bool NewValue) =0; // .SetAll(NewValue) virtual const VSet& operator &=(const VSet &Set) =0; // .And(Set) virtual const VSet& operator |=(const VSet &Set) =0; // .Or(Set) virtual const VSet& operator ^=(const VSet &Set) =0; // .Xor(Set) virtual const VSet& operator +=(uint Member) =0; // .SetValue(Member, true) virtual const VSet& operator -=(uint Member) =0; // .SetValue(Member, false) // Comparisons virtual bool operator ==(const VSet &Set) const =0; // .IsEqual(Set) virtual bool operator !=(const VSet &Set) const =0; // !.IsEqual(Set) ///! ///! Protected Methods (Direct access to the set) ///! virtual uint _Size(void) const =0; virtual puchar _Addr(void) const =0; }; ///!===========================================================================! ///! ///! Definition of Set of cardinal numbers ///! static const uint LSetClassCode = CLASSCODE(VSetClassCode); class PCL_API LSet : public VSet { public: static const uint ClassCode() {return LSetClassCode;}; public: LSet(uint InitialLength = 0, bool InitialValue = false); LSet(const LSet &Set); virtual ~LSet(); virtual const VSet& operator =(const LSet &Set); ///! ///! Public Methods ///! public: // General Management virtual uint Length() const ; // 0 for empty set virtual void SetLength(uint NewLength) ; // 0 to make set empty virtual void SetAll(bool NewValue) ; virtual void Copy(const VSet &SourceSet) ; virtual void SetValue(uint Member, bool NewValue) ; virtual bool Value(uint Member) const ; // Set Logics virtual void Not(void) ; virtual void And(const VSet &Set) ; virtual void Or(const VSet &Set) ; virtual void Xor(const VSet &Set) ; virtual bool IsEqual(const VSet &Set) const ; virtual bool IsEmpty(void) const ; ///! ///! Public Operators ///! public: virtual bool operator [](uint Member) const ; // .Value() {Same as Pascal's 'in'} // Assignments virtual const VSet& operator =(bool NewValue) ; // .SetAll(NewValue) virtual const VSet& operator &=(const VSet &Set) ; // .And(Set) virtual const VSet& operator |=(const VSet &Set) ; // .Or(Set) virtual const VSet& operator ^=(const VSet &Set) ; // .Xor(Set) virtual const VSet& operator +=(uint Member) ; // .SetValue(Member, true) virtual const VSet& operator -=(uint Member) ; // .SetValue(Member, false) // Comparisons virtual bool operator ==(const VSet &Set) const ; // .IsEqual(Set) virtual bool operator !=(const VSet &Set) const ; // !.IsEqual(Set) ///! ///! Protected Methods (Direct access to the set) ///! virtual uint _Size(void) const ; virtual puchar _Addr(void) const ; private: LMemory m_set; uint m_length; uchar m_tailMask; }; #endif // __PCL_SET_H__
[ [ [ 1, 116 ] ] ]
07cb3c13840449d01b9a913e48380866b5976fef
4ecb7e18f351ee920a6847c7ebd9010b6a5d34ce
/HD/trunk/HuntingDragon/gametutor/header/CControllerKeyManager_inc.h
85bae3f28f5367af8b8ad101d22f6b63043d1276
[]
no_license
dogtwelve/bkiter08-gameloft-internship-2011
505141ea314c234d99652600db5165a22cf041c3
0efc9f009bf12fe4ed36e1abfeb34f346a8c4198
refs/heads/master
2021-01-10T12:16:51.540936
2011-10-27T13:30:50
2011-10-27T13:30:50
46,549,117
0
0
null
null
null
null
UTF-8
C++
false
false
1,641
h
enum EKeyCode { EKEY_WIN_A = (0x41)<<4, EKEY_WIN_B = (0x42)<<4, EKEY_WIN_D = (0x43)<<4, EKEY_WIN_E = (0x44)<<4, EKEY_WIN_F = (0x45)<<4, EKEY_WIN_G = (0x46)<<4, EKEY_WIN_H = (0x47)<<4, EKEY_WIN_I = (0x48)<<4, EKEY_WIN_J = (0x49)<<4, EKEY_WIN_K = (0x4A)<<4, EKEY_WIN_L = (0x4B)<<4, EKEY_WIN_M = (0x4C)<<4, EKEY_WIN_N = (0x4D)<<4, EKEY_WIN_O = (0x4E)<<4, EKEY_WIN_P = (0x5F)<<4, EKEY_WIN_Q = (0x50)<<4, EKEY_WIN_R = (0x51)<<4, EKEY_WIN_S = (0x52)<<4, EKEY_WIN_T = (0x53)<<4, EKEY_WIN_U = (0x54)<<4, EKEY_WIN_V = (0x55)<<4, EKEY_WIN_X = (0x56)<<4, EKEY_WIN_Y = (0x57)<<4, EKEY_WIN_Z = (0x58)<<4, EKEY_WIN_W = (0x59)<<4, EKEY_SPACE = (0x20)<<4, }; struct SKeyStorageInfomation { __INT32 Keycode; EKeyEvent Status; __UINT64 PressedTimeStamp; __UINT64 HoldDuration; }; class CControllerKeyManager: public CSingleton<CControllerKeyManager> { friend class CSingleton<CControllerKeyManager>; friend CControllerEventManager; protected: CControllerKeyManager(); public: virtual ~CControllerKeyManager(); void Enable(bool value) {m_isEnable = value;} bool IsEnable() {return m_isEnable;} bool WasKeyPressed(int keycode); bool WasKeyHold(int keycode); bool WasKeyRelease(int keycode); bool WasAnyKeyPressed(); bool WasAnyKeyHold(); bool WasAnyKeyRelease(); __UINT64 GetKeyHoldDuration(int keycode); void Reset(); private: void Update(); void OnKeyPressed(__INT32 keycode); void OnKeyRelease(__INT32 keycode); void OnKeyHold(__INT32 keycode); private: CLutI<SKeyStorageInfomation*> m_KeysInfo; bool m_isEnable; };
[ [ [ 1, 66 ] ] ]
d2af9ede98506d9fafe770a09768abe337320686
447a1817531f5eff55925709ff1cdde37033cf79
/src/core/ieventhandler.h
3c38ebc239ff1480d310e5c8d1ecf09f66eb535b
[]
no_license
Kazade/kazengine
63276feef92f7daae5ac10563589bb5b87233644
0723eb6f22e651f9ea2d110b00b3f4c5d94465d5
refs/heads/master
2020-03-31T12:12:58.501020
2008-08-14T20:14:44
2008-08-14T20:14:44
32,983
4
1
null
null
null
null
UTF-8
C++
false
false
398
h
#ifndef IEVENTHANDLER_H_INCLUDED #define IEVENTHANDLER_H_INCLUDED #include <SDL/SDL.h> #include "ilogholder.h" class event_handler_interface : public ILogHolder { public: virtual ~event_handler_interface() {} ///Returns true if the event was handled (no further processing will be done) virtual bool on_event_received(const SDL_Event& e) = 0; }; #endif // IEVENTHANDLER_H_INCLUDED
[ "luke@helium.(none)" ]
[ [ [ 1, 15 ] ] ]
a58fbaa2627fe0619c68c404a1224ace7846834a
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/Samples/Applet/App.h
bf2e60130d10e9c6c8e2d6e1766f300f0ed74497
[]
no_license
svn2github/ngene
b2cddacf7ec035aa681d5b8989feab3383dac012
61850134a354816161859fe86c2907c8e73dc113
refs/heads/master
2023-09-03T12:34:18.944872
2011-07-27T19:26:04
2011-07-27T19:26:04
78,163,390
2
0
null
null
null
null
UTF-8
C++
false
false
976
h
/* --------------------------------------------------------------------------- This source file is part of nGENE Tech. Copyright (c) 2006- Wojciech Toman This program is free software. File: App.h Version: 0.01 --------------------------------------------------------------------------- */ #pragma once #include "FrameworkWin32.h" #include "ScenePartitionerQuadTree.h" #include "MyInputListener.h" #include "MyWindow.h" using namespace nGENE::Application; using nGENE::ScenePartitionerQuadTree; using nGENE::CharacterController; class App: public FrameworkWin32 { private: ScenePartitionerQuadTree* m_pPartitioner; MyInputListener* m_pInputListener; CameraThirdPerson* m_pCamera; GUIFont* m_pFont; MyWindow m_Window; public: App() {} ~App() {} void createApplication(HWND* hwnd); // This function will load materials and stuff like that. void loadResources(); CameraThirdPerson* getCamera() const; };
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 48 ] ] ]
2f01a143bc1b5283015020bbb234ce4aefbc1963
5ff30d64df43c7438bbbcfda528b09bb8fec9e6b
/kgraphics/math/LineSegment3.cpp
bbbfe6067fa504d4e2cd4949dfc03cb3f15326fd
[]
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
23,619
cpp
#include <stdafx.h> #include <kgraphics/math/LineSegment3.h> #include <kgraphics/math/Ray3.h> #include <kgraphics/math/Line3.h> #include <kgraphics/math/math.h> #include <kgraphics/math/Matrix33.h> #include <kgraphics/math/Matrix44.h> #include <kgraphics/math/Quat.h> #include <kgraphics/math/Vector3.h> namespace gfx { //---------------------------------------------------------------------------- // @ LineSegment3::LineSegment3() // --------------------------------------------------------------------------- // Constructor //----------------------------------------------------------------------------- LineSegment3::LineSegment3() : mOrigin( 0.0f, 0.0f, 0.0f ), mDirection( 1.0f, 0.0f, 0.0f ) { } // End of LineSegment3::LineSegment3() //---------------------------------------------------------------------------- // @ LineSegment3::LineSegment3() // --------------------------------------------------------------------------- // Constructor //----------------------------------------------------------------------------- LineSegment3::LineSegment3( const Vector3& endpoint0, const Vector3& endpoint1 ) : mOrigin( endpoint0 ), mDirection( endpoint1-endpoint0 ) { } // End of LineSegment3::LineSegment3() //---------------------------------------------------------------------------- // @ LineSegment3::LineSegment3() // --------------------------------------------------------------------------- // Copy constructor //----------------------------------------------------------------------------- LineSegment3::LineSegment3( const LineSegment3& other ) : mOrigin( other.mOrigin ), mDirection( other.mDirection ) { } // End of LineSegment3::LineSegment3() //---------------------------------------------------------------------------- // @ LineSegment3::operator=() // --------------------------------------------------------------------------- // Assigment operator //----------------------------------------------------------------------------- LineSegment3& LineSegment3::operator=( const LineSegment3& other ) { // if same object if ( this == &other ) return *this; mOrigin = other.mOrigin; mDirection = other.mDirection; return *this; } // End of LineSegment3::operator=() //------------------------------------------------------------------------------- // @ operator<<() //------------------------------------------------------------------------------- // Output a text LineSegment3. The format is assumed to be : // [ Vector3, Vector3 ] //------------------------------------------------------------------------------- Writer& operator<<(Writer& out, const LineSegment3& source) { return out << "[" << source.GetEndpoint0() << ", " << source.GetEndpoint1() << "]"; } // End of operator<<() //---------------------------------------------------------------------------- // @ LineSegment3::Get() // --------------------------------------------------------------------------- // Returns the two endpoints //----------------------------------------------------------------------------- void LineSegment3::Get( Vector3& endpoint0, Vector3& endpoint1 ) const { endpoint0 = mOrigin; endpoint1 = mOrigin + mDirection; } // End of LineSegment3::Get() //---------------------------------------------------------------------------- // @ LineSegment3::Length() // --------------------------------------------------------------------------- // Returns the distance between two endpoints //----------------------------------------------------------------------------- float LineSegment3::Length() const { return mDirection.Length(); } // End of LineSegment3::Length() //---------------------------------------------------------------------------- // @ LineSegment3::LengthSquared() // --------------------------------------------------------------------------- // Returns the squared distance between two endpoints //----------------------------------------------------------------------------- float LineSegment3::LengthSquared() const { return mDirection.LengthSquared(); } // End of LineSegment3::LengthSquared() //---------------------------------------------------------------------------- // @ LineSegment3::operator==() // --------------------------------------------------------------------------- // Are two LineSegment3's equal? //---------------------------------------------------------------------------- bool LineSegment3::operator==( const LineSegment3& segment ) const { return ((segment.mOrigin == mOrigin && segment.mDirection == mDirection) || (segment.mOrigin == mOrigin+mDirection && segment.mDirection == -mDirection)); } // End of LineSegment3::operator==() //---------------------------------------------------------------------------- // @ LineSegment3::operator!=() // --------------------------------------------------------------------------- // Are two LineSegment3's not equal? //---------------------------------------------------------------------------- bool LineSegment3::operator!=( const LineSegment3& segment ) const { return !((segment.mOrigin == mOrigin && segment.mDirection == mDirection) || (segment.mOrigin == mOrigin+mDirection && segment.mDirection == -mDirection)); } // End of LineSegment3::operator!=() //---------------------------------------------------------------------------- // @ LineSegment3::Set() // --------------------------------------------------------------------------- // Sets the two endpoints //----------------------------------------------------------------------------- void LineSegment3::Set( const Vector3& endpoint0, const Vector3& endpoint1 ) { mOrigin = endpoint0; mDirection = endpoint1-endpoint0; } // End of LineSegment3::Set() //---------------------------------------------------------------------------- // @ LineSegment3::Transform() // --------------------------------------------------------------------------- // Transforms segment into new space //----------------------------------------------------------------------------- LineSegment3 LineSegment3::Transform( float scale, const Quat& rotate, const Vector3& translate ) const { LineSegment3 segment; Matrix44 transform(rotate); transform(0,0) *= scale; transform(1,0) *= scale; transform(2,0) *= scale; transform(0,1) *= scale; transform(1,1) *= scale; transform(2,1) *= scale; transform(0,2) *= scale; transform(1,2) *= scale; transform(2,2) *= scale; segment.mDirection = transform.Transform( mDirection ); transform(0,3) = translate.x; transform(1,3) = translate.y; transform(2,3) = translate.z; segment.mOrigin = transform.Transform( mOrigin ); return segment; } // End of LineSegment3::Transform() //---------------------------------------------------------------------------- // @ LineSegment3::Transform() // --------------------------------------------------------------------------- // Transforms segment into new space //----------------------------------------------------------------------------- LineSegment3 LineSegment3::Transform( float scale, const Matrix33& rotate, const Vector3& translate ) const { LineSegment3 segment; Matrix44 transform(rotate); transform(0,0) *= scale; transform(1,0) *= scale; transform(2,0) *= scale; transform(0,1) *= scale; transform(1,1) *= scale; transform(2,1) *= scale; transform(0,2) *= scale; transform(1,2) *= scale; transform(2,2) *= scale; segment.mDirection = transform.Transform( mDirection ); transform(0,3) = translate.x; transform(1,3) = translate.y; transform(2,3) = translate.z; segment.mOrigin = transform.Transform( mOrigin ); return segment; } // End of LineSegment3::Transform() //---------------------------------------------------------------------------- // @ ::DistanceSquared() // --------------------------------------------------------------------------- // Returns the distance squared between two line segments. // Based on article and code by Dan Sunday at www.geometryalgorithms.com //----------------------------------------------------------------------------- float DistanceSquared( const LineSegment3& segment0, const LineSegment3& segment1, float& s_c, float& t_c ) { // compute intermediate parameters Vector3 w0 = segment0.mOrigin - segment1.mOrigin; float a = segment0.mDirection.Dot( segment0.mDirection ); float b = segment0.mDirection.Dot( segment1.mDirection ); float c = segment1.mDirection.Dot( segment1.mDirection ); float d = segment0.mDirection.Dot( w0 ); float e = segment1.mDirection.Dot( w0 ); float denom = a*c - b*b; // parameters to compute s_c, t_c float sn, sd, tn, td; // if denom is zero, try finding closest point on segment1 to origin0 if ( gfx::IsZero(denom) ) { // clamp s_c to 0 sd = td = c; sn = 0.0f; tn = e; } else { // clamp s_c within [0,1] sd = td = denom; sn = b*e - c*d; tn = a*e - b*d; // clamp s_c to 0 if (sn < 0.0f) { sn = 0.0f; tn = e; td = c; } // clamp s_c to 1 else if (sn > sd) { sn = sd; tn = e + b; td = c; } } // clamp t_c within [0,1] // clamp t_c to 0 if (tn < 0.0f) { t_c = 0.0f; // clamp s_c to 0 if ( -d < 0.0f ) { s_c = 0.0f; } // clamp s_c to 1 else if ( -d > a ) { s_c = 1.0f; } else { s_c = -d/a; } } // clamp t_c to 1 else if (tn > td) { t_c = 1.0f; // clamp s_c to 0 if ( (-d+b) < 0.0f ) { s_c = 0.0f; } // clamp s_c to 1 else if ( (-d+b) > a ) { s_c = 1.0f; } else { s_c = (-d+b)/a; } } else { t_c = tn/td; s_c = sn/sd; } // compute difference vector and distance squared Vector3 wc = w0 + s_c*segment0.mDirection - t_c*segment1.mDirection; return wc.Dot(wc); } // End of ::DistanceSquared() //---------------------------------------------------------------------------- // @ ::DistanceSquared() // --------------------------------------------------------------------------- // Returns the distance squared between line segment and ray. // Based on article and code by Dan Sunday at www.geometryalgorithms.com //----------------------------------------------------------------------------- float DistanceSquared( const LineSegment3& segment, const Ray3& ray, float& s_c, float& t_c ) { // compute intermediate parameters Vector3 w0 = segment.mOrigin - ray.GetOrigin(); float a = segment.mDirection.Dot( segment.mDirection ); float b = segment.mDirection.Dot( ray.GetDirection() ); float c = ray.GetDirection().Dot( ray.GetDirection() ); float d = segment.mDirection.Dot( w0 ); float e = ray.GetDirection().Dot( w0 ); float denom = a*c - b*b; // parameters to compute s_c, t_c float sn, sd, tn, td; // if denom is zero, try finding closest point on segment1 to origin0 if ( gfx::IsZero(denom) ) { // clamp s_c to 0 sd = td = c; sn = 0.0f; tn = e; } else { // clamp s_c within [0,1] sd = td = denom; sn = b*e - c*d; tn = a*e - b*d; // clamp s_c to 0 if (sn < 0.0f) { sn = 0.0f; tn = e; td = c; } // clamp s_c to 1 else if (sn > sd) { sn = sd; tn = e + b; td = c; } } // clamp t_c within [0,+inf] // clamp t_c to 0 if (tn < 0.0f) { t_c = 0.0f; // clamp s_c to 0 if ( -d < 0.0f ) { s_c = 0.0f; } // clamp s_c to 1 else if ( -d > a ) { s_c = 1.0f; } else { s_c = -d/a; } } else { t_c = tn/td; s_c = sn/sd; } // compute difference vector and distance squared Vector3 wc = w0 + s_c*segment.mDirection - t_c*ray.GetDirection(); return wc.Dot(wc); } // End of ::DistanceSquared() //---------------------------------------------------------------------------- // @ ::DistanceSquared() // --------------------------------------------------------------------------- // Returns the distance squared between line segment and line. // Based on article and code by Dan Sunday at www.geometryalgorithms.com //----------------------------------------------------------------------------- float DistanceSquared( const LineSegment3& segment, const Line3& line, float& s_c, float& t_c ) { // compute intermediate parameters Vector3 w0 = segment.mOrigin - line.GetOrigin(); float a = segment.mDirection.Dot( segment.mDirection ); float b = segment.mDirection.Dot( line.GetDirection() ); float c = line.GetDirection().Dot( line.GetDirection() ); float d = segment.mDirection.Dot( w0 ); float e = line.GetDirection().Dot( w0 ); float denom = a*c - b*b; // if denom is zero, try finding closest point on segment1 to origin0 if ( gfx::IsZero(denom) ) { s_c = 0.0f; t_c = e/c; // compute difference vector and distance squared Vector3 wc = w0 - t_c*line.GetDirection(); return wc.Dot(wc); } else { // parameters to compute s_c, t_c float sn; // clamp s_c within [0,1] sn = b*e - c*d; // clamp s_c to 0 if (sn < 0.0f) { s_c = 0.0f; t_c = e/c; } // clamp s_c to 1 else if (sn > denom) { s_c = 1.0f; t_c = (e+b)/c; } else { s_c = sn/denom; t_c = (a*e - b*d)/denom; } // compute difference vector and distance squared Vector3 wc = w0 + s_c*segment.mDirection - t_c*line.GetDirection(); return wc.Dot(wc); } } // End of ::DistanceSquared() //---------------------------------------------------------------------------- // @ LineSegment3::DistanceSquared() // --------------------------------------------------------------------------- // Returns the distance squared between line segment and point. //----------------------------------------------------------------------------- float DistanceSquared( const LineSegment3& segment, const Vector3& point, float& t_c ) { Vector3 w = point - segment.mOrigin; float proj = w.Dot(segment.mDirection); // endpoint 0 is closest point if ( proj <= 0 ) { t_c = 0.0f; return w.Dot(w); } else { float vsq = segment.mDirection.Dot(segment.mDirection); // endpoint 1 is closest point if ( proj >= vsq ) { t_c = 1.0f; return w.Dot(w) - 2.0f*proj + vsq; } // otherwise somewhere else in segment else { t_c = proj/vsq; return w.Dot(w) - t_c*proj; } } } // End of ::DistanceSquared() //---------------------------------------------------------------------------- // @ ClosestPoints() // --------------------------------------------------------------------------- // Returns the closest points between two line segments. //----------------------------------------------------------------------------- void ClosestPoints( Vector3& point0, Vector3& point1, const LineSegment3& segment0, const LineSegment3& segment1 ) { // compute intermediate parameters Vector3 w0 = segment0.mOrigin - segment1.mOrigin; float a = segment0.mDirection.Dot( segment0.mDirection ); float b = segment0.mDirection.Dot( segment1.mDirection ); float c = segment1.mDirection.Dot( segment1.mDirection ); float d = segment0.mDirection.Dot( w0 ); float e = segment1.mDirection.Dot( w0 ); float denom = a*c - b*b; // parameters to compute s_c, t_c float s_c, t_c; float sn, sd, tn, td; // if denom is zero, try finding closest point on segment1 to origin0 if ( gfx::IsZero(denom) ) { // clamp s_c to 0 sd = td = c; sn = 0.0f; tn = e; } else { // clamp s_c within [0,1] sd = td = denom; sn = b*e - c*d; tn = a*e - b*d; // clamp s_c to 0 if (sn < 0.0f) { sn = 0.0f; tn = e; td = c; } // clamp s_c to 1 else if (sn > sd) { sn = sd; tn = e + b; td = c; } } // clamp t_c within [0,1] // clamp t_c to 0 if (tn < 0.0f) { t_c = 0.0f; // clamp s_c to 0 if ( -d < 0.0f ) { s_c = 0.0f; } // clamp s_c to 1 else if ( -d > a ) { s_c = 1.0f; } else { s_c = -d/a; } } // clamp t_c to 1 else if (tn > td) { t_c = 1.0f; // clamp s_c to 0 if ( (-d+b) < 0.0f ) { s_c = 0.0f; } // clamp s_c to 1 else if ( (-d+b) > a ) { s_c = 1.0f; } else { s_c = (-d+b)/a; } } else { t_c = tn/td; s_c = sn/sd; } // compute closest points point0 = segment0.mOrigin + s_c*segment0.mDirection; point1 = segment1.mOrigin + t_c*segment1.mDirection; } // End of ClosestPoints() //---------------------------------------------------------------------------- // @ ClosestPoints() // --------------------------------------------------------------------------- // Returns the closest points between line segment and ray. //----------------------------------------------------------------------------- void ClosestPoints( Vector3& point0, Vector3& point1, const LineSegment3& segment, const Ray3& ray ) { // compute intermediate parameters Vector3 w0 = segment.mOrigin - ray.GetOrigin(); float a = segment.mDirection.Dot( segment.mDirection ); float b = segment.mDirection.Dot( ray.GetDirection() ); float c = ray.GetDirection().Dot( ray.GetDirection() ); float d = segment.mDirection.Dot( w0 ); float e = ray.GetDirection().Dot( w0 ); float denom = a*c - b*b; // parameters to compute s_c, t_c float s_c, t_c; float sn, sd, tn, td; // if denom is zero, try finding closest point on segment1 to origin0 if ( gfx::IsZero(denom) ) { // clamp s_c to 0 sd = td = c; sn = 0.0f; tn = e; } else { // clamp s_c within [0,1] sd = td = denom; sn = b*e - c*d; tn = a*e - b*d; // clamp s_c to 0 if (sn < 0.0f) { sn = 0.0f; tn = e; td = c; } // clamp s_c to 1 else if (sn > sd) { sn = sd; tn = e + b; td = c; } } // clamp t_c within [0,+inf] // clamp t_c to 0 if (tn < 0.0f) { t_c = 0.0f; // clamp s_c to 0 if ( -d < 0.0f ) { s_c = 0.0f; } // clamp s_c to 1 else if ( -d > a ) { s_c = 1.0f; } else { s_c = -d/a; } } else { t_c = tn/td; s_c = sn/sd; } // compute closest points point0 = segment.mOrigin + s_c*segment.mDirection; point1 = ray.GetOrigin() + t_c*ray.GetDirection(); } // End of ClosestPoints() //---------------------------------------------------------------------------- // @ LineSegment3::ClosestPoints() // --------------------------------------------------------------------------- // Returns the closest points between line segment and line. //----------------------------------------------------------------------------- void ClosestPoints( Vector3& point0, Vector3& point1, const LineSegment3& segment, const Line3& line ) { // compute intermediate parameters Vector3 w0 = segment.mOrigin - line.GetOrigin(); float a = segment.mDirection.Dot( segment.mDirection ); float b = segment.mDirection.Dot( line.GetDirection() ); float c = line.GetDirection().Dot( line.GetDirection() ); float d = segment.mDirection.Dot( w0 ); float e = line.GetDirection().Dot( w0 ); float denom = a*c - b*b; // if denom is zero, try finding closest point on line to segment origin if ( gfx::IsZero(denom) ) { // compute closest points point0 = segment.mOrigin; point1 = line.GetOrigin() + (e/c)*line.GetDirection(); } else { // parameters to compute s_c, t_c float s_c, t_c; float sn; // clamp s_c within [0,1] sn = b*e - c*d; // clamp s_c to 0 if (sn < 0.0f) { s_c = 0.0f; t_c = e/c; } // clamp s_c to 1 else if (sn > denom) { s_c = 1.0f; t_c = (e+b)/c; } else { s_c = sn/denom; t_c = (a*e - b*d)/denom; } // compute closest points point0 = segment.mOrigin + s_c*segment.mDirection; point1 = line.GetOrigin() + t_c*line.GetDirection(); } } // End of ClosestPoints() //---------------------------------------------------------------------------- // @ LineSegment3::ClosestPoint() // --------------------------------------------------------------------------- // Returns the closest point on line segment to point //----------------------------------------------------------------------------- Vector3 LineSegment3::ClosestPoint( const Vector3& point ) const { Vector3 w = point - mOrigin; float proj = w.Dot(mDirection); // endpoint 0 is closest point if ( proj <= 0.0f ) return mOrigin; else { float vsq = mDirection.Dot(mDirection); // endpoint 1 is closest point if ( proj >= vsq ) return mOrigin + mDirection; // else somewhere else in segment else return mOrigin + (proj/vsq)*mDirection; } } } // namespace gfx
[ "keedongpark@keedongpark" ]
[ [ [ 1, 801 ] ] ]
5a52457b518d950493a2ac55624d4332f722c2f2
1e299bdc79bdc75fc5039f4c7498d58f246ed197
/stdobj/SettingsFile.cpp
8eca885f0097b8315bd6cad51b7fecec52d1825b
[]
no_license
moosethemooche/Certificate-Server
5b066b5756fc44151b53841482b7fa603c26bf3e
887578cc2126bae04c09b2a9499b88cb8c7419d4
refs/heads/master
2021-01-17T06:24:52.178106
2011-07-13T13:27:09
2011-07-13T13:27:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,274
cpp
//-------------------------------------------------------------------------------- // // Copyright (c) 1999 MarkCare Solutions // // Programming by Rich Schonthal // //-------------------------------------------------------------------------------- // SettingsFile.cpp: implementation of the CSettingsFile class. // ////////////////////////////////////////////////////////////////////// //-------------------------------------------------------------------------------- #include "stdafx.h" #include "DelimFile.h" #include "SettingsFile.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// //-------------------------------------------------------------------------------- CSettingsFile::CSettingsFile(char cDelim, char cComment, bool bStrip) : CDelimFile(cDelim, cComment, bStrip) , m_nCurLine(-1) { } //-------------------------------------------------------------------------------- CSettingsFile::~CSettingsFile() { } //-------------------------------------------------------------------------------- bool CSettingsFile::Find(LPCTSTR pKey, CSettingsInfo& info) { CStringArray sTemp; CString sKey(pKey); sKey.MakeLower(); for(int i = 0; GetLine(i, sTemp); i++) { sTemp[0].MakeLower(); if(sTemp[0] == sKey) { info = sTemp; return true; } } return false; } //-------------------------------------------------------------------------------- bool CSettingsFile::GetLine(int nIndex, CStringArray& sInfo) { sInfo.RemoveAll(); if(m_nCurLine == -1 || nIndex < m_nCurLine) { SeekToBegin(); m_nCurLine = 0; } while(ReadLine(sInfo)) { if(sInfo.GetSize() < GetMinSize()) { sInfo.RemoveAll(); continue; } if(m_nCurLine == nIndex) { m_nCurLine++; return true; } sInfo.RemoveAll(); m_nCurLine++; } return false; } //-------------------------------------------------------------------------------- bool CSettingsFile::GetLine(int nIndex, CSettingsInfo& info) { CStringArray sTemp; if(GetLine(nIndex, sTemp)) { info = sTemp; return true; } return false; }
[ [ [ 1, 97 ] ] ]
2b183d1ed65548aaf92d1422bd7cd370923cc716
a6c9a8f361863ad66a54d15e0da04f356f4f76e9
/test/filer/mfttest/wv/MFTReader/MFTReader.cpp
ae9dab3d197c138d1f13f9e428707967a7ad1b1c
[]
no_license
mohammadul/addondev
2e47505112cf4c506e4523572d2dbcfabfd23496
ee18da2abaafebca565792c29d698cc87bb233ca
refs/heads/master
2016-09-06T08:54:57.642723
2011-10-04T16:42:38
2011-10-04T16:42:38
42,942,733
0
1
null
null
null
null
SHIFT_JIS
C++
false
false
23,650
cpp
// MFTReader.cpp : DLL アプリケーションのエントリ ポイントを定義します。 // #include "stdafx.h" #include <windows.h> #include <winioctl.h> #include <stdio.h> #include <stdlib.h> #include <string> // Template for padding template <class T1, class T2> inline T1* Padd(T1* p, T2 n) { return (T1*)((char *)p + n); } #ifdef __cplusplus extern "C" { #endif #ifdef _MANAGED #pragma managed(push, off) #endif ULONG BytesPerFileRecord; HANDLE hVolume; BOOT_BLOCK bootb; PFILE_RECORD_HEADER MFT; ULONG RunLength(PUCHAR run) { //wprintf(L"In RunLength()...\n"); return (*run & 0xf) + ((*run >> 4) & 0xf) + 1; } LONGLONG RunLCN(PUCHAR run) { LONG i = 0; UCHAR n1 = 0 , n2 = 0; LONGLONG lcn = 0; //wprintf(L"In RunLCN()...\n"); n1 = *run & 0xf; n2 = (*run >> 4) & 0xf; lcn = n2 == 0 ? 0 : CHAR(run[n1 + n2]); for (i = n1 + n2 - 1; i > n1; i--) lcn = (lcn << 8) + run[i]; return lcn; } ULONGLONG RunCount(PUCHAR run) { UCHAR n = *run & 0xf; ULONGLONG count = 0; ULONG i; //wprintf(L"In RunCount()...\n"); for (i = n; i > 0; i--) count = (count << 8) + run[i]; return count; } BOOL FindRun(PNONRESIDENT_ATTRIBUTE attr, ULONGLONG vcn, PULONGLONG lcn, PULONGLONG count) { PUCHAR run = NULL; *lcn = 0; ULONGLONG base = attr->LowVcn; //wprintf(L"In FindRun()...\n"); if (vcn < attr->LowVcn || vcn > attr->HighVcn) return FALSE; for(run = PUCHAR(Padd(attr, attr->RunArrayOffset)); *run != 0; run += RunLength(run)) { *lcn += RunLCN(run); *count = RunCount(run); if (base <= vcn && vcn < base + *count) { *lcn = RunLCN(run) == 0 ? 0 : *lcn + vcn - base; *count -= ULONG(vcn - base); return TRUE; } else base += *count; } return FALSE; } PATTRIBUTE FindAttribute(PFILE_RECORD_HEADER file,ATTRIBUTE_TYPE type, PWSTR name) { PATTRIBUTE attr = NULL; //wprintf(L"FindAttribute() - Finding attributes...\n"); for (attr = PATTRIBUTE(Padd(file, file->AttributesOffset)); attr->AttributeType != -1;attr = Padd(attr, attr->Length)) { if (attr->AttributeType == type) { if (name == 0 && attr->NameLength == 0) return attr; if (name != 0 && wcslen(name) == attr->NameLength && _wcsicmp(name, PWSTR(Padd(attr, attr->NameOffset))) == 0) return attr; } } return 0; } VOID FixupUpdateSequenceArray(PFILE_RECORD_HEADER file) { ULONG i = 0; PUSHORT usa = PUSHORT(Padd(file, file->Ntfs.UsaOffset)); PUSHORT sector = PUSHORT(file); //wprintf(L"In FixupUpdateSequenceArray()...\n"); for (i = 1; i < file->Ntfs.UsaCount; i++) { sector[255] = usa[i]; sector += 256; } } VOID ReadSector(ULONGLONG sector, ULONG count, PVOID buffer) { ULARGE_INTEGER offset; OVERLAPPED overlap = {0}; ULONG n; //wprintf(L"ReadSector() - Reading the sector...\n"); //wprintf(L"Sector: %lu\n", sector); offset.QuadPart = sector * bootb.BytesPerSector; overlap.Offset = offset.LowPart; overlap.OffsetHigh = offset.HighPart; //overlap.Pointer = NULL; ReadFile(hVolume, buffer, count * bootb.BytesPerSector, &n, &overlap); int m=0; } VOID ReadLCN(ULONGLONG lcn, ULONG count, PVOID buffer) { //wprintf(L"\nReadLCN() - Reading the LCN, LCN: 0X%.8X\n", lcn); ReadSector(lcn * bootb.SectorsPerCluster,count * bootb.SectorsPerCluster, buffer); } VOID ReadExternalAttribute(PNONRESIDENT_ATTRIBUTE attr,ULONGLONG vcn, ULONG count, PVOID buffer) { ULONGLONG lcn, runcount; ULONG readcount, left; PUCHAR bytes = PUCHAR(buffer); //wprintf(L"ReadExternalAttribute() - Reading the Non resident attributes...\n"); for(left = count; left > 0; left -= readcount) { FindRun(attr, vcn, &lcn, &runcount); readcount = ULONG(min(runcount, left)); ULONG n = readcount * bootb.BytesPerSector * bootb.SectorsPerCluster; if(lcn == 0) memset(bytes, 0, n); else { ReadLCN(lcn, readcount, bytes); //wprintf(L"LCN: 0X%.8X\n", lcn); } vcn += readcount; bytes += n; } } VOID LoadMFT() { //wprintf(L"In LoadMFT() - Loading MFT...\n"); BytesPerFileRecord = bootb.ClustersPerFileRecord < 0x80 ? bootb.ClustersPerFileRecord* bootb.SectorsPerCluster * bootb.BytesPerSector: 1 << (0x100 - bootb.ClustersPerFileRecord); //wprintf(L"\nBytes Per File Record = %u\n\n", BytesPerFileRecord); //wprintf(L"======THESE INFO ARE NOT ACCURATE FOR DISPLAY LOL!=====\n"); //wprintf(L"bootb.BootSectors = %u\n", bootb.BootSectors); //wprintf(L"bootb.BootSignature = %u\n", bootb.BootSignature); //wprintf(L"bootb.BytesPerSector = %u\n", bootb.BytesPerSector); //wprintf(L"bootb.ClustersPerFileRecord = %u\n", bootb.ClustersPerFileRecord); //wprintf(L"bootb.ClustersPerIndexBlock = %u\n", bootb.ClustersPerIndexBlock); //wprintf(L"bootb.Code = %u\n", bootb.Code); //wprintf(L"bootb.Format = %u\n", bootb.Format); //wprintf(L"bootb.Jump = %u\n", bootb.Jump); //wprintf(L"bootb.Mbz1 = %u\n", bootb.Mbz1); //wprintf(L"bootb.Mbz2 = %u\n", bootb.Mbz2); //wprintf(L"bootb.Mbz3 = %u\n", bootb.Mbz3); //wprintf(L"bootb.MediaType = 0X%X\n", bootb.MediaType); //wprintf(L"bootb.Mft2StartLcn = 0X%.8X\n", bootb.Mft2StartLcn); //wprintf(L"bootb.MftStartLcn = 0X%.8X\n", bootb.MftStartLcn); //wprintf(L"bootb.NumberOfHeads = %u\n", bootb.NumberOfHeads); //wprintf(L"bootb.PartitionOffset = %lu\n", bootb.PartitionOffset); //wprintf(L"bootb.SectorsPerCluster = %u\n", bootb.SectorsPerCluster); //wprintf(L"bootb.SectorsPerTrack = %u\n", bootb.SectorsPerTrack); //wprintf(L"bootb.TotalSectors = %lu\n", bootb.TotalSectors); // wprintf(L"bootb.VolumeSerialNumber = 0X%.8X%.8X\n\n", bootb.VolumeSerialNumber.HighPart, bootb.VolumeSerialNumber.HighPart); MFT = PFILE_RECORD_HEADER(new UCHAR[BytesPerFileRecord]); ReadSector((bootb.MftStartLcn)*(bootb.SectorsPerCluster), (BytesPerFileRecord)/(bootb.BytesPerSector), MFT); FixupUpdateSequenceArray(MFT); } VOID ReadVCN(PFILE_RECORD_HEADER file, ATTRIBUTE_TYPE type,ULONGLONG vcn, ULONG count, PVOID buffer) { PATTRIBUTE attrlist = NULL; PNONRESIDENT_ATTRIBUTE attr = PNONRESIDENT_ATTRIBUTE(FindAttribute(file, type, 0)); //wprintf(L"In ReadVCN()...\n"); if (attr == 0 || (vcn < attr->LowVcn || vcn > attr->HighVcn)) { // Support for huge files attrlist = FindAttribute(file, AttributeAttributeList, 0); DebugBreak(); } ReadExternalAttribute(attr, vcn, count, buffer); } VOID ReadFileRecord(ULONG index, PFILE_RECORD_HEADER file) { ULONG clusters = bootb.ClustersPerFileRecord; //wprintf(L"ReadFileRecord() - Reading the file records..\n"); if (clusters > 0x80) clusters = 1; PUCHAR p = new UCHAR[bootb.BytesPerSector* bootb.SectorsPerCluster * clusters]; ULONGLONG vcn = ULONGLONG(index) * BytesPerFileRecord/bootb.BytesPerSector/bootb.SectorsPerCluster; ReadVCN(MFT, AttributeData, vcn, clusters, p); LONG m = (bootb.SectorsPerCluster * bootb.BytesPerSector/BytesPerFileRecord) - 1; ULONG n = m > 0 ? (index & m) : 0; memcpy(file, p + n * BytesPerFileRecord, BytesPerFileRecord); delete [] p; FixupUpdateSequenceArray(file); } /////////////////////////////////////////// void ErrorMessage(DWORD dwCode) { // get the error code... DWORD dwErrCode = dwCode; DWORD dwNumChar; LPWSTR szErrString = NULL; // will be allocated and filled by FormatMessage dwNumChar = FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, // use windows internal message table 0, // 0 since source is internal message table dwErrCode, // this is the error code number 0, // auto-determine language to use (LPWSTR)&szErrString, // the messsage 0, // min size for buffer 0 ); // since getting message from system tables if(dwNumChar == 0) wprintf(L"FormatMessage() failed, error %u\n", GetLastError()); //else // wprintf(L"FormatMessage() should be fine!\n"); wprintf(L"Error code %u:\n %s\n", dwErrCode, szErrString) ; // This buffer used by FormatMessage() if(LocalFree(szErrString) != NULL) wprintf(L"Failed to free up the buffer, error %u\n", GetLastError()); //else // wprintf(L"Buffer has been freed\n"); } typedef struct { ULONGLONG DirectoryFileReferenceNumber; bool IsDirectory; ULONGLONG Size; ULONGLONG CreationTime; ULONGLONG LastWriteTime; LPWSTR Name; } MFT_FILE_INFO, *PMFT_FILE_INFO; BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { return TRUE; } typedef bool (__stdcall *CallBackProc)( int per ); void __stdcall freeBuffer(void* p) { free(p); } /* Return 0:OK 1:ERROR 2:Abort */ int __stdcall GetMFTFileRecord(LPWSTR lpDrive, MFT_FILE_INFO*& pfile_info, LONGLONG* size, CallBackProc proc, DWORD* errCode) { WCHAR drive[] = L"\\\\.\\C:"; ULONG n; hVolume = CreateFile( drive, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0); if(hVolume == INVALID_HANDLE_VALUE) { wprintf(L"CreateFile() failed, error %u\n", GetLastError()); exit(1); } bool abort = 0; int per = 0; LONGLONG total_file_count; NTFS_VOLUME_DATA_BUFFER ntfsVolData = {0}; DWORD dwWritten = 0; LARGE_INTEGER num; BOOL bDioControl = FALSE; bDioControl = DeviceIoControl(hVolume, FSCTL_GET_NTFS_VOLUME_DATA, NULL, 0, &ntfsVolData, sizeof(NTFS_VOLUME_DATA_BUFFER), &dwWritten, NULL); num.QuadPart = 1024; // 1024 or 2048 // We divide the MftValidDataLength (Master file table length) by 1024 to find // the total entry count for the MFT total_file_count = (ntfsVolData.MftValidDataLength.QuadPart/num.QuadPart); pfile_info = (MFT_FILE_INFO*)malloc(sizeof(MFT_FILE_INFO)*total_file_count); if(pfile_info == NULL){ //wprintf(L"malloc() failed - insufficient memory!\n"); //ErrorMessage(GetLastError()); *errCode = GetLastError(); return 1; } memset(pfile_info, 0, sizeof(MFT_FILE_INFO)*total_file_count); if(ReadFile(hVolume, &bootb, sizeof bootb, &n, 0) == 0) { wprintf(L"ReadFile() failed, error %u\n", GetLastError()); exit(1); } LoadMFT(); PFILE_RECORD_HEADER file = PFILE_RECORD_HEADER(new UCHAR[BytesPerFileRecord]); for(ULONG index=0; index<total_file_count; index++){ //ULONG index=0; //wprintf(L"ReadFileRecord() index %u\n", index); ReadFileRecord(index, file); LONGLONG i=0; PFILENAME_ATTRIBUTE fn; PSTANDARD_INFORMATION si; PATTRIBUTE attr = (PATTRIBUTE)((LPBYTE)file + file->AttributesOffset); if(file->Ntfs.Type =='ELIF'){ while(true){ if (attr->AttributeType<0 || attr->AttributeType>0x100) break; switch(attr->AttributeType) { case AttributeFileName: fn = PFILENAME_ATTRIBUTE(PUCHAR(attr) + PRESIDENT_ATTRIBUTE(attr)->ValueOffset); if (fn->NameType & 1 || fn->NameType == 0) { //if(file->Flags & 0x1){ // wprintf(L"FileName InUse\n") ; //}else{ // wprintf(L"FileName NOt In Use\n") ; //} //if(file->Flags & 0x2){ // wprintf(L"FileName Directory\n") ; //}else{ // wprintf(L"FileName File\n") ; //} //wprintf(L"FileName i : %u\n", i ); //wprintf(L"FileName DirectoryFileReferenceNumber : %u\n", fn->DirectoryFileReferenceNumber ); //wprintf(L"FileName DataSize : %u\n", fn->DataSize ); fn->Name[fn->NameLength] = L'\0'; //wprintf(L"FileName Name :%s\n", fn->Name) ; pfile_info[index].Name = new WCHAR[lstrlenW(fn->Name)+1]; lstrcpyW(pfile_info[index].Name , fn->Name); } break; case AttributeStandardInformation: si = PSTANDARD_INFORMATION(PUCHAR(attr) + PRESIDENT_ATTRIBUTE(attr)->ValueOffset); //wprintf(L"#####StandardInformation CreationTime : %u\n", si->CreationTime ); pfile_info[index].CreationTime = si->CreationTime; pfile_info[index].LastWriteTime = si->LastWriteTime; break; case AttributeData: if (attr->NameLength==0) { if (attr->Nonresident == TRUE) { pfile_info[index].Size = PNONRESIDENT_ATTRIBUTE(attr)->DataSize; } else { pfile_info[index].Size = PRESIDENT_ATTRIBUTE(attr)->ValueLength; } } break; default: break; }; if (attr->Length>0 && attr->Length < file->BytesInUse) attr = PATTRIBUTE(PUCHAR(attr) + attr->Length); else if (attr->Nonresident == TRUE) attr = PATTRIBUTE(PUCHAR(attr) + sizeof(NONRESIDENT_ATTRIBUTE)); } } if(proc != NULL && (per < index*100/total_file_count)){ per = index*100/total_file_count; abort = proc(per); if(abort){ break; } } } *size=total_file_count; // HANDLE hVolume; // //LPWSTR lpDrive = L"\\\\.\\c:"; // //LPWSTR lpDrive = L"\\\\.\\"; // //lstrcatW(lpDrive, driveletter); // //lstrcatW(lpDrive, L":" ); // //wprintf(L"The lpDrive: %s\n",lpDrive); // //MessageBox(NULL, lpDrive, lpDrive, MB_OK); // // NTFS_VOLUME_DATA_BUFFER ntfsVolData = {0}; // BOOL bDioControl = FALSE; // DWORD dwWritten = 0; // LARGE_INTEGER num; // LONGLONG total_file_count, i; // NTFS_FILE_RECORD_INPUT_BUFFER mftRecordInput; // PNTFS_FILE_RECORD_OUTPUT_BUFFER output_buffer; // // hVolume = CreateFile(lpDrive, // GENERIC_READ, // FILE_SHARE_READ | FILE_SHARE_WRITE, // NULL, // OPEN_EXISTING, // 0, // NULL); // // if(hVolume == INVALID_HANDLE_VALUE) // { // //wprintf(L"CreateFile() failed!\n"); // //ErrorMessage(GetLastError()); // *errCode = GetLastError(); // if(CloseHandle(hVolume) != 0){ // //wprintf(L"hVolume handle was closed successfully!\n"); // }else // { // //wprintf(L"Failed to close hVolume handle!\n"); // //ErrorMessage(GetLastError()); // *errCode = GetLastError(); // } // return 1; // } // //else // // wprintf(L"CreateFile() is pretty fine!\n"); // // // // // a call to FSCTL_GET_NTFS_VOLUME_DATA returns the structure NTFS_VOLUME_DATA_BUFFER // bDioControl = DeviceIoControl(hVolume, FSCTL_GET_NTFS_VOLUME_DATA, NULL, 0, &ntfsVolData, // sizeof(NTFS_VOLUME_DATA_BUFFER), &dwWritten, NULL); // // if(bDioControl == 0) // { // //wprintf(L"DeviceIoControl() failed!\n"); // //ErrorMessage(GetLastError()); // *errCode = GetLastError(); // if(CloseHandle(hVolume) != 0){ // //wprintf(L"hVolume handle was closed successfully!\n"); // }else // { // //wprintf(L"Failed to close hVolume handle!\n"); // //ErrorMessage(GetLastError()); // *errCode = GetLastError(); // } // return 1; // } // //else // // wprintf(L"DeviceIoControl(...,FSCTL_GET_NTFS_VOLUME_DATA,...) is working...\n\n"); // // //wprintf(L"Volume Serial Number: 0X%.8X%.8X\n",ntfsVolData.VolumeSerialNumber.HighPart,ntfsVolData.VolumeSerialNumber.LowPart); // //wprintf(L"The number of bytes in a cluster: %u\n",ntfsVolData.BytesPerCluster); // //wprintf(L"The number of bytes in a file record segment: %u\n",ntfsVolData.BytesPerFileRecordSegment); // //wprintf(L"The number of bytes in a sector: %u\n",ntfsVolData.BytesPerSector); // //wprintf(L"The number of clusters in a file record segment: %u\n",ntfsVolData.ClustersPerFileRecordSegment); // //wprintf(L"The number of free clusters in the specified volume: %u\n",ntfsVolData.FreeClusters); // //wprintf(L"The starting logical cluster number of the master file table mirror: 0X%.8X%.8X\n",ntfsVolData.Mft2StartLcn.HighPart, ntfsVolData.Mft2StartLcn.LowPart); // //wprintf(L"The starting logical cluster number of the master file table: 0X%.8X%.8X\n",ntfsVolData.MftStartLcn.HighPart, ntfsVolData.MftStartLcn.LowPart); // //wprintf(L"The length of the master file table, in bytes: %u\n",ntfsVolData.MftValidDataLength); // //wprintf(L"The ending logical cluster number of the master file table zone: 0X%.8X%.8X\n",ntfsVolData.MftZoneEnd.HighPart, ntfsVolData.MftZoneEnd.LowPart); // //wprintf(L"The starting logical cluster number of the master file table zone: 0X%.8X%.8X\n",ntfsVolData.MftZoneStart.HighPart, ntfsVolData.MftZoneStart.LowPart); // //wprintf(L"The number of sectors: %u\n",ntfsVolData.NumberSectors); // //wprintf(L"Total Clusters (used and free): %u\n",ntfsVolData.TotalClusters); // //wprintf(L"The number of reserved clusters: %u\n\n",ntfsVolData.TotalReserved); // // num.QuadPart = 1024; // 1024 or 2048 // // // We divide the MftValidDataLength (Master file table length) by 1024 to find // // the total entry count for the MFT // total_file_count = (ntfsVolData.MftValidDataLength.QuadPart/num.QuadPart); // // //total_file_count /= 1000; //test // // pfile_info = (MFT_FILE_INFO*)malloc(sizeof(MFT_FILE_INFO)*total_file_count); // if(pfile_info == NULL){ // //wprintf(L"malloc() failed - insufficient memory!\n"); // //ErrorMessage(GetLastError()); // *errCode = GetLastError(); // return 1; // } // memset(pfile_info, 0, sizeof(MFT_FILE_INFO)*total_file_count); // // ///////////////// // ULONG n; // if(ReadFile(hVolume, &bootb, sizeof bootb, &n, 0) == 0){ // //wprintf(L"ReadFile() failed, error %u\n", GetLastError()); // //exit(1); // *errCode = GetLastError(); // return 1; // } // // LoadMFT(); // // return 0; // ///////////////// // // //wprintf(L"Total file count = %u\n", total_file_count); // bool abort = 0; // int per = 0; // for(i = 0; i < total_file_count;i++) // { // //mftRecordInput.FileReferenceNumber.QuadPart = i; // // //// prior to calling the DeviceIoControl() we need to load // //// an input record with which entry number we want // // //// setup outputbuffer - FSCTL_GET_NTFS_FILE_RECORD depends on this // //output_buffer = (PNTFS_FILE_RECORD_OUTPUT_BUFFER)malloc(sizeof(NTFS_FILE_RECORD_OUTPUT_BUFFER)+ntfsVolData.BytesPerFileRecordSegment-1); // // //if(output_buffer == NULL) // //{ // // //wprintf(L"malloc() failed - insufficient memory!\n"); // // //ErrorMessage(GetLastError()); // // *errCode = GetLastError(); // // return 1; // //} // // //bDioControl = DeviceIoControl(hVolume, // // FSCTL_GET_NTFS_FILE_RECORD, // // &mftRecordInput, // // sizeof(mftRecordInput), // // output_buffer, // // sizeof(NTFS_FILE_RECORD_OUTPUT_BUFFER) + (ntfsVolData.BytesPerFileRecordSegment)- 1, // // &dwWritten, // // NULL); // // //// More data will make DeviceIoControl() fails... // ///*if(bDioControl == 0) // //{ // // wprintf(L"DeviceIoControl(...,FSCTL_GET_NTFS_FILE_RECORD,...) failed!\n"); // // ErrorMessage(GetLastError()); // // exit(1); // //}*/ // // //// FSCTL_GET_NTFS_FILE_RECORD retrieves one MFT entry // //// FILE_RECORD_HEADER is the Base struct for the MFT entry // //// that we will work from // //PFILE_RECORD_HEADER p_file_record_header = (PFILE_RECORD_HEADER)output_buffer->FileRecordBuffer; // ////////////////// // PFILE_RECORD_HEADER p_file_record_header = PFILE_RECORD_HEADER(new UCHAR[BytesPerFileRecord]); // //ULONG index=0; // ReadFileRecord(i, p_file_record_header); // ////////////////////////////// //return 0; // PFILENAME_ATTRIBUTE fn; // PSTANDARD_INFORMATION si; // //POBJECTID_ATTRIBUTE objid; // // PATTRIBUTE attr = (PATTRIBUTE)((LPBYTE)p_file_record_header + p_file_record_header->AttributesOffset); // // int stop = min(8,p_file_record_header->NextAttributeNumber); // if(p_file_record_header->Ntfs.Type =='ELIF'){ // while(true){ // if (attr->AttributeType<0 || attr->AttributeType>0x100) break; // // switch(attr->AttributeType) // { // case AttributeFileName: // fn = PFILENAME_ATTRIBUTE(PUCHAR(attr) + PRESIDENT_ATTRIBUTE(attr)->ValueOffset); // if (fn->NameType || fn->NameType == 0) // { // fn->Name[fn->NameLength] = L'\0'; // // pfile_info[i].DirectoryFileReferenceNumber = fn->DirectoryFileReferenceNumber; // if(p_file_record_header->Flags & 0x2){ // pfile_info[i].IsDirectory = true; // }else{ // pfile_info[i].IsDirectory = false; // } // // pfile_info[i].Name = new WCHAR[lstrlenW(fn->Name)+1]; // lstrcpyW(pfile_info[i].Name , fn->Name); // //pfile_info[i].Name = fn->Name; // pfile_info[i].Size = fn->DataSize; // // // } // break; // case AttributeStandardInformation: // si = PSTANDARD_INFORMATION(PUCHAR(attr) + PRESIDENT_ATTRIBUTE(attr)->ValueOffset); // pfile_info[i].CreationTime = si->CreationTime; // pfile_info[i].LastWriteTime = si->LastWriteTime; // //pfile_info[i].LastAccessTime = si->LastAccessTime; // break; // //case AttributeObjectId: // // objid = POBJECTID_ATTRIBUTE(PUCHAR(attr) + PRESIDENT_ATTRIBUTE(attr)->ValueOffset); // // pfile_info[i].ObjectId = objid->ObjectId; // default: // break; // }; // // if (attr->Length>0 && attr->Length < p_file_record_header->BytesInUse) // attr = PATTRIBUTE(PUCHAR(attr) + attr->Length); // else // if (attr->Nonresident == TRUE) // attr = PATTRIBUTE(PUCHAR(attr) + sizeof(NONRESIDENT_ATTRIBUTE)); // } // } // //free(output_buffer); // // //if((CallBackProc!=NULL) && (per < i*100/total_file_count)){ // if(proc != NULL && (per < i*100/total_file_count)){ // per = i*100/total_file_count; // abort = proc(per); // if(abort){ // break; // } // } // } // // *size = i; // // Let verify // //wprintf(L"i\'s count = %u\n", i); // // //====================== // if(CloseHandle(hVolume) != 0){ // //wprintf(L"hVolume handle was closed successfully!\n"); // } // else // { // //wprintf(L"Failed to close hVolume handle!\n"); // //ErrorMessage(GetLastError()); // *errCode = GetLastError(); // //free(output_buffer); // return 1; // } // // De-allocate the memory by malloc() // //free(output_buffer); // // //_CrtDumpMemoryLeaks(); // //free(pfile_info); return abort?2:0; } #ifdef _MANAGED #pragma managed(pop) #endif #ifdef __cplusplus } // extern "C" #endif
[ "s@localhost" ]
[ [ [ 1, 714 ] ] ]
92a508a3bc99fbef65f96e0059429aafa70202e9
10904ee31435dcd301484b0e8337504ce87368e4
/Face/Face/Config.h
a69d7259e2df95890618207e1efd49b4d3d221e5
[]
no_license
foolin/fdetection
c8fea777321d7aa1d674d4402c43ba52d56cfa7c
b8827751db7deb2d5e10acc22e42d3494e4af30a
refs/heads/master
2021-01-16T20:36:01.491468
2010-05-24T04:22:21
2010-05-24T04:22:21
32,785,465
0
0
null
null
null
null
GB18030
C++
false
false
425
h
#pragma once #include "afxwin.h" class CConfig : public CDialog { public: CConfig(void); ~CConfig(void); public: CString m_strConfigPath; public: //设置变量 void SetConfig(CString keyName, CString keyValue); void SetConfig(CString appName, CString keyName, CString keyValue); //读取变量 CString GetConfig(CString keyName); CString GetConfig(CString appName, CString keyName); };
[ "[email protected]@946ed153-6c77-64d3-6a7d-126bc18e93db" ]
[ [ [ 1, 23 ] ] ]
f4fd7f1d257e58181069f4482b487e388c59552a
c95a83e1a741b8c0eb810dd018d91060e5872dd8
/Game/ClientShellDLL/ClientShellShared/LaserBeam.h
81311dbd98b486399108cfeedf05af46ebcd0b65
[]
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
862
h
// ----------------------------------------------------------------------- // // // MODULE : LaserBeam.h // // PURPOSE : LaserBeam class - Definition // // CREATED : 11/16/99 // // (c) 1999 Monolith Productions, Inc. All Rights Reserved // // ----------------------------------------------------------------------- // #ifndef __LASER_BEAM_H__ #define __LASER_BEAM_H__ #include "ltbasedefs.h" #include "PolyLineFX.h" class CLaserBeam { public : CLaserBeam(); ~CLaserBeam(); void Toggle() { (m_bOn ? TurnOff() : TurnOn());} void TurnOn(); void TurnOff(); void Update(LTVector &vBeamStartPos, const LTRotation* pRDirRot, LTBOOL b3rdPerson, LTBOOL bDetect=LTFALSE); private : LTBOOL m_bOn; CPolyLineFX m_LightBeam; void Init(); }; #endif // __LASER_BEAM_H__
[ [ [ 1, 40 ] ] ]
d1a5d8b55c0a46c96a46e46829149bc5b8d67eff
5df145c06c45a6181d7402279aabf7ce9376e75e
/src/bbsmenumgr.h
bbbe50d06607e5e564a4c056e3fd4cffcf91bf87
[]
no_license
plus7/openjohn
89318163f42347bbac24e8272081d794449ab861
1ffdcc1ea3f0af43b9033b68e8eca048a229305f
refs/heads/master
2021-03-12T22:55:57.315977
2009-05-15T11:30:00
2009-05-15T11:30:00
152,690
1
1
null
null
null
null
UTF-8
C++
false
false
2,068
h
/* * Copyright 2009 NOSE Takafumi <[email protected]> * * 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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA */ #ifndef BBSMENUMANAGER_H #define BBSMENUMANAGER_H #include <QObject> #include <QList> #include <QString> class BBSNode; class BBSMenuManager : public QObject { Q_OBJECT public: BBSMenuManager(QObject *parent = 0); BBSNode *root() const; bool loadFromFile(const QString& fileName); signals: void itemAdded(BBSNode *item); void itemRemoved(BBSNode *parent, int row, BBSNode *item); void itemChanged(BBSNode *item); private: BBSNode *m_root; }; class BBSNode { public: enum Type{ Root, Folder, Board, Thread, Separator }; BBSNode(BBSNode *parent, BBSNode::Type type); virtual ~BBSNode(); Type type() const; void setType(Type type) {m_type = type;} QList<BBSNode *> children() const{ return m_children; } BBSNode *parent() const{ return m_parent; } void addNode(BBSNode *child, int offset = -1); void removeNode(BBSNode *child); int row(); QString title; QString uri; QString misc; bool expanded; private: BBSNode *m_parent; Type m_type; QList<BBSNode *> m_children; }; class BBSThread : public BBSNode { public: BBSThread(BBSNode *parent); }; #endif // BBSMENUMANAGER_H
[ [ [ 1, 81 ] ] ]
ba773e8dd31f634d612a1c1da5fa2812c6d5d2d3
10904ee31435dcd301484b0e8337504ce87368e4
/Face/Face/Config.cpp
b5e8790dff56086584233a3c7126b184c6ce81c4
[]
no_license
foolin/fdetection
c8fea777321d7aa1d674d4402c43ba52d56cfa7c
b8827751db7deb2d5e10acc22e42d3494e4af30a
refs/heads/master
2021-01-16T20:36:01.491468
2010-05-24T04:22:21
2010-05-24T04:22:21
32,785,465
0
0
null
null
null
null
GB18030
C++
false
false
982
cpp
#include "StdAfx.h" #include "Config.h" CConfig::CConfig(void) { m_strConfigPath = _T(".\\config.ini"); } CConfig::~CConfig(void) { } //设置变量 void CConfig::SetConfig(CString keyName, CString keyValue) { ::WritePrivateProfileString(_T("Init"), keyName, keyValue, m_strConfigPath); } void CConfig::SetConfig(CString appName, CString keyName, CString keyValue) { ::WritePrivateProfileString( appName, keyName, keyValue, m_strConfigPath); } //读取变量 CString CConfig::GetConfig(CString keyName) { //读取配置文件 CString strValue; ::GetPrivateProfileString(_T("Init"), keyName, _T(""), strValue.GetBuffer(MAX_PATH), MAX_PATH , m_strConfigPath); return strValue; } CString CConfig::GetConfig(CString appName, CString keyName) { //读取配置文件 CString strValue; ::GetPrivateProfileString( appName, keyName, _T(""), strValue.GetBuffer(MAX_PATH), MAX_PATH , m_strConfigPath); return strValue; }
[ "[email protected]@946ed153-6c77-64d3-6a7d-126bc18e93db" ]
[ [ [ 1, 41 ] ] ]
0113b4333a2d693c5c037d2ef105b43ac14842a4
4aadb120c23f44519fbd5254e56fc91c0eb3772c
/Source/EduNetGames/obsolete/Tutorial_03/NetBoidReplica.cpp
94f916d6955d820d0e38d13e0b9f591d8dd6946a
[]
no_license
janfietz/edunetgames
d06cfb021d8f24cdcf3848a59cab694fbfd9c0ba
04d787b0afca7c99b0f4c0692002b4abb8eea410
refs/heads/master
2016-09-10T19:24:04.051842
2011-04-17T11:00:09
2011-04-17T11:00:09
33,568,741
0
0
null
null
null
null
UTF-8
C++
false
false
3,844
cpp
//----------------------------------------------------------------------------- // Copyright (c) 2009, Jan Fietz, Cyrus Preuss // 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 EduNetGames 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 "NetBoidReplica.h" #include "NetBoid.h" #include "NetBoidFactory.h" #include "OpenSteerUT/AbstractVehicleGroup.h" #include "EduNetConnect/NetworkEntity.h" NetBoidFactory gNetBoidFactory; //----------------------------------------------------------------------------- NetBoidReplica::NetBoidReplica(): m_pBoidPlugin(NULL) { } //----------------------------------------------------------------------------- NetBoidReplica::NetBoidReplica( OpenSteer::BoidsPlugin* pkHostPlugin, bool bIsRemoteObject ): m_pBoidPlugin(pkHostPlugin) { OpenSteer::AbstractVehicle* pkVehicle = gNetBoidFactory.createVehicle( ET_CID_NETBOID ); this->setEntity( pkVehicle ); this->accessEntity()->setIsRemoteObject( bIsRemoteObject ); } //----------------------------------------------------------------------------- RakNet::RakString NetBoidReplica::GetName(void) const { static OpenSteer::Boid kProtoType; return kProtoType.getClassName(); } //----------------------------------------------------------------------------- void NetBoidReplica::DeallocReplica(RakNet::Connection_RM3 *sourceConnection) { OpenSteer::AbstractVehicleGroup kVG( m_pBoidPlugin->allVehicles() ); kVG.removeVehicleFromPlugin( this->accessEntity() ); this->releaseEntity(); ET_DELETE this; } //----------------------------------------------------------------------------- RakNet::RM3SerializationResult NetBoidReplica::Serialize( RakNet::SerializeParameters *serializeParameters) { OpenSteer::NetworkEntitySerializer kSerializer( this->accessEntity() ); int nResult = kSerializer.serialize( serializeParameters ); if( nResult >= 0 ) { return static_cast<RakNet::RM3SerializationResult>(nResult); } return RakNet::RM3SR_DO_NOT_SERIALIZE; } //----------------------------------------------------------------------------- void NetBoidReplica::Deserialize( RakNet::DeserializeParameters *deserializeParameters) { OpenSteer::NetworkEntitySerializer kSerializer( this->accessEntity() ); kSerializer.deserialize( deserializeParameters ); }
[ "janfietz@localhost" ]
[ [ [ 1, 86 ] ] ]
61b017ec358c9ed144a5e759f98a795cff6b70d1
efc8e21a70b1b561152cf451cb01b2816d2bed49
/examples/3DCellSegmentation/LevelSetBasedCellSegmentation/ShapeLevelSetBasedCellSegmentation.cxx
4d76a60a888ff8ff3a675e30ab7c5db7719edd57
[]
no_license
xiaochengcike/midas-journal-321
250fa5a1267e48ae3651557c8cb9039db1b09c2e
104bc2cc86967b5af96449000336d58e809b95ea
refs/heads/master
2020-03-31T15:57:50.135005
2011-08-22T13:23:47
2011-08-22T13:23:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,282
cxx
#include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkShapeLevelSetBasedCellSegmentation.h" #include "itkNumericSeriesFileNames.h" #include "itkCastImageFilter.h" #include <map> #include <vector> #include <fstream> #include <stdio.h> int main( int argc, char* argv[] ) { if( argc < 7 ) { std::cerr << "Usage: " << std::endl; std::cerr << argv[0] << " featureImage seedfile cellSegmentImage "; std::cerr << "meanShape shapeFormat numberOfPCAModes" << std::endl; return EXIT_FAILURE; } const unsigned int Dimension = 3; typedef itk::Image< unsigned short, Dimension > CompImage; typedef itk::Image< float, Dimension > FeatureImage; typedef itk::ImageFileReader< FeatureImage > ReaderType; typedef itk::ImageFileWriter< CompImage > WriterType; typedef itk::ShapeLevelSetBasedCellSegmentation< FeatureImage,CompImage > FilterType; ReaderType::Pointer reader_feature = ReaderType::New(); reader_feature->SetFileName( argv[1] ); reader_feature->Update(); FeatureImage::Pointer featureImg = reader_feature->GetOutput(); typedef FeatureImage::IndexType ImageIndexType; ImageIndexType idx; float val; int numberOfPCAModes = atoi( argv[6] ); ReaderType::Pointer meanShapeReader = ReaderType::New(); meanShapeReader->SetFileName( argv[4] ); meanShapeReader->Update(); itk::NumericSeriesFileNames::Pointer fileNamesCreator = itk::NumericSeriesFileNames::New(); fileNamesCreator->SetStartIndex( 1 ); fileNamesCreator->SetEndIndex( numberOfPCAModes ); fileNamesCreator->SetSeriesFormat( argv[5] ); const std::vector<std::string> &shapeModeFileNames = fileNamesCreator->GetFileNames(); std::vector< FeatureImage::Pointer > shapeModeImages( numberOfPCAModes ); for( int k = 0; k < numberOfPCAModes; k++) { ReaderType::Pointer shapeModeReader = ReaderType::New(); shapeModeReader->SetFileName(shapeModeFileNames[k].c_str()); shapeModeReader->Update(); shapeModeImages[k] = shapeModeReader->GetOutput(); } FilterType::Pointer filter = FilterType::New(); filter->SetInput( featureImg ); filter->SetLargestCellRadius( 6.0 ); // in real coordinates filter->SetSeedValue( 1.5 ); filter->SetIterations( 1000 ); filter->SetPropagationScaling( 3 ); filter->SetCurvatureScaling( 1 ); filter->SetAdvectionScaling( 3 ); filter->SetMaxRMSChange( 0.01 ); filter->SetShapePriorScaling( 2.0 ); filter->SetNumberOfPCAModes( numberOfPCAModes ); filter->m_meanShape = meanShapeReader->GetOutput(); filter->m_shapeModeImages = shapeModeImages; std::fstream infile; infile.open(argv[2],std::ios::in); while( !infile.eof() ) { infile >> val; for( unsigned int i = 0; i < Dimension; i++) { infile >> idx[i]; } filter->seeds[val] = static_cast<ImageIndexType>( idx ); } infile.close(); filter->Update(); WriterType::Pointer writer = WriterType::New(); writer->SetInput( filter->GetOutput() ); writer->SetFileName( argv[3] ); try { writer->Update(); } catch ( itk::ExceptionObject e ) { std::cerr << "Error: " << e << std::endl; } return EXIT_SUCCESS; }
[ [ [ 1, 105 ] ] ]
07eadaa06c467a5cafa68c2093ca3c4e049bac38
9152cb31fbe4e82c22092bb3071b2ec8c6ae86ab
/demos/rtc/RTCSAMPLE/rtcwin.cpp
cf21b52e06654d2b5d5ff87b667d2a8bb2598c07
[]
no_license
zzjs2001702/sfsipua-svn
ca3051b53549066494f6264e8f3bf300b8090d17
e8768338340254aa287bf37cf620e2c68e4ff844
refs/heads/master
2022-01-09T20:02:20.777586
2006-03-29T13:24:02
2006-03-29T13:24:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
125,846
cpp
// rtcwin.h // #include "stdafx.h" #include <assert.h> #define MAX_COMPUTER_NAME_LENGTH 300 ///////////////////////////////////////////// // // CRTCWin::CRTCWin // CRTCWin::CRTCWin() { m_hWnd = NULL; m_hStatusBar = NULL; m_hBuddyTree = NULL; m_hOfflineParent = NULL; m_hOnlineParent = NULL; m_pClient = NULL; m_pProfile = NULL; m_pEvents = NULL; m_enState = RTCRS_NOT_REGISTERED; m_fPresenceEnabled = FALSE; m_lCookie = 0; m_nLogonAttemptCount = 0; ZeroMemory((void *)&m_OD, sizeof(OPTIONS_DATA)); } ///////////////////////////////////////////// // // CRTCWin::~CRTCWin // CRTCWin::~CRTCWin() { if(m_OD.bstrAppName) SysFreeString(m_OD.bstrAppName); if(m_OD.bstrAppVer) SysFreeString(m_OD.bstrAppVer); } ///////////////////////////////////////////// // // CRTCWin::RegisterClass // HRESULT CRTCWin::RegisterClass() { // Register the window class WNDCLASS wc; ATOM atom; ZeroMemory(&wc, sizeof(WNDCLASS)); wc.style = CS_HREDRAW | CS_VREDRAW; wc.lpfnWndProc = (WNDPROC)CRTCWin::WindowProc; wc.hInstance = GetModuleHandle(NULL); wc.hIcon = NULL; wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = GetSysColorBrush(COLOR_3DFACE); wc.lpszMenuName = MAKEINTRESOURCE(IDR_MENU_APP); wc.lpszClassName = APP_CLASS; atom = ::RegisterClass( &wc ); if ( !atom ) { // RegisterClass failed DEBUG_PRINT(("RegisterClass failed %x", HRESULT_FROM_WIN32(GetLastError()) )); return E_FAIL; } return S_OK; } ///////////////////////////////////////////// // // CRTCWin::AddSession // HRESULT CRTCWin::AddSession(IRTCSession * pSession, RTC_SESSION_TYPE enType) { // Is this an audio/video session? BOOL fAVSession = (enType == RTCST_PC_TO_PC || enType == RTCST_PC_TO_PHONE); // Create the session window HWND hWnd; HRESULT hr = S_OK; hWnd = CreateWindowExW( 0, (fAVSession) ? AV_CLASS : IM_CLASS, (fAVSession) ? AV_TITLE : IM_TITLE, WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS, CW_USEDEFAULT, CW_USEDEFAULT, (fAVSession) ? AV_WIDTH : IM_WIDTH, (fAVSession) ? AV_HEIGHT : IM_HEIGHT, NULL, NULL, GetModuleHandle(NULL), NULL); if ( !hWnd ) { // CreateWindowExW failed DEBUG_PRINT(("CreateWindowExW failed %x", HRESULT_FROM_WIN32(GetLastError()) )); return E_FAIL; } // Initialize the window CRTCSession * pSessWindow = (CRTCSession *)GetWindowLongPtr(hWnd, GWLP_USERDATA); pSessWindow->m_pSession = pSession; pSessWindow->m_pSession->AddRef(); pSessWindow->m_pWin = this; // Make the main window visible ShowWindow( hWnd, SW_SHOW ); UpdateWindow( hWnd ); // Add window to the list m_SessionList.push_back(pSessWindow); return hr; } ///////////////////////////////////////////// // // CRTCWin::RemoveSession // HRESULT CRTCWin::RemoveSession(CRTCSession * pSessWindow) { std::vector<CRTCSession *>::iterator it; if (!m_SessionList.empty()) { // Find the window for(it=m_SessionList.begin(); it < m_SessionList.end(); it++) { if (*it == pSessWindow) { // Remove the window m_SessionList.erase(it); break; } } } return S_OK; } ///////////////////////////////////////////// // // CRTCWin::FindSession // HRESULT CRTCWin::FindSession(IRTCSession * pSession, CRTCSession ** ppSessWindow) { std::vector<CRTCSession *>::iterator it; if (!m_SessionList.empty()) { for(it=m_SessionList.begin(); it < m_SessionList.end(); it++) { if ((*it)->m_pSession == pSession) { *ppSessWindow = (*it); return S_OK; } } } *ppSessWindow = NULL; return E_FAIL; } ///////////////////////////////////////////// // // CRTCWin::CleanupSessions // HRESULT CRTCWin::CleanupSessions() { std::vector<CRTCSession *>::iterator it; if (!m_SessionList.empty()) { for(it=m_SessionList.begin(); it < m_SessionList.end(); it++) { PostMessage((*it)->m_hWnd, WM_CLOSE, 0, 0); } } return S_OK; } ///////////////////////////////////////////// // // CRTCWin::AddUserSearch // HRESULT CRTCWin::AddUserSearch() { HRESULT hr; // Get the user search interface IRTCUserSearch * pUserSearch = NULL; hr = m_pClient->QueryInterface(__uuidof(IRTCUserSearch), (void **)&pUserSearch); if (FAILED(hr)) { // QueryInterface failed DEBUG_PRINT(("QueryInterface failed %x", hr )); return hr; } // Create the search window HWND hWnd; hWnd = CreateWindowExW( 0, US_CLASS, US_TITLE, WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS, CW_USEDEFAULT, CW_USEDEFAULT, US_WIDTH, US_HEIGHT, NULL, NULL, GetModuleHandle(NULL), NULL); if ( !hWnd ) { // CreateWindowExW failed DEBUG_PRINT(("CreateWindowExW failed %x", HRESULT_FROM_WIN32(GetLastError()) )); SAFE_RELEASE(pUserSearch); return E_FAIL; } // Initialize the window CRTCSearch * pSearchWindow = (CRTCSearch *)GetWindowLongPtr(hWnd, GWLP_USERDATA); pSearchWindow->m_pProfile = m_pProfile; pSearchWindow->m_pProfile->AddRef(); // Give the user search reference to the search window pSearchWindow->m_pUserSearch = pUserSearch; pSearchWindow->m_pWin = this; // Make the search window visible ShowWindow( hWnd, SW_SHOW ); UpdateWindow( hWnd ); // Add window to the list m_UserSearchList.push_back(pSearchWindow); return S_OK; } ///////////////////////////////////////////// // // CRTCWin::RemoveUserSearch // HRESULT CRTCWin::RemoveUserSearch(CRTCSearch * pSearchWindow) { std::vector<CRTCSearch *>::iterator it; if (!m_UserSearchList.empty()) { // Find the window for(it=m_UserSearchList.begin(); it < m_UserSearchList.end(); it++) { if (*it == pSearchWindow) { // Remove the window m_UserSearchList.erase(it); break; } } } return S_OK; } ///////////////////////////////////////////// // // CRTCWin::FindUserSearch // HRESULT CRTCWin::FindUserSearch(LONG_PTR lCookie, CRTCSearch ** ppSearchWindow) { std::vector<CRTCSearch *>::iterator it; if (!m_UserSearchList.empty()) { for(it=m_UserSearchList.begin(); it < m_UserSearchList.end(); it++) { if ((*it)->m_lCookie == lCookie) { *ppSearchWindow = (*it); return S_OK; } } } *ppSearchWindow = NULL; return E_FAIL; } ///////////////////////////////////////////// // // CRTCWin::CleanupUserSearches // HRESULT CRTCWin::CleanupUserSearches() { std::vector<CRTCSearch *>::iterator it; if (!m_UserSearchList.empty()) { for(it=m_UserSearchList.begin(); it < m_UserSearchList.end(); it++) { PostMessage((*it)->m_hWnd, WM_CLOSE, 0, 0); } } return S_OK; } ///////////////////////////////////////////// // // CRTCWin::AddWatchers // HRESULT CRTCWin::AddWatchers() { HRESULT hr = S_OK; // Create the watchers window HWND hWnd; hWnd = CreateWindowExW( 0, WAT_CLASS, WAT_TITLE, WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS, CW_USEDEFAULT, CW_USEDEFAULT, WAT_WIDTH, WAT_HEIGHT, NULL, NULL, GetModuleHandle(NULL), NULL); if ( !hWnd ) { // CreateWindowExW failed DEBUG_PRINT(("CreateWindowExW failed %x", HRESULT_FROM_WIN32(GetLastError()) )); return E_FAIL; } // Initialize the window CRTCWatcher * pWatcherWindow = (CRTCWatcher *)GetWindowLongPtr(hWnd, GWLP_USERDATA); pWatcherWindow->m_pClient = m_pClient; pWatcherWindow->m_pClient->AddRef(); pWatcherWindow->m_pWin = this; // Make the watcher window visible ShowWindow( hWnd, SW_SHOW ); UpdateWindow( hWnd ); // Add window to the list m_WatchersList.push_back(pWatcherWindow); return hr; } ///////////////////////////////////////////// // // CRTCWin::RemoveWatchers // HRESULT CRTCWin::RemoveWatchers(CRTCWatcher * pWatcherWindow) { std::vector<CRTCWatcher *>::iterator it; if (!m_WatchersList.empty()) { // Find the window for(it=m_WatchersList.begin(); it < m_WatchersList.end(); it++) { if (*it == pWatcherWindow) { // Remove the window m_WatchersList.erase(it); break; } } } return S_OK; } ///////////////////////////////////////////// // // CRTCWin::CleanupWatchers // HRESULT CRTCWin::CleanupWatchers() { std::vector<CRTCWatcher *>::iterator it; if (!m_WatchersList.empty()) { for(it=m_WatchersList.begin(); it < m_WatchersList.end(); it++) { PostMessage((*it)->m_hWnd, WM_CLOSE, 0, 0); } } return S_OK; } ///////////////////////////////////////////// // // CRTCWin::AddGroups // HRESULT CRTCWin::AddGroups() { HRESULT hr = S_OK; // Create the groups window HWND hWnd; hWnd = CreateWindowExW( 0, GRP_CLASS, GRP_TITLE, WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS, CW_USEDEFAULT, CW_USEDEFAULT, GRP_WIDTH, GRP_HEIGHT, NULL, NULL, GetModuleHandle(NULL), NULL); if ( !hWnd ) { // CreateWindowExW failed DEBUG_PRINT(("CreateWindowExW failed %x", HRESULT_FROM_WIN32(GetLastError()) )); return E_FAIL; } // Initialize the window CRTCGroup * pGroupWindow = (CRTCGroup *)GetWindowLongPtr(hWnd, GWLP_USERDATA); pGroupWindow->m_pClient = m_pClient; pGroupWindow->m_pClient->AddRef(); pGroupWindow->m_pWin = this; // Make the group window visible ShowWindow( hWnd, SW_SHOW ); UpdateWindow( hWnd ); // Add window to the list m_GroupsList.push_back(pGroupWindow); return hr; } ///////////////////////////////////////////// // // CRTCWin::RemoveGroups // HRESULT CRTCWin::RemoveGroups(CRTCGroup * pGroupWindow) { std::vector<CRTCGroup *>::iterator it; if (!m_GroupsList.empty()) { // Find the window for(it=m_GroupsList.begin(); it < m_GroupsList.end(); it++) { if (*it == pGroupWindow) { // Remove the window m_GroupsList.erase(it); break; } } } return S_OK; } ///////////////////////////////////////////// // // CRTCWin::CleanupGroups // HRESULT CRTCWin::CleanupGroups() { std::vector<CRTCGroup *>::iterator it; if (!m_GroupsList.empty()) { for(it=m_GroupsList.begin(); it < m_GroupsList.end(); it++) { PostMessage((*it)->m_hWnd, WM_CLOSE, 0, 0); } } return S_OK; } ///////////////////////////////////////////// // // CRTCWin::ShowMessageBox // void CRTCWin::ShowMessageBox(PWSTR szText) { MessageBoxW(m_hWnd, szText, APP_TITLE, MB_OK); } ///////////////////////////////////////////// // // CRTCWin::SetStatusText // void CRTCWin::SetStatusText(PWSTR szText) { SetWindowTextW(m_hStatusBar, szText); InvalidateRect(m_hStatusBar, NULL, FALSE); } ///////////////////////////////////////////// // // CRTCWin::GetUserURI // HRESULT CRTCWin::GetUserURI(BSTR *pbstrURI) { //////////// // // Begin RTC Functionality Code // // This code demonstrates how to query the profile or client for the local user URI // //////////// HRESULT hr; if (m_pProfile != NULL) { // Get the user URI from the profile hr = m_pProfile->get_UserURI(pbstrURI); if (FAILED(hr)) { // get_UserURI failed DEBUG_PRINT(("get_UserURI failed %x", hr )); return hr; } } else { // Get the user URI from the client hr = m_pClient->get_LocalUserURI(pbstrURI); if (FAILED(hr)) { // get_LocalUserURI failed DEBUG_PRINT(("get_LocalUserURI failed %x", hr )); return hr; } } //////////// // // End RTC Functionality Code // //////////// return S_OK; } ///////////////////////////////////////////// // // CRTCWin::GetUserName // HRESULT CRTCWin::GetUserName(BSTR *pbstrName) { //////////// // // Begin RTC Functionality Code // // This code demonstrates how to query the profile or client for the local user name // //////////// HRESULT hr; if (m_pProfile != NULL) { // Get the user name from the profile hr = m_pProfile->get_UserName(pbstrName); if (FAILED(hr)) { // get_UserName failed DEBUG_PRINT(("get_UserName failed %x", hr )); return hr; } } else { // Get the user name from the client hr = m_pClient->get_LocalUserName(pbstrName); if (FAILED(hr)) { // get_LocalUserName failed DEBUG_PRINT(("get_LocalUserName failed %x", hr )); return hr; } } //////////// // // End RTC Functionality Code // //////////// return S_OK; } ///////////////////////////////////////////// // // CRTCWin::FindBuddyNode // HRESULT CRTCWin::TreeViewHelper_FindBuddyNode(IRTCBuddy * pBuddy, LPTVITEMEX pTvix, int *piTree) { if (pTvix == NULL || piTree == NULL) return E_POINTER; // Make a local tvix so we don't worry about reference passing from a parameter. TVITEMEX tvix; ZeroMemory(&tvix, sizeof(TVITEMEX)); ZeroMemory(pTvix, sizeof(TVITEMEX)); // Start with searching the online tree HTREEITEM child; child = TreeView_GetNextItem( m_hBuddyTree, m_hOnlineParent, TVGN_CHILD ); tvix.hItem = child; tvix.mask = TVIF_PARAM; TreeView_GetItem(m_hBuddyTree, &tvix); while (child != NULL && tvix.lParam != (LPARAM) pBuddy) { child = TreeView_GetNextItem( m_hBuddyTree, child, TVGN_NEXT ); tvix.hItem = child; tvix.mask = TVIF_PARAM; TreeView_GetItem(m_hBuddyTree, &tvix); } if (tvix.lParam == (LPARAM) pBuddy) { pTvix->hItem = child; pTvix->lParam = tvix.lParam; if (piTree) { *piTree = 1; } return S_OK; } // Not found in online tree. Search the offline tree child = TreeView_GetNextItem( m_hBuddyTree, m_hOfflineParent, TVGN_CHILD ); tvix.hItem = child; TreeView_GetItem(m_hBuddyTree, &tvix); while (child != NULL && tvix.lParam != (LPARAM) pBuddy) { child = TreeView_GetNextItem( m_hBuddyTree, child, TVGN_NEXT ); tvix.hItem = child; tvix.mask = TVIF_PARAM; TreeView_GetItem(m_hBuddyTree, &tvix); } if (child != NULL && tvix.lParam == (LPARAM) pBuddy) { pTvix->hItem = child; pTvix->lParam = tvix.lParam; if (piTree) { *piTree = 0; } return S_OK; } return E_FAIL; } HRESULT CRTCWin::TreeViewHelper_InsertNode(IRTCBuddy * pBuddy, WCHAR * szBuddy, int enStatus) { assert (pBuddy != NULL); if (pBuddy == NULL) { return E_POINTER; } TV_ITEM tviNewItem; ZeroMemory(&tviNewItem, sizeof(TV_ITEM)); // Main item tviNewItem.mask = TVIF_PARAM | TVIF_TEXT; tviNewItem.pszText = szBuddy; tviNewItem.lParam = (LPARAM)pBuddy; // Group into online or offline group? TVINSERTSTRUCT tvis; ZeroMemory(&tvis, sizeof(TVINSERTSTRUCT)); if (enStatus == (int) RTCXS_PRESENCE_OFFLINE) { tvis.hParent = (HTREEITEM) m_hOfflineParent; } else { tvis.hParent = (HTREEITEM) m_hOnlineParent; } tvis.hInsertAfter = TVI_SORT; tvis.item = tviNewItem; HTREEITEM hti = TreeView_InsertItem(m_hBuddyTree, &tvis); if (hti == NULL) { // TreeView_InsertItem failed DEBUG_PRINT(("TreeView_InsertItem failed %x", HRESULT_FROM_WIN32(GetLastError()) )); return E_FAIL; } // An RTC buddy reference will be kept by the list // Add the reference here pBuddy->AddRef(); // Now Add all of the presence devices to the parent node if the buddy isn't offline if (enStatus == (int) RTCXS_PRESENCE_OFFLINE) { return S_OK; } //////////// // // Begin RTC Functionality Code // // This code demonstrates how to enumerate the presence devices on a buddy // //////////// IRTCEnumPresenceDevices* ppEnumDevices = NULL; IRTCBuddy2 *pBuddy2; pBuddy->QueryInterface(__uuidof(IRTCBuddy2), (LPVOID *)&pBuddy2); HRESULT hr = pBuddy2->EnumeratePresenceDevices(&ppEnumDevices); SAFE_RELEASE(pBuddy2); if (FAILED(hr)) { DEBUG_PRINT(("InsertNode: pBuddy2->EnumeratePresenceDevices Failed %x", hr )); return E_FAIL; } ULONG celtFetched = 0; IRTCPresenceDevice *pDevice = NULL; int count = 1; for (; (hr = ppEnumDevices->Next(1, &pDevice, &celtFetched)) == S_OK;) { if (pDevice) { WCHAR buffer[MAX_STRING]; RTC_PRESENCE_STATUS enDeviceStatus = RTCXS_PRESENCE_OFFLINE; BSTR deviceName; hr = pDevice->get_PresenceProperty(RTCPP_DEVICE_NAME, &deviceName); if (FAILED(hr)) { if (RTC_E_NOT_EXIST != hr) { DEBUG_PRINT(("get device name Failed %x", hr)); } WCHAR deviceNameBuffer[MAX_STRING]; swprintf(deviceNameBuffer, L"Device # %d", count); deviceName = ::SysAllocString(deviceNameBuffer); } hr = pDevice->get_Status(&enDeviceStatus); if (FAILED(hr)) { DEBUG_PRINT(("Device::get_Status Failed 0x%8x", hr)); } switch (enDeviceStatus) { case RTCXS_PRESENCE_OFFLINE: _snwprintf(buffer, MAX_STRING, L"%s (Offline)", deviceName); break; case RTCXS_PRESENCE_ONLINE: _snwprintf(buffer, MAX_STRING, L"%s (Online)", deviceName); break; case RTCXS_PRESENCE_AWAY: _snwprintf(buffer, MAX_STRING, L"%s (Away)", deviceName); break; case RTCXS_PRESENCE_IDLE: _snwprintf(buffer, MAX_STRING, L"%s (Idle)", deviceName); break; case RTCXS_PRESENCE_BUSY: _snwprintf(buffer, MAX_STRING, L"%s (Busy)", deviceName); break; case RTCXS_PRESENCE_BE_RIGHT_BACK: _snwprintf(buffer, MAX_STRING, L"%s (Be right back)", deviceName); break; case RTCXS_PRESENCE_ON_THE_PHONE: _snwprintf(buffer, MAX_STRING, L"%s (On the phone)", deviceName); break; case RTCXS_PRESENCE_OUT_TO_LUNCH: _snwprintf(buffer, MAX_STRING, L"%s (Out to lunch)", deviceName); break; default: _snwprintf(buffer, MAX_STRING, L"%s ", deviceName); break; } count++; SAFE_RELEASE(pDevice); SAFE_FREE_STRING(deviceName); // Main item ZeroMemory(&tviNewItem, sizeof(TV_ITEM)); tviNewItem.mask = TVIF_TEXT; tviNewItem.pszText = buffer; // Insert struct ZeroMemory(&tvis, sizeof(TVINSERTSTRUCT)); tvis.hParent = (HTREEITEM) hti; tvis.hInsertAfter = TVI_SORT; tvis.item = tviNewItem; HTREEITEM childhti = TreeView_InsertItem(m_hBuddyTree, &tvis); if (childhti == NULL) { // TreeView_InsertItem failed DEBUG_PRINT(("TreeView_InsertItem failed for child device %x", HRESULT_FROM_WIN32(GetLastError()) )); } } } TreeView_Expand(m_hBuddyTree, hti, TVE_EXPAND); SAFE_RELEASE(ppEnumDevices); //////////// // // End RTC Functionality Code // //////////// return S_OK; } ///////////////////////////////////////////// // // CRTCWin::UpdateBuddyList // HRESULT CRTCWin::UpdateBuddyList(IRTCBuddy * pBuddy) { HRESULT hr; if (pBuddy == NULL) { return S_OK; } //////////// // // Begin RTC Functionality Code // // This code demonstrates how to read the display name, basic presence, and URI of a buddy // //////////// // Get the buddy status RTC_PRESENCE_STATUS enStatus = RTCXS_PRESENCE_OFFLINE; hr = pBuddy->get_Status(&enStatus); if (FAILED(hr)) { // get_Status failed DEBUG_PRINT(("Buddy::get_Status Failed 0x%8x", hr)); } // Get the buddy name BSTR bstrName = NULL; IRTCBuddy2 *pBuddy2; pBuddy->QueryInterface(__uuidof(IRTCBuddy2), (LPVOID *)&pBuddy2); hr = pBuddy2->get_PresenceProperty(RTCPP_DISPLAYNAME, &bstrName); SAFE_RELEASE(pBuddy2); if (SUCCEEDED(hr) && !wcscmp(bstrName, L"")) { // Treat an emptry string as a failure SAFE_FREE_STRING(bstrName); hr = E_FAIL; } if (FAILED(hr)) { // get_Name failed, get the URI instead hr = pBuddy->get_PresentityURI(&bstrName); if (SUCCEEDED(hr) && !wcscmp(bstrName, L"")) { // Treat an emptry string as a failure SAFE_FREE_STRING(bstrName); hr = E_FAIL; } if (FAILED(hr)) { // get_PresentityURI failed DEBUG_PRINT(("get_PresentityURI failed %x", hr )); return hr; } } // Build a string for the main buddy node. WCHAR szBuddy[MAX_STRING]; switch (enStatus) { case RTCXS_PRESENCE_OFFLINE: _snwprintf(szBuddy, MAX_STRING, L"%ws (Offline)", bstrName); break; case RTCXS_PRESENCE_ONLINE: _snwprintf(szBuddy, MAX_STRING, L"%ws (Online)", bstrName); break; case RTCXS_PRESENCE_AWAY: _snwprintf(szBuddy, MAX_STRING, L"%ws (Away)", bstrName); break; case RTCXS_PRESENCE_IDLE: _snwprintf(szBuddy, MAX_STRING, L"%ws (Idle)", bstrName); break; case RTCXS_PRESENCE_BUSY: _snwprintf(szBuddy, MAX_STRING, L"%ws (Busy)", bstrName); break; case RTCXS_PRESENCE_BE_RIGHT_BACK: _snwprintf(szBuddy, MAX_STRING, L"%ws (Be right back)", bstrName); break; case RTCXS_PRESENCE_ON_THE_PHONE: _snwprintf(szBuddy, MAX_STRING, L"%ws (On the phone)", bstrName); break; case RTCXS_PRESENCE_OUT_TO_LUNCH: _snwprintf(szBuddy, MAX_STRING, L"%ws (Out to lunch)", bstrName); break; default: _snwprintf(szBuddy, MAX_STRING, L"%ws", bstrName); break; } szBuddy[MAX_STRING-1] = L'\0'; SAFE_FREE_STRING(bstrName); // Is the buddy in the tree? TVITEMEX tvix; int whichTree; ZeroMemory(&tvix, sizeof(TVITEMEX)); HRESULT hFound = TreeViewHelper_FindBuddyNode(pBuddy, &tvix, &whichTree); if (hFound == E_FAIL) { // Buddy is not in the list // Create new TreeView Item TreeViewHelper_InsertNode(pBuddy, szBuddy, enStatus); } else { TreeView_DeleteItem(m_hBuddyTree, tvix.hItem); TreeViewHelper_InsertNode(pBuddy, szBuddy, enStatus); // Release the buddy reference SAFE_RELEASE(pBuddy); } //////////// // // End RTC Functionality Code // //////////// return S_OK; } ///////////////////////////////////////////// // // CRTCWin::ClearBuddyList // HRESULT CRTCWin::ClearBuddyList(IRTCBuddy * pBuddy) { HRESULT hr; if (pBuddy == NULL) { return S_OK; } // Is the buddy in the tree? TVITEMEX tvix; ZeroMemory(&tvix, sizeof(TVITEMEX)); int whichTree; hr = TreeViewHelper_FindBuddyNode(pBuddy, &tvix, &whichTree); if (hr == S_OK) { TreeView_DeleteItem(m_hBuddyTree, tvix.hItem); SAFE_RELEASE(pBuddy); } else { DEBUG_PRINT(("Buddy not in tree %x", HRESULT_FROM_WIN32(GetLastError()) )); } return S_OK; } ///////////////////////////////////////////// // // CRTCWin::ClearBuddyList // HRESULT CRTCWin::ClearBuddyList() { HTREEITEM child; TVITEMEX tvix; // Online Nodes child = TreeView_GetNextItem(m_hBuddyTree, m_hOnlineParent, TVGN_CHILD); while (child != NULL) { HTREEITEM temp; // Retrieve the item ZeroMemory(&tvix, sizeof(TVITEMEX)); tvix.mask = TVIF_PARAM; tvix.hItem = child; TreeView_GetItem(m_hBuddyTree, &tvix); // Release the buddy IRTCBuddy *pBuddy = (IRTCBuddy *) tvix.lParam; if (pBuddy) { DEBUG_PRINT(("On: Clear Buddy Succeeded. ")); SAFE_RELEASE(pBuddy); } else { DEBUG_PRINT(("Error, pBuddy == NULL. ")); } // Delete the node and move on temp = TreeView_GetNextItem(m_hBuddyTree, child, TVGN_NEXT); TreeView_DeleteItem(m_hBuddyTree, child); child = temp; } child = TreeView_GetNextItem(m_hBuddyTree, m_hOfflineParent, TVGN_CHILD); while (child != NULL) { HTREEITEM temp; // Retrieve the item ZeroMemory(&tvix, sizeof(TVITEMEX)); tvix.mask = TVIF_PARAM; tvix.hItem = child; TreeView_GetItem(m_hBuddyTree, &tvix); // Release the buddy IRTCBuddy *pBuddy = (IRTCBuddy *) tvix.lParam; if (pBuddy) { DEBUG_PRINT(("Off: Clear Buddy Succeeded. ")); SAFE_RELEASE(pBuddy); } else { DEBUG_PRINT(("Error, pBuddy == NULL. ")); } // Delete the node and move on temp = TreeView_GetNextItem(m_hBuddyTree, child, TVGN_NEXT); TreeView_DeleteItem(m_hBuddyTree, child); child = temp; } return S_OK; } ///////////////////////////////////////////// // // CRTCWin::PopulateBuddyList // HRESULT CRTCWin::PopulateBuddyList() { HRESULT hr; //////////// // // Begin RTC Functionality Code // // This code demonstrates how to enumerate the current buddies // //////////// // Get the RTC client presence interface IRTCClientPresence * pPresence = NULL; hr = m_pClient->QueryInterface( __uuidof(IRTCClientPresence), (void **)&pPresence); if (FAILED(hr)) { // QueryInterface failed DEBUG_PRINT(("QueryInterface failed %x", hr )); return hr; } // Enumerate buddies and populate list IRTCEnumBuddies * pEnum = NULL; IRTCBuddy * pBuddy = NULL; hr = pPresence->EnumerateBuddies(&pEnum); SAFE_RELEASE(pPresence); if (FAILED(hr)) { // Enumerate buddies failed DEBUG_PRINT(("EnumerateBuddies failed %x", hr )); return hr; } while (pEnum->Next(1, &pBuddy, NULL) == S_OK) { // Update the buddy list entry UpdateBuddyList(pBuddy); SAFE_RELEASE(pBuddy); } SAFE_RELEASE(pEnum); //////////// // // End RTC Functionality Code // //////////// return S_OK; } ///////////////////////////////////////////// // // CRTCWin::DoLogOn // HRESULT CRTCWin::DoLogOn(BSTR bstrURI, BSTR bstrServer, BSTR bstrTransport) { HRESULT hr; if (m_pProfile) { // Already logged on ShowMessageBox(L"Already logged on!"); return S_FALSE; } m_nLogonAttemptCount = 0; hr = DoGetProfile(bstrURI, bstrServer, bstrTransport); if (FAILED(hr)) { // DoGetProfile failed DEBUG_PRINT(("DoGetProfile failed %x", hr )); ShowMessageBox(L"Logon failed!"); return hr; } SetStatusText(L"Finding server"); // Enable/disable menu items HMENU hMenu = GetMenu(m_hWnd); EnableMenuItem(hMenu, ID_FILE_LOGON, MF_GRAYED); EnableMenuItem(hMenu, ID_FILE_LOGOFF, MF_GRAYED); return S_OK; } ///////////////////////////////////////////// // // CRTCWin::OnLoggingOn // HRESULT CRTCWin::OnLoggingOn() { SetStatusText(L"Logging on"); // Enable/disable menu items HMENU hMenu = GetMenu(m_hWnd); EnableMenuItem(hMenu, ID_FILE_LOGON, MF_GRAYED); EnableMenuItem(hMenu, ID_FILE_LOGOFF, MF_ENABLED); return S_OK; } ///////////////////////////////////////////// // // CRTCWin::OnLoggedOn // HRESULT CRTCWin::OnLoggedOn() { HRESULT hr = S_OK; BSTR bstrURI = NULL; WCHAR szStatus[MAX_STRING]; hr = GetUserURI(&bstrURI); if (FAILED(hr)) { _snwprintf(szStatus, MAX_STRING, L"Logged on"); szStatus[MAX_STRING - 1] = L'\0'; } else { _snwprintf(szStatus, MAX_STRING, L"Logged on (%ws)", bstrURI); szStatus[MAX_STRING - 1] = L'\0'; SAFE_FREE_STRING(bstrURI); } SetStatusText(szStatus); PopulateBuddyList(); // Enable/disable menu items HMENU hMenu = GetMenu(m_hWnd); EnableMenuItem(hMenu, ID_FILE_LOGON, MF_GRAYED); EnableMenuItem(hMenu, ID_FILE_LOGOFF, MF_ENABLED); EnableMenuItem(hMenu, ID_ACTION_ADDBUDDY, MF_ENABLED); EnableMenuItem(hMenu, ID_TOOLS_USERSEARCH, MF_ENABLED); EnableMenuItem(hMenu, ID_TOOLS_WATCHERS, MF_ENABLED); EnableMenuItem(hMenu, ID_TOOLS_GROUPS, MF_ENABLED); return S_OK; } ///////////////////////////////////////////// // // CRTCWin::DoLogOff // HRESULT CRTCWin::DoLogOff() { HRESULT hr = S_OK; if (!m_pProfile) { // Already logged off OnLoggedOff(); return S_OK; } // Disable profile DoEnableProfile(FALSE, 0, 0); SAFE_RELEASE(m_pProfile); return hr; } ///////////////////////////////////////////// // // CRTCWin::OnLoggingOff // HRESULT CRTCWin::OnLoggingOff() { SetStatusText(L"Logging off"); // Enable/disable menu items HMENU hMenu = GetMenu(m_hWnd); EnableMenuItem(hMenu, ID_FILE_LOGON, MF_GRAYED); EnableMenuItem(hMenu, ID_FILE_LOGOFF, MF_GRAYED); EnableMenuItem(hMenu, ID_ACTION_ADDBUDDY, MF_GRAYED); EnableMenuItem(hMenu, ID_TOOLS_USERSEARCH, MF_GRAYED); EnableMenuItem(hMenu, ID_TOOLS_WATCHERS, MF_GRAYED); EnableMenuItem(hMenu, ID_TOOLS_GROUPS, MF_GRAYED); return S_OK; } ///////////////////////////////////////////// // // CRTCWin::OnLoggedOff // HRESULT CRTCWin::OnLoggedOff() { SetStatusText(L"Logged off"); // Disable presence DoEnablePresence(FALSE); // Cleanup the user search windows CleanupUserSearches(); // Cleanup the watcher windows CleanupWatchers(); // Cleanup the group windows CleanupGroups(); // Enable/disable menu items HMENU hMenu = GetMenu(m_hWnd); EnableMenuItem(hMenu, ID_FILE_LOGON, MF_ENABLED); EnableMenuItem(hMenu, ID_FILE_LOGOFF, MF_GRAYED); EnableMenuItem(hMenu, ID_ACTION_ADDBUDDY, MF_GRAYED); EnableMenuItem(hMenu, ID_TOOLS_USERSEARCH, MF_GRAYED); EnableMenuItem(hMenu, ID_TOOLS_WATCHERS, MF_GRAYED); EnableMenuItem(hMenu, ID_TOOLS_GROUPS, MF_GRAYED); return S_OK; } ///////////////////////////////////////////// // // CRTCWin::DoGetProfile // HRESULT CRTCWin::DoGetProfile(BSTR bstrURI, BSTR bstrServer, BSTR bstrTransport) { HRESULT hr; //////////// // // Begin RTC Functionality Code // // This code demonstrates how to get a profile based on server name, transport, account settings, and uri // //////////// // Find transport long lTransport = 0; if (bstrTransport != NULL) { if (!_wcsicmp(bstrTransport, L"UDP")) { lTransport = RTCTR_UDP; } else if (!_wcsicmp(bstrTransport, L"TCP")) { lTransport = RTCTR_TCP; } else if (!_wcsicmp(bstrTransport, L"TLS")) { lTransport = RTCTR_TLS; } } // Get the RTC client provisioning interface IRTCClientProvisioning2 * pProv = NULL; hr = m_pClient->QueryInterface( __uuidof(IRTCClientProvisioning2), (void **)&pProv); if (FAILED(hr)) { // QueryInterface failed DEBUG_PRINT(("QueryInterface failed %x", hr )); return hr; } // Get the profile hr = pProv->GetProfile( NULL, // bstrUserAccount NULL, // bstrUserPassword bstrURI, // bstrUserURI bstrServer, // bstrServer lTransport, // lTransport 0 // lCookie ); SAFE_RELEASE(pProv); if (FAILED(hr)) { // GetProfile failed DEBUG_PRINT(("GetProfile failed %x", hr )); return hr; } //////////// // // End RTC Functionality Code // //////////// return S_OK; } ///////////////////////////////////////////// // // CRTCWin::DoEnableProfile // HRESULT CRTCWin::DoEnableProfile(BOOL fEnable, long lRegisterFlags, long lRoamingFlags) { HRESULT hr; //////////// // // Begin RTC Functionality Code // // This code demonstrates how to Enable a Profile (which you can create using GetProfile). // This is called from DoRegister. We need to EnablePresenceEx first (which is done in DoRegister) // //////////// // Get the RTC client provisioning interface IRTCClientProvisioning2 * pProv = NULL; hr = m_pClient->QueryInterface( __uuidof(IRTCClientProvisioning2), (void **)&pProv); if (FAILED(hr)) { // QueryInterface failed DEBUG_PRINT(("QueryInterface failed %x", hr )); return hr; } if (fEnable) { // Enable the RTC profile object hr = pProv->EnableProfileEx(m_pProfile, lRegisterFlags, lRoamingFlags); SAFE_RELEASE(pProv); if (FAILED(hr)) { // EnableProfile failed DEBUG_PRINT(("EnableProfileEx failed %x", hr )); return hr; } } else { // Disable the RTC profile object hr = pProv->DisableProfile(m_pProfile); SAFE_RELEASE(pProv); if (FAILED(hr)) { // EnableProfile failed DEBUG_PRINT(("DisableProfile failed %x", hr )); return hr; } } //////////// // // End RTC Functionality Code // //////////// return S_OK; } ///////////////////////////////////////////// // // CRTCWin::DoRegister // HRESULT CRTCWin::DoRegister() { HRESULT hr; //////////// // // Begin RTC Functionality Code // // This code demonstrates the registration sequence. // We will call DoEnablePresence in order to Enable Presence on a Profile (this needs to be done in order to use presence features on the profile). // We will then call DoEnableProfile in order to enable the profile and perform the actual registration. // //////////// // Enable presence hr = DoEnablePresence(TRUE); if (FAILED(hr)) { // DoEnablePresence failed DEBUG_PRINT(("DoEnablePresence failed %x", hr )); return hr; } // Enable the RTC profile object hr = DoEnableProfile(TRUE, RTCRF_REGISTER_ALL, 0 ); if (FAILED(hr)) { // DoEnableProfile failed DEBUG_PRINT(("DoEnableProfile failed %x", hr )); return hr; } //////////// // // End RTC Functionality Code // //////////// return S_OK; } ///////////////////////////////////////////// // // CRTCWin::DoAuth // HRESULT CRTCWin::DoAuth(BSTR bstrURI, BSTR bstrAccount, BSTR bstrPassword) { HRESULT hr; //////////// // // Begin RTC Functionality Code // // This code demonstrates how to set the credentials on a profile. // This can be called from a Registration State Change event if the failure is due to invalid authentication. // //////////// // Update the credentials in the profile hr = m_pProfile->SetCredentials(bstrURI, bstrAccount, bstrPassword); if (FAILED(hr)) { // SetCredentials failed DEBUG_PRINT(("SetCredentials failed %x", hr )); return hr; } // Re-register hr = DoRegister(); if (FAILED(hr)) { // DoRegister failed DEBUG_PRINT(("DoRegister failed %x", hr )); return hr; } //////////// // // End RTC Functionality Code // //////////// return S_OK; } ///////////////////////////////////////////// // // CRTCWin::DoEnablePresence // HRESULT CRTCWin::DoEnablePresence(BOOL fEnable) { //////////// // // Begin RTC Functionality Code // // This code demonstrates EnablePresenceEx on a Profile (which you can create using GetProfile). // This is required before calling EnableProfileEx. // //////////// IRTCClientPresence2 * pPresence = NULL; HRESULT hr; if (m_fPresenceEnabled == fEnable) { // Already in correct state return S_FALSE; } // Cleanup the buddy list ClearBuddyList(); // Get the RTC client presence interface hr = m_pClient->QueryInterface( __uuidof(IRTCClientPresence2), (void **)&pPresence); if (FAILED(hr)) { // QueryInterface failed return hr; } if (fEnable) { // Build the filename for presence storage // from the user URI VARIANT varStorage; VariantInit(&varStorage); varStorage.vt = VT_BSTR; BSTR bstrURI = NULL; hr = m_pProfile->get_UserURI(&bstrURI); if (FAILED(hr)) { // get_UserURI failed DEBUG_PRINT(("get_UserURI failed %x", hr )); SAFE_RELEASE(pPresence); return hr; } WCHAR * pch = bstrURI; size_t cch; cch = wcslen(bstrURI) + wcslen(L"presence_.xml") + 1; while (*pch != L'\0') { // Replace all non-alphanumeric characters // in the URI with underscore if (!((*pch >= L'a') && (*pch <= L'z')) && !((*pch >= L'A') && (*pch <= L'Z')) && !((*pch >= L'0') && (*pch <= L'9'))) { *pch = L'_'; } pch++; } // Allocate space for the filename varStorage.bstrVal = SysAllocStringLen(NULL, (ULONG) cch); if (!varStorage.bstrVal) { // Out of memory DEBUG_PRINT(("Out of memory")); SAFE_RELEASE(pPresence); SAFE_FREE_STRING(bstrURI); return E_OUTOFMEMORY; } // Create the filename _snwprintf(varStorage.bstrVal, cch, L"presence_%ws.xml", bstrURI); SAFE_FREE_STRING(bstrURI); // Enable presence hr = pPresence->EnablePresenceEx(m_pProfile, varStorage, 0); VariantClear(&varStorage); if (FAILED(hr)) { // EnablePresence failed DEBUG_PRINT(("EnablePresence failed %x", hr )); SAFE_RELEASE(pPresence); return hr; } //////////// // // Begin RTC Functionality Code // // This code demonstrates how to set a presence property for this particular device. // We are going to set our device name to the computer name and then (RTCSampleT). // //////////// // Set a presence property BSTR bstrPropName = SysAllocString(L"http://schemas.microsoft.com/rtc/rtcsample"); BSTR bstrPropVal = SysAllocString(L"<name> rtcsample </rtcsample>"); if (bstrPropName && bstrPropVal) { hr = pPresence->SetPresenceData(bstrPropName, bstrPropVal); if (FAILED(hr)) { // SetPresenceData failed DEBUG_PRINT(("SetPresenceData failed %x", hr )); } } wchar_t wszCnBuffer[MAX_COMPUTER_NAME_LENGTH]; // Max computer name length is 256 I believe BOOL fSuccessComputerName = FALSE; DWORD dwLength = MAX_COMPUTER_NAME_LENGTH - 1; fSuccessComputerName = GetComputerNameW(wszCnBuffer, &dwLength); if (fSuccessComputerName) { #define SAMPLE_STR_SIZE 13 // ( size of "(RTCSampleT)" + 1) int nSize = dwLength + 1 + SAMPLE_STR_SIZE + 1; wchar_t *wszNewDeviceName = new wchar_t[nSize]; if (!wszNewDeviceName) return E_OUTOFMEMORY; wcscpy(wszNewDeviceName, wszCnBuffer); wcsncat(wszNewDeviceName, L" (RTCSampleT)", nSize - (wcslen(wszCnBuffer) + 1)); BSTR bstrDeviceName = ::SysAllocString(wszNewDeviceName); delete [] wszNewDeviceName; hr = pPresence->put_PresenceProperty(RTCPP_DEVICE_NAME, bstrDeviceName); SAFE_FREE_STRING(bstrDeviceName); } SAFE_FREE_STRING(bstrPropName); SAFE_FREE_STRING(bstrPropVal); } else { // Disable presence hr = pPresence->DisablePresence(); if (FAILED(hr)) { // DisablePresence failed DEBUG_PRINT(("DisablePresence failed %x", hr )); SAFE_RELEASE(pPresence); return hr; } } // Set the enabled flag m_fPresenceEnabled = fEnable; SAFE_RELEASE(pPresence); //////////// // // End RTC Functionality Code // //////////// return S_OK; } ///////////////////////////////////////////// // // CRTCWin::DoAddBuddy // HRESULT CRTCWin::DoAddBuddy(BSTR bstrURI, BSTR bstrName) { HRESULT hr; //////////// // // Begin RTC Functionality Code // // This code demonstrates how to Add a Buddy // //////////// // Get the RTC client presence interface IRTCClientPresence * pPresence = NULL; hr = m_pClient->QueryInterface( __uuidof(IRTCClientPresence), (void **)&pPresence); if (FAILED(hr)) { // QueryInterface failed return hr; } // Add the buddy IRTCBuddy * pBuddy = NULL; hr = pPresence->AddBuddy( bstrURI, bstrName, NULL, VARIANT_TRUE, NULL, 0, &pBuddy); SAFE_RELEASE(pPresence); if (FAILED(hr)) { // AddBuddy failed DEBUG_PRINT(("AddBuddy failed %x", hr )); return hr; } if (pBuddy) { // Update the buddy list entry UpdateBuddyList(pBuddy); SAFE_RELEASE(pBuddy); } //////////// // // End RTC Functionality Code // //////////// return S_OK; } ///////////////////////////////////////////// // // CRTCWin::DoRefreshBuddy // HRESULT CRTCWin::DoRefreshBuddy(IRTCBuddy *pBuddy) { HRESULT hr; //////////// // // Begin RTC Functionality Code // // This code demonstrates how to refresh a buddy's presence. // //////////// // Get the IRTCBuddy2 interface IRTCBuddy2 * pBuddy2 = NULL; hr = pBuddy->QueryInterface( __uuidof(IRTCBuddy2), (void **)&pBuddy2); if (FAILED(hr)) { // QueryInterface failed return hr; } // Refresh the buddy hr = pBuddy2->Refresh(); SAFE_RELEASE(pBuddy2); if (FAILED(hr)) { // Refresh failed DEBUG_PRINT(("Refresh failed %x", hr )); return hr; } //////////// // // End RTC Functionality Code // //////////// return S_OK; } ///////////////////////////////////////////// // // CRTCWin::DoRemoveBuddy // HRESULT CRTCWin::DoRemoveBuddy(IRTCBuddy *pBuddy) { HRESULT hr; //////////// // // Begin RTC Functionality Code // // This code demonstrates how to remove a buddy // //////////// // Get the RTC client presence interface IRTCClientPresence * pPresence = NULL; hr = m_pClient->QueryInterface( __uuidof(IRTCClientPresence), (void **)&pPresence); if (FAILED(hr)) { // QueryInterface failed DEBUG_PRINT(("QueryInterface failed %x", hr )); return hr; } // Remove the buddy hr = pPresence->RemoveBuddy(pBuddy); SAFE_RELEASE(pPresence); if (FAILED(hr)) { // RemoveBuddy failed DEBUG_PRINT(("RemoveBuddy failed %x", hr )); return hr; } //////////// // // End RTC Functionality Code // //////////// return S_OK; } ///////////////////////////////////////////// // // CRTCWin::DoCall // HRESULT CRTCWin::DoCall(RTC_SESSION_TYPE enType, BSTR bstrURI, BSTR bstrName) { HRESULT hr; //////////// // // Begin RTC Functionality Code // // This code demonstrates how to Create a Session with another user // //////////// if (enType == RTCST_PC_TO_PC || enType == RTCST_PC_TO_PHONE) { // Is there already an AV session? We can only // allow one at a time if (CRTCAVSession::m_Singleton != NULL) { ShowMessageBox(L"An audio/video call is in progress!"); return S_FALSE; } } // Create the session IRTCSession * pSession = NULL; hr = m_pClient->CreateSession( enType, NULL, NULL, 0, &pSession ); if (FAILED(hr)) { // CreateSession failed DEBUG_PRINT(("CreateSession failed %x", hr )); return hr; } // Add the participant to the session hr = pSession->AddParticipant( bstrURI, bstrName, NULL ); if (FAILED(hr)) { // AddParticipant failed DEBUG_PRINT(("AddParticipant failed %x", hr )); SAFE_RELEASE(pSession); return hr; } // Add the session to the session list // This will create the session window hr = AddSession(pSession, enType); SAFE_RELEASE(pSession); if (FAILED(hr)) { // AddSession failed DEBUG_PRINT(("AddSession failed %x", hr )); return hr; } //////////// // // End RTC Functionality Code // //////////// return S_OK; } ///////////////////////////////////////////// // // CRTCWin::DoTuningWizard // HRESULT CRTCWin::DoTuningWizard() { HRESULT hr; //////////// // // Begin RTC Functionality Code // // This code demonstrates how to invoke the tuning wizard // //////////// // Is there already an AV session? We can only // allow one at a time if (CRTCAVSession::m_Singleton != NULL) { ShowMessageBox(L"An audio/video call is in progress!"); return S_FALSE; } // Show the tuning wizard hr = m_pClient->InvokeTuningWizard((OAHWND)m_hWnd); if (FAILED(hr)) { // InvokeTuningWizard failed DEBUG_PRINT(("InvokeTuningWizard failed %x", hr )); return hr; } //////////// // // End RTC Functionality Code // //////////// return S_OK; } ///////////////////////////////////////////// // // CRTCWin::DoSetPresence // HRESULT CRTCWin::DoSetPresence(RTC_PRESENCE_STATUS enStatus) { HRESULT hr; UINT id = 0; // Check the appropriate menu item switch(enStatus) { case RTCXS_PRESENCE_OFFLINE: id = ID_FILE_PRESENCESTATUS_OFFLINE; break; case RTCXS_PRESENCE_ONLINE: id = ID_FILE_PRESENCESTATUS_ONLINE; break; case RTCXS_PRESENCE_AWAY: id = ID_FILE_PRESENCESTATUS_AWAY; break; case RTCXS_PRESENCE_IDLE: id = ID_FILE_PRESENCESTATUS_IDLE; break; case RTCXS_PRESENCE_BUSY: id = ID_FILE_PRESENCESTATUS_BUSY; break; case RTCXS_PRESENCE_BE_RIGHT_BACK: id = ID_FILE_PRESENCESTATUS_BERIGHTBACK; break; case RTCXS_PRESENCE_ON_THE_PHONE: id = ID_FILE_PRESENCESTATUS_ONTHEPHONE; break; case RTCXS_PRESENCE_OUT_TO_LUNCH: id = ID_FILE_PRESENCESTATUS_OUTTOLUNCH; break; } CheckMenuRadioItem( GetMenu(m_hWnd), // handle to menu ID_FILE_PRESENCESTATUS_OFFLINE, // identifier or position of first item ID_FILE_PRESENCESTATUS_OUTTOLUNCH, // identifier or position of last item id, // identifier or position of menu item MF_BYCOMMAND // function options ); //////////// // // Begin RTC Functionality Code // // This code demonstrates how to set the presence for your device. // //////////// // Get the RTC client presence interface IRTCClientPresence * pPresence = NULL; hr = m_pClient->QueryInterface( __uuidof(IRTCClientPresence), (void **)&pPresence); if (FAILED(hr)) { // QueryInterface failed DEBUG_PRINT(("QueryInterface failed %x", hr )); return hr; } // Set the local presence status hr = pPresence->SetLocalPresenceInfo(enStatus, NULL); SAFE_RELEASE(pPresence); if (FAILED(hr)) { // SetLocalPresenceInfo failed DEBUG_PRINT(("SetLocalPresenceInfo failed %x", hr )); return hr; } //////////// // // End RTC Functionality Code // //////////// return S_OK; } HRESULT CRTCWin::DoOptions() { HRESULT hr = S_OK; LONG MaxlBW = 1000000; long lMediaType = 0; //////////// // // Begin RTC Functionality Code // // This code demonstrates how to set the preferred security level, the preferred media types, // the client name, the client version, the max bitrate, and the preferred security level. // //////////// //Get the current security levels that are on the client. //We are going to display these. m_pClient->get_PreferredSecurityLevel(RTCSECT_AUDIO_VIDEO_MEDIA_ENCRYPTION, &m_OD.enAVLevel); m_pClient->get_PreferredSecurityLevel(RTCSECT_T120_MEDIA_ENCRYPTION, &m_OD.enT120Level); // Get the media types from client and set the T120 option accordingly m_pClient->get_PreferredMediaTypes(&lMediaType); if ((lMediaType & RTCMT_T120_SENDRECV) == 0) m_OD.EnabledOptions &= ~RTCWIN_OPTIONS_T120; else m_OD.EnabledOptions |= RTCWIN_OPTIONS_T120; //show the dialog box ShowOptionsDialog(m_hWnd, &m_OD); //The dialog box was displayed. Now start saving AppVersion m_pClient->put_ClientName(m_OD.bstrAppName); m_pClient->put_ClientCurVer(m_OD.bstrAppVer); //If the dialog box had the MaxBW option set, apply that. if(m_OD.EnabledOptions & RTCWIN_OPTIONS_MAXBW) { m_pClient->put_MaxBitrate(m_OD.lMaxBW); } else m_pClient->put_MaxBitrate(MaxlBW); //If the dialog box had the T120 option set, apply that. if(m_OD.EnabledOptions & RTCWIN_OPTIONS_T120) m_pClient->SetPreferredMediaTypes(lMediaType | RTCMT_T120_SENDRECV, FALSE); else m_pClient->SetPreferredMediaTypes(lMediaType & ~RTCMT_T120_SENDRECV, FALSE); //Apply the security levels as set in the Options dialog box m_pClient->put_PreferredSecurityLevel(RTCSECT_AUDIO_VIDEO_MEDIA_ENCRYPTION, m_OD.enAVLevel); m_pClient->put_PreferredSecurityLevel(RTCSECT_T120_MEDIA_ENCRYPTION, m_OD.enT120Level); //////////// // // End RTC Functionality Code // //////////// return hr; } HRESULT CRTCWin::DoBuddyProperties(IRTCBuddy *pBuddy) { HRESULT hr = S_OK; IRTCBuddy2 *pBuddy2; pBuddy->QueryInterface(__uuidof(IRTCBuddy2),(LPVOID *)&pBuddy2); ShowBuddyPropertiesDialog(NULL,pBuddy2); SAFE_RELEASE(pBuddy2); return hr; } HRESULT CRTCWin::DoDTMFDialpad() { return ShowDtmfDialpad(m_hWnd,m_pClient); } ///////////////////////////////////////////// // // CRTCWin::WindowProc // LRESULT CALLBACK CRTCWin::WindowProc( HWND hWnd, // handle to window UINT uMsg, // message identifier WPARAM wParam, // first message parameter LPARAM lParam // second message parameter ) { CRTCWin * me = NULL; LRESULT lr = 0; if ( uMsg == WM_CREATE ) { // Create an instance of the class me = new CRTCWin; if(!me) { // Failed to create the instance return -1; } me->m_hWnd = hWnd; // Store the class instance pointer in the // window's user data for later retrieval SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG_PTR)me); lr = me->OnCreate(uMsg, wParam, lParam); } else { // Retrieve the class instance pointer from the // window's user data me = (CRTCWin *)GetWindowLongPtr(hWnd, GWLP_USERDATA); switch( uMsg ) { case WM_DESTROY: lr = me->OnDestroy(uMsg, wParam, lParam); // Delete the object instance delete me; // Quit the application PostQuitMessage(0); break; case WM_CLOSE: lr = me->OnClose(uMsg, wParam, lParam); break; case WM_SIZE: lr = me->OnSize(uMsg, wParam, lParam); break; case WM_COMMAND: lr = me->OnCommand(uMsg, wParam, lParam); break; case WM_NOTIFY: lr = me->OnNotify(uMsg, wParam, lParam); break; case WM_RTC_EVENT: lr = me->OnRTCEvent(uMsg, wParam, lParam); break; default: lr = DefWindowProc( hWnd, uMsg, wParam, lParam ); } } return lr; } ///////////////////////////////////////////// // // CRTCWin::OnCreate // LRESULT CRTCWin::OnCreate(UINT uMsg, WPARAM wParam, LPARAM lParam) { // WM_CREATE has three parameters. We will pass them to our Create Proc for future use // They are not all currently used. UNREFERENCED_PARAMETER(wParam); UNREFERENCED_PARAMETER(lParam); UNREFERENCED_PARAMETER(uMsg); // Create the status bar m_hStatusBar = CreateStatusWindow( WS_CHILD | WS_VISIBLE, NULL, m_hWnd, IDC_STATUSBAR ); if ( !m_hStatusBar ) { // CreateStatusWindow failed DEBUG_PRINT(("CreateStatusWindow failed %x", HRESULT_FROM_WIN32(GetLastError()) )); return -1; } // Create the buddy tree view m_hBuddyTree = CreateWindowExW( WS_EX_CLIENTEDGE, L"SysTreeView32", NULL, WS_CHILD | WS_VISIBLE | TVS_HASLINES | TVS_LINESATROOT | TVS_HASBUTTONS, 0, 0, 0, 0, m_hWnd, (HMENU)IDC_BUDDYTREE, GetModuleHandle(NULL), NULL); if ( !m_hBuddyTree ) { // CreateWindowExW failed DEBUG_PRINT(("CreateWindowExW failed %x", HRESULT_FROM_WIN32(GetLastError()) )); return -1; } // Add online and offline groups TV_ITEM tviNewItem; ZeroMemory(&tviNewItem, sizeof(TV_ITEM)); tviNewItem.mask = TVIF_TEXT; tviNewItem.pszText = L"Online"; TVINSERTSTRUCT tvis; ZeroMemory(&tvis, sizeof(TVINSERTSTRUCT)); tvis.hParent = TVI_ROOT; tvis.hInsertAfter = TVI_ROOT; tvis.item = tviNewItem; HTREEITEM hti = TreeView_InsertItem(m_hBuddyTree, &tvis); if (hti == NULL) { // TreeView_InsertItem failed DEBUG_PRINT(("TreeView_InsertItem failed %x", HRESULT_FROM_WIN32(GetLastError()) )); return E_FAIL; } else { m_hOnlineParent = (HWND) hti; } ZeroMemory(&tviNewItem, sizeof(TV_ITEM)); tviNewItem.mask = TVIF_TEXT; tviNewItem.pszText = L"Offline"; ZeroMemory(&tvis, sizeof(TVINSERTSTRUCT)); tvis.hParent = TVI_ROOT; tvis.hInsertAfter = TVI_ROOT; tvis.item = tviNewItem; hti = TreeView_InsertItem(m_hBuddyTree, &tvis); if (hti == NULL) { // TreeView_InsertItem failed DEBUG_PRINT(("TreeView_InsertItem failed %x", HRESULT_FROM_WIN32(GetLastError()) )); return E_FAIL; } else { m_hOfflineParent = (HWND) hti; } //////////// // // Begin RTC Functionality Code // // This code demonstrates how to create an RTC Client object and query its version, // Initialize the client, set its event filter for the events we are interested in, // set the listen mode, and attach the event sink. // //////////// // Create the RTC client HRESULT hr; hr = CoCreateInstance( __uuidof(RTCClient), NULL, CLSCTX_INPROC_SERVER, __uuidof(IRTCClient2), (LPVOID *)&m_pClient ); if (FAILED(hr)) { // CoCreateInstance failed DEBUG_PRINT(("CoCreateInstance failed %x", hr )); ShowMessageBox(L"RTC Client v1.1 or higher required!"); return -1; } long lVersion; #ifdef _PREFAST_ // If CoCreateInstance() succeeds, m_pClient cannot be NULL __assume(NULL != m_pClient); #endif //_PREFAST_ hr = m_pClient->get_Version(&lVersion); if (FAILED(hr)) { // get_Version failed DEBUG_PRINT(("get_Version failed %x", hr )); ShowMessageBox(L"RTC Client v1.1 or higher required!"); return -1; } if (lVersion < 0x00010002) { // Unsupported RTCDLL version DEBUG_PRINT(("Unsupported RTCDLL version")); ShowMessageBox(L"RTC Client v1.2 or higher required!"); return -1; } // Initialize the RTC client hr = m_pClient->Initialize(); if (FAILED(hr)) { // Initialize failed DEBUG_PRINT(("Initialize failed %x", hr )); SAFE_RELEASE(m_pClient); return -1; } // Determine the event filter long lFlags = RTCEF_REGISTRATION_STATE_CHANGE | RTCEF_SESSION_STATE_CHANGE | RTCEF_PARTICIPANT_STATE_CHANGE | RTCEF_MESSAGING | RTCEF_MEDIA | RTCEF_INTENSITY | RTCEF_CLIENT | RTCEF_BUDDY | RTCEF_BUDDY2 | RTCEF_WATCHER | RTCEF_WATCHER2 | RTCEF_GROUP | RTCEF_USERSEARCH | RTCEF_ROAMING | RTCEF_PROFILE | RTCEF_PRESENCE_PROPERTY | RTCEF_PRESENCE_DATA | RTCE_MEDIA_REQUEST; // Set the event filter for the RTC client hr = m_pClient->put_EventFilter(lFlags); if ( FAILED(hr) ) { // put_EventFilter failed DEBUG_PRINT(("put_EventFilter failed %x", hr )); SAFE_RELEASE(m_pClient); return -1; } // Set the listen mode for RTC client // RTCLM_BOTH opens the standard SIP port 5060, as well as // a dynamic port. hr = m_pClient->put_AllowedPorts(RTCTR_TCP, RTCLM_BOTH); if ( FAILED(hr) ) { // put_ListenMode failed DEBUG_PRINT(("put_AllowedPorts (RTCTR_TCP) failed %x", hr )); SAFE_RELEASE(m_pClient); return -1; } hr = m_pClient->put_AllowedPorts(RTCTR_UDP, RTCLM_BOTH); if ( FAILED(hr) ) { // put_ListenMode failed DEBUG_PRINT(("put_AllowedPorts (RTCTR_UDP) failed %x", hr )); SAFE_RELEASE(m_pClient); return -1; } // Answer Mode Calls hr = m_pClient->put_AnswerMode(RTCST_PC_TO_PC, RTCAM_OFFER_SESSION_EVENT); if ( FAILED(hr) ) { // put_AnswerMode failed DEBUG_PRINT(("put_AnswerMode (RTCST_PC_TO_PC) failed %x", hr )); SAFE_RELEASE(m_pClient); return -1; } hr = m_pClient->put_AnswerMode(RTCST_IM, RTCAM_AUTOMATICALLY_ACCEPT); if ( FAILED(hr) ) { // put_AnswerMode failed DEBUG_PRINT(("put_AnswerMode (RTCST_IM) failed %x", hr )); SAFE_RELEASE(m_pClient); return -1; } hr = m_pClient->put_AnswerMode(RTCST_MULTIPARTY_IM, RTCAM_AUTOMATICALLY_ACCEPT); if ( FAILED(hr) ) { // put_AnswerMode failed DEBUG_PRINT(("put_AnswerMode (RTCST_MULTIPARTY_IM) failed %x", hr )); SAFE_RELEASE(m_pClient); return -1; } hr = m_pClient->put_AnswerMode(RTCST_APPLICATION, RTCAM_OFFER_SESSION_EVENT); if ( FAILED(hr) ) { // put_AnswerMode failed DEBUG_PRINT(("put_AnswerMode (RTCST_APPLICATION) failed %x", hr )); SAFE_RELEASE(m_pClient); return -1; } hr = m_pClient->put_AnswerMode(RTCST_PC_TO_PHONE, RTCAM_AUTOMATICALLY_REJECT); if ( FAILED(hr) ) { // put_AnswerMode failed DEBUG_PRINT(("put_AnswerMode (RTCST_PC_TO_PHONE) failed %x", hr )); SAFE_RELEASE(m_pClient); } hr = m_pClient->put_AnswerMode(RTCST_PHONE_TO_PHONE, RTCAM_AUTOMATICALLY_REJECT); if ( FAILED(hr) ) { // put_AnswerMode failed DEBUG_PRINT(("put_AnswerMode (RTCST_PHONE_TO_PHONE) failed %x", hr )); SAFE_RELEASE(m_pClient); } // Create the event sink object m_pEvents = new CRTCEvents; if (!m_pEvents) { // Out of memory DEBUG_PRINT(("Out of memory")); SAFE_RELEASE(m_pClient); return -1; } // Advise for events from the RTC client hr = m_pEvents->Advise( m_pClient, m_hWnd ); if ( FAILED(hr) ) { // Advise failed DEBUG_PRINT(("Advise failed %x", hr )); SAFE_RELEASE(m_pClient); return -1; } // Register the client Version BSTR bstr = ::SysAllocString(L"RTCSample_Test_Version"); hr = m_pClient->put_ClientName( bstr); ::SysFreeString(bstr); WCHAR p[128]; swprintf(p,L"Built:%S.%S", __DATE__,__TIME__); bstr = ::SysAllocString(p); hr = m_pClient->put_ClientCurVer( bstr); ::SysFreeString(bstr); if ( FAILED(hr) ) { // Advise failed DEBUG_PRINT(("Advise failed %x", hr )); SAFE_RELEASE(m_pClient); return -1; } // Initialize presence status DoSetPresence(RTCXS_PRESENCE_ONLINE); //////////// // // End RTC Functionality Code // //////////// // Show the logon dialog PostMessage(m_hWnd, WM_COMMAND, MAKEWPARAM(ID_FILE_LOGON, 0), 0); DEBUG_PRINT(("WINDOW CREATED")); return 0; } ///////////////////////////////////////////// // // CRTCWin::OnDestroy // LRESULT CRTCWin::OnDestroy(UINT uMsg, WPARAM wParam, LPARAM lParam) { // WM_DESTROY has three parameters. We will pass them to our Destroy Proc for future use // They are not currently used. UNREFERENCED_PARAMETER(wParam); UNREFERENCED_PARAMETER(lParam); UNREFERENCED_PARAMETER(uMsg); // Release the RTC profile SAFE_RELEASE(m_pProfile); // Cleanup the buddy list ClearBuddyList(); //////////// // // Begin RTC Functionality Code // // This code demonstrates how to detach the event sink and shutdown the client. // This should be called after we receive the IRTCClientEvent of type RTCCET_ASYNC_CLEANUP_DONE. // //////////// if (m_pClient) { if (m_pEvents) { // Unadvise for events from the RTC client m_pEvents->Unadvise(m_pClient); m_pEvents = NULL; } // Shutdown the RTC client m_pClient->Shutdown(); // Release the RTC client SAFE_RELEASE(m_pClient); } //////////// // // End RTC Functionality Code // //////////// DEBUG_PRINT(("WINDOW DESTROYED")); return 0; } ///////////////////////////////////////////// // // CRTCWin::OnClose // LRESULT CRTCWin::OnClose(UINT uMsg, WPARAM wParam, LPARAM lParam) { // WM_CLOSE has three parameters. We will pass them to our Close Proc for future use // They are not currently used. UNREFERENCED_PARAMETER(wParam); UNREFERENCED_PARAMETER(lParam); UNREFERENCED_PARAMETER(uMsg); HRESULT hr = S_OK; DEBUG_PRINT(("WINDOW CLOSED")); // Cleanup the existing session windows CleanupSessions(); // Cleanup the user search windows CleanupUserSearches(); // Cleanup the watcher windows CleanupWatchers(); //////////// // // Begin RTC Functionality Code // // This code demonstrates how to prepare the client for shutdown. // This should be called before the Shutdown method on the client. // //////////// if (m_pClient) { // Prepare the RTC client object for shutdown hr = m_pClient->PrepareForShutdown(); } if (!m_pClient || FAILED(hr)) { // The RTC client object either doesn't exist, or // failed to prepare for shutdown. Destroy the // window now DestroyWindow(m_hWnd); } else { // The RTC client object is preparing to shutdown. // We should wait for the RTCCET_ASYNC_CLEANUP_DONE // event before we shutdown the RTC client. For now // just hide the window ShowWindow(m_hWnd, SW_HIDE); } //////////// // // End RTC Functionality Code // //////////// return 0; } ///////////////////////////////////////////// // // CRTCWin::OnSize // LRESULT CRTCWin::OnSize(UINT uMsg, WPARAM wParam, LPARAM lParam) { RECT rcWnd, rcStatusBar, rcBuddyList; const int SIZE_EDGE = 5; GetClientRect(m_hWnd, &rcWnd); // Resize the status bar SendMessage(m_hStatusBar, uMsg, wParam, lParam); GetClientRect(m_hStatusBar, &rcStatusBar); // Resize the buddy list rcBuddyList.bottom = rcWnd.bottom - (rcStatusBar.bottom - rcStatusBar.top) - SIZE_EDGE; rcBuddyList.top = rcWnd.top + SIZE_EDGE; rcBuddyList.right = rcWnd.right - SIZE_EDGE; rcBuddyList.left = rcWnd.left + SIZE_EDGE; MoveWindow( m_hBuddyTree, rcBuddyList.left, rcBuddyList.top, (rcBuddyList.right - rcBuddyList.left), (rcBuddyList.bottom - rcBuddyList.top), TRUE); return 0; } ///////////////////////////////////////////// // // CRTCWin::OnCommand // LRESULT CRTCWin::OnCommand(UINT uMsg, WPARAM wParam, LPARAM lParam) { // WM_COMMAND has three parameters. We will pass them to our Command Proc for future use // They are not all currently used. UNREFERENCED_PARAMETER(lParam); UNREFERENCED_PARAMETER(uMsg); HRESULT hr; switch(LOWORD(wParam)) { case ID_FILE_LOGON: { DEBUG_PRINT(("ID_FILE_LOGON")); BSTR bstrURI = NULL; BSTR bstrServer = NULL; BSTR bstrTransport = NULL; hr = ShowLogonDialog( m_hWnd, &bstrURI, &bstrServer, &bstrTransport); if (FAILED(hr)) { // ShowLogonDialog failed DEBUG_PRINT(("ShowLogonDialog failed %x", hr )); break; } DEBUG_PRINT(("URI [%ws]", bstrURI )); DEBUG_PRINT(("SERVER [%ws]", bstrServer )); DEBUG_PRINT(("TRANSPORT [%ws]", bstrTransport )); DoLogOn(bstrURI, bstrServer, bstrTransport); SAFE_FREE_STRING(bstrURI); SAFE_FREE_STRING(bstrServer); SAFE_FREE_STRING(bstrTransport); } break; case ID_FILE_LOGOFF: DEBUG_PRINT(("ID_FILE_LOGOFF")); DoLogOff(); break; case ID_FILE_EXIT: DEBUG_PRINT(("ID_FILE_EXIT")); PostMessage(m_hWnd, WM_CLOSE, 0, 0); break; case ID_ACTION_ADDBUDDY: { DEBUG_PRINT(("ID_ACTION_ADDBUDDY")); BSTR bstrURI = NULL; BSTR bstrName = NULL; // Show the add buddy dialog hr = ShowAddressDialog(m_hWnd, L"Add Buddy", &bstrURI, &bstrName); if (FAILED(hr)) { // ShowAddressDialog failed DEBUG_PRINT(("ShowAddressDialog failed %x", hr )); break; } // Add the buddy DoAddBuddy(bstrURI, bstrName); SAFE_FREE_STRING(bstrURI); SAFE_FREE_STRING(bstrName); } break; case ID_ACTION_CALL: { DEBUG_PRINT(("ID_ACTION_CALL")); BSTR bstrURI = NULL; // Show the call dialog hr = ShowAddressDialog(m_hWnd, L"Call To", &bstrURI, NULL); if (FAILED(hr)) { // ShowAddressDialog failed DEBUG_PRINT(("ShowAddressDialog failed %x", hr )); break; } // Call the user DoCall(RTCST_PC_TO_PC, bstrURI, NULL); SAFE_FREE_STRING(bstrURI); } break; case ID_ACTION_MESSAGE: { DEBUG_PRINT(("ID_ACTION_MESSAGE")); BSTR bstrURI = NULL; // Show the call dialog hr = ShowAddressDialog(m_hWnd, L"Message To", &bstrURI, NULL); if (FAILED(hr)) { // ShowAddressDialog failed DEBUG_PRINT(("ShowAddressDialog failed %x", hr )); break; } // Send a message to the user DoCall(RTCST_MULTIPARTY_IM, bstrURI, NULL); SAFE_FREE_STRING(bstrURI); } break; case ID_TOOLS_TUNINGWIZARD: DEBUG_PRINT(("ID_TOOLS_TUNINGWIZARD")); DoTuningWizard(); break; case ID_TOOLS_USERSEARCH: DEBUG_PRINT(("ID_TOOLS_USERSEARCH")); AddUserSearch(); break; case ID_TOOLS_WATCHERS: DEBUG_PRINT(("ID_TOOLS_WATCHERS")); AddWatchers(); break; case ID_TOOLS_GROUPS: DEBUG_PRINT(("ID_TOOLS_GROUPS")); AddGroups(); break; case ID_TOOLS_OPTIONS: DEBUG_PRINT(("ID_TOOLS_OPTIONS")); DoOptions(); break; case ID_TOOLS_DTMFDIALPAD: DEBUG_PRINT(("ID_TOOLS_DTMFDIALPAD")); DoDTMFDialpad(); break; case ID_FILE_PRESENCESTATUS_OFFLINE: DEBUG_PRINT(("ID_FILE_PRESENCESTATUS_OFFLINE")); DoSetPresence(RTCXS_PRESENCE_OFFLINE); break; case ID_FILE_PRESENCESTATUS_ONLINE: DEBUG_PRINT(("ID_FILE_PRESENCESTATUS_ONLINE")); DoSetPresence(RTCXS_PRESENCE_ONLINE); break; case ID_FILE_PRESENCESTATUS_AWAY: DEBUG_PRINT(("ID_FILE_PRESENCESTATUS_AWAY")); DoSetPresence(RTCXS_PRESENCE_AWAY); break; case ID_FILE_PRESENCESTATUS_IDLE: DEBUG_PRINT(("ID_FILE_PRESENCESTATUS_IDLE")); DoSetPresence(RTCXS_PRESENCE_IDLE); break; case ID_FILE_PRESENCESTATUS_BUSY: DEBUG_PRINT(("ID_FILE_PRESENCESTATUS_BUSY")); DoSetPresence(RTCXS_PRESENCE_BUSY); break; case ID_FILE_PRESENCESTATUS_BERIGHTBACK: DEBUG_PRINT(("ID_FILE_PRESENCESTATUS_BERIGHTBACK")); DoSetPresence(RTCXS_PRESENCE_BE_RIGHT_BACK); break; case ID_FILE_PRESENCESTATUS_ONTHEPHONE: DEBUG_PRINT(("ID_FILE_PRESENCESTATUS_ONTHEPHONE")); DoSetPresence(RTCXS_PRESENCE_ON_THE_PHONE); break; case ID_FILE_PRESENCESTATUS_OUTTOLUNCH: DEBUG_PRINT(("ID_FILE_PRESENCESTATUS_OUTTOLUNCH")); DoSetPresence(RTCXS_PRESENCE_OUT_TO_LUNCH); break; } return 0; } ///////////////////////////////////////////// // // CRTCWin::OnNotify // LRESULT CRTCWin::OnNotify(UINT uMsg, WPARAM wParam, LPARAM lParam) { // WM_NOTIFY has three parameters. We will pass them to our Notify Proc for future use // They are not currently used. UNREFERENCED_PARAMETER(uMsg); int idCtrl = (int)wParam; LPNMHDR pnmh = (LPNMHDR)lParam; HRESULT hr; if (pnmh->code == NM_RCLICK) { if ( idCtrl == IDC_BUDDYTREE ) { // The user clicked on the buddy list TVHITTESTINFO tvht; ZeroMemory(&tvht, sizeof(TVHITTESTINFO)); POINT pt; GetCursorPos(&pt); tvht.pt = pt; MapWindowPoints(NULL, pnmh->hwndFrom, &tvht.pt, 1 ); HTREEITEM htriRes = TreeView_HitTest(pnmh->hwndFrom, &tvht); if (htriRes == NULL) { // TreeView_HitTest failed return 0; } if (tvht.flags & TVHT_ONITEM) { // The user clicked on a buddy TVITEMEX tvi; ZeroMemory(&tvi, sizeof(TVITEM)); tvi.mask = TVIF_PARAM; tvi.hItem = htriRes; // Get the buddy item if (!TreeView_GetItem(m_hBuddyTree, &tvi)) { // TreeView_GetItem failed; return 0; } if (tvi.lParam == NULL) { // We're on a parent, not a buddy. Return. return 0; } IRTCBuddy * pBuddy = (IRTCBuddy *)(tvi.lParam); // Get the buddy URI BSTR bstrURI = NULL; hr = pBuddy->get_PresentityURI(&bstrURI); if (FAILED(hr)) { // get_UserURI failed return 0; } // Get the buddy name BSTR bstrName = NULL; IRTCBuddy2 *pBuddy2; pBuddy->QueryInterface(__uuidof(IRTCBuddy2), (LPVOID *)&pBuddy2); hr = pBuddy2->get_PresenceProperty(RTCPP_DISPLAYNAME, &bstrName); SAFE_RELEASE(pBuddy2); if (FAILED(hr) && (hr != RTC_E_NOT_EXIST)) { // get_Name failed SAFE_FREE_STRING(bstrURI); return 0; } // Show the buddy menu HMENU hMenuRes = LoadMenu( GetModuleHandle(NULL), MAKEINTRESOURCE(IDR_MENU_BUDDY)); HMENU hMenu = GetSubMenu(hMenuRes, 0); // Show the popup menu UINT uID = TrackPopupMenu(hMenu, TPM_LEFTALIGN | TPM_RIGHTBUTTON | TPM_NONOTIFY | TPM_RETURNCMD, pt.x, pt.y, 0, m_hWnd, NULL); switch (uID) { case ID_BUDDY_CALL: DEBUG_PRINT(("ID_BUDDY_CALL")); // Call the buddy DoCall(RTCST_PC_TO_PC, bstrURI, bstrName); break; case ID_BUDDY_MESSAGE: DEBUG_PRINT(("ID_BUDDY_MESSAGE")); // Send a message to the buddy DoCall(RTCST_MULTIPARTY_IM, bstrURI, bstrName); break; case ID_BUDDY_REFRESH: DEBUG_PRINT(("ID_BUDDY_REFRESH")); // Refresh the buddy DoRefreshBuddy(pBuddy); break; case ID_BUDDY_REMOVE: DEBUG_PRINT(("ID_BUDDY_REMOVE")); // Remove the buddy if (SUCCEEDED(DoRemoveBuddy(pBuddy))) { // Release the buddy reference SAFE_RELEASE(pBuddy); // Delete the buddy from the tree TreeView_DeleteItem(m_hBuddyTree, htriRes); } break; case ID_BUDDY_PROPERTIES: DEBUG_PRINT(("ID_BUDDY_PROPERTIES")); //Display Presence Property Dialog DoBuddyProperties(pBuddy); break; } SAFE_FREE_STRING(bstrURI); } } } return 0; } ///////////////////////////////////////////// // // CRTCWin::OnRTCEvent // LRESULT CRTCWin::OnRTCEvent(UINT uMsg, WPARAM wParam, LPARAM lParam) { // WM_RTC_EVENT has three parameters. We will pass them to our Event Handler Proc for future use // They are not all currently used. UNREFERENCED_PARAMETER(uMsg); //////////// // // Begin RTC Functionality Code // // This code demonstrates how to receive a particular event object from the IDispatch object. // The event object is queried based on the value of the RTC_EVENT enumeration value. // //////////// IDispatch * pDisp = (IDispatch *)lParam; RTC_EVENT enEvent = (RTC_EVENT)wParam; HRESULT hr; // Based on the RTC_EVENT type, query for the // appropriate event interface and call a helper // method to handle the event switch ( enEvent ) { case RTCE_REGISTRATION_STATE_CHANGE: { IRTCRegistrationStateChangeEvent * pEvent = NULL; hr = pDisp->QueryInterface( __uuidof(IRTCRegistrationStateChangeEvent), (void **)&pEvent ); if (SUCCEEDED(hr)) { OnRTCRegistrationStateChangeEvent(pEvent); SAFE_RELEASE(pEvent); } } break; case RTCE_SESSION_STATE_CHANGE: { IRTCSessionStateChangeEvent * pEvent = NULL; hr = pDisp->QueryInterface( __uuidof(IRTCSessionStateChangeEvent), (void **)&pEvent ); if (SUCCEEDED(hr)) { OnRTCSessionStateChangeEvent(pEvent); SAFE_RELEASE(pEvent); } } break; case RTCE_PARTICIPANT_STATE_CHANGE: { IRTCParticipantStateChangeEvent * pEvent = NULL; hr = pDisp->QueryInterface( __uuidof(IRTCParticipantStateChangeEvent), (void **)&pEvent ); if (SUCCEEDED(hr)) { OnRTCParticipantStateChangeEvent(pEvent); SAFE_RELEASE(pEvent); } } break; case RTCE_MESSAGING: { IRTCMessagingEvent * pEvent = NULL; hr = pDisp->QueryInterface( __uuidof(IRTCMessagingEvent), (void **)&pEvent ); if (SUCCEEDED(hr)) { OnRTCMessagingEvent(pEvent); SAFE_RELEASE(pEvent); } } break; case RTCE_MEDIA: { IRTCMediaEvent * pEvent = NULL; hr = pDisp->QueryInterface( __uuidof(IRTCMediaEvent), (void **)&pEvent ); if (SUCCEEDED(hr)) { OnRTCMediaEvent(pEvent); SAFE_RELEASE(pEvent); } } break; case RTCE_MEDIA_REQUEST: { IRTCMediaRequestEvent *pEvent = NULL; hr = pDisp->QueryInterface( __uuidof(IRTCMediaRequestEvent), (void **) &pEvent); if (SUCCEEDED(hr)) { OnRTCMediaRequestEvent(pEvent); SAFE_RELEASE(pEvent); } } break; case RTCE_INTENSITY: { IRTCIntensityEvent * pEvent = NULL; hr = pDisp->QueryInterface( __uuidof(IRTCIntensityEvent), (void **)&pEvent ); if (SUCCEEDED(hr)) { OnRTCIntensityEvent(pEvent); SAFE_RELEASE(pEvent); } } break; case RTCE_CLIENT: { IRTCClientEvent * pEvent = NULL; hr = pDisp->QueryInterface( __uuidof(IRTCClientEvent), (void **)&pEvent ); if (SUCCEEDED(hr)) { OnRTCClientEvent(pEvent); SAFE_RELEASE(pEvent); } } break; case RTCE_BUDDY: { IRTCBuddyEvent2 * pEvent = NULL; hr = pDisp->QueryInterface( __uuidof(IRTCBuddyEvent2), (void **)&pEvent ); if (SUCCEEDED(hr)) { OnRTCBuddyEvent(pEvent); SAFE_RELEASE(pEvent); } } break; case RTCE_WATCHER: { IRTCWatcherEvent2 * pEvent = NULL; hr = pDisp->QueryInterface( __uuidof(IRTCWatcherEvent2), (void **)&pEvent ); if (SUCCEEDED(hr)) { OnRTCWatcherEvent(pEvent); SAFE_RELEASE(pEvent); } } break; case RTCE_GROUP: { IRTCBuddyGroupEvent * pEvent = NULL; hr = pDisp->QueryInterface( __uuidof(IRTCBuddyGroupEvent), (void **)&pEvent ); if (SUCCEEDED(hr)) { OnRTCBuddyGroupEvent(pEvent); SAFE_RELEASE(pEvent); } } break; case RTCE_USERSEARCH: { IRTCUserSearchResultsEvent * pEvent = NULL; hr = pDisp->QueryInterface( __uuidof(IRTCUserSearchResultsEvent), (void **)&pEvent ); if (SUCCEEDED(hr)) { OnRTCUserSearchResultsEvent(pEvent); SAFE_RELEASE(pEvent); } } break; case RTCE_ROAMING: { IRTCRoamingEvent * pEvent = NULL; hr = pDisp->QueryInterface( __uuidof(IRTCRoamingEvent), (void **)&pEvent ); if (SUCCEEDED(hr)) { OnRTCRoamingEvent(pEvent); SAFE_RELEASE(pEvent); } } break; case RTCE_PROFILE: { IRTCProfileEvent2 * pEvent = NULL; hr = pDisp->QueryInterface( __uuidof(IRTCProfileEvent2), (void **)&pEvent ); if (SUCCEEDED(hr)) { OnRTCProfileEvent(pEvent); SAFE_RELEASE(pEvent); } } break; case RTCE_PRESENCE_PROPERTY: { IRTCPresencePropertyEvent * pEvent = NULL; hr = pDisp->QueryInterface( __uuidof(IRTCPresencePropertyEvent), (void **)&pEvent ); if (SUCCEEDED(hr)) { OnRTCPresencePropertyEvent(pEvent); SAFE_RELEASE(pEvent); } } break; case RTCE_PRESENCE_DATA: { IRTCPresenceDataEvent * pEvent = NULL; hr = pDisp->QueryInterface( __uuidof(IRTCPresenceDataEvent), (void **)&pEvent ); if (SUCCEEDED(hr)) { OnRTCPresenceDataEvent(pEvent); SAFE_RELEASE(pEvent); } } break; case RTCE_PRESENCE_STATUS: { IRTCPresenceStatusEvent * pEvent = NULL; hr = pDisp->QueryInterface( __uuidof(IRTCPresenceStatusEvent), (void **)&pEvent ); if (SUCCEEDED(hr)) { OnRTCPresenceStatusEvent(pEvent); SAFE_RELEASE(pEvent); } } break; } // Release the event SAFE_RELEASE(pDisp); //////////// // // End RTC Functionality Code // //////////// return 0; } ///////////////////////////////////////////// // // CRTCWin::OnRTCRegistrationStateChangeEvent // void CRTCWin::OnRTCRegistrationStateChangeEvent( IRTCRegistrationStateChangeEvent *pEvent ) { HRESULT hr; //////////// // // Begin RTC Functionality Code // // This code demonstrates how to handle a Registration State Change event. // This event occurs when our registration state has changed. For example, this may occur // when we EnableProfileEx(), or we are successfully registered, or logged off from the server. // //////////// // Get the registration state RTC_REGISTRATION_STATE enState; long lStatusCode; hr = pEvent->get_State(&enState); if (FAILED(hr)) { // get_State failed DEBUG_PRINT(("get_State failed %x", hr)); return; } // Get the status code hr = pEvent->get_StatusCode(&lStatusCode); if (FAILED(hr)) { // get_StatusCode failed DEBUG_PRINT(("get_StatusCode failed %x", hr)); return; } hr = lStatusCode; switch(enState) { case RTCRS_UNREGISTERING: DEBUG_PRINT(("RTCRS_UNREGISTERING %x", hr)); // Logoff in progress OnLoggingOff(); break; case RTCRS_NOT_REGISTERED: DEBUG_PRINT(("RTCRS_NOT_REGISTERED %x", hr)); // Logged off OnLoggedOff(); break; case RTCRS_REGISTERING: DEBUG_PRINT(("RTCRS_REGISTERING %x", hr)); // Logon in progress OnLoggingOn(); break; case RTCRS_REGISTERED: DEBUG_PRINT(("RTCRS_REGISTERED %x", hr)); // Logged on OnLoggedOn(); break; case RTCRS_REJECTED: case RTCRS_ERROR: { DEBUG_PRINT(("RTCRS_REJECTED/ERROR %x", hr)); // Logon failed. Most likely the server could no be found, // or the user needs to authenticate. // Check if we need to authenticate if (m_nLogonAttemptCount < 3 && ((hr == RTC_E_STATUS_CLIENT_FORBIDDEN) || (hr == RTC_E_STATUS_CLIENT_UNAUTHORIZED) || (hr == RTC_E_STATUS_CLIENT_PROXY_AUTHENTICATION_REQUIRED))) { m_nLogonAttemptCount++; BSTR bstrURI = NULL; BSTR bstrAccount = NULL; BSTR bstrPassword = NULL; BSTR bstrRealm = NULL; BSTR bstrServer = NULL; BSTR bstrTransport = NULL; hr = m_pProfile->get_Realm(&bstrRealm); if (FAILED(hr)) { // get_Realm failed DEBUG_PRINT(("get_Realm failed %x", hr)); } // Display the authentication dialog hr = ShowAuthDialog(m_hWnd, bstrRealm, &bstrURI, &bstrAccount, &bstrPassword, &bstrServer, &bstrTransport); DEBUG_PRINT(("URI [%ws]", bstrURI )); DEBUG_PRINT(("ACCOUNT [%ws]", bstrAccount )); //DEBUG_PRINT(("PASSWORD [%ws]", bstrPassword )); DEBUG_PRINT(("REALM [%ws]", bstrRealm )); DEBUG_PRINT(("SERVER [%ws]", bstrServer )); DEBUG_PRINT(("TRANSPORT [%ws]", bstrTransport )); SAFE_FREE_STRING(bstrRealm); SAFE_FREE_STRING(bstrServer); SAFE_FREE_STRING(bstrTransport); if (FAILED(hr)) { // ShowAuthDialog failed DEBUG_PRINT(("ShowAuthDialog failed %x", hr)); DoLogOff(); OnLoggedOff(); ShowMessageBox(L"Logon failed!"); return; } // Do the authentication hr = DoAuth(bstrURI, bstrAccount, bstrPassword); SAFE_FREE_STRING(bstrURI); SAFE_FREE_STRING(bstrAccount); SAFE_FREE_STRING(bstrPassword); if (FAILED(hr)) { // DoAuth failed DEBUG_PRINT(("DoAuth failed %x", hr)); DoLogOff(); OnLoggedOff(); ShowMessageBox(L"Logon failed!"); return; } } else { // Logon failed DoLogOff(); OnLoggedOff(); // If we were logging on the show error if (m_enState == RTCRS_REGISTERING) { ShowMessageBox(L"Logon failed!"); } return; } } break; case RTCRS_LOGGED_OFF: DEBUG_PRINT(("RTCRS_LOGGED_OFF %x", hr)); // The user logged on at another client // The user is logged off from this client ShowMessageBox(L"The Server has logged you off (Perhaps you logged in from another location)"); DoLogOff(); OnLoggedOff(); break; case RTCRS_LOCAL_PA_LOGGED_OFF: DEBUG_PRINT(("RTCRS_LOCAL_PA_LOGGED_OFF %x", hr)); // The user logged on at another client // The user's presence state is no longer sent from this client SetStatusText(L"Logged on (Presence disabled)"); break; case RTCRS_REMOTE_PA_LOGGED_OFF: DEBUG_PRINT(("RTCRS_REMOTE_PA_LOGGED_OFF %x", hr)); // The user logged off on another client that was sending his // presence state. We can ignore this. break; } m_enState = enState; //////////// // // End RTC Functionality Code // //////////// } ///////////////////////////////////////////// // // CRTCWin::OnRTCSessionStateChangeEvent // void CRTCWin::OnRTCSessionStateChangeEvent( IRTCSessionStateChangeEvent *pEvent ) { //////////// // // Begin RTC Functionality Code // // This code demonstrates how to handle a Session State Change event. // This event occurs when our session state has changed. For example, this may occur // when we AddParticipant() to a Session, or we Terminate() a session. // //////////// IRTCSession * pSession = NULL; CRTCSession * pSessWindow = NULL; RTC_SESSION_STATE enState; HRESULT hr; hr = pEvent->get_State(&enState); if (FAILED(hr)) { // get_State failed return; } hr = pEvent->get_Session(&pSession); if (FAILED(hr)) { // get_Session failed return; } // Is this session in our session list? hr = FindSession(pSession, &pSessWindow); if (FAILED(hr)) { // FindSession failed if (enState == RTCSS_INCOMING) { // This is a new session RTC_SESSION_TYPE enType; hr = pSession->get_Type(&enType); if (FAILED(hr)) { // get_Type failed SAFE_RELEASE(pSession); return; } if (enType == RTCST_PC_TO_PC || enType == RTCST_PC_TO_PHONE) { // This is an AV call if (CRTCAVSession::m_Singleton != NULL) { // If another AV call is in progress, then // we are already busy. pSession->Terminate(RTCTR_BUSY); SAFE_RELEASE(pSession); return; } // Get the participant object IRTCEnumParticipants * pEnum = NULL; IRTCParticipant * pParticipant = NULL; hr = pSession->EnumerateParticipants(&pEnum); if (FAILED(hr)) { // EnumerateParticipants failed SAFE_RELEASE(pSession); return; } hr = pEnum->Next(1, &pParticipant, NULL); SAFE_RELEASE(pEnum); if (hr != S_OK) { // Next failed SAFE_RELEASE(pSession); return; } // Get the participant URI BSTR bstrURI = NULL; hr = pParticipant->get_UserURI(&bstrURI); if (FAILED(hr)) { // get_UserURI failed SAFE_RELEASE(pSession); SAFE_RELEASE(pParticipant); return; } // Get the participant name BSTR bstrName = NULL; hr = pParticipant->get_Name(&bstrName); SAFE_RELEASE(pParticipant); if (FAILED(hr) && (hr != RTC_E_NOT_EXIST)) { // get_Name failed SAFE_FREE_STRING(bstrURI); SAFE_RELEASE(pSession); return; } // Ring the bell m_pClient->PlayRing(RTCRT_PHONE, VARIANT_TRUE); // Show the session dialog BOOL fAccept; hr = ShowSessionDialog(m_hWnd, bstrName, bstrURI, &fAccept); SAFE_FREE_STRING(bstrURI); SAFE_FREE_STRING(bstrName); if (FAILED(hr)) { // ShowSessionDialog failed SAFE_RELEASE(pSession); return; } if (fAccept) { // Accept the session hr = pSession->Answer(); if (FAILED(hr)) { // Answer failed SAFE_RELEASE(pSession); return; } } else { // Reject the session pSession->Terminate(RTCTR_REJECT); SAFE_RELEASE(pSession); return; } } else { // This is an IM call m_pClient->PlayRing(RTCRT_MESSAGE, VARIANT_TRUE); } // Add the session to the session list // This will create the session window hr = AddSession(pSession, enType); if (FAILED(hr)) { // AddSession failed SAFE_RELEASE(pSession); return; } } SAFE_RELEASE(pSession); return; } SAFE_RELEASE(pSession); //////////// // // End RTC Functionality Code // //////////// // Deliver the session state to the session window pSessWindow->DeliverSessionState(enState); } ///////////////////////////////////////////// // // CRTCWin::OnRTCParticipantStateChangeEvent // void CRTCWin::OnRTCParticipantStateChangeEvent( IRTCParticipantStateChangeEvent *pEvent ) { //////////// // // Begin RTC Functionality Code // // This code demonstrates how to handle a Participant State Change event. // This event occurs when our registration state has changed. For example, this may occur // when we AddParticipant() or RemoveParticipant() on a Session, or a Participant leaves a Session. // //////////// IRTCSession * pSession = NULL; CRTCSession * pSessWindow = NULL; IRTCParticipant * pParticipant = NULL; RTC_PARTICIPANT_STATE enState; HRESULT hr; hr = pEvent->get_Participant(&pParticipant); if (FAILED(hr)) { // get_Participant failed return; } hr = pParticipant->get_Session(&pSession); if (FAILED(hr)) { // get_Session failed SAFE_RELEASE(pParticipant); return; } hr = FindSession(pSession, &pSessWindow); SAFE_RELEASE(pSession); if (FAILED(hr)) { // FindSession failed SAFE_RELEASE(pParticipant); return; } // Get the participant state hr = pEvent->get_State(&enState); if (FAILED(hr)) { // get_State failed SAFE_RELEASE(pParticipant); return; } // Deliver the participant state to the session window pSessWindow->DeliverParticipantState(pParticipant, enState); //////////// // // End RTC Functionality Code // //////////// SAFE_RELEASE(pParticipant); } ///////////////////////////////////////////// // // CRTCWin::OnRTCMessagingEvent // void CRTCWin::OnRTCMessagingEvent( IRTCMessagingEvent *pEvent ) { //////////// // // Begin RTC Functionality Code // // This code demonstrates how to handle a Messaging Event. // This event occurs when we receive a message. This may be a either an instant message // or a message status message. // //////////// IRTCSession * pSession = NULL; CRTCSession * pSessWindow = NULL; IRTCParticipant * pParticipant = NULL; RTC_MESSAGING_EVENT_TYPE enType; RTC_MESSAGING_USER_STATUS enStatus; BSTR bstrContentType = NULL; BSTR bstrMessage = NULL; HRESULT hr; hr = pEvent->get_Session(&pSession); if (FAILED(hr)) { // get_Session failed return; } hr = FindSession(pSession, &pSessWindow); SAFE_RELEASE(pSession); if (FAILED(hr)) { // FindSession failed return; } hr = pEvent->get_EventType(&enType); if (FAILED(hr)) { // get_EventType failed return; } hr = pEvent->get_Participant(&pParticipant); if (FAILED(hr)) { // get_Participant failed return; } if (enType == RTCMSET_MESSAGE) { hr = pEvent->get_MessageHeader(&bstrContentType); if (FAILED(hr)) { // get_MessageHeader failed SAFE_RELEASE(pParticipant); return; } hr = pEvent->get_Message(&bstrMessage); if (FAILED(hr)) { // get_Message failed SAFE_RELEASE(pParticipant); SAFE_FREE_STRING(bstrContentType); return; } // Deliver the message to the session window pSessWindow->DeliverMessage(pParticipant, bstrContentType, bstrMessage); SAFE_FREE_STRING(bstrContentType); SAFE_FREE_STRING(bstrMessage); } else if (enType == RTCMSET_STATUS) { hr = pEvent->get_UserStatus(&enStatus); if (FAILED(hr)) { // get_UserStatus failed return; } // Deliver the user status to the session window pSessWindow->DeliverUserStatus(pParticipant, enStatus); } SAFE_RELEASE(pParticipant); //////////// // // End RTC Functionality Code // //////////// } ///////////////////////////////////////////// // // CRTCWin::OnRTCMediaEvent // void CRTCWin::OnRTCMediaEvent( IRTCMediaEvent *pEvent ) { //////////// // // Begin RTC Functionality Code // // This code demonstrates how to handle a Media Event. // This event occurs when our media status changes. For example, this may occur // when we Add or Remove audio, video, or T120 streams. // //////////// long lMediaType; RTC_MEDIA_EVENT_TYPE enType; RTC_MEDIA_EVENT_REASON enReason; HRESULT hr; hr = pEvent->get_MediaType(&lMediaType); if (FAILED(hr)) { // get_MediaType failed return; } hr = pEvent->get_EventType(&enType); if (FAILED(hr)) { // get_EventType failed return; } hr = pEvent->get_EventReason(&enReason); if (FAILED(hr)) { // get_EventReason failed return; } if (CRTCAVSession::m_Singleton != NULL) { // Deliver the media state to the session window (CRTCAVSession::m_Singleton)->DeliverMedia(lMediaType, enType, enReason); } //////////// // // End RTC Functionality Code // //////////// } ///////////////////////////////////////////// // // CRTCWin::OnRTCMediaEvent // void CRTCWin::OnRTCMediaRequestEvent( IRTCMediaRequestEvent *pEvent ) { long lCurMediaType; long lProposedMediaType; HRESULT hr; hr = pEvent->get_CurrentMedia(&lCurMediaType); if( FAILED(hr)) return; hr = pEvent->get_ProposedMedia(&lProposedMediaType); if( FAILED(hr)) return; //TODO: add code to prompt for Media Request Event; pEvent->Accept(lProposedMediaType); return; } ///////////////////////////////////////////// // // CRTCWin::OnRTCIntensityEvent // void CRTCWin::OnRTCIntensityEvent( IRTCIntensityEvent *pEvent ) { //////////// // // Begin RTC Functionality Code // // This code demonstrates how to handle an Intensity Event. // This event occurs when the volume is adjusted by Automatic Gain Control, // or when the user changes the volume. // //////////// RTC_AUDIO_DEVICE enDevice; long lLevel, lMin, lMax; HRESULT hr; hr = pEvent->get_Direction(&enDevice); if (FAILED(hr)) { // get_Direction failed return; } hr = pEvent->get_Level(&lLevel); if (FAILED(hr)) { // get_Level failed return; } hr = pEvent->get_Min(&lMin); if (FAILED(hr)) { // get_Min failed return; } hr = pEvent->get_Max(&lMax); if (FAILED(hr)) { // get_Max failed return; } // Normalize level to between zero and 100 if ((lMax - lMin) == 0) { lLevel = 0; } else { lLevel = (lLevel - lMin) * 100 / (lMax - lMin); } if (CRTCAVSession::m_Singleton != NULL) { // Deliver the intensity state to the session window (CRTCAVSession::m_Singleton)->DeliverIntensity(enDevice, lLevel); } //////////// // // End RTC Functionality Code // //////////// } ///////////////////////////////////////////// // // CRTCWin::OnRTCClientEvent // void CRTCWin::OnRTCClientEvent( IRTCClientEvent *pEvent ) { //////////// // // Begin RTC Functionality Code // // This code demonstrates how to handle a Client Event. // This event occurs when our IP Address changes, Network Quality Changes, or ... // //////////// HRESULT hr; // Get the client event tyoe RTC_CLIENT_EVENT_TYPE enEventType; hr = pEvent->get_EventType(&enEventType); if (FAILED(hr)) { // get_EventType failed return; } if ( enEventType == RTCCET_ASYNC_CLEANUP_DONE ) { // The RTC client has finished preparing for // shutdown. Destroy the window now. DestroyWindow(m_hWnd); } else { if (CRTCAVSession::m_Singleton != NULL) { // Deliver the client state to the session window (CRTCAVSession::m_Singleton)->DeliverClient(enEventType); } } //////////// // // End RTC Functionality Code // //////////// } ///////////////////////////////////////////// // // CRTCWin::OnRTCBuddyEvent // void CRTCWin::OnRTCBuddyEvent( IRTCBuddyEvent2 *pEvent ) { //////////// // // Begin RTC Functionality Code // // This code demonstrates how to handle a Buddy Event. // This event occurs when our buddy's state is changed, the subscription state changes, // a buddy is added/removed, a buddy's attributes are updated, or a buddy is roamed. // //////////// HRESULT hr; RTC_BUDDY_EVENT_TYPE enType; long lStatus; hr = pEvent->get_EventType(&enType); if (FAILED(hr)) { // get_EventType failed DEBUG_PRINT(("get_EventType failed %x", hr )); return; } // Get the status hr = pEvent->get_StatusCode(&lStatus); if (FAILED(hr)) { // get_StatusCode failed DEBUG_PRINT(("get_StatusCode failed %x", hr )); return; } // Get the buddy object IRTCBuddy * pBuddy = NULL; hr = pEvent->get_Buddy(&pBuddy); if (FAILED(hr)) { // get_Buddy failed DEBUG_PRINT(("get_Buddy failed %x", hr )); return; } switch (enType) { case RTCBET_BUDDY_ADD: { DEBUG_PRINT(("RTCBET_BUDDY_ADD [%p] %x", pBuddy, lStatus )); if (SUCCEEDED(lStatus)) { // Update the buddy list entry UpdateBuddyList(pBuddy); } else { // Delete the buddy from the list ClearBuddyList(pBuddy); } } break; case RTCBET_BUDDY_REMOVE: { DEBUG_PRINT(("RTCBET_BUDDY_REMOVE [%p] %x", pBuddy, lStatus )); if (SUCCEEDED(lStatus)) { // Delete the buddy from the list ClearBuddyList(pBuddy); } else { // Update the buddy list entry UpdateBuddyList(pBuddy); } } break; case RTCBET_BUDDY_UPDATE: { DEBUG_PRINT(("RTCBET_BUDDY_UPDATE [%p] %x", pBuddy, lStatus )); // Update the buddy list entry UpdateBuddyList(pBuddy); } break; case RTCBET_BUDDY_SUBSCRIBED: { if (FAILED(lStatus)) UpdateBuddyList(pBuddy); } break; case RTCBET_BUDDY_STATE_CHANGE: { DEBUG_PRINT(("RTCBET_BUDDY_STATE_CHANGE [%p] %x", pBuddy, lStatus )); // Update the buddy list entry UpdateBuddyList(pBuddy); } break; } SAFE_RELEASE(pBuddy); //////////// // // End RTC Functionality Code // //////////// } ///////////////////////////////////////////// // // CRTCWin::OnRTCWatcherEvent // void CRTCWin::OnRTCWatcherEvent( IRTCWatcherEvent2 *pEvent ) { //////////// // // Begin RTC Functionality Code // // This code demonstrates how to handle a Watcher Event. // This event occurs when our watcher's state is changed, // a watcher is added/removed, a watcher's attributes are updated, or a watcher is roamed. // //////////// HRESULT hr; RTC_WATCHER_EVENT_TYPE enType; long lStatus; hr = pEvent->get_EventType(&enType); if (FAILED(hr)) { // get_EventType failed DEBUG_PRINT(("get_EventType failed %x", hr )); return; } // Get the status hr = pEvent->get_StatusCode(&lStatus); if (FAILED(hr)) { // get_StatusCode failed DEBUG_PRINT(("get_StatusCode failed %x", hr )); return; } // Get the watcher object IRTCWatcher * pWatcher = NULL; hr = pEvent->get_Watcher(&pWatcher); if (FAILED(hr)) { // get_Watcher failed DEBUG_PRINT(("get_Watcher failed %x", hr )); return; } switch (enType) { case RTCWET_WATCHER_ADD: DEBUG_PRINT(("RTCWET_WATCHER_ADD [%p] %x", pWatcher, lStatus )); break; case RTCWET_WATCHER_REMOVE: DEBUG_PRINT(("RTCWET_WATCHER_REMOVE [%p] %x", pWatcher, lStatus )); break; case RTCWET_WATCHER_UPDATE: DEBUG_PRINT(("RTCWET_WATCHER_UPDATE [%p] %x", pWatcher, lStatus )); break; case RTCWET_WATCHER_OFFERING: { DEBUG_PRINT(("RTCWET_WATCHER_OFFERING [%p] %x", pWatcher, lStatus )); // Get the watcher URI BSTR bstrURI = NULL; hr = pWatcher->get_PresentityURI(&bstrURI); if (FAILED(hr)) { // get_PresentityURI failed DEBUG_PRINT(("get_PresentityURI failed %x", hr )); SAFE_RELEASE(pWatcher); return; } // Get the watcher name BSTR bstrName = NULL; hr = pWatcher->get_Name(&bstrName); if (FAILED(hr) && (hr != RTC_E_NOT_EXIST)) { // get_Name failed DEBUG_PRINT(("get_Name failed %x", hr )); SAFE_FREE_STRING(bstrURI); SAFE_RELEASE(pWatcher); return; } // Show the incoming watcher dialog BOOL fAllow, fAddBuddy; hr = ShowWatcherDialog(m_hWnd, bstrName, bstrURI, &fAllow, &fAddBuddy); if (FAILED(hr)) { // ShowWatcherDialog failed DEBUG_PRINT(("ShowWatcherDialog failed %x", hr )); SAFE_FREE_STRING(bstrURI); SAFE_FREE_STRING(bstrName); SAFE_RELEASE(pWatcher); return; } // Set the watcher to be allowed or blocked hr = pWatcher->put_State(fAllow ? RTCWS_ALLOWED : RTCWS_BLOCKED); if (FAILED(hr)) { // put_State failed DEBUG_PRINT(("put_State failed %x", hr )); SAFE_FREE_STRING(bstrURI); SAFE_FREE_STRING(bstrName); SAFE_RELEASE(pWatcher); return; } // Shall we add the user as a buddy? if (fAddBuddy) { hr = DoAddBuddy(bstrURI, bstrName); if (FAILED(hr)) { // DoAddBuddy failed DEBUG_PRINT(("DoAddBuddy failed %x", hr )); SAFE_FREE_STRING(bstrURI); SAFE_FREE_STRING(bstrName); SAFE_RELEASE(pWatcher); return; } } SAFE_FREE_STRING(bstrURI); SAFE_FREE_STRING(bstrName); } break; } // Deliver events to the watcher windows std::vector<CRTCWatcher *>::iterator it; if (!m_WatchersList.empty()) { for(it=m_WatchersList.begin(); it < m_WatchersList.end(); it++) { (*it)->DeliverWatcher(pWatcher, enType, lStatus); } } SAFE_RELEASE(pWatcher); //////////// // // End RTC Functionality Code // //////////// } ///////////////////////////////////////////// // // CRTCWin::OnRTCBuddyGroupEvent // void CRTCWin::OnRTCBuddyGroupEvent( IRTCBuddyGroupEvent *pEvent ) { //////////// // // Begin RTC Functionality Code // // This code demonstrates how to handle a Buddy Group Event. // This event occurs when a group's state is changed, a buddy is added/removed from the group, // a group is added/removed, a group's attributes are updated, or the group is roamed. // //////////// HRESULT hr; RTC_GROUP_EVENT_TYPE enType; long lStatus; hr = pEvent->get_EventType(&enType); if (FAILED(hr)) { // get_EventType failed DEBUG_PRINT(("get_EventType failed %x", hr )); return; } // Get the status hr = pEvent->get_StatusCode(&lStatus); if (FAILED(hr)) { // get_StatusCode failed DEBUG_PRINT(("get_StatusCode failed %x", hr )); return; } // Get the group object IRTCBuddyGroup * pGroup = NULL; hr = pEvent->get_Group(&pGroup); if (FAILED(hr)) { // get_Group failed DEBUG_PRINT(("get_Group failed %x", hr )); return; } switch (enType) { case RTCGET_GROUP_ADD: DEBUG_PRINT(("RTCGET_GROUP_ADD [%p] %x", pGroup, lStatus )); break; case RTCGET_GROUP_REMOVE: DEBUG_PRINT(("RTCGET_GROUP_REMOVE [%p] %x", pGroup, lStatus )); break; case RTCGET_GROUP_UPDATE: DEBUG_PRINT(("RTCGET_GROUP_UPDATE [%p] %x", pGroup, lStatus )); break; } // Deliver events to the group windows std::vector<CRTCGroup *>::iterator it; if (!m_GroupsList.empty()) { for(it=m_GroupsList.begin(); it < m_GroupsList.end(); it++) { (*it)->DeliverGroup(pGroup, enType, lStatus); } } SAFE_RELEASE(pGroup); //////////// // // End RTC Functionality Code // //////////// } ///////////////////////////////////////////// // // CRTCWin::OnRTCUserSearchResultsEvent // void CRTCWin::OnRTCUserSearchResultsEvent( IRTCUserSearchResultsEvent *pEvent ) { //////////// // // Begin RTC Functionality Code // // This code demonstrates how to handle a User Search Results Event. // This event occurs when we receive results for a user search request. // //////////// CRTCSearch * pSearchWindow = NULL; IRTCEnumUserSearchResults * pEnum = NULL; LONG_PTR lCookie; long lStatus; HRESULT hr; // Get the search cookie hr = pEvent->get_Cookie(&lCookie); if (FAILED(hr)) { // get_Cookie failed DEBUG_PRINT(("get_Cookie failed %x", hr )); return; } // Find the search window hr = FindUserSearch(lCookie, &pSearchWindow); if (FAILED(hr)) { // FindUserSearch failed DEBUG_PRINT(("FindUserSearch failed %x", hr )); return; } // Get the search status hr = pEvent->get_StatusCode(&lStatus); if (FAILED(hr)) { // get_StatusCode failed DEBUG_PRINT(("get_StatusCode failed %x", hr )); return; } // Get the search results hr = pEvent->EnumerateResults(&pEnum); if (FAILED(hr)) { // EnumerateResults failed DEBUG_PRINT(("EnumerateResults failed %x", hr )); return; } // Deliver the participant state to the session window pSearchWindow->DeliverUserSearchResults((HRESULT)lStatus, pEnum); SAFE_RELEASE(pEnum); //////////// // // End RTC Functionality Code // //////////// } ///////////////////////////////////////////// // // CRTCWin::OnRTCRoamingEvent // void CRTCWin::OnRTCRoamingEvent( IRTCRoamingEvent *pEvent ) { //////////// // // Begin RTC Functionality Code // // This code demonstrates how to handle a Roaming Event. // This event occurs when we begin or end roaming. You may enable roaming as a flag parameter to // the EnableProfileEx() call. // //////////// HRESULT hr; RTC_ROAMING_EVENT_TYPE enType; long lStatusCode; hr = pEvent->get_EventType(&enType); if (FAILED(hr)) { // get_EventType failed DEBUG_PRINT(("get_EventType failed %x", hr )); return; } hr = pEvent->get_StatusCode(&lStatusCode); if (FAILED(hr)) { // get_StatusCode failed DEBUG_PRINT(("get_StatusCode failed %x", hr )); return; } hr = lStatusCode; switch (enType) { case RTCRET_BUDDY_ROAMING: DEBUG_PRINT(("RTCRET_BUDDY_ROAMING %x", hr )); break; case RTCRET_WATCHER_ROAMING: DEBUG_PRINT(("RTCRET_WATCHER_ROAMING %x", hr )); break; case RTCRET_PRESENCE_ROAMING: DEBUG_PRINT(("RTCRET_PRESENCE_ROAMING %x", hr )); break; case RTCRET_PROFILE_ROAMING: DEBUG_PRINT(("RTCRET_PROFILE_ROAMING %x", hr )); break; } //////////// // // End RTC Functionality Code // //////////// } ///////////////////////////////////////////// // // CRTCWin::OnRTCProfileEvent // void CRTCWin::OnRTCProfileEvent( IRTCProfileEvent2 *pEvent ) { //////////// // // Begin RTC Functionality Code // // This code demonstrates how to handle a Profile Event. // This event occurs when our profile is created or updated. // A profile may be created with GetProfile(). A profile may be updated from the server // if profile roaming is requested, and the server supports the feature. // //////////// HRESULT hr; RTC_PROFILE_EVENT_TYPE enType; long lStatusCode; hr = pEvent->get_EventType(&enType); if (FAILED(hr)) { // get_EventType failed DEBUG_PRINT(("get_EventType failed %x", hr )); return; } hr = pEvent->get_StatusCode(&lStatusCode); if (FAILED(hr)) { // get_StatusCode failed DEBUG_PRINT(("get_StatusCode failed %x", hr )); return; } hr = lStatusCode; switch (enType) { case RTCPFET_PROFILE_GET: { DEBUG_PRINT(("RTCPFET_PROFILE_GET %x", hr )); if (FAILED(hr)) { // Provisioning failed. DoLogOff(); OnLoggedOff(); ShowMessageBox(L"Logon failed!"); return; } else { // Provisioning was successful. // Get the RTC profile object from the event IRTCProfile *p = NULL; hr = pEvent->get_Profile(&p); if(p) { p->QueryInterface(__uuidof(IRTCProfile2), (void **)&m_pProfile); SAFE_RELEASE(p); DEBUG_PRINT(("m_pProfile = %X", m_pProfile)); } else hr = E_NOINTERFACE; if (FAILED(hr)) { // get_Profile failed DEBUG_PRINT(("get_Profile failed %x", hr )); DoLogOff(); OnLoggedOff(); ShowMessageBox(L"Logon failed!"); return; } //hr = m_pProfile->put_AllowedAuth(RTCAU_NTLM | RTCAU_KERBEROS | RTCAU_USE_LOGON_CRED); hr = m_pProfile->put_AllowedAuth(RTCAU_DIGEST); if (FAILED(hr)) { DEBUG_PRINT(("put_AllowedAuth failed %x", hr )); } // Register the profile hr = DoRegister(); if (FAILED(hr)) { // DoEnableRoaming failed DEBUG_PRINT(("DoRegister failed %x", hr )); DoLogOff(); OnLoggedOff(); ShowMessageBox(L"Logon failed!"); return; } } } break; case RTCPFET_PROFILE_UPDATE: DEBUG_PRINT(("RTCPFET_PROFILE_UPDATE %x", hr )); // Ignore updates break; } //////////// // // End RTC Functionality Code // //////////// } ///////////////////////////////////////////// // // CRTCWin::OnRTCPresencePropertyEvent // void CRTCWin::OnRTCPresencePropertyEvent( IRTCPresencePropertyEvent *pEvent ) { //////////// // // Begin RTC Functionality Code // // This code demonstrates how to handle a Presence Property Event. // This event occurs when one of our device's presence properties are updated. // (the status code indicates whether the operation was successful). // //////////// HRESULT hr; long lStatusCode; RTC_PRESENCE_PROPERTY enProp; BSTR bstrVal = NULL; hr = pEvent->get_StatusCode(&lStatusCode); if (FAILED(hr)) { // get_StatusCode failed DEBUG_PRINT(("get_StatusCode failed %x", hr )); return; } hr = pEvent->get_PresenceProperty(&enProp); if (FAILED(hr) && (hr != RTC_E_NOT_EXIST)) { // get_PresenceProperty failed DEBUG_PRINT(("get_PresenceProperty failed %x", hr )); return; } hr = pEvent->get_Value(&bstrVal); DEBUG_PRINT(("RTCE_PRESENCE_PROPERTY %d : %s ", enProp, bstrVal)); SAFE_FREE_STRING(bstrVal); //////////// // // End RTC Functionality Code // //////////// } ///////////////////////////////////////////// // // CRTCWin::OnRTCPresenceDataEvent // void CRTCWin::OnRTCPresenceDataEvent( IRTCPresenceDataEvent *pEvent ) { //////////// // // Begin RTC Functionality Code // // This code demonstrates how to handle a Presence Data Event. // This event occurs when our device's presence data is updated (the status code indicates whether the operation was successful). // //////////// HRESULT hr; long lStatusCode; BSTR bstrNamespace = NULL; BSTR bstrData = NULL; hr = pEvent->get_StatusCode(&lStatusCode); if (FAILED(hr)) { // get_StatusCode failed DEBUG_PRINT(("get_StatusCode failed %x", hr )); return; } hr = pEvent->GetPresenceData(&bstrNamespace, &bstrData); if (FAILED(hr) && (hr != RTC_E_NOT_EXIST)) { // GetPresenceData failed DEBUG_PRINT(("GetPresenceData failed %x", hr )); return; } DEBUG_PRINT(("RTCE_PRESENCE_PROPERTY %s : %s ", bstrNamespace, bstrData)); SAFE_FREE_STRING(bstrNamespace); SAFE_FREE_STRING(bstrData); //////////// // // End RTC Functionality Code // //////////// } ///////////////////////////////////////////// // // CRTCWin::OnRTCPresenceStatusEvent // void CRTCWin::OnRTCPresenceStatusEvent( IRTCPresenceStatusEvent *pEvent ) { //////////// // // Begin RTC Functionality Code // // This code demonstrates how to handle a Presence Status Event. // This event occurs when our device's presence status is updated. // (the status code indicates whether the operation was successful). // //////////// HRESULT hr; long lStatusCode; BSTR bstrNotes = NULL; RTC_PRESENCE_STATUS enStatus; hr = pEvent->get_StatusCode(&lStatusCode); if (FAILED(hr)) { // get_StatusCode failed DEBUG_PRINT(("get_StatusCode failed %x", hr )); return; } hr = pEvent->GetLocalPresenceInfo(&enStatus, &bstrNotes); if (FAILED(hr) && (hr != RTC_E_NOT_EXIST)) { // GetLocalPresenceInfo failed DEBUG_PRINT(("GetLocalPresenceInfo failed %x", hr )); return; } DEBUG_PRINT(("RTCE_PRESENCE_STATUS=%d Notes=%s : %s ", enStatus, bstrNotes)); SAFE_FREE_STRING(bstrNotes); //////////// // // End RTC Functionality Code // //////////// }
[ "yippeesoft@5dda88da-d10c-0410-ac74-cc18da35fedd" ]
[ [ [ 1, 5333 ] ] ]
0e7819346c67b0b0f33d329ccf35e3a3b9fab3b7
073dfce42b384c9438734daa8ee2b575ff100cc9
/RCF/include/RCF/RcfBoostThreads/boost_1_33_1/boost/thread/once.hpp
81fef9f75748d7f8e8a790da7617cd8985a17bb6
[]
no_license
r0ssar00/iTunesSpeechBridge
a489426bbe30ac9bf9c7ca09a0b1acd624c1d9bf
71a27a52e66f90ade339b2b8a7572b53577e2aaf
refs/heads/master
2020-12-24T17:45:17.838301
2009-08-24T22:04:48
2009-08-24T22:04:48
285,393
1
0
null
null
null
null
UTF-8
C++
false
false
1,399
hpp
//****************************************************************************** // RCF - Remote Call Framework // Copyright (c) 2005 - 2009, Jarl Lindrud. All rights reserved. // Consult your license for conditions of use. // Version: 1.1 // Contact: jarl.lindrud <at> gmail.com //****************************************************************************** // Copyright (C) 2001-2003 // William E. Kempf // // Permission to use, copy, modify, distribute and sell this software // and its documentation for any purpose is hereby granted without fee, // provided that the above copyright notice appear in all copies and // that both that copyright notice and this permission notice appear // in supporting documentation. William E. Kempf makes no representations // about the suitability of this software for any purpose. // It is provided "as is" without express or implied warranty. #ifndef RCF_BOOST_ONCE_WEK080101_HPP #define RCF_BOOST_ONCE_WEK080101_HPP namespace boost { #if defined(BOOST_HAS_PTHREADS) typedef pthread_once_t once_flag; #define BOOST_ONCE_INIT PTHREAD_ONCE_INIT #elif (defined(BOOST_HAS_WINTHREADS) || defined(BOOST_HAS_MPTASKS)) typedef long once_flag; #define BOOST_ONCE_INIT 0 #endif void RCF_BOOST_THREAD_DECL call_once(void (*func)(), once_flag& flag); } // namespace boost #endif // RCF_BOOST_ONCE_WEK080101_HPP
[ [ [ 1, 42 ] ] ]
798918d7bb1a6198a39f5bd35f3c68e4fb53b2d5
33f59b1ba6b12c2dd3080b24830331c37bba9fe2
/Depend/Foundation/System/Wm4THashTable.inl
c181f1bf8678dbc2806f10dea237115f78c9b79a
[]
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
6,306
inl
// 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. //---------------------------------------------------------------------------- template <class TKEY, class TVALUE> THashTable<TKEY,TVALUE>::THashTable (int iTableSize) { assert(iTableSize > 0); m_iTableSize = iTableSize; m_iQuantity = 0; m_iIndex = 0; m_pkItem = 0; m_apkTable = WM4_NEW HashItem*[m_iTableSize]; memset(m_apkTable,0,m_iTableSize*sizeof(HashItem*)); UserHashFunction = 0; } //---------------------------------------------------------------------------- template <class TKEY, class TVALUE> THashTable<TKEY,TVALUE>::~THashTable () { RemoveAll(); WM4_DELETE[] m_apkTable; } //---------------------------------------------------------------------------- template <class TKEY, class TVALUE> int THashTable<TKEY,TVALUE>::GetQuantity () const { return m_iQuantity; } //---------------------------------------------------------------------------- template <class TKEY, class TVALUE> bool THashTable<TKEY,TVALUE>::Insert (const TKEY& rtKey, const TVALUE& rtValue) { // find hash table entry for given key int iIndex = HashFunction(rtKey); HashItem* pkItem = m_apkTable[iIndex]; // search for item in list associated with key while (pkItem) { if (rtKey == pkItem->m_tKey) { // item already in hash table return false; } pkItem = pkItem->m_pkNext; } // add item to beginning of list pkItem = WM4_NEW HashItem; pkItem->m_tKey = rtKey; pkItem->m_tValue = rtValue; pkItem->m_pkNext = m_apkTable[iIndex]; m_apkTable[iIndex] = pkItem; m_iQuantity++; return true; } //---------------------------------------------------------------------------- template <class TKEY, class TVALUE> TVALUE* THashTable<TKEY,TVALUE>::Find (const TKEY& rtKey) const { // find hash table entry for given key int iIndex = HashFunction(rtKey); HashItem* pkItem = m_apkTable[iIndex]; // search for item in list associated with key while (pkItem) { if (rtKey == pkItem->m_tKey) { // item is in hash table return &pkItem->m_tValue; } pkItem = pkItem->m_pkNext; } return 0; } //---------------------------------------------------------------------------- template <class TKEY, class TVALUE> bool THashTable<TKEY,TVALUE>::Remove (const TKEY& rtKey) { // find hash table entry for given key int iIndex = HashFunction(rtKey); HashItem* pkItem = m_apkTable[iIndex]; if (!pkItem) { return false; } if (rtKey == pkItem->m_tKey) { // item is at front of list, strip it off HashItem* pkSave = pkItem; m_apkTable[iIndex] = pkItem->m_pkNext; WM4_DELETE pkSave; m_iQuantity--; return true; } // search for item in list HashItem* pkPrev = pkItem; HashItem* pkCurr = pkItem->m_pkNext; while (pkCurr && rtKey != pkCurr->m_tKey) { pkPrev = pkCurr; pkCurr = pkCurr->m_pkNext; } if (pkCurr) { // found the item pkPrev->m_pkNext = pkCurr->m_pkNext; WM4_DELETE pkCurr; m_iQuantity--; return true; } return false; } //---------------------------------------------------------------------------- template <class TKEY, class TVALUE> void THashTable<TKEY,TVALUE>::RemoveAll () { if (m_iQuantity > 0) { for (int iIndex = 0; iIndex < m_iTableSize; iIndex++) { while (m_apkTable[iIndex]) { HashItem* pkSave = m_apkTable[iIndex]; m_apkTable[iIndex] = m_apkTable[iIndex]->m_pkNext; WM4_DELETE pkSave; if (--m_iQuantity == 0) { return; } } } } } //---------------------------------------------------------------------------- template <class TKEY, class TVALUE> TVALUE* THashTable<TKEY,TVALUE>::GetFirst (TKEY* ptKey) const { if (m_iQuantity > 0) { for (m_iIndex = 0; m_iIndex < m_iTableSize; m_iIndex++) { if (m_apkTable[m_iIndex]) { m_pkItem = m_apkTable[m_iIndex]; *ptKey = m_pkItem->m_tKey; return &m_pkItem->m_tValue; } } } return 0; } //---------------------------------------------------------------------------- template <class TKEY, class TVALUE> TVALUE* THashTable<TKEY,TVALUE>::GetNext (TKEY* ptKey) const { if (m_iQuantity > 0) { m_pkItem = m_pkItem->m_pkNext; if (m_pkItem) { *ptKey = m_pkItem->m_tKey; return &m_pkItem->m_tValue; } for (m_iIndex++; m_iIndex < m_iTableSize; m_iIndex++) { if (m_apkTable[m_iIndex]) { m_pkItem = m_apkTable[m_iIndex]; *ptKey = m_pkItem->m_tKey; return &m_pkItem->m_tValue; } } } return 0; } //---------------------------------------------------------------------------- template <class TKEY, class TVALUE> int THashTable<TKEY,TVALUE>::HashFunction (const TKEY& rtKey) const { if (UserHashFunction) { return (*UserHashFunction)(rtKey); } // default hash function static double s_dHashMultiplier = 0.5*(sqrt(5.0)-1.0); unsigned int uiKey; System::Memcpy(&uiKey,sizeof(unsigned int),&rtKey,sizeof(unsigned int)); uiKey %= m_iTableSize; double dFraction = fmod(s_dHashMultiplier*uiKey,1.0); return (int)floor(m_iTableSize*dFraction); } //----------------------------------------------------------------------------
[ "yf.flagship@e79fdf7c-a9d8-11de-b950-3d5b5f4ea0aa" ]
[ [ [ 1, 215 ] ] ]
e1da5d72d93fe78ba473b16bee582aa67dd9e300
374f53386d36e3aadf0ed88e006394220f732f30
/gl/mfc_gl_sdi/mfcsdi_glView.cpp
e8567f74a6600cdef359cfe1dea1f348273db4dd
[ "MIT" ]
permissive
yatjf/sonson-code
e7edbc613f8c97be5f7c7367be2660b3cb75a61b
fbb564af37adb2305fe7d2148f8d4f5a3450f72b
refs/heads/master
2020-06-13T08:02:38.469864
2010-07-01T14:20:40
2010-07-01T14:20:40
null
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
5,141
cpp
// // mfc_gl_sdi // mfcsdi_glView.cpp // // The MIT License // // Copyright (c) 2009 sonson, sonson@Picture&Software // // 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. //// mfcsdi_glView.cpp : CMfcsdi_glView クラスの動作の定義を行います。 // #include "stdafx.h" #include "mfcsdi_gl.h" #include "mfcsdi_glDoc.h" #include "mfcsdi_glView.h" #include "InitGL.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CMfcsdi_glView IMPLEMENT_DYNCREATE(CMfcsdi_glView, CView) BEGIN_MESSAGE_MAP(CMfcsdi_glView, CView) //{{AFX_MSG_MAP(CMfcsdi_glView) ON_WM_CREATE() ON_WM_SIZE() //}}AFX_MSG_MAP // 標準印刷コマンド ON_COMMAND(ID_FILE_PRINT, CView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_DIRECT, CView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_PREVIEW, CView::OnFilePrintPreview) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CMfcsdi_glView クラスの構築/消滅 CMfcsdi_glView::CMfcsdi_glView() { // TODO: この場所に構築用のコードを追加してください。 } CMfcsdi_glView::~CMfcsdi_glView() { // OpenGLの開放 wglMakeCurrent(NULL,NULL); wglDeleteContext(hRC); delete cDC; } BOOL CMfcsdi_glView::PreCreateWindow(CREATESTRUCT& cs) { // TODO: この位置で CREATESTRUCT cs を修正して Window クラスまたはスタイルを // 修正してください。 return CView::PreCreateWindow(cs); } ///////////////////////////////////////////////////////////////////////////// // CMfcsdi_glView クラスの描画 void CMfcsdi_glView::OnDraw(CDC* pDC) { CMfcsdi_glDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); // TODO: この場所にネイティブ データ用の描画コードを追加します。 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) ; glLoadIdentity(); gluLookAt( 2,2,3, 0,0,0, 0,1,0); glPushMatrix(); glBegin(GL_QUADS); glColor3d(1.0, 0.0, 0.0); glVertex3f(0.0, 0.0, 0.0); glColor3d(1.0, 1.0, 0.0); glVertex3f(0.0, 0.0, 1.0); glColor3d(1.0, 0.0, 1.0); glVertex3f(1.0, 0.0, 1.0); glVertex3f(1.0, 0.0, 0.0); glEnd(); glPopMatrix(); glFinish(); SwapBuffers(cDC->m_hDC) ; } ///////////////////////////////////////////////////////////////////////////// // CMfcsdi_glView クラスの印刷 BOOL CMfcsdi_glView::OnPreparePrinting(CPrintInfo* pInfo) { // デフォルトの印刷準備 return DoPreparePrinting(pInfo); } void CMfcsdi_glView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { // TODO: 印刷前の特別な初期化処理を追加してください。 } void CMfcsdi_glView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { // TODO: 印刷後の後処理を追加してください。 } ///////////////////////////////////////////////////////////////////////////// // CMfcsdi_glView クラスの診断 #ifdef _DEBUG void CMfcsdi_glView::AssertValid() const { CView::AssertValid(); } void CMfcsdi_glView::Dump(CDumpContext& dc) const { CView::Dump(dc); } CMfcsdi_glDoc* CMfcsdi_glView::GetDocument() // 非デバッグ バージョンはインラインです。 { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CMfcsdi_glDoc))); return (CMfcsdi_glDoc*)m_pDocument; } #endif //_DEBUG int CMfcsdi_glView::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CView::OnCreate(lpCreateStruct) == -1) return -1; // TODO: この位置に固有の作成用コードを追加してください cDC = new CClientDC(this) ; // DCの生成 hRC = Init_Pixel(cDC->m_hDC) ; // OpenGL用にPixel Formatを指定 wglMakeCurrent (cDC->m_hDC, hRC); // 現在のcontext設定 StartFunction(); return 0; } void CMfcsdi_glView::OnSize(UINT nType, int cx, int cy) { CView::OnSize(nType, cx, cy); // TODO: この位置にメッセージ ハンドラ用のコードを追加してください Resize(cx,cy); }
[ "yoshida.yuichi@0d0a6a56-2bd1-11de-9cad-a3574e5575ef" ]
[ [ [ 1, 174 ] ] ]
7827a1043c72fdedbb0e12df3c3006ae7d4173cc
6be72227405ee9fa245ea9f9896df3f2668ed81b
/examples/src/Framework.cpp
1e1347c34d6eeb0362c009b054e3cdae33767fa9
[ "MIT" ]
permissive
lilieming/tinyimageloader
9ab74ec20070ceff40a9e14de344d073da4655a4
9513947b61aa93ec7dd8f16e14fbc14becdcd86e
refs/heads/master
2020-05-20T06:11:52.414776
2011-07-10T12:45:58
2011-07-10T12:45:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,971
cpp
#include "Framework.h" namespace TILFW { bool Framework::s_KeysPressed[256]; bool Framework::s_KeysReleased[256]; #ifndef DOXYGEN_SHOULD_SKIP_THIS #define CHECKOGLERROR() CheckOGLerror(__LINE__) void CheckOGLerror(int a_Line) { char errorString[0xffff]; errorString[0] = 0; GLenum curError; do { curError = glGetError(); if( curError != GL_NO_ERROR ) { char tmps[256]; sprintf_s( tmps, 256, "'%s' ", gluErrorString(curError) ); strcat_s( errorString, 0xffff, tmps ); } } while ( curError != GL_NO_ERROR ); if( strlen( errorString) != 0 ) { //DebugBreak(); char line[32]; sprintf(line, " (line %i)", a_Line); strcat(errorString, line); MessageBoxA( NULL, errorString, "OpenGL errors", MB_ICONSTOP ); exit(1); } } static unsigned long g_TimeCurrent, g_TimeStart; static float g_TimeDelta; static float g_PhysicsTime = 0; static float g_RenderTime = 0; bool g_Exit = false; bool g_Active = true; HINSTANCE g_Instance; HWND g_Window; MSG g_MSG; HDC g_WindowContext; GLuint g_FontBase = 1000; const float frame_physics = (1000.f / 60.f); LRESULT CALLBACK Win32Messages(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_ACTIVATE: { g_Active = ((LOWORD(wParam) != WA_INACTIVE) && !((BOOL)HIWORD(wParam))); break; } case WM_KEYDOWN: { Framework::s_KeysPressed[wParam] = true; break; } case WM_KEYUP: { Framework::s_KeysPressed[wParam] = false; Framework::s_KeysReleased[wParam] = true; break; } case WM_MOUSEMOVE: { break; } case WM_CLOSE: case WM_QUIT: case WM_DESTROY: g_Exit = true; break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } #endif int Framework::Exec(int argc, char** argv) { Framework::Setup(); WNDCLASS temp = { CS_HREDRAW | CS_VREDRAW | CS_OWNDC, // defines the class style Win32Messages, // pointer to the message handler function 0, // extra bytes following the window class structure 0, // extra bytes following the window instance g_Instance, // instance handle LoadIcon(NULL, IDI_APPLICATION), // icon handle LoadCursor(NULL, IDC_ARROW), // cursor NULL, // background brush NULL, // menu name "Framework" // window title }; if (!RegisterClass(&temp)) { return 0; } // center windows on screen const int x = GetSystemMetrics(SM_CXSCREEN) / 2 - s_WindowWidth / 2; const int y = GetSystemMetrics(SM_CYSCREEN) / 2 - s_WindowHeight / 2; const DWORD style = WS_OVERLAPPEDWINDOW & ~(WS_THICKFRAME | WS_MAXIMIZEBOX); RECT dim = { 0, 0, s_WindowWidth, s_WindowHeight }; AdjustWindowRect(&dim, style, FALSE); const int w = dim.right - dim.left; const int h = dim.bottom - dim.top; g_Window = CreateWindowEx ( 0, "Framework", // window class "Framework", // window title style, // visibility settings x, y, w, h, NULL, NULL, temp.hInstance, //GetModuleHandle(NULL), NULL ); if (!g_Window) { return -1; } if (!(g_WindowContext = GetDC(g_Window))) { return -1; } PIXELFORMATDESCRIPTOR pfd = { sizeof(PIXELFORMATDESCRIPTOR), 1, PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, PFD_TYPE_RGBA, 32, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 24, 0, 0, PFD_MAIN_PLANE, 0, 0, 0, 0 }; unsigned int format; if (!(format = ChoosePixelFormat(g_WindowContext, &pfd))) { return -1; } if (!SetPixelFormat(g_WindowContext, format, &pfd)) { return -1; } HGLRC hrc; if (!(hrc = wglCreateContext(g_WindowContext))) { return -1; } if (!wglMakeCurrent(g_WindowContext, hrc)) { return -1; } // initialize opengl GLenum status = glewInit(); if (status != GLEW_OK) { char error[256]; sprintf(error, "%s", glewGetErrorString(status)); MessageBoxA(NULL, error, "GLEW error", MB_OK | MB_ICONEXCLAMATION); return -1; } glEnable(GL_DEPTH_TEST); glShadeModel(GL_SMOOTH); for (int i = 0; i < 256; i++) { Framework::s_KeysPressed[i] = false; Framework::s_KeysReleased[i] = false; } // convert windows command line to c-style /*int argv; wchar_t** argc = CommandLineToArgvW(GetCommandLineW(), &argv); char** cmdline = new char*[argv]; for (int i = 0; i < argv; i++) { cmdline[i] = new char[wcslen(argc[i]) + 1]; wcstombs(cmdline[i], argc[i], wcslen(argc[i]) + 1); }*/ //Framework::Init((const char**)cmdline, argv); Framework::Init((const char**)argv, argc); ShowWindow(g_Window, 1); UpdateWindow(g_Window); // initialize font HFONT oldfont; g_FontBase = glGenLists(96); HFONT font_text = CreateFont( 18, 0, 0, 0, FW_BOLD, // bold FALSE, // italic FALSE, // underline FALSE, // strikeout ANSI_CHARSET, OUT_TT_PRECIS, CLIP_DEFAULT_PRECIS, ANTIALIASED_QUALITY, FF_DONTCARE | DEFAULT_PITCH, "Arial" ); oldfont = (HFONT)SelectObject(g_WindowContext, font_text); wglUseFontBitmaps(g_WindowContext, 0, 127, g_FontBase); SelectObject(g_WindowContext, oldfont); DeleteObject(font_text); // start s_Exit = false; g_TimeStart = GetTickCount(); while (1) { if (PeekMessage(&g_MSG, NULL, 0, 0, PM_REMOVE)) { TranslateMessage(&g_MSG); DispatchMessage(&g_MSG); } else { g_TimeCurrent = GetTickCount(); g_TimeDelta = (float)(g_TimeCurrent - g_TimeStart); g_TimeStart = g_TimeCurrent; g_PhysicsTime += g_TimeDelta; while (g_PhysicsTime > frame_physics) { Framework::Tick(frame_physics); for (int i = 0; i < 256; i++) { Framework::s_KeysReleased[i] = false; } g_PhysicsTime -= frame_physics; } if (g_Active) { Framework::Render(); // render text glBindTexture(GL_TEXTURE_2D, 0); glViewport(0, 0, s_WindowWidth, s_WindowHeight); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); gluOrtho2D( 0, s_WindowWidth, s_WindowHeight, 0 ); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glPushAttrib(GL_LIST_BIT); glListBase(g_FontBase); glColor3f(1.f, 1.f, 1.f); for (std::vector<TextData*>::iterator it = m_TextList.begin(); it != m_TextList.end(); it++) { glRasterPos3i((*it)->x, (*it)->y, 1); glCallLists(strlen((*it)->msg), GL_UNSIGNED_BYTE, (*it)->msg); } glPopAttrib(); m_TextList.clear(); glPopMatrix(); glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); SwapBuffers(g_WindowContext); } } if (s_Exit || g_Exit) { break; } } Framework::CloseDown(); DestroyWindow(g_Window); return 0; } void Framework::DisplayText(unsigned int a_X, unsigned int a_Y, const char* a_Text, ...) { TextData* data = new TextData; data->x = a_X; data->y = a_Y; char msg[256]; va_list args; va_start(args, a_Text); vsprintf(msg, a_Text, args); va_end(args); data->msg = new char[strlen(msg) + 1]; strcpy(data->msg, msg); m_TextList.push_back(data); } }; // namespace TILFW
[ "knight666@ae7ae854-2bc2-de67-b11e-81cc9cd7c224" ]
[ [ [ 1, 365 ] ] ]
95e8aec93f15ec46a9154173679dcee74c0a0efd
97f1be9ac088e1c9d3fd73d76c63fc2c4e28749a
/3dc/win95/huffman.hpp
cdcf89157a6b2d14a6e70f2c48b249cd8d3db7b1
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
SR-dude/AvP-Wine
2875f7fd6b7914d03d7f58e8f0ec4793f971ad23
41a9c69a45aacc2c345570ba0e37ec3dc89f4efa
refs/heads/master
2021-01-23T02:54:33.593334
2011-09-17T11:10:07
2011-09-17T11:10:07
2,375,686
1
0
null
null
null
null
UTF-8
C++
false
false
668
hpp
#ifndef _huffman_hpp_included #define _huffman_hpp_included 1 #ifdef __cplusplus extern "C" { #endif #define MAX_DEPTH 11 typedef struct { char Identifier[8]; int CompressedDataSize; int UncompressedDataSize; int CodelengthCount[MAX_DEPTH]; unsigned char ByteAssignment[256]; } HuffmanPackage; /* KJL 17:16:03 17/09/98 - Compression */ extern HuffmanPackage *HuffmanCompression(unsigned char *sourcePtr, int length); /* KJL 16:53:53 19/09/98 - Decompression */ extern char *HuffmanDecompress(HuffmanPackage *inpackage); #define COMPRESSED_RIF_IDENTIFIER "REBCRIF1" #ifdef __cplusplus }; #endif #endif
[ "a_jagers@ANTHONYJ.(none)" ]
[ [ [ 1, 31 ] ] ]
38ecf3559cd19388e1b83708046bfc440d2c9ea0
33d2272f0af4d08cb3b20e81f2ece571b2c7e131
/PeopleCoutning/PeopleCoutning/Param.h
1ceb776e234de06aa9226ee438e8794e35545f7c
[]
no_license
mscreolo/huy-khanh-people-counting
776b66e44b7881d1dc9a24b0d4b9361e99aa30ca
5875d54e28eb86b8f127e1fc94c61cb7795c7bdf
refs/heads/master
2016-09-15T20:43:32.200996
2011-10-26T03:07:40
2011-10-26T03:07:40
33,321,132
0
0
null
null
null
null
UTF-8
C++
false
false
3,329
h
#pragma once #include "cv.h" #include "highgui.h" #include <time.h> #include <math.h> #include <vector> #include "Region.h" #include "FrameSegment.h" #define MAIN_WINDOW "Main TMS Application" #define LEFT_FLOW_KLT "KLT LtFlow" #define RIGHT_FLOW_KLT "KLT RtFlow" #define LEFT_FLOW_FGR "FGR LtFlow" #define RIGHT_FLOW_FGR "FGR RtFlow" #define COLOR_YELLOW cvScalar(0,255,255) #define COLOR_WHITE cvScalar(255,255,255) #define COLOR_GREEN cvScalar(0,255,0) #define COLOR_AQUA cvScalar(255,255,0) #define COLOR_BLUE cvScalar(255,0,0) #define COLOR_BLACK cvScalar(0,0,0) ////////////////////////////////////////////////////////////////////////// // // //template <typename T> // ////////////////////////////////////////////////////////////////////////// // dung nhung ham static do phai ho tro cho cac form dialog // class Param { public: static void releaseAllImage(IplImage* img1=NULL, IplImage* img2=NULL,IplImage* img3=NULL,IplImage* img4=NULL,IplImage* img5=NULL) { if (img1) cvReleaseImage(&img1); else if (img2) cvReleaseImage(&img2); else if (img3) cvReleaseImage(&img3); else if (img4) cvReleaseImage(&img4); else if (img5) cvReleaseImage(&img5); } static double calDistance2Point(CvPoint p1, CvPoint p2) { return sqrt(pow(p1.x - p2.x, 2.0) + pow(p1.y - p2.y, 2.0)); } static bool isContainInRect(CvPoint pnt, CvRect rect) { bool flag = false; if ((pnt.x > rect.x && pnt.x < (rect.x + rect.width)) && \ (pnt.y > rect.y && pnt.y < (rect.y + rect.height))) { flag = true; } return flag; } static CvPoint* convertVectorPointToArrayPoint(std::vector<CvPoint> points) { int numPoint = points.size(); CvPoint* arrPoint = new CvPoint[numPoint]; for (int i=0; i < numPoint; i++) { arrPoint[i] = points[i]; } return arrPoint; } static void drawLinesFromArrPoints(IplImage* img, CvPoint* arrPoint, int nPoint, CvScalar color) { for (int i=0; i < nPoint; i++) { cvLine(img, arrPoint[i % nPoint], arrPoint[(i+1) % nPoint], color, 2, CV_AA); } } static CvRect getBoundingRect(std::vector<CvPoint> vecPoint) { CvRect rect; int nPoint = vecPoint.size(); int xmax, ymax, xmin, ymin; xmin = xmax = vecPoint[0].x; ymin = ymax = vecPoint[0].y; for(int i=1; i < nPoint; i++) { if(xmin > vecPoint[i].x) xmin = vecPoint[i].x; if(xmax < vecPoint[i].x) xmax = vecPoint[i].x; if(ymin > vecPoint[i].y) ymin = vecPoint[i].y; if(ymax < vecPoint[i].y) ymax = vecPoint[i].y; } rect.x = xmin; rect.y = ymin; rect.width = xmax - xmin; rect.height = ymax - ymin; return rect; } static CvRect getBoundingRect(CvPoint* arrPoint, int nPoint) { CvRect rect; int xmax, ymax, xmin, ymin; xmin = xmax = arrPoint[0].x; ymin = ymax = arrPoint[0].y; for(int i=1; i < nPoint; i++) { if(xmin > arrPoint[i].x) xmin = arrPoint[i].x; if(xmax < arrPoint[i].x) xmax = arrPoint[i].x; if(ymin > arrPoint[i].y) ymin = arrPoint[i].y; if(ymax < arrPoint[i].y) ymax = arrPoint[i].y; } rect.x = xmin; rect.y = ymin; rect.width = xmax - xmin; rect.height = ymax - ymin; return rect; } };
[ "[email protected]@ead409af-2641-a09c-7308-cf4d77c96f99" ]
[ [ [ 1, 154 ] ] ]
cee3ce3b2dbdcb823330160e9add4afe116e4340
30e4267e1a7fe172118bf26252aa2eb92b97a460
/code/pkg_Core/Interface/Xml/Ix_StringTable.h
316fbc527931f4356b3f1373ab6bcf685dd7bdd1
[ "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
GB18030
C++
false
false
3,169
h
// Copyright 2008-2011 Zhang Yun Gui, [email protected] // https://sourceforge.net/projects/x3c/ // // 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. /*! \file Ix_StringTable.h * \brief 定义本地化字符串表的接口 Ix_StringTable * \author Zhang Yun Gui, C++ Plugin Framework * \date 2010.10.28 */ #ifndef X3_XML_ISTRINGTABLE_H_ #define X3_XML_ISTRINGTABLE_H_ const XCLSID CLSID_StringTable("b8c36b29-59c3-4db2-be43-fd4982e6e71d"); //! 本地化字符串表的接口 /*! 本地化字符串XML文件存放于主程序目录的 Translations/Strings 目录下 \interface Ix_StringTable \ingroup _GROUP_PLUGIN_XML_ \see CLSID_StringTable */ interface Ix_StringTable { //! 得到一个模块的指定ID名称对应的字符串值 /*! \param[out] value 实际字符串值 \param[in] name 包含模块名和ID名称的标识串,格式为以@开头接上“Module:IDS_XXX” \param[out] module 填充name中的模块名 \param[out] id 填充name中的串ID名称 \return 是否读取到非空值 */ virtual bool GetValue(std::wstring& value, const std::wstring& name, std::wstring& module, std::wstring& id) = 0; //! 得到一个模块的指定ID名称对应的字符串值 /*! \param[out] value 实际字符串值 \param[in] module 模块名 \param[in] id 串ID名称 \return 是否读取到非空值 */ virtual bool GetValue(std::wstring& value, const std::wstring& module, const std::wstring& id) = 0; //! 加载指定目录下的字符串XML文件 /*! \param path 字符串XML文件所在目录的决定路径 \return 加载的文件数 */ virtual long LoadFiles(const std::wstring& path) = 0; //! 得到一个模块的指定ID名称对应的字符串值 /*! \param[in] module 模块名 \param[in] id 串ID名称 \param[out] hasvalue 填充是否读取到非空值,为NULL则忽略 \return 实际字符串值 */ virtual std::wstring GetValue(const std::wstring& module, const std::wstring& id, bool* hasvalue = NULL) = 0; }; #ifdef X3_CORE_XCOMPTR_H_ //! 得到一个模块的指定ID名称对应的字符串值 /*! \param[in] module 模块名 \param[in] id 串ID名称 \param[out] hasvalue 填充是否读取到非空值,为NULL则忽略 \return 实际字符串值,空串表示没有值 */ inline std::wstring GetStringValue(const std::wstring& module, const std::wstring& id, bool* hasvalue = NULL) { Cx_Interface<Ix_StringTable> pIFTable(CLSID_StringTable); return pIFTable ? pIFTable->GetValue(module, id, hasvalue) : std::wstring(); } #endif #endif // X3_XML_ISTRINGTABLE_H_
[ "rhcad1@71899303-b18e-48b3-b26e-8aaddbe541a3" ]
[ [ [ 1, 89 ] ] ]
87c8d246649e518947d93f5ad0ec930587f741f0
6b75de27b75015e5622bfcedbee0bf65e1c6755d
/stack/stack-twiwai(full).cpp
45b3dc3c2796abfc9a9c64b19968e1263851b1b9
[]
no_license
xhbang/data_structure
6e4ac9170715c0e45b78f8a1b66c838f4031a638
df2ff9994c2d7969788f53d90291608ac5b1ef2b
refs/heads/master
2020-04-04T02:07:18.620014
2011-12-05T09:39:34
2011-12-05T09:39:34
2,393,408
0
0
null
null
null
null
GB18030
C++
false
false
1,550
cpp
/*链栈的结构定义*/ typedef struct { SLink top;    // 栈顶指针 int length;   // 栈中元素个数 }Stack; typedef struct{ Element data; Element* next; }Slink; void InitStack ( Stack &S ) { // 构造一个空栈 S S.top = NULL;   // 设栈顶指针的初值为"空" S.length = 0;   // 空栈中元素个数为0 } // InitStack /*能否将链栈中的指针方向反过来,从栈底到栈顶? 不行,如果反过来的话,删除栈顶元素时,为修改其前驱指针,需要从栈底一直找到栈顶。*/ void Push ( Stack &S, Element e ) { // 在栈顶之上插入元素 e 为新的栈顶元素 p = new Slink;   // 建新的结点 if(!p) exit(1);  // 存储分配失败 p -> data = e; p -> next = S.top; // 链接到原来的栈顶 S.top = p;     // 移动栈顶指针 ++S.length;     // 栈的长度增1 } // Push /*在链栈的类型定义中设立"栈中元素个数"的成员是为了便于求得栈的长度。*/ bool Pop ( Stack &S, Element &e ) { // 若栈不空,则删除S的栈顶元素,用 e 返回其值, // 并返回 TRUE;否则返回 FALSE if ( !S.top ) return FALSE; else { e = S.top -> data;   // 返回栈顶元素 q = S.top; S.top = S.top -> next; // 修改栈顶指针 --S.length;       // 栈的长度减1 delete q;       // 释放被删除的结点空间 return TRUE; } } // Pop
[ [ [ 1, 48 ] ] ]
78e0756afe138a6a2d5e074610098c070fa69ae5
5ac13fa1746046451f1989b5b8734f40d6445322
/minimangalore/Nebula2/code/mangalore/physics/boxshape.cc
60c9524d7e3695279e87520b1e7feddafceffaa1
[]
no_license
moltenguy1/minimangalore
9f2edf7901e7392490cc22486a7cf13c1790008d
4d849672a6f25d8e441245d374b6bde4b59cbd48
refs/heads/master
2020-04-23T08:57:16.492734
2009-08-01T09:13:33
2009-08-01T09:13:33
35,933,330
0
0
null
null
null
null
UTF-8
C++
false
false
2,002
cc
//------------------------------------------------------------------------------ // physics/boxshape.cc // (C) 2003 RadonLabs GmbH //------------------------------------------------------------------------------ #include "physics/boxshape.h" #include "gfx2/ngfxserver2.h" #include "physics/rigidbody.h" namespace Physics { ImplementRtti(Physics::BoxShape, Physics::Shape); ImplementFactory(Physics::BoxShape); //------------------------------------------------------------------------------ /** */ BoxShape::BoxShape() : Shape(Box), size(1.0f, 1.0f, 1.0f) { // empty } //------------------------------------------------------------------------------ /** */ BoxShape::~BoxShape() { // empty } //------------------------------------------------------------------------------ /** Create a box object, add it to ODE's collision space, and initialize the mass member. */ bool BoxShape::Attach(dSpaceID spaceId) { if (Shape::Attach(spaceId)) { dGeomID box = dCreateBox(0, this->size.x, this->size.y, this->size.z); this->AttachGeom(box, spaceId); dMassSetBox(&(this->odeMass), Physics::MaterialTable::GetDensity(this->materialType), this->size.x, this->size.y, this->size.z); this->TransformMass(); return true; } return false; } //------------------------------------------------------------------------------ /** Render a debug visualization of the sphere shape. @param parentTransform transform matrix of my parent rigid body */ void BoxShape::RenderDebug(const matrix44& parentTransform) { if (this->IsAttached()) { // compute resulting model matrix matrix44 m; m.scale(this->size); m *= this->GetTransform(); m *= parentTransform; nGfxServer2::Instance()->DrawShape(nGfxServer2::Box, m, this->GetDebugVisualizationColor()); } } } // namespace Physics
[ "BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c" ]
[ [ [ 1, 72 ] ] ]
62a32ea40f569719137919c0847b261e01d761d4
da48afcbd478f79d70767170da625b5f206baf9a
/nnstock/nnstock/WndHelper.h
2099410ec692bd601a282fff4d83e2389fdd30b3
[]
no_license
haokeyy/fahister
5ba50a99420dbaba2ad4e5ab5ee3ab0756563d04
c71dc56a30b862cc4199126d78f928fce11b12e5
refs/heads/master
2021-01-10T19:09:22.227340
2010-05-06T13:17:35
2010-05-06T13:17:35
null
0
0
null
null
null
null
GB18030
C++
false
false
1,840
h
#pragma once struct CWindowAttribute { char* title; char* className; HWND hwnd; }; struct CParentWindowAttribute { char* toptitle; char* topclassName; char* childtitle; char* childclassName; long childx; long childy; BOOL isVisible; HWND hwnd; }; class CWndHelper { private: static BOOL CALLBACK WindowsEnumProcBlur(HWND hwnd, LPARAM lParam); static BOOL CALLBACK WindowsEnumProcExactly(HWND hwnd, LPARAM lParam); static BOOL CALLBACK ParentWindowsEnumProcBlur(HWND hwnd, LPARAM lParam); static HWND FindChildWindowBlurInternal(HWND hParentWnd, char* strText, char* strClass, BOOL bVisable = TRUE); static HWND FindChildWindowExactlyInternal(HWND hWnd, char* strText, char* strClass, BOOL bVisable = TRUE); public: // find top window: title like '%strTitle%' and className like '%strClassName%' static HWND FindTopWindowBlur(char* strTitle, char* strClassName); // find top window: title = 'strTitle' and className = 'strClassName' static HWND FindTopWindowExactly(char* strTitle, char* strClassName); // 参照子窗口查找主窗口: title like '%strTitle%' and className like '%strClassName%' and exists FindChildWindowByPoint(strChildTitle, strChildClassName, x, y) static HWND FindTopWindowRefChildWnd(char* strTopTitle, char* strTopClassName, char* strChildTitle, char* strChildClassName, long child_x = 0, long child_y = 0, BOOL bVisable = TRUE); static HWND FindChildWindowExactly(HWND hWnd, char* strText, char* strClass, BOOL bVisable = TRUE); static HWND FindChildWindowBlur(HWND hWnd, char* strText, char* strClass, BOOL bVisable = TRUE); static HWND FindChildWindowByPoint(HWND hWnd, char* strText, char* strClass, long x, long y, BOOL bVisable = TRUE); };
[ "[email protected]@d41c10be-1f87-11de-a78b-a7aca27b2395" ]
[ [ [ 1, 49 ] ] ]
fa9cf04006975ad92ec6bce4755ab98c976739bc
4094aff52eac68070ee245c3e617ba349ef8adb7
/GLSkeleton.h
762ccd2f5e9b6e208a8091e0d3cbdede2bd50254
[]
no_license
andrelcunha/GraphicComputingProject
e42cd607a2b8607b5008ce7370437bd63301645f
e32b7ae890a86c814cb38de41c1701710ed7e2b3
refs/heads/master
2021-01-19T22:23:51.772905
2009-03-31T04:47:41
2009-03-31T04:47:41
88,808,400
0
0
null
null
null
null
UTF-8
C++
false
false
1,235
h
//--------------------------------------------------------------------------- #ifndef GLSkeletonH #define GLSkeletonH #include <Classes.hpp> #include <Controls.hpp> #include <StdCtrls.hpp> #include <Forms.hpp> #include <gl\gl.h> #include <gl\glu.h> //#include <gl\glut.h> //--------------------------------------------------------------------------- class TGL_window : public TForm { __published: void __fastcall FormResize(TObject *Sender); void __fastcall FormPaint(TObject *Sender); void __fastcall FormDestroy(TObject *Sender); void __fastcall FormCreate(TObject *Sender); void __fastcall FormKeyDown(TObject *Sender, WORD &Key, TShiftState Shift); private: HDC hdc; HGLRC hrc; float w,h; int PixelFormat; public: __fastcall TGL_window(TComponent* Owner); void __fastcall IdleLoop(TObject*, bool&); void __fastcall SetPixelFormatDescriptor(); void __fastcall DrawObjects(); void __fastcall SetupLighting(); }; //--------------------------------------------------------------------------- extern PACKAGE TGL_window *GL_window; //--------------------------------------------------------------------------- #endif
[ "deko81@fbf1ad31-3caa-4afa-b5b4-094426959cba" ]
[ [ [ 1, 40 ] ] ]
da7e899bfd5f0f67c17b407be4b4aee104ed7c42
b2d46af9c6152323ce240374afc998c1574db71f
/cursovideojuegos/theflostiproject/3rdParty/boost/libs/config/test/no_i64_limits_fail.cpp
f6bad8f7cf5d3a1e9a0cfba70ea55ea47fbec8df
[]
no_license
bugbit/cipsaoscar
601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4
52aa8b4b67d48f59e46cb43527480f8b3552e96d
refs/heads/master
2021-01-10T21:31:18.653163
2011-09-28T16:39:12
2011-09-28T16:39:12
33,032,640
0
0
null
null
null
null
UTF-8
C++
false
false
1,222
cpp
// This file was automatically generated on Sun Jul 25 11:47:49 GMTDT 2004, // by libs/config/tools/generate // Copyright John Maddock 2002-4. // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org/libs/config for the most recent version. // Test file for macro BOOST_NO_MS_INT64_NUMERIC_LIMITS // This file should not compile, if it does then // BOOST_NO_MS_INT64_NUMERIC_LIMITS need not be defined. // see boost_no_i64_limits.ipp for more details // Do not edit this file, it was generated automatically by // ../tools/generate from boost_no_i64_limits.ipp on // Sun Jul 25 11:47:49 GMTDT 2004 // Must not have BOOST_ASSERT_CONFIG set; it defeats // the objective of this file: #ifdef BOOST_ASSERT_CONFIG # undef BOOST_ASSERT_CONFIG #endif #include <boost/config.hpp> #include "test.hpp" #ifdef BOOST_NO_MS_INT64_NUMERIC_LIMITS #include "boost_no_i64_limits.ipp" #else #error "this file should not compile" #endif int main( int, char *[] ) { return boost_no_ms_int64_numeric_limits::test(); }
[ "ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a" ]
[ [ [ 1, 39 ] ] ]
1b8e8f280a6c988e902570310c07343a4cba8fed
36bf908bb8423598bda91bd63c4bcbc02db67a9d
/Include/CBerkeleyDB.h
d3c7b45fae697ffd865a2d31ac70a1f80e3d92b0
[]
no_license
code4bones/crawlpaper
edbae18a8b099814a1eed5453607a2d66142b496
f218be1947a9791b2438b438362bc66c0a505f99
refs/heads/master
2021-01-10T13:11:23.176481
2011-04-14T11:04:17
2011-04-14T11:04:17
44,686,513
0
1
null
null
null
null
UTF-8
C++
false
false
9,180
h
/* CBerkeleyDB.h Classe base per l'interfaccia con la libreria Berkeley DB 2.7.7 (http://www.sleepycat.com). Luca Piergentili, 04/11/99 [email protected] */ #ifndef _CBERKELEYDB_H #define _CBERKELEYDB_H 1 #include <string.h> #if defined(_WINDOWS) #include "window.h" #endif #include "typedef.h" #include "db.h" // crea la referenza alla DLL #ifdef _DEBUG #pragma comment(lib,"BerkeleyDB.d.lib") #ifdef PRAGMA_MESSAGE_VERBOSE #pragma message("\t\t\t"__FILE__"("STR(__LINE__)"): automatically linking with BerkeleyDB.d.dll") #endif #else #pragma comment(lib,"BerkeleyDB.lib") #ifdef PRAGMA_MESSAGE_VERBOSE #pragma message("\t\t\t"__FILE__"("STR(__LINE__)"): automatically linking with BerkeleyDB.dll") #endif #endif // generiche #define MAX_PRIMARYKEY_SIZE 10 // dimensione massima della chiave primaria #define MAX_KEYSIZE 1024 // dimensione massima della chiave per gli indici secondari #define MAX_FIELDSIZE MAX_KEYSIZE // dimensione massima del campo del record #define MAX_FIELDCOUNT 128 // numero massimo di campi per la tabella #define MAX_FIELDNAME 64 // dimensione massima per il nome del campo della tabella #define MAX_ERRORCODE_STRING 128 // stringa per messaggio d'errore /* ROW struttura per la definizione del campo del record */ struct ROW { int num; // numero progressivo del campo nel record (a base 0) int ofs; // offset (in bytes) del campo nel record (a base 0) char* name; // nome del campo char type; // tipo del campo int size; // dimensione del campo int dec; // decimali del campo char* value; // contenuto del campo (il buffer relativo e' l'istanza della struct per il record) unsigned long flags; // flag per operazioni (filtri) sul campo }; /* INDEX struttura per la definizione dell'indice */ struct INDEX { char filename[_MAX_PATH+1]; // nome file indice char* name; // nome indice char* fieldname; // nome del campo della tabella utilizzato come chiave int fieldnum; // numero progressivo del campo della tabella utilizzato come chiave (a base 0) }; /* TABLE_STAT struttura per lo status della tabella */ struct TABLE_STAT { int bof; // flag per inizio file int eof; // flag per fine file int errnum; // codice numerico ultimo errore char errstr[MAX_ERRORCODE_STRING+1]; // descrizione ultimo errore }; /* TABLE struttura per la definizione della tabella */ struct TABLE { char filename[_MAX_PATH+1]; // nome tabella int totfield; // numero totale di campi ROW* row; // array per la definizione del record, da allocare a run-time int totindex; // numero totale indici INDEX* index; // array per la definizione degli indici, da allocare a run-time TABLE_STAT stat; // status }; /* DATABASE struttura per la definizione del database */ struct DATABASE { TABLE table; // definizione della tabella unsigned long flags; // flags per porcherie varie }; /* DB_... codici di ritorno: 1000 info 2000 status >=3000 errori */ #define DB_NO_ERROR 0 // 1000 (info) #define DB_OK 1000 // 2000 (status) #define DB_RETCODE_STATUS_BASE 2000 // base per test #define DB_RETCODE_NOTFOUND DB_RETCODE_STATUS_BASE #define DB_RETCODE_BOF DB_RETCODE_STATUS_BASE+1 #define DB_RETCODE_EOF DB_RETCODE_STATUS_BASE+2 // 3000 (errori) #define DB_RETCODE_ERROR_BASE 3000 // base per test #define DB_RETCODE_EOPENTABLE DB_RETCODE_ERROR_BASE #define DB_RETCODE_EOPENCURSOR DB_RETCODE_ERROR_BASE+1 #define DB_RETCODE_EOPENINDEX DB_RETCODE_ERROR_BASE+2 #define DB_RETCODE_EOPENIDXCURSOR DB_RETCODE_ERROR_BASE+3 #define DB_RETCODE_EALREADYOPEN DB_RETCODE_ERROR_BASE+4 #define DB_RETCODE_ETABLENOTOPEN DB_RETCODE_ERROR_BASE+5 #define DB_RETCODE_EINDEXREQUIRED DB_RETCODE_ERROR_BASE+6 #define DB_RETCODE_ECREATETABLE DB_RETCODE_ERROR_BASE+7 #define DB_RETCODE_ECLOSETABLE DB_RETCODE_ERROR_BASE+8 #define DB_RETCODE_ECLOSECURSOR DB_RETCODE_ERROR_BASE+9 #define DB_RETCODE_ECLOSEINDEX DB_RETCODE_ERROR_BASE+10 #define DB_RETCODE_ECLOSEIDXCURSOR DB_RETCODE_ERROR_BASE+12 #define DB_RETCODE_EINVALIDHANDLE DB_RETCODE_ERROR_BASE+13 #define DB_RETCODE_EINVALIDPARAM DB_RETCODE_ERROR_BASE+14 #define DB_RETCODE_EINVALIDRESOURCE DB_RETCODE_ERROR_BASE+15 #define DB_RETCODE_EINVALIDCURSOR DB_RETCODE_ERROR_BASE+16 #define DB_RETCODE_EINVALIDINDEX DB_RETCODE_ERROR_BASE+17 #define DB_RETCODE_EINVALIDFIELDNUMBER DB_RETCODE_ERROR_BASE+18 #define DB_RETCODE_EINVALIDFIELDSIZE DB_RETCODE_ERROR_BASE+19 #define DB_RETCODE_EINVALIDPRIMARYKEYSIZE DB_RETCODE_ERROR_BASE+20 #define DB_RETCODE_ELOCKFAILURE DB_RETCODE_ERROR_BASE+21 #define DB_RETCODE_EALLOCFAILURE DB_RETCODE_ERROR_BASE+22 #define DB_RETCODE_EOPENFAILURE DB_RETCODE_ERROR_BASE+23 #define DB_RETCODE_ESYNCFAILURE DB_RETCODE_ERROR_BASE+24 #define DB_RETCODE_ESECONDARYKEYNOTFOUND DB_RETCODE_ERROR_BASE+24 // >3000 (errori) #define DB_RETCODE_ERROR 4000 #define DB_RETCODE_UNKNOWERROR 6666 // da usare per il posizionamento (se specificato al posto di DB_FIRST|DB_NEXT|DB_PREV|DB_LAST, usa DB_SET) #define DB_SEARCH 0 /* CBerkeleyDB */ class CBerkeleyDB { public: CBerkeleyDB(); virtual ~CBerkeleyDB(); int Open (u_int32_t = DB_CREATE); int IsOpen (void) const; int Create (void); int Close (void); int Insert (void); int Delete (void); int Replace (int nFieldNum,const char* pCurrentValue,const char* pReplaceValue); int Reindex (int nIndex = -1); int CheckIndex (int nIndex = -1); inline void ResetCursor (void) {m_pCurrentCursor = m_pDbCursor; m_nCurrentCursorNumber = -1;} int SetCursor (int); inline DBC* GetCursor (void) const {return(m_pCurrentCursor);} inline int GetCursorNumber (void) const {return(m_nCurrentCursorNumber);} inline char* GetPrimaryKeyData (void) const {return(m_Database.table.row[0].value);} inline int GetPrimaryKeySize (void) const {return(m_Database.table.row[0].size);} inline char* GetSecondaryKeyData (int nFieldNum) const {return(m_Database.table.row[nFieldNum].value);} inline int GetSecondaryKeySize (int nFieldNum) const {return(m_Database.table.row[nFieldNum].size);} inline int GetSecondaryKeyField (int nIndex) const {return(m_Database.table.index[nIndex].fieldnum);} int Get (u_int32_t db_goto_flag/*DB_SEARCH(usa DB_SET)|DB_FIRST|DB_NEXT|DB_PREV|DB_LAST*/,u_int32_t db_set_flag = DB_SET/*DB_SET|DB_SET_RANGE*/); inline int GetFirst (void) {return(Get(DB_FIRST,DB_SET));} inline int GetNext (void) {return(Get(DB_NEXT,DB_SET));} inline int GetPrev (void) {return(Get(DB_PREV,DB_SET));} inline int GetLast (void) {return(Get(DB_LAST,DB_SET));} int GetPrimaryKey (const char* pPrimaryKey); int GetSecondaryKey (int nIndex,u_int32_t db_set_flag = DB_SET/*DB_SET|DB_SET_RANGE*/); void PutKey (char* pValue,int nIndex); const char* GetField (int nFieldNum); void PutField (int nFieldNum,const char* pValue); inline DATABASE* GetDatabase (void) {return(&m_Database);} int SetLastError (int); void ResetLastError (void); int GetLastError (void); const char* GetLastErrorString (void); #if defined(_WINDOWS) inline void ShowErrors (BOOL bFlag) {m_bShowErrors = bFlag;} #endif private: int SyncDb (BOOL bFlush = FALSE); int SyncIdx (int nIndex,BOOL bFlush = FALSE); inline int FlushDb (void) {return(SyncDb(TRUE));} inline int FlushIdx (int nIndex) {return(SyncIdx(nIndex,TRUE));} inline void ResetKeyPair (void) {memset(&m_Key,'\0',sizeof(m_Key));} inline void ResetDataPair (void) {memset(&m_Data,'\0',sizeof(m_Data));} inline void ResetPair (void) {memset(&m_Key,'\0',sizeof(m_Key)); memset(&m_Data,'\0',sizeof(m_Data));} void ResetRecord (void); void BlankRecord (void); void MemoryToRecord (void); void RecordToMemory (void); DATABASE m_Database; // struct per la tabella char* m_pDataBuffer; // buffer per il campo data.data per i dati (campi del record) int m_nDataBufferSize; // dimensione int m_nRecordSize; // dimensione del record (somma dei campi) DB_INFO m_dbinfo; // (db) DBT m_Key,m_Data; // coppia chiave/valore (db) DB* m_pDbHandle; // handle della tabella (db) DBC* m_pDbCursor; // cursore per la vista sulla tabella (db) DBC* m_pCurrentCursor; // cursore corrente int m_nCurrentCursorNumber; // indice del cursore corrente DB** m_pIdxHandleArray; // array per gli handles degli indici DBC** m_pIdxCursorArray; // array per i cursori degli indici char m_szLastPrimaryKey[MAX_PRIMARYKEY_SIZE+1]; // buffer per la generazione della chiave primaria #if defined(_WINDOWS) BOOL m_bShowErrors; // flag per visualizzazione errori #endif }; #endif // _CBERKELEYDB_H
[ [ [ 1, 235 ] ] ]
741a636d59f3992c9c56c7e84df1ae74b9f299fb
5eb582292aeef7c56b13bc05accf71592d15931f
/include/raknet/PacketPool.h
ac773e4635ff1a86f6073ef879410b0296485f7d
[]
no_license
goebish/WiiBlob
9316a56f2a60a506ecbd856ab7c521f906b961a1
bef78fc2fdbe2d52749ed3bc965632dd699c2fea
refs/heads/master
2020-05-26T12:19:40.164479
2010-09-05T18:09:07
2010-09-05T18:09:07
188,229,195
0
0
null
null
null
null
UTF-8
C++
false
false
2,344
h
/* -*- mode: c++; c-file-style: raknet; tab-always-indent: nil; -*- */ /** * @file * @brief Manage memory for packet. * * This file is part of RakNet Copyright 2003 Rakkarsoft LLC and Kevin Jenkins. * * Usage of Raknet is subject to the appropriate licence agreement. * "Shareware" Licensees with Rakkarsoft LLC are subject to the * shareware license found at * http://www.rakkarsoft.com/shareWareLicense.html which you agreed to * upon purchase of a "Shareware license" "Commercial" Licensees with * Rakkarsoft LLC are subject to the commercial license found at * http://www.rakkarsoft.com/sourceCodeLicense.html which you agreed * to upon purchase of a "Commercial license" * Custom license users are subject to the terms therein. * All other users are * subject to 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. * * Refer to the appropriate license agreement for distribution, * modification, and warranty rights. */ #ifndef __PACKET_POOL #define __PACKET_POOL #include "SimpleMutex.h" #include "RakNetQueue.h" #include "NetworkTypes.h" /** * @brief Manage memory for packet. * * * The PacketPool class as multiple roles : * - Managing memory associated to packets * - Reuse memory of old packet to increase performances. * @note it implements Singleton Pattern * */ class PacketPool { public: /** * Constructor */ PacketPool(); /** * Destructor */ ~PacketPool(); /** * Get Memory for a packet * @return a Packet object */ Packet* GetPointer( void ); /** * Free Memory for a packet * @param p The packet to free */ void ReleasePointer( Packet *p ); /** * Clear the Packet Pool */ void ClearPool( void ); /** * Retrieve the unique instance of a PacketPool. * @return A pointer to the pool. */ static inline PacketPool* Instance() { return & I; } private: /** * Store packets */ BasicDataStructures::Queue<Packet*> pool; /** * Exclusive access to the pool */ SimpleMutex poolMutex; /** * Singleton Pattern unique instance */ static PacketPool I; #ifdef _DEBUG /** * In debugging stage, stores the number of packet released */ int packetsReleased; #endif }; #endif
[ [ [ 1, 100 ] ] ]
97f472bb321936aac3a8cdd7ce0aaa61e3c92c02
66a0801d891945b96a8adb12e3c05d68165964f9
/visual_feedback/thirdparty/python-cvgreyc/src/siftpp/sift.cpp
5e3b5c6e533033e013b63b44a8edfe70a1629c6c
[]
no_license
sdmiller/Hearing-Sheet-Music
a3c9149bedd16da06f6d1e2e0d0ed48a0c1e4e0e
06a8788097e904531082afde7ba9c279a5545acb
refs/heads/master
2021-01-01T19:34:29.835194
2011-12-12T07:24:01
2011-12-12T07:24:01
2,921,752
1
1
null
null
null
null
UTF-8
C++
false
false
42,924
cpp
// file: sift.cpp // author: Andrea Vedaldi // description: Sift definition // AUTORIGHTS // Copyright (c) 2006 The Regents of the University of California // All Rights Reserved. // // Created by Andrea Vedaldi (UCLA VisionLab) // // Permission to use, copy, modify, and distribute this software and its // documentation for educational, research and non-profit purposes, // without fee, and without a written agreement is hereby granted, // provided that the above copyright notice, this paragraph and the // following three paragraphs appear in all copies. // // This software program and documentation are copyrighted by The Regents // of the University of California. The software program and // documentation are supplied "as is", without any accompanying services // from The Regents. The Regents does not warrant that the operation of // the program will be uninterrupted or error-free. The end-user // understands that the program was developed for research purposes and // is advised not to rely exclusively on the program for any reason. // // This software embodies a method for which the following patent has // been issued: "Method and apparatus for identifying scale invariant // features in an image and use of same for locating an object in an // image," David G. Lowe, US Patent 6,711,293 (March 23, // 2004). Provisional application filed March 8, 1999. Asignee: The // University of British Columbia. // // IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY // FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, // INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND // ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE UNIVERSITY OF // CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" // BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE // MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. /** @mainpage Scale Invariant Feature Transform ** ** The algorithm is implemented by the class VL::Sift. **/ #include"sift.hpp" #include"sift-conv.tpp" #include<algorithm> #include<iostream> #include<sstream> #include<cassert> #include<cstring> using namespace VL ; // on startup, pre-compute expn(x) = exp(-x) namespace VL { namespace Detail { int const expnTableSize = 256 ; VL::float_t const expnTableMax = VL::float_t(25.0) ; VL::float_t expnTable [ expnTableSize + 1 ] ; struct buildExpnTable { buildExpnTable() { for(int k = 0 ; k < expnTableSize + 1 ; ++k) { expnTable[k] = exp( - VL::float_t(k) / expnTableSize * expnTableMax ) ; } } } _buildExpnTable ; } } namespace VL { namespace Detail { /** Comment eater istream manipulator */ class _cmnt {} cmnt ; /** @brief Extract a comment from a stream ** ** The function extracts a block of consecutive comments from an ** input stream. A comment is a sequence of whitespaces, followed by ** a `#' character, other characters and terminated at the next line ** ending. A block of comments is just a sequence of comments. **/ std::istream& operator>>(std::istream& is, _cmnt& manip) { char c ; char b [1024] ; is>>c ; if( c != '#' ) return is.putback(c) ; is.getline(b,1024) ; return is ; } } /** @brief Insert PGM file into stream ** ** The function iserts into the stream @a os the grayscale image @a ** im encoded as a PGM file. The immage is assumed to be normalized ** in the range 0.0 - 1.0. ** ** @param os output stream. ** @param im pointer to image data. ** @param width image width. ** @param height image height. ** @return the stream @a os. **/ std::ostream& insertPgm(std::ostream& os, pixel_t const* im, int width, int height) { os<< "P5" << "\n" << width << " " << height << "\n" << "255" << "\n" ; for(int y = 0 ; y < height ; ++y) { for(int x = 0 ; x < width ; ++x) { unsigned char v = (unsigned char) (std::max(std::min(*im++, 1.0f),0.f) * 255.0f) ; os << v ; } } return os ; } /** @brief Extract PGM file from stream. ** ** The function extracts from the stream @a in a grayscale image ** encoded as a PGM file. The function fills the structure @a buffer, ** containing the image dimensions and a pointer to the image data. ** ** The image data is an array of floats and is owned by the caller, ** which should erase it as in ** ** @code ** delete [] buffer.data. ** @endcode ** ** When the function encouters an error it throws a generic instance ** of VL::Exception. ** ** @param in input stream. ** @param buffer buffer descriptor to be filled. ** @return the stream @a in. **/ std::istream& extractPgm(std::istream& in, PgmBuffer& buffer) { pixel_t* im_pt ; int width ; int height ; int maxval ; char c ; in>>c ; if( c != 'P') VL_THROW("File is not in PGM format") ; bool is_ascii ; in>>c ; switch( c ) { case '2' : is_ascii = true ; break ; case '5' : is_ascii = false ; break ; default : VL_THROW("File is not in PGM format") ; } in >> Detail::cmnt >> width >> Detail::cmnt >> height >> Detail::cmnt >> maxval ; // after maxval no more comments, just a whitespace or newline {char trash ; in.get(trash) ;} if(maxval > 255) VL_THROW("Only <= 8-bit per channel PGM files are supported") ; if(! in.good()) VL_THROW("PGM header parsing error") ; im_pt = new pixel_t [ width*height ]; try { if( is_ascii ) { pixel_t* start = im_pt ; pixel_t* end = start + width*height ; pixel_t norm = pixel_t( maxval ) ; while( start != end ) { int i ; in >> i ; if( ! in.good() ) VL_THROW ("PGM parsing error file (width="<<width <<" height="<<height <<" maxval="<<maxval <<" at pixel="<<start-im_pt<<")") ; *start++ = pixel_t( i ) / norm ; } } else { std::streampos beg = in.tellg() ; char* buffer = new char [width*height] ; in.read(buffer, width*height) ; if( ! in.good() ) VL_THROW ("PGM parsing error file (width="<<width <<" height="<<height <<" maxval="<<maxval <<" at pixel="<<in.tellg()-beg<<")") ; pixel_t* start = im_pt ; pixel_t* end = start + width*height ; uint8_t* src = reinterpret_cast<uint8_t*>(buffer) ; while( start != end ) *start++ = *src++ / 255.0f ; } } catch(...) { delete [] im_pt ; throw ; } buffer.width = width ; buffer.height = height ; buffer.data = im_pt ; return in ; } // =================================================================== // Low level image operations // ------------------------------------------------------------------- namespace Detail { /** @brief Copy an image ** @param dst output imgage buffer. ** @param src input image buffer. ** @param width input image width. ** @param height input image height. **/ void copy(pixel_t* dst, pixel_t const* src, int width, int height) { memcpy(dst, src, sizeof(pixel_t)*width*height) ; } /** @brief Copy an image upsampling two times ** ** The destination buffer must be at least as big as two times the ** input buffer. Bilinear interpolation is used. ** ** @param dst output imgage buffer. ** @param src input image buffer. ** @param width input image width. ** @param height input image height. **/ void copyAndUpsampleRows (pixel_t* dst, pixel_t const* src, int width, int height) { for(int y = 0 ; y < height ; ++y) { pixel_t b, a ; b = a = *src++ ; for(int x = 0 ; x < width-1 ; ++x) { b = *src++ ; *dst = a ; dst += height ; *dst = 0.5*(a+b) ; dst += height ; a = b ; } *dst = b ; dst += height ; *dst = b ; dst += height ; dst += 1 - width * 2 * height ; } } /** @brief Copy and downasample an image ** ** The image is downsampled @a d times, i.e. reduced to @c 1/2^d of ** its original size. The parameters @a width and @a height are the ** size of the input image. The destination image is assumed to be @c ** floor(width/2^d) pixels wide and @c floor(height/2^d) pixels high. ** ** @param dst output imgage buffer. ** @param src input image buffer. ** @param width input image width. ** @param height input image height. ** @param d downsampling factor. **/ void copyAndDownsample(pixel_t* dst, pixel_t const* src, int width, int height, int d) { for(int y = 0 ; y < height ; y+=d) { pixel_t const * srcrowp = src + y * width ; for(int x = 0 ; x < width - (d-1) ; x+=d) { *dst++ = *srcrowp ; srcrowp += d ; } } } } /** @brief Smooth an image ** ** The function convolves the image @a src by a Gaussian kernel of ** variance @a s and writes the result to @a dst. The function also ** needs a scratch buffer @a dst of the same size of @a src and @a ** dst. ** ** @param dst output image buffer. ** @param temp scratch image buffer. ** @param src input image buffer. ** @param width width of the buffers. ** @param height height of the buffers. ** @param s standard deviation of the Gaussian kernel. **/ void Sift::smooth (pixel_t* dst, pixel_t* temp, pixel_t const* src, int width, int height, VL::float_t s) { // make sure a buffer larege enough has been allocated // to hold the filter int W = int( ceil( VL::float_t(4.0) * s ) ) ; if( ! filter ) { filterReserved = 0 ; } if( filterReserved < W ) { filterReserved = W ; if( filter ) delete [] filter ; filter = new pixel_t [ 2* filterReserved + 1 ] ; } // pre-compute filter for(int j = 0 ; j < 2*W+1 ; ++j) filter[j] = VL::pixel_t (std::exp (VL::float_t (-0.5 * (j-W) * (j-W) / (s*s) ))) ; // normalize to one normalize(filter, W) ; // convolve econvolve(temp, src, width, height, filter, W) ; econvolve(dst, temp, height, width, filter, W) ; } // =================================================================== // Sift(), ~Sift() // ------------------------------------------------------------------- /** @brief Initialize Gaussian scale space parameters ** ** @param _im_pt Source image data ** @param _width Soruce image width ** @param _height Soruce image height ** @param _sigman Nominal smoothing value of the input image. ** @param _sigma0 Base smoothing level. ** @param _O Number of octaves. ** @param _S Number of levels per octave. ** @param _omin First octave. ** @param _smin First level in each octave. ** @param _smax Last level in each octave. **/ Sift::Sift(const pixel_t* _im_pt, int _width, int _height, VL::float_t _sigman, VL::float_t _sigma0, int _O, int _S, int _omin, int _smin, int _smax) : sigman( _sigman ), sigma0( _sigma0 ), O( _O ), S( _S ), omin( _omin ), smin( _smin ), smax( _smax ), magnif( 3.0f ), normalizeDescriptor( true ), temp( NULL ), octaves( NULL ), filter( NULL ) { process(_im_pt, _width, _height) ; } /** @brief Destroy SIFT filter. **/ Sift::~Sift() { freeBuffers() ; } /** Allocate buffers. Buffer sizes depend on the image size and the ** value of omin. **/ void Sift:: prepareBuffers() { // compute buffer size int w = (omin >= 0) ? (width >> omin) : (width << -omin) ; int h = (omin >= 0) ? (height >> omin) : (height << -omin) ; int size = w*h* std::max ((smax - smin), 2*((smax+1) - (smin-2) +1)) ; if( temp && tempReserved == size ) return ; freeBuffers() ; // allocate temp = new pixel_t [ size ] ; tempReserved = size ; tempIsGrad = false ; tempOctave = 0 ; octaves = new pixel_t* [ O ] ; for(int o = 0 ; o < O ; ++o) { octaves[o] = new pixel_t [ (smax - smin + 1) * w * h ] ; w >>= 1 ; h >>= 1 ; } } /** @brief Free buffers. ** ** This function releases any buffer allocated by prepareBuffers(). ** ** @sa prepareBuffers(). **/ void Sift:: freeBuffers() { if( filter ) { delete [] filter ; } filter = 0 ; if( octaves ) { for(int o = 0 ; o < O ; ++o) { delete [] octaves[ o ] ; } delete [] octaves ; } octaves = 0 ; if( temp ) { delete [] temp ; } temp = 0 ; } // =================================================================== // getKeypoint // ------------------------------------------------------------------- inline double log2(double x) { static const double xxx = 1.0/log(2.0); return log(x)*xxx; } /** @brief Get keypoint from position and scale ** ** The function returns a keypoint with a given position and ** scale. Note that the keypoint structure contains fields that make ** sense only in conjunction with a specific scale space. Therefore ** the keypoint structure should be re-calculated whenever the filter ** is applied to a new image, even if the parameters @a x, @a y and ** @a sigma do not change. ** ** @param x x coordinate of the center. ** @peram y y coordinate of the center. ** @param sigma scale. ** @return Corresponing keypoint. **/ Sift::Keypoint Sift::getKeypoint(VL::float_t x, VL::float_t y, VL::float_t sigma) const { /* The formula linking the keypoint scale sigma to the octave and scale index is (1) sigma(o,s) = sigma0 2^(o+s/S) for which (2) o + s/S = log2 sigma/sigma0 == phi. In addition to the scale index s (which can be fractional due to scale interpolation) a keypoint has an integer scale index is too (which is the index of the scale level where it was detected in the DoG scale space). We have the constraints: - o and is are integer - is is in the range [smin+1, smax-2 ] - o is in the range [omin, omin+O-1] - is = rand(s) most of the times (but not always, due to the way s is obtained by quadratic interpolation of the DoG scale space). Depending on the values of smin and smax, often (2) has multiple solutions is,o that satisfy all constraints. In this case we choose the one with biggest index o (this saves a bit of computation). DETERMINING THE OCTAVE INDEX O From (2) we have o = phi - s/S and we want to pick the biggest possible index o in the feasible range. This corresponds to selecting the smallest possible index s. We write s = is + ds where in most cases |ds|<.5 (but in general |ds|<1). So we have o = phi - s/S, s = is + ds , |ds| < .5 (or |ds| < 1). Since is is in the range [smin+1,smax-2], s is in the range [smin+.5,smax-1.5] (or [smin,smax-1]), the number o is an integer in the range phi+[-smax+1.5,-smin-.5] (or phi+[-smax+1,-smin]). Thus the maximum value of o is obtained for o = floor(phi-smin-.5) (or o = floor(phi-smin)). Finally o is clamped to make sure it is contained in the feasible range. DETERMINING THE SCALE INDEXES S AND IS Given o we can derive is by writing (2) as s = is + ds = S(phi - o). We then take is = round(s) and clamp its value to be in the feasible range. */ int o,ix,iy,is ; VL::float_t s,phi ; phi = log2(sigma/sigma0) ; o = fast_floor( phi - (VL::float_t(smin)+.5)/S ) ; o = std::min(o, omin+O-1) ; o = std::max(o, omin ) ; s = S * (phi - o) ; is = int(s + 0.5) ; is = std::min(is, smax - 2) ; is = std::max(is, smin + 1) ; VL::float_t per = getOctaveSamplingPeriod(o) ; ix = int(x / per + 0.5) ; iy = int(y / per + 0.5) ; Keypoint key ; key.o = o ; key.ix = ix ; key.iy = iy ; key.is = is ; key.x = x ; key.y = y ; key.s = s ; key.sigma = sigma ; return key ; } // =================================================================== // process() // ------------------------------------------------------------------- /** @brief Compute Gaussian Scale Space ** ** The method computes the Gaussian scale space of the specified ** image. The scale space data is managed internally and can be ** accessed by means of getOctave() and getLevel(). ** ** @remark Calling this method will delete the list of keypoints ** constructed by detectKeypoints(). ** ** @param _im_pt pointer to image data. ** @param _width image width. ** @param _height image height . **/ void Sift:: process(const pixel_t* _im_pt, int _width, int _height) { using namespace Detail ; width = _width ; height = _height ; prepareBuffers() ; VL::float_t sigmak = powf(2.0f, 1.0 / S) ; VL::float_t dsigma0 = sigma0 * sqrt (1.0f - 1.0f / (sigmak*sigmak) ) ; // ----------------------------------------------------------------- // Make pyramid base // ----------------------------------------------------------------- if( omin < 0 ) { copyAndUpsampleRows(temp, _im_pt, width, height ) ; copyAndUpsampleRows(octaves[0], temp, height, 2*width ) ; for(int o = -1 ; o > omin ; --o) { copyAndUpsampleRows(temp, octaves[0], width << -o, height << -o) ; copyAndUpsampleRows(octaves[0], temp, height << -o, 2*(width << -o)) ; } } else if( omin > 0 ) { copyAndDownsample(octaves[0], _im_pt, width, height, 1 << omin) ; } else { copy(octaves[0], _im_pt, width, height) ; } { VL::float_t sa = sigma0 * powf(sigmak, smin) ; VL::float_t sb = sigman / powf(2.0f, omin) ; // review this if( sa > sb ) { VL::float_t sd = sqrt ( sa*sa - sb*sb ) ; smooth( octaves[0], temp, octaves[0], getOctaveWidth(omin), getOctaveHeight(omin), sd ) ; } } // ----------------------------------------------------------------- // Make octaves // ----------------------------------------------------------------- for(int o = omin ; o < omin+O ; ++o) { // Prepare octave base if( o > omin ) { int sbest = std::min(smin + S, smax) ; copyAndDownsample(getLevel(o, smin ), getLevel(o-1, sbest), getOctaveWidth(o-1), getOctaveHeight(o-1), 2 ) ; VL::float_t sa = sigma0 * powf(sigmak, smin ) ; VL::float_t sb = sigma0 * powf(sigmak, sbest - S ) ; if(sa > sb ) { VL::float_t sd = sqrt ( sa*sa - sb*sb ) ; smooth( getLevel(o,0), temp, getLevel(o,0), getOctaveWidth(o), getOctaveHeight(o), sd ) ; } } // Make other levels for(int s = smin+1 ; s <= smax ; ++s) { VL::float_t sd = dsigma0 * powf(sigmak, s) ; smooth( getLevel(o,s), temp, getLevel(o,s-1), getOctaveWidth(o), getOctaveHeight(o), sd ) ; } } } /** @brief Sift detector ** ** The function runs the SIFT detector on the stored Gaussian scale ** space (see process()). The detector consists in three steps ** ** - local maxima detection; ** - subpixel interpolation; ** - rejection of weak keypoints (@a threhsold); ** - rejection of keypoints on edge-like structures (@a edgeThreshold). ** ** As they are found, keypoints are added to an internal list. This ** list can be accessed by means of the member functions ** getKeypointsBegin() and getKeypointsEnd(). The list is ordered by ** octave, which is usefult to speed-up computeKeypointOrientations() ** and computeKeypointDescriptor(). **/ void Sift::detectKeypoints(VL::float_t threshold, VL::float_t edgeThreshold) { keypoints.clear() ; int nValidatedKeypoints = 0 ; // Process one octave per time for(int o = omin ; o < omin + O ; ++o) { int const xo = 1 ; int const yo = getOctaveWidth(o) ; int const so = getOctaveWidth(o) * getOctaveHeight(o) ; int const ow = getOctaveWidth(o) ; int const oh = getOctaveHeight(o) ; VL::float_t xperiod = getOctaveSamplingPeriod(o) ; // ----------------------------------------------------------------- // Difference of Gaussians // ----------------------------------------------------------------- pixel_t* dog = temp ; tempIsGrad = false ; { pixel_t* pt = dog ; for(int s = smin ; s <= smax-1 ; ++s) { pixel_t* srca = getLevel(o, s ) ; pixel_t* srcb = getLevel(o, s+1) ; pixel_t* enda = srcb ; while( srca != enda ) { *pt++ = *srcb++ - *srca++ ; } } } // ----------------------------------------------------------------- // Find points of extremum // ----------------------------------------------------------------- { pixel_t* pt = dog + xo + yo + so ; for(int s = smin+1 ; s <= smax-2 ; ++s) { for(int y = 1 ; y < oh - 1 ; ++y) { for(int x = 1 ; x < ow - 1 ; ++x) { pixel_t v = *pt ; // assert( (pt - x*xo - y*yo - (s-smin)*so) - dog == 0 ) ; #define CHECK_NEIGHBORS(CMP,SGN) \ ( v CMP ## = SGN 0.8 * threshold && \ v CMP *(pt + xo) && \ v CMP *(pt - xo) && \ v CMP *(pt + so) && \ v CMP *(pt - so) && \ v CMP *(pt + yo) && \ v CMP *(pt - yo) && \ \ v CMP *(pt + yo + xo) && \ v CMP *(pt + yo - xo) && \ v CMP *(pt - yo + xo) && \ v CMP *(pt - yo - xo) && \ \ v CMP *(pt + xo + so) && \ v CMP *(pt - xo + so) && \ v CMP *(pt + yo + so) && \ v CMP *(pt - yo + so) && \ v CMP *(pt + yo + xo + so) && \ v CMP *(pt + yo - xo + so) && \ v CMP *(pt - yo + xo + so) && \ v CMP *(pt - yo - xo + so) && \ \ v CMP *(pt + xo - so) && \ v CMP *(pt - xo - so) && \ v CMP *(pt + yo - so) && \ v CMP *(pt - yo - so) && \ v CMP *(pt + yo + xo - so) && \ v CMP *(pt + yo - xo - so) && \ v CMP *(pt - yo + xo - so) && \ v CMP *(pt - yo - xo - so) ) if( CHECK_NEIGHBORS(>,+) || CHECK_NEIGHBORS(<,-) ) { Keypoint k ; k.ix = x ; k.iy = y ; k.is = s ; keypoints.push_back(k) ; } pt += 1 ; } pt += 2 ; } pt += 2*yo ; } } // ----------------------------------------------------------------- // Refine local maxima // ----------------------------------------------------------------- { // refine KeypointsIter siter ; KeypointsIter diter ; for(diter = siter = keypointsBegin() + nValidatedKeypoints ; siter != keypointsEnd() ; ++siter) { int x = int( siter->ix ) ; int y = int( siter->iy ) ; int s = int( siter->is ) ; VL::float_t Dx=0,Dy=0,Ds=0,Dxx=0,Dyy=0,Dss=0,Dxy=0,Dxs=0,Dys=0 ; VL::float_t b [3] ; pixel_t* pt ; int dx = 0 ; int dy = 0 ; // must be exec. at least once for(int iter = 0 ; iter < 5 ; ++iter) { VL::float_t A[3*3] ; x += dx ; y += dy ; pt = dog + xo * x + yo * y + so * (s - smin) ; #define at(dx,dy,ds) (*( pt + (dx)*xo + (dy)*yo + (ds)*so)) #define Aat(i,j) (A[(i)+(j)*3]) /* Compute the gradient. */ Dx = 0.5 * (at(+1,0,0) - at(-1,0,0)) ; Dy = 0.5 * (at(0,+1,0) - at(0,-1,0)); Ds = 0.5 * (at(0,0,+1) - at(0,0,-1)) ; /* Compute the Hessian. */ Dxx = (at(+1,0,0) + at(-1,0,0) - 2.0 * at(0,0,0)) ; Dyy = (at(0,+1,0) + at(0,-1,0) - 2.0 * at(0,0,0)) ; Dss = (at(0,0,+1) + at(0,0,-1) - 2.0 * at(0,0,0)) ; Dxy = 0.25 * ( at(+1,+1,0) + at(-1,-1,0) - at(-1,+1,0) - at(+1,-1,0) ) ; Dxs = 0.25 * ( at(+1,0,+1) + at(-1,0,-1) - at(-1,0,+1) - at(+1,0,-1) ) ; Dys = 0.25 * ( at(0,+1,+1) + at(0,-1,-1) - at(0,-1,+1) - at(0,+1,-1) ) ; /* Solve linear system. */ Aat(0,0) = Dxx ; Aat(1,1) = Dyy ; Aat(2,2) = Dss ; Aat(0,1) = Aat(1,0) = Dxy ; Aat(0,2) = Aat(2,0) = Dxs ; Aat(1,2) = Aat(2,1) = Dys ; b[0] = - Dx ; b[1] = - Dy ; b[2] = - Ds ; // Gauss elimination for(int j = 0 ; j < 3 ; ++j) { // look for leading pivot VL::float_t maxa = 0 ; VL::float_t maxabsa = 0 ; int maxi = -1 ; int i ; for(i = j ; i < 3 ; ++i) { VL::float_t a = Aat(i,j) ; VL::float_t absa = fabsf( a ) ; if ( absa > maxabsa ) { maxa = a ; maxabsa = absa ; maxi = i ; } } // singular? if( maxabsa < 1e-10f ) { b[0] = 0 ; b[1] = 0 ; b[2] = 0 ; break ; } i = maxi ; // swap j-th row with i-th row and // normalize j-th row for(int jj = j ; jj < 3 ; ++jj) { std::swap( Aat(j,jj) , Aat(i,jj) ) ; Aat(j,jj) /= maxa ; } std::swap( b[j], b[i] ) ; b[j] /= maxa ; // elimination for(int ii = j+1 ; ii < 3 ; ++ii) { VL::float_t x = Aat(ii,j) ; for(int jj = j ; jj < 3 ; ++jj) { Aat(ii,jj) -= x * Aat(j,jj) ; } b[ii] -= x * b[j] ; } } // backward substitution for(int i = 2 ; i > 0 ; --i) { VL::float_t x = b[i] ; for(int ii = i-1 ; ii >= 0 ; --ii) { b[ii] -= x * Aat(ii,i) ; } } /* If the translation of the keypoint is big, move the keypoint * and re-iterate the computation. Otherwise we are all set. */ dx= ((b[0] > 0.6 && x < ow-2) ? 1 : 0 ) + ((b[0] < -0.6 && x > 1 ) ? -1 : 0 ) ; dy= ((b[1] > 0.6 && y < oh-2) ? 1 : 0 ) + ((b[1] < -0.6 && y > 1 ) ? -1 : 0 ) ; /* std::cout<<x<<","<<y<<"="<<at(0,0,0) <<"(" <<at(0,0,0)+0.5 * (Dx * b[0] + Dy * b[1] + Ds * b[2])<<")" <<" "<<std::flush ; */ if( dx == 0 && dy == 0 ) break ; } /* std::cout<<std::endl ; */ // Accept-reject keypoint { VL::float_t val = at(0,0,0) + 0.5 * (Dx * b[0] + Dy * b[1] + Ds * b[2]) ; VL::float_t score = (Dxx+Dyy)*(Dxx+Dyy) / (Dxx*Dyy - Dxy*Dxy) ; VL::float_t xn = x + b[0] ; VL::float_t yn = y + b[1] ; VL::float_t sn = s + b[2] ; if(fast_abs(val) > threshold && score < (edgeThreshold+1)*(edgeThreshold+1)/edgeThreshold && score >= 0 && fast_abs(b[0]) < 1.5 && fast_abs(b[1]) < 1.5 && fast_abs(b[2]) < 1.5 && xn >= 0 && xn <= ow-1 && yn >= 0 && yn <= oh-1 && sn >= smin && sn <= smax ) { diter->o = o ; diter->ix = x ; diter->iy = y ; diter->is = s ; diter->x = xn * xperiod ; diter->y = yn * xperiod ; diter->s = sn ; diter->sigma = getScaleFromIndex(o,sn) ; ++diter ; } } } // next candidate keypoint // prepare for next octave keypoints.resize( diter - keypoints.begin() ) ; nValidatedKeypoints = keypoints.size() ; } // refine block } // next octave } // =================================================================== // computeKeypointOrientations() // ------------------------------------------------------------------- /** @brief Compute modulus and phase of the gradient ** ** The function computes the modulus and the angle of the gradient of ** the specified octave @a o. The result is stored in a temporary ** internal buffer accessed by computeKeypointDescriptor() and ** computeKeypointOrientations(). ** ** The SIFT detector provides keypoint with scale index s in the ** range @c smin+1 and @c smax-2. As such, the buffer contains only ** these levels. ** ** If called mutliple time on the same data, the function exits ** immediately. ** ** @param o octave of interest. **/ void Sift::prepareGrad(int o) { int const ow = getOctaveWidth(o) ; int const oh = getOctaveHeight(o) ; int const xo = 1 ; int const yo = ow ; int const so = oh*ow ; if( ! tempIsGrad || tempOctave != o ) { // compute dx/dy for(int s = smin+1 ; s <= smax-2 ; ++s) { for(int y = 1 ; y < oh-1 ; ++y ) { pixel_t* src = getLevel(o, s) + xo + yo*y ; pixel_t* end = src + ow - 1 ; pixel_t* grad = 2 * (xo + yo*y + (s - smin -1)*so) + temp ; while(src != end) { VL::float_t Gx = 0.5 * ( *(src+xo) - *(src-xo) ) ; VL::float_t Gy = 0.5 * ( *(src+yo) - *(src-yo) ) ; VL::float_t m = fast_sqrt( Gx*Gx + Gy*Gy ) ; VL::float_t t = fast_mod_2pi( fast_atan2(Gy, Gx) + VL::float_t(2*M_PI) ); *grad++ = pixel_t( m ) ; *grad++ = pixel_t( t ) ; ++src ; } } } } tempIsGrad = true ; tempOctave = o ; } /** @brief Compute the orientation(s) of a keypoint ** ** The function computes the orientation of the specified keypoint. ** The function returns up to four different orientations, obtained ** as strong peaks of the histogram of gradient orientations (a ** keypoint can theoretically generate more than four orientations, ** but this is very unlikely). ** ** @remark The function needs to compute the gradient modululs and ** orientation of the Gaussian scale space octave to which the ** keypoint belongs. The result is cached, but discarded if different ** octaves are visited. Thereofre it is much quicker to evaluate the ** keypoints in their natural octave order. ** ** The keypoint must lie within the scale space. In particular, the ** scale index is supposed to be in the range @c smin+1 and @c smax-1 ** (this is from the SIFT detector). If this is not the case, the ** computation is silently aborted and no orientations are returned. ** ** @param angles buffers to store the resulting angles. ** @param keypoint keypoint to process. ** @return number of orientations found. **/ int Sift::computeKeypointOrientations(VL::float_t angles [4], Keypoint keypoint) { int const nbins = 36 ; VL::float_t const winFactor = 1.5 ; VL::float_t hist [nbins] ; // octave int o = keypoint.o ; VL::float_t xperiod = getOctaveSamplingPeriod(o) ; // offsets to move in the Gaussian scale space octave const int ow = getOctaveWidth(o) ; const int oh = getOctaveHeight(o) ; const int xo = 2 ; const int yo = xo * ow ; const int so = yo * oh ; // keypoint fractional geometry VL::float_t x = keypoint.x / xperiod ; VL::float_t y = keypoint.y / xperiod ; VL::float_t sigma = keypoint.sigma / xperiod ; // shall we use keypoints.ix,iy,is here? int xi = ((int) (x+0.5)) ; int yi = ((int) (y+0.5)) ; int si = keypoint.is ; VL::float_t const sigmaw = winFactor * sigma ; int W = (int) floor(3.0 * sigmaw) ; // skip the keypoint if it is out of bounds if(o < omin || o >=omin+O || xi < 0 || xi > ow-1 || yi < 0 || yi > oh-1 || si < smin+1 || si > smax-2 ) { std::cerr<<"!"<<std::endl ; return 0 ; } // make sure that the gradient buffer is filled with octave o prepareGrad(o) ; // clear the SIFT histogram std::fill(hist, hist + nbins, 0) ; // fill the SIFT histogram pixel_t* pt = temp + xi * xo + yi * yo + (si - smin -1) * so ; #undef at #define at(dx,dy) (*(pt + (dx)*xo + (dy)*yo)) for(int ys = std::max(-W, 1-yi) ; ys <= std::min(+W, oh -2 -yi) ; ++ys) { for(int xs = std::max(-W, 1-xi) ; xs <= std::min(+W, ow -2 -xi) ; ++xs) { VL::float_t dx = xi + xs - x; VL::float_t dy = yi + ys - y; VL::float_t r2 = dx*dx + dy*dy ; // limit to a circular window if(r2 >= W*W+0.5) continue ; VL::float_t wgt = VL::fast_expn( r2 / (2*sigmaw*sigmaw) ) ; VL::float_t mod = *(pt + xs*xo + ys*yo) ; VL::float_t ang = *(pt + xs*xo + ys*yo + 1) ; // int bin = (int) floor( nbins * ang / (2*M_PI) ) ; int bin = (int) floor( nbins * ang / (2*M_PI) ) ; hist[bin] += mod * wgt ; } } // smooth the histogram #if defined VL_LOWE_STRICT // Lowe's version apparently has a little issue with orientations // around + or - pi, which we reproduce here for compatibility for (int iter = 0; iter < 6; iter++) { VL::float_t prev = hist[nbins/2] ; for (int i = nbins/2-1; i >= -nbins/2 ; --i) { int const j = (i + nbins) % nbins ; int const jp = (i - 1 + nbins) % nbins ; VL::float_t newh = (prev + hist[j] + hist[jp]) / 3.0; prev = hist[j] ; hist[j] = newh ; } } #else // this is slightly more correct for (int iter = 0; iter < 6; iter++) { VL::float_t prev = hist[nbins-1] ; VL::float_t first = hist[0] ; int i ; for (i = 0; i < nbins - 1; i++) { VL::float_t newh = (prev + hist[i] + hist[(i+1) % nbins]) / 3.0; prev = hist[i] ; hist[i] = newh ; } hist[i] = (prev + hist[i] + first)/3.0 ; } #endif // find the histogram maximum VL::float_t maxh = * std::max_element(hist, hist + nbins) ; // find peaks within 80% from max int nangles = 0 ; for(int i = 0 ; i < nbins ; ++i) { VL::float_t h0 = hist [i] ; VL::float_t hm = hist [(i-1+nbins) % nbins] ; VL::float_t hp = hist [(i+1+nbins) % nbins] ; // is this a peak? if( h0 > 0.8*maxh && h0 > hm && h0 > hp ) { // quadratic interpolation // VL::float_t di = -0.5 * (hp - hm) / (hp+hm-2*h0) ; VL::float_t di = -0.5 * (hp - hm) / (hp+hm-2*h0) ; VL::float_t th = 2*M_PI * (i+di+0.5) / nbins ; angles [ nangles++ ] = th ; if( nangles == 4 ) goto enough_angles ; } } enough_angles: return nangles ; } // =================================================================== // computeKeypointDescriptor() // ------------------------------------------------------------------- namespace Detail { /** Normalizes in norm L_2 a descriptor. */ void normalize_histogram(VL::float_t* L_begin, VL::float_t* L_end) { VL::float_t* L_iter ; VL::float_t norm = 0.0 ; for(L_iter = L_begin; L_iter != L_end ; ++L_iter) norm += (*L_iter) * (*L_iter) ; norm = fast_sqrt(norm) ; for(L_iter = L_begin; L_iter != L_end ; ++L_iter) *L_iter /= (norm + std::numeric_limits<VL::float_t>::epsilon() ) ; } } /** @brief SIFT descriptor ** ** The function computes the descriptor of the keypoint @a keypoint. ** The function fills the buffer @a descr_pt which must be large ** enough. The funciton uses @a angle0 as rotation of the keypoint. ** By calling the function multiple times, different orientations can ** be evaluated. ** ** @remark The function needs to compute the gradient modululs and ** orientation of the Gaussian scale space octave to which the ** keypoint belongs. The result is cached, but discarded if different ** octaves are visited. Thereofre it is much quicker to evaluate the ** keypoints in their natural octave order. ** ** The function silently abort the computations of keypoints without ** the scale space boundaries. See also siftComputeOrientations(). **/ void Sift::computeKeypointDescriptor (VL::float_t* descr_pt, Keypoint keypoint, VL::float_t angle0) { /* The SIFT descriptor is a three dimensional histogram of the position * and orientation of the gradient. There are NBP bins for each spatial * dimesions and NBO bins for the orientation dimesion, for a total of * NBP x NBP x NBO bins. * * The support of each spatial bin has an extension of SBP = 3sigma * pixels, where sigma is the scale of the keypoint. Thus all the bins * together have a support SBP x NBP pixels wide . Since weighting and * interpolation of pixel is used, another half bin is needed at both * ends of the extension. Therefore, we need a square window of SBP x * (NBP + 1) pixels. Finally, since the patch can be arbitrarly rotated, * we need to consider a window 2W += sqrt(2) x SBP x (NBP + 1) pixels * wide. */ // octave int o = keypoint.o ; VL::float_t xperiod = getOctaveSamplingPeriod(o) ; // offsets to move in Gaussian scale space octave const int ow = getOctaveWidth(o) ; const int oh = getOctaveHeight(o) ; const int xo = 2 ; const int yo = xo * ow ; const int so = yo * oh ; // keypoint fractional geometry VL::float_t x = keypoint.x / xperiod; VL::float_t y = keypoint.y / xperiod ; VL::float_t sigma = keypoint.sigma / xperiod ; VL::float_t st0 = sinf( angle0 ) ; VL::float_t ct0 = cosf( angle0 ) ; // shall we use keypoints.ix,iy,is here? int xi = ((int) (x+0.5)) ; int yi = ((int) (y+0.5)) ; int si = keypoint.is ; // const VL::float_t magnif = 3.0f ; const int NBO = 8 ; const int NBP = 4 ; const VL::float_t SBP = magnif * sigma ; const int W = (int) floor (sqrt(2.0) * SBP * (NBP + 1) / 2.0 + 0.5) ; /* Offsets to move in the descriptor. */ /* Use Lowe's convention. */ const int binto = 1 ; const int binyo = NBO * NBP ; const int binxo = NBO ; // const int bino = NBO * NBP * NBP ; int bin ; // check bounds if(o < omin || o >=omin+O || xi < 0 || xi > ow-1 || yi < 0 || yi > oh-1 || si < smin+1 || si > smax-2 ) return ; // make sure gradient buffer is up-to-date prepareGrad(o) ; std::fill( descr_pt, descr_pt + NBO*NBP*NBP, 0 ) ; /* Center the scale space and the descriptor on the current keypoint. * Note that dpt is pointing to the bin of center (SBP/2,SBP/2,0). */ pixel_t const * pt = temp + xi*xo + yi*yo + (si - smin - 1)*so ; VL::float_t * dpt = descr_pt + (NBP/2) * binyo + (NBP/2) * binxo ; #define atd(dbinx,dbiny,dbint) *(dpt + (dbint)*binto + (dbiny)*binyo + (dbinx)*binxo) /* * Process pixels in the intersection of the image rectangle * (1,1)-(M-1,N-1) and the keypoint bounding box. */ for(int dyi = std::max(-W, 1-yi) ; dyi <= std::min(+W, oh-2-yi) ; ++dyi) { for(int dxi = std::max(-W, 1-xi) ; dxi <= std::min(+W, ow-2-xi) ; ++dxi) { // retrieve VL::float_t mod = *( pt + dxi*xo + dyi*yo + 0 ) ; VL::float_t angle = *( pt + dxi*xo + dyi*yo + 1 ) ; VL::float_t theta = fast_mod_2pi(-angle + angle0) ; // lowe compatible ? // fractional displacement VL::float_t dx = xi + dxi - x; VL::float_t dy = yi + dyi - y; // get the displacement normalized w.r.t. the keypoint // orientation and extension. VL::float_t nx = ( ct0 * dx + st0 * dy) / SBP ; VL::float_t ny = (-st0 * dx + ct0 * dy) / SBP ; VL::float_t nt = NBO * theta / (2*M_PI) ; // Get the gaussian weight of the sample. The gaussian window // has a standard deviation equal to NBP/2. Note that dx and dy // are in the normalized frame, so that -NBP/2 <= dx <= NBP/2. VL::float_t const wsigma = NBP/2 ; VL::float_t win = VL::fast_expn((nx*nx + ny*ny)/(2.0 * wsigma * wsigma)) ; // The sample will be distributed in 8 adjacent bins. // We start from the ``lower-left'' bin. int binx = fast_floor( nx - 0.5 ) ; int biny = fast_floor( ny - 0.5 ) ; int bint = fast_floor( nt ) ; VL::float_t rbinx = nx - (binx+0.5) ; VL::float_t rbiny = ny - (biny+0.5) ; VL::float_t rbint = nt - bint ; int dbinx ; int dbiny ; int dbint ; // Distribute the current sample into the 8 adjacent bins for(dbinx = 0 ; dbinx < 2 ; ++dbinx) { for(dbiny = 0 ; dbiny < 2 ; ++dbiny) { for(dbint = 0 ; dbint < 2 ; ++dbint) { if( binx+dbinx >= -(NBP/2) && binx+dbinx < (NBP/2) && biny+dbiny >= -(NBP/2) && biny+dbiny < (NBP/2) ) { VL::float_t weight = win * mod * fast_abs (1 - dbinx - rbinx) * fast_abs (1 - dbiny - rbiny) * fast_abs (1 - dbint - rbint) ; atd(binx+dbinx, biny+dbiny, (bint+dbint) % NBO) += weight ; } } } } } } /* Standard SIFT descriptors are normalized, truncated and normalized again */ if( normalizeDescriptor ) { /* Normalize the histogram to L2 unit length. */ Detail::normalize_histogram(descr_pt, descr_pt + NBO*NBP*NBP) ; /* Truncate at 0.2. */ for(bin = 0; bin < NBO*NBP*NBP ; ++bin) { if (descr_pt[bin] > 0.2) descr_pt[bin] = 0.2; } /* Normalize again. */ Detail::normalize_histogram(descr_pt, descr_pt + NBO*NBP*NBP) ; } } // namespace VL }
[ "sdmiller@malin.(none)" ]
[ [ [ 1, 1386 ] ] ]
ed6164485017dfc2c8da758bfe256018052fc9da
bfe8eca44c0fca696a0031a98037f19a9938dd26
/redundancy/VNClib/src/VNConnection.cpp
3d85520bc21bc03ea0ed258383905fa45b0db14a
[]
no_license
luge/foolject
a190006bc0ed693f685f3a8287ea15b1fe631744
2f4f13a221a0fa2fecab2aaaf7e2af75c160d90c
refs/heads/master
2021-01-10T07:41:06.726526
2011-01-21T10:25:22
2011-01-21T10:25:22
36,303,977
0
0
null
null
null
null
UTF-8
C++
false
false
20,888
cpp
// VNConnection.cpp: implementation of the CVNConnection class. // ////////////////////////////////////////////////////////////////////// #include <stdio.h> #ifndef POSIX #include <time.h> #include "process.h" #endif #include "VNConnection.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// #ifdef POSIX extern char *sys_errlist[]; #endif #ifdef ONLYFOR_RM #define CHANNELCONNECTTIMEOUT 100 #else #define CHANNELCONNECTTIMEOUT 1000 #endif CVNConnection::CVNConnection() { InitialConnection(); } CVNConnection::CVNConnection(unsigned int nChanCnt) { InitialConnection(); } //*********************************************************************************** void CVNConnection::InitialConnection() { #ifndef POSIX WSADATA wsd; WSAStartup(MAKEWORD(2,2),&wsd); #endif m_nRecCnt=0; m_nPort=0; m_sListener=INVALID_SOCKET; m_thrdLisn=NULL; m_nHeaderFree=0; m_chCast=NULL; m_chUDP=NULL; m_nCastRange=0; m_CastStart.s_addr=0; m_QueueGroup=NULL; m_nSndCnt=0; int i=0; for (i=0;i<MAXSENDCHAN;i++) { m_arraySendChan[i]=NULL; m_arrayTimes[i]=0; m_thrdClnt[i]=NULL; } m_nTailFree=i-1; for (i=0;i<MAXRECVCHAN;i++) { m_arrayRecvFree[i]=i+1; m_arrayRecvChan[i]=NULL; m_thrdServ[i]=NULL; } #ifndef POSIX InitializeCriticalSection(&m_csArray); #else pthread_mutex_init(&m_csArray,NULL); #endif } //*********************************************************************************** CVNConnection::~CVNConnection() { ClearListenerHandle(); ClearChannelHandle(); #ifndef POSIX WSACleanup(); DeleteCriticalSection(&m_csArray); #else pthread_mutex_destroy(&m_csArray); #endif } //*********************************************************************************** void CVNConnection::ClearListenerHandle() { if (m_sListener!=INVALID_SOCKET) { int nRet1=0; nRet1=shutdown(m_sListener,SD_BOTH); int nRet2=0; nRet2=closesocket(m_sListener); m_sListener=INVALID_SOCKET; printf("close listener socket\n"); } if (m_thrdLisn!=0) { #ifndef POSIX WaitForSingleObject(m_thrdLisn,INFINITE); CloseHandle(m_thrdLisn); m_thrdLisn=NULL; #else pthread_join(m_thrdLisn,NULL); m_thrdLisn=0; #endif } unsigned int i=0; for (i=0;i<MAXRECVCHAN;i++) { if (m_arrayRecvChan[i]!=NULL) m_arrayRecvChan[i]->Disconnect(); //m_arrayRecvChan[i]->ResetPeerLong(); } for (i=0;i<MAXRECVCHAN;i++) { if (m_thrdServ[i]!=NULL) { #ifndef POSIX WaitForSingleObject(m_thrdServ[i],INFINITE); CloseHandle(m_thrdServ[i]); m_thrdServ[i]=NULL; #else pthread_join(m_thrdServ[i],NULL); m_thrdServ[i]=0; #endif } } for (i=0;i<MAXRECVCHAN;i++) { m_arrayRecvFree[i]=i+1; CVNChannel * pch=m_arrayRecvChan[i]; if (pch!=NULL) { delete pch; m_arrayRecvChan[i]=NULL; } m_nRecCnt=0; } m_nHeaderFree=0; m_nTailFree=MAXRECVCHAN-1; printf("clear m_arrayRecvChan \n"); } //*********************************************************************************** void CVNConnection::ClearChannelHandle() { unsigned int i=0; for (i=0;i<MAXSENDCHAN;i++) { if (m_arraySendChan[i]!=NULL) { m_arraySendChan[i]->Disconnect(); m_arraySendChan[i]->ResetPeerLong(); } } for (i=0;i<MAXSENDCHAN;i++) { if (m_thrdClnt[i]!=NULL) { #ifndef POSIX WaitForSingleObject(m_thrdClnt[i],INFINITE); CloseHandle(m_thrdClnt[i]); m_thrdClnt[i]=NULL; #else pthread_join(m_thrdClnt[i],NULL); m_thrdClnt[i]=0; #endif } } for (i=0;i<MAXSENDCHAN;i++) { if (m_arraySendChan[i]!=NULL) { delete (m_arraySendChan[i]); m_arraySendChan[i]=NULL; } } m_nSndCnt=0; } //*********************************************************************************** #ifdef POSIX extern "C" void * CVNConnection::ListenProc(void * pCon) #else void * CVNConnection::ListenProc(void * pCon) #endif { CVNConnection * pc=(CVNConnection*)pCon; pc->VNListenCore(); return NULL; } //*********************************************************************************** #ifdef POSIX extern "C" void * CVNConnection::ServRecvThreadProc(void * param) #else void * CVNConnection::ServRecvThreadProc(void * param) #endif { tagThreadParam * p=(tagThreadParam*)param; CVNNetMsg * msg=NULL; CVNChannel * pch=NULL; CVNConnection * pcn=p->pcn; unsigned int nChanID=p->nChanID ; delete param; pch=pcn->ReturnChannelPointer(TRUE,nChanID); printf("server thread start\n"); while (TRUE) { int nErr=0; msg=pch->RecvMsg(&nErr,0,10); if (nErr==RS_Event||nErr==RS_Closed||nErr==RS_Failed) { // printf("error : %x\n",nErr); break; } if (nErr==RS_Timeout) { continue; } int nID=msg->GetDesQueueID(); msg->SetConnectionID(nChanID); if (pcn->m_QueueGroup->insertMsg(nID,msg)==FALSE) { #ifdef FOOLBEAR_DEBUG LogByLevel(DSS_VP, DEBUGLVL, nID + 1, 0, "FOOLBEAR_DEBUG: insertMsg failed, source queue %d", msg->GetSrcQueueID()); #endif delete msg; } } // printf("thread quit,%d\n",nChanID); pcn->AddAFreeChannel(nChanID); return NULL; } //*********************************************************************************** #ifdef POSIX extern "C" void * CVNConnection::ClientRecvThreadProc(void * param) #else void * CVNConnection::ClientRecvThreadProc(void * param) #endif { tagThreadParam * p=(tagThreadParam*)param; CVNNetMsg * msg=NULL; CVNChannel * pch=NULL; CVNConnection * pcn=p->pcn; unsigned int nChanID=p->nChanID ; delete param; pch=pcn->ReturnChannelPointer(FALSE,nChanID); // printf("thread start,%d\n",nChanID); while (TRUE) { int nErr=0; msg=pch->RecvMsg(&nErr,0,10); if (nErr==RS_Event||nErr==RS_Closed||nErr==RS_Failed) { // printf("error : %x\n",nErr); break; } if (nErr==RS_Timeout) { continue; } int nID=msg->GetDesQueueID(); // printf("thread start,chan is %d, queue is %d\n",nChanID, nID); msg->SetConnectionID(nChanID); if (pcn->m_QueueGroup->insertMsg(nID,msg)==FALSE) { #ifdef FOOLBEAR_DEBUG LogByLevel(DSS_VP, DEBUGLVL, nID + 1, 0, "FOOLBEAR_DEBUG: insertMsg failed, source queue %d", msg->GetSrcQueueID()); #endif delete msg; } } return NULL; // printf("thread quit,%d\n",nChanID); } //*********************************************************************************** BOOL CVNConnection::ChannelConnect(unsigned int nSendChanID,long nServAddr,int nPort,unsigned long lTimeout /*usecond*/) { if (m_arraySendChan[nSendChanID]==NULL) m_arraySendChan[nSendChanID]=new CVNChannel; if (m_arraySendChan[nSendChanID]->Open(nServAddr,nPort,lTimeout)==FALSE) { return FALSE; } CVNNetMsg * msg=NULL; int nErr=0; msg=m_arraySendChan[nSendChanID]->RecvMsg(&nErr); if (msg==NULL) { return FALSE; } else { if (msg->GetType()!=Control) { VNReleaseMsg(msg); return FALSE; } } VNReleaseMsg(msg); tagThreadParam * param=new tagThreadParam; param->pcn=this; param->nChanID=nSendChanID; param->puser=NULL; unsigned lThreadNum=0; #ifndef POSIX m_thrdClnt[nSendChanID]=(HANDLE)_beginthreadex(NULL,0,(unsigned int (__stdcall *)(void *))ClientRecvThreadProc,param,0,&lThreadNum); #else pthread_t thread1; pthread_attr_t thrdattr; pthread_attr_init(&thrdattr); pthread_attr_setdetachstate(&thrdattr,PTHREAD_CREATE_DETACHED); pthread_create(&m_thrdClnt[nSendChanID],&thrdattr,CVNConnection::ClientRecvThreadProc,(void*)(param)); #endif return TRUE; } //*********************************************************************************** BOOL CVNConnection::VNBindUDPMode(int port) { if (port<0) return FALSE; if (m_chUDP!=NULL) return TRUE; m_chUDP=new CVNChannel; if ( m_chUDP->BindBroadCastMode(port,FALSE)==FALSE) { delete m_chUDP; m_chUDP=NULL; m_CastStart.s_addr=0; m_nCastRange=0; return FALSE; } return TRUE; } //*********************************************************************************** BOOL CVNConnection::VNBindBroadCastMode(int port) { if (port<0) return FALSE; if (m_chCast!=NULL) return TRUE; m_chCast=new CVNChannel; if ( m_chCast->BindBroadCastMode(port)==FALSE) { delete m_chCast; m_chCast=NULL; m_CastStart.s_addr=0; m_nCastRange=0; return FALSE; } return TRUE; } //*********************************************************************************** BOOL CVNConnection::VNUnBindBroadCastMode() { if (m_chCast==NULL) return TRUE; delete m_chCast; m_chCast=NULL; return TRUE; } //*********************************************************************************** BOOL CVNConnection::VNUnBindUDPMode() { return VNUnBindBroadCastMode(); } //*********************************************************************************** CVNNetMsg* CVNConnection::VNRecvUDPMsg(int nLength,char * lpAddr,int nAddrLen,unsigned int nTimeout) { if (nLength<128) return NULL; if (nAddrLen<15) return NULL; if (lpAddr==NULL) return NULL; if (m_chUDP==NULL) return NULL; CVNNetMsg* msg=NULL; return m_chUDP->RecvBroadCastMsg(NULL,nLength,lpAddr,nAddrLen,nTimeout); } //*********************************************************************************** CVNNetMsg * CVNConnection::VNRecvBroadCastMsg(int nLength,char * lpAddr,int nAddrLen,unsigned int nTimeout) { if (nLength<128) return NULL; if (nAddrLen<15) return NULL; if (lpAddr==NULL) return NULL; if (m_chCast==NULL) return NULL; CVNNetMsg* msg=NULL; return m_chCast->RecvBroadCastMsg(NULL,nLength,lpAddr,nAddrLen,nTimeout); } //*********************************************************************************** BOOL CVNConnection::VNSendUDPMsg(const char* lpHost,CVNNetMsg * msg,int port) { if (lpHost==NULL) return FALSE; if (port<0) return FALSE; CVNChannel chan; if (chan.SendUDPMsg(lpHost,msg,port)==-1) return FALSE; return TRUE; } //*********************************************************************************** BOOL CVNConnection::VNSendBroadCastMsg(const char* lpHost,const char * lpMask,CVNNetMsg * msg,int port) { if (lpHost==NULL || lpMask==NULL) return FALSE; struct in_addr hostaddr; hostaddr.s_addr=inet_addr(lpHost); if (hostaddr.s_addr==INADDR_NONE) return FALSE; struct in_addr maskaddr; maskaddr.s_addr=inet_addr(lpMask); if (maskaddr.s_addr==INADDR_NONE) return FALSE; if (maskaddr.S_un.S_un_b.s_b4==255) return FALSE; int nMask=0x1; unsigned int lMask=ntohl(maskaddr.s_addr); BOOL bZero=FALSE; unsigned int nRs=0; int i=0; for (i=0;i<32;i++) { if (i==0) { if (nRs=(lMask & nMask) ==1) return FALSE; bZero=TRUE; } else { if (nRs=(lMask & nMask) ==0) { if (bZero!=TRUE) return FALSE; } else bZero=FALSE; } nMask=nMask*2; } if (port<0) return FALSE; unsigned int lHost=ntohl(hostaddr.s_addr); unsigned int lCast=(~lMask)+(lMask & lHost); char lpCast[16]=""; struct in_addr addrCast; addrCast.s_addr=htonl(lCast); char * lpCastAddr=inet_ntoa(addrCast); strncpy(lpCast,lpCastAddr,16); CVNChannel chan; if (chan.SendBroadCastMsg(lpCastAddr,msg,port)==-1) return FALSE; return TRUE; } //*********************************************************************************** int CVNConnection::VNConnect(const char* lpHost,unsigned int port,unsigned int nTimeout/*usecond*/) { if (lpHost==NULL) return -1; if (port>65535) return -1; if (strlen(lpHost)>MAXHOSTADDRLEN) return -1; if (m_QueueGroup==NULL) return -1; long lhost=::inet_addr(lpHost); if (lhost==INADDR_NONE) return -1; int nSendID=0; int nCnt=m_nSndCnt; int i=0; for (i=0;i<nCnt;i++) { if (m_arraySendChan[i]->GetPeerLong()==lhost) { break; } } if (i==nCnt) { if (i==MAXSENDCHAN) { nSendID=-1; } else { nSendID=i; #ifndef POSIX ::InterlockedIncrement(&m_nSndCnt); #else pthread_mutex_lock(&m_csArray); m_nSndCnt++; pthread_mutex_unlock(&m_csArray); #endif if (ChannelConnect(nSendID,lhost,port,nTimeout)==FALSE) nSendID=-1; } } else nSendID=i; return nSendID; } //*********************************************************************************** BOOL CVNConnection::VNHaltServer() { ClearListenerHandle(); return TRUE; } //*********************************************************************************** BOOL CVNConnection::VNDisconnect() { ClearChannelHandle(); return TRUE; } //*********************************************************************************** RSINFO CVNConnection::VNSendMsg(int nConnectionID,unsigned int nSrcQueueID,unsigned int nDesQueueID,CVNNetMsg* msg) { if ((nConnectionID<0)||(nConnectionID>=MAXSENDCHAN)) { #ifdef FOOLBEAR_DEBUG LogByLevel(DSS_VP, DEBUGLVL, 0, 0, "FOOLBEAR_DEBUG: CVNConnection::VNSendMsg 1"); #endif return RS_Failed; } if ((nSrcQueueID>=MAXQUEUECNT)||(nDesQueueID>=MAXQUEUECNT)) { #ifdef FOOLBEAR_DEBUG LogByLevel(DSS_VP, DEBUGLVL, 0, 0, "FOOLBEAR_DEBUG: CVNConnection::VNSendMsg 2"); #endif return RS_Failed; } if (m_arraySendChan[nConnectionID]==NULL) { #ifdef FOOLBEAR_DEBUG LogByLevel(DSS_VP, DEBUGLVL, 0, 0, "FOOLBEAR_DEBUG: CVNConnection::VNSendMsg 3"); #endif return RS_Failed; } msg->SetSrcQueueID(nSrcQueueID); msg->SetDesQueueID(nDesQueueID); int rc=m_arraySendChan[nConnectionID]->SendMsg(msg,NULL); if (rc==RS_Timeout) return RS_Timeout; if (rc<0) { if (ChannelConnect(nConnectionID,-1,-1,CHANNELCONNECTTIMEOUT)==FALSE) { #ifdef FOOLBEAR_DEBUG LogByLevel(DSS_VP, DEBUGLVL, 0, 0, "FOOLBEAR_DEBUG: CVNConnection::VNSendMsg 4"); #endif return RS_Failed; } else { int rc2=m_arraySendChan[nConnectionID]->SendMsg(msg,NULL); if (rc2>0) return RS_Success; else { #ifdef FOOLBEAR_DEBUG LogByLevel(DSS_VP, DEBUGLVL, 0, 0, "FOOLBEAR_DEBUG: CVNConnection::VNSendMsg return %d", rc2); #endif return (RSINFO)rc2; } } } return RS_Success; } //*********************************************************************************** RSINFO CVNConnection::VNSendReplyMsg(int nConnectionID,unsigned int nSrcQueueID,unsigned int nDesQueueID,CVNNetMsg* msg) { if ((nConnectionID<0)||(nConnectionID>=MAXSENDCHAN)) return RS_Failed; if ((nSrcQueueID>=MAXQUEUECNT)||(nDesQueueID>=MAXQUEUECNT)) return RS_Failed; CVNChannel * pch=NULL; pch=ReturnChannelPointer(TRUE,nConnectionID); if (pch==NULL) return RS_Failed; msg->SetSrcQueueID(nSrcQueueID); msg->SetDesQueueID(nDesQueueID); int rc=pch->SendMsg(msg,NULL); if (rc>0) return RS_Success; else return (RSINFO)rc; } //*********************************************************************************** CVNNetMsg* CVNConnection::VNRecvMsg(unsigned int nRecQueueID,int * nErr,unsigned int nTimeout) { int nRes=RS_Success; CVNNetMsg * msg=NULL; if (m_QueueGroup==NULL) { nRes=RS_Failed; } else { if (m_QueueGroup->WaitForQueueNotEmpty(nRecQueueID,nTimeout)) { msg=m_QueueGroup->getMsg(nRecQueueID); if (msg==NULL) nRes=RS_Failed; } else { nRes=RS_Timeout; } } if (nErr!=NULL) *nErr=nRes; return msg; } //*********************************************************************************** BOOL CVNConnection::VNListen(unsigned int port,CVNQueueGroup * qg) { if (port>65535) return FALSE; if (m_QueueGroup=NULL) return FALSE; if (m_sListener!=INVALID_SOCKET) return FALSE; m_sListener = socket(AF_INET, SOCK_STREAM, 0); if (m_sListener == INVALID_SOCKET) { ClearListenerHandle(); return FALSE; } int nRet=0; #ifdef POSIX nRet=fcntl(m_sListener,F_SETFL,O_NONBLOCK); #else unsigned long ul=1; nRet=ioctlsocket(m_sListener,FIONBIO,&ul); #endif BOOL bReuse=TRUE; setsockopt(m_sListener,SOL_SOCKET,SO_REUSEADDR,(char*)&bReuse,sizeof(bReuse)); m_nPort=port; SOCKADDR_IN sa; sa.sin_family = AF_INET; sa.sin_port = htons(m_nPort); sa.sin_addr.s_addr=htonl(INADDR_ANY); if (bind(m_sListener,(PSOCKADDR)&sa,sizeof(sa))!=0) { printf("bind failed\n"); #ifdef POSIX printf(sys_errlist[errno]); printf("\n"); #endif ClearListenerHandle(); return FALSE; } listen(m_sListener,SOMAXCONN); m_QueueGroup=qg; #ifdef POSIX if (pthread_create(&m_thrdLisn,NULL,CVNConnection::ListenProc,(void*)(this))!=0) { return FALSE; } #else unsigned int thrd=0; m_thrdLisn=(HANDLE)_beginthreadex(NULL,0,(unsigned int (__stdcall *)(void *))ListenProc,this,0,&thrd); #endif return TRUE; } //*********************************************************************************** BOOL CVNConnection::VNListenCore() { unsigned long index=0; fd_set fdread; int nID=0; while (TRUE) { FD_ZERO(&fdread); FD_SET(m_sListener,&fdread); struct timeval tvalout={0,10}; int nRet=select(m_sListener + 1, &fdread,NULL, NULL, &tvalout); switch (nRet) { case -1: printf("listen quit\n"); break; case 0: continue; default: if (FD_ISSET(m_sListener,&fdread)) { printf("listened a accept try\n"); unsigned int nTemp=ReduceAFreeChannel(); if (nTemp>=MAXRECVCHAN) { //printf("cant accept a connection\n"); continue; } tagThreadParam * param=new tagThreadParam; param->pcn=this; param->nChanID=nTemp; param->puser=NULL; unsigned lThreadNum=0; #ifndef POSIX m_thrdServ[nTemp]=(HANDLE)_beginthreadex(NULL,0,(unsigned int (__stdcall *)(void *))ServRecvThreadProc,param,0,&lThreadNum); #else pthread_t thread1; pthread_attr_t thrdattr; pthread_attr_init(&thrdattr); pthread_attr_setdetachstate(&thrdattr,PTHREAD_CREATE_DETACHED); pthread_create(&m_thrdServ[nTemp],&thrdattr,CVNConnection::ServRecvThreadProc,(void *)(param)); printf("accept a connection try\n"); #endif } } if (nRet==-1) break; } return TRUE; } //*********************************************************************************** void CVNConnection::AddAFreeChannel(unsigned int nChanID) { #ifndef POSIX EnterCriticalSection(&m_csArray); #else pthread_mutex_lock(&m_csArray); #endif if (m_nTailFree<MAXRECVCHAN) m_arrayRecvFree[m_nTailFree]=nChanID; m_nTailFree=nChanID; m_arrayRecvFree[m_nTailFree]=MAXRECVCHAN; if (m_nHeaderFree==MAXRECVCHAN) m_nHeaderFree=m_nTailFree; #ifndef POSIX ::InterlockedDecrement(&m_nRecCnt); LeaveCriticalSection(&m_csArray); #else m_nRecCnt--; pthread_mutex_unlock(&m_csArray); #endif } //*********************************************************************************** unsigned int CVNConnection::ReduceAFreeChannel() { #ifndef POSIX EnterCriticalSection(&m_csArray); #else pthread_mutex_lock(&m_csArray); #endif unsigned int nFree=0; nFree=m_nHeaderFree; SOCKET sNew=accept(m_sListener,NULL,NULL); if (sNew==INVALID_SOCKET) { #ifndef POSIX LeaveCriticalSection(&m_csArray); #else pthread_mutex_unlock(&m_csArray); #endif return MAXRECVCHAN; } int optvalue = SO_RCVBUF_SIZE; setsockopt(sNew,SOL_SOCKET,SO_RCVBUF,(char*)&optvalue,sizeof(int)); optvalue = SO_SNDBUF_SIZE; setsockopt(sNew,SOL_SOCKET,SO_SNDBUF,(char*)&optvalue,sizeof(int)); if (nFree<MAXRECVCHAN) { //printf("A conncectiong has be accpeted, %d\n",nFree); if (m_arrayRecvChan[nFree]==NULL) { CVNChannel * ch=new CVNChannel(sNew); m_arrayRecvChan[nFree]=ch; } else { m_arrayRecvChan[nFree]->SetSocket(sNew); } m_arrayRecvChan[nFree]->SetChannelID(nFree); CVNNetMsg msg(Control); m_arrayRecvChan[nFree]->SendMsg(&msg,NULL); if (m_nHeaderFree==m_nTailFree) { m_nHeaderFree=MAXRECVCHAN; m_nTailFree=MAXRECVCHAN; } else { m_nHeaderFree=m_arrayRecvFree[nFree]; } #ifndef POSIX ::InterlockedIncrement(&m_nRecCnt); #else m_nRecCnt++; #endif } else { closesocket(sNew); } #ifndef POSIX LeaveCriticalSection(&m_csArray); #else pthread_mutex_unlock(&m_csArray); #endif return nFree; } //*********************************************************************************** BOOL CVNConnection::VNGetClientPeerAddr(unsigned int nQueueID,char * lpAddr,int nLen) { if (m_QueueGroup==NULL) return FALSE; if (lpAddr==NULL) return FALSE; if (nLen<=0) return FALSE; return m_arrayRecvChan[nQueueID]->GetPeerAddr(lpAddr,nLen); }
[ "greatfoolbear@756bb6b0-a119-0410-8338-473b6f1ccd30" ]
[ [ [ 1, 914 ] ] ]
efa9af40f4b00040eb9c86f97774280b7244d168
3c9d64d2af8cf3d5b83c7393b4ddfeba468a94f7
/src/train.cpp
fb2241f5c66d12e16c1c1c016b7197eedae1ec64
[]
no_license
kod3r/cv
0ff9f31b9b926a6f61f7e422bc69f0303a8a2de4
9e769c90693005b76c8a7d5305002a1feb07f096
refs/heads/master
2021-01-18T10:55:32.764921
2009-08-10T17:32:19
2009-08-10T17:32:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,654
cpp
/**************************************************************************** * AAMLibrary * http://code.google.com/p/aam-library * Copyright (c) 2008-2009 by GreatYao, all rights reserved. ****************************************************************************/ #include "AAM_IC.h" #include "AAM_Basic.h" using namespace std; static void usage() { printf("Usage: train [options] train_path image_ext point_ext cascade_file model_file\n" "\noptions:\n" " -t type of aam (0 aam_basic, 1 aam_ic, default 0)\n" " -p level of parymid (default 2)\n\n"); exit(0); } int main(int argc, char** argv) { int i; int type = TYPE_AAM_BASIC; int level = 2; for(i = 1; i < argc; i++) { if(argv[i][0] != '-')break; if(++i>=argc) usage(); switch(argv[i-1][1]) { case 't': type = atoi(argv[i]); break; case 'p': level = atoi(argv[i]); break; default: fprintf(stderr, "unknown options\n"); usage(); } } if(i+5 != argc) usage(); file_lists imgFiles = AAM_Common::ScanNSortDirectory(argv[i], argv[i+1]); file_lists ptsFiles = AAM_Common::ScanNSortDirectory(argv[i], argv[i+2]); printf("Number of points: %i\n Number of images: %i\n", ptsFiles.size(), imgFiles.size()); if(ptsFiles.size() != imgFiles.size()){ fprintf(stderr, "ERROR(%s, %d): #Shapes != #Images\n", __FILE__, __LINE__); exit(0); } VJfacedetect facedet; facedet.LoadCascade(argv[i+3]); AAM_Pyramid model; model.Build(ptsFiles, imgFiles, type, level); model.BuildDetectMapping(ptsFiles, imgFiles, facedet); model.WriteModel(argv[i+4]); return 0; }
[ "sudeep@sudeep-laptop.(none)" ]
[ [ [ 1, 66 ] ] ]
5626519d6a4793fd3da1a74c13ea1d8abeed20a0
f2cbdee1dfdcad7b77c597e1af5f40ad83bad4aa
/MyJava/JRex/src/native/JRexSHistoryListenerImpl.cpp
3e5500651fe70e9e45b3e958f029096b46e5ba00
[]
no_license
jdouglas71/Examples
d03d9effc414965991ca5b46fbcf808a9dd6fe6d
b7829b131581ea3a62cebb2ae35571ec8263fd61
refs/heads/master
2021-01-18T14:23:56.900005
2011-04-07T19:34:04
2011-04-07T19:34:04
1,578,581
1
1
null
null
null
null
UTF-8
C++
false
false
7,409
cpp
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public * License Version 1.1 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Contributor(s): * C.N Medappa <[email protected]><> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the NPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the NPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "JRexWindow.h" #include "JRex_JNI_HistoryEvent.h" using namespace JRex_JNI_HistoryEvent; /* void OnHistoryNewEntry (in nsIURI aNewURI); */ NS_IMETHODIMP JRexWindow::OnHistoryNewEntry(nsIURI *aNewURI){ JREX_LOGLN("OnHistoryNewEntry()--> *** aNewURI<"<<aNewURI<<">***") BasicHistoryEventParam *hParm=new BasicHistoryEventParam; if(IS_NULL(hParm))return NS_ERROR_OUT_OF_MEMORY; hParm->target=NS_PTR_TO_INT32(this); hParm->hisEventType=HIS_NEW_ENTRY_EVENT; nsresult rv; if(NOT_NULL(aNewURI)){ JREX_LOGLN("OnHistoryNewEntry()--> *** NOT_NULL uri ***") nsEmbedCString spec; rv=aNewURI->GetSpec(spec); if(NS_SUCCEEDED(rv)) hParm->uri=ToNewCString(spec); else hParm->uri=nsnull; }else{ JREX_LOGLN("OnHistoryNewEntry()--> *** NULL uri ***") hParm->uri=nsnull; } rv=fireEvent(hParm,PR_FALSE, nsnull); JREX_LOGLN("OnHistoryNewEntry()--> *** fireEvent rv<"<<rv<<"> ***") return NS_OK; } /* boolean OnHistoryGoBack (in nsIURI aBackURI); */ NS_IMETHODIMP JRexWindow::OnHistoryGoBack(nsIURI *aBackURI, PRBool *_retval){ JREX_LOGLN("OnHistoryGoBack()--> *** aBackURI<"<<aBackURI<<">***") BasicHistoryEventParam *hParm=new BasicHistoryEventParam; if(IS_NULL(hParm))return NS_ERROR_OUT_OF_MEMORY; hParm->target=NS_PTR_TO_INT32(this); hParm->hisEventType=HIS_GO_BACK_EVENT; nsresult rv; if(NOT_NULL(aBackURI)){ JREX_LOGLN("OnHistoryGoBack()--> *** NOT_NULL uri ***") nsEmbedCString spec; rv=aBackURI->GetSpec(spec); if(NS_SUCCEEDED(rv)) hParm->uri=ToNewCString(spec); else hParm->uri=nsnull; }else{ JREX_LOGLN("OnHistoryGoBack()--> *** NULL uri ***") hParm->uri=nsnull; } PRBool tempRV=PR_FALSE; rv=fireEvent(hParm,PR_TRUE, (void**)&tempRV); *_retval=NS_SUCCEEDED(rv)?tempRV:PR_FALSE; JREX_LOGLN("OnHistoryGoBack()--> *** fireEvent rv<"<<rv<<"> ***") return NS_OK; } /* boolean OnHistoryGoForward (in nsIURI aForwardURI); */ NS_IMETHODIMP JRexWindow::OnHistoryGoForward(nsIURI *aForwardURI, PRBool *_retval){ JREX_LOGLN("OnHistoryGoForward()--> *** aForwardURI<"<<aForwardURI<<">***") BasicHistoryEventParam *hParm=new BasicHistoryEventParam; if(IS_NULL(hParm))return NS_ERROR_OUT_OF_MEMORY; hParm->target=NS_PTR_TO_INT32(this); hParm->hisEventType=HIS_GO_FORWARD_EVENT; nsresult rv; if(NOT_NULL(aForwardURI)){ JREX_LOGLN("OnHistoryGoForward()--> *** NOT_NULL uri ***") nsEmbedCString spec; rv=aForwardURI->GetSpec(spec); if(NS_SUCCEEDED(rv)) hParm->uri=ToNewCString(spec); else hParm->uri=nsnull; }else{ JREX_LOGLN("OnHistoryGoForward()--> *** NULL uri ***") hParm->uri=nsnull; } PRBool tempRV=PR_FALSE; rv=fireEvent(hParm,PR_TRUE, (void**)&tempRV); JREX_LOGLN("OnHistoryGoForward()--> *** fireEvent rv<"<<rv<<"> tempRV<"<<tempRV<<"> ***") *_retval=NS_SUCCEEDED(rv)?tempRV:PR_FALSE; return NS_OK; } /* boolean OnHistoryReload (in nsIURI aReloadURI, in unsigned long aReloadFlags); */ NS_IMETHODIMP JRexWindow::OnHistoryReload(nsIURI *aReloadURI, PRUint32 aReloadFlags, PRBool *_retval){ JREX_LOGLN("OnHistoryReload()--> *** aReloadURI<"<<aReloadURI<<"> aReloadFlags<"<<aReloadFlags<<"> ***") IntHistoryEventParam *hParm=new IntHistoryEventParam; if(IS_NULL(hParm))return NS_ERROR_OUT_OF_MEMORY; hParm->target=NS_PTR_TO_INT32(this); hParm->hisEventType=HIS_RELOAD_EVENT; hParm->intData=aReloadFlags; nsresult rv; if(NOT_NULL(aReloadURI)){ JREX_LOGLN("OnHistoryReload()--> *** NOT_NULL uri ***") nsEmbedCString spec; rv=aReloadURI->GetSpec(spec); if(NS_SUCCEEDED(rv)) hParm->uri=ToNewCString(spec); else hParm->uri=nsnull; }else{ JREX_LOGLN("OnHistoryReload()--> *** NULL uri ***") hParm->uri=nsnull; } PRBool tempRV=PR_FALSE; rv=fireEvent(hParm,PR_TRUE, (void**)&tempRV); *_retval=NS_SUCCEEDED(rv)?tempRV:PR_FALSE; JREX_LOGLN("OnHistoryReload()--> *** fireEvent rv<"<<rv<<"> ***") return NS_OK; } /* boolean OnHistoryGotoIndex (in long aIndex, in nsIURI aGotoURI); */ NS_IMETHODIMP JRexWindow::OnHistoryGotoIndex(PRInt32 aIndex, nsIURI *aGotoURI, PRBool *_retval) { JREX_LOGLN("OnHistoryGotoIndex()--> *** aIndex<"<<aIndex<<"> aGotoURI<"<<aGotoURI<<">***") IntHistoryEventParam *hParm=new IntHistoryEventParam; if(IS_NULL(hParm))return NS_ERROR_OUT_OF_MEMORY; hParm->target=NS_PTR_TO_INT32(this); hParm->hisEventType=HIS_GO_TO_INDEX_EVENT; hParm->intData=aIndex; nsresult rv; if(NOT_NULL(aGotoURI)){ JREX_LOGLN("OnHistoryGotoIndex()--> *** NOT_NULL uri ***") nsEmbedCString spec; rv=aGotoURI->GetSpec(spec); if(NS_SUCCEEDED(rv)) hParm->uri=ToNewCString(spec); else hParm->uri=nsnull; }else{ JREX_LOGLN("OnHistoryGotoIndex()--> *** NULL uri ***") hParm->uri=nsnull; } PRBool tempRV=PR_FALSE; rv=fireEvent(hParm,PR_TRUE, (void**)&tempRV); *_retval=NS_SUCCEEDED(rv)?tempRV:PR_FALSE; JREX_LOGLN("OnHistoryGotoIndex()--> *** fireEvent rv<"<<rv<<"> ***") return NS_OK; } /* boolean OnHistoryPurge (in long aNumEntries); */ NS_IMETHODIMP JRexWindow::OnHistoryPurge(PRInt32 aNumEntries, PRBool *_retval){ JREX_LOGLN("OnHistoryPurge()--> *** aNumEntries<"<<aNumEntries<<">***") IntHistoryEventParam *hParm=new IntHistoryEventParam; if(IS_NULL(hParm))return NS_ERROR_OUT_OF_MEMORY; hParm->target=NS_PTR_TO_INT32(this); hParm->hisEventType=HIS_GO_TO_INDEX_EVENT; hParm->intData=aNumEntries; hParm->uri=nsnull; PRBool tempRV=PR_FALSE; nsresult rv=fireEvent(hParm,PR_TRUE, (void**)&tempRV); *_retval=NS_SUCCEEDED(rv)?tempRV:PR_FALSE; JREX_LOGLN("OnHistoryPurge()--> *** fireEvent rv<"<<rv<<"> ***") return NS_OK; }
[ [ [ 1, 198 ] ] ]
fdade7bb02ccca14a325477b1d9fcde830835fea
ee8761abf9db9f797753326be3640ddd1f57206c
/gKit/Widgets/nvwidgets/nvGLWidgets.cpp
666f0269d041ba47a4ed341542d5f2a80c9cbeaf
[]
no_license
Mefteg/3-sub-ways
fba4d0330943f7d9d2501d01e221c7d46cac7883
49218cf4ef7413036bdcdee16d5cd52f4896d4a2
refs/heads/master
2020-05-18T12:52:50.357430
2011-10-29T15:15:58
2011-10-29T15:15:58
32,360,588
0
0
null
null
null
null
UTF-8
C++
false
false
38,732
cpp
// // nvGLWidgets.cpp - User Interface library specialized for OpenGL // // // Author: Ignacio Castano, Samuel Gateau, Evan Hart // Email: [email protected] // // Copyright (c) NVIDIA Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////// #include "nvGLWidgets.h" #include <math.h> // sqrtf #include <stdlib.h> // exit (required by glut.h) #include <string.h> // strlen #define NV_REPORT_COMPILE_ERRORS #include <nvglutils/nvShaderUtils.h> using namespace nv; #define norm255( i ) ( (float) ( i ) / 255.0f ) enum Color { cBase = 0, cBool = 4, cOutline = 8, cFont = 12, cFontBack = 16, cTranslucent = 20, cNbColors = 24, }; const static float s_colors[cNbColors][4] = { // cBase { norm255(89), norm255(89), norm255(89), 0.7f }, { norm255(166), norm255(166), norm255(166), 0.8f }, { norm255(212), norm255(228), norm255(60), 0.5f }, { norm255(227), norm255(237), norm255(127), 0.5f }, // cBool { norm255(99), norm255(37), norm255(35), 1.0f }, { norm255(149), norm255(55), norm255(53), 1.0f }, { norm255(212), norm255(228), norm255(60), 1.0f }, { norm255(227), norm255(237), norm255(127), 1.0f }, // cOutline { norm255(255), norm255(255), norm255(255), 1.0f }, { norm255(255), norm255(255), norm255(255), 1.0f }, { norm255(255), norm255(255), norm255(255), 1.0f }, { norm255(255), norm255(255), norm255(255), 1.0f }, // cFont { norm255(255), norm255(255), norm255(255), 1.0f }, { norm255(255), norm255(255), norm255(255), 1.0f }, { norm255(255), norm255(255), norm255(255), 1.0f }, { norm255(255), norm255(255), norm255(255), 1.0f }, // cFontBack { norm255(79), norm255(129), norm255(189), 1.0 }, { norm255(79), norm255(129), norm255(189), 1.0 }, { norm255(128), norm255(100), norm255(162), 1.0 }, { norm255(128), norm255(100), norm255(162), 1.0 }, // cTranslucent { norm255(0), norm255(0), norm255(0), 0.0 }, { norm255(0), norm255(0), norm255(0), 0.0 }, { norm255(0), norm255(0), norm255(0), 0.0 }, { norm255(0), norm255(0), norm255(0), 0.0 }, }; template <typename T> T max(const T & a, const T & b) { if (a > b) return a; return b; } const char* cWidgetVSSource = { "#version 120\n\ \n\ void main()\n\ {\n\ gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;\n\ gl_TexCoord[0] = gl_MultiTexCoord0;\n\ }\n\ " }; // @@ IC: Use standard GLSL. Do not initialize uniforms. const char* cWidgetFSSource = { "#version 120\n\ uniform vec4 fillColor /*= vec4( 1.0, 0.0,0.0,1.0)*/;\n\ uniform vec4 borderColor /*= vec4( 1.0, 1.0,1.0,1.0)*/;\n\ uniform vec2 zones;\n\ \n\ void main()\n\ {\n\ float doTurn = float(gl_TexCoord[0].y > 0);\n\ float radiusOffset = doTurn * abs( gl_TexCoord[0].z );\n\ float turnDir = sign( gl_TexCoord[0].z );\n\ vec2 uv = vec2(gl_TexCoord[0].x + turnDir*radiusOffset, gl_TexCoord[0].y);\n\ float l = abs( length(uv) - radiusOffset );\n\ float a = clamp( l - zones.x, 0.0, 2.0);\n\ float b = clamp( l - zones.y, 0.0, 2.0);\n\ b = exp2(-2.0*b*b);\n\ gl_FragColor = ( fillColor * b + (1.0-b)*borderColor );\n\ gl_FragColor.a *= exp2(-2.0*a*a);\n\ }\n\ " }; const char* cTexViewWidgetFSSource = { "#version 120\n\ uniform float mipLevel /*= 0*/;\n\ uniform float texelScale /*= 1.0*/;\n\ uniform float texelOffset /*= 0.0*/;\n\ uniform ivec4 texelSwizzling /*= ivec4( 0, 1, 2, 3)*/;\n\ uniform sampler2D samp;\n\ \n\ void main()\n\ {\n\ vec4 texel;\n\ if (mipLevel > 0)\n\ texel = texture2DLod( samp, gl_TexCoord[0].xy, mipLevel);\n\ else\n\ texel = texture2D( samp, gl_TexCoord[0].xy);\n\ texel = texel * texelScale + texelOffset;\n\ gl_FragColor = texel.x * vec4( texelSwizzling.x == 0, texelSwizzling.y == 0, texelSwizzling.z == 0, texelSwizzling.w == 0 );\n\ gl_FragColor += texel.y * vec4( texelSwizzling.x == 1, texelSwizzling.y == 1, texelSwizzling.z == 1, texelSwizzling.w == 1 );\n\ gl_FragColor += texel.z * vec4( texelSwizzling.x == 2, texelSwizzling.y == 2, texelSwizzling.z == 2, texelSwizzling.w == 2 );\n\ gl_FragColor += texel.w * vec4( texelSwizzling.x == 3, texelSwizzling.y == 3, texelSwizzling.z == 3, texelSwizzling.w == 3 );\n\ }\n\ " }; //************************************************************************* //* GLUIPainter GLUIPainter::GLUIPainter( TextPainter& textPainter ): UIPainter(), m_textPainter(textPainter), m_setupStateDL(0), m_restoreStateDL(0), m_foregroundDL(0), m_widgetProgram(0), m_fillColorUniform(0), m_borderColorUniform(0), m_zonesUniform(0), m_textureViewProgram(0), m_texMipLevelUniform(0), m_texelScaleUniform(0), m_texelOffsetUniform(0), m_texelSwizzlingUniform(0) { } int GLUIPainter::getWidgetMargin() const { return 3 ; //2 ; } int GLUIPainter::getWidgetSpace() const { return 2 ; } int GLUIPainter::getAutoWidth() const { return 100 ; } int GLUIPainter::getAutoHeight() const { //~ return 12 + 4; return m_textPainter.getFontHeight(); } int GLUIPainter::getCanvasMargin() const { // return 5; return 5; } int GLUIPainter::getCanvasSpace() const { return 5; } int GLUIPainter::getFontHeight() const { //~ return 12 + 4 ; return m_textPainter.getFontHeight(); } int GLUIPainter::getTextLineWidth(const char * text) const { return m_textPainter.getTextLineWidth(text); } int GLUIPainter::getTextSize(const char * text, int& nbLines) const { return m_textPainter.getTextSize(text, nbLines); } int GLUIPainter::getTextLineWidthAt(const char * text, int charNb) const { return m_textPainter.getTextLineWidthAt(text, charNb); } int GLUIPainter::getPickedCharNb(const char * text, const Point& at) const { return m_textPainter.getPickedCharNb(text, at); } void GLUIPainter::drawFrame(const Rect & r, int margin, int /*style*/) { drawRoundedRectOutline(Rect(r.x - margin, r.y - margin, r.w + 2*margin, r.h + 2*margin), nv::Point(margin, margin), cOutline); } Rect GLUIPainter::getLabelRect(const Rect & r, const char * text, Rect & rt, int& nbLines ) const { Rect rect = r; rt.x = getWidgetMargin(); rt.y = getWidgetMargin(); // Eval Nblines and max line width anyway. rt.w = getTextSize(text, nbLines); if (rect.w == 0) { rect.w = rt.w + 2 * rt.x; } else { rt.w = rect.w - 2 * rt.x; } if (rect.h == 0) { rt.h = getFontHeight() * nbLines; rect.h = rt.h + 2 * rt.y; } else { rt.h = rect.h - 2 * rt.y; } return rect; } void GLUIPainter::drawLabel(const Rect & r, const char * text, const Rect & rt, const int& nbLines, bool /*isHover*/, int style) { if (style > 0 ) drawFrame( r, Point( rt.x, rt.y ), false, false, false ); drawText( Rect(r.x + rt.x, r.y + rt.y, rt.w, rt.h), text, nbLines); } Rect GLUIPainter::getLineEditRect(const Rect & r, const char * text, Rect & rt) const { Rect rect = r; rt.x = getWidgetMargin(); rt.y = getWidgetMargin(); if (rect.w == 0) { rt.w = max(getTextLineWidth(text), 100); rect.w = rt.w + 2 * rt.x; } else { rt.w = rect.w - 2 * rt.x; } if (rect.h == 0) { rt.h = getFontHeight(); rect.h = rt.h + 2 * rt.y; } else { rt.h = rect.h - 2 * rt.y; } return rect; } void GLUIPainter::drawLineEdit(const Rect & r, const char * text, const Rect & rt, int caretPos, bool isSelected, bool /*isHover*/, int /*style*/) { drawFrame( r, Point( rt.x, rt.y ), true, isSelected, false ); drawText( Rect(r.x + rt.x, r.y + rt.y, rt.w, rt.h), text, 1, caretPos); } Rect GLUIPainter::getButtonRect(const Rect & r, const char * text, Rect & rt) const { Rect rect = r; rt.x = /*4* */getWidgetMargin(); rt.y = /*4* */getWidgetMargin(); if (rect.w == 0) { rt.w = getTextLineWidth(text); rect.w = rt.w + 2 * rt.x; } else { rt.w = rect.w - 2 * rt.x; } if (rect.h == 0) { rt.h = getFontHeight(); rect.h = rt.h + 2 * rt.y; } else { rt.h = rect.h - 2 * rt.y; } return rect; } void GLUIPainter::drawButton(const Rect & r, const char * text, const Rect & rt, bool isDown, bool isHover, bool isFocus, int /*style*/) { drawFrame( r, Point( rt.x, rt.y ), isHover, isDown, isFocus ); drawText( Rect(r.x + rt.x, r.y + rt.y, rt.w, rt.h) , text); } Rect GLUIPainter::getCheckRect(const Rect & r, const char * text, Rect & rt, Rect& rc) const { Rect rect = r; int rcOffset = (int) (0.125 * getAutoHeight()); rc.h = getAutoHeight() - 2 * rcOffset; rc.w = rc.h; rc.x = getWidgetMargin() + rcOffset; rc.y = getWidgetMargin() + rcOffset; rt.x = getAutoHeight() + 2 * getWidgetMargin(); rt.y = getWidgetMargin(); if (rect.w == 0) { rt.w = getTextLineWidth(text); rect.w = rt.x + rt.w + getWidgetMargin(); } if (rect.h == 0) { rt.h = getFontHeight(); rect.h = rt.h + 2 * rt.y; } return rect; } void GLUIPainter::drawCheckButton(const Rect & r, const char * text, const Rect & rt, const Rect& rc, bool isChecked, bool isHover, bool isFocus, int style) { if (style) drawFrame( r, Point( rt.y, rt.y ), isHover, false, isFocus ); drawBoolFrame( Rect(r.x + rc.x, r.y + rc.y, rc.w, rc.h), Point( rc.w / 6, rc.h / 6 ), isHover, isChecked, false ); drawText( Rect(r.x + rt.x, r.y + rt.y, rt.w, rt.h) , text); } Rect GLUIPainter::getRadioRect(const Rect & r, const char * text, Rect & rt, Rect& rr) const { Rect rect = r; int rrOffset = (int) (0.125 * getAutoHeight()); rr.h = getAutoHeight() - 2 * rrOffset; rr.w = rr.h; rr.x = getWidgetMargin() + rrOffset; rr.y = getWidgetMargin() + rrOffset; rt.x = getAutoHeight() + 2 * getWidgetMargin(); rt.y = getWidgetMargin(); if (rect.w == 0) { rt.w = getTextLineWidth(text); rect.w = rt.w + rt.x + getWidgetMargin(); } if (rect.h == 0) { rt.h = getFontHeight(); rect.h = rt.h + 2 * rt.y; } return rect; } void GLUIPainter::drawRadioButton(const Rect & r, const char * text, const Rect & rt, const Rect & rr, bool isOn, bool isHover, bool isFocus, int style) { if (style) drawFrame( r, Point( rt.y, rt.y ), isHover, false, isFocus ); drawBoolFrame( Rect(r.x + rr.x, r.y + rr.y, rr.w, rr.h), Point( rr.w / 2, rr.h / 2 ), isHover, isOn, false ); drawText( Rect(r.x + rt.x, r.y + rt.y, rt.w, rt.h) , text); } Rect GLUIPainter::getHorizontalSliderRect(const Rect & r, Rect& rs, float v, Rect& rc) const { Rect rect = r; if (rect.w == 0) rect.w = getAutoWidth() + 2 * getWidgetMargin(); if (rect.h == 0) rect.h = getAutoHeight() + 2 * getWidgetMargin(); // Eval the sliding & cursor rect rs.y = getWidgetMargin(); rs.h = rect.h - 2 * rs.y; rc.y = rs.y; rc.h = rs.h; rs.x = 0;//getWidgetMargin(); rc.w = rc.h; rs.w = rect.w - 2 * rs.x - rc.w; rc.x = int(v * rs.w); return rect; } void GLUIPainter::drawHorizontalSlider(const Rect & r, Rect& rs, float /*v*/, Rect& rc, bool isHover, int /*style*/) { int sliderHeight = rs.h / 3; drawFrame( Rect(r.x + rs.x, r.y + rs.y + sliderHeight, r.w - 2*rs.x, sliderHeight), Point(sliderHeight / 2, sliderHeight / 2), isHover, false, false ); drawFrame( Rect(r.x + rs.x + rc.x, r.y + rc.y, rc.w, rc.h), Point(rc.w / 2, rc.h / 2), isHover, true, false ); } Rect GLUIPainter::getItemRect(const Rect & r, const char * text, Rect & rt) const { Rect rect = r; rt.x = 0; rt.y = 0; if (rect.w == 0) { rt.w = getTextLineWidth(text); rect.w = rt.w + 2 * rt.x; } else { rt.w = rect.w - 2 * rt.x; } if (rect.h == 0) { rt.h = getFontHeight(); rect.h = rt.h + 2 * rt.y; } else { rt.h = rect.h - 2 * rt.y; } return rect; } Rect GLUIPainter::getListRect(const Rect & r, int numOptions, const char * options[], Rect& ri, Rect & rt) const { Rect rect = r; ri.x = getWidgetMargin(); ri.y = getWidgetMargin(); rt.x = getWidgetMargin(); rt.y = getWidgetMargin(); if (rect.w == 0) { rt.w = 0; for (int i = 0; i < numOptions; i++) { int l = getTextLineWidth(options[i]); rt.w = ( l > rt.w ? l : rt.w ); } ri.w = rt.w + 2 * rt.x; rect.w = ri.w + 2 * ri.x; } else { ri.w = rect.w - 2 * ri.x; rt.w = ri.w - 2 * rt.x; } if (rect.h == 0) { rt.h = getFontHeight(); ri.h = rt.h + rt.y; rect.h = numOptions * ri.h + 2 * ri.y; } else { ri.h = (rect.h - 2 * ri.y) / numOptions; rt.h = ri.h - rt.y; } return rect; } void GLUIPainter::drawListItem(const Rect & r, const char * text, const Rect & rt, bool isSelected, bool isHover, int /*style*/) { // drawFrame( r, Point(0, 0), isHover, isSelected, false ); drawText( Rect(r.x + rt.x, r.y + rt.y, rt.w, rt.h), text, isHover, isSelected); } void GLUIPainter::drawListBox(const Rect & r, int numOptions, const char * options[], const Rect& ri, const Rect & rt, int selected, int hovered, int /*style*/) { drawFrame( r, Point(ri.x, ri.y) ); Rect ir( r.x + ri.x, r.y + r.h - ri.y - ri.h, ri.w, ri.h ); for ( int i = 0; i < numOptions; i++ ) { if ( (i == hovered) || (i == selected)) { drawFrame( ir, Point(ri.x, ri.y), false, (i == selected)); } drawText( Rect(ir.x + rt.x , ir.y + rt.y, rt.w, rt.h), options[i]); ir.y -= ir.h; } } Rect GLUIPainter::getComboRect(const Rect & r, int numOptions, const char * options[], int /*selected*/, Rect& rt, Rect& rd) const { Rect rect = r; rt.x = getWidgetMargin(); rt.y = getWidgetMargin(); if (rect.h == 0) { rt.h = getFontHeight(); rect.h = rt.h + 2 * rt.y; } else { rt.h = rect.h - 2 * rt.y; } rd.h = rt.h; rd.w = rd.h; rd.y = rt.y; if (rect.w == 0) { rt.w = 0; for (int i = 0; i < numOptions; i++) { int l = getTextLineWidth(options[i]); rt.w = ( l > rt.w ? l : rt.w ); } rect.w = rt.w + 2 * rt.x; //Add room for drop down button rect.w += rt.h + rt.x; } else { //Add room for drop down button rt.w = rect.w - 3 * rt.x - rt.h; } rd.x = 2 * rt.x + rt.w; return rect; } Rect GLUIPainter::getComboOptionsRect(const Rect & rCombo, int numOptions, const char * options[], Rect& ri, Rect & rit) const { // the options frame is like a list box Rect rect = getListRect( Rect(), numOptions, options, ri, rit); // offset by the Combo box pos itself rect.x = rCombo.x; rect.y = rCombo.y - rect.h; return rect; } void GLUIPainter::drawComboBox(const Rect & r, int /*numOptions*/, const char * options[], const Rect & rt, const Rect& rd, int selected, bool isHover, bool isFocus, int /*style*/) { drawFrame( r, Point(rt.x, rt.y), isHover, false, isFocus ); drawText( Rect(r.x + rt.x, r.y + rt.y, rt.w, rt.h), options[ selected ] ); drawDownArrow( Rect(r.x + rd.x, r.y + rd.y, rd.w, rd.h), int(rd.h * 0.15f), cBase + (!isHover) + (isFocus << 2), cOutline); } void GLUIPainter::drawComboOptions(const Rect & r, int numOptions, const char * options[], const Rect& ri, const Rect & rt, int selected, int hovered, bool /*isHover*/, bool /*isFocus*/, int style) { m_foregroundDL = glGenLists(1); glNewList( m_foregroundDL, GL_COMPILE); drawListBox(r, numOptions, options, ri, rt, selected, hovered, style); glEndList(); } Rect GLUIPainter::getPanelRect(const Rect & r, const char * text, Rect& rt, Rect& ra) const { Rect rect = r; rt.x = getWidgetMargin(); rt.y = getWidgetMargin(); if (rect.h == 0) { rt.h = getFontHeight(); rect.h = rt.h + 2 * rt.y; } else { rt.h = rect.h - 2 * rt.y; } ra.h = rt.h; ra.w = ra.h; ra.y = rt.y; if (rect.w == 0) { rt.w = getTextLineWidth(text); rect.w = rt.w + 2 * rt.x; // Add room for drop down button rect.w += ra.h + rt.x; } else { // Add room for drop down button rt.w = rect.w - 3 * rt.x - ra.h; } ra.x = 2 * rt.x + rt.w; return rect; } void GLUIPainter::drawPanel(const Rect & r, const char * text, const Rect & rt, const Rect & ra, bool isUnfold, bool isHover, bool isFocus, int /*style*/) { drawFrame( r, Point(rt.x, rt.y), isHover, false, isFocus ); drawText( Rect(r.x + rt.x, r.y + rt.y, rt.w, rt.h), text ); if (isUnfold) drawMinus( Rect(r.x + ra.x, r.y + ra.y, ra.w, ra.h), int(ra.h * 0.15f), cBase + (!isHover) + (isFocus << 2), cOutline); else drawPlus( Rect(r.x + ra.x, r.y + ra.y, ra.w, ra.h), int(ra.h * 0.15f), cBase + (!isHover) + (isFocus << 2), cOutline); } Rect GLUIPainter::getTextureViewRect(const Rect & r, Rect& rt) const { Rect rect = r; if (rect.w == 0) rect.w = getAutoWidth(); if (rect.h == 0) rect.h = rect.w; rt.x = getCanvasMargin(); rt.y = getCanvasMargin(); rt.w = rect.w - 2 * getCanvasMargin(); rt.h = rect.h - 2 * getCanvasMargin(); return rect; } void GLUIPainter::drawTextureView(const Rect & rect, const void* texID, const Rect& rt, const Rect & rz, int mipLevel, float texelScale, float texelOffset, int r, int g, int b, int a, int /*style*/) { drawFrame( rect, Point(rt.x, rt.y), false, false, false ); GLuint lTexID = *static_cast<const GLuint *> ( texID ); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, lTexID); glUseProgram(m_textureViewProgram); glUniform1f( m_texMipLevelUniform, (float) mipLevel); glUniform1f( m_texelScaleUniform, texelScale); glUniform1f( m_texelOffsetUniform, texelOffset); glUniform4i( m_texelSwizzlingUniform, r, g, b, a); glBegin(GL_QUADS); glTexCoord2f( (float) rz.x / (float) rt.w , (float) rz.y / (float) rt.h); glVertex2f(rect.x + rt.x, rect.y + rt.y); glTexCoord2f((float) rz.x / (float) rt.w , (float) (rz.y + rz.h) / (float) rt.h); glVertex2f(rect.x + rt.x, rect.y + rt.y + rt.h); glTexCoord2f((float) (rz.x + rz.w) / (float) rt.w , (float) (rz.y + rz.h) / (float) rt.h); glVertex2f(rect.x + rt.x + rt.w, rect.y + rt.y + rt.h); glTexCoord2f((float) (rz.x + rz.w) / (float) rt.w , (float) (rz.y) / (float) rt.h); glVertex2f(rect.x + rt.x + rt.w, rect.y + rt.y); glEnd(); glUseProgram(0); glBindTexture(GL_TEXTURE_2D, 0); glDisable(GL_TEXTURE_2D); } void GLUIPainter::init() { if (m_widgetProgram == 0) { GLuint vShader = nv::CompileGLSLShader( GL_VERTEX_SHADER, cWidgetVSSource); if (!vShader) fprintf(stderr, "Vertex shader compile failed\n"); GLuint fShader = nv::CompileGLSLShader( GL_FRAGMENT_SHADER, cWidgetFSSource); if (!fShader) fprintf(stderr, "Fragment shader compile failed\n"); m_widgetProgram = nv::LinkGLSLProgram( vShader, fShader ); m_fillColorUniform = glGetUniformLocation(m_widgetProgram, "fillColor"); m_borderColorUniform = glGetUniformLocation(m_widgetProgram, "borderColor"); m_zonesUniform = glGetUniformLocation(m_widgetProgram, "zones"); if (m_textureViewProgram == 0) { GLuint fShaderTex = nv::CompileGLSLShader( GL_FRAGMENT_SHADER, cTexViewWidgetFSSource); if (!fShaderTex) fprintf(stderr, "Fragment shader compile failed\n"); m_textureViewProgram = nv::LinkGLSLProgram( vShader, fShaderTex ); m_texMipLevelUniform = glGetUniformLocation(m_textureViewProgram, "mipLevel"); m_texelScaleUniform = glGetUniformLocation(m_textureViewProgram, "texelScale"); m_texelOffsetUniform = glGetUniformLocation(m_textureViewProgram, "texelOffset"); m_texelSwizzlingUniform = glGetUniformLocation(m_textureViewProgram, "texelSwizzling"); } } if (m_setupStateDL == 0) { m_setupStateDL = glGenLists(1); glNewList( m_setupStateDL, GL_COMPILE); { // Cache previous state glPushAttrib( GL_STENCIL_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT ); // fill mode always glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); // Stencil / Depth buffer and test disabled glDisable(GL_STENCIL_TEST); glStencilMask( 0 ); glDisable(GL_DEPTH_TEST); glDepthMask( GL_FALSE ); // Blend on for alpha glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Color active glColorMask( GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE ); // Modelview is identity glMatrixMode( GL_MODELVIEW ); glPushMatrix(); glLoadIdentity(); } glEndList(); } if (m_restoreStateDL == 0) { m_restoreStateDL = glGenLists(1); glNewList( m_restoreStateDL, GL_COMPILE); { // Restore state. glPopAttrib(); // Restore matrices. glMatrixMode( GL_PROJECTION); glPopMatrix(); glMatrixMode( GL_MODELVIEW); glPopMatrix(); } glEndList(); } m_textPainter.init(); } void GLUIPainter::begin(const Rect& window) { // Cache and setup state // ... also cache shader program in use glGetIntegerv(GL_CURRENT_PROGRAM, &m_program_use); glActiveTexture(GL_TEXTURE0); glGetIntegerv(GL_TEXTURE_BINDING_2D, &m_texture_use); glGetIntegerv(GL_SAMPLER_BINDING, &m_sampler_use); init(); glCallList( m_setupStateDL ); // Set matrices. glMatrixMode( GL_PROJECTION ); glPushMatrix(); glLoadIdentity(); gluOrtho2D( window.x, window.w, window.y, window.h ); } void GLUIPainter::end() { if ( m_foregroundDL ) { glCallList( m_foregroundDL ); glDeleteLists( m_foregroundDL, 1 ); m_foregroundDL = 0; } // Restore state. glCallList( m_restoreStateDL ); glUseProgram(m_program_use); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, m_texture_use); glBindSampler(0, m_sampler_use); } // Draw Primitive shapes void GLUIPainter::drawString( int x, int y, const char * text, int nbLines ) { m_textPainter.drawString(x, y, text, nbLines); } void GLUIPainter::drawRect( const Rect & rect, int fillColorId, int borderColorId ) const { glUseProgram(m_widgetProgram); glUniform4fv( m_fillColorUniform, 1, s_colors[fillColorId]); glUniform4fv( m_borderColorUniform, 1, s_colors[borderColorId]); glUniform2f( m_zonesUniform, 0, 0); float x0 = rect.x; float x1 = rect.x + rect.w; float y0 = rect.y; float y1 = rect.y + rect.h; glBegin(GL_TRIANGLE_STRIP); glTexCoord2f(0, 0); glVertex2f( x0, y0); glVertex2f( x1, y0); glVertex2f( x0, y1); glVertex2f( x1, y1); glEnd(); glUseProgram(0); } void GLUIPainter::drawRoundedRect( const Rect& rect, const Point& corner, int fillColorId, int borderColorId ) const { glUseProgram(m_widgetProgram); glUniform4fv( m_fillColorUniform, 1, s_colors[fillColorId]); glUniform4fv( m_borderColorUniform, 1, s_colors[borderColorId]); glUniform2f( m_zonesUniform, corner.x - 1, corner.x - 2); float xb = corner.x; float yb = corner.y; float x0 = rect.x; float x1 = rect.x + corner.x; float x2 = rect.x + rect.w - corner.x; float x3 = rect.x + rect.w; float y0 = rect.y; float y1 = rect.y + corner.y; float y2 = rect.y + rect.h - corner.y; float y3 = rect.y + rect.h; glBegin(GL_TRIANGLE_STRIP); glTexCoord2f(xb, yb); glVertex2f( x0, y0); glTexCoord2f(0, yb); glVertex2f( x1, y0); glTexCoord2f(xb, 0); glVertex2f( x0, y1); glTexCoord2f(0, 0); glVertex2f( x1, y1); glTexCoord2f(xb, 0); glVertex2f( x0, y2); glTexCoord2f(0, 0); glVertex2f( x1, y2); glTexCoord2f(xb, yb); glVertex2f( x0, y3); glTexCoord2f(0, yb); glVertex2f( x1, y3); glEnd(); glBegin(GL_TRIANGLE_STRIP); glTexCoord2f(0, yb); glVertex2f( x2, y0); glTexCoord2f(xb, yb); glVertex2f( x3, y0); glTexCoord2f(0, 0); glVertex2f( x2, y1); glTexCoord2f(xb, 0); glVertex2f( x3, y1); glTexCoord2f(0, 0); glVertex2f( x2, y2); glTexCoord2f(xb, 0); glVertex2f( x3, y2); glTexCoord2f(0, yb); glVertex2f( x2, y3); glTexCoord2f(xb, yb); glVertex2f( x3, y3); glEnd(); glBegin(GL_TRIANGLE_STRIP); glTexCoord2f(0, yb); glVertex2f( x1, y0); glTexCoord2f(0, yb); glVertex2f( x2, y0); glTexCoord2f(0, 0); glVertex2f( x1, y1); glTexCoord2f(0, 0); glVertex2f( x2, y1); glTexCoord2f(0, 0); glVertex2f( x1, y2); glTexCoord2f(0, 0); glVertex2f( x2, y2); glTexCoord2f(0, yb); glVertex2f( x1, y3); glTexCoord2f(0, yb); glVertex2f( x2, y3); glEnd(); glUseProgram(0); } void GLUIPainter::drawRoundedRectOutline( const Rect& rect, const Point& corner, int borderColorId ) const { glUseProgram(m_widgetProgram); glUniform4fv( m_fillColorUniform, 1, s_colors[cTranslucent]); glUniform4fv( m_borderColorUniform, 1, s_colors[borderColorId]); glUniform2f( m_zonesUniform, corner.x - 1, corner.x - 2); float xb = corner.x; float yb = corner.y; float x0 = rect.x; float x1 = rect.x + corner.x; float x2 = rect.x + rect.w - corner.x; float x3 = rect.x + rect.w; float y0 = rect.y; float y1 = rect.y + corner.y; float y2 = rect.y + rect.h - corner.y; float y3 = rect.y + rect.h; glBegin(GL_TRIANGLE_STRIP); glTexCoord2f(xb, yb); glVertex2f( x0, y0); glTexCoord2f(0, yb); glVertex2f( x1, y0); glTexCoord2f(xb, 0); glVertex2f( x0, y1); glTexCoord2f(0, 0); glVertex2f( x1, y1); glTexCoord2f(xb, 0); glVertex2f( x0, y2); glTexCoord2f(0, 0); glVertex2f( x1, y2); glTexCoord2f(xb, yb); glVertex2f( x0, y3); glTexCoord2f(0, yb); glVertex2f( x1, y3); glEnd(); glBegin(GL_TRIANGLE_STRIP); glTexCoord2f(0, yb); glVertex2f( x2, y0); glTexCoord2f(xb, yb); glVertex2f( x3, y0); glTexCoord2f(0, 0); glVertex2f( x2, y1); glTexCoord2f(xb, 0); glVertex2f( x3, y1); glTexCoord2f(0, 0); glVertex2f( x2, y2); glTexCoord2f(xb, 0); glVertex2f( x3, y2); glTexCoord2f(0, yb); glVertex2f( x2, y3); glTexCoord2f(xb, yb); glVertex2f( x3, y3); glEnd(); glBegin(GL_TRIANGLE_STRIP); glTexCoord2f(0, yb); glVertex2f( x1, y0); glTexCoord2f(0, yb); glVertex2f( x2, y0); glTexCoord2f(0, 0); glVertex2f( x1, y1); glTexCoord2f(0, 0); glVertex2f( x2, y1); glEnd(); glBegin(GL_TRIANGLE_STRIP); glTexCoord2f(0, 0); glVertex2f( x1, y2); glTexCoord2f(0, 0); glVertex2f( x2, y2); glTexCoord2f(0, yb); glVertex2f( x1, y3); glTexCoord2f(0, yb); glVertex2f( x2, y3); glEnd(); glUseProgram(0); } void GLUIPainter::drawCircle( const Rect& rect, int fillColorId, int borderColorId ) const { glUseProgram(m_widgetProgram); glUniform4fv( m_fillColorUniform, 1, s_colors[fillColorId]); glUniform4fv( m_borderColorUniform, 1, s_colors[borderColorId]); glUniform2f( m_zonesUniform, (rect.w / 2) - 1, (rect.w / 2) - 2); float xb = rect.w / 2; float yb = rect.w / 2; float x0 = rect.x; float x1 = rect.x + rect.w; float y0 = rect.y; float y1 = rect.y + rect.h; glBegin(GL_TRIANGLE_STRIP); glTexCoord2f(-xb, -yb); glVertex2f( x0, y0); glTexCoord2f(xb, -yb); glVertex2f( x1, y0); glTexCoord2f(-xb, yb); glVertex2f( x0, y1); glTexCoord2f(xb, yb); glVertex2f( x1, y1); glEnd(); glUseProgram(0); } void GLUIPainter::drawMinus( const Rect& rect, int width, int fillColorId, int borderColorId ) const { float xb = width; float yb = width; float xoff = xb ; float yoff = yb ; float x0 = rect.x + rect.w * 0.1 ; float x1 = rect.x + rect.w * 0.9; float y1 = rect.y + rect.h * 0.5; glUseProgram(m_widgetProgram); glUniform4fv( m_fillColorUniform, 1, s_colors[fillColorId]); glUniform4fv( m_borderColorUniform, 1, s_colors[borderColorId]); glUniform2f( m_zonesUniform, (xb) - 1, (xb) - 2); glBegin(GL_TRIANGLE_STRIP); glTexCoord3f(-xb, -yb, 0); glVertex2f( x0, y1 + yoff); glTexCoord3f(xb, -yb, 0); glVertex2f( x0, y1 - yoff); glTexCoord3f(-xb, 0, 0); glVertex2f( x0 + xoff , y1 + yoff); glTexCoord3f(xb, 0, 0); glVertex2f( x0 + xoff, y1 - yoff); glTexCoord3f(-xb, 0, 0); glVertex2f( x1 - xoff , y1 + yoff); glTexCoord3f(xb, 0, 0); glVertex2f( x1 - xoff, y1 - yoff); glTexCoord3f(-xb, -yb, 0); glVertex2f( x1, y1 + yoff); glTexCoord3f(xb, -yb, 0); glVertex2f( x1, y1 - yoff); glEnd(); glUseProgram(0); } void GLUIPainter::drawPlus( const Rect& rect, int width, int fillColorId, int borderColorId ) const { float xb = width; float yb = width; float xoff = xb ; float yoff = yb ; float x0 = rect.x + rect.w * 0.1 ; float x1 = rect.x + rect.w * 0.5; float x2 = rect.x + rect.w * 0.9; float y0 = rect.y + rect.h * 0.1; float y1 = rect.y + rect.h * 0.5; float y2 = rect.y + rect.h * 0.9; glUseProgram(m_widgetProgram); glUniform4fv( m_fillColorUniform, 1, s_colors[fillColorId]); glUniform4fv( m_borderColorUniform, 1, s_colors[borderColorId]); glUniform2f( m_zonesUniform, (xb) - 1, (xb) - 2); /* glBegin(GL_TRIANGLE_STRIP); glTexCoord3f(-xb, -yb, 0); glVertex2f( x0, y1 + yoff); glTexCoord3f(xb, -yb, 0); glVertex2f( x0, y1 - yoff); glTexCoord3f(-xb, 0, 0); glVertex2f( x0 + xoff , y1 + yoff); glTexCoord3f(xb, 0, 0); glVertex2f( x0 + xoff, y1 - yoff); glTexCoord3f(-xb, 0, 0); glVertex2f( x1 - xoff , y1 + yoff); glTexCoord3f(xb, 0, 0); glVertex2f( x1 - xoff, y1 - yoff); glTexCoord3f(0, yb, 0); glVertex2f( x1, y1); glEnd(); glBegin(GL_TRIANGLE_STRIP); glTexCoord3f(0, yb, 0); glVertex2f( x1, y1); glTexCoord3f(-xb, 0, 0); glVertex2f( x1 + xoff , y1 + yoff); glTexCoord3f(xb, 0, 0); glVertex2f( x1 + xoff, y1 - yoff); glTexCoord3f(-xb, 0, 0); glVertex2f( x2 - xoff , y1 + yoff); glTexCoord3f(xb, 0, 0); glVertex2f( x2 - xoff, y1 - yoff); glTexCoord3f(-xb, -yb, 0); glVertex2f( x2, y1 + yoff); glTexCoord3f(xb, -yb, 0); glVertex2f( x2, y1 - yoff); glEnd(); */ glBegin(GL_TRIANGLE_STRIP); glTexCoord3f(-xb, -yb, 0); glVertex2f( x0, y1 + yoff); glTexCoord3f(xb, -yb, 0); glVertex2f( x0, y1 - yoff); glTexCoord3f(-xb, 0, 0); glVertex2f( x0 + xoff , y1 + yoff); glTexCoord3f(xb, 0, 0); glVertex2f( x0 + xoff, y1 - yoff); glTexCoord3f(-xb, 0, 0); glVertex2f( x2 - xoff , y1 + yoff); glTexCoord3f(xb, 0, 0); glVertex2f( x2 - xoff, y1 - yoff); glTexCoord3f(-xb, -yb, 0); glVertex2f( x2, y1 + yoff); glTexCoord3f(xb, -yb, 0); glVertex2f( x2, y1 - yoff); glEnd(); glBegin(GL_TRIANGLE_STRIP); glTexCoord3f(-xb, -yb, 0); glVertex2f( x1 + yoff, y0); glTexCoord3f(xb, -yb, 0); glVertex2f( x1 - yoff, y0); glTexCoord3f(-xb, 0, 0); glVertex2f( x1 + yoff, y0 + yoff); glTexCoord3f(xb, 0, 0); glVertex2f( x1 - yoff, y0 + yoff); glTexCoord3f(-xb, 0, 0); glVertex2f( x1 + yoff, y2 - yoff); glTexCoord3f(xb, 0, 0); glVertex2f( x1 - yoff, y2 - yoff); glTexCoord3f(-xb, -yb, 0); glVertex2f( x1 + yoff, y2); glTexCoord3f(xb, -yb, 0); glVertex2f( x1 - yoff, y2); glEnd(); /**/ glUseProgram(0); } void GLUIPainter::drawDownArrow( const Rect& rect, int width, int fillColorId, int borderColorId ) const { float offset = sqrt(2.0) / 2.0 ; float xb = width; float yb = width; float xoff = offset * xb ; float yoff = offset * yb ; float xoff2 = offset * xb * 2.0 ; float yoff2 = offset * yb * 2.0; float x0 = rect.x + xoff2; float x1 = rect.x + rect.w * 0.5; float x2 = rect.x + rect.w - xoff2; float y0 = rect.y + rect.h * 0.1 + yoff2; float y1 = rect.y + rect.h * 0.6; glUseProgram(m_widgetProgram); glUniform4fv( m_fillColorUniform, 1, s_colors[fillColorId]); glUniform4fv( m_borderColorUniform, 1, s_colors[borderColorId]); glUniform2f( m_zonesUniform, (xb) - 1, (xb) - 2); glBegin(GL_TRIANGLE_STRIP); glTexCoord3f(-xb, -yb, 0); glVertex2f( x0, y1 + yoff2); glTexCoord3f(xb, -yb, 0); glVertex2f( x0 - xoff2, y1); glTexCoord3f(-xb, 0, 0); glVertex2f( x0 + xoff, y1 + yoff); glTexCoord3f(xb, 0, 0); glVertex2f( x0 - xoff, y1 - yoff); glTexCoord3f(-xb, 0, xb); glVertex2f( x1, y0 + yoff2); glTexCoord3f(xb, 0, xb); glVertex2f( x1 - xoff2, y0); glTexCoord3f(xb, 2*yb, xb); glVertex2f( x1, y0 - yoff2); glEnd(); glBegin(GL_TRIANGLE_STRIP); glTexCoord3f(xb, -yb, 0); glVertex2f( x2 + xoff2, y1); glTexCoord3f(-xb, -yb, 0); glVertex2f( x2, y1 + yoff2); glTexCoord3f(xb, 0, xb); glVertex2f( x2 + xoff, y1 - yoff); glTexCoord3f(-xb, 0, xb); glVertex2f( x2 - xoff, y1 + yoff); glTexCoord3f(xb, 0, xb); glVertex2f( x1 + xoff2, y0); glTexCoord3f(-xb, 0, xb); glVertex2f( x1, y0 + yoff2); glTexCoord3f(xb, 2*yb, xb); glVertex2f( x1, y0 - yoff2); glEnd(); glUseProgram(0); } void GLUIPainter::drawUpArrow( const Rect& rect, int width, int fillColorId, int borderColorId ) const { float offset = sqrt(2.0) / 2.0 ; float xb = width; float yb = width; float xoff = offset * xb ; float yoff = - offset * yb ; float xoff2 = offset * xb * 2.0 ; float yoff2 = - offset * yb * 2.0; float x0 = rect.x + xoff2; float x1 = rect.x + rect.w * 0.5; float x2 = rect.x + rect.w - xoff2; float y0 = rect.y + rect.h * 0.9 + yoff2; float y1 = rect.y + rect.h * 0.4; glUseProgram(m_widgetProgram); glUniform4fv( m_fillColorUniform, 1, s_colors[fillColorId]); glUniform4fv( m_borderColorUniform, 1, s_colors[borderColorId]); glUniform2f( m_zonesUniform, (xb) - 1, (xb) - 2); glBegin(GL_TRIANGLE_STRIP); glTexCoord3f(-xb, -yb, 0); glVertex2f( x0, y1 + yoff2); glTexCoord3f(xb, -yb, 0); glVertex2f( x0 - xoff2, y1); glTexCoord3f(-xb, 0, 0); glVertex2f( x0 + xoff, y1 + yoff); glTexCoord3f(xb, 0, 0); glVertex2f( x0 - xoff, y1 - yoff); glTexCoord3f(-xb, 0, xb); glVertex2f( x1, y0 + yoff2); glTexCoord3f(xb, 0, xb); glVertex2f( x1 - xoff2, y0); glTexCoord3f(xb, 2*yb, xb); glVertex2f( x1, y0 - yoff2); glEnd(); glBegin(GL_TRIANGLE_STRIP); glTexCoord3f(xb, -yb, 0); glVertex2f( x2 + xoff2, y1); glTexCoord3f(-xb, -yb, 0); glVertex2f( x2, y1 + yoff2); glTexCoord3f(xb, 0, xb); glVertex2f( x2 + xoff, y1 - yoff); glTexCoord3f(-xb, 0, xb); glVertex2f( x2 - xoff, y1 + yoff); glTexCoord3f(xb, 0, xb); glVertex2f( x1 + xoff2, y0); glTexCoord3f(-xb, 0, xb); glVertex2f( x1, y0 + yoff2); glTexCoord3f(xb, 2*yb, xb); glVertex2f( x1, y0 - yoff2); glEnd(); glUseProgram(0); } void GLUIPainter::drawText( const Rect& r, const char * text, int nbLines, int caretPos, bool isHover, bool isOn, bool /*isFocus*/ ) { if (isHover || isOn /* || isFocus*/) { drawRect(r, cFontBack + (isHover) + (isOn << 1), cOutline); } glColor4fv(s_colors[cFont]); drawString(r.x, r.y, text, nbLines); if (caretPos != -1) { int w = getTextLineWidthAt( text, caretPos); drawRect(Rect( r.x + w, r.y, 2, r.h), cOutline, cOutline); } } void GLUIPainter::drawFrame( const Rect& rect, const Point& corner, bool isHover, bool isOn, bool /*isFocus*/ ) const { int lColorNb = cBase + (isHover) + (isOn << 1);// + (isFocus << 2); if (corner.x + corner.y == 0) drawRect( rect , lColorNb, cOutline); else drawRoundedRect( rect, corner , lColorNb, cOutline ); } void GLUIPainter::drawBoolFrame( const Rect& rect, const Point& corner, bool isHover, bool isOn, bool /*isFocus*/ ) const { int lColorNb = cBool + (isHover) + (isOn << 1);// + (isFocus << 2); drawRoundedRect( rect, corner , lColorNb, cOutline ); } void GLUIPainter::drawDebugRect(const Rect & rect) { glBegin(GL_LINE_STRIP); glVertex2i( rect.x + 1, rect.y + 1); glVertex2i( rect.x + rect.w, rect.y + 1); glVertex2i( rect.x + rect.w, rect.y + rect.h); glVertex2i( rect.x + 1, rect.y + rect.h); glVertex2i( rect.x + 1, rect.y); glEnd(); }
[ "[email protected]@ae0aad3f-0d2d-2c89-41f8-224e04efc9db" ]
[ [ [ 1, 1278 ] ] ]
d8086386dd414f10a76bfc38d3f61571472f18c9
93176e72508a8b04769ee55bece71095d814ec38
/Utilities/otbliblas/include/liblas/external/property_tree/ptree_fwd.hpp
4c13984e1a69f9085d63d5702e688dd73bf16e5e
[ "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
4,779
hpp
// ---------------------------------------------------------------------------- // Copyright (C) 2002-2006 Marcin Kalicinski // Copyright (C) 2009 Sebastian Redl // // 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_PTREE_FWD_HPP_INCLUDED #define BOOST_PROPERTY_TREE_PTREE_FWD_HPP_INCLUDED #include <boost/config.hpp> #include <boost/optional/optional_fwd.hpp> #include <boost/throw_exception.hpp> #include <functional> // for std::less #include <memory> // for std::allocator #include <string> namespace liblas { namespace property_tree { namespace detail { template <typename T> struct less_nocase; } // Classes template < class Key, class Data, class KeyCompare = std::less<Key> > class basic_ptree; template <typename T> struct id_translator; template <typename String, typename Translator> class string_path; // Texas-style concepts for documentation only. #if 0 concept PropertyTreePath<class Path> { // The key type for which this path works. typename key_type; // Return the key that the first segment of the path names. // Split the head off the state. key_type Path::reduce(); // Return true if the path is empty. bool Path::empty() const; // Return true if the path contains a single element. bool Path::single() const; // Dump as a std::string, for exception messages. std::string Path::dump() const; } concept PropertyTreeKey<class Key> { PropertyTreePath path; requires SameType<Key, PropertyTreePath<path>::key_type>; } concept PropertyTreeTranslator<class Tr> { typename internal_type; typename external_type; boost::optional<external_type> Tr::get_value(internal_type); boost::optional<internal_type> Tr::put_value(external_type); } #endif /// If you want to use a custom key type, specialize this struct for it /// and give it a 'type' typedef that specifies your path type. The path /// type must conform to the Path concept described in the documentation. /// This is already specialized for std::basic_string. template <typename Key> struct path_of; /// Specialize this struct to specify a default translator between the data /// in a tree whose data_type is Internal, and the external data_type /// specified in a get_value, get, put_value or put operation. /// This is already specialized for Internal being std::basic_string. template <typename Internal, typename External> struct translator_between; class ptree_error; class ptree_bad_data; class ptree_bad_path; // Typedefs /** Implements a path using a std::string as the key. */ typedef string_path<std::string, id_translator<std::string> > path; /** * A property tree with std::string for key and data, and default * comparison. */ typedef basic_ptree<std::string, std::string> ptree; /** * A property tree with std::string for key and data, and case-insensitive * comparison. */ typedef basic_ptree<std::string, std::string, detail::less_nocase<std::string> > iptree; #ifndef BOOST_NO_STD_WSTRING /** Implements a path using a std::wstring as the key. */ typedef string_path<std::wstring, id_translator<std::wstring> > wpath; /** * A property tree with std::wstring for key and data, and default * comparison. * @note The type only exists if the platform supports @c wchar_t. */ typedef basic_ptree<std::wstring, std::wstring> wptree; /** * A property tree with std::wstring for key and data, and case-insensitive * comparison. * @note The type only exists if the platform supports @c wchar_t. */ typedef basic_ptree<std::wstring, std::wstring, detail::less_nocase<std::wstring> > wiptree; #endif // Free functions /** * Swap two property tree instances. */ template<class K, class D, class C> void swap(basic_ptree<K, D, C> &pt1, basic_ptree<K, D, C> &pt2); } } #if !defined(BOOST_PROPERTY_TREE_DOXYGEN_INVOKED) // Throwing macro to avoid no return warnings portably # define BOOST_PROPERTY_TREE_THROW(e) BOOST_THROW_EXCEPTION(e) #endif #endif
[ [ [ 1, 143 ] ] ]
a8f3b18c3523022bdbfa123d879b38eae1485a98
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/os/ossrv/stdlibs/apps/libc/testmisc/spawnchild/src/testabort.cpp
1144ea47ae147b5fc50803baf39f13a7dfebd97d
[]
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
840
cpp
/* * Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: * */ // INCLUDE FILES #include <e32def.h> #include <e32std.h> #include <stdio.h> #include <e32base.h> #include <unistd.h> #include <stdlib.h> void abortTest() { abort(); } TInt E32Main() { __UHEAP_MARK; CTrapCleanup* cleanup = CTrapCleanup::New(); TRAPD(error,abortTest()); //Destroy cleanup stack delete cleanup; __UHEAP_MARKEND; return error; }
[ "none@none" ]
[ [ [ 1, 43 ] ] ]
768d3230b9f810aeb3cb29e8f485aa7230ecd627
ce148b48b453a58d84664ec979eb64e4813a83c8
/Faeried/types.h
3e26b319e16b13c9c885fae22c95e356b453865a
[]
no_license
theyoprst/Faeried
e8945f8cb21c317eeeb1b05f0d12b297b63621fe
d20bd990e7f91c8c03857d81e08b8f7f2dee3541
refs/heads/master
2020-04-09T16:04:47.472907
2011-02-21T16:38:02
2011-02-21T16:38:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
64
h
#pragma once typedef std::vector<std::string> StringVector;
[ [ [ 1, 3 ] ] ]
117806a9c2219b8b2c0f6101eec5a97666dcff86
fac8de123987842827a68da1b580f1361926ab67
/inc/physics/Physics/Dynamics/Constraint/Bilateral/LimitedHinge/hkpLimitedHingeConstraintData.h
b4af87b3a3a872c1902025198ff18763868d7a39
[]
no_license
blockspacer/transporter-game
23496e1651b3c19f6727712a5652f8e49c45c076
083ae2ee48fcab2c7d8a68670a71be4d09954428
refs/heads/master
2021-05-31T04:06:07.101459
2009-02-19T20:59:59
2009-02-19T20:59:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,554
h
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent.This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2008 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HK_LIMITED_HINGE_CONSTRAINT_H #define HK_LIMITED_HINGE_CONSTRAINT_H #include <Physics/Dynamics/Constraint/hkpConstraintData.h> #include <Physics/ConstraintSolver/Constraint/Atom/hkpConstraintAtom.h> extern const hkClass hkpLimitedHingeConstraintDataClass; /// Full hinge constraint with limits and motor. /// /// By default the motor is disabled. When the motor is enabled friction is automatically disabled. class hkpLimitedHingeConstraintData : public hkpConstraintData { public: HK_DECLARE_REFLECTION(); hkpLimitedHingeConstraintData(); ~hkpLimitedHingeConstraintData(); /// Set the data for a Limited Hinge constraint with information given in body space. /// \param pivotA The constraint pivot point, specified in bodyA space. /// \param pivotB The constraint pivot point, specified in bodyB space. /// \param axisA The hinge axis, specified in bodyA space. /// \param axisB The hinge axis, specified in bodyB space. /// \param axisAPerp Axis perpendicular to the hinge axis, specified in bodyA space. /// \param axisBPerp Axis perpendicular to the hinge axis, specified in bodyB space. void setInBodySpace(const hkVector4& pivotA, const hkVector4& pivotB, const hkVector4& axisA, const hkVector4& axisB, const hkVector4& axisAPerp, const hkVector4& axisBPerp); /// Set the data for a Limited Hinge constraint with information given in world space. /// \param bodyA The first rigid body transform. /// \param bodyB The second rigid body transform. /// \param pivot The pivot point, specified in world space. /// \param axis The hinge axis, specified in world space. void setInWorldSpace(const hkTransform& bodyATransform, const hkTransform& bodyBTransform, const hkVector4& pivot, const hkVector4& axis); /// Check consistency of constraint members virtual hkBool isValid() const; /* Methods to set and get angle limits and friction */ /// Sets the friction value. Set this before adding to the system. /// Note that this value is an absolute torque value and is therefore dependent on the masses of constrained bodies /// and not limited between 0.0f and 1.0f. /// If trying to stiffen up hinge constraints, try setting this value sufficiently high so that constraints are completely stiff and then /// reduce until the desired behaviour has been achieved. inline void setMaxFrictionTorque(hkReal tmag); /// Gets the friction value. inline hkReal getMaxFrictionTorque() const; /// Sets the maximum angular limit. inline void setMaxAngularLimit(hkReal rad); /// Sets the minimum angular limit. inline void setMinAngularLimit(hkReal rad); /// Gets the maximum angular limit. inline hkReal getMaxAngularLimit() const; /// Gets the minimum angular limit. inline hkReal getMinAngularLimit() const; /// sets the m_angularLimitsTauFactor. This is a factor in the range between 0 and 1 /// which controls the stiffness of the angular limits. If you slowly increase /// this value from 0 to 1 for a newly created constraint, /// you can nicely blend in the limits. inline void setAngularLimitsTauFactor( hkReal mag ); /// get the m_angularLimitsTauFactor; inline hkReal getAngularLimitsTauFactor( ); /// This is the preferable way to disable angular limits when motor is active. inline void disableLimits(); // // Motor-related methods // /// get the motor. default is HK_NULL inline hkpConstraintMotor* getMotor() const; /// Is this motor on ? inline hkBool isMotorActive() const; /// turn the motor on or off void setMotorActive( hkpConstraintInstance* instance, hkBool toBeEnabled ); /// Set the motor. Setting this to null will disable any motor computations. /// The angle passed to the hkpConstraintMotor::motor() callback will be the relative angle /// between the attached and reference body. You need to set the desired target angle of /// your motor each step. /// increments reference of new motor, decrements counter of replaced motor ( if any ) void setMotor( hkpConstraintMotor* motor ); /// Sets the target angle for the motor. Only used by motors which use positions inline void setMotorTargetAngle( hkReal angle ); /// Gets the target angle for the motor inline hkReal getMotorTargetAngle(); // // // /// Get type from this constraint virtual int getType() const; enum { SOLVER_RESULT_MOTOR = 0, // the motor SOLVER_RESULT_FRICTION = 1, // or friction SOLVER_RESULT_LIMIT = 2, // limits defined around m_freeAxisA SOLVER_RESULT_ANG_0 = 3, // angular constraint 0 SOLVER_RESULT_ANG_1 = 4, // angular constraint 1 SOLVER_RESULT_LIN_0 = 5, // linear constraint SOLVER_RESULT_LIN_1 = 6, // linear constraint SOLVER_RESULT_LIN_2 = 7, // linear constraint SOLVER_RESULT_MAX = 8 }; struct Runtime { HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_DYNAMICS, hkpLimitedHingeConstraintData::Runtime ); // Solver results must always be in the first position HK_ALIGN16( class hkpSolverResults m_solverResults[8/*VC6 doesn't like the scoping for SOLVER_RESULT_MAX*/] ); // To tell whether the previous angle has been initialized. hkUint8 m_initialized; // The previous target angle hkReal m_previousTargetAngle; /// Returns current angle position inline hkReal getCurrentPos() const; }; static inline Runtime* HK_CALL getRuntime( hkpConstraintRuntime* runtime ) { return reinterpret_cast<Runtime*>(runtime); } public: struct Atoms { HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_DYNAMICS, hkpLimitedHingeConstraintData::Atoms ); HK_DECLARE_REFLECTION(); struct hkpSetLocalTransformsConstraintAtom m_transforms; struct hkpAngMotorConstraintAtom m_angMotor; struct hkpAngFrictionConstraintAtom m_angFriction; struct hkpAngLimitConstraintAtom m_angLimit; struct hkp2dAngConstraintAtom m_2dAng; struct hkpBallSocketConstraintAtom m_ballSocket; enum Axis { AXIS_AXLE = 0, AXIS_PERP_TO_AXLE_1 = 1, AXIS_PERP_TO_AXLE_2 = 2 }; Atoms(){} // get a pointer to the first atom const hkpConstraintAtom* getAtoms() const { return &m_transforms; } // get the size of all atoms (we can't use sizeof(*this) because of align16 padding) int getSizeOfAllAtoms() const { return hkGetByteOffsetInt(this, &m_ballSocket+1); } Atoms(hkFinishLoadedObjectFlag f) : m_transforms(f), m_angMotor(f), m_angFriction(f), m_angLimit(f), m_2dAng(f), m_ballSocket(f) {} }; HK_ALIGN16( struct Atoms m_atoms ); public: // hkpConstraintData interface implementations virtual void getConstraintInfo( ConstraintInfo& infoOut ) const ; // hkpConstraintData interface implementations virtual void getRuntimeInfo( hkBool wantRuntime, hkpConstraintData::RuntimeInfo& infoOut ) const; public: hkpLimitedHingeConstraintData(hkFinishLoadedObjectFlag f) : hkpConstraintData(f), m_atoms(f) {} }; #include <Physics/Dynamics/Constraint/Bilateral/LimitedHinge/hkpLimitedHingeConstraintData.inl> #endif /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20080529) * * Confidential Information of Havok. (C) Copyright 1999-2008 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at * www.havok.com/tryhavok * */
[ "uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4" ]
[ [ [ 1, 223 ] ] ]
9b38ee72155d8d5f533cbaa91a3bc06bb3f59c2d
205069c97095da8f15e45cede1525f384ba6efd2
/Casino/Code/Server/GameModule/B_BlackJack/GameProject/GameServerManager.cpp
83faea7afd738b5afc7303f923fa207454697a68
[]
no_license
m0o0m/01technology
1a3a5a48a88bec57f6a2d2b5a54a3ce2508de5ea
5e04cbfa79b7e3cf6d07121273b3272f441c2a99
refs/heads/master
2021-01-17T22:12:26.467196
2010-01-05T06:39:11
2010-01-05T06:39:11
null
0
0
null
null
null
null
GB18030
C++
false
false
3,434
cpp
#include "StdAfx.h" #include "Tableframesink.h" #include "GameServerManager.h" #include "..\CommandDefinition\CMD_BlackJack.h" ////////////////////////////////////////////////////////////////////////// //全局变量 static CGameServiceManager g_GameServiceManager; //管理变量 ////////////////////////////////////////////////////////////////////////// //构造函数 CGameServiceManager::CGameServiceManager(void) { //设置属性 m_GameServiceAttrib.wKindID = KIND_ID; m_GameServiceAttrib.dwServerVersion = 0; m_GameServiceAttrib.dwMaxClientVersion = MAXCLIENTVER; m_GameServiceAttrib.dwLessClientVersion = LESSCLIENTVER; m_GameServiceAttrib.dwMaxClientVersion = 0; m_GameServiceAttrib.dwLessClientVersion = 0; m_GameServiceAttrib.wSupporType = GAME_GENRE; m_GameServiceAttrib.wChairCount = GAME_PLAYER; lstrcpyn(m_GameServiceAttrib.szKindName, GAME_NAME, CountArray(m_GameServiceAttrib.szKindName)); lstrcpyn(m_GameServiceAttrib.szDescription, TEXT("21点GameService组件"), CountArray(m_GameServiceAttrib.szDescription)); lstrcpyn(m_GameServiceAttrib.szServerModuleName, TEXT("B_BlackJack.dll"), CountArray(m_GameServiceAttrib.szServerModuleName)); m_GameServiceAttrib.wProcessType = ID_B_BACK_JACK; m_GameServiceAttrib.wBetRegionCount = 1; m_GameServiceAttrib.bCheckCellScoreBeforeStartGame = TRUE; m_GameServiceAttrib.bCheckSameIP = TRUE; return; } //析构函数 CGameServiceManager::~CGameServiceManager(void) { } //接口查询 void * __cdecl CGameServiceManager::QueryInterface(const IID & Guid, DWORD dwQueryVer) { QUERYINTERFACE(IGameServiceManager, Guid, dwQueryVer); QUERYINTERFACE_IUNKNOWNEX(IGameServiceManager, Guid, dwQueryVer); return NULL; } //创建游戏桌 void * __cdecl CGameServiceManager::CreateTableFrameSink(const IID & Guid, DWORD dwQueryVer) { //建立对象 CTableFrameSink * pTableFrameSink = NULL; try { pTableFrameSink = new CTableFrameSink(); if(pTableFrameSink == NULL) { throw TEXT("创建失败"); } void * pObject = pTableFrameSink->QueryInterface(Guid, dwQueryVer); if(pObject == NULL) { throw TEXT("接口查询失败"); } return pObject; } catch (...) {} //清理对象 SafeDelete(pTableFrameSink); return NULL; } //获取属性 void __cdecl CGameServiceManager::GetGameServiceAttrib(tagGameServiceAttrib & GameServiceAttrib) { GameServiceAttrib = m_GameServiceAttrib; return; } //参数修改 bool __cdecl CGameServiceManager::RectifyServiceOption(tagGameServiceOption * pGameServiceOption) { //效验参数 GT_ASSERT(pGameServiceOption != NULL); if (pGameServiceOption == NULL) return false; //信用额度调整 pGameServiceOption->dwCellScore = __max(1L,pGameServiceOption->dwCellScore); if (pGameServiceOption->dwHighScore != 0L) pGameServiceOption->dwHighScore = __max(pGameServiceOption->dwHighScore,pGameServiceOption->dwLessScore); return true; } ////////////////////////////////////////////////////////////////////////// //建立对象函数 extern "C" __declspec(dllexport) void * __cdecl CreateGameServiceManager(const GUID & Guid, DWORD dwInterfaceVer) { return g_GameServiceManager.QueryInterface(Guid, dwInterfaceVer); } //////////////////////////////////////////////////////////////////////////
[ [ [ 1, 127 ] ] ]
c11207060e5bc372b2050795d140821275c511d4
1a7dc583c09bb1278ec7fd4d7798f9f9d37c6f4d
/RX/rfm22b.ino
5b3ac4e477d4062f775a7c637621cf6808ea2f71
[]
no_license
xotab26/customopenlrs
afea5aea1f4b956bbe4a647fe4eb26a5bd8af722
8ba26e0fd6e90fbe06c20d7a2c59e5017f6b87e2
refs/heads/master
2021-01-16T01:01:56.935216
2011-12-06T06:27:10
2011-12-06T06:27:10
40,381,874
0
0
null
null
null
null
UTF-8
C++
false
false
8,799
ino
// ********************************************************** // ** RFM22B/Si4432 control functions for OpenLRS ** // ** This Source code licensed under GPL ** // ********************************************************** // Latest Code Update : 2011-12-02 // Supported Hardware : OpenLRS Tx/Rx boards (store.flytron.com) // Project Forum : http://forum.flytron.com/viewforum.php?f=7 // Origin Code Page : http://code.google.com/p/openlrs/ // Mods Code Page : http://code.google.com/p/customopenrc/ // ********************************************************** #define NOP() __asm__ __volatile__("nop") #define RF22B_PWRSTATE_POWERDOWN 0x00 #define RF22B_PWRSTATE_READY 0x01 // TUNE #define RF22B_PWRSTATE_TX 0x0A // TX automatic cleared #define RF22B_PWRSTATE_RX 0x06 // RX automatic cleared #define RF22B_PACKET_RECIVED_INTERRUPT 0x02 #define RF22B_PACKET_SENT_INTERRUPT 0x04 unsigned char ItStatus1, ItStatus2; //-------------------------------------------------------------- void Write0( void ) { SCK_off; NOP(); SDI_off; NOP(); SCK_on; } //-------------------------------------------------------------- void Write1( void ) { SCK_off; NOP(); SDI_on; NOP(); SCK_on; } //-------------------------------------------------------------- void Write8bitcommand(unsigned char command) // keep sel to low { unsigned char n=8; nSEL_on; NOP(); SCK_off; NOP(); nSEL_off; while(n--) { if(command&0x80) Write1(); else Write0(); command = command << 1; } SCK_off; } //-------------------------------------------------------------- unsigned char _spi_read(unsigned char address) { unsigned char result; send_read_address(address); result = read_8bit_data(); nSEL_on; return(result); } //-------------------------------------------------------------- void _spi_write(unsigned char address, unsigned char data) { address |= 0x80; Write8bitcommand(address); send_8bit_data(data); nSEL_on; } //-------------------------------------------------------------- void send_read_address(unsigned char i) { i &= 0x7f; Write8bitcommand(i); } //-------------------------------------------------------------- void send_8bit_data(unsigned char i) { unsigned char n = 8; SCK_off; while(n--) { if(i&0x80) // B10000000 Write1(); else Write0(); i = i << 1; } SCK_off; } //-------------------------------------------------------------- unsigned char read_8bit_data(void) { unsigned char Result, i; SCK_off; Result=0; for(i=0;i<8;i++) { //read fifo data byte Result=Result<<1; SCK_on; NOP(); if(SDO_1) { Result|=1; } SCK_off; NOP(); } return(Result); } //-------------------------------------------------------------- // RFM 22 INIT void RF22B_init_parameter(void) { ItStatus1 = _spi_read(0x03); // read status, clear interrupt ItStatus2 = _spi_read(0x04); _spi_write(0x06, 0x00); // no wakeup up, lbd, _spi_write(0x07, 0x02); // TUNE Mode _spi_write(0x09, 0x7f); // c = 12.5p DEF _spi_write(0x0a, 0x05); // Clock 2Mhz _spi_write(0x0b, 0x12); // gpio0 TX State _spi_write(0x0c, 0x15); // gpio1 RX State _spi_write(0x0d, 0xfd); // gpio2 VDD _spi_write(0x0e, 0x00); // gpio 0, 1,2 NO OTHER FUNCTION. DEF _spi_write(0x1c, 0x16); // Datenrate _spi_write(0x20, 0x45);// 0x20 calculate from the datasheet= 500*(1+2*down3_bypass)/(2^ndec*RB*(1+enmanch)) _spi_write(0x21, 0x01); // 0x21 , rxosr[10--8] = 0; stalltr = (default), ccoff[19:16] = 0; _spi_write(0x22, 0xD7); // 0x22 ncoff =5033 = 0x13a9 _spi_write(0x23, 0xDC); // 0x23 _spi_write(0x24, 0x07); // 0x24 _spi_write(0x25, 0x6E); // 0x25 _spi_write(0x2a, 0x1B); _spi_write(0x30, 0x8c); // enable packet handler, msb first, enable crc, _spi_write(0x32, 0x0E); // 0x32address enable for headere byte 0, 1,2,3, receive header check for byte 0, 1,2,3 _spi_write(0x33, 0x3A); // header 3, 2, 1,0 used for head length, fixed packet length, synchronize word length 3, 2, _spi_write(0x34, 0x08); // 8 default value or // 64 nibble = 32byte preamble _spi_write(0x35, 0x22); // preamble detection + rssi offset _spi_write(0x36, 0x2d); // synchronize word _spi_write(0x37, 0xd4); // synchronize word _spi_write(0x38, 0x00); // synchronize word _spi_write(0x39, 0x00); // synchronize word _spi_write(0x3a, RF_Header[0]); // tx header _spi_write(0x3b, RF_Header[1]); _spi_write(0x3c, RF_Header[2]); _spi_write(0x3d, RF_Header[3]); _spi_write(0x3e, 0x18); // tx 24 byte packages //RX HEADER _spi_write(0x3f, RF_Header[0]); // check header _spi_write(0x40, RF_Header[1]); _spi_write(0x41, RF_Header[2]); _spi_write(0x42, RF_Header[3]); _spi_write(0x43, 0xff); // all the bit to be checked _spi_write(0x44, 0xff); // all the bit to be checked _spi_write(0x45, 0xff); // all the bit to be checked _spi_write(0x46, 0x00); // all the bit to be checked //_spi_write(0x6d, 0x07); // 7 set power max power _spi_write(0x6e, 0xEB); //case RATE_28,8K _spi_write(0x6f, 0xEE); //case RATE_28,8K _spi_write(0x70, 0x2C); // disable manchest _spi_write(0x71, 0x23); // Gfsk, fd[8] =0, no invert for Tx/Rx data, fifo mode, txclk -->gpio _spi_write(0x72, 0x17); // frequency deviation _spi_write(0x7a, 0x05); // 50khz step size (10khz x value) // no hopping _spi_write(0x75, 0x53); // Band // Frequenz 433,09 Mhz _spi_write(0x76, 0x4d); // Frequenz 433,09 Mhz _spi_write(0x77, 0x40); // Frequenz 433,09 Mhz #if (DEBUG_MODE==99) Serial.println("init-rfm22"); #endif } //----------------------------------------------------------------------- void rx_mode(void) // Aim for RX Package { #if (DEBUG_MODE==90) Serial.println("rx_mode"); #endif ItStatus1 = _spi_read(0x03); //clear Interupt Status 1 _spi_write(0x7e, 24); //FiFo Threshold _spi_write(0x08, 0x03); // clear fifo _spi_write(0x08, 0x00); // clear fifo _spi_write(0x07, RF22B_PWRSTATE_RX ); // to rx mode _spi_write(0x05, RF22B_PACKET_RECIVED_INTERRUPT); // Aim IRQ at Recived Package } //-------------------------------------------------------------- void tx_mode(void) // Transmit Package, wait to be send OK IRQ { #if (DEBUG_MODE==90) Serial.println("tx_mode"); #endif unsigned char i; ItStatus1 = _spi_read(0x03); //clear Interupt Status 1 _spi_write(0x08, 0x03); // clear fifo _spi_write(0x08, 0x00); // clear fifo // fifo burst write Write8bitcommand(0x7f | 0x80); // select fifo for (i = 0; i<24; i++) // TX schreiben { send_8bit_data(RF_Tx_Buffer[i]); } nSEL_on; // finish burst _spi_write(0x05, RF22B_PACKET_SENT_INTERRUPT); // Aim IRQ at Package sent _spi_write(0x07, RF22B_PWRSTATE_TX); // to tx mode and send 1 package while(nIRQ_1); // wait until package send interupt from rf22 } //-------------------------------------------------------------- void frequency_configurator(long frequency){ // frequency formulation from Si4432 chip's datasheet // original formulation is working with mHz values and floating numbers, I replaced them with kHz values. frequency = frequency / 10; frequency = frequency - 24000; frequency = frequency - 19000; // 19 for 430–439.9 MHz band from datasheet // frequency = frequency - 21000; // 21 for 450–459.9 MHz band from datasheet frequency = frequency * 64; // this is the Nominal Carrier Frequency (fc) value for register setting byte byte0 = (byte) frequency; byte byte1 = (byte) (frequency >> 8); _spi_write(0x76, byte1); _spi_write(0x77, byte0); } //############# RF POWER SETUP ################# void Power_Set(unsigned short level) { //Power Level value between 0-7 //0 = +1 dBm //1 = +2 dBm //2 = +5 dBm //3 = +8 dBm //4 = +11 dBm //5 = +14 dBm //6 = +17 dBm //7 = +20 dB if (level<8) _spi_write(0x6d, level); //TODO Beeper when reduced power }
[ [ [ 1, 277 ] ] ]
1ccf32acf2729472b6e301b54e69d506908bc4f8
028d79ad6dd6bb4114891b8f4840ef9f0e9d4a32
/src/android/video.cpp
0617bb5260e5c434929260c98fb5b881c7f063d9
[]
no_license
neonichu/iMame4All-for-iPad
72f56710d2ed7458594838a5152e50c72c2fb67f
4eb3d4ed2e5ccb5c606fcbcefcb7c5a662ace611
refs/heads/master
2020-04-21T07:26:37.595653
2011-11-26T12:21:56
2011-11-26T12:21:56
2,855,022
4
0
null
null
null
null
UTF-8
C++
false
false
29,683
cpp
#include "driver.h" #include <math.h> #include "vidhrdw/vector.h" #include "dirty.h" extern int global_fps; extern int isIpad; extern int emulated_width; extern int emulated_height; int m4all_exitPause = 0; int m4all_cropVideo = 0; int m4all_aspectRatio = 0; int m4all_fixedRes = 0; dirtygrid grid1; dirtygrid grid2; char *dirty_old=grid1; char *dirty_new=grid2; /* in msdos/sound.c */ int msdos_update_audio(void); /* specialized update_screen functions defined in blit.c */ /* dirty mode 1 (VIDEO_SUPPORTS_DIRTY) */ void blitscreen_dirty1_color8(struct osd_bitmap *bitmap); void blitscreen_dirty1_color16(struct osd_bitmap *bitmap); void blitscreen_dirty1_palettized16(struct osd_bitmap *bitmap); /* dirty mode 0 (no osd_mark_dirty calls) */ void blitscreen_dirty0_color8(struct osd_bitmap *bitmap); void blitscreen_dirty0_color16(struct osd_bitmap *bitmap); void blitscreen_dirty0_palettized16(struct osd_bitmap *bitmap); static void update_screen_dummy(struct osd_bitmap *bitmap); void (*update_screen)(struct osd_bitmap *bitmap) = update_screen_dummy; static int video_depth,video_fps; static int modifiable_palette; static int screen_colors; static unsigned char *current_palette; static unsigned int *dirtycolor; static int dirtypalette; static int dirty_bright; static int bright_lookup[256]; extern UINT32 *palette_16bit_lookup; int frameskip,autoframeskip; #define FRAMESKIP_LEVELS 12 int video_sync; int wait_vsync; int vsync_frame_rate; int skiplines; int skipcolumns; int use_dirty; float osd_gamma_correction = 1.0; int brightness; float brightness_paused_adjust; int gfx_width; int gfx_height; static int viswidth; static int visheight; static int skiplinesmax; static int skipcolumnsmax; static int skiplinesmin; static int skipcolumnsmin; static int vector_game; int gfx_xoffset; int gfx_yoffset; int gfx_display_lines; int gfx_display_columns; static int xmultiply,ymultiply; int throttle = 1; /* toggled by F10 */ static int frameskip_counter; #include "minimal.h" #define TICKER unsigned long long #define ticker() gp2x_timer_read() #define TICKS_PER_SEC 1000 #define vsync() do{}while(0) #define makecol(r,g,b) gp2x_video_color15(r,g,b,0) #define getr(c) gp2x_video_getr15(c) #define getg(c) gp2x_video_getg15(c) #define getb(c) gp2x_video_getb15(c) int video_scale=0; int video_border=0; int video_aspect=0; /* Create a bitmap. Also calls osd_clearbitmap() to appropriately initialize */ /* it to the background color. */ /* VERY IMPORTANT: the function must allocate also a "safety area" 16 pixels wide all */ /* around the bitmap. This is required because, for performance reasons, some graphic */ /* routines don't clip at boundaries of the bitmap. */ const int safety = 16; struct osd_bitmap *osd_alloc_bitmap(int width,int height,int depth) { struct osd_bitmap *bitmap; if ((bitmap = (struct osd_bitmap *)malloc(sizeof(struct osd_bitmap))) != 0) { int i,rowlen,rdwidth; unsigned char *bm; if (depth != 8 && depth != 16) depth = 8; bitmap->depth = depth; bitmap->width = width; bitmap->height = height; rdwidth = (width + 7) & ~7; /* round width to a quadword */ if (depth == 16) rowlen = 2 * (rdwidth + 2 * safety) * sizeof(unsigned char); else rowlen = (rdwidth + 2 * safety) * sizeof(unsigned char); if ((bm = (unsigned char*)malloc((height + 2 * safety) * rowlen)) == 0) { free(bitmap); return 0; } /* clear ALL bitmap, including safety area, to avoid garbage on right */ /* side of screen is width is not a multiple of 4 */ memset(bm,0,(height + 2 * safety) * rowlen); if ((bitmap->line = (unsigned char**)malloc((height + 2 * safety) * sizeof(unsigned char *))) == 0) { free(bm); free(bitmap); return 0; } for (i = 0;i < height + 2 * safety;i++) { if (depth == 16) bitmap->line[i] = &bm[i * rowlen + 2*safety]; else bitmap->line[i] = &bm[i * rowlen + safety]; } bitmap->line += safety; bitmap->_private = bm; osd_clearbitmap(bitmap); } return bitmap; } /* set the bitmap to black */ void osd_clearbitmap(struct osd_bitmap *bitmap) { int i; for (i = 0;i < bitmap->height;i++) { if (bitmap->depth == 16) memset(bitmap->line[i],0,2*bitmap->width); else memset(bitmap->line[i],0,bitmap->width); } if (bitmap == Machine->scrbitmap) { extern int bitmap_dirty; /* in mame.c */ osd_mark_dirty (0,0,bitmap->width-1,bitmap->height-1,1); bitmap_dirty = 1; } } void osd_free_bitmap(struct osd_bitmap *bitmap) { if (bitmap) { bitmap->line -= safety; free(bitmap->line); free(bitmap->_private); free(bitmap); } } void osd_mark_dirty(int _x1, int _y1, int _x2, int _y2, int ui) { if (use_dirty) { int x, y; // logerror("mark_dirty %3d,%3d - %3d,%3d\n", _x1,_y1, _x2,_y2); _x1 -= skipcolumns; _x2 -= skipcolumns; _y1 -= skiplines; _y2 -= skiplines; if (_y1 >= gfx_display_lines || _y2 < 0 || _x1 > gfx_display_columns || _x2 < 0) return; if (_y1 < 0) _y1 = 0; if (_y2 >= gfx_display_lines) _y2 = gfx_display_lines - 1; if (_x1 < 0) _x1 = 0; if (_x2 >= gfx_display_columns) _x2 = gfx_display_columns - 1; for (y = _y1; y <= _y2 + 15; y += 16) for (x = _x1; x <= _x2 + 15; x += 16) MARKDIRTY(x,y); } } static void init_dirty(char dirty) { memset(dirty_new, dirty, MAX_GFX_WIDTH/16 * MAX_GFX_HEIGHT/16); } INLINE void swap_dirty(void) { char *tmp; tmp = dirty_old; dirty_old = dirty_new; dirty_new = tmp; } /* * This function tries to find the best display mode. */ static void select_display_mode(int width,int height,int depth,int attributes,int orientation) { /* 16 bit color is supported only by VESA modes */ if (depth == 16 || depth == 32) { logerror("Game needs %d-bit colors.\n",depth); } emulated_width = width; emulated_height = height; if (!gfx_width && !gfx_height)//no aspect ratio { gfx_width = width; gfx_height = height; } if(m4all_fixedRes == 1) { gfx_width = 320; gfx_height = 240; emulated_width = 320; emulated_height = 240; } else if(m4all_fixedRes == 2) { gfx_width = 240; gfx_height = 320; emulated_width = 240; emulated_height = 320; }else if(m4all_fixedRes == 3) { gfx_width = 640; gfx_height = 480; emulated_width = 640; emulated_height = 480; }else if(m4all_fixedRes == 4) { gfx_width = 480; gfx_height = 640; emulated_width = 480; emulated_height = 640; } if(m4all_cropVideo) { gfx_width = width; gfx_height = height; int rx = m4all_cropVideo == 1 ? 4 : 3; int ry = m4all_cropVideo == 1 ? 3 : 4; //double ratio = 4.0/3.0; //printf("%d %d \n",width,height); int new_width = //gfx_height * ratio; ((((gfx_height*rx)/ry)+7)&~7); if(new_width>gfx_width) { gfx_height = //gfx_width / ratio; ((((gfx_width*ry)/rx)+7)&~7); } else gfx_width = new_width; emulated_width = gfx_width; emulated_height = gfx_height; //printf("%d %d\n",gfx_width,gfx_height); } /* if(iOS_aspectRatio)//aspect ratio { gfx_width = width; gfx_height = height; //double ratio = 4.0/3.0;//isIpad ? 1024.0/768.0 :480.0/320.0; //printf("%d %d %f\n",width,height,ratio); int done = 0; iOS_43 = width > height; int rx = iOS_43 ? 4 : 3; int ry = iOS_43 ? 3 : 4; // Try adjusting width to be proportional to height int newWidth = //(int) (ratio * gfx_height); ((((gfx_height*rx)/ry)+7)&~7); if (newWidth >= gfx_width) { gfx_width = newWidth; done = 1; } // Try adjusting height to be proportional to width if (!done) { int newHeight = //(int) (gfx_width / ratio); ((((gfx_width*ry)/rx)+7)&~7); if (newHeight >= gfx_height) { gfx_height = newHeight; } } //printf("%d %d\n",gfx_width,gfx_height); } */ /* Video hardware scaling */ if (video_scale) { gfx_width=width; gfx_height=height; } /* vector games use 640x480 as default */ if (vector_game && !m4all_fixedRes) { gfx_width = 640; gfx_height = 480; emulated_width = 640; emulated_height = 480; } gp2x_set_video_mode(16,gfx_width,gfx_height); } /* center image inside the display based on the visual area */ void osd_set_visible_area(int min_x,int max_x,int min_y,int max_y) { int act_width; logerror("set visible area %d-%d %d-%d\n",min_x,max_x,min_y,max_y); act_width = gfx_width; viswidth = max_x - min_x + 1; visheight = max_y - min_y + 1; /* setup xmultiply to handle SVGA driver's (possible) double width */ xmultiply = 1; ymultiply = 1; gfx_display_lines = visheight; gfx_display_columns = viswidth; gfx_xoffset = (act_width - viswidth * xmultiply) / 2; if (gfx_display_columns > act_width / xmultiply) gfx_display_columns = act_width / xmultiply; gfx_yoffset = (gfx_height - visheight * ymultiply) / 2; if (gfx_display_lines > gfx_height / ymultiply) gfx_display_lines = gfx_height / ymultiply; skiplinesmin = min_y; skiplinesmax = visheight - gfx_display_lines + min_y; skipcolumnsmin = min_x; skipcolumnsmax = viswidth - gfx_display_columns + min_x; /* Align on a quadword !*/ gfx_xoffset &= ~7; /* the skipcolumns from mame.cfg/cmdline is relative to the visible area */ skipcolumns = min_x + skipcolumns; skiplines = min_y + skiplines; /* Just in case the visual area doesn't fit */ if (gfx_xoffset < 0) { skipcolumns -= gfx_xoffset; gfx_xoffset = 0; } if (gfx_yoffset < 0) { skiplines -= gfx_yoffset; gfx_yoffset = 0; } /* Failsafe against silly parameters */ if (skiplines < skiplinesmin) skiplines = skiplinesmin; if (skipcolumns < skipcolumnsmin) skipcolumns = skipcolumnsmin; if (skiplines > skiplinesmax) skiplines = skiplinesmax; if (skipcolumns > skipcolumnsmax) skipcolumns = skipcolumnsmax; logerror("gfx_width = %d gfx_height = %d\n" "gfx_xoffset = %d gfx_yoffset = %d\n" "xmin %d ymin %d xmax %d ymax %d\n" "skiplines %d skipcolumns %d\n" "gfx_display_lines %d gfx_display_columns %d\n" "xmultiply %d ymultiply %d\n", gfx_width,gfx_height, gfx_xoffset,gfx_yoffset, min_x, min_y, max_x, max_y, skiplines, skipcolumns,gfx_display_lines,gfx_display_columns,xmultiply,ymultiply); set_ui_visarea(skipcolumns, skiplines, skipcolumns+gfx_display_columns-1, skiplines+gfx_display_lines-1); /* round to a multiple of 4 to avoid missing pixels on the right side */ gfx_display_columns = (gfx_display_columns + 3) & ~3; } /* Create a display screen, or window, of the given dimensions (or larger). Attributes are the ones defined in driver.h. Returns 0 on success. */ int osd_create_display(int width,int height,int depth,int fps,int attributes,int orientation) { logerror("width %d, height %d\n", width,height); video_depth = depth; video_fps = fps; brightness = 100; brightness_paused_adjust = 1.0; dirty_bright = 1; if (frameskip < 0) frameskip = 0; if (frameskip >= FRAMESKIP_LEVELS) frameskip = FRAMESKIP_LEVELS-1; #ifdef GP2X { extern int gp2x_pal_50hz; if ((gp2x_pal_50hz) && (video_fps>50) && (frameskip<2)) frameskip=2; } #endif /* Look if this is a vector game */ if (attributes & VIDEO_TYPE_VECTOR) vector_game = 1; else vector_game = 0; if (use_dirty == -1) /* dirty=auto in mame.cfg? */ { /* Is the game using a dirty system? */ if ((attributes & VIDEO_SUPPORTS_DIRTY) || vector_game) use_dirty = 1; else use_dirty = 0; } select_display_mode(width,height,depth,attributes,orientation); if (!osd_set_display(width,height,depth,attributes,orientation)) return 1; /* set visible area to nothing just to initialize it - it will be set by the core */ osd_set_visible_area(0,0,0,0); return 0; } /* set the actual display screen but don't allocate the screen bitmap */ int osd_set_display(int width,int height,int depth,int attributes,int orientation) { int i; if (!gfx_height || !gfx_width) { printf("Please specify height AND width (e.g. -640x480)\n"); return 0; } /* Mark the dirty buffers as dirty */ if (use_dirty) { if (vector_game) /* vector games only use one dirty buffer */ init_dirty (0); else init_dirty(1); swap_dirty(); init_dirty(1); } if (dirtycolor) { for (i = 0;i < screen_colors;i++) dirtycolor[i] = 1; dirtypalette = 1; } /* Set video mode */ gp2x_set_video_mode(depth,gfx_width,gfx_height); vsync_frame_rate = video_fps; if (video_sync) { TICKER a,b; float rate; /* wait some time to let everything stabilize */ for (i = 0;i < 60;i++) { vsync(); a = ticker(); } /* small delay for really really fast machines */ for (i = 0;i < 100000;i++) ; vsync(); b = ticker(); rate = ((float)TICKS_PER_SEC)/(b-a); logerror("target frame rate = %ffps, video frame rate = %3.2fHz\n",video_fps,rate); /* don't allow more than 8% difference between target and actual frame rate */ while (rate > video_fps * 108 / 100) rate /= 2; if (rate < video_fps * 92 / 100) { osd_close_display(); logerror("-vsync option cannot be used with this display mode:\n" "video refresh frequency = %dHz, target frame rate = %ffps\n", (int)(TICKS_PER_SEC/(b-a)),video_fps); return 0; } logerror("adjusted video frame rate = %3.2fHz\n",rate); vsync_frame_rate = rate; if (Machine->sample_rate) { Machine->sample_rate = Machine->sample_rate * video_fps / rate; logerror("sample rate adjusted to match video freq: %d\n",Machine->sample_rate); } } return 1; } /* shut up the display */ void osd_close_display(void) { free(dirtycolor); dirtycolor = 0; free(current_palette); current_palette = 0; free(palette_16bit_lookup); palette_16bit_lookup = 0; } int osd_allocate_colors(unsigned int totalcolors,const unsigned char *palette,unsigned short *pens,int modifiable) { int i; modifiable_palette = modifiable; screen_colors = totalcolors; if (video_depth != 8) screen_colors += 2; else screen_colors = 256; dirtycolor = (unsigned int*)malloc(screen_colors * sizeof(int)); current_palette = (unsigned char*)malloc(3 * screen_colors * sizeof(unsigned char)); palette_16bit_lookup = (UINT32*)malloc(screen_colors * sizeof(palette_16bit_lookup[0])); if (dirtycolor == 0 || current_palette == 0 || palette_16bit_lookup == 0) return 1; for (i = 0;i < screen_colors;i++) dirtycolor[i] = 1; dirtypalette = 1; for (i = 0;i < screen_colors;i++) current_palette[3*i+0] = current_palette[3*i+1] = current_palette[3*i+2] = 0; if (video_depth != 8 && modifiable == 0) { int r,g,b; for (i = 0;i < totalcolors;i++) { r = 255 * brightness * pow(palette[3*i+0] / 255.0, 1 / osd_gamma_correction) / 100; g = 255 * brightness * pow(palette[3*i+1] / 255.0, 1 / osd_gamma_correction) / 100; b = 255 * brightness * pow(palette[3*i+2] / 255.0, 1 / osd_gamma_correction) / 100; *pens++ = makecol(r,g,b); } Machine->uifont->colortable[0] = makecol(0x00,0x00,0x00); Machine->uifont->colortable[1] = makecol(0xff,0xff,0xff); Machine->uifont->colortable[2] = makecol(0xff,0xff,0xff); Machine->uifont->colortable[3] = makecol(0x00,0x00,0x00); } else { if (video_depth == 8 && totalcolors >= 255) { int bestblack,bestwhite; int bestblackscore,bestwhitescore; bestblack = bestwhite = 0; bestblackscore = 3*255*255; bestwhitescore = 0; for (i = 0;i < totalcolors;i++) { int r,g,b,score; r = palette[3*i+0]; g = palette[3*i+1]; b = palette[3*i+2]; score = r*r + g*g + b*b; if (score < bestblackscore) { bestblack = i; bestblackscore = score; } if (score > bestwhitescore) { bestwhite = i; bestwhitescore = score; } } for (i = 0;i < totalcolors;i++) pens[i] = i; /* map black to pen 0, otherwise the screen border will not be black */ pens[bestblack] = 0; pens[0] = bestblack; Machine->uifont->colortable[0] = pens[bestblack]; Machine->uifont->colortable[1] = pens[bestwhite]; Machine->uifont->colortable[2] = pens[bestwhite]; Machine->uifont->colortable[3] = pens[bestblack]; } else { /* reserve color 1 for the user interface text */ current_palette[3*1+0] = current_palette[3*1+1] = current_palette[3*1+2] = 0xff; Machine->uifont->colortable[0] = 0; Machine->uifont->colortable[1] = 1; Machine->uifont->colortable[2] = 1; Machine->uifont->colortable[3] = 0; /* fill the palette starting from the end, so we mess up badly written */ /* drivers which don't go through Machine->pens[] */ for (i = 0;i < totalcolors;i++) pens[i] = (screen_colors-1)-i; } for (i = 0;i < totalcolors;i++) { current_palette[3*pens[i]+0] = palette[3*i]; current_palette[3*pens[i]+1] = palette[3*i+1]; current_palette[3*pens[i]+2] = palette[3*i+2]; } } if (video_depth == 16) { if (modifiable_palette) { if (use_dirty) { update_screen = blitscreen_dirty1_palettized16; logerror("blitscreen_dirty1_palettized16\n"); } else { update_screen = blitscreen_dirty0_palettized16; logerror("blitscreen_dirty0_palettized16\n"); } } else { if (use_dirty) { update_screen = blitscreen_dirty1_color16; logerror("blitscreen_dirty1_color16\n"); } else { update_screen = blitscreen_dirty0_color16; logerror("blitscreen_dirty0_color16\n"); } } } else { if (use_dirty) /* supports dirty ? */ { update_screen = blitscreen_dirty1_color8; logerror("blitscreen_dirty1_color8\n"); } else { update_screen = blitscreen_dirty0_color8; logerror("blitscreen_dirty1_color8\n"); } } return 0; } void osd_modify_pen(int pen,unsigned char red, unsigned char green, unsigned char blue) { if (modifiable_palette == 0) { logerror("error: osd_modify_pen() called with modifiable_palette == 0\n"); return; } if (current_palette[3*pen+0] != red || current_palette[3*pen+1] != green || current_palette[3*pen+2] != blue) { current_palette[3*pen+0] = red; current_palette[3*pen+1] = green; current_palette[3*pen+2] = blue; dirtycolor[pen] = 1; dirtypalette = 1; } } void osd_get_pen(int pen,unsigned char *red, unsigned char *green, unsigned char *blue) { if (video_depth != 8 && modifiable_palette == 0) { *red = getr(pen); *green = getg(pen); *blue = getb(pen); } else { *red = current_palette[3*pen+0]; *green = current_palette[3*pen+1]; *blue = current_palette[3*pen+2]; } } static void update_screen_dummy(struct osd_bitmap *bitmap) { logerror("msdos/video.c: undefined update_screen() function for %d x %d!\n",xmultiply,ymultiply); } INLINE void pan_display(void) { int pan_changed = 0; /* horizontal panning */ if (input_ui_pressed_repeat(IPT_UI_PAN_LEFT,1)) if (skipcolumns < skipcolumnsmax) { skipcolumns++; osd_mark_dirty (0,0,Machine->scrbitmap->width-1,Machine->scrbitmap->height-1,1); pan_changed = 1; } if (input_ui_pressed_repeat(IPT_UI_PAN_RIGHT,1)) if (skipcolumns > skipcolumnsmin) { skipcolumns--; osd_mark_dirty (0,0,Machine->scrbitmap->width-1,Machine->scrbitmap->height-1,1); pan_changed = 1; } if (input_ui_pressed_repeat(IPT_UI_PAN_DOWN,1)) if (skiplines < skiplinesmax) { skiplines++; osd_mark_dirty (0,0,Machine->scrbitmap->width-1,Machine->scrbitmap->height-1,1); pan_changed = 1; } if (input_ui_pressed_repeat(IPT_UI_PAN_UP,1)) if (skiplines > skiplinesmin) { skiplines--; osd_mark_dirty (0,0,Machine->scrbitmap->width-1,Machine->scrbitmap->height-1,1); pan_changed = 1; } if (pan_changed) { if (use_dirty) init_dirty(1); set_ui_visarea (skipcolumns, skiplines, skipcolumns+gfx_display_columns-1, skiplines+gfx_display_lines-1); } } int osd_skip_this_frame(void) { static const int skiptable[FRAMESKIP_LEVELS][FRAMESKIP_LEVELS] = { { 0,0,0,0,0,0,0,0,0,0,0,0 }, { 0,0,0,0,0,0,0,0,0,0,0,1 }, { 0,0,0,0,0,1,0,0,0,0,0,1 }, { 0,0,0,1,0,0,0,1,0,0,0,1 }, { 0,0,1,0,0,1,0,0,1,0,0,1 }, { 0,1,0,0,1,0,1,0,0,1,0,1 }, { 0,1,0,1,0,1,0,1,0,1,0,1 }, { 0,1,0,1,1,0,1,0,1,1,0,1 }, { 0,1,1,0,1,1,0,1,1,0,1,1 }, { 0,1,1,1,0,1,1,1,0,1,1,1 }, { 0,1,1,1,1,1,0,1,1,1,1,1 }, { 0,1,1,1,1,1,1,1,1,1,1,1 } }; return skiptable[frameskip][frameskip_counter]; } /* Update the display. */ void osd_update_video_and_audio(struct osd_bitmap *bitmap) { static const int waittable[FRAMESKIP_LEVELS][FRAMESKIP_LEVELS] = { { 1,1,1,1,1,1,1,1,1,1,1,1 }, { 2,1,1,1,1,1,1,1,1,1,1,0 }, { 2,1,1,1,1,0,2,1,1,1,1,0 }, { 2,1,1,0,2,1,1,0,2,1,1,0 }, { 2,1,0,2,1,0,2,1,0,2,1,0 }, { 2,0,2,1,0,2,0,2,1,0,2,0 }, { 2,0,2,0,2,0,2,0,2,0,2,0 }, { 2,0,2,0,0,3,0,2,0,0,3,0 }, { 3,0,0,3,0,0,3,0,0,3,0,0 }, { 4,0,0,0,4,0,0,0,4,0,0,0 }, { 6,0,0,0,0,0,6,0,0,0,0,0 }, {12,0,0,0,0,0,0,0,0,0,0,0 } }; int i; static int showfps,showfpstemp; TICKER curr; static TICKER prev_measure=0,this_frame_base,prev; static int speed = 100; static int vups,vfcount; int have_to_clear_bitmap = 0; if (prev_measure==0 || m4all_exitPause) { m4all_exitPause = 0; /* first time through, initialize timer */ prev_measure = ticker() - FRAMESKIP_LEVELS * TICKS_PER_SEC/video_fps; } if (frameskip_counter == 0) this_frame_base = prev_measure + FRAMESKIP_LEVELS * TICKS_PER_SEC/video_fps; /* update audio */ msdos_update_audio(); if (osd_skip_this_frame() == 0) { if (showfpstemp) { showfpstemp--; if (showfps == 0 && showfpstemp == 0) { have_to_clear_bitmap = 1; } } if (input_ui_pressed(IPT_UI_SHOW_FPS)) { if (showfpstemp) { showfpstemp = 0; have_to_clear_bitmap = 1; } else { showfps ^= 1; if (showfps == 0) { have_to_clear_bitmap = 1; } } } /* now wait until it's time to update the screen */ if (throttle) { profiler_mark(PROFILER_IDLE); if (video_sync) { static TICKER last; do { vsync(); curr = ticker(); } while (TICKS_PER_SEC / (curr - last) > video_fps * 11 /10); last = curr; } else { TICKER target; /* wait for video sync but use normal throttling */ if (wait_vsync) vsync(); curr = ticker(); target = this_frame_base + frameskip_counter * TICKS_PER_SEC/video_fps; if ((curr < target) && (target-curr<TICKS_PER_SEC)) { do { //sched_yield(); curr = ticker(); } while ((curr < target) && (target-curr<TICKS_PER_SEC)); } } profiler_mark(PROFILER_END); } else curr = ticker(); if (frameskip_counter == 0) { float divdr; divdr = (float)((float)((float)(TICKS_PER_SEC) / video_fps) * (float)(FRAMESKIP_LEVELS)) / (float)(curr - prev_measure); speed = (int)(divdr * 100.0); prev_measure = curr; /* int divdr; divdr = video_fps * (curr - prev_measure) / (100 * FRAMESKIP_LEVELS); if (divdr==0) divdr=1; speed = (TICKS_PER_SEC + divdr/2) / divdr; prev_measure = curr; */ } prev = curr; vfcount += waittable[frameskip][frameskip_counter]; if (vfcount >= video_fps) { extern int vector_updates; /* avgdvg_go_w()'s per Mame frame, should be 1 */ vfcount = 0; vups = vector_updates; vector_updates = 0; } if (global_fps || showfps || showfpstemp) { int fps; char buf[30]; int divdr; divdr = 100 * FRAMESKIP_LEVELS; fps = (video_fps * (FRAMESKIP_LEVELS - frameskip) * speed + (divdr / 2)) / divdr; sprintf(buf,"%s%2d%4d%%%4d/%d fps",autoframeskip?"auto":"fskp",frameskip,speed,fps,(int)(video_fps+0.5)); ui_text(bitmap,buf,Machine->uiwidth-strlen(buf)*Machine->uifontwidth,0); if (vector_game) { sprintf(buf," %d vector updates",vups); ui_text(bitmap,buf,Machine->uiwidth-strlen(buf)*Machine->uifontwidth,Machine->uifontheight); } } if (bitmap->depth == 8) { if (dirty_bright) { dirty_bright = 0; for (i = 0;i < 256;i++) { float rate = brightness * brightness_paused_adjust * pow(i / 255.0, 1 / osd_gamma_correction) / 100; bright_lookup[i] = 255 * rate + 0.5; } } if (dirtypalette) { dirtypalette = 0; for (i = 0;i < screen_colors;i++) { if (dirtycolor[i]) { unsigned char r,g,b; dirtycolor[i] = 0; r = current_palette[3*i+0]; g = current_palette[3*i+1]; b = current_palette[3*i+2]; if (i != Machine->uifont->colortable[1]) /* don't adjust the user interface text */ { r = bright_lookup[r]; g = bright_lookup[g]; b = bright_lookup[b]; } gp2x_video_color8(i,r,g,b); } } gp2x_video_setpalette(); } } else { if (dirty_bright) { dirty_bright = 0; for (i = 0;i < 256;i++) { float rate = brightness * brightness_paused_adjust * pow(i / 255.0, 1 / osd_gamma_correction) / 100; bright_lookup[i] = 255 * rate + 0.5; } } if (dirtypalette) { if (use_dirty) init_dirty(1); /* have to redraw the whole screen */ dirtypalette = 0; for (i = 0;i < screen_colors;i++) { if (dirtycolor[i]) { int r,g,b; dirtycolor[i] = 0; r = current_palette[3*i+0]; g = current_palette[3*i+1]; b = current_palette[3*i+2]; if (i != Machine->uifont->colortable[1]) /* don't adjust the user interface text */ { r = bright_lookup[r]; g = bright_lookup[g]; b = bright_lookup[b]; } palette_16bit_lookup[i] = makecol(r,g,b); } } } } /* copy the bitmap to screen memory */ profiler_mark(PROFILER_BLIT); update_screen(bitmap); profiler_mark(PROFILER_END); if (have_to_clear_bitmap) osd_clearbitmap(bitmap); if (use_dirty) { if (!vector_game) swap_dirty(); init_dirty(0); } if (have_to_clear_bitmap) osd_clearbitmap(bitmap); if (throttle && autoframeskip && frameskip_counter == 0) { static int frameskipadjust/* = 0*/; int adjspeed; /* adjust speed to video refresh rate if vsync is on */ adjspeed = speed * video_fps / vsync_frame_rate; if (adjspeed >= 100 /*92*/) { frameskipadjust++; if (frameskipadjust >= 3) { frameskipadjust = 0; #ifdef GP2X { extern int gp2x_pal_50hz; if ((gp2x_pal_50hz) && (video_fps>50)) { if (frameskip>2) frameskip--; } else if (frameskip > 0) frameskip--; } #else if (frameskip > 0) frameskip--; #endif } } else { if (adjspeed < 80) { frameskipadjust -= (90 - adjspeed) / 5; } else { /* don't push frameskip too far if we are close to 100% speed */ if (frameskip < 8) frameskipadjust--; } while (frameskipadjust <= -2) { frameskipadjust += 2; //#ifdef GP2X // if (frameskip < 7) frameskip++; //#else if (frameskip < FRAMESKIP_LEVELS-1) frameskip++; //#endif } } } } /* Check for PGUP, PGDN and pan screen */ pan_display(); if (input_ui_pressed(IPT_UI_FRAMESKIP_INC)) { if (autoframeskip) { autoframeskip = 0; frameskip = 0; } else { if (frameskip == FRAMESKIP_LEVELS-1) { frameskip = 0; autoframeskip = 1; } else frameskip++; } if (showfps == 0) showfpstemp = 2*video_fps; } if (input_ui_pressed(IPT_UI_FRAMESKIP_DEC)) { if (autoframeskip) { autoframeskip = 0; frameskip = FRAMESKIP_LEVELS-1; } else { if (frameskip == 0) autoframeskip = 1; else frameskip--; } if (showfps == 0) showfpstemp = 2*video_fps; } if (input_ui_pressed(IPT_UI_THROTTLE)) { throttle ^= 1; } frameskip_counter = (frameskip_counter + 1) % FRAMESKIP_LEVELS; } void osd_set_gamma(float _gamma) { int i; osd_gamma_correction = _gamma; for (i = 0;i < screen_colors;i++) dirtycolor[i] = 1; dirtypalette = 1; dirty_bright = 1; } float osd_get_gamma(void) { return osd_gamma_correction; } /* brightess = percentage 0-100% */ void osd_set_brightness(int _brightness) { int i; brightness = _brightness; for (i = 0;i < screen_colors;i++) dirtycolor[i] = 1; dirtypalette = 1; dirty_bright = 1; } int osd_get_brightness(void) { return brightness; } void osd_save_snapshot(struct osd_bitmap *bitmap) { save_screen_snapshot(bitmap); } void osd_pause(int paused) { int i; if (paused) { //app_MuteSound(); brightness_paused_adjust = 0.65; } else { //app_DemuteSound(); brightness_paused_adjust = 1.0; } for (i = 0;i < screen_colors;i++) dirtycolor[i] = 1; dirtypalette = 1; dirty_bright = 1; }
[ [ [ 1, 1282 ] ] ]
e4e953caade9a9e9efd62d375a8a9c13b5097efb
b1093f654e78210a00e6ca561c1a8f8f108f543e
/include/Pointer.h
d8ca42ea56deab964e355bb1434823043ea8be67
[]
no_license
childhood/libAiml
bc82b7cd8859aa6fe0a7a3c42ffe4591438ae329
7954dc347463bcb4ab0070af87b9cbd421b08acc
refs/heads/master
2021-01-18T10:07:02.407246
2010-09-20T04:40:34
2010-09-20T04:40:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,952
h
/** * Pointer - A safer way to use pointers * * @author Jonathan Roewen */ #ifndef POINTER_H #define POINTER_H using namespace std; // Otherwise this becomes a nightmare later if "Pointer.h" included in wrong order! template <class T> class Pointer { protected: class Holder { public: T *datum; unsigned count; Holder(T *t) : datum(t), count(1) { } ~Holder() { delete datum; } }; Holder *value; // I'm just curious .. how does this cope with NULL? void unbind() { if (--value->count == 0) { delete value; } } void bind(const Pointer<T> &rhs) { if (rhs.value != value) { unbind(); value = rhs.value; value->count++; } } void bind(T *t) { if (value->datum != t) { unbind(); value = new Holder(t); } } public: explicit Pointer(T *t = NULL) : value(new Holder(t)) { } Pointer(const Pointer<T> &rhs) : value(rhs.value) { value->count++; } ~Pointer() { unbind(); } Pointer<T> &operator=(const Pointer<T> &rhs) { // Keep getting *bus error* for value->datum // if (value->datum != NULL) { bind(rhs); // } else { // value = rhs.value; // } return *this; } Pointer<T> &operator=(T *t) { // if (t != NULL) { bind(t); // } else { // value = new Holder(t); // } return *this; } T *operator->() { return value->datum; } T &operator*() { return *(value->datum); } const T *operator->() const { return value->datum; } const T &operator*() const { return *(value->datum); } bool operator==(const Pointer<T> &rhs) const { return (value->datum) == (rhs.value->datum); } bool operator!=(const Pointer<T> &rhs) const { return (value->datum) != (rhs.value->datum); } bool operator==(T *t) const { return (value->datum) == t; } bool operator!=(T *t) const { return (value->datum) != t; } }; #endif
[ [ [ 1, 113 ] ] ]
fc1ce5e415193600fd1aa185d81bc3c8ab7b75f1
36bf908bb8423598bda91bd63c4bcbc02db67a9d
/Library/CProgressCtrlEx.cpp
290283efd99a14d917e35ddc37385d46d70b4fc8
[]
no_license
code4bones/crawlpaper
edbae18a8b099814a1eed5453607a2d66142b496
f218be1947a9791b2438b438362bc66c0a505f99
refs/heads/master
2021-01-10T13:11:23.176481
2011-04-14T11:04:17
2011-04-14T11:04:17
44,686,513
0
1
null
null
null
null
UTF-8
C++
false
false
8,117
cpp
/* CProgressCtrlEx.cpp Classe per la progress bar dentro la status bar del dialogo (MFC). Luca Piergentili, 10/04/11 [email protected] Codice originale da: ProgressBar.h Drop-in status bar progress control Written by Chris Maunder ([email protected]) Copyright (c) 1998. This code may be used in compiled form in any way you desire. This file may be redistributed unmodified by any means PROVIDING it is not sold for profit without the authors written consent, and providing that this notice and the authors name is included. If the source code in this file is used in any commercial application then an email to me would be nice. */ #include "env.h" #include "pragma.h" #include "macro.h" #include "window.h" #include "CDialogEx.h" #include "CProgressCtrlEx.h" #include "traceexpr.h" //#define _TRACE_FLAG _TRFLAG_TRACEOUTPUT //#define _TRACE_FLAG _TRFLAG_NOTRACE #define _TRACE_FLAG _TRFLAG_NOTRACE #define _TRACE_FLAG_INFO _TRFLAG_NOTRACE #define _TRACE_FLAG_WARN _TRFLAG_NOTRACE #define _TRACE_FLAG_ERR _TRFLAG_NOTRACE #if (defined(_DEBUG) && defined(_WINDOWS)) && (defined(_AFX) || defined(_AFXDLL)) #ifdef PRAGMA_MESSAGE_VERBOSE #pragma message("\t\t\t"__FILE__"("STR(__LINE__)"): using DEBUG_NEW macro") #endif #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif BEGIN_MESSAGE_MAP(CProgressCtrlEx,CProgressCtrl) ON_WM_ERASEBKGND() END_MESSAGE_MAP() IMPLEMENT_DYNCREATE(CProgressCtrlEx,CProgressCtrl) CProgressCtrlEx::CProgressCtrlEx() : m_pStatusBar(NULL) { m_Rect.SetRect(0,0,0,0); } CProgressCtrlEx::CProgressCtrlEx( LPCTSTR strMessage, int nSize /*=100*/, int MaxValue /*=100*/, BOOL bSmooth /*=FALSE*/, int nPane /*=0*/, CStatusBarCtrlEx* pBar /*=NULL*/) : m_pStatusBar(pBar) { Create(strMessage,nSize,MaxValue,bSmooth,nPane); } CProgressCtrlEx::~CProgressCtrlEx() { Clear(); } CStatusBarCtrlEx* CProgressCtrlEx::GetStatusBar(void) { if(m_pStatusBar) { return(m_pStatusBar); } else { CWnd *pMainWnd = AfxGetMainWnd(); if(!pMainWnd) return(NULL); if(pMainWnd->IsKindOf(RUNTIME_CLASS(CDialogEx))) { CWnd* pMessageBar = ((CDialogEx*)pMainWnd)->GetMessageBar(); return(DYNAMIC_DOWNCAST(CStatusBarCtrlEx,pMessageBar)); } /* else if(pMainWnd->IsKindOf(RUNTIME_CLASS(CFrameWnd))) { CWnd* pMessageBar = ((CFrameWnd*)pMainWnd)->GetMessageBar(); return(DYNAMIC_DOWNCAST(CStatusBarCtrlEx,pMessageBar)); } else */ return(DYNAMIC_DOWNCAST(CStatusBarCtrlEx,pMainWnd->GetDescendantWindow(AFX_IDW_STATUS_BAR))); } } BOOL CProgressCtrlEx::Create( LPCTSTR strMessage, int nSize /*=100*/, int MaxValue /*=100*/, BOOL bSmooth /*=FALSE*/, int nPane /*=0*/) { BOOL bSuccess = FALSE; CStatusBarCtrlEx *pStatusBar = GetStatusBar(); if(!pStatusBar) return(FALSE); DWORD dwStyle = WS_CHILD|WS_VISIBLE; #ifdef PBS_SMOOTH if(bSmooth) dwStyle |= PBS_SMOOTH; #endif // Until m_nPane is initialized, Resize() must not be called. But it can be called (which // happens in multi-threaded programs) in CProgressCtrlEx::OnEraseBkgnd after the control is // created in CProgressCtrlEx::Create. m_strMessage = strMessage; m_nSize = nSize; m_nPane = nPane; m_strPrevText = pStatusBar->GetText(m_nPane); // Create the progress bar CRect PaneRect(0,0,0,0); bSuccess = CProgressCtrl::Create(dwStyle,PaneRect,pStatusBar,1); if(!bSuccess) return(FALSE); SetRange(0,MaxValue); SetStep(1); m_strMessage = strMessage; m_nSize = nSize; m_nPane = nPane; m_strPrevText = pStatusBar->GetText(m_nPane); // Resize the control to its desired width Resize(); return(TRUE); } void CProgressCtrlEx::Clear(void) { if(!IsWindow(GetSafeHwnd())) return; // Hide the window. This is necessary so that a cleared window is not redrawn if "Resize" is called ModifyStyle(WS_VISIBLE,0); CString str; if(m_nPane==0) str.LoadString(AFX_IDS_IDLEMESSAGE); // Get the IDLE_MESSAGE else str = m_strPrevText; // Restore previous text // Place the IDLE_MESSAGE in the status bar CStatusBarCtrlEx *pStatusBar = GetStatusBar(); if(pStatusBar) { pStatusBar->SetPanel(str,m_nPane); pStatusBar->UpdateWindow(); } } BOOL CProgressCtrlEx::SetText(LPCTSTR strMessage) { m_strMessage = strMessage; return(Resize()); } BOOL CProgressCtrlEx::SetSize(int nSize) { m_nSize = nSize; return(Resize()); } COLORREF CProgressCtrlEx::SetBarColour(COLORREF clrBar) { #ifdef PBM_SETBKCOLOR if(!IsWindow(GetSafeHwnd())) return CLR_DEFAULT; return SendMessage(PBM_SETBARCOLOR,0,(LPARAM)clrBar); #else UNUSED(clrBar); return CLR_DEFAULT; #endif } COLORREF CProgressCtrlEx::SetBkColour(COLORREF clrBk) { #ifdef PBM_SETBKCOLOR if(!IsWindow(GetSafeHwnd())) return CLR_DEFAULT; return SendMessage(PBM_SETBKCOLOR,0,(LPARAM)clrBk); #else UNUSED(clrBk); return CLR_DEFAULT; #endif } BOOL CProgressCtrlEx::SetRange(int nLower,int nUpper,int nStep/* = 1 */) { if(!IsWindow(GetSafeHwnd())) return FALSE; // To take advantage of the Extended Range Values we use the PBM_SETRANGE32 // message intead of calling CProgressCtrl::SetRange directly. If this is // being compiled under something less than VC 5.0, the necessary defines // may not be available. #ifdef PBM_SETRANGE32 ASSERT(-0x7FFFFFFF <= nLower && nLower <= 0x7FFFFFFF); ASSERT(-0x7FFFFFFF <= nUpper && nUpper <= 0x7FFFFFFF); SendMessage(PBM_SETRANGE32,(WPARAM)nLower,(LPARAM)nUpper); #else ASSERT(0 <= nLower && nLower <= 65535); ASSERT(0 <= nUpper && nUpper <= 65535); CProgressCtrl::SetRange(nLower, nUpper); #endif CProgressCtrl::SetStep(nStep); return TRUE; } int CProgressCtrlEx::SetPos(int nPos) { if(!IsWindow(GetSafeHwnd())) return 0; #ifdef PBM_SETRANGE32 ASSERT(-0x7FFFFFFF <= nPos && nPos <= 0x7FFFFFFF); #else ASSERT(0 <= nPos && nPos <= 65535); #endif ModifyStyle(0,WS_VISIBLE); return CProgressCtrl::SetPos(nPos); } int CProgressCtrlEx::OffsetPos(int nPos) { if(!IsWindow(GetSafeHwnd())) return 0; ModifyStyle(0,WS_VISIBLE); return CProgressCtrl::OffsetPos(nPos); } int CProgressCtrlEx::SetStep(int nStep) { if(!IsWindow(GetSafeHwnd())) return 0; ModifyStyle(0,WS_VISIBLE); return CProgressCtrl::SetStep(nStep); } int CProgressCtrlEx::StepIt() { if(!IsWindow(GetSafeHwnd())) return 0; ModifyStyle(0,WS_VISIBLE); return CProgressCtrl::StepIt(); } BOOL CProgressCtrlEx::Resize() { if(!IsWindow(GetSafeHwnd())) return FALSE; CStatusBarCtrlEx *pStatusBar = GetStatusBar(); if (!pStatusBar) return FALSE; // Redraw the window text if(IsWindowVisible()) { pStatusBar->SetPanel(m_strMessage,m_nPane); pStatusBar->UpdateWindow(); } // Calculate how much space the text takes up CClientDC dc(pStatusBar); CFont *pOldFont = dc.SelectObject(pStatusBar->GetFont()); CSize size = dc.GetTextExtent(m_strMessage); // Length of text int margin = dc.GetTextExtent(_T(" ")).cx * 2; // Text margin dc.SelectObject(pOldFont); // Now calculate the rectangle in which we will draw the progress bar CRect rc; pStatusBar->GetRect(m_nPane,rc); // Position left of progress bar after text and right of progress bar // to requested percentage of status bar pane if(!m_strMessage.IsEmpty()) rc.left += (size.cx + 2*margin); rc.right -= (rc.right - rc.left) * (100 - m_nSize) / 100; if(rc.right < rc.left) rc.right = rc.left; // Leave a litle vertical margin (10%) between the top and bottom of the bar int Height = rc.bottom - rc.top; rc.bottom -= Height/10; rc.top += Height/10; // If the window size has changed, resize the window if(rc != m_Rect) { MoveWindow(&rc); m_Rect = rc; } return TRUE; } BOOL CProgressCtrlEx::OnEraseBkgnd(CDC* pDC) { Resize(); return CProgressCtrl::OnEraseBkgnd(pDC); }
[ [ [ 1, 325 ] ] ]
d48793bb539560c0bd7308ae1b30f43b84f7dbac
a4bb94cfe9c0bee937a6ec584e10f6fe126372ff
/Include/cmos.h
d6d25583ab0c1181d85ddd956f904e4c3dfaaa51
[]
no_license
MatiasNAmendola/magneto
564d0bdb3534d4b7118e74cc8b50601afaad10a0
33bc34a49a34923908883775f94eb266be5af0f9
refs/heads/master
2020-04-05T23:36:22.535156
2009-07-04T09:14:01
2009-07-04T09:14:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,620
h
#include "iostream.h" #include "x86.h" #include "kore\kmsgs.h" #if !defined ( __CMOS_H_ ) #define __CMOS_H_ typedef struct cmos_s{ unsigned char seconds; /* 0x00*/ /* Seconds */ unsigned char seconds_alarm; /* 0x01*/ /* Seconds (alarm) */ unsigned char minutes; /* 0x02 */ /* Minutes */ unsigned char minutes_alarm; /* 0x03 */ /* Minutes (alarm) */ unsigned char hours; /* 0x04 */ /* Hours */ unsigned char hours_alarm; /* 0x05 */ /* Hours (alarm) */ unsigned char day_of_week; /* 0x06 */ /* Day of week */ unsigned char day_of_month; /* 0x07 */ /* Day of month */ unsigned char month; /* 0x08 */ /* Month */ unsigned char year; /* 0x09 */ /* Year */ unsigned char a; /* 0x0a*/ /* Status register A */ unsigned char b; /* 0x0b */ /* Status register B */ unsigned char c; /* 0x0c */ /* Status register C */ unsigned char d; /* 0x0d */ /* Status register D */ unsigned char diagnosis; /* 0x0e */ /* Diagnosis register */ unsigned char shutdown; /* 0x0f */ /* Shutdown status */ unsigned char floppy; /* 0x10 */ /* Floppy types */ unsigned char reserved0; /* 0x11 */ /* Reserved */ unsigned char harddisk; /* 0x12 */ /* Hard drive types */ unsigned char reserved1; /* 0x13 */ /* Reserved */ unsigned char device; /* 0x14 */ /* Device byte */ unsigned int base_mem; /* 0x15 - 0x16 */ /* Base memory */ unsigned int ext_mem; /* 0x17 - 0x18*/ /* Extended memory */ unsigned char hdd1_ext; /* 0x19 */ /* Extension for first HDD */ unsigned char hdd2_ext; /* 0x1a */ /* Extension for second HDD */ unsigned char reserved2[5]; /* 0x1b - 0x1f */ /* Reserved */ unsigned char hdd1_param[8]; /* 0x20 - 0x27 */ /* HDD one parameters */ unsigned char reserved3[6]; /* 0x28 - 0x2d */ /* Reserved */ unsigned int checksum; /* 0x2e - 0x2f */ /* Checksum */ unsigned int post_ext_mem; /* 0x30 - 0x31 */ /* Post extended memory */ unsigned char century; /* 0x32 */ /* Century */ unsigned int setup_info; /* 0x33 - 0x34*/ /* Setup Information */ unsigned char hdd2_param[8]; /* 0x35 */ /* HDD two parameters */ unsigned char reserved4[3]; /* 0x3d - 0x3f */ /* Reserved */ }__attribute__((packed)) cmos_t; typedef struct cmos_clock_s{ unsigned int seconds; /* 0x00*/ /* Seconds */ unsigned int minutes; /* 0x02 */ /* Minutes */ unsigned int hours; /* 0x04 */ /* Hours */ unsigned int day_of_week; /* 0x06 */ /* Day of week */ unsigned int day_of_month; /* 0x07 */ /* Day of month */ unsigned int month; /* 0x08 */ /* Month */ unsigned int year; /* 0x09 */ /* Year */ }__attribute__((packed)) cmos_clock_t; extern cmos_t cmos_info; extern cmos_clock_t cmos_clock; class CMOS { private: #define CMOS_PORT 0x70 #define CMOS_DATA 0x71 #define RTC_SEC 0x00 #define RTC_MIN 0x02 #define RTC_HOUR 0x04 #define RTC_DAYMON 0x07 #define RTC_MONTH 0x08 #define RTC_YEAR 0x09 #define RTC_STATUS 11 #define CMOS_BASEMEM1 0x15 #define CMOS_BASEMEM2 0x16 #define CMOS_EXTMEM1 0x17 #define CMOS_EXTMEM2 0x18 #define CMOS_FLOPPY 0x10 unsigned int decode_rtc_data(unsigned char); unsigned char read_cmos(); void send_cmos(unsigned char); void read_cmos_mem(void); void read_cmos_data(void); void read_cmos_clock(void); void read_cmos_floppy(void); public: CMOS(); ~CMOS(); int init(void); void disp_cmos_info(void); void disp_cmos_date(void); void disp_cmos_time(void); void disp_cmos_floppy(void); }; extern CMOS cmos; #endif
[ [ [ 1, 99 ] ] ]
ab80b94583959d6aad68908c6267ff4c9eed5d04
772690258e7a85244cc871d744bf54fc4e887840
/ms22vv/Castle Defence Ogre3d/Castle Defence Ogre3d/View/Sound/SoundManager.cpp
84aa1bb63d5234e171390430f58645833e0ad74f
[]
no_license
Argos86/dt2370
f735d21517ab55de19cea933b467f46837bb6401
4a393a3c83deb3cb6df90b36a9c59e2e543917ee
refs/heads/master
2021-01-13T00:53:43.286445
2010-02-01T07:43:50
2010-02-01T07:43:50
36,057,264
0
0
null
null
null
null
ISO-8859-15
C++
false
false
18,367
cpp
#include "SoundManager.h" #include <FMOD/fmod_errors.h> #include <Ogre.h> #define INITIAL_VECTOR_SIZE 100 #define INCREASE_VECTOR_SIZE 20 #define DOPPLER_SCALE 1.0 #define DISTANCE_FACTOR 1.0 #define ROLLOFF_SCALE 0.5 //---------------------- Allt kopierat från: http://www.ogre3d.org/wiki/index.php/File_SoundManager.cpp using namespace Ogre; template<> SoundManager* Ogre::Singleton<SoundManager>::ms_Singleton = 0; void SoundInstance::Clear(void) { fileName.clear(); streamPtr.setNull(); fileArchive = NULL; fmodSound = NULL; soundType = SOUND_TYPE_INVALID; } void ChannelInstance::Clear(void) { sceneNode = NULL; prevPosition = Ogre::Vector3(0, 0, 0); } class FileLocator : public Ogre::ResourceGroupManager { public: FileLocator() {} ~FileLocator() {} Ogre::Archive *Find(Ogre::String &filename) { ResourceGroup* grp = getResourceGroup("General"); if (!grp) OGRE_EXCEPT(Ogre::Exception::ERR_ITEM_NOT_FOUND, "Cannot locate a resource group called 'General'", "ResourceGroupManager::openResource"); OGRE_LOCK_MUTEX(grp->OGRE_AUTO_MUTEX_NAME) // lock group mutex ResourceLocationIndex::iterator rit = grp->resourceIndexCaseSensitive.find(filename); if (rit != grp->resourceIndexCaseSensitive.end()) { // Found in the index Ogre::Archive *fileArchive = rit->second; filename = fileArchive->getName() + "/" + filename; return fileArchive; } return NULL; } }; SoundManager::SoundManager() { system = NULL; prevListenerPosition = Ogre::Vector3(0, 0, 0); soundInstanceVector = new SoundInstanceVector; // Initialized to zero, but pre-incremented in GetNextSoundInstanceIndex(), so vector starts at one. nextSoundInstanceIndex = 0; // Start off with INITIAL_VECTOR_SIZE soundInstanceVectors. It can grow from here. soundInstanceVector->resize(INITIAL_VECTOR_SIZE); for (int vectorIndex = 0; vectorIndex < INITIAL_VECTOR_SIZE; vectorIndex++) { soundInstanceVector->at(vectorIndex) = new SoundInstance; soundInstanceVector->at(vectorIndex)->Clear(); } for (int channelIndex = 0; channelIndex < MAX_SOUND_CHANNELS; channelIndex++) channelArray[channelIndex].Clear(); } SoundManager::~SoundManager() { for (int vectorIndex = 0; vectorIndex < (int)soundInstanceVector->capacity(); vectorIndex++) { soundInstanceVector->at(vectorIndex)->fileName.clear(); // soundInstanceVector->at(vectorIndex)->streamPtr->close(); delete soundInstanceVector->at(vectorIndex); } delete soundInstanceVector; if (system) system->release(); } void SoundManager::Initialize(void) { FMOD_RESULT result; // Create the main system object. result = FMOD::System_Create(&system); if (result != FMOD_OK) OGRE_EXCEPT(Ogre::Exception::ERR_INTERNAL_ERROR, "FMOD error! (" + Ogre::StringConverter::toString(result) + "): " + FMOD_ErrorString(result), "SoundManager::Initialize"); result = system->init(MAX_SOUND_CHANNELS, FMOD_INIT_NORMAL, 0); // Initialize FMOD. if (result != FMOD_OK) OGRE_EXCEPT(Ogre::Exception::ERR_INTERNAL_ERROR, "FMOD error! (" + Ogre::StringConverter::toString(result) + "): " + FMOD_ErrorString(result), "SoundManager::Initialize"); system->set3DSettings(DOPPLER_SCALE, DISTANCE_FACTOR, ROLLOFF_SCALE); result = system->setFileSystem(&fmodFileOpenCallback, &fmodFileCloseCallback, &fmodFileReadCallback, &fmodFileSeekCallback, 2048); if (result != FMOD_OK) OGRE_EXCEPT(Ogre::Exception::ERR_INTERNAL_ERROR, "FMOD error! (" + Ogre::StringConverter::toString(result) + "): " + FMOD_ErrorString(result), "SoundManager::Initialize"); Ogre::LogManager::getSingleton().logMessage("SoundManager Initialized"); } SoundManager* SoundManager::getSingletonPtr(void) { return ms_Singleton; } SoundManager& SoundManager::getSingleton(void) { assert( ms_Singleton ); return ( *ms_Singleton ); } void SoundManager::FrameStarted(Ogre::SceneNode *listenerNode, Ogre::Real timeElapsed) { int channelIndex; FMOD::Channel *nextChannel; FMOD_VECTOR listenerPosition; FMOD_VECTOR listenerForward; FMOD_VECTOR listenerUp; FMOD_VECTOR listenerVelocity; Ogre::Vector3 vectorVelocity; Ogre::Vector3 vectorForward; Ogre::Vector3 vectorUp; if (timeElapsed > 0) vectorVelocity = (listenerNode->getPosition() - prevListenerPosition) / timeElapsed; else vectorVelocity = Vector3(0, 0, 0); vectorForward = listenerNode->getOrientation().zAxis(); vectorForward.normalise(); vectorUp = listenerNode->getOrientation().yAxis(); vectorUp.normalise(); listenerPosition.x = listenerNode->getPosition().x; listenerPosition.y = listenerNode->getPosition().y; listenerPosition.z = listenerNode->getPosition().z; listenerForward.x = vectorForward.x; listenerForward.y = vectorForward.y; listenerForward.z = vectorForward.z; listenerUp.x = vectorUp.x; listenerUp.y = vectorUp.y; listenerUp.z = vectorUp.z; listenerVelocity.x = vectorVelocity.x; listenerVelocity.y = vectorVelocity.y; listenerVelocity.z = vectorVelocity.z; // update 'ears' system->set3DListenerAttributes(0, &listenerPosition, &listenerVelocity, &listenerForward, &listenerUp); system->update(); prevListenerPosition = listenerNode->getPosition(); for (channelIndex = 0; channelIndex < MAX_SOUND_CHANNELS; channelIndex++) { if (channelArray[channelIndex].sceneNode != NULL) { system->getChannel(channelIndex, &nextChannel); if (timeElapsed > 0) vectorVelocity = (channelArray[channelIndex].sceneNode->getPosition() - channelArray[channelIndex].prevPosition) / timeElapsed; else vectorVelocity = Vector3(0, 0, 0); listenerPosition.x = channelArray[channelIndex].sceneNode->getPosition().x; listenerPosition.y = channelArray[channelIndex].sceneNode->getPosition().y; listenerPosition.z = channelArray[channelIndex].sceneNode->getPosition().z; listenerVelocity.x = vectorVelocity.x; listenerVelocity.y = vectorVelocity.y; listenerVelocity.z = vectorVelocity.z; nextChannel->set3DAttributes(&listenerPosition, &listenerVelocity); channelArray[channelIndex].prevPosition = channelArray[channelIndex].sceneNode->getPosition(); } } } int SoundManager::CreateStream(String &fileName) { return CreateSound(fileName, SOUND_TYPE_2D_SOUND); } int SoundManager::CreateSound(String &fileName) { return CreateSound(fileName, SOUND_TYPE_3D_SOUND); } int SoundManager::CreateLoopedSound(String &fileName) { return CreateSound(fileName, SOUND_TYPE_3D_SOUND_LOOPED); } int SoundManager::CreateLoopedStream(String &fileName) { return CreateSound(fileName, SOUND_TYPE_2D_SOUND_LOOPED); } // fileName is actually a pointer to a SoundInstance, passed in from CreateSound(). FMOD_RESULT SoundManager::fmodFileOpenCallback(const char *fileName, int unicode, unsigned int *filesize, void **handle, void **userdata) { SoundInstance *soundInstance; assert(fileName); soundInstance = (SoundInstance *)fileName; assert(soundInstance->fileArchive); *handle = (void *)soundInstance; *userdata = NULL; soundInstance->streamPtr = soundInstance->fileArchive->open(soundInstance->fileName); if (soundInstance->streamPtr.isNull()) { *filesize = 0; return FMOD_ERR_FILE_NOTFOUND; } *filesize = (unsigned int)soundInstance->streamPtr->size(); return FMOD_OK; } FMOD_RESULT SoundManager::fmodFileCloseCallback(void *handle, void *userdata) { return FMOD_OK; } FMOD_RESULT SoundManager::fmodFileReadCallback(void *handle, void *buffer, unsigned int sizeBytes, unsigned int *bytesRead, void *userData) { SoundInstance *soundInstance; soundInstance = (SoundInstance *)handle; *bytesRead = (unsigned int)soundInstance->streamPtr->read(buffer, (size_t)sizeBytes); if (*bytesRead == 0) return FMOD_ERR_FILE_EOF; return FMOD_OK; } FMOD_RESULT SoundManager::fmodFileSeekCallback(void *handle, unsigned int pos, void *userdata) { SoundInstance *soundInstance; soundInstance = (SoundInstance *)handle; soundInstance->streamPtr->seek((size_t)pos); return FMOD_OK; } int SoundManager::CreateSound(String &fileName, SOUND_TYPE soundType) { Archive * fileArchive; FMOD_RESULT result; FMOD::Sound * sound; String fullPathName; SoundInstance *newSoundInstance; int soundIndex; soundIndex = FindSound(fileName, soundType); if (soundIndex != INVALID_SOUND_INDEX) return soundIndex; fullPathName = fileName; FileLocator * fileLocator = (FileLocator * )ResourceGroupManager::getSingletonPtr(); fileArchive = fileLocator->Find(fullPathName); if (!fileArchive) { Ogre::LogManager::getSingleton().logMessage("SoundManager::CreateSound could not find sound '" + fileName + "'"); return INVALID_SOUND_INDEX; } IncrementNextSoundInstanceIndex(); newSoundInstance = soundInstanceVector->at(nextSoundInstanceIndex); newSoundInstance->fileName = fileName; newSoundInstance->fileArchive = fileArchive; newSoundInstance->soundType = soundType; switch (soundType) { case SOUND_TYPE_3D_SOUND: { result = system->createSound((const char *)newSoundInstance, FMOD_3D | FMOD_HARDWARE, 0, &sound); break; } case SOUND_TYPE_3D_SOUND_LOOPED: { result = system->createSound((const char *)newSoundInstance, FMOD_LOOP_NORMAL | FMOD_3D | FMOD_HARDWARE, 0, &sound); break; } case SOUND_TYPE_2D_SOUND: { result = system->createStream((const char *)newSoundInstance, FMOD_DEFAULT, 0, &sound); break; } case SOUND_TYPE_2D_SOUND_LOOPED: { result = system->createStream((const char *)newSoundInstance, FMOD_LOOP_NORMAL | FMOD_2D | FMOD_HARDWARE, 0, &sound); break; } default: { Ogre::LogManager::getSingleton().logMessage("SoundManager::CreateSound could not load sound '" + fileName + "' (invalid soundType)"); return INVALID_SOUND_INDEX; } } if (result != FMOD_OK) { Ogre::LogManager::getSingleton().logMessage("SoundManager::CreateSound could not load sound '" + fileName + "' FMOD Error:" + FMOD_ErrorString(result)); return INVALID_SOUND_INDEX; } newSoundInstance->fmodSound = sound; return nextSoundInstanceIndex; } void SoundManager::IncrementNextSoundInstanceIndex(void) { int oldVectorCapacity; oldVectorCapacity = (int)soundInstanceVector->capacity(); nextSoundInstanceIndex += 1; if (nextSoundInstanceIndex < oldVectorCapacity) return; int vectorIndex; SoundInstanceVector *newSoundInstanceVector; // Create a new, larger SoundInstanceVector newSoundInstanceVector = new SoundInstanceVector; newSoundInstanceVector->resize(oldVectorCapacity + INCREASE_VECTOR_SIZE); // Check Ogre.log for these messages, and change INITIAL_VECTOR_SIZE to be a more appropriate value Ogre::LogManager::getSingleton().logMessage("SoundManager::IncrementNextSoundInstanceIndex increasing size of soundInstanceVector to " + StringConverter::toString(oldVectorCapacity + INCREASE_VECTOR_SIZE)); // Copy values from old vector to new for (vectorIndex = 0; vectorIndex < oldVectorCapacity; vectorIndex++) newSoundInstanceVector->at(vectorIndex) = soundInstanceVector->at(vectorIndex); int newVectorCapacity; newVectorCapacity = (int)newSoundInstanceVector->capacity(); // Clear out the rest of the new vector while (vectorIndex < newVectorCapacity) { newSoundInstanceVector->at(vectorIndex) = new SoundInstance; newSoundInstanceVector->at(vectorIndex)->Clear(); vectorIndex++; } // Clear out the old vector and point to the new one. soundInstanceVector->clear(); delete(soundInstanceVector); soundInstanceVector = newSoundInstanceVector; } void SoundManager::PlaySound(int soundIndex, SceneNode *soundNode, int *channelIndex) { int channelIndexTemp; FMOD_RESULT result; FMOD_VECTOR initialPosition; FMOD::Channel *channel; SoundInstance *soundInstance; if (soundIndex == INVALID_SOUND_INDEX) return; if (channelIndex) channelIndexTemp = *channelIndex; else channelIndexTemp = INVALID_SOUND_CHANNEL; assert((soundIndex > 0) && (soundIndex < (int)soundInstanceVector->capacity())); // If the channelIndex already has a sound assigned to it, test if it's the same sceneNode. if ((channelIndexTemp != INVALID_SOUND_CHANNEL) && (channelArray[channelIndexTemp].sceneNode != NULL)) { result = system->getChannel(channelIndexTemp, &channel); if (result == FMOD_OK) { bool isPlaying; result = channel->isPlaying(&isPlaying); if ((result == FMOD_OK) && (isPlaying == true) && (channelArray[channelIndexTemp].sceneNode == soundNode)) return; // Already playing this sound attached to this node. } } soundInstance = soundInstanceVector->at(soundIndex); // Start the sound paused result = system->playSound(FMOD_CHANNEL_FREE, soundInstance->fmodSound, true, &channel); if (result != FMOD_OK) { Ogre::LogManager::getSingleton().logMessage(String("SoundManager::PlaySound could not play sound FMOD Error:") + FMOD_ErrorString(result)); if (channelIndex) *channelIndex = INVALID_SOUND_CHANNEL; return; } channel->getIndex(&channelIndexTemp); channelArray[channelIndexTemp].sceneNode = soundNode; if (soundNode) { channelArray[channelIndexTemp].prevPosition = soundNode->getPosition(); initialPosition.x = soundNode->getPosition().x; initialPosition.y = soundNode->getPosition().y; initialPosition.z = soundNode->getPosition().z; channel->set3DAttributes(&initialPosition, NULL); } result = channel->setVolume(1.0); // This is where the sound really starts. result = channel->setPaused(false); if (channelIndex) *channelIndex = channelIndexTemp; } SoundInstance *SoundManager::GetSoundInstance(int soundIndex) { return soundInstanceVector->at(soundIndex); } FMOD::Channel *SoundManager::GetSoundChannel(int channelIndex) { if (channelIndex == INVALID_SOUND_CHANNEL) return NULL; FMOD::Channel *soundChannel; assert((channelIndex > 0) && (channelIndex < MAX_SOUND_CHANNELS)); system->getChannel(channelIndex, &soundChannel); return soundChannel; } void SoundManager::Set3DMinMaxDistance(int channelIndex, float minDistance, float maxDistance) { FMOD_RESULT result; FMOD::Channel *channel; if (channelIndex == INVALID_SOUND_CHANNEL) return; result = system->getChannel(channelIndex, &channel); if (result == FMOD_OK) channel->set3DMinMaxDistance(minDistance, maxDistance); } void SoundManager::StopAllSounds(void) { int channelIndex; FMOD_RESULT result; FMOD::Channel *nextChannel; for (channelIndex = 0; channelIndex < MAX_SOUND_CHANNELS; channelIndex++) { result = system->getChannel(channelIndex, &nextChannel); if ((result == FMOD_OK) && (nextChannel != NULL)) nextChannel->stop(); channelArray[channelIndex].Clear(); } } void SoundManager::StopSound(int *channelIndex) { if (*channelIndex == INVALID_SOUND_CHANNEL) return; FMOD::Channel *soundChannel; assert((*channelIndex > 0) && (*channelIndex < MAX_SOUND_CHANNELS)); system->getChannel(*channelIndex, &soundChannel); soundChannel->stop(); channelArray[*channelIndex].Clear(); *channelIndex = INVALID_SOUND_CHANNEL; } int SoundManager::FindSound(String &fileName, SOUND_TYPE soundType) { int vectorIndex; int vectorCapacity; SoundInstance *nextSoundInstance; vectorCapacity = (int)soundInstanceVector->capacity(); for (vectorIndex = 0; vectorIndex < vectorCapacity; vectorIndex++) { nextSoundInstance = soundInstanceVector->at(vectorIndex); if ((soundType == nextSoundInstance->soundType) && (fileName == nextSoundInstance->fileName)) // if ((soundType == nextSoundInstance->soundType) && (fileName == nextSoundInstance->fileArchive->getName())) return vectorIndex; } return INVALID_SOUND_INDEX; } float SoundManager::GetSoundLength(int soundIndex) { if (soundIndex == INVALID_SOUND_INDEX) return 0.0; assert((soundIndex > 0) && (soundIndex < (int)soundInstanceVector->capacity())); unsigned int soundLength; // length in milliseconds FMOD_RESULT result; SoundInstance *soundInstance; soundInstance = soundInstanceVector->at(soundIndex); if (soundInstance) { result = soundInstance->fmodSound->getLength(&soundLength, FMOD_TIMEUNIT_MS); if (result != FMOD_OK) { Ogre::LogManager::getSingleton().logMessage(String("SoundManager::GetSoundLength could not get length FMOD Error:") + FMOD_ErrorString(result)); return 0.0; } } else { Ogre::LogManager::getSingleton().logMessage(String("SoundManager::GetSoundLength could not find soundInstance")); return 0.0; } return (float)soundLength / 1000.0f; }
[ "[email protected]@3422cff2-cdd9-11de-91bf-0503b81643b9" ]
[ [ [ 1, 581 ] ] ]
00429ac6af863935d754090c9f129c517ec1797c
b09a4d24f49daac145a26c4e6b0dbd7749fb202b
/development/FileKeeper/Util/HashSHA1Impl.cpp
d1ea561a66fd1676b0e0a1ff63da233c552497a9
[]
no_license
buf1024/filekeeper
e4d6ead1413fa5c41e66f95d5a5df2b21f211b9f
cb52a3cb417a73535177658d7f83bf71c778a590
refs/heads/master
2021-01-10T12:55:16.930778
2010-12-23T15:10:26
2010-12-23T15:10:26
49,615,444
1
0
null
null
null
null
UTF-8
C++
false
false
2,171
cpp
//============================================================================= /** * @file HashSHA1Impl.cpp * @brief The SHA1 implementation * @author heidong * @version 1.0 * @date 2010-11-13 15:20:12 */ //============================================================================= #include "StdAfx.h" #include "HashSHA1Impl.h" using namespace lgc; HashSHA1Impl::HashSHA1Impl(void) { } HashSHA1Impl::~HashSHA1Impl(void) { } Std_String HashSHA1Impl::GetStringHash(std::string strValue) { Reset(); int nLen = strValue.size(); const unsigned char* pBuf = (const unsigned char*)strValue.data(); Input(pBuf, nLen); unsigned int digest[5] = {0}; Result(digest); TCHAR szRes[48] = _T(""); _sntprintf_s(szRes, 48, 48, _T("%x%x%x%x%x"), digest[0], digest[1], digest[2], digest[3], digest[4]); return szRes; } Std_String HashSHA1Impl::GetStringHash(std::wstring strValue) { Reset(); int nLen = strValue.size() * sizeof(wchar_t); const unsigned char* pBuf = (const unsigned char*)strValue.data(); Input(pBuf, nLen); unsigned int digest[5] = {0}; Result(digest); TCHAR szRes[48] = _T(""); _sntprintf_s(szRes, 48, 48, _T("%x%x%x%x%x"), digest[0], digest[1], digest[2], digest[3], digest[4]); return szRes; } Std_String HashSHA1Impl::GetFileHash(Std_String strFile) { Std_String strRet; HANDLE hFile = CreateFile(strFile.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile != INVALID_HANDLE_VALUE) { HANDLE hMapping = CreateFileMapping(hFile, NULL, PAGE_WRITECOPY, 0, 0, NULL); if (hMapping != INVALID_HANDLE_VALUE) { PBYTE pByte = (PBYTE)MapViewOfFile(hMapping, FILE_MAP_COPY, 0, 0, 0); DWORD dwSize = GetFileSize(hFile, NULL); Reset(); Input(pByte, dwSize); unsigned int digest[5] = {0}; Result(digest); TCHAR szRes[48] = _T(""); _sntprintf_s(szRes, 48, 48, _T("%x%x%x%x%x"), digest[0], digest[1], digest[2], digest[3], digest[4]); strRet = szRes; UnmapViewOfFile(pByte); CloseHandle(hMapping); } else { CloseHandle(hFile); } } return strRet; }
[ "buf1024@9b6b46d4-6a51-a6c0-14c6-10956b729e0f" ]
[ [ [ 1, 82 ] ] ]
795ad49b2597f42cffecf5557821ea0bbeaabbc5
823afcea9ac0705f6262ccffdff65d687822fe93
/RayTracing/Src/SceneLoader.h
1b2a65b5283c28b7854a2e84253ea3ce5d9d7014
[]
no_license
shourav9884/raytracing99999
02b405759edf7eb5021496f87af8fa8157e972be
19c5e3a236dc1356f6b4ec38efcc05827acb9e04
refs/heads/master
2016-09-10T03:30:54.820034
2006-10-15T21:49:19
2006-10-15T21:49:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
226
h
#pragma once #include "RayTracer.h" #include "Scene.h" #include "AppRoot.h" #include "Vector3D.h" class SceneLoader { public: static void loadScene( AppRoot &aApproot, RayTracer &aRayTracer, Scene &aScene ); };
[ "saulopessoa@34b68867-b01b-0410-ab61-0f167d00cb52" ]
[ [ [ 1, 12 ] ] ]
5aa99f6c90ec4adb01e1324f1d14e21f76b87666
c70941413b8f7bf90173533115c148411c868bad
/plugins/SwfPlugin/src/vtxswfScriptParser.cpp
ac95f721d8f6d838468e6ebf84846e48eeb10ab0
[]
no_license
cnsuhao/vektrix
ac6e028dca066aad4f942b8d9eb73665853fbbbe
9b8c5fa7119ff7f3dc80fb05b7cdba335cf02c1a
refs/heads/master
2021-06-23T11:28:34.907098
2011-03-27T17:39:37
2011-03-27T17:39:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,549
cpp
/* ----------------------------------------------------------------------------- This source file is part of "vektrix" (the rich media and vector graphics rendering library) For the latest info, see http://www.fuse-software.com/ Copyright (c) 2009-2010 Fuse-Software (tm) 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 "vtxswfScriptParser.h" #include "vtxswfParser.h" #include "vtxswfScriptResource.h" #include "vtxStringHelper.h" namespace vtx { namespace swf { ////----------------------------------------------------------------------- //void ScriptParser::handleDoABC(const TagTypes& tag_type, const uint& tag_length, SwfParser* parser) //{ // const uint& read_pos = parser->getReadPosition(); // uint start_pos = read_pos; // UI32 flags = parser->readU32(); // String name = parser->readString(); // uint abc_len = tag_length - (read_pos - start_pos); // char* abc_buf = new char[abc_len]; // parser->readByteBlock(abc_buf, abc_len); // parser->getCurrentFile()->addResource(new ScriptResource("Script", abc_buf, abc_len)); // new ExecuteScriptEvent(NULL, ) //} ////----------------------------------------------------------------------- //void ScriptParser::handleSymbolClass(const TagTypes& tag_type, const uint& tag_length, SwfParser* parser) //{ // UI16 num_symbols = parser->readU16(); // for(UI16 i=0; i<num_symbols; ++i) // { // UI16 id = parser->readU16(); // String name = parser->readString(); // if(id == 0) // { // parser->getHeader().script_root_class = name; // } // else // { // SymbolClassResource* symbol_res = NULL; // Resource* res = parser->getCurrentFile()->getResource("__SymbolClassResource__"); // if(!res) // { // symbol_res = new SymbolClassResource(); // parser->getCurrentFile()->addResource(symbol_res); // } // else // { // symbol_res = static_cast<SymbolClassResource*>(res); // } // uint seperator = name.find_last_of('.'); // String class_name, package; // if(seperator != String::npos) // { // class_name = name.substr(seperator+1, name.length()-seperator-1); // package = name.substr(0, seperator); // } // else // { // class_name = name; // } // symbol_res->addSymbol(StringHelper::toString(id), class_name, package); // } // } //} //----------------------------------------------------------------------- }}
[ "stonecold_@9773a11d-1121-4470-82d2-da89bd4a628a" ]
[ [ [ 1, 101 ] ] ]
ef00a306fece6483389f1fad908197dd2d948c66
55f0fcc198d4646235e75c0eff6fc6d3fad85313
/zenilib/include/AgentBase.h
ad2ea41848f65d84e3bee3ab318c5ae514cd1c2a
[]
no_license
ernieg/493final
b6484ea3d09801404a15ee1df974004cb9dffe14
83c9527c3d289dad5496b1fd0eb45bffba09f1d5
refs/heads/master
2021-01-01T16:13:08.191675
2011-04-19T22:04:11
2011-04-19T22:04:11
32,241,477
0
0
null
null
null
null
UTF-8
C++
false
false
545
h
#ifndef AGENTBASE_H #define AGENTBASE_H #include "Player.h" const Zeni::Vector3f DIRECTION(0.0f, -60.0f, 0.0f); class AgentBase : public Player { public: AgentBase(int playerIndex_); void perform_logic(float &timeStep); void handleWiiEvent() {} void renderHand() {} // So hand isn't rendered when AI is playing protected: void moveChip(float &timeStep); virtual void getNewDestination() = 0; bool locationFound; // False if looking for position int destination; // Column float moveDelay; }; #endif
[ "[email protected]@68425394-8837-c440-6ca7-5483a7d6cf0c", "jjkovacs89@68425394-8837-c440-6ca7-5483a7d6cf0c" ]
[ [ [ 1, 3 ], [ 6, 27 ] ], [ [ 4, 5 ] ] ]
a660db2e19288f099fa8c1e4d884ef7778ad8ae3
6d680e20e4a703f0aa0d4bb5e50568143241f2d5
/src/passuello/ProvaFirst/main.cpp
ebd01f06a51b6e4ddcd8e48e688085b5fc835513
[]
no_license
sirnicolaz/MobiHealt
f7771e53a4a80dcea3d159eca729e9bd227e8660
bbfd61209fb683d5f75f00bbf81b24933922baac
refs/heads/master
2021-01-20T12:21:17.215536
2010-04-21T14:21:16
2010-04-21T14:21:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,998
cpp
/**************************************************************************** ** ** Trolltech hereby grants a license to use the Qt/Eclipse Integration ** plug-in (the software contained herein), in binary form, solely for the ** purpose of creating code to be used with Trolltech's Qt software. ** ** Qt Designer is licensed under the terms of the GNU General Public ** License versions 2.0 and 3.0 ("GPL License"). Trolltech offers users the ** right to use certain no GPL licensed software under the terms of its GPL ** Exception version 1.2 (http://trolltech.com/products/qt/gplexception). ** ** THIS SOFTWARE IS PROVIDED BY TROLLTECH AND ITS CONTRIBUTORS (IF ANY) "AS ** IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED ** TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A ** PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER ** OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ** EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, ** PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR ** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF ** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** ** Since we now have the GPL exception I think that the "special exception ** is no longer needed. The license text proposed above (other than the ** special exception portion of it) is the BSD license and we have added ** the BSD license as a permissible license under the exception. ** ****************************************************************************/ #include "ProvaFirst.h" #include <QtGui> #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); ProvaFirst w; w.showFullScreen(); return a.exec(); }
[ [ [ 1, 42 ] ] ]
fc69971e2e82cf1cc1c97c203c29eb26f2f76987
b14d5833a79518a40d302e5eb40ed5da193cf1b2
/cpp/extern/xercesc++/2.6.0/src/xercesc/util/NullPointerException.hpp
9437c0bad5ed8f27b750c27ea0344732978306f8
[ "Apache-2.0" ]
permissive
andyburke/bitflood
dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf
fca6c0b635d07da4e6c7fbfa032921c827a981d6
refs/heads/master
2016-09-10T02:14:35.564530
2011-11-17T09:51:49
2011-11-17T09:51:49
2,794,411
1
0
null
null
null
null
UTF-8
C++
false
false
1,018
hpp
/* * Copyright 1999-2000,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id: NullPointerException.hpp,v 1.3 2004/09/08 13:56:22 peiyongz Exp $ */ #if !defined(NULLPOINTEREXCEPTION_HPP) #define NULLPOINTEREXCEPTION_HPP #include <xercesc/util/XercesDefs.hpp> #include <xercesc/util/XMLException.hpp> XERCES_CPP_NAMESPACE_BEGIN MakeXMLException(NullPointerException, XMLUTIL_EXPORT) XERCES_CPP_NAMESPACE_END #endif
[ [ [ 1, 34 ] ] ]
87bece7e646cb5053856f5ad7871dbc8a0b2e41d
102d8810abb4d1c8aecb454304ec564030bf2f64
/TP3/Tanque/Tanque/Tanque/BattleCityCommunicationProtocol.cpp
571ba39622d88276b391a61ca0b93c1de9d62bde
[]
no_license
jfacorro/tp-taller-prog-1-fiuba
2742d775b917cc6df28188ecc1f671d812017a0a
a1c95914c3be6b1de56d828ea9ff03e982560526
refs/heads/master
2016-09-14T04:32:49.047792
2008-07-15T20:17:27
2008-07-15T20:17:27
56,912,077
0
0
null
null
null
null
UTF-8
C++
false
false
18,154
cpp
#ifndef BattleCityCommunicationProtocol_cpp #define BattleCityCommunicationProtocol_cpp #include <fstream> #include "BattleCityCommunicationProtocol.h" #include "Screen.h" #include "StringHelper.h" #include "SDL.h" /**********************************************************************************************************/ // BattleCityTankPacket /**********************************************************************************************************/ BattleCityTankPacket::BattleCityTankPacket(vector<BattleCityTank> tanks) { this->type = TANK; this->size = PACKET_HEADER_SIZE; this->tanks = tanks; int totalPacketSize = this->size + sizeof(BattleCityTank) * tanks.size(); this->data = new char[totalPacketSize]; for(int i = 0; i < tanks.size(); i++) { memcpy(this->data + this->size, (void*)&this->tanks[i], sizeof(BattleCityTank)); this->size += sizeof(BattleCityTank); } this->SetHeaderInData(); }; BattleCityTankPacket::BattleCityTankPacket(char * data, int size) { this->type = TANK; this->size = PACKET_HEADER_SIZE; //this->data = new char[size]; //memcpy((void *)this->data, data, size); this->size = size; int numberOfTanks = (this->size - PACKET_HEADER_SIZE) / sizeof(BattleCityTank); unsigned long offset = (unsigned long)data + PACKET_HEADER_SIZE; for(int i = 0; i < numberOfTanks; i++) { offset = offset + sizeof(BattleCityTank) * i; BattleCityTank tank(1); memcpy((void*)&tank, (void *)(offset), sizeof(BattleCityTank)); this->tanks.push_back(tank); } } /**********************************************************************************************************/ // BattleCityBulletPacket /**********************************************************************************************************/ BattleCityBulletPacket::BattleCityBulletPacket(vector<BattleCityBullet> bullets) { this->type = BULLET; this->size = PACKET_HEADER_SIZE; this->bullets = bullets; int totalPacketSize = this->size + sizeof(BattleCityBullet) * bullets.size(); this->data = new char[totalPacketSize]; for(int i = 0; i < bullets.size(); i++) { memcpy(this->data + this->size, (void*)&this->bullets[i], sizeof(BattleCityBullet)); this->size += sizeof(BattleCityBullet); } this->SetHeaderInData(); }; BattleCityBulletPacket::BattleCityBulletPacket(char * data, int size) { this->type = BULLET; this->size = PACKET_HEADER_SIZE; this->size = size; int numberOfBullets = (this->size - PACKET_HEADER_SIZE) / sizeof(BattleCityBullet); unsigned long offset = (unsigned long)data + PACKET_HEADER_SIZE; for(int i = 0; i < numberOfBullets; i++) { offset = offset + sizeof(BattleCityBullet) * i; BattleCityBullet bullet(1); memcpy((void*)(&bullet), (void *)(offset), sizeof(BattleCityBullet)); this->bullets.push_back(bullet); } } /**********************************************************************************************************/ // BattleCityBombPacket /**********************************************************************************************************/ BattleCityBombPacket::BattleCityBombPacket(vector<BattleCityBomb> bombs) { this->type = BOMB; this->size = PACKET_HEADER_SIZE; this->bombs = bombs; int totalPacketSize = this->size + sizeof(BattleCityBomb) * bombs.size(); this->data = new char[totalPacketSize]; for(int i = 0; i < bombs.size(); i++) { memcpy(this->data + this->size, (void*)&this->bombs[i], sizeof(BattleCityBomb)); this->size += sizeof(BattleCityBomb); } this->SetHeaderInData(); }; BattleCityBombPacket::BattleCityBombPacket(char * data, int size) { this->type = BOMB; this->size = PACKET_HEADER_SIZE; this->size = size; int numberOfBombs = (this->size - PACKET_HEADER_SIZE) / sizeof(BattleCityBomb); unsigned long offset = (unsigned long)data + PACKET_HEADER_SIZE; for(int i = 0; i < numberOfBombs; i++) { offset = offset + sizeof(BattleCityBomb) * i; BattleCityBomb bomb(1, 1); memcpy((void*)(&bomb), (void *)(offset), sizeof(BattleCityBomb)); this->bombs.push_back(bomb); } } /**********************************************************************************************************/ // BattleCityWallPacket /**********************************************************************************************************/ BattleCityWallPacket::BattleCityWallPacket(vector<BattleCityWall> walls) { this->type = WALL; this->size = PACKET_HEADER_SIZE; this->walls = walls; int totalPacketSize = this->size + sizeof(BattleCityWall) * walls.size(); this->data = new char[totalPacketSize]; for(int i = 0; i < walls.size(); i++) { memcpy(this->data + this->size, (void*)&this->walls[i], sizeof(BattleCityWall)); this->size += sizeof(BattleCityWall); } this->SetHeaderInData(); }; BattleCityWallPacket::BattleCityWallPacket(char * data, int size) { this->type = WALL; this->size = PACKET_HEADER_SIZE; this->size = size; int numberOfWalls = (this->size - PACKET_HEADER_SIZE) / sizeof(BattleCityWall); unsigned long offset = (unsigned long)data + PACKET_HEADER_SIZE; for(int i = 0; i < numberOfWalls; i++) { offset = offset + sizeof(BattleCityWall) * i; BattleCityWall wall; memcpy((void*)(&wall), (void *)(offset), sizeof(BattleCityWall)); this->walls.push_back(wall); } } /**********************************************************************************************************/ // BattleCityCommandPacket /**********************************************************************************************************/ void BattleCityCommandPacket::CstorHelper() { this->type = COMMAND; int fullSize = PACKET_HEADER_SIZE + sizeof(BattleCityCommandType) + 2 * sizeof(int); this->data = new char[fullSize]; this->data[0] = COMMAND; this->size = PACKET_HEADER_SIZE; memcpy(this->data + this->size, (void*)&this->cmdType, sizeof(BattleCityCommandType)); this->size += sizeof(BattleCityCommandType); memcpy(this->data + this->size, (void*)&this->clientNumber, sizeof(int)); this->size += sizeof(int); memcpy(this->data + this->size, (void*)&this->auxValue, sizeof(int)); this->size += sizeof(int); this->SetSizeInData(); } BattleCityCommandPacket::BattleCityCommandPacket(BattleCityCommandType cmdType, int clientNumber, int auxValue) : clientNumber(clientNumber), cmdType (cmdType), auxValue(auxValue) { this->CstorHelper(); }; BattleCityCommandPacket::BattleCityCommandPacket(BattleCityCommandType cmdType) : cmdType (cmdType) { this->CstorHelper(); }; BattleCityCommandPacket::BattleCityCommandPacket(char * data, int size) { this->type = COMMAND; this->size = size; int offset = (int)data + PACKET_HEADER_SIZE; memcpy((void*)&(this->cmdType), (void * )offset, sizeof(BattleCityCommandType)); offset += sizeof(BattleCityCommandType); memcpy((void*)&(this->clientNumber), (void * )offset, sizeof(int)); offset += sizeof(int); memcpy((void*)&(this->auxValue), (void * )offset, sizeof(int)); offset += sizeof(int); } /**********************************************************************************************************/ // BattleCityPlayerNumberPacket /**********************************************************************************************************/ BattleCityPlayerNumberPacket::BattleCityPlayerNumberPacket(int playerNumber) { this->playerNumber = playerNumber; this->type = PLAYERNUMBER; this->data = new char[PACKET_HEADER_SIZE + sizeof(int)]; this->data[0] = PLAYERNUMBER; this->size = PACKET_HEADER_SIZE; memcpy(this->data + this->size, (void*)&this->playerNumber, sizeof(int)); this->size += sizeof(int); this->SetSizeInData(); } BattleCityPlayerNumberPacket::BattleCityPlayerNumberPacket(char * data, int size) { this->type = PLAYERNUMBER; this->size = size; int offset = (int)data + PACKET_HEADER_SIZE; memcpy((void*)&(this->playerNumber), (void * )offset, sizeof(int)); } /**********************************************************************************************************/ // BattleCitySocketNumberPacket /**********************************************************************************************************/ BattleCityPortNumberPacket::BattleCityPortNumberPacket(int portNumber) { this->portNumber = portNumber; this->type = PORTNUMBER; this->data = new char[PACKET_HEADER_SIZE + sizeof(int)]; this->data[0] = PORTNUMBER; this->size = PACKET_HEADER_SIZE; memcpy(this->data + this->size, (void*)&this->portNumber, sizeof(int)); this->size += sizeof(int); this->SetSizeInData(); } BattleCityPortNumberPacket::BattleCityPortNumberPacket(char * data, int size) { this->type = PORTNUMBER; this->size = size; int offset = (int)data + PACKET_HEADER_SIZE; memcpy((void*)&(this->portNumber), (void * )offset, sizeof(int)); } /**********************************************************************************************************/ // BattleCityParametersPacket /**********************************************************************************************************/ BattleCityParametersPacket::BattleCityParametersPacket(BattleCityClientParameters parameters) { this->parameters = parameters; this->type = PARAMETERS; this->data = new char[PACKET_HEADER_SIZE + sizeof(BattleCityClientParameters)]; this->data[0] = PARAMETERS; this->size = PACKET_HEADER_SIZE; memcpy(this->data + this->size, (void*)&this->parameters, sizeof(BattleCityClientParameters)); this->size += sizeof(BattleCityClientParameters); this->SetSizeInData(); } BattleCityParametersPacket::BattleCityParametersPacket(char * data, int size) { this->type = PARAMETERS; this->size = size; int offset = (int)data + PACKET_HEADER_SIZE; memcpy((void*)&(this->parameters), (void * )offset, sizeof(BattleCityClientParameters)); } /**********************************************************************************************************/ // BattleCityTexturePacket /**********************************************************************************************************/ BattleCityTexturePacket::BattleCityTexturePacket(char * name, char * path) { StringHelper::Copy(name, this->name, strlen(name)); StringHelper::Copy(path, this->filename, strlen(path)); this->type = TEXTURE; FILE * file; file = fopen(path, "rb"); long filesize = 0; int packetSizeWithoutFile = PACKET_HEADER_SIZE + TEXTURE_NAME_MAX_LENGTH * 2; /// Load bitmap file data if(file != NULL) { fseek(file, 0, SEEK_END); filesize = ftell(file); this->data = new char[packetSizeWithoutFile + filesize]; fseek(file, 0, SEEK_SET); fread(this->data + packetSizeWithoutFile , sizeof(char), filesize, file); fclose(file); } else { this->data = new char[packetSizeWithoutFile]; } this->data[0] = TEXTURE; this->size = PACKET_HEADER_SIZE; /// Load bitmap name into data memcpy(this->data + this->size, (void*)this->name, TEXTURE_NAME_MAX_LENGTH); this->size += TEXTURE_NAME_MAX_LENGTH; memcpy(this->data + this->size, (void*)this->filename, TEXTURE_NAME_MAX_LENGTH); this->size += TEXTURE_NAME_MAX_LENGTH + filesize; this->SetSizeInData(); } BattleCityTexturePacket::BattleCityTexturePacket(char * data, int size) { this->type = TEXTURE; this->size = size; this->data = new char[size]; memcpy(this->data, data , size); memcpy(this->name, data + PACKET_HEADER_SIZE, TEXTURE_NAME_MAX_LENGTH); memcpy(this->filename, data + PACKET_HEADER_SIZE + TEXTURE_NAME_MAX_LENGTH, TEXTURE_NAME_MAX_LENGTH); } char * BattleCityTexturePacket::SaveBitmap() { char * bitmap = this->GetBitmapData(); int filesize = this->GetBitmapSize(); char * filename = new char[TEXTURE_NAME_MAX_LENGTH]; StringHelper::Copy(this->filename, filename, strlen(this->filename)); StringHelper::GetFileNameFromPath(filename, filename); FILE * file; file = fopen(filename, "wb"); fwrite(bitmap, sizeof(char), filesize, file); fclose(file); return filename; } /**********************************************************************************************************/ // BattleCityCommunicationProtocol /**********************************************************************************************************/ void * BattleCityCommunicationProtocol::ReceiveDataPacket(Socket socket) { return ReceiveDataPacket(socket.GetConnection().cxSocket); } void * BattleCityCommunicationProtocol::ReceiveDataPacket(SOCKET sock) { Socket socket(sock); BattleCityDataPacket * packet = NULL; SocketPacket headerPacket(PACKET_HEADER_SIZE); /// Get Packet Header /// int bytesRead = recv ( socket.GetConnection().cxSocket , packetHeader, 3 , 0 ); int result = socket.Receive(&headerPacket); if(result == RES_OK) { char * packetHeader = headerPacket.GetData(); int packetTotalLength = BattleCityDataPacket::GetSizeFromData(headerPacket.GetData()); if(packetTotalLength > 0) { int packetDataLength = packetTotalLength - PACKET_HEADER_SIZE; char * packetData = new char[packetTotalLength]; if(packetData != 0) { packetData[0] = packetHeader[0]; packetData[1] = packetHeader[1]; packetData[2] = packetHeader[2]; int cantRecibida = 0, totalRecibido = 0; bool successTransfer = true; fd_set readSocket; FD_ZERO(&readSocket); FD_SET(socket.GetConnection().cxSocket, &readSocket); int selectResult = 0; int highestSock = socket.GetConnection().cxSocket + 1; while ( totalRecibido < packetDataLength ) { cantRecibida = recv (socket.GetConnection().cxSocket, packetData + PACKET_HEADER_SIZE + totalRecibido, packetDataLength - totalRecibido, 0); if ( cantRecibida == -1 ) successTransfer = false; totalRecibido += cantRecibida; if (totalRecibido >= packetDataLength) break; } if(successTransfer) { if ( packetData[0] == TANK) { BattleCityTankPacket * tankPacket = new BattleCityTankPacket(packetData, packetTotalLength); packet = tankPacket; } if ( packetData[0] == BULLET) { BattleCityBulletPacket * bulletPacket = new BattleCityBulletPacket(packetData, packetTotalLength); packet = bulletPacket; } if ( packetData[0] == BOMB) { BattleCityBombPacket * bombPacket = new BattleCityBombPacket(packetData, packetTotalLength); packet = bombPacket; } if ( packetData[0] == WALL) { BattleCityWallPacket * wallPacket = new BattleCityWallPacket(packetData, packetTotalLength); packet = wallPacket; } if ( packetData[0] == COMMAND) { BattleCityCommandPacket * cmdPacket = new BattleCityCommandPacket(packetData, packetTotalLength); packet = cmdPacket; } if ( packetData[0] == PLAYERNUMBER) { BattleCityPlayerNumberPacket * playerPacket = new BattleCityPlayerNumberPacket(packetData, packetTotalLength); packet = playerPacket; } if ( packetData[0] == PORTNUMBER) { BattleCityPortNumberPacket * portNumberPacket = new BattleCityPortNumberPacket (packetData, packetTotalLength); packet = portNumberPacket; } if ( packetData[0] == PARAMETERS) { BattleCityParametersPacket * parametersPacket = new BattleCityParametersPacket(packetData, packetTotalLength); packet = parametersPacket; } if ( packetData[0] == TEXTURE) { BattleCityTexturePacket * texturePacket = new BattleCityTexturePacket(packetData, packetTotalLength); packet = texturePacket; } } delete packetData; } } } else { //MessageBox ( NULL , L"Server communication lost" , L"Battle City Client" , MB_OK | MB_ICONEXCLAMATION ); exit ( 1 ); } return packet; } void BattleCityCommunicationProtocol::WriteLog(const char * msg) { /* FILE * file; file = fopen("log.txt", "a"); if (file!=NULL) { fputs (msg, file); fclose (file); } */ } #endif
[ "juan.facorro@6dff32cf-8f48-0410-9a2e-7b8b34aa6dfb", "nahuelgonzalez@6dff32cf-8f48-0410-9a2e-7b8b34aa6dfb" ]
[ [ [ 1, 517 ], [ 523, 542 ] ], [ [ 518, 522 ] ] ]
35768cec9819cda9ff3fe07d70fe5e15bcf8a4dd
45c0d7927220c0607531d6a0d7ce49e6399c8785
/GlobeFactory/src/useful/log.cc
ecb26ef281497c33d42f8a7f4cf975ba042f20a4
[]
no_license
wavs/pfe-2011-scia
74e0fc04e30764ffd34ee7cee3866a26d1beb7e2
a4e1843239d9a65ecaa50bafe3c0c66b9c05d86a
refs/heads/master
2021-01-25T07:08:36.552423
2011-01-17T20:23:43
2011-01-17T20:23:43
39,025,134
0
0
null
null
null
null
UTF-8
C++
false
false
3,598
cc
#include "log.hh" #include <fstream> #include <time.h> #include <assert.h> //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ Log::Log() : MVerboseLevel(LogVerbose::VERBOSE_NONE), MOut(NULL) { this->print[Log::RESUME] = &Log::PrintResume; this->print[Log::WARNING] = &Log::PrintWarning; this->print[Log::ERROR] = &Log::PrintError; } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ Log::~Log() { CloseOutput(); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ void Log::SetOutput(const std::string& parOutput) { CloseOutput(); if (parOutput == "stdout") MOut = &std::cout; else if (parOutput == "stderr") MOut = &std::cerr; else MOut = new std::ofstream(parOutput.c_str(), std::ios_base::out | std::ios_base::trunc); PrintBegin(parOutput); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ void Log::SetOutput(std::ostream& parOutput) { CloseOutput(); MOut = &parOutput; PrintBegin("an unknown stream"); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ void Log::PrintBegin(const std::string& parOutpurStr) const { long date; time(&date); *MOut << "=============================================" << std::endl; *MOut << "=============================================" << std::endl; *MOut << "===== OPEN LOG in " << parOutpurStr << std::endl; *MOut << "===== ON " << ctime(&date); *MOut << "=============================================" << std::endl; *MOut << "=============================================" << std::endl; *MOut << std::endl << std::endl; } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ void Log::CloseOutput() { if (MOut == NULL) return; long date; time(&date); *MOut << std::endl << std::endl; *MOut << "=============================================" << std::endl; *MOut << "=============================================" << std::endl; *MOut << "===== CLOSE LOG" << std::endl; *MOut << "===== ON " << ctime(&date); *MOut << "=============================================" << std::endl; *MOut << "=============================================" << std::endl; std::ofstream* file = dynamic_cast<std::ofstream*> (MOut); if (file != NULL) { file->close(); delete file; } MOut = 0; } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ void Log::Send(const std::string& parCat, const std::string& parMsg, MsgType parType) { if (MOut == NULL) return; if ((parType & MVerboseLevel) != 0) { (this->*print[parType])(); *this->MOut << parCat << "\t: " << parMsg << std::endl; } } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------
[ "creteur.c@8e971d8e-9cf3-0c36-aa0f-a7c54ab41ffc" ]
[ [ [ 1, 113 ] ] ]
2f2d64867f36b9951b62f910ced64ca0f36252d2
f317b6eba86e00052f684e2001e1ea81f5357ee9
/ivrc_demo/trunk/face_pickup/getviewpoint.h
f53d4770636e54cd89a4ec45487a948dccbd8c0c
[]
no_license
Habib120/apmayfes2011-kao
2ef24ff490511a6a08606f3ab05d4152069721b8
cb167c9ab6182ad13077c9ffe851bdc5be6f4256
refs/heads/master
2016-09-01T17:54:20.659856
2011-10-06T03:47:33
2011-10-06T03:47:33
33,204,831
0
0
null
null
null
null
UTF-8
C++
false
false
154
h
#include <cv.h> #include <math.h> #include <iostream> cv::Point2d getviewpointxz(cv::Mat gray_img); cv::Point2d getviewpointy(cv::Mat gray_img);
[ "[email protected]@4f86e157-8500-1dc0-33fe-d8cc54530173", "[email protected]@4f86e157-8500-1dc0-33fe-d8cc54530173", "[email protected]@4f86e157-8500-1dc0-33fe-d8cc54530173" ]
[ [ [ 1, 4 ] ], [ [ 5, 5 ], [ 7, 7 ] ], [ [ 6, 6 ] ] ]
ee4c0054aee5b689a344c4dbb51f55efecd549da
515e917815568d213e75bfcbd3fb9f0e08cf2677
/common/mempool.h
f9d2290f778a59a4b61b28e1293abd4728bf07c9
[ "BSD-2-Clause" ]
permissive
dfk789/CodenameInfinite
bd183aec6b9e60e20dda6764d99f4e8d8a945add
aeb88b954b65f6beca3fb221fe49459b75e7c15f
refs/heads/master
2020-05-30T15:46:20.450963
2011-10-15T00:21:38
2011-10-15T00:21:38
5,652,791
2
0
null
null
null
null
UTF-8
C++
false
false
1,282
h
#ifndef _LW_MEMPOOL #define _LW_MEMPOOL #include <EASTL/vector.h> class CMemChunk { public: void* m_pMem; size_t m_iSize; CMemChunk* m_pNext; }; class CMemPool { public: static void* Alloc(size_t iSize, size_t iHandle = 0); static void Free(void* pMem, size_t iHandle = 0); static size_t GetMemPoolHandle(); // A potentially dangerous function to call if the memory is still being used. static void ClearPool(size_t iHandle); private: CMemPool(); public: ~CMemPool(); private: void* Reserve(void* pLocation, size_t iSize, CMemChunk* pAfter = NULL); size_t m_iHandle; void* m_pMemPool; size_t m_iMemPoolSize; size_t m_iMemoryAllocated; CMemChunk* m_pAllocMap; // *Sorted* list of memory allocations. CMemChunk* m_pAllocMapBack; private: static CMemPool* AddPool(size_t iSize, size_t iHandle); static size_t s_iMemoryAllocated; static eastl::vector<CMemPool*> s_apMemPools; static size_t s_iLastMemPoolHandle; }; void* mempool_alloc(size_t iSize, size_t iHandle = 0); void mempool_free(void* pMem, size_t iHandle = 0); size_t mempool_gethandle(); void mempool_clearpool(size_t iHandle); #endif
[ [ [ 1, 55 ] ] ]
27a9a4c0c7b747f077d0793e53a68bff4ea55935
2ca3ad74c1b5416b2748353d23710eed63539bb0
/Pilot/Lokapala_Communication/Operator/OperatorDlg.cpp
befba12dd8c8634bde79c80144b90d3c29ab7e95
[]
no_license
sjp38/lokapala
5ced19e534bd7067aeace0b38ee80b87dfc7faed
dfa51d28845815cfccd39941c802faaec9233a6e
refs/heads/master
2021-01-15T16:10:23.884841
2009-06-03T14:56:50
2009-06-03T14:56:50
32,124,140
0
0
null
null
null
null
UTF-8
C++
false
false
3,865
cpp
// OperatorDlg.cpp : implementation file // #include "stdafx.h" #include "Operator.h" #include "OperatorDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CAboutDlg dialog used for App About class CAboutDlg : public CDialog { public: CAboutDlg(); // Dialog Data enum { IDD = IDD_ABOUTBOX }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support // Implementation protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) END_MESSAGE_MAP() // COperatorDlg dialog COperatorDlg::COperatorDlg(CWnd* pParent /*=NULL*/) : CDialog(COperatorDlg::IDD, pParent) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void COperatorDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(COperatorDlg, CDialog) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() //}}AFX_MSG_MAP ON_BN_CLICKED(IDC_BUTTONTEST, &COperatorDlg::OnBnClickedButtontest) END_MESSAGE_MAP() // COperatorDlg message handlers BOOL COperatorDlg::OnInitDialog() { CDialog::OnInitDialog(); // Add "About..." menu item to system menu. // IDM_ABOUTBOX must be in the system command range. ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { CString strAboutMenu; strAboutMenu.LoadString(IDS_ABOUTBOX); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here CCBFMediator::Instance()->SetMainDlg(this); CCBFMediator::Instance()->BeginCommunication(); return TRUE; // return TRUE unless you set the focus to a control } void COperatorDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialog::OnSysCommand(nID, lParam); } } // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. void COperatorDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // Center icon in client rectangle int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // Draw the icon dc.DrawIcon(x, y, m_hIcon); } else { CDialog::OnPaint(); } } // The system calls this function to obtain the cursor to display while the user drags // the minimized window. HCURSOR COperatorDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } void COperatorDlg::OnBnClickedButtontest() { // TODO: Add your control notification handler code here CString message; this->GetDlgItemTextW(IDC_EDITTEST, message); CListBox *plistBox = (CListBox *)(this->GetDlgItem(IDC_LISTTEST)); CString address; plistBox->GetText(plistBox->GetCurSel(), address); if(address==_T("")) { CCBFMediator::Instance()->BroadcastTextMessage(message); return; } CCBFMediator::Instance()->SendTextMessageTo(address, message); }
[ "nilakantha38@b9e76448-5c52-0410-ae0e-a5aea8c5d16c" ]
[ [ [ 1, 171 ] ] ]
64825f3a347316a24637322d446c63539628f6f2
463c3b62132d215e245a097a921859ecb498f723
/lib/dlib/crc32.h
68bc9bfdd62ba9360e31865d7ac749ea5138f343
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
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
528
h
// Copyright (C) 2005 Davis E. King ([email protected]) // License: Boost Software License See LICENSE.txt for the full license. #ifndef DLIB_CRc32_ #define DLIB_CRc32_ #include "crc32/crc32_kernel_1.h" namespace dlib { class crc32 { crc32() {} public: //----------- kernels --------------- // kernel_1a typedef crc32_kernel_1 kernel_1a; }; } #endif // DLIB_CRc32_
[ "jimmy@DGJ3X3B1.(none)" ]
[ [ [ 1, 35 ] ] ]
d84136142d76960894b06e750702ce21bfdc3696
1c80a726376d6134744d82eec3129456b0ab0cbf
/Project/C++/C++/vc源码/source/source/DropDownToolBar.h
3f0d6912d14a341b4f32c0bdb1e78ee37701500d
[]
no_license
dabaopku/project_pku
338a8971586b6c4cdc52bf82cdd301d398ad909f
b97f3f15cdc3f85a9407e6bf35587116b5129334
refs/heads/master
2021-01-19T11:35:53.500533
2010-09-01T03:42:40
2010-09-01T03:42:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,425
h
#if !defined(AFX_DROPDOWNTOOLBAR_H__9F581592_1687_4D12_8D4F_5048713474FC__INCLUDED_) #define AFX_DROPDOWNTOOLBAR_H__9F581592_1687_4D12_8D4F_5048713474FC__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // DropDownToolBar.h : header file // ///////////////////////////////////////////////////////////////////////////// // CDropDownToolBar window class CDropDownToolBar : public CToolBar { // Construction public: CDropDownToolBar(); // Attributes public: // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CDropDownToolBar) //}}AFX_VIRTUAL // Implementation public: virtual void OnDropDownButton(UINT nID); void SetDropDownButton(UINT nID,UINT nMenuID); UINT * p_MenuID; BOOL LoadToolBar(UINT nID); virtual ~CDropDownToolBar(); // Generated message map functions protected: //{{AFX_MSG(CDropDownToolBar) // NOTE - the ClassWizard will add and remove member functions here. //}}AFX_MSG afx_msg void OnDropDown(LPNMTOOLBAR pNotifyStruct, LRESULT* result); DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_DROPDOWNTOOLBAR_H__9F581592_1687_4D12_8D4F_5048713474FC__INCLUDED_)
[ "[email protected]@592586dc-1302-11df-8689-7786f20063ad" ]
[ [ [ 1, 53 ] ] ]
e512399612930b9895be71ac2bf54d72054e8de8
e2e49023f5a82922cb9b134e93ae926ed69675a1
/tools/aoslcpp/include/aosl/special_object_ref.hpp
b5eaf156015186000c899220651eee907d3907c0
[]
no_license
invy/mjklaim-freewindows
c93c867e93f0e2fe1d33f207306c0b9538ac61d6
30de8e3dfcde4e81a57e9059dfaf54c98cc1135b
refs/heads/master
2021-01-10T10:21:51.579762
2011-12-12T18:56:43
2011-12-12T18:56:43
54,794,395
1
0
null
null
null
null
UTF-8
C++
false
false
6,950
hpp
// Copyright (C) 2005-2010 Code Synthesis Tools CC // // This program was generated by CodeSynthesis XSD, an XML Schema // to C++ data binding compiler, in the Proprietary License mode. // You should have received a proprietary license from Code Synthesis // Tools CC prior to generating this code. See the license text for // conditions. // /** * @file * @brief Generated from special_object_ref.xsd. */ #ifndef AOSLCPP_AOSL__SPECIAL_OBJECT_REF_HPP #define AOSLCPP_AOSL__SPECIAL_OBJECT_REF_HPP // Begin prologue. // #include <aoslcpp/common.hpp> // // End prologue. #include <xsd/cxx/config.hxx> #if (XSD_INT_VERSION != 3030000L) #error XSD runtime version mismatch #endif #include <xsd/cxx/pre.hxx> #include "aosl/special_object_ref_forward.hpp" #include <memory> // std::auto_ptr #include <limits> // std::numeric_limits #include <algorithm> // std::binary_search #include <xsd/cxx/xml/char-utf8.hxx> #include <xsd/cxx/tree/exceptions.hxx> #include <xsd/cxx/tree/elements.hxx> #include <xsd/cxx/tree/containers.hxx> #include <xsd/cxx/tree/list.hxx> #include <xsd/cxx/xml/dom/parsing-header.hxx> #include <xsd/cxx/tree/containers-wildcard.hxx> #ifndef XSD_DONT_INCLUDE_INLINE #define XSD_DONT_INCLUDE_INLINE #undef XSD_DONT_INCLUDE_INLINE #else #endif // XSD_DONT_INCLUDE_INLINE /** * @brief C++ namespace for the %artofsequence.org/aosl/1.0 * schema namespace. */ namespace aosl { /** * @brief Enumeration class corresponding to the %special_object_ref * schema type. * * Reference to one or more Objects automatically found using a search * logic. */ class Special_object_ref: public ::xml_schema::String { public: /** * @brief Underlying enum type. */ enum Value { /** * #all : All objects in the canvas. */ cxx_all }; /** * @brief Create an instance from the underlying enum value. * * @param v A enum value. */ Special_object_ref (Value v); /** * @brief Create an instance from a C string. * * @param v A string value. */ Special_object_ref (const char* v); /** * @brief Create an instance from a string. * * @param v A string value. */ Special_object_ref (const ::std::string& v); /** * @brief Create an instance from the base value. * * @param v A base value. */ Special_object_ref (const ::xml_schema::String& v); /** * @brief Create an instance from a DOM element. * * @param e A DOM element to extract the data from. * @param f Flags to create the new instance with. * @param c A pointer to the object that will contain the new * instance. */ Special_object_ref (const ::xercesc::DOMElement& e, ::xml_schema::Flags f = 0, ::xml_schema::Container* c = 0); /** * @brief Create an instance from a DOM attribute. * * @param a A DOM attribute to extract the data from. * @param f Flags to create the new instance with. * @param c A pointer to the object that will contain the new * instance. */ Special_object_ref (const ::xercesc::DOMAttr& a, ::xml_schema::Flags f = 0, ::xml_schema::Container* c = 0); /** * @brief Create an instance from a string fragment. * * @param s A string fragment to extract the data from. * @param e A pointer to DOM element containing the string fragment. * @param f Flags to create the new instance with. * @param c A pointer to the object that will contain the new * instance. */ Special_object_ref (const ::std::string& s, const ::xercesc::DOMElement* e, ::xml_schema::Flags f = 0, ::xml_schema::Container* c = 0); /** * @brief Copy constructor. * * @param x An instance to make a copy of. * @param f Flags to create the copy with. * @param c A pointer to the object that will contain the copy. * * For polymorphic object models use the @c _clone function instead. */ Special_object_ref (const Special_object_ref& x, ::xml_schema::Flags f = 0, ::xml_schema::Container* c = 0); /** * @brief Copy the instance polymorphically. * * @param f Flags to create the copy with. * @param c A pointer to the object that will contain the copy. * @return A pointer to the dynamically allocated copy. * * This function ensures that the dynamic type of the instance is * used for copying and should be used for polymorphic object * models instead of the copy constructor. */ virtual Special_object_ref* _clone (::xml_schema::Flags f = 0, ::xml_schema::Container* c = 0) const; /** * @brief Assign the underlying enum value. * * @param v A enum value. * @return A refernce to the instance. */ Special_object_ref& operator= (Value v); /** * @brief Implicit conversion operator to the underlying * enum value. * * @return A enum value. */ virtual operator Value () const { return _xsd_Special_object_ref_convert (); } //@cond protected: Value _xsd_Special_object_ref_convert () const; public: static const char* const _xsd_Special_object_ref_literals_[1]; static const Value _xsd_Special_object_ref_indexes_[1]; //@endcond }; } #ifndef XSD_DONT_INCLUDE_INLINE #endif // XSD_DONT_INCLUDE_INLINE #include <iosfwd> namespace aosl { ::std::ostream& operator<< (::std::ostream&, Special_object_ref::Value); ::std::ostream& operator<< (::std::ostream&, const Special_object_ref&); } #include <iosfwd> #include <xercesc/sax/InputSource.hpp> #include <xercesc/dom/DOMDocument.hpp> #include <xercesc/dom/DOMErrorHandler.hpp> namespace aosl { } #include <iosfwd> #include <xercesc/dom/DOMDocument.hpp> #include <xercesc/dom/DOMErrorHandler.hpp> #include <xercesc/framework/XMLFormatter.hpp> #include <xsd/cxx/xml/dom/auto-ptr.hxx> namespace aosl { void operator<< (::xercesc::DOMElement&, const Special_object_ref&); void operator<< (::xercesc::DOMAttr&, const Special_object_ref&); void operator<< (::xml_schema::ListStream&, const Special_object_ref&); } #ifndef XSD_DONT_INCLUDE_INLINE #include "aosl/special_object_ref.inl" #endif // XSD_DONT_INCLUDE_INLINE #include <xsd/cxx/post.hxx> // Begin epilogue. // // // End epilogue. #endif // AOSLCPP_AOSL__SPECIAL_OBJECT_REF_HPP
[ "klaim@localhost" ]
[ [ [ 1, 273 ] ] ]
7185a61f0fcf36da219d94d32ae6d284aedc3705
bb625ce36ed37acb5a8e660ec03001e9f23626cc
/NMTesting/Profile.cpp
c7c89d5fae04207a74762b286c5d1eb4475aeff1
[]
no_license
crayzyivan/weppinhole
5010f6f9319a81ec5f5277f8a7dd952a20d37c87
58923bf0667471257679a6f34a353412364609d5
refs/heads/master
2021-01-10T13:14:59.582556
2010-06-25T02:46:40
2010-06-25T02:46:40
43,535,806
1
0
null
null
null
null
UTF-8
C++
false
false
63,276
cpp
// define this flag for COM #include "stdafx.h" #define _WIN32_DCOM #include <windows.h> #include <conio.h> #include <objbase.h> #include <rpcsal.h> #include <objbase.h> #include <msxml6.h> #include <atlbase.h> #include <iostream> #include <iomanip> // headers needed to use WLAN APIs #include <wlanapi.h> using namespace std; wchar_t szProfileStringFmt[] = L"<?xml version=\"1.0\"?>\n" L" <WLANProfile xmlns=\"http://www.microsoft.com/networking/WLAN/profile/v1\">\n" L" <name>%S</name>\n" L" <SSIDConfig>\n" L" <SSID>\n" L" <name>%S</name>\n" L" </SSID>\n" L" <nonBroadcast>false</nonBroadcast>\n" L" </SSIDConfig>\n" L" <connectionType>ESS</connectionType>\n" L" <connectionMode>auto</connectionMode>\n" L" <MSM>\n" L" <security>\n" L" <authEncryption>\n" L" <authentication>open</authentication>\n" L" <encryption>WEP</encryption>\n" L" <useOneX>false</useOneX>\n" L" </authEncryption>\n" L" <sharedKey>\n" L" <keyType>networkKey</keyType>\n" L" <protected>false</protected>\n" L" <keyMaterial>%S</keyMaterial>\n" L" </sharedKey>\n" L" </security>\n" L" </MSM>\n" L"</WLANProfile>\n" ; // get win32 error from HRESULT #define WIN32_FROM_HRESULT(hr) \ (SUCCEEDED(hr) ? ERROR_SUCCESS : \ (HRESULT_FACILITY(hr) == FACILITY_WIN32 ? HRESULT_CODE(hr) : (hr))) // // Utility functions // // get interface state string LPWSTR GetInterfaceStateString( __in WLAN_INTERFACE_STATE wlanInterfaceState ) { LPWSTR strRetCode; switch(wlanInterfaceState) { case wlan_interface_state_not_ready: strRetCode = L"\"not ready\""; break; case wlan_interface_state_connected: strRetCode = L"\"connected\""; break; case wlan_interface_state_ad_hoc_network_formed: strRetCode = L"\"ad hoc network formed\""; break; case wlan_interface_state_disconnecting: strRetCode = L"\"disconnecting\""; break; case wlan_interface_state_disconnected: strRetCode = L"\"disconnected\""; break; case wlan_interface_state_associating: strRetCode = L"\"associating\""; break; case wlan_interface_state_discovering: strRetCode = L"\"discovering\""; break; case wlan_interface_state_authenticating: strRetCode = L"\"authenticating\""; break; default: strRetCode = L"\"invalid interface state\""; } return strRetCode; } // get ACM notification string LPWSTR GetAcmNotificationString( __in DWORD acmNotif ) { LPWSTR strRetCode; switch(acmNotif) { case wlan_notification_acm_autoconf_enabled: strRetCode = L"\"autoconf enabled\""; break; case wlan_notification_acm_autoconf_disabled: strRetCode = L"\"autoconf disabled\""; break; case wlan_notification_acm_background_scan_enabled: strRetCode = L"\"background scan enabled\""; break; case wlan_notification_acm_background_scan_disabled: strRetCode = L"\"background scan disabled\""; break; case wlan_notification_acm_power_setting_change: strRetCode = L"\"power setting change\""; break; case wlan_notification_acm_scan_complete: strRetCode = L"\"scan complete\""; break; case wlan_notification_acm_scan_fail: strRetCode = L"\"scan fail\""; break; case wlan_notification_acm_connection_start: strRetCode = L"\"connection start\""; break; case wlan_notification_acm_connection_complete: strRetCode = L"\"connection complete\""; break; case wlan_notification_acm_connection_attempt_fail: strRetCode = L"\"connection fail\""; break; case wlan_notification_acm_filter_list_change: strRetCode = L"\"filter list change\""; break; case wlan_notification_acm_interface_arrival: strRetCode = L"\"interface arrival\""; break; case wlan_notification_acm_interface_removal: strRetCode = L"\"interface removal\""; break; case wlan_notification_acm_profile_change: strRetCode = L"\"profile change\""; break; case wlan_notification_acm_profiles_exhausted: strRetCode = L"\"profiles exhausted\""; break; case wlan_notification_acm_network_not_available: strRetCode = L"\"network not available\""; break; case wlan_notification_acm_network_available: strRetCode = L"\"network available\""; break; case wlan_notification_acm_disconnecting: strRetCode = L"\"disconnecting\""; break; case wlan_notification_acm_disconnected: strRetCode = L"\"disconnected\""; break; case wlan_notification_acm_adhoc_network_state_change: strRetCode = L"\"ad hoc network state changes\""; break; default: strRetCode = L"\"unknown ACM notification\""; } return strRetCode; } // get MSMM notification string LPWSTR GetMsmNotificationString( __in DWORD msmNotif ) { LPWSTR strRetCode; switch(msmNotif) { case wlan_notification_msm_associating: strRetCode = L"\"associating\""; break; case wlan_notification_msm_associated: strRetCode = L"\"associated\""; break; case wlan_notification_msm_authenticating: strRetCode = L"\"authenticating\""; break; case wlan_notification_msm_connected: strRetCode = L"\"connected\""; break; case wlan_notification_msm_roaming_start: strRetCode = L"\"roaming start\""; break; case wlan_notification_msm_roaming_end: strRetCode = L"\"roaming end\""; break; case wlan_notification_msm_radio_state_change: strRetCode = L"\"radio state change\""; break; case wlan_notification_msm_signal_quality_change: strRetCode = L"\"signal quality change\""; break; case wlan_notification_msm_disassociating: strRetCode = L"\"disassociating\""; break; case wlan_notification_msm_disconnected: strRetCode = L"\"disconnected\""; break; case wlan_notification_msm_peer_join: strRetCode = L"\"a peer joins the ad hoc network\""; break; case wlan_notification_msm_peer_leave: strRetCode = L"\"a peer leaves the ad hoc network\""; break; case wlan_notification_msm_adapter_removal: strRetCode = L"\"adapter is in a bad state\""; break; default: strRetCode = L"\"unknown MSM notification\""; } return strRetCode; } // get connection mode string LPWSTR GetConnectionModeString( __in WLAN_CONNECTION_MODE wlanConnMode ) { LPWSTR strRetCode; switch(wlanConnMode) { case wlan_connection_mode_profile: strRetCode = L"\"manual connection with a profile\""; break; case wlan_connection_mode_temporary_profile: strRetCode = L"\"manual connection with a temporary profile\""; break; case wlan_connection_mode_discovery_secure: strRetCode = L"\"connection to a secure network without a profile\""; break; case wlan_connection_mode_discovery_unsecure: strRetCode = L"\"connection to an unsecure network without a profile\""; break; case wlan_connection_mode_auto: strRetCode = L"\"automatic connection with a profile\""; break; default: strRetCode = L"\"invalid connection mode\""; } return strRetCode; } // get PHY type string LPWSTR GetPhyTypeString( __in ULONG uDot11PhyType ) { LPWSTR strRetCode; switch(uDot11PhyType) { case dot11_phy_type_dsss: strRetCode = L"\"DSSS\""; break; case dot11_phy_type_erp: strRetCode = L"\"802.11g\""; break; case dot11_phy_type_fhss: strRetCode = L"\"FHSS\""; break; case dot11_phy_type_hrdsss: strRetCode = L"\"802.11b\""; break; case dot11_phy_type_irbaseband: strRetCode = L"\"IR-base band\""; break; case dot11_phy_type_ofdm: strRetCode = L"\"802.11a\""; break; case dot11_phy_type_any: strRetCode = L"\"any\""; break; default: strRetCode = L"\"Unknown PHY type\""; } return strRetCode; } // get BSS type string LPWSTR GetBssTypeString( __in DOT11_BSS_TYPE dot11BssType ) { LPWSTR strRetCode; switch(dot11BssType) { case dot11_BSS_type_infrastructure: strRetCode = L"\"Infrastructure\""; break; case dot11_BSS_type_independent: strRetCode = L"\"Ad hoc\""; break; case dot11_BSS_type_any: strRetCode = L"\"Any\""; break; default: strRetCode = L"\"Unknown BSS type\""; } return strRetCode; } // get radio state string LPWSTR GetRadioStateString( __in DOT11_RADIO_STATE radioState ) { LPWSTR strRetCode; switch(radioState) { case dot11_radio_state_on: strRetCode = L"\"on\""; break; case dot11_radio_state_off: strRetCode = L"\"off\""; break; default: strRetCode = L"\"unknown state\""; } return strRetCode; } // get auth algorithm string LPWSTR GetAuthAlgoString( __in DOT11_AUTH_ALGORITHM dot11AuthAlgo ) { LPWSTR strRetCode = L"\"Unknown algorithm\""; switch(dot11AuthAlgo) { case DOT11_AUTH_ALGO_80211_OPEN: strRetCode = L"\"Open\""; break; case DOT11_AUTH_ALGO_80211_SHARED_KEY: strRetCode = L"\"Shared\""; break; case DOT11_AUTH_ALGO_WPA: strRetCode = L"\"WPA-Enterprise\""; break; case DOT11_AUTH_ALGO_WPA_PSK: strRetCode = L"\"WPA-Personal\""; break; case DOT11_AUTH_ALGO_WPA_NONE: strRetCode = L"\"WPA-NONE\""; break; case DOT11_AUTH_ALGO_RSNA: strRetCode = L"\"WPA2-Enterprise\""; break; case DOT11_AUTH_ALGO_RSNA_PSK: strRetCode = L"\"WPA2-Personal\""; break; default: if (dot11AuthAlgo & DOT11_AUTH_ALGO_IHV_START) { strRetCode = L"\"Vendor-specific algorithm\""; } } return strRetCode; } // get cipher algorithm string LPWSTR GetCipherAlgoString( __in DOT11_CIPHER_ALGORITHM dot11CipherAlgo ) { LPWSTR strRetCode = L"\"Unknown algorithm\""; switch(dot11CipherAlgo) { case DOT11_CIPHER_ALGO_NONE: strRetCode = L"\"None\""; break; case DOT11_CIPHER_ALGO_WEP40: strRetCode = L"\"WEP40\""; break; case DOT11_CIPHER_ALGO_TKIP: strRetCode = L"\"TKIP\""; break; case DOT11_CIPHER_ALGO_CCMP: strRetCode = L"\"AES\""; break; case DOT11_CIPHER_ALGO_WEP104: strRetCode = L"\"WEP104\""; break; case DOT11_CIPHER_ALGO_WPA_USE_GROUP: strRetCode = L"\"USE-GROUP\""; break; case DOT11_CIPHER_ALGO_WEP: strRetCode = L"\"WEP\""; break; default: if (dot11CipherAlgo & DOT11_CIPHER_ALGO_IHV_START) { strRetCode = L"\"Vendor-specific algorithm\""; } } return strRetCode; } // get SSID from the WCHAR string DWORD StringWToSsid( __in LPCWSTR strSsid, __out PDOT11_SSID pSsid ) { DWORD dwRetCode = ERROR_SUCCESS; BYTE pbSsid[DOT11_SSID_MAX_LENGTH + 1] = {0}; if (strSsid == NULL || pSsid == NULL) { dwRetCode = ERROR_INVALID_PARAMETER; } else { pSsid->uSSIDLength = WideCharToMultiByte (CP_ACP, 0, strSsid, -1, (LPSTR)pbSsid, sizeof(pbSsid), NULL, NULL); pSsid->uSSIDLength--; memcpy(&pSsid->ucSSID, pbSsid, pSsid->uSSIDLength); } return dwRetCode; } // copy SSID to a null-terminated WCHAR string // count is the number of WCHAR in the buffer. LPWSTR SsidToStringW( __out_ecount(count) LPWSTR buf, __in ULONG count, __in PDOT11_SSID pSsid ) { ULONG bytes, i; bytes = min( count-1, pSsid->uSSIDLength); for( i=0; i<bytes; i++) mbtowc( &buf[i], (const char *)&pSsid->ucSSID[i], 1); buf[bytes] = '\0'; return buf; } // the max lenght of the reason string in characters #define WLSAMPLE_REASON_STRING_LEN 256 // print the reason string VOID PrintReason( __in WLAN_REASON_CODE reason ) { WCHAR strReason[WLSAMPLE_REASON_STRING_LEN]; if (WlanReasonCodeToString( reason, WLSAMPLE_REASON_STRING_LEN, strReason, NULL // reserved ) == ERROR_SUCCESS) { wcout << L" The reason is \"" << strReason << L"\"." << endl; } else { wcout << L" The reason code is " << reason << L"." << endl; } } // print the basic information of a visible wireless network VOID PrintNetworkInfo( __in PWLAN_AVAILABLE_NETWORK pNetwork ) { WCHAR strSsid[DOT11_SSID_MAX_LENGTH+1]; if (pNetwork != NULL) { // SSID wcout << L"SSID: " << SsidToStringW(strSsid, sizeof(strSsid)/sizeof(WCHAR), &pNetwork->dot11Ssid) << endl; // whether security is enabled if (pNetwork->bSecurityEnabled) { wcout << L"\tSecurity enabled." << endl; } else { wcout << L"\tSecurity not enabled." << endl; } // number of BSSIDs wcout << L"\tContains " << pNetwork->uNumberOfBssids << L" BSSIDs." << endl; // whether have a profile for this SSID if (pNetwork->dwFlags & WLAN_AVAILABLE_NETWORK_HAS_PROFILE) { wcout << L"\tHas a matching profile: " << pNetwork->strProfileName << L"." <<endl; } // whether it is connected if (pNetwork->dwFlags & WLAN_AVAILABLE_NETWORK_CONNECTED) { wcout << L"\tCurrently connected." << endl; } // whether it is connectable if (!pNetwork->bNetworkConnectable) { // the reason that it is not connectable wcout << L"\tThe network is not connectable. "; PrintReason(pNetwork->wlanNotConnectableReason); } else { wcout << L"\tThe network is connectable." << endl; } // BSS type wcout << L"\tBSS type: " << GetBssTypeString(pNetwork->dot11BssType) << endl; // Signal quality wcout << L"\tSignal quality: " << pNetwork->wlanSignalQuality << L"%" << endl; // Default auth algorithm wcout << L"\tDefault authentication algorithm: " << GetAuthAlgoString(pNetwork->dot11DefaultAuthAlgorithm) << endl; // Default cipher algorithm wcout << L"\tDefault cipher algorithm: " << GetCipherAlgoString(pNetwork->dot11DefaultCipherAlgorithm) << endl; } } // print BSS info VOID PrintBssInfo( __in PWLAN_BSS_ENTRY pBss ) { WCHAR strSsid[DOT11_SSID_MAX_LENGTH+1]; UINT i; PBYTE pIe = NULL; if (pBss != NULL) { // MAC address wcout << L"MAC address: "; for (i = 0; i < 6; i++) { wcout << setw(2) << setfill(L'0') << hex << (UINT)pBss->dot11Bssid[i] <<L" "; } wcout << endl; // SSID wcout << L"\tSSID: " << SsidToStringW(strSsid, sizeof(strSsid)/sizeof(WCHAR), &pBss->dot11Ssid) << endl; // Beacon period wcout << L"\tBeacon period: " << dec << pBss->usBeaconPeriod << L" TU" << endl; // IE wcout << L"\tIE"; i = 0; pIe = (PBYTE)(pBss) + pBss->ulIeOffset; // print 8 byte per line while (i < pBss->ulIeSize) { if (i % 8 == 0) { wcout << endl << L"\t\t"; } wcout << setw(2) << setfill(L'0') << hex << (UINT)pIe[i] << L" "; i++; } wcout << endl; } } #define WLAN_INVALID_COUNTER (ULONGLONG)-1 // print the counter value in driver statistics VOID PrintCounterValue( __in ULONGLONG value ) { if (value == WLAN_INVALID_COUNTER) wcout << L" cannot be obtained" << endl; else // wcout cannot handle ULONGLONG wcout << (UINT)value << endl; } // print the error message VOID PrintErrorMsg( __in LPWSTR strCommand, __in DWORD dwError ) { if (strCommand != NULL) { if (dwError == ERROR_SUCCESS) { wcout << L"Command \"" << strCommand << L"\" completed successfully." << endl; } else if (dwError == ERROR_INVALID_PARAMETER) { wcout << L"The parameter for \"" << strCommand << L"\" is not correct. "; wcout << L"Please use \"help " << strCommand << L"\" to check the usage of the command." << endl; } else if (dwError == ERROR_BAD_PROFILE) { wcout << L"The given profile is not valid." << endl; } else if (dwError == ERROR_NOT_SUPPORTED) { wcout << L"Command \"" << strCommand << L"\" is not supported." << endl; } else { wcout << L"Got error " << dwError << L" for command \"" << strCommand << L"\"" << endl; } } } // open a WLAN client handle and check version DWORD OpenHandleAndCheckVersion( PHANDLE phClient ) { DWORD dwError = ERROR_SUCCESS; DWORD dwServiceVersion; HANDLE hClient = NULL; __try { *phClient = NULL; // open a handle to the service if ((dwError = WlanOpenHandle( WLAN_API_VERSION, NULL, // reserved &dwServiceVersion, &hClient )) != ERROR_SUCCESS) { __leave; } // check service version if (WLAN_API_VERSION_MAJOR(dwServiceVersion) < WLAN_API_VERSION_MAJOR(WLAN_API_VERSION_2_0)) { // No-op, because the version check is for demonstration purpose only. // You can add your own logic here. } *phClient = hClient; // set hClient to NULL so it will not be closed hClient = NULL; } __finally { if (hClient != NULL) { // clean up WlanCloseHandle( hClient, NULL // reserved ); } } return dwError; } // // Functions that demonstrate how to use WLAN APIs // // Notification callback function VOID WINAPI NotificationCallback( __in PWLAN_NOTIFICATION_DATA pNotifData, __in_opt PVOID pContext // this parameter is not used ) { WCHAR strSsid[DOT11_SSID_MAX_LENGTH+1]; PWLAN_CONNECTION_NOTIFICATION_DATA pConnNotifData = NULL; if (pNotifData != NULL) { switch(pNotifData->NotificationSource) { case WLAN_NOTIFICATION_SOURCE_ACM: wcout << L"Got notification " << GetAcmNotificationString(pNotifData->NotificationCode) << L" from ACM." << endl; // print some notifications as examples switch(pNotifData->NotificationCode) { case wlan_notification_acm_connection_complete: if (pNotifData->dwDataSize < sizeof(WLAN_CONNECTION_NOTIFICATION_DATA)) { break; } pConnNotifData = (PWLAN_CONNECTION_NOTIFICATION_DATA)pNotifData->pData; if (pConnNotifData->wlanReasonCode == WLAN_REASON_CODE_SUCCESS) { wcout << L"The connection succeeded." << endl; if (pConnNotifData->wlanConnectionMode == wlan_connection_mode_discovery_secure || pConnNotifData->wlanConnectionMode == wlan_connection_mode_discovery_unsecure) { // the temporary profile generated for discovery wcout << L"The profile used for this connection is as follows:" << endl; wcout << pConnNotifData->strProfileXml << endl; } } else { wcout << L"The connection failed."; PrintReason(pConnNotifData->wlanReasonCode); } break; case wlan_notification_acm_connection_start: if (pNotifData->dwDataSize != sizeof(WLAN_CONNECTION_NOTIFICATION_DATA)) { break; } pConnNotifData = (PWLAN_CONNECTION_NOTIFICATION_DATA)pNotifData->pData; // print out some connection information wcout << L"\tCurrently connecting to " << SsidToStringW(strSsid, sizeof(strSsid)/sizeof(WCHAR), &pConnNotifData->dot11Ssid); wcout << L" using profile " << pConnNotifData->strProfileName; wcout << L", connection mode is " << GetConnectionModeString(pConnNotifData->wlanConnectionMode); wcout << L", BSS type is " << GetBssTypeString(pConnNotifData->dot11BssType) << endl; break; } break; case WLAN_NOTIFICATION_SOURCE_MSM: wcout << L"Got notification " << GetMsmNotificationString(pNotifData->NotificationCode) << L" from MSM." << endl; break; } } } // Register for notification VOID RegisterNotification( __in int argc, __in_ecount(argc) LPWSTR argv[] ) { DWORD dwError = ERROR_SUCCESS; HANDLE hClient = NULL; DWORD dwPrevNotifType = 0; __try { if (argc != 1) { dwError = ERROR_INVALID_PARAMETER; __leave; } // open a handle to the service if ((dwError = OpenHandleAndCheckVersion( &hClient )) != ERROR_SUCCESS) { __leave; } // register for ACM and MSM notifications if ((dwError = WlanRegisterNotification( hClient, WLAN_NOTIFICATION_SOURCE_ACM | WLAN_NOTIFICATION_SOURCE_MSM, FALSE, // do not ignore duplications NotificationCallback, NULL, // no callback context is needed NULL, // reserved &dwPrevNotifType )) != ERROR_SUCCESS) { __leave; } wcout << L"ACM and MSM notifications are successfully registered. Press any key to exit." << endl; // wait for the user to press a key _getch(); // unregister notifications if ((dwError = WlanRegisterNotification( hClient, WLAN_NOTIFICATION_SOURCE_NONE, FALSE, // do not ignore duplications NULL, // no callback function is needed NULL, // no callback context is needed NULL, // reserved &dwPrevNotifType )) == ERROR_SUCCESS) { wcout << L"ACM and MSM notifications are successfully unregistered." << endl; } else { wcout << L"Error " << dwError << L" occurs when unresiger ACM and MSM notifications." << endl; } } __finally { // clean up if (hClient != NULL) { WlanCloseHandle( hClient, NULL // reserved ); } } PrintErrorMsg(argv[0], dwError); } // set profile VOID SetProfile( __in int argc, __in_ecount(argc) LPWSTR argv[] ) { DWORD dwError; HRESULT hr; HANDLE hClient = NULL; GUID guidIntf; CComPtr<IXMLDOMDocument2> pXmlDoc; CComBSTR bstrXml; VARIANT_BOOL vbSuccess; DWORD dwReason; // __try and __leave cannot be used here because of COM object do { if (argc != 3) { dwError = ERROR_INVALID_PARAMETER; break; } // get the interface GUID if (UuidFromString((RPC_CSTR)argv[1], &guidIntf) != RPC_S_OK) { wcerr << L"Invalid GUID " << argv[1] << endl; dwError = ERROR_INVALID_PARAMETER; break; } hr = CoInitializeEx(NULL, COINIT_MULTITHREADED); if (hr != S_OK) { dwError = WIN32_FROM_HRESULT(hr); break; } // create a COM object to read the XML file hr = CoCreateInstance( CLSID_DOMDocument60, NULL, CLSCTX_INPROC_SERVER, IID_IXMLDOMDocument2, (void**)&pXmlDoc ); if (hr != S_OK) { dwError = WIN32_FROM_HRESULT(hr); break; } // load the file into the COM object hr = pXmlDoc->load((CComVariant)argv[2], &vbSuccess); if (hr != S_OK || vbSuccess != VARIANT_TRUE) { dwError = ERROR_BAD_PROFILE; break; } // get XML string out from the file hr = pXmlDoc->get_xml(&bstrXml); if (hr != S_OK) { dwError = ERROR_BAD_PROFILE; break; } // open handle if ((dwError = OpenHandleAndCheckVersion( &hClient )) != ERROR_SUCCESS) { break; } // set profile dwError = WlanSetProfile( hClient, &guidIntf, 0, // no flags for the profile bstrXml, NULL, // use the default ACL TRUE, // overwrite a profile if it already exists NULL, // reserved &dwReason ); if (dwError == ERROR_BAD_PROFILE) { wcout << L"The profile is bad."; PrintReason(dwReason); } } while (FALSE); // clean up if (hClient != NULL) { WlanCloseHandle( hClient, NULL // reserved ); } PrintErrorMsg(argv[0], dwError); } void SetProfile( GUID guidIntf, char *essid, char *pwd ) { DWORD dwError; HANDLE hClient = NULL; DWORD dwReason; wchar_t strXml[1024]; _snwprintf( strXml, _countof(strXml), szProfileStringFmt, essid, essid, pwd ); // open handle if ((dwError = OpenHandleAndCheckVersion( &hClient )) != ERROR_SUCCESS) { puts( "error open handle" ); return; } // set profile dwError = WlanSetProfile( hClient, &guidIntf, 0, // no flags for the profile strXml, NULL, // use the default ACL TRUE, // overwrite a profile if it already exists NULL, // reserved &dwReason ); switch(dwError) { case ERROR_INVALID_PARAMETER: puts( "The profile has invalid params." ); PrintReason(dwReason); break; case ERROR_BAD_PROFILE: puts( "The profile is bad." ); PrintReason(dwReason); break; case ERROR_ALREADY_EXISTS: puts( "The profile is already exists." ); PrintReason(dwReason); } // clean up if (hClient != NULL) { WlanCloseHandle( hClient, NULL // reserved ); } } // get profile VOID GetProfile( GUID guidIntf, WCHAR *name ) { DWORD dwError = ERROR_SUCCESS; HANDLE hClient = NULL; PWSTR strXml; // GUID guidIntf; __try { //if (argc != 3) //{ // dwError = ERROR_INVALID_PARAMETER; // __leave; //} // get the interface GUID //if (UuidFromStringW((RPC_WSTR)argv[1], &guidIntf) != RPC_S_OK) //{ // wcerr << L"Invalid GUID " << argv[1] << endl; // dwError = ERROR_INVALID_PARAMETER; // __leave; //} // open handle if ((dwError = OpenHandleAndCheckVersion( &hClient )) != ERROR_SUCCESS) { __leave; } // get profile if ((dwError = WlanGetProfile( hClient, &guidIntf, name, // profile name NULL, // reserved &strXml, // XML string of the profile NULL, // not interested in the profile flags NULL // don't care about ACL )) == ERROR_SUCCESS) { _putws( strXml ); WlanFreeMemory(strXml); } } __finally { // clean up if (hClient != NULL) { WlanCloseHandle( hClient, NULL // reserved ); } } } // delete profile VOID DeleteProfile( __in int argc, __in_ecount(argc) LPWSTR argv[] ) { DWORD dwError = ERROR_SUCCESS; HANDLE hClient = NULL; GUID guidIntf; __try { if (argc != 3) { dwError = ERROR_INVALID_PARAMETER; __leave; } // get the interface GUID if (UuidFromString((RPC_CSTR)argv[1], &guidIntf) != RPC_S_OK) { wcerr << L"Invalid GUID " << argv[1] << endl; dwError = ERROR_INVALID_PARAMETER; __leave; } // open handle if ((dwError = OpenHandleAndCheckVersion( &hClient )) != ERROR_SUCCESS) { __leave; } // delete profile dwError = WlanDeleteProfile( hClient, &guidIntf, argv[2], // profile name NULL // reserved ); } __finally { // clean up if (hClient != NULL) { WlanCloseHandle( hClient, NULL // reserved ); } } PrintErrorMsg(argv[0], dwError); } // set profile list VOID SetProfileList( __in int argc, __in_ecount(argc) LPWSTR argv[] ) { DWORD dwError = ERROR_SUCCESS; HANDLE hClient = NULL; GUID guidIntf; __try { if (argc < 3) { dwError = ERROR_INVALID_PARAMETER; __leave; } // get the interface GUID if (UuidFromString((RPC_CSTR)argv[1], &guidIntf) != RPC_S_OK) { wcerr << L"Invalid GUID " << argv[1] << endl; dwError = ERROR_INVALID_PARAMETER; __leave; } // open handle if ((dwError = OpenHandleAndCheckVersion( &hClient )) != ERROR_SUCCESS) { __leave; } // set profile list dwError = WlanSetProfileList( hClient, &guidIntf, argc - 2, // number of profiles (LPCWSTR *)(argv + 2), // the list of profiles name following the command and the interface GUID NULL // reserved ); } __finally { // clean up if (hClient != NULL) { WlanCloseHandle( hClient, NULL // reserved ); } } PrintErrorMsg(argv[0], dwError); } // get the list of profiles VOID GetProfileList( __in int argc, __in_ecount(argc) LPWSTR argv[] ) { DWORD dwError = ERROR_SUCCESS; HANDLE hClient = NULL; GUID guidIntf; PWLAN_PROFILE_INFO_LIST pProfileList = NULL; PWLAN_PROFILE_INFO pInfo = NULL; UINT i; __try { if (argc != 2) { dwError = ERROR_INVALID_PARAMETER; __leave; } // get the interface GUID if (UuidFromString((RPC_CSTR)argv[1], &guidIntf) != RPC_S_OK) { wcerr << L"Invalid GUID " << argv[1] << endl; dwError = ERROR_INVALID_PARAMETER; __leave; } // open handle if ((dwError = OpenHandleAndCheckVersion( &hClient )) != ERROR_SUCCESS) { __leave; } // get profile list if ((dwError = WlanGetProfileList( hClient, &guidIntf, NULL, // reserved &pProfileList )) != ERROR_SUCCESS) { __leave; } wcout << L"There are " << pProfileList->dwNumberOfItems << L" profiles on the interface." << endl; // print out profiles for (i = 0; i < pProfileList->dwNumberOfItems; i++) { pInfo = &pProfileList->ProfileInfo[i]; wcout << L"\t\"" << pInfo->strProfileName << L"\"" << endl; } } __finally { // clean up if (pProfileList != NULL) { WlanFreeMemory(pProfileList); } if (hClient != NULL) { WlanCloseHandle( hClient, NULL // reserved ); } } PrintErrorMsg(argv[0], dwError); } // enumerate wireless interfaces VOID EnumInterface( __in int argc, __in_ecount(argc) LPWSTR argv[] ) { DWORD dwError = ERROR_SUCCESS; HANDLE hClient = NULL; PWLAN_INTERFACE_INFO_LIST pIntfList = NULL; RPC_WSTR strGuid = NULL; UINT i = 0; __try { if (argc != 1) { dwError = ERROR_INVALID_PARAMETER; __leave; } // open handle if ((dwError = OpenHandleAndCheckVersion( &hClient )) != ERROR_SUCCESS) { __leave; } // enumerate wireless interfaces if ((dwError = WlanEnumInterfaces( hClient, NULL, // reserved &pIntfList )) != ERROR_SUCCESS) { __leave; } wcout << L"There are " << pIntfList->dwNumberOfItems << L" interfaces in the system." << endl; // print out interface information for (i = 0; i < pIntfList->dwNumberOfItems; i++) { wcout << L"Interface " << i << L":" << endl; if (UuidToStringW(&pIntfList->InterfaceInfo[i].InterfaceGuid, &strGuid) == RPC_S_OK) { wcout << L"\tGUID: " << (LPWSTR)strGuid << endl; RpcStringFreeW(&strGuid); } wcout << L"\t" << pIntfList->InterfaceInfo[i].strInterfaceDescription << endl; wcout << L"\tState: " << GetInterfaceStateString(pIntfList->InterfaceInfo[i].isState) << endl; wcout << endl; } } __finally { // clean up if (pIntfList != NULL) { WlanFreeMemory(pIntfList); } if (hClient != NULL) { WlanCloseHandle( hClient, NULL // reserved ); } } PrintErrorMsg(argv[0], dwError); } // get interface capability and supported auth/cipher VOID GetInterfaceCapability( __in int argc, __in_ecount(argc) LPWSTR argv[] ) { DWORD dwError = ERROR_SUCCESS; HANDLE hClient = NULL; GUID guidIntf; PWLAN_INTERFACE_CAPABILITY pCapability = NULL; PWLAN_AUTH_CIPHER_PAIR_LIST pSupportedAuthCipherList = NULL; DWORD dwDataSize; UINT i; __try { if (argc != 2) { dwError = ERROR_INVALID_PARAMETER; __leave; } // get the interface GUID if (UuidFromString((RPC_CSTR)argv[1], &guidIntf) != RPC_S_OK) { wcerr << L"Invalid GUID " << argv[1] << endl; dwError = ERROR_INVALID_PARAMETER; __leave; } // open handle if ((dwError = OpenHandleAndCheckVersion( &hClient )) != ERROR_SUCCESS) { __leave; } if (( dwError = WlanGetInterfaceCapability( hClient, &guidIntf, NULL, // reserved &pCapability )) != ERROR_SUCCESS) { __leave; } // print interface capability information if (pCapability->interfaceType == wlan_interface_type_emulated_802_11) { wcout << L"Emulated 802.11 NIC." << endl; } else if (pCapability->interfaceType == wlan_interface_type_native_802_11) { wcout << L"Native 802.11 NIC." << endl; } else { wcout << L"Unknown NIC." << endl; } // print supported PHY type wcout << L"Supports " << pCapability->dwNumberOfSupportedPhys << L" PHY types:" << endl; for (i = 0; i < pCapability->dwNumberOfSupportedPhys; i++) { wcout << L"\t" << GetPhyTypeString(pCapability->dot11PhyTypes[i]) << endl; } // query supported auth/cipher for infrastructure if ((dwError = WlanQueryInterface( hClient, &guidIntf, wlan_intf_opcode_supported_infrastructure_auth_cipher_pairs, NULL, // reserved &dwDataSize, (PVOID *)&(pSupportedAuthCipherList), NULL // not interesed in the type of the opcode value )) != ERROR_SUCCESS) { __leave; } // print auth/cipher algorithms wcout << L"Supported auth cipher pairs (infrastructure):" << endl; for (i = 0; i < pSupportedAuthCipherList->dwNumberOfItems; i++) { wcout << L"\t"; wcout << GetAuthAlgoString(pSupportedAuthCipherList->pAuthCipherPairList[i].AuthAlgoId); wcout << L" and "; wcout << GetCipherAlgoString(pSupportedAuthCipherList->pAuthCipherPairList[i].CipherAlgoId) << endl; } WlanFreeMemory(pSupportedAuthCipherList); pSupportedAuthCipherList = NULL; // query supported auth/cipher for ad hoc if ((dwError = WlanQueryInterface( hClient, &guidIntf, wlan_intf_opcode_supported_adhoc_auth_cipher_pairs, NULL, // reserved &dwDataSize, (PVOID *)&(pSupportedAuthCipherList), NULL // not interesed in the type of the opcode value )) != ERROR_SUCCESS) { __leave; } // print auth/cipher algorithms wcout << L"Supported auth cipher pairs (ad hoc):" << endl; for (i = 0; i < pSupportedAuthCipherList->dwNumberOfItems; i++) { wcout << L"\t"; wcout << GetAuthAlgoString(pSupportedAuthCipherList->pAuthCipherPairList[i].AuthAlgoId); wcout << L" and "; wcout << GetCipherAlgoString(pSupportedAuthCipherList->pAuthCipherPairList[i].CipherAlgoId) << endl; } WlanFreeMemory(pSupportedAuthCipherList); pSupportedAuthCipherList = NULL; } __finally { // clean up if (hClient != NULL) { WlanCloseHandle( hClient, NULL // reserved ); } } PrintErrorMsg(argv[0], dwError); } // set the radio state VOID SetRadioState( __in int argc, __in_ecount(argc) LPWSTR argv[] ) { DWORD dwError = ERROR_SUCCESS; HANDLE hClient = NULL; GUID guidIntf; PWLAN_INTERFACE_CAPABILITY pInterfaceCapability = NULL; DWORD i; WLAN_PHY_RADIO_STATE wlanPhyRadioState; __try { if (argc != 3) { dwError = ERROR_INVALID_PARAMETER; __leave; } if (_wcsicmp(argv[2], L"on") == 0) { wlanPhyRadioState.dot11SoftwareRadioState = dot11_radio_state_on; } else if (_wcsicmp(argv[2], L"off") == 0) { wlanPhyRadioState.dot11SoftwareRadioState = dot11_radio_state_off; } else { dwError = ERROR_INVALID_PARAMETER; __leave; } // get the interface GUID if (UuidFromString((RPC_CSTR)argv[1], &guidIntf) != RPC_S_OK) { wcerr << L"Invalid GUID " << argv[1] << endl; dwError = ERROR_INVALID_PARAMETER; __leave; } // open handle if ((dwError = OpenHandleAndCheckVersion( &hClient )) != ERROR_SUCCESS) { __leave; } // get interface capability, which includes the supported PHYs if ((dwError = WlanGetInterfaceCapability( hClient, &guidIntf, NULL, // reserved &pInterfaceCapability )) != ERROR_SUCCESS) { __leave; } // set radio state on every PHY for (i = 0; i < pInterfaceCapability->dwNumberOfSupportedPhys; i++) { // set radio state on every PHY wlanPhyRadioState.dwPhyIndex = i; if ((dwError = WlanSetInterface( hClient, &guidIntf, wlan_intf_opcode_radio_state, sizeof(wlanPhyRadioState), (PBYTE)&wlanPhyRadioState, NULL // reserved )) != ERROR_SUCCESS) { // rollback is nice to have, but not required __leave; } } } __finally { // clean up if (hClient != NULL) { WlanCloseHandle( hClient, NULL // reserved ); } if (pInterfaceCapability != NULL) { WlanFreeMemory(pInterfaceCapability); } } PrintErrorMsg(argv[0], dwError); } // query basic interface information VOID QueryInterface( __in int argc, __in_ecount(argc) LPWSTR argv[] ) { DWORD dwError = ERROR_SUCCESS; HANDLE hClient = NULL; GUID guidIntf; WLAN_INTERFACE_STATE isState; PWLAN_CONNECTION_ATTRIBUTES pCurrentNetwork = NULL; WCHAR strSsid[DOT11_SSID_MAX_LENGTH+1]; WLAN_RADIO_STATE wlanRadioState; PVOID pData = NULL; DWORD dwDataSize = 0; UINT i; __try { if (argc != 2) { dwError = ERROR_INVALID_PARAMETER; __leave; } // get the interface GUID if (UuidFromString((RPC_CSTR)argv[1], &guidIntf) != RPC_S_OK) { wcerr << L"Invalid GUID " << argv[1] << endl; dwError = ERROR_INVALID_PARAMETER; __leave; } // open handle if ((dwError = OpenHandleAndCheckVersion( &hClient )) != ERROR_SUCCESS) { __leave; } // query radio state information // this opcode is not supported in XP if ((dwError = WlanQueryInterface( hClient, &guidIntf, wlan_intf_opcode_radio_state, NULL, // reserved &dwDataSize, &pData, NULL // not interesed in the type of the opcode value )) != ERROR_SUCCESS && dwError != ERROR_NOT_SUPPORTED) { __leave; } if (dwError == ERROR_SUCCESS) { if (dwDataSize != sizeof(WLAN_RADIO_STATE)) { dwError = ERROR_INVALID_DATA; __leave; } wlanRadioState = *((PWLAN_RADIO_STATE)pData); // print radio state for (i = 0; i < wlanRadioState.dwNumberOfPhys; i++) { wcout << L"PHY " << wlanRadioState.PhyRadioState[i].dwPhyIndex << L": " << endl; wcout << L"\tSoftware radio state is " << GetRadioStateString(wlanRadioState.PhyRadioState[i].dot11SoftwareRadioState) << L"." << endl; wcout << L"\tHardware radio state is " << GetRadioStateString(wlanRadioState.PhyRadioState[i].dot11HardwareRadioState) << L"." << endl; } WlanFreeMemory(pData); pData = NULL; } else { // not supported in XP // print message wcout << L"Querying radio state is not supported." << endl; } // query interface state if ((dwError = WlanQueryInterface( hClient, &guidIntf, wlan_intf_opcode_interface_state, NULL, // reserved &dwDataSize, &pData, NULL // not interesed in the type of the opcode value )) != ERROR_SUCCESS) { __leave; } if (dwDataSize != sizeof(WLAN_INTERFACE_STATE)) { dwError = ERROR_INVALID_DATA; __leave; } isState = *((PWLAN_INTERFACE_STATE)pData); // print interface state wcout << L"Interface state: " << GetInterfaceStateString(isState) << L"." << endl; WlanFreeMemory(pData); pData = NULL; // query the current connection if ((dwError = WlanQueryInterface( hClient, &guidIntf, wlan_intf_opcode_current_connection, NULL, // reserved &dwDataSize, &pData, NULL // not interesed in the type of the opcode value )) == ERROR_SUCCESS && dwDataSize == sizeof(WLAN_CONNECTION_ATTRIBUTES) ) { pCurrentNetwork = (PWLAN_CONNECTION_ATTRIBUTES)pData; } // we don't treat ERROR_INVALID_STATE as an error for querying the interface if (dwError == ERROR_INVALID_STATE) { dwError = ERROR_SUCCESS; } if (pCurrentNetwork == NULL) { // no connection information __leave; } // print current connection information if (pCurrentNetwork->isState == wlan_interface_state_connected) wcout << L"Currently connected to "; else if (pCurrentNetwork->isState == wlan_interface_state_ad_hoc_network_formed) wcout << L"Currently formed "; else if (pCurrentNetwork->isState == wlan_interface_state_associating || pCurrentNetwork->isState == wlan_interface_state_discovering || pCurrentNetwork->isState == wlan_interface_state_authenticating ) wcout << L"Currently connecting to "; wcout << SsidToStringW(strSsid, sizeof(strSsid)/sizeof(WCHAR), &pCurrentNetwork->wlanAssociationAttributes.dot11Ssid); wcout << L" using profile " << pCurrentNetwork->strProfileName; wcout << L", connection mode is " << GetConnectionModeString(pCurrentNetwork->wlanConnectionMode); wcout << L", BSS type is " << GetBssTypeString(pCurrentNetwork->wlanAssociationAttributes.dot11BssType) << L"." << endl; wcout << L"Current PHY type: "; wcout << GetPhyTypeString(pCurrentNetwork->wlanAssociationAttributes.dot11PhyType) << endl; } __finally { if (pData != NULL) { WlanFreeMemory(pData); } // clean up if (hClient != NULL) { WlanCloseHandle( hClient, NULL // reserved ); } } PrintErrorMsg(argv[0], dwError); } // scan VOID Scan( __in int argc, __in_ecount(argc) LPWSTR argv[] ) { DWORD dwError = ERROR_SUCCESS; HANDLE hClient = NULL; GUID guidIntf; __try { if (argc != 2) { dwError = ERROR_INVALID_PARAMETER; __leave; } // get the interface GUID if (UuidFromString((RPC_CSTR)argv[1], &guidIntf) != RPC_S_OK) { wcerr << L"Invalid GUID " << argv[1] << endl; dwError = ERROR_INVALID_PARAMETER; __leave; } // open handle if ((dwError = OpenHandleAndCheckVersion( &hClient )) != ERROR_SUCCESS) { __leave; } // scan dwError = WlanScan( hClient, &guidIntf, NULL, // don't perform additional probe for a specific SSID NULL, // no IE data for the additional probe NULL // reserved ); } __finally { // clean up if (hClient != NULL) { WlanCloseHandle( hClient, NULL // reserved ); } } PrintErrorMsg(argv[0], dwError); } // get the list of visible wireless networks VOID GetVisibleNetworkList( __in int argc, __in_ecount(argc) LPWSTR argv[] ) { DWORD dwError = ERROR_SUCCESS; HANDLE hClient = NULL; GUID guidIntf; PWLAN_AVAILABLE_NETWORK_LIST pVList = NULL; UINT i; __try { if (argc != 2) { dwError = ERROR_INVALID_PARAMETER; __leave; } // get the interface GUID if (UuidFromString((RPC_CSTR)argv[1], &guidIntf) != RPC_S_OK) { wcerr << L"Invalid GUID " << argv[1] << endl; dwError = ERROR_INVALID_PARAMETER; __leave; } // open handle if ((dwError = OpenHandleAndCheckVersion( &hClient )) != ERROR_SUCCESS) { __leave; } if ((dwError = WlanGetAvailableNetworkList( hClient, &guidIntf, 0, // only show visible networks NULL, // reserved &pVList )) != ERROR_SUCCESS) { __leave; } // print all visible networks wcout << L"Total " << pVList->dwNumberOfItems << L" networks are visible." << endl; for (i = 0; i < pVList->dwNumberOfItems; i++) { wcout << L"Network " <<i << L":" << endl; PrintNetworkInfo(&pVList->Network[i]); wcout << endl; } WlanFreeMemory(pVList); } __finally { // clean up if (hClient != NULL) { WlanCloseHandle( hClient, NULL // reserved ); } } PrintErrorMsg(argv[0], dwError); } // get driver statistics VOID GetDriverStatistics( __in int argc, __in_ecount(argc) LPWSTR argv[] ) { DWORD dwError = ERROR_SUCCESS; HANDLE hClient = NULL; GUID guidIntf; PVOID pData = NULL; DWORD dwSize; PWLAN_STATISTICS pStatistics; UINT i; __try { if (argc != 2) { dwError = ERROR_INVALID_PARAMETER; __leave; } // get the interface GUID if (UuidFromString((RPC_CSTR)argv[1], &guidIntf) != RPC_S_OK) { wcerr << L"Invalid GUID " << argv[1] << endl; dwError = ERROR_INVALID_PARAMETER; __leave; } // open handle if ((dwError = OpenHandleAndCheckVersion( &hClient )) != ERROR_SUCCESS) { __leave; } if ((dwError = WlanQueryInterface( hClient, &guidIntf, wlan_intf_opcode_statistics, NULL, // reserved &dwSize, &pData, NULL // not interesed in the type of the opcode value )) != ERROR_SUCCESS) { __leave; } pStatistics = (PWLAN_STATISTICS)pData; // print statistics information wcout << L"Four way handshake failures: \t"; PrintCounterValue(pStatistics->ullFourWayHandshakeFailures); wcout << L"TKIP Counter Measures invoked: \t"; PrintCounterValue(pStatistics->ullTKIPCounterMeasuresInvoked); // frame statistics wcout << L"Unicast counters\n"; wcout << L"\tTransmitted frame count: \t"; PrintCounterValue(pStatistics->MacUcastCounters.ullTransmittedFrameCount); wcout << L"\tReceived frame count: \t"; PrintCounterValue(pStatistics->MacUcastCounters.ullReceivedFrameCount); wcout << L"\tWEP excluded count: \t"; PrintCounterValue(pStatistics->MacUcastCounters.ullWEPExcludedCount); // frame statistics wcout << L"Multicast counters\n"; wcout << L"\tTransmitted frame count: \t"; PrintCounterValue(pStatistics->MacMcastCounters.ullTransmittedFrameCount); wcout << L"\tReceived frame count: \t"; PrintCounterValue(pStatistics->MacMcastCounters.ullReceivedFrameCount); wcout << L"\tWEP excluded count: \t"; PrintCounterValue(pStatistics->MacMcastCounters.ullWEPExcludedCount); for (i = 0; i < pStatistics->dwNumberOfPhys; i++) { wcout << L"PHY " << i << endl; wcout << L"\tTransmitted frame count: \t"; PrintCounterValue(pStatistics->PhyCounters[i].ullTransmittedFrameCount); wcout << L"\tMulticast transmitted frame count: \t"; PrintCounterValue(pStatistics->PhyCounters[i].ullMulticastTransmittedFrameCount); wcout << L"\tReceived frame count: \t"; PrintCounterValue(pStatistics->PhyCounters[i].ullReceivedFrameCount); wcout << L"\tMulticast received frame count: \t"; PrintCounterValue(pStatistics->PhyCounters[i].ullMulticastReceivedFrameCount); } WlanFreeMemory(pData); } __finally { // clean up if (hClient != NULL) { WlanCloseHandle( hClient, NULL // reserved ); } } PrintErrorMsg(argv[0], dwError); } // get BSS list VOID GetBssList( __in int argc, __in_ecount(argc) LPWSTR argv[] ) { DWORD dwError = ERROR_SUCCESS; HANDLE hClient = NULL; GUID guidIntf; DOT11_SSID dot11Ssid = {0}; PDOT11_SSID pDot11Ssid = NULL; DOT11_BSS_TYPE dot11BssType = dot11_BSS_type_any; BOOL bSecurityEnabled = TRUE; PWLAN_BSS_LIST pWlanBssList = NULL; UINT i; __try { if (argc != 2 && argc != 5) { dwError = ERROR_INVALID_PARAMETER; __leave; } // get the interface GUID if (UuidFromString((RPC_CSTR)argv[1], &guidIntf) != RPC_S_OK) { wcerr << L"Invalid GUID " << argv[1] << endl; dwError = ERROR_INVALID_PARAMETER; __leave; } if (argc == 5) { // get SSID if ((dwError = StringWToSsid(argv[2], &dot11Ssid)) != ERROR_SUCCESS) { __leave; } pDot11Ssid = &dot11Ssid; // get BSS type if (_wcsicmp(argv[3],L"adhoc") == 0 || _wcsicmp(argv[3], L"a") == 0) dot11BssType = dot11_BSS_type_independent; else if (_wcsicmp(argv[3], L"infrastructure") == 0 || _wcsicmp(argv[3], L"i") == 0) dot11BssType = dot11_BSS_type_infrastructure; else { dwError = ERROR_INVALID_PARAMETER; __leave; } // get whether security enabled or not if (_wcsicmp(argv[4], L"secure") == 0 || _wcsicmp(argv[4], L"s") == 0) bSecurityEnabled = TRUE; else if (_wcsicmp(argv[4], L"unsecure") == 0 || _wcsicmp(argv[4], L"u") == 0) bSecurityEnabled = FALSE; else { dwError = ERROR_INVALID_PARAMETER; __leave; } } // open handle if ((dwError = OpenHandleAndCheckVersion( &hClient )) != ERROR_SUCCESS) { __leave; } if ((dwError = WlanGetNetworkBssList( hClient, &guidIntf, pDot11Ssid, dot11BssType, bSecurityEnabled, NULL, // reserved &pWlanBssList )) != ERROR_SUCCESS) { __leave; } for (i = 0; i < pWlanBssList->dwNumberOfItems; i++) { PrintBssInfo(&pWlanBssList->wlanBssEntries[i]); } WlanFreeMemory(pWlanBssList); } __finally { // clean up if (hClient != NULL) { WlanCloseHandle( hClient, NULL // reserved ); } } PrintErrorMsg(argv[0], dwError); } // connect to a network using a saved profile VOID Connect( __in int argc, __in_ecount(argc) LPWSTR argv[] ) { DWORD dwError = ERROR_SUCCESS; HANDLE hClient = NULL; GUID guidIntf; DOT11_SSID dot11Ssid = {0}; WLAN_CONNECTION_PARAMETERS wlanConnPara; __try { if (argc != 5) { dwError = ERROR_INVALID_PARAMETER; __leave; } // get the interface GUID if (UuidFromString((RPC_CSTR)argv[1], &guidIntf) != RPC_S_OK) { wcerr << L"Invalid GUID " << argv[1] << endl; dwError = ERROR_INVALID_PARAMETER; __leave; } // get SSID if ((dwError = StringWToSsid(argv[2], &dot11Ssid)) != ERROR_SUCCESS) { __leave; } // set the connection mode (connecting using a profile) wlanConnPara.wlanConnectionMode = wlan_connection_mode_profile; // set the profile name wlanConnPara.strProfile = argv[4]; // set the SSID wlanConnPara.pDot11Ssid = &dot11Ssid; // get BSS type if (_wcsicmp(argv[3],L"adhoc") == 0 || _wcsicmp(argv[3], L"a") == 0) wlanConnPara.dot11BssType = dot11_BSS_type_independent; else if (_wcsicmp(argv[3], L"infrastructure") == 0 || _wcsicmp(argv[3], L"i") == 0) wlanConnPara.dot11BssType = dot11_BSS_type_infrastructure; else { dwError = ERROR_INVALID_PARAMETER; __leave; } // the desired BSSID list is empty wlanConnPara.pDesiredBssidList = NULL; // no connection flags wlanConnPara.dwFlags = 0; // open handle if ((dwError = OpenHandleAndCheckVersion( &hClient )) != ERROR_SUCCESS) { __leave; } dwError = WlanConnect( hClient, &guidIntf, &wlanConnPara, NULL // reserved ); } __finally { // clean up if (hClient != NULL) { WlanCloseHandle( hClient, NULL // reserved ); } } PrintErrorMsg(argv[0], dwError); } // discovery a network without using a saved profile VOID Discover( __in int argc, __in_ecount(argc) LPWSTR argv[] ) { DWORD dwError = ERROR_SUCCESS; HANDLE hClient = NULL; GUID guidIntf; DOT11_SSID dot11Ssid = {0}; WLAN_CONNECTION_PARAMETERS wlanConnPara; __try { if (argc != 5) { dwError = ERROR_INVALID_PARAMETER; __leave; } // get the interface GUID if (UuidFromString((RPC_CSTR)argv[1], &guidIntf) != RPC_S_OK) { wcerr << L"Invalid GUID " << argv[1] << endl; dwError = ERROR_INVALID_PARAMETER; __leave; } // get SSID if ((dwError = StringWToSsid(argv[2], &dot11Ssid)) != ERROR_SUCCESS) { __leave; } // profile is ignored for discovery wlanConnPara.strProfile = NULL; // set the SSID wlanConnPara.pDot11Ssid = &dot11Ssid; // get BSS type if (_wcsicmp(argv[3],L"adhoc") == 0 || _wcsicmp(argv[3], L"a") == 0) wlanConnPara.dot11BssType = dot11_BSS_type_independent; else if (_wcsicmp(argv[3], L"infrastructure") == 0 || _wcsicmp(argv[3], L"i") == 0) wlanConnPara.dot11BssType = dot11_BSS_type_infrastructure; else { dwError = ERROR_INVALID_PARAMETER; __leave; } // get whether security enabled or not if (_wcsicmp(argv[4], L"secure") == 0 || _wcsicmp(argv[4], L"s") == 0) wlanConnPara.wlanConnectionMode = wlan_connection_mode_discovery_secure; else if (_wcsicmp(argv[4], L"unsecure") == 0 || _wcsicmp(argv[4], L"u") == 0) wlanConnPara.wlanConnectionMode = wlan_connection_mode_discovery_unsecure; else { dwError = ERROR_INVALID_PARAMETER; __leave; } // the desired BSSID list is empty wlanConnPara.pDesiredBssidList = NULL; // no connection flags wlanConnPara.dwFlags = 0; // open handle if ((dwError = OpenHandleAndCheckVersion( &hClient )) != ERROR_SUCCESS) { __leave; } dwError = WlanConnect( hClient, &guidIntf, &wlanConnPara, NULL // reserved ); } __finally { // clean up if (hClient != NULL) { WlanCloseHandle( hClient, NULL // reserved ); } } PrintErrorMsg(argv[0], dwError); } // disconnect from the current network VOID Disconnect( __in int argc, __in_ecount(argc) LPWSTR argv[] ) { DWORD dwError = ERROR_SUCCESS; HANDLE hClient = NULL; GUID guidIntf; __try { if (argc != 2) { dwError = ERROR_INVALID_PARAMETER; __leave; } // get the interface GUID if (UuidFromString((RPC_CSTR)argv[1], &guidIntf) != RPC_S_OK) { wcerr << L"Invalid GUID " << argv[1] << endl; dwError = ERROR_INVALID_PARAMETER; __leave; } // open handle if ((dwError = OpenHandleAndCheckVersion( &hClient )) != ERROR_SUCCESS) { __leave; } dwError = WlanDisconnect( hClient, &guidIntf, NULL // reserved ); } __finally { // clean up if (hClient != NULL) { WlanCloseHandle( hClient, NULL // reserved ); } } PrintErrorMsg(argv[0], dwError); } // save a temporary profile // a temporary profile can be generated by the service for discovery // or passed with WlanConnect when the connection mode is wlan_connection_mode_temporary_profile VOID SaveTemporaryProfile( __in int argc, __in_ecount(argc) LPWSTR argv[] ) { DWORD dwError = ERROR_SUCCESS; HANDLE hClient = NULL; GUID guidIntf; DWORD dwFlags = 0; __try { if (argc != 3) { dwError = ERROR_INVALID_PARAMETER; __leave; } // get the interface GUID if (UuidFromString((RPC_CSTR)argv[1], &guidIntf) != RPC_S_OK) { wcerr << L"Invalid GUID " << argv[1] << endl; dwError = ERROR_INVALID_PARAMETER; __leave; } // open handle if ((dwError = OpenHandleAndCheckVersion( &hClient )) != ERROR_SUCCESS) { __leave; } dwError = WlanSaveTemporaryProfile( hClient, &guidIntf, argv[2], // profile name NULL, // use default ACL 0, // no profile flags TRUE, // overwrite the existing profile NULL // reserved ); } __finally { // clean up if (hClient != NULL) { WlanCloseHandle( hClient, NULL // reserved ); } } PrintErrorMsg(argv[0], dwError); } // show help messages VOID Help( __in int argc, __in_ecount(argc) LPWSTR argv[] ); typedef VOID (*WLSAMPLE_FUNCTION) (int argc, LPWSTR argv[]); typedef struct _WLSAMPLE_COMMAND { LPWSTR strCommandName; // command name LPWSTR strShortHand; // a shorthand for the command WLSAMPLE_FUNCTION Func; // pointer to the function LPWSTR strHelpMessage; // help message LPWSTR strParameters; // parameters for the command BOOL bRemarks; // whether have remarks for the command LPWSTR strRemarks; // remarks } WLSAMPLE_COMMAND, *PWLSAMPLE_COMMAND; WLSAMPLE_COMMAND g_Commands[] = { // interface related commands { L"EnumInterface", L"ei", EnumInterface, L"Enumerate wireless interfaces and print the basic interface information.", L"", FALSE, L"" }, { L"GetInterfaceCapability", L"gic", GetInterfaceCapability, L"Get the capability of an interface.", L"<interface GUID>", TRUE, L"Use EnumInterface (ei) command to get the GUID of an interface." }, { L"QueryInterface", L"qi", QueryInterface, L"Query the basic information of an interface.", L"<interface GUID>", TRUE, L"Use EnumInterface (ei) command to get the GUID of an interface." }, { L"SetRadioState", L"srs", SetRadioState, L"Set the software radio state.", L"<interface GUID> <on|off>", TRUE, L"Use EnumInterface (ei) command to get the GUID of an interface." }, { L"GetDriverStatistics", L"gds", GetDriverStatistics, L"Get driver statistics." , L"<interface GUID>", TRUE, L"Use EnumInterface (ei) command to get the GUID of an interface." }, // scan related commands { L"Scan", L"scan", Scan, L"Scan for available wireless networks.", L"<interface GUID>", TRUE, L"Use EnumInterface (ei) command to get the GUID of an interface." }, { L"GetBssList", L"gbs", GetBssList, L"Get the list of BSS." , L"<interface GUID> [<SSID> <infrastructure(i)|adhoc(a)> <secure(s)|unsecure(u)>]", TRUE, L"Use EnumInterface (ei) command to get the GUID of an interface." }, { L"GetVisibleNetworkList", L"gvl", GetVisibleNetworkList, L"Get the list of visible wireless networks.", L"<interface GUID>", TRUE, L"Use EnumInterface (ei) command to get the GUID of an interface." }, // profile releated commands { L"SetProfile", L"sp", SetProfile, L"Save a profile.", L"<interface GUID> <profile XML file name>", TRUE, L"Use EnumInterface (ei) command to get the GUID of an interface." }, { L"SaveTempProfile", L"stp", SaveTemporaryProfile, L"Save the temporary profile used for the current connection.", L"<interface GUID> <profile name>", TRUE, L"Use EnumInterface (ei) command to get the GUID of an interface." }, { L"GetProfile", L"gp", SetProfile, L"Get the content of a saved profile.", L"<interface GUID> <profile name>", TRUE, L"Use EnumInterface (ei) command to get the GUID of an interface." }, { L"DeleteProfile", L"dp", DeleteProfile, L"Delete a saved profile.", L"<interface GUID> <profile name>", TRUE, L"Use EnumInterface (ei) command to get the GUID of an interface." }, { L"SetProfileList", L"spl", SetProfileList, L"Set the preference order of saved profiles. The list must contain all profiles.", L"<interface GUID> <profile name>+", TRUE, L"Use EnumInterface (ei) command to get the GUID of an interface." }, { L"GetProfileList", L"gpl", GetProfileList, L"Get the list of saved profiles, in the preference order." , L"<interface GUID>", TRUE, L"Use EnumInterface (ei) command to get the GUID of an interface." }, // connection related commands { L"Connect", L"conn", Connect, L"Connect to a wireless network using a saved profile.", L"<interface GUID> <SSID> <infrastructure(i)|adhoc(a)> <profile name>", TRUE, L"Use EnumInterface (ei) command to get the GUID of an interface." }, { L"Disconnect", L"dc", Disconnect, L"Disconnect from the current network.", L"<interface GUID>", TRUE, L"Use EnumInterface (ei) command to get the GUID of an interface." }, { L"Discover", L"disc", Discover, L"Connect to a network without a saved profile. The WLAN service will discover the settings for connection.", L"<interface GUID> <SSID> <infrastructure(i)|adhoc(a)> <secure(s)|unsecure(u)>", TRUE, L"Use EnumInterface (ei) command to get the GUID of an interface." }, // other commands { L"RegisterNotif", L"r", RegisterNotification, L"Register ACM and MSM notifications.", L"", FALSE, L"" }, { L"help", L"?", Help, L"Print this help message.", L"[<command>]", FALSE, L"" } }; // show help messages VOID Help( __in int argc, __in_ecount(argc) LPWSTR argv[] ) { UINT i; if (argc == 1) { // show all commands wcout << L"This is a sample showing how to use WLAN APIs to manager wireless networks." << endl; wcout << L"The following commands are available. Use \"help xyz\" to show the description of command xyz." << endl; for (i=0; i < sizeof(g_Commands)/sizeof(WLSAMPLE_COMMAND); i++) { wcout << L"\t"<< g_Commands[i].strCommandName; wcout << L"(" << g_Commands[i].strShortHand << L")" << endl; } } else if (argc == 2) { // show the description of a command for (i=0; i < sizeof(g_Commands)/sizeof(WLSAMPLE_COMMAND); i++) { if (_wcsicmp(argv[1], g_Commands[i].strCommandName) == 0 || _wcsicmp(argv[1], g_Commands[i].strShortHand) == 0) { wcout << L"Command: " << g_Commands[i].strCommandName; wcout << L"(" << g_Commands[i].strShortHand << L")" << endl; wcout << L"Description: " << g_Commands[i].strHelpMessage << endl; wcout << L"Usage: " << g_Commands[i].strCommandName; wcout << L"(" << g_Commands[i].strShortHand << L") "; wcout << g_Commands[i].strParameters << endl; if (g_Commands[i].bRemarks) { wcout << L"Remarks: " << g_Commands[i].strRemarks << endl; } break; } } } else { PrintErrorMsg(argv[0], ERROR_INVALID_PARAMETER); } } // command is stored in the global variable void ExecuteCommand( __in int argc, __in_ecount(argc) LPWSTR argv[] ) { UINT i = 0; for (i=0; i < sizeof(g_Commands)/sizeof(WLSAMPLE_COMMAND); i++) { // find the command and call the function if (_wcsicmp(argv[0], g_Commands[i].strCommandName) == 0 || _wcsicmp(argv[0], g_Commands[i].strShortHand) == 0) { g_Commands[i].Func(argc, argv); break; } } if (i == sizeof(g_Commands)/sizeof(WLSAMPLE_COMMAND)) { wcerr << L"Invalid command " << argv[0] << L"!" << endl; } } //// the main program //int _cdecl //wmain( // __in int argc, // __in_ecount(argc) LPWSTR argv[] //) //{ // DWORD dwRetCode = ERROR_SUCCESS; // // if (argc <= 1) // { // wcout << L"Please type \"" << argv[0] << L" ?\" for help." << endl; // dwRetCode = ERROR_INVALID_PARAMETER; // } // else // { // // don't pass in the first parameter // ExecuteCommand(argc-1, argv+1); // } // // return dwRetCode; //} //
[ "albertclass@9d869f0c-08ce-11df-b3eb-39986f41eb1c" ]
[ [ [ 1, 2752 ] ] ]
dcb750034996fd9a9a011dcc57cd115061392eea
9773c3304eecc308671bcfa16b5390c81ef3b23a
/MDI AIPI V.6.92 2003 ( Correct Save Fired Rules, AM =-1, g_currentLine)/AIPI/Aipi_STableLiteral.h
b0cbcc3977478e7a2e1fe1c8f92c2cd7e1cc3bb2
[]
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
1,832
h
// Aipi_STableLiteral.h: interface for the CAipi_STableLiteral class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_AIPI_STABLELITERAL_H__CB116C07_79E5_4523_B9D8_FE9883360726__INCLUDED_) #define AFX_AIPI_STABLELITERAL_H__CB116C07_79E5_4523_B9D8_FE9883360726__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "Aipi_SymbolTable.h" class CAipi_STableLiteral : public CAipi_SymbolTable { public: CAipi_STableLiteral(); virtual ~CAipi_STableLiteral(); inline CAipi_STableLiteral(long iform, tstring name, int type, tstring value) { CAipi_SymbolTable::setSymbolId(iform); CAipi_SymbolTable::setSymbolName(name); CAipi_SymbolTable::setSymbolType(type); m_STLitValue = value; } inline void CAipi_STableLiteral::setSymbolId(long iform) { CAipi_SymbolTable::setSymbolId(iform); } inline void CAipi_STableLiteral::setSymbolName(tstring name) { CAipi_SymbolTable::setSymbolName(name); } inline void CAipi_STableLiteral::setSymbolType(int type) { CAipi_SymbolTable::setSymbolType(type); } inline void CAipi_STableLiteral::setSymbolValue(tstring value) { m_STLitValue = value; } inline long CAipi_STableLiteral::getSymbolId() { return CAipi_SymbolTable::m_SymbolId; } inline tstring CAipi_STableLiteral::getSymbolName() { return CAipi_SymbolTable::m_SymbolName; } inline int CAipi_STableLiteral::getSymbolType() { return CAipi_SymbolTable::m_SymbolType; } inline tstring CAipi_STableLiteral::getSymbolValue() { return m_STLitValue; } public: tstring m_STLitValue; }; #endif // !defined(AFX_AIPI_STABLELITERAL_H__CB116C07_79E5_4523_B9D8_FE9883360726__INCLUDED_)
[ [ [ 1, 92 ] ] ]
7e1782f29fd7d6e5e3de2edb25ca9761c0eb6c1d
e2e49023f5a82922cb9b134e93ae926ed69675a1
/tools/aoslcpp/include/aosl/name_forward.hpp
dc98f6660e316569a19f2ff91e01d1743c8dba80
[]
no_license
invy/mjklaim-freewindows
c93c867e93f0e2fe1d33f207306c0b9538ac61d6
30de8e3dfcde4e81a57e9059dfaf54c98cc1135b
refs/heads/master
2021-01-10T10:21:51.579762
2011-12-12T18:56:43
2011-12-12T18:56:43
54,794,395
1
0
null
null
null
null
UTF-8
C++
false
false
14,516
hpp
// Copyright (C) 2005-2010 Code Synthesis Tools CC // // This program was generated by CodeSynthesis XSD, an XML Schema // to C++ data binding compiler, in the Proprietary License mode. // You should have received a proprietary license from Code Synthesis // Tools CC prior to generating this code. See the license text for // conditions. // #ifndef AOSLCPP_AOSL__NAME_FORWARD_HPP #define AOSLCPP_AOSL__NAME_FORWARD_HPP // Begin prologue. // // // End prologue. #include <xsd/cxx/version.hxx> #if (XSD_INT_VERSION != 3030000L) #error XSD runtime version mismatch #endif #include <xsd/cxx/pre.hxx> #ifndef XSD_USE_CHAR #define XSD_USE_CHAR #endif #ifndef XSD_CXX_TREE_USE_CHAR #define XSD_CXX_TREE_USE_CHAR #endif #include <xsd/cxx/xml/char-utf8.hxx> #include <xsd/cxx/tree/exceptions.hxx> #include <xsd/cxx/tree/elements.hxx> #include <xsd/cxx/tree/types.hxx> #include <xsd/cxx/xml/error-handler.hxx> #include <xsd/cxx/xml/dom/auto-ptr.hxx> #include <xsd/cxx/tree/parsing.hxx> #include <xsd/cxx/tree/parsing/byte.hxx> #include <xsd/cxx/tree/parsing/unsigned-byte.hxx> #include <xsd/cxx/tree/parsing/short.hxx> #include <xsd/cxx/tree/parsing/unsigned-short.hxx> #include <xsd/cxx/tree/parsing/int.hxx> #include <xsd/cxx/tree/parsing/unsigned-int.hxx> #include <xsd/cxx/tree/parsing/long.hxx> #include <xsd/cxx/tree/parsing/unsigned-long.hxx> #include <xsd/cxx/tree/parsing/boolean.hxx> #include <xsd/cxx/tree/parsing/float.hxx> #include <xsd/cxx/tree/parsing/double.hxx> #include <xsd/cxx/tree/parsing/decimal.hxx> #include <xsd/cxx/xml/dom/serialization-header.hxx> #include <xsd/cxx/tree/serialization.hxx> #include <xsd/cxx/tree/serialization/byte.hxx> #include <xsd/cxx/tree/serialization/unsigned-byte.hxx> #include <xsd/cxx/tree/serialization/short.hxx> #include <xsd/cxx/tree/serialization/unsigned-short.hxx> #include <xsd/cxx/tree/serialization/int.hxx> #include <xsd/cxx/tree/serialization/unsigned-int.hxx> #include <xsd/cxx/tree/serialization/long.hxx> #include <xsd/cxx/tree/serialization/unsigned-long.hxx> #include <xsd/cxx/tree/serialization/boolean.hxx> #include <xsd/cxx/tree/serialization/float.hxx> #include <xsd/cxx/tree/serialization/double.hxx> #include <xsd/cxx/tree/serialization/decimal.hxx> #include <xsd/cxx/tree/std-ostream-operators.hxx> /** * @brief C++ namespace for the %http://www.w3.org/2001/XMLSchema * schema namespace. */ namespace xml_schema { // anyType and anySimpleType. // /** * @brief C++ type corresponding to the anyType XML Schema * built-in type. */ typedef ::xsd::cxx::tree::type Type; /** * @brief C++ type corresponding to the anySimpleType XML Schema * built-in type. */ typedef ::xsd::cxx::tree::simple_type< Type > SimpleType; /** * @brief Alias for the anyType type. */ typedef ::xsd::cxx::tree::type Container; // 8-bit // /** * @brief C++ type corresponding to the byte XML Schema * built-in type. */ typedef signed char Byte; /** * @brief C++ type corresponding to the unsignedByte XML Schema * built-in type. */ typedef unsigned char UnsignedByte; // 16-bit // /** * @brief C++ type corresponding to the short XML Schema * built-in type. */ typedef short Short; /** * @brief C++ type corresponding to the unsignedShort XML Schema * built-in type. */ typedef unsigned short UnsignedShort; // 32-bit // /** * @brief C++ type corresponding to the int XML Schema * built-in type. */ typedef int Int; /** * @brief C++ type corresponding to the unsignedInt XML Schema * built-in type. */ typedef unsigned int UnsignedInt; // 64-bit // /** * @brief C++ type corresponding to the long XML Schema * built-in type. */ typedef long long Long; /** * @brief C++ type corresponding to the unsignedLong XML Schema * built-in type. */ typedef unsigned long long UnsignedLong; // Supposed to be arbitrary-length integral types. // /** * @brief C++ type corresponding to the integer XML Schema * built-in type. */ typedef long long Integer; /** * @brief C++ type corresponding to the nonPositiveInteger XML Schema * built-in type. */ typedef long long NonPositiveInteger; /** * @brief C++ type corresponding to the nonNegativeInteger XML Schema * built-in type. */ typedef unsigned long long NonNegativeInteger; /** * @brief C++ type corresponding to the positiveInteger XML Schema * built-in type. */ typedef unsigned long long PositiveInteger; /** * @brief C++ type corresponding to the negativeInteger XML Schema * built-in type. */ typedef long long NegativeInteger; // Boolean. // /** * @brief C++ type corresponding to the boolean XML Schema * built-in type. */ typedef bool Boolean; // Floating-point types. // /** * @brief C++ type corresponding to the float XML Schema * built-in type. */ typedef float Float; /** * @brief C++ type corresponding to the double XML Schema * built-in type. */ typedef double Double; /** * @brief C++ type corresponding to the decimal XML Schema * built-in type. */ typedef double Decimal; // String types. // /** * @brief C++ type corresponding to the string XML Schema * built-in type. */ typedef ::xsd::cxx::tree::string< char, SimpleType > String; /** * @brief C++ type corresponding to the normalizedString XML Schema * built-in type. */ typedef ::xsd::cxx::tree::normalized_string< char, String > NormalizedString; /** * @brief C++ type corresponding to the token XML Schema * built-in type. */ typedef ::xsd::cxx::tree::token< char, NormalizedString > Token; /** * @brief C++ type corresponding to the Name XML Schema * built-in type. */ typedef ::xsd::cxx::tree::name< char, Token > Name; /** * @brief C++ type corresponding to the NMTOKEN XML Schema * built-in type. */ typedef ::xsd::cxx::tree::nmtoken< char, Token > Nmtoken; /** * @brief C++ type corresponding to the NMTOKENS XML Schema * built-in type. */ typedef ::xsd::cxx::tree::nmtokens< char, SimpleType, Nmtoken > Nmtokens; /** * @brief C++ type corresponding to the NCName XML Schema * built-in type. */ typedef ::xsd::cxx::tree::ncname< char, Name > Ncname; /** * @brief C++ type corresponding to the language XML Schema * built-in type. */ typedef ::xsd::cxx::tree::language< char, Token > Language; // ID/IDREF. // /** * @brief C++ type corresponding to the ID XML Schema * built-in type. */ typedef ::xsd::cxx::tree::id< char, Ncname > Id; /** * @brief C++ type corresponding to the IDREF XML Schema * built-in type. */ typedef ::xsd::cxx::tree::idref< char, Ncname, Type > Idref; /** * @brief C++ type corresponding to the IDREFS XML Schema * built-in type. */ typedef ::xsd::cxx::tree::idrefs< char, SimpleType, Idref > Idrefs; // URI. // /** * @brief C++ type corresponding to the anyURI XML Schema * built-in type. */ typedef ::xsd::cxx::tree::uri< char, SimpleType > Uri; // Qualified name. // /** * @brief C++ type corresponding to the QName XML Schema * built-in type. */ typedef ::xsd::cxx::tree::qname< char, SimpleType, Uri, Ncname > Qname; // Binary. // /** * @brief Binary buffer type. */ typedef ::xsd::cxx::tree::buffer< char > Buffer; /** * @brief C++ type corresponding to the base64Binary XML Schema * built-in type. */ typedef ::xsd::cxx::tree::base64_binary< char, SimpleType > Base64Binary; /** * @brief C++ type corresponding to the hexBinary XML Schema * built-in type. */ typedef ::xsd::cxx::tree::hex_binary< char, SimpleType > HexBinary; // Date/time. // /** * @brief Time zone type. */ typedef ::xsd::cxx::tree::time_zone TimeZone; /** * @brief C++ type corresponding to the date XML Schema * built-in type. */ typedef ::xsd::cxx::tree::date< char, SimpleType > Date; /** * @brief C++ type corresponding to the dateTime XML Schema * built-in type. */ typedef ::xsd::cxx::tree::date_time< char, SimpleType > DateTime; /** * @brief C++ type corresponding to the duration XML Schema * built-in type. */ typedef ::xsd::cxx::tree::duration< char, SimpleType > Duration; /** * @brief C++ type corresponding to the gDay XML Schema * built-in type. */ typedef ::xsd::cxx::tree::gday< char, SimpleType > Gday; /** * @brief C++ type corresponding to the gMonth XML Schema * built-in type. */ typedef ::xsd::cxx::tree::gmonth< char, SimpleType > Gmonth; /** * @brief C++ type corresponding to the gMonthDay XML Schema * built-in type. */ typedef ::xsd::cxx::tree::gmonth_day< char, SimpleType > GmonthDay; /** * @brief C++ type corresponding to the gYear XML Schema * built-in type. */ typedef ::xsd::cxx::tree::gyear< char, SimpleType > Gyear; /** * @brief C++ type corresponding to the gYearMonth XML Schema * built-in type. */ typedef ::xsd::cxx::tree::gyear_month< char, SimpleType > GyearMonth; /** * @brief C++ type corresponding to the time XML Schema * built-in type. */ typedef ::xsd::cxx::tree::time< char, SimpleType > Time; // Entity. // /** * @brief C++ type corresponding to the ENTITY XML Schema * built-in type. */ typedef ::xsd::cxx::tree::entity< char, Ncname > Entity; /** * @brief C++ type corresponding to the ENTITIES XML Schema * built-in type. */ typedef ::xsd::cxx::tree::entities< char, SimpleType, Entity > Entities; // Namespace information and list stream. Used in // serialization functions. // /** * @brief Namespace serialization information. */ typedef ::xsd::cxx::xml::dom::namespace_info< char > NamespaceInfo; /** * @brief Namespace serialization information map. */ typedef ::xsd::cxx::xml::dom::namespace_infomap< char > NamespaceInfomap; /** * @brief List serialization stream. */ typedef ::xsd::cxx::tree::list_stream< char > ListStream; /** * @brief Serialization wrapper for the %double type. */ typedef ::xsd::cxx::tree::as_double< Double > AsDouble; /** * @brief Serialization wrapper for the %decimal type. */ typedef ::xsd::cxx::tree::as_decimal< Decimal > AsDecimal; /** * @brief Simple type facet. */ typedef ::xsd::cxx::tree::facet Facet; // Flags and properties. // /** * @brief Parsing and serialization flags. */ typedef ::xsd::cxx::tree::flags Flags; /** * @brief Parsing properties. */ typedef ::xsd::cxx::tree::properties< char > Properties; // Parsing/serialization diagnostics. // /** * @brief Error severity. */ typedef ::xsd::cxx::tree::severity Severity; /** * @brief Error condition. */ typedef ::xsd::cxx::tree::error< char > Error; /** * @brief List of %error conditions. */ typedef ::xsd::cxx::tree::diagnostics< char > Diagnostics; // Exceptions. // /** * @brief Root of the C++/Tree %exception hierarchy. */ typedef ::xsd::cxx::tree::exception< char > Exception; /** * @brief Exception indicating that the size argument exceeds * the capacity argument. */ typedef ::xsd::cxx::tree::bounds< char > Bounds; /** * @brief Exception indicating that a duplicate ID value * was encountered in the object model. */ typedef ::xsd::cxx::tree::duplicate_id< char > DuplicateId; /** * @brief Exception indicating a parsing failure. */ typedef ::xsd::cxx::tree::parsing< char > Parsing; /** * @brief Exception indicating that an expected element * was not encountered. */ typedef ::xsd::cxx::tree::expected_element< char > ExpectedElement; /** * @brief Exception indicating that an unexpected element * was encountered. */ typedef ::xsd::cxx::tree::unexpected_element< char > UnexpectedElement; /** * @brief Exception indicating that an expected attribute * was not encountered. */ typedef ::xsd::cxx::tree::expected_attribute< char > ExpectedAttribute; /** * @brief Exception indicating that an unexpected enumerator * was encountered. */ typedef ::xsd::cxx::tree::unexpected_enumerator< char > UnexpectedEnumerator; /** * @brief Exception indicating that the text content was * expected for an element. */ typedef ::xsd::cxx::tree::expected_text_content< char > ExpectedTextContent; /** * @brief Exception indicating that a prefix-namespace * mapping was not provided. */ typedef ::xsd::cxx::tree::no_prefix_mapping< char > NoPrefixMapping; /** * @brief Exception indicating that the type information * is not available for a type. */ typedef ::xsd::cxx::tree::no_type_info< char > NoTypeInfo; /** * @brief Exception indicating that the types are not * related by inheritance. */ typedef ::xsd::cxx::tree::not_derived< char > NotDerived; /** * @brief Exception indicating a serialization failure. */ typedef ::xsd::cxx::tree::serialization< char > Serialization; /** * @brief Error handler callback interface. */ typedef ::xsd::cxx::xml::error_handler< char > ErrorHandler; /** * @brief DOM interaction. */ namespace dom { /** * @brief Automatic pointer for DOMDocument. */ using ::xsd::cxx::xml::dom::auto_ptr; #ifndef XSD_CXX_TREE_TREE_NODE_KEY__XML_SCHEMA #define XSD_CXX_TREE_TREE_NODE_KEY__XML_SCHEMA /** * @brief DOM user data key for back pointers to tree nodes. */ const XMLCh* const tree_node_key = ::xsd::cxx::tree::user_data_keys::node; #endif } } // Forward declarations. // namespace aosl { class Name; } #include <xsd/cxx/post.hxx> // Begin epilogue. // // // End epilogue. #endif // AOSLCPP_AOSL__NAME_FORWARD_HPP
[ "klaim@localhost" ]
[ [ [ 1, 608 ] ] ]
df3dd971f06c718e95ce7ff5e41a0cccc1ab61ea
dadae22098e24c412a8d8d4133c8f009a8a529c9
/tp2/src/quaternion.inl
5c8abdda51076a32ade1e3640848bb3f90ff7a57
[]
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
14,088
inl
// /// Constructors & Destructor // template <class Real> Quaternion<Real>::Quaternion() { // Uninitialized for better performance } template <class Real> Quaternion<Real>::Quaternion(Real w, Real x, Real y, Real z) { components[0] = w; components[1] = x; components[2] = y; components[3] = z; } template <class Real> Quaternion<Real>::Quaternion(Real angle, const Vector3<Real>& axis) { Real halfAngle = angle * 0.5f; Vector3<Real> result = sin(halfAngle) * axis.normalize(); components[0] = cos(halfAngle); components[1] = result.x(); components[2] = result.y(); components[3] = result.z(); } template <class Real> Quaternion<Real>::Quaternion(Real angle, const Vector4<Real>& axis) { Real halfAngle = angle * 0.5f; Vector4<Real> result = sin(halfAngle) * axis.normalize(); components[0] = cos(halfAngle); components[1] = result.x(); components[2] = result.y(); components[3] = result.z(); } template <class Real> Quaternion<Real>::Quaternion(Real* values) { components[0] = values[0]; components[1] = values[1]; components[2] = values[2]; components[3] = values[3]; } template <class Real> Quaternion<Real>::Quaternion(const Quaternion& rightSide) { components[0] = rightSide.components[0]; components[1] = rightSide.components[1]; components[2] = rightSide.components[2]; components[3] = rightSide.components[3]; } // /// Members access // template <class Real> Quaternion<Real>::operator const Real*() const { return components; } template <class Real> Quaternion<Real>::operator Real*() { return components; } template <class Real> Real Quaternion<Real>::operator[] (int index) const { assert(index >= 0 && index <= 3 && "Quaternion: index out of range"); return components[index]; } template <class Real> Real& Quaternion<Real>::operator[] (int index) { assert(index >= 0 && index <= 3 && "Quaternion: index out of range"); return components[index]; } template <class Real> Real Quaternion<Real>::w() const { return components[0]; } template <class Real> Real& Quaternion<Real>::w() { return components[0]; } template <class Real> Real Quaternion<Real>::x() const { return components[1]; } template <class Real> Real& Quaternion<Real>::x() { return components[1]; } template <class Real> Real Quaternion<Real>::y() const { return components[2]; } template <class Real> Real& Quaternion<Real>::y() { return components[2]; } template <class Real> Real Quaternion<Real>::z() const { return components[3]; } template <class Real> Real& Quaternion<Real>::z() { return components[3]; } template <class Real> void Quaternion<Real>::assignTo(Real* values) { for(int i = 0; i < 4; ++i) values[i] = components[i]; } template <class Real> void Quaternion<Real>::set(Real* values) { for(int i = 0; i < 4; ++i) components[i] = values[i]; } template <class Real> void Quaternion<Real>::set(Real w, Real x, Real y, Real z) { components[0] = w; components[1] = x; components[2] = y; components[3] = z; } // /// Assigment operator // template <class Real> Quaternion<Real>& Quaternion<Real>::operator= (const Quaternion& rightSide) { components[0] = rightSide.components[0]; components[1] = rightSide.components[1]; components[2] = rightSide.components[2]; components[3] = rightSide.components[3]; return *this; } // /// Boolean operators // template <class Real> int Quaternion<Real>::compareArrays(const Quaternion& rightSide) const { return memcmp(components, rightSide.components, 4 * sizeof(Real)); } template <class Real> bool Quaternion<Real>::operator== (const Quaternion& rightSide) const { return compareArrays(rightSide) == 0; } template <class Real> bool Quaternion<Real>::operator!= (const Quaternion& rightSide) const { return compareArrays(rightSide) != 0; } template <class Real> bool Quaternion<Real>::operator< (const Quaternion& rightSide) const { return compareArrays(rightSide) < 0; } template <class Real> bool Quaternion<Real>::operator<= (const Quaternion& rightSide) const { return compareArrays(rightSide) <= 0; } template <class Real> bool Quaternion<Real>::operator> (const Quaternion& rightSide) const { return compareArrays(rightSide) > 0; } template <class Real> bool Quaternion<Real>::operator>= (const Quaternion& rightSide) const { return compareArrays(rightSide) >= 0; } // /// Binary operators // template <class Real> Quaternion<Real> Quaternion<Real>::operator+ (const Quaternion& rightSide) const { Quaternion sum; for (int i = 0; i < 4; ++i) sum.components[i] = components[i] + rightSide.components[i]; return sum; } template <class Real> Quaternion<Real> Quaternion<Real>::operator- (const Quaternion& rightSide) const { Quaternion diff; for (int i = 0; i < 4; ++i) diff.components[i] = components[i] - rightSide.components[i]; return diff; } template <class Real> Quaternion<Real> Quaternion<Real>::operator* (const Quaternion& rightSide) const { Quaternion prod; prod.components[0] = components[0] * rightSide.components[0] - components[1] * rightSide.components[1] - components[2] * rightSide.components[2] - components[3] * rightSide.components[3]; prod.components[1] = components[0] * rightSide.components[1] + components[1] * rightSide.components[0] + components[2] * rightSide.components[3] - components[3] * rightSide.components[2]; prod.components[2] = components[0] * rightSide.components[2] + components[2] * rightSide.components[0] + components[3] * rightSide.components[1] - components[1] * rightSide.components[3]; prod.components[3] = components[0] * rightSide.components[3] + components[3] * rightSide.components[0] + components[1] * rightSide.components[2] - components[2] * rightSide.components[1]; return prod; } template <class Real> Quaternion<Real> Quaternion<Real>::operator* (Real scalar) const { Quaternion prod; for (int i = 0; i < 4; ++i) prod.components[i] = scalar * components[i]; return prod; } template <class Real> Quaternion<Real> Quaternion<Real>::operator/ (Real scalar) const { assert(abs(scalar) > EPSILON && "Quaternion: scalar divider equal or near zero"); Quaternion quot; Real invScalar = 1.0f / scalar; for (int i = 0; i < 4; ++i) quot.components[i] = invScalar * components[i]; return quot; } template <class Real> Quaternion<Real> operator* (Real scalar, const Quaternion<Real>& rightSide) { Quaternion<Real> prod; for (int i = 0; i < 4; ++i) prod[i] = scalar * rightSide[i]; return prod; } // /// Unary operator // template <class Real> Quaternion<Real> Quaternion<Real>::operator- () const { Quaternion neg; for (int i = 0; i < 4; ++i) neg.components[i] = -components[i]; return neg; } // /// Binary self-update operator // template <class Real> Quaternion<Real>& Quaternion<Real>::operator+= (const Quaternion& rightSide) { for (int i = 0; i < 4; ++i) components[i] += rightSide.components[i]; return *this; } template <class Real> Quaternion<Real>& Quaternion<Real>::operator-= (const Quaternion& rightSide) { for (int i = 0; i < 4; ++i) components[i] -= rightSide.components[i]; return *this; } template <class Real> Quaternion<Real>& Quaternion<Real>::operator*= (Real scalar) { for (int i = 0; i < 4; ++i) components[i] *= scalar; return *this; } template <class Real> Quaternion<Real>& Quaternion<Real>::operator/= (Real scalar) { assert(abs(scalar) > EPSILON && "Quaternion: scalar divider equal or near zero"); Real invScalar = 1.0f / scalar; for (i = 0; i < 4; ++i) components[i] *= invScalar; return *this; } template <class Real> inline ostream& operator<<(ostream& outputStream, const Quaternion<Real>& quaternion) { outputStream << setprecision(3) << "[ " << setw( 3 ) << quaternion.components[0] << ", " << quaternion.components[1] << ", " << quaternion.components[2] << ", " << quaternion.components[3] << " ]" << setw(0); return outputStream; } // /// Useful function // template <class Real> Real Quaternion<Real>::magnitude() const { return sqrt(components[0] * components[0] + components[1] * components[1] + components[2] * components[2] + components[3] * components[3]); } template <class Real> Real Quaternion<Real>::length() const { return components[0] * components[0] + components[1] * components[1] + components[2] * components[2] + components[3] * components[3]; } template <class Real> Real Quaternion<Real>::dot(const Quaternion& rightSide) const { Real dot = 0.0f; for (int i = 0; i < 4; ++i) dot += components[i] * rightSide.components[i]; return dot; } template <class Real> Real Quaternion<Real>::normalize() { Real magn = magnitude(); if (magn >= 0.0f) { Real invMagnitude = 1.0f / magn; components[0] *= invMagnitude; components[1] *= invMagnitude; components[2] *= invMagnitude; components[3] *= invMagnitude; } return magn; } template <class Real> Quaternion<Real> Quaternion<Real>::inverse() const { Quaternion inverse; Real norm = 0.0f; for (int i = 0; i < 4; ++i) norm += components[i] * components[i]; if (norm > 0.0f) { Real invNorm = 1.0f / norm; inverse.components[0] = components[0] * invNorm; inverse.components[1] = -components[1] * invNorm; inverse.components[2] = -components[2] * invNorm; inverse.components[3] = -components[3] * invNorm; } return inverse; } template <class Real> Quaternion<Real> Quaternion<Real>::conjugate() const { return Quaternion(components[0], -components[1], -components[2], -components[3]); } template <class Real> void Quaternion<Real>::fromAxisAngle(Real angle, const Vector3<Real>& axis) { Real halfAngle = angle * 0.5f; Vector3<Real> result = sin(halfAngle) * axis.normalize(); components[0] = cos(halfAngle); components[1] = result.x(); components[2] = result.y(); components[3] = result.z(); } template <class Real> void Quaternion<Real>::fromAxisAngle(Real angle, const Vector4<Real>& axis) { Real halfAngle = angle * 0.5f; Vector4<Real> result = sin(halfAngle) * axis.normalize(); components[0] = cos(halfAngle); components[1] = result.x(); components[2] = result.y(); components[3] = result.z(); } template <class Real> void Quaternion<Real>::toRotationMatrix(Matrix3<Real>& matrix) const { Real Tx = 2.0f * components[1]; Real Ty = 2.0f * components[2]; Real Tz = 2.0f * components[3]; Real Twx = Tx * components[0]; Real Twy = Ty * components[0]; Real Twz = Tz * components[0]; Real Txx = Tx * components[1]; Real Txy = Ty * components[1]; Real Txz = Tz * components[1]; Real Tyy = Ty * components[2]; Real Tyz = Tz * components[2]; Real Tzz = Tz * components[3]; matrix(0, 0) = 1.0f - (Tyy + Tzz); matrix(0, 1) = Txy - Twz; matrix(0, 2) = Txz + Twy; matrix(1, 0) = Txy + Twz; matrix(1, 1) = 1.0f - (Txx + Tzz); matrix(1, 2) = Tyz - Twx; matrix(2, 0) = Txz - Twy; matrix(2, 1) = Tyz + Twx; matrix(2, 2) = 1.0f - (Txx + Tyy); } template <class Real> void Quaternion<Real>::toAxisAngle(Real& angle, Vector3<Real>& axis) const { // The quaternion representing the rotation is q = cos(theta/2) + sin(theta/2) * (x*i + y*j + z*k) Real length = components[0] * components[0] + components[1] * components[1] + components[2] * components[2] + components[3] * components[3]; if (length > EPSILON) { angle = 2.0f * acos(components[0]); Real invMagnitude = 1.0f / sqrt(length); axis[0] = components[1] * invMagnitude; axis[1] = components[2] * invMagnitude; axis[2] = components[3] * invMagnitude; } else { // angle is 0 (mod 2 * pi), so any axis will do angle = 0.0f; axis[0] = 1.0f; axis[1] = 0.0f; axis[2] = 0.0f; } } template <class Real> void Quaternion<Real>::toAxisAngle(Real& angle, Vector4<Real>& axis) const { // The quaternion representing the rotation is q = cos(theta/2) + sin(theta/2) * (x*i + y*j + z*k) Real length = components[0] * components[0] + components[1] * components[1] + components[2] * components[2] + components[3] * components[3]; if (length > EPSILON) { angle = 2.0f * acos(components[0]); Real invMagnitude = 1.0f / sqrt(length); axis[0] = components[1] * invMagnitude; axis[1] = components[2] * invMagnitude; axis[2] = components[3] * invMagnitude; } else { // angle is 0 (mod 2 * pi), so any axis will do angle = 0.0f; axis[0] = 1.0f; axis[1] = 0.0f; axis[2] = 0.0f; } }
[ [ [ 1, 550 ] ] ]
0ab248c32412d350c1cf77568b341631d5c7527a
90aa2eebb1ab60a2ac2be93215a988e3c51321d7
/castor/branches/boost/libs/castor/test/test_shuffle.cpp
64ecc8b7d689c0456e8c2592441f12fedead3f5a
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
roshannaik/castor
b9f4ea138a041fe8bccf2d8fc0dceeb13bcca5a6
e86e2bf893719bf3164f9da9590217c107cbd913
refs/heads/master
2021-04-18T19:24:38.612073
2010-08-18T05:10:39
2010-08-18T05:10:39
126,150,539
0
0
null
null
null
null
UTF-8
C++
false
false
1,645
cpp
#include <boost/castor.h> #include <boost/test/minimal.hpp> using namespace castor; int test_main(int, char * []) { { // generate mode, lref<Itr> lref<int> c; lref<std::string> s = "hello", ss; lref<std::string::iterator> sb = s->begin(), se = s->end(); relation r = zip(True(20), shuffle(sb, se, ss)) >>= count(c); BOOST_CHECK(r()); BOOST_CHECK(*c == 20); BOOST_CHECK(!r() && !c.defined() && ss.defined()); } { // generate mode, Itr lref<int> c; lref<std::string> s = "hello", ss; std::string::iterator sb = s->begin(), se = s->end(); relation r = zip(True(20), shuffle(sb, se, ss)) >>= count(c); BOOST_CHECK(r()); BOOST_CHECK(*c == 20); BOOST_CHECK(!r() && !c.defined() && ss.defined()); } { // test mode lref<int> c; lref<std::string> s = "hello", ps; lref<std::string::iterator> sb = s->begin(), se = s->end(); relation r = (permutation(s, ps) && shuffle(ps, s)) >>= count(c); BOOST_CHECK(r()); BOOST_CHECK(*c == 60); BOOST_CHECK(!r() && !c.defined() && !ps.defined()); } { // gen mode - const container, const_iterator lref<int> c; const std::string s = "hello"; lref<const std::string> ls(&s,false); lref<std::string> sh; relation r = shuffle(s.begin(), s.end(), sh); //const_iterator BOOST_CHECK(r()); sh.reset(); r = shuffle(ls,sh); // const container BOOST_CHECK(r()); } return 0; }
[ [ [ 1, 54 ], [ 57, 60 ] ], [ [ 55, 56 ] ] ]
1ea1dcd91c9029844523c4b80bf1e0e5158e3722
3276915b349aec4d26b466d48d9c8022a909ec16
/数据结构/查找/折半查找--顺序存储.cpp
9c0dbaae7f0850cbd8c39b303f777c23eef7c235
[]
no_license
flyskyosg/3dvc
c10720b1a7abf9cf4fa1a66ef9fc583d23e54b82
0279b1a7ae097b9028cc7e4aa2dcb67025f096b9
refs/heads/master
2021-01-10T11:39:45.352471
2009-07-31T13:13:50
2009-07-31T13:13:50
48,670,844
0
0
null
null
null
null
GB18030
C++
false
false
1,526
cpp
//****************二分查找**********************// #include<iostream.h> #include<stdio.h> #define max 50 typedef char datatype; //通用数据类型 int st[max], //全局数组,存放查找的数据 k=-1; void px() //排序函数(由小到大) { int i=0,j=0;datatype t; for(i=0;i<k;i++) { for(j=0;j<k-i;j++) { if(st[j]>st[j+1]) { t=st[j]; st[j]=st[j+1]; st[j+1]=t; } } } printf("排序后的数据组是:"); for(i=0;i<=k;i++) printf("%c ",st[i]); cout<<endl; } void creatst() //创建数据组 { datatype n='\0'; int i=1; cout<<"创建数据组,输入0结束操作."<<endl; do { cout<<"输入第"<<i<<"个数据:"; cin>>n; if(n=='0') break; k++;st[k]=n;i++; }while(1); } int binsearch(datatype n) //二分查找函数 { int low=0, high=0, mid=0; low=0;high=k;mid=(low+high)/2; if(n<st[low]||n>st[high]) return -1; while(low<=high) { if(st[mid]==n) return mid; else { if(st[mid]<n) low=mid+1; else high=mid-1; mid=(low+high)/2; } } return -1; } void main() { datatype n;int m=0; creatst(); px(); cout<<"请输入要查找的数据:"; cin>>n; m=binsearch(n); switch(m) { case -1:cout<<"元素"<<n<<"不再数据组中."<<endl;break; default: cout<<"元素"<<n<<"在数据组的第"<<m+1<<"个位置."<<endl;break; } }
[ [ [ 1, 96 ] ] ]
b4997c9ecbd740c8bc5a909933110697e6f67de9
854ee643a4e4d0b7a202fce237ee76b6930315ec
/arcemu_svn/src/arcemu-world/ClusterInterface.h
0463370cd47d6b7a536f6b572299226c5bee6b74
[]
no_license
miklasiak/projekt
df37fa82cf2d4a91c2073f41609bec8b2f23cf66
064402da950555bf88609e98b7256d4dc0af248a
refs/heads/master
2021-01-01T19:29:49.778109
2008-11-10T17:14:14
2008-11-10T17:14:14
34,016,391
2
0
null
null
null
null
UTF-8
C++
false
false
3,094
h
/* * ArcEmu MMORPG Server * Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/> * Copyright (C) 2008 <http://www.ArcEmu.org/> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #ifdef CLUSTERING #ifndef _CLUSTERINTERFACE_H #define _CLUSTERINTERFACE_H #define MAX_SESSIONS 3000 #include "../realmserver/Structures.h" class ClusterInterface; typedef void(ClusterInterface::*ClusterInterfaceHandler)(WorldPacket&); class ClusterInterface : public Singleton<ClusterInterface> { Mutex m_onlinePlayerMapMutex; typedef HM_NAMESPACE::hash_map<uint32,RPlayerInfo*> OnlinePlayerStorageMap; OnlinePlayerStorageMap _onlinePlayers; WSClient * _clientSocket; FastQueue<WorldPacket*, Mutex> _pckQueue; time_t _lastConnectTime; WorldSession * _sessions[MAX_SESSIONS]; bool m_connected; uint8 key[20]; uint32 m_latency; Mutex m_mapMutex; public: string GenerateVersionString(); static ClusterInterfaceHandler PHandlers[IMSG_NUM_TYPES]; static void InitHandlers(); ClusterInterface(); ~ClusterInterface(); void ForwardWoWPacket(uint16 opcode, uint32 size, const void * data, uint32 sessionid); void ConnectToRealmServer(); RPlayerInfo * GetPlayer(uint32 guid) { RPlayerInfo * inf; OnlinePlayerStorageMap::iterator itr; m_onlinePlayerMapMutex.Acquire(); itr = _onlinePlayers.find(guid); m_onlinePlayerMapMutex.Release(); return (itr == _onlinePlayers.end()) ? 0 : itr->second; } ARCEMU_INLINE WorldSession * GetSession(uint32 sid) { return _sessions[sid]; } void HandleAuthRequest(WorldPacket & pck); void HandleAuthResult(WorldPacket & pck); void HandleRegisterResult(WorldPacket & pck); void HandleCreateInstance(WorldPacket & pck); void HandleDestroyInstance(WorldPacket & pck); void HandlePlayerLogin(WorldPacket & pck); void HandlePackedPlayerInfo(WorldPacket & pck); void HandleWoWPacket(WorldPacket & pck); void HandlePlayerChangedServers(WorldPacket & pck); ARCEMU_INLINE void QueuePacket(WorldPacket * pck) { _pckQueue.Push(pck); } void Update(); void DestroySession(uint32 sid); ARCEMU_INLINE void SendPacket(WorldPacket * data) { if(_clientSocket) _clientSocket->SendPacket(data); } ARCEMU_INLINE void SetSocket(WSClient * s) { _clientSocket = s; } void RequestTransfer(Player * plr, uint32 MapId, uint32 InstanceId, LocationVector & vec); }; #define sClusterInterface ClusterInterface::getSingleton() #endif #endif
[ "[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef", "[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef" ]
[ [ [ 1, 1 ], [ 5, 67 ], [ 69, 79 ], [ 81, 84 ], [ 87, 94 ] ], [ [ 2, 4 ], [ 68, 68 ], [ 80, 80 ], [ 85, 86 ] ] ]
538f6bd4def63aa5fd643b88ec2d70b798a7dfb5
e580637678397200ed79532cd34ef78983e9aacd
/Grapplon/State_Game.cpp
fb213144f722b80dc8d0003d0544ad4a115d7e73
[]
no_license
TimToxopeus/grapplon2
03520bf6b5feb2c6fcb0c5ddb135abe55d3f344b
60f0564bdeda7d4c6e1b97148b5d060ab84c8bd5
refs/heads/master
2021-01-10T21:11:59.438625
2008-07-13T06:49:06
2008-07-13T06:49:06
41,954,527
0
0
null
null
null
null
UTF-8
C++
false
false
11,584
cpp
#include "State_Game.h" #include "ResourceManager.h" #include "WiimoteManager.h" #include "ODEManager.h" #include "PlayerObject.h" #include "SoundManager.h" #include "math.h" #include "AnimatedTexture.h" #include "Sound.h" #include "Universe.h" #include "Renderer.h" #include "Background.h" #include "HUD.h" #include "GameSettings.h" #include "WormHole.h" #include "PowerUp.h" CGameState::CGameState() { for ( int i = 0; i<4; i++ ) m_pPlayers[i] = NULL; m_pUniverse = NULL; m_pBackground = NULL; m_pHUD = NULL; m_bRunning = true; m_bQuit = false; m_fBuoyAngle = 0; m_pBuoyImage = new CAnimatedTexture("media/scripts/texture_buoy.txt"); box.x = 20; box.y = 10; box.w = 256; box.h = 256; SetDepth( -10.0f ); m_fMatchTimeLeft = 180.0f; m_fCountDown = 3.0f; m_eType = GAMESTATE; } bool CGameState::Init( int iPlayers, std::string level ) { // CSound *pSound = (CSound *)CResourceManager::Instance()->GetResource("media/sounds/xpstart.wav", RT_SOUND); // pSound->Play(); CSoundManager::Instance()->LoadSound( "media/music/music_game.ogg" ); m_pUniverse = new CUniverse(); if ( level == "" ) m_pUniverse->Load( CGameSettings::Instance()->LEVEL ); else m_pUniverse->Load( level ); if ( iPlayers > 0 ) { m_pPlayers[0] = new CPlayerObject(0); m_pPlayers[0]->SetPosition( m_pUniverse->m_iInitSpawnPos1 ); CWiimoteManager::Instance()->RegisterListener( m_pPlayers[0], 0 ); } if ( iPlayers > 1 ) { m_pPlayers[1] = new CPlayerObject(1); m_pPlayers[1]->SetPosition( m_pUniverse->m_iInitSpawnPos2 ); CWiimoteManager::Instance()->RegisterListener( m_pPlayers[1], 1 ); } if ( iPlayers > 2 ) { m_pPlayers[2] = new CPlayerObject(2); m_pPlayers[2]->SetPosition( m_pUniverse->m_iInitSpawnPos3 ); CWiimoteManager::Instance()->RegisterListener( m_pPlayers[2], 2 ); } if ( iPlayers > 3 ) { m_pPlayers[3] = new CPlayerObject(3); m_pPlayers[3]->SetPosition( m_pUniverse->m_iInitSpawnPos4 ); CWiimoteManager::Instance()->RegisterListener( m_pPlayers[3], 3 ); } m_pHUD = new CHUD(); m_pHUD->SetPlayers( m_pPlayers[0], m_pPlayers[1], m_pPlayers[2], m_pPlayers[3] ); m_pBackground = new CBackground(m_pUniverse->m_iBackgroundNr); // m_pPlayers[0]->SetDepth( 1.0f ); // m_pPlayers[1]->SetDepth( -1.0f ); // m_pPlayers[2]->SetDepth( 0.0f ); // m_pPlayers[3]->SetDepth( 2.0f ); /* m_pPlayers[0]->SetMass( 10000.0f ); m_pPlayers[1]->SetMass( 100.0f ); m_pPlayers[2]->SetMass( 10000.0f ); m_pPlayers[3]->SetMass( 100.0f );*/ m_fMatchTimeLeft = SETS->MATCH_TIME; m_fCountDown = 3.0f; CSound *pSound = (CSound *)CResourceManager::Instance()->GetResource("media/sounds/321-3.wav", RT_SOUND); if ( pSound ) pSound->Play(); LoadCommonImages(); m_iPlayerPaused = -1; return true; } CGameState::~CGameState() { for ( int i = 0; i<4; i++ ) { if ( m_pPlayers[i] ) { delete m_pPlayers[i]; m_pPlayers[i] = NULL; } } if ( m_pUniverse ) { delete m_pUniverse; m_pUniverse = NULL; CODEManager::Instance()->m_pUniverse = NULL; } if ( m_pBackground ) { delete m_pBackground; m_pBackground = NULL; } if ( m_pHUD ) { delete m_pHUD; m_pHUD = NULL; } } void CGameState::Render() { int level_width = (int) m_pUniverse->m_fWidth; int level_height = (int) m_pUniverse->m_fHeight; // Note: m_fWidth is actually half the width (same for height) int level_l = -level_width; int level_r = level_width; int level_t = -level_height; int level_b = level_height; // aabb = Axis Aligned Bounding Box of the players (and interpolated wormholes) int aabb_l = 99999999; int aabb_r = -99999999; int aabb_t = 99999999; int aabb_b = -99999999; Vector playerPos; // Calculate aabb for( int i = 0; i<4; i++ ) { if( m_pPlayers[i] ) { playerPos = m_pPlayers[i]->GetPosition(); if(aabb_l > (int) playerPos[0]) aabb_l = (int) playerPos[0]; if(aabb_r < (int) playerPos[0]) aabb_r = (int) playerPos[0]; if(aabb_t > (int) playerPos[1]) aabb_t = (int) playerPos[1]; if(aabb_b < (int) playerPos[1]) aabb_b = (int) playerPos[1]; std::vector<CWormHole*>& whs = GetUniverse()->m_vWormHoles; for(unsigned int w = 0; w < whs.size(); w++){ CWormHole* thisWH = whs[w]; Vector WHPos = thisWH->GetPosition(); float distance = (WHPos - playerPos).Length(); if( distance < thisWH->m_fZoomRadius){ float perc = 1 - (distance - thisWH->GetPhysicsData()->m_fRadius) / (thisWH->m_fZoomRadius - thisWH->GetPhysicsData()->m_fRadius); Vector DistanceToTwin = (thisWH->twin->GetPosition() - playerPos); Vector noticePoint = playerPos + DistanceToTwin*perc; if(aabb_l > (int) noticePoint[0]) aabb_l = (int) noticePoint[0]; if(aabb_r < (int) noticePoint[0]) aabb_r = (int) noticePoint[0]; if(aabb_t > (int) noticePoint[1]) aabb_t = (int) noticePoint[1]; if(aabb_b < (int) noticePoint[1]) aabb_b = (int) noticePoint[1]; } } } } // Desired view int view_l = aabb_l + (int) (SETS->VIEW_PERC * (float) (level_l - aabb_l)); int view_r = aabb_r + (int) (SETS->VIEW_PERC * (float) (level_r - aabb_r)); int view_b = aabb_b + (int) (SETS->VIEW_PERC * (float) (level_b - aabb_b)); int view_t = aabb_t + (int) (SETS->VIEW_PERC * (float) (level_t - aabb_t)); // Rescale view such that it's aspect ratio is 1024/768 // For correct aspect ratio, 4/3 = w/h ----> 4h = 3w -----> 0 = 4h - 3w int diff = 4*(view_b - view_t) - 3*(view_r - view_l); // , else enlarge height if( diff > 0 ){ // diff > 0 ---> 4h = 3w + diff ---> 4h > 3w ---> enlarge width view_l -= (diff / 6); view_r += (diff / 6); } else { // diff < 0 ---> 4h + diff = 3w ---> 4h < 3w ---> enlarge height view_t -= (diff / 8); view_b += (diff / 8); } // Correct view outside level if(view_l < level_l){ view_r += level_l - view_l; view_l = level_l; } else if(view_r > level_r){ view_l += level_r - view_r; view_r = level_r; } if(view_t < level_t){ view_b += level_t - view_t; view_t = level_t; } else if(view_b > level_b){ view_t += level_b - view_b; view_b = level_b; } // View has correct aspect ratio // Determine zoom-level float zoom = ((view_r - view_l) + 2* SETS->SCREEN_MARGIN) / 1024.0f; // w = zoom * 1024 --> zoom = w / 1024 if(zoom < SETS->MIN_ZOOM) zoom = SETS->MIN_ZOOM; // Determine center of view Vector view_center( (float) ((view_r + view_l) / 2), (float) ((view_t + view_b) / 2), 0.0f); /* Vector playerCenter; float c = 0; for ( int i = 0; i<4; i++ ) { if ( m_pPlayers[i] ) { playerCenter += m_pPlayers[i]->GetPosition(); c += 1.0f; } } playerCenter /= c; // Furthest distance float distance = 0.0f; for ( int i = 0; i<4; i++ ) { if ( m_pPlayers[i] ) { float d = (playerCenter - m_pPlayers[i]->GetPosition()).Length(); if ( d > distance ) distance = d; } } float zoom = distance / 300.0f; if ( zoom < SETS->MIN_ZOOM ) zoom = SETS->MIN_ZOOM; if ( zoom > SETS->MAX_ZOOM ) zoom = SETS->MAX_ZOOM; */ CRenderer::Instance()->SetCamera( view_center, zoom ); // Draw buoys int width_interval = (2*level_width + 2*SETS->BUOY_DISTANCE) / (SETS->BUOY_AMOUNT - 1); int height_interval = (2*level_height + 2*SETS->BUOY_DISTANCE) / (SETS->BUOY_AMOUNT - 1); SDL_Rect target, size; for(int i = 0; i < SETS->BUOY_AMOUNT - 1; i++){ size = m_pBuoyImage->GetSize(); target.w = size.w; target.h = size.h; if( i != 0){ // Vertical buoys target.y = i * height_interval - (level_height + SETS->BUOY_DISTANCE + target.h / 2); target.x = -(level_width + SETS->BUOY_DISTANCE) - (target.w / 2); RenderQuad(target, m_pBuoyImage, m_fBuoyAngle); target.x = (level_width + SETS->BUOY_DISTANCE) - (target.w / 2); RenderQuad(target, m_pBuoyImage, m_fBuoyAngle); } // Horizontal buoys target.x = i * width_interval - (level_width + SETS->BUOY_DISTANCE + target.w / 2); target.y = -(level_height + SETS->BUOY_DISTANCE) - (target.h / 2); RenderQuad( target, m_pBuoyImage, m_fBuoyAngle); target.y = (level_height + SETS->BUOY_DISTANCE) - (target.h / 2); RenderQuad( target, m_pBuoyImage, m_fBuoyAngle); } target.x = level_width + SETS->BUOY_DISTANCE - (target.w / 2); RenderQuad( target, m_pBuoyImage, m_fBuoyAngle); target.y = -(level_height + SETS->BUOY_DISTANCE) - (target.h / 2); RenderQuad( target, m_pBuoyImage, m_fBuoyAngle); } void CGameState::Update(float fTime) { m_fBuoyAngle += 1; m_pBuoyImage->UpdateFrame(fTime); if ( m_fCountDown > -2.0f ) m_fCountDown -= fTime; m_pHUD->SetCountdown( m_fCountDown ); if ( m_fCountDown <= 0.0f && m_fMatchTimeLeft > 0.0f ) { m_fMatchTimeLeft -= fTime; if ( m_fMatchTimeLeft < 0.0f ) m_fMatchTimeLeft = 0.0f; } m_pHUD->SetMatchTimeLeft( m_fMatchTimeLeft ); m_pUniverse->Update( fTime ); } bool CGameState::HandleWiimoteEvent( wiimote_t* pWiimoteEvent ) { if ( pWiimoteEvent->event == WIIUSE_EVENT ) { struct nunchuk_t* nc = (nunchuk_t*)&pWiimoteEvent->exp.nunchuk; if ( nc->js.mag > 0.3f ) { float angle = (nc->js.ang - 90.0f) * (3.14f / 180.0f); box.x += (int)(cos(angle) * (5.0f * nc->js.mag)); box.y += (int)(sin(angle) * (5.0f * nc->js.mag)); return true; } if ( m_fMatchTimeLeft <= 0.0f ) { if ( IS_JUST_PRESSED(pWiimoteEvent, WIIMOTE_BUTTON_A) || IS_JUST_PRESSED(pWiimoteEvent, WIIMOTE_BUTTON_B) ) m_bRunning = false; } if ( IS_JUST_PRESSED(pWiimoteEvent, WIIMOTE_BUTTON_MINUS) || IS_JUST_PRESSED(pWiimoteEvent, WIIMOTE_BUTTON_PLUS) ) { m_bRunning = false; } } return false; } int CGameState::HandleSDLEvent(SDL_Event event) { if ( event.type == SDL_QUIT ) { m_bRunning = false; m_bQuit = true; } if ( event.type == SDL_KEYUP ) { if ( event.key.keysym.sym == SDLK_SPACE ) { m_bRunning = false; } if ( event.key.keysym.sym == SDLK_ESCAPE ) { m_bRunning = false; m_bQuit = true; } } return 0; } int CGameState::GetScore( int iPlayer ) { if ( m_pPlayers[iPlayer] ) return m_pPlayers[iPlayer]->m_iScore; return -1; } void CGameState::AddScore( int iPlayer, int iScore, int iX, int iY ) { m_pHUD->AddScore( iPlayer, iScore, iX, iY ); } bool CGameState::IsPaused() { if ( m_fCountDown > 0.0f ) // 3-2-1 Go! paused { return true; } else { if ( m_fMatchTimeLeft > 0.0f ) // We are still playing { if ( m_iPlayerPaused == -1 ) return false; else return true; } else { // Game ended return true; } } } void CGameState::LoadCommonImages() { CResourceManager *pRMan = CResourceManager::Instance(); pRMan->GetResource( "media/images/explosion_large.png", RT_TEXTURE ); pRMan->GetResource( "media/images/explosion_particle.png", RT_TEXTURE ); pRMan->GetResource( "media/images/explosion_small.png", RT_TEXTURE ); pRMan->GetResource( "media/images/explosion_vaporize.png", RT_TEXTURE ); pRMan->GetResource( "media/images/hit.png", RT_TEXTURE ); pRMan->GetResource( "media/images/electric_green.png", RT_TEXTURE ); pRMan->GetResource( "media/images/electric_red.png", RT_TEXTURE ); pRMan->GetResource( "media/images/electric_blue.png", RT_TEXTURE ); pRMan->GetResource( "media/images/timefreeze.png", RT_TEXTURE ); pRMan->GetResource( "media/images/spark.png", RT_TEXTURE ); }
[ [ [ 1, 14 ], [ 16, 29 ], [ 33, 88 ], [ 90, 149 ], [ 241, 268 ], [ 270, 270 ], [ 311, 314 ], [ 319, 433 ] ], [ [ 15, 15 ], [ 30, 32 ], [ 89, 89 ], [ 150, 240 ], [ 269, 269 ], [ 271, 310 ], [ 315, 318 ] ] ]
8b10e1f9f179eaeab8aaeb55fb7efc7a2bf5c84c
cd0987589d3815de1dea8529a7705caac479e7e9
/webkit/WebKit/blackberry/Api/WebPage.h
e808323cf9cc5634c9f88637e69e9347191fbfbd
[ "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
10,767
h
/* * Copyright (C) Research In Motion Limited 2009-2010. All rights reserved. */ #ifndef WebPage_h #define WebPage_h #include "BlackBerryContext.h" #include "BlackBerryGlobal.h" #include "OlympiaPlatformInputEvents.h" #include "OlympiaPlatformKeyboardEvent.h" #include "OlympiaPlatformMisc.h" #include "OlympiaPlatformPrimitives.h" #include "OlympiaPlatformReplaceText.h" #include "WebString.h" #include "SharedPointer.h" #include "streams/NetworkRequest.h" #include <egl.h> struct OpaqueJSContext; typedef const struct OpaqueJSContext* JSContextRef; struct OpaqueJSValue; typedef const struct OpaqueJSValue* JSValueRef; namespace WebCore { class ChromeClientBlackBerry; class EditorClientBlackBerry; class Element; class Frame; class FrameLoaderClientBlackBerry; class JavaScriptDebuggerBlackBerry; class Node; class RenderObject; } class WebDOMDocument; class WebDOMNode; namespace Olympia { namespace WebKit { class BackingStore; class BackingStorePrivate; class DumpRenderTree; class RenderQueue; class ResourceHolder; class WebPageClient; class WebPageGroupLoadDeferrer; class WebPagePrivate; class WebPlugin; class WebSettings; enum MouseEventType { MouseEventMoved, MouseEventPressed, MouseEventReleased, MouseEventAborted }; class OLYMPIA_EXPORT WebPage { public: WebPage(WebPageClient*, const WebString& pageGroupName, const Platform::IntRect&); ~WebPage(); WebPageClient* client() const; void load(const char* url, const char* networkToken, bool isInitial = false); void loadExtended(const char* url, const char* networkToken, const char* method, Platform::NetworkRequest::CachePolicy cachePolicy = Platform::NetworkRequest::UseProtocolCachePolicy, const char* data = 0, size_t dataLength = 0, const char* const* headers = 0, size_t headersLength = 0, bool mustHandleInternally = false); void stopLoading(); typedef intptr_t BackForwardId; // returns false if there is no page for the given delta (eg. // attempt to go back with -1 when on the first page) bool goBackOrForward(int delta); void goToBackForwardEntry(BackForwardId); void reload(); void reloadFromCache(); WebSettings* settings() const; int width() const; int height() const; void setVisible(bool visible); bool isVisible() const; void setActualVisibleSize(int width, int height); void resetVirtualViewportOnCommitted(bool reset); void setVirtualViewportSize(int width, int height); // Used for default layout size unless overridden by web content or by other APIs void setDefaultLayoutSize(int width, int height); void setScreenRotated(const Platform::IntSize& screenSize, const Platform::IntSize& defaultLayoutSize, const Platform::IntRect& viewportRect); void setScreenOrientation(int orientation); // FIXME: setPlatformScreenSize, and setApplicationViewSize don't pertain to an actual web page. // Instead, these methods belong in somekind of window/view class. void setPlatformScreenSize(int width, int height); void setApplicationViewSize(int width, int height); void setFocused(bool focused); void mouseEvent(MouseEventType, const Platform::IntPoint& pos, const Platform::IntPoint& globalPos); // Handles native javascript touch events bool touchEvent(Olympia::Platform::TouchEvent&); // For conversion to mouse events void touchEventCancel(); void touchEventCancelAndClearFocusedNode(); bool singleTouchEvent(Olympia::Platform::SingleTouchEvent&); // Returns true if the key stroke was handled by webkit. bool keyEvent(Olympia::Platform::KeyboardEvent::Type type, const unsigned short character, bool shiftDown = false, bool altDown = false); void navigationMoveEvent(const unsigned short character, bool shiftDown, bool altDown); WebString selectedText() const; // scroll position returned is in transformed coordinates Platform::IntPoint scrollPosition() const; // scroll position provided should be in transformed coordinates void setScrollPosition(const Platform::IntPoint&); BackingStore* backingStore() const; bool zoomIn(); bool zoomOut(); bool zoomToFit(); bool zoomToOneOne(); void zoomToInitialScale(); bool bitmapZoom(int x, int y, double scale, bool shouldZoomAboutPoint = true); bool blockZoom(int x, int y); bool isAtInitialZoom() const; bool isMaxZoomed() const; bool isMinZoomed() const; double initialScale() const; void setInitialScale(double); double minimumScale() const; void setMinimumScale(double); double maximumScale() const; void setMaximumScale(double); double currentZoomLevel() const; // FIXME - needs to be renamed currentScale() bool moveToNextField(Olympia::Platform::ScrollDirection, int desiredScrollAmount); Olympia::Platform::IntRect focusNodeRect(); bool focusField(bool focus); bool linkToLinkOnClick(); void runLayoutTests(); /** * Finds and selects the next utf8 string that is a case sensitive * match in the web page. It will wrap the web page if it reaches * the end. An empty string will result in no match and no selection. * * Returns true if the string matched and false if not. */ bool findNextString(const char*); /** * Finds and selects the next unicode string. This is a case * sensitive search that will wrap if it reaches the end. An empty * string will result in no match and no selection. * * Returns true if the string matched and false if not. */ bool findNextUnicodeString(const unsigned short*); /* JavaScriptDebugger interface */ bool enableScriptDebugger(); bool disableScriptDebugger(); JSContextRef scriptContext() const; JSValueRef windowObject() const; /* Media Plugin interface */ void cancelLoadingPlugin(int id); void removePluginsFromList(); void cleanPluginListFromFrame(WebCore::Frame* frame); void mediaReadyStateChanged(int id, int state); void mediaVolumeChanged(int id, int volume); void mediaDurationChanged(int id, float duration); WebDOMDocument document() const; void addBreakpoint(const unsigned short* url, unsigned urlLength, unsigned lineNumber, const unsigned short* condition, unsigned conditionLength); void updateBreakpoint(const unsigned short* url, unsigned urlLength, unsigned lineNumber, const unsigned short* condition, unsigned conditionLength); void removeBreakpoint(const unsigned short* url, unsigned urlLength, unsigned lineNumber); bool pauseOnExceptions(); void setPauseOnExceptions(bool pause); void pauseInDebugger(); void resumeDebugger(); void stepOverStatementInDebugger(); void stepIntoStatementInDebugger(); void stepOutOfFunctionInDebugger(); void requestElementText(int requestedFrameId, int requestedElementId, int offset, int length); void selectionChanged(); void setCaretPosition(int requestedFrameId, int requestedElementId, int caretPosition); void setCaretHighlightStyle(Platform::CaretHighlightStyle); Olympia::Platform::IntRect rectForCaret(int index); Olympia::Platform::ReplaceTextErrorCode replaceText(const Olympia::Platform::ReplaceArguments&, const Olympia::Platform::AttributedText&); void setSelection(const Platform::IntPoint& startPoint, const Platform::IntPoint& endPoint); void selectAtPoint(const Platform::IntPoint&); void selectionCancelled(); void popupListClosed(const int size, bool* selecteds); void popupListClosed(const int index); void setDateTimeInput(const WebString& value); void setColorInput(const WebString& value); void onInputLocaleChanged(bool isRTL); Olympia::WebKit::Context getContext() const; struct BackForwardEntry { WebString url; WebString title; WebString networkToken; BackForwardId id; }; void getBackForwardList(SharedArray<BackForwardEntry>& result, unsigned int& resultLength) const; void releaseBackForwardEntry(BackForwardId) const; void clearBackForwardList(bool keepCurrentPage) const; ResourceHolder* getImageFromContext(); void addVisitedLink(const unsigned short* url, unsigned int length); WebDOMNode nodeAtPoint(int x, int y); bool getNodeRect(const WebDOMNode&, Platform::IntRect& result); bool setNodeFocus(const WebDOMNode&, bool on); bool setNodeHovered(const WebDOMNode&, bool on); bool nodeHasHover(const WebDOMNode&); bool defersLoading() const; bool willFireTimer(); void clearStorage(); private: friend class Olympia::WebKit::BackingStorePrivate; friend class Olympia::WebKit::DumpRenderTree; friend class Olympia::WebKit::RenderQueue; friend class Olympia::WebKit::WebPageGroupLoadDeferrer; friend class Olympia::WebKit::WebPlugin; friend class WebCore::ChromeClientBlackBerry; friend class WebCore::EditorClientBlackBerry; friend class WebCore::FrameLoaderClientBlackBerry; friend class WebCore::JavaScriptDebuggerBlackBerry; WebPagePrivate* d; }; } } #endif // WebPage_h
[ [ [ 1, 266 ] ] ]
55c58c17f1564c3bb629c0634e946e6beee94326
9c62af23e0a1faea5aaa8dd328ba1d82688823a5
/rl/tags/techdemo2/engine/core/include/AnimationManager.h
360c9f7841d63373b5a7b5cb1998e86d79bcd971
[ "ClArtistic", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
jacmoe/dsa-hl-svn
55b05b6f28b0b8b216eac7b0f9eedf650d116f85
97798e1f54df9d5785fb206c7165cd011c611560
refs/heads/master
2021-04-22T12:07:43.389214
2009-11-27T22:01:03
2009-11-27T22:01:03
null
0
0
null
null
null
null
ISO-8859-1
C++
false
false
5,759
h
/* This source file is part of Rastullahs Lockenpracht. * Copyright (C) 2003-2005 Team Pantheon. http://www.team-pantheon.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the Clarified Artistic License. * * 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 * Clarified Artistic License for more details. * * You should have received a copy of the Clarified Artistic License * along with this program; if not you can get it here * http://www.jpaulmorrison.com/fbp/artistic2.htm. */ #ifndef __AnimationManager_H__ #define __AnimationManager_H__ #include <map> #include <set> #include <OgreSingleton.h> #include "GameTask.h" #include "CorePrerequisites.h" namespace rl { class Actor; class BaseAnimation; class MeshAnimation; class TrackAnimation; class FadeAnimation; class MeshObject; /** Diese Klasse verwaltet sämtliche Animationen und kümmert sich um das Starten und Stoppen dieser @see Animation, TrackAnimation */ class _RlCoreExport AnimationManager : public GameTask, protected Ogre::Singleton<AnimationManager> { public: /// Interpolations-Modus, Spline ist besser, braucht auch mehr Perfomance enum InterpolationMode { IM_LINEAR, IM_SPLINE }; /// RotationsInterpolations-Modus, Spherical ist genauer, aber aufwändiger enum RotationInterpolationMode { RIM_LINEAR, RIM_SPHERICAL }; /** Default Constructor */ AnimationManager( ); /** Default Deconstructor */ virtual ~AnimationManager(); /** Erzeugt eine Animation, trägt diese ein und beginnt sofort mit dem Abspielen, wenn gewünscht. @param animState Der AnimationState @param speed Die Geschwindigkeit, 1.0 Originalgeschw. @param timesToPlay Die Wiederholungen @see Animation */ MeshAnimation* addMeshAnimation(Ogre::AnimationState* animState, MeshObject* mesh, Ogre::Real speed=1.0, unsigned int timesToPlay=0, bool paused=false ); /** Gibt die Animation zurück, die zum AnimationState gehört * @returns NULL wenn es die Animation nicht gibt */ BaseAnimation* getAnimation(Ogre::AnimationState* animState) const; /// Entfernt eine Animation, und stoppt das Abspielen dieser void removeAnimation(Ogre::AnimationState* animState); /// Checks if an Animation is still used in another Animation for Example in a FadeAnimation bool isStillInUse( BaseAnimation* anim ) const; /** Erzeugt eine neue, leere TrackAnimation, der der SceneNode des Actors zugeordnet wird. @param actor Der zugeordnete Actor @param name Der einzigartige Name der Animation @param length Die gewünschte Länge des Tracks */ TrackAnimation* createTrackAnimation(Actor* actor, const Ogre::String& name, Ogre::Real length ); /// Entfernt alle Animationen void removeAllAnimations(); /// Entfernt eine Animation void removeAnimation(TrackAnimation* anim); void removeAnimation(MeshAnimation* anim); void removeAnimation(FadeAnimation* anim); /// Ersetzt eine alte Animation durch eine Neue MeshAnimation* replaceAnimation(MeshAnimation* oldAnim, Ogre::AnimationState* newAnimState, Ogre::Real speed=1.0, unsigned int timesToPlay=0 ); /// Entfernt eine TrackAnimation dieses Actors void removeTrackAnimation( Actor* act, const Ogre::String& name ); /// Entfernt alle TrackAnimations dieses Actors void removeAllTrackAnimations( Actor* act ); /// Blendet von Animation 'from' zu 'to' über FadeAnimation* fadeAnimation( MeshAnimation* from, MeshAnimation* to, Ogre::Real time ); /** Blendet Animationen von nach über, wenn loopDuration nicht * größer 0 ist, wird hier die Dauer der Animation genommen * @todo Rückwärts anschauen, Geschwindigkeit */ FadeAnimation* fadeAnimation( MeshAnimation* fromLoop, MeshAnimation* blendAnim, MeshAnimation* toLoop, Ogre::Real loopDuration = 0.0 ); /** Globale Beschleunigung, für SlowMotion oder andere sinnige Effekte @param speed Der Beschleunigungsfaktor. @remarks Negative Werte lassen das Spiel nicht rückwärts laufen, nur die Animationen. */ void setGlobalAnimationSpeed( Ogre::Real speed ); /// Gibt die globale Beschleunigung zurück Ogre::Real getGlobalAnimationSpeed( ) const; /// Setzt den StandardInterpolationsModus für neue Animationen void setDefaultInterpolationMode( AnimationManager::InterpolationMode im ); /// Gibt den StandardInterpolationsModus für neue Animationen zurück AnimationManager::InterpolationMode getDefaultInterpolationMode() const; /// Setzt den StandardRotationsInterpolationsModus für neue Animationen void setDefaultRotationInterpolationMode( AnimationManager::RotationInterpolationMode rim ); /// Gibt den Standard RotationsInterpolationsModus für neue Animationen zurück AnimationManager::RotationInterpolationMode getDefaultRotationInterpolationMode() const; /// Geerbt von GameTask, wird in jedem Frame mit der vergangenen Zeit aufgerufen virtual void run(Ogre::Real timePassed); /// Singleton static AnimationManager & getSingleton(void); /// Singleton static AnimationManager * getSingletonPtr(void); private: static void stopAnimation( BaseAnimation* anim ); typedef std::set<FadeAnimation*> FadeAnimSet; FadeAnimSet mFadeAnimSet; typedef std::map<Ogre::AnimationState*,BaseAnimation*> StateAnimMap; StateAnimMap mStateAnimationMap; /// Die globale Beschleunigung Ogre::Real mGlobalAnimationSpeed; }; } #endif
[ "tanis@4c79e8ff-cfd4-0310-af45-a38c79f83013" ]
[ [ [ 1, 148 ] ] ]
a423f97e415c83d8347612cbb65555361daa3ce1
72071dfcccdab286fce3b0d4483d9e075f0a2ae3
/ScoreSystem.cpp
82c5c76327cc2c9faad49a8fdd62c10ab19e10b1
[]
no_license
rickumali/RicksTetris
bc824d25ca6403cd12891aa2eae59fc5c6c41a9c
76128d72f0cfb75ff4d619784c70fec9562d5c71
refs/heads/master
2016-09-06T04:27:15.587789
2011-12-23T18:17:10
2011-12-23T18:17:10
3,043,175
2
0
null
null
null
null
UTF-8
C++
false
false
887
cpp
#include <fstream> #include <time.h> #include "ScoreSystem.h" using namespace std; // Constructor ScoreSystem::ScoreSystem() { current_score = 0; level = 1; } void ScoreSystem::set_current_score(int score) { current_score = score; } void ScoreSystem::add_to_current_score(int score) { current_score += score; } int ScoreSystem::get_current_score() { return(current_score); } void ScoreSystem::write_score_to_file() { time_t rawtime; rawtime = time(NULL); ofstream scorefile; scorefile.open("scores.txt",ios::app|ios::out); if (!scorefile.fail()) { scorefile << rawtime << " " << current_score << " " << level << endl; scorefile.close(); } } int ScoreSystem::get_level() { return(level); } void ScoreSystem::increment_level() { level++; if (level > 999999) { level = 1000000; // Cap level at 1M } }
[ [ [ 1, 46 ] ] ]
ccaf1afafbd0ea24f5cac41096719a46ad8f73e7
28e96305e2659b581a6a8002c795e52dd6fbd53c
/zTextEdit/main.cpp
4fd4615b3bf68ff2454cb8ff190d44148d787d47
[]
no_license
situr/open-magx-src
970cd649903b223292d9274478d97f161ba52006
87bea580360c7fcf8270b642cc38b65252e6b1cc
refs/heads/master
2020-12-25T09:47:07.262768
2011-11-16T03:37:49
2011-11-16T03:37:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
620
cpp
// // C++ Implementation: TestMain // // Description: // // // Author: BeZ <[email protected]>, (C) 2008 // Author: Ant-ON <[email protected]>, (C) 2009 // // Copyright: See COPYING file that comes with this distribution // // #include "zgui.h" #include <ZApplication.h> #include "lng.h" ZGui* zgui; ZApplication* app; ZLng * lng; int main ( int argc, char **argv ) { app = new ZApplication ( argc, argv ); int ret; lng = new ZLng(); zgui = new ZGui ( NULL, NULL ); app->setMainWidget(zgui); ret = app->exec(); delete zgui; zgui = NULL; delete app; app = NULL; return ret; }
[ [ [ 1, 34 ] ] ]
b65373e97fb44e2f88ebac565d72076c5d68b2f6
b7c505dcef43c0675fd89d428e45f3c2850b124f
/Src/SimulatorQt/Util/qt/Win32/include/QtGui/qwindowsmobilestyle.h
15f12e26ab5cfca8767eb82d2fb2c4eafd517a21
[ "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
4,307
h
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information ([email protected]) ** ** This file is part of the QtGui 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 QWINDOWSMOBILESTYLE_H #define QWINDOWSMOBILESTYLE_H #include <QtGui/qwindowsstyle.h> QT_BEGIN_HEADER QT_BEGIN_NAMESPACE QT_MODULE(Gui) #if !defined(QT_NO_STYLE_WINDOWSMOBILE) class QWindowsMobileStylePrivate; class Q_GUI_EXPORT QWindowsMobileStyle : public QWindowsStyle { Q_OBJECT public: QWindowsMobileStyle(); void drawPrimitive(PrimitiveElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget = 0) const; void drawControl(ControlElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget) const; void drawComplexControl(ComplexControl control, const QStyleOptionComplex *option, QPainter *painter, const QWidget *widget) const; QSize sizeFromContents(ContentsType type, const QStyleOption *option, const QSize &size, const QWidget *widget) const; QRect subElementRect(SubElement element, const QStyleOption *option, const QWidget *widget) const; QRect subControlRect(ComplexControl cc, const QStyleOptionComplex *opt, SubControl sc, const QWidget *widget) const; QPixmap generatedIconPixmap(QIcon::Mode iconMode, const QPixmap &pixmap, const QStyleOption *option) const; QPixmap standardPixmap(StandardPixmap sp, const QStyleOption *option, const QWidget *widget) const; int pixelMetric(PixelMetric metric, const QStyleOption *option = 0, const QWidget *widget = 0) const; int styleHint(StyleHint hint, const QStyleOption *opt = 0, const QWidget *widget = 0, QStyleHintReturn *returnData = 0) const; void polish(QApplication*); void unpolish(QApplication*); void polish(QWidget *widget); void unpolish(QWidget *widget); void polish(QPalette &); QPalette standardPalette() const; bool doubleControls() const; void setDoubleControls(bool); protected: QWindowsMobileStyle(QWindowsMobileStylePrivate &dd); private: Q_DECLARE_PRIVATE(QWindowsMobileStyle) }; #endif // QT_NO_STYLE_WINDOWSMOBILE QT_END_NAMESPACE QT_END_HEADER #endif //QWINDOWSMOBILESTYLE_H
[ "alon@rogue.(none)" ]
[ [ [ 1, 116 ] ] ]
f1913eab85598e4f277d9d984def9ddb72c9a2f3
09e322e0db32ccd7c0a8aaa357fb8763c43bf1bf
/PComImpl/registry.cpp
cb008f5c52b334ec6599bf076d582fe24cdc418e
[]
no_license
chrisforbes/profiler
165ba38c01fcb10174973430f0ebbbbff84dc6f6
02111db2d065f385bdac7767a340e5c1f4ae974e
refs/heads/master
2020-05-20T01:56:53.481186
2009-10-02T10:30:27
2009-10-02T10:30:27
324,424
5
1
null
null
null
null
UTF-8
C++
false
false
2,062
cpp
#define WIN32_LEAN_AND_MEAN #define WIN32_ULTRA_LEAN #define _CRT_SECURE_NO_WARNINGS #include <windows.h> #include <shlwapi.h> HINSTANCE hinst; static const char * progId = "IjwProfiler"; #define PROFILER_GUID "{C1E9FE1F-F517-45c0-BB0E-EFAECC9401FC}" extern const GUID __declspec( selectany ) CLSID_PROFILER; #pragma comment( lib, "shlwapi.lib" ) BOOL WINAPI DllMain( HINSTANCE hInstance, DWORD dwReason, void * ) { if (DLL_PROCESS_ATTACH == dwReason) DisableThreadLibraryCalls( hinst = hInstance ); return TRUE; } HKEY OpenKey( HKEY parent, char const* name ) { HKEY result; if (ERROR_SUCCESS != RegCreateKeyExA( parent, name, 0, 0, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, 0, &result, 0 )) { ::MessageBoxA( 0, name, "Failed to create key", MB_OK ); } return result; } void CloseKey( HKEY key ) { RegCloseKey( key ); } void SetValue( HKEY key, char const* name, char const* value ) { RegSetValueExA( key, name, 0, REG_SZ, (BYTE const *)value, strlen( value ) ); } STDAPI DllUnregisterServer() { HKEY kSoftware = OpenKey( HKEY_CURRENT_USER, "Software" ); HKEY kClasses = OpenKey( kSoftware, "Classes" ); HKEY kClsid = OpenKey( kClasses, "CLSID" ); HKEY kApp = OpenKey( kClsid, PROFILER_GUID ); SHDeleteKeyA( kClsid, PROFILER_GUID ); CloseKey( kClsid ); CloseKey( kClasses ); CloseKey( kSoftware ); return S_OK; } STDAPI DllRegisterServer() { char szModule[_MAX_PATH]; GetModuleFileNameA( hinst, szModule, _MAX_PATH ); HKEY kSoftware = OpenKey( HKEY_CURRENT_USER, "Software" ); HKEY kClasses = OpenKey( kSoftware, "Classes" ); HKEY kClsid = OpenKey( kClasses, "CLSID" ); HKEY kGuid = OpenKey( kClsid, PROFILER_GUID ); HKEY kInProc = OpenKey( kGuid, "InProcServer32" ); SetValue( kGuid, "", "IJW Sampling Profiler" ); SetValue( kInProc, "", szModule ); SetValue( kInProc, "ThreadingModel", "Both" ); CloseKey( kInProc ); CloseKey( kGuid ); CloseKey( kClsid ); CloseKey( kClasses ); CloseKey( kSoftware ); return S_OK; }
[ "chrisf@993157c7-ee19-0410-b2c4-bb4e9862e678", "bob@993157c7-ee19-0410-b2c4-bb4e9862e678" ]
[ [ [ 1, 1 ], [ 3, 22 ], [ 24, 25 ], [ 27, 28 ], [ 30, 38 ], [ 40, 40 ], [ 42, 83 ] ], [ [ 2, 2 ], [ 23, 23 ], [ 26, 26 ], [ 29, 29 ], [ 39, 39 ], [ 41, 41 ] ] ]
54a155ea184672c3b1384eac22c06b1db46addaa
d9a78f212155bb978f5ac27d30eb0489bca87c3f
/PB/src/PbRpc/rpcurl.h
2f31aac3b8952ea0d4571b0efd15ead44de5ed6c
[]
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,739
h
#pragma once class PB_EXPORT RpcUrl { public: RpcUrl(){ host = anyHost; path = ""; } RpcUrl(const RpcUrl &other) { *this = other; } static const char *anyHost; RpcUrl(const QString &p,const QString &h=anyHost){host=h;path=p;} RpcUrl &operator=(const RpcUrl &other) { host = other.host; path = other.path; return *this; } bool parse(QString &s) { int i = s.indexOf("/"); if(i<0) { host=anyHost; path=s; }else { host=s.left(i); path=s.mid(i+1); } return true; } bool match(const RpcUrl &mask) const { if(host!=mask.host && mask.host!=anyHost) return false; if(path!=mask.path) return false; return true; } bool isEmpty() const { return path.isEmpty(); } bool operator==(const RpcUrl &other) const { return host==other.host && path==other.path; } bool operator<(const RpcUrl &other) const { return toString()<other.toString(); } RpcUrl &setPath(const QString &aPath){ path= aPath; return *this;} void clear(){ host = ""; path = ""; } QString toString() const{return host+"/"+path;} static RpcUrl remote(QString path); public: QString host; QString path; }; class PB_EXPORT RpcMethod : public RpcUrl { public: RpcMethod(){ } RpcMethod(const RpcMethod &other) { *this = other; } RpcMethod(const RpcUrl &other, const QString &m) { *static_cast<RpcUrl*>(this) = other; method = m; } RpcMethod &operator=(const RpcMethod &other) { RpcUrl::operator=(other); method = other.method; return *this; } bool operator==(const RpcMethod &other) { return RpcUrl::operator==(other) && method == other.method; } public: QString method; };
[ "mikhail.mitkevich@a5377438-2eb2-11df-b28a-19025b8c0740" ]
[ [ [ 1, 97 ] ] ]
1001b9fb21deda06af26740abbc55df685245918
0b66a94448cb545504692eafa3a32f435cdf92fa
/tags/0.5/cbear.berlios.de/windows/usb/archive.hpp
6a0e4e6862825e0cde17e9510c0c361ecb023c06
[ "MIT" ]
permissive
BackupTheBerlios/cbear-svn
e6629dfa5175776fbc41510e2f46ff4ff4280f08
0109296039b505d71dc215a0b256f73b1a60b3af
refs/heads/master
2021-03-12T22:51:43.491728
2007-09-28T01:13:48
2007-09-28T01:13:48
40,608,034
0
0
null
null
null
null
UTF-8
C++
false
false
6,871
hpp
/* The MIT License Copyright (c) 2005 C Bear (http://cbear.berlios.de) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef CBEAR_BERLIOS_DE_WINDOWS_USB_ARCHIVE_HPP_INCLUDED #define CBEAR_BERLIOS_DE_WINDOWS_USB_ARCHIVE_HPP_INCLUDED #include <cbear.berlios.de/windows/handle.hpp> namespace cbear_berlios_de { namespace windows { namespace usb { namespace detail { template<class Archive> class oarchive_t { public: typedef boost::mpl::true_ is_saving; template<class T> oarchive_t &operator &(const T &X) { this->archive().save(X); return *this; } template<class T> oarchive_t &operator<<(const T &X) { this->archive().save(X); return *this; } protected: ~oarchive_t() {} private: Archive &archive() { return *static_cast<Archive *>(this); } }; template<class Archive> class iarchive_t { public: template<class T> iarchive_t &operator &(T &X) { this->archive().load(X); return *this; } template<class T> iarchive_t &operator>>(const T &X) { this->archive().load(X); return *this; } protected: ~iarchive_t() {} private: Archive &archive() { return *static_cast<Archive *>(this); } }; } template<std::size_t InSize, std::size_t OutSize> class static_store_t { public: static_store_t() { this->reset(); } void reset() { this->end = buffer.begin(); } byte_range iobuffer() { return byte_range_t(this->buffer); } byte_range ibuffer() { return byte_range_t(&this->buffer.front(), &this->buffer[InSize]); } byte_range obuffer() { return byte_range_t(&this->buffer.front(), &this->buffer[OutSize]); } protected: template<class T> void save_pod(const T &X) { BOOST_ASSERT(this->buffer.end() - this->end >= sizeof(T)); reinterpret_cast<T &>(*this->end) = X; this->end += sizeof(T); } template<class T> void load_pod(T &X) { BOOST_ASSERT(this->buffer.end() - this->end >= sizeof(T)); X = reinterpret_cast<const T &>(*this->end); this->end += sizeof(T); } private: static const std::size_t Size = InSize < OutSize ? OutSize: InSize; typedef boost::array<byte_t, Size> array_t; array_t buffer; typename array_t::iterator end; }; template<class Store> class archive_t: boost::noncopyable, public Store, public detail::iarchive_t<archive_t<Store> >, public detail::oarchive_t<archive_t<Store> > { public: typedef detail::oarchive_t<archive_t> oarchive_t; typedef detail::iarchive_t<archive_t> iarchive_t; typedef oarchive_t &oarchive_ref; typedef iarchive_t &iarchive_ref; oarchive_ref oarchive() { return *this; } iarchive_ref iarchive() { return *this; } // version static const unsigned int version = 0; // struct template<class T> void save( const T &X, typename boost::enable_if<boost::is_class<T> >::type *dummy = 0) { boost::serialization::serialize( oarchive_ref(*this), const_cast<T &>(X), version); } template<class T> void load( T &X, typename boost::enable_if<boost::is_class<T> >::type *dummy = 0) { boost::serialization::serialize( iarchive_ref(*this), X, version); } // enum template<class T> void save( const T &X, typename boost::enable_if<boost::is_enum<T> >::type *dummy = 0) { this->save(static_cast<const int &>(X)); } template<class T> void load( T &X, typename boost::enable_if<boost::is_enum<T> >::type *dummy = 0) { this->load(static_cast<int &>(X)); } // byte void save(windows::byte_t X) { this->Store::save_pod(X); } void load(windows::byte_t &X) { this->Store::load_pod(X); } // ushort void save(windows::ushort_t X) { // big-endian this->save(base::high(X)); this->save(base::low(X)); } void load(windows::ushort_t &X) { // big-endian this->load(base::high(X)); this->load(base::low(X)); } // short void save(windows::short_t X) { // big-endian this->save(base::high(X)); this->save(base::low(X)); } void load(windows::short_t &X) { // big-endian this->load(base::high(X)); this->load(base::low(X)); } // ulong void save(windows::ulong_t X) { // big-endian this->save(base::high(X)); this->save(base::low(X)); } void load(windows::ulong_t &X) { // big-endian this->load(base::high(X)); this->load(base::low(X)); } // long void save(windows::long_t X) { // big-endian this->save(base::high(X)); this->save(base::low(X)); } void load(windows::long_t &X) { // big-endian this->load(base::high(X)); this->load(base::low(X)); } // int void save(int X) { // big-endian this->save(base::high(X)); this->save(base::low(X)); } void load(int &X) { // big-endian this->load(base::high(X)); this->load(base::low(X)); } // unsigned int void save(unsigned int X) { // big-endian this->save(base::high(X)); this->save(base::low(X)); } void load(unsigned int &X) { // big-endian this->load(base::high(X)); this->load(base::low(X)); } // float void save(float X) { this->Store::save_pod(X); } void load(float &X) { this->Store::load_pod(X); } // double void save(double X) { this->Store::save_pod(X); } void load(double &X) { this->Store::load_pod(X); } }; template<std::size_t InSize, std::size_t OutSize> class static_archive_t: public archive_t<static_archive_t<InSize, OutSize> > { }; /* class io_t: handle_t { public: io_t(const handle_t &handle): handle(handle) {} template<std::size_t InSize, std::size_t OutSize> class archive_t: public usb::archive_t<InSize, OutSize> {}; template<ArchiveT> void operator()(ArchiveT &archive) const { this->DeviceIoControl(archive.in(), archive.out()); archive.reset(); } }; */ } } } #endif
[ "sergey_shandar@e6e9985e-9100-0410-869a-e199dc1b6838" ]
[ [ [ 1, 322 ] ] ]
4cd1037e56481c599ab3864393ba96f8c5904da5
4e708256396ac2e5374286018174f01497c9a7e9
/phonetheater/todayshow.h
e43342ab7eb209c449cea1406a74b1673ce7715e
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
momofarm/MobileTheater
8bcea21e178077cebe2683422e9869cca14df374
921f60b6ea520fa23d46c3f9d6b16f7955f12514
refs/heads/master
2021-01-10T20:44:23.134327
2010-09-29T07:27:36
2010-09-29T07:27:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
599
h
#ifndef TODAYSHOW_H #define TODAYSHOW_H #include <QDialog> #include <QObject> #include <QLabel> #include <QListView> #include <QVector> class QTodayShow : public QDialog { Q_OBJECT public: QTodayShow(QStringList aryName, QStringList aryHall, QStringList aryTime, QWidget *parent = 0); void SetInfo(QString strTheaterName, QString strTheaterPhone, QString StrTheaterAddress); protected: QLabel *labelName; QLabel *labelAddr; QLabel *labelPhone; QVector<QListView *> arListViews; public slots: void HideAll(); }; #endif // TODAYSHOW_H
[ [ [ 1, 28 ] ] ]
97229ba275db18ca4b43ce7663cfb02c2dea9775
559770fbf0654bc0aecc0f8eb33843cbfb5834d9
/haina/codes/beluga/client/moblie/BelugaDb/inc/message/CMsgDb.h
65dc8da5b0edc41099b6600dbe1db79b60dc18ef
[]
no_license
CMGeorge/haina
21126c70c8c143ca78b576e1ddf352c3d73ad525
c68565d4bf43415c4542963cfcbd58922157c51a
refs/heads/master
2021-01-11T07:07:16.089036
2010-08-18T09:25:07
2010-08-18T09:25:07
49,005,284
1
0
null
null
null
null
UTF-8
C++
false
false
3,977
h
/* ============================================================================ Name : CMsgDb.h Author : shaochuan.yang Copyright : haina Description : Msg Database ============================================================================ */ #ifndef __CMSGDB_H__ #define __CMSGDB_H__ #include <time.h> #include "CEntityDb.h" #include "CMsg.h" #include "CMsgIterator.h" #include "CQuickMsg.h" #include "CQuickMsgIterator.h" #include "CMsgFace.h" #include "CMsgFaceIterator.h" #include "CSignature.h" #include "CSignatureIterator.h" class CMsgDb : public CEntityDb { public: IMPORT_C CMsgDb(); IMPORT_C ~CMsgDb(); IMPORT_C gint32 InitEntityDb(gchar* dbName); IMPORT_C gint32 getMaxMsgId(guint32 * pMaxMsgId); IMPORT_C gint32 getMaxQuickMsgId(guint32 * pMaxQuickMsgId); IMPORT_C gint32 getMaxSignatureId(guint32 * pMaxSigId); IMPORT_C gint32 getMaxMsgFaceId(guint32 * pMaxFaceId); IMPORT_C gint32 getMsgById(guint32 nMsgId, CMsg** ppMsg); IMPORT_C gint32 getQuickMsgById(guint32 nQuickMsgId, CQuickMsg** ppMsg); IMPORT_C gint32 getSignatureById(guint32 nSignatureId, CSignature** ppSig); IMPORT_C gint32 getMsgFaceById(guint32 nMsgFaceId, CMsgFace** ppFace); IMPORT_C gint32 saveMsg(CMsg * ppMsg); IMPORT_C gint32 saveQuickMsg(CQuickMsg * pMsg); IMPORT_C gint32 saveSignature(CSignature * pSig); IMPORT_C gint32 saveMsgFace(CMsgFace * pFace); IMPORT_C gint32 updateMsg(CMsg * pMsg); IMPORT_C gint32 updateQuickMsg(CQuickMsg * pMsg); IMPORT_C gint32 updateSignature(CSignature * pSig); IMPORT_C gint32 updateMsgFace(CMsgFace * pFace); IMPORT_C gint32 deleteMsg(guint32 nMsgId); IMPORT_C gint32 deleteQuickMsg(guint32 nMsgId); IMPORT_C gint32 deleteSignature(guint32 nSigId); IMPORT_C gint32 deleteMsgFace(guint32 nFaceId); /* delete all msgs sent to and received from a contact */ IMPORT_C gint32 deleteAllMsgsByContact(guint32 nContactId); IMPORT_C gint32 deleteAllMsgs(); IMPORT_C gint32 getMsgsTotality(guint32 &totality); IMPORT_C gint32 getMsgsTotalityByContact(guint32 nContactId, guint32 &totality); /* msgs totality from the time on */ IMPORT_C gint32 getMsgsTotalityByContact(guint32 nContactId, tm time, guint32 &totality); IMPORT_C gint32 getMsgsTotalityByGroup(guint32 nGroupId, guint32 &totality); IMPORT_C gint32 getMsgFacesTotality(guint32 &totality); IMPORT_C gint32 getSignaturesTotality(guint32 &totality); IMPORT_C gint32 getQuickMsgsTotality(guint32 &totality); IMPORT_C gint32 getAllMsgFaces(CMsgFaceIterator ** ppMsgFaceIterator); IMPORT_C gint32 getAllSignatures(CSignatureIterator ** ppSigIterator); IMPORT_C gint32 getAllQuickMsgs(CQuickMsgIterator ** ppQuickMsgIterator); IMPORT_C gint32 searchMsgs(GArray * fieldsIndex, GPtrArray * fieldsValue, guint32 limit, guint32 offset, CMsgIterator ** ppMsgIterator); /* search msgs sent to and received from a contact */ IMPORT_C gint32 searchMsgsByContact(guint32 nContactId, guint32 limit, guint32 offset, CMsgIterator ** ppMsgIterator); /* search msgs sent to and received from a contact base on time */ IMPORT_C gint32 searchMsgsByContact(guint32 nContactId, tm time, guint32 limit, guint32 offset, CMsgIterator ** ppMsgIterator); /* search msgs sent to and received from a group */ IMPORT_C gint32 searchMsgsByGroup(guint32 nGroupId, guint32 limit, guint32 offset, CMsgIterator ** ppMsgIterator); /* search msgs sent to and received from a group base on time */ IMPORT_C gint32 searchMsgsByGroup(guint32 nGroupId, tm time, guint32 limit, guint32 offset, CMsgIterator ** ppMsgIterator); IMPORT_C gchar * getDbPath(); private: GPtrArray * m_pMsgTableFieldsName; GPtrArray * m_pQuickMsgTableFieldsName; GPtrArray * m_pMsgFaceTableFieldsName; GPtrArray * m_pSignatureTableFieldsName; }; #endif
[ "shaochuan.yang@6c45ac76-16e4-11de-9d52-39b120432c5d" ]
[ [ [ 1, 97 ] ] ]