<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: swfntcch.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: hr $ $Date: 2007-09-27 09:26:58 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    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.
 *
 *    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
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"

#ifndef _VIEWSH_HXX
#include <viewsh.hxx>
#endif
#include "swfntcch.hxx"
#include "fmtcol.hxx"
#include "swfont.hxx"

// aus atrstck.cxx
extern const BYTE StackPos[];

// globale Variablen, werden in SwFntCch.Hxx bekanntgegeben
// Der FontCache wird in TxtInit.Cxx _TXTINIT erzeugt und in _TXTEXIT geloescht
SwFontCache *pSwFontCache = NULL;

/*************************************************************************
|*
|*  SwFontObj::SwFontObj(), ~SwFontObj()
|*
|*  Ersterstellung      AMA 25. Jun. 95
|*  Letzte Aenderung    AMA 25. Jun. 95
|*
|*************************************************************************/

SwFontObj::SwFontObj( const void *pOwn, ViewShell *pSh ) :
    SwCacheObj( (void*)pOwn ),
    aSwFont( &((SwTxtFmtColl *)pOwn)->GetAttrSet(), pSh ? pSh->getIDocumentSettingAccess() : 0 )
{
    aSwFont.GoMagic( pSh, aSwFont.GetActual() );
    const SwAttrSet& rAttrSet = ((SwTxtFmtColl *)pOwn)->GetAttrSet();
    for (USHORT i = RES_CHRATR_BEGIN; i < RES_CHRATR_END; i++)
        pDefaultArray[ StackPos[ i ] ] = &rAttrSet.Get( i, TRUE );
}

SwFontObj::~SwFontObj()
{
}

/*************************************************************************
|*
|*  SwFontAccess::SwFontAccess()
|*
|*  Ersterstellung      AMA 25. Jun. 95
|*  Letzte Aenderung    AMA 25. Jun. 95
|*
|*************************************************************************/

SwFontAccess::SwFontAccess( const void *pOwn, ViewShell *pSh ) :
    SwCacheAccess( *pSwFontCache, pOwn,
            ((SwTxtFmtColl*)pOwn)->IsInSwFntCache() ),
    pShell( pSh )
{
}

SwFontObj *SwFontAccess::Get( )
{
    return (SwFontObj *) SwCacheAccess::Get( );
}

SwCacheObj *SwFontAccess::NewObj( )
{
    ((SwTxtFmtColl*)pOwner)->SetInSwFntCache( TRUE );
    return new SwFontObj( pOwner, pShell );
}

<commit_msg>INTEGRATION: CWS changefileheader (1.9.242); FILE MERGED 2008/04/01 12:54:29 thb 1.9.242.2: #i85898# Stripping all external header guards 2008/03/31 16:54:59 rt 1.9.242.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: swfntcch.cxx,v $
 * $Revision: 1.10 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"

#include <viewsh.hxx>
#include "swfntcch.hxx"
#include "fmtcol.hxx"
#include "swfont.hxx"

// aus atrstck.cxx
extern const BYTE StackPos[];

// globale Variablen, werden in SwFntCch.Hxx bekanntgegeben
// Der FontCache wird in TxtInit.Cxx _TXTINIT erzeugt und in _TXTEXIT geloescht
SwFontCache *pSwFontCache = NULL;

/*************************************************************************
|*
|*  SwFontObj::SwFontObj(), ~SwFontObj()
|*
|*  Ersterstellung      AMA 25. Jun. 95
|*  Letzte Aenderung    AMA 25. Jun. 95
|*
|*************************************************************************/

SwFontObj::SwFontObj( const void *pOwn, ViewShell *pSh ) :
    SwCacheObj( (void*)pOwn ),
    aSwFont( &((SwTxtFmtColl *)pOwn)->GetAttrSet(), pSh ? pSh->getIDocumentSettingAccess() : 0 )
{
    aSwFont.GoMagic( pSh, aSwFont.GetActual() );
    const SwAttrSet& rAttrSet = ((SwTxtFmtColl *)pOwn)->GetAttrSet();
    for (USHORT i = RES_CHRATR_BEGIN; i < RES_CHRATR_END; i++)
        pDefaultArray[ StackPos[ i ] ] = &rAttrSet.Get( i, TRUE );
}

SwFontObj::~SwFontObj()
{
}

/*************************************************************************
|*
|*  SwFontAccess::SwFontAccess()
|*
|*  Ersterstellung      AMA 25. Jun. 95
|*  Letzte Aenderung    AMA 25. Jun. 95
|*
|*************************************************************************/

SwFontAccess::SwFontAccess( const void *pOwn, ViewShell *pSh ) :
    SwCacheAccess( *pSwFontCache, pOwn,
            ((SwTxtFmtColl*)pOwn)->IsInSwFntCache() ),
    pShell( pSh )
{
}

SwFontObj *SwFontAccess::Get( )
{
    return (SwFontObj *) SwCacheAccess::Get( );
}

SwCacheObj *SwFontAccess::NewObj( )
{
    ((SwTxtFmtColl*)pOwner)->SetInSwFntCache( TRUE );
    return new SwFontObj( pOwner, pShell );
}

<|endoftext|>


<commit_before><commit_msg>fdo#39468 Translate German Comments - shellio.cxx<commit_after><|endoftext|>


<commit_before>// Copyright © 2015 German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
//
// Author: Christian Kellner <kellner@bio.lmu.de>

#include "TestH5.hpp"

#include <nix/hdf5/FileHDF5.hpp>
#include <nix/hdf5/ExceptionHDF5.hpp>

#include "RefTester.hpp"

#include <iostream>
#include <sstream>
#include <iterator>
#include <stdexcept>
#include <limits>

unsigned int & TestH5::open_mode()
{
    static unsigned int openMode = H5F_ACC_TRUNC;
    return openMode;
}

void TestH5::setUp() {
    unsigned int &openMode = open_mode();

    if (openMode == H5F_ACC_TRUNC) {
        h5file = H5Fcreate("test_h5.h5", openMode, H5P_DEFAULT, H5P_DEFAULT);
    } else {
        h5file = H5Fopen("test_h5.h5", openMode, H5P_DEFAULT);
    }

    CPPUNIT_ASSERT(H5Iis_valid(h5file));

    hid_t g;
    if (openMode == H5F_ACC_TRUNC) {
        g = H5Gcreate2(h5file, "h5", H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
    } else {
        g = H5Gopen2(h5file, "h5", H5P_DEFAULT);
    }

    CPPUNIT_ASSERT(H5Iis_valid(g));
    h5group = nix::hdf5::Group(g);

    openMode = H5F_ACC_RDWR;
}

void TestH5::tearDown() {
    h5group.close();
    H5Fclose(h5file);
}

void TestH5::testBase() {
    CPPUNIT_ASSERT(h5group.isValid());

    nix::hdf5::Group g_invalid{};
    CPPUNIT_ASSERT_EQUAL(false, g_invalid.isValid());
    CPPUNIT_ASSERT_THROW(g_invalid.check("Error"), nix::hdf5::H5Exception);

    // check HTri

    typedef nix::hdf5::HTri::value_type tri_type;

    nix::hdf5::HTri htri_true(static_cast<tri_type >(1));
    nix::hdf5::HTri htri_false(static_cast<tri_type >(0));
    nix::hdf5::HTri htri_error(static_cast<tri_type >(-1));

    CPPUNIT_ASSERT_EQUAL(static_cast<tri_type >(1), htri_true.value);
    CPPUNIT_ASSERT_EQUAL(true, htri_true.result());
    CPPUNIT_ASSERT_EQUAL(false, htri_true.isError());
    CPPUNIT_ASSERT_EQUAL(false, !htri_true);
    CPPUNIT_ASSERT_EQUAL(true, htri_true.check("Error"));

    CPPUNIT_ASSERT_EQUAL(static_cast<tri_type >(0), htri_false.value);
    CPPUNIT_ASSERT_EQUAL(false, htri_false.result());
    CPPUNIT_ASSERT_EQUAL(false, htri_false.isError());
    CPPUNIT_ASSERT_EQUAL(true, !htri_false);
    CPPUNIT_ASSERT_EQUAL(false, htri_false.check("Error"));

    CPPUNIT_ASSERT_EQUAL(static_cast<tri_type >(-1), htri_error.value);
    CPPUNIT_ASSERT_EQUAL(false, htri_error.result());
    CPPUNIT_ASSERT_EQUAL(true, htri_error.isError());
    CPPUNIT_ASSERT_EQUAL(true, !htri_error);
    CPPUNIT_ASSERT_THROW(htri_error.check("Error"), nix::hdf5::H5Exception);

    // check HErr

    typedef nix::hdf5::HErr::value_type err_type;

    nix::hdf5::HErr herr_success(static_cast<err_type>(1));
    nix::hdf5::HErr herr_fail(static_cast<err_type>(-1));

    CPPUNIT_ASSERT_EQUAL(static_cast<tri_type >(1), herr_success.value);
    CPPUNIT_ASSERT_EQUAL(false, herr_success.isError());
    CPPUNIT_ASSERT_EQUAL(false, !herr_success);
    CPPUNIT_ASSERT_EQUAL(true, herr_success.check("Error"));

    CPPUNIT_ASSERT_EQUAL(static_cast<tri_type >(-1), herr_fail.value);
    CPPUNIT_ASSERT_EQUAL(true, herr_fail.isError());
    CPPUNIT_ASSERT_EQUAL(true, !herr_fail);
    CPPUNIT_ASSERT_THROW(herr_fail.check("Error"), nix::hdf5::H5Error);

    nix::hdf5::HErr herr_default;
    CPPUNIT_ASSERT_EQUAL(true, herr_default.isError());

    //check BaseHDF5

    //ref counting
    hid_t ga = H5Gopen(h5file, "/", H5P_DEFAULT);
    hid_t gb = H5Gopen(h5file, "/h5", H5P_DEFAULT);

    CPPUNIT_ASSERT(ga > 0);
    CPPUNIT_ASSERT(gb > 0);

    test_refcounting<nix::hdf5::BaseHDF5>(ga, gb);

    test_refcounting<nix::hdf5::LocID>(ga, gb);

    //name()
    std::string name = h5group.name();

    CPPUNIT_ASSERT_EQUAL(std::string("/h5"), name);
    CPPUNIT_ASSERT_EQUAL(std::string{}, g_invalid.name());
}

void TestH5::testDataType() {
    namespace h5x = nix::hdf5::h5x;

    hid_t t_int = H5Tcopy(H5T_NATIVE_INT);
    hid_t t_dbl = H5Tcopy(H5T_NATIVE_DOUBLE);

    CPPUNIT_ASSERT(t_int > 0);
    CPPUNIT_ASSERT(t_dbl > 0);

    test_refcounting<h5x::DataType>(t_int, t_dbl);

    H5Tclose(t_int);
    H5Tclose(t_dbl);

    h5x::DataType v_str = h5x::DataType::makeStrType();
    CPPUNIT_ASSERT_EQUAL(true, v_str.isVariableString());

    h5x::DataType str_255 = h5x::DataType::makeStrType(255);
    CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(255), str_255.size());

}

void TestH5::testDataSpace() {

    std::vector<hsize_t> dims = {4, 6};
    hid_t ds = H5Screate_simple(static_cast<int>(dims.size()), dims.data(), nullptr);
    nix::hdf5::DataSpace space(ds);

    nix::NDSize es = space.extent();
    CPPUNIT_ASSERT_EQUAL(es.size(), dims.size());
    CPPUNIT_ASSERT_EQUAL(es[0], dims[0]);
    CPPUNIT_ASSERT_EQUAL(es[1], dims[1]);

    CPPUNIT_ASSERT_EQUAL(1, H5Iget_ref(ds));
    space.close();
}
<commit_msg>[test] test check_h5_arg_name<commit_after>// Copyright © 2015 German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
//
// Author: Christian Kellner <kellner@bio.lmu.de>

#include "TestH5.hpp"

#include <nix/hdf5/FileHDF5.hpp>
#include <nix/hdf5/ExceptionHDF5.hpp>

#include "RefTester.hpp"

#include <iostream>
#include <sstream>
#include <iterator>
#include <stdexcept>
#include <limits>

unsigned int & TestH5::open_mode()
{
    static unsigned int openMode = H5F_ACC_TRUNC;
    return openMode;
}

void TestH5::setUp() {
    unsigned int &openMode = open_mode();

    if (openMode == H5F_ACC_TRUNC) {
        h5file = H5Fcreate("test_h5.h5", openMode, H5P_DEFAULT, H5P_DEFAULT);
    } else {
        h5file = H5Fopen("test_h5.h5", openMode, H5P_DEFAULT);
    }

    CPPUNIT_ASSERT(H5Iis_valid(h5file));

    hid_t g;
    if (openMode == H5F_ACC_TRUNC) {
        g = H5Gcreate2(h5file, "h5", H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
    } else {
        g = H5Gopen2(h5file, "h5", H5P_DEFAULT);
    }

    CPPUNIT_ASSERT(H5Iis_valid(g));
    h5group = nix::hdf5::Group(g);

    openMode = H5F_ACC_RDWR;
}

void TestH5::tearDown() {
    h5group.close();
    H5Fclose(h5file);
}

void TestH5::testBase() {
    CPPUNIT_ASSERT(h5group.isValid());

    nix::hdf5::Group g_invalid{};
    CPPUNIT_ASSERT_EQUAL(false, g_invalid.isValid());
    CPPUNIT_ASSERT_THROW(g_invalid.check("Error"), nix::hdf5::H5Exception);

    // check check, heh
    CPPUNIT_ASSERT_THROW(check_h5_arg_name("foo/bar"), std::invalid_argument);

    // check HTri

    typedef nix::hdf5::HTri::value_type tri_type;

    nix::hdf5::HTri htri_true(static_cast<tri_type >(1));
    nix::hdf5::HTri htri_false(static_cast<tri_type >(0));
    nix::hdf5::HTri htri_error(static_cast<tri_type >(-1));

    CPPUNIT_ASSERT_EQUAL(static_cast<tri_type >(1), htri_true.value);
    CPPUNIT_ASSERT_EQUAL(true, htri_true.result());
    CPPUNIT_ASSERT_EQUAL(false, htri_true.isError());
    CPPUNIT_ASSERT_EQUAL(false, !htri_true);
    CPPUNIT_ASSERT_EQUAL(true, htri_true.check("Error"));

    CPPUNIT_ASSERT_EQUAL(static_cast<tri_type >(0), htri_false.value);
    CPPUNIT_ASSERT_EQUAL(false, htri_false.result());
    CPPUNIT_ASSERT_EQUAL(false, htri_false.isError());
    CPPUNIT_ASSERT_EQUAL(true, !htri_false);
    CPPUNIT_ASSERT_EQUAL(false, htri_false.check("Error"));

    CPPUNIT_ASSERT_EQUAL(static_cast<tri_type >(-1), htri_error.value);
    CPPUNIT_ASSERT_EQUAL(false, htri_error.result());
    CPPUNIT_ASSERT_EQUAL(true, htri_error.isError());
    CPPUNIT_ASSERT_EQUAL(true, !htri_error);
    CPPUNIT_ASSERT_THROW(htri_error.check("Error"), nix::hdf5::H5Exception);

    // check HErr

    typedef nix::hdf5::HErr::value_type err_type;

    nix::hdf5::HErr herr_success(static_cast<err_type>(1));
    nix::hdf5::HErr herr_fail(static_cast<err_type>(-1));

    CPPUNIT_ASSERT_EQUAL(static_cast<tri_type >(1), herr_success.value);
    CPPUNIT_ASSERT_EQUAL(false, herr_success.isError());
    CPPUNIT_ASSERT_EQUAL(false, !herr_success);
    CPPUNIT_ASSERT_EQUAL(true, herr_success.check("Error"));

    CPPUNIT_ASSERT_EQUAL(static_cast<tri_type >(-1), herr_fail.value);
    CPPUNIT_ASSERT_EQUAL(true, herr_fail.isError());
    CPPUNIT_ASSERT_EQUAL(true, !herr_fail);
    CPPUNIT_ASSERT_THROW(herr_fail.check("Error"), nix::hdf5::H5Error);

    nix::hdf5::HErr herr_default;
    CPPUNIT_ASSERT_EQUAL(true, herr_default.isError());

    //check BaseHDF5

    //ref counting
    hid_t ga = H5Gopen(h5file, "/", H5P_DEFAULT);
    hid_t gb = H5Gopen(h5file, "/h5", H5P_DEFAULT);

    CPPUNIT_ASSERT(ga > 0);
    CPPUNIT_ASSERT(gb > 0);

    test_refcounting<nix::hdf5::BaseHDF5>(ga, gb);

    test_refcounting<nix::hdf5::LocID>(ga, gb);

    //name()
    std::string name = h5group.name();

    CPPUNIT_ASSERT_EQUAL(std::string("/h5"), name);
    CPPUNIT_ASSERT_EQUAL(std::string{}, g_invalid.name());
}

void TestH5::testDataType() {
    namespace h5x = nix::hdf5::h5x;

    hid_t t_int = H5Tcopy(H5T_NATIVE_INT);
    hid_t t_dbl = H5Tcopy(H5T_NATIVE_DOUBLE);

    CPPUNIT_ASSERT(t_int > 0);
    CPPUNIT_ASSERT(t_dbl > 0);

    test_refcounting<h5x::DataType>(t_int, t_dbl);

    H5Tclose(t_int);
    H5Tclose(t_dbl);

    h5x::DataType v_str = h5x::DataType::makeStrType();
    CPPUNIT_ASSERT_EQUAL(true, v_str.isVariableString());

    h5x::DataType str_255 = h5x::DataType::makeStrType(255);
    CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(255), str_255.size());

}

void TestH5::testDataSpace() {

    std::vector<hsize_t> dims = {4, 6};
    hid_t ds = H5Screate_simple(static_cast<int>(dims.size()), dims.data(), nullptr);
    nix::hdf5::DataSpace space(ds);

    nix::NDSize es = space.extent();
    CPPUNIT_ASSERT_EQUAL(es.size(), dims.size());
    CPPUNIT_ASSERT_EQUAL(es[0], dims[0]);
    CPPUNIT_ASSERT_EQUAL(es[1], dims[1]);

    CPPUNIT_ASSERT_EQUAL(1, H5Iget_ref(ds));
    space.close();
}
<|endoftext|>


<commit_before>//
// Created by Bentoo on 2017-04-13.
//

#include <cstring>
#include <Utils/MemoryBlock.h>
#include "Core/Gfx/SpriteBatchManager.h"
#include "Core/Gfx/SpriteBatch.h"
#include "Core/Gfx/Sprite.h"
#include "Core/Gfx/Camera.h"
#include "Core/Resources/Material/MaterialManager.h"
#include "Core/Engine.h"
#include "Core/Logger.h"

namespace Gfx
{
	const std::int32_t SpriteBuffer::DEFAULT_BUFFER_SIZE = 1000;
	const std::int32_t SpriteBuffer::MAX_BUFFER_SIZE = 64*1000;

	SpriteBuffer::SpriteBuffer(Memory::IMemoryBlock& memory, std::int32_t size)
		: _mappedPtr(nullptr), _vbo(nullptr), maximumSize(size), currentSize(0), offset(0)
	{
		_vbo = OpenGL::VBO::Create(memory);

		gl::BindBuffer(gl::ARRAY_BUFFER, *_vbo);
		OpenGL::checkError();

		gl::BufferData(gl::ARRAY_BUFFER, maximumSize * sizeof(SpriteVertex), nullptr, gl::DYNAMIC_DRAW);
		OpenGL::checkError();

		_vao = OpenGL::VAO::Create(memory);

		gl::BindVertexArray(getVAO());

		Core::Logger::info("SpriteBatchManager : creating sprite VAO...");

		gl::EnableVertexAttribArray(0);
		OpenGL::checkError();
		gl::VertexAttribPointer(0, 3, gl::FLOAT, gl::FALSE_, sizeof(SpriteVertex), reinterpret_cast<void*>(0));
		OpenGL::checkError();

		gl::EnableVertexAttribArray(1);
		OpenGL::checkError();
		auto textureOffset = sizeof(glm::vec3);
		gl::VertexAttribPointer(1, 3, gl::FLOAT, gl::FALSE_, sizeof(SpriteVertex), reinterpret_cast<void*>(textureOffset));
		OpenGL::checkError();

		gl::EnableVertexAttribArray(2);
		OpenGL::checkError();
		auto colorOffset = sizeof(glm::vec3) * 2;
		gl::VertexAttribPointer(2, 4, gl::UNSIGNED_BYTE, gl::TRUE_, sizeof(SpriteVertex), reinterpret_cast<void*>(colorOffset));
		OpenGL::checkError();

		Core::Logger::info("SpriteBatchManager : Created sprite VAO!");

		gl::BindVertexArray(0);
		gl::BindBuffer(gl::ARRAY_BUFFER, 0);
	}

	void SpriteBuffer::clear()
	{
		offset = 0;
		currentSize = 0;
		unmapMemory();
		mapMemory();
	}

	void SpriteBuffer::mapMemory()
	{
		if(_mappedPtr != nullptr)
			return;

		gl::BindBuffer(gl::ARRAY_BUFFER, getVBO());
		OpenGL::checkError();

		_mappedPtr = gl::MapBufferRange(gl::ARRAY_BUFFER, 0, maximumSize * sizeof(SpriteVertex),
										gl::MAP_WRITE_BIT | gl::MAP_INVALIDATE_RANGE_BIT);
		OpenGL::checkError();

		gl::BindBuffer(gl::ARRAY_BUFFER, 0);
		OpenGL::checkError();
	}

	void SpriteBuffer::unmapMemory()
	{
		if(_mappedPtr == nullptr)
			return;

		_mappedPtr = nullptr;
		gl::BindBuffer (gl::ARRAY_BUFFER, getVBO());
		OpenGL::checkError();

		gl::UnmapBuffer(gl::ARRAY_BUFFER);
		OpenGL::checkError();

		gl::BindBuffer (gl::ARRAY_BUFFER, 0);
		OpenGL::checkError();
	}

	void SpriteBuffer::copyData(SpriteVertex (&array)[6])
	{
		SpriteVertex* buffer = static_cast<SpriteVertex*>(_mappedPtr);
		mempcpy(buffer, array, sizeof(SpriteVertex) * 6);

		buffer		+= 6;
		currentSize	+= 6;
		_mappedPtr	 = buffer;
	}

	SpriteBatchManager::SpriteBatchManager(Core::Engine& engine,
										   Memory::IMemoryBlock& memory)
		: IManager(engine, memory),
		  _memory(memory),
		  _buffers(memory),
		  _batches(memory),
		  _currentBuffer(0)
	{ }

	SpriteBatchManager::~SpriteBatchManager()
	{
		for (auto& buffer : _buffers)
		{
			Memory::Delete(_memory, buffer->_vao);
			Memory::Delete(_memory, buffer->_vbo);
			Memory::Delete(_memory, buffer);
		}
	}

	bool SpriteBatchManager::initialize()
	{
		return true;
	}

	void SpriteBatchManager::clear()
	{
		for(auto& batch : _batches)
		{
			batch.clear();
		}

		for(auto* buffer : _buffers)
		{
			buffer->clear();
		}
	}

	SpriteBuffer& SpriteBatchManager::createNewBuffer(std::uint32_t size)
	{
		_buffers.emplace(YAGE_CREATE_NEW(_memory, SpriteBuffer)(_memory, SpriteBuffer::DEFAULT_BUFFER_SIZE));
		_buffers.back()->mapMemory();
		_currentBuffer++;

		return *_buffers.back();
	}

	SpriteBatch& SpriteBatchManager::getSpriteBatch(Utils::Handle<Core::Material> material, Camera* camera, int32_t minimalSize)
	{
		auto* mat = _engine.MaterialManager->tryGetMaterial(material);

		YAGE_ASSERT(camera != nullptr && mat != nullptr, "SpriteBatchManager : Tried to create SpriteBatch without material or camera!");

		BatchIndex index(camera->sortIndex, material.index);
		SpriteBatch* batchPtr = nullptr;

		auto batchItr = _batchMap.find(index.key);
		if (batchItr == _batchMap.end())
		{
			_batchMap[index.key] = _batches.size();

			// Todo : dynamically find buffer of best fitting size
			// if (getCurrentBuffer().getFreeSize() < minimalSize)
			// 	createNewBuffer(std::max(minimalSize, SpriteBuffer::MAX_BUFFER_SIZE));

			if (minimalSize < 0)
				minimalSize = SpriteBuffer::DEFAULT_BUFFER_SIZE;

			_batches.emplace(createNewBuffer(std::min(minimalSize, SpriteBuffer::MAX_BUFFER_SIZE)));
			batchPtr = &_batches.back();
		}
		else
		{
			batchPtr = &_batches[batchItr->second];

			if(minimalSize > 0)
				batchPtr->ensureCapacity(minimalSize);
		}

		YAGE_ASSERT(batchPtr != nullptr, "SpriteBatchManager : was unable to create SpriteBatch!");

		batchPtr->_cameraPtr = camera;
		batchPtr->_materialPtr = mat;

		return *batchPtr;
	}
}
<commit_msg>Changed mempcpy to memcpy<commit_after>//
// Created by Bentoo on 2017-04-13.
//

#include <Utils/MemoryBlock.h>
#include "Core/Gfx/SpriteBatchManager.h"
#include "Core/Gfx/SpriteBatch.h"
#include "Core/Gfx/Sprite.h"
#include "Core/Gfx/Camera.h"
#include "Core/Resources/Material/MaterialManager.h"
#include "Core/Engine.h"
#include "Core/Logger.h"

namespace Gfx
{
	const std::int32_t SpriteBuffer::DEFAULT_BUFFER_SIZE = 1000;
	const std::int32_t SpriteBuffer::MAX_BUFFER_SIZE = 64*1000;

	SpriteBuffer::SpriteBuffer(Memory::IMemoryBlock& memory, std::int32_t size)
		: _mappedPtr(nullptr), _vbo(nullptr), maximumSize(size), currentSize(0), offset(0)
	{
		_vbo = OpenGL::VBO::Create(memory);

		gl::BindBuffer(gl::ARRAY_BUFFER, *_vbo);
		OpenGL::checkError();

		gl::BufferData(gl::ARRAY_BUFFER, maximumSize * sizeof(SpriteVertex), nullptr, gl::DYNAMIC_DRAW);
		OpenGL::checkError();

		_vao = OpenGL::VAO::Create(memory);

		gl::BindVertexArray(getVAO());

		Core::Logger::info("SpriteBatchManager : creating sprite VAO...");

		gl::EnableVertexAttribArray(0);
		OpenGL::checkError();
		gl::VertexAttribPointer(0, 3, gl::FLOAT, gl::FALSE_, sizeof(SpriteVertex), reinterpret_cast<void*>(0));
		OpenGL::checkError();

		gl::EnableVertexAttribArray(1);
		OpenGL::checkError();
		auto textureOffset = sizeof(glm::vec3);
		gl::VertexAttribPointer(1, 3, gl::FLOAT, gl::FALSE_, sizeof(SpriteVertex), reinterpret_cast<void*>(textureOffset));
		OpenGL::checkError();

		gl::EnableVertexAttribArray(2);
		OpenGL::checkError();
		auto colorOffset = sizeof(glm::vec3) * 2;
		gl::VertexAttribPointer(2, 4, gl::UNSIGNED_BYTE, gl::TRUE_, sizeof(SpriteVertex), reinterpret_cast<void*>(colorOffset));
		OpenGL::checkError();

		Core::Logger::info("SpriteBatchManager : Created sprite VAO!");

		gl::BindVertexArray(0);
		gl::BindBuffer(gl::ARRAY_BUFFER, 0);
	}

	void SpriteBuffer::clear()
	{
		offset = 0;
		currentSize = 0;
		unmapMemory();
		mapMemory();
	}

	void SpriteBuffer::mapMemory()
	{
		if(_mappedPtr != nullptr)
			return;

		gl::BindBuffer(gl::ARRAY_BUFFER, getVBO());
		OpenGL::checkError();

		_mappedPtr = gl::MapBufferRange(gl::ARRAY_BUFFER, 0, maximumSize * sizeof(SpriteVertex),
										gl::MAP_WRITE_BIT | gl::MAP_INVALIDATE_RANGE_BIT);
		OpenGL::checkError();

		gl::BindBuffer(gl::ARRAY_BUFFER, 0);
		OpenGL::checkError();
	}

	void SpriteBuffer::unmapMemory()
	{
		if(_mappedPtr == nullptr)
			return;

		_mappedPtr = nullptr;
		gl::BindBuffer (gl::ARRAY_BUFFER, getVBO());
		OpenGL::checkError();

		gl::UnmapBuffer(gl::ARRAY_BUFFER);
		OpenGL::checkError();

		gl::BindBuffer (gl::ARRAY_BUFFER, 0);
		OpenGL::checkError();
	}

	void SpriteBuffer::copyData(SpriteVertex (&array)[6])
	{
		SpriteVertex* buffer = static_cast<SpriteVertex*>(_mappedPtr);
		memcpy(buffer, array, sizeof(SpriteVertex) * 6);

		buffer		+= 6;
		currentSize	+= 6;
		_mappedPtr	 = buffer;
	}

	SpriteBatchManager::SpriteBatchManager(Core::Engine& engine,
										   Memory::IMemoryBlock& memory)
		: IManager(engine, memory),
		  _memory(memory),
		  _buffers(memory),
		  _batches(memory),
		  _currentBuffer(0)
	{ }

	SpriteBatchManager::~SpriteBatchManager()
	{
		for (auto& buffer : _buffers)
		{
			Memory::Delete(_memory, buffer->_vao);
			Memory::Delete(_memory, buffer->_vbo);
			Memory::Delete(_memory, buffer);
		}
	}

	bool SpriteBatchManager::initialize()
	{
		return true;
	}

	void SpriteBatchManager::clear()
	{
		for(auto& batch : _batches)
		{
			batch.clear();
		}

		for(auto* buffer : _buffers)
		{
			buffer->clear();
		}
	}

	SpriteBuffer& SpriteBatchManager::createNewBuffer(std::uint32_t size)
	{
		_buffers.emplace(YAGE_CREATE_NEW(_memory, SpriteBuffer)(_memory, SpriteBuffer::DEFAULT_BUFFER_SIZE));
		_buffers.back()->mapMemory();
		_currentBuffer++;

		return *_buffers.back();
	}

	SpriteBatch& SpriteBatchManager::getSpriteBatch(Utils::Handle<Core::Material> material, Camera* camera, int32_t minimalSize)
	{
		auto* mat = _engine.MaterialManager->tryGetMaterial(material);

		YAGE_ASSERT(camera != nullptr && mat != nullptr, "SpriteBatchManager : Tried to create SpriteBatch without material or camera!");

		BatchIndex index(camera->sortIndex, material.index);
		SpriteBatch* batchPtr = nullptr;

		auto batchItr = _batchMap.find(index.key);
		if (batchItr == _batchMap.end())
		{
			_batchMap[index.key] = _batches.size();

			// Todo : dynamically find buffer of best fitting size
			// if (getCurrentBuffer().getFreeSize() < minimalSize)
			// 	createNewBuffer(std::max(minimalSize, SpriteBuffer::MAX_BUFFER_SIZE));

			if (minimalSize < 0)
				minimalSize = SpriteBuffer::DEFAULT_BUFFER_SIZE;

			_batches.emplace(createNewBuffer(std::min(minimalSize, SpriteBuffer::MAX_BUFFER_SIZE)));
			batchPtr = &_batches.back();
		}
		else
		{
			batchPtr = &_batches[batchItr->second];

			if(minimalSize > 0)
				batchPtr->ensureCapacity(minimalSize);
		}

		YAGE_ASSERT(batchPtr != nullptr, "SpriteBatchManager : was unable to create SpriteBatch!");

		batchPtr->_cameraPtr = camera;
		batchPtr->_materialPtr = mat;

		return *batchPtr;
	}
}
<|endoftext|>


<commit_before>// GUI_Main_Common_Core - Core GUI for MediaInfo
// Copyright (C) 2007-2010 MediaArea.net SARL, Info@MediaArea.net
//
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

//---------------------------------------------------------------------------
#include "GUI/Common/GUI_Main_Common_Core.h"
#include "Common/Core.h"
//---------------------------------------------------------------------------

//***************************************************************************
// Constructor/Destructor
//***************************************************************************

//---------------------------------------------------------------------------
GUI_Main_Common_Core::GUI_Main_Common_Core(Core* _C)
{
    //Internal
    C=_C;
    File_Pos=(size_t)-1;
}

//***************************************************************************
// Actions - Global
//***************************************************************************

//---------------------------------------------------------------------------
size_t GUI_Main_Common_Core::FilesCount_Get()
{
    return C->MI->Count_Get();
}

//---------------------------------------------------------------------------
size_t GUI_Main_Common_Core::FilesPos_Get()
{
    return File_Pos;
}

//***************************************************************************
// Actions - Per file
//***************************************************************************

//---------------------------------------------------------------------------
String GUI_Main_Common_Core::FileName_Get()
{
    return C->MI->Get(File_Pos, Stream_General, 0, _T("CompleteName")).c_str();
}

//***************************************************************************
// Actions - Per StreamKind
//***************************************************************************

//---------------------------------------------------------------------------
size_t GUI_Main_Common_Core::StreamsCount_Get(stream_t StreamKind)
{
    return C->MI->Count_Get(File_Pos, StreamKind);
}

//***************************************************************************
// Actions - Per Stream
//***************************************************************************

//---------------------------------------------------------------------------
String GUI_Main_Common_Core::Summary_Get(stream_t StreamKind, size_t StreamPos)
{
    C->MI->Option(_T("Inform"), _T("Summary"));
    return C->MI->Get(File_Pos, StreamKind, StreamPos, _T("Inform")).c_str();
}

//---------------------------------------------------------------------------
String GUI_Main_Common_Core::Inform_Get(stream_t StreamKind, size_t StreamPos)
{
    C->MI->Option(_T("Inform"), _T(""));
    return C->MI->Get(File_Pos, StreamKind, StreamPos, _T("Inform")).c_str();
}

//---------------------------------------------------------------------------
String GUI_Main_Common_Core::CodecID_Url_Get(stream_t StreamKind, size_t StreamPos)
{
    return C->MI->Get(File_Pos, StreamKind, StreamPos, _T("CodecID/Url")).c_str();
}

<commit_msg>x GUI, displaying URl of Format if URl of CodecID is not known<commit_after>// GUI_Main_Common_Core - Core GUI for MediaInfo
// Copyright (C) 2007-2010 MediaArea.net SARL, Info@MediaArea.net
//
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

//---------------------------------------------------------------------------
#include "GUI/Common/GUI_Main_Common_Core.h"
#include "Common/Core.h"
//---------------------------------------------------------------------------

//***************************************************************************
// Constructor/Destructor
//***************************************************************************

//---------------------------------------------------------------------------
GUI_Main_Common_Core::GUI_Main_Common_Core(Core* _C)
{
    //Internal
    C=_C;
    File_Pos=(size_t)-1;
}

//***************************************************************************
// Actions - Global
//***************************************************************************

//---------------------------------------------------------------------------
size_t GUI_Main_Common_Core::FilesCount_Get()
{
    return C->MI->Count_Get();
}

//---------------------------------------------------------------------------
size_t GUI_Main_Common_Core::FilesPos_Get()
{
    return File_Pos;
}

//***************************************************************************
// Actions - Per file
//***************************************************************************

//---------------------------------------------------------------------------
String GUI_Main_Common_Core::FileName_Get()
{
    return C->MI->Get(File_Pos, Stream_General, 0, _T("CompleteName")).c_str();
}

//***************************************************************************
// Actions - Per StreamKind
//***************************************************************************

//---------------------------------------------------------------------------
size_t GUI_Main_Common_Core::StreamsCount_Get(stream_t StreamKind)
{
    return C->MI->Count_Get(File_Pos, StreamKind);
}

//***************************************************************************
// Actions - Per Stream
//***************************************************************************

//---------------------------------------------------------------------------
String GUI_Main_Common_Core::Summary_Get(stream_t StreamKind, size_t StreamPos)
{
    C->MI->Option(_T("Inform"), _T("Summary"));
    return C->MI->Get(File_Pos, StreamKind, StreamPos, _T("Inform")).c_str();
}

//---------------------------------------------------------------------------
String GUI_Main_Common_Core::Inform_Get(stream_t StreamKind, size_t StreamPos)
{
    C->MI->Option(_T("Inform"), _T(""));
    return C->MI->Get(File_Pos, StreamKind, StreamPos, _T("Inform")).c_str();
}

//---------------------------------------------------------------------------
String GUI_Main_Common_Core::CodecID_Url_Get(stream_t StreamKind, size_t StreamPos)
{
    if (!C->MI->Get(File_Pos, StreamKind, StreamPos, _T("CodecID/Url")).empty())
        return C->MI->Get(File_Pos, StreamKind, StreamPos, _T("CodecID/Url")).c_str();
    else
        return C->MI->Get(File_Pos, StreamKind, StreamPos, _T("Format/Url")).c_str();
}

<|endoftext|>


<commit_before>// GUI_Main_Easy_Box - WxWidgets GUI for MediaInfo
// Copyright (C) 2007-2008 Jerome Martinez, Zen@MediaArea.net
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

//---------------------------------------------------------------------------
#include "wx/wxprec.h"
#ifndef WX_PRECOMP
    #include "wx/wx.h"
#endif
#ifdef __BORLANDC__
    #pragma hdrstop
#endif
#include "GUI/WxWidgets/GUI_Main_Easy_Box.h"
#include "GUI/WxWidgets/GUI_Main_Easy.h"
#include "Common/Core.h"
#include <wx/choice.h>
#include <wx/statbox.h>
#include <wx/stattext.h>
#include <wx/button.h>
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
BEGIN_EVENT_TABLE(GUI_Main_Easy_Box, wxPanel)
    //Button
    EVT_BUTTON(26991, GUI_Main_Easy_Box::OnClick)
END_EVENT_TABLE()

//***************************************************************************
// Constructor/Destructor
//***************************************************************************

//---------------------------------------------------------------------------
GUI_Main_Easy_Box::GUI_Main_Easy_Box(Core* _C, GUI_Main_Easy* Parent, wxWindow* Left, wxWindow* Top, stream_t StreamKind, size_t StreamPos)
    : wxPanel(Parent, 26991, wxPoint(0, 0), wxSize(Parent->GetClientSize().GetWidth()-0, Parent->GetClientSize().GetHeight()-0)),
    GUI_Main_Easy_Box_Core(_C, Parent, StreamKind, StreamPos)
{
    //Internal
    GUI_Main_Easy_Box::Parent=Parent;
    GUI_Main_Easy_Box::Left=Left;
    GUI_Main_Easy_Box::Top=Top;

    //Creation
    Box=new wxStaticBox  (this, 26991, wxEmptyString);
    Text=new wxStaticText(this, 26991, wxEmptyString);
    Tags=new wxStaticText(this, 26991, wxEmptyString);
    Button=new wxButton  (this, 26991, wxEmptyString);

    //Update
    GUI_Resize();
    GUI_Refresh();
}

//***************************************************************************
// Actions
//***************************************************************************

//---------------------------------------------------------------------------
void GUI_Main_Easy_Box::GUI_Refresh()
{
    //Translation
    Box->SetLabel(Box_Get().c_str());

    //Info
    Text->SetLabel(Text_Get().c_str());
    Text->SetToolTip(ToolTip_Get().c_str());
    Tags->SetLabel(Tags_Get().c_str());

    if (Button_Show())
    {
        Button->SetLabel(Button_Get().c_str());
        Button->Show();
    }
}

//---------------------------------------------------------------------------
void GUI_Main_Easy_Box::GUI_Resize()
{
    //Configuring
    if (MustHide())
    {
        SetSize     (Left?(Left->GetPosition().x+Left->GetSize().GetWidth()):2,
                    Top?(Top->GetPosition().y+Top->GetSize().GetHeight()):0,
                    0,
                    0);
        Hide();
        return;
    }

    //Calculating Parent data
    int Parent_Width=(Parent->GetClientSize().GetWidth()-1)/(int)Boxes_Show_Get();
    if (IsLastBox())
        Parent_Width+=(Parent->GetClientSize().GetWidth()-1)%(int)Boxes_Show_Get();
    const int Box_Boundary=3;

    //Text
    Text->SetSize  (Box_Boundary,
                    Box->GetCharHeight(),
                    (Parent_Width-Box_Boundary*2-(Tags_Get().empty()?0:Box->GetCharWidth()))/(Tags_Get().empty()?1:2)-1,
                    Text->GetCharHeight());
    Tags->SetSize  (Text->GetPosition().x+Text->GetSize().GetWidth()+Box->GetCharWidth(),
                    Text->GetPosition().y,
                    Tags_Get().empty()?0:Text->GetSize().GetWidth(),
                    Text->GetSize().GetHeight());
    int Text_Width=Text->GetSize().GetWidth();
    Text->SetLabel(Text_Get().c_str());
    Tags->SetLabel(Tags_Get().c_str());
    Text->Wrap(Text_Width);
    Tags->Wrap(Text_Width);
    Text->SetSize  (-1,
                    -1,
                    Text_Width,
                    Text->GetSize().GetHeight()>Text->GetCharHeight()*(int)Lines_Count_Get()*2?Text->GetCharHeight()*(int)Lines_Count_Get()*2:(unsigned int)-1);
    Tags->SetSize  (-1,
                    -1,
                    Text_Width,
                    Tags->GetSize().GetHeight()>Tags->GetCharHeight()*(int)Lines_Count_Get()*2?Text->GetCharHeight()*(int)Lines_Count_Get()*2:(unsigned int)-1);

    //Button
    Button->SetSize(Box_Boundary,
                    Text->GetPosition().y+(Text->GetSize().GetHeight()>Tags->GetSize().GetHeight()?Text->GetSize().GetHeight():Tags->GetSize().GetHeight()),
                    Parent_Width-Box_Boundary*2,
                    Button_Show()?(Button->GetBestSize().GetHeight()):0);

    //Panel
    Box->SetSize   (0,
                    0,
                    Parent_Width-2,
                    Button->GetPosition().y+Button->GetSize().GetHeight()+Box_Boundary);
    SetSize         (Left?(Left->GetPosition().x+Left->GetSize().GetWidth()):1,
                    Top?(Top->GetPosition().y+Top->GetSize().GetHeight()):0,
                    Parent_Width,
                    Box->GetSize().GetHeight());

    if (Button_Show())
        Button->Show();
    else
        Button->Hide();
    Show();
}

//---------------------------------------------------------------------------
void GUI_Main_Easy_Box::OnClick(wxCommandEvent&)
{
    //Showing
    //wxMessageBox(Button_Click().c_str(), _T("Should launch"), wxOK | wxICON_INFORMATION, this);
    #if defined (_WINDOWS)
        ShellExecute(NULL, _T("open"), Button_Click().c_str(), NULL, NULL, 0); //wxExecute(_T("cmd /C start ")+Button_Click());
    #elif defined (_MACOS) || defined (_MACOSX)
        wxExecute(_T("open ")+Button_Click());
    #else
        wxExecute(_T("xdg-open ")+Button_Click());
    #endif
}
<commit_msg><commit_after>// GUI_Main_Easy_Box - WxWidgets GUI for MediaInfo
// Copyright (C) 2007-2008 Jerome Martinez, Zen@MediaArea.net
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

//---------------------------------------------------------------------------
#include "wx/wxprec.h"
#ifndef WX_PRECOMP
    #include "wx/wx.h"
#endif
#ifdef __BORLANDC__
    #pragma hdrstop
#endif
#include "GUI/WxWidgets/GUI_Main_Easy_Box.h"
#include "GUI/WxWidgets/GUI_Main_Easy.h"
#include "Common/Core.h"
#include <wx/choice.h>
#include <wx/statbox.h>
#include <wx/stattext.h>
#include <wx/button.h>
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
BEGIN_EVENT_TABLE(GUI_Main_Easy_Box, wxPanel)
    //Button
    EVT_BUTTON(26991, GUI_Main_Easy_Box::OnClick)
END_EVENT_TABLE()

//***************************************************************************
// Constructor/Destructor
//***************************************************************************

//---------------------------------------------------------------------------
GUI_Main_Easy_Box::GUI_Main_Easy_Box(Core* _C, GUI_Main_Easy* Parent, wxWindow* Left, wxWindow* Top, stream_t StreamKind, size_t StreamPos)
    : wxPanel(Parent, 26991, wxPoint(0, 0), wxSize(Parent->GetClientSize().GetWidth()-0, Parent->GetClientSize().GetHeight()-0)),
    GUI_Main_Easy_Box_Core(_C, Parent, StreamKind, StreamPos)
{
    //Internal
    GUI_Main_Easy_Box::Parent=Parent;
    GUI_Main_Easy_Box::Left=Left;
    GUI_Main_Easy_Box::Top=Top;

    //Creation
    Box=new wxStaticBox  (this, 26991, wxEmptyString);
    Text=new wxStaticText(this, 26991, wxEmptyString);
    Tags=new wxStaticText(this, 26991, wxEmptyString);
    Button=new wxButton  (this, 26991, wxEmptyString);

    //Update
    GUI_Resize();
    GUI_Refresh();
}

//***************************************************************************
// Actions
//***************************************************************************

//---------------------------------------------------------------------------
void GUI_Main_Easy_Box::GUI_Refresh()
{
    //Translation
    Box->SetLabel(Box_Get().c_str());

    //Info
    Text->SetLabel(Text_Get().c_str());
    Text->SetToolTip(ToolTip_Get().c_str());
    Tags->SetLabel(Tags_Get().c_str());

    if (Button_Show())
    {
        Button->SetLabel(Button_Get().c_str());
        Button->Show();
    }
}

//---------------------------------------------------------------------------
void GUI_Main_Easy_Box::GUI_Resize()
{
    //Configuring
    if (MustHide())
    {
        SetSize     (Left?(Left->GetPosition().x+Left->GetSize().GetWidth()):2,
                    Top?(Top->GetPosition().y+Top->GetSize().GetHeight()):0,
                    0,
                    0);
        Hide();
        return;
    }

    //Calculating Parent data
    int Parent_Width=(Parent->GetClientSize().GetWidth()-1)/(int)Boxes_Show_Get();
    if (IsLastBox())
        Parent_Width+=(Parent->GetClientSize().GetWidth()-1)%(int)Boxes_Show_Get();
    const int Box_Boundary=3;

    //Text
    Text->SetSize  (Box_Boundary,
                    Box->GetCharHeight(),
                    (Parent_Width-Box_Boundary*2-(Tags_Get().empty()?0:Box->GetCharWidth()))/(Tags_Get().empty()?1:2)-1,
                    Text->GetCharHeight());
    Tags->SetSize  (Text->GetPosition().x+Text->GetSize().GetWidth()+Box->GetCharWidth(),
                    Text->GetPosition().y,
                    Tags_Get().empty()?0:Text->GetSize().GetWidth(),
                    Text->GetSize().GetHeight());
    int Text_Width=Text->GetSize().GetWidth();
    Text->SetLabel(Text_Get().c_str());
    Tags->SetLabel(Tags_Get().c_str());
    Text->Wrap(Text_Width);
    Tags->Wrap(Text_Width);
    Text->SetSize  (-1,
                    -1,
                    Text_Width,
                    Text->GetSize().GetHeight()>Text->GetCharHeight()*(int)Lines_Count_Get()*2?Text->GetCharHeight()*(int)Lines_Count_Get()*2:(unsigned int)-1);
    Tags->SetSize  (-1,
                    -1,
                    Text_Width,
                    Tags->GetSize().GetHeight()>Tags->GetCharHeight()*(int)Lines_Count_Get()*2?Text->GetCharHeight()*(int)Lines_Count_Get()*2:(unsigned int)-1);

    //Button
    Button->SetSize(Box_Boundary,
                    Text->GetPosition().y+(Text->GetSize().GetHeight()>Tags->GetSize().GetHeight()?Text->GetSize().GetHeight():Tags->GetSize().GetHeight()),
                    Parent_Width-Box_Boundary*2,
                    Button_Show()?(Button->GetBestSize().GetHeight()):0);

    //Panel
    Box->SetSize   (0,
                    0,
                    Parent_Width-2,
                    Button->GetPosition().y+Button->GetSize().GetHeight()+Box_Boundary);
    SetSize         (Left?(Left->GetPosition().x+Left->GetSize().GetWidth()):1,
                    Top?(Top->GetPosition().y+Top->GetSize().GetHeight()):0,
                    Parent_Width,
                    Box->GetSize().GetHeight());

    if (Button_Show())
        Button->Show();
    else
        Button->Hide();
    Show();
}

//---------------------------------------------------------------------------
void GUI_Main_Easy_Box::OnClick(wxCommandEvent&)
{
    //Showing
    //wxMessageBox(Button_Click().c_str(), _T("Should launch"), wxOK | wxICON_INFORMATION, this);
    #if defined (_WINDOWS)
        ShellExecute(NULL, _T("open"), Button_Click().c_str(), NULL, NULL, 0); //wxExecute(_T("cmd /C start ")+Button_Click());
    #elif defined (_MACOS) || defined (_MACOSX)
        wxExecute((_T("open ")+Button_Click()).c_str());
    #else
        wxExecute(_T("xdg-open ")+Button_Click());
    #endif
}
<|endoftext|>


<commit_before>#ifndef _XMLStreamReaderDelegate_hpp_
#define _XMLStreamReaderDelegate_hpp_

#include "MXA/Common/MXASetGetMacros.h"

#include "MXA/Base/IMXADataModelReaderDelegate.h"
#include <MXA/Base/IDataModel.h>
#include "MXA/XML/DataModelXMLEvtHandler.h"

#define BUFFER_SIZE 1024

template<typename T>
class XMLStreamReaderDelegate: public IMXADataModelReaderDelegate,
                               public ExpatEvtHandler
{
  public:
    MXA_SHARED_POINTERS(XMLStreamReaderDelegate<T> )
    MXA_TYPE_MACRO(XMLStreamReaderDelegate<T> )

    typedef typename boost::shared_ptr<T>  StreamPointer;

    static Pointer New()
    {
     StreamPointer out = StreamPointer(new T);
     Pointer sharedPtr(new XMLStreamReaderDelegate<T>(out));
     return sharedPtr;
    }

    virtual ~XMLStreamReaderDelegate() {}

    virtual IDataModel::Pointer readModel();

    MXA_INSTANCE_PROPERTY_m(StreamPointer, StreamPointer);

  protected:
    XMLStreamReaderDelegate(StreamPointer stream)
    {
      m_StreamPointer = stream;
    }

  private:
    MXA_INSTANCE_PROPERTY_m(IDataModel::Pointer, DataModel)
    MXA_INSTANCE_PROPERTY_m(DataModelXMLEvtHandler::Pointer, XMLEvtHandler)

    ExpatParser::Pointer      m_Parser;

    XMLStreamReaderDelegate(const XMLStreamReaderDelegate&); // Copy Constructor Not Implemented
    void operator=(const XMLStreamReaderDelegate&); // Operator '=' Not Implemented
};

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
template<typename T>
IDataModel::Pointer XMLStreamReaderDelegate<T>::readModel()
{
//  std::cout << "XMLDataModelReader::readDataModel -> Data Records Size: " << this->_dataModel->getDataRecords().size() << std::endl;
//  if ( this->m_DataModel->getDataRecords().size() != 0 )
//  {
//    std::cout << "XMLStreamReaderDelegate::readDataModel - The data model has Data Records. This will turn out to be bad. You should be"
//    << " supplying a data model that is clean." << std::endl;
//    return IDataModel::NullPointer();
//  }

  m_DataModel = MXADataModel::New();

  // Create and initialise an instance of the parser.
  ExpatEvtHandler::Pointer evtHandler = DataModelXMLEvtHandler::NewExpatEvtHandler(m_DataModel);
  m_Parser = ExpatParser::New(evtHandler.get() );
  DataModelXMLEvtHandler* dmEvtHandler = dynamic_cast<DataModelXMLEvtHandler*>(evtHandler.get());
  dmEvtHandler->setParser(m_Parser.get() ); // We use the raw pointer other wise a circular dependency will occur

  m_Parser->Create(NULL, NULL);
  m_Parser->EnableElementHandler();
  m_Parser->EnableCharacterDataHandler();

  // Load the XML file.
  char buf[BUFFER_SIZE];
  bool   atEnd = false;
  size_t nRead;
  int xmlParseError = 0;
  if ( !m_StreamPointer->good())
  {
    return IDataModel::NullPointer();
  }

  while ( false == atEnd && xmlParseError >= 0)
  {
    // Read a block from the XML file and pass it to the parser
    m_StreamPointer->read (buf, BUFFER_SIZE);
    nRead = m_StreamPointer->gcount();
    if (m_StreamPointer->eof() || m_StreamPointer->fail() )
    {
      atEnd = true;
    }
    m_Parser->Parse(buf, nRead, atEnd);
    xmlParseError = evtHandler->getParseError();
  }

  if (xmlParseError < 0) {
    return IDataModel::NullPointer();
  }
  return m_DataModel;
}

#endif /* _XMLStreamReaderDelegate_hpp_  */
<commit_msg>Fixing some missing include files<commit_after>#ifndef _XMLStreamReaderDelegate_hpp_
#define _XMLStreamReaderDelegate_hpp_

#include "MXA/Common/MXASetGetMacros.h"

#include "MXA/Base/IMXADataModelReaderDelegate.h"
#include <MXA/Base/IDataModel.h>
#include "MXA/Core/MXADataModel.h"
#include "MXA/XML/DataModelXMLEvtHandler.h"

#define BUFFER_SIZE 1024

template<typename T>
class XMLStreamReaderDelegate: public IMXADataModelReaderDelegate,
                               public ExpatEvtHandler
{
  public:
    MXA_SHARED_POINTERS(XMLStreamReaderDelegate<T> )
    MXA_TYPE_MACRO(XMLStreamReaderDelegate<T> )

    typedef typename boost::shared_ptr<T>  StreamPointer;

    static Pointer New()
    {
     StreamPointer out = StreamPointer(new T);
     Pointer sharedPtr(new XMLStreamReaderDelegate<T>(out));
     return sharedPtr;
    }

    virtual ~XMLStreamReaderDelegate() {}

    virtual IDataModel::Pointer readModel();

    MXA_INSTANCE_PROPERTY_m(StreamPointer, StreamPointer);

  protected:
    XMLStreamReaderDelegate(StreamPointer stream)
    {
      m_StreamPointer = stream;
    }

  private:
    MXA_INSTANCE_PROPERTY_m(IDataModel::Pointer, DataModel)
    MXA_INSTANCE_PROPERTY_m(DataModelXMLEvtHandler::Pointer, XMLEvtHandler)

    ExpatParser::Pointer      m_Parser;

    XMLStreamReaderDelegate(const XMLStreamReaderDelegate&); // Copy Constructor Not Implemented
    void operator=(const XMLStreamReaderDelegate&); // Operator '=' Not Implemented
};

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
template<typename T>
IDataModel::Pointer XMLStreamReaderDelegate<T>::readModel()
{
//  std::cout << "XMLDataModelReader::readDataModel -> Data Records Size: " << this->_dataModel->getDataRecords().size() << std::endl;
//  if ( this->m_DataModel->getDataRecords().size() != 0 )
//  {
//    std::cout << "XMLStreamReaderDelegate::readDataModel - The data model has Data Records. This will turn out to be bad. You should be"
//    << " supplying a data model that is clean." << std::endl;
//    return IDataModel::NullPointer();
//  }

  m_DataModel = MXADataModel::New();

  // Create and initialise an instance of the parser.
  ExpatEvtHandler::Pointer evtHandler = DataModelXMLEvtHandler::NewExpatEvtHandler(m_DataModel);
  m_Parser = ExpatParser::New(evtHandler.get() );
  DataModelXMLEvtHandler* dmEvtHandler = dynamic_cast<DataModelXMLEvtHandler*>(evtHandler.get());
  dmEvtHandler->setParser(m_Parser.get() ); // We use the raw pointer other wise a circular dependency will occur

  m_Parser->Create(NULL, NULL);
  m_Parser->EnableElementHandler();
  m_Parser->EnableCharacterDataHandler();

  // Load the XML file.
  char buf[BUFFER_SIZE];
  bool   atEnd = false;
  size_t nRead;
  int xmlParseError = 0;
  if ( !m_StreamPointer->good())
  {
    return IDataModel::NullPointer();
  }

  while ( false == atEnd && xmlParseError >= 0)
  {
    // Read a block from the XML file and pass it to the parser
    m_StreamPointer->read (buf, BUFFER_SIZE);
    nRead = m_StreamPointer->gcount();
    if (m_StreamPointer->eof() || m_StreamPointer->fail() )
    {
      atEnd = true;
    }
    m_Parser->Parse(buf, nRead, atEnd);
    xmlParseError = evtHandler->getParseError();
  }

  if (xmlParseError < 0) {
    return IDataModel::NullPointer();
  }
  return m_DataModel;
}

#endif /* _XMLStreamReaderDelegate_hpp_  */
<|endoftext|>


<commit_before>//
// Copyright (c) 2008-2016 the Urho3D project.
//
// 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.
//

#ifdef URHO3D_ANGELSCRIPT
#include <Urho3D/AngelScript/ScriptFile.h>
#include <Urho3D/AngelScript/Script.h>
#endif
#include <Urho3D/Core/Main.h>
#include <Urho3D/Engine/Engine.h>
#include <Urho3D/IO/FileSystem.h>
#include <Urho3D/IO/Log.h>
#ifdef URHO3D_LUA
#include <Urho3D/LuaScript/LuaScript.h>
#endif
#include <Urho3D/Resource/ResourceCache.h>
#include <Urho3D/Resource/ResourceEvents.h>

#include "Urho3DPlayer.h"

#include <Urho3D/DebugNew.h>

URHO3D_DEFINE_APPLICATION_MAIN(Urho3DPlayer);

Urho3DPlayer::Urho3DPlayer(Context* context) :
    Application(context)
{
}

void Urho3DPlayer::Setup()
{
    // Web platform depends on the resource system to read any data files. Skip parsing the command line file now
    // and try later when the resource system is live
#ifndef __EMSCRIPTEN__
    // Read command line from a file if no arguments given. This is primarily intended for mobile platforms.
    // Note that the command file name uses a hardcoded path that does not utilize the resource system
    // properly (including resource path prefix), as the resource system is not yet initialized at this point
    FileSystem* filesystem = GetSubsystem<FileSystem>();
    const String commandFileName = filesystem->GetProgramDir() + "Data/CommandLine.txt";
    if (GetArguments().Empty() && filesystem->FileExists(commandFileName))
    {
        SharedPtr<File> commandFile(new File(context_, commandFileName));
        String commandLine = commandFile->ReadLine();
        commandFile->Close();
        ParseArguments(commandLine, false);
        // Reparse engine startup parameters now
        engineParameters_ = Engine::ParseParameters(GetArguments());
    }

    // Check for script file name from the arguments
    GetScriptFileName();

    // Show usage if not found
    if (scriptFileName_.Empty())
    {
        ErrorExit("Usage: Urho3DPlayer <scriptfile> [options]\n\n"
            "The script file should implement the function void Start() for initializing the "
            "application and subscribing to all necessary events, such as the frame update.\n"
            #ifndef WIN32
            "\nCommand line options:\n"
            "-x <res>     Horizontal resolution\n"
            "-y <res>     Vertical resolution\n"
            "-m <level>   Enable hardware multisampling\n"
            "-v           Enable vertical sync\n"
            "-t           Enable triple buffering\n"
            "-w           Start in windowed mode\n"
            "-s           Enable resizing when in windowed mode\n"
            "-hd          Enable high DPI, only supported by Apple platforms (OSX, iOS, and tvOS)\n"
            "-q           Enable quiet mode which does not log to standard output stream\n"
            "-b <length>  Sound buffer length in milliseconds\n"
            "-r <freq>    Sound mixing frequency in Hz\n"
            "-p <paths>   Resource path(s) to use, separated by semicolons\n"
            "-ap <paths>  Autoload resource path(s) to use, seperated by semicolons\n"
            "-log <level> Change the log level, valid 'level' values are 'debug', 'info', 'warning', 'error'\n"
            "-ds <file>   Dump used shader variations to a file for precaching\n"
            "-mq <level>  Material quality level, default 2 (high)\n"
            "-tq <level>  Texture quality level, default 2 (high)\n"
            "-tf <level>  Texture filter mode, default 2 (trilinear)\n"
            "-af <level>  Texture anisotropy level, default 4. Also sets anisotropic filter mode\n"
            "-gl2         Force OpenGL 2 use even if OpenGL 3 is available\n"
            "-flushgpu    Flush GPU command queue each frame. Effective only on Direct3D\n"
            "-borderless  Borderless window mode\n"
            "-headless    Headless mode. No application window will be created\n"
            "-landscape   Use landscape orientations (iOS only, default)\n"
            "-portrait    Use portrait orientations (iOS only)\n"
            "-prepass     Use light pre-pass rendering\n"
            "-deferred    Use deferred rendering\n"
            "-renderpath <name> Use the named renderpath (must enter full resource name)\n"
            "-lqshadows   Use low-quality (1-sample) shadow filtering\n"
            "-noshadows   Disable shadow rendering\n"
            "-nolimit     Disable frame limiter\n"
            "-nothreads   Disable worker threads\n"
            "-nosound     Disable sound output\n"
            "-noip        Disable sound mixing interpolation\n"
            "-touch       Touch emulation on desktop platform\n"
            #endif
        );
    }
    else
    {
        // Use the script file name as the base name for the log file
        engineParameters_["LogName"] = filesystem->GetAppPreferencesDir("urho3d", "logs") + GetFileNameAndExtension(scriptFileName_) + ".log";
    }
#else
    // On Web platform setup a default windowed resolution similar to the executable samples
    engineParameters_["FullScreen"]  = false;
#endif

    // Construct a search path to find the resource prefix with two entries:
    // The first entry is an empty path which will be substituted with program/bin directory -- this entry is for binary when it is still in build tree
    // The second and third entries are possible relative paths from the installed program/bin directory to the asset directory -- these entries are for binary when it is in the Urho3D SDK installation location
    if (!engineParameters_.Contains("ResourcePrefixPaths"))
        engineParameters_["ResourcePrefixPaths"] = ";../share/Resources;../share/Urho3D/Resources";
}

void Urho3DPlayer::Start()
{
    // Reattempt reading the command line now on Web platform
#ifdef __EMSCRIPTEN__
    if (GetArguments().Empty())
    {
        SharedPtr<File> commandFile = GetSubsystem<ResourceCache>()->GetFile("CommandLine.txt", false);
        if (commandFile)
        {
            String commandLine = commandFile->ReadLine();
            commandFile->Close();
            ParseArguments(commandLine, false);
        }
    }

    GetScriptFileName();

    if (scriptFileName_.Empty())
    {
        ErrorExit("Script file name not specified; cannot proceed");
        return;
    }
#endif

    String extension = GetExtension(scriptFileName_);
    if (extension != ".lua" && extension != ".luc")
    {
#ifdef URHO3D_ANGELSCRIPT
        // Instantiate and register the AngelScript subsystem
        context_->RegisterSubsystem(new Script(context_));

        // Hold a shared pointer to the script file to make sure it is not unloaded during runtime
        scriptFile_ = GetSubsystem<ResourceCache>()->GetResource<ScriptFile>(scriptFileName_);

        /// \hack If we are running the editor, also instantiate Lua subsystem to enable editing Lua ScriptInstances
#ifdef URHO3D_LUA
        if (scriptFileName_.Contains("Editor.as", false))
            context_->RegisterSubsystem(new LuaScript(context_));
#endif
        // If script loading is successful, proceed to main loop
        if (scriptFile_ && scriptFile_->Execute("void Start()"))
        {
            // Subscribe to script's reload event to allow live-reload of the application
            SubscribeToEvent(scriptFile_, E_RELOADSTARTED, URHO3D_HANDLER(Urho3DPlayer, HandleScriptReloadStarted));
            SubscribeToEvent(scriptFile_, E_RELOADFINISHED, URHO3D_HANDLER(Urho3DPlayer, HandleScriptReloadFinished));
            SubscribeToEvent(scriptFile_, E_RELOADFAILED, URHO3D_HANDLER(Urho3DPlayer, HandleScriptReloadFailed));
            return;
        }
#else
        ErrorExit("AngelScript is not enabled!");
        return;
#endif
    }
    else
    {
#ifdef URHO3D_LUA
        // Instantiate and register the Lua script subsystem
        LuaScript* luaScript = new LuaScript(context_);
        context_->RegisterSubsystem(luaScript);

        // If script loading is successful, proceed to main loop
        if (luaScript->ExecuteFile(scriptFileName_))
        {
            luaScript->ExecuteFunction("Start");
            return;
        }
#else
        ErrorExit("Lua is not enabled!");
        return;
#endif
    }

    // The script was not successfully loaded. Show the last error message and do not run the main loop
    ErrorExit();
}

void Urho3DPlayer::Stop()
{
#ifdef URHO3D_ANGELSCRIPT
    if (scriptFile_)
    {
        // Execute the optional stop function
        if (scriptFile_->GetFunction("void Stop()"))
            scriptFile_->Execute("void Stop()");
    }
#else
    if (false)
    {
    }
#endif

#ifdef URHO3D_LUA
    else
    {
        LuaScript* luaScript = GetSubsystem<LuaScript>();
        if (luaScript && luaScript->GetFunction("Stop", true))
            luaScript->ExecuteFunction("Stop");
    }
#endif
}

void Urho3DPlayer::HandleScriptReloadStarted(StringHash eventType, VariantMap& eventData)
{
#ifdef URHO3D_ANGELSCRIPT
    if (scriptFile_->GetFunction("void Stop()"))
        scriptFile_->Execute("void Stop()");
#endif
}

void Urho3DPlayer::HandleScriptReloadFinished(StringHash eventType, VariantMap& eventData)
{
#ifdef URHO3D_ANGELSCRIPT
    // Restart the script application after reload
    if (!scriptFile_->Execute("void Start()"))
    {
        scriptFile_.Reset();
        ErrorExit();
    }
#endif
}

void Urho3DPlayer::HandleScriptReloadFailed(StringHash eventType, VariantMap& eventData)
{
#ifdef URHO3D_ANGELSCRIPT
    scriptFile_.Reset();
    ErrorExit();
#endif
}

void Urho3DPlayer::GetScriptFileName()
{
    const Vector<String>& arguments = GetArguments();
    if (arguments.Size() && arguments[0][0] != '-')
        scriptFileName_ = GetInternalPath(arguments[0]);
}
<commit_msg>Sync Urho3DPlayer command line help from the documentation.<commit_after>//
// Copyright (c) 2008-2016 the Urho3D project.
//
// 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.
//

#ifdef URHO3D_ANGELSCRIPT
#include <Urho3D/AngelScript/ScriptFile.h>
#include <Urho3D/AngelScript/Script.h>
#endif
#include <Urho3D/Core/Main.h>
#include <Urho3D/Engine/Engine.h>
#include <Urho3D/IO/FileSystem.h>
#include <Urho3D/IO/Log.h>
#ifdef URHO3D_LUA
#include <Urho3D/LuaScript/LuaScript.h>
#endif
#include <Urho3D/Resource/ResourceCache.h>
#include <Urho3D/Resource/ResourceEvents.h>

#include "Urho3DPlayer.h"

#include <Urho3D/DebugNew.h>

URHO3D_DEFINE_APPLICATION_MAIN(Urho3DPlayer);

Urho3DPlayer::Urho3DPlayer(Context* context) :
    Application(context)
{
}

void Urho3DPlayer::Setup()
{
    // Web platform depends on the resource system to read any data files. Skip parsing the command line file now
    // and try later when the resource system is live
#ifndef __EMSCRIPTEN__
    // Read command line from a file if no arguments given. This is primarily intended for mobile platforms.
    // Note that the command file name uses a hardcoded path that does not utilize the resource system
    // properly (including resource path prefix), as the resource system is not yet initialized at this point
    FileSystem* filesystem = GetSubsystem<FileSystem>();
    const String commandFileName = filesystem->GetProgramDir() + "Data/CommandLine.txt";
    if (GetArguments().Empty() && filesystem->FileExists(commandFileName))
    {
        SharedPtr<File> commandFile(new File(context_, commandFileName));
        String commandLine = commandFile->ReadLine();
        commandFile->Close();
        ParseArguments(commandLine, false);
        // Reparse engine startup parameters now
        engineParameters_ = Engine::ParseParameters(GetArguments());
    }

    // Check for script file name from the arguments
    GetScriptFileName();

    // Show usage if not found
    if (scriptFileName_.Empty())
    {
        ErrorExit("Usage: Urho3DPlayer <scriptfile> [options]\n\n"
            "The script file should implement the function void Start() for initializing the "
            "application and subscribing to all necessary events, such as the frame update.\n"
            #ifndef WIN32
            "\nCommand line options:\n"
            "-x <res>     Horizontal resolution\n"
            "-y <res>     Vertical resolution\n"
            "-m <level>   Enable hardware multisampling\n"
            "-v           Enable vertical sync\n"
            "-t           Enable triple buffering\n"
            "-w           Start in windowed mode\n"
            "-s           Enable resizing when in windowed mode\n"
            "-hd          Enable high DPI, only supported by Apple platforms (OSX, iOS, and tvOS)\n"
            "-q           Enable quiet mode which does not log to standard output stream\n"
            "-b <length>  Sound buffer length in milliseconds\n"
            "-r <freq>    Sound mixing frequency in Hz\n"
            "-pp <paths>  Resource prefix path(s), separated by semicolons, default to executable path\n"
            "The resource prefix paths can also be defined using URHO3D_PREFIX_PATH env - var\n"
            "When both are defined, the paths set by -pp takes higher precedence\n"
            "-p <paths>   Resource path(s) to use, separated by semicolons, default to 'Data;CoreData'\n"
            "-pf <files>  Resource package file to use, separated by semicolons, default to none\n"
            "-ap <paths>  Resource autoload path(s), separated by semicolons, default to 'AutoLoad'\n"
            "-log <level> Change the log level, valid 'level' values: 'debug', 'info', 'warning', 'error'\n"
            "-ds <file>   Dump used shader variations to a file for precaching\n"
            "-mq <level>  Material quality level, default 2 (high)\n"
            "-tq <level>  Texture quality level, default 2 (high)\n"
            "-tf <level>  Texture filter mode, default 2 (trilinear)\n"
            "-af <level>  Texture anisotropy level, default 4. Also sets anisotropic filter mode\n"
            "-gl2         Force OpenGL 2 use even if OpenGL 3 is available\n"
            "-flushgpu    Flush GPU command queue each frame. Effective only on Direct3D\n"
            "-borderless  Borderless window mode\n"
            "-headless    Headless mode. No application window will be created\n"
            "-landscape   Use landscape orientations (iOS only, default)\n"
            "-portrait    Use portrait orientations (iOS only)\n"
            "-prepass     Use light pre-pass rendering\n"
            "-deferred    Use deferred rendering\n"
            "-renderpath <name> Use the named renderpath (must enter full resource name)\n"
            "-lqshadows   Use low-quality (1-sample) shadow filtering\n"
            "-noshadows   Disable shadow rendering\n"
            "-nolimit     Disable frame limiter\n"
            "-nothreads   Disable worker threads\n"
            "-nosound     Disable sound output\n"
            "-noip        Disable sound mixing interpolation\n"
            "-touch       Touch emulation on desktop platform\n"
            #endif
        );
    }
    else
    {
        // Use the script file name as the base name for the log file
        engineParameters_["LogName"] = filesystem->GetAppPreferencesDir("urho3d", "logs") + GetFileNameAndExtension(scriptFileName_) + ".log";
    }
#else
    // On Web platform setup a default windowed resolution similar to the executable samples
    engineParameters_["FullScreen"]  = false;
#endif

    // Construct a search path to find the resource prefix with two entries:
    // The first entry is an empty path which will be substituted with program/bin directory -- this entry is for binary when it is still in build tree
    // The second and third entries are possible relative paths from the installed program/bin directory to the asset directory -- these entries are for binary when it is in the Urho3D SDK installation location
    if (!engineParameters_.Contains("ResourcePrefixPaths"))
        engineParameters_["ResourcePrefixPaths"] = ";../share/Resources;../share/Urho3D/Resources";
}

void Urho3DPlayer::Start()
{
    // Reattempt reading the command line now on Web platform
#ifdef __EMSCRIPTEN__
    if (GetArguments().Empty())
    {
        SharedPtr<File> commandFile = GetSubsystem<ResourceCache>()->GetFile("CommandLine.txt", false);
        if (commandFile)
        {
            String commandLine = commandFile->ReadLine();
            commandFile->Close();
            ParseArguments(commandLine, false);
        }
    }

    GetScriptFileName();

    if (scriptFileName_.Empty())
    {
        ErrorExit("Script file name not specified; cannot proceed");
        return;
    }
#endif

    String extension = GetExtension(scriptFileName_);
    if (extension != ".lua" && extension != ".luc")
    {
#ifdef URHO3D_ANGELSCRIPT
        // Instantiate and register the AngelScript subsystem
        context_->RegisterSubsystem(new Script(context_));

        // Hold a shared pointer to the script file to make sure it is not unloaded during runtime
        scriptFile_ = GetSubsystem<ResourceCache>()->GetResource<ScriptFile>(scriptFileName_);

        /// \hack If we are running the editor, also instantiate Lua subsystem to enable editing Lua ScriptInstances
#ifdef URHO3D_LUA
        if (scriptFileName_.Contains("Editor.as", false))
            context_->RegisterSubsystem(new LuaScript(context_));
#endif
        // If script loading is successful, proceed to main loop
        if (scriptFile_ && scriptFile_->Execute("void Start()"))
        {
            // Subscribe to script's reload event to allow live-reload of the application
            SubscribeToEvent(scriptFile_, E_RELOADSTARTED, URHO3D_HANDLER(Urho3DPlayer, HandleScriptReloadStarted));
            SubscribeToEvent(scriptFile_, E_RELOADFINISHED, URHO3D_HANDLER(Urho3DPlayer, HandleScriptReloadFinished));
            SubscribeToEvent(scriptFile_, E_RELOADFAILED, URHO3D_HANDLER(Urho3DPlayer, HandleScriptReloadFailed));
            return;
        }
#else
        ErrorExit("AngelScript is not enabled!");
        return;
#endif
    }
    else
    {
#ifdef URHO3D_LUA
        // Instantiate and register the Lua script subsystem
        LuaScript* luaScript = new LuaScript(context_);
        context_->RegisterSubsystem(luaScript);

        // If script loading is successful, proceed to main loop
        if (luaScript->ExecuteFile(scriptFileName_))
        {
            luaScript->ExecuteFunction("Start");
            return;
        }
#else
        ErrorExit("Lua is not enabled!");
        return;
#endif
    }

    // The script was not successfully loaded. Show the last error message and do not run the main loop
    ErrorExit();
}

void Urho3DPlayer::Stop()
{
#ifdef URHO3D_ANGELSCRIPT
    if (scriptFile_)
    {
        // Execute the optional stop function
        if (scriptFile_->GetFunction("void Stop()"))
            scriptFile_->Execute("void Stop()");
    }
#else
    if (false)
    {
    }
#endif

#ifdef URHO3D_LUA
    else
    {
        LuaScript* luaScript = GetSubsystem<LuaScript>();
        if (luaScript && luaScript->GetFunction("Stop", true))
            luaScript->ExecuteFunction("Stop");
    }
#endif
}

void Urho3DPlayer::HandleScriptReloadStarted(StringHash eventType, VariantMap& eventData)
{
#ifdef URHO3D_ANGELSCRIPT
    if (scriptFile_->GetFunction("void Stop()"))
        scriptFile_->Execute("void Stop()");
#endif
}

void Urho3DPlayer::HandleScriptReloadFinished(StringHash eventType, VariantMap& eventData)
{
#ifdef URHO3D_ANGELSCRIPT
    // Restart the script application after reload
    if (!scriptFile_->Execute("void Start()"))
    {
        scriptFile_.Reset();
        ErrorExit();
    }
#endif
}

void Urho3DPlayer::HandleScriptReloadFailed(StringHash eventType, VariantMap& eventData)
{
#ifdef URHO3D_ANGELSCRIPT
    scriptFile_.Reset();
    ErrorExit();
#endif
}

void Urho3DPlayer::GetScriptFileName()
{
    const Vector<String>& arguments = GetArguments();
    if (arguments.Size() && arguments[0][0] != '-')
        scriptFileName_ = GetInternalPath(arguments[0]);
}
<|endoftext|>


<commit_before><commit_msg>coverity#708606 Uninitialized scalar field<commit_after><|endoftext|>


<commit_before><commit_msg>fdo#74702 update bad advise in comment in DrawTransparentNatively()<commit_after><|endoftext|>


<commit_before><commit_msg>VCL: Remove unnecessary headers from outdev/text.cxx<commit_after><|endoftext|>


<commit_before>#pragma once

#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4100 4701 4127 4706 4267 4324)
#endif
#include <beast/websocket.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif

#include <silicium/config.hpp>

namespace warpcoil
{
    namespace beast
    {
        enum class websocket_error
        {
            close,
            unexpected_opcode
        };

        struct websocket_error_category : boost::system::error_category
        {
            virtual const char *name() const BOOST_SYSTEM_NOEXCEPT override
            {
                return "websocket_error";
            }

            virtual std::string message(int ev) const override
            {
                switch (static_cast<websocket_error>(ev))
                {
                case websocket_error::close:
                    return "close";
                case websocket_error::unexpected_opcode:
                    return "unexpected_opcode";
                }
                SILICIUM_UNREACHABLE();
            }
        };

        inline boost::system::error_code make_error_code(websocket_error error)
        {
            static websocket_error_category const category;
            return boost::system::error_code(static_cast<int>(error), category);
        }

        template <class WebsocketStream>
        struct async_stream_adaptor
        {
            template <class... Args>
            explicit async_stream_adaptor(Args &&... args)
                : m_websocket(std::forward<Args>(args)...)
            {
            }

            WebsocketStream &next_layer()
            {
                return m_websocket;
            }

            WebsocketStream const &next_layer() const
            {
                return m_websocket;
            }

            template <class MutableBufferSequence, class CompletionToken>
            auto async_read_some(MutableBufferSequence buffers, CompletionToken &&token)
            {
                ::beast::async_completion<CompletionToken, void(boost::system::error_code, std::size_t)> completion(
                    token);
                std::size_t const read = read_from_receive_buffer(buffers);
                if (read)
                {
                    std::move(completion.handler)(boost::system::error_code(), read);
                }
                else
                {
                    m_websocket.async_read(
                        m_receivedOpcode, m_receiveBuffer,
                        [ this, buffers, handler = std::move(completion.handler) ](boost::system::error_code ec) mutable
                        {
                            if (!!ec)
                            {
                                std::move(handler)(ec, 0);
                                return;
                            }
                            switch (m_receivedOpcode)
                            {
                            case ::beast::websocket::opcode::binary:
                            case ::beast::websocket::opcode::text:
                                std::move(handler)(ec, read_from_receive_buffer(buffers));
                                break;

                            case ::beast::websocket::opcode::close:
                                std::move(handler)(websocket_error::close, 0);
                                break;

                            case ::beast::websocket::opcode::cont:
                            case ::beast::websocket::opcode::rsv3:
                            case ::beast::websocket::opcode::rsv4:
                            case ::beast::websocket::opcode::rsv5:
                            case ::beast::websocket::opcode::rsv6:
                            case ::beast::websocket::opcode::rsv7:
                            case ::beast::websocket::opcode::ping:
                            case ::beast::websocket::opcode::pong:
                            case ::beast::websocket::opcode::crsvb:
                            case ::beast::websocket::opcode::crsvc:
                            case ::beast::websocket::opcode::crsvd:
                            case ::beast::websocket::opcode::crsve:
                            case ::beast::websocket::opcode::crsvf:
                                std::move(handler)(websocket_error::unexpected_opcode, 0);
                                break;
                            }
                        });
                }
                return completion.result.get();
            }

            template <class ConstBufferSequence, class CompletionToken>
            auto async_write_some(ConstBufferSequence buffers, CompletionToken &&token)
            {
                ::beast::async_completion<CompletionToken, void(boost::system::error_code, std::size_t)> completion(
                    token);
                std::size_t const size = boost::asio::buffer_size(buffers);
                m_websocket.async_write(
                    buffers, [ handler = std::move(completion.handler), size ](boost::system::error_code ec) mutable
                    {
                        std::move(handler)(ec, ec ? 0 : size);
                    });
                return completion.result.get();
            }

        private:
            WebsocketStream m_websocket;
            ::beast::websocket::opcode m_receivedOpcode;
            ::beast::streambuf m_receiveBuffer;

            template <class MutableBufferSequence>
            std::size_t read_from_receive_buffer(MutableBufferSequence buffers)
            {
                std::size_t const copied = boost::asio::buffer_copy(buffers, m_receiveBuffer.data());
                m_receiveBuffer.consume(copied);
                return copied;
            }
        };
    }
}

namespace boost
{
    namespace system
    {
        template <>
        struct is_error_code_enum<warpcoil::beast::websocket_error> : std::true_type
        {
        };
    }
}
<commit_msg>invoke handlers correctly in async_write_some in the websocket adapter<commit_after>#pragma once

#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4100 4701 4127 4706 4267 4324)
#endif
#include <beast/websocket.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif

#include <silicium/config.hpp>

namespace warpcoil
{
    namespace beast
    {
        enum class websocket_error
        {
            close,
            unexpected_opcode
        };

        struct websocket_error_category : boost::system::error_category
        {
            virtual const char *name() const BOOST_SYSTEM_NOEXCEPT override
            {
                return "websocket_error";
            }

            virtual std::string message(int ev) const override
            {
                switch (static_cast<websocket_error>(ev))
                {
                case websocket_error::close:
                    return "close";
                case websocket_error::unexpected_opcode:
                    return "unexpected_opcode";
                }
                SILICIUM_UNREACHABLE();
            }
        };

        inline boost::system::error_code make_error_code(websocket_error error)
        {
            static websocket_error_category const category;
            return boost::system::error_code(static_cast<int>(error), category);
        }

        template <class WebsocketStream>
        struct async_stream_adaptor
        {
            template <class... Args>
            explicit async_stream_adaptor(Args &&... args)
                : m_websocket(std::forward<Args>(args)...)
            {
            }

            WebsocketStream &next_layer()
            {
                return m_websocket;
            }

            WebsocketStream const &next_layer() const
            {
                return m_websocket;
            }

            template <class MutableBufferSequence, class CompletionToken>
            auto async_read_some(MutableBufferSequence buffers, CompletionToken &&token)
            {
                ::beast::async_completion<CompletionToken, void(boost::system::error_code, std::size_t)> completion(
                    token);
                std::size_t const read = read_from_receive_buffer(buffers);
                if (read)
                {
                    std::move(completion.handler)(boost::system::error_code(), read);
                }
                else
                {
                    m_websocket.async_read(
                        m_receivedOpcode, m_receiveBuffer,
                        [ this, buffers, handler = std::move(completion.handler) ](boost::system::error_code ec) mutable
                        {
                            if (!!ec)
                            {
                                std::move(handler)(ec, 0);
                                return;
                            }
                            switch (m_receivedOpcode)
                            {
                            case ::beast::websocket::opcode::binary:
                            case ::beast::websocket::opcode::text:
                                std::move(handler)(ec, read_from_receive_buffer(buffers));
                                break;

                            case ::beast::websocket::opcode::close:
                                std::move(handler)(websocket_error::close, 0);
                                break;

                            case ::beast::websocket::opcode::cont:
                            case ::beast::websocket::opcode::rsv3:
                            case ::beast::websocket::opcode::rsv4:
                            case ::beast::websocket::opcode::rsv5:
                            case ::beast::websocket::opcode::rsv6:
                            case ::beast::websocket::opcode::rsv7:
                            case ::beast::websocket::opcode::ping:
                            case ::beast::websocket::opcode::pong:
                            case ::beast::websocket::opcode::crsvb:
                            case ::beast::websocket::opcode::crsvc:
                            case ::beast::websocket::opcode::crsvd:
                            case ::beast::websocket::opcode::crsve:
                            case ::beast::websocket::opcode::crsvf:
                                std::move(handler)(websocket_error::unexpected_opcode, 0);
                                break;
                            }
                        });
                }
                return completion.result.get();
            }

            template <class ConstBufferSequence, class CompletionToken>
            auto async_write_some(ConstBufferSequence buffers, CompletionToken &&token)
            {
                ::beast::async_completion<CompletionToken, void(boost::system::error_code, std::size_t)> completion(
                    token);
                std::size_t const size = boost::asio::buffer_size(buffers);
                m_websocket.async_write(
                    buffers, write_operation<decltype(completion.handler)>(std::move(completion.handler), size));
                return completion.result.get();
            }

        private:
            WebsocketStream m_websocket;
            ::beast::websocket::opcode m_receivedOpcode;
            ::beast::streambuf m_receiveBuffer;

            template <class Handler>
            struct write_operation
            {
                Handler handler;
                std::size_t bytes_transferred;

                explicit write_operation(Handler handler, std::size_t bytes_transferred)
                    : handler(std::move(handler))
                    , bytes_transferred(bytes_transferred)
                {
                }

                void operator()(boost::system::error_code ec)
                {
                    handler(ec, ec ? 0 : bytes_transferred);
                }

                template <class Function>
                friend void asio_handler_invoke(Function &&f, write_operation *operation)
                {
                    using boost::asio::asio_handler_invoke;
                    asio_handler_invoke(f, &operation->handler);
                }
            };

            template <class MutableBufferSequence>
            std::size_t read_from_receive_buffer(MutableBufferSequence buffers)
            {
                std::size_t const copied = boost::asio::buffer_copy(buffers, m_receiveBuffer.data());
                m_receiveBuffer.consume(copied);
                return copied;
            }
        };
    }
}

namespace boost
{
    namespace system
    {
        template <>
        struct is_error_code_enum<warpcoil::beast::websocket_error> : std::true_type
        {
        };
    }
}
<|endoftext|>