<commit_before>#include "xchainer/native/native_device.h"

#include <cassert>
#include <cstdint>

#ifdef XCHAINER_ENABLE_BLAS
#include <cblas.h>
#endif  // XCHAINER_ENABLE_BLAS

#include "xchainer/array.h"
#include "xchainer/device.h"
#include "xchainer/dtype.h"
#include "xchainer/indexable_array.h"
#include "xchainer/native/elementwise.h"
#include "xchainer/routines/creation.h"
#include "xchainer/shape.h"

namespace xchainer {
namespace native {

namespace {

#ifdef XCHAINER_ENABLE_BLAS
// Dispatch gemm routines based on the element type T
template <typename T>
struct GemmImpl;

template <>
struct GemmImpl<float> {
    template <typename... Args>
    void operator()(Args&&... args) const {
        cblas_sgemm(std::forward<Args>(args)...);
    }
};

template <>
struct GemmImpl<double> {
    template <typename... Args>
    void operator()(Args&&... args) const {
        cblas_dgemm(std::forward<Args>(args)...);
    }
};

struct GemmInputLayout {
    int64_t ld = 0;
    CBLAS_TRANSPOSE trans = CblasNoTrans;

    // Makes the array C or Fortran contiguous and configure leading dimension and transposition accordingly.
    Array Configure(const Array& a) {
        assert(a.ndim() == 2);
        if (a.strides()[0] == a.item_size() && a.strides()[0] * a.shape()[0] == a.strides()[1]) {
            // Fortran contiguous
            ld = a.shape()[0];
            trans = CblasTrans;
            return a;
        }
        // Force C contiguous
        ld = a.shape()[1];
        return AsContiguousArray(a);
    }
};

void Gemm(const Array& a, const Array& b, const Array& out) {
    assert(a.ndim() == 2);
    assert(b.ndim() == 2);
    assert(out.ndim() == 2);
    assert(out.dtype() == Dtype::kFloat32 || out.dtype() == Dtype::kFloat64);

    int64_t m = a.shape()[0];
    int64_t k = a.shape()[1];
    int64_t n = b.shape()[1];
    assert(b.shape()[0] == k);
    assert(out.shape()[0] == m);
    assert(out.shape()[1] == n);

    bool is_out_contiguous = out.IsContiguous();
    Array out_contiguous = is_out_contiguous ? out : EmptyLike(out, out.device());

    auto gemm_impl = [&](auto pt) {
        using T = typename decltype(pt)::type;

        GemmInputLayout a_layout;
        GemmInputLayout b_layout;
        Array a_config = a_layout.Configure(a);
        Array b_config = b_layout.Configure(b);

        const T one = 1;
        const T zero = 0;
        const T* a_ptr = internal::GetRawOffsetData<const T>(a_config);
        const T* b_ptr = internal::GetRawOffsetData<const T>(b_config);
        T* out_ptr = internal::GetRawOffsetData<T>(out_contiguous);
        GemmImpl<T>{}(
                CblasRowMajor, a_layout.trans, b_layout.trans, m, n, k, one, a_ptr, a_layout.ld, b_ptr, b_layout.ld, zero, out_ptr, n);
    };

    if (a.dtype() == Dtype::kFloat32) {
        gemm_impl(PrimitiveType<float>{});
    } else {
        assert(a.dtype() == Dtype::kFloat64);
        gemm_impl(PrimitiveType<double>{});
    }

    if (!is_out_contiguous) {
        out.device().Copy(out_contiguous, out);
    }
}
#endif  // XCHAINER_ENABLE_BLAS

void DotCheckNdim(int8_t ndim) {
    // TODO(sonots): Support ndim >= 2
    if (ndim != 2) {
        throw DimensionError{"XChainer dot supports only 2-dimensional arrays."};
    }
}

}  // namespace

void NativeDevice::Dot(const Array& a, const Array& b, const Array& out) {
    CheckDevicesCompatible(a, b, out);

    DotCheckNdim(a.ndim());
    DotCheckNdim(b.ndim());
    DotCheckNdim(out.ndim());

#ifdef XCHAINER_ENABLE_BLAS
    if (out.dtype() == Dtype::kFloat32 || out.dtype() == Dtype::kFloat64) {
        Gemm(a, b, out);
        return;
    }
#endif  // XCHAINER_ENABLE_BLAS

    out.Fill(0);
    VisitDtype(out.dtype(), [&](auto pt) {
        using T = typename decltype(pt)::type;
        IndexableArray<const T, 2> a_iarray{a};
        IndexableArray<const T, 2> b_iarray{b};
        IndexableArray<T, 2> out_iarray{out};

        int64_t m = a.shape()[0];
        int64_t k = a.shape()[1];
        int64_t n = b.shape()[1];
        assert(b.shape()[0] == k);
        assert(out.shape()[0] == m);
        assert(out.shape()[1] == n);

        for (int64_t i = 0; i < m; ++i) {
            for (int64_t l = 0; l < k; ++l) {
                int64_t a_i_l[] = {i, l};
                T a_value = a_iarray[a_i_l];
                for (int64_t j = 0; j < n; ++j) {
                    int64_t out_i_j[] = {i, j};
                    int64_t b_l_j[] = {l, j};
                    out_iarray[out_i_j] += a_value * b_iarray[b_l_j];
                }
            }
        }
    });
}

}  // namespace native
}  // namespace xchainer
<commit_msg>trivial cleanup<commit_after>#include "xchainer/native/native_device.h"

#include <cassert>
#include <cstdint>

#ifdef XCHAINER_ENABLE_BLAS
#include <cblas.h>
#endif  // XCHAINER_ENABLE_BLAS

#include "xchainer/array.h"
#include "xchainer/device.h"
#include "xchainer/dtype.h"
#include "xchainer/indexable_array.h"
#include "xchainer/native/elementwise.h"
#include "xchainer/routines/creation.h"
#include "xchainer/shape.h"

namespace xchainer {
namespace native {

#ifdef XCHAINER_ENABLE_BLAS
namespace {

// Dispatch gemm routines based on the element type T
template <typename T>
struct GemmImpl;

template <>
struct GemmImpl<float> {
    template <typename... Args>
    void operator()(Args&&... args) const {
        cblas_sgemm(std::forward<Args>(args)...);
    }
};

template <>
struct GemmImpl<double> {
    template <typename... Args>
    void operator()(Args&&... args) const {
        cblas_dgemm(std::forward<Args>(args)...);
    }
};

struct GemmInputLayout {
    int64_t ld = 0;
    CBLAS_TRANSPOSE trans = CblasNoTrans;

    // Makes the array C or Fortran contiguous and configure leading dimension and transposition accordingly.
    Array Configure(const Array& a) {
        assert(a.ndim() == 2);
        if (a.strides()[0] == a.item_size() && a.strides()[0] * a.shape()[0] == a.strides()[1]) {
            // Fortran contiguous
            ld = a.shape()[0];
            trans = CblasTrans;
            return a;
        }
        // Force C contiguous
        ld = a.shape()[1];
        return AsContiguousArray(a);
    }
};

void Gemm(const Array& a, const Array& b, const Array& out) {
    assert(a.ndim() == 2);
    assert(b.ndim() == 2);
    assert(out.ndim() == 2);
    assert(out.dtype() == Dtype::kFloat32 || out.dtype() == Dtype::kFloat64);

    int64_t m = a.shape()[0];
    int64_t k = a.shape()[1];
    int64_t n = b.shape()[1];
    assert(b.shape()[0] == k);
    assert(out.shape()[0] == m);
    assert(out.shape()[1] == n);

    bool is_out_contiguous = out.IsContiguous();
    Array out_contiguous = is_out_contiguous ? out : EmptyLike(out, out.device());

    auto gemm_impl = [&](auto pt) {
        using T = typename decltype(pt)::type;

        GemmInputLayout a_layout;
        GemmInputLayout b_layout;
        Array a_config = a_layout.Configure(a);
        Array b_config = b_layout.Configure(b);

        const T one = 1;
        const T zero = 0;
        const T* a_ptr = internal::GetRawOffsetData<const T>(a_config);
        const T* b_ptr = internal::GetRawOffsetData<const T>(b_config);
        T* out_ptr = internal::GetRawOffsetData<T>(out_contiguous);
        GemmImpl<T>{}(
                CblasRowMajor, a_layout.trans, b_layout.trans, m, n, k, one, a_ptr, a_layout.ld, b_ptr, b_layout.ld, zero, out_ptr, n);
    };

    if (a.dtype() == Dtype::kFloat32) {
        gemm_impl(PrimitiveType<float>{});
    } else {
        assert(a.dtype() == Dtype::kFloat64);
        gemm_impl(PrimitiveType<double>{});
    }

    if (!is_out_contiguous) {
        out.device().Copy(out_contiguous, out);
    }
}

}  // namespace
#endif  // XCHAINER_ENABLE_BLAS

void NativeDevice::Dot(const Array& a, const Array& b, const Array& out) {
    CheckDevicesCompatible(a, b, out);

    // TODO(sonots): Support ndim >= 2
    if (a.ndim() != 2 || b.ndim() != 2 || out.ndim() != 2) {
        throw DimensionError{"XChainer dot supports only 2-dimensional arrays."};
    }

#ifdef XCHAINER_ENABLE_BLAS
    if (out.dtype() == Dtype::kFloat32 || out.dtype() == Dtype::kFloat64) {
        Gemm(a, b, out);
        return;
    }
#endif  // XCHAINER_ENABLE_BLAS

    out.Fill(0);
    VisitDtype(out.dtype(), [&](auto pt) {
        using T = typename decltype(pt)::type;
        IndexableArray<const T, 2> a_iarray{a};
        IndexableArray<const T, 2> b_iarray{b};
        IndexableArray<T, 2> out_iarray{out};

        int64_t m = a.shape()[0];
        int64_t k = a.shape()[1];
        int64_t n = b.shape()[1];
        assert(b.shape()[0] == k);
        assert(out.shape()[0] == m);
        assert(out.shape()[1] == n);

        for (int64_t i = 0; i < m; ++i) {
            for (int64_t l = 0; l < k; ++l) {
                int64_t a_i_l[] = {i, l};
                T a_value = a_iarray[a_i_l];
                for (int64_t j = 0; j < n; ++j) {
                    int64_t out_i_j[] = {i, j};
                    int64_t b_l_j[] = {l, j};
                    out_iarray[out_i_j] += a_value * b_iarray[b_l_j];
                }
            }
        }
    });
}

}  // namespace native
}  // namespace xchainer
<|endoftext|>


<commit_before><commit_msg>Setting the data type from the command line.<commit_after>// Copyright 2014 Alessio Sclocco <a.sclocco@vu.nl>
//
// 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 <iostream>
#include <string>
#include <vector>
#include <exception>
#include <fstream>
#include <iomanip>
#include <limits>
#include <ctime>

#include <ArgumentList.hpp>
#include <Observation.hpp>
#include <utils.hpp>
#include <Shifts.hpp>
#include <Dedispersion.hpp>

int main(int argc, char *argv[]) {
  bool localMem = false;
	unsigned int nrSamplesPerBlock = 0;
	unsigned int nrDMsPerBlock = 0;
  unsigned int nrSamplesPerThread = 0;
  unsigned int nrDMsPerThread = 0;
  unsigned int unroll = 0;
  std::string typeName;
  AstroData::Observation observation;

  try {
    isa::utils::ArgumentList args(argc, argv);
    observation.setPadding(args.getSwitchArgument< unsigned int >("-padding"));
    localMem = args.getSwitch("-local");
		nrSamplesPerBlock = args.getSwitchArgument< unsigned int >("-sb");
		nrDMsPerBlock = args.getSwitchArgument< unsigned int >("-db");
		nrSamplesPerThread = args.getSwitchArgument< unsigned int >("-st");
		nrDMsPerThread = args.getSwitchArgument< unsigned int >("-dt");
    unroll = args.getSwitchArgument< unsigned int >("-unroll");
    typeName = args.getSwitchArgument< std::string >("-type");
    observation.setFrequencyRange(args.getSwitchArgument< unsigned int >("-channels"), args.getSwitchArgument< float >("-min_freq"), args.getSwitchArgument< float >("-channel_bandwidth"));
		observation.setNrSamplesPerSecond(args.getSwitchArgument< unsigned int >("-samples"));
    observation.setDMRange(args.getSwitchArgument< unsigned int >("-dms"), args.getSwitchArgument< float >("-dm_first"), args.getSwitchArgument< float >("-dm_step"));
	} catch  ( isa::utils::SwitchNotFound &err ) {
    std::cerr << err.what() << std::endl;
    return 1;
  }catch ( std::exception &err ) {
    std::cerr << "Usage: " << argv[0] << " -padding ... [-local] -sb ... -db ... -st ... -dt ... -unroll ... -type ... -min_freq ... -channel_bandwidth ... -samples ... -channels ... -dms ... -dm_first ... -dm_step ..." << std::endl;
		return 1;
	}

  std::vector< unsigned int > * shifts = PulsarSearch::getShifts(observation);
  observation.setNrSamplesPerDispersedChannel(observation.getNrSamplesPerSecond() + (*shifts)[((observation.getNrDMs() - 1) * observation.getNrPaddedChannels())]);

	// Generate kernel
  std::string * code = PulsarSearch::getDedispersionOpenCL(localMem, nrSamplesPerBlock, nrDMsPerBlock, nrSamplesPerThread, nrDMsPerThread, unroll, typeName, observation, *shifts);
  std::cout << *code << std::endl;

	return 0;
}

<|endoftext|>


<commit_before>/**
 *  Copyright (c) 2014-present, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under both the Apache 2.0 license (found in the
 *  LICENSE file in the root directory of this source tree) and the GPLv2 (found
 *  in the COPYING file in the root directory of this source tree).
 *  You may select, at your option, one of the above-listed licenses.
 */

#ifdef WIN32
#include <intrin.h>
#endif

#include <iomanip>
#include <map>
#include <sstream>
#include <string>
#include <vector>

#include <osquery/core.h>
#include <osquery/tables.h>

#define FEATURE(name, reg, bit) std::make_pair(name, std::make_pair(reg, bit))

namespace osquery {
namespace tables {

using RegisterBit = std::pair<std::string, size_t>;
using FeatureDef = std::pair<std::string, RegisterBit>;

std::map<size_t, std::vector<FeatureDef>> kCPUFeatures{
    {1,
     {
         FEATURE("pae", "edx", 6),         FEATURE("msr", "edx", 5),
         FEATURE("sep", "edx", 11),        FEATURE("mtrr", "edx", 12),
         FEATURE("pge", "edx", 13),        FEATURE("mca", "edx", 14),
         FEATURE("pat", "edx", 16),        FEATURE("clfsh", "edx", 19),
         FEATURE("acpi", "edx", 22),       FEATURE("mmz", "edx", 23),
         FEATURE("sse", "edx", 25),        FEATURE("sse2", "edx", 26),
         FEATURE("ss", "edx", 27),         FEATURE("htt", "edx", 28),
         FEATURE("ia64", "edx", 30),

         FEATURE("sse3", "ecx", 0),        FEATURE("vmx", "ecx", 5),
         FEATURE("smx", "ecx", 6),         FEATURE("ssse3", "ecx", 9),
         FEATURE("sdbg", "ecx", 11),       FEATURE("pdcm", "ecx", 15),
         FEATURE("pcid", "ecx", 17),       FEATURE("dca", "ecx", 18),
         FEATURE("sse4.1", "ecx", 19),     FEATURE("sse4.2", "ecx", 20),
         FEATURE("aes", "ecx", 25),        FEATURE("avx", "ecx", 28),
         FEATURE("hypervisor", "ecx", 31),
     }},
    {7,
     {
         FEATURE("sgx", "ebx", 2),        FEATURE("hle", "ebx", 4),
         FEATURE("avx2", "ebx", 5),       FEATURE("smep", "ebx", 7),
         FEATURE("bmi2", "ebx", 8),       FEATURE("erms", "ebx", 9),
         FEATURE("invpcid", "ebx", 10),   FEATURE("rtm", "ebx", 11),
         FEATURE("pqm", "ebx", 12),       FEATURE("mpx", "ebx", 14),
         FEATURE("pqe", "ebx", 15),       FEATURE("avx512f", "ebx", 16),
         FEATURE("avx512dq", "ebx", 17),  FEATURE("rdseed", "ebx", 18),
         FEATURE("adx", "ebx", 19),       FEATURE("smap", "ebx", 20),
         FEATURE("intel_pt", "ebx", 25),  FEATURE("sha", "ebx", 29),

         FEATURE("umip", "ecx", 2),       FEATURE("pku", "ecx", 3),
         FEATURE("ospke", "ecx", 4),      FEATURE("gfni", "ecx", 8),
         FEATURE("vaes", "ecx", 9),       FEATURE("sgx_lc", "ecx", 30),

         FEATURE("spec_ctrl", "edx", 26),
     }},
    {0x80000001,
     {
         FEATURE("svm", "ecx", 2),
         FEATURE("ibs", "ecx", 10),
         FEATURE("skinit", "ecx", 12),
         FEATURE("lwp", "ecx", 15),
     }}};

static inline void cpuid(size_t eax, size_t ecx, int regs[4]) {
#if defined(WIN32)
  __cpuidex(
      static_cast<int*>(regs), static_cast<int>(eax), static_cast<int>(ecx));
#else
  asm volatile("cpuid"
               : "=a"(regs[0]), "=b"(regs[1]), "=c"(regs[2]), "=d"(regs[3])
               : "a"(eax), "c"(ecx));
#endif
}

static inline void registerToString(int reg, std::stringstream& stream) {
  for (size_t i = 0; i < 4; i++) {
    stream << ((char*)&reg)[i];
  }
}

static inline bool isBitSet(size_t bit, unsigned int reg) {
  return ((reg & (1 << bit)) != 0);
}

inline Status genStrings(QueryData& results) {
  int regs[4] = {-1};

  cpuid(0, 0, regs);
  if (regs[0] < 1) {
    // The CPUID ASM call is not supported.
    return Status(1, "Failed to run cpuid");
  }

  std::stringstream vendor_string;
  registerToString(regs[1], vendor_string);
  registerToString(regs[3], vendor_string);
  registerToString(regs[2], vendor_string);

  Row r;
  r["feature"] = "vendor";
  r["value"] = vendor_string.str();
  r["output_register"] = "ebx,edx,ecx";
  r["output_bit"] = "0";
  r["input_eax"] = "0";
  results.push_back(r);

  // The CPU canonicalized name can also be accessed via cpuid accesses.
  // Subsequent accesses allow a 32-character CPU name.
  std::stringstream product_name;
  for (size_t i = 0; i < 3; i++) {
    cpuid(0x80000002 + i, 0U, regs);
    registerToString(regs[0], product_name);
    registerToString(regs[1], product_name);
    registerToString(regs[2], product_name);
    registerToString(regs[3], product_name);
  }

  r["feature"] = "product_name";
  r["value"] = product_name.str();
  r["output_register"] = "eax,ebx,ecx,edx";
  r["output_bit"] = "0";
  r["input_eax"] = "0x80000002";
  results.push_back(r);

  // Do the same to grab the optional hypervisor ID.
  cpuid(0x40000000, 0, regs);
  if (regs[0] && 0xFF000000 != 0) {
    std::stringstream hypervisor;
    hypervisor << std::hex << std::setw(8) << std::setfill('0')
               << static_cast<int>(regs[0]);
    hypervisor << std::hex << std::setw(8) << std::setfill('0')
               << static_cast<int>(regs[1]);
    hypervisor << std::hex << std::setw(8) << std::setfill('0')
               << static_cast<int>(regs[2]);

    r["feature"] = "hypervisor_id";
    r["value"] = hypervisor.str();
    r["output_register"] = "ebx,ecx,edx";
    r["output_bit"] = "0";
    r["input_eax"] = "0x40000000";
    results.push_back(r);
  }

  // Finally, check the processor serial number.
  std::stringstream serial;
  cpuid(1, 0, regs);
  serial << std::hex << std::setw(8) << std::setfill('0')
         << static_cast<int>(regs[0]);
  cpuid(3, 0, regs);
  serial << std::hex << std::setw(8) << std::setfill('0')
         << static_cast<int>(regs[0]);
  serial << std::hex << std::setw(8) << std::setfill('0')
         << static_cast<int>(regs[3]);

  r["feature"] = "serial";
  r["value"] = serial.str();
  r["output_register"] = "eax,eax,ecx";
  r["output_bit"] = "0";
  r["input_eax"] = "1,3";
  results.push_back(r);

  return Status(0, "OK");
}

inline void genFamily(QueryData& results) {
  int regs[4] = {-1};

  cpuid(1, 0, regs);
  auto family = regs[0] & 0xf00;

  std::stringstream family_string;
  family_string << std::hex << std::setw(4) << std::setfill('0') << family;

  Row r;
  r["feature"] = "family";
  r["value"] = family_string.str();
  r["output_register"] = "eax";
  r["output_bit"] = "0";
  r["input_eax"] = "1";

  results.push_back(r);
}

QueryData genCPUID(QueryContext& context) {
  QueryData results;

  if (!genStrings(results).ok()) {
    return results;
  }

  // Get the CPU meta-data about the model, stepping, family.
  genFamily(results);

  int regs[4] = {-1};
  for (const auto& feature_set : kCPUFeatures) {
    auto eax = feature_set.first;
    cpuid(eax, 0, regs);

    for (const auto& feature : feature_set.second) {
      Row r;

      r["feature"] = feature.first;

      // Get the return register holding the feature bit.
      auto feature_register = 0;
      if (feature.second.first == "edx") {
        feature_register = 3;
      } else if (feature.second.first == "ebx") {
        feature_register = 1;
      } else if (feature.second.first == "ecx") {
        feature_register = 2;
      }

      auto feature_bit = feature.second.second;
      r["value"] = isBitSet(feature_bit, regs[feature_register]) ? "1" : "0";
      r["output_register"] = feature.second.first;
      r["output_bit"] = INTEGER(feature_bit);
      r["input_eax"] = boost::lexical_cast<std::string>(eax);
      results.push_back(r);
    }
  }

  {
    Row r;
    r["output_register"] = "eax,ebx,ecx,edx";
    r["output_bit"] = INTEGER(0);

    cpuid(0x12, 0, regs);
    std::stringstream sgx0;
    sgx0 << std::hex << std::setw(8) << std::setfill('0')
         << static_cast<int>(regs[0]);
    sgx0 << std::hex << std::setw(8) << std::setfill('0')
         << static_cast<int>(regs[1]);
    sgx0 << std::hex << std::setw(8) << std::setfill('0')
         << static_cast<int>(regs[2]);
    sgx0 << std::hex << std::setw(8) << std::setfill('0')
         << static_cast<int>(regs[3]);
    r["feature"] = "sgx0";
    r["value"] = sgx0.str();
    r["input_eax"] = std::to_string(0x12);
    results.push_back(r);

    cpuid(0x12, 1, regs);
    std::stringstream sgx1;
    sgx1 << std::hex << std::setw(8) << std::setfill('0')
         << static_cast<int>(regs[0]);
    sgx1 << std::hex << std::setw(8) << std::setfill('0')
         << static_cast<int>(regs[1]);
    sgx1 << std::hex << std::setw(8) << std::setfill('0')
         << static_cast<int>(regs[2]);
    sgx1 << std::hex << std::setw(8) << std::setfill('0')
         << static_cast<int>(regs[3]);
    r["feature"] = "sgx1";
    r["value"] = sgx1.str();
    r["input_eax"] = std::to_string(0x12) + ",1";
    results.push_back(r);
  }

  return results;
}
} // namespace tables
} // namespace osquery
<commit_msg>Add some more features to the cpuid table. (#4192)<commit_after>/**
 *  Copyright (c) 2014-present, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under both the Apache 2.0 license (found in the
 *  LICENSE file in the root directory of this source tree) and the GPLv2 (found
 *  in the COPYING file in the root directory of this source tree).
 *  You may select, at your option, one of the above-listed licenses.
 */

#ifdef WIN32
#include <intrin.h>
#endif

#include <iomanip>
#include <map>
#include <sstream>
#include <string>
#include <vector>

#include <osquery/core.h>
#include <osquery/tables.h>

#define FEATURE(name, reg, bit) std::make_pair(name, std::make_pair(reg, bit))

namespace osquery {
namespace tables {

using RegisterBit = std::pair<std::string, size_t>;
using FeatureDef = std::pair<std::string, RegisterBit>;

std::map<size_t, std::vector<FeatureDef>> kCPUFeatures{
    {1,
     {
         FEATURE("pae", "edx", 6),         FEATURE("msr", "edx", 5),
         FEATURE("sep", "edx", 11),        FEATURE("mtrr", "edx", 12),
         FEATURE("pge", "edx", 13),        FEATURE("mca", "edx", 14),
         FEATURE("pat", "edx", 16),        FEATURE("clfsh", "edx", 19),
         FEATURE("acpi", "edx", 22),       FEATURE("mmz", "edx", 23),
         FEATURE("sse", "edx", 25),        FEATURE("sse2", "edx", 26),
         FEATURE("ss", "edx", 27),         FEATURE("htt", "edx", 28),
         FEATURE("ia64", "edx", 30),

         FEATURE("sse3", "ecx", 0),        FEATURE("vmx", "ecx", 5),
         FEATURE("smx", "ecx", 6),         FEATURE("ssse3", "ecx", 9),
         FEATURE("sdbg", "ecx", 11),       FEATURE("pdcm", "ecx", 15),
         FEATURE("pcid", "ecx", 17),       FEATURE("dca", "ecx", 18),
         FEATURE("sse4.1", "ecx", 19),     FEATURE("sse4.2", "ecx", 20),
         FEATURE("aes", "ecx", 25),        FEATURE("avx", "ecx", 28),
         FEATURE("hypervisor", "ecx", 31),
     }},
    {7,
     {
         FEATURE("sgx", "ebx", 2),        FEATURE("hle", "ebx", 4),
         FEATURE("avx2", "ebx", 5),       FEATURE("smep", "ebx", 7),
         FEATURE("bmi2", "ebx", 8),       FEATURE("erms", "ebx", 9),
         FEATURE("invpcid", "ebx", 10),   FEATURE("rtm", "ebx", 11),
         FEATURE("pqm", "ebx", 12),       FEATURE("mpx", "ebx", 14),
         FEATURE("pqe", "ebx", 15),       FEATURE("avx512f", "ebx", 16),
         FEATURE("avx512dq", "ebx", 17),  FEATURE("rdseed", "ebx", 18),
         FEATURE("adx", "ebx", 19),       FEATURE("smap", "ebx", 20),
         FEATURE("intel_pt", "ebx", 25),  FEATURE("sha", "ebx", 29),

         FEATURE("umip", "ecx", 2),       FEATURE("pku", "ecx", 3),
         FEATURE("ospke", "ecx", 4),      FEATURE("gfni", "ecx", 8),
         FEATURE("vaes", "ecx", 9),       FEATURE("sgx_lc", "ecx", 30),

         FEATURE("spec_ctrl", "edx", 26),
     }},
    {0x80000001,
     {
         FEATURE("lahfsahf", "ecx", 0),
         FEATURE("svm", "ecx", 2),
         FEATURE("3dnowprefetch", "ecx", 8),
         FEATURE("ibs", "ecx", 10),
         FEATURE("skinit", "ecx", 12),
         FEATURE("lwp", "ecx", 15),

         FEATURE("nx", "edx", 20),
         FEATURE("page1gb", "edx", 26),
         FEATURE("lm", "edx", 29),
     }}};

static inline void cpuid(size_t eax, size_t ecx, int regs[4]) {
#if defined(WIN32)
  __cpuidex(
      static_cast<int*>(regs), static_cast<int>(eax), static_cast<int>(ecx));
#else
  asm volatile("cpuid"
               : "=a"(regs[0]), "=b"(regs[1]), "=c"(regs[2]), "=d"(regs[3])
               : "a"(eax), "c"(ecx));
#endif
}

static inline void registerToString(int reg, std::stringstream& stream) {
  for (size_t i = 0; i < 4; i++) {
    stream << ((char*)&reg)[i];
  }
}

static inline bool isBitSet(size_t bit, unsigned int reg) {
  return ((reg & (1 << bit)) != 0);
}

inline Status genStrings(QueryData& results) {
  int regs[4] = {-1};

  cpuid(0, 0, regs);
  if (regs[0] < 1) {
    // The CPUID ASM call is not supported.
    return Status(1, "Failed to run cpuid");
  }

  std::stringstream vendor_string;
  registerToString(regs[1], vendor_string);
  registerToString(regs[3], vendor_string);
  registerToString(regs[2], vendor_string);

  Row r;
  r["feature"] = "vendor";
  r["value"] = vendor_string.str();
  r["output_register"] = "ebx,edx,ecx";
  r["output_bit"] = "0";
  r["input_eax"] = "0";
  results.push_back(r);

  // The CPU canonicalized name can also be accessed via cpuid accesses.
  // Subsequent accesses allow a 32-character CPU name.
  std::stringstream product_name;
  for (size_t i = 0; i < 3; i++) {
    cpuid(0x80000002 + i, 0U, regs);
    registerToString(regs[0], product_name);
    registerToString(regs[1], product_name);
    registerToString(regs[2], product_name);
    registerToString(regs[3], product_name);
  }

  r["feature"] = "product_name";
  r["value"] = product_name.str();
  r["output_register"] = "eax,ebx,ecx,edx";
  r["output_bit"] = "0";
  r["input_eax"] = "0x80000002";
  results.push_back(r);

  // Do the same to grab the optional hypervisor ID.
  cpuid(0x40000000, 0, regs);
  if (regs[0] && 0xFF000000 != 0) {
    std::stringstream hypervisor;
    hypervisor << std::hex << std::setw(8) << std::setfill('0')
               << static_cast<int>(regs[0]);
    hypervisor << std::hex << std::setw(8) << std::setfill('0')
               << static_cast<int>(regs[1]);
    hypervisor << std::hex << std::setw(8) << std::setfill('0')
               << static_cast<int>(regs[2]);

    r["feature"] = "hypervisor_id";
    r["value"] = hypervisor.str();
    r["output_register"] = "ebx,ecx,edx";
    r["output_bit"] = "0";
    r["input_eax"] = "0x40000000";
    results.push_back(r);
  }

  // Finally, check the processor serial number.
  std::stringstream serial;
  cpuid(1, 0, regs);
  serial << std::hex << std::setw(8) << std::setfill('0')
         << static_cast<int>(regs[0]);
  cpuid(3, 0, regs);
  serial << std::hex << std::setw(8) << std::setfill('0')
         << static_cast<int>(regs[0]);
  serial << std::hex << std::setw(8) << std::setfill('0')
         << static_cast<int>(regs[3]);

  r["feature"] = "serial";
  r["value"] = serial.str();
  r["output_register"] = "eax,eax,ecx";
  r["output_bit"] = "0";
  r["input_eax"] = "1,3";
  results.push_back(r);

  return Status(0, "OK");
}

inline void genFamily(QueryData& results) {
  int regs[4] = {-1};

  cpuid(1, 0, regs);
  auto family = regs[0] & 0xf00;

  std::stringstream family_string;
  family_string << std::hex << std::setw(4) << std::setfill('0') << family;

  Row r;
  r["feature"] = "family";
  r["value"] = family_string.str();
  r["output_register"] = "eax";
  r["output_bit"] = "0";
  r["input_eax"] = "1";

  results.push_back(r);
}

QueryData genCPUID(QueryContext& context) {
  QueryData results;

  if (!genStrings(results).ok()) {
    return results;
  }

  // Get the CPU meta-data about the model, stepping, family.
  genFamily(results);

  int regs[4] = {-1};
  for (const auto& feature_set : kCPUFeatures) {
    auto eax = feature_set.first;
    cpuid(eax, 0, regs);

    for (const auto& feature : feature_set.second) {
      Row r;

      r["feature"] = feature.first;

      // Get the return register holding the feature bit.
      auto feature_register = 0;
      if (feature.second.first == "edx") {
        feature_register = 3;
      } else if (feature.second.first == "ebx") {
        feature_register = 1;
      } else if (feature.second.first == "ecx") {
        feature_register = 2;
      }

      auto feature_bit = feature.second.second;
      r["value"] = isBitSet(feature_bit, regs[feature_register]) ? "1" : "0";
      r["output_register"] = feature.second.first;
      r["output_bit"] = INTEGER(feature_bit);
      r["input_eax"] = boost::lexical_cast<std::string>(eax);
      results.push_back(r);
    }
  }

  {
    Row r;
    r["output_register"] = "eax,ebx,ecx,edx";
    r["output_bit"] = INTEGER(0);

    cpuid(0x12, 0, regs);
    std::stringstream sgx0;
    sgx0 << std::hex << std::setw(8) << std::setfill('0')
         << static_cast<int>(regs[0]);
    sgx0 << std::hex << std::setw(8) << std::setfill('0')
         << static_cast<int>(regs[1]);
    sgx0 << std::hex << std::setw(8) << std::setfill('0')
         << static_cast<int>(regs[2]);
    sgx0 << std::hex << std::setw(8) << std::setfill('0')
         << static_cast<int>(regs[3]);
    r["feature"] = "sgx0";
    r["value"] = sgx0.str();
    r["input_eax"] = std::to_string(0x12);
    results.push_back(r);

    cpuid(0x12, 1, regs);
    std::stringstream sgx1;
    sgx1 << std::hex << std::setw(8) << std::setfill('0')
         << static_cast<int>(regs[0]);
    sgx1 << std::hex << std::setw(8) << std::setfill('0')
         << static_cast<int>(regs[1]);
    sgx1 << std::hex << std::setw(8) << std::setfill('0')
         << static_cast<int>(regs[2]);
    sgx1 << std::hex << std::setw(8) << std::setfill('0')
         << static_cast<int>(regs[3]);
    r["feature"] = "sgx1";
    r["value"] = sgx1.str();
    r["input_eax"] = std::to_string(0x12) + ",1";
    results.push_back(r);
  }

  return results;
}
} // namespace tables
} // namespace osquery
<|endoftext|>


<commit_before>// apt_signs.cxx -- build airport signs on the fly
//
// Written by Curtis Olson, started July 2001.
//
// Copyright (C) 2001  Curtis L. Olson  - http://www.flightgear.org/~curt
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
//
// $Id$

#ifdef HAVE_CONFIG_H
#  include <simgear_config.h>
#endif

#include <simgear/debug/logstream.hxx>
#include <simgear/math/sg_types.hxx>
#include <simgear/scene/tgdb/leaf.hxx>
#include <simgear/scene/material/mat.hxx>
#include <simgear/scene/material/matlib.hxx>

#include "apt_signs.hxx"

#define TAXI "OBJECT_TAXI_SIGN: "
#define RWY "OBJECT_RUNWAY_SIGN: "

// for temporary storage of sign elements
struct element_info {
    element_info(SGMaterial *m, SGMaterialGlyph *g, double h, bool l)
        : material(m), glyph(g), height(h), lighted(l)
    {
        scale = h * m->get_xsize()
                / (m->get_ysize() < 0.001 ? 1.0 : m->get_ysize());
    }
    SGMaterial *material;
    SGMaterialGlyph *glyph;
    double height;
    double scale;
    bool lighted;
};

// standard panel height sizes
const double HT[5] = {0.460, 0.610, 0.760, 1.220, 0.760};

// translation table for "command" to "glyph name"
struct pair {
    const char *keyword;
    const char *glyph_name;
} cmds[] = {
    {"@u",       "up"},
    {"@d",       "down"},
    {"@l",       "left"},
    {"@lu",      "left-up"},
    {"@ul",      "left-up"},
    {"@ld",      "left-down"},
    {"@dl",      "left-down"},
    {"@r",       "right"},
    {"@ru",      "right-up"},
    {"@ur",      "right-up"},
    {"@rd",      "right-down"},
    {"@dr",      "right-down"},
    {0, 0},
};

// Y ... black on yellow            -> direction, destination, boundary
// R ... white on red               -> mandatory instruction
// L ... yellow on black with frame -> runway/taxiway location
// B ... white on black             -> runway distance remaining
//
// u/d/l/r     ... up/down/left/right arrow or two-letter combinations
//                 thereof (ur, dl, ...)
//
// Example: {l}E|{L}[T]|{Y,ur}L|E{r}
//
ssgBranch *sgMakeTaxiSign( SGMaterialLib *matlib,
                           const string path, const string content )
{
    double sign_height = 1.0;  // meter
    bool lighted = true;

    vector<element_info *> elements;
    element_info *close = 0;
    double total_width = 0.0;
    bool cmd = false;
    char *newmat = "BlackSign";
    int size = -1;
    char oldtype = 0, newtype = 0;

    ssgBranch *object = new ssgBranch();
    object->setName((char *)content.c_str());
    SGMaterial *material = matlib->find(newmat);

    // Part I: parse & measure
    for (const char *s = content.data(); *s; s++) {
        string name;
        const char *newmat = 0;

        if (*s == '{') {
            if (cmd)
                SG_LOG(SG_TERRAIN, SG_ALERT, TAXI "unexpected { in sign contents");
            cmd = true;
            continue;

        } else if (*s == '}') {
            if (!cmd)
                SG_LOG(SG_TERRAIN, SG_ALERT, TAXI "unexpected } in sign contents");
            cmd = false;
            continue;

        } else if (!cmd) {
            name = *s;

        } else {
            if (*s == ',')
                continue;

            string value;
            for (; *s; s++) {
                name += *s;
                if (s[1] == ',' || s[1] == '}' || s[1] == '=')
                    break;
            }
            if (!*s) {
                SG_LOG(SG_TERRAIN, SG_ALERT, TAXI "unclosed { in sign contents");
            } else if (s[1] == '=') {
                for (s += 2; *s; s++) {
                    value += *s;
                    if (s[1] == ',' || s[1] == '}')
                        break;
                }
                if (!*s)
                    SG_LOG(SG_TERRAIN, SG_ALERT, TAXI "unclosed { in sign contents");
            }

            if (name == "@size") {
                sign_height = strtod(value.data(), 0);
                continue;
            }

            if (name == "@light") {
                lighted = (value != "0" && value != "no" && value != "off" && value != "false");
                continue;
            }

            if (name == "@material")
                newmat = value.data();
            else if (name.size() == 2 || name.size() == 3) {
                if (name.size() == 3 && name[2] >= '1' && name[2] <= '5') {
                    size = name[2] - '1';
                    name = name.substr(0, 2);
                }

                if (name == "@Y") {
                    if (size < 3) {
                        sign_height = HT[size < 0 ? 2 : size];
                        newmat = "YellowSign";
                        newtype = 'Y';
                    }
                } else if (name == "@R") {
                    if (size < 3) {
                        sign_height = HT[size < 0 ? 2 : size];
                        newmat = "RedSign";
                        newtype = 'R';
                    }
                } else if (name == "@L") {
                    if (size < 3) {
                        sign_height = HT[size < 0 ? 2 : size];
                        newmat = "FramedSign";
                        newtype = 'L';
                    }
                } else if (name == "@B") {
                    if (size < 0 || size == 3 || size == 4) {
                        sign_height = HT[size < 0 ? 3 : size];
                        newmat = "BlackSign";
                        newtype = 'B';
                    }
                }
            }

            if (newmat) {
                material = matlib->find(newmat);
                continue;
            }

            for (int i = 0; cmds[i].keyword; i++) {
                if (name == cmds[i].keyword) {
                    name = cmds[i].glyph_name;
                    break;
                }
            }

            if (name[0] == '@') {
                SG_LOG(SG_TERRAIN, SG_ALERT, TAXI "ignoring unknown command `" << name << '\'');
                continue;
            }
        }

        if (!material) {
            SG_LOG( SG_TERRAIN, SG_ALERT, TAXI "material doesn't exit");
            continue;
        }

        SGMaterialGlyph *glyph = material->get_glyph(name);
        if (!glyph) {
            SG_LOG( SG_TERRAIN, SG_ALERT, TAXI "unsupported glyph `" << *s << '\'');
            continue;
        }

        // in managed mode push frame stop and frame start first
        element_info *e;
        if (newtype && newtype != oldtype) {
            if (close) {
                elements.push_back(close);
                total_width += close->glyph->get_width() * close->scale;
                close = 0;
            }
            oldtype = newtype;
            SGMaterialGlyph *g = material->get_glyph("stop-frame");
            if (g)
                close = new element_info(material, g, sign_height, lighted);
            g = material->get_glyph("start-frame");
            if (g) {
                e = new element_info(material, g, sign_height, lighted);
                elements.push_back(e);
                total_width += e->glyph->get_width() * e->scale;
            }
        }
        // now the actually requested glyph
        e = new element_info(material, glyph, sign_height, lighted);
        elements.push_back(e);
        total_width += e->glyph->get_width() * e->scale;
    }

    // in managed mode close frame
    if (close) {
        elements.push_back(close);
        total_width += close->glyph->get_width() * close->scale;
        close = 0;
    }

    // Part II: typeset
    double hpos = -total_width / 2;
    const double dist = 0.5;        // hard-code distance from surface for now

    sgVec3 normal;
    sgSetVec3(normal, 0, -1, 0);

    sgVec4 color;
    sgSetVec4(color, 1.0, 1.0, 1.0, 1.0);

    for (unsigned int i = 0; i < elements.size(); i++) {
        element_info *element = elements[i];

        double xoffset = element->glyph->get_left();
        double height = element->height;
        double width = element->glyph->get_width();
        double abswidth = width * element->scale;

        // vertices
        ssgVertexArray *vl = new ssgVertexArray(4);
        vl->add(hpos,            0, dist);
        vl->add(hpos + abswidth, 0, dist);
        vl->add(hpos,            0, dist + height);
        vl->add(hpos + abswidth, 0, dist + height);

        // texture coordinates
        ssgTexCoordArray *tl = new ssgTexCoordArray(4);
        tl->add(xoffset,         0);
        tl->add(xoffset + width, 0);
        tl->add(xoffset,         1);
        tl->add(xoffset + width, 1);

        // normals
        ssgNormalArray *nl = new ssgNormalArray(1);
        nl->add(normal);

        // colors
        ssgColourArray *cl = new ssgColourArray(1);
        cl->add(color);

        ssgLeaf *leaf = new ssgVtxTable(GL_TRIANGLE_STRIP, vl, nl, tl, cl);
        ssgSimpleState *state = element->material->get_state();
        if (!element->lighted) {
            // FIXME: clone state for unlighted elements only once per material
            state = (ssgSimpleState *)state->clone(SSG_CLONE_STATE);
            state->setMaterial(GL_EMISSION, 0.3, 0.3, 0.3, 1);
        }
        leaf->setState(state);

        object->addKid(leaf);
        hpos += abswidth;
        delete element;
    }

    return object;
}

ssgBranch *sgMakeRunwaySign( SGMaterialLib *matlib,
                             const string path, const string name )
{
    // for demo purposes we assume each element (letter) is 1x1 meter.
    // Sign is placed 0.25 meters above the ground

    ssgBranch *object = new ssgBranch();
    object->setName( (char *)name.c_str() );

    double width = name.length() / 3.0;

    string material = name;

    point_list nodes;
    point_list normals;
    point_list texcoords;
    int_list vertex_index;
    int_list normal_index;
    int_list tex_index;

    nodes.push_back( Point3D( -width, 0, 0.25 ) );
    nodes.push_back( Point3D( width + 1, 0, 0.25 ) );
    nodes.push_back( Point3D( -width, 0, 1.25 ) );
    nodes.push_back( Point3D( width + 1, 0, 1.25 ) );

    normals.push_back( Point3D( 0, -1, 0 ) );

    texcoords.push_back( Point3D( 0, 0, 0 ) );
    texcoords.push_back( Point3D( 1, 0, 0 ) );
    texcoords.push_back( Point3D( 0, 1, 0 ) );
    texcoords.push_back( Point3D( 1, 1, 0 ) );

    vertex_index.push_back( 0 );
    vertex_index.push_back( 1 );
    vertex_index.push_back( 2 );
    vertex_index.push_back( 3 );

    normal_index.push_back( 0 );
    normal_index.push_back( 0 );
    normal_index.push_back( 0 );
    normal_index.push_back( 0 );

    tex_index.push_back( 0 );
    tex_index.push_back( 1 );
    tex_index.push_back( 2 );
    tex_index.push_back( 3 );

    ssgLeaf *leaf = sgMakeLeaf( path, GL_TRIANGLE_STRIP, matlib, material,
                                nodes, normals, texcoords,
                                vertex_index, normal_index, tex_index,
                                false, NULL );

    object->addKid( leaf );

    return object;
}
<commit_msg>add minimalistic backside to signs as a temporary solution<commit_after>// apt_signs.cxx -- build airport signs on the fly
//
// Written by Curtis Olson, started July 2001.
//
// Copyright (C) 2001  Curtis L. Olson  - http://www.flightgear.org/~curt
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
//
// $Id$

#ifdef HAVE_CONFIG_H
#  include <simgear_config.h>
#endif

#include <simgear/debug/logstream.hxx>
#include <simgear/math/sg_types.hxx>
#include <simgear/scene/tgdb/leaf.hxx>
#include <simgear/scene/material/mat.hxx>
#include <simgear/scene/material/matlib.hxx>

#include "apt_signs.hxx"

#define TAXI "OBJECT_TAXI_SIGN: "
#define RWY "OBJECT_RUNWAY_SIGN: "

// for temporary storage of sign elements
struct element_info {
    element_info(SGMaterial *m, SGMaterialGlyph *g, double h, bool l)
        : material(m), glyph(g), height(h), lighted(l)
    {
        scale = h * m->get_xsize()
                / (m->get_ysize() < 0.001 ? 1.0 : m->get_ysize());
    }
    SGMaterial *material;
    SGMaterialGlyph *glyph;
    double height;
    double scale;
    bool lighted;
};

// standard panel height sizes
const double HT[5] = {0.460, 0.610, 0.760, 1.220, 0.760};

// translation table for "command" to "glyph name"
struct pair {
    const char *keyword;
    const char *glyph_name;
} cmds[] = {
    {"@u",       "up"},
    {"@d",       "down"},
    {"@l",       "left"},
    {"@lu",      "left-up"},
    {"@ul",      "left-up"},
    {"@ld",      "left-down"},
    {"@dl",      "left-down"},
    {"@r",       "right"},
    {"@ru",      "right-up"},
    {"@ur",      "right-up"},
    {"@rd",      "right-down"},
    {"@dr",      "right-down"},
    {0, 0},
};

// Y ... black on yellow            -> direction, destination, boundary
// R ... white on red               -> mandatory instruction
// L ... yellow on black with frame -> runway/taxiway location
// B ... white on black             -> runway distance remaining
//
// u/d/l/r     ... up/down/left/right arrow or two-letter combinations
//                 thereof (ur, dl, ...)
//
// Example: {l}E|{L}[T]|{Y,ur}L|E{r}
//
ssgBranch *sgMakeTaxiSign( SGMaterialLib *matlib,
                           const string path, const string content )
{
    double sign_height = 1.0;  // meter
    bool lighted = true;

    vector<element_info *> elements;
    element_info *close = 0;
    double total_width = 0.0;
    bool cmd = false;
    char *newmat = "BlackSign";
    int size = -1;
    char oldtype = 0, newtype = 0;

    ssgBranch *object = new ssgBranch();
    object->setName((char *)content.c_str());
    SGMaterial *material = matlib->find(newmat);

    // Part I: parse & measure
    for (const char *s = content.data(); *s; s++) {
        string name;
        const char *newmat = 0;

        if (*s == '{') {
            if (cmd)
                SG_LOG(SG_TERRAIN, SG_ALERT, TAXI "unexpected { in sign contents");
            cmd = true;
            continue;

        } else if (*s == '}') {
            if (!cmd)
                SG_LOG(SG_TERRAIN, SG_ALERT, TAXI "unexpected } in sign contents");
            cmd = false;
            continue;

        } else if (!cmd) {
            name = *s;

        } else {
            if (*s == ',')
                continue;

            string value;
            for (; *s; s++) {
                name += *s;
                if (s[1] == ',' || s[1] == '}' || s[1] == '=')
                    break;
            }
            if (!*s) {
                SG_LOG(SG_TERRAIN, SG_ALERT, TAXI "unclosed { in sign contents");
            } else if (s[1] == '=') {
                for (s += 2; *s; s++) {
                    value += *s;
                    if (s[1] == ',' || s[1] == '}')
                        break;
                }
                if (!*s)
                    SG_LOG(SG_TERRAIN, SG_ALERT, TAXI "unclosed { in sign contents");
            }

            if (name == "@size") {
                sign_height = strtod(value.data(), 0);
                continue;
            }

            if (name == "@light") {
                lighted = (value != "0" && value != "no" && value != "off" && value != "false");
                continue;
            }

            if (name == "@material")
                newmat = value.data();
            else if (name.size() == 2 || name.size() == 3) {
                if (name.size() == 3 && name[2] >= '1' && name[2] <= '5') {
                    size = name[2] - '1';
                    name = name.substr(0, 2);
                }

                if (name == "@Y") {
                    if (size < 3) {
                        sign_height = HT[size < 0 ? 2 : size];
                        newmat = "YellowSign";
                        newtype = 'Y';
                    }
                } else if (name == "@R") {
                    if (size < 3) {
                        sign_height = HT[size < 0 ? 2 : size];
                        newmat = "RedSign";
                        newtype = 'R';
                    }
                } else if (name == "@L") {
                    if (size < 3) {
                        sign_height = HT[size < 0 ? 2 : size];
                        newmat = "FramedSign";
                        newtype = 'L';
                    }
                } else if (name == "@B") {
                    if (size < 0 || size == 3 || size == 4) {
                        sign_height = HT[size < 0 ? 3 : size];
                        newmat = "BlackSign";
                        newtype = 'B';
                    }
                }
            }

            if (newmat) {
                material = matlib->find(newmat);
                continue;
            }

            for (int i = 0; cmds[i].keyword; i++) {
                if (name == cmds[i].keyword) {
                    name = cmds[i].glyph_name;
                    break;
                }
            }

            if (name[0] == '@') {
                SG_LOG(SG_TERRAIN, SG_ALERT, TAXI "ignoring unknown command `" << name << '\'');
                continue;
            }
        }

        if (!material) {
            SG_LOG( SG_TERRAIN, SG_ALERT, TAXI "material doesn't exit");
            continue;
        }

        SGMaterialGlyph *glyph = material->get_glyph(name);
        if (!glyph) {
            SG_LOG( SG_TERRAIN, SG_ALERT, TAXI "unsupported glyph `" << *s << '\'');
            continue;
        }

        // in managed mode push frame stop and frame start first
        element_info *e;
        if (newtype && newtype != oldtype) {
            if (close) {
                elements.push_back(close);
                total_width += close->glyph->get_width() * close->scale;
                close = 0;
            }
            oldtype = newtype;
            SGMaterialGlyph *g = material->get_glyph("stop-frame");
            if (g)
                close = new element_info(material, g, sign_height, lighted);
            g = material->get_glyph("start-frame");
            if (g) {
                e = new element_info(material, g, sign_height, lighted);
                elements.push_back(e);
                total_width += e->glyph->get_width() * e->scale;
            }
        }
        // now the actually requested glyph
        e = new element_info(material, glyph, sign_height, lighted);
        elements.push_back(e);
        total_width += e->glyph->get_width() * e->scale;
    }

    // in managed mode close frame
    if (close) {
        elements.push_back(close);
        total_width += close->glyph->get_width() * close->scale;
        close = 0;
    }

    // Part II: typeset
    double hpos = -total_width / 2;
    const double dist = 0.5;        // hard-code distance from surface for now

    sgVec3 normal;
    sgSetVec3(normal, 0, -1, 0);

    sgVec4 color;
    sgSetVec4(color, 1.0, 1.0, 1.0, 1.0);

    for (unsigned int i = 0; i < elements.size(); i++) {
        element_info *element = elements[i];

        double xoffset = element->glyph->get_left();
        double height = element->height;
        double width = element->glyph->get_width();
        double abswidth = width * element->scale;

        // vertices
        ssgVertexArray *vl = new ssgVertexArray(4);
        vl->add(hpos,            0, dist);
        vl->add(hpos + abswidth, 0, dist);
        vl->add(hpos,            0, dist + height);
        vl->add(hpos + abswidth, 0, dist + height);

        // texture coordinates
        ssgTexCoordArray *tl = new ssgTexCoordArray(4);
        tl->add(xoffset,         0);
        tl->add(xoffset + width, 0);
        tl->add(xoffset,         1);
        tl->add(xoffset + width, 1);

        // normals
        ssgNormalArray *nl = new ssgNormalArray(1);
        nl->add(normal);

        // colors
        ssgColourArray *cl = new ssgColourArray(1);
        cl->add(color);

        ssgLeaf *leaf = new ssgVtxTable(GL_TRIANGLE_STRIP, vl, nl, tl, cl);
        ssgSimpleState *state = element->material->get_state();
        if (!element->lighted) {
            // FIXME: clone state for unlighted elements only once per material
            state = (ssgSimpleState *)state->clone(SSG_CLONE_STATE);
            state->setMaterial(GL_EMISSION, 0.3, 0.3, 0.3, 1);
        }
        leaf->setState(state);

        object->addKid(leaf);
        hpos += abswidth;
        delete element;
    }

    // minimalistic backside
    ssgVertexArray *vl = new ssgVertexArray(4);
    vl->add(hpos,               0, dist);
    vl->add(hpos - total_width, 0, dist);
    vl->add(hpos,               0, dist + sign_height);
    vl->add(hpos - total_width, 0, dist + sign_height);

    ssgNormalArray *nl = new ssgNormalArray(1);
    nl->add(0, 1, 0);

    ssgLeaf *leaf = new ssgVtxTable(GL_TRIANGLE_STRIP, vl, nl, 0, 0);
    SGMaterial *mat = matlib->find("BlackSign");
    if (mat)
        leaf->setState(mat->get_state());
    object->addKid(leaf);

    return object;
}

ssgBranch *sgMakeRunwaySign( SGMaterialLib *matlib,
                             const string path, const string name )
{
    // for demo purposes we assume each element (letter) is 1x1 meter.
    // Sign is placed 0.25 meters above the ground

    ssgBranch *object = new ssgBranch();
    object->setName( (char *)name.c_str() );

    double width = name.length() / 3.0;

    string material = name;

    point_list nodes;
    point_list normals;
    point_list texcoords;
    int_list vertex_index;
    int_list normal_index;
    int_list tex_index;

    nodes.push_back( Point3D( -width, 0, 0.25 ) );
    nodes.push_back( Point3D( width + 1, 0, 0.25 ) );
    nodes.push_back( Point3D( -width, 0, 1.25 ) );
    nodes.push_back( Point3D( width + 1, 0, 1.25 ) );

    normals.push_back( Point3D( 0, -1, 0 ) );

    texcoords.push_back( Point3D( 0, 0, 0 ) );
    texcoords.push_back( Point3D( 1, 0, 0 ) );
    texcoords.push_back( Point3D( 0, 1, 0 ) );
    texcoords.push_back( Point3D( 1, 1, 0 ) );

    vertex_index.push_back( 0 );
    vertex_index.push_back( 1 );
    vertex_index.push_back( 2 );
    vertex_index.push_back( 3 );

    normal_index.push_back( 0 );
    normal_index.push_back( 0 );
    normal_index.push_back( 0 );
    normal_index.push_back( 0 );

    tex_index.push_back( 0 );
    tex_index.push_back( 1 );
    tex_index.push_back( 2 );
    tex_index.push_back( 3 );

    ssgLeaf *leaf = sgMakeLeaf( path, GL_TRIANGLE_STRIP, matlib, material,
                                nodes, normals, texcoords,
                                vertex_index, normal_index, tex_index,
                                false, NULL );

    object->addKid( leaf );

    return object;
}
<|endoftext|>


<commit_before>// Copyright (c) 2014 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "scicon.h"

#include <QApplication>
#include <QColor>
#include <QIcon>
#include <QImage>
#include <QPalette>
#include <QPixmap>

static void MakeSingleColorImage(QImage& img, const QColor& colorbase)
{
    img = img.convertToFormat(QImage::Format_ARGB32);
    for (int x = img.width(); x--; )
    {
        for (int y = img.height(); y--; )
        {
            const QRgb rgb = img.pixel(x, y);
            img.setPixel(x, y, qRgba(colorbase.red(), colorbase.green(), colorbase.blue(), qAlpha(rgb)));
        }
    }
}

QImage SingleColorImage(const QString& filename, const QColor& colorbase)
{
    QImage img(filename);
    MakeSingleColorImage(img, colorbase);
    return img;
}

QIcon SingleColorIcon(const QIcon& ico, const QColor& colorbase)
{
    QIcon new_ico;
    QSize sz;
    Q_FOREACH(sz, ico.availableSizes())
    {
        QImage img(ico.pixmap(sz).toImage());
        MakeSingleColorImage(img, colorbase);
        new_ico.addPixmap(QPixmap::fromImage(img));
    }
    return new_ico;
}

QIcon SingleColorIcon(const QString& filename, const QColor& colorbase)
{
    return QIcon(QPixmap::fromImage(SingleColorImage(filename, colorbase)));
}

QColor SingleColor()
{
    const QColor colorHighlightBg(QApplication::palette().color(QPalette::Highlight));
    const QColor colorHighlightFg(QApplication::palette().color(QPalette::HighlightedText));
    const QColor colorText(QApplication::palette().color(QPalette::WindowText));
    const int colorTextLightness = colorText.lightness();
    QColor colorbase;
    if (abs(colorHighlightBg.lightness() - colorTextLightness) < abs(colorHighlightFg.lightness() - colorTextLightness))
        colorbase = colorHighlightBg;
    else
        colorbase = colorHighlightFg;
    return colorbase;
}

QIcon SingleColorIcon(const QString& filename)
{
    return SingleColorIcon(filename, SingleColor());
}

static QColor TextColor()
{
    return QColor(QApplication::palette().color(QPalette::WindowText));
}

QIcon TextColorIcon(const QString& filename)
{
    return SingleColorIcon(filename, TextColor());
}

QIcon TextColorIcon(const QIcon& ico)
{
    return SingleColorIcon(ico, TextColor());
}
<commit_msg>[QT] don't colorize icons on win and mac<commit_after>// Copyright (c) 2014 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "scicon.h"

#include <QApplication>
#include <QColor>
#include <QIcon>
#include <QImage>
#include <QPalette>
#include <QPixmap>

static void MakeSingleColorImage(QImage& img, const QColor& colorbase)
{
    img = img.convertToFormat(QImage::Format_ARGB32);
    for (int x = img.width(); x--; )
    {
        for (int y = img.height(); y--; )
        {
            const QRgb rgb = img.pixel(x, y);
            img.setPixel(x, y, qRgba(colorbase.red(), colorbase.green(), colorbase.blue(), qAlpha(rgb)));
        }
    }
}

QImage SingleColorImage(const QString& filename, const QColor& colorbase)
{
    QImage img(filename);
#if !defined(WIN32) && !defined(MAC_OSX)
    MakeSingleColorImage(img, colorbase);
#endif
    return img;
}

QIcon SingleColorIcon(const QIcon& ico, const QColor& colorbase)
{
#if defined(WIN32) || defined(MAC_OSX)
    return ico;
#else
    QIcon new_ico;
    QSize sz;
    Q_FOREACH(sz, ico.availableSizes())
    {
        QImage img(ico.pixmap(sz).toImage());
        MakeSingleColorImage(img, colorbase);
        new_ico.addPixmap(QPixmap::fromImage(img));
    }
    return new_ico;
#endif
}

QIcon SingleColorIcon(const QString& filename, const QColor& colorbase)
{
    return QIcon(QPixmap::fromImage(SingleColorImage(filename, colorbase)));
}

QColor SingleColor()
{
#if defined(WIN32) || defined(MAC_OSX)
    return QColor(0,0,0);
#else
    const QColor colorHighlightBg(QApplication::palette().color(QPalette::Highlight));
    const QColor colorHighlightFg(QApplication::palette().color(QPalette::HighlightedText));
    const QColor colorText(QApplication::palette().color(QPalette::WindowText));
    const int colorTextLightness = colorText.lightness();
    QColor colorbase;
    if (abs(colorHighlightBg.lightness() - colorTextLightness) < abs(colorHighlightFg.lightness() - colorTextLightness))
        colorbase = colorHighlightBg;
    else
        colorbase = colorHighlightFg;
    return colorbase;
#endif
}

QIcon SingleColorIcon(const QString& filename)
{
    return SingleColorIcon(filename, SingleColor());
}

static QColor TextColor()
{
    return QColor(QApplication::palette().color(QPalette::WindowText));
}

QIcon TextColorIcon(const QString& filename)
{
    return SingleColorIcon(filename, TextColor());
}

QIcon TextColorIcon(const QIcon& ico)
{
    return SingleColorIcon(ico, TextColor());
}
<|endoftext|>


<commit_before><commit_msg>dev: Fixed some issues with console functions.<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "rpcclient.h"

#include "rpcprotocol.h"
#include "util.h"
#include "ui_interface.h"
#include "chainparams.h" // for Params().RPCPort()

#include <stdint.h>

#include <boost/algorithm/string.hpp>
#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/iostreams/concepts.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/shared_ptr.hpp>
#include "json/json_spirit_writer_template.h"

using namespace std;
using namespace boost;
using namespace boost::asio;
using namespace json_spirit;

Object CallRPC(const string& strMethod, const Array& params)
{
    if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
        throw runtime_error(strprintf(
            _("You must set rpcpassword=<password> in the configuration file:\n%s\n"
              "If the file does not exist, create it with owner-readable-only file permissions."),
                GetConfigFile().string().c_str()));

    // Connect to localhost
    bool fUseSSL = GetBoolArg("-rpcssl", false);
    asio::io_service io_service;
    ssl::context context(io_service, ssl::context::sslv23);
    context.set_options(ssl::context::no_sslv2);
    asio::ssl::stream<asio::ip::tcp::socket> sslStream(io_service, context);
    SSLIOStreamDevice<asio::ip::tcp> d(sslStream, fUseSSL);
    iostreams::stream< SSLIOStreamDevice<asio::ip::tcp> > stream(d);

    bool fWait = GetBoolArg("-rpcwait", false); // -rpcwait means try until server has started
    do {
        bool fConnected = d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", itostr(Params().RPCPort())));
        if (fConnected) break;
        if (fWait)
            MilliSleep(1000);
        else
            throw runtime_error("couldn't connect to server");
    } while (fWait);

    // HTTP basic authentication
    string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);
    map<string, string> mapRequestHeaders;
    mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64;

    // Send request
    string strRequest = JSONRPCRequest(strMethod, params, 1);
    string strPost = HTTPPost(strRequest, mapRequestHeaders);
    stream << strPost << std::flush;

    // Receive HTTP reply status
    int nProto = 0;
    int nStatus = ReadHTTPStatus(stream, nProto);

    // Receive HTTP reply message headers and body
    map<string, string> mapHeaders;
    string strReply;
    ReadHTTPMessage(stream, mapHeaders, strReply, nProto);

    if (nStatus == HTTP_UNAUTHORIZED)
        throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
    else if (nStatus >= 400 && nStatus != HTTP_BAD_REQUEST && nStatus != HTTP_NOT_FOUND && nStatus != HTTP_INTERNAL_SERVER_ERROR)
        throw runtime_error(strprintf("server returned HTTP error %d", nStatus));
    else if (strReply.empty())
        throw runtime_error("no response from server");

    // Parse reply
    Value valReply;
    if (!read_string(strReply, valReply))
        throw runtime_error("couldn't parse reply from server");
    const Object& reply = valReply.get_obj();
    if (reply.empty())
        throw runtime_error("expected reply to have result, error and id properties");

    return reply;
}

template<typename T>
void ConvertTo(Value& value, bool fAllowNull=false)
{
    if (fAllowNull && value.type() == null_type)
        return;
    if (value.type() == str_type)
    {
        // reinterpret string as unquoted json value
        Value value2;
        string strJSON = value.get_str();
        if (!read_string(strJSON, value2))
            throw runtime_error(string("Error parsing JSON:")+strJSON);
        ConvertTo<T>(value2, fAllowNull);
        value = value2;
    }
    else
    {
        value = value.get_value<T>();
    }
}

// Convert strings to command-specific RPC representation
Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams)
{
    Array params;
    BOOST_FOREACH(const std::string &param, strParams)
        params.push_back(param);

    int n = params.size();

    //
    // Special case non-string parameter types
    //
    if (strMethod == "stop"                   && n > 0) ConvertTo<bool>(params[0]);
    if (strMethod == "getaddednodeinfo"       && n > 0) ConvertTo<bool>(params[0]);
    if (strMethod == "setgenerate"            && n > 0) ConvertTo<bool>(params[0]);
    if (strMethod == "setgenerate"            && n > 1) ConvertTo<boost::int64_t>(params[1]);
    if (strMethod == "getnetworkhashps"       && n > 0) ConvertTo<boost::int64_t>(params[0]);
    if (strMethod == "getnetworkhashps"       && n > 1) ConvertTo<boost::int64_t>(params[1]);
    if (strMethod == "sendtoaddress"          && n > 1) ConvertTo<double>(params[1]);
    if (strMethod == "settxfee"               && n > 0) ConvertTo<double>(params[0]);
    if (strMethod == "getreceivedbyaddress"   && n > 1) ConvertTo<boost::int64_t>(params[1]);
    if (strMethod == "getreceivedbyaccount"   && n > 1) ConvertTo<boost::int64_t>(params[1]);
    if (strMethod == "listreceivedbyaddress"  && n > 0) ConvertTo<boost::int64_t>(params[0]);
    if (strMethod == "listreceivedbyaddress"  && n > 1) ConvertTo<bool>(params[1]);
    if (strMethod == "listreceivedbyaccount"  && n > 0) ConvertTo<boost::int64_t>(params[0]);
    if (strMethod == "listreceivedbyaccount"  && n > 1) ConvertTo<bool>(params[1]);
    if (strMethod == "getbalance"             && n > 1) ConvertTo<boost::int64_t>(params[1]);
    if (strMethod == "getblockhash"           && n > 0) ConvertTo<boost::int64_t>(params[0]);
    if (strMethod == "move"                   && n > 2) ConvertTo<double>(params[2]);
    if (strMethod == "move"                   && n > 3) ConvertTo<boost::int64_t>(params[3]);
    if (strMethod == "sendfrom"               && n > 2) ConvertTo<double>(params[2]);
    if (strMethod == "sendfrom"               && n > 3) ConvertTo<boost::int64_t>(params[3]);
    if (strMethod == "listtransactions"       && n > 1) ConvertTo<boost::int64_t>(params[1]);
    if (strMethod == "listtransactions"       && n > 2) ConvertTo<boost::int64_t>(params[2]);
    if (strMethod == "listaccounts"           && n > 0) ConvertTo<boost::int64_t>(params[0]);
    if (strMethod == "walletpassphrase"       && n > 1) ConvertTo<boost::int64_t>(params[1]);
    if (strMethod == "getblocktemplate"       && n > 0) ConvertTo<Object>(params[0]);
    if (strMethod == "listsinceblock"         && n > 1) ConvertTo<boost::int64_t>(params[1]);
    if (strMethod == "sendmany"               && n > 1) ConvertTo<Object>(params[1]);
    if (strMethod == "sendmany"               && n > 2) ConvertTo<boost::int64_t>(params[2]);
    if (strMethod == "addmultisigaddress"     && n > 0) ConvertTo<boost::int64_t>(params[0]);
    if (strMethod == "addmultisigaddress"     && n > 1) ConvertTo<Array>(params[1]);
    if (strMethod == "createmultisig"         && n > 0) ConvertTo<boost::int64_t>(params[0]);
    if (strMethod == "createmultisig"         && n > 1) ConvertTo<Array>(params[1]);
    if (strMethod == "listunspent"            && n > 0) ConvertTo<boost::int64_t>(params[0]);
    if (strMethod == "listunspent"            && n > 1) ConvertTo<boost::int64_t>(params[1]);
    if (strMethod == "listunspent"            && n > 2) ConvertTo<Array>(params[2]);
    if (strMethod == "getblock"               && n > 1) ConvertTo<bool>(params[1]);
    if (strMethod == "getrawtransaction"      && n > 1) ConvertTo<boost::int64_t>(params[1]);
    if (strMethod == "createrawtransaction"   && n > 0) ConvertTo<Array>(params[0]);
    if (strMethod == "createrawtransaction"   && n > 1) ConvertTo<Object>(params[1]);
    if (strMethod == "signrawtransaction"     && n > 1) ConvertTo<Array>(params[1], true);
    if (strMethod == "signrawtransaction"     && n > 2) ConvertTo<Array>(params[2], true);
    if (strMethod == "sendrawtransaction"     && n > 1) ConvertTo<bool>(params[1], true);
    if (strMethod == "gettxout"               && n > 1) ConvertTo<boost::int64_t>(params[1]);
    if (strMethod == "gettxout"               && n > 2) ConvertTo<bool>(params[2]);
    if (strMethod == "lockunspent"            && n > 0) ConvertTo<bool>(params[0]);
    if (strMethod == "lockunspent"            && n > 1) ConvertTo<Array>(params[1]);
    if (strMethod == "importprivkey"          && n > 2) ConvertTo<bool>(params[2]);
    if (strMethod == "verifychain"            && n > 0) ConvertTo<boost::int64_t>(params[0]);
    if (strMethod == "verifychain"            && n > 1) ConvertTo<boost::int64_t>(params[1]);
    if (strMethod == "keypoolrefill"          && n > 0) ConvertTo<boost::int64_t>(params[0]);
    if (strMethod == "getrawmempool"          && n > 0) ConvertTo<bool>(params[0]);

    return params;
}

int CommandLineRPC(int argc, char *argv[])
{
    string strPrint;
    int nRet = 0;
    try
    {
        // Skip switches
        while (argc > 1 && IsSwitchChar(argv[1][0]))
        {
            argc--;
            argv++;
        }

        // Method
        if (argc < 2)
            throw runtime_error("too few parameters");
        string strMethod = argv[1];

        // Parameters default to strings
        std::vector<std::string> strParams(&argv[2], &argv[argc]);
        Array params = RPCConvertValues(strMethod, strParams);

        // Execute
        Object reply = CallRPC(strMethod, params);

        // Parse reply
        const Value& result = find_value(reply, "result");
        const Value& error  = find_value(reply, "error");

        if (error.type() != null_type)
        {
            // Error
            strPrint = "error: " + write_string(error, false);
            int code = find_value(error.get_obj(), "code").get_int();
            nRet = abs(code);
        }
        else
        {
            // Result
            if (result.type() == null_type)
                strPrint = "";
            else if (result.type() == str_type)
                strPrint = result.get_str();
            else
                strPrint = write_string(result, true);
        }
    }
    catch (boost::thread_interrupted) {
        throw;
    }
    catch (std::exception& e) {
        strPrint = string("error: ") + e.what();
        nRet = abs(RPC_MISC_ERROR);
    }
    catch (...) {
        PrintExceptionContinue(NULL, "CommandLineRPC()");
        throw;
    }

    if (strPrint != "")
    {
        fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
    }
    return nRet;
}

std::string HelpMessageCli(bool mainProgram)
{
    string strUsage;
    if(mainProgram)
    {
        strUsage += _("Options:") + "\n";
        strUsage += "  -?                     " + _("This help message") + "\n";
        strUsage += "  -conf=<file>           " + _("Specify configuration file (default: fractalcoin.conf)") + "\n";
        strUsage += "  -datadir=<dir>         " + _("Specify data directory") + "\n";
        strUsage += "  -testnet               " + _("Use the test network") + "\n";
        strUsage += "  -regtest               " + _("Enter regression test mode, which uses a special chain in which blocks can be "
                                                    "solved instantly. This is intended for regression testing tools and app development.") + "\n";
    } else {
        strUsage += _("RPC client options:") + "\n";
    }

    strUsage += "  -rpcconnect=<ip>       " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n";
    strUsage += "  -rpcport=<port>        " + _("Connect to JSON-RPC on <port> (default: 33111 or testnet: 44111)") + "\n";
    strUsage += "  -rpcwait               " + _("Wait for RPC server to start") + "\n";
    strUsage += "  -rpcuser=<user>        " + _("Username for JSON-RPC connections") + "\n";
    strUsage += "  -rpcpassword=<pw>      " + _("Password for JSON-RPC connections") + "\n";

    if(mainProgram)
    {
        strUsage += "\n" + _("SSL options: (see the Bitcoin Wiki for SSL setup instructions)") + "\n";
        strUsage += "  -rpcssl                " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n";
    }

    return strUsage;
}

<commit_msg>carry over rpcclient changes from bitcoin<commit_after>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "rpcclient.h"

#include "rpcprotocol.h"
#include "util.h"
#include "ui_interface.h"
#include "chainparams.h" // for Params().RPCPort()

#include <stdint.h>

#include <boost/algorithm/string.hpp>
#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/iostreams/concepts.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/shared_ptr.hpp>
#include "json/json_spirit_writer_template.h"

using namespace std;
using namespace boost;
using namespace boost::asio;
using namespace json_spirit;

Object CallRPC(const string& strMethod, const Array& params)
{
    if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
        throw runtime_error(strprintf(
            _("You must set rpcpassword=<password> in the configuration file:\n%s\n"
              "If the file does not exist, create it with owner-readable-only file permissions."),
                GetConfigFile().string().c_str()));

    // Connect to localhost
    bool fUseSSL = GetBoolArg("-rpcssl", false);
    asio::io_service io_service;
    ssl::context context(io_service, ssl::context::sslv23);
    context.set_options(ssl::context::no_sslv2);
    asio::ssl::stream<asio::ip::tcp::socket> sslStream(io_service, context);
    SSLIOStreamDevice<asio::ip::tcp> d(sslStream, fUseSSL);
    iostreams::stream< SSLIOStreamDevice<asio::ip::tcp> > stream(d);

    bool fWait = GetBoolArg("-rpcwait", false); // -rpcwait means try until server has started
    do {
        bool fConnected = d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", itostr(Params().RPCPort())));
        if (fConnected) break;
        if (fWait)
            MilliSleep(1000);
        else
            throw runtime_error("couldn't connect to server");
    } while (fWait);

    // HTTP basic authentication
    string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);
    map<string, string> mapRequestHeaders;
    mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64;

    // Send request
    string strRequest = JSONRPCRequest(strMethod, params, 1);
    string strPost = HTTPPost(strRequest, mapRequestHeaders);
    stream << strPost << std::flush;

    // Receive HTTP reply status
    int nProto = 0;
    int nStatus = ReadHTTPStatus(stream, nProto);

    // Receive HTTP reply message headers and body
    map<string, string> mapHeaders;
    string strReply;
    ReadHTTPMessage(stream, mapHeaders, strReply, nProto);

    if (nStatus == HTTP_UNAUTHORIZED)
        throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
    else if (nStatus >= 400 && nStatus != HTTP_BAD_REQUEST && nStatus != HTTP_NOT_FOUND && nStatus != HTTP_INTERNAL_SERVER_ERROR)
        throw runtime_error(strprintf("server returned HTTP error %d", nStatus));
    else if (strReply.empty())
        throw runtime_error("no response from server");

    // Parse reply
    Value valReply;
    if (!read_string(strReply, valReply))
        throw runtime_error("couldn't parse reply from server");
    const Object& reply = valReply.get_obj();
    if (reply.empty())
        throw runtime_error("expected reply to have result, error and id properties");

    return reply;
}

template<typename T>
void ConvertTo(Value& value, bool fAllowNull=false)
{
    if (fAllowNull && value.type() == null_type)
        return;
    if (value.type() == str_type)
    {
        // reinterpret string as unquoted json value
        Value value2;
        string strJSON = value.get_str();
        if (!read_string(strJSON, value2))
            throw runtime_error(string("Error parsing JSON:")+strJSON);
        ConvertTo<T>(value2, fAllowNull);
        value = value2;
    }
    else
    {
        value = value.get_value<T>();
    }
}

// Convert strings to command-specific RPC representation
Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams)
{
    Array params;
    BOOST_FOREACH(const std::string &param, strParams)
        params.push_back(param);

    int n = params.size();

    //
    // Special case non-string parameter types
    //
    if (strMethod == "stop"                   && n > 0) ConvertTo<bool>(params[0]);
    if (strMethod == "getaddednodeinfo"       && n > 0) ConvertTo<bool>(params[0]);
    if (strMethod == "setgenerate"            && n > 0) ConvertTo<bool>(params[0]);
    if (strMethod == "setgenerate"            && n > 1) ConvertTo<boost::int64_t>(params[1]);
    if (strMethod == "getnetworkhashps"       && n > 0) ConvertTo<boost::int64_t>(params[0]);
    if (strMethod == "getnetworkhashps"       && n > 1) ConvertTo<boost::int64_t>(params[1]);
    if (strMethod == "sendtoaddress"          && n > 1) ConvertTo<double>(params[1]);
    if (strMethod == "sendtoaddress"          && n > 4) ConvertTo<bool>(params[4]);
    if (strMethod == "settxfee"               && n > 0) ConvertTo<double>(params[0]);
    if (strMethod == "getreceivedbyaddress"   && n > 1) ConvertTo<boost::int64_t>(params[1]);
    if (strMethod == "getreceivedbyaccount"   && n > 1) ConvertTo<boost::int64_t>(params[1]);
    if (strMethod == "listreceivedbyaddress"  && n > 0) ConvertTo<boost::int64_t>(params[0]);
    if (strMethod == "listreceivedbyaddress"  && n > 1) ConvertTo<bool>(params[1]);
    if (strMethod == "listreceivedbyaccount"  && n > 0) ConvertTo<boost::int64_t>(params[0]);
    if (strMethod == "listreceivedbyaccount"  && n > 1) ConvertTo<bool>(params[1]);
    if (strMethod == "getbalance"             && n > 1) ConvertTo<boost::int64_t>(params[1]);
    if (strMethod == "getblockhash"           && n > 0) ConvertTo<boost::int64_t>(params[0]);
    if (strMethod == "move"                   && n > 2) ConvertTo<double>(params[2]);
    if (strMethod == "move"                   && n > 3) ConvertTo<boost::int64_t>(params[3]);
    if (strMethod == "sendfrom"               && n > 2) ConvertTo<double>(params[2]);
    if (strMethod == "sendfrom"               && n > 3) ConvertTo<boost::int64_t>(params[3]);
    if (strMethod == "sendfrom"               && n > 6) ConvertTo<bool>(params[6]);
    if (strMethod == "listtransactions"       && n > 1) ConvertTo<boost::int64_t>(params[1]);
    if (strMethod == "listtransactions"       && n > 2) ConvertTo<boost::int64_t>(params[2]);
    if (strMethod == "listaccounts"           && n > 0) ConvertTo<boost::int64_t>(params[0]);
    if (strMethod == "walletpassphrase"       && n > 1) ConvertTo<boost::int64_t>(params[1]);
    if (strMethod == "getblocktemplate"       && n > 0) ConvertTo<Object>(params[0]);
    if (strMethod == "listsinceblock"         && n > 1) ConvertTo<boost::int64_t>(params[1]);
    if (strMethod == "sendmany"               && n > 1) ConvertTo<Object>(params[1]);
    if (strMethod == "sendmany"               && n > 2) ConvertTo<boost::int64_t>(params[2]);
    if (strMethod == "sendmany"               && n > 4) ConvertTo<bool>(params[2]);
    if (strMethod == "addmultisigaddress"     && n > 0) ConvertTo<boost::int64_t>(params[0]);
    if (strMethod == "addmultisigaddress"     && n > 1) ConvertTo<Array>(params[1]);
    if (strMethod == "createmultisig"         && n > 0) ConvertTo<boost::int64_t>(params[0]);
    if (strMethod == "createmultisig"         && n > 1) ConvertTo<Array>(params[1]);
    if (strMethod == "listunspent"            && n > 0) ConvertTo<boost::int64_t>(params[0]);
    if (strMethod == "listunspent"            && n > 1) ConvertTo<boost::int64_t>(params[1]);
    if (strMethod == "listunspent"            && n > 2) ConvertTo<Array>(params[2]);
    if (strMethod == "getblock"               && n > 1) ConvertTo<bool>(params[1]);
    if (strMethod == "getrawtransaction"      && n > 1) ConvertTo<boost::int64_t>(params[1]);
    if (strMethod == "createrawtransaction"   && n > 0) ConvertTo<Array>(params[0]);
    if (strMethod == "createrawtransaction"   && n > 1) ConvertTo<Object>(params[1]);
    if (strMethod == "signrawtransaction"     && n > 1) ConvertTo<Array>(params[1], true);
    if (strMethod == "signrawtransaction"     && n > 2) ConvertTo<Array>(params[2], true);
    if (strMethod == "sendrawtransaction"     && n > 1) ConvertTo<bool>(params[1], true);
    if (strMethod == "gettxout"               && n > 1) ConvertTo<boost::int64_t>(params[1]);
    if (strMethod == "gettxout"               && n > 2) ConvertTo<bool>(params[2]);
    if (strMethod == "lockunspent"            && n > 0) ConvertTo<bool>(params[0]);
    if (strMethod == "lockunspent"            && n > 1) ConvertTo<Array>(params[1]);
    if (strMethod == "importprivkey"          && n > 2) ConvertTo<bool>(params[2]);
    if (strMethod == "verifychain"            && n > 0) ConvertTo<boost::int64_t>(params[0]);
    if (strMethod == "verifychain"            && n > 1) ConvertTo<boost::int64_t>(params[1]);
    if (strMethod == "keypoolrefill"          && n > 0) ConvertTo<boost::int64_t>(params[0]);
    if (strMethod == "getrawmempool"          && n > 0) ConvertTo<bool>(params[0]);

    return params;
}

int CommandLineRPC(int argc, char *argv[])
{
    string strPrint;
    int nRet = 0;
    try
    {
        // Skip switches
        while (argc > 1 && IsSwitchChar(argv[1][0]))
        {
            argc--;
            argv++;
        }

        // Method
        if (argc < 2)
            throw runtime_error("too few parameters");
        string strMethod = argv[1];

        // Parameters default to strings
        std::vector<std::string> strParams(&argv[2], &argv[argc]);
        Array params = RPCConvertValues(strMethod, strParams);

        // Execute
        Object reply = CallRPC(strMethod, params);

        // Parse reply
        const Value& result = find_value(reply, "result");
        const Value& error  = find_value(reply, "error");

        if (error.type() != null_type)
        {
            // Error
            strPrint = "error: " + write_string(error, false);
            int code = find_value(error.get_obj(), "code").get_int();
            nRet = abs(code);
        }
        else
        {
            // Result
            if (result.type() == null_type)
                strPrint = "";
            else if (result.type() == str_type)
                strPrint = result.get_str();
            else
                strPrint = write_string(result, true);
        }
    }
    catch (boost::thread_interrupted) {
        throw;
    }
    catch (std::exception& e) {
        strPrint = string("error: ") + e.what();
        nRet = abs(RPC_MISC_ERROR);
    }
    catch (...) {
        PrintExceptionContinue(NULL, "CommandLineRPC()");
        throw;
    }

    if (strPrint != "")
    {
        fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
    }
    return nRet;
}

std::string HelpMessageCli(bool mainProgram)
{
    string strUsage;
    if(mainProgram)
    {
        strUsage += _("Options:") + "\n";
        strUsage += "  -?                     " + _("This help message") + "\n";
        strUsage += "  -conf=<file>           " + _("Specify configuration file (default: fractalcoin.conf)") + "\n";
        strUsage += "  -datadir=<dir>         " + _("Specify data directory") + "\n";
        strUsage += "  -testnet               " + _("Use the test network") + "\n";
        strUsage += "  -regtest               " + _("Enter regression test mode, which uses a special chain in which blocks can be "
                                                    "solved instantly. This is intended for regression testing tools and app development.") + "\n";
    } else {
        strUsage += _("RPC client options:") + "\n";
    }

    strUsage += "  -rpcconnect=<ip>       " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n";
    strUsage += "  -rpcport=<port>        " + _("Connect to JSON-RPC on <port> (default: 33111 or testnet: 44111)") + "\n";
    strUsage += "  -rpcwait               " + _("Wait for RPC server to start") + "\n";
    strUsage += "  -rpcuser=<user>        " + _("Username for JSON-RPC connections") + "\n";
    strUsage += "  -rpcpassword=<pw>      " + _("Password for JSON-RPC connections") + "\n";

    if(mainProgram)
    {
        strUsage += "\n" + _("SSL options: (see the Bitcoin Wiki for SSL setup instructions)") + "\n";
        strUsage += "  -rpcssl                " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n";
    }

    return strUsage;
}

<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014 liblcf authors
 * This file is released under the MIT License
 * http://opensource.org/licenses/MIT
 */

#include "reader_options.h"
#include "rpg_actor.h"
#include "rpg_event.h"
#include "rpg_map.h"
#include "rpg_mapinfo.h"
#include "rpg_system.h"
#include "rpg_save.h"
#include "rpg_chipset.h"
#include "rpg_parameters.h"
#include "data.h"

void RPG::SaveActor::Setup(int actor_id) {
	const RPG::Actor& actor = Data::actors[actor_id - 1];
	ID = actor.ID;
	name = actor.name;
	title = actor.title;
	sprite_name = actor.character_name;
	sprite_id = actor.character_index;
	sprite_flags = actor.transparent ? 3 : 0;
	face_name = actor.face_name;
	face_id = actor.face_index;
	level = actor.initial_level;
	exp = 0;
	hp_mod = 0;
	sp_mod = 0;
	attack_mod = 0;
	defense_mod = 0;
	spirit_mod = 0;
	agility_mod = 0;
	skills_size = 0;
	skills.clear();
	equipped.clear();
	equipped.push_back(actor.initial_equipment.weapon_id);
	equipped.push_back(actor.initial_equipment.shield_id);
	equipped.push_back(actor.initial_equipment.armor_id);
	equipped.push_back(actor.initial_equipment.helmet_id);
	equipped.push_back(actor.initial_equipment.accessory_id);
	current_hp = 0;
	current_sp = 0;
	battle_commands = actor.battle_commands;
	status_size = 0;
	status.clear();
	changed_class = false;
	class_id = actor.class_id;
	row = -1;
	two_weapon = actor.two_swords_style;
	lock_equipment = actor.fix_equipment;
	auto_battle = actor.auto_battle;
	mighty_guard = actor.super_guard;
	unknown_60 = -1;
}

void RPG::SaveInventory::Setup() {
	party = Data::system.party;
	party_size = party.size();
}

void RPG::SaveMapEvent::Setup(const RPG::Event& event) {
	ID = event.ID;
	position_x = event.x;
	position_y = event.y;
}

void RPG::SaveMapInfo::Setup() {
	position_x = 0;
	position_y = 0;
	lower_tiles.resize(144);
	upper_tiles.resize(144);
	for (int i = 0; i < 144; i++) {
		lower_tiles[i] = i;
		upper_tiles[i] = i;
	}
}

void RPG::SaveMapInfo::Setup(const RPG::Map& map) {
	chipset_id = map.chipset_id;
	parallax_name = map.parallax_name;
	parallax_horz = map.parallax_loop_x;
	parallax_vert = map.parallax_loop_y;
	parallax_horz_auto = map.parallax_auto_loop_x;
	parallax_vert_auto = map.parallax_auto_loop_y;
	parallax_horz_speed = map.parallax_sx;
	parallax_vert_speed = map.parallax_sy;
}

void RPG::SaveMapInfo::Setup(const RPG::MapInfo& map_info) {
	encounter_rate = map_info.encounter_steps;
}

void RPG::SaveSystem::Setup() {
	const RPG::System& system = Data::system;
	screen = 0;
	frame_count = 0;
	graphics_name = system.system_name;
	switches_size = Data::switches.size();
	switches.clear();
	switches.resize(switches_size);
	variables_size = Data::variables.size();
	variables.clear();
	variables.resize(variables_size);
	face_name = "";
	face_id = -1;
	face_right = false;
	face_flip = false;
	transparent = false;
	unknown_3d_music_fadeout = -1;
	title_music = system.title_music;
	battle_music = system.battle_music;
	battle_end_music = system.battle_end_music;
	inn_music = system.inn_music;
	// current_music
	// unknown1_music FIXME
	// unknown2_music FIXME
	// stored_music
	boat_music = system.boat_music;
	ship_music = system.ship_music;
	airship_music = system.airship_music;
	gameover_music = system.gameover_music;
	cursor_se = system.cursor_se;
	decision_se = system.decision_se;
	cancel_se = system.cancel_se;
	buzzer_se = system.buzzer_se;
	battle_se = system.battle_se;
	escape_se = system.escape_se;
	enemy_attack_se = system.enemy_attack_se;
	enemy_damaged_se = system.enemy_damaged_se;
	actor_damaged_se = system.actor_damaged_se;
	dodge_se = system.dodge_se;
	enemy_death_se = system.enemy_death_se;
	item_se = system.item_se;
	transition_out = system.transition_out;
	transition_in = system.transition_in;
	battle_start_fadeout = system.battle_start_fadeout;
	battle_start_fadein = system.battle_start_fadein;
	battle_end_fadeout = system.battle_end_fadeout;
	battle_end_fadein = system.battle_end_fadein;
	teleport_allowed = true;
	escape_allowed = true;
	save_allowed = true;
	menu_allowed = true;
	background = "";
	save_count = 0;
	save_slot = -1;
}

void RPG::Save::Setup() {
	system.Setup();
	screen = RPG::SaveScreen();
	pictures.clear();
	pictures.resize(50);
	for (int i = 1; i <= (int)pictures.size(); i++) {
		pictures[i - 1].ID = i;
	}
	actors.clear();
	actors.resize(Data::actors.size());
	for (int i = 1; i <= (int) actors.size(); i++)
		actors[i - 1].Setup(i);
	map_info.Setup();
}

void RPG::Actor::Setup() {
	if (Data::system.ldb_id == 2003) {
		final_level = final_level == -1 ? 99 : final_level;
		exp_base = exp_base == -1 ? 300 : exp_base;
		exp_inflation = exp_inflation == -1 ? 300 : exp_inflation;
	}
	else {
		final_level = final_level == -1 ? 50 : final_level;
		exp_base = exp_base == -1 ? 30 : exp_base;
		exp_inflation = exp_inflation == -1 ? 30 : exp_inflation;
	}
	parameters.Setup(final_level);
}

void RPG::MapInfo::Init() {
	music.name = "(OFF)";
}

void RPG::Chipset::Init() {
	terrain_data.resize(162, 1);
	passable_data_lower.resize(162, 15);
	passable_data_upper.resize(144, 15);
	passable_data_upper.front() = 31;
}

void RPG::Parameters::Setup(int final_level) {
	maxhp.resize(final_level, 1);
	maxsp.resize(final_level, 0);
	attack.resize(final_level, 1);
	defense.resize(final_level, 1);
	spirit.resize(final_level, 1);
	agility.resize(final_level, 1);
}
<commit_msg>Copy message stretch to savegame. Required by Player#479<commit_after>/*
 * Copyright (c) 2014 liblcf authors
 * This file is released under the MIT License
 * http://opensource.org/licenses/MIT
 */

#include "reader_options.h"
#include "rpg_actor.h"
#include "rpg_event.h"
#include "rpg_map.h"
#include "rpg_mapinfo.h"
#include "rpg_system.h"
#include "rpg_save.h"
#include "rpg_chipset.h"
#include "rpg_parameters.h"
#include "data.h"

void RPG::SaveActor::Setup(int actor_id) {
	const RPG::Actor& actor = Data::actors[actor_id - 1];
	ID = actor.ID;
	name = actor.name;
	title = actor.title;
	sprite_name = actor.character_name;
	sprite_id = actor.character_index;
	sprite_flags = actor.transparent ? 3 : 0;
	face_name = actor.face_name;
	face_id = actor.face_index;
	level = actor.initial_level;
	exp = 0;
	hp_mod = 0;
	sp_mod = 0;
	attack_mod = 0;
	defense_mod = 0;
	spirit_mod = 0;
	agility_mod = 0;
	skills_size = 0;
	skills.clear();
	equipped.clear();
	equipped.push_back(actor.initial_equipment.weapon_id);
	equipped.push_back(actor.initial_equipment.shield_id);
	equipped.push_back(actor.initial_equipment.armor_id);
	equipped.push_back(actor.initial_equipment.helmet_id);
	equipped.push_back(actor.initial_equipment.accessory_id);
	current_hp = 0;
	current_sp = 0;
	battle_commands = actor.battle_commands;
	status_size = 0;
	status.clear();
	changed_class = false;
	class_id = actor.class_id;
	row = -1;
	two_weapon = actor.two_swords_style;
	lock_equipment = actor.fix_equipment;
	auto_battle = actor.auto_battle;
	mighty_guard = actor.super_guard;
	unknown_60 = -1;
}

void RPG::SaveInventory::Setup() {
	party = Data::system.party;
	party_size = party.size();
}

void RPG::SaveMapEvent::Setup(const RPG::Event& event) {
	ID = event.ID;
	position_x = event.x;
	position_y = event.y;
}

void RPG::SaveMapInfo::Setup() {
	position_x = 0;
	position_y = 0;
	lower_tiles.resize(144);
	upper_tiles.resize(144);
	for (int i = 0; i < 144; i++) {
		lower_tiles[i] = i;
		upper_tiles[i] = i;
	}
}

void RPG::SaveMapInfo::Setup(const RPG::Map& map) {
	chipset_id = map.chipset_id;
	parallax_name = map.parallax_name;
	parallax_horz = map.parallax_loop_x;
	parallax_vert = map.parallax_loop_y;
	parallax_horz_auto = map.parallax_auto_loop_x;
	parallax_vert_auto = map.parallax_auto_loop_y;
	parallax_horz_speed = map.parallax_sx;
	parallax_vert_speed = map.parallax_sy;
}

void RPG::SaveMapInfo::Setup(const RPG::MapInfo& map_info) {
	encounter_rate = map_info.encounter_steps;
}

void RPG::SaveSystem::Setup() {
	const RPG::System& system = Data::system;
	screen = 0;
	frame_count = 0;
	graphics_name = system.system_name;
	switches_size = Data::switches.size();
	switches.clear();
	switches.resize(switches_size);
	variables_size = Data::variables.size();
	variables.clear();
	variables.resize(variables_size);
	face_name = "";
	face_id = -1;
	face_right = false;
	face_flip = false;
	transparent = false;
	unknown_3d_music_fadeout = -1;
	title_music = system.title_music;
	battle_music = system.battle_music;
	battle_end_music = system.battle_end_music;
	inn_music = system.inn_music;
	// current_music
	// unknown1_music FIXME
	// unknown2_music FIXME
	// stored_music
	boat_music = system.boat_music;
	ship_music = system.ship_music;
	airship_music = system.airship_music;
	gameover_music = system.gameover_music;
	cursor_se = system.cursor_se;
	decision_se = system.decision_se;
	cancel_se = system.cancel_se;
	buzzer_se = system.buzzer_se;
	battle_se = system.battle_se;
	escape_se = system.escape_se;
	enemy_attack_se = system.enemy_attack_se;
	enemy_damaged_se = system.enemy_damaged_se;
	actor_damaged_se = system.actor_damaged_se;
	dodge_se = system.dodge_se;
	enemy_death_se = system.enemy_death_se;
	item_se = system.item_se;
	transition_out = system.transition_out;
	transition_in = system.transition_in;
	battle_start_fadeout = system.battle_start_fadeout;
	battle_start_fadein = system.battle_start_fadein;
	battle_end_fadeout = system.battle_end_fadeout;
	battle_end_fadein = system.battle_end_fadein;
	message_stretch = system.message_stretch;
	teleport_allowed = true;
	escape_allowed = true;
	save_allowed = true;
	menu_allowed = true;
	background = "";
	save_count = 0;
	save_slot = -1;
}

void RPG::Save::Setup() {
	system.Setup();
	screen = RPG::SaveScreen();
	pictures.clear();
	pictures.resize(50);
	for (int i = 1; i <= (int)pictures.size(); i++) {
		pictures[i - 1].ID = i;
	}
	actors.clear();
	actors.resize(Data::actors.size());
	for (int i = 1; i <= (int) actors.size(); i++)
		actors[i - 1].Setup(i);
	map_info.Setup();
}

void RPG::Actor::Setup() {
	if (Data::system.ldb_id == 2003) {
		final_level = final_level == -1 ? 99 : final_level;
		exp_base = exp_base == -1 ? 300 : exp_base;
		exp_inflation = exp_inflation == -1 ? 300 : exp_inflation;
	}
	else {
		final_level = final_level == -1 ? 50 : final_level;
		exp_base = exp_base == -1 ? 30 : exp_base;
		exp_inflation = exp_inflation == -1 ? 30 : exp_inflation;
	}
	parameters.Setup(final_level);
}

void RPG::MapInfo::Init() {
	music.name = "(OFF)";
}

void RPG::Chipset::Init() {
	terrain_data.resize(162, 1);
	passable_data_lower.resize(162, 15);
	passable_data_upper.resize(144, 15);
	passable_data_upper.front() = 31;
}

void RPG::Parameters::Setup(int final_level) {
	maxhp.resize(final_level, 1);
	maxsp.resize(final_level, 0);
	attack.resize(final_level, 1);
	defense.resize(final_level, 1);
	spirit.resize(final_level, 1);
	agility.resize(final_level, 1);
}
<|endoftext|>