<commit_before>/*
 * Copyright 2003,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.
 */

#ifndef PSVIWRITERHANDLER_HPP
#define PSVIWRITERHANDLER_HPP

// ---------------------------------------------------------------------------
//  Includes
// ---------------------------------------------------------------------------
#include <xercesc/sax2/Attributes.hpp>
#include <xercesc/sax2/DefaultHandler.hpp>
#include <xercesc/framework/psvi/XSConstants.hpp>
#include <xercesc/framework/psvi/PSVIHandler.hpp>
#include <xercesc/framework/psvi/PSVIAttribute.hpp>
#include <xercesc/framework/psvi/PSVIAttributeList.hpp>
#include <xercesc/framework/psvi/PSVIElement.hpp>
#include <xercesc/framework/psvi/PSVIItem.hpp>
#include <xercesc/framework/psvi/XSAnnotation.hpp>
#include <xercesc/framework/psvi/XSAttributeDeclaration.hpp>
#include <xercesc/framework/psvi/XSAttributeGroupDefinition.hpp>
#include <xercesc/framework/psvi/XSAttributeUse.hpp>
#include <xercesc/framework/psvi/XSComplexTypeDefinition.hpp>
#include <xercesc/framework/psvi/XSElementDeclaration.hpp>
#include <xercesc/framework/psvi/XSFacet.hpp>
#include <xercesc/framework/psvi/XSIDCDefinition.hpp>
#include <xercesc/framework/psvi/XSModel.hpp>
#include <xercesc/framework/psvi/XSModelGroup.hpp>
#include <xercesc/framework/psvi/XSModelGroupDefinition.hpp>
#include <xercesc/framework/psvi/XSMultiValueFacet.hpp>
#include <xercesc/framework/psvi/XSNamedMap.hpp>
#include <xercesc/framework/psvi/XSNamespaceItem.hpp>
#include <xercesc/framework/psvi/XSNotationDeclaration.hpp>
#include <xercesc/framework/psvi/XSParticle.hpp>
#include <xercesc/framework/psvi/XSSimpleTypeDefinition.hpp>
#include <xercesc/framework/psvi/XSTypeDefinition.hpp>
#include <xercesc/framework/psvi/XSWildcard.hpp>
#include <xercesc/framework/XMLFormatter.hpp>
#include <xercesc/dom/DOMElement.hpp>
#include <xercesc/dom/DOMNamedNodeMap.hpp>
#include <xercesc/util/ValueStackOf.hpp>
#include <xercesc/util/ValueVectorOf.hpp>
#include <xercesc/util/XMLEntityResolver.hpp>
#include <xercesc/util/XMLResourceIdentifier.hpp>
#include <stdlib.h>
#include <string.h>

XERCES_CPP_NAMESPACE_USE

class AttrInfo {
public:
	AttrInfo(const XMLCh* pUri, const XMLCh* pName, const XMLCh* pType, const XMLCh* pValue) {
		uri = XMLString::replicate(pUri);
		name = XMLString::replicate(pName);
		type = XMLString::replicate(pType);
		value = XMLString::replicate(pValue);
	}

	~AttrInfo() {
		XMLString::release((XMLCh**)&uri);
		XMLString::release((XMLCh**)&name);
		XMLString::release((XMLCh**)&type);
		XMLString::release((XMLCh**)&value);
	}

	const XMLCh* getUri() const {
		return uri;
	}

	const XMLCh* getLocalName() const {
		return name;
	}

	const XMLCh* getType() const {
		return type;
	}

	const XMLCh* getValue() const {
		return value;
	}

private:
	const XMLCh* uri;
	const XMLCh* name;
	const XMLCh* type;
	const XMLCh* value;
};

class PSVIWriterHandlers : public PSVIHandler, public DefaultHandler, public XMLEntityResolver {
public:
    // -----------------------------------------------------------------------
    //  Constructors and Destructor
    // -----------------------------------------------------------------------
    PSVIWriterHandlers(XMLFormatter* outputFormatter, XMLFormatter* errorFormatter = NULL);
    ~PSVIWriterHandlers();

    // -----------------------------------------------------------------------
    //  Convenience Utility
    // -----------------------------------------------------------------------
	void resetPSVIFormatter(XMLFormatter* outputFormatter);
    void resetDocument();

    // -----------------------------------------------------------------------
    //  Handlers for the SAX ContentHandler interface
    // -----------------------------------------------------------------------
    void startElement(const XMLCh* const uri, const XMLCh* const localname, const XMLCh* const qname, const Attributes& attrs);
    void endElement(const XMLCh* const uri, const XMLCh* const localname, const XMLCh* const qname);
    void startDocument();
    void endDocument();
    void characters(const XMLCh* const chars, const unsigned int length);
    void ignorableWhitespace(const XMLCh* const chars, const unsigned int length);
    void comment(const XMLCh* const chars, const unsigned int length);
    void processingInstruction(const XMLCh* const target, const XMLCh* const data);
    void startPrefixMapping(const XMLCh* const prefix, const XMLCh* const uri);
    void endPrefixMapping(const XMLCh* const prefix);
    InputSource* resolveEntity(XMLResourceIdentifier* resourceIdentifier);

    // -----------------------------------------------------------------------
    //  Handlers for the SAX ErrorHandler interface
    // -----------------------------------------------------------------------
	void warning(const SAXParseException& exception);
    void error(const SAXParseException& exception);
    void fatalError(const SAXParseException& exception);
    void resetErrors();

    // -----------------------------------------------------------------------
    //  Handlers for the PSVIHandler interface
    // -----------------------------------------------------------------------

	void handleAttributesPSVI( const XMLCh* const localName,
								const XMLCh* const uri,
								PSVIAttributeList* psviAttributes );
	void handleElementPSVI(	const XMLCh* const localName,
								const XMLCh* const uri,
								PSVIElement* elementInfo );

private:
    // -----------------------------------------------------------------------
    //  Private methods
    // -----------------------------------------------------------------------

    void processAttributes(PSVIAttributeList* psviAttributes, const RefVectorOf<AttrInfo>* attributesInfo);
    void processNamespaceAttributes(PSVIAttributeList* psviAttributes, const RefVectorOf<AttrInfo>* attributes);
    void processAttributePSVI(PSVIAttribute* attribute);
    void processInScopeNamespaces();
    void processActualValue(PSVIItem*);
    void formDateTime(XSValue*);

    void processSchemaInformation(XSModel* model);
    void processNamespaceItem(XSNamespaceItem* namespaceItem);
    void processSchemaComponents(XSNamespaceItem* namespaceItem);
    void processSchemaDocuments(XSNamespaceItem* namespaceItem);
    void processSchemaAnnotations(XSAnnotationList* annotations);
    void processSchemaErrorCode(StringList* errors);

    void processTypeDefinition(XSTypeDefinition* type);
    void processComplexTypeDefinition(XSComplexTypeDefinition* complexType);
    void processSimpleTypeDefinition(XSSimpleTypeDefinition* simpleType);
    void processModelGroupDefinition(XSModelGroupDefinition* modelGroup);
    void processAttributeGroupDefinition(XSAttributeGroupDefinition* attributeGroup);

    void processElementDeclaration(XSElementDeclaration* element);
    void processAttributeDeclaration(XSAttributeDeclaration* attribute);
    void processNotationDeclaration(XSNotationDeclaration* notation);

    void processAnnotations(XSAnnotationList* annotations);
    void processAttributeUses(XSAttributeUseList* attributeUses);
    void processFacets(XSFacetList* facets, XSMultiValueFacetList* multiFacets);
    void processFundamentalFacets(XSSimpleTypeDefinition* facets);
    void processMemberTypeDefinitions(XSSimpleTypeDefinitionList* memberTypes);

    void processAnnotation(XSAnnotation* annotation);
    void processDOMElement(const XMLCh* const encloseName, DOMElement* rootElem, const XMLCh* const elementName);
    void processDOMAttributes(DOMNamedNodeMap* attrs);
    void processWildcard(XSWildcard* wildcard);
    void processModelGroup(XSModelGroup* modelGroup);
    void processParticle(XSParticle* particle);

    void processAttributeWildcard(XSWildcard* wildcard);
    void processScope(XSComplexTypeDefinition* enclosingCTD, short scope);
    void processValueConstraint(XSConstants::VALUE_CONSTRAINT ConstraintType, const XMLCh* constraintValue);

    void processIdentityConstraintDefinition(XSNamedMap<XSIDCDefinition>* identityConstraint);
    void processFields(StringList* fields);
    void processXPath(const XMLCh* xpath);

    void processChildren();
    void processChildrenEnd();

    void processTypeDefinitionOrRef(const XMLCh* enclose, XSTypeDefinition* type);
	void processSimpleTypeDefinitionOrRef(XSSimpleTypeDefinition* type);
    void processAttributeDeclarationOrRef(XSAttributeDeclaration* attrDecl);
    void processElementDeclarationOrRef(XSElementDeclaration* elemDecl);
	void processTypeDefinitionRef(const XMLCh* enclose, XSTypeDefinition* type);
    void processAttributeDeclarationRef(const XMLCh* enclose, XSAttributeDeclaration* attrDecl);
    void processElementDeclarationRef(const XMLCh* enclose, XSElementDeclaration* elemDecl);
    void sendReference(const XMLCh* elementName, XSObject* obj);

    void sendElementEmpty(const XMLCh* elementName);
	void sendElementValueInt(const XMLCh* elementName, const int value);
    void sendElementValue(const XMLCh* elementName, const XMLCh* const value);
    void sendElementValueList(const XMLCh* const elementName, const StringList* const values);

	void sendIndentedElement(const XMLCh* elementName);
    void sendIndentedElementWithID(const XMLCh* elementName, XSObject* obj);	//adds the ID to the attribute list before sending
    void sendUnindentedElement(const XMLCh* elementName);

    void writeOpen(const XMLCh* const elementName);
	void writeOpen(const XMLCh* const elementName, const StringList* const attrs);
	void writeClose(const XMLCh* const elementName);
	void writeValue(const XMLCh* const elementName, const XMLCh* const value);
	void writeValue(const XMLCh* const elementName, const StringList* const values);
	void writeEmpty(const XMLCh* const elementName, const StringList* const attrs);
	void writeEmpty(const XMLCh* const elementName);
    void writeString(const XMLCh* const string);

    const XMLCh* translateScope(XSConstants::SCOPE scope);
    const XMLCh* translateValueConstraint(XSConstants::VALUE_CONSTRAINT constraintKind);
    const XMLCh* translateBlockOrFinal(short val);
    const XMLCh* translateDerivationMethod(XSConstants::DERIVATION_TYPE derivation);
    const XMLCh* translateProcessContents(XSWildcard::PROCESS_CONTENTS processContents);
    const XMLCh* translateCompositor(XSModelGroup::COMPOSITOR_TYPE compositor);
    const XMLCh* translateValidity(PSVIItem::VALIDITY_STATE validity);
    const XMLCh* translateValidationAttempted(PSVIItem::ASSESSMENT_TYPE validation);
    const XMLCh* translateIdConstraintCategory(XSIDCDefinition::IC_CATEGORY category);
    const XMLCh* translateComplexContentType(XSComplexTypeDefinition::CONTENT_TYPE contentType);
    const XMLCh* translateSimpleTypeVariety(XSSimpleTypeDefinition::VARIETY variety);
    const XMLCh* translateOrderedFacet(XSSimpleTypeDefinition::ORDERING ordered);
    const XMLCh* translateFacet(XSSimpleTypeDefinition::FACET facetKind);
    const XMLCh* translateComponentType(XSConstants::COMPONENT_TYPE type);
    const XMLCh* translateBool(bool flag);

    XMLCh* createID(XSObject* obj);
    const XMLCh* getIdName(XSObject* obj);
    void incIndent();
    void decIndent();

protected:
	XMLFormatter* fFormatter;
	XMLFormatter* fErrorFormatter;

	StringList* fAttrList;
    XMLCh* fTempResult;
    XMLCh* fIndentChars;
    XMLCh* fBaseUri;

    unsigned int fIndent;
    unsigned int fIndentCap;
    unsigned int fAnonNum;

	RefHashTableOf<XMLCh>* fIdMap;
    RefVectorOf<XSObject>* fDefinedIds;
    RefArrayVectorOf<XMLCh>* fIdNames;
    RefArrayVectorOf<XMLCh>* fObjectLocations;

	RefHashTableOf<XMLCh>* fPrefixMap;
    RefArrayVectorOf<XMLCh>* fNamespaces;

	ValueVectorOf<unsigned int>* fNSAttributes;  //REVISIT  dont need if NSAttrs in different object
	ValueStackOf<bool>* fElementChildren;

	RefVectorOf<AttrInfo>* fAttributesInfo;
};

#endif

<commit_msg>Handle partial PSVIElement<commit_after>/*
 * Copyright 2003,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.
 */

#ifndef PSVIWRITERHANDLER_HPP
#define PSVIWRITERHANDLER_HPP

// ---------------------------------------------------------------------------
//  Includes
// ---------------------------------------------------------------------------
#include <xercesc/sax2/Attributes.hpp>
#include <xercesc/sax2/DefaultHandler.hpp>
#include <xercesc/framework/psvi/XSConstants.hpp>
#include <xercesc/framework/psvi/PSVIHandler.hpp>
#include <xercesc/framework/psvi/PSVIAttribute.hpp>
#include <xercesc/framework/psvi/PSVIAttributeList.hpp>
#include <xercesc/framework/psvi/PSVIElement.hpp>
#include <xercesc/framework/psvi/PSVIItem.hpp>
#include <xercesc/framework/psvi/XSAnnotation.hpp>
#include <xercesc/framework/psvi/XSAttributeDeclaration.hpp>
#include <xercesc/framework/psvi/XSAttributeGroupDefinition.hpp>
#include <xercesc/framework/psvi/XSAttributeUse.hpp>
#include <xercesc/framework/psvi/XSComplexTypeDefinition.hpp>
#include <xercesc/framework/psvi/XSElementDeclaration.hpp>
#include <xercesc/framework/psvi/XSFacet.hpp>
#include <xercesc/framework/psvi/XSIDCDefinition.hpp>
#include <xercesc/framework/psvi/XSModel.hpp>
#include <xercesc/framework/psvi/XSModelGroup.hpp>
#include <xercesc/framework/psvi/XSModelGroupDefinition.hpp>
#include <xercesc/framework/psvi/XSMultiValueFacet.hpp>
#include <xercesc/framework/psvi/XSNamedMap.hpp>
#include <xercesc/framework/psvi/XSNamespaceItem.hpp>
#include <xercesc/framework/psvi/XSNotationDeclaration.hpp>
#include <xercesc/framework/psvi/XSParticle.hpp>
#include <xercesc/framework/psvi/XSSimpleTypeDefinition.hpp>
#include <xercesc/framework/psvi/XSTypeDefinition.hpp>
#include <xercesc/framework/psvi/XSWildcard.hpp>
#include <xercesc/framework/XMLFormatter.hpp>
#include <xercesc/dom/DOMElement.hpp>
#include <xercesc/dom/DOMNamedNodeMap.hpp>
#include <xercesc/util/ValueStackOf.hpp>
#include <xercesc/util/ValueVectorOf.hpp>
#include <xercesc/util/XMLEntityResolver.hpp>
#include <xercesc/util/XMLResourceIdentifier.hpp>
#include <stdlib.h>
#include <string.h>

XERCES_CPP_NAMESPACE_USE

class AttrInfo {
public:
	AttrInfo(const XMLCh* pUri, const XMLCh* pName, const XMLCh* pType, const XMLCh* pValue) {
		uri = XMLString::replicate(pUri);
		name = XMLString::replicate(pName);
		type = XMLString::replicate(pType);
		value = XMLString::replicate(pValue);
	}

	~AttrInfo() {
		XMLString::release((XMLCh**)&uri);
		XMLString::release((XMLCh**)&name);
		XMLString::release((XMLCh**)&type);
		XMLString::release((XMLCh**)&value);
	}

	const XMLCh* getUri() const {
		return uri;
	}

	const XMLCh* getLocalName() const {
		return name;
	}

	const XMLCh* getType() const {
		return type;
	}

	const XMLCh* getValue() const {
		return value;
	}

private:
	const XMLCh* uri;
	const XMLCh* name;
	const XMLCh* type;
	const XMLCh* value;
};

class PSVIWriterHandlers : public PSVIHandler, public DefaultHandler, public XMLEntityResolver {
public:
    // -----------------------------------------------------------------------
    //  Constructors and Destructor
    // -----------------------------------------------------------------------
    PSVIWriterHandlers(XMLFormatter* outputFormatter, XMLFormatter* errorFormatter = NULL);
    ~PSVIWriterHandlers();

    // -----------------------------------------------------------------------
    //  Convenience Utility
    // -----------------------------------------------------------------------
	void resetPSVIFormatter(XMLFormatter* outputFormatter);
    void resetDocument();

    // -----------------------------------------------------------------------
    //  Handlers for the SAX ContentHandler interface
    // -----------------------------------------------------------------------
    void startElement(const XMLCh* const uri, const XMLCh* const localname, const XMLCh* const qname, const Attributes& attrs);
    void endElement(const XMLCh* const uri, const XMLCh* const localname, const XMLCh* const qname);
    void startDocument();
    void endDocument();
    void characters(const XMLCh* const chars, const unsigned int length);
    void ignorableWhitespace(const XMLCh* const chars, const unsigned int length);
    void comment(const XMLCh* const chars, const unsigned int length);
    void processingInstruction(const XMLCh* const target, const XMLCh* const data);
    void startPrefixMapping(const XMLCh* const prefix, const XMLCh* const uri);
    void endPrefixMapping(const XMLCh* const prefix);
    InputSource* resolveEntity(XMLResourceIdentifier* resourceIdentifier);

    // -----------------------------------------------------------------------
    //  Handlers for the SAX ErrorHandler interface
    // -----------------------------------------------------------------------
	void warning(const SAXParseException& exception);
    void error(const SAXParseException& exception);
    void fatalError(const SAXParseException& exception);
    void resetErrors();

    // -----------------------------------------------------------------------
    //  Handlers for the PSVIHandler interface
    // -----------------------------------------------------------------------

	void handleAttributesPSVI( const XMLCh* const localName,
								const XMLCh* const uri,
								PSVIAttributeList* psviAttributes );
	void handleElementPSVI(	const XMLCh* const localName,
                                const XMLCh* const uri,
                                PSVIElement* elementInfo );
	void handlePartialElementPSVI( const XMLCh* const localName,
                                   const XMLCh* const uri,
                                   PSVIElement* elementInfo ) {};
private:
    // -----------------------------------------------------------------------
    //  Private methods
    // -----------------------------------------------------------------------

    void processAttributes(PSVIAttributeList* psviAttributes, const RefVectorOf<AttrInfo>* attributesInfo);
    void processNamespaceAttributes(PSVIAttributeList* psviAttributes, const RefVectorOf<AttrInfo>* attributes);
    void processAttributePSVI(PSVIAttribute* attribute);
    void processInScopeNamespaces();
    void processActualValue(PSVIItem*);
    void formDateTime(XSValue*);

    void processSchemaInformation(XSModel* model);
    void processNamespaceItem(XSNamespaceItem* namespaceItem);
    void processSchemaComponents(XSNamespaceItem* namespaceItem);
    void processSchemaDocuments(XSNamespaceItem* namespaceItem);
    void processSchemaAnnotations(XSAnnotationList* annotations);
    void processSchemaErrorCode(StringList* errors);

    void processTypeDefinition(XSTypeDefinition* type);
    void processComplexTypeDefinition(XSComplexTypeDefinition* complexType);
    void processSimpleTypeDefinition(XSSimpleTypeDefinition* simpleType);
    void processModelGroupDefinition(XSModelGroupDefinition* modelGroup);
    void processAttributeGroupDefinition(XSAttributeGroupDefinition* attributeGroup);

    void processElementDeclaration(XSElementDeclaration* element);
    void processAttributeDeclaration(XSAttributeDeclaration* attribute);
    void processNotationDeclaration(XSNotationDeclaration* notation);

    void processAnnotations(XSAnnotationList* annotations);
    void processAttributeUses(XSAttributeUseList* attributeUses);
    void processFacets(XSFacetList* facets, XSMultiValueFacetList* multiFacets);
    void processFundamentalFacets(XSSimpleTypeDefinition* facets);
    void processMemberTypeDefinitions(XSSimpleTypeDefinitionList* memberTypes);

    void processAnnotation(XSAnnotation* annotation);
    void processDOMElement(const XMLCh* const encloseName, DOMElement* rootElem, const XMLCh* const elementName);
    void processDOMAttributes(DOMNamedNodeMap* attrs);
    void processWildcard(XSWildcard* wildcard);
    void processModelGroup(XSModelGroup* modelGroup);
    void processParticle(XSParticle* particle);

    void processAttributeWildcard(XSWildcard* wildcard);
    void processScope(XSComplexTypeDefinition* enclosingCTD, short scope);
    void processValueConstraint(XSConstants::VALUE_CONSTRAINT ConstraintType, const XMLCh* constraintValue);

    void processIdentityConstraintDefinition(XSNamedMap<XSIDCDefinition>* identityConstraint);
    void processFields(StringList* fields);
    void processXPath(const XMLCh* xpath);

    void processChildren();
    void processChildrenEnd();

    void processTypeDefinitionOrRef(const XMLCh* enclose, XSTypeDefinition* type);
	void processSimpleTypeDefinitionOrRef(XSSimpleTypeDefinition* type);
    void processAttributeDeclarationOrRef(XSAttributeDeclaration* attrDecl);
    void processElementDeclarationOrRef(XSElementDeclaration* elemDecl);
	void processTypeDefinitionRef(const XMLCh* enclose, XSTypeDefinition* type);
    void processAttributeDeclarationRef(const XMLCh* enclose, XSAttributeDeclaration* attrDecl);
    void processElementDeclarationRef(const XMLCh* enclose, XSElementDeclaration* elemDecl);
    void sendReference(const XMLCh* elementName, XSObject* obj);

    void sendElementEmpty(const XMLCh* elementName);
	void sendElementValueInt(const XMLCh* elementName, const int value);
    void sendElementValue(const XMLCh* elementName, const XMLCh* const value);
    void sendElementValueList(const XMLCh* const elementName, const StringList* const values);

	void sendIndentedElement(const XMLCh* elementName);
    void sendIndentedElementWithID(const XMLCh* elementName, XSObject* obj);	//adds the ID to the attribute list before sending
    void sendUnindentedElement(const XMLCh* elementName);

    void writeOpen(const XMLCh* const elementName);
	void writeOpen(const XMLCh* const elementName, const StringList* const attrs);
	void writeClose(const XMLCh* const elementName);
	void writeValue(const XMLCh* const elementName, const XMLCh* const value);
	void writeValue(const XMLCh* const elementName, const StringList* const values);
	void writeEmpty(const XMLCh* const elementName, const StringList* const attrs);
	void writeEmpty(const XMLCh* const elementName);
    void writeString(const XMLCh* const string);

    const XMLCh* translateScope(XSConstants::SCOPE scope);
    const XMLCh* translateValueConstraint(XSConstants::VALUE_CONSTRAINT constraintKind);
    const XMLCh* translateBlockOrFinal(short val);
    const XMLCh* translateDerivationMethod(XSConstants::DERIVATION_TYPE derivation);
    const XMLCh* translateProcessContents(XSWildcard::PROCESS_CONTENTS processContents);
    const XMLCh* translateCompositor(XSModelGroup::COMPOSITOR_TYPE compositor);
    const XMLCh* translateValidity(PSVIItem::VALIDITY_STATE validity);
    const XMLCh* translateValidationAttempted(PSVIItem::ASSESSMENT_TYPE validation);
    const XMLCh* translateIdConstraintCategory(XSIDCDefinition::IC_CATEGORY category);
    const XMLCh* translateComplexContentType(XSComplexTypeDefinition::CONTENT_TYPE contentType);
    const XMLCh* translateSimpleTypeVariety(XSSimpleTypeDefinition::VARIETY variety);
    const XMLCh* translateOrderedFacet(XSSimpleTypeDefinition::ORDERING ordered);
    const XMLCh* translateFacet(XSSimpleTypeDefinition::FACET facetKind);
    const XMLCh* translateComponentType(XSConstants::COMPONENT_TYPE type);
    const XMLCh* translateBool(bool flag);

    XMLCh* createID(XSObject* obj);
    const XMLCh* getIdName(XSObject* obj);
    void incIndent();
    void decIndent();

protected:
	XMLFormatter* fFormatter;
	XMLFormatter* fErrorFormatter;

	StringList* fAttrList;
    XMLCh* fTempResult;
    XMLCh* fIndentChars;
    XMLCh* fBaseUri;

    unsigned int fIndent;
    unsigned int fIndentCap;
    unsigned int fAnonNum;

	RefHashTableOf<XMLCh>* fIdMap;
    RefVectorOf<XSObject>* fDefinedIds;
    RefArrayVectorOf<XMLCh>* fIdNames;
    RefArrayVectorOf<XMLCh>* fObjectLocations;

	RefHashTableOf<XMLCh>* fPrefixMap;
    RefArrayVectorOf<XMLCh>* fNamespaces;

	ValueVectorOf<unsigned int>* fNSAttributes;  //REVISIT  dont need if NSAttrs in different object
	ValueStackOf<bool>* fElementChildren;

	RefVectorOf<AttrInfo>* fAttributesInfo;
};

#endif

<|endoftext|>


<commit_before><commit_msg>- ExtINT implemented (some progress with FreeBSD 5.3 boot cd) - fixed a warning<commit_after><|endoftext|>


<commit_before>#include "../../include/game/Game.hpp"
#include "../../include/game/Level.hpp"
#include "../../include/game/Settings.hpp"
#include "../../include/game/DialogScreen.hpp"
#include "../../include/game/HighscoreUploader.hpp"
#include "../../include/game/HighscoreBoard.hpp"
#include "../../include/game/Tracer.hpp"
#include "../../include/aw/utilities/Converter.hpp"

#include <SFML/Window/Event.hpp>
#include <SFML/Window/Keyboard.hpp>
#include <SFML/Graphics/RenderWindow.hpp>
#include <SFML/Graphics/Color.hpp>
#include <SFML/Graphics/RectangleShape.hpp>

#include <cmath> // sqrt

Game::Game(sf::RenderWindow &window) : m_window(window)
{
    m_pLevel = nullptr;

    m_position = sf::Vector2f(100,100);
    m_lastFrameTime = 0;

    m_running = true;
    m_returnValue = "menu";
}

Game::~Game()
{
    if(m_pLevel)
        delete m_pLevel;

    m_pLevel = nullptr;
}

std::string Game::Run(std::string levelName, Tracer &currentTracer, Tracer &lastTracer)
{
    m_levelName = levelName;

    Init();

    m_gameTime.restart();

    SetWindowName();

    if(settings::IsMusicOn())
    {
        m_music.setVolume(settings::GetMusicVolume());
        m_music.play();
    }

    bool start = false;

    while(m_window.isOpen() && m_running && !start)
    {
        sf::Event e;

        while(m_window.pollEvent(e))
        {
            switch(e.type)
            {
            case sf::Event::Closed:
                m_running = false;
                m_returnValue = "exit";
                break;
            case sf::Event::KeyPressed:
                start = true;
                break;
            default:
                break;
            }
        }

        m_window.clear();

        m_pLevel->Draw(m_view.getCenter().x);

        sf::RectangleShape fade;
        fade.setSize(sf::Vector2f(m_window.getSize().x, m_window.getSize().y));
        fade.setFillColor(sf::Color(0,0,0,180));

        sf::Text temp;
        temp.setFont(m_font);
        temp.setString("Press any key to start the game!");
        temp.setPosition(60, 175);
        temp.setCharacterSize(25);

        m_window.draw(fade);
        m_window.draw(temp);

        m_window.display();
    }

    m_frameTime.restart();
    m_gameTime.restart();

    while(m_window.isOpen() && m_running)
    {
        HandleEvents();

        DoLogic(currentTracer);

        if(m_pLevel->GetFinished())
            Finish();

        Draw(currentTracer, lastTracer);

        SetWindowName();
    }

    m_window.setTitle("Kroniax");

    return m_returnValue;
}

void Game::HandleEvents()
{
    sf::Event e;

    while(m_window.pollEvent(e))
    {
        if(e.type == sf::Event::Closed)
            m_window.close();

        if(e.type == sf::Event::KeyPressed && e.key.code == sf::Keyboard::Escape)
            m_running = false;

        if(e.type == sf::Event::KeyPressed && e.key.code == sf::Keyboard::P)
        {
            PauseTheGame();
        }

        if(e.type == sf::Event::Resized)
        {
            int width = e.size.width;
            int height = width / 16 * 9;
            m_window.setSize(sf::Vector2u(width, height));

            PauseTheGame();
        }

        if(e.type == sf::Event::KeyPressed && (e.key.code == sf::Keyboard::LAlt || e.key.code == sf::Keyboard::RAlt || e.key.code == sf::Keyboard::Home))
        {
            PauseTheGame();
        }

        if(e.type == sf::Event::LostFocus)
        {
            PauseTheGame();
        }

    }

    if(settings::GetGamemode() == 1)
    {
        if(settings::GetSpeedX() < 750)
        {
            if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
            {
                settings::SetSpeedX(settings::GetSpeedX() + (150*m_lastFrameTime));
            }
        }

        if(settings::GetSpeedX() > -750)
        {
            if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
            {
                settings::SetSpeedX(settings::GetSpeedX() - (150*m_lastFrameTime));

            }
        }
    }

}

void Game::DoLogic(Tracer &currentTracer)
{

    m_pLevel->CheckForScripts(m_position.x+20);

    if(sf::Keyboard::isKeyPressed(sf::Keyboard::Space))
    {
        float newValue = settings::GetSpeedY() - (2.3f*settings::GetDownforce() * m_lastFrameTime);
        settings::SetSpeedY(newValue);
    }

    settings::SetSpeedY(settings::GetSpeedY() + settings::GetDownforce()*m_lastFrameTime);

    m_position.x += settings::GetSpeedX() * m_lastFrameTime;
    m_position.y += settings::GetSpeedY() * m_lastFrameTime;

    m_viewPositionFloat = sf::Vector2f(m_viewPositionFloat.x + (settings::GetSpeedX() * m_lastFrameTime), m_viewPositionFloat.y);
    m_view.setCenter(static_cast<int>(m_viewPositionFloat.x), m_viewPositionFloat.y);

    //m_view.setCenter(m_viewPositionFloat);
    m_window.setView(m_view);

    //Time things
    m_time.setPosition(5,5);
    m_speedX.setPosition(150,5);
    if(m_running)
    {
        m_time.setString("Time: "+aw::conv::ToString(aw::conv::ToInt(m_gameTime.GetTimeInMs()/1000.f)));
        m_speedX.setString("SpeedX: " + aw::conv::ToString(aw::conv::ToInt(settings::GetSpeedX())));
    }

    // Check if there current Tracer need an update
    // Multiply with 1000 because this function need milliseconds and not seconds
    if(currentTracer.Update(m_lastFrameTime*1000))
    {
        bool steerUp = sf::Keyboard::isKeyPressed(sf::Keyboard::Space);

        bool speedUp   = false;
        bool speedDown = false;
        //Only check for speedUps and Downs if the gamemode is Speed Challenge
        if(settings::GetGamemode() == 1)
        {
            speedUp = sf::Keyboard::isKeyPressed(sf::Keyboard::Right);
            speedDown = sf::Keyboard::isKeyPressed(sf::Keyboard::Left);
        }

        currentTracer.AddPoint(m_position, steerUp, speedUp, speedDown);
    }

}

void Game::Draw(Tracer &currentTracer, Tracer &lastTracer)
{
    m_window.clear(sf::Color::Black);

    m_pLevel->Draw(m_view.getCenter().x);

    //Draw the tracerlines
    lastTracer.Draw(m_window);
    currentTracer.Draw(m_window);

    CreateBody();
    m_window.draw(m_body, 3, sf::Triangles);

    m_window.setView(m_window.getDefaultView());

    m_window.draw(m_time);

    if(settings::GetGamemode() == 1)
    {
        m_window.draw(m_speedX);
    }
    m_window.display();

    //Collision
    if(m_pLevel->Collide(m_view.getCenter().x, sf::Vector2i(m_body[0].position.x, m_body[0].position.y),
                              sf::Vector2i(m_body[1].position.x, m_body[1].position.y),
                              sf::Vector2i(m_body[2].position.x, m_body[2].position.y)))
    {
        if(db::DialogYesNo(m_window, "You hit the wall!\nDo you want to restart this level?"))
        {
            m_returnValue = "restart";
            m_running = false;
        }
        else
        {
            m_returnValue = "menu";
            m_running = false;
        }
    }

    m_lastFrameTime = m_frameTime.getElapsedTime().asSeconds();
    m_frameTime.restart();
}

void Game::Init()
{
    m_pLevel = new Level(m_window);

    if(!m_pLevel->Load(m_levelName))
    {
        db::DialogYesNo(m_window , "Couldnt load the Level!\nMaybe name is wrong?");
        m_running = false;
    }

    if(settings::IsMusicOn())
    {
        if(settings::GetMusic() == 1)
        {
            m_music.openFromFile("data/audio/Galaxy - New Electro House Techno by MafiaFLairBeatz.ogg");
        }
        else if(settings::GetMusic() == 2)
        {
            m_music.openFromFile("data/audio/Infinity - Techno Trance Project 2011 by MafiaFLairBeatz.ogg");
        }
        else
        {
            m_music.openFromFile("data/audio/Return of the Electro by MafiaFLairBeatz.ogg");
        }
    }

    sf::Vector2u sizeWin = m_window.getSize();

    m_view = m_window.getView();
    m_view.setCenter(400, 225);
    m_view.setSize(sf::Vector2f(800,450));
    m_viewPositionFloat = m_view.getCenter();

    m_window.setView(m_view);

    m_window.setSize(sizeWin);

    m_font.loadFromFile("data/font/good times.ttf");

    m_time.setFont(m_font);
    m_time.setPosition(m_window.mapPixelToCoords(sf::Vector2i(5,5)));
    m_time.setCharacterSize(12);
    m_time.setString("Time: 0");

    m_speedX.setFont(m_font);
    m_speedX.setPosition(m_window.mapPixelToCoords(sf::Vector2i(5, 40)));
    m_speedX.setCharacterSize(12);
    m_speedX.setString("SpeedX: " + aw::conv::ToString(aw::conv::ToInt(settings::GetSpeedX())));

    settings::SetSpeedX(settings::GetStartSpeedX());

    CreateBody();
}

void Game::PauseTheGame()
{
    m_gameTime.pause();
    db::DialogOK(m_window, "Game Paused! Press return/enter to continue");
    m_gameTime.resume();
    m_frameTime.restart();
}

void Game::Finish()
{

    if(settings::GetGamemode() == 0)
    {

        int position = settings::GetUnlockedLevel() -1;
        if(position < 0)
            position = 0;

        if(m_levelName == settings::GetLevelList().at(position))
        {
            if(settings::IncreaseUnlockLevel())
            {
                db::DialogOK(m_window, "You unlocked a new Map!");
            }
        }

        db::DialogOK(m_window, "Congratulation, you completed\nthis Level!");

        m_running = false;
        m_returnValue = "win";
    }

    else if(settings::GetGamemode() == 1)
    {
        m_gameTime.pause();

        if(db::DialogYesNo(m_window, "Do you want to upload your time?\nInternetconnection is needed"))
        {
            HighscoreUploader uploader;

            std::string name = db::InputDialog(m_window, "Please insert your name: ", "guest");

            //Return false = The connection failed
            if(!uploader.Submit(m_levelName, name, m_pLevel->GetLevelLength(), m_pLevel->GetFilledBlocks(), m_pLevel->GetCollisionBlocks(), m_gameTime.GetTimeInMs()))
            {
                // Give the user feedback about the failed Connection
                db::DialogOK(m_window, uploader.GetError());
            }
            else
            {
                //If the connection works get the Highscore
                std::vector<Score> &temp = uploader.GetScore();
                // And display them
                ListHighscore(m_window, m_levelName, temp);
            }

            if(db::DialogYesNo(m_window, "Do you want to play this level again?"))
            {
                m_returnValue = "restart";
            }
            else
            {
                m_returnValue = "win";
            }
            m_running = false;
        }
    }

}

void Game::CreateBody()
{
    float height = 7;
    float width  = 25;

    sf::Vector2f dVec; // unitVector of v
    double magSpeed = std::sqrt((settings::GetSpeedX() * settings::GetSpeedX()) + (settings::GetSpeedY() * settings::GetSpeedY()));
    dVec.x = settings::GetSpeedX() / magSpeed;
    dVec.y = settings::GetSpeedY() / magSpeed;

    m_body[2] = sf::Vertex(sf::Vector2f(m_position.x + (width * dVec.x), m_position.y + (width * dVec.y)), sf::Color(255,255,255)); // Right

    // normal Vector from the unint V vector
    sf::Vector2f dnVec;
    dnVec.x = dVec.y;
    dnVec.y = -dVec.x;

    m_body[0] = sf::Vertex(sf::Vector2f(m_position.x + height * dnVec.x, m_position.y + height * dnVec.y), sf::Color(255,255,255)); // Left Bot
    m_body[1] = sf::Vertex(sf::Vector2f(m_position.x - height * dnVec.x, m_position.y - height * dnVec.y), sf::Color(255,255,255)); // Left Top

}

void Game::SetWindowName()
{
    float progress = m_position.x / (m_pLevel->GetLevelLength()*m_pLevel->GetTileSize().x);
    int iProgress = static_cast<int>(progress*10);

    int i = 0;
    std::string title = m_levelName+ "Progress: ";

    while(i < 10)
    {
        if(i == iProgress)
            title = title + ">";
        else
            title = title + "-";

        i++;
    }

    m_window.setTitle(title);

}
<commit_msg>Bugfixes (level progress)<commit_after>#include "../../include/game/Game.hpp"
#include "../../include/game/Level.hpp"
#include "../../include/game/Settings.hpp"
#include "../../include/game/DialogScreen.hpp"
#include "../../include/game/HighscoreUploader.hpp"
#include "../../include/game/HighscoreBoard.hpp"
#include "../../include/game/Tracer.hpp"
#include "../../include/aw/utilities/Converter.hpp"

#include <SFML/Window/Event.hpp>
#include <SFML/Window/Keyboard.hpp>
#include <SFML/Graphics/RenderWindow.hpp>
#include <SFML/Graphics/Color.hpp>
#include <SFML/Graphics/RectangleShape.hpp>

#include <cmath> // sqrt

Game::Game(sf::RenderWindow &window) : m_window(window)
{
    m_pLevel = nullptr;

    m_position = sf::Vector2f(100,100);
    m_lastFrameTime = 0;

    m_running = true;
    m_returnValue = "menu";
}

Game::~Game()
{
    if(m_pLevel)
        delete m_pLevel;

    m_pLevel = nullptr;
}

std::string Game::Run(std::string levelName, Tracer &currentTracer, Tracer &lastTracer)
{
    m_levelName = levelName;

    Init();

    m_gameTime.restart();

    SetWindowName();

    if(settings::IsMusicOn())
    {
        m_music.setVolume(settings::GetMusicVolume());
        m_music.play();
    }

    bool start = false;

    while(m_window.isOpen() && m_running && !start)
    {
        sf::Event e;

        while(m_window.pollEvent(e))
        {
            switch(e.type)
            {
            case sf::Event::Closed:
                m_running = false;
                m_returnValue = "exit";
                break;
            case sf::Event::KeyPressed:
                start = true;
                break;
            default:
                break;
            }
        }

        m_window.clear();

        m_pLevel->Draw(m_view.getCenter().x);

        sf::RectangleShape fade;
        fade.setSize(sf::Vector2f(m_window.getSize().x, m_window.getSize().y));
        fade.setFillColor(sf::Color(0,0,0,180));

        sf::Text temp;
        temp.setFont(m_font);
        temp.setString("Press any key to start the game!");
        temp.setPosition(60, 175);
        temp.setCharacterSize(25);

        m_window.draw(fade);
        m_window.draw(temp);

        m_window.display();
    }

    m_frameTime.restart();
    m_gameTime.restart();

    while(m_window.isOpen() && m_running)
    {
        HandleEvents();

        DoLogic(currentTracer);

        if(m_pLevel->GetFinished())
            Finish();

        Draw(currentTracer, lastTracer);

        SetWindowName();
    }

    m_window.setTitle("Kroniax");

    return m_returnValue;
}

void Game::HandleEvents()
{
    sf::Event e;

    while(m_window.pollEvent(e))
    {
        if(e.type == sf::Event::Closed)
            m_window.close();

        if(e.type == sf::Event::KeyPressed && e.key.code == sf::Keyboard::Escape)
            m_running = false;

        if(e.type == sf::Event::KeyPressed && e.key.code == sf::Keyboard::P)
        {
            PauseTheGame();
        }

        if(e.type == sf::Event::Resized)
        {
            int width = e.size.width;
            int height = width / 16 * 9;
            m_window.setSize(sf::Vector2u(width, height));

            PauseTheGame();
        }

        if(e.type == sf::Event::KeyPressed && (e.key.code == sf::Keyboard::LAlt || e.key.code == sf::Keyboard::RAlt || e.key.code == sf::Keyboard::Home))
        {
            PauseTheGame();
        }

        if(e.type == sf::Event::LostFocus)
        {
            PauseTheGame();
        }

    }

    if(settings::GetGamemode() == 1)
    {
        if(settings::GetSpeedX() < 750)
        {
            if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
            {
                settings::SetSpeedX(settings::GetSpeedX() + (150*m_lastFrameTime));
            }
        }

        if(settings::GetSpeedX() > -750)
        {
            if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
            {
                settings::SetSpeedX(settings::GetSpeedX() - (150*m_lastFrameTime));

            }
        }
    }

}

void Game::DoLogic(Tracer &currentTracer)
{

    m_pLevel->CheckForScripts(m_position.x+20);

    if(sf::Keyboard::isKeyPressed(sf::Keyboard::Space))
    {
        float newValue = settings::GetSpeedY() - (2.3f*settings::GetDownforce() * m_lastFrameTime);
        settings::SetSpeedY(newValue);
    }

    settings::SetSpeedY(settings::GetSpeedY() + settings::GetDownforce()*m_lastFrameTime);

    m_position.x += settings::GetSpeedX() * m_lastFrameTime;
    m_position.y += settings::GetSpeedY() * m_lastFrameTime;

    m_viewPositionFloat = sf::Vector2f(m_viewPositionFloat.x + (settings::GetSpeedX() * m_lastFrameTime), m_viewPositionFloat.y);
    m_view.setCenter(static_cast<int>(m_viewPositionFloat.x), m_viewPositionFloat.y);

    //m_view.setCenter(m_viewPositionFloat);
    m_window.setView(m_view);

    //Time things
    m_time.setPosition(5,5);
    m_speedX.setPosition(150,5);
    if(m_running)
    {
        m_time.setString("Time: "+aw::conv::ToString(aw::conv::ToInt(m_gameTime.GetTimeInMs()/1000.f)));
        m_speedX.setString("SpeedX: " + aw::conv::ToString(aw::conv::ToInt(settings::GetSpeedX())));
    }

    // Check if there current Tracer need an update
    // Multiply with 1000 because this function need milliseconds and not seconds
    if(currentTracer.Update(m_lastFrameTime*1000))
    {
        bool steerUp = sf::Keyboard::isKeyPressed(sf::Keyboard::Space);

        bool speedUp   = false;
        bool speedDown = false;
        //Only check for speedUps and Downs if the gamemode is Speed Challenge
        if(settings::GetGamemode() == 1)
        {
            speedUp = sf::Keyboard::isKeyPressed(sf::Keyboard::Right);
            speedDown = sf::Keyboard::isKeyPressed(sf::Keyboard::Left);
        }

        currentTracer.AddPoint(m_position, steerUp, speedUp, speedDown);
    }

}

void Game::Draw(Tracer &currentTracer, Tracer &lastTracer)
{
    m_window.clear(sf::Color::Black);

    m_pLevel->Draw(m_view.getCenter().x);

    //Draw the tracerlines
    lastTracer.Draw(m_window);
    currentTracer.Draw(m_window);

    CreateBody();
    m_window.draw(m_body, 3, sf::Triangles);

    m_window.setView(m_window.getDefaultView());

    m_window.draw(m_time);

    if(settings::GetGamemode() == 1)
    {
        m_window.draw(m_speedX);
    }
    m_window.display();

    //Collision
    if(m_pLevel->Collide(m_view.getCenter().x, sf::Vector2i(m_body[0].position.x, m_body[0].position.y),
                              sf::Vector2i(m_body[1].position.x, m_body[1].position.y),
                              sf::Vector2i(m_body[2].position.x, m_body[2].position.y)))
    {
        if(db::DialogYesNo(m_window, "You hit the wall!\nDo you want to restart this level?"))
        {
            m_returnValue = "restart";
            m_running = false;
        }
        else
        {
            m_returnValue = "menu";
            m_running = false;
        }
    }

    m_lastFrameTime = m_frameTime.getElapsedTime().asSeconds();
    m_frameTime.restart();
}

void Game::Init()
{
    m_pLevel = new Level(m_window);

    if(!m_pLevel->Load(m_levelName))
    {
        db::DialogYesNo(m_window , "Couldnt load the Level!\nMaybe name is wrong?");
        m_running = false;
    }

    if(settings::IsMusicOn())
    {
        if(settings::GetMusic() == 1)
        {
            m_music.openFromFile("data/audio/Galaxy - New Electro House Techno by MafiaFLairBeatz.ogg");
        }
        else if(settings::GetMusic() == 2)
        {
            m_music.openFromFile("data/audio/Infinity - Techno Trance Project 2011 by MafiaFLairBeatz.ogg");
        }
        else
        {
            m_music.openFromFile("data/audio/Return of the Electro by MafiaFLairBeatz.ogg");
        }
    }

    sf::Vector2u sizeWin = m_window.getSize();

    m_view = m_window.getView();
    m_view.setCenter(400, 225);
    m_view.setSize(sf::Vector2f(800,450));
    m_viewPositionFloat = m_view.getCenter();

    m_window.setView(m_view);

    m_window.setSize(sizeWin);

    m_font.loadFromFile("data/font/good times.ttf");

    m_time.setFont(m_font);
    m_time.setPosition(m_window.mapPixelToCoords(sf::Vector2i(5,5)));
    m_time.setCharacterSize(12);
    m_time.setString("Time: 0");

    m_speedX.setFont(m_font);
    m_speedX.setPosition(m_window.mapPixelToCoords(sf::Vector2i(5, 40)));
    m_speedX.setCharacterSize(12);
    m_speedX.setString("SpeedX: " + aw::conv::ToString(aw::conv::ToInt(settings::GetSpeedX())));

    settings::SetSpeedX(settings::GetStartSpeedX());

    CreateBody();
}

void Game::PauseTheGame()
{
    m_gameTime.pause();
    db::DialogOK(m_window, "Game Paused! Press return/enter to continue");
    m_gameTime.resume();
    m_frameTime.restart();
}

void Game::Finish()
{

    if(settings::GetGamemode() == 0)
    {

        int position = settings::GetUnlockedLevel() -1;
        if(position < 0)
            position = 0;

        if(m_levelName == settings::GetLevelList().at(position))
        {
            if(settings::IncreaseUnlockLevel())
            {
                db::DialogOK(m_window, "You unlocked a new Map!");
                //To save the current level progress
                settings::Save();
            }
        }

        db::DialogOK(m_window, "Congratulation, you completed\nthis Level!");

        m_running = false;
        m_returnValue = "win";
    }

    else if(settings::GetGamemode() == 1)
    {
        m_gameTime.pause();

        if(db::DialogYesNo(m_window, "Do you want to upload your time?\nInternetconnection is needed"))
        {
            HighscoreUploader uploader;

            std::string name = db::InputDialog(m_window, "Please insert your name: ", "guest");

            //Return false = The connection failed
            if(!uploader.Submit(m_levelName, name, m_pLevel->GetLevelLength(), m_pLevel->GetFilledBlocks(), m_pLevel->GetCollisionBlocks(), m_gameTime.GetTimeInMs()))
            {
                // Give the user feedback about the failed Connection
                db::DialogOK(m_window, uploader.GetError());
            }
            else
            {
                //If the connection works get the Highscore
                std::vector<Score> &temp = uploader.GetScore();
                // And display them
                ListHighscore(m_window, m_levelName, temp);
            }

            if(db::DialogYesNo(m_window, "Do you want to play this level again?"))
            {
                m_returnValue = "restart";
            }
            else
            {
                m_returnValue = "win";
            }
            m_running = false;
        }
    }

}

void Game::CreateBody()
{
    float height = 7;
    float width  = 25;

    sf::Vector2f dVec; // unitVector of v
    double magSpeed = std::sqrt((settings::GetSpeedX() * settings::GetSpeedX()) + (settings::GetSpeedY() * settings::GetSpeedY()));
    dVec.x = settings::GetSpeedX() / magSpeed;
    dVec.y = settings::GetSpeedY() / magSpeed;

    m_body[2] = sf::Vertex(sf::Vector2f(m_position.x + (width * dVec.x), m_position.y + (width * dVec.y)), sf::Color(255,255,255)); // Right

    // normal Vector from the unint V vector
    sf::Vector2f dnVec;
    dnVec.x = dVec.y;
    dnVec.y = -dVec.x;

    m_body[0] = sf::Vertex(sf::Vector2f(m_position.x + height * dnVec.x, m_position.y + height * dnVec.y), sf::Color(255,255,255)); // Left Bot
    m_body[1] = sf::Vertex(sf::Vector2f(m_position.x - height * dnVec.x, m_position.y - height * dnVec.y), sf::Color(255,255,255)); // Left Top

}

void Game::SetWindowName()
{
    float progress = m_position.x / (m_pLevel->GetLevelLength()*m_pLevel->GetTileSize().x);
    int iProgress = static_cast<int>(progress*10);

    int i = 0;
    std::string title = m_levelName+ "Progress: ";

    while(i < 10)
    {
        if(i == iProgress)
            title = title + ">";
        else
            title = title + "-";

        i++;
    }

    m_window.setTitle(title);

}
<|endoftext|>


<commit_before>#include <cassert>
#include <cstddef>
#include <functional>
#include <utility>
#include <jegp/utility.hpp>

// [hash.combine]

struct X {
    int v;
};
struct Y { };
struct Z { };

template <> struct std::hash<X> {
    constexpr std::size_t operator()(X x) const noexcept { return x.v; }
};
template <> struct std::hash<Y> {
    std::size_t operator()(Y) const { return 0; }
};
template <> struct std::hash<Z> : std::hash<void> { };

template <class... Args> constexpr bool is_hash_combinable = requires { jegp::hash_combine(std::declval<Args>()...); };

constexpr void test_hash_combine() {
    static_assert(not is_hash_combinable<>);
    static_assert(not is_hash_combinable<int>);
    static_assert(not is_hash_combinable<X>);
    static_assert(not is_hash_combinable<Y>);
    static_assert(not is_hash_combinable<Z>);
    static_assert(is_hash_combinable<int, int>);
    static_assert(is_hash_combinable<int, X>);
    static_assert(is_hash_combinable<X, int>);
    static_assert(is_hash_combinable<X, X>);
    static_assert(is_hash_combinable<int, Y>);
    static_assert(is_hash_combinable<Y, int>);
    static_assert(is_hash_combinable<Y, Y>);
    static_assert(not is_hash_combinable<int, Z>);
    static_assert(not is_hash_combinable<Z, int>);
    static_assert(not is_hash_combinable<Z, Z>);

    static_assert(noexcept(jegp::hash_combine(0, 0)));
    static_assert(noexcept(jegp::hash_combine(0, X{})));
    static_assert(noexcept(jegp::hash_combine(X{}, 0)));
    static_assert(noexcept(jegp::hash_combine(X{}, X{})));
    static_assert(not noexcept(jegp::hash_combine(0, Y{})));
    static_assert(not noexcept(jegp::hash_combine(Y{}, 0)));
    static_assert(not noexcept(jegp::hash_combine(Y{}, Y{})));

    const X x[]{17, 20, -23};

    std::size_t seed{0};

    seed ^= x[0].v;
    seed ^= x[1].v + (seed << 6) + (seed >> 2);

    assert(seed == jegp::hash_combine(x[0], x[1]));

    seed ^= x[2].v + (seed << 6) + (seed >> 2);

    assert(seed == jegp::hash_combine(x[0], x[1], x[2]));
}

// [static.downcast]

template <class DerivedRef, class Base> constexpr bool is_static_downcastable = requires {
    jegp::static_downcast<DerivedRef>(std::declval<Base>());
};

template <class Derived, class Base, bool ExpectedToPass = true>
    requires(
        std::is_same_v<Derived, std::remove_cvref_t<Derived>>and std::is_same_v<Base, std::remove_cvref_t<Base>> and
        not std::is_same_v<Derived, Base> and std::is_base_of_v<Base, Derived>)
constexpr void assert_is_static_downcastable() {
    auto ok = [](bool b) { return b == ExpectedToPass; };

    static_assert(ok(is_static_downcastable<Derived&, Base&>));
    static_assert(ok(is_static_downcastable<const Derived&, Base&>));
    static_assert(ok(is_static_downcastable<Derived&&, Base&>));
    static_assert(ok(is_static_downcastable<const Derived&&, Base&>));

    static_assert(not is_static_downcastable<Derived&, const Base&>);
    static_assert(ok(is_static_downcastable<const Derived&, const Base&>));
    static_assert(not is_static_downcastable<Derived&&, const Base&>);
    static_assert(ok(is_static_downcastable<const Derived&&, const Base&>));

    static_assert(not is_static_downcastable<Derived&, Base>);
    static_assert(not is_static_downcastable<const Derived&, Base>);
    static_assert(ok(is_static_downcastable<Derived&&, Base>));
    static_assert(ok(is_static_downcastable<const Derived&&, Base>));

    static_assert(not is_static_downcastable<Derived&, const Base>);
    static_assert(not is_static_downcastable<const Derived&, const Base>);
    static_assert(not is_static_downcastable<Derived&&, const Base>);
    static_assert(ok(is_static_downcastable<const Derived&&, const Base>));

    static_assert(not is_static_downcastable<Derived, Base&>);
    static_assert(not is_static_downcastable<Derived, const Base&>);
    static_assert(not is_static_downcastable<Derived, Base>);
    static_assert(not is_static_downcastable<Derived, const Base>);
}

constexpr void test_static_downcast() {
    struct B { };
    struct D : B { };
    struct D2 : private B { };
    struct D3 : D, B { };
    struct D4 : virtual B { };
    assert_is_static_downcastable<D, B>();
    assert_is_static_downcastable<D2, B, false>();
    assert_is_static_downcastable<D3, B, false>();
    assert_is_static_downcastable<D4, B, false>();
}

consteval void test() {
    test_hash_combine();
    test_static_downcast();
}

int main() { test(); }
<commit_msg>refactor: #include <type_traits><commit_after>#include <cassert>
#include <cstddef>
#include <functional>
#include <type_traits>
#include <utility>
#include <jegp/utility.hpp>

// [hash.combine]

struct X {
    int v;
};
struct Y { };
struct Z { };

template <> struct std::hash<X> {
    constexpr std::size_t operator()(X x) const noexcept { return x.v; }
};
template <> struct std::hash<Y> {
    std::size_t operator()(Y) const { return 0; }
};
template <> struct std::hash<Z> : std::hash<void> { };

template <class... Args> constexpr bool is_hash_combinable = requires { jegp::hash_combine(std::declval<Args>()...); };

constexpr void test_hash_combine() {
    static_assert(not is_hash_combinable<>);
    static_assert(not is_hash_combinable<int>);
    static_assert(not is_hash_combinable<X>);
    static_assert(not is_hash_combinable<Y>);
    static_assert(not is_hash_combinable<Z>);
    static_assert(is_hash_combinable<int, int>);
    static_assert(is_hash_combinable<int, X>);
    static_assert(is_hash_combinable<X, int>);
    static_assert(is_hash_combinable<X, X>);
    static_assert(is_hash_combinable<int, Y>);
    static_assert(is_hash_combinable<Y, int>);
    static_assert(is_hash_combinable<Y, Y>);
    static_assert(not is_hash_combinable<int, Z>);
    static_assert(not is_hash_combinable<Z, int>);
    static_assert(not is_hash_combinable<Z, Z>);

    static_assert(noexcept(jegp::hash_combine(0, 0)));
    static_assert(noexcept(jegp::hash_combine(0, X{})));
    static_assert(noexcept(jegp::hash_combine(X{}, 0)));
    static_assert(noexcept(jegp::hash_combine(X{}, X{})));
    static_assert(not noexcept(jegp::hash_combine(0, Y{})));
    static_assert(not noexcept(jegp::hash_combine(Y{}, 0)));
    static_assert(not noexcept(jegp::hash_combine(Y{}, Y{})));

    const X x[]{17, 20, -23};

    std::size_t seed{0};

    seed ^= x[0].v;
    seed ^= x[1].v + (seed << 6) + (seed >> 2);

    assert(seed == jegp::hash_combine(x[0], x[1]));

    seed ^= x[2].v + (seed << 6) + (seed >> 2);

    assert(seed == jegp::hash_combine(x[0], x[1], x[2]));
}

// [static.downcast]

template <class DerivedRef, class Base> constexpr bool is_static_downcastable = requires {
    jegp::static_downcast<DerivedRef>(std::declval<Base>());
};

template <class Derived, class Base, bool ExpectedToPass = true>
    requires(
        std::is_same_v<Derived, std::remove_cvref_t<Derived>>and std::is_same_v<Base, std::remove_cvref_t<Base>> and
        not std::is_same_v<Derived, Base> and std::is_base_of_v<Base, Derived>)
constexpr void assert_is_static_downcastable() {
    auto ok = [](bool b) { return b == ExpectedToPass; };

    static_assert(ok(is_static_downcastable<Derived&, Base&>));
    static_assert(ok(is_static_downcastable<const Derived&, Base&>));
    static_assert(ok(is_static_downcastable<Derived&&, Base&>));
    static_assert(ok(is_static_downcastable<const Derived&&, Base&>));

    static_assert(not is_static_downcastable<Derived&, const Base&>);
    static_assert(ok(is_static_downcastable<const Derived&, const Base&>));
    static_assert(not is_static_downcastable<Derived&&, const Base&>);
    static_assert(ok(is_static_downcastable<const Derived&&, const Base&>));

    static_assert(not is_static_downcastable<Derived&, Base>);
    static_assert(not is_static_downcastable<const Derived&, Base>);
    static_assert(ok(is_static_downcastable<Derived&&, Base>));
    static_assert(ok(is_static_downcastable<const Derived&&, Base>));

    static_assert(not is_static_downcastable<Derived&, const Base>);
    static_assert(not is_static_downcastable<const Derived&, const Base>);
    static_assert(not is_static_downcastable<Derived&&, const Base>);
    static_assert(ok(is_static_downcastable<const Derived&&, const Base>));

    static_assert(not is_static_downcastable<Derived, Base&>);
    static_assert(not is_static_downcastable<Derived, const Base&>);
    static_assert(not is_static_downcastable<Derived, Base>);
    static_assert(not is_static_downcastable<Derived, const Base>);
}

constexpr void test_static_downcast() {
    struct B { };
    struct D : B { };
    struct D2 : private B { };
    struct D3 : D, B { };
    struct D4 : virtual B { };
    assert_is_static_downcastable<D, B>();
    assert_is_static_downcastable<D2, B, false>();
    assert_is_static_downcastable<D3, B, false>();
    assert_is_static_downcastable<D4, B, false>();
}

consteval void test() {
    test_hash_combine();
    test_static_downcast();
}

int main() { test(); }
<|endoftext|>


<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (testabilitydriver@nokia.com)
**
** This file is part of Testability Driver Qt Agent
**
** If you have questions regarding the use of this file, please contact
** Nokia at testabilitydriver@nokia.com .
**
** This library is free software; you can redistribute it and/or
** modify it 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.
**
****************************************************************************/

#include <QApplication>
#include <QtPlugin>
#include <QDebug>
#include <QHash>

#include <taslogger.h>
#include <testabilityutils.h>
#include <tasqtdatamodel.h>

#include "MobilitySysInfoFixture.h"

static const QString ACTION_GET_IMEI = "imei";
static const QString ACTION_GET_IMSI = "imsi";

Q_EXPORT_PLUGIN2(mobilitysysinfofixture, MobilitySysInfoFixture)

/*!
\class MobilitySysInfoFixture
\brief Manages contact on device

*/

/*!
Constructor
*/
MobilitySysInfoFixture::MobilitySysInfoFixture(QObject* parent)
    :QObject(parent)
{}

/*!
  Destructor
*/
MobilitySysInfoFixture::~MobilitySysInfoFixture()
{}

/*!
  Implementation for traverse so always true.
*/
bool MobilitySysInfoFixture::execute(void * objectInstance, QString actionName, QHash<QString, QString> parameters, QString & stdOut)
{
    Q_UNUSED(objectInstance);

    TasLogger::logger()->debug("> MobilitySysInfoFixture::execute:" + actionName);

    QSystemDeviceInfo * di = new QSystemDeviceInfo(this);

    bool retVal = false;

    if (actionName == ACTION_GET_IMEI) {
        stdOut.append(di->imei());
        retVal = true;
    } if (actionName == ACTION_GET_IMSI) {
        stdOut.append(di->imsi());
        retVal = true;
    } else {
        stdOut.append("Invalid contact fixture command: "+ actionName);
        return false;
    }

    return retVal;
}

<commit_msg>imei support<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (testabilitydriver@nokia.com)
**
** This file is part of Testability Driver Qt Agent
**
** If you have questions regarding the use of this file, please contact
** Nokia at testabilitydriver@nokia.com .
**
** This library is free software; you can redistribute it and/or
** modify it 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.
**
****************************************************************************/

#include <QApplication>
#include <QtPlugin>
#include <QDebug>
#include <QHash>

#include <taslogger.h>
#include <testabilityutils.h>
#include <tasqtdatamodel.h>

#include "MobilitySysInfoFixture.h"

static const QString ACTION_GET_IMEI = "imei";
static const QString ACTION_GET_IMSI = "imsi";

Q_EXPORT_PLUGIN2(mobilitysysinfofixture, MobilitySysInfoFixture)

/*!
\class MobilitySysInfoFixture
\brief Manages contact on device

*/

/*!
Constructor
*/
MobilitySysInfoFixture::MobilitySysInfoFixture(QObject* parent)
    :QObject(parent)
{}

/*!
  Destructor
*/
MobilitySysInfoFixture::~MobilitySysInfoFixture()
{}

/*!
  Implementation for traverse so always true.
*/
bool MobilitySysInfoFixture::execute(void * objectInstance, QString actionName, QHash<QString, QString> parameters, QString & stdOut)
{
    Q_UNUSED(objectInstance);

    TasLogger::logger()->debug("> MobilitySysInfoFixture::execute:" + actionName);

    QSystemDeviceInfo * di = new QSystemDeviceInfo(this);

    bool retVal = false;

    if (actionName == ACTION_GET_IMEI) {
        stdOut.append(di->imei());
        retVal = true;
    } else if (actionName == ACTION_GET_IMSI) {
        stdOut.append(di->imsi());
        retVal = true;
    } else {
        stdOut.append("Invalid mobility sysinfo command: "+ actionName);
        return false;
    }

    return retVal;
}

<|endoftext|>


<commit_before>//
// Created by Harrand on 25/12/2019.
//

#ifndef TOPAZ_GL_OBJECT_HPP
#define TOPAZ_GL_OBJECT_HPP
#include "gl/buffer.hpp"
#include <vector>
#include <memory>

namespace tz::gl
{
    using ObjectHandle = GLuint;

    /**
     * TODO: Document
     */
    class Object
    {
    public:
        /**
         * TODO: Document
         */
        Object();
        /**
         * TODO: Document
         */
        ~Object();
        /**
         * TODO: Document
         */
        void bind() const;
        /**
         * TODO: Document
         */
        void unbind() const;

        /**
         * TODO: Document
         */
        std::size_t size() const;

        bool operator==(ObjectHandle handle) const;
        bool operator==(const Object& rhs) const;
        bool operator!=(ObjectHandle handle) const;
        bool operator!=(const Object& rhs) const;

        std::size_t add_buffer(std::unique_ptr<tz::gl::IBuffer> buffer);
        template<tz::gl::BufferType Type, typename... Args>
        std::size_t emplace_buffer(Args&&... args);

        tz::gl::IBuffer* operator[](std::size_t idx);
        const tz::gl::IBuffer* operator[](std::size_t idx) const;

        void bind_child(std::size_t idx) const;

        template<tz::gl::BufferType Type>
        tz::gl::Buffer<Type>* get(std::size_t idx);
        template<tz::gl::BufferType Type>
        const tz::gl::Buffer<Type>* get(std::size_t idx) const;
    private:
        void verify() const;

        ObjectHandle vao;
        std::vector<std::unique_ptr<tz::gl::IBuffer>> buffers;
    };

    namespace bound
    {
        int vao();
    }
}

#include "gl/object.inl"
#endif // TOPAZ_GL_OBJECT_HPP<commit_msg>* Better documentation for tz::gl::Object!<commit_after>//
// Created by Harrand on 25/12/2019.
//

#ifndef TOPAZ_GL_OBJECT_HPP
#define TOPAZ_GL_OBJECT_HPP
#include "gl/buffer.hpp"
#include <vector>
#include <memory>

namespace tz::gl
{
    using ObjectHandle = GLuint;

    /**
     * tz::gl::Objects represent arbitrary Objects stored in VRAM. In OpenGL nomenclature, it is little more than a glorified VAO.
     *
     * tz::gl::Objects are responsible for ownership of at least zero tz::gl::Buffers. Some Buffers need no Object parent to work, but some do.
     */
    class Object
    {
    public:
        /**
         * Construct an empty Object. This object will be valid to the eyes of the graphics card drivers but has no useful information.
         */
        Object();
        /**
         * Cleans up VRAM resources used and will destroy all parent Buffers.
         */
        ~Object();
        /**
         * Bind the Object. TODO: Document this better.
         */
        void bind() const;
        /**
         * Unbind the Object. TODO: Document this better.
         */
        void unbind() const;

        /**
         * Retrieve the number of Buffers that this Object owns.
         * @return Number of child buffers.
         */
        std::size_t size() const;

        bool operator==(ObjectHandle handle) const;
        bool operator==(const Object& rhs) const;
        bool operator!=(ObjectHandle handle) const;
        bool operator!=(const Object& rhs) const;

        /**
         * Take ownership of an existing Buffer and retrieve an opaque ID handle corresponding to that Buffer.
         *
         * Note: This handle can be passed to operator[] to retrieve a pointer to the Buffer.
         * @param buffer The buffer to take ownership of.
         * @return Handle ID of the now-owned Buffer.
         */
        std::size_t add_buffer(std::unique_ptr<tz::gl::IBuffer> buffer);
        /**
         * Create a new Buffer in-place and retrieve an opaque ID handle corresponding to the new Buffer.
         *
         * Note: This handle can be passed to operator[] to retrieve a pointer to the Buffer.
         * @tparam Type The type specialisation to create the Buffer.
         * @tparam Args Types of arguments used to construct the Buffer.
         * @param args Values of arguments used to construct the Buffer.
         * @return Handle ID of the newly-created and owned Buffer.
         */
        template<tz::gl::BufferType Type, typename... Args>
        std::size_t emplace_buffer(Args&&... args);

        /**
         * Retrieve a pointer to an existing Buffer using its Handle ID.
         *
         * Note: This can return nullptr if the Buffer at this index was previously erased or released.
         * Precondition: The given index must be in-range (0 <= idx <= this->size()). Otherwise this will assert and invoke UB.
         * @param idx Handle ID whose corresponding Buffer should be retrieved.
         * @return Pointer to the existing Buffer if it exists. Otherwise nullptr.
         */
        tz::gl::IBuffer* operator[](std::size_t idx);
        /**
         * Retrieve a pointer to an existing IBuffer using its Handle ID. This will return the underlying interface.
         *
         * Note: This can return nullptr if the Buffer at this index was previously erased or released.
         * Precondition: The given index must be in-range (0 <= idx <= this->size()). Otherwise this will assert and invoke UB.
         * @param idx Handle ID whose corresponding Buffer should be retrieved.
         * @return Pointer to the existing Buffer if it exists. Otherwise nullptr.
         */
        const tz::gl::IBuffer* operator[](std::size_t idx) const;

        /**
         * Bind this Object, and then bind the child at the given index. This corresponds to the handle ID used when creating or taking ownership of the Buffer.
         * Precondition: See IBuffer::bind()
         * Precondition: The given index must be in-range (0 <= idx <= this->size()). Otherwise this will assert and invoke UB.
         * @param idx Handle ID whose corresponding Buffer should be bound.
         */
        void bind_child(std::size_t idx) const;
        /**
         * Retrieve a pointer to an existing IBuffer using its Handle ID. This will return the underlying interface.
         *
         * Note: This can return nullptr if the Buffer at this index was previously erased or released.
         * Note: If the underlying type o the Buffer is not known, you can instead retrieve a pointer to the interface via this->operator[].
         * Precondition: The given index must be in-range (0 <= idx <= this->size()). Otherwise this will assert and invoke UB.
         * Precondition: The Buffer at the given index must have underlying type matching Type. Otherwise this will invoke UB without asserting.
         * @tparam Type Underlying type of the Buffer at the given index.
         * @param idx Handle ID whose corresponding Buffer should be retrieved.
         * @return Pointer to the existing Buffer if it exists. Otherwise nullptr.
         */
        template<tz::gl::BufferType Type>
        tz::gl::Buffer<Type>* get(std::size_t idx);
        /**
         * Retrieve a pointer to an existing IBuffer using its Handle ID. This will return the underlying interface.
         *
         * Note: This can return nullptr if the Buffer at this index was previously erased or released.
         * Note: If the underlying type o the Buffer is not known, you can instead retrieve a pointer to the interface via this->operator[].
         * Precondition: The given index must be in-range (0 <= idx <= this->size()). Otherwise this will assert and invoke UB.
         * Precondition: The Buffer at the given index must have underlying type matching Type. Otherwise this will invoke UB without asserting.
         * @tparam Type Underlying type of the Buffer at the given index.
         * @param idx Handle ID whose corresponding Buffer should be retrieved.
         * @return Pointer to the existing Buffer if it exists. Otherwise nullptr.
         */
        template<tz::gl::BufferType Type>
        const tz::gl::Buffer<Type>* get(std::size_t idx) const;
    private:
        void verify() const;

        ObjectHandle vao;
        std::vector<std::unique_ptr<tz::gl::IBuffer>> buffers;
    };

    namespace bound
    {
        /**
         * Retrieve the currently bound VAO. This will return 0 if no VAO is bound.
         * @return Positive integer representing bound VAO if there is one. Otherwise 0.
         */
        int vao();
    }
}

#include "gl/object.inl"
#endif // TOPAZ_GL_OBJECT_HPP<|endoftext|>


<commit_before>// glfw_main.cpp

#include <GL/glew.h>

#if defined(_WIN32)
#  include <Windows.h>
#  define GLFW_EXPOSE_NATIVE_WIN32
#  define GLFW_EXPOSE_NATIVE_WGL
#elif defined(__linux__)
#  include <X11/X.h>
#  include <X11/extensions/Xrandr.h>
#  define GLFW_EXPOSE_NATIVE_X11
#  define GLFW_EXPOSE_NATIVE_GLX
#endif

#include <GLFW/glfw3.h>

#if !defined(__APPLE__)
#  include <GLFW/glfw3native.h>
#endif

#include <glm/gtc/type_ptr.hpp>

#include <stdio.h>
#include <string.h>
#include <sstream>

#include "ShaderFunctions.h"

// Set VSync is framework-dependent and has to come before the include
///@param state 0=off, 1=on, -1=adaptive
// Set vsync for both contexts.
static void SetVsync(int state)
{
    glfwSwapInterval(state);
}

static void ErrorCallback(int p_Error, const char* p_Description)
{
    (void)p_Error;
    (void)p_Description;
}

void keyboard(GLFWwindow* pWindow, int key, int codes, int action, int mods)
{
    (void)pWindow;
    (void)codes;

    if (action == GLFW_PRESS)
    {
    switch (key)
    {
        default:
            break;

        case GLFW_KEY_ESCAPE:
            glfwTerminate();
            break;
        }
    }
}

void resize(GLFWwindow* pWindow, int w, int h)
{
    (void)pWindow;
}

int main(int argc, char** argv)
{
    bool useOpenGLCoreContext = false;

#ifdef USE_CORE_CONTEXT
   // useOpenGLCoreContext = true;
#endif

#ifdef _LINUX
    // Linux driver seems to be lagging a bit
    useOpenGLCoreContext = false;
#endif

    // Command line options
    for (int i=0; i<argc; ++i)
    {
        const std::string a = argv[i];
        if (!a.compare("-core"))
        {
            useOpenGLCoreContext = true;
        }
        else if (!a.compare("-compat"))
        {
            useOpenGLCoreContext = false;
        }
    }

    GLFWwindow* l_Window = NULL;
    glfwSetErrorCallback(ErrorCallback);
    if (!glfwInit())
    {
        exit(EXIT_FAILURE);
    }

#ifndef _LINUX
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
#  if defined(_MACOS)
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
#  else
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
#  endif
#endif //ndef _LINUX
    if (useOpenGLCoreContext)
    {
        glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
        glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    }
    else
    {
#ifndef _LINUX
        glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_COMPAT_PROFILE);
#endif
    }

    glfwWindowHint(GLFW_SAMPLES, 0);
    l_Window = glfwCreateWindow(800, 600, "kinderegg", NULL, NULL);
    if (!l_Window)
    {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    glfwMakeContextCurrent(l_Window);
    glfwSetWindowSizeCallback(l_Window, resize);
    glfwSetKeyCallback(l_Window, keyboard);

    glfwMakeContextCurrent(l_Window);

    // Don't forget to initialize Glew, turn glewExperimental on to
    // avoid problems fetching function pointers...
    glewExperimental = GL_TRUE;
    const GLenum l_Result = glewInit();
    if (l_Result != GLEW_OK)
    {
        exit(EXIT_FAILURE);
    }

    GLuint l_vao = 0;
    glGenVertexArrays(1, &l_vao);
    glBindVertexArray(l_vao);

    GLuint prog = makeShaderByName("basic");

    while (!glfwWindowShouldClose(l_Window))
    {
        glfwPollEvents();

        glUseProgram(prog);
#if 1
        glBegin(GL_TRIANGLES);
        glColor3f(1.f, 0.f, 0.f);
        glVertex3f(0.f, 0.f, 0.f);

        glColor3f(0.f, 1.f, 0.f);
        glVertex3f(1.f, 0.f, 0.f);

        glColor3f(0.f, 0.f, 1.f);
        glVertex3f(0.f, 1.f, 0.f);

        glEnd();
#endif

        glfwSwapBuffers(l_Window);
    }

    glfwDestroyWindow(l_Window);
    glfwTerminate();
    exit(EXIT_SUCCESS);
}
<commit_msg>Draw rect to fill screen.<commit_after>// glfw_main.cpp

#include <GL/glew.h>

#if defined(_WIN32)
#  include <Windows.h>
#  define GLFW_EXPOSE_NATIVE_WIN32
#  define GLFW_EXPOSE_NATIVE_WGL
#elif defined(__linux__)
#  include <X11/X.h>
#  include <X11/extensions/Xrandr.h>
#  define GLFW_EXPOSE_NATIVE_X11
#  define GLFW_EXPOSE_NATIVE_GLX
#endif

#include <GLFW/glfw3.h>

#if !defined(__APPLE__)
#  include <GLFW/glfw3native.h>
#endif

#include <glm/gtc/type_ptr.hpp>

#include <stdio.h>
#include <string.h>
#include <sstream>

#include "ShaderFunctions.h"

// Set VSync is framework-dependent and has to come before the include
///@param state 0=off, 1=on, -1=adaptive
// Set vsync for both contexts.
static void SetVsync(int state)
{
    glfwSwapInterval(state);
}

static void ErrorCallback(int p_Error, const char* p_Description)
{
    (void)p_Error;
    (void)p_Description;
}

void keyboard(GLFWwindow* pWindow, int key, int codes, int action, int mods)
{
    (void)pWindow;
    (void)codes;

    if (action == GLFW_PRESS)
    {
    switch (key)
    {
        default:
            break;

        case GLFW_KEY_ESCAPE:
            glfwTerminate();
            break;
        }
    }
}

void resize(GLFWwindow* pWindow, int w, int h)
{
    (void)pWindow;
}

int main(int argc, char** argv)
{
    bool useOpenGLCoreContext = false;

#ifdef USE_CORE_CONTEXT
   // useOpenGLCoreContext = true;
#endif

#ifdef _LINUX
    // Linux driver seems to be lagging a bit
    useOpenGLCoreContext = false;
#endif

    // Command line options
    for (int i=0; i<argc; ++i)
    {
        const std::string a = argv[i];
        if (!a.compare("-core"))
        {
            useOpenGLCoreContext = true;
        }
        else if (!a.compare("-compat"))
        {
            useOpenGLCoreContext = false;
        }
    }

    GLFWwindow* l_Window = NULL;
    glfwSetErrorCallback(ErrorCallback);
    if (!glfwInit())
    {
        exit(EXIT_FAILURE);
    }

#ifndef _LINUX
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
#  if defined(_MACOS)
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
#  else
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
#  endif
#endif //ndef _LINUX
    if (useOpenGLCoreContext)
    {
        glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
        glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    }
    else
    {
#ifndef _LINUX
        glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_COMPAT_PROFILE);
#endif
    }

    glfwWindowHint(GLFW_SAMPLES, 0);
    l_Window = glfwCreateWindow(800, 600, "kinderegg", NULL, NULL);
    if (!l_Window)
    {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    glfwMakeContextCurrent(l_Window);
    glfwSetWindowSizeCallback(l_Window, resize);
    glfwSetKeyCallback(l_Window, keyboard);

    glfwMakeContextCurrent(l_Window);

    // Don't forget to initialize Glew, turn glewExperimental on to
    // avoid problems fetching function pointers...
    glewExperimental = GL_TRUE;
    const GLenum l_Result = glewInit();
    if (l_Result != GLEW_OK)
    {
        exit(EXIT_FAILURE);
    }

    GLuint l_vao = 0;
    glGenVertexArrays(1, &l_vao);
    glBindVertexArray(l_vao);

    GLuint prog = makeShaderByName("basic");

    while (!glfwWindowShouldClose(l_Window))
    {
        glfwPollEvents();

        glUseProgram(prog);
        glRecti(-1,-1,1,1);

        glfwSwapBuffers(l_Window);
    }

    glfwDestroyWindow(l_Window);
    glfwTerminate();
    exit(EXIT_SUCCESS);
}
<|endoftext|>


<commit_before>#include <string>
#include <vector>
#include <iostream>
#include <GL/glew.h>
#include <glm/glm.hpp>
#include <glm/ext.hpp>
#include "../include/handle.h"
#include "../include/glshader.h"
#include "../include/glprogram.h"

const std::function<void(GLuint*)> GL::Program::sProgDelete =
	[](GLuint *p){ glDeleteProgram(*p); };

GL::Program::Program(){
}
GL::Program::Program(std::string vertex, std::string frag){
	VertexShader vertShader(vertex);
	FragmentShader fragShader(frag);
	//Make sure the shaders are ok
	if (!vertShader.status() || !fragShader.status()){
		std::cout << vertShader.getLog() << std::endl
			<< fragShader.getLog() << std::endl;
	}
	link(vertShader, fragShader);
}
GL::Program::Program(VertexShader &vert, FragmentShader &frag){
	link(vert, frag);
}
void GL::Program::link(VertexShader &vert, FragmentShader &frag){
	mHandle = Handle(glCreateProgram(), sProgDelete);
	glAttachShader(mHandle, vert);
	glAttachShader(mHandle, frag);
	glLinkProgram(mHandle);
	glDetachShader(mHandle, vert);
	glDetachShader(mHandle, frag);
}
std::string GL::Program::getLog(){
	if (!status()){
		//Get the log length and then get the log
		GLint logLength;
		glGetShaderiv(mHandle, GL_INFO_LOG_LENGTH, &logLength);
		std::vector<char> log(logLength);
		glGetShaderInfoLog(mHandle, logLength, NULL, &log[0]);

		return "Program errors:\n" + std::string(log.begin(), log.end());
	}
	return "Success";
}
bool GL::Program::status(){
	GLint status;
	glGetProgramiv(mHandle, GL_LINK_STATUS, &status);
	return (status == GL_TRUE);
}
void GL::Program::use(){
	glUseProgram(mHandle);
}
GLint GL::Program::getAttribute(const std::string &name){
	return glGetAttribLocation(mHandle, name.c_str());
}
GLint GL::Program::getUniformBlockIndex(const std::string &name){
	return glGetUniformBlockIndex(mHandle, name.c_str());
}
void GL::Program::uniform1i(const std::string &attrib, int i){
	glUseProgram(mHandle);
	GLint attribLoc = glGetUniformLocation(mHandle, attrib.c_str());
	glUniform1i(attribLoc, i);
}
void GL::Program::uniform1f(const std::string &attrib, float f){
	glUseProgram(mHandle);
	GLint attribLoc = glGetUniformLocation(mHandle, attrib.c_str());
	glUniform1f(attribLoc, f);
}
void GL::Program::uniform3fv(const std::string &attrib, const glm::vec3 &vec){
	glUseProgram(mHandle);
	GLint attribLoc = glGetUniformLocation(mHandle, attrib.c_str());
	glUniform3fv(attribLoc, 1, glm::value_ptr(vec));
}
void GL::Program::uniform4fv(const std::string &attrib, const glm::vec4 &vec){
	glUseProgram(mHandle);
	GLint attribLoc = glGetUniformLocation(mHandle, attrib.c_str());
	glUniform4fv(attribLoc, 1, glm::value_ptr(vec));
}
void GL::Program::uniformMat4x4(const std::string &attrib, const glm::mat4 &matrix){
	glUseProgram(mHandle);
	GLint attribLoc = glGetUniformLocation(mHandle, attrib.c_str());
	glUniformMatrix4fv(attribLoc, 1, GL_FALSE, glm::value_ptr(matrix));
}
GL::Program::operator GLuint(){
	return mHandle;
}
<commit_msg>glprogram.cpp doesn't need to include iostream><commit_after>#include <string>
#include <vector>
#include <GL/glew.h>
#include <glm/glm.hpp>
#include <glm/ext.hpp>
#include "../include/handle.h"
#include "../include/glshader.h"
#include "../include/glprogram.h"

const std::function<void(GLuint*)> GL::Program::sProgDelete =
	[](GLuint *p){ glDeleteProgram(*p); };

GL::Program::Program(){
}
GL::Program::Program(std::string vertex, std::string frag){
	VertexShader vertShader(vertex);
	FragmentShader fragShader(frag);
	//Make sure the shaders are ok
	if (!vertShader.status() || !fragShader.status()){
		std::cout << vertShader.getLog() << std::endl
			<< fragShader.getLog() << std::endl;
	}
	link(vertShader, fragShader);
}
GL::Program::Program(VertexShader &vert, FragmentShader &frag){
	link(vert, frag);
}
void GL::Program::link(VertexShader &vert, FragmentShader &frag){
	mHandle = Handle(glCreateProgram(), sProgDelete);
	glAttachShader(mHandle, vert);
	glAttachShader(mHandle, frag);
	glLinkProgram(mHandle);
	glDetachShader(mHandle, vert);
	glDetachShader(mHandle, frag);
}
std::string GL::Program::getLog(){
	if (!status()){
		//Get the log length and then get the log
		GLint logLength;
		glGetShaderiv(mHandle, GL_INFO_LOG_LENGTH, &logLength);
		std::vector<char> log(logLength);
		glGetShaderInfoLog(mHandle, logLength, NULL, &log[0]);

		return "Program errors:\n" + std::string(log.begin(), log.end());
	}
	return "Success";
}
bool GL::Program::status(){
	GLint status;
	glGetProgramiv(mHandle, GL_LINK_STATUS, &status);
	return (status == GL_TRUE);
}
void GL::Program::use(){
	glUseProgram(mHandle);
}
GLint GL::Program::getAttribute(const std::string &name){
	return glGetAttribLocation(mHandle, name.c_str());
}
GLint GL::Program::getUniformBlockIndex(const std::string &name){
	return glGetUniformBlockIndex(mHandle, name.c_str());
}
void GL::Program::uniform1i(const std::string &attrib, int i){
	glUseProgram(mHandle);
	GLint attribLoc = glGetUniformLocation(mHandle, attrib.c_str());
	glUniform1i(attribLoc, i);
}
void GL::Program::uniform1f(const std::string &attrib, float f){
	glUseProgram(mHandle);
	GLint attribLoc = glGetUniformLocation(mHandle, attrib.c_str());
	glUniform1f(attribLoc, f);
}
void GL::Program::uniform3fv(const std::string &attrib, const glm::vec3 &vec){
	glUseProgram(mHandle);
	GLint attribLoc = glGetUniformLocation(mHandle, attrib.c_str());
	glUniform3fv(attribLoc, 1, glm::value_ptr(vec));
}
void GL::Program::uniform4fv(const std::string &attrib, const glm::vec4 &vec){
	glUseProgram(mHandle);
	GLint attribLoc = glGetUniformLocation(mHandle, attrib.c_str());
	glUniform4fv(attribLoc, 1, glm::value_ptr(vec));
}
void GL::Program::uniformMat4x4(const std::string &attrib, const glm::mat4 &matrix){
	glUseProgram(mHandle);
	GLint attribLoc = glGetUniformLocation(mHandle, attrib.c_str());
	glUniformMatrix4fv(attribLoc, 1, GL_FALSE, glm::value_ptr(matrix));
}
GL::Program::operator GLuint(){
	return mHandle;
}
<|endoftext|>


<commit_before>///
/// @file  C.cpp
/// @brief Simple demonstration implementation of the C(x, y) formula
///        in Xavier Gourdon's prime counting algorithm. This
///        implementation uses O(x^(1/2)) memory instead of O(x^(1/3))
///        in order to simplify the implementation.
///
///        I guess this implementation can be optimized significantly
///        by using an algorithm that is similar to the algorithm used
///        in S2_easy.cpp for the clustered easy leaves.
///
/// Copyright (C) 2019 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include <PiTable.hpp>
#include <primecount-internal.hpp>
#include <fast_div.hpp>
#include <generate.hpp>
#include <int128_t.hpp>
#include <min.hpp>
#include <imath.hpp>
#include <print.hpp>
#include <S2Status.hpp>

#include "FactorTableGourdon.hpp"

#include <stdint.h>
#include <vector>

using namespace std;
using namespace primecount;

namespace {

template <typename T, typename Primes, typename FactorTable>
T C_OpenMP(T x,
           int64_t y,
           int64_t z,
           int64_t k,
           Primes& primes,
           FactorTable& factor,
           int threads)
{
  T sum = 0;
  T y2 = y * (T) y;
  int64_t x_star = max(iroot<4>(x), x / y2);
  int64_t thread_threshold = 1000;
  threads = ideal_num_threads(threads, x_star, thread_threshold);

  PiTable pi(isqrt(x));
  int64_t pi_x_star = pi[x_star];
  S2Status status(x);

  #pragma omp parallel for schedule(dynamic) num_threads(threads) reduction(-: sum)
  for (int64_t b = k + 1; b <= pi_x_star; b++)
  {
    int64_t prime = primes[b];
    T x2 = x / prime;
    int64_t m = min(x2 / prime, z);
    int64_t min_m = x / ipow<T>(prime, 3);
    min_m = max(min_m, prime, z / prime);

    factor.to_index(&m);
    factor.to_index(&min_m);

    for (; m > min_m; m--)
    {
      // leastPrimeFactor[m] > prime && maxPrimeFactor[m] <= y
      if (prime < factor.is_leaf(m))
      {
        int64_t n = factor.get_number(m);
        int64_t xn = fast_div64(x2, n);
        sum -= factor.mu(m) * (pi[xn] - b + 2);
      }
    }

    if (is_print())
      status.print(b, pi_x_star);
  }

  return sum;
}

} // namespace

namespace primecount {

int64_t C(int64_t x,
          int64_t y,
          int64_t z,
          int64_t k,
          int threads)
{
  print("");
  print("=== C(x, y) ===");
  print(x, y, z, k, threads);

  double time = get_time();
  auto primes = generate_primes<int32_t>(z);
  FactorTableGourdon<uint16_t> factor(y, z, threads);
  int64_t c = C_OpenMP((intfast64_t) x, y, z, k, primes, factor, threads);

  print("C", c, time);
  return c;
}

#ifdef HAVE_INT128_T

int128_t C(int128_t x,
           int64_t y,
           int64_t z,
           int64_t k,
           int threads)
{
  print("");
  print("=== C(x, y) ===");
  print(x, y, z, k, threads);

  double time = get_time();
  int128_t c;

  // uses less memory
  if (z <= numeric_limits<uint32_t>::max())
  {
    auto primes = generate_primes<uint32_t>(y);
    FactorTableGourdon<uint16_t> factor(y, z, threads);
    c = C_OpenMP((intfast128_t) x, y, z, k, primes, factor, threads);
  }
  else
  {
    auto primes = generate_primes<int64_t>(y);
    FactorTableGourdon<uint32_t> factor(y, z, threads);
    c = C_OpenMP((intfast128_t) x, y, z, k, primes, factor, threads);
  }

  print("C", c, time);
  return c;
}

#endif

} // namespace
<commit_msg>Big speedup<commit_after>///
/// @file  C.cpp
/// @brief Simple demonstration implementation of the C(x, y) formula
///        in Xavier Gourdon's prime counting algorithm. This
///        implementation uses O(x^(1/2)) memory instead of O(x^(1/3))
///        in order to simplify the implementation.
///
/// Copyright (C) 2019 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include <PiTable.hpp>
#include <primecount-internal.hpp>
#include <fast_div.hpp>
#include <generate.hpp>
#include <int128_t.hpp>
#include <min.hpp>
#include <imath.hpp>
#include <print.hpp>
#include <S2Status.hpp>

#include <stdint.h>
#include <vector>

using namespace std;
using namespace primecount;

namespace {

/// Recursively iterate over the square free numbers coprime
/// to the first b primes. This algorithm is described in
/// section 2.2 of the paper: Douglas Staple, "The Combinatorial
/// Algorithm For Computing pi(x)", arXiv:1503.01839, 6 March
/// 2015.
///
template <int MU, typename T, typename Primes>
T C(T xp,
    uint64_t i,
    uint64_t m,
    uint64_t min_m,
    uint64_t max_m,
    uint64_t b,
    Primes& primes,
    PiTable& pi)
{
  T sum = 0;

  for (i++; i < primes.size(); i++)
  {
    uint64_t next_m = m * primes[i];

    // next_m may be 128-bit
    if ((T) m * primes[i] > max_m)
      return sum;

    if (next_m > min_m)
    {
      uint64_t xpm = fast_div64(xp, next_m);
      sum += MU * (pi[xpm] - b + 2);
    }

    sum += C<-MU>(xp, i, next_m, min_m, max_m, b, primes, pi);
  }

  return sum;
}

template <typename T, typename Primes>
T C_OpenMP(T x,
           int64_t y,
           int64_t z,
           int64_t k,
           Primes& primes,
           int threads)
{
  T sum = 0;
  T y2 = y * (T) y;
  int64_t x_star = max(iroot<4>(x), x / y2);
  int64_t thread_threshold = 1000;
  threads = ideal_num_threads(threads, x_star, thread_threshold);

  PiTable pi(isqrt(x));
  int64_t pi_x_star = pi[x_star];
  S2Status status(x);

  #pragma omp parallel for schedule(dynamic) num_threads(threads) reduction(-: sum)
  for (int64_t b = k + 1; b <= pi_x_star; b++)
  {
    int64_t prime = primes[b];
    T xp = x / prime;
    int64_t max_m = min(xp / prime, z);
    int64_t min_m = x / ipow<T>(prime, 3);
    min_m = max(min_m, prime, z / prime);

    sum -= C<-1>(xp, b, 1, min_m, max_m, b, primes, pi);

    if (is_print())
      status.print(b, pi_x_star);
  }

  return sum;
}

} // namespace

namespace primecount {

int64_t C(int64_t x,
          int64_t y,
          int64_t z,
          int64_t k,
          int threads)
{
  print("");
  print("=== C(x, y) ===");
  print(x, y, z, k, threads);

  double time = get_time();
  auto primes = generate_primes<int32_t>(y);
  int64_t c = C_OpenMP((intfast64_t) x, y, z, k, primes, threads);

  print("C", c, time);
  return c;
}

#ifdef HAVE_INT128_T

int128_t C(int128_t x,
           int64_t y,
           int64_t z,
           int64_t k,
           int threads)
{
  print("");
  print("=== C(x, y) ===");
  print(x, y, z, k, threads);

  double time = get_time();
  int128_t c;

  // uses less memory
  if (y <= numeric_limits<uint32_t>::max())
  {
    auto primes = generate_primes<uint32_t>(y);
    c = C_OpenMP((intfast128_t) x, y, z, k, primes, threads);
  }
  else
  {
    auto primes = generate_primes<int64_t>(y);
    c = C_OpenMP((intfast128_t) x, y, z, k, primes, threads);
  }

  print("C", c, time);
  return c;
}

#endif

} // namespace
<|endoftext|>