<commit_before>/*
Copyright libCellML Contributors

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

#include "gtest/gtest.h"

#include <iostream>
#include <libcellml>

#include "test_utils.h"

/*
 * The tests in this file are here to catch any branches of code that
 * are not picked up by the main tests testing the API of the library
 */
TEST(Coverage, import)
{
    const std::string e = "";
    libcellml::ImportSource i, im;

    im = std::move(i);

    // Copy constructor
    libcellml::ImportSource ic(im);

    const std::string a = ic.getId();
    EXPECT_EQ(e, a);
}

TEST(Coverage, printer)
{
    libcellml::Printer p, pm;

    pm = std::move(p);

    // Copy constructor
    libcellml::Printer pc(pm);

    size_t error_count = pc.errorCount();
    EXPECT_EQ(0u, error_count);
}

TEST(Coverage, units)
{
    const std::string e =
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
        "<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n"
        "  <units name=\"dimensionless\"/>\n"
        "</model>\n";
    libcellml::ModelPtr m = createModel();
    libcellml::UnitsPtr u = std::make_shared<libcellml::Units>();
    libcellml::UnitsPtr um = std::make_shared<libcellml::Units>();

    u->setName("dimensionless");

    um = std::move(u);

    // Copy constructor
    libcellml::UnitsPtr uc(um);
    m->addUnits(uc);

    libcellml::Printer printer;
    const std::string a = printer.printModel(m);
    EXPECT_EQ(e, a);
}

TEST(Coverage, when)
{
    const std::string e =
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
        "<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n"
        "  <component>\n"
        "    <reset>\n"
        "      <when/>\n"
        "    </reset>\n"
        "  </component>\n"
        "</model>\n";
    libcellml::ModelPtr m = createModelWithComponent();
    libcellml::ComponentPtr c = m->getComponent(0);
    libcellml::When w, wm;
    libcellml::ResetPtr r = std::make_shared<libcellml::Reset>();
    c->addReset(r);

    wm = std::move(w);

    libcellml::When wc(wm);

    libcellml::WhenPtr wp = std::make_shared<libcellml::When>(wc);
    r->addWhen(wp);

    libcellml::Printer printer;
    const std::string a = printer.printModel(m);
    EXPECT_EQ(e, a);
}

TEST(Coverage, unitsGetVariations)
{
    libcellml::Model m;

    libcellml::UnitsPtr u = std::make_shared<libcellml::Units>();
    u->setName("a_unit");

    u->addUnit(libcellml::Units::StandardUnit::AMPERE, "micro");
    m.addUnits(u);

    libcellml::UnitsPtr un = m.getUnits(0);
    EXPECT_EQ("a_unit", un->getName());
    libcellml::UnitsPtr uSn = static_cast<const libcellml::Model>(m).getUnits(0);
    EXPECT_EQ("a_unit", uSn->getName());

    libcellml::UnitsPtr uns = m.getUnits("a_unit");
    EXPECT_EQ("a_unit", uns->getName());
    libcellml::UnitsPtr uSns = static_cast<const libcellml::Model>(m).getUnits("a_unit");
    EXPECT_EQ("a_unit", uSns->getName());

    EXPECT_EQ(nullptr, m.getUnits("b_unit"));
    EXPECT_EQ(nullptr, m.getUnits(4));
}

TEST(Coverage, prefixToString)
{
    libcellml::Model m;
    libcellml::Printer printer;

    std::vector<std::string> prefixString =
        {"atto",
         "centi",
         "deca",
         "deci",
         "exa",
         "femto",
         "giga",
         "hecto",
         "kilo",
         "mega",
         "micro",
         "milli",
         "nano",
         "peta",
         "pico",
         "tera",
         "yocto",
         "yotta",
         "zepto",
         "zetta"};
    std::vector<libcellml::Prefix> prefixEnum =
        {libcellml::Prefix::ATTO,
         libcellml::Prefix::CENTI,
         libcellml::Prefix::DECA,
         libcellml::Prefix::DECI,
         libcellml::Prefix::EXA,
         libcellml::Prefix::FEMTO,
         libcellml::Prefix::GIGA,
         libcellml::Prefix::HECTO,
         libcellml::Prefix::KILO,
         libcellml::Prefix::MEGA,
         libcellml::Prefix::MICRO,
         libcellml::Prefix::MILLI,
         libcellml::Prefix::NANO,
         libcellml::Prefix::PETA,
         libcellml::Prefix::PICO,
         libcellml::Prefix::TERA,
         libcellml::Prefix::YOCTO,
         libcellml::Prefix::YOTTA,
         libcellml::Prefix::ZEPTO,
         libcellml::Prefix::ZETTA};
    for (std::vector<std::string>::size_type i = 0; i != prefixString.size(); ++i) {
        libcellml::UnitsPtr u = std::make_shared<libcellml::Units>();
        u->setName("abcdefg");
        u->addUnit("empty", prefixEnum[i]);

        m.addUnits(u);

        const std::string a = printer.printModel(m);
        std::size_t found = a.find(prefixString[i]);
        EXPECT_NE(std::string::npos, found);
        m.removeAllUnits();
    }
}

TEST(Coverage, variable)
{
    const std::string e =
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
        "<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n"
        "  <component>\n"
        "    <variable units=\"dimensionless\" initial_value=\"1\" interface=\"public\"/>\n"
        "  </component>\n"
        "</model>\n";
    libcellml::ModelPtr m = createModelWithComponent();
    libcellml::ComponentPtr c = m->getComponent(0);
    libcellml::VariablePtr v = std::make_shared<libcellml::Variable>();
    libcellml::VariablePtr vm = std::make_shared<libcellml::Variable>();
    libcellml::UnitsPtr u = std::make_shared<libcellml::Units>();

    v->setInitialValue(1.0);
    v->setInterfaceType("public");
    u->setName("dimensionless");
    v->setUnits(u);

    vm = std::move(v);

    // Copy constructor
    libcellml::VariablePtr vc(vm);
    c->addVariable(vc);

    libcellml::Printer printer;
    const std::string a = printer.printModel(m);
    EXPECT_EQ(e, a);
}

TEST(Coverage, component)
{
    const std::string e =
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
        "<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n"
        "  <component name=\"name\">\n"
        "    <variable/>\n"
        "    <1+1=2>\n"
        "  </component>\n"
        "</model>\n";
    const std::string math = "<1+1=2>\n";

    libcellml::ModelPtr m = createModel();
    libcellml::ComponentPtr c = std::make_shared<libcellml::Component>();
    libcellml::ComponentPtr cm = std::make_shared<libcellml::Component>();
    libcellml::VariablePtr v = std::make_shared<libcellml::Variable>();

    c->setName("name");
    c->addVariable(v);
    c->setMath(math);
    m->addComponent(c);

    libcellml::Printer printer;
    std::string a = printer.printModel(m);
    EXPECT_EQ(e, a);

    cm = std::move(c);
    a = printer.printModel(m);
    EXPECT_EQ(e, a);

    // Copy constructor
    m->removeAllComponents();
    libcellml::ComponentPtr cc(cm);
    m->addComponent(cc);

    a = printer.printModel(m);
    EXPECT_EQ(e, a);
}

TEST(Coverage, error)
{
    libcellml::ErrorPtr err = std::make_shared<libcellml::Error>();
    libcellml::Error e, em;
    const std::string description = "test";

    e.setDescription(description);
    e.setKind(libcellml::Error::Kind::XML);

    em = std::move(e);
    // Copy constructor
    libcellml::Error ec(em);

    EXPECT_EQ(description, ec.getDescription());
    EXPECT_EQ(libcellml::Error::Kind::XML, ec.getKind());
}
<commit_msg>Improve coverage through coverage tests.<commit_after>/*
Copyright libCellML Contributors

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

#include "gtest/gtest.h"

#include <iostream>
#include <libcellml>

/*
 * The tests in this file are here to catch any branches of code that
 * are not picked up by the main tests testing the API of the library
 */
TEST(Coverage, import)
{
    const std::string e = "";
    libcellml::ImportSource i, im;

    im = std::move(i);

    // Copy constructor
    libcellml::ImportSource ic(im);

    const std::string a = ic.getId();
    EXPECT_EQ(e, a);
}

TEST(Coverage, printer)
{
    libcellml::Printer p, pm;

    pm = std::move(p);

    // Copy constructor
    libcellml::Printer pc(pm);

    size_t error_count = pc.errorCount();
    EXPECT_EQ(0u, error_count);
}

TEST(Coverage, units)
{
    const std::string e = "<units name=\"dimensionless\"/>\n";
    libcellml::Units u, um;

    u.setName("dimensionless");

    um = std::move(u);

    // Copy constructor
    libcellml::Units uc(um);

    EXPECT_EQ("dimensionless", uc.getName());
}

TEST(Coverage, when)
{
    const std::string e =
        "<reset>\n"
        "  <when/>\n"
        "</reset>\n";
    libcellml::When w, wm;
    libcellml::Reset r;

    w.setValue("4738");
    wm = std::move(w);

    libcellml::When wc(wm);

    libcellml::WhenPtr wp = std::make_shared<libcellml::When>(wc);
    r.addWhen(wp);

    EXPECT_EQ("4738", wc.getValue());
}

TEST(Coverage, unitsGetVariations)
{
    libcellml::Model m;

    libcellml::UnitsPtr u = std::make_shared<libcellml::Units>();
    u->setName("a_unit");

    u->addUnit(libcellml::Units::StandardUnit::AMPERE, "micro");
    m.addUnits(u);

    libcellml::UnitsPtr un = m.getUnits(0);
    EXPECT_EQ("a_unit", un->getName());
    libcellml::UnitsPtr uSn = static_cast<const libcellml::Model>(m).getUnits(0);
    EXPECT_EQ("a_unit", uSn->getName());

    libcellml::UnitsPtr uns = m.getUnits("a_unit");
    EXPECT_EQ("a_unit", uns->getName());
    libcellml::UnitsPtr uSns = static_cast<const libcellml::Model>(m).getUnits("a_unit");
    EXPECT_EQ("a_unit", uSns->getName());

    EXPECT_EQ(nullptr, m.getUnits("b_unit"));
    EXPECT_EQ(nullptr, m.getUnits(4));
}

TEST(Coverage, prefixToString)
{
    libcellml::Model m;
    libcellml::Printer printer;

    std::vector<std::string> prefixString =
        {"atto",
         "centi",
         "deca",
         "deci",
         "exa",
         "femto",
         "giga",
         "hecto",
         "kilo",
         "mega",
         "micro",
         "milli",
         "nano",
         "peta",
         "pico",
         "tera",
         "yocto",
         "yotta",
         "zepto",
         "zetta"};
    std::vector<libcellml::Prefix> prefixEnum =
        {libcellml::Prefix::ATTO,
         libcellml::Prefix::CENTI,
         libcellml::Prefix::DECA,
         libcellml::Prefix::DECI,
         libcellml::Prefix::EXA,
         libcellml::Prefix::FEMTO,
         libcellml::Prefix::GIGA,
         libcellml::Prefix::HECTO,
         libcellml::Prefix::KILO,
         libcellml::Prefix::MEGA,
         libcellml::Prefix::MICRO,
         libcellml::Prefix::MILLI,
         libcellml::Prefix::NANO,
         libcellml::Prefix::PETA,
         libcellml::Prefix::PICO,
         libcellml::Prefix::TERA,
         libcellml::Prefix::YOCTO,
         libcellml::Prefix::YOTTA,
         libcellml::Prefix::ZEPTO,
         libcellml::Prefix::ZETTA};
    for (std::vector<std::string>::size_type i = 0; i != prefixString.size(); ++i) {
        libcellml::UnitsPtr u = std::make_shared<libcellml::Units>();
        u->setName("abcdefg");
        u->addUnit("empty", prefixEnum[i]);

        m.addUnits(u);

        const std::string a = printer.printModel(m);
        std::size_t found = a.find(prefixString[i]);
        EXPECT_NE(std::string::npos, found);
        m.removeAllUnits();
    }
}

TEST(Coverage, variable)
{
    const std::string e = "<variable units=\"dimensionless\" initial_value=\"1\" interface=\"public\"/>\n";
    libcellml::Variable v, vm;
    libcellml::UnitsPtr u = std::make_shared<libcellml::Units>();

    v.setInitialValue(1.0);
    v.setInterfaceType("public");
    u->setName("dimensionless");
    v.setUnits(u);

    vm = std::move(v);

    // Copy constructor
    libcellml::Variable vc(vm);

    EXPECT_EQ("dimensionless", vc.getUnits());
}

TEST(Coverage, component)
{
    const std::string math = "<1+1=2>\n";

    libcellml::Component c, cm;
    libcellml::VariablePtr v = std::make_shared<libcellml::Variable>();

    c.setName("name");
    c.addVariable(v);
    c.setMath(math);

    EXPECT_EQ(1u, c.variableCount());

    cm = std::move(c);
    EXPECT_EQ(1u, cm.variableCount());

    // Copy constructor
    libcellml::Component cc(cm);
    EXPECT_EQ(1u, cc.variableCount());
}

TEST(Coverage, error)
{
    libcellml::ErrorPtr err = std::make_shared<libcellml::Error>();
    libcellml::Error e, em;
    const std::string description = "test";

    e.setDescription(description);
    e.setKind(libcellml::Error::Kind::XML);

    em = std::move(e);
    // Copy constructor
    libcellml::Error ec(em);

    EXPECT_EQ(description, ec.getDescription());
    EXPECT_EQ(libcellml::Error::Kind::XML, ec.getKind());
}
<|endoftext|>


<commit_before>// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "base/path_service.h"
#include "content/browser/gpu/gpu_process_host.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/common/content_paths.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/url_constants.h"
#include "content/public/test/browser_test_utils.h"
#include "content/shell/browser/shell.h"
#include "content/test/content_browser_test.h"
#include "content/test/content_browser_test_utils.h"

namespace content {

namespace {
  void VerifyGPUProcessLaunch(bool* result) {
    GpuProcessHost* host =
        GpuProcessHost::Get(GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED,
                            content::CAUSE_FOR_GPU_LAUNCH_NO_LAUNCH);
    *result = !!host;
  }
}

class GpuFunctionalTest : public ContentBrowserTest {
 protected:
  virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
    base::FilePath test_dir;
    ASSERT_TRUE(PathService::Get(DIR_TEST_DATA, &test_dir));
    gpu_test_dir_ = test_dir.AppendASCII("gpu");
  }

  virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
    command_line->AppendSwitch(switches::kDisableGpuProcessPrelaunch);
  }

  void VerifyHardwareAccelerated(const std::string& feature) {
    NavigateToURL(shell(),
                  GURL(std::string(chrome::kChromeUIScheme).
                       append("://").
                       append(kChromeUIGpuHost)));

    {
      // Verify that the given feature is hardware accelerated..
      std::string javascript =
          "function VerifyHardwareAccelerated(feature) {"
          "  var list = document.querySelector(\".feature-status-list\");"
          "  for (var i=0; i < list.childElementCount; i++) {"
          "    var span_list = list.children[i].getElementsByTagName('span');"
          "    var feature_str = span_list[0].textContent;"
          "    var value_str = span_list[1].textContent;"
          "    if ((feature_str == feature) &&"
          "        (value_str == 'Hardware accelerated')) {"
          "      domAutomationController.send(\"success\");"
          "    }"
          "  }"
          "};";
      javascript.append("VerifyHardwareAccelerated(\"");
      javascript.append(feature);
      javascript.append("\");");
      std::string result;
      EXPECT_TRUE(ExecuteScriptAndExtractString(shell()->web_contents(),
                                                javascript,
                                                &result));
      EXPECT_EQ(result, "success");
    }
  }

  void VerifyGPUProcessOnPage(std::string filename, bool wait) {
    Shell::Initialize();
    ASSERT_TRUE(test_server()->Start());
    DOMMessageQueue message_queue;

    std::string url("files/gpu/");
    GURL full_url = test_server()->GetURL(url.append(filename));
    NavigateToURL(shell(), full_url);

    if (wait) {
      std::string result_string;
      ASSERT_TRUE(message_queue.WaitForMessage(&result_string));
    }

    bool result = false;
    BrowserThread::PostTaskAndReply(
        BrowserThread::IO,
        FROM_HERE,
        base::Bind(&VerifyGPUProcessLaunch, &result),
        base::MessageLoop::QuitClosure());
    base::MessageLoop::current()->Run();
    EXPECT_TRUE(result);
  }

  base::FilePath gpu_test_dir_;
};

#if defined(OS_LINUX) && !defined(NDEBUG)
// http://crbug.com/254724
#define IF_NOT_DEBUG_LINUX(x) DISABLED_ ## x
#else
#define IF_NOT_DEBUG_LINUX(x) x
#endif

IN_PROC_BROWSER_TEST_F(
    GpuFunctionalTest,
    IF_NOT_DEBUG_LINUX(MANUAL_TestFeatureHardwareAccelerated)) {
  VerifyHardwareAccelerated("WebGL: ");
  VerifyHardwareAccelerated("Canvas: ");
  VerifyHardwareAccelerated("3D CSS: ");
}

// Verify that gpu process is spawned in webgl example.
IN_PROC_BROWSER_TEST_F(GpuFunctionalTest,
                       IF_NOT_DEBUG_LINUX(MANUAL_TestWebGL)) {
  VerifyGPUProcessOnPage("functional_webgl.html", false);
}

// Verify that gpu process is spawned when viewing a 2D canvas.
IN_PROC_BROWSER_TEST_F(GpuFunctionalTest,
                       IF_NOT_DEBUG_LINUX(MANUAL_Test2dCanvas)) {
  VerifyGPUProcessOnPage("functional_canvas_demo.html", false);
}

// Verify that gpu process is spawned when viewing a 3D CSS page.
IN_PROC_BROWSER_TEST_F(GpuFunctionalTest,
                       IF_NOT_DEBUG_LINUX(MANUAL_Test3dCss)) {
  VerifyGPUProcessOnPage("functional_3d_css.html", false);
}

#if defined(OS_LINUX)
// crbug.com/257109
#define MANUAL_TestGpuWithVideo DISABLED_TestGpuWithVideo
#endif

// Verify that gpu process is started when viewing video.
IN_PROC_BROWSER_TEST_F(GpuFunctionalTest,
                       MANUAL_TestGpuWithVideo) {
  VerifyGPUProcessOnPage("functional_video.html", true);
}

} // namespace content
<commit_msg>remove unnecessary Shell::Initialize causing DCHECK on gpu_win bots<commit_after>// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "base/path_service.h"
#include "content/browser/gpu/gpu_process_host.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/common/content_paths.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/url_constants.h"
#include "content/public/test/browser_test_utils.h"
#include "content/shell/browser/shell.h"
#include "content/test/content_browser_test.h"
#include "content/test/content_browser_test_utils.h"

namespace content {

namespace {
  void VerifyGPUProcessLaunch(bool* result) {
    GpuProcessHost* host =
        GpuProcessHost::Get(GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED,
                            content::CAUSE_FOR_GPU_LAUNCH_NO_LAUNCH);
    *result = !!host;
  }
}

class GpuFunctionalTest : public ContentBrowserTest {
 protected:
  virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
    base::FilePath test_dir;
    ASSERT_TRUE(PathService::Get(DIR_TEST_DATA, &test_dir));
    gpu_test_dir_ = test_dir.AppendASCII("gpu");
  }

  virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
    command_line->AppendSwitch(switches::kDisableGpuProcessPrelaunch);
  }

  void VerifyHardwareAccelerated(const std::string& feature) {
    NavigateToURL(shell(),
                  GURL(std::string(chrome::kChromeUIScheme).
                       append("://").
                       append(kChromeUIGpuHost)));

    {
      // Verify that the given feature is hardware accelerated..
      std::string javascript =
          "function VerifyHardwareAccelerated(feature) {"
          "  var list = document.querySelector(\".feature-status-list\");"
          "  for (var i=0; i < list.childElementCount; i++) {"
          "    var span_list = list.children[i].getElementsByTagName('span');"
          "    var feature_str = span_list[0].textContent;"
          "    var value_str = span_list[1].textContent;"
          "    if ((feature_str == feature) &&"
          "        (value_str == 'Hardware accelerated')) {"
          "      domAutomationController.send(\"success\");"
          "    }"
          "  }"
          "};";
      javascript.append("VerifyHardwareAccelerated(\"");
      javascript.append(feature);
      javascript.append("\");");
      std::string result;
      EXPECT_TRUE(ExecuteScriptAndExtractString(shell()->web_contents(),
                                                javascript,
                                                &result));
      EXPECT_EQ(result, "success");
    }
  }

  void VerifyGPUProcessOnPage(std::string filename, bool wait) {
    ASSERT_TRUE(test_server()->Start());
    DOMMessageQueue message_queue;

    std::string url("files/gpu/");
    GURL full_url = test_server()->GetURL(url.append(filename));
    NavigateToURL(shell(), full_url);

    if (wait) {
      std::string result_string;
      ASSERT_TRUE(message_queue.WaitForMessage(&result_string));
    }

    bool result = false;
    BrowserThread::PostTaskAndReply(
        BrowserThread::IO,
        FROM_HERE,
        base::Bind(&VerifyGPUProcessLaunch, &result),
        base::MessageLoop::QuitClosure());
    base::MessageLoop::current()->Run();
    EXPECT_TRUE(result);
  }

  base::FilePath gpu_test_dir_;
};

#if defined(OS_LINUX) && !defined(NDEBUG)
// http://crbug.com/254724
#define IF_NOT_DEBUG_LINUX(x) DISABLED_ ## x
#else
#define IF_NOT_DEBUG_LINUX(x) x
#endif

IN_PROC_BROWSER_TEST_F(
    GpuFunctionalTest,
    IF_NOT_DEBUG_LINUX(MANUAL_TestFeatureHardwareAccelerated)) {
  VerifyHardwareAccelerated("WebGL: ");
  VerifyHardwareAccelerated("Canvas: ");
  VerifyHardwareAccelerated("3D CSS: ");
}

// Verify that gpu process is spawned in webgl example.
IN_PROC_BROWSER_TEST_F(GpuFunctionalTest,
                       IF_NOT_DEBUG_LINUX(MANUAL_TestWebGL)) {
  VerifyGPUProcessOnPage("functional_webgl.html", false);
}

// Verify that gpu process is spawned when viewing a 2D canvas.
IN_PROC_BROWSER_TEST_F(GpuFunctionalTest,
                       IF_NOT_DEBUG_LINUX(MANUAL_Test2dCanvas)) {
  VerifyGPUProcessOnPage("functional_canvas_demo.html", false);
}

// Verify that gpu process is spawned when viewing a 3D CSS page.
IN_PROC_BROWSER_TEST_F(GpuFunctionalTest,
                       IF_NOT_DEBUG_LINUX(MANUAL_Test3dCss)) {
  VerifyGPUProcessOnPage("functional_3d_css.html", false);
}

#if defined(OS_LINUX)
// crbug.com/257109
#define MANUAL_TestGpuWithVideo DISABLED_TestGpuWithVideo
#endif

// Verify that gpu process is started when viewing video.
IN_PROC_BROWSER_TEST_F(GpuFunctionalTest,
                       MANUAL_TestGpuWithVideo) {
  VerifyGPUProcessOnPage("functional_video.html", true);
}

} // namespace content
<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#if defined(ENABLE_GPU)

#include "content/common/gpu/image_transport_surface.h"

#include "base/bind.h"
#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/win/windows_version.h"
#include "content/common/gpu/gpu_messages.h"
#include "content/public/common/content_switches.h"
#include "ui/gfx/gl/gl_bindings.h"
#include "ui/gfx/gl/gl_context.h"
#include "ui/gfx/gl/gl_implementation.h"
#include "ui/gfx/gl/gl_surface_egl.h"
#include "ui/gfx/native_widget_types.h"

namespace {

// We are backed by an Pbuffer offscreen surface through which ANGLE provides
// a handle to the corresponding render target texture through an extension.
class PbufferImageTransportSurface
    : public gfx::GLSurfaceAdapter,
      public ImageTransportSurface,
      public base::SupportsWeakPtr<PbufferImageTransportSurface> {
 public:
  PbufferImageTransportSurface(GpuChannelManager* manager,
                               int32 render_view_id,
                               int32 renderer_id,
                               int32 command_buffer_id);

  // gfx::GLSurface implementation
  virtual bool Initialize() OVERRIDE;
  virtual void Destroy() OVERRIDE;
  virtual bool IsOffscreen() OVERRIDE;
  virtual bool SwapBuffers() OVERRIDE;
  virtual bool PostSubBuffer(int x, int y, int width, int height) OVERRIDE;
  virtual std::string GetExtensions() OVERRIDE;
  virtual void SetVisible(bool visible) OVERRIDE;

 protected:
  // ImageTransportSurface implementation
  virtual void OnNewSurfaceACK(uint64 surface_id,
                               TransportDIB::Handle shm_handle) OVERRIDE;
  virtual void OnBuffersSwappedACK() OVERRIDE;
  virtual void OnPostSubBufferACK() OVERRIDE;
  virtual void OnResizeViewACK() OVERRIDE;
  virtual void OnResize(gfx::Size size) OVERRIDE;

 private:
  virtual ~PbufferImageTransportSurface();
  void SendBuffersSwapped();

  // Whether the surface is currently visible.
  bool is_visible_;

  // Size to resize to when the surface becomes visible.
  gfx::Size visible_size_;

  scoped_ptr<ImageTransportHelper> helper_;

  DISALLOW_COPY_AND_ASSIGN(PbufferImageTransportSurface);
};

PbufferImageTransportSurface::PbufferImageTransportSurface(
    GpuChannelManager* manager,
    int32 render_view_id,
    int32 renderer_id,
    int32 command_buffer_id)
        : GLSurfaceAdapter(new gfx::PbufferGLSurfaceEGL(false,
                                                        gfx::Size(1, 1))),
          is_visible_(true) {
  helper_.reset(new ImageTransportHelper(this,
                                         manager,
                                         render_view_id,
                                         renderer_id,
                                         command_buffer_id,
                                         gfx::kNullPluginWindow));
}

PbufferImageTransportSurface::~PbufferImageTransportSurface() {
  Destroy();
}

bool PbufferImageTransportSurface::Initialize() {
  // Only support this path if the GL implementation is ANGLE.
  // IO surfaces will not work with, for example, OSMesa software renderer
  // GL contexts.
  if (gfx::GetGLImplementation() != gfx::kGLImplementationEGLGLES2)
    return false;

  if (!helper_->Initialize())
    return false;

  return GLSurfaceAdapter::Initialize();
}

void PbufferImageTransportSurface::Destroy() {
  helper_->Destroy();
  GLSurfaceAdapter::Destroy();
}

bool PbufferImageTransportSurface::IsOffscreen() {
  return false;
}

bool PbufferImageTransportSurface::SwapBuffers() {
  HANDLE surface_handle = GetShareHandle();
  if (!surface_handle)
    return false;

  helper_->DeferToFence(base::Bind(
      &PbufferImageTransportSurface::SendBuffersSwapped,
      AsWeakPtr()));

  return true;
}

bool PbufferImageTransportSurface::PostSubBuffer(
    int x, int y, int width, int height) {
  NOTREACHED();
  return false;
}

void PbufferImageTransportSurface::SetVisible(bool visible) {
  if (visible == is_visible_)
    return;

  is_visible_ = visible;

  if (visible)
    Resize(visible_size_);
  else
    Resize(gfx::Size(1, 1));
}

std::string PbufferImageTransportSurface::GetExtensions() {
  std::string extensions = gfx::GLSurface::GetExtensions();
  extensions += extensions.empty() ? "" : " ";
  extensions += "GL_CHROMIUM_front_buffer_cached";
  return extensions;
}

void PbufferImageTransportSurface::SendBuffersSwapped() {
  GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params params;
  params.surface_id = reinterpret_cast<int64>(GetShareHandle());
  params.size = GetSize();
  helper_->SendAcceleratedSurfaceBuffersSwapped(params);

  helper_->SetScheduled(false);
}

void PbufferImageTransportSurface::OnBuffersSwappedACK() {
  helper_->SetScheduled(true);
}

void PbufferImageTransportSurface::OnPostSubBufferACK() {
  NOTREACHED();
}

void PbufferImageTransportSurface::OnNewSurfaceACK(
    uint64 surface_id,
    TransportDIB::Handle shm_handle) {
  NOTREACHED();
}

void PbufferImageTransportSurface::OnResizeViewACK() {
  NOTREACHED();
}

void PbufferImageTransportSurface::OnResize(gfx::Size size) {
  if (is_visible_)
    Resize(size);

  visible_size_ = size;
}

}  // namespace anonymous

// static
scoped_refptr<gfx::GLSurface> ImageTransportSurface::CreateSurface(
    GpuChannelManager* manager,
    int32 render_view_id,
    int32 renderer_id,
    int32 command_buffer_id,
    gfx::PluginWindowHandle handle) {
  scoped_refptr<gfx::GLSurface> surface;

  base::win::OSInfo* os_info = base::win::OSInfo::GetInstance();

  if (gfx::GetGLImplementation() == gfx::kGLImplementationEGLGLES2 &&
      gfx::g_EGL_ANGLE_query_surface_pointer &&
      gfx::g_EGL_ANGLE_d3d_share_handle_client_buffer &&
      !CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kDisableImageTransportSurface)) {
    surface = new PbufferImageTransportSurface(manager,
                                               render_view_id,
                                               renderer_id,
                                               command_buffer_id);
  } else {
    surface = gfx::GLSurface::CreateViewGLSurface(false, handle);
    if (!surface.get())
      return NULL;

    surface = new PassThroughImageTransportSurface(manager,
                                                   render_view_id,
                                                   renderer_id,
                                                   command_buffer_id,
                                                   surface.get());
  }

  if (surface->Initialize())
    return surface;
  else
    return NULL;
}

#endif  // ENABLE_GPU
<commit_msg>Decide whether to use image transport surface on windows by querying EGL extensions directly.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#if defined(ENABLE_GPU)

#include "content/common/gpu/image_transport_surface.h"

#include "base/bind.h"
#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/win/windows_version.h"
#include "content/common/gpu/gpu_messages.h"
#include "content/public/common/content_switches.h"
#include "third_party/angle/include/EGL/egl.h"
#include "ui/gfx/gl/gl_bindings.h"
#include "ui/gfx/gl/gl_context.h"
#include "ui/gfx/gl/gl_implementation.h"
#include "ui/gfx/gl/gl_surface_egl.h"
#include "ui/gfx/native_widget_types.h"

namespace {

// We are backed by an Pbuffer offscreen surface through which ANGLE provides
// a handle to the corresponding render target texture through an extension.
class PbufferImageTransportSurface
    : public gfx::GLSurfaceAdapter,
      public ImageTransportSurface,
      public base::SupportsWeakPtr<PbufferImageTransportSurface> {
 public:
  PbufferImageTransportSurface(GpuChannelManager* manager,
                               int32 render_view_id,
                               int32 renderer_id,
                               int32 command_buffer_id);

  // gfx::GLSurface implementation
  virtual bool Initialize() OVERRIDE;
  virtual void Destroy() OVERRIDE;
  virtual bool IsOffscreen() OVERRIDE;
  virtual bool SwapBuffers() OVERRIDE;
  virtual bool PostSubBuffer(int x, int y, int width, int height) OVERRIDE;
  virtual std::string GetExtensions() OVERRIDE;
  virtual void SetVisible(bool visible) OVERRIDE;

 protected:
  // ImageTransportSurface implementation
  virtual void OnNewSurfaceACK(uint64 surface_id,
                               TransportDIB::Handle shm_handle) OVERRIDE;
  virtual void OnBuffersSwappedACK() OVERRIDE;
  virtual void OnPostSubBufferACK() OVERRIDE;
  virtual void OnResizeViewACK() OVERRIDE;
  virtual void OnResize(gfx::Size size) OVERRIDE;

 private:
  virtual ~PbufferImageTransportSurface();
  void SendBuffersSwapped();

  // Whether the surface is currently visible.
  bool is_visible_;

  // Size to resize to when the surface becomes visible.
  gfx::Size visible_size_;

  scoped_ptr<ImageTransportHelper> helper_;

  DISALLOW_COPY_AND_ASSIGN(PbufferImageTransportSurface);
};

PbufferImageTransportSurface::PbufferImageTransportSurface(
    GpuChannelManager* manager,
    int32 render_view_id,
    int32 renderer_id,
    int32 command_buffer_id)
        : GLSurfaceAdapter(new gfx::PbufferGLSurfaceEGL(false,
                                                        gfx::Size(1, 1))),
          is_visible_(true) {
  helper_.reset(new ImageTransportHelper(this,
                                         manager,
                                         render_view_id,
                                         renderer_id,
                                         command_buffer_id,
                                         gfx::kNullPluginWindow));
}

PbufferImageTransportSurface::~PbufferImageTransportSurface() {
  Destroy();
}

bool PbufferImageTransportSurface::Initialize() {
  // Only support this path if the GL implementation is ANGLE.
  // IO surfaces will not work with, for example, OSMesa software renderer
  // GL contexts.
  if (gfx::GetGLImplementation() != gfx::kGLImplementationEGLGLES2)
    return false;

  if (!helper_->Initialize())
    return false;

  return GLSurfaceAdapter::Initialize();
}

void PbufferImageTransportSurface::Destroy() {
  helper_->Destroy();
  GLSurfaceAdapter::Destroy();
}

bool PbufferImageTransportSurface::IsOffscreen() {
  return false;
}

bool PbufferImageTransportSurface::SwapBuffers() {
  HANDLE surface_handle = GetShareHandle();
  if (!surface_handle)
    return false;

  helper_->DeferToFence(base::Bind(
      &PbufferImageTransportSurface::SendBuffersSwapped,
      AsWeakPtr()));

  return true;
}

bool PbufferImageTransportSurface::PostSubBuffer(
    int x, int y, int width, int height) {
  NOTREACHED();
  return false;
}

void PbufferImageTransportSurface::SetVisible(bool visible) {
  if (visible == is_visible_)
    return;

  is_visible_ = visible;

  if (visible)
    Resize(visible_size_);
  else
    Resize(gfx::Size(1, 1));
}

std::string PbufferImageTransportSurface::GetExtensions() {
  std::string extensions = gfx::GLSurface::GetExtensions();
  extensions += extensions.empty() ? "" : " ";
  extensions += "GL_CHROMIUM_front_buffer_cached";
  return extensions;
}

void PbufferImageTransportSurface::SendBuffersSwapped() {
  GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params params;
  params.surface_id = reinterpret_cast<int64>(GetShareHandle());
  params.size = GetSize();
  helper_->SendAcceleratedSurfaceBuffersSwapped(params);

  helper_->SetScheduled(false);
}

void PbufferImageTransportSurface::OnBuffersSwappedACK() {
  helper_->SetScheduled(true);
}

void PbufferImageTransportSurface::OnPostSubBufferACK() {
  NOTREACHED();
}

void PbufferImageTransportSurface::OnNewSurfaceACK(
    uint64 surface_id,
    TransportDIB::Handle shm_handle) {
  NOTREACHED();
}

void PbufferImageTransportSurface::OnResizeViewACK() {
  NOTREACHED();
}

void PbufferImageTransportSurface::OnResize(gfx::Size size) {
  if (is_visible_)
    Resize(size);

  visible_size_ = size;
}

}  // namespace anonymous

// static
scoped_refptr<gfx::GLSurface> ImageTransportSurface::CreateSurface(
    GpuChannelManager* manager,
    int32 render_view_id,
    int32 renderer_id,
    int32 command_buffer_id,
    gfx::PluginWindowHandle handle) {
  scoped_refptr<gfx::GLSurface> surface;
  base::win::OSInfo* os_info = base::win::OSInfo::GetInstance();

  if (gfx::GetGLImplementation() == gfx::kGLImplementationEGLGLES2 &&
      !CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kDisableImageTransportSurface)) {
    const char* extensions = eglQueryString(eglGetDisplay(EGL_DEFAULT_DISPLAY),
                                            EGL_EXTENSIONS);
    if (strstr(extensions, "EGL_ANGLE_query_surface_pointer") &&
        strstr(extensions, "EGL_ANGLE_surface_d3d_texture_2d_share_handle")) {
      surface = new PbufferImageTransportSurface(manager,
                                                 render_view_id,
                                                 renderer_id,
                                                 command_buffer_id);
    }
  }

  if (!surface.get()) {
    surface = gfx::GLSurface::CreateViewGLSurface(false, handle);
    if (!surface.get())
      return NULL;

    surface = new PassThroughImageTransportSurface(manager,
                                                   render_view_id,
                                                   renderer_id,
                                                   command_buffer_id,
                                                   surface.get());
  }

  if (surface->Initialize())
    return surface;
  else
    return NULL;
}

#endif  // ENABLE_GPU
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: SchXMLParagraphContext.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: rt $ $Date: 2008-03-12 10:26:27 $
 *
 *  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_xmloff.hxx"

#include "SchXMLImport.hxx"
#include "SchXMLParagraphContext.hxx"

#include "xmlnmspe.hxx"
#include <xmloff/xmltoken.hxx>
#include <xmloff/nmspmap.hxx>

using ::rtl::OUString;
using namespace com::sun::star;
using namespace ::xmloff::token;

SchXMLParagraphContext::SchXMLParagraphContext( SvXMLImport& rImport,
                                                const OUString& rLocalName,
                                                OUString& rText,
                                                OUString * pOutId /* = 0 */ ) :
        SvXMLImportContext( rImport, XML_NAMESPACE_TEXT, rLocalName ),
        mrText( rText ),
        mpId( pOutId )
{
}

SchXMLParagraphContext::~SchXMLParagraphContext()
{}

void SchXMLParagraphContext::StartElement( const uno::Reference< xml::sax::XAttributeList >& xAttrList )
{
    // remember the id. It is used for storing the original cell range string in
    // a local table (cached data)
    if( mpId )
    {
        sal_Int16 nAttrCount = xAttrList.is()? xAttrList->getLength(): 0;
        rtl::OUString aValue;

        for( sal_Int16 i = 0; i < nAttrCount; i++ )
        {
            rtl::OUString sAttrName = xAttrList->getNameByIndex( i );
            rtl::OUString aLocalName;
            USHORT nPrefix = GetImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName );

            if( nPrefix == XML_NAMESPACE_TEXT &&
                IsXMLToken( aLocalName, XML_ID ) )
            {
                (*mpId) = xAttrList->getValueByIndex( i );
                break;   // we only need this attribute
            }
        }
    }
}

void SchXMLParagraphContext::EndElement()
{
    mrText = maBuffer.makeStringAndClear();
}

SvXMLImportContext* SchXMLParagraphContext::CreateChildContext(
    USHORT nPrefix,
    const OUString& rLocalName,
    const uno::Reference< xml::sax::XAttributeList >& )
{
    if( nPrefix == XML_NAMESPACE_TEXT )
    {
        if( rLocalName.equals( ::xmloff::token::GetXMLToken( ::xmloff::token::XML_TAB_STOP )))
        {
            maBuffer.append( sal_Unicode( 0x0009 ));  // tabulator
        }
        else if( rLocalName.equals( ::xmloff::token::GetXMLToken( ::xmloff::token::XML_LINE_BREAK )))
        {
            maBuffer.append( sal_Unicode( 0x000A ));  // linefeed
        }
    }

    return new SvXMLImportContext( GetImport(), nPrefix, rLocalName );
}

void SchXMLParagraphContext::Characters( const OUString& rChars )
{
    maBuffer.append( rChars );
}
<commit_msg>INTEGRATION: CWS changefileheader (1.8.18); FILE MERGED 2008/03/31 16:28:00 rt 1.8.18.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: SchXMLParagraphContext.cxx,v $
 * $Revision: 1.9 $
 *
 * 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_xmloff.hxx"

#include "SchXMLImport.hxx"
#include "SchXMLParagraphContext.hxx"

#include "xmlnmspe.hxx"
#include <xmloff/xmltoken.hxx>
#include <xmloff/nmspmap.hxx>

using ::rtl::OUString;
using namespace com::sun::star;
using namespace ::xmloff::token;

SchXMLParagraphContext::SchXMLParagraphContext( SvXMLImport& rImport,
                                                const OUString& rLocalName,
                                                OUString& rText,
                                                OUString * pOutId /* = 0 */ ) :
        SvXMLImportContext( rImport, XML_NAMESPACE_TEXT, rLocalName ),
        mrText( rText ),
        mpId( pOutId )
{
}

SchXMLParagraphContext::~SchXMLParagraphContext()
{}

void SchXMLParagraphContext::StartElement( const uno::Reference< xml::sax::XAttributeList >& xAttrList )
{
    // remember the id. It is used for storing the original cell range string in
    // a local table (cached data)
    if( mpId )
    {
        sal_Int16 nAttrCount = xAttrList.is()? xAttrList->getLength(): 0;
        rtl::OUString aValue;

        for( sal_Int16 i = 0; i < nAttrCount; i++ )
        {
            rtl::OUString sAttrName = xAttrList->getNameByIndex( i );
            rtl::OUString aLocalName;
            USHORT nPrefix = GetImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName );

            if( nPrefix == XML_NAMESPACE_TEXT &&
                IsXMLToken( aLocalName, XML_ID ) )
            {
                (*mpId) = xAttrList->getValueByIndex( i );
                break;   // we only need this attribute
            }
        }
    }
}

void SchXMLParagraphContext::EndElement()
{
    mrText = maBuffer.makeStringAndClear();
}

SvXMLImportContext* SchXMLParagraphContext::CreateChildContext(
    USHORT nPrefix,
    const OUString& rLocalName,
    const uno::Reference< xml::sax::XAttributeList >& )
{
    if( nPrefix == XML_NAMESPACE_TEXT )
    {
        if( rLocalName.equals( ::xmloff::token::GetXMLToken( ::xmloff::token::XML_TAB_STOP )))
        {
            maBuffer.append( sal_Unicode( 0x0009 ));  // tabulator
        }
        else if( rLocalName.equals( ::xmloff::token::GetXMLToken( ::xmloff::token::XML_LINE_BREAK )))
        {
            maBuffer.append( sal_Unicode( 0x000A ));  // linefeed
        }
    }

    return new SvXMLImportContext( GetImport(), nPrefix, rLocalName );
}

void SchXMLParagraphContext::Characters( const OUString& rChars )
{
    maBuffer.append( rChars );
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: XMLSectionImportContext.hxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 15:17:48 $
 *
 *  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
 *
 ************************************************************************/

#ifndef _XMLOFF_XMLSECTIONIMPORTCONTEXT_HXX_
#define _XMLOFF_XMLSECTIONIMPORTCONTEXT_HXX_

#ifndef _XMLOFF_XMLICTXT_HXX
#include "xmlictxt.hxx"
#endif

#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif

#ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_
#include <com/sun/star/uno/Sequence.h>
#endif

namespace com { namespace sun { namespace star {
    namespace text { class XTextRange;  }
    namespace beans { class XPropertySet; }
    namespace xml { namespace sax { class XAttributeList; } }
} } }
namespace rtl { class OUString; }
class XMLTextImportHelper;

/**
 * Import text sections.
 *
 * This context may *also* be used for index header sections. The
 * differentiates its behaviour based on GetLocalName().
 */
class XMLSectionImportContext : public SvXMLImportContext
{
    /// start position; ranges aquired via getStart(),getEnd() don't move
    ::com::sun::star::uno::Reference<
        ::com::sun::star::text::XTextRange> xStartRange;

    /// end position
    ::com::sun::star::uno::Reference<
        ::com::sun::star::text::XTextRange> xEndRange;

    /// TextSection (as XPropertySet) for passing down to data source elements
    ::com::sun::star::uno::Reference<
        ::com::sun::star::beans::XPropertySet> xSectionPropertySet;

    const ::rtl::OUString sTextSection;
    const ::rtl::OUString sIndexHeaderSection;
    const ::rtl::OUString sCondition;
    const ::rtl::OUString sIsVisible;
    const ::rtl::OUString sProtectionKey;
    const ::rtl::OUString sIsProtected;
    const ::rtl::OUString sIsCurrentlyVisible;
    const ::rtl::OUString sEmpty;

    ::rtl::OUString sStyleName;
    ::rtl::OUString sName;
    ::rtl::OUString sCond;
    ::com::sun::star::uno::Sequence<sal_Int8> aSequence;
    sal_Bool bProtect;
    sal_Bool bCondOK;
    sal_Bool bIsVisible;
    sal_Bool bValid;
    sal_Bool bSequenceOK;
    sal_Bool bIsCurrentlyVisible;
    sal_Bool bIsCurrentlyVisibleOK;

    sal_Bool bHasContent;

public:

    TYPEINFO();

    XMLSectionImportContext(
        SvXMLImport& rImport,
        sal_uInt16 nPrfx,
        const ::rtl::OUString& rLocalName );

    ~XMLSectionImportContext();

protected:

    virtual void StartElement(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::xml::sax::XAttributeList> & xAttrList);

    virtual void EndElement();

    virtual SvXMLImportContext *CreateChildContext(
        sal_uInt16 nPrefix,
        const ::rtl::OUString& rLocalName,
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::xml::sax::XAttributeList> & xAttrList );

    void ProcessAttributes(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::xml::sax::XAttributeList> & xAttrList );
};

#endif
<commit_msg>INTEGRATION: CWS vgbugs07 (1.10.274); FILE MERGED 2007/06/04 13:23:38 vg 1.10.274.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: XMLSectionImportContext.hxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 16:05:45 $
 *
 *  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
 *
 ************************************************************************/

#ifndef _XMLOFF_XMLSECTIONIMPORTCONTEXT_HXX_
#define _XMLOFF_XMLSECTIONIMPORTCONTEXT_HXX_

#ifndef _XMLOFF_XMLICTXT_HXX
#include <xmloff/xmlictxt.hxx>
#endif

#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif

#ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_
#include <com/sun/star/uno/Sequence.h>
#endif

namespace com { namespace sun { namespace star {
    namespace text { class XTextRange;  }
    namespace beans { class XPropertySet; }
    namespace xml { namespace sax { class XAttributeList; } }
} } }
namespace rtl { class OUString; }
class XMLTextImportHelper;

/**
 * Import text sections.
 *
 * This context may *also* be used for index header sections. The
 * differentiates its behaviour based on GetLocalName().
 */
class XMLSectionImportContext : public SvXMLImportContext
{
    /// start position; ranges aquired via getStart(),getEnd() don't move
    ::com::sun::star::uno::Reference<
        ::com::sun::star::text::XTextRange> xStartRange;

    /// end position
    ::com::sun::star::uno::Reference<
        ::com::sun::star::text::XTextRange> xEndRange;

    /// TextSection (as XPropertySet) for passing down to data source elements
    ::com::sun::star::uno::Reference<
        ::com::sun::star::beans::XPropertySet> xSectionPropertySet;

    const ::rtl::OUString sTextSection;
    const ::rtl::OUString sIndexHeaderSection;
    const ::rtl::OUString sCondition;
    const ::rtl::OUString sIsVisible;
    const ::rtl::OUString sProtectionKey;
    const ::rtl::OUString sIsProtected;
    const ::rtl::OUString sIsCurrentlyVisible;
    const ::rtl::OUString sEmpty;

    ::rtl::OUString sStyleName;
    ::rtl::OUString sName;
    ::rtl::OUString sCond;
    ::com::sun::star::uno::Sequence<sal_Int8> aSequence;
    sal_Bool bProtect;
    sal_Bool bCondOK;
    sal_Bool bIsVisible;
    sal_Bool bValid;
    sal_Bool bSequenceOK;
    sal_Bool bIsCurrentlyVisible;
    sal_Bool bIsCurrentlyVisibleOK;

    sal_Bool bHasContent;

public:

    TYPEINFO();

    XMLSectionImportContext(
        SvXMLImport& rImport,
        sal_uInt16 nPrfx,
        const ::rtl::OUString& rLocalName );

    ~XMLSectionImportContext();

protected:

    virtual void StartElement(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::xml::sax::XAttributeList> & xAttrList);

    virtual void EndElement();

    virtual SvXMLImportContext *CreateChildContext(
        sal_uInt16 nPrefix,
        const ::rtl::OUString& rLocalName,
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::xml::sax::XAttributeList> & xAttrList );

    void ProcessAttributes(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::xml::sax::XAttributeList> & xAttrList );
};

#endif
<|endoftext|>


<commit_before>// Ouzel by Elviss Strazdins

#ifndef OUZEL_AUDIO_ALCERRORCATEGORY_HPP
#define OUZEL_AUDIO_ALCERRORCATEGORY_HPP

#include "../../core/Setup.h"

#if OUZEL_COMPILE_OPENAL

#include <system_error>
#ifdef __APPLE__
#  include <OpenAl/alc.h>
#else
#  include <AL/alc.h>
#endif

namespace ouzel::audio::alc
{
    class ErrorCategory final: public std::error_category
        {
        public:
            const char* name() const noexcept override
            {
                return "ALC";
            }

            std::string message(const int condition) const override
            {
                switch (condition)
                {
                    case ALC_INVALID_DEVICE: return "ALC_INVALID_DEVICE";
                    case ALC_INVALID_CONTEXT: return "ALC_INVALID_CONTEXT";
                    case ALC_INVALID_ENUM: return "ALC_INVALID_ENUM";
                    case ALC_INVALID_VALUE: return "ALC_INVALID_VALUE";
                    case ALC_OUT_OF_MEMORY: return "ALC_OUT_OF_MEMORY";
                    default: return "Unknown error (" + std::to_string(condition) + ")";
                }
            }
        };
}
#endif

#endif // OUZEL_AUDIO_ALCERRORCATEGORY_HPP
<commit_msg>Fix tabbing<commit_after>// Ouzel by Elviss Strazdins

#ifndef OUZEL_AUDIO_ALCERRORCATEGORY_HPP
#define OUZEL_AUDIO_ALCERRORCATEGORY_HPP

#include "../../core/Setup.h"

#if OUZEL_COMPILE_OPENAL

#include <system_error>
#ifdef __APPLE__
#  include <OpenAl/alc.h>
#else
#  include <AL/alc.h>
#endif

namespace ouzel::audio::alc
{
    class ErrorCategory final: public std::error_category
    {
    public:
        const char* name() const noexcept override
        {
            return "ALC";
        }

        std::string message(const int condition) const override
        {
            switch (condition)
            {
                case ALC_INVALID_DEVICE: return "ALC_INVALID_DEVICE";
                case ALC_INVALID_CONTEXT: return "ALC_INVALID_CONTEXT";
                case ALC_INVALID_ENUM: return "ALC_INVALID_ENUM";
                case ALC_INVALID_VALUE: return "ALC_INVALID_VALUE";
                case ALC_OUT_OF_MEMORY: return "ALC_OUT_OF_MEMORY";
                default: return "Unknown error (" + std::to_string(condition) + ")";
            }
        }
    };
}
#endif

#endif // OUZEL_AUDIO_ALCERRORCATEGORY_HPP
<|endoftext|>


<commit_before>/* Copyright (c) 2017-2020 Hans-Kristian Arntzen
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#pragma once

#include <vector>
#include <list>
#include <type_traits>
#include <stdexcept>
#include "command_buffer.hpp"
#include "hash.hpp"
#include "enum_cast.hpp"
#include "intrusive_hash_map.hpp"
#include "math.hpp"

namespace Granite
{
class ShaderSuite;
class RenderContext;
class AbstractRenderable;
class PositionalLight;
struct VolumetricDiffuseLightComponent;
struct RenderInfoComponent;

struct RenderableInfo
{
	const AbstractRenderable *renderable;
	const RenderInfoComponent *transform;
	Util::Hash transform_hash;
};

struct PositionalLightInfo
{
	PositionalLight *light;
	const RenderInfoComponent *transform;
	Util::Hash transform_hash;
};
using VisibilityList = std::vector<RenderableInfo>;
using PositionalLightList = std::vector<PositionalLightInfo>;

struct VolumetricDiffuseLightInfo
{
	VolumetricDiffuseLightComponent *light;
	const RenderInfoComponent *transform;
};
using VolumetricDiffuseLightList = std::vector<VolumetricDiffuseLightInfo>;

enum class Queue : unsigned
{
	Opaque = 0,
	OpaqueEmissive,
	Light, // Relevant only for classic deferred rendering
	Transparent,
	Count
};

enum class StaticLayer : unsigned
{
	Front,
	Default,
	Back,
	Last,
	Count
};

struct RenderInfo
{
	static uint64_t get_sort_key(const RenderContext &context, Queue queue_type,
	                             Util::Hash pipeline_hash, Util::Hash draw_hash,
	                             const vec3 &center,
	                             StaticLayer layer = StaticLayer::Default);
	static uint64_t get_sprite_sort_key(Queue queue_type,
	                                    Util::Hash pipeline_hash, Util::Hash draw_hash,
	                                    float layer, StaticLayer static_layer = StaticLayer::Default);
	static uint64_t get_background_sort_key(Queue queue_type, Util::Hash pipeline_hash, Util::Hash draw_hash);

private:
	RenderInfo() = default;
};

struct RenderQueueData;
using RenderFunc = void (*)(Vulkan::CommandBuffer &, const RenderQueueData *, unsigned);

struct RenderQueueData
{
	// How to render an object.
	RenderFunc render;

	// Per-draw call specific data. Understood by the render callback.
	const void *render_info;

	// Per-instance specific data. Understood by the render callback.
	const void *instance_data;

	// Sorting key.
	// Lower sorting keys will appear earlier.
	uint64_t sorting_key;
};

struct QueueDataWrappedErased : Util::IntrusiveHashMapEnabled<QueueDataWrappedErased>
{
};

template <typename T>
struct QueueDataWrapped : QueueDataWrappedErased
{
	T data;
};

class RenderQueue
{
public:
	enum { BlockSize = 64 * 1024 };

	RenderQueue() = default;
	void operator=(const RenderQueue &) = delete;
	RenderQueue(const RenderQueue &) = delete;
	~RenderQueue();

	template <typename T>
	T *push(Queue queue, Util::Hash instance_key, uint64_t sorting_key,
	        RenderFunc render, void *instance_data)
	{
		static_assert(std::is_trivially_destructible<T>::value, "Dispatchable type is not trivially destructible!");

		assert(instance_key != 0);
		assert(sorting_key != 0);

		Util::Hasher h(instance_key);
		h.pointer(render);

		using WrappedT = QueueDataWrapped<T>;

		auto *itr = render_infos.find(h.get());
		if (itr)
		{
			auto *t = static_cast<WrappedT *>(itr);
			enqueue_queue_data(queue, { render, &t->data, instance_data, sorting_key });
			return nullptr;
		}
		else
		{
			void *buffer = allocate(sizeof(WrappedT), alignof(WrappedT));
			if (!buffer)
				throw std::bad_alloc();

			auto *t = new(buffer) WrappedT();
			t->set_hash(h.get());
			render_infos.insert_replace(t);
			enqueue_queue_data(queue, { render, &t->data, instance_data, sorting_key });
			return &t->data;
		}
	}

	void *allocate(size_t size, size_t alignment = 64);

	template <typename T>
	T *allocate_one()
	{
		static_assert(std::is_trivially_destructible<T>::value, "Type is not trivially destructible!");
		return static_cast<T *>(allocate(sizeof(T), alignof(T)));
	}

	template <typename T>
	T *allocate_many(size_t n)
	{
		static_assert(std::is_trivially_destructible<T>::value, "Type is not trivially destructible!");
		return static_cast<T *>(allocate(sizeof(T) * n, alignof(T)));
	}

	void combine_render_info(const RenderQueue &queue);
	void reset();

	using RenderQueueDataVector = Util::SmallVector<RenderQueueData, 64>;

	const RenderQueueDataVector &get_queue_data(Queue queue) const
	{
		return queues[Util::ecast(queue)];
	}

	void sort();
	void dispatch(Queue queue, Vulkan::CommandBuffer &cmd, const Vulkan::CommandBufferSavedState *state) const;
	void dispatch_range(Queue queue, Vulkan::CommandBuffer &cmd, const Vulkan::CommandBufferSavedState *state, size_t begin, size_t end) const;
	void dispatch_subset(Queue queue, Vulkan::CommandBuffer &cmd, const Vulkan::CommandBufferSavedState *state, unsigned index, unsigned num_indices) const;
	size_t get_dispatch_size(Queue queue) const;

	void set_shader_suites(ShaderSuite *suite)
	{
		shader_suites = suite;
	}

	ShaderSuite *get_shader_suites() const
	{
		return shader_suites;
	}

	void push_renderables(const RenderContext &context, const RenderableInfo *visible, size_t count);
	void push_depth_renderables(const RenderContext &context, const RenderableInfo *visible, size_t count);

private:
	void enqueue_queue_data(Queue queue, const RenderQueueData &data);

	struct Block : Util::IntrusivePtrEnabled<Block>
	{
		std::unique_ptr<uint8_t[]> large_buffer;
		uintptr_t ptr = 0;
		uintptr_t begin = 0;
		uintptr_t end = 0;
		uint8_t inline_buffer[BlockSize];

		explicit Block(size_t size)
		{
			large_buffer.reset(new uint8_t[size]);
			begin = reinterpret_cast<uintptr_t>(large_buffer.get());
			end = reinterpret_cast<uintptr_t>(large_buffer.get()) + size;
			reset();
		}

		Block()
		{
			begin = reinterpret_cast<uintptr_t>(inline_buffer);
			end = reinterpret_cast<uintptr_t>(inline_buffer) + BlockSize;
			reset();
		}

		void operator=(const Block &) = delete;
		Block(const Block &) = delete;

		void reset()
		{
			ptr = begin;
		}
	};

	static Util::ThreadSafeObjectPool<Block> allocator_pool;

	static void *allocate_from_block(Block &block, size_t size, size_t alignment);
	Block *insert_block();
	Block *insert_large_block(size_t size, size_t alignment);

	RenderQueueDataVector queues[static_cast<unsigned>(Queue::Count)];
	Util::SmallVector<Block *, 64> blocks;
	Block *current = nullptr;

	ShaderSuite *shader_suites = nullptr;
	Util::IntrusiveHashMapHolder<QueueDataWrappedErased> render_infos;
	void recycle_blocks();
};
}
<commit_msg>Default construct RenderQueue::allocate<T>.<commit_after>/* Copyright (c) 2017-2020 Hans-Kristian Arntzen
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#pragma once

#include <vector>
#include <list>
#include <type_traits>
#include <stdexcept>
#include "command_buffer.hpp"
#include "hash.hpp"
#include "enum_cast.hpp"
#include "intrusive_hash_map.hpp"
#include "math.hpp"

namespace Granite
{
class ShaderSuite;
class RenderContext;
class AbstractRenderable;
class PositionalLight;
struct VolumetricDiffuseLightComponent;
struct RenderInfoComponent;

struct RenderableInfo
{
	const AbstractRenderable *renderable;
	const RenderInfoComponent *transform;
	Util::Hash transform_hash;
};

struct PositionalLightInfo
{
	PositionalLight *light;
	const RenderInfoComponent *transform;
	Util::Hash transform_hash;
};
using VisibilityList = std::vector<RenderableInfo>;
using PositionalLightList = std::vector<PositionalLightInfo>;

struct VolumetricDiffuseLightInfo
{
	VolumetricDiffuseLightComponent *light;
	const RenderInfoComponent *transform;
};
using VolumetricDiffuseLightList = std::vector<VolumetricDiffuseLightInfo>;

enum class Queue : unsigned
{
	Opaque = 0,
	OpaqueEmissive,
	Light, // Relevant only for classic deferred rendering
	Transparent,
	Count
};

enum class StaticLayer : unsigned
{
	Front,
	Default,
	Back,
	Last,
	Count
};

struct RenderInfo
{
	static uint64_t get_sort_key(const RenderContext &context, Queue queue_type,
	                             Util::Hash pipeline_hash, Util::Hash draw_hash,
	                             const vec3 &center,
	                             StaticLayer layer = StaticLayer::Default);
	static uint64_t get_sprite_sort_key(Queue queue_type,
	                                    Util::Hash pipeline_hash, Util::Hash draw_hash,
	                                    float layer, StaticLayer static_layer = StaticLayer::Default);
	static uint64_t get_background_sort_key(Queue queue_type, Util::Hash pipeline_hash, Util::Hash draw_hash);

private:
	RenderInfo() = default;
};

struct RenderQueueData;
using RenderFunc = void (*)(Vulkan::CommandBuffer &, const RenderQueueData *, unsigned);

struct RenderQueueData
{
	// How to render an object.
	RenderFunc render;

	// Per-draw call specific data. Understood by the render callback.
	const void *render_info;

	// Per-instance specific data. Understood by the render callback.
	const void *instance_data;

	// Sorting key.
	// Lower sorting keys will appear earlier.
	uint64_t sorting_key;
};

struct QueueDataWrappedErased : Util::IntrusiveHashMapEnabled<QueueDataWrappedErased>
{
};

template <typename T>
struct QueueDataWrapped : QueueDataWrappedErased
{
	T data;
};

class RenderQueue
{
public:
	enum { BlockSize = 64 * 1024 };

	RenderQueue() = default;
	void operator=(const RenderQueue &) = delete;
	RenderQueue(const RenderQueue &) = delete;
	~RenderQueue();

	template <typename T>
	T *push(Queue queue, Util::Hash instance_key, uint64_t sorting_key,
	        RenderFunc render, void *instance_data)
	{
		static_assert(std::is_trivially_destructible<T>::value, "Dispatchable type is not trivially destructible!");

		assert(instance_key != 0);
		assert(sorting_key != 0);

		Util::Hasher h(instance_key);
		h.pointer(render);

		using WrappedT = QueueDataWrapped<T>;

		auto *itr = render_infos.find(h.get());
		if (itr)
		{
			auto *t = static_cast<WrappedT *>(itr);
			enqueue_queue_data(queue, { render, &t->data, instance_data, sorting_key });
			return nullptr;
		}
		else
		{
			void *buffer = allocate(sizeof(WrappedT), alignof(WrappedT));
			if (!buffer)
				throw std::bad_alloc();

			auto *t = new(buffer) WrappedT();
			t->set_hash(h.get());
			render_infos.insert_replace(t);
			enqueue_queue_data(queue, { render, &t->data, instance_data, sorting_key });
			return &t->data;
		}
	}

	void *allocate(size_t size, size_t alignment = 64);

	template <typename T>
	T *allocate_one()
	{
		static_assert(std::is_trivially_destructible<T>::value, "Type is not trivially destructible!");
		auto *t = static_cast<T *>(allocate(sizeof(T), alignof(T)));
		if (t)
			new (t) T();
		return t;
	}

	template <typename T>
	T *allocate_many(size_t n)
	{
		static_assert(std::is_trivially_destructible<T>::value, "Type is not trivially destructible!");
		auto *t = static_cast<T *>(allocate(sizeof(T) * n, alignof(T)));
		if (t)
			for (size_t i = 0; i < n; i++)
				new (&t[i]) T();
		return t;
	}

	void combine_render_info(const RenderQueue &queue);
	void reset();

	using RenderQueueDataVector = Util::SmallVector<RenderQueueData, 64>;

	const RenderQueueDataVector &get_queue_data(Queue queue) const
	{
		return queues[Util::ecast(queue)];
	}

	void sort();
	void dispatch(Queue queue, Vulkan::CommandBuffer &cmd, const Vulkan::CommandBufferSavedState *state) const;
	void dispatch_range(Queue queue, Vulkan::CommandBuffer &cmd, const Vulkan::CommandBufferSavedState *state, size_t begin, size_t end) const;
	void dispatch_subset(Queue queue, Vulkan::CommandBuffer &cmd, const Vulkan::CommandBufferSavedState *state, unsigned index, unsigned num_indices) const;
	size_t get_dispatch_size(Queue queue) const;

	void set_shader_suites(ShaderSuite *suite)
	{
		shader_suites = suite;
	}

	ShaderSuite *get_shader_suites() const
	{
		return shader_suites;
	}

	void push_renderables(const RenderContext &context, const RenderableInfo *visible, size_t count);
	void push_depth_renderables(const RenderContext &context, const RenderableInfo *visible, size_t count);

private:
	void enqueue_queue_data(Queue queue, const RenderQueueData &data);

	struct Block : Util::IntrusivePtrEnabled<Block>
	{
		std::unique_ptr<uint8_t[]> large_buffer;
		uintptr_t ptr = 0;
		uintptr_t begin = 0;
		uintptr_t end = 0;
		uint8_t inline_buffer[BlockSize];

		explicit Block(size_t size)
		{
			large_buffer.reset(new uint8_t[size]);
			begin = reinterpret_cast<uintptr_t>(large_buffer.get());
			end = reinterpret_cast<uintptr_t>(large_buffer.get()) + size;
			reset();
		}

		Block()
		{
			begin = reinterpret_cast<uintptr_t>(inline_buffer);
			end = reinterpret_cast<uintptr_t>(inline_buffer) + BlockSize;
			reset();
		}

		void operator=(const Block &) = delete;
		Block(const Block &) = delete;

		void reset()
		{
			ptr = begin;
		}
	};

	static Util::ThreadSafeObjectPool<Block> allocator_pool;

	static void *allocate_from_block(Block &block, size_t size, size_t alignment);
	Block *insert_block();
	Block *insert_large_block(size_t size, size_t alignment);

	RenderQueueDataVector queues[static_cast<unsigned>(Queue::Count)];
	Util::SmallVector<Block *, 64> blocks;
	Block *current = nullptr;

	ShaderSuite *shader_suites = nullptr;
	Util::IntrusiveHashMapHolder<QueueDataWrappedErased> render_infos;
	void recycle_blocks();
};
}
<|endoftext|>


<commit_before>#include "stdafx.h"
#include "lua.h"
#include "Event.h"
#include "Logs.h"
#include "MemCell.h"
#include "Driver.h"
#include "lua_ffi.h"
#include "simulation.h"

lua::lua()
{
    state = luaL_newstate();
    if (!state)
        throw std::runtime_error("cannot create lua state");
    lua_atpanic(state, atpanic);
    luaL_openlibs(state);

    lua_getglobal(state, "package");
    lua_pushstring(state, "preload");
    lua_gettable(state, -2);
    lua_pushcclosure(state, openffi, 0);
    lua_setfield(state, -2, "eu07.events");
    lua_settop(state, 0);
}

lua::~lua()
{
    lua_close(state);
    state = nullptr;
}

void lua::interpret(std::string file)
{
    if (luaL_dofile(state, file.c_str()))
        throw std::runtime_error(lua_tostring(state, -1));
}

// NOTE: we cannot throw exceptions in callbacks
// because it is not supported by LuaJIT on x86 windows

int lua::atpanic(lua_State *s)
{
	std::string err(lua_tostring(s, -1));
    ErrorLog(err);
#ifdef _WIN32
        MessageBox(NULL, err.c_str(), "MaSzyna", MB_OK);
#endif
    return 0;
}

int lua::openffi(lua_State *s)
{
    if (luaL_dostring(s, lua_ffi))
    {
        ErrorLog(std::string(lua_tostring(s, -1)));
        return 0;
    }
    return 1;
}

#ifdef _WIN32
#define EXPORT __declspec(dllexport)
#else
#define EXPORT
#endif

extern "C"
{
    EXPORT basic_event* scriptapi_event_create(const char* name, double delay, double randomdelay, lua::eventhandler_t handler)
    {
        basic_event *event = new lua_event(handler);
        event->m_name = std::string(name);
        event->m_delay = delay;
        event->m_delayrandom = randomdelay;

		if (simulation::Events.insert(event))
			return event;
		else
			return nullptr;
    }

    EXPORT basic_event* scriptapi_event_find(const char* name)
    {
        std::string str(name);
        basic_event *e = simulation::Events.FindEvent(str);
        if (e)
            return e;
        else
            WriteLog("lua: missing event: " + str);
        return nullptr;
    }

    EXPORT TTrack* scriptapi_track_find(const char* name)
    {
        std::string str(name);
		TTrack *track = simulation::Paths.find(str);
        if (track)
            return track;
        else
            WriteLog("lua: missing track: " + str);
        return nullptr;
    }

    EXPORT bool scriptapi_track_isoccupied(TTrack* track)
    {
        if (track)
            return !track->IsEmpty();
        return false;
    }

	EXPORT TIsolated* scriptapi_isolated_find(const char* name)
	{
		std::string str(name);
        TIsolated *isolated = TIsolated::Find(name);
		if (isolated)
			return isolated;
		else
			WriteLog("lua: missing isolated: " + str);
		return nullptr;
	}

	EXPORT bool scriptapi_isolated_isoccupied(TIsolated* isolated)
	{
		if (isolated)
			return isolated->Busy();
		return false;
	}

    EXPORT const char* scriptapi_event_getname(basic_event *e)
    {
        if (e)
            return e->m_name.c_str();
        return nullptr;
    }

    EXPORT const char* scriptapi_train_getname(TDynamicObject *dyn)
    {
        if (dyn && dyn->Mechanik)
            return dyn->Mechanik->TrainName().c_str();
        return nullptr;
    }

    EXPORT void scriptapi_event_dispatch(basic_event *e, TDynamicObject *activator, double delay)
    {
        if (e)
            simulation::Events.AddToQuery(e, activator, delay);
    }

    EXPORT double scriptapi_random(double a, double b)
    {
        return Random(a, b);
    }

    EXPORT void scriptapi_writelog(const char* txt)
    {
        WriteLog("lua: log: " + std::string(txt), logtype::lua);
    }

    EXPORT void scriptapi_writeerrorlog(const char* txt)
    {
        ErrorLog("lua: log: " + std::string(txt), logtype::lua);
    }

    struct memcell_values { const char *str; double num1; double num2; };

    EXPORT TMemCell* scriptapi_memcell_find(const char *name)
    {
        std::string str(name);
        TMemCell *mc = simulation::Memory.find(str);
        if (mc)
            return mc;
        else
            WriteLog("lua: missing memcell: " + str);
        return nullptr;
    }

    EXPORT memcell_values scriptapi_memcell_read(TMemCell *mc)
    {
        if (!mc)
            return { nullptr, 0.0, 0.0 };
        return { mc->Text().c_str(), mc->Value1(), mc->Value2() };
    }

    EXPORT void scriptapi_memcell_update(TMemCell *mc, const char *str, double num1, double num2)
    {
        if (!mc)
            return;
        mc->UpdateValues(std::string(str), num1, num2,
                         basic_event::flags::text | basic_event::flags::value_1 | basic_event::flags::value_2);
    }

    EXPORT void scriptapi_dynobj_putvalues(TDynamicObject *dyn, const char *str, double num1, double num2)
    {
        if (!dyn)
            return;
        TLocation loc;
        if (dyn->Mechanik)
            dyn->Mechanik->PutCommand(std::string(str), num1, num2, nullptr);
        else
            dyn->MoverParameters->PutCommand(std::string(str), num1, num2, loc);
    }
}
<commit_msg>lua putvalues fix<commit_after>#include "stdafx.h"
#include "lua.h"
#include "Event.h"
#include "Logs.h"
#include "MemCell.h"
#include "Driver.h"
#include "lua_ffi.h"
#include "simulation.h"

lua::lua()
{
    state = luaL_newstate();
    if (!state)
        throw std::runtime_error("cannot create lua state");
    lua_atpanic(state, atpanic);
    luaL_openlibs(state);

    lua_getglobal(state, "package");
    lua_pushstring(state, "preload");
    lua_gettable(state, -2);
    lua_pushcclosure(state, openffi, 0);
    lua_setfield(state, -2, "eu07.events");
    lua_settop(state, 0);
}

lua::~lua()
{
    lua_close(state);
    state = nullptr;
}

void lua::interpret(std::string file)
{
    if (luaL_dofile(state, file.c_str()))
        throw std::runtime_error(lua_tostring(state, -1));
}

// NOTE: we cannot throw exceptions in callbacks
// because it is not supported by LuaJIT on x86 windows

int lua::atpanic(lua_State *s)
{
	std::string err(lua_tostring(s, -1));
    ErrorLog(err);
#ifdef _WIN32
        MessageBox(NULL, err.c_str(), "MaSzyna", MB_OK);
#endif
    return 0;
}

int lua::openffi(lua_State *s)
{
    if (luaL_dostring(s, lua_ffi))
    {
        ErrorLog(std::string(lua_tostring(s, -1)));
        return 0;
    }
    return 1;
}

#ifdef _WIN32
#define EXPORT __declspec(dllexport)
#else
#define EXPORT
#endif

extern "C"
{
    EXPORT basic_event* scriptapi_event_create(const char* name, double delay, double randomdelay, lua::eventhandler_t handler)
    {
        basic_event *event = new lua_event(handler);
        event->m_name = std::string(name);
        event->m_delay = delay;
        event->m_delayrandom = randomdelay;

		if (simulation::Events.insert(event))
			return event;
		else
			return nullptr;
    }

    EXPORT basic_event* scriptapi_event_find(const char* name)
    {
        std::string str(name);
        basic_event *e = simulation::Events.FindEvent(str);
        if (e)
            return e;
        else
            WriteLog("lua: missing event: " + str);
        return nullptr;
    }

    EXPORT TTrack* scriptapi_track_find(const char* name)
    {
        std::string str(name);
		TTrack *track = simulation::Paths.find(str);
        if (track)
            return track;
        else
            WriteLog("lua: missing track: " + str);
        return nullptr;
    }

    EXPORT bool scriptapi_track_isoccupied(TTrack* track)
    {
        if (track)
            return !track->IsEmpty();
        return false;
    }

	EXPORT TIsolated* scriptapi_isolated_find(const char* name)
	{
		std::string str(name);
        TIsolated *isolated = TIsolated::Find(name);
		if (isolated)
			return isolated;
		else
			WriteLog("lua: missing isolated: " + str);
		return nullptr;
	}

	EXPORT bool scriptapi_isolated_isoccupied(TIsolated* isolated)
	{
		if (isolated)
			return isolated->Busy();
		return false;
	}

    EXPORT const char* scriptapi_event_getname(basic_event *e)
    {
        if (e)
            return e->m_name.c_str();
        return nullptr;
    }

    EXPORT const char* scriptapi_train_getname(TDynamicObject *dyn)
    {
        if (dyn && dyn->Mechanik)
            return dyn->Mechanik->TrainName().c_str();
        return nullptr;
    }

    EXPORT void scriptapi_event_dispatch(basic_event *e, TDynamicObject *activator, double delay)
    {
        if (e)
            simulation::Events.AddToQuery(e, activator, delay);
    }

    EXPORT double scriptapi_random(double a, double b)
    {
        return Random(a, b);
    }

    EXPORT void scriptapi_writelog(const char* txt)
    {
        WriteLog("lua: log: " + std::string(txt), logtype::lua);
    }

    EXPORT void scriptapi_writeerrorlog(const char* txt)
    {
        ErrorLog("lua: log: " + std::string(txt), logtype::lua);
    }

    struct memcell_values { const char *str; double num1; double num2; };

    EXPORT TMemCell* scriptapi_memcell_find(const char *name)
    {
        std::string str(name);
        TMemCell *mc = simulation::Memory.find(str);
        if (mc)
            return mc;
        else
            WriteLog("lua: missing memcell: " + str);
        return nullptr;
    }

    EXPORT memcell_values scriptapi_memcell_read(TMemCell *mc)
    {
        if (!mc)
            return { nullptr, 0.0, 0.0 };
        return { mc->Text().c_str(), mc->Value1(), mc->Value2() };
    }

    EXPORT void scriptapi_memcell_update(TMemCell *mc, const char *str, double num1, double num2)
    {
        if (!mc)
            return;
        mc->UpdateValues(std::string(str), num1, num2,
                         basic_event::flags::text | basic_event::flags::value_1 | basic_event::flags::value_2);
    }

    EXPORT void scriptapi_dynobj_putvalues(TDynamicObject *dyn, const char *str, double num1, double num2)
    {
        if (!dyn)
            return;
        TLocation loc;
        if (dyn->Mechanik)
            dyn->Mechanik->PutCommand(std::string(str), num1, num2, loc);
        else
            dyn->MoverParameters->PutCommand(std::string(str), num1, num2, loc);
    }
}
<|endoftext|>


<commit_before>
#include "cpu.h"

#if defined(YUNI_OS_DARWIN) || defined(YUNI_OS_FREEBSD) || defined(YUNI_OS_NETBSD) || defined(YUNI_OS_OPENBSD)
# include <sys/param.h>
# include <sys/sysctl.h>
#endif
#if defined(YUNI_OS_LINUX) || defined(YUNI_OS_CYGWIN)
# include <fstream>
# include "../string.h"
#endif
#include "windows.hdr.h"

namespace Yuni
{
namespace System
{
namespace CPU
{

	#if defined(YUNI_OS_DARWIN) || defined(YUNI_OS_FREEBSD) || defined(YUNI_OS_NETBSD) || defined(YUNI_OS_OPENBSD)
	# define YUNI_CPU_COUNT_HAS_IMPLEMENTATION
	uint Count()
	{
		int count;
		size_t size = sizeof(count);

		if (sysctlbyname("hw.ncpu", &count, &size, NULL, 0))
			return 1;
		return (count <= 0) ? 1 : (uint) count;
	}
	#endif

	#ifdef YUNI_OS_WINDOWS
	# define YUNI_CPU_COUNT_HAS_IMPLEMENTATION
	uint Count()
	{
		SYSTEM_INFO si;
		GetSystemInfo(&si);
		return si.dwNumberOfProcessors;
	}
	#endif

	#if defined(YUNI_OS_LINUX) || defined(YUNI_OS_CYGWIN)
	# define YUNI_CPU_COUNT_HAS_IMPLEMENTATION
	uint Count()
	{
		// It seems there's no better way to get this info on Linux systems.
		// If somebody can find it without depending on the location of /proc,
		// please patch this function.
		uint count = 0;
		std::ifstream cpuInfo("/proc/cpuinfo", std::ifstream::in);
		std::string lineBuffer;

		std::getline(cpuInfo, lineBuffer);
		while (cpuInfo.good())
		{
			if (std::string::npos != lineBuffer.find("processor"))
				++count;
			std::getline(cpuInfo, lineBuffer);
		}
		cpuInfo.close();

		return (0 == count ? 1 : count);
	}
	#endif

	#ifndef YUNI_CPU_COUNT_HAS_IMPLEMENTATION
	#  warning "The method Yuni::System::CPU::Count() has not been implemented for the current platform"
	uint Count()
	{
		return 1; // Default value
	}
	#endif

} // namespace CPU
} // namespace System
} // namespace Yuni

<commit_msg>System::CPU: cygwin should follow the windows implementation, not the linux one<commit_after>
#include "cpu.h"

#if defined(YUNI_OS_DARWIN) || defined(YUNI_OS_FREEBSD) || defined(YUNI_OS_NETBSD) || defined(YUNI_OS_OPENBSD)
# include <sys/param.h>
# include <sys/sysctl.h>
#endif
#if defined(YUNI_OS_LINUX) || defined(YUNI_OS_CYGWIN)
# include <fstream>
# include "../string.h"
#endif
#include "windows.hdr.h"

namespace Yuni
{
namespace System
{
namespace CPU
{

	#if defined(YUNI_OS_DARWIN) || defined(YUNI_OS_FREEBSD) || defined(YUNI_OS_NETBSD) || defined(YUNI_OS_OPENBSD)
	# define YUNI_CPU_COUNT_HAS_IMPLEMENTATION
	uint Count()
	{
		int count;
		size_t size = sizeof(count);

		if (sysctlbyname("hw.ncpu", &count, &size, NULL, 0))
			return 1;
		return (count <= 0) ? 1 : (uint) count;
	}
	#endif

	#if defined(YUNI_OS_WINDOWS) || defined(YUNI_OS_CYGWIN)
	# define YUNI_CPU_COUNT_HAS_IMPLEMENTATION
	uint Count()
	{
		SYSTEM_INFO si;
		GetSystemInfo(&si);
		return si.dwNumberOfProcessors;
	}
	#endif

	#if defined(YUNI_OS_LINUX)
	# define YUNI_CPU_COUNT_HAS_IMPLEMENTATION
	uint Count()
	{
		// It seems there's no better way to get this info on Linux systems.
		// If somebody can find it without depending on the location of /proc,
		// please patch this function.
		uint count = 0;
		std::ifstream cpuInfo("/proc/cpuinfo", std::ifstream::in);
		std::string lineBuffer;

		std::getline(cpuInfo, lineBuffer);
		while (cpuInfo.good())
		{
			if (std::string::npos != lineBuffer.find("processor"))
				++count;
			std::getline(cpuInfo, lineBuffer);
		}
		cpuInfo.close();

		return (0 == count ? 1 : count);
	}
	#endif

	#ifndef YUNI_CPU_COUNT_HAS_IMPLEMENTATION
	#  warning "The method Yuni::System::CPU::Count() has not been implemented for the current platform"
	uint Count()
	{
		return 1; // Default value
	}
	#endif

} // namespace CPU
} // namespace System
} // namespace Yuni

<|endoftext|>