<commit_before>/*
 * Copyright (c) 2019, ARM Limited, All Rights Reserved
 * SPDX-License-Identifier: Apache-2.0
 *
 * 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.
 */

#define WIFI 2
#if !defined(MBED_CONF_TARGET_NETWORK_DEFAULT_INTERFACE_TYPE) || \
    (MBED_CONF_TARGET_NETWORK_DEFAULT_INTERFACE_TYPE == WIFI && !defined(MBED_CONF_NSAPI_DEFAULT_WIFI_SSID))
#error [NOT_SUPPORTED] No network configuration found for this target.
#else
#ifndef MBED_CONF_APP_ECHO_SERVER_ADDR
#error [NOT_SUPPORTED] Requires parameters from mbed_app.json
#else

#if !defined(DEVICE_EMAC) || \
    (!defined(MBED_CONF_APP_WIFI_SECURE_SSID) && !defined(MBED_CONF_APP_WIFI_UNSECURE_SSID))
#error [NOT_SUPPORTED] Both Wifi and Ethernet devices are required for multihoming tests.
#else

#define STRING_VERIFY(str) (str != NULL ? str : "not supported")

#include "greentea-client/test_env.h"
#include "unity/unity.h"
#include "utest.h"
#include "utest/utest_stack_trace.h"
#include "multihoming_tests.h"
#include "LWIPStack.h"

using namespace utest::v1;

namespace {
EthInterface *eth;
WiFiInterface *wifi;
}

char interface_name[MBED_CONF_MULTIHOMING_MAX_INTERFACES_NUM][INTERFACE_NAME_LEN];
int  interface_num = 0;

#if MBED_CONF_NSAPI_SOCKET_STATS_ENABLED
mbed_stats_socket_t udp_stats[MBED_CONF_NSAPI_SOCKET_STATS_MAX_COUNT];
#endif

#if defined(MBED_CONF_APP_WIFI_SECURE_SSID) || defined(MBED_CONF_APP_WIFI_UNSECURE_SSID)
#define SSID_MAX_LEN 32
#define PWD_MAX_LEN 64

#endif

NetworkInterface *get_interface(int interface_index)
{
    if (interface_index == ETH_INTERFACE) {
        return eth;
    } else if (interface_index == WIFI_INTERFACE) {
        return wifi;
    }
    return NULL;
}

static void _ifup()
{
    eth = EthInterface::get_default_instance();
    nsapi_error_t err = eth->connect();
    eth->get_interface_name(interface_name[interface_num]);
    TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, err);
    SocketAddress eth_ip_address;
    eth->get_ip_address(&eth_ip_address);
    printf("MBED: IP address is '%s' interface name %s\n", eth_ip_address.get_ip_address(), interface_name[interface_num]);
    SocketAddress eth_ip_address_if;
    LWIP::get_instance().get_ip_address_if(&eth_ip_address_if, interface_name[interface_num]);
    printf("IP_if: %s\n", eth_ip_address.get_ip_address());
    TEST_ASSERT_EQUAL(eth_ip_address_if, eth_ip_address);
    interface_num++;

    wifi = WiFiInterface::get_default_instance();

    if (wifi) {
#if defined(MBED_CONF_APP_WIFI_SECURE_SSID)
        char ssid[SSID_MAX_LEN + 1] = MBED_CONF_APP_WIFI_SECURE_SSID;
        char pwd[PWD_MAX_LEN + 1] = MBED_CONF_APP_WIFI_PASSWORD;
        nsapi_security_t security = NSAPI_SECURITY_WPA_WPA2;

#elif defined(MBED_CONF_APP_WIFI_UNSECURE_SSID)
        char ssid[SSID_MAX_LEN + 1] = MBED_CONF_APP_WIFI_UNSECURE_SSID;
        char pwd[PWD_MAX_LEN + 1] = NULL;
        nsapi_security_t security = NSAPI_SECURITY_NONE;
#endif

        printf("\nConnecting to %s...\n", ssid);
        int ret = wifi->connect(ssid, pwd, security);
        if (ret != 0) {
            TEST_FAIL_MESSAGE("Wifi connection error!");
            return;
        }
        printf("Wifi interface name: %s\n\n", STRING_VERIFY(wifi->get_interface_name(interface_name[interface_num])));
        printf("MAC: %s\n", STRING_VERIFY(wifi->get_mac_address()));
        SocketAddress wifi_ip_address;
        wifi->get_ip_address(&wifi_ip_address);
        printf("IP: %s\n", STRING_VERIFY(wifi_ip_address.get_ip_address()));
        SocketAddress wifi_ip_address_if;
        LWIP::get_instance().get_ip_address_if(&wifi_ip_address_if, interface_name[interface_num]);
        printf("IP_if: %s\n", STRING_VERIFY(wifi_ip_address_if.get_ip_address()));
        TEST_ASSERT_EQUAL(wifi_ip_address_if, wifi_ip_address);
        SocketAddress wifi_netmask;
        wifi->get_netmask(&wifi_netmask);
        printf("Netmask: %s\n", STRING_VERIFY(wifi_netmask.get_ip_address()));
        SocketAddress wifi_gateway;
        wifi->get_gateway(&wifi_gateway);
        printf("Gateway: %s\n", STRING_VERIFY(wifi_gateway.get_ip_address()));
        printf("RSSI: %d\n\n", wifi->get_rssi());
        interface_num++;
    } else {
        TEST_FAIL_MESSAGE("ERROR: No WiFiInterface found!");
    }
}

static void _ifdown()
{
    interface_num = 0;
    if (eth != NULL) {
        eth->disconnect();
    }
#if defined(MBED_CONF_APP_WIFI_SECURE_SSID) || defined(MBED_CONF_APP_WIFI_UNSECURE_SSID)
    if (wifi != NULL) {
        wifi->disconnect();
    }
#endif
    printf("MBED: ifdown\n");
}

void fill_tx_buffer_ascii(char *buff, size_t len)
{
    for (size_t i = 0; i < len; ++i) {
        buff[i] = (rand() % 43) + '0';
    }
}

#if MBED_CONF_NSAPI_SOCKET_STATS_ENABLED
int fetch_stats()
{
    return SocketStats::mbed_stats_socket_get_each(&udp_stats[0], MBED_CONF_NSAPI_SOCKET_STATS_MAX_COUNT);
}
#endif

// Test setup
utest::v1::status_t greentea_setup(const size_t number_of_cases)
{
    GREENTEA_SETUP(480, "default_auto");
    _ifup();
    return greentea_test_setup_handler(number_of_cases);
}

void greentea_teardown(const size_t passed, const size_t failed, const failure_t failure)
{
    _ifdown();
    return greentea_test_teardown_handler(passed, failed, failure);
}

Case cases[] = {
    Case("MULTIHOMING_SYNCHRONOUS_DNS", MULTIHOMING_SYNCHRONOUS_DNS),
    Case("MULTIHOMING_ASYNCHRONOUS_DNS", MULTIHOMING_ASYNCHRONOUS_DNS),
    Case("MULTIHOMING_UDPSOCKET_ECHOTEST", MULTIHOMING_UDPSOCKET_ECHOTEST),
    Case("MULTIHOMING_UDPSOCKET_ECHOTEST_NONBLOCK", MULTIHOMING_UDPSOCKET_ECHOTEST_NONBLOCK),
};

Specification specification(greentea_setup, cases, greentea_teardown, greentea_continue_handlers);

int main()
{
    return !Harness::run(specification);
}

#endif // !defined(DEVICE_EMAC) || (!defined(MBED_CONF_APP_WIFI_SECURE_SSID) && !defined(MBED_CONF_APP_WIFI_UNSECURE_SSID))
#endif // MBED_CONF_APP_ECHO_SERVER_ADDR
#endif // !defined(MBED_CONF_TARGET_NETWORK_DEFAULT_INTERFACE_TYPE) || (MBED_CONF_TARGET_NETWORK_DEFAULT_INTERFACE_TYPE == WIFI && !defined(MBED_CONF_NSAPI_DEFAULT_WIFI_SSID))
<commit_msg>Testing: Fix SocketAddress compare<commit_after>/*
 * Copyright (c) 2019, ARM Limited, All Rights Reserved
 * SPDX-License-Identifier: Apache-2.0
 *
 * 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.
 */

#define WIFI 2
#if !defined(MBED_CONF_TARGET_NETWORK_DEFAULT_INTERFACE_TYPE) || \
    (MBED_CONF_TARGET_NETWORK_DEFAULT_INTERFACE_TYPE == WIFI && !defined(MBED_CONF_NSAPI_DEFAULT_WIFI_SSID))
#error [NOT_SUPPORTED] No network configuration found for this target.
#else
#ifndef MBED_CONF_APP_ECHO_SERVER_ADDR
#error [NOT_SUPPORTED] Requires parameters from mbed_app.json
#else

#if !defined(DEVICE_EMAC) || \
    (!defined(MBED_CONF_APP_WIFI_SECURE_SSID) && !defined(MBED_CONF_APP_WIFI_UNSECURE_SSID))
#error [NOT_SUPPORTED] Both Wifi and Ethernet devices are required for multihoming tests.
#else

#define STRING_VERIFY(str) (str != NULL ? str : "not supported")

#include "greentea-client/test_env.h"
#include "unity/unity.h"
#include "utest.h"
#include "utest/utest_stack_trace.h"
#include "multihoming_tests.h"
#include "LWIPStack.h"

using namespace utest::v1;

namespace {
EthInterface *eth;
WiFiInterface *wifi;
}

char interface_name[MBED_CONF_MULTIHOMING_MAX_INTERFACES_NUM][INTERFACE_NAME_LEN];
int  interface_num = 0;

#if MBED_CONF_NSAPI_SOCKET_STATS_ENABLED
mbed_stats_socket_t udp_stats[MBED_CONF_NSAPI_SOCKET_STATS_MAX_COUNT];
#endif

#if defined(MBED_CONF_APP_WIFI_SECURE_SSID) || defined(MBED_CONF_APP_WIFI_UNSECURE_SSID)
#define SSID_MAX_LEN 32
#define PWD_MAX_LEN 64

#endif

NetworkInterface *get_interface(int interface_index)
{
    if (interface_index == ETH_INTERFACE) {
        return eth;
    } else if (interface_index == WIFI_INTERFACE) {
        return wifi;
    }
    return NULL;
}

static void _ifup()
{
    eth = EthInterface::get_default_instance();
    nsapi_error_t err = eth->connect();
    eth->get_interface_name(interface_name[interface_num]);
    TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, err);
    SocketAddress eth_ip_address;
    eth->get_ip_address(&eth_ip_address);
    printf("MBED: IP address is '%s' interface name %s\n", eth_ip_address.get_ip_address(), interface_name[interface_num]);
    SocketAddress eth_ip_address_if;
    LWIP::get_instance().get_ip_address_if(&eth_ip_address_if, interface_name[interface_num]);
    printf("IP_if: %s\n", eth_ip_address.get_ip_address());
    TEST_ASSERT(eth_ip_address_if == eth_ip_address);
    interface_num++;

    wifi = WiFiInterface::get_default_instance();

    if (wifi) {
#if defined(MBED_CONF_APP_WIFI_SECURE_SSID)
        char ssid[SSID_MAX_LEN + 1] = MBED_CONF_APP_WIFI_SECURE_SSID;
        char pwd[PWD_MAX_LEN + 1] = MBED_CONF_APP_WIFI_PASSWORD;
        nsapi_security_t security = NSAPI_SECURITY_WPA_WPA2;

#elif defined(MBED_CONF_APP_WIFI_UNSECURE_SSID)
        char ssid[SSID_MAX_LEN + 1] = MBED_CONF_APP_WIFI_UNSECURE_SSID;
        char pwd[PWD_MAX_LEN + 1] = NULL;
        nsapi_security_t security = NSAPI_SECURITY_NONE;
#endif

        printf("\nConnecting to %s...\n", ssid);
        int ret = wifi->connect(ssid, pwd, security);
        if (ret != 0) {
            TEST_FAIL_MESSAGE("Wifi connection error!");
            return;
        }
        printf("Wifi interface name: %s\n\n", STRING_VERIFY(wifi->get_interface_name(interface_name[interface_num])));
        printf("MAC: %s\n", STRING_VERIFY(wifi->get_mac_address()));
        SocketAddress wifi_ip_address;
        wifi->get_ip_address(&wifi_ip_address);
        printf("IP: %s\n", STRING_VERIFY(wifi_ip_address.get_ip_address()));
        SocketAddress wifi_ip_address_if;
        LWIP::get_instance().get_ip_address_if(&wifi_ip_address_if, interface_name[interface_num]);
        printf("IP_if: %s\n", STRING_VERIFY(wifi_ip_address_if.get_ip_address()));
        TEST_ASSERT(wifi_ip_address_if == wifi_ip_address);
        SocketAddress wifi_netmask;
        wifi->get_netmask(&wifi_netmask);
        printf("Netmask: %s\n", STRING_VERIFY(wifi_netmask.get_ip_address()));
        SocketAddress wifi_gateway;
        wifi->get_gateway(&wifi_gateway);
        printf("Gateway: %s\n", STRING_VERIFY(wifi_gateway.get_ip_address()));
        printf("RSSI: %d\n\n", wifi->get_rssi());
        interface_num++;
    } else {
        TEST_FAIL_MESSAGE("ERROR: No WiFiInterface found!");
    }
}

static void _ifdown()
{
    interface_num = 0;
    if (eth != NULL) {
        eth->disconnect();
    }
#if defined(MBED_CONF_APP_WIFI_SECURE_SSID) || defined(MBED_CONF_APP_WIFI_UNSECURE_SSID)
    if (wifi != NULL) {
        wifi->disconnect();
    }
#endif
    printf("MBED: ifdown\n");
}

void fill_tx_buffer_ascii(char *buff, size_t len)
{
    for (size_t i = 0; i < len; ++i) {
        buff[i] = (rand() % 43) + '0';
    }
}

#if MBED_CONF_NSAPI_SOCKET_STATS_ENABLED
int fetch_stats()
{
    return SocketStats::mbed_stats_socket_get_each(&udp_stats[0], MBED_CONF_NSAPI_SOCKET_STATS_MAX_COUNT);
}
#endif

// Test setup
utest::v1::status_t greentea_setup(const size_t number_of_cases)
{
    GREENTEA_SETUP(480, "default_auto");
    _ifup();
    return greentea_test_setup_handler(number_of_cases);
}

void greentea_teardown(const size_t passed, const size_t failed, const failure_t failure)
{
    _ifdown();
    return greentea_test_teardown_handler(passed, failed, failure);
}

Case cases[] = {
    Case("MULTIHOMING_SYNCHRONOUS_DNS", MULTIHOMING_SYNCHRONOUS_DNS),
    Case("MULTIHOMING_ASYNCHRONOUS_DNS", MULTIHOMING_ASYNCHRONOUS_DNS),
    Case("MULTIHOMING_UDPSOCKET_ECHOTEST", MULTIHOMING_UDPSOCKET_ECHOTEST),
    Case("MULTIHOMING_UDPSOCKET_ECHOTEST_NONBLOCK", MULTIHOMING_UDPSOCKET_ECHOTEST_NONBLOCK),
};

Specification specification(greentea_setup, cases, greentea_teardown, greentea_continue_handlers);

int main()
{
    return !Harness::run(specification);
}

#endif // !defined(DEVICE_EMAC) || (!defined(MBED_CONF_APP_WIFI_SECURE_SSID) && !defined(MBED_CONF_APP_WIFI_UNSECURE_SSID))
#endif // MBED_CONF_APP_ECHO_SERVER_ADDR
#endif // !defined(MBED_CONF_TARGET_NETWORK_DEFAULT_INTERFACE_TYPE) || (MBED_CONF_TARGET_NETWORK_DEFAULT_INTERFACE_TYPE == WIFI && !defined(MBED_CONF_NSAPI_DEFAULT_WIFI_SSID))
<|endoftext|>


<commit_before>#include <neat-socketapi.h>

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

static const char* properties = "{\
    \"transport\": [\
        {\
            \"value\": \"TCP\",\
            \"precedence\": 1\
        }\
    ]\
}";\

int main(int argc, char** argv)
{
   int sd = nsa_socket(AF_INET6, SOCK_SEQPACKET, IPPROTO_SCTP, properties);
   if(sd < 0) {
      perror("nsa_socket() failed");
      exit(1);
   }
   printf("sd=%d\n", sd);

   sockaddr_in local;
   memset(&local, 0, sizeof(local));
   local.sin_family = AF_INET;
   local.sin_port   = htons(8888);
   if(nsa_bind(sd, (sockaddr*)&local, sizeof(local)) < 0) {
      perror("nsa_bind() failed");
      exit(1);
   }

   if(nsa_listen(sd, 10) < 0) {
      perror("nsa_listen() failed");
      exit(1);
   }

   puts("### LISTENING ... ###");

   int newSD = nsa_accept(sd, NULL, NULL);
   if(newSD >= 0) {
      puts("### ACCEPTED ###");

      if(nsa_write(newSD, "TEST\n", 5) < 0) {
         perror("nsa_write() failed");
      }

      char buffer[1024];
      ssize_t r = nsa_read(newSD, (char*)&buffer, sizeof(buffer));
      if(r > 0) {
         printf("r=%d\n", (int)r);
         if(nsa_write(newSD, buffer, r) < 0) {
            perror("nsa_write() failed");
         }
      }

      nsa_close(newSD);
   }
   else {
      perror("nsa_accept() failed");
   }

   nsa_close(sd);

   nsa_cleanup();
   return 0;
}
<commit_msg>Some testing.<commit_after>#include <neat-socketapi.h>

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <assert.h>

static const char* properties = "{\
    \"transport\": [\
        {\
            \"value\": \"SCTP\",\
            \"precedence\": 1\
        },\
        {\
            \"value\": \"TCP\",\
            \"precedence\": 1\
        }\
    ]\
}";\

int main(int argc, char** argv)
{
   int sd = nsa_socket(AF_INET6, SOCK_SEQPACKET, IPPROTO_SCTP, properties);
   if(sd < 0) {
      perror("nsa_socket() failed");
      exit(1);
   }
   printf("sd=%d\n", sd);

   sockaddr_in local;
   memset(&local, 0, sizeof(local));
   local.sin_family = AF_INET;
   local.sin_port   = htons(8888);
   if(nsa_bind(sd, (sockaddr*)&local, sizeof(local)) < 0) {
      perror("nsa_bind() failed");
      exit(1);
   }

   if(nsa_listen(sd, 10) < 0) {
      perror("nsa_listen() failed");
      exit(1);
   }

   puts("### LISTENING ... ###");

   int newSD = nsa_accept(sd, NULL, NULL);
   if(newSD >= 0) {
      puts("### ACCEPTED ###");

      if(nsa_write(newSD, "TEST\n", 5) < 0) {
         perror("nsa_write() failed");
      }

      struct sockaddr* addrs = NULL;
      const int n = nsa_getpaddrs(newSD, 0, &addrs);
      if(n > 0) {
         struct sockaddr* a = addrs;
         for(int i = 0; i < n; i++) {
            switch(a->sa_family) {
               case AF_INET:
                  printf("Address %d/%d: IPv4\n", i, n);
                  a = (struct sockaddr*)((long)a + (long)sizeof(sockaddr_in));
                break;
               case AF_INET6:
                  printf("Address %d/%d: IPv6\n", i, n);
                  a = (struct sockaddr*)((long)a + (long)sizeof(sockaddr_in6));
               default:
                  assert(false);
                break;
            }
         }
         free(addrs);
      }

      char buffer[1024];
      ssize_t r = nsa_read(newSD, (char*)&buffer, sizeof(buffer));
      if(r > 0) {
         printf("r=%d\n", (int)r);
         if(nsa_write(newSD, buffer, r) < 0) {
            perror("nsa_write() failed");
         }
      }

      nsa_close(newSD);
   }
   else {
      perror("nsa_accept() failed");
   }

   nsa_close(sd);

   nsa_cleanup();
   return 0;
}
<|endoftext|>


<commit_before>/**
 * @brief Test cases for materialization node.
 *
 * Copyright(c) 2015, CMU
 */

#include <memory>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>

#include "gtest/gtest.h"

#include "catalog/manager.h"
#include "catalog/schema.h"
#include "common/types.h"
#include "common/value_factory.h"
#include "executor/logical_tile.h"
#include "executor/logical_tile_factory.h"
#include "executor/materialization_executor.h"
#include "planner/abstract_plan_node.h"
#include "planner/materialization_node.h"
#include "storage/tile.h"
#include "storage/tile_group.h"
#include "storage/tuple.h"
#include "storage/vm_backend.h"

#include "executor/executor_tests_util.h"
#include "executor/mock_executor.h"
#include "harness.h"

using ::testing::IsNull;
using ::testing::NotNull;
using ::testing::Return;

namespace nstore {
namespace test {

// Utility functions.
namespace {

/**
 * @brief TODO
 */
void PopulateTiles(storage::TileGroup *tile_group, int num_rows) {
  // Create tuple schema from tile schemas.
  std::vector<catalog::Schema> &tile_schemas = tile_group->GetTileSchemas();
  std::unique_ptr<catalog::Schema> schema(
    catalog::Schema::AppendSchemaList(tile_schemas));

  // Ensure that the tile group created by ExecutorTestsUtil is as expected.
  assert(tile_schemas.size() == 2);
  assert(schema->GetColumnCount() == 4);

  // Insert tuples into tile_group.
  const bool allocate = true;
  const txn_id_t txn_id = GetTransactionId();
  for (int i = 0; i < num_rows; i++) {
    storage::Tuple tuple(schema.get(), allocate);
    tuple.SetValue(0, ValueFactory::GetIntegerValue(10 * i));
    tuple.SetValue(1, ValueFactory::GetIntegerValue(10 * i + 1));
    tuple.SetValue(2, ValueFactory::GetTinyIntValue(10 * i + 2));
    tuple.SetValue(
        3,
        ValueFactory::GetStringValue(std::to_string(10 * i + 3),
        tile_group->GetTilePool(1)));
    tile_group->InsertTuple(txn_id, &tuple);
  }
}

/**
 * @brief TODO
 */
void VerifyLeftTile(
    storage::Tile *base_tile,
    executor::LogicalTile *logical_tile,
    int tuple_count) {
  // Check that the base tile has the correct values.
  for (int i = 0; i < tuple_count; i++) {
    EXPECT_EQ(ValueFactory::GetIntegerValue(10 * i),
              base_tile->GetValue(i, 0));
    EXPECT_EQ(ValueFactory::GetIntegerValue(10 * i + 1),
              base_tile->GetValue(i, 1));

    // Double check that logical tile is functioning.
    EXPECT_EQ(base_tile->GetValue(i, 0),
              logical_tile->GetValue(0, i));
    EXPECT_EQ(base_tile->GetValue(i, 1),
              logical_tile->GetValue(1, i));
  }
}

} // namespace

// "Pass-through" test case. There is nothing to materialize as
// there is only one base tile in the logical tile.
TEST(MaterializationTests, SingleBaseTileTest) {
  storage::VMBackend backend;
  const int tuple_count = 9;
  std::unique_ptr<storage::TileGroup> tile_group(
      ExecutorTestsUtil::CreateSimpleTileGroup(
        &backend,
        tuple_count));

  PopulateTiles(tile_group.get(), tuple_count);

  // Create logical tile from single base tile.
  storage::Tile *source_base_tile = tile_group->GetTile(0);
  const bool own_base_tile = false;
  std::unique_ptr<executor::LogicalTile> source_tile(
      executor::LogicalTileFactory::WrapBaseTile(
          source_base_tile,
          own_base_tile));

  // Create materialization node for this test.
  //TODO This should be deleted soon... Should we use default copy constructor?
  std::unique_ptr<catalog::Schema> output_schema(catalog::Schema::CopySchema(
      &source_base_tile->GetSchema()));
  std::unordered_map<id_t, id_t> old_to_new_cols;

  unsigned int column_count = output_schema->GetColumnCount();
  for (id_t col = 0; col < column_count; col++) {
    // Create identity mapping.
    old_to_new_cols[col] = col;
  }
  planner::MaterializationNode node(
      std::move(old_to_new_cols),
      output_schema.release());

  // Pass them through materialization executor.
  executor::MaterializationExecutor executor(&node);
  MockExecutor child_executor;
  executor.AddChild(&child_executor);

  // Uneventful init...
  EXPECT_CALL(child_executor, SubInit())
    .WillOnce(Return(true));
  EXPECT_TRUE(executor.Init());

  // Where the main work takes place...
  EXPECT_CALL(child_executor, SubGetNextTile())
    .WillOnce(Return(source_tile.release()))
    .WillOnce(Return(nullptr));

  std::unique_ptr<executor::LogicalTile> result_logical_tile(
    executor.GetNextTile());
  EXPECT_THAT(result_logical_tile, NotNull());
  EXPECT_THAT(executor.GetNextTile(), IsNull());

  // Verify that logical tile is only made up of a single base tile.
  int num_cols = result_logical_tile->NumCols();
  EXPECT_EQ(2, num_cols);
  storage::Tile *result_base_tile = result_logical_tile->GetBaseTile(0);
  EXPECT_THAT(result_base_tile, NotNull());
  EXPECT_TRUE(source_base_tile != result_base_tile);
  EXPECT_EQ(result_logical_tile->GetBaseTile(1), result_base_tile);

  VerifyLeftTile(result_base_tile, result_logical_tile.get(), tuple_count);
}

TEST(MaterializationTests, TwoBaseTilesTest) {
  //TODO Implement.
  //TODO WaTeRmArK
  storage::VMBackend backend;
  const int tuple_count = 9;
  std::unique_ptr<storage::TileGroup> tile_group(
      ExecutorTestsUtil::CreateSimpleTileGroup(
        &backend,
        tuple_count));

  PopulateTiles(tile_group.get(), tuple_count);

  // Create logical tile from single base tile.
  storage::Tile *source_base_tile = tile_group->GetTile(0);
  const bool own_base_tile = false;
  std::unique_ptr<executor::LogicalTile> source_tile(
      executor::LogicalTileFactory::WrapBaseTile(
          source_base_tile,
          own_base_tile));

  // Create materialization node for this test.
  //TODO This should be deleted soon... Should we use default copy constructor?
  std::unique_ptr<catalog::Schema> output_schema(catalog::Schema::CopySchema(
      &source_base_tile->GetSchema()));
  std::unordered_map<id_t, id_t> old_to_new_cols;

  unsigned int column_count = output_schema->GetColumnCount();
  for (id_t col = 0; col < column_count; col++) {
    // Create identity mapping.
    old_to_new_cols[col] = col;
  }
  planner::MaterializationNode node(
      std::move(old_to_new_cols),
      output_schema.release());

  // Pass them through materialization executor.
  executor::MaterializationExecutor executor(&node);
  MockExecutor child_executor;
  executor.AddChild(&child_executor);

  // Uneventful init...
  EXPECT_CALL(child_executor, SubInit())
    .WillOnce(Return(true));
  EXPECT_TRUE(executor.Init());

  // Where the main work takes place...
  EXPECT_CALL(child_executor, SubGetNextTile())
    .WillOnce(Return(source_tile.release()))
    .WillOnce(Return(nullptr));

  std::unique_ptr<executor::LogicalTile> result_logical_tile(
    executor.GetNextTile());
  EXPECT_THAT(result_logical_tile, NotNull());
  EXPECT_THAT(executor.GetNextTile(), IsNull());

  // Verify that logical tile is only made up of a single base tile.
  int num_cols = result_logical_tile->NumCols();
  EXPECT_EQ(2, num_cols);
  storage::Tile *result_base_tile = result_logical_tile->GetBaseTile(0);
  EXPECT_THAT(result_base_tile, NotNull());
  EXPECT_TRUE(source_base_tile != result_base_tile);
  EXPECT_EQ(result_logical_tile->GetBaseTile(1), result_base_tile);

  VerifyLeftTile(result_base_tile, result_logical_tile.get(), tuple_count);
}

} // namespace test
} // namespace nstore
<commit_msg>Small refactor in materialize test.<commit_after>/**
 * @brief Test cases for materialization node.
 *
 * Copyright(c) 2015, CMU
 */

#include <memory>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>

#include "gtest/gtest.h"

#include "catalog/manager.h"
#include "catalog/schema.h"
#include "common/types.h"
#include "common/value_factory.h"
#include "executor/logical_tile.h"
#include "executor/logical_tile_factory.h"
#include "executor/materialization_executor.h"
#include "planner/abstract_plan_node.h"
#include "planner/materialization_node.h"
#include "storage/tile.h"
#include "storage/tile_group.h"
#include "storage/tuple.h"
#include "storage/vm_backend.h"

#include "executor/executor_tests_util.h"
#include "executor/mock_executor.h"
#include "harness.h"

using ::testing::IsNull;
using ::testing::NotNull;
using ::testing::Return;

namespace nstore {
namespace test {

// Utility functions.
namespace {

/**
 * @brief Populates the tiles in the given tile-group in a specific manner.
 * @param tile_group Tile-group to populate with values.
 * @param num_rows Number of tuples to insert.
 *
 * This is a convenience function for the test cases.
 */
void PopulateTiles(storage::TileGroup *tile_group, int num_rows) {
  // Create tuple schema from tile schemas.
  std::vector<catalog::Schema> &tile_schemas = tile_group->GetTileSchemas();
  std::unique_ptr<catalog::Schema> schema(
    catalog::Schema::AppendSchemaList(tile_schemas));

  // Ensure that the tile group created by ExecutorTestsUtil is as expected.
  assert(tile_schemas.size() == 2);
  assert(schema->GetColumnCount() == 4);

  // Insert tuples into tile_group.
  const bool allocate = true;
  const txn_id_t txn_id = GetTransactionId();
  for (int i = 0; i < num_rows; i++) {
    storage::Tuple tuple(schema.get(), allocate);
    tuple.SetValue(0, ValueFactory::GetIntegerValue(10 * i));
    tuple.SetValue(1, ValueFactory::GetIntegerValue(10 * i + 1));
    tuple.SetValue(2, ValueFactory::GetTinyIntValue(10 * i + 2));
    tuple.SetValue(
        3,
        ValueFactory::GetStringValue(std::to_string(10 * i + 3),
        tile_group->GetTilePool(1)));
    tile_group->InsertTuple(txn_id, &tuple);
  }
}

} // namespace

// "Pass-through" test case. There is nothing to materialize as
// there is only one base tile in the logical tile.
TEST(MaterializationTests, SingleBaseTileTest) {
  storage::VMBackend backend;
  const int tuple_count = 9;
  std::unique_ptr<storage::TileGroup> tile_group(
      ExecutorTestsUtil::CreateSimpleTileGroup(
        &backend,
        tuple_count));

  PopulateTiles(tile_group.get(), tuple_count);

  // Create logical tile from single base tile.
  storage::Tile *source_base_tile = tile_group->GetTile(0);
  const bool own_base_tile = false;
  std::unique_ptr<executor::LogicalTile> source_tile(
      executor::LogicalTileFactory::WrapBaseTile(
          source_base_tile,
          own_base_tile));

  // Create materialization node for this test.
  //TODO This should be deleted soon... Should we use default copy constructor?
  std::unique_ptr<catalog::Schema> output_schema(catalog::Schema::CopySchema(
      &source_base_tile->GetSchema()));
  std::unordered_map<id_t, id_t> old_to_new_cols;

  unsigned int column_count = output_schema->GetColumnCount();
  for (id_t col = 0; col < column_count; col++) {
    // Create identity mapping.
    old_to_new_cols[col] = col;
  }
  planner::MaterializationNode node(
      std::move(old_to_new_cols),
      output_schema.release());

  // Pass them through materialization executor.
  executor::MaterializationExecutor executor(&node);
  MockExecutor child_executor;
  executor.AddChild(&child_executor);

  // Uneventful init...
  EXPECT_CALL(child_executor, SubInit())
    .WillOnce(Return(true));
  EXPECT_TRUE(executor.Init());

  // Where the main work takes place...
  EXPECT_CALL(child_executor, SubGetNextTile())
    .WillOnce(Return(source_tile.release()))
    .WillOnce(Return(nullptr));

  std::unique_ptr<executor::LogicalTile> result_logical_tile(
    executor.GetNextTile());
  EXPECT_THAT(result_logical_tile, NotNull());
  EXPECT_THAT(executor.GetNextTile(), IsNull());

  // Verify that logical tile is only made up of a single base tile.
  int num_cols = result_logical_tile->NumCols();
  EXPECT_EQ(2, num_cols);
  storage::Tile *result_base_tile = result_logical_tile->GetBaseTile(0);
  EXPECT_THAT(result_base_tile, NotNull());
  EXPECT_TRUE(source_base_tile != result_base_tile);
  EXPECT_EQ(result_logical_tile->GetBaseTile(1), result_base_tile);

  // Check that the base tile has the correct values.
  for (int i = 0; i < tuple_count; i++) {
    EXPECT_EQ(ValueFactory::GetIntegerValue(10 * i),
              result_base_tile->GetValue(i, 0));
    EXPECT_EQ(ValueFactory::GetIntegerValue(10 * i + 1),
              result_base_tile->GetValue(i, 1));

    // Double check that logical tile is functioning.
    EXPECT_EQ(result_base_tile->GetValue(i, 0),
              result_logical_tile->GetValue(0, i));
    EXPECT_EQ(result_base_tile->GetValue(i, 1),
              result_logical_tile->GetValue(1, i));
  }
}

TEST(MaterializationTests, TwoBaseTilesTest) {
  //TODO Implement.
  //TODO WaTeRmArK
  storage::VMBackend backend;
  const int tuple_count = 9;
  std::unique_ptr<storage::TileGroup> tile_group(
      ExecutorTestsUtil::CreateSimpleTileGroup(
        &backend,
        tuple_count));

  PopulateTiles(tile_group.get(), tuple_count);

  // Create logical tile from single base tile.
  storage::Tile *source_base_tile = tile_group->GetTile(0);
  const bool own_base_tile = false;
  std::unique_ptr<executor::LogicalTile> source_tile(
      executor::LogicalTileFactory::WrapBaseTile(
          source_base_tile,
          own_base_tile));

  // Create materialization node for this test.
  //TODO This should be deleted soon... Should we use default copy constructor?
  std::unique_ptr<catalog::Schema> output_schema(catalog::Schema::CopySchema(
      &source_base_tile->GetSchema()));
  std::unordered_map<id_t, id_t> old_to_new_cols;

  unsigned int column_count = output_schema->GetColumnCount();
  for (id_t col = 0; col < column_count; col++) {
    // Create identity mapping.
    old_to_new_cols[col] = col;
  }
  planner::MaterializationNode node(
      std::move(old_to_new_cols),
      output_schema.release());

  // Pass them through materialization executor.
  executor::MaterializationExecutor executor(&node);
  MockExecutor child_executor;
  executor.AddChild(&child_executor);

  // Uneventful init...
  EXPECT_CALL(child_executor, SubInit())
    .WillOnce(Return(true));
  EXPECT_TRUE(executor.Init());

  // Where the main work takes place...
  EXPECT_CALL(child_executor, SubGetNextTile())
    .WillOnce(Return(source_tile.release()))
    .WillOnce(Return(nullptr));

  std::unique_ptr<executor::LogicalTile> result_logical_tile(
    executor.GetNextTile());
  EXPECT_THAT(result_logical_tile, NotNull());
  EXPECT_THAT(executor.GetNextTile(), IsNull());

  // Verify that logical tile is only made up of a single base tile.
  int num_cols = result_logical_tile->NumCols();
  EXPECT_EQ(2, num_cols);
  storage::Tile *result_base_tile = result_logical_tile->GetBaseTile(0);
  EXPECT_THAT(result_base_tile, NotNull());
  EXPECT_TRUE(source_base_tile != result_base_tile);
  EXPECT_EQ(result_logical_tile->GetBaseTile(1), result_base_tile);

  // Check that the base tile has the correct values.
  for (int i = 0; i < tuple_count; i++) {
    EXPECT_EQ(ValueFactory::GetIntegerValue(10 * i),
              result_base_tile->GetValue(i, 0));
    EXPECT_EQ(ValueFactory::GetIntegerValue(10 * i + 1),
              result_base_tile->GetValue(i, 1));

    // Double check that logical tile is functioning.
    EXPECT_EQ(result_base_tile->GetValue(i, 0),
              result_logical_tile->GetValue(0, i));
    EXPECT_EQ(result_base_tile->GetValue(i, 1),
              result_logical_tile->GetValue(1, i));
  }
}

} // namespace test
} // namespace nstore
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: winpluginlib.cpp,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2006-10-12 12:33:19 $
 *
 *  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
 *
 ************************************************************************/

#ifdef SVX_DLLIMPLEMENTATION
#undef SVX_DLLIMPLEMENTATION
#endif

#if defined _MSC_VER
#pragma warning(push, 1)
#endif
#include <windows.h>
#if defined _MSC_VER
#pragma warning(pop)
#endif
#include <Winreg.h>
#include <Shlwapi.h>
#include <stdio.h>

#define SO_PATH_SIZE        4096
#define MOZ_PLUGIN_DLL_NAME "npsopluginmi.dll"
extern "C" {
int lc_isInstalled(const  char* realFilePath)
{
    HKEY hKeySoftware;
    HKEY hMozillaPlugins;
    HKEY hStarOffice;
    char sSoPath[SO_PATH_SIZE];
    char sPluginPath[SO_PATH_SIZE];

    LONG ret;
    ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE,  "SOFTWARE",  0,  KEY_READ, &hKeySoftware);
    if(ret != ERROR_SUCCESS){
        ret = RegOpenKeyEx(HKEY_CURRENT_USER,  "SOFTWARE",  0,  KEY_READ, &hKeySoftware);
        if(ret != ERROR_SUCCESS){
            return -1;
        }
    }
    ret = RegOpenKeyEx(hKeySoftware,  "MozillaPlugins",  0,  KEY_READ, &hMozillaPlugins);
    if(ret != ERROR_SUCCESS){
        RegCloseKey(hKeySoftware);
        if( ret == ERROR_FILE_NOT_FOUND)
            return 1;
        else
            return -1;
    }
    ret = RegOpenKeyEx(hMozillaPlugins,  "@sun.com/npsopluginmi;version=1.0",  0,  KEY_READ, &hStarOffice);
    if(ret != ERROR_SUCCESS){
        RegCloseKey(hKeySoftware);
        RegCloseKey(hMozillaPlugins);
        if( ret == ERROR_FILE_NOT_FOUND)
            return 1;
        else
            return -1;
    }

    if((realFilePath == NULL) || (strlen(realFilePath) == 0) || (strlen(realFilePath) >= SO_PATH_SIZE))
        ret = -1;
    else{
        sprintf(sSoPath,"%s", realFilePath);
        ret = 0;
    }
    //ret =  GetCurrentDirectory( SO_PATH_SIZE, sSoPath);
    //ret = GetEnvironmentVariable("prog", sSoPath, SO_PATH_SIZE);
    // GetCurrentDirectory return the char number of the string
    if(ret == 0){
        DWORD  dType = REG_SZ;
        DWORD  dSize = SO_PATH_SIZE;
        ret = RegQueryValueEx (hStarOffice, "Path", NULL,  &dType , (LPBYTE) sPluginPath, &dSize);
        if(ret == ERROR_SUCCESS){
            if(strcmp(sPluginPath, sSoPath) == 0)
                ret = 0;
            else
                ret = 1;
        }
        else
            ret = -1;
    }
    else
        ret = -1;
    RegCloseKey(hStarOffice);
    RegCloseKey(hMozillaPlugins);
    RegCloseKey(hKeySoftware);
    return ret;
}

int lc_uninstallPlugin(const  char*)
{
    HKEY hKeySoftware;
    HKEY hMozillaPlugins;
    HKEY hStarOffice;

    LONG ret;
    ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE,  "SOFTWARE",  0,  KEY_READ|KEY_WRITE, &hKeySoftware);
    if(ret != ERROR_SUCCESS){
        ret = RegOpenKeyEx(HKEY_CURRENT_USER,  "SOFTWARE",  0,  KEY_READ|KEY_WRITE, &hKeySoftware);
        if(ret != ERROR_SUCCESS){
            return -1;
        }
    }
    ret = RegOpenKeyEx(hKeySoftware,  "MozillaPlugins",  0,  KEY_READ|KEY_WRITE, &hMozillaPlugins);
    if(ret != ERROR_SUCCESS){
        RegCloseKey(hKeySoftware);
        if( ret == ERROR_FILE_NOT_FOUND)
            return 0;
        else
            return -1;
    }

    ret = RegOpenKeyEx(hMozillaPlugins,  "@sun.com/npsopluginmi;version=1.0",  0,  KEY_READ|KEY_WRITE, &hStarOffice);
    if(ret != ERROR_SUCCESS){
        RegCloseKey(hKeySoftware);
        RegCloseKey(hMozillaPlugins);
        if( ret == ERROR_FILE_NOT_FOUND)
            return 0;
        else
            return -1;
    }
    RegCloseKey(hStarOffice);
    ret = SHDeleteKey(hMozillaPlugins,  "@sun.com/npsopluginmi;version=1.0");
    if(ret != ERROR_SUCCESS){
        ret = -1;
    }
    RegFlushKey(hMozillaPlugins);
    RegCloseKey(hMozillaPlugins);
    RegCloseKey(hKeySoftware);
    return ret;
}

int lc_installPlugin(const  char* realFilePath)
{
    HKEY hKeySoftware;
    HKEY hMozillaPlugins;
    HKEY hStarOffice;
    char sSoPath[SO_PATH_SIZE];
    DWORD  sState;

    LONG ret;
    ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE,  "SOFTWARE",  0,  KEY_READ|KEY_WRITE, &hKeySoftware);
    if(ret != ERROR_SUCCESS){
        ret = RegOpenKeyEx(HKEY_CURRENT_USER,  "SOFTWARE",  0,  KEY_READ|KEY_WRITE, &hKeySoftware);
        if(ret != ERROR_SUCCESS){
            return -1;
        }
    }
    ret = RegOpenKeyEx(hKeySoftware,  "MozillaPlugins",  0,  KEY_READ|KEY_WRITE, &hMozillaPlugins);
    if(ret != ERROR_SUCCESS){
        RegCreateKeyEx(hKeySoftware,
            "MozillaPlugins",
            0,
            NULL,
            REG_OPTION_NON_VOLATILE,
            KEY_READ|KEY_WRITE,
            NULL,
            &hMozillaPlugins,
            &sState);
    }

    ret = RegCreateKeyEx(hMozillaPlugins,
        "@sun.com/npsopluginmi;version=1.0",
        0,
        NULL,
        REG_OPTION_NON_VOLATILE,
        KEY_READ|KEY_WRITE,
        NULL,
        &hStarOffice,
        &sState);
    if(ret != ERROR_SUCCESS){
        RegCloseKey(hKeySoftware);
        RegCloseKey(hMozillaPlugins);
        return -1;
    }

    RegFlushKey(hStarOffice);
    RegFlushKey(hMozillaPlugins);

    if((realFilePath == NULL) || (strlen(realFilePath) == 0) || (strlen(realFilePath) >= SO_PATH_SIZE))
        ret = -1;
    else{
        sprintf(sSoPath,"%s", realFilePath);
        ret = 0;
    }

    //ret =  GetCurrentDirectory( SO_PATH_SIZE, sSoPath);
    // GetCurrentDirectory return the char number of the string
    if(ret == 0){
        ret = RegSetValueEx( hStarOffice, "Path", 0, REG_SZ,  (LPBYTE) sSoPath, strlen(sSoPath) + 1);
        if(ret == ERROR_SUCCESS)
            ret = 0;
        else
            ret = -1;
    }
    else
        ret = -1;
    RegFlushKey(hStarOffice);
    RegFlushKey(hMozillaPlugins);
    RegCloseKey(hStarOffice);
    RegCloseKey(hMozillaPlugins);
    RegCloseKey(hKeySoftware);
    RegFlushKey(HKEY_LOCAL_MACHINE);

    return ret;
}
}
<commit_msg>INTEGRATION: CWS changefileheader (1.5.698); FILE MERGED 2008/03/31 14:20:09 rt 1.5.698.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: winpluginlib.cpp,v $
 * $Revision: 1.6 $
 *
 * 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.
 *
 ************************************************************************/

#ifdef SVX_DLLIMPLEMENTATION
#undef SVX_DLLIMPLEMENTATION
#endif

#if defined _MSC_VER
#pragma warning(push, 1)
#endif
#include <windows.h>
#if defined _MSC_VER
#pragma warning(pop)
#endif
#include <Winreg.h>
#include <Shlwapi.h>
#include <stdio.h>

#define SO_PATH_SIZE        4096
#define MOZ_PLUGIN_DLL_NAME "npsopluginmi.dll"
extern "C" {
int lc_isInstalled(const  char* realFilePath)
{
    HKEY hKeySoftware;
    HKEY hMozillaPlugins;
    HKEY hStarOffice;
    char sSoPath[SO_PATH_SIZE];
    char sPluginPath[SO_PATH_SIZE];

    LONG ret;
    ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE,  "SOFTWARE",  0,  KEY_READ, &hKeySoftware);
    if(ret != ERROR_SUCCESS){
        ret = RegOpenKeyEx(HKEY_CURRENT_USER,  "SOFTWARE",  0,  KEY_READ, &hKeySoftware);
        if(ret != ERROR_SUCCESS){
            return -1;
        }
    }
    ret = RegOpenKeyEx(hKeySoftware,  "MozillaPlugins",  0,  KEY_READ, &hMozillaPlugins);
    if(ret != ERROR_SUCCESS){
        RegCloseKey(hKeySoftware);
        if( ret == ERROR_FILE_NOT_FOUND)
            return 1;
        else
            return -1;
    }
    ret = RegOpenKeyEx(hMozillaPlugins,  "@sun.com/npsopluginmi;version=1.0",  0,  KEY_READ, &hStarOffice);
    if(ret != ERROR_SUCCESS){
        RegCloseKey(hKeySoftware);
        RegCloseKey(hMozillaPlugins);
        if( ret == ERROR_FILE_NOT_FOUND)
            return 1;
        else
            return -1;
    }

    if((realFilePath == NULL) || (strlen(realFilePath) == 0) || (strlen(realFilePath) >= SO_PATH_SIZE))
        ret = -1;
    else{
        sprintf(sSoPath,"%s", realFilePath);
        ret = 0;
    }
    //ret =  GetCurrentDirectory( SO_PATH_SIZE, sSoPath);
    //ret = GetEnvironmentVariable("prog", sSoPath, SO_PATH_SIZE);
    // GetCurrentDirectory return the char number of the string
    if(ret == 0){
        DWORD  dType = REG_SZ;
        DWORD  dSize = SO_PATH_SIZE;
        ret = RegQueryValueEx (hStarOffice, "Path", NULL,  &dType , (LPBYTE) sPluginPath, &dSize);
        if(ret == ERROR_SUCCESS){
            if(strcmp(sPluginPath, sSoPath) == 0)
                ret = 0;
            else
                ret = 1;
        }
        else
            ret = -1;
    }
    else
        ret = -1;
    RegCloseKey(hStarOffice);
    RegCloseKey(hMozillaPlugins);
    RegCloseKey(hKeySoftware);
    return ret;
}

int lc_uninstallPlugin(const  char*)
{
    HKEY hKeySoftware;
    HKEY hMozillaPlugins;
    HKEY hStarOffice;

    LONG ret;
    ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE,  "SOFTWARE",  0,  KEY_READ|KEY_WRITE, &hKeySoftware);
    if(ret != ERROR_SUCCESS){
        ret = RegOpenKeyEx(HKEY_CURRENT_USER,  "SOFTWARE",  0,  KEY_READ|KEY_WRITE, &hKeySoftware);
        if(ret != ERROR_SUCCESS){
            return -1;
        }
    }
    ret = RegOpenKeyEx(hKeySoftware,  "MozillaPlugins",  0,  KEY_READ|KEY_WRITE, &hMozillaPlugins);
    if(ret != ERROR_SUCCESS){
        RegCloseKey(hKeySoftware);
        if( ret == ERROR_FILE_NOT_FOUND)
            return 0;
        else
            return -1;
    }

    ret = RegOpenKeyEx(hMozillaPlugins,  "@sun.com/npsopluginmi;version=1.0",  0,  KEY_READ|KEY_WRITE, &hStarOffice);
    if(ret != ERROR_SUCCESS){
        RegCloseKey(hKeySoftware);
        RegCloseKey(hMozillaPlugins);
        if( ret == ERROR_FILE_NOT_FOUND)
            return 0;
        else
            return -1;
    }
    RegCloseKey(hStarOffice);
    ret = SHDeleteKey(hMozillaPlugins,  "@sun.com/npsopluginmi;version=1.0");
    if(ret != ERROR_SUCCESS){
        ret = -1;
    }
    RegFlushKey(hMozillaPlugins);
    RegCloseKey(hMozillaPlugins);
    RegCloseKey(hKeySoftware);
    return ret;
}

int lc_installPlugin(const  char* realFilePath)
{
    HKEY hKeySoftware;
    HKEY hMozillaPlugins;
    HKEY hStarOffice;
    char sSoPath[SO_PATH_SIZE];
    DWORD  sState;

    LONG ret;
    ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE,  "SOFTWARE",  0,  KEY_READ|KEY_WRITE, &hKeySoftware);
    if(ret != ERROR_SUCCESS){
        ret = RegOpenKeyEx(HKEY_CURRENT_USER,  "SOFTWARE",  0,  KEY_READ|KEY_WRITE, &hKeySoftware);
        if(ret != ERROR_SUCCESS){
            return -1;
        }
    }
    ret = RegOpenKeyEx(hKeySoftware,  "MozillaPlugins",  0,  KEY_READ|KEY_WRITE, &hMozillaPlugins);
    if(ret != ERROR_SUCCESS){
        RegCreateKeyEx(hKeySoftware,
            "MozillaPlugins",
            0,
            NULL,
            REG_OPTION_NON_VOLATILE,
            KEY_READ|KEY_WRITE,
            NULL,
            &hMozillaPlugins,
            &sState);
    }

    ret = RegCreateKeyEx(hMozillaPlugins,
        "@sun.com/npsopluginmi;version=1.0",
        0,
        NULL,
        REG_OPTION_NON_VOLATILE,
        KEY_READ|KEY_WRITE,
        NULL,
        &hStarOffice,
        &sState);
    if(ret != ERROR_SUCCESS){
        RegCloseKey(hKeySoftware);
        RegCloseKey(hMozillaPlugins);
        return -1;
    }

    RegFlushKey(hStarOffice);
    RegFlushKey(hMozillaPlugins);

    if((realFilePath == NULL) || (strlen(realFilePath) == 0) || (strlen(realFilePath) >= SO_PATH_SIZE))
        ret = -1;
    else{
        sprintf(sSoPath,"%s", realFilePath);
        ret = 0;
    }

    //ret =  GetCurrentDirectory( SO_PATH_SIZE, sSoPath);
    // GetCurrentDirectory return the char number of the string
    if(ret == 0){
        ret = RegSetValueEx( hStarOffice, "Path", 0, REG_SZ,  (LPBYTE) sSoPath, strlen(sSoPath) + 1);
        if(ret == ERROR_SUCCESS)
            ret = 0;
        else
            ret = -1;
    }
    else
        ret = -1;
    RegFlushKey(hStarOffice);
    RegFlushKey(hMozillaPlugins);
    RegCloseKey(hStarOffice);
    RegCloseKey(hMozillaPlugins);
    RegCloseKey(hKeySoftware);
    RegFlushKey(HKEY_LOCAL_MACHINE);

    return ret;
}
}
<|endoftext|>


<commit_before>//// Copyright (C) 2010 and 2011 Marcin Arkadiusz Skrobiranda.
//// All rights reserved.
////
//// Redistribution and use in source and binary forms, with or without
//// modification, are permitted provided that the following conditions
//// are met:
//// 1. Redistributions of source code must retain the above copyright
////    notice, this list of conditions and the following disclaimer.
//// 2. Redistributions in binary form must reproduce the above copyright
////    notice, this list of conditions and the following disclaimer in the
////    documentation and/or other materials provided with the distribution.
//// 3. Neither the name of the project nor the names of its contributors
////    may be used to endorse or promote products derived from this software
////    without specific prior written permission.
////
//// THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS "AS IS" AND
//// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
//// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
//// ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
//// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
//// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
//// OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
//// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
//// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
//// SUCH DAMAGE.
//
//#include "Human.hpp"
//
//namespace GameServer
//{
//namespace Human
//{
//
//Human::Human(
//    Key const & a_key
//)
//    : m_key(a_key)
//{
//}
//
//Key const & Human::getKey() const
//{
//    return m_key;
//}
//
//IDHuman const & Human::getIDHuman() const
//{
//    return m_key.getInternalKey().get<0>();
//}
//
//Experience const & Human::getExperience() const
//{
//    return m_key.getInternalKey().get<1>();
//}
//
//} // namespace Human
//} // namespace GameServer
<commit_msg>Fix: an obsolete file removed.<commit_after><|endoftext|>


<commit_before>// OpenSG example: ClipPlaneCaps
//
// Demonstrates the use of the ClipPlaneChunk, and StencilChunk for capping
// of clipped geometry (e.g. to make a clipped object appear solid).
// See the comments in main() for details on the scene setup used to make this
// work.

#include <vector>

#include <OpenSG/OSGGLUT.h>
#include <OpenSG/OSGConfig.h>
#include <OpenSG/OSGSimpleGeometry.h>
#include <OpenSG/OSGPassiveWindow.h>
#include <OpenSG/OSGSimpleSceneManager.h>
#include <OpenSG/OSGSceneFileHandler.h>

#include <OpenSG/OSGMaterialGroup.h>
#include <OpenSG/OSGChunkMaterial.h>
#include <OpenSG/OSGSimpleMaterial.h>
#include <OpenSG/OSGClipPlaneChunk.h>
#include <OpenSG/OSGStencilChunk.h>

OSG_USING_NAMESPACE

typedef std::vector<NodeRefPtr> VecNodesT;

struct ClipPlaneData
{
    Vec4f _equation;
    bool  _enabled;
};
typedef std::vector<ClipPlaneData> VecClipPlaneData;

struct ClipPlaneDetails
{
    ClipPlaneChunkRefPtr  _clipPlaneChunk;
    NodeRefPtr            _clipPlaneBeacon;
    NodeRefPtr            _planeTrafoNode;
    MaterialGroupRefPtr   _materialCore;
};
typedef std::vector<ClipPlaneDetails> VecClipPlaneDetailsT;

// global state
VecClipPlaneDetailsT  vecClipPlaneDetails;
SimpleSceneManager   *mgr;

// the number of clipping planes supported by the demo
const int iNumClipPlanes = 2;

void createClipPlaneDetails(void)
{
    for (int i = 0; i < iNumClipPlanes; ++i)
    {
        ClipPlaneDetails details;

        //
        // Create clip plane chunk
        //
        details._clipPlaneChunk = ClipPlaneChunk::create();
        details._clipPlaneChunk->setEquation(Vec4f(1,0,0,0));
        details._clipPlaneChunk->setEnable(false);

        // the beacon is only held in a weak pointer by the ClipPlaneChunk,
        // so we need to store it somewhere with a real reference.
        // (This is true for other beacons in the system as well and prevents
        // circular references in the common case where the beacon is a
        // parent of the object).
        details._clipPlaneBeacon = Node::create();
        details._clipPlaneChunk->setBeacon(details._clipPlaneBeacon);

        //
        // Create plane geometry
        //
        NodeRefPtr planeGeoNode = makePlane(10.f, 10.f, 128, 128);

        Matrix mat;
        mat.setIdentity();

        TransformRefPtr transfCore = Transform::create();
        transfCore->setMatrix(mat);

        details._planeTrafoNode = Node::create();
        details._planeTrafoNode->setCore(transfCore);
        details._planeTrafoNode->addChild(planeGeoNode);

        //
        // Create stencil material core
        //
        StencilChunkRefPtr stencilChunk = StencilChunk::create();
        stencilChunk->setClearBuffer(1);
        stencilChunk->setStencilFunc(GL_NEVER);
        stencilChunk->setStencilValue(1);
        stencilChunk->setStencilMask(1);
        stencilChunk->setStencilOpFail(GL_INVERT);
        stencilChunk->setStencilOpZFail(GL_INVERT);
        stencilChunk->setStencilOpZPass(GL_INVERT);

        ChunkMaterialRefPtr mat1 = ChunkMaterial::create();
        mat1->addChunk(stencilChunk);
        mat1->addChunk(details._clipPlaneChunk);
        mat1->setSortKey(2*i + 0);

        details._materialCore = MaterialGroup::create();
        details._materialCore->setMaterial(mat1);

        vecClipPlaneDetails.push_back(details);
    }
}

void destroyClipPlaneDetails(void)
{
    vecClipPlaneDetails.clear();
}

void updateClipPlanes(const VecClipPlaneData& vec)
{
    int sz  = vec.size();

    for (int i = 0; i < iNumClipPlanes; ++i)
    {
        ClipPlaneChunk *clipPlaneChunk =
            vecClipPlaneDetails[i]._clipPlaneChunk;

        clipPlaneChunk->setEnable(false);

        if(i < sz)
        {
            const ClipPlaneData &data = vec[i];

            clipPlaneChunk->setEquation(data._equation);
            clipPlaneChunk->setEnable(data._enabled);

            Matrix mat;
            Vec4f v1(0.f, 0.f, -1.f, 0.f);
            Quaternion q(Vec3f(v1), Vec3f(data._equation));
            mat.setTransform(q);

            Transform *transformCore = dynamic_cast<Transform *>(
                vecClipPlaneDetails[i]._planeTrafoNode->getCore());

            transformCore->setMatrix(mat);
        }
    }
}

// redraw the window
void display(void)
{
    // render

    mgr->redraw();

    // all done, swap -- need to do this by hand as we are using a PassiveWindow
    glutSwapBuffers();
}

// react to size changes
void reshape(int w, int h)
{
    mgr->resize(w,h);
    glutPostRedisplay();
}

// react to mouse button presses
void mouse(int button, int state, int x, int y)
{
    if (state)
        mgr->mouseButtonRelease(button, x, y);
    else
        mgr->mouseButtonPress(button, x, y);

    glutPostRedisplay();
}

// react to mouse motions with pressed buttons
void motion(int x, int y)
{
    mgr->mouseMove(x, y);
    glutPostRedisplay();
}

// react to keys
void keyboard(unsigned char k, int, int)
{
    switch(k)
    {
    case 27:    destroyClipPlaneDetails();
                delete mgr;

                osgExit();
                exit(0);
                break;
    }
}

int doMain(int argc, char **argv)
{
    osgInit(argc,argv);

    // GLUT init
    glutInit(&argc, argv);

    glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_STENCIL | GLUT_DOUBLE);

    glutCreateWindow("OpenSG - ClipPlaneCaps");

    glutReshapeFunc(reshape);
    glutDisplayFunc(display);
    glutIdleFunc(display);
    glutMouseFunc(mouse);
    glutMotionFunc(motion);
    glutKeyboardFunc(keyboard);

    PassiveWindowRefPtr pwin = PassiveWindow::create();
    pwin->init();

    // create the SimpleSceneManager helper
    mgr = new SimpleSceneManager;

    // create the window and initial camera/viewport
    mgr->setWindow(pwin);

    //
    // We need 3 material groups for the clip plane capping trick:
    //
    //                        scene
    //                          |
    //     +--------------------+--------------------+
    //     |                    |                    |
    //  group1 (mat1)        group2 (mat2)        group3 (mat3)
    //     |                    |                    |
    // geometry (geo1)      geometry (geo2)      geometry (geo1)
    //
    //    geo1 : actual geometry to draw
    //    geo2 : plane geometry coincident with the clip plane
    //
    //    mat1 : has a stencil chunk that clears the stencil buffer first,
    //           than does the inversion, and has
    //           a clip plane chunk that enables one clip plane. Sortkey 0.
    //    mat2 : has a stencil chunk and settings for drawing the clip plane
    //           geometry. All clip planes but the
    //           one coincident with the plane are activated. Sortkey 1.
    //    mat3 : the material used for the actual geometry. All clip planes
    //           are activated. Sortkey 3.
    //
    //    For each active clip plane copies of the left two branches need to
    //    be added.
    //

    //
    // Implementation details:
    //      For each clipplane we provide a ClipPlaneChunk, a MaterialGroup
    //      mat1 and the plane geometry geo2
    //      conveniently in a vector of type VecClipPlaneDetailsT. The next
    //      function call initializes this
    //      data structure. Later on, we provide actual details for the
    //      vector elements.
    //
    createClipPlaneDetails();

    GeometryRefPtr geo1 = makeTorusGeo(0.2, 2, 8, 16);

    NodeRefPtr geometryNode = Node::create();
    geometryNode->setCore(geo1);

    VecNodesT vecMaterialNodes1;
    VecNodesT vecMaterialNodes2;
    for(int i = 0; i < iNumClipPlanes; ++i)
    {
        NodeRefPtr geomNode = Node::create();
        geomNode->setCore(geo1);

        NodeRefPtr          materialNode1 = Node::create();
        MaterialGroupRefPtr mgrp1         = vecClipPlaneDetails[i]._materialCore;

        materialNode1->setCore(mgrp1);
        materialNode1->addChild(geomNode);

        vecMaterialNodes1.push_back(materialNode1);

        NodeRefPtr         materialNode2 = Node        ::create();
        StencilChunkRefPtr stencilChunk  = StencilChunk::create();

        stencilChunk->setClearBuffer(2);
        stencilChunk->setStencilFunc(GL_EQUAL);
        stencilChunk->setStencilValue(1);
        stencilChunk->setStencilMask(1);
        stencilChunk->setStencilOpFail(GL_KEEP);
        stencilChunk->setStencilOpZFail(GL_ZERO);
        stencilChunk->setStencilOpZPass(GL_ZERO);

        SimpleMaterialRefPtr mat2 = SimpleMaterial::create();

        mat2->setDiffuse(Color3f(0,1,0));
        mat2->setSpecular(Color3f(1,1,1));
        mat2->setLit(true);

        for(int j = 0; j < iNumClipPlanes; ++j)
        {
            if(i != j)
                mat2->addChunk(vecClipPlaneDetails[j]._clipPlaneChunk);
        }
        mat2->addChunk(stencilChunk);
        mat2->setSortKey(2*i + 1);

        MaterialGroupRefPtr mgrp2 = MaterialGroup::create();
        mgrp2->setMaterial(mat2);

        materialNode2->setCore(mgrp2);
        materialNode2->addChild(vecClipPlaneDetails[i]._planeTrafoNode);

        vecMaterialNodes2.push_back(materialNode2);
    }

    NodeRefPtr           materialNode3 = Node          ::create();
    SimpleMaterialRefPtr mat3          = SimpleMaterial::create();

    mat3->setDiffuse(Color3f(1,0,0));
    mat3->setSpecular(Color3f(1,1,1));
    mat3->setLit(true);

    for(int i = 0; i < iNumClipPlanes; ++i)
    {
        mat3->addChunk(vecClipPlaneDetails[i]._clipPlaneChunk);
    }
    mat3->setSortKey(2*(iNumClipPlanes-1) + 2);

    MaterialGroupRefPtr mgrp3 = MaterialGroup::create();
    mgrp3->setMaterial(mat3);

    materialNode3->setCore(mgrp3);
    materialNode3->addChild(geometryNode);

    // create the scene
    NodeRefPtr scene = Node::create();
    scene->setCore(Group::create());

    for (int i = 0; i < iNumClipPlanes; ++i)
    {
        scene->addChild(vecMaterialNodes1[i]);
        scene->addChild(vecMaterialNodes2[i]);
    }

    scene->addChild(materialNode3);

    //
    // Build concrete clipping planes
    //
    ClipPlaneData data1;
    ClipPlaneData data2;

    data1._equation = Vec4f(0,0,1,0);
    data1._enabled  = true;

    data2._equation = Vec4f(1,0,0,0);
    data2._enabled  = true;

    VecClipPlaneData vecData;
    vecData.push_back(data1);
    vecData.push_back(data2);

    updateClipPlanes(vecData);

    // tell the manager what to manage
    mgr->setRoot(scene);

    // show the whole scene
    mgr->showAll();
    mgr->redraw();
}

int main(int argc, char *argv[])
{
    doMain(argc, argv);

    // GLUT main loop
    glutMainLoop();

    return 0;
}
<commit_msg>added: make clip planes moveable with keys<commit_after>// OpenSG example: ClipPlaneCaps
//
// Demonstrates the use of the ClipPlaneChunk, and StencilChunk for capping
// of clipped geometry (e.g. to make a clipped object appear solid).
// See the comments in main() for details on the scene setup used to make this
// work.

#include <vector>

#include <OpenSG/OSGGLUT.h>
#include <OpenSG/OSGConfig.h>
#include <OpenSG/OSGSimpleGeometry.h>
#include <OpenSG/OSGPassiveWindow.h>
#include <OpenSG/OSGSimpleSceneManager.h>
#include <OpenSG/OSGSceneFileHandler.h>

#include <OpenSG/OSGMaterialGroup.h>
#include <OpenSG/OSGChunkMaterial.h>
#include <OpenSG/OSGSimpleMaterial.h>
#include <OpenSG/OSGClipPlaneChunk.h>
#include <OpenSG/OSGStencilChunk.h>

OSG_USING_NAMESPACE

typedef std::vector<NodeRefPtr> VecNodesT;

struct ClipPlaneData
{
    Vec4f _equation;
    bool  _enabled;
};
typedef std::vector<ClipPlaneData> VecClipPlaneData;

struct ClipPlaneDetails
{
    ClipPlaneChunkRefPtr  _clipPlaneChunk;
    NodeRefPtr            _clipPlaneBeacon;
    NodeRefPtr            _planeTrafoNode;
    MaterialGroupRefPtr   _materialCore;
};
typedef std::vector<ClipPlaneDetails> VecClipPlaneDetailsT;

// global state
VecClipPlaneDetailsT  vecClipPlaneDetails;
VecClipPlaneData      vecClipPlaneData;
SimpleSceneManager   *mgr;

// the number of clipping planes supported by the demo
const int iNumClipPlanes = 2;

void createClipPlaneDetails(void)
{
    for (int i = 0; i < iNumClipPlanes; ++i)
    {
        ClipPlaneDetails details;

        //
        // Create clip plane chunk
        //
        details._clipPlaneChunk = ClipPlaneChunk::create();
        details._clipPlaneChunk->setEquation(Vec4f(1,0,0,0));
        details._clipPlaneChunk->setEnable(false);

        // the beacon is only held in a weak pointer by the ClipPlaneChunk,
        // so we need to store it somewhere with a real reference.
        // (This is true for other beacons in the system as well and prevents
        // circular references in the common case where the beacon is a
        // parent of the object).
        details._clipPlaneBeacon = Node::create();
        details._clipPlaneChunk->setBeacon(details._clipPlaneBeacon);

        //
        // Create plane geometry
        //
        NodeRefPtr planeGeoNode = makePlane(10.f, 10.f, 128, 128);

        Matrix mat;
        mat.setIdentity();

        TransformRefPtr transfCore = Transform::create();
        transfCore->setMatrix(mat);

        details._planeTrafoNode = Node::create();
        details._planeTrafoNode->setCore(transfCore);
        details._planeTrafoNode->addChild(planeGeoNode);

        //
        // Create stencil material core
        //
        StencilChunkRefPtr stencilChunk = StencilChunk::create();
        stencilChunk->setClearBuffer(1);
        stencilChunk->setStencilFunc(GL_NEVER);
        stencilChunk->setStencilValue(1);
        stencilChunk->setStencilMask(1);
        stencilChunk->setStencilOpFail(GL_INVERT);
        stencilChunk->setStencilOpZFail(GL_INVERT);
        stencilChunk->setStencilOpZPass(GL_INVERT);

        ChunkMaterialRefPtr mat1 = ChunkMaterial::create();
        mat1->addChunk(stencilChunk);
        mat1->addChunk(details._clipPlaneChunk);
        mat1->setSortKey(2*i + 0);

        details._materialCore = MaterialGroup::create();
        details._materialCore->setMaterial(mat1);

        vecClipPlaneDetails.push_back(details);
    }
}

void destroyClipPlaneDetails(void)
{
    vecClipPlaneDetails.clear();
}

void updateClipPlanes(const VecClipPlaneData& vec)
{
    int sz  = vec.size();

    for (int i = 0; i < iNumClipPlanes; ++i)
    {
        ClipPlaneChunk *clipPlaneChunk =
            vecClipPlaneDetails[i]._clipPlaneChunk;

        clipPlaneChunk->setEnable(false);

        if(i < sz)
        {
            const ClipPlaneData &data = vec[i];

            clipPlaneChunk->setEquation(data._equation);
            clipPlaneChunk->setEnable(data._enabled);

            Matrix rotMat;
            Vec4f v1(0.f, 0.f, -1.f, 0.f);
            Quaternion q(Vec3f(v1), Vec3f(data._equation));
            rotMat.setTransform(q);

            Matrix mat;
            Vec3f v2(0.0f, 0.0f, data._equation[3]);
            mat.setTranslate(v2);

            mat.multLeft(rotMat);

            Transform *transformCore = dynamic_cast<Transform *>(
                vecClipPlaneDetails[i]._planeTrafoNode->getCore());

            transformCore->setMatrix(mat);
        }
    }
}

// redraw the window
void display(void)
{
    // render

    mgr->redraw();

    // all done, swap -- need to do this by hand as we are using a PassiveWindow
    glutSwapBuffers();
}

// react to size changes
void reshape(int w, int h)
{
    mgr->resize(w,h);
    glutPostRedisplay();
}

// react to mouse button presses
void mouse(int button, int state, int x, int y)
{
    if (state)
        mgr->mouseButtonRelease(button, x, y);
    else
        mgr->mouseButtonPress(button, x, y);

    glutPostRedisplay();
}

// react to mouse motions with pressed buttons
void motion(int x, int y)
{
    mgr->mouseMove(x, y);
    glutPostRedisplay();
}

// react to keys
void keyboard(unsigned char k, int, int)
{
    static Real32 val0 = 0.f;
    static Real32 val1 = 0.f;

    switch(k)
    {
        case 'a':
        {
            vecClipPlaneData[0]._enabled = !vecClipPlaneData[0]._enabled;
            updateClipPlanes(vecClipPlaneData);
        }
        break;
        case 's':
        {
            vecClipPlaneData[1]._enabled = !vecClipPlaneData[1]._enabled;
            updateClipPlanes(vecClipPlaneData);
        }
        break;
        case 'y':
        case 'z':
        {
            val0 -= 0.2;
            vecClipPlaneData[0]._equation[3] = val0;
            updateClipPlanes(vecClipPlaneData);
        }
        break;
        case 'x':
        {
            val0 += 0.2;
            vecClipPlaneData[0]._equation[3] = val0;
            updateClipPlanes(vecClipPlaneData);
        }
        break;
        case 'n':
        {
            val1 -= 0.2;
            vecClipPlaneData[1]._equation[3] = val1;
            updateClipPlanes(vecClipPlaneData);
        }
        break;
        case 'm':
        {
            val1 += 0.2;
            vecClipPlaneData[1]._equation[3] = val1;
            updateClipPlanes(vecClipPlaneData);
        }
        break;

        case 27:
        {
            destroyClipPlaneDetails();
            delete mgr;

            osgExit();
            exit(0);
        }
    }
}

int doMain(int argc, char **argv)
{
    osgInit(argc,argv);

    // GLUT init
    glutInit(&argc, argv);

    glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_STENCIL | GLUT_DOUBLE);

    glutCreateWindow("OpenSG - ClipPlaneCaps");

    glutReshapeFunc(reshape);
    glutDisplayFunc(display);
    glutIdleFunc(display);
    glutMouseFunc(mouse);
    glutMotionFunc(motion);
    glutKeyboardFunc(keyboard);

    PassiveWindowRefPtr pwin = PassiveWindow::create();
    pwin->init();

    // create the SimpleSceneManager helper
    mgr = new SimpleSceneManager;

    // create the window and initial camera/viewport
    mgr->setWindow(pwin);

    //
    // We need 3 material groups for the clip plane capping trick:
    //
    //                        scene
    //                          |
    //     +--------------------+--------------------+
    //     |                    |                    |
    //  group1 (mat1)        group2 (mat2)        group3 (mat3)
    //     |                    |                    |
    // geometry (geo1)      geometry (geo2)      geometry (geo1)
    //
    //    geo1 : actual geometry to draw
    //    geo2 : plane geometry coincident with the clip plane
    //
    //    mat1 : has a stencil chunk that clears the stencil buffer first,
    //           than does the inversion, and has
    //           a clip plane chunk that enables one clip plane. Sortkey 0.
    //    mat2 : has a stencil chunk and settings for drawing the clip plane
    //           geometry. All clip planes but the
    //           one coincident with the plane are activated. Sortkey 1.
    //    mat3 : the material used for the actual geometry. All clip planes
    //           are activated. Sortkey 3.
    //
    //    For each active clip plane copies of the left two branches need to
    //    be added.
    //

    //
    // Implementation details:
    //      For each clipplane we provide a ClipPlaneChunk, a MaterialGroup
    //      mat1 and the plane geometry geo2
    //      conveniently in a vector of type VecClipPlaneDetailsT. The next
    //      function call initializes this
    //      data structure. Later on, we provide actual details for the
    //      vector elements.
    //
    createClipPlaneDetails();

    GeometryRefPtr geo1 = makeTorusGeo(0.5, 3, 8, 16);

    NodeRefPtr geometryNode = Node::create();
    geometryNode->setCore(geo1);

    VecNodesT vecMaterialNodes1;
    VecNodesT vecMaterialNodes2;
    for(int i = 0; i < iNumClipPlanes; ++i)
    {
        NodeRefPtr geomNode = Node::create();
        geomNode->setCore(geo1);

        NodeRefPtr          materialNode1 = Node::create();
        MaterialGroupRefPtr mgrp1         = vecClipPlaneDetails[i]._materialCore;

        materialNode1->setCore(mgrp1);
        materialNode1->addChild(geomNode);

        vecMaterialNodes1.push_back(materialNode1);

        NodeRefPtr         materialNode2 = Node        ::create();
        StencilChunkRefPtr stencilChunk  = StencilChunk::create();

        stencilChunk->setClearBuffer(2);
        stencilChunk->setStencilFunc(GL_EQUAL);
        stencilChunk->setStencilValue(1);
        stencilChunk->setStencilMask(1);
        stencilChunk->setStencilOpFail(GL_KEEP);
        stencilChunk->setStencilOpZFail(GL_ZERO);
        stencilChunk->setStencilOpZPass(GL_ZERO);

        SimpleMaterialRefPtr mat2 = SimpleMaterial::create();

        mat2->setDiffuse(Color3f(0,1,0));
        mat2->setSpecular(Color3f(1,1,1));
        mat2->setLit(true);

        for(int j = 0; j < iNumClipPlanes; ++j)
        {
            if(i != j)
                mat2->addChunk(vecClipPlaneDetails[j]._clipPlaneChunk);
        }
        mat2->addChunk(stencilChunk);
        mat2->setSortKey(2*i + 1);

        MaterialGroupRefPtr mgrp2 = MaterialGroup::create();
        mgrp2->setMaterial(mat2);

        materialNode2->setCore(mgrp2);
        materialNode2->addChild(vecClipPlaneDetails[i]._planeTrafoNode);

        vecMaterialNodes2.push_back(materialNode2);
    }

    NodeRefPtr           materialNode3 = Node          ::create();
    SimpleMaterialRefPtr mat3          = SimpleMaterial::create();

    mat3->setDiffuse(Color3f(1,0,0));
    mat3->setSpecular(Color3f(1,1,1));
    mat3->setLit(true);

    for(int i = 0; i < iNumClipPlanes; ++i)
    {
        mat3->addChunk(vecClipPlaneDetails[i]._clipPlaneChunk);
    }
    mat3->setSortKey(2*(iNumClipPlanes-1) + 2);

    MaterialGroupRefPtr mgrp3 = MaterialGroup::create();
    mgrp3->setMaterial(mat3);

    materialNode3->setCore(mgrp3);
    materialNode3->addChild(geometryNode);

    // create the scene
    NodeRefPtr scene = Node::create();
    scene->setCore(Group::create());

    for (int i = 0; i < iNumClipPlanes; ++i)
    {
        scene->addChild(vecMaterialNodes1[i]);
        scene->addChild(vecMaterialNodes2[i]);
    }

    scene->addChild(materialNode3);

    //
    // Build concrete clipping planes
    //
    ClipPlaneData data1;
    ClipPlaneData data2;

    data1._equation = Vec4f(0,0,1,0);
    data1._enabled  = true;

    data2._equation = Vec4f(1,0,0,0);
    data2._enabled  = true;

    vecClipPlaneData.push_back(data1);
    vecClipPlaneData.push_back(data2);

    updateClipPlanes(vecClipPlaneData);

    // tell the manager what to manage
    mgr->setRoot(scene);

    // show the whole scene
    mgr->showAll();
    mgr->redraw();
}

int main(int argc, char *argv[])
{
    doMain(argc, argv);

    // GLUT main loop
    glutMainLoop();

    return 0;
}
<|endoftext|>


<commit_before>//===-- Debug.cpp - An easy way to add debug output to your code ----------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements a handy way of adding debugging information to your
// code, without it being enabled all of the time, and without having to add
// command line options to enable it.
//
// In particular, just wrap your code with the DEBUG() macro, and it will be
// enabled automatically if you specify '-debug' on the command-line.
// Alternatively, you can also use the SET_DEBUG_TYPE("foo") macro to specify
// that your debug code belongs to class "foo".  Then, on the command line, you
// can specify '-debug-only=foo' to enable JUST the debug information for the
// foo class.
//
// When compiling without assertions, the -debug-* options and all code in
// DEBUG() statements disappears, so it does not affect the runtime of the code.
//
//===----------------------------------------------------------------------===//

#include "llvm/Support/Debug.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/circular_raw_ostream.h"

using namespace llvm;

// All Debug.h functionality is a no-op in NDEBUG mode.
#ifndef NDEBUG
bool llvm::DebugFlag;  // DebugFlag - Exported boolean set by the -debug option

// -debug - Command line option to enable the DEBUG statements in the passes.
// This flag may only be enabled in debug builds.
static cl::opt<bool, true>
Debug("debug", cl::desc("Enable debug output"), cl::Hidden,
      cl::location(DebugFlag));

// -debug-buffer-size - Buffer the last N characters of debug output
//until program termination.
static cl::opt<unsigned>
DebugBufferSize("debug-buffer-size",
                cl::desc("Buffer the last N characters of debug output "
                         "until program termination. "
                         "[default 0 -- immediate print-out]"),
                cl::Hidden,
                cl::init(0));

static std::string CurrentDebugType;

namespace {

struct DebugOnlyOpt {
  void operator=(const std::string &Val) const {
    DebugFlag |= !Val.empty();
    CurrentDebugType = Val;
  }
};

}

static DebugOnlyOpt DebugOnlyOptLoc;

static cl::opt<DebugOnlyOpt, true, cl::parser<std::string> >
DebugOnly("debug-only", cl::desc("Enable a specific type of debug output"),
          cl::Hidden, cl::value_desc("debug string"),
          cl::location(DebugOnlyOptLoc), cl::ValueRequired);

// Signal handlers - dump debug output on termination.
static void debug_user_sig_handler(void *Cookie) {
  // This is a bit sneaky.  Since this is under #ifndef NDEBUG, we
  // know that debug mode is enabled and dbgs() really is a
  // circular_raw_ostream.  If NDEBUG is defined, then dbgs() ==
  // errs() but this will never be invoked.
  llvm::circular_raw_ostream *dbgout =
    static_cast<llvm::circular_raw_ostream *>(&llvm::dbgs());
  dbgout->flushBufferWithBanner();
}

// isCurrentDebugType - Return true if the specified string is the debug type
// specified on the command line, or if none was specified on the command line
// with the -debug-only=X option.
//
bool llvm::isCurrentDebugType(const char *DebugType) {
  return CurrentDebugType.empty() || DebugType == CurrentDebugType;
}

/// setCurrentDebugType - Set the current debug type, as if the -debug-only=X
/// option were specified.  Note that DebugFlag also needs to be set to true for
/// debug output to be produced.
///
void llvm::setCurrentDebugType(const char *Type) {
  CurrentDebugType = Type;
}

/// dbgs - Return a circular-buffered debug stream.
raw_ostream &llvm::dbgs() {
  // Do one-time initialization in a thread-safe way.
  static struct dbgstream {
    circular_raw_ostream strm;

    dbgstream() :
        strm(errs(), "*** Debug Log Output ***\n",
             (!EnableDebugBuffering || !DebugFlag) ? 0 : DebugBufferSize) {
      if (EnableDebugBuffering && DebugFlag && DebugBufferSize != 0)
        // TODO: Add a handler for SIGUSER1-type signals so the user can
        // force a debug dump.
        sys::AddSignalHandler(&debug_user_sig_handler, nullptr);
      // Otherwise we've already set the debug stream buffer size to
      // zero, disabling buffering so it will output directly to errs().
    }
  } thestrm;

  return thestrm.strm;
}

#else
// Avoid "has no symbols" warning.
namespace llvm {
  /// dbgs - Return errs().
  raw_ostream &dbgs() {
    return errs();
  }
}

#endif

/// EnableDebugBuffering - Turn on signal handler installation.
///
bool llvm::EnableDebugBuffering = false;
<commit_msg>Removing static initializer from Debug.cpp by converting to a ManagedStatic.<commit_after>//===-- Debug.cpp - An easy way to add debug output to your code ----------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements a handy way of adding debugging information to your
// code, without it being enabled all of the time, and without having to add
// command line options to enable it.
//
// In particular, just wrap your code with the DEBUG() macro, and it will be
// enabled automatically if you specify '-debug' on the command-line.
// Alternatively, you can also use the SET_DEBUG_TYPE("foo") macro to specify
// that your debug code belongs to class "foo".  Then, on the command line, you
// can specify '-debug-only=foo' to enable JUST the debug information for the
// foo class.
//
// When compiling without assertions, the -debug-* options and all code in
// DEBUG() statements disappears, so it does not affect the runtime of the code.
//
//===----------------------------------------------------------------------===//

#include "llvm/Support/Debug.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/circular_raw_ostream.h"
#include "llvm/Support/ManagedStatic.h"

using namespace llvm;

// All Debug.h functionality is a no-op in NDEBUG mode.
#ifndef NDEBUG
bool llvm::DebugFlag;  // DebugFlag - Exported boolean set by the -debug option

// -debug - Command line option to enable the DEBUG statements in the passes.
// This flag may only be enabled in debug builds.
static cl::opt<bool, true>
Debug("debug", cl::desc("Enable debug output"), cl::Hidden,
      cl::location(DebugFlag));

// -debug-buffer-size - Buffer the last N characters of debug output
//until program termination.
static cl::opt<unsigned>
DebugBufferSize("debug-buffer-size",
                cl::desc("Buffer the last N characters of debug output "
                         "until program termination. "
                         "[default 0 -- immediate print-out]"),
                cl::Hidden,
                cl::init(0));

static ManagedStatic<std::string> CurrentDebugType;

namespace {

struct DebugOnlyOpt {
  void operator=(const std::string &Val) const {
    DebugFlag |= !Val.empty();
    *CurrentDebugType = Val;
  }
};

}

static DebugOnlyOpt DebugOnlyOptLoc;

static cl::opt<DebugOnlyOpt, true, cl::parser<std::string> >
DebugOnly("debug-only", cl::desc("Enable a specific type of debug output"),
          cl::Hidden, cl::value_desc("debug string"),
          cl::location(DebugOnlyOptLoc), cl::ValueRequired);

// Signal handlers - dump debug output on termination.
static void debug_user_sig_handler(void *Cookie) {
  // This is a bit sneaky.  Since this is under #ifndef NDEBUG, we
  // know that debug mode is enabled and dbgs() really is a
  // circular_raw_ostream.  If NDEBUG is defined, then dbgs() ==
  // errs() but this will never be invoked.
  llvm::circular_raw_ostream *dbgout =
    static_cast<llvm::circular_raw_ostream *>(&llvm::dbgs());
  dbgout->flushBufferWithBanner();
}

// isCurrentDebugType - Return true if the specified string is the debug type
// specified on the command line, or if none was specified on the command line
// with the -debug-only=X option.
//
bool llvm::isCurrentDebugType(const char *DebugType) {
  return CurrentDebugType->empty() || DebugType == *CurrentDebugType;
}

/// setCurrentDebugType - Set the current debug type, as if the -debug-only=X
/// option were specified.  Note that DebugFlag also needs to be set to true for
/// debug output to be produced.
///
void llvm::setCurrentDebugType(const char *Type) {
  *CurrentDebugType = Type;
}

/// dbgs - Return a circular-buffered debug stream.
raw_ostream &llvm::dbgs() {
  // Do one-time initialization in a thread-safe way.
  static struct dbgstream {
    circular_raw_ostream strm;

    dbgstream() :
        strm(errs(), "*** Debug Log Output ***\n",
             (!EnableDebugBuffering || !DebugFlag) ? 0 : DebugBufferSize) {
      if (EnableDebugBuffering && DebugFlag && DebugBufferSize != 0)
        // TODO: Add a handler for SIGUSER1-type signals so the user can
        // force a debug dump.
        sys::AddSignalHandler(&debug_user_sig_handler, nullptr);
      // Otherwise we've already set the debug stream buffer size to
      // zero, disabling buffering so it will output directly to errs().
    }
  } thestrm;

  return thestrm.strm;
}

#else
// Avoid "has no symbols" warning.
namespace llvm {
  /// dbgs - Return errs().
  raw_ostream &dbgs() {
    return errs();
  }
}

#endif

/// EnableDebugBuffering - Turn on signal handler installation.
///
bool llvm::EnableDebugBuffering = false;
<|endoftext|>