hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e1f1de31733247187346cd74863b641aa6dc772b | 2,974 | cc | C++ | lib/kahypar/tools/remove_heavy_nodes.cc | sjkelly/LSOracle | 21688c5d542740dfc8577349fa615ee655acd92c | [
"MIT"
] | null | null | null | lib/kahypar/tools/remove_heavy_nodes.cc | sjkelly/LSOracle | 21688c5d542740dfc8577349fa615ee655acd92c | [
"MIT"
] | 1 | 2021-07-26T22:09:49.000Z | 2021-07-26T22:09:49.000Z | lib/kahypar/tools/remove_heavy_nodes.cc | sjkelly/LSOracle | 21688c5d542740dfc8577349fa615ee655acd92c | [
"MIT"
] | 2 | 2021-07-26T14:46:51.000Z | 2021-11-09T11:32:09.000Z | /*******************************************************************************
* This file is part of KaHyPar.
*
* Copyright (C) 2020 Nikolai Maas <nikolai.maas@student.kit.edu>
*
* KaHyPar is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* KaHyPar 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 KaHyPar. If not, see <http://www.gnu.org/licenses/>.
*
******************************************************************************/
#include "kahypar/definitions.h"
#include "kahypar/io/hypergraph_io.h"
#include "kahypar/macros.h"
using namespace kahypar;
HypernodeID removeHeavyNodes(Hypergraph& hypergraph, HypernodeID k, double epsilon) {
HypernodeWeight total_weight = hypergraph.totalWeight();
HypernodeID new_k = k;
std::vector<HypernodeID> to_remove;
do {
HypernodeWeight allowed_block_weight = std::floor((1 + epsilon)
* ceil(static_cast<double>(total_weight) / new_k));
to_remove.clear();
for (const HypernodeID& hn : hypergraph.nodes()) {
if (hypergraph.nodeWeight(hn) > allowed_block_weight) {
to_remove.push_back(hn);
}
}
for (const HypernodeID& hn : to_remove) {
total_weight -= hypergraph.nodeWeight(hn);
hypergraph.removeNode(hn);
--new_k;
}
} while (!to_remove.empty());
return new_k;
}
int main(int argc, char *argv[]) {
if (argc != 5) {
std::cout << "Wrong number of arguments" << std::endl;
std::cout << "Usage: RemoveHeavyNodes <.hgr> <output_file> <k> <e>" << std::endl;
exit(0);
}
std::string hgr_filename(argv[1]);
std::string output_filename(argv[2]);
HypernodeID k = std::stoul(argv[3]);
double epsilon = std::stod(argv[4]);
Hypergraph hypergraph(io::createHypergraphFromFile(hgr_filename, k));
HypernodeID new_k = removeHeavyNodes(hypergraph, k, epsilon);
for (const HyperedgeID& he : hypergraph.edges()) {
if (hypergraph.edgeSize(he) <= 1) {
hypergraph.removeEdge(he);
}
}
auto modified_hg = ds::reindex(hypergraph);
std::cout << "k=" << new_k << std::endl;
std::cout << "removed=" << (k - new_k) << std::endl;
// change hypergraph type to avoid writing edge weights unnecessarily
bool hasEdgeWeights = false;
for (const HyperedgeID& edge : hypergraph.edges()) {
hasEdgeWeights |= hypergraph.edgeWeight(edge) != 1;
}
if (!hasEdgeWeights) {
modified_hg.first->setType(HypergraphType::NodeWeights);
}
io::writeHypergraphFile(*modified_hg.first, output_filename);
return 0;
}
| 33.41573 | 94 | 0.643578 | [
"vector"
] |
e1f2fd345c4e44d507d63328b48cb7d9d136f777 | 2,835 | cpp | C++ | external/swak/libraries/swakSourceFields/expressionSource.cpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | external/swak/libraries/swakSourceFields/expressionSource.cpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | external/swak/libraries/swakSourceFields/expressionSource.cpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | /*---------------------------------------------------------------------------*\
Copyright: ICE Stroemungsfoschungs GmbH
Copyright held by original author
-------------------------------------------------------------------------------
License
This file is based on CAELUS.
CAELUS is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
CAELUS 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 CAELUS. If not, see <http://www.gnu.org/licenses/>.
Contributors/Copyright:
2010-2011, 2013-2014 Bernhard F.W. Gschaider <bgschaid@ice-sf.at>
\*---------------------------------------------------------------------------*/
#include "expressionSource.hpp"
#include "polyMesh.hpp"
#include "cellSet.hpp"
#include "FieldValueExpressionDriver.hpp"
namespace CML {
// * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * //
// * * * * * * * * * * * * * Private Member Functions * * * * * * * * * * * //
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
// Construct from dictionary
template<class T>
expressionSource<T>::expressionSource
(
const dictionary& dict,
const fvMesh& mesh
)
:
FieldValueExpressionDriver(dict,mesh),
expression_(
dict.lookup("expression"),
dict
)
{
createWriterAndRead(dict.name().name()+"_"+this->type()+"<"+pTraits<T>::typeName+">");
}
// * * * * * * * * * * * * * * * * Destructor * * * * * * * * * * * * * * * //
template<class T>
expressionSource<T>::~expressionSource()
{}
// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
template<class T>
tmp<typename expressionSource<T>::resultField> expressionSource<T>::operator()()
{
clearVariables();
parse(expression_);
if(!resultIsTyp<resultField>()) {
FatalErrorInFunction
<< "Result of " << expression_ << " is not a " << pTraits<T>::typeName
<< endl
<< exit(FatalError);
}
tmp<resultField> result(new resultField(getResult<resultField>()));
return result;
}
template
class expressionSource<scalar>;
template
class expressionSource<vector>;
template
class expressionSource<tensor>;
template
class expressionSource<symmTensor>;
template
class expressionSource<sphericalTensor>;
} // end namespace
// ************************************************************************* //
| 27.524272 | 90 | 0.555203 | [
"mesh",
"vector"
] |
e1f34bdf5f3442a80954a6d4cf25e04baef637f7 | 945 | cpp | C++ | Nov2020/20Nov/BaseballGame.cpp | shivanisbp/2monthsOfCoding | 26dc53e3160c7b313dff974b957c81350bf9f1a1 | [
"MIT"
] | null | null | null | Nov2020/20Nov/BaseballGame.cpp | shivanisbp/2monthsOfCoding | 26dc53e3160c7b313dff974b957c81350bf9f1a1 | [
"MIT"
] | null | null | null | Nov2020/20Nov/BaseballGame.cpp | shivanisbp/2monthsOfCoding | 26dc53e3160c7b313dff974b957c81350bf9f1a1 | [
"MIT"
] | null | null | null | /*
Problem name: Baseball Game
Problem link: https://leetcode.com/problems/baseball-game/
*/
class Solution {
public:
int calPoints(vector<string>& ops) {
int sum=0,i=0,t1=0,t2=0;
stack<int> record;
while(i<ops.size()){
if(ops[i]=="+"){
t1=record.top();
record.pop();
t2=record.top();
record.push(t1);
record.push(t1+t2);
sum+=t1+t2;
}
else if(ops[i]=="D"){
sum+=2*record.top();
record.push(2*record.top());
}
else if(ops[i]=="C"){
sum-=record.top();
record.pop();
}
else{
record.push(stoi(ops[i]));
sum+=stoi(ops[i]);
}
i++;
}
return sum;
}
};
| 23.625 | 58 | 0.367196 | [
"vector"
] |
e1fefabeae35c9431ed3f178398f680182c55e1f | 1,561 | cc | C++ | pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/language/compiler/module.cc | quanpands/wflow | b454a55e4a63556eaac3fbabd97f8a0b80901e5a | [
"MIT"
] | null | null | null | pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/language/compiler/module.cc | quanpands/wflow | b454a55e4a63556eaac3fbabd97f8a0b80901e5a | [
"MIT"
] | null | null | null | pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/language/compiler/module.cc | quanpands/wflow | b454a55e4a63556eaac3fbabd97f8a0b80901e5a | [
"MIT"
] | null | null | null | // -----------------------------------------------------------------------------
// Fern © Geoneric
//
// This file is part of Geoneric Fern which is available under the terms of
// the GNU General Public License (GPL), version 2. If you do not want to
// be bound by the terms of the GPL, you may purchase a proprietary license
// from Geoneric (http://www.geoneric.eu/contact).
// -----------------------------------------------------------------------------
#include "fern/language/compiler/module.h"
namespace fern {
namespace language {
Module::Module(
std::vector<DataDescription> const& arguments,
std::vector<DataDescription> const& results)
: _arguments(arguments),
_results(results)
{
}
std::vector<DataDescription> const& Module::arguments() const
{
return _arguments;
}
std::vector<DataDescription> const& Module::results() const
{
return _results;
}
/*!
@exception std::runtime_error If an error occured.
*/
void Module::check_sources_and_syncs(
std::vector<std::shared_ptr<DataSource>> const& data_sources,
std::vector<std::shared_ptr<DataSync>> const& /* data_syncs */) const
{
if(_arguments.size() > data_sources.size()) {
// TODO Message.
throw std::invalid_argument("Not enough data sources");
}
else if(_arguments.size() < data_sources.size()) {
// TODO Message.
throw std::invalid_argument("Too many data sources");
}
// TODO Compare properties of arguments with properties of data sources.
}
} // namespace language
} // namespace fern
| 26.457627 | 80 | 0.618834 | [
"vector"
] |
c006093f7172e7afa378bd2f65c87ed602de60f2 | 3,507 | cpp | C++ | ThirdParty/libtorrent-rasterbar-0.15.6/examples/enum_if.cpp | CarysT/medusa | 8e79f7738534d8cf60577ec42ed86621533ac269 | [
"MIT"
] | 32 | 2016-05-22T23:09:19.000Z | 2022-03-13T03:32:27.000Z | ThirdParty/libtorrent-rasterbar-0.15.6/examples/enum_if.cpp | CarysT/medusa | 8e79f7738534d8cf60577ec42ed86621533ac269 | [
"MIT"
] | 2 | 2016-05-30T19:45:58.000Z | 2018-01-24T22:29:51.000Z | ThirdParty/libtorrent-rasterbar-0.15.6/examples/enum_if.cpp | CarysT/medusa | 8e79f7738534d8cf60577ec42ed86621533ac269 | [
"MIT"
] | 17 | 2016-05-27T11:01:42.000Z | 2022-03-13T03:32:30.000Z | /*
Copyright (c) 2008, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include <libtorrent/enum_net.hpp>
#include <libtorrent/socket.hpp>
#include <libtorrent/broadcast_socket.hpp>
#include <vector>
#include <iomanip>
#include <iostream>
using namespace libtorrent;
int main()
{
io_service ios;
error_code ec;
address local = guess_local_address(ios);
std::cout << "Local address: " << local << std::endl;
address def_gw = get_default_gateway(ios, ec);
if (ec)
{
std::cerr << ec.message() << std::endl;
return 1;
}
std::cout << "Default gateway: " << def_gw << std::endl;
std::cout << "=========== Routes ===========\n";
std::vector<ip_route> routes = enum_routes(ios, ec);
if (ec)
{
std::cerr << ec.message() << std::endl;
return 1;
}
std::cout << std::setiosflags(std::ios::left)
<< std::setw(18) << "destination"
<< std::setw(18) << "netmask"
<< std::setw(35) << "gateway"
<< "interface name"
<< std::endl;
for (std::vector<ip_route>::const_iterator i = routes.begin()
, end(routes.end()); i != end; ++i)
{
std::cout << std::setiosflags(std::ios::left)
<< std::setw(18) << i->destination
<< std::setw(18) << i->netmask
<< std::setw(35) << i->gateway
<< i->name
<< std::endl;
}
std::cout << "========= Interfaces =========\n";
std::vector<ip_interface> const& net = enum_net_interfaces(ios, ec);
if (ec)
{
std::cerr << ec.message() << std::endl;
return 1;
}
std::cout << std::setiosflags(std::ios::left)
<< std::setw(35) << "address"
<< std::setw(45) << "netmask"
<< std::setw(18) << "name"
<< "flags"
<< std::endl;
for (std::vector<ip_interface>::const_iterator i = net.begin()
, end(net.end()); i != end; ++i)
{
std::cout << std::setiosflags(std::ios::left)
<< std::setw(35) << i->interface_address
<< std::setw(45) << i->netmask
<< std::setw(18) << i->name
<< (is_multicast(i->interface_address)?"multicast ":"")
<< (is_local(i->interface_address)?"local ":"")
<< (is_loopback(i->interface_address)?"loopback ":"")
<< std::endl;
}
}
| 30.232759 | 78 | 0.674651 | [
"vector"
] |
c008230e9613fc27bda8a31626a3388f94d22abd | 4,528 | cc | C++ | tools/symbol-index/command_line_options.cc | DamieFC/fuchsia | f78a4a1326f4a4bb5834500918756173c01bab4f | [
"BSD-2-Clause"
] | 1 | 2020-12-29T17:07:06.000Z | 2020-12-29T17:07:06.000Z | tools/symbol-index/command_line_options.cc | DamieFC/fuchsia | f78a4a1326f4a4bb5834500918756173c01bab4f | [
"BSD-2-Clause"
] | null | null | null | tools/symbol-index/command_line_options.cc | DamieFC/fuchsia | f78a4a1326f4a4bb5834500918756173c01bab4f | [
"BSD-2-Clause"
] | null | null | null | // Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "tools/symbol-index/command_line_options.h"
#include <lib/cmdline/args_parser.h>
#include "src/lib/fxl/strings/string_printf.h"
namespace symbol_index {
namespace {
const char kHelpIntro[] = R"(symbol-index [ <options> ] <verb> [ <arguments> ... ]
Manipulates a symbol-index file.
Available verbs:
list
Lists all paths in symbol-index.
add <symbol path> [ <build directory> ]
Adds a new symbol path to symbol-index. A symbol path could be either a
a text file in "ids.txt" format, or a directory in ".build-id" structure.
An optional build directory could be supplemented, which is used by zxdb
to locate the source code. If the symbol path is already in symbol-index,
no changes will be made regardless of the optional build directory.
add-all [ <input file> ]
Reads the input and adds all symbol paths with optional build directories.
The input file can contain multiple lines, each describing a symbol path.
An optional build directory could be supplemented and separated from the
symbol path with whitespaces. Relative paths will be resolved based on
the input file. Empty lines and lines starting with "#" will be ignored.
If the input file is not specified, the input will be read from the stdin.
remove <symbol path>
Removes a symbol path from symbol-index.
purge
Removes all non-existent paths from symbol-index.
Options
)";
const char kConfigHelp[] = R"( --config=<path>
-c <path>
Path to the symbol-index config file, default to
~/.fuchsia/debug/symbol-index.)";
const char kHelpHelp[] = R"( --help
-h
Prints this help.)";
const char kVersionHelp[] = R"( --version
-v
Prints the version.)";
} // namespace
Error CommandLineOptions::SetVerb(const std::string& str) {
if (str == "list")
verb = Verb::kList;
else if (str == "add")
verb = Verb::kAdd;
else if (str == "add-all")
verb = Verb::kAddAll;
else if (str == "remove")
verb = Verb::kRemove;
else if (str == "purge")
verb = Verb::kPurge;
else
return fxl::StringPrintf("Unsupported verb: %s", str.c_str());
return "";
}
Error CommandLineOptions::Validate() {
size_t params_size = params.size();
switch (verb) {
case Verb::kList:
if (params_size != 0)
return fxl::StringPrintf("Verb list requires 0 arguments, but %lu is given.", params_size);
break;
case Verb::kAdd:
if (params_size < 1 || params_size > 2) {
return fxl::StringPrintf("Verb add requires 1 or 2 arguments, but %lu is given.",
params_size);
}
break;
case Verb::kAddAll:
if (params_size > 1) {
return fxl::StringPrintf("Verb add-all requires 0 or 1 arguments, but %lu is given.",
params_size);
}
break;
case Verb::kRemove:
if (params_size != 1)
return fxl::StringPrintf("Verb remove requires 1 argument, but %lu is given.", params_size);
break;
case Verb::kPurge:
if (params_size != 0)
return fxl::StringPrintf("Verb purge requires 0 arguments, but %lu is given.", params_size);
break;
}
return "";
}
Error ParseCommandLine(int argc, const char* argv[], CommandLineOptions* options) {
std::vector<std::string> params;
cmdline::ArgsParser<CommandLineOptions> parser;
parser.AddSwitch("config", 'c', kConfigHelp, &CommandLineOptions::symbol_index_file);
parser.AddSwitch("version", 'v', kVersionHelp, &CommandLineOptions::requested_version);
// Special --help switch which doesn't exist in the options structure.
bool requested_help = false;
parser.AddGeneralSwitch("help", 'h', kHelpHelp, [&requested_help]() { requested_help = true; });
auto s = parser.Parse(argc, argv, options, ¶ms);
if (s.has_error()) {
return s.error_message();
}
if (options->requested_version) {
return "";
}
if (requested_help || params.empty()) {
return kHelpIntro + parser.GetHelp();
}
if (Error err = options->SetVerb(params[0]); !err.empty()) {
return err;
}
options->params.resize(params.size() - 1);
std::copy(params.begin() + 1, params.end(), options->params.begin());
if (Error err = options->Validate(); !err.empty()) {
return err;
}
return "";
}
} // namespace symbol_index
| 30.186667 | 100 | 0.655698 | [
"vector"
] |
c009c0c2a59c454db0691e0215c0dc067bf638a3 | 5,712 | cpp | C++ | faceid/src/v20180301/model/CreateUploadUrlResponse.cpp | TencentCloud/tencentcloud-sdk-cpp-intl-en | 752c031f5ad2c96868183c5931eae3a42dd5ae6c | [
"Apache-2.0"
] | 1 | 2022-01-27T09:27:34.000Z | 2022-01-27T09:27:34.000Z | faceid/src/v20180301/model/CreateUploadUrlResponse.cpp | TencentCloud/tencentcloud-sdk-cpp-intl-en | 752c031f5ad2c96868183c5931eae3a42dd5ae6c | [
"Apache-2.0"
] | null | null | null | faceid/src/v20180301/model/CreateUploadUrlResponse.cpp | TencentCloud/tencentcloud-sdk-cpp-intl-en | 752c031f5ad2c96868183c5931eae3a42dd5ae6c | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* 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 <tencentcloud/faceid/v20180301/model/CreateUploadUrlResponse.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Faceid::V20180301::Model;
using namespace std;
CreateUploadUrlResponse::CreateUploadUrlResponse() :
m_uploadUrlHasBeenSet(false),
m_resourceUrlHasBeenSet(false),
m_expiredTimestampHasBeenSet(false)
{
}
CoreInternalOutcome CreateUploadUrlResponse::Deserialize(const string &payload)
{
rapidjson::Document d;
d.Parse(payload.c_str());
if (d.HasParseError() || !d.IsObject())
{
return CoreInternalOutcome(Core::Error("response not json format"));
}
if (!d.HasMember("Response") || !d["Response"].IsObject())
{
return CoreInternalOutcome(Core::Error("response `Response` is null or not object"));
}
rapidjson::Value &rsp = d["Response"];
if (!rsp.HasMember("RequestId") || !rsp["RequestId"].IsString())
{
return CoreInternalOutcome(Core::Error("response `Response.RequestId` is null or not string"));
}
string requestId(rsp["RequestId"].GetString());
SetRequestId(requestId);
if (rsp.HasMember("Error"))
{
if (!rsp["Error"].IsObject() ||
!rsp["Error"].HasMember("Code") || !rsp["Error"]["Code"].IsString() ||
!rsp["Error"].HasMember("Message") || !rsp["Error"]["Message"].IsString())
{
return CoreInternalOutcome(Core::Error("response `Response.Error` format error").SetRequestId(requestId));
}
string errorCode(rsp["Error"]["Code"].GetString());
string errorMsg(rsp["Error"]["Message"].GetString());
return CoreInternalOutcome(Core::Error(errorCode, errorMsg).SetRequestId(requestId));
}
if (rsp.HasMember("UploadUrl") && !rsp["UploadUrl"].IsNull())
{
if (!rsp["UploadUrl"].IsString())
{
return CoreInternalOutcome(Core::Error("response `UploadUrl` IsString=false incorrectly").SetRequestId(requestId));
}
m_uploadUrl = string(rsp["UploadUrl"].GetString());
m_uploadUrlHasBeenSet = true;
}
if (rsp.HasMember("ResourceUrl") && !rsp["ResourceUrl"].IsNull())
{
if (!rsp["ResourceUrl"].IsString())
{
return CoreInternalOutcome(Core::Error("response `ResourceUrl` IsString=false incorrectly").SetRequestId(requestId));
}
m_resourceUrl = string(rsp["ResourceUrl"].GetString());
m_resourceUrlHasBeenSet = true;
}
if (rsp.HasMember("ExpiredTimestamp") && !rsp["ExpiredTimestamp"].IsNull())
{
if (!rsp["ExpiredTimestamp"].IsInt64())
{
return CoreInternalOutcome(Core::Error("response `ExpiredTimestamp` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_expiredTimestamp = rsp["ExpiredTimestamp"].GetInt64();
m_expiredTimestampHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
string CreateUploadUrlResponse::ToJsonString() const
{
rapidjson::Document value;
value.SetObject();
rapidjson::Document::AllocatorType& allocator = value.GetAllocator();
if (m_uploadUrlHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "UploadUrl";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_uploadUrl.c_str(), allocator).Move(), allocator);
}
if (m_resourceUrlHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ResourceUrl";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_resourceUrl.c_str(), allocator).Move(), allocator);
}
if (m_expiredTimestampHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ExpiredTimestamp";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_expiredTimestamp, allocator);
}
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RequestId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value().SetString(GetRequestId().c_str(), allocator), allocator);
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
value.Accept(writer);
return buffer.GetString();
}
string CreateUploadUrlResponse::GetUploadUrl() const
{
return m_uploadUrl;
}
bool CreateUploadUrlResponse::UploadUrlHasBeenSet() const
{
return m_uploadUrlHasBeenSet;
}
string CreateUploadUrlResponse::GetResourceUrl() const
{
return m_resourceUrl;
}
bool CreateUploadUrlResponse::ResourceUrlHasBeenSet() const
{
return m_resourceUrlHasBeenSet;
}
int64_t CreateUploadUrlResponse::GetExpiredTimestamp() const
{
return m_expiredTimestamp;
}
bool CreateUploadUrlResponse::ExpiredTimestampHasBeenSet() const
{
return m_expiredTimestampHasBeenSet;
}
| 32.827586 | 133 | 0.686099 | [
"object",
"model"
] |
c00a98b96381a4032e1e4d89102241bdb44b50a6 | 16,557 | cc | C++ | cavs/midend/graph_util.cc | xsz/HPops | 35bcc0316fe313529b67472ad6702ceacf771d01 | [
"Apache-2.0"
] | 9 | 2020-09-19T06:29:48.000Z | 2022-01-31T09:24:25.000Z | cavs/midend/graph_util.cc | xsz/HPops | 35bcc0316fe313529b67472ad6702ceacf771d01 | [
"Apache-2.0"
] | 1 | 2021-02-15T05:56:57.000Z | 2021-02-17T21:15:27.000Z | cavs/midend/graph_util.cc | xsz/HPops | 35bcc0316fe313529b67472ad6702ceacf771d01 | [
"Apache-2.0"
] | 3 | 2020-09-19T16:22:47.000Z | 2021-02-16T07:34:47.000Z | #include "cavs/midend/graph_util.h"
#include "cavs/midend/statement.h"
#include "cavs/backend/op_decl.h"
#include "cavs/util/logging.h"
#include "cavs/util/macros_gpu.h"
#include "cavs/util/op_def_builder.h"
#include "cavs/util/op_util.h"
#include <string>
#include <algorithm>
#include <list>
using namespace std;
namespace midend {
OpDef GraphUtil::PartialGrad(const Node* node, const string& edge) {
CHECK(node->IsSingleNode());
const vector<OpDef>& grads =
::backend::MakeGradient(dynamic_cast<const SingleNode*>(node)->op_def());
CHECK(grads.size()) << dynamic_cast<const SingleNode*>(node)->op_def().DebugString();
for (auto& grad : grads) {
if (std::find(grad.output().begin(), grad.output().end(),
GetGradientName(edge)) != grad.output().end()) {
return grad;
}
}
LOG(FATAL) << "No gradient valid for " << edge
<< "\n from " << node->debug_info();
}
bool GraphUtil::GenCriticalPath(vector<bool>* cpath,
vector<unordered_map<size_t, OpDef>>* grads,
const Edge* curr,
const Edge* loss,
const Scope* scope) {
CHECK(curr->scope() == scope) << curr->scoped_name();
CHECK(loss->scope() == scope);
CHECK(curr->src_size(true) == 1) << curr->debug_info();
CHECK(curr->src_size(false) == 1 || curr->isVariable()) << curr->debug_info();
VLOG_IF(V_DEBUG, curr->dst_size() > 1) << curr->scoped_name();
//VLOG(V_DEBUG) << "GenCriticalPath:\t" << curr->scoped_name();
CHECK(scope->node2idx_.find(curr->src(0)) != scope->node2idx_.end());
if (curr == loss) {
int idx = scope->node2idx_.at(curr->src(0));
CHECK(cpath->size() > idx);
cpath->at(idx) = true;
return true;
}else {
bool inpath = false;
for (Node* node : curr->dst(true)) {
int idx = scope->node2idx_.at(node);
CHECK(cpath->size() > idx);
if (!cpath->at(idx)) {
for (int i = 0; i < node->output_size(); i++) {
Edge* edge = node->output(i);
if (GenCriticalPath(cpath, grads, edge, loss, scope)) {
cpath->at(idx) = true;
inpath = true;
}
}
if (cpath->at(idx)) {
const OpDef& def = PartialGrad(node, curr->name());
size_t hashcode = GetHash(def);
CHECK(grads->at(idx).find(hashcode) == grads->at(idx).end());
grads->at(idx).emplace(hashcode, def);
}
}else {
const OpDef& def = PartialGrad(node, curr->name());
//VLOG(V_DEBUG) << "CHECKING whether this partial is already inserted\t"
//<< def.DebugString();
size_t hashcode = GetHash(def);
if (grads->at(idx).find(hashcode) == grads->at(idx).end()) {
//VLOG(V_DEBUG) << "CHECKING RESULT: False\n";
grads->at(idx).emplace(hashcode, def);
}else {
//VLOG(V_DEBUG) << "CHECKING RESULT: True\n";
}
inpath = true;
}
}
return inpath;
}
}
void GraphUtil::GenGradient(Scope* loss_scope,
const vector<bool>& critical_path,
const vector<unordered_map<size_t, OpDef>>& grads,
const Edge* loss_edge) {
CHECK(critical_path.size() == grads.size());
CHECK(critical_path.size() == s_->typological_sorted_nodes_.size());
VLOG(V_DEBUG) << "Forwarding...";
for (int i = 0; i < critical_path.size(); i++) {
if (critical_path[i]) {
VLOG(V_DEBUG) << "[" << i << "]:\n"
<< dynamic_cast<SingleNode*>(s_->typological_sorted_nodes_[i])->op_def().DebugString();
CHECK(s_->typological_sorted_nodes_[i]->IsSingleNode());
SingleNode* node = loss_scope->AddOp(dynamic_cast<SingleNode*>(s_->typological_sorted_nodes_[i])->op_def());
}else {
CHECK(grads[i].empty());
}
}
OpDef const_op;
OpDefBuilder("ConstOp")
.Output(GetGradientName(loss_edge->name()))
.Shape(loss_edge->shape())
.AttrSingle("init", 1.f)
.Device("GPU")
.Finalize(&const_op);
loss_scope->AddOp(const_op);
VLOG(V_DEBUG) << "Backwarding...";
for (int i = critical_path.size()-1 ; i >= 0; i--) {
if (critical_path[i]) {
CHECK(s_->typological_sorted_nodes_[i]->IsSingleNode());
VLOG(V_DEBUG) << "Backwarding for "
<< dynamic_cast<SingleNode*>(s_->typological_sorted_nodes_[i])->op_def().DebugString();
SingleNode* grad_node = NULL;
for (auto& iter : grads[i]) {
VLOG(V_DEBUG) << "Adding grad op\n" << iter.second.DebugString();
grad_node = loss_scope->AddOp(iter.second);
CHECK(grad_node);
VLOG(V_DEBUG) << "Getting input shape..." << grad_node->debug_info();
const vector<TensorShapeDef>& inputs =
grad_node->input_shapes();
VLOG(V_DEBUG) << "Shaping Inference...";
const vector<TensorShapeDef>& shapes =
::backend::ShapeInference(iter.second, inputs);
VLOG(V_DEBUG) << "Setting shape...";
grad_node->SetShape(shapes);
VLOG(V_DEBUG) << "One grad added";
}
if (dynamic_cast<SingleNode*>(s_->typological_sorted_nodes_[i])->IsGraphOp()) {
CHECK_NOTNULL(grad_node);
//CHECK(gnode_map.find(i) != gnode_map.end());
//dynamic_cast<GraphGradNode*>(grad_node)->SetGraphForwardNode(gnode_map[i]);
for (auto&& func_name : {"Node"}) {
//find the childscope of father or ancestor(optimizer case)
VLOG(V_DEBUG) << "Compute Gradient for " << func_name << "...";
const Scope* func_scope = s_->FindChildScope(func_name);
Scope* func_grad_scope = new Scope(func_scope, GetGradientName(func_name));
CHECK(func_scope);
CHECK(func_grad_scope);
ComputeGradientForFunction(func_grad_scope, func_scope);
}
}
}
}
}
void GraphUtil::ComputeGradient(
Scope* loss_scope,
ScopedNode* loss_scope_node,
const vector<string>& vars,
const Edge* loss_edge,
const Scope* main_scope) {
CHECK(loss_scope);
CHECK(main_scope);
vector<bool> critical_path(main_scope->typological_sorted_nodes_.size(), false);
vector<unordered_map<size_t, OpDef>> grads(main_scope->typological_sorted_nodes_.size());
for (auto& var_name : vars) {
VLOG(V_DEBUG) << var_name;
const Edge* var = loss_scope->FindEdge(var_name);
if (!GenCriticalPath(&critical_path, &grads, var, loss_edge, main_scope)) {
LOG(FATAL) << var_name << "\tis not a trainable variable";
}
}
//dealing with the dependency
for (int i = 0; i < critical_path.size(); i++) {
if (critical_path[i]) {//other nodes are dependent on this node
for (auto* e : main_scope->typological_sorted_nodes_[i]->control_dependency()) {
CHECK(e->scope() == main_scope);
CHECK(e->src_size(true) == 1);
for (auto* n : e->src(true)) {
if (!critical_path[main_scope->node2idx_.at(n)]) {
VLOG(V_DEBUG) << "ScopedNode dependency: "
<< loss_scope_node->scoped_name()
<< " depends on " << e->scoped_name();
loss_scope_node->AddControlDependency(e);
}
}
}
for (auto* e : main_scope->typological_sorted_nodes_[i]->output()) {
for (auto* n : e->control_dependency()) {
CHECK(n->scope() == main_scope);
if (!critical_path[main_scope->node2idx_.at(n)]) {
VLOG(V_DEBUG) << "Triger dependency in ScopedNode: "
<< n->scoped_name()
<< " depends on " << e->scoped_name();
critical_path[main_scope->node2idx_.at(n)] = true;
}
}
}
}
}
VLOG(V_DEBUG) << "Generating gradient...";
GenGradient(loss_scope, critical_path, grads, loss_edge);
}
void GraphUtil::GradientProcess(
Scope* loss_scope,
const vector<string>& vars,
float clip) {
vector<string> outputs;
vector<TensorShapeDef> outputs_shape;
for (auto& var_name : vars) {
outputs.emplace_back(GetGradientName(var_name));
const Edge* var = loss_scope->FindEdge(var_name);
outputs_shape.emplace_back(var->shape());
}
OpDef clipper;
OpDefBuilder("Clip")
.Input(outputs)
.Output(outputs)
.Shape(outputs_shape)
.Device("GPU")
.AttrSingle<float>("clip", clip)
.Finalize(&clipper);
loss_scope->AddOp(clipper);
}
void GraphUtil::ApplyGradient(
Scope* loss_scope,
const vector<string>& vars,
const string& solver,
const string& proj,
float lr) {
for (auto& var_name : vars) {
const Edge* var = loss_scope->FindEdge(var_name);
OpDef update;
OpDefBuilder(solver)
.Input(var_name)
.Input(GetGradientName(var_name))
.Output(var_name)
.Shape(var->shape())
.AttrSingle<float>("Learning_rate", lr)
.Device("GPU")
.Finalize(&update);
loss_scope->AddOp(update);
if (proj.length() > 0) {
OpDef projection;
OpDefBuilder(proj)
.Input(var_name)
.Output(var_name)
.Shape(var->shape())
.Device("GPU")
.Finalize(&projection);
loss_scope->AddOp(projection);
}
}
}
GraphUtil::GraphUtil(Scope* s) : s_(s) {}
ScopedNode* GraphUtil::AddOptimizerOp(const OpDef& def) {
CHECK(def.input_size() == 1);
const string& loss = def.input(0);
vector<string> var_names = GetListArg<string>(def, string("Vars"));
int iters = GetSingleArg(def, "Iters" , 0 );
float lr = GetSingleArg(def, "Learning_rate", 0.f );
float clip = GetSingleArg(def, "Clip" , 0.f );
string proj = GetSingleArg(def, "Projection" , string(""));
string solver = GetSingleArg(def, "Solver" , string(""));
CHECK(!var_names.empty());
CHECK(iters > 0);
CHECK(lr > 0);
CHECK(clip >= 0);
CHECK(!solver.empty());
Scope* loss_scope = new Scope(s_, def.output(0));
const Edge* loss_edge = s_->FindEdge(loss);
CHECK(loss_edge);
ScopedNode* sn = new ScopedNode(s_, def.output(0), iters);
VLOG(V_DEBUG) << "Compute Gradients...";
ComputeGradient(loss_scope, sn, var_names, loss_edge, s_);
VLOG(V_DEBUG) << "Gradient process...";
if (clip > 0) GradientProcess(loss_scope, var_names, clip);
ApplyGradient(loss_scope, var_names, solver, proj, lr);
sn->SetContainedScope(loss_scope);
VLOG(V_DEBUG) << "Optimizer generated...";
return sn;
}
TensorShapeDef GraphUtil::AddFunction(const FunctionDef& def) {
string func_scope_name = def.name();
Scope* func_scope = new Scope(s_, func_scope_name);
TensorShapeDef out_shape;
bool push_op = false;
for (auto& op : def.ops()) {
SingleNode* node = func_scope->AddOp(op);
const vector<TensorShapeDef>& input_shapes =
node->input_shapes();
const vector<TensorShapeDef>& shape_def =
::backend::ShapeInference(op, input_shapes);
node->SetShape(shape_def);
if (node->name() == "Gather" || node->name() == "Pull") {
node->SetDynamicEnabled();
}else {
for (Edge* e : node->input()) {
if (e->IsDynamicEnabled()) {
node->SetDynamicEnabled();
break;
}
}
}
if (node->name() == "Push") {
//Currently, push only has one output.
//There is one and only one push op per function
CHECK(node->output_size() == 1);
CHECK(!push_op);
push_op = true;
out_shape = shape_def[0];
}
}
CHECK(push_op);
return out_shape;
}
void GraphUtil::ComputeGradientForFunction(
Scope* func_grad_scope,
const Scope* func_scope) {
CHECK(func_grad_scope);
CHECK(func_scope);
vector<bool> critical_path(func_scope->typological_sorted_nodes_.size(), false);
vector<unordered_map<size_t, OpDef>> grads(func_scope->typological_sorted_nodes_.size());
set<Edge*> origins;
set<Edge*> terminals;
VLOG(V_DEBUG) << "Computing gradient for function";
for (auto* node : func_scope->typological_sorted_nodes_) {
VLOG(V_DEBUG) << node->debug_info();
if (node->name() == "Gather" || node->name() == "Pull") {
CHECK(func_scope->node2idx_.find(node) != func_scope->node2idx_.end());
critical_path[func_scope->node2idx_.at(node)] = true;
//Gather node is special, because it is a source node without input
//so PartialGrad can not be applied to the Gather node differentiation
const vector<OpDef>& grad_defs =
::backend::MakeGradient(dynamic_cast<const SingleNode*>(node)->op_def());
CHECK(grad_defs.size() == 1);
grads.at(func_scope->node2idx_.at(node)).emplace(GetHash(grad_defs[0]), grad_defs[0]);
CHECK(node->output_size() == 1);
origins.insert(node->output(0));
}
if (node->name() == "Push" || node->name() == "Scatter") {
CHECK(node->output_size() == 1);
terminals.insert(node->output(0));
}
}
//CHECK(origins.size() == 2) << origins.size();
CHECK(terminals.size() == 2) << terminals.size();
for (auto* o_edge : origins) {
for (auto* t_edge : terminals) {
vector<bool> cpath_each(critical_path.size(), false);
vector<unordered_map<size_t, OpDef>> grads_each(grads.size());
if (!GenCriticalPath(&cpath_each, &grads_each, o_edge, t_edge, func_scope)) {
LOG(FATAL) << o_edge->name()
<< "\tis not a trainable variable in function";
}
for (int i = 0; i < critical_path.size(); i++) {
critical_path[i] = critical_path[i] || cpath_each[i];
grads[i].insert(grads_each[i].begin(), grads_each[i].end());
}
}
}
////for the data path on pull/gather to push/scatter, it can be batched
//for (int i = 0; i < critical_path.size(); i++) {
//if (critical_path[i]) {
//Node* node = func_scope->typological_sorted_nodes_[i];
//if (node->IsSingleNode()) {
//dynamic_cast<SingleNode*>(node)->SetBatchEnabled();
//}
//}
//}
for (auto& edge: func_scope->in_edges_) {
for (auto* node : edge.second->dst()) {
if (node->scope() == func_scope) {
CHECK(node->output_size() == 1);
vector<bool> cpath_each(critical_path.size(), false);
vector<unordered_map<size_t, OpDef>> grads_each(grads.size());
for (auto* t_edge : terminals) {
if (GenCriticalPath(&cpath_each, &grads_each, node->output(0), t_edge, func_scope)) {
for (int i = 0; i < critical_path.size(); i++) {
critical_path[i] = critical_path[i] || cpath_each[i];
grads[i].insert(grads_each[i].begin(), grads_each[i].end());
}
CHECK(func_scope->node2idx_.find(node) != func_scope->node2idx_.end());
critical_path[func_scope->node2idx_.at(node)] = true;
OpDef def = PartialGrad(node, edge.second->name());
grads.at(func_scope->node2idx_.at(node)).emplace(GetHash(def), def);
}
}
}
}
}
for (int i = 0; i < critical_path.size(); i++) {
if (critical_path[i]) {
//VLOG(V_DEBUG) << i << "\tth operator:";
Node* node = func_scope->typological_sorted_nodes_[i];
CHECK(node->output_size() == 1);
if (node->output(0)->dst_size(true) > 1) {
VLOG(V_DEBUG) << node->output(0)->debug_info();
}
}
}
VLOG(V_DEBUG) << "Generating gradient...";
GenGradientForFunction(func_grad_scope, critical_path, grads, func_scope);
}
void GraphUtil::GenGradientForFunction(Scope* func_grad_scope,
const vector<bool>& critical_path,
const vector<unordered_map<size_t, OpDef>>& grads,
const Scope* func_scope) {
CHECK(critical_path.size() == grads.size());
CHECK(critical_path.size() == func_scope->typological_sorted_nodes_.size());
VLOG(V_DEBUG) << "Function auto-diff does not need forwarding...";
VLOG(V_DEBUG) << "Function auto-diff backwarding...";
for (int i = critical_path.size()-1 ; i >= 0; i--) {
if (critical_path[i]) {
VLOG(V_DEBUG) << "Backwarding for "
<< func_scope->typological_sorted_nodes_[i]->debug_info();
for (auto& iter : grads[i]) {
VLOG(V_DEBUG) << "Adding grad op\n" << iter.second.DebugString();
SingleNode* grad_node = func_grad_scope->AddOp(iter.second);
CHECK(grad_node) << iter.second.DebugString();
VLOG(V_DEBUG) << "Getting input shape...";
const vector<TensorShapeDef>& inputs =
grad_node->input_shapes();
VLOG(V_DEBUG) << "Shaping Inference...";
const vector<TensorShapeDef>& shapes =
::backend::ShapeInference(iter.second, inputs);
VLOG(V_DEBUG) << "Setting shape...";
grad_node->SetShape(shapes);
VLOG(V_DEBUG) << "One grad added";
}
}
}
}
} //namespace midend
| 35.915401 | 114 | 0.610014 | [
"shape",
"vector"
] |
c00f38126ad6d6580d547df8c49f2c3828c6ffb2 | 11,260 | cc | C++ | content/renderer/pepper/pepper_media_device_manager.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/renderer/pepper/pepper_media_device_manager.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/renderer/pepper/pepper_media_device_manager.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2021-01-05T23:43:46.000Z | 2021-01-07T23:36:34.000Z | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/renderer/pepper/pepper_media_device_manager.h"
#include "base/bind.h"
#include "base/check.h"
#include "base/feature_list.h"
#include "base/location.h"
#include "base/notreached.h"
#include "base/single_thread_task_runner.h"
#include "base/stl_util.h"
#include "base/threading/thread_task_runner_handle.h"
#include "content/public/common/content_features.h"
#include "content/renderer/pepper/renderer_ppapi_host_impl.h"
#include "content/renderer/render_frame_impl.h"
#include "media/media_buildflags.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "ppapi/shared_impl/ppb_device_ref_shared.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "third_party/blink/public/mojom/devtools/console_message.mojom.h"
#include "third_party/blink/public/web/modules/mediastream/web_media_stream_device_observer.h"
namespace content {
namespace {
const char kPepperInsecureOriginMessage[] =
"Microphone and Camera access no longer works on insecure origins. To use "
"this feature, you should consider switching your application to a "
"secure origin, such as HTTPS. See https://goo.gl/rStTGz for more "
"details.";
PP_DeviceType_Dev FromMediaDeviceType(blink::MediaDeviceType type) {
switch (type) {
case blink::MEDIA_DEVICE_TYPE_AUDIO_INPUT:
return PP_DEVICETYPE_DEV_AUDIOCAPTURE;
case blink::MEDIA_DEVICE_TYPE_VIDEO_INPUT:
return PP_DEVICETYPE_DEV_VIDEOCAPTURE;
case blink::MEDIA_DEVICE_TYPE_AUDIO_OUTPUT:
return PP_DEVICETYPE_DEV_AUDIOOUTPUT;
default:
NOTREACHED();
return PP_DEVICETYPE_DEV_INVALID;
}
}
blink::MediaDeviceType ToMediaDeviceType(PP_DeviceType_Dev type) {
switch (type) {
case PP_DEVICETYPE_DEV_AUDIOCAPTURE:
return blink::MEDIA_DEVICE_TYPE_AUDIO_INPUT;
case PP_DEVICETYPE_DEV_VIDEOCAPTURE:
return blink::MEDIA_DEVICE_TYPE_VIDEO_INPUT;
case PP_DEVICETYPE_DEV_AUDIOOUTPUT:
return blink::MEDIA_DEVICE_TYPE_AUDIO_OUTPUT;
default:
NOTREACHED();
return blink::MEDIA_DEVICE_TYPE_AUDIO_OUTPUT;
}
}
ppapi::DeviceRefData FromMediaDeviceInfo(
blink::MediaDeviceType type,
const blink::WebMediaDeviceInfo& info) {
ppapi::DeviceRefData data;
data.id = info.device_id;
// Some Flash content can't handle an empty string, so stick a space in to
// make them happy. See crbug.com/408404.
data.name = info.label.empty() ? std::string(" ") : info.label;
data.type = FromMediaDeviceType(type);
return data;
}
std::vector<ppapi::DeviceRefData> FromMediaDeviceInfoArray(
blink::MediaDeviceType type,
const blink::WebMediaDeviceInfoArray& device_infos) {
std::vector<ppapi::DeviceRefData> devices;
devices.reserve(device_infos.size());
for (const auto& device_info : device_infos)
devices.push_back(FromMediaDeviceInfo(type, device_info));
return devices;
}
} // namespace
base::WeakPtr<PepperMediaDeviceManager>
PepperMediaDeviceManager::GetForRenderFrame(
RenderFrame* render_frame) {
PepperMediaDeviceManager* handler =
PepperMediaDeviceManager::Get(render_frame);
if (!handler)
handler = new PepperMediaDeviceManager(render_frame);
return handler->AsWeakPtr();
}
PepperMediaDeviceManager::PepperMediaDeviceManager(RenderFrame* render_frame)
: RenderFrameObserver(render_frame),
RenderFrameObserverTracker<PepperMediaDeviceManager>(render_frame) {}
PepperMediaDeviceManager::~PepperMediaDeviceManager() {
DCHECK(open_callbacks_.empty());
}
void PepperMediaDeviceManager::EnumerateDevices(PP_DeviceType_Dev type,
DevicesOnceCallback callback) {
bool request_audio_input = type == PP_DEVICETYPE_DEV_AUDIOCAPTURE;
bool request_video_input = type == PP_DEVICETYPE_DEV_VIDEOCAPTURE;
bool request_audio_output = type == PP_DEVICETYPE_DEV_AUDIOOUTPUT;
CHECK(request_audio_input || request_video_input || request_audio_output);
GetMediaDevicesDispatcher()->EnumerateDevices(
request_audio_input, request_video_input, request_audio_output,
false /* request_video_input_capabilities */,
false /* request_audio_input_capabilities */,
base::BindOnce(&PepperMediaDeviceManager::DevicesEnumerated, AsWeakPtr(),
std::move(callback), ToMediaDeviceType(type)));
}
size_t PepperMediaDeviceManager::StartMonitoringDevices(
PP_DeviceType_Dev type,
const DevicesCallback& callback) {
bool subscribe_audio_input = type == PP_DEVICETYPE_DEV_AUDIOCAPTURE;
bool subscribe_video_input = type == PP_DEVICETYPE_DEV_VIDEOCAPTURE;
bool subscribe_audio_output = type == PP_DEVICETYPE_DEV_AUDIOOUTPUT;
CHECK(subscribe_audio_input || subscribe_video_input ||
subscribe_audio_output);
mojo::PendingRemote<blink::mojom::MediaDevicesListener> listener;
size_t subscription_id =
receivers_.Add(this, listener.InitWithNewPipeAndPassReceiver());
GetMediaDevicesDispatcher()->AddMediaDevicesListener(
subscribe_audio_input, subscribe_video_input, subscribe_audio_output,
std::move(listener));
SubscriptionList& subscriptions =
device_change_subscriptions_[ToMediaDeviceType(type)];
subscriptions.push_back(Subscription{subscription_id, callback});
return subscription_id;
}
void PepperMediaDeviceManager::StopMonitoringDevices(PP_DeviceType_Dev type,
size_t subscription_id) {
SubscriptionList& subscriptions =
device_change_subscriptions_[ToMediaDeviceType(type)];
base::EraseIf(subscriptions,
[subscription_id](const Subscription& subscription) {
return subscription.first == subscription_id;
});
receivers_.Remove(subscription_id);
}
int PepperMediaDeviceManager::OpenDevice(PP_DeviceType_Dev type,
const std::string& device_id,
PP_Instance pp_instance,
OpenDeviceCallback callback) {
open_callbacks_[next_id_] = std::move(callback);
int request_id = next_id_++;
RendererPpapiHostImpl* host =
RendererPpapiHostImpl::GetForPPInstance(pp_instance);
if (!host->IsSecureContext(pp_instance)) {
RenderFrame* render_frame = host->GetRenderFrameForInstance(pp_instance);
if (render_frame) {
render_frame->AddMessageToConsole(
blink::mojom::ConsoleMessageLevel::kWarning,
kPepperInsecureOriginMessage);
}
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(&PepperMediaDeviceManager::OnDeviceOpened,
AsWeakPtr(), request_id, false, std::string(),
blink::MediaStreamDevice()));
return request_id;
}
GetMediaStreamDispatcherHost()->OpenDevice(
request_id, device_id,
PepperMediaDeviceManager::FromPepperDeviceType(type),
base::BindOnce(&PepperMediaDeviceManager::OnDeviceOpened, AsWeakPtr(),
request_id));
return request_id;
}
void PepperMediaDeviceManager::CancelOpenDevice(int request_id) {
open_callbacks_.erase(request_id);
GetMediaStreamDispatcherHost()->CancelRequest(request_id);
}
void PepperMediaDeviceManager::CloseDevice(const std::string& label) {
if (!GetMediaStreamDeviceObserver()->RemoveStream(
blink::WebString::FromUTF8(label)))
return;
GetMediaStreamDispatcherHost()->CloseDevice(label);
}
base::UnguessableToken PepperMediaDeviceManager::GetSessionID(
PP_DeviceType_Dev type,
const std::string& label) {
switch (type) {
case PP_DEVICETYPE_DEV_AUDIOCAPTURE:
return GetMediaStreamDeviceObserver()->GetAudioSessionId(
blink::WebString::FromUTF8(label));
case PP_DEVICETYPE_DEV_VIDEOCAPTURE:
return GetMediaStreamDeviceObserver()->GetVideoSessionId(
blink::WebString::FromUTF8(label));
default:
NOTREACHED();
return base::UnguessableToken();
}
}
// static
blink::mojom::MediaStreamType PepperMediaDeviceManager::FromPepperDeviceType(
PP_DeviceType_Dev type) {
switch (type) {
case PP_DEVICETYPE_DEV_INVALID:
return blink::mojom::MediaStreamType::NO_SERVICE;
case PP_DEVICETYPE_DEV_AUDIOCAPTURE:
return blink::mojom::MediaStreamType::DEVICE_AUDIO_CAPTURE;
case PP_DEVICETYPE_DEV_VIDEOCAPTURE:
return blink::mojom::MediaStreamType::DEVICE_VIDEO_CAPTURE;
default:
NOTREACHED();
return blink::mojom::MediaStreamType::NO_SERVICE;
}
}
void PepperMediaDeviceManager::OnDevicesChanged(
blink::MediaDeviceType type,
const blink::WebMediaDeviceInfoArray& device_infos) {
std::vector<ppapi::DeviceRefData> devices =
FromMediaDeviceInfoArray(type, device_infos);
SubscriptionList& subscriptions = device_change_subscriptions_[type];
for (auto& subscription : subscriptions)
subscription.second.Run(devices);
}
void PepperMediaDeviceManager::OnDeviceOpened(
int request_id,
bool success,
const std::string& label,
const blink::MediaStreamDevice& device) {
auto iter = open_callbacks_.find(request_id);
if (iter == open_callbacks_.end()) {
// The callback may have been unregistered.
return;
}
if (success)
GetMediaStreamDeviceObserver()->AddStream(blink::WebString::FromUTF8(label),
device);
OpenDeviceCallback callback = std::move(iter->second);
open_callbacks_.erase(iter);
std::move(callback).Run(request_id, success, success ? label : std::string());
}
void PepperMediaDeviceManager::DevicesEnumerated(
DevicesOnceCallback client_callback,
blink::MediaDeviceType type,
const std::vector<blink::WebMediaDeviceInfoArray>& enumeration,
std::vector<blink::mojom::VideoInputDeviceCapabilitiesPtr>
video_input_capabilities,
std::vector<blink::mojom::AudioInputDeviceCapabilitiesPtr>
audio_input_capabilities) {
std::move(client_callback)
.Run(FromMediaDeviceInfoArray(type, enumeration[type]));
}
blink::mojom::MediaStreamDispatcherHost*
PepperMediaDeviceManager::GetMediaStreamDispatcherHost() {
if (!dispatcher_host_) {
CHECK(render_frame());
render_frame()->GetBrowserInterfaceBroker()->GetInterface(
dispatcher_host_.BindNewPipeAndPassReceiver());
}
return dispatcher_host_.get();
}
blink::WebMediaStreamDeviceObserver*
PepperMediaDeviceManager::GetMediaStreamDeviceObserver() const {
DCHECK(render_frame());
blink::WebMediaStreamDeviceObserver* const observer =
static_cast<RenderFrameImpl*>(render_frame())
->MediaStreamDeviceObserver();
DCHECK(observer);
return observer;
}
blink::mojom::MediaDevicesDispatcherHost*
PepperMediaDeviceManager::GetMediaDevicesDispatcher() {
if (!media_devices_dispatcher_) {
CHECK(render_frame());
render_frame()->GetBrowserInterfaceBroker()->GetInterface(
media_devices_dispatcher_.BindNewPipeAndPassReceiver());
}
return media_devices_dispatcher_.get();
}
void PepperMediaDeviceManager::OnDestruct() {
delete this;
}
} // namespace content
| 36.440129 | 94 | 0.739609 | [
"vector"
] |
c010116d62b78f626052bb0ba7f75a62c860e885 | 5,196 | cpp | C++ | Modules/Graphics/Core/Sources/Methane/Graphics/Vulkan/RenderCommandListVK.cpp | navono/MethaneKit | 5cf55dcbbc23392f5c06b178570c7c32b6368ca7 | [
"Apache-2.0"
] | null | null | null | Modules/Graphics/Core/Sources/Methane/Graphics/Vulkan/RenderCommandListVK.cpp | navono/MethaneKit | 5cf55dcbbc23392f5c06b178570c7c32b6368ca7 | [
"Apache-2.0"
] | null | null | null | Modules/Graphics/Core/Sources/Methane/Graphics/Vulkan/RenderCommandListVK.cpp | navono/MethaneKit | 5cf55dcbbc23392f5c06b178570c7c32b6368ca7 | [
"Apache-2.0"
] | null | null | null | /******************************************************************************
Copyright 2019-2020 Evgeny Gorodetskiy
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.
*******************************************************************************
FILE: Methane/Graphics/Vulkan/RenderCommandListVK.mm
Vulkan implementation of the render command list interface.
******************************************************************************/
#include "RenderCommandListVK.h"
#include "ParallelRenderCommandListVK.h"
#include "RenderStateVK.h"
#include "RenderPassVK.h"
#include "CommandQueueVK.h"
#include "ContextVK.h"
#include "BufferVK.h"
#include <Methane/Instrumentation.h>
#include <Methane/Checks.hpp>
#include <magic_enum.hpp>
namespace Methane::Graphics
{
Ptr<RenderCommandList> RenderCommandList::Create(CommandQueue& command_queue, RenderPass& render_pass)
{
META_FUNCTION_TASK();
return std::make_shared<RenderCommandListVK>(static_cast<CommandQueueBase&>(command_queue), static_cast<RenderPassBase&>(render_pass));
}
Ptr<RenderCommandList> RenderCommandList::Create(ParallelRenderCommandList& parallel_render_command_list)
{
META_FUNCTION_TASK();
return std::make_shared<RenderCommandListVK>(static_cast<ParallelRenderCommandListBase&>(parallel_render_command_list));
}
Ptr<RenderCommandList> RenderCommandListBase::CreateForSynchronization(CommandQueue&)
{
META_FUNCTION_TASK();
return nullptr;
}
RenderCommandListVK::RenderCommandListVK(CommandQueueBase& command_queue, RenderPassBase& render_pass)
: RenderCommandListBase(command_queue, render_pass)
{
META_FUNCTION_TASK();
}
RenderCommandListVK::RenderCommandListVK(ParallelRenderCommandListBase& parallel_render_command_list)
: RenderCommandListBase(parallel_render_command_list)
{
META_FUNCTION_TASK();
}
void RenderCommandListVK::Reset(DebugGroup* p_debug_group)
{
META_FUNCTION_TASK();
RenderCommandListBase::ResetCommandState();
RenderCommandListBase::Reset(p_debug_group);
}
void RenderCommandListVK::ResetWithState(RenderState& render_state, DebugGroup* p_debug_group)
{
META_FUNCTION_TASK();
RenderCommandListBase::ResetCommandState();
RenderCommandListBase::ResetWithState(render_state, p_debug_group);
}
void RenderCommandListVK::SetName(const std::string& name)
{
META_FUNCTION_TASK();
RenderCommandListBase::SetName(name);
}
void RenderCommandListVK::PushDebugGroup(DebugGroup& debug_group)
{
META_FUNCTION_TASK();
CommandListBase::PushDebugGroup(debug_group);
}
void RenderCommandListVK::PopDebugGroup()
{
META_FUNCTION_TASK();
CommandListBase::PopDebugGroup();
}
bool RenderCommandListVK::SetVertexBuffers(BufferSet& vertex_buffers, bool set_resource_barriers)
{
META_FUNCTION_TASK();
if (!RenderCommandListBase::SetVertexBuffers(vertex_buffers, set_resource_barriers))
return false;
return true;
}
bool RenderCommandListVK::SetIndexBuffer(Buffer& index_buffer, bool set_resource_barriers)
{
META_FUNCTION_TASK();
if (!RenderCommandListBase::SetIndexBuffer(index_buffer, set_resource_barriers))
return false;
return true;
}
void RenderCommandListVK::DrawIndexed(Primitive primitive, uint32_t index_count, uint32_t start_index, uint32_t start_vertex,
uint32_t instance_count, uint32_t start_instance)
{
META_FUNCTION_TASK();
DrawingState& drawing_state = GetDrawingState();
if (index_count == 0 && drawing_state.index_buffer_ptr)
{
index_count = drawing_state.index_buffer_ptr->GetFormattedItemsCount();
}
RenderCommandListBase::DrawIndexed(primitive, index_count, start_index, start_vertex, instance_count, start_instance);
}
void RenderCommandListVK::Draw(Primitive primitive, uint32_t vertex_count, uint32_t start_vertex,
uint32_t instance_count, uint32_t start_instance)
{
META_FUNCTION_TASK();
RenderCommandListBase::Draw(primitive, vertex_count, start_vertex, instance_count, start_instance);
}
void RenderCommandListVK::Commit()
{
META_FUNCTION_TASK();
META_CHECK_ARG_FALSE(IsCommitted());
RenderCommandListBase::Commit();
}
void RenderCommandListVK::Execute(uint32_t frame_index, const CompletedCallback& completed_callback)
{
META_FUNCTION_TASK();
RenderCommandListBase::Execute(frame_index, completed_callback);
}
CommandQueueVK& RenderCommandListVK::GetCommandQueueVK() noexcept
{
META_FUNCTION_TASK();
return static_cast<class CommandQueueVK&>(GetCommandQueue());
}
RenderPassVK& RenderCommandListVK::GetPassVK()
{
META_FUNCTION_TASK();
return static_cast<class RenderPassVK&>(GetPass());
}
} // namespace Methane::Graphics
| 30.928571 | 139 | 0.745189 | [
"render"
] |
84fccb37d72e7c16167ce60f3696d7f56d075460 | 6,853 | hpp | C++ | src/client/headers/client/sqf/intersects.hpp | xdr1000/intercept | 0c7b2deda7351dc0c264dd167bfae2371e463625 | [
"MIT"
] | null | null | null | src/client/headers/client/sqf/intersects.hpp | xdr1000/intercept | 0c7b2deda7351dc0c264dd167bfae2371e463625 | [
"MIT"
] | null | null | null | src/client/headers/client/sqf/intersects.hpp | xdr1000/intercept | 0c7b2deda7351dc0c264dd167bfae2371e463625 | [
"MIT"
] | null | null | null | /*!
@file
@author Verox (verox.averre@gmail.com)
@author Nou (korewananda@gmail.com)
@author Glowbal (thomasskooi@live.nl)
@brief Intersection command wrappers.
These are commands that are used to test 3D intersections and collisions in the
game world.
https://github.com/NouberNou/intercept
*/
#pragma once
#include "shared.hpp"
#include "client\client.hpp"
#include "shared\client_types.hpp"
using namespace intercept::types;
namespace intercept {
namespace sqf {
struct intersect_surfaces {
vector3 intersect_pos_asl; // the actual position where line intersects 1st surface
vector3 surface_normal; // a normal to the intersected surface
object intersect_object; // the object the surface belongs to(could be proxy object)
object parent_object; // the object proxy object belongs to(not always the same as intersect object)
};
typedef std::vector<intersect_surfaces> intersect_surfaces_list;
namespace __helpers {
intersect_surfaces_list __line_intersects_surfaces(const game_value& intersects_value_);
}
/**
* Finds named selections in object which are in specified LOD, intersected by given section of a line
*/
bool intersect(const vector3 &begin_pos_, const vector3 &end_pos_, const object& obj_, const std::string &lodname_);
/**
* Returns list of intersections with surfaces from begPosASL to endPosASL.
* If there is ground intersection, it is also included. Works on units. Works underwater.
* Doesn't return intersection with sea surface. Hardcoded max distance: 5000m.
* Biki: https://community.bistudio.com/wiki/lineIntersectsSurfaces
*
* @params begin_pos_asl_: PositionASL - virtual line start
* @params end_pos_asl_: PositionASL - virtual line end
*
* @returns vector of intersections in format [[intersectPosASL, surfaceNormal, intersectObj, parentObject],...]
*/
intersect_surfaces_list line_intersects_surfaces(const vector3 &begin_pos_asl_, const vector3 &end_pos_asl_);
/**
* Returns list of intersections with surfaces from begPosASL to endPosASL.
* If there is ground intersection, it is also included. Works on units. Works underwater.
* Doesn't return intersection with sea surface. Hardcoded max distance: 5000m.
* Biki: https://community.bistudio.com/wiki/lineIntersectsSurfaces
*
* @params begin_pos_asl_: PositionASL - virtual line start
* @params end_pos_asl_: PositionASL - virtual line end
* @params ignore_obj1_ (Optional) first object to ignore or objNull: Default: objNull
*
* @returns vector of intersections in format [[intersectPosASL, surfaceNormal, intersectObj, parentObject],...]
*/
intersect_surfaces_list line_intersects_surfaces(const vector3 &begin_pos_asl_, const vector3 &end_pos_asl_, const object& ignore_obj1_);
/**
* Returns list of intersections with surfaces from begPosASL to endPosASL.
* If there is ground intersection, it is also included. Works on units. Works underwater.
* Doesn't return intersection with sea surface. Hardcoded max distance: 5000m.
* Biki: https://community.bistudio.com/wiki/lineIntersectsSurfaces
*
* @params begin_pos_asl_: PositionASL - virtual line start
* @params end_pos_asl_: PositionASL - virtual line end
* @params ignore_obj1_ (Optional) first object to ignore or objNull: Default: objNull
* @params ignore_obj2_ (Optional) second object to ignore or objNull: Default: objNull
* @params sort_mode_ (Optional): true: closest to furthest, false: furthest to closest. Default: true
* @params max_results_ (Optional) Max results to return. -1 to return every result. Default: 1
* @params lod1_ (Optional) Primary LOD to look for intersection. Default: "VIEW"
* @params lod2_ (Optional) Secondary LOD to look for intersection. Default: "FIRE"
*
* @returns vector of intersections in format [[intersectPosASL, surfaceNormal, intersectObj, parentObject],...]
*/
intersect_surfaces_list line_intersects_surfaces(const vector3 &begin_pos_asl_, const vector3 &end_pos_asl_, const object& ignore_obj1_, const object& ignore_obj2_, bool sort_mode_ = true, int max_results_ = 1, const std::string &lod1_ = "VIEW", const std::string &lod2_ = "FIRE");
/**
* Returns objects intersecting with the virtual line from begPos to endPos
*/
std::vector<object> line_intersects_with(const vector3 &begin_pos_, const vector3 &end_pos_, bool sort_by_distance_ = true);
std::vector<object> line_intersects_with(const vector3 &begin_pos_, const vector3 &end_pos_, bool sort_by_distance_, const object & ignore_obj_one_);
std::vector<object> line_intersects_with(const vector3 &begin_pos_, const vector3 &end_pos_, bool sort_by_distance_, const object & ignore_obj_one_, const object & ignore_obj_two_);
/**
* Checks for intersection of terrain between two positions. Returns true if intersects with terrain. Uses PositionAGL
*/
bool terrain_intersect(const vector3 &begin_pos_, const vector3 &end_pos_);
/**
* Checks for intersection of terrain between two positions. Returns true if intersects with terrain. Uses PositionASL
*/
bool terrain_intersect_asl(const vector3 &begin_pos_, const vector3 &end_pos_);
/**
* Checks for object intersection with a virtual line between two positions. Returns true if intersects with an object.
*/
bool line_intersects(const vector3 &begin_position_, const vector3 &end_position_);
/**
* Checks for object intersection with a virtual line between two positions. Returns true if intersects with an object.
*/
bool line_intersects(const vector3 &begin_position_, const vector3 &end_position_, const object& ignore_obj_one_);
/**
* Checks for object intersection with a virtual line between two positions. Returns true if intersects with an object.
*/
bool line_intersects(const vector3 &begin_position_, const vector3 &end_position_, const object& ignore_obj_one_, const object& ignore_obj_two_);
/**
* Find list of objects intersected by given line from begin_position_ to end_position_
*/
std::vector<object> line_intersects_objs(const vector3 &begin_position_, const vector3 &end_position_, const object& with_object_, const object& ignore_obj_, bool sort_by_distance_, int flags_);
}
}
| 55.266129 | 290 | 0.696483 | [
"object",
"vector",
"3d"
] |
1704696c5694f3af701512e73516a999114825d9 | 1,129 | cpp | C++ | src/exporter/exporter.cpp | LibreTextus/LibreTextus | a142c0bed2237b1b252e1ff5dcfdbe82bd4439d3 | [
"CC0-1.0"
] | 3 | 2020-08-26T06:18:42.000Z | 2021-01-16T17:22:29.000Z | src/exporter/exporter.cpp | LibreTextus/LibreTextus | a142c0bed2237b1b252e1ff5dcfdbe82bd4439d3 | [
"CC0-1.0"
] | null | null | null | src/exporter/exporter.cpp | LibreTextus/LibreTextus | a142c0bed2237b1b252e1ff5dcfdbe82bd4439d3 | [
"CC0-1.0"
] | null | null | null | #include "exporter.hpp"
Libre::Exporter::Exporter(rapidxml::xml_document<> * doc, std::string & p, std::string & s, std::string & pos) : search_engine(s) {
this->file = doc;
this->path = p;
this->position = pos;
this->source = s;
fout.open(this->path + ".tmp");
search_engine.set_search_argument(this->position);
}
int Libre::Exporter::export_note() {
this->get_position_from_default_source();
this->extract_notes_from_file();
fout.close();
return system(("mv " + this->path + ".tmp " + this->path).c_str());
}
void Libre::Exporter::get_position_from_default_source() {
std::string r;
while (search_engine.search(&r)) {}
}
void Libre::Exporter::extract_notes_from_file() {
std::vector<std::string> * v = search_engine.get_last_search_results();
for (rapidxml::xml_node<> * i = this->file->first_node("notebook")->first_node("note"); i; i = i->next_sibling()) {
bool is_in_range = std::find(v->begin(), v->end(), std::string(i->first_attribute("name")->value())) != v->end();
if (is_in_range) {
fout << "# " << i->first_attribute("name")->value() << '\n';
fout << i->value() << '\n';
}
}
}
| 28.225 | 131 | 0.648361 | [
"vector"
] |
17093b06edd6f901136be6c7fe83d3936f532810 | 8,364 | cpp | C++ | src/CScheduleAlgorithmSufferageMig2Dyn.cpp | aw32/sched | b6ef35c5b517875a5954c70e2dc366fab3721a60 | [
"BSD-2-Clause"
] | null | null | null | src/CScheduleAlgorithmSufferageMig2Dyn.cpp | aw32/sched | b6ef35c5b517875a5954c70e2dc366fab3721a60 | [
"BSD-2-Clause"
] | null | null | null | src/CScheduleAlgorithmSufferageMig2Dyn.cpp | aw32/sched | b6ef35c5b517875a5954c70e2dc366fab3721a60 | [
"BSD-2-Clause"
] | null | null | null | // Copyright 2019, Alex Wiens <awiens@mail.upb.de>, Achim Lösch <achim.loesch@upb.de>
// SPDX-License-Identifier: BSD-2-Clause
#include <limits>
#include <list>
#include <algorithm>
#include "CScheduleAlgorithmSufferageMig2Dyn.h"
#include "CTask.h"
#include "CTaskCopy.h"
#include "CEstimation.h"
#include "CSchedule.h"
#include "CScheduleExt.h"
#include "CResource.h"
#include "CLogger.h"
using namespace sched::algorithm;
using sched::task::CTask;
using sched::schedule::STaskEntry;
using sched::schedule::CSchedule;
using sched::schedule::CScheduleExt;
CScheduleAlgorithmSufferageMig2Dyn::CScheduleAlgorithmSufferageMig2Dyn(std::vector<CResource*>& rResources)
: CScheduleAlgorithm(rResources)
{
mpEstimation = CEstimation::getEstimation();
}
CScheduleAlgorithmSufferageMig2Dyn::~CScheduleAlgorithmSufferageMig2Dyn() {
delete mpEstimation;
mpEstimation = 0;
}
int CScheduleAlgorithmSufferageMig2Dyn::init() {
return 0;
}
void CScheduleAlgorithmSufferageMig2Dyn::fini() {
}
CSchedule* CScheduleAlgorithmSufferageMig2Dyn::compute(std::vector<CTaskCopy>* pTasks, std::vector<CTaskCopy*>* runningTasks, volatile int* interrupt, int updated) {
int tasks = pTasks->size();
int machines = mrResources.size();
if (machines < 2) {
CLogger::mainlog->error("Sufferage: less than 2 resources !!!");
}
CScheduleExt* sched = new CScheduleExt(tasks, machines, mrResources, pTasks);
sched->setRunningTasks(runningTasks);
int unmappedTasks = tasks;
struct MigOpt min_suff_mig;
struct MigOpt min_ct_mig;
while (unmappedTasks > 0) {
// reset best option
min_suff_mig.parts[0].mix = -1;
for (int tix = 0; tix < tasks; tix++) {
// skip already mapped tasks
if (sched->taskLastPartMapped(tix) == true) {
continue;
}
// skip tasks whose predecessors are not ready
if (sched->taskDependencySatisfied(tix) == false) {
continue;
}
double readyTask = sched->taskReadyTime(tix);
// reset best completion time option
min_ct_mig.parts[0].mix = -1;
double completeFirst = 0.0;
double completeSecond = 0.0;
CTaskCopy* task = &((*pTasks)[tix]);
// check migration options
for (int mixA = 0; mixA < machines; mixA++) {
CResource* resA = mrResources[mixA];
if (task->validResource(resA) == false) {
continue;
}
double resReadyA = sched->taskReadyTimeResource(tix, resA, mpEstimation);
if (readyTask > resReadyA) {
resReadyA = readyTask;
}
CLogger::mainlog->debug("Sufferage ready mix %d mixtasks %d tix %d ready %lf",
mixA, sched->resourceTasks(mixA),
tix, resReadyA);
for (int mixB = 0; mixB < machines; mixB++) {
CResource* resB = mrResources[mixB];
if (task->validResource(resB) == false) {
continue;
}
double resReadyB = sched->taskReadyTimeResource(tix, resB, mpEstimation);
if (readyTask > resReadyB) {
resReadyB = readyTask;
}
CLogger::mainlog->debug("Sufferage ready mix %d mixtasks %d tix %d ready %lf",
mixB, sched->resourceTasks(mixB),
tix, resReadyB);
if (resReadyB <= resReadyA) {
continue;
}
double readyDiff = resReadyB-resReadyA;
double initA = mpEstimation->taskTimeInit(task, resA);
if (sched->taskRunningResource(tix) == mixA &&
sched->resourceTasks(mixA) == 0) {
// task already running on resource and
// slot is first slot
initA = 0.0;
}
double initB = mpEstimation->taskTimeInit(task, resB);
double finiA = mpEstimation->taskTimeFini(task, resA);
double finiB = mpEstimation->taskTimeFini(task, resB);
double budget = readyDiff - initA - finiA;
int pointsA = mpEstimation->taskTimeComputeCheckpoint(task, resA, task->mProgress, budget);
if (budget <= 0.0 || pointsA <= 0) {
// no gain
continue;
}
if (pointsA >= task->mCheckpoints - task->mProgress) {
// migration unnecessary
continue;
}
double timeA = initA + finiA + mpEstimation->taskTimeCompute(task, resA, task->mProgress, task->mProgress+pointsA);
double timeB = initB + finiB + mpEstimation->taskTimeCompute(task, resB, task->mProgress+pointsA, task->mCheckpoints);
double completeA = resReadyA + timeA;
double completeB = resReadyB + timeB;
CLogger::mainlog->debug("Sufferage: possible mig taskid %d mixA %d mixB %d readyA %lf readyB %lf completeA %lf completeB %lf",
task->mId,
mixA,
mixB,
resReadyA,
resReadyB,
completeA,
completeB
);
if (min_ct_mig.parts[0].mix == -1 || completeB < min_ct_mig.complete) {
min_ct_mig.tix = tix;
min_ct_mig.complete = completeB;
min_ct_mig.parts[0].mix = mixA;
min_ct_mig.parts[0].startProgress = task->mProgress;
min_ct_mig.parts[0].stopProgress = task->mProgress+pointsA;
min_ct_mig.parts[0].complete = completeA;
min_ct_mig.parts[1].mix = mixB;
min_ct_mig.parts[1].startProgress = task->mProgress+pointsA;
min_ct_mig.parts[1].stopProgress = task->mCheckpoints;
min_ct_mig.parts[1].complete = completeB;
}
// update completion time
if (completeB < completeFirst) {
completeSecond = completeFirst;
completeFirst = completeB;
} else
if (completeB < completeSecond) {
completeSecond = completeB;
}
} // end for mixB
} // end for mix A
// check normal options
for (int mix = 0; mix<machines; mix++) {
CResource* res = mrResources[mix];
if (task->validResource(res) == false) {
continue;
}
double ready = sched->taskReadyTimeResource(tix, res, mpEstimation);
CLogger::mainlog->debug("Sufferage ready mix %d mixtasks %d tix %d ready %lf",
mix, sched->resourceTasks(mix),
tix, ready);
double init = mpEstimation->taskTimeInit(task, res);
if (sched->taskRunningResource(tix) == mix &&
sched->resourceTasks(mix) == 0) {
// task already running on resource and
// slot is first slot
init = 0.0;
}
double compute = mpEstimation->taskTimeCompute(task, res, task->mProgress, task->mCheckpoints);
double fini = mpEstimation->taskTimeFini(task, res);
double complete = ready + init + compute + fini;
if (min_ct_mig.parts[0].mix == -1 || min_ct_mig.complete > complete) {
min_ct_mig.tix = tix;
min_ct_mig.complete = complete;
min_ct_mig.parts[0].mix = mix;
min_ct_mig.parts[0].startProgress = task->mProgress;
min_ct_mig.parts[0].stopProgress = task->mCheckpoints;
min_ct_mig.parts[0].complete = complete;
min_ct_mig.parts[1].mix = -1;
}
if (complete < completeFirst) {
completeSecond = completeFirst;
completeFirst = complete;
} else
if (complete < completeSecond) {
completeSecond = complete;
}
} // end for mix
// compute sufferage
min_ct_mig.sufferage = completeSecond - completeFirst;
// adopt option if sufferage is larger
if (min_suff_mig.parts[0].mix == -1 || min_ct_mig.sufferage < min_suff_mig.sufferage) {
min_suff_mig = min_ct_mig;
}
} // end for tix
CTaskCopy* task = &((*pTasks)[min_suff_mig.tix]);
STaskEntry* entry = new STaskEntry();
entry->taskcopy = task;
entry->taskid = entry->taskcopy->mId;
entry->startProgress = min_suff_mig.parts[0].startProgress;
entry->stopProgress = min_suff_mig.parts[0].stopProgress;
sched->addEntry(entry, mrResources[min_suff_mig.parts[0].mix], -1);
CLogger::mainlog->debug("Sufferage: apply task %d mix %d start %d stop %d", task->mId, min_suff_mig.parts[0].mix,
min_suff_mig.parts[0].startProgress,
min_suff_mig.parts[0].stopProgress);
// migration option
if (min_suff_mig.parts[1].mix != -1) {
CTaskCopy* task = &((*pTasks)[min_suff_mig.tix]);
STaskEntry* entry = new STaskEntry();
entry->taskcopy = task;
entry->taskid = entry->taskcopy->mId;
entry->startProgress = min_suff_mig.parts[1].startProgress;
entry->stopProgress = min_suff_mig.parts[1].stopProgress;
sched->addEntry(entry, mrResources[min_suff_mig.parts[1].mix], -1);
CLogger::mainlog->debug("Sufferage: apply task %d mix %d start %d stop %d", task->mId, min_suff_mig.parts[1].mix,
min_suff_mig.parts[1].startProgress,
min_suff_mig.parts[1].stopProgress);
}
unmappedTasks--;
if (unmappedTasks == 0) {
break;
}
}
sched->computeTimes();
// clean up
return sched;
}
| 30.525547 | 165 | 0.672286 | [
"vector"
] |
17186afd9bcd73b1f3167b33ce62f9552fc9e0b8 | 1,316 | cpp | C++ | mesh/hexahedron.cpp | ajithvallabai/mfem | 5920fbf645f328c29a9d6489f2474d989f808451 | [
"BSD-3-Clause"
] | 969 | 2015-07-10T02:28:17.000Z | 2022-03-31T17:28:02.000Z | mesh/hexahedron.cpp | ajithvallabai/mfem | 5920fbf645f328c29a9d6489f2474d989f808451 | [
"BSD-3-Clause"
] | 2,604 | 2015-07-14T08:22:22.000Z | 2022-03-31T23:51:41.000Z | mesh/hexahedron.cpp | ajithvallabai/mfem | 5920fbf645f328c29a9d6489f2474d989f808451 | [
"BSD-3-Clause"
] | 407 | 2015-08-26T14:14:22.000Z | 2022-03-31T03:32:16.000Z | // Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#include "mesh_headers.hpp"
namespace mfem
{
Hexahedron::Hexahedron(const int *ind, int attr)
: Element(Geometry::CUBE)
{
attribute = attr;
for (int i = 0; i < 8; i++)
{
indices[i] = ind[i];
}
}
Hexahedron::Hexahedron(int ind1, int ind2, int ind3, int ind4,
int ind5, int ind6, int ind7, int ind8,
int attr) : Element(Geometry::CUBE)
{
attribute = attr;
indices[0] = ind1;
indices[1] = ind2;
indices[2] = ind3;
indices[3] = ind4;
indices[4] = ind5;
indices[5] = ind6;
indices[6] = ind7;
indices[7] = ind8;
}
void Hexahedron::GetVertices(Array<int> &v) const
{
v.SetSize(8);
for (int i = 0; i < 8; i++)
{
v[i] = indices[i];
}
}
TriLinear3DFiniteElement HexahedronFE;
}
| 23.927273 | 80 | 0.642097 | [
"geometry"
] |
171a7c33176cbf61ba602cb4f0c69d2d9adf42cd | 1,062 | cpp | C++ | engine/src/physics/2d/circlecollider2d.cpp | TRBFLXR/x808 | d5ab9e96c5a6109283151a591c261e4183628075 | [
"MIT"
] | null | null | null | engine/src/physics/2d/circlecollider2d.cpp | TRBFLXR/x808 | d5ab9e96c5a6109283151a591c261e4183628075 | [
"MIT"
] | null | null | null | engine/src/physics/2d/circlecollider2d.cpp | TRBFLXR/x808 | d5ab9e96c5a6109283151a591c261e4183628075 | [
"MIT"
] | null | null | null | //
// Created by FLXR on 9/18/2018.
//
#include <Box2D/Box2D.h>
#include <xe/physics/2d/physicsworld2d.hpp>
#include <xe/physics/2d/circlecollider2d.hpp>
namespace xe {
CircleCollider2D::CircleCollider2D(PhysicsWorld2D *world, ColliderType type,
CircleShape *circle, bool fixedRotation) :
Collider2D(world, type, circle, fixedRotation) {
shape = new b2CircleShape();
}
CircleCollider2D::~CircleCollider2D() {
delete shape;
}
void CircleCollider2D::update() {
CircleShape *circle = (CircleShape *) transformable;
if (circle->isRadiusChanged()) {
circle->setRadiusChanged(false);
recreate();
}
transformable->setPosition(getPosition());
transformable->setRotation(getRotation());
}
void CircleCollider2D::recreate() {
const CircleShape *circle = (CircleShape *) transformable;
world->destroyBody(body);
create(world);
shape->m_radius = xeb2(circle->getRadius());
fixtureDef->shape = shape;
body->CreateFixture(fixtureDef);
}
} | 22.125 | 79 | 0.663842 | [
"shape"
] |
1722903d050f07df433c2cb559d7b9ba30006f14 | 5,024 | cpp | C++ | lib/Core/MAHandler.cpp | qiaokang92/P4wn | cd2418de2dff238f67508898e3bfdf2aae1889a4 | [
"NCSA"
] | 10 | 2020-12-26T07:18:14.000Z | 2022-01-11T23:46:13.000Z | lib/Core/MAHandler.cpp | qiaokang92/P4wn | cd2418de2dff238f67508898e3bfdf2aae1889a4 | [
"NCSA"
] | 1 | 2021-05-25T03:54:19.000Z | 2021-05-25T04:22:29.000Z | lib/Core/MAHandler.cpp | qiaokang92/P4wn | cd2418de2dff238f67508898e3bfdf2aae1889a4 | [
"NCSA"
] | null | null | null | #include <stdio.h>
#include <string>
#include <map>
#include <fstream>
#include "llvm/Support/raw_ostream.h"
#include <cstdio>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <array>
#include <regex>
#include "helper.h"
#include "klee/ExecutionState.h"
#include "klee/Internal/ADT/RNG.h"
#include <boost/math/distributions/binomial.hpp>
#include "Executor.h"
#include <cmath>
#include "MAHandler.h"
#include "klee/klee.h"
using namespace klee;
using namespace std;
using namespace llvm;
using boost::math::binomial;
namespace klee {
extern RNG theRNG;
}
MAHandler::MAHandler(Executor &_executor)
: executor(_executor)
{
printf("new MA handler created!\n");
}
MAHandler::MAHandler(MAHandler &_handler):
executor(_handler.executor)
{
}
MAHandler::~MAHandler()
{
}
MATable::MATable(int _nflows, ExecutionState *_state):
state(_state),
nflows(_nflows),
cur_size(0)
{
LOG(LOG_MASK_MA, "state[%d]: creating an MA table, nflows=%d",
state->id, _nflows);
}
MATable::MATable(const MATable &_ma):
nflows(_ma.nflows),
cur_size(_ma.cur_size),
status(_ma.status),
data(_ma.data)
{
LOG(LOG_MASK_MA, "state[%d]: forking a MA table, nflows=%d",
_ma.state->id, _ma.nflows);
}
MATable::~MATable()
{
}
int MATable::ma_insert(int val)
{
/*
LOG(LOG_MASK_MA, "state[%d]: inserting val=%d to MA, cur_size %d -> %d",
state->id, val, cur_size, cur_size + 1);
cur_size += 1;
auto it = data.find(val);
if (it == data.end()) {
data[val] = 1;
} else {
data[val] += 1;
}
*/
LOG(LOG_MASK_MA, "ignore MA table insertion request, val=%d", val);
return 0;
}
int MAHandler::ma_init(ExecutionState &cur)
{
//int nflows = executor.queryHandler->queryProbByName("nflows");
int nflows = 100; // not used
LOG(LOG_MASK_CMIN, "state[%d]: allocating MA, nflows=%d", cur.id, nflows);
cur.ma = new MATable(nflows, &cur);
return 0;
}
int MAHandler::ma_insert(ExecutionState &cur, int val)
{
//return cur.ma->ma_insert(val);
LOG(LOG_MASK_MA, "ignore MA table insertion request, val=%d", val);
return 0;
}
int MAHandler::ma_access(ExecutionState &cur,
std::vector<ExecutionState*> &states,
std::vector<int> &rets)
{
MATable *ma = cur.ma;
// empty MA table, will have to miss on the table
/*
if (ma->cur_size == 0) {
states.push_back(&cur);
rets.push_back(GREYBOX_MISS);
return 0;
}
*/
// fork 2 paths, hit or miss, and update the flag
//unsigned nflows = executor.queryHandler->queryProbByName("nflows");
//unsigned npkts = executor.queryHandler->queryProbByName("ntcp");
//unsigned npkts_per_flow = npkts / nflows;
double probMiss = executor.queryHandler->queryProbTableMiss();
double probHit = 1 - probMiss;
executor.branchTableAccessNoCond(cur, 2, states);
LOG(LOG_MASK_MA, "probMiss=%g", probMiss);
// the hit path
rets.push_back(GREYBOX_HIT);
states[0]->updatePathProb(probHit);
states[0]->ma->status = GREYBOX_HIT;
LOG(LOG_MASK_MA, "probHit %g, state[%d] is the hit branch, pathProb %g",
probHit, states[0]->id, states[0]->getPathProb());
// the miss path
rets.push_back(GREYBOX_MISS);
states[1]->updatePathProb(probMiss);
states[1]->ma->status = GREYBOX_MISS;
LOG(LOG_MASK_MA, "probMiss %g, state[%d] is the miss branch, pathProb %g",
probMiss, states[1]->id, states[1]->getPathProb());
return 0;
}
int MAHandler::ma_read(ExecutionState &cur,
std::vector<ExecutionState*> &states,
std::vector<int> &rets)
{
MATable *ma = cur.ma;
/*
if (ma->cur_size == 0 || ma->status != GREYBOX_HIT) {
ERR("illegal ma_read request");
assert(0);
}
vector<double> probs;
int sum = 0;
for (auto i : ma->data) {
if (i.second > 0) {
rets.push_back(i.first);
probs.push_back((double)i.second / (double)ma->cur_size);
}
sum += i.second;
}
assert(sum == ma->cur_size);
assert(rets.size() > 0);
LOG(LOG_MASK_MA, "read operation will return %ld paths", rets.size());
executor.branchTableAccessNoCond(cur, rets.size(), states);
for (int i = 0; i < states.size(); i ++) {
states[i]->updatePathProb(probs[i]);
LOG(LOG_MASK_MA, "state[%d] read val %d, prob %f, pathProb updated to %f",
states[i]->id, rets[i], probs[i], states[i]->getPathProb());
}
*/
// Assume the MA table only contains binary values.
double probTrue = executor.queryHandler->queryProbByName("ma_true");
double probFalse = 1 - probTrue;
rets.push_back(MA_READ_TRUE);
rets.push_back(MA_READ_FALSE);
executor.branchTableAccessNoCond(cur, rets.size(), states);
states[0]->updatePathProb(probTrue);
states[1]->updatePathProb(probFalse);
LOG(LOG_MASK_MA, "MA read: true path prob %g", states[0]->getPathProb());
LOG(LOG_MASK_MA, "MA read: false path prob %g", states[1]->getPathProb());
return 0;
}
| 24.995025 | 80 | 0.641521 | [
"vector"
] |
172411ee78068497d037be6ee2bd983d804f3756 | 5,688 | cpp | C++ | src/validators/claims/claimvalidatorfactory.cpp | bang-olufsen/jwt-cpp | cb649385ab5c0c7c0483b7b44bff909cf5fb0de1 | [
"MIT"
] | null | null | null | src/validators/claims/claimvalidatorfactory.cpp | bang-olufsen/jwt-cpp | cb649385ab5c0c7c0483b7b44bff909cf5fb0de1 | [
"MIT"
] | null | null | null | src/validators/claims/claimvalidatorfactory.cpp | bang-olufsen/jwt-cpp | cb649385ab5c0c7c0483b7b44bff909cf5fb0de1 | [
"MIT"
] | null | null | null | // Copyright (c) 2015 Erwin Jansen
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#include "jwt/claimvalidatorfactory.h"
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include "jwt/allocators.h"
#include "jwt/listclaimvalidator.h"
#include "jwt/timevalidator.h"
#include "private/buildwrappers.h"
#include <nlohmann/json.hpp>
using json = nlohmann::json;
ClaimValidatorFactory::~ClaimValidatorFactory() {
for (auto it = build_.begin(); it != build_.end(); it++) {
delete *it;
}
}
ClaimValidator *ClaimValidatorFactory::Build(const std::string &fromJson) {
json json = json::parse(fromJson);
return Build(json);
}
ClaimValidator *ClaimValidatorFactory::BuildInternal(const json &json) {
if (json.empty()) {
throw std::logic_error("Cannot construct from empty json!");
}
if (json.size() > 1) {
std::ostringstream msg;
msg << "More than one property at: " << json;
throw std::logic_error(msg.str());
}
ClaimValidator *constructed = nullptr;
try {
if (json.count("iss")) {
constructed = new IssValidator(BuildList(json["iss"]));
} else if (json.count("sub")) {
constructed = new SubValidator(BuildList(json["sub"]));
} else if (json.count("aud")) {
constructed = new AudValidator(BuildList(json["aud"]));
} else if (json.count("exp")) {
::json val = json["exp"];
::json leeway = val["leeway"];
constructed =
new ExpValidator(leeway.is_null() ? 0 : leeway.get<int>());
} else if (json.count("nbf")) {
::json val = json["nbf"];
::json leeway = val["leeway"];
constructed =
new NbfValidator(leeway.is_null() ? 0 : leeway.get<int>());
} else if (json.count("iat")) {
::json val = json["iat"];
::json leeway = val["leeway"];
constructed =
new IatValidator(leeway.is_null() ? 0 : leeway.get<int>());
} else if (json.count("all")) {
constructed =
new AllClaimValidator(BuildValidatorList(json["all"]));
} else if (json.count("any")) {
constructed =
new AnyClaimValidator(BuildValidatorList(json["any"]));
} else if (json.count("optional")) {
ClaimValidator *inner = BuildInternal(json["optional"]);
constructed = new OptionalClaimValidator(inner);
}
} catch (std::exception &le) {
throw std::logic_error(
std::string("Failed to construct validator at: ") + json.dump() +
", " + le.what());
}
if (!constructed) {
throw std::logic_error(std::string("No validator declared at: ") +
json.dump());
}
build_.push_back(constructed);
return constructed;
}
ClaimValidator *ClaimValidatorFactory::Build(const json &json) {
ClaimValidatorFactory factory;
ClaimValidator *root = factory.BuildInternal(json);
ParsedClaimvalidator *validator =
new ParsedClaimvalidator(json, factory.build_, root);
factory.build_.clear();
return validator;
}
std::vector<ClaimValidator *> ClaimValidatorFactory::BuildValidatorList(
const json &json) {
if (!json.is_array()) {
throw std::logic_error(json.dump() + " is not an array!");
}
std::vector<ClaimValidator *> result;
for (auto it = json.begin(); it != json.end(); ++it) {
result.push_back(BuildInternal(*it));
}
return result;
}
std::vector<std::string> ClaimValidatorFactory::BuildList(const json &object) {
if (!object.is_array()) {
throw std::logic_error(object.dump() + " is not an array!");
}
std::vector<std::string> result;
for (auto it = object.begin(); it != object.end(); ++it) {
if (!it->is_string()) {
throw std::logic_error("array can only contain strings");
}
result.push_back(it->get<std::string>());
}
return result;
}
ParsedClaimvalidator::ParsedClaimvalidator(
const json &json, const std::vector<ClaimValidator *> &children,
ClaimValidator *root)
: ClaimValidator(root->property()),
json_(json),
children_(children),
root_(root) {}
bool ParsedClaimvalidator::IsValid(const json &claimset) const {
return root_->IsValid(claimset);
}
ParsedClaimvalidator::~ParsedClaimvalidator() {
for (auto it = children_.begin(); it != children_.end(); it++) {
delete *it;
}
}
std::string ParsedClaimvalidator::toJson() const { return root_->toJson(); }
| 34.472727 | 79 | 0.629747 | [
"object",
"vector"
] |
17329e0f0501e5a821c4057f80acd4dbefa03a1a | 1,294 | hpp | C++ | scripts/tests/echolib.hpp | DongweiYe/muscle3 | 0c2fcf5f62995b8639fc84ce1b983c8a8e6248d0 | [
"Apache-2.0"
] | 11 | 2018-03-12T10:43:46.000Z | 2020-06-01T10:58:56.000Z | scripts/tests/echolib.hpp | DongweiYe/muscle3 | 0c2fcf5f62995b8639fc84ce1b983c8a8e6248d0 | [
"Apache-2.0"
] | 85 | 2018-03-03T15:10:56.000Z | 2022-03-18T14:05:14.000Z | scripts/tests/echolib.hpp | DongweiYe/muscle3 | 0c2fcf5f62995b8639fc84ce1b983c8a8e6248d0 | [
"Apache-2.0"
] | 6 | 2018-03-12T10:47:11.000Z | 2022-02-03T13:44:07.000Z | #pragma once
#include <cstdint>
#include <stdexcept>
#include <string>
#include <vector>
namespace echolib {
enum class Color {
RED = 1,
GREEN = 2,
BLUE = 3
};
class Echo {
public:
Echo(int argc, char const * const * argv);
void echo_nothing() const;
int echo_int(int value) const;
int64_t echo_int64_t(int64_t value) const;
double echo_double(double value) const;
bool echo_bool(bool value) const;
Color echo_enum(Color value) const;
std::string echo_string(std::string const & value) const;
std::vector<double> echo_double_vec(std::vector<double> const & value) const;
std::vector<std::vector<double>> echo_double_vec2(
std::vector<std::vector<double>> const & value) const;
Echo echo_object(Echo const & value) const;
std::vector<char> echo_bytes(std::vector<char> const & value) const;
std::string echo_error(double value) const;
template <typename T>
T echo_template(T const & value) const;
};
template <typename T>
T Echo::echo_template(T const & value) const {
return value;
}
template<>
inline int Echo::echo_template<int>(int const & value) const {
throw std::out_of_range("Testing exceptions and templates");
}
}
| 25.372549 | 85 | 0.649923 | [
"vector"
] |
1734dfdfe52f750f05788ccb1b76177734f3d4cb | 74,094 | cc | C++ | api.pb.cc | blockchainhelppro/Ninja-Trader-Integration-With-Bitoin-Trading | 5cd15b9399b1cd32504fdbbe91e16e2fd215680c | [
"MIT"
] | null | null | null | api.pb.cc | blockchainhelppro/Ninja-Trader-Integration-With-Bitoin-Trading | 5cd15b9399b1cd32504fdbbe91e16e2fd215680c | [
"MIT"
] | null | null | null | api.pb.cc | blockchainhelppro/Ninja-Trader-Integration-With-Bitoin-Trading | 5cd15b9399b1cd32504fdbbe91e16e2fd215680c | [
"MIT"
] | null | null | null | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/protobuf/api.proto
#include <google/protobuf/api.pb.h>
#include <algorithm>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/extension_set.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
// @@protoc_insertion_point(includes)
#include <google/protobuf/port_def.inc>
extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fapi_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_Mixin_google_2fprotobuf_2fapi_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fapi_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_Method_google_2fprotobuf_2fapi_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fsource_5fcontext_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_SourceContext_google_2fprotobuf_2fsource_5fcontext_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2ftype_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_Option_google_2fprotobuf_2ftype_2eproto;
namespace google {
namespace protobuf {
class ApiDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<Api> _instance;
} _Api_default_instance_;
class MethodDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<Method> _instance;
} _Method_default_instance_;
class MixinDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<Mixin> _instance;
} _Mixin_default_instance_;
} // namespace protobuf
} // namespace google
static void InitDefaultsApi_google_2fprotobuf_2fapi_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::google::protobuf::_Api_default_instance_;
new (ptr) ::google::protobuf::Api();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::google::protobuf::Api::InitAsDefaultInstance();
}
PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<4> scc_info_Api_google_2fprotobuf_2fapi_2eproto =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 4, InitDefaultsApi_google_2fprotobuf_2fapi_2eproto}, {
&scc_info_Method_google_2fprotobuf_2fapi_2eproto.base,
&scc_info_Option_google_2fprotobuf_2ftype_2eproto.base,
&scc_info_SourceContext_google_2fprotobuf_2fsource_5fcontext_2eproto.base,
&scc_info_Mixin_google_2fprotobuf_2fapi_2eproto.base,}};
static void InitDefaultsMethod_google_2fprotobuf_2fapi_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::google::protobuf::_Method_default_instance_;
new (ptr) ::google::protobuf::Method();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::google::protobuf::Method::InitAsDefaultInstance();
}
PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_Method_google_2fprotobuf_2fapi_2eproto =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsMethod_google_2fprotobuf_2fapi_2eproto}, {
&scc_info_Option_google_2fprotobuf_2ftype_2eproto.base,}};
static void InitDefaultsMixin_google_2fprotobuf_2fapi_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::google::protobuf::_Mixin_default_instance_;
new (ptr) ::google::protobuf::Mixin();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::google::protobuf::Mixin::InitAsDefaultInstance();
}
PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Mixin_google_2fprotobuf_2fapi_2eproto =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsMixin_google_2fprotobuf_2fapi_2eproto}, {}};
void InitDefaults_google_2fprotobuf_2fapi_2eproto() {
::google::protobuf::internal::InitSCC(&scc_info_Api_google_2fprotobuf_2fapi_2eproto.base);
::google::protobuf::internal::InitSCC(&scc_info_Method_google_2fprotobuf_2fapi_2eproto.base);
::google::protobuf::internal::InitSCC(&scc_info_Mixin_google_2fprotobuf_2fapi_2eproto.base);
}
::google::protobuf::Metadata file_level_metadata_google_2fprotobuf_2fapi_2eproto[3];
constexpr ::google::protobuf::EnumDescriptor const** file_level_enum_descriptors_google_2fprotobuf_2fapi_2eproto = nullptr;
constexpr ::google::protobuf::ServiceDescriptor const** file_level_service_descriptors_google_2fprotobuf_2fapi_2eproto = nullptr;
const ::google::protobuf::uint32 TableStruct_google_2fprotobuf_2fapi_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::google::protobuf::Api, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::google::protobuf::Api, name_),
PROTOBUF_FIELD_OFFSET(::google::protobuf::Api, methods_),
PROTOBUF_FIELD_OFFSET(::google::protobuf::Api, options_),
PROTOBUF_FIELD_OFFSET(::google::protobuf::Api, version_),
PROTOBUF_FIELD_OFFSET(::google::protobuf::Api, source_context_),
PROTOBUF_FIELD_OFFSET(::google::protobuf::Api, mixins_),
PROTOBUF_FIELD_OFFSET(::google::protobuf::Api, syntax_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::google::protobuf::Method, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::google::protobuf::Method, name_),
PROTOBUF_FIELD_OFFSET(::google::protobuf::Method, request_type_url_),
PROTOBUF_FIELD_OFFSET(::google::protobuf::Method, request_streaming_),
PROTOBUF_FIELD_OFFSET(::google::protobuf::Method, response_type_url_),
PROTOBUF_FIELD_OFFSET(::google::protobuf::Method, response_streaming_),
PROTOBUF_FIELD_OFFSET(::google::protobuf::Method, options_),
PROTOBUF_FIELD_OFFSET(::google::protobuf::Method, syntax_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::google::protobuf::Mixin, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::google::protobuf::Mixin, name_),
PROTOBUF_FIELD_OFFSET(::google::protobuf::Mixin, root_),
};
static const ::google::protobuf::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
{ 0, -1, sizeof(::google::protobuf::Api)},
{ 12, -1, sizeof(::google::protobuf::Method)},
{ 24, -1, sizeof(::google::protobuf::Mixin)},
};
static ::google::protobuf::Message const * const file_default_instances[] = {
reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_Api_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_Method_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_Mixin_default_instance_),
};
::google::protobuf::internal::AssignDescriptorsTable assign_descriptors_table_google_2fprotobuf_2fapi_2eproto = {
{}, AddDescriptors_google_2fprotobuf_2fapi_2eproto, "google/protobuf/api.proto", schemas,
file_default_instances, TableStruct_google_2fprotobuf_2fapi_2eproto::offsets,
file_level_metadata_google_2fprotobuf_2fapi_2eproto, 3, file_level_enum_descriptors_google_2fprotobuf_2fapi_2eproto, file_level_service_descriptors_google_2fprotobuf_2fapi_2eproto,
};
::google::protobuf::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fapi_2eproto = {
false, InitDefaults_google_2fprotobuf_2fapi_2eproto,
"\n\031google/protobuf/api.proto\022\017google.prot"
"obuf\032$google/protobuf/source_context.pro"
"to\032\032google/protobuf/type.proto\"\201\002\n\003Api\022\014"
"\n\004name\030\001 \001(\t\022(\n\007methods\030\002 \003(\0132\027.google.p"
"rotobuf.Method\022(\n\007options\030\003 \003(\0132\027.google"
".protobuf.Option\022\017\n\007version\030\004 \001(\t\0226\n\016sou"
"rce_context\030\005 \001(\0132\036.google.protobuf.Sour"
"ceContext\022&\n\006mixins\030\006 \003(\0132\026.google.proto"
"buf.Mixin\022\'\n\006syntax\030\007 \001(\0162\027.google.proto"
"buf.Syntax\"\325\001\n\006Method\022\014\n\004name\030\001 \001(\t\022\030\n\020r"
"equest_type_url\030\002 \001(\t\022\031\n\021request_streami"
"ng\030\003 \001(\010\022\031\n\021response_type_url\030\004 \001(\t\022\032\n\022r"
"esponse_streaming\030\005 \001(\010\022(\n\007options\030\006 \003(\013"
"2\027.google.protobuf.Option\022\'\n\006syntax\030\007 \001("
"\0162\027.google.protobuf.Syntax\"#\n\005Mixin\022\014\n\004n"
"ame\030\001 \001(\t\022\014\n\004root\030\002 \001(\tBu\n\023com.google.pr"
"otobufB\010ApiProtoP\001Z+google.golang.org/ge"
"nproto/protobuf/api;api\242\002\003GPB\252\002\036Google.P"
"rotobuf.WellKnownTypesb\006proto3"
,
"google/protobuf/api.proto", &assign_descriptors_table_google_2fprotobuf_2fapi_2eproto, 750,
};
void AddDescriptors_google_2fprotobuf_2fapi_2eproto() {
static constexpr ::google::protobuf::internal::InitFunc deps[2] =
{
::AddDescriptors_google_2fprotobuf_2fsource_5fcontext_2eproto,
::AddDescriptors_google_2fprotobuf_2ftype_2eproto,
};
::google::protobuf::internal::AddDescriptors(&descriptor_table_google_2fprotobuf_2fapi_2eproto, deps, 2);
}
// Force running AddDescriptors() at dynamic initialization time.
static bool dynamic_init_dummy_google_2fprotobuf_2fapi_2eproto = []() { AddDescriptors_google_2fprotobuf_2fapi_2eproto(); return true; }();
namespace google {
namespace protobuf {
// ===================================================================
void Api::InitAsDefaultInstance() {
::google::protobuf::_Api_default_instance_._instance.get_mutable()->source_context_ = const_cast< ::google::protobuf::SourceContext*>(
::google::protobuf::SourceContext::internal_default_instance());
}
class Api::HasBitSetters {
public:
static const ::google::protobuf::SourceContext& source_context(const Api* msg);
};
const ::google::protobuf::SourceContext&
Api::HasBitSetters::source_context(const Api* msg) {
return *msg->source_context_;
}
void Api::clear_options() {
options_.Clear();
}
void Api::clear_source_context() {
if (GetArenaNoVirtual() == NULL && source_context_ != NULL) {
delete source_context_;
}
source_context_ = NULL;
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int Api::kNameFieldNumber;
const int Api::kMethodsFieldNumber;
const int Api::kOptionsFieldNumber;
const int Api::kVersionFieldNumber;
const int Api::kSourceContextFieldNumber;
const int Api::kMixinsFieldNumber;
const int Api::kSyntaxFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
Api::Api()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Api)
}
Api::Api(const Api& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
methods_(from.methods_),
options_(from.options_),
mixins_(from.mixins_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.name().size() > 0) {
name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_);
}
version_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.version().size() > 0) {
version_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.version_);
}
if (from.has_source_context()) {
source_context_ = new ::google::protobuf::SourceContext(*from.source_context_);
} else {
source_context_ = NULL;
}
syntax_ = from.syntax_;
// @@protoc_insertion_point(copy_constructor:google.protobuf.Api)
}
void Api::SharedCtor() {
::google::protobuf::internal::InitSCC(
&scc_info_Api_google_2fprotobuf_2fapi_2eproto.base);
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
version_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
::memset(&source_context_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&syntax_) -
reinterpret_cast<char*>(&source_context_)) + sizeof(syntax_));
}
Api::~Api() {
// @@protoc_insertion_point(destructor:google.protobuf.Api)
SharedDtor();
}
void Api::SharedDtor() {
name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
version_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (this != internal_default_instance()) delete source_context_;
}
void Api::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const Api& Api::default_instance() {
::google::protobuf::internal::InitSCC(&::scc_info_Api_google_2fprotobuf_2fapi_2eproto.base);
return *internal_default_instance();
}
void Api::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.Api)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
methods_.Clear();
options_.Clear();
mixins_.Clear();
name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
version_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (GetArenaNoVirtual() == NULL && source_context_ != NULL) {
delete source_context_;
}
source_context_ = NULL;
syntax_ = 0;
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* Api::_InternalParse(const char* begin, const char* end, void* object,
::google::protobuf::internal::ParseContext* ctx) {
auto msg = static_cast<Api*>(object);
::google::protobuf::uint32 size; (void)size;
int depth; (void)depth;
::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
auto ptr = begin;
while (ptr < end) {
::google::protobuf::uint32 tag;
ptr = Varint::Parse32Inline(ptr, &tag);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
switch (tag >> 3) {
// string name = 1;
case 1: {
if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual;
ptr = Varint::Parse32Inline(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
ctx->extra_parse_data().SetFieldName("google.protobuf.Api.name");
parser_till_end = ::google::protobuf::internal::StringParserUTF8;
::std::string* str = msg->mutable_name();
str->clear();
object = str;
if (size > end - ptr) goto len_delim_till_end;
auto newend = ptr + size;
if (size) ptr = parser_till_end(ptr, newend, object, ctx);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
break;
}
// repeated .google.protobuf.Method methods = 2;
case 2: {
if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual;
do {
ptr = Varint::Parse32Inline(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
parser_till_end = ::google::protobuf::Method::_InternalParse;
object = msg->add_methods();
if (size > end - ptr) goto len_delim_till_end;
auto newend = ptr + size;
bool ok = ctx->ParseExactRange({parser_till_end, object},
ptr, newend);
GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
ptr = newend;
if (ptr >= end) break;
} while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 18 && (ptr += 1));
break;
}
// repeated .google.protobuf.Option options = 3;
case 3: {
if (static_cast<::google::protobuf::uint8>(tag) != 26) goto handle_unusual;
do {
ptr = Varint::Parse32Inline(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
parser_till_end = ::google::protobuf::Option::_InternalParse;
object = msg->add_options();
if (size > end - ptr) goto len_delim_till_end;
auto newend = ptr + size;
bool ok = ctx->ParseExactRange({parser_till_end, object},
ptr, newend);
GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
ptr = newend;
if (ptr >= end) break;
} while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 26 && (ptr += 1));
break;
}
// string version = 4;
case 4: {
if (static_cast<::google::protobuf::uint8>(tag) != 34) goto handle_unusual;
ptr = Varint::Parse32Inline(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
ctx->extra_parse_data().SetFieldName("google.protobuf.Api.version");
parser_till_end = ::google::protobuf::internal::StringParserUTF8;
::std::string* str = msg->mutable_version();
str->clear();
object = str;
if (size > end - ptr) goto len_delim_till_end;
auto newend = ptr + size;
if (size) ptr = parser_till_end(ptr, newend, object, ctx);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
break;
}
// .google.protobuf.SourceContext source_context = 5;
case 5: {
if (static_cast<::google::protobuf::uint8>(tag) != 42) goto handle_unusual;
ptr = Varint::Parse32Inline(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
parser_till_end = ::google::protobuf::SourceContext::_InternalParse;
object = msg->mutable_source_context();
if (size > end - ptr) goto len_delim_till_end;
auto newend = ptr + size;
bool ok = ctx->ParseExactRange({parser_till_end, object},
ptr, newend);
GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
ptr = newend;
break;
}
// repeated .google.protobuf.Mixin mixins = 6;
case 6: {
if (static_cast<::google::protobuf::uint8>(tag) != 50) goto handle_unusual;
do {
ptr = Varint::Parse32Inline(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
parser_till_end = ::google::protobuf::Mixin::_InternalParse;
object = msg->add_mixins();
if (size > end - ptr) goto len_delim_till_end;
auto newend = ptr + size;
bool ok = ctx->ParseExactRange({parser_till_end, object},
ptr, newend);
GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
ptr = newend;
if (ptr >= end) break;
} while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 50 && (ptr += 1));
break;
}
// .google.protobuf.Syntax syntax = 7;
case 7: {
if (static_cast<::google::protobuf::uint8>(tag) != 56) goto handle_unusual;
::google::protobuf::uint64 val;
ptr = Varint::Parse64(ptr, &val);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
::google::protobuf::Syntax value = static_cast<::google::protobuf::Syntax>(val);
msg->set_syntax(value);
break;
}
default: {
handle_unusual: (void)&&handle_unusual;
if ((tag & 7) == 4 || tag == 0) {
bool ok = ctx->ValidEndGroup(tag);
GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
return ptr;
}
auto res = UnknownFieldParse(tag, {_InternalParse, msg},
ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
ptr = res.first;
if (res.second) return ptr;
}
} // switch
} // while
return ptr;
len_delim_till_end: (void)&&len_delim_till_end;
return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
{parser_till_end, object}, size);
group_continues: (void)&&group_continues;
GOOGLE_DCHECK(ptr >= end);
ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
return ptr;
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool Api::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.Api)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// string name = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_name()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"google.protobuf.Api.name"));
} else {
goto handle_unusual;
}
break;
}
// repeated .google.protobuf.Method methods = 2;
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) == (18 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_methods()));
} else {
goto handle_unusual;
}
break;
}
// repeated .google.protobuf.Option options = 3;
case 3: {
if (static_cast< ::google::protobuf::uint8>(tag) == (26 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_options()));
} else {
goto handle_unusual;
}
break;
}
// string version = 4;
case 4: {
if (static_cast< ::google::protobuf::uint8>(tag) == (34 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_version()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->version().data(), static_cast<int>(this->version().length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"google.protobuf.Api.version"));
} else {
goto handle_unusual;
}
break;
}
// .google.protobuf.SourceContext source_context = 5;
case 5: {
if (static_cast< ::google::protobuf::uint8>(tag) == (42 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_source_context()));
} else {
goto handle_unusual;
}
break;
}
// repeated .google.protobuf.Mixin mixins = 6;
case 6: {
if (static_cast< ::google::protobuf::uint8>(tag) == (50 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_mixins()));
} else {
goto handle_unusual;
}
break;
}
// .google.protobuf.Syntax syntax = 7;
case 7: {
if (static_cast< ::google::protobuf::uint8>(tag) == (56 & 0xFF)) {
int value = 0;
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
set_syntax(static_cast< ::google::protobuf::Syntax >(value));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:google.protobuf.Api)
return true;
failure:
// @@protoc_insertion_point(parse_failure:google.protobuf.Api)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void Api::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.Api)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// string name = 1;
if (this->name().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Api.name");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
1, this->name(), output);
}
// repeated .google.protobuf.Method methods = 2;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->methods_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
2,
this->methods(static_cast<int>(i)),
output);
}
// repeated .google.protobuf.Option options = 3;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->options_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
3,
this->options(static_cast<int>(i)),
output);
}
// string version = 4;
if (this->version().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->version().data(), static_cast<int>(this->version().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Api.version");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
4, this->version(), output);
}
// .google.protobuf.SourceContext source_context = 5;
if (this->has_source_context()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
5, HasBitSetters::source_context(this), output);
}
// repeated .google.protobuf.Mixin mixins = 6;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->mixins_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
6,
this->mixins(static_cast<int>(i)),
output);
}
// .google.protobuf.Syntax syntax = 7;
if (this->syntax() != 0) {
::google::protobuf::internal::WireFormatLite::WriteEnum(
7, this->syntax(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.Api)
}
::google::protobuf::uint8* Api::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.Api)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// string name = 1;
if (this->name().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Api.name");
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
1, this->name(), target);
}
// repeated .google.protobuf.Method methods = 2;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->methods_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
2, this->methods(static_cast<int>(i)), deterministic, target);
}
// repeated .google.protobuf.Option options = 3;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->options_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
3, this->options(static_cast<int>(i)), deterministic, target);
}
// string version = 4;
if (this->version().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->version().data(), static_cast<int>(this->version().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Api.version");
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
4, this->version(), target);
}
// .google.protobuf.SourceContext source_context = 5;
if (this->has_source_context()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
5, HasBitSetters::source_context(this), deterministic, target);
}
// repeated .google.protobuf.Mixin mixins = 6;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->mixins_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
6, this->mixins(static_cast<int>(i)), deterministic, target);
}
// .google.protobuf.Syntax syntax = 7;
if (this->syntax() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray(
7, this->syntax(), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Api)
return target;
}
size_t Api::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.Api)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// repeated .google.protobuf.Method methods = 2;
{
unsigned int count = static_cast<unsigned int>(this->methods_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
::google::protobuf::internal::WireFormatLite::MessageSize(
this->methods(static_cast<int>(i)));
}
}
// repeated .google.protobuf.Option options = 3;
{
unsigned int count = static_cast<unsigned int>(this->options_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
::google::protobuf::internal::WireFormatLite::MessageSize(
this->options(static_cast<int>(i)));
}
}
// repeated .google.protobuf.Mixin mixins = 6;
{
unsigned int count = static_cast<unsigned int>(this->mixins_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
::google::protobuf::internal::WireFormatLite::MessageSize(
this->mixins(static_cast<int>(i)));
}
}
// string name = 1;
if (this->name().size() > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->name());
}
// string version = 4;
if (this->version().size() > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->version());
}
// .google.protobuf.SourceContext source_context = 5;
if (this->has_source_context()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*source_context_);
}
// .google.protobuf.Syntax syntax = 7;
if (this->syntax() != 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::EnumSize(this->syntax());
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void Api::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.Api)
GOOGLE_DCHECK_NE(&from, this);
const Api* source =
::google::protobuf::DynamicCastToGenerated<Api>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.Api)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.Api)
MergeFrom(*source);
}
}
void Api::MergeFrom(const Api& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Api)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
methods_.MergeFrom(from.methods_);
options_.MergeFrom(from.options_);
mixins_.MergeFrom(from.mixins_);
if (from.name().size() > 0) {
name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_);
}
if (from.version().size() > 0) {
version_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.version_);
}
if (from.has_source_context()) {
mutable_source_context()->::google::protobuf::SourceContext::MergeFrom(from.source_context());
}
if (from.syntax() != 0) {
set_syntax(from.syntax());
}
}
void Api::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.Api)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void Api::CopyFrom(const Api& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.Api)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool Api::IsInitialized() const {
return true;
}
void Api::Swap(Api* other) {
if (other == this) return;
InternalSwap(other);
}
void Api::InternalSwap(Api* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
CastToBase(&methods_)->InternalSwap(CastToBase(&other->methods_));
CastToBase(&options_)->InternalSwap(CastToBase(&other->options_));
CastToBase(&mixins_)->InternalSwap(CastToBase(&other->mixins_));
name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
version_.Swap(&other->version_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
swap(source_context_, other->source_context_);
swap(syntax_, other->syntax_);
}
::google::protobuf::Metadata Api::GetMetadata() const {
::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fapi_2eproto);
return ::file_level_metadata_google_2fprotobuf_2fapi_2eproto[kIndexInFileMessages];
}
// ===================================================================
void Method::InitAsDefaultInstance() {
}
class Method::HasBitSetters {
public:
};
void Method::clear_options() {
options_.Clear();
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int Method::kNameFieldNumber;
const int Method::kRequestTypeUrlFieldNumber;
const int Method::kRequestStreamingFieldNumber;
const int Method::kResponseTypeUrlFieldNumber;
const int Method::kResponseStreamingFieldNumber;
const int Method::kOptionsFieldNumber;
const int Method::kSyntaxFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
Method::Method()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Method)
}
Method::Method(const Method& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
options_(from.options_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.name().size() > 0) {
name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_);
}
request_type_url_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.request_type_url().size() > 0) {
request_type_url_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.request_type_url_);
}
response_type_url_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.response_type_url().size() > 0) {
response_type_url_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.response_type_url_);
}
::memcpy(&request_streaming_, &from.request_streaming_,
static_cast<size_t>(reinterpret_cast<char*>(&syntax_) -
reinterpret_cast<char*>(&request_streaming_)) + sizeof(syntax_));
// @@protoc_insertion_point(copy_constructor:google.protobuf.Method)
}
void Method::SharedCtor() {
::google::protobuf::internal::InitSCC(
&scc_info_Method_google_2fprotobuf_2fapi_2eproto.base);
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
request_type_url_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
response_type_url_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
::memset(&request_streaming_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&syntax_) -
reinterpret_cast<char*>(&request_streaming_)) + sizeof(syntax_));
}
Method::~Method() {
// @@protoc_insertion_point(destructor:google.protobuf.Method)
SharedDtor();
}
void Method::SharedDtor() {
name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
request_type_url_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
response_type_url_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
void Method::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const Method& Method::default_instance() {
::google::protobuf::internal::InitSCC(&::scc_info_Method_google_2fprotobuf_2fapi_2eproto.base);
return *internal_default_instance();
}
void Method::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.Method)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
options_.Clear();
name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
request_type_url_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
response_type_url_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
::memset(&request_streaming_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&syntax_) -
reinterpret_cast<char*>(&request_streaming_)) + sizeof(syntax_));
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* Method::_InternalParse(const char* begin, const char* end, void* object,
::google::protobuf::internal::ParseContext* ctx) {
auto msg = static_cast<Method*>(object);
::google::protobuf::uint32 size; (void)size;
int depth; (void)depth;
::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
auto ptr = begin;
while (ptr < end) {
::google::protobuf::uint32 tag;
ptr = Varint::Parse32Inline(ptr, &tag);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
switch (tag >> 3) {
// string name = 1;
case 1: {
if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual;
ptr = Varint::Parse32Inline(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
ctx->extra_parse_data().SetFieldName("google.protobuf.Method.name");
parser_till_end = ::google::protobuf::internal::StringParserUTF8;
::std::string* str = msg->mutable_name();
str->clear();
object = str;
if (size > end - ptr) goto len_delim_till_end;
auto newend = ptr + size;
if (size) ptr = parser_till_end(ptr, newend, object, ctx);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
break;
}
// string request_type_url = 2;
case 2: {
if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual;
ptr = Varint::Parse32Inline(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
ctx->extra_parse_data().SetFieldName("google.protobuf.Method.request_type_url");
parser_till_end = ::google::protobuf::internal::StringParserUTF8;
::std::string* str = msg->mutable_request_type_url();
str->clear();
object = str;
if (size > end - ptr) goto len_delim_till_end;
auto newend = ptr + size;
if (size) ptr = parser_till_end(ptr, newend, object, ctx);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
break;
}
// bool request_streaming = 3;
case 3: {
if (static_cast<::google::protobuf::uint8>(tag) != 24) goto handle_unusual;
::google::protobuf::uint64 val;
ptr = Varint::Parse64(ptr, &val);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
bool value = val;
msg->set_request_streaming(value);
break;
}
// string response_type_url = 4;
case 4: {
if (static_cast<::google::protobuf::uint8>(tag) != 34) goto handle_unusual;
ptr = Varint::Parse32Inline(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
ctx->extra_parse_data().SetFieldName("google.protobuf.Method.response_type_url");
parser_till_end = ::google::protobuf::internal::StringParserUTF8;
::std::string* str = msg->mutable_response_type_url();
str->clear();
object = str;
if (size > end - ptr) goto len_delim_till_end;
auto newend = ptr + size;
if (size) ptr = parser_till_end(ptr, newend, object, ctx);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
break;
}
// bool response_streaming = 5;
case 5: {
if (static_cast<::google::protobuf::uint8>(tag) != 40) goto handle_unusual;
::google::protobuf::uint64 val;
ptr = Varint::Parse64(ptr, &val);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
bool value = val;
msg->set_response_streaming(value);
break;
}
// repeated .google.protobuf.Option options = 6;
case 6: {
if (static_cast<::google::protobuf::uint8>(tag) != 50) goto handle_unusual;
do {
ptr = Varint::Parse32Inline(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
parser_till_end = ::google::protobuf::Option::_InternalParse;
object = msg->add_options();
if (size > end - ptr) goto len_delim_till_end;
auto newend = ptr + size;
bool ok = ctx->ParseExactRange({parser_till_end, object},
ptr, newend);
GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
ptr = newend;
if (ptr >= end) break;
} while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 50 && (ptr += 1));
break;
}
// .google.protobuf.Syntax syntax = 7;
case 7: {
if (static_cast<::google::protobuf::uint8>(tag) != 56) goto handle_unusual;
::google::protobuf::uint64 val;
ptr = Varint::Parse64(ptr, &val);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
::google::protobuf::Syntax value = static_cast<::google::protobuf::Syntax>(val);
msg->set_syntax(value);
break;
}
default: {
handle_unusual: (void)&&handle_unusual;
if ((tag & 7) == 4 || tag == 0) {
bool ok = ctx->ValidEndGroup(tag);
GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
return ptr;
}
auto res = UnknownFieldParse(tag, {_InternalParse, msg},
ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
ptr = res.first;
if (res.second) return ptr;
}
} // switch
} // while
return ptr;
len_delim_till_end: (void)&&len_delim_till_end;
return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
{parser_till_end, object}, size);
group_continues: (void)&&group_continues;
GOOGLE_DCHECK(ptr >= end);
ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
return ptr;
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool Method::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.Method)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// string name = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_name()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"google.protobuf.Method.name"));
} else {
goto handle_unusual;
}
break;
}
// string request_type_url = 2;
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) == (18 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_request_type_url()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->request_type_url().data(), static_cast<int>(this->request_type_url().length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"google.protobuf.Method.request_type_url"));
} else {
goto handle_unusual;
}
break;
}
// bool request_streaming = 3;
case 3: {
if (static_cast< ::google::protobuf::uint8>(tag) == (24 & 0xFF)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &request_streaming_)));
} else {
goto handle_unusual;
}
break;
}
// string response_type_url = 4;
case 4: {
if (static_cast< ::google::protobuf::uint8>(tag) == (34 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_response_type_url()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->response_type_url().data(), static_cast<int>(this->response_type_url().length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"google.protobuf.Method.response_type_url"));
} else {
goto handle_unusual;
}
break;
}
// bool response_streaming = 5;
case 5: {
if (static_cast< ::google::protobuf::uint8>(tag) == (40 & 0xFF)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &response_streaming_)));
} else {
goto handle_unusual;
}
break;
}
// repeated .google.protobuf.Option options = 6;
case 6: {
if (static_cast< ::google::protobuf::uint8>(tag) == (50 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_options()));
} else {
goto handle_unusual;
}
break;
}
// .google.protobuf.Syntax syntax = 7;
case 7: {
if (static_cast< ::google::protobuf::uint8>(tag) == (56 & 0xFF)) {
int value = 0;
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
set_syntax(static_cast< ::google::protobuf::Syntax >(value));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:google.protobuf.Method)
return true;
failure:
// @@protoc_insertion_point(parse_failure:google.protobuf.Method)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void Method::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.Method)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// string name = 1;
if (this->name().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Method.name");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
1, this->name(), output);
}
// string request_type_url = 2;
if (this->request_type_url().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->request_type_url().data(), static_cast<int>(this->request_type_url().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Method.request_type_url");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
2, this->request_type_url(), output);
}
// bool request_streaming = 3;
if (this->request_streaming() != 0) {
::google::protobuf::internal::WireFormatLite::WriteBool(3, this->request_streaming(), output);
}
// string response_type_url = 4;
if (this->response_type_url().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->response_type_url().data(), static_cast<int>(this->response_type_url().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Method.response_type_url");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
4, this->response_type_url(), output);
}
// bool response_streaming = 5;
if (this->response_streaming() != 0) {
::google::protobuf::internal::WireFormatLite::WriteBool(5, this->response_streaming(), output);
}
// repeated .google.protobuf.Option options = 6;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->options_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
6,
this->options(static_cast<int>(i)),
output);
}
// .google.protobuf.Syntax syntax = 7;
if (this->syntax() != 0) {
::google::protobuf::internal::WireFormatLite::WriteEnum(
7, this->syntax(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.Method)
}
::google::protobuf::uint8* Method::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.Method)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// string name = 1;
if (this->name().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Method.name");
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
1, this->name(), target);
}
// string request_type_url = 2;
if (this->request_type_url().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->request_type_url().data(), static_cast<int>(this->request_type_url().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Method.request_type_url");
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
2, this->request_type_url(), target);
}
// bool request_streaming = 3;
if (this->request_streaming() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(3, this->request_streaming(), target);
}
// string response_type_url = 4;
if (this->response_type_url().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->response_type_url().data(), static_cast<int>(this->response_type_url().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Method.response_type_url");
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
4, this->response_type_url(), target);
}
// bool response_streaming = 5;
if (this->response_streaming() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(5, this->response_streaming(), target);
}
// repeated .google.protobuf.Option options = 6;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->options_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
6, this->options(static_cast<int>(i)), deterministic, target);
}
// .google.protobuf.Syntax syntax = 7;
if (this->syntax() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray(
7, this->syntax(), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Method)
return target;
}
size_t Method::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.Method)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// repeated .google.protobuf.Option options = 6;
{
unsigned int count = static_cast<unsigned int>(this->options_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
::google::protobuf::internal::WireFormatLite::MessageSize(
this->options(static_cast<int>(i)));
}
}
// string name = 1;
if (this->name().size() > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->name());
}
// string request_type_url = 2;
if (this->request_type_url().size() > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->request_type_url());
}
// string response_type_url = 4;
if (this->response_type_url().size() > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->response_type_url());
}
// bool request_streaming = 3;
if (this->request_streaming() != 0) {
total_size += 1 + 1;
}
// bool response_streaming = 5;
if (this->response_streaming() != 0) {
total_size += 1 + 1;
}
// .google.protobuf.Syntax syntax = 7;
if (this->syntax() != 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::EnumSize(this->syntax());
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void Method::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.Method)
GOOGLE_DCHECK_NE(&from, this);
const Method* source =
::google::protobuf::DynamicCastToGenerated<Method>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.Method)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.Method)
MergeFrom(*source);
}
}
void Method::MergeFrom(const Method& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Method)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
options_.MergeFrom(from.options_);
if (from.name().size() > 0) {
name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_);
}
if (from.request_type_url().size() > 0) {
request_type_url_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.request_type_url_);
}
if (from.response_type_url().size() > 0) {
response_type_url_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.response_type_url_);
}
if (from.request_streaming() != 0) {
set_request_streaming(from.request_streaming());
}
if (from.response_streaming() != 0) {
set_response_streaming(from.response_streaming());
}
if (from.syntax() != 0) {
set_syntax(from.syntax());
}
}
void Method::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.Method)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void Method::CopyFrom(const Method& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.Method)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool Method::IsInitialized() const {
return true;
}
void Method::Swap(Method* other) {
if (other == this) return;
InternalSwap(other);
}
void Method::InternalSwap(Method* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
CastToBase(&options_)->InternalSwap(CastToBase(&other->options_));
name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
request_type_url_.Swap(&other->request_type_url_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
response_type_url_.Swap(&other->response_type_url_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
swap(request_streaming_, other->request_streaming_);
swap(response_streaming_, other->response_streaming_);
swap(syntax_, other->syntax_);
}
::google::protobuf::Metadata Method::GetMetadata() const {
::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fapi_2eproto);
return ::file_level_metadata_google_2fprotobuf_2fapi_2eproto[kIndexInFileMessages];
}
// ===================================================================
void Mixin::InitAsDefaultInstance() {
}
class Mixin::HasBitSetters {
public:
};
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int Mixin::kNameFieldNumber;
const int Mixin::kRootFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
Mixin::Mixin()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Mixin)
}
Mixin::Mixin(const Mixin& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.name().size() > 0) {
name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_);
}
root_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.root().size() > 0) {
root_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.root_);
}
// @@protoc_insertion_point(copy_constructor:google.protobuf.Mixin)
}
void Mixin::SharedCtor() {
::google::protobuf::internal::InitSCC(
&scc_info_Mixin_google_2fprotobuf_2fapi_2eproto.base);
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
root_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
Mixin::~Mixin() {
// @@protoc_insertion_point(destructor:google.protobuf.Mixin)
SharedDtor();
}
void Mixin::SharedDtor() {
name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
root_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
void Mixin::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const Mixin& Mixin::default_instance() {
::google::protobuf::internal::InitSCC(&::scc_info_Mixin_google_2fprotobuf_2fapi_2eproto.base);
return *internal_default_instance();
}
void Mixin::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.Mixin)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
root_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* Mixin::_InternalParse(const char* begin, const char* end, void* object,
::google::protobuf::internal::ParseContext* ctx) {
auto msg = static_cast<Mixin*>(object);
::google::protobuf::uint32 size; (void)size;
int depth; (void)depth;
::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
auto ptr = begin;
while (ptr < end) {
::google::protobuf::uint32 tag;
ptr = Varint::Parse32Inline(ptr, &tag);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
switch (tag >> 3) {
// string name = 1;
case 1: {
if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual;
ptr = Varint::Parse32Inline(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
ctx->extra_parse_data().SetFieldName("google.protobuf.Mixin.name");
parser_till_end = ::google::protobuf::internal::StringParserUTF8;
::std::string* str = msg->mutable_name();
str->clear();
object = str;
if (size > end - ptr) goto len_delim_till_end;
auto newend = ptr + size;
if (size) ptr = parser_till_end(ptr, newend, object, ctx);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
break;
}
// string root = 2;
case 2: {
if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual;
ptr = Varint::Parse32Inline(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
ctx->extra_parse_data().SetFieldName("google.protobuf.Mixin.root");
parser_till_end = ::google::protobuf::internal::StringParserUTF8;
::std::string* str = msg->mutable_root();
str->clear();
object = str;
if (size > end - ptr) goto len_delim_till_end;
auto newend = ptr + size;
if (size) ptr = parser_till_end(ptr, newend, object, ctx);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
break;
}
default: {
handle_unusual: (void)&&handle_unusual;
if ((tag & 7) == 4 || tag == 0) {
bool ok = ctx->ValidEndGroup(tag);
GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
return ptr;
}
auto res = UnknownFieldParse(tag, {_InternalParse, msg},
ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
ptr = res.first;
if (res.second) return ptr;
}
} // switch
} // while
return ptr;
len_delim_till_end: (void)&&len_delim_till_end;
return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
{parser_till_end, object}, size);
group_continues: (void)&&group_continues;
GOOGLE_DCHECK(ptr >= end);
ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
return ptr;
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool Mixin::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.Mixin)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// string name = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_name()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"google.protobuf.Mixin.name"));
} else {
goto handle_unusual;
}
break;
}
// string root = 2;
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) == (18 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_root()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->root().data(), static_cast<int>(this->root().length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"google.protobuf.Mixin.root"));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:google.protobuf.Mixin)
return true;
failure:
// @@protoc_insertion_point(parse_failure:google.protobuf.Mixin)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void Mixin::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.Mixin)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// string name = 1;
if (this->name().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Mixin.name");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
1, this->name(), output);
}
// string root = 2;
if (this->root().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->root().data(), static_cast<int>(this->root().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Mixin.root");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
2, this->root(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.Mixin)
}
::google::protobuf::uint8* Mixin::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.Mixin)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// string name = 1;
if (this->name().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Mixin.name");
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
1, this->name(), target);
}
// string root = 2;
if (this->root().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->root().data(), static_cast<int>(this->root().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Mixin.root");
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
2, this->root(), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Mixin)
return target;
}
size_t Mixin::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.Mixin)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// string name = 1;
if (this->name().size() > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->name());
}
// string root = 2;
if (this->root().size() > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->root());
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void Mixin::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.Mixin)
GOOGLE_DCHECK_NE(&from, this);
const Mixin* source =
::google::protobuf::DynamicCastToGenerated<Mixin>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.Mixin)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.Mixin)
MergeFrom(*source);
}
}
void Mixin::MergeFrom(const Mixin& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Mixin)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.name().size() > 0) {
name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_);
}
if (from.root().size() > 0) {
root_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.root_);
}
}
void Mixin::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.Mixin)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void Mixin::CopyFrom(const Mixin& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.Mixin)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool Mixin::IsInitialized() const {
return true;
}
void Mixin::Swap(Mixin* other) {
if (other == this) return;
InternalSwap(other);
}
void Mixin::InternalSwap(Mixin* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
root_.Swap(&other->root_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
::google::protobuf::Metadata Mixin::GetMetadata() const {
::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fapi_2eproto);
return ::file_level_metadata_google_2fprotobuf_2fapi_2eproto[kIndexInFileMessages];
}
// @@protoc_insertion_point(namespace_scope)
} // namespace protobuf
} // namespace google
namespace google {
namespace protobuf {
template<> PROTOBUF_NOINLINE ::google::protobuf::Api* Arena::CreateMaybeMessage< ::google::protobuf::Api >(Arena* arena) {
return Arena::CreateInternal< ::google::protobuf::Api >(arena);
}
template<> PROTOBUF_NOINLINE ::google::protobuf::Method* Arena::CreateMaybeMessage< ::google::protobuf::Method >(Arena* arena) {
return Arena::CreateInternal< ::google::protobuf::Method >(arena);
}
template<> PROTOBUF_NOINLINE ::google::protobuf::Mixin* Arena::CreateMaybeMessage< ::google::protobuf::Mixin >(Arena* arena) {
return Arena::CreateInternal< ::google::protobuf::Mixin >(arena);
}
} // namespace protobuf
} // namespace google
// @@protoc_insertion_point(global_scope)
#include <google/protobuf/port_undef.inc>
| 38.731835 | 186 | 0.677113 | [
"object"
] |
173b6c89b1cecba276aea3bd16ef28ec877d3fe5 | 1,427 | cpp | C++ | src/myImportandFunction/alignTranscript.cpp | illarionovaanastasia/GEAN | b81bbf45dd869ffde2833fd1eb78463d09de45cb | [
"MIT"
] | 34 | 2019-01-17T22:47:17.000Z | 2021-12-20T08:36:44.000Z | src/myImportandFunction/alignTranscript.cpp | illarionovaanastasia/GEAN | b81bbf45dd869ffde2833fd1eb78463d09de45cb | [
"MIT"
] | 7 | 2019-04-23T02:50:13.000Z | 2021-05-05T07:32:46.000Z | src/myImportandFunction/alignTranscript.cpp | illarionovaanastasia/GEAN | b81bbf45dd869ffde2833fd1eb78463d09de45cb | [
"MIT"
] | 5 | 2019-03-14T23:05:46.000Z | 2020-08-17T09:14:17.000Z | //
// Created by song on 8/26/18.
//
#include "alignTranscript.h"
AlignTranscript::AlignTranscript(std::string& dna_d, std::string& dna_q, int & startCodonPosition, int & stopCodonPosition,
std::vector<SpliceSitePosition>& splitSitePositions, std::map<std::string, std::string>& parameters, NucleotideCodeSubstitutionMatrix& nucleotideCodeSubstitutionMatrix){
#ifdef __AVX2__
if( dna_d.length() > 3270 || dna_q.length()>3270 ){
alignNeedlemanForTranscript_simd_avx2int32(dna_d, dna_q, startCodonPosition, stopCodonPosition, splitSitePositions, parameters, nucleotideCodeSubstitutionMatrix,alignment_q, alignment_d, infor);
}else{
avx16 = new alignNeedlemanForTranscript_simd_avx2int16(dna_d, dna_q, startCodonPosition, stopCodonPosition, splitSitePositions, parameters, nucleotideCodeSubstitutionMatrix);
alignment_q = avx16->getAlignment_q();
alignment_d = avx16->getAlignment_d();
infor = avx16->getInfor();
}
#else
alignNeedlemanForTranscript(dna_d, dna_q, startCodonPosition, stopCodonPosition, splitSitePositions, parameters, nucleotideCodeSubstitutionMatrix,alignment_q, alignment_d, infor);
#endif
}
AlignTranscript::~AlignTranscript(){
if( avx16 != NULL ){
delete(avx16);
}
}
std::string AlignTranscript::getAlignment_q(){
return this->alignment_q;
}
std::string AlignTranscript::getAlignment_d(){
return this->alignment_d;
}
| 39.638889 | 202 | 0.756132 | [
"vector"
] |
173c776195593301bfe6aad72afda986ccc41f91 | 1,097 | hpp | C++ | OGL - EGE/engine/system/System.hpp | johnathontheriot/Edge | 916db7c49e33569e172917c5aff93414e4d2b174 | [
"MIT"
] | 1 | 2018-01-08T14:37:57.000Z | 2018-01-08T14:37:57.000Z | OGL - EGE/engine/system/System.hpp | johnathontheriot/Edge | 916db7c49e33569e172917c5aff93414e4d2b174 | [
"MIT"
] | 18 | 2018-01-08T14:35:25.000Z | 2018-02-14T19:29:27.000Z | OGL - EGE/engine/system/System.hpp | johnathontheriot/Edge | 916db7c49e33569e172917c5aff93414e4d2b174 | [
"MIT"
] | null | null | null | //
// System.hpp
// OGL - EGE
//
// Created by Johnathon Theriot on 1/5/18.
// Copyright © 2018 Johnathon Theriot. All rights reserved.
//
#ifndef System_hpp
#define System_hpp
#include <unordered_map>
#include "WindowConfig.hpp"
#include "../../vendor/json.hpp"
#include "../object/scene/Scene.hpp"
#include "Dimensions.hpp"
using json = nlohmann::json;
class System {
private:
int monitorCount = 0;
GLFWmonitor * primaryMonitor;
GLFWmonitor ** monitors;
GLFWwindow * activeWindow;
System();
public:
static System * Instance;
static std::string readFile(std::string path);
static std::string configPath;
static System * getInstance();
bool shouldClose();
GLFWwindow * addWindow(WindowConfig * config);
GLFWwindow * getActiveWindow();
void setActiveWindow(std::string name);
void setActiveWindow(GLFWwindow * window);
std::unordered_map<std::string, GLFWwindow*> * windows;
Dimensions getWindowDimenions(std::string name);
Dimensions getWindowDimenions(GLFWwindow * window);
void start();
};
#endif /* System_hpp */
| 24.931818 | 60 | 0.696445 | [
"object"
] |
173e698b7f726f522faff85dc26b337c07d06537 | 51,407 | cpp | C++ | source/CompilerSpirV/SpirvExprVisitor.cpp | Praetonus/ShaderWriter | 1c5b3961e3e1b91cb7158406998519853a4add07 | [
"MIT"
] | null | null | null | source/CompilerSpirV/SpirvExprVisitor.cpp | Praetonus/ShaderWriter | 1c5b3961e3e1b91cb7158406998519853a4add07 | [
"MIT"
] | null | null | null | source/CompilerSpirV/SpirvExprVisitor.cpp | Praetonus/ShaderWriter | 1c5b3961e3e1b91cb7158406998519853a4add07 | [
"MIT"
] | null | null | null | /*
See LICENSE file in root folder
*/
#include "SpirvExprVisitor.hpp"
#include "SpirvHelpers.hpp"
#include "SpirvGetSwizzleComponents.hpp"
#include "SpirvImageAccessConfig.hpp"
#include "SpirvImageAccessNames.hpp"
#include "SpirvIntrinsicConfig.hpp"
#include "SpirvIntrinsicNames.hpp"
#include "SpirvMakeAccessChain.hpp"
#include "SpirvTextureAccessConfig.hpp"
#include "SpirvTextureAccessNames.hpp"
#include <ShaderAST/Type/TypeImage.hpp>
#include <ShaderAST/Type/TypeSampledImage.hpp>
#include <ShaderAST/Visitors/GetExprName.hpp>
#include <ShaderAST/Visitors/GetOutermostExpr.hpp>
#include <algorithm>
#include <numeric>
#include <sstream>
#include <stdexcept>
namespace spirv
{
namespace
{
class HasFnCall
: public ast::expr::SimpleVisitor
{
public:
static bool submit( ast::expr::Expr * expr )
{
bool result{ false };
HasFnCall vis{ result };
expr->accept( &vis );
return result;
}
private:
HasFnCall( bool & result )
: m_result{ result }
{
}
private:
void visitUnaryExpr( ast::expr::Unary * expr )override
{
expr->getOperand()->accept( this );
}
void visitBinaryExpr( ast::expr::Binary * expr )override
{
expr->getLHS()->accept( this );
expr->getRHS()->accept( this );
}
void visitAggrInitExpr( ast::expr::AggrInit * expr )override
{
if ( expr->getIdentifier() )
{
expr->getIdentifier()->accept( this );
}
for ( auto & arg : expr->getInitialisers() )
{
arg->accept( this );
}
}
void visitCompositeConstructExpr( ast::expr::CompositeConstruct * expr )override
{
for ( auto & arg : expr->getArgList() )
{
arg->accept( this );
}
}
void visitMbrSelectExpr( ast::expr::MbrSelect * expr )override
{
expr->getOuterExpr()->accept( this );
}
void visitFnCallExpr( ast::expr::FnCall * expr )override
{
expr->getFn()->accept( this );
for ( auto & arg : expr->getArgList() )
{
arg->accept( this );
}
m_result = true;
}
void visitIntrinsicCallExpr( ast::expr::IntrinsicCall * expr )override
{
for ( auto & arg : expr->getArgList() )
{
arg->accept( this );
}
m_result = true;
}
void visitTextureAccessCallExpr( ast::expr::TextureAccessCall * expr )override
{
for ( auto & arg : expr->getArgList() )
{
arg->accept( this );
}
m_result = true;
}
void visitImageAccessCallExpr( ast::expr::ImageAccessCall * expr )override
{
for ( auto & arg : expr->getArgList() )
{
arg->accept( this );
}
m_result = true;
}
void visitIdentifierExpr( ast::expr::Identifier * expr )override
{
}
void visitInitExpr( ast::expr::Init * expr )override
{
expr->getIdentifier()->accept( this );
expr->getInitialiser()->accept( this );
}
void visitLiteralExpr( ast::expr::Literal * expr )override
{
}
void visitQuestionExpr( ast::expr::Question * expr )override
{
expr->getCtrlExpr()->accept( this );
expr->getTrueExpr()->accept( this );
expr->getFalseExpr()->accept( this );
}
void visitSwitchCaseExpr( ast::expr::SwitchCase * expr )override
{
expr->getLabel()->accept( this );
}
void visitSwitchTestExpr( ast::expr::SwitchTest * expr )override
{
expr->getValue()->accept( this );
}
void visitSwizzleExpr( ast::expr::Swizzle * expr )override
{
expr->getOuterExpr()->accept( this );
}
private:
bool & m_result;
};
std::string adaptName( std::string const & name )
{
static std::map< std::string, std::string > const names
{
{ "gl_InstanceID", "gl_InstanceIndex" },
{ "gl_VertexID", "gl_VertexIndex" },
};
auto it = names.find( name );
if ( it != names.end() )
{
return it->second;
}
return name;
}
spv::Id loadVariable( spv::Id varId
, ast::type::TypePtr type
, Module & module
, Block & currentBlock
, LoadedVariableArray & loadedVariables )
{
auto it = std::find_if( loadedVariables.begin()
, loadedVariables.end()
, [varId]( LoadedVariable const & lookup )
{
return lookup.varId == varId;
} );
if ( loadedVariables.end() == it )
{
auto loadedRhsId = module.loadVariable( varId
, type
, currentBlock );
loadedVariables.push_back( { varId, loadedRhsId } );
it = loadedVariables.begin() + loadedVariables.size() - 1u;
}
return it->loadedId;
}
inline spv::Op getCastOp( ast::type::Kind src, ast::type::Kind dst )
{
spv::Op result = spv::OpNop;
if ( isDoubleType( src ) )
{
if ( isFloatType( dst ) || isHalfType( dst ) )
{
result = spv::OpFConvert;
}
else if ( isSignedIntType( dst ) )
{
result = spv::OpConvertFToS;
}
else if ( isUnsignedIntType( dst ) )
{
result = spv::OpConvertFToU;
}
else
{
assert( false && "Unsupported cast expression" );
}
}
else if ( isFloatType( src ) )
{
if ( isDoubleType( dst ) || isHalfType( dst ) )
{
result = spv::OpFConvert;
}
else if ( isSignedIntType( dst ) )
{
result = spv::OpConvertFToS;
}
else if ( isUnsignedIntType( dst ) )
{
result = spv::OpConvertFToU;
}
else
{
assert( false && "Unsupported cast expression" );
}
}
else if ( isHalfType( src ) )
{
if ( isDoubleType( dst ) || isFloatType( dst ) )
{
result = spv::OpFConvert;
}
else if ( isSignedIntType( dst ) )
{
result = spv::OpConvertFToS;
}
else if ( isUnsignedIntType( dst ) )
{
result = spv::OpConvertFToU;
}
else
{
assert( false && "Unsupported cast expression" );
}
}
else if ( isSignedIntType( src ) )
{
if ( isDoubleType( dst )
|| isFloatType( dst ) )
{
result = spv::OpConvertSToF;
}
else if ( isSignedIntType( dst ) )
{
}
else if ( isUnsignedIntType( dst ) )
{
result = spv::OpBitcast;
}
else
{
assert( false && "Unsupported cast expression" );
}
}
else if ( isUnsignedIntType( src ) )
{
if ( isDoubleType( dst )
|| isFloatType( dst ) )
{
result = spv::OpConvertUToF;
}
else if ( isSignedIntType( dst ) )
{
result = spv::OpBitcast;
}
else if ( isUnsignedIntType( dst ) )
{
}
else
{
assert( false && "Unsupported cast expression" );
}
}
else
{
assert( false && "Unsupported cast expression" );
}
return result;
}
}
spv::StorageClass getStorageClass( ast::var::VariablePtr var )
{
var = getOutermost( var );
spv::StorageClass result = spv::StorageClassFunction;
if ( var->isLocale() )
{
result = spv::StorageClassFunction;
}
if ( var->isUniform() )
{
if ( var->isConstant() )
{
result = spv::StorageClassUniformConstant;
}
else
{
result = spv::StorageClassUniform;
}
}
else if ( var->isBuiltin() )
{
if ( var->isShaderInput() )
{
result = spv::StorageClassInput;
}
else if ( var->isShaderOutput() )
{
result = spv::StorageClassOutput;
}
else
{
assert( false && "Unsupported built-in variable storage." );
}
}
else if ( var->isShaderInput() )
{
result = spv::StorageClassInput;
}
else if ( var->isShaderOutput() )
{
result = spv::StorageClassOutput;
}
else if ( var->isShaderConstant() )
{
result = spv::StorageClassInput;
}
else if ( var->isSpecialisationConstant() )
{
result = spv::StorageClassInput;
}
else if ( var->isPushConstant() )
{
result = spv::StorageClassPushConstant;
}
else if ( var->isStatic() && var->isConstant() )
{
result = spv::StorageClassPrivate;
}
return result;
}
spv::Id ExprVisitor::submit( ast::expr::Expr * expr
, Block & currentBlock
, Module & module
, bool loadVariable )
{
bool allLiterals{ false };
LoadedVariableArray loadedVariables;
return submit( expr
, currentBlock
, module
, allLiterals
, loadVariable
, loadedVariables );
}
spv::Id ExprVisitor::submit( ast::expr::Expr * expr
, Block & currentBlock
, Module & module
, bool loadVariable
, LoadedVariableArray & loadedVariables )
{
bool allLiterals{ false };
return submit( expr
, currentBlock
, module
, allLiterals
, loadVariable
, loadedVariables );
}
spv::Id ExprVisitor::submit( ast::expr::Expr * expr
, Block & currentBlock
, Module & module
, spv::Id initialiser
, bool hasFuncInit
, LoadedVariableArray & loadedVariables )
{
bool allLiterals{ false };
return submit( expr
, currentBlock
, module
, allLiterals
, initialiser
, hasFuncInit
, loadedVariables );
}
spv::Id ExprVisitor::submit( ast::expr::Expr * expr
, Block & currentBlock
, Module & module
, bool & allLiterals
, bool loadVariable )
{
LoadedVariableArray loadedVariables;
return submit( expr
, currentBlock
, module
, allLiterals
, loadVariable
, loadedVariables );
}
spv::Id ExprVisitor::submit( ast::expr::Expr * expr
, Block & currentBlock
, Module & module
, bool & allLiterals
, bool loadVariable
, LoadedVariableArray & loadedVariables )
{
spv::Id result{ 0u };
ExprVisitor vis{ result
, currentBlock
, module
, allLiterals
, loadVariable
, loadedVariables };
expr->accept( &vis );
return result;
}
spv::Id ExprVisitor::submit( ast::expr::Expr * expr
, Block & currentBlock
, Module & module
, bool & allLiterals
, spv::Id initialiser
, bool hasFuncInit
, LoadedVariableArray & loadedVariables )
{
spv::Id result{ 0u };
ExprVisitor vis{ result
, currentBlock
, module
, allLiterals
, initialiser
, hasFuncInit
, loadedVariables };
expr->accept( &vis );
return result;
}
ExprVisitor::ExprVisitor( spv::Id & result
, Block & currentBlock
, Module & module
, bool & allLiterals
, bool loadVariable
, LoadedVariableArray & loadedVariables )
: m_result{ result }
, m_currentBlock{ currentBlock }
, m_module{ module }
, m_allLiterals{ allLiterals }
, m_loadVariable{ loadVariable }
, m_initialiser{ 0u }
, m_hasFuncInit{ false }
, m_loadedVariables{ loadedVariables }
{
}
ExprVisitor::ExprVisitor( spv::Id & result
, Block & currentBlock
, Module & module
, bool & allLiterals
, spv::Id initialiser
, bool hasFuncInit
, LoadedVariableArray & loadedVariables )
: m_result{ result }
, m_currentBlock{ currentBlock }
, m_module{ module }
, m_allLiterals{ allLiterals }
, m_loadVariable{ false }
, m_initialiser{ initialiser }
, m_hasFuncInit{ hasFuncInit }
, m_loadedVariables{ loadedVariables }
{
}
spv::Id ExprVisitor::doSubmit( ast::expr::Expr * expr )
{
return submit( expr, m_currentBlock, m_module, m_loadVariable, m_loadedVariables );
}
spv::Id ExprVisitor::doSubmit( ast::expr::Expr * expr
, LoadedVariableArray & loadedVariables )
{
return submit( expr, m_currentBlock, m_module, m_loadVariable, loadedVariables );
}
spv::Id ExprVisitor::doSubmit( ast::expr::Expr * expr
, bool loadVariable )
{
return submit( expr, m_currentBlock, m_module, loadVariable, m_loadedVariables );
}
spv::Id ExprVisitor::doSubmit( ast::expr::Expr * expr
, spv::Id initialiser
, bool hasFuncInit )
{
return submit( expr, m_currentBlock, m_module, initialiser, hasFuncInit, m_loadedVariables );
}
spv::Id ExprVisitor::doSubmit( ast::expr::Expr * expr
, bool loadVariable
, LoadedVariableArray & loadedVariables )
{
return submit( expr, m_currentBlock, m_module, loadVariable, loadedVariables );
}
spv::Id ExprVisitor::doSubmit( ast::expr::Expr * expr
, bool & allLiterals
, bool loadVariable )
{
return submit( expr, m_currentBlock, m_module, allLiterals, loadVariable, m_loadedVariables );
}
spv::Id ExprVisitor::doSubmit( ast::expr::Expr * expr
, bool & allLiterals
, bool loadVariable
, LoadedVariableArray & loadedVariables )
{
return submit( expr, m_currentBlock, m_module, allLiterals, loadVariable, loadedVariables );
}
void ExprVisitor::visitAssignmentExpr( ast::expr::Assign * expr )
{
m_allLiterals = false;
if ( expr->getLHS()->getKind() == ast::expr::Kind::eSwizzle )
{
// For LHS swizzle, the variable must first be loaded,
// then it must be shuffled with the RHS, to compute the final result.
auto & lhsSwizzle = static_cast< ast::expr::Swizzle const & >( *expr->getLHS() );
auto lhsSwizzleKind = lhsSwizzle.getSwizzle();
// Process the RHS first, asking for the needed variables to be loaded.
auto rhsId = doSubmit( expr->getRHS(), true, m_loadedVariables );
auto lhsOuter = lhsSwizzle.getOuterExpr();
assert( lhsOuter->getKind() == ast::expr::Kind::eIdentifier
|| isAccessChain( lhsOuter ) );
if ( lhsSwizzleKind.isOneComponent() )
{
// One component swizzles must be processed separately:
// - Create an access chain to the selected component.
// No load to retrieve the variable ID.
auto lhsId = getVariableIdNoLoad( lhsOuter );
// Register component selection as a literal.
auto componentId = m_module.registerLiteral( lhsSwizzleKind.toIndex() );
// Register pointer type.
auto typeId = m_module.registerType( lhsSwizzle.getType() );
// Retrieve outermost identifier, to be able to retrieve its variable's storage class.
auto lhsOutermost = ast::getOutermostExpr( lhsOuter );
assert( lhsOutermost->getKind() == ast::expr::Kind::eIdentifier );
auto pointerTypeId = m_module.registerPointerType( typeId
, getStorageClass( static_cast< ast::expr::Identifier const & >( *lhsOutermost ).getVariable() ) );
// Create the access chain.
auto intermediateId = m_module.getIntermediateResult();
m_currentBlock.instructions.emplace_back( makeInstruction< AccessChainInstruction >( pointerTypeId
, intermediateId
, IdList{ lhsId, componentId } ) );
// - Store the RHS into this access chain.
m_currentBlock.instructions.emplace_back( makeInstruction< StoreInstruction >( intermediateId, rhsId ) );
m_result = intermediateId;
}
else
{
// - No load to retrieve the variable ID.
auto lhsId = getVariableIdNoLoad( lhsOuter );
// - Load the variable manually.
auto loadedLhsId = loadVariable( lhsId
, lhsOuter->getType() );
// - The resulting shuffle indices will contain the RHS values for wanted LHS components,
// and LHS values for the remaining ones.
auto typeId = m_module.registerType( lhsOuter->getType() );
auto intermediateId = m_module.getIntermediateResult();
IdList shuffle;
shuffle.emplace_back( loadedLhsId );
shuffle.emplace_back( rhsId );
ast::expr::SwizzleKind rhsSwizzleKind;
if ( expr->getRHS()->getKind() == ast::expr::Kind::eSwizzle
&& static_cast< ast::expr::Swizzle const & >( *expr->getRHS() ).getOuterExpr()->getKind() != ast::expr::Kind::eIntrinsicCall
&& static_cast< ast::expr::Swizzle const & >( *expr->getRHS() ).getOuterExpr()->getKind() != ast::expr::Kind::eTextureAccessCall
&& static_cast< ast::expr::Swizzle const & >( *expr->getRHS() ).getOuterExpr()->getKind() != ast::expr::Kind::eImageAccessCall )
{
rhsSwizzleKind = static_cast< ast::expr::Swizzle const & >( *expr->getRHS() ).getSwizzle();
}
else
{
auto rhsCount = getComponentCount( expr->getRHS()->getType()->getKind() );
assert( rhsCount >= 2u && rhsCount <= 4u );
switch ( rhsCount )
{
case 2u:
rhsSwizzleKind = ast::expr::SwizzleKind::e01;
break;
case 3u:
rhsSwizzleKind = ast::expr::SwizzleKind::e012;
break;
default:
rhsSwizzleKind = ast::expr::SwizzleKind::e0123;
break;
}
}
auto swizzleComponents = getSwizzleComponents( lhsSwizzleKind
, rhsSwizzleKind
, getComponentCount( lhsOuter->getType()->getKind() ) );
shuffle.insert( shuffle.end()
, swizzleComponents.begin()
, swizzleComponents.end() );
m_currentBlock.instructions.emplace_back( makeInstruction< VectorShuffleInstruction >( typeId
, intermediateId
, shuffle ) );
m_currentBlock.instructions.emplace_back( makeInstruction< StoreInstruction >( lhsId, intermediateId ) );
m_result = lhsId;
}
}
else
{
// No load to retrieve the variable ID.
auto lhsId = getVariableIdNoLoad( expr->getLHS() );
// Ask for the needed variables to be loaded.
auto rhsId = doSubmit( expr->getRHS(), true, m_loadedVariables );
m_currentBlock.instructions.emplace_back( makeInstruction< StoreInstruction >( lhsId, rhsId ) );
m_result = lhsId;
}
}
void ExprVisitor::visitOpAssignmentExpr( ast::expr::Assign * expr )
{
m_allLiterals = false;
auto typeId = m_module.registerType( expr->getType() );
// No load to retrieve the variable ID.
auto lhsId = getVariableIdNoLoad( expr->getLHS() );
// Load the variable manually.
auto loadedLhsId = loadVariable( lhsId
, expr->getType() );
// Ask for the needed variables to be loaded.
auto rhsId = doSubmit( expr->getRHS()
, true );
auto intermediateId = writeBinOpExpr( expr->getKind()
, expr->getLHS()->getType()->getKind()
, expr->getRHS()->getType()->getKind()
, typeId
, loadedLhsId
, rhsId
, expr->getLHS()->isSpecialisationConstant() );
m_currentBlock.instructions.emplace_back( makeInstruction< StoreInstruction >( lhsId, intermediateId ) );
m_module.putIntermediateResult( intermediateId );
m_module.putIntermediateResult( loadedLhsId );
m_result = lhsId;
}
void ExprVisitor::visitUnaryExpr( ast::expr::Unary * expr )
{
m_allLiterals = false;
auto operandId = doSubmit( expr->getOperand() );
auto typeId = m_module.registerType( expr->getType() );
m_result = m_module.getIntermediateResult();
if ( expr->isSpecialisationConstant() )
{
m_currentBlock.instructions.emplace_back( makeInstruction< SpecConstantOpInstruction >( typeId
, m_result
, makeOperands( spv::Id( getUnOpCode( expr->getKind(), expr->getType()->getKind() ) )
, operandId ) ) );
}
else
{
m_currentBlock.instructions.emplace_back( makeUnInstruction( typeId
, m_result
, expr->getKind()
, expr->getType()->getKind()
, operandId ) );
}
}
void ExprVisitor::visitBinaryExpr( ast::expr::Binary * expr )
{
m_allLiterals = false;
auto lhsId = doSubmit( expr->getLHS() );
auto loadedLhsId = lhsId;
auto rhsId = doSubmit( expr->getRHS() );
auto loadedRhsId = rhsId;
auto typeId = m_module.registerType( expr->getType() );
m_result = writeBinOpExpr( expr->getKind()
, expr->getLHS()->getType()->getKind()
, expr->getRHS()->getType()->getKind()
, typeId
, loadedLhsId
, loadedRhsId
, expr->isSpecialisationConstant() );
}
void ExprVisitor::visitCastExpr( ast::expr::Cast * expr )
{
m_allLiterals = false;
auto operandId = doSubmit( expr->getOperand() );
auto dstTypeId = m_module.registerType( expr->getType() );
auto op = getCastOp( expr->getOperand()->getType()->getKind()
, expr->getType()->getKind() );
if ( op == spv::OpNop )
{
m_result = operandId;
}
else
{
m_result = m_module.getIntermediateResult();
if ( expr->isSpecialisationConstant() )
{
m_currentBlock.instructions.emplace_back( makeInstruction< SpecConstantOpInstruction >( dstTypeId
, m_result
, makeOperands( spv::Id( op )
, operandId ) ) );
}
else
{
m_currentBlock.instructions.emplace_back( makeCastInstruction( dstTypeId
, m_result
, op
, operandId ) );
}
}
}
void ExprVisitor::visitPreDecrementExpr( ast::expr::PreDecrement * expr )
{
m_allLiterals = false;
auto literal = m_module.registerLiteral( 1 );
auto operandId = doSubmit( expr->getOperand(), true );
auto typeId = m_module.registerType( expr->getType() );
m_result = m_module.getIntermediateResult();
m_currentBlock.instructions.emplace_back( makeBinInstruction( typeId
, m_result
, ast::expr::Kind::eMinus
, expr->getOperand()->getType()->getKind()
, ast::type::Kind::eInt
, operandId
, literal ) );
operandId = m_module.getNonIntermediate( operandId );
m_currentBlock.instructions.emplace_back( makeInstruction< StoreInstruction >( operandId, m_result ) );
}
void ExprVisitor::visitPreIncrementExpr( ast::expr::PreIncrement * expr )
{
m_allLiterals = false;
auto literal = m_module.registerLiteral( 1 );
auto operandId = doSubmit( expr->getOperand(), true );
auto typeId = m_module.registerType( expr->getType() );
m_result = m_module.getIntermediateResult();
m_currentBlock.instructions.emplace_back( makeBinInstruction( typeId
, m_result
, ast::expr::Kind::eAdd
, expr->getOperand()->getType()->getKind()
, ast::type::Kind::eInt
, operandId
, literal ) );
operandId = m_module.getNonIntermediate( operandId );
m_currentBlock.instructions.emplace_back( makeInstruction< StoreInstruction >( operandId, m_result ) );
}
void ExprVisitor::visitPostDecrementExpr( ast::expr::PostDecrement * expr )
{
m_allLiterals = false;
auto literal1 = m_module.registerLiteral( 1 );
auto literal0 = m_module.registerLiteral( 0 );
// No load to retrieve the variable ID.
auto originId = getVariableIdNoLoad( expr->getOperand() );
// Load the variable manually.
auto operandId = loadVariable( originId
, expr->getType() );
auto typeId = m_module.registerType( expr->getType() );
m_result = m_module.getIntermediateResult();
m_currentBlock.instructions.emplace_back( makeBinInstruction( typeId
, m_result
, ast::expr::Kind::eAdd
, expr->getOperand()->getType()->getKind()
, ast::type::Kind::eInt
, operandId
, literal0 ) );
auto operand2 = m_module.getIntermediateResult();
m_currentBlock.instructions.emplace_back( makeBinInstruction( typeId
, operand2
, ast::expr::Kind::eMinus
, expr->getOperand()->getType()->getKind()
, ast::type::Kind::eInt
, operandId
, literal1 ) );
m_currentBlock.instructions.emplace_back( makeInstruction< StoreInstruction >( originId, operand2 ) );
}
void ExprVisitor::visitPostIncrementExpr( ast::expr::PostIncrement * expr )
{
m_allLiterals = false;
auto literal1 = m_module.registerLiteral( 1 );
auto literal0 = m_module.registerLiteral( 0 );
// No load to retrieve the variable ID.
auto originId = getVariableIdNoLoad( expr->getOperand() );
// Load the variable manually.
auto operandId = loadVariable( originId
, expr->getType() );
auto typeId = m_module.registerType( expr->getType() );
m_result = m_module.getIntermediateResult();
m_currentBlock.instructions.emplace_back( makeBinInstruction( typeId
, m_result
, ast::expr::Kind::eAdd
, expr->getOperand()->getType()->getKind()
, ast::type::Kind::eInt
, operandId
, literal0 ) );
auto operand2 = m_module.getIntermediateResult();
m_currentBlock.instructions.emplace_back( makeBinInstruction( typeId
, operand2
, ast::expr::Kind::eAdd
, expr->getOperand()->getType()->getKind()
, ast::type::Kind::eInt
, operandId
, literal1 ) );
m_currentBlock.instructions.emplace_back( makeInstruction< StoreInstruction >( originId, operand2 ) );
}
void ExprVisitor::visitUnaryPlusExpr( ast::expr::UnaryPlus * expr )
{
m_result = doSubmit( expr );
}
void ExprVisitor::visitAddAssignExpr( ast::expr::AddAssign * expr )
{
visitOpAssignmentExpr( expr );
}
void ExprVisitor::visitAndAssignExpr( ast::expr::AndAssign * expr )
{
visitOpAssignmentExpr( expr );
}
void ExprVisitor::visitAssignExpr( ast::expr::Assign * expr )
{
visitAssignmentExpr( expr );
}
void ExprVisitor::visitDivideAssignExpr( ast::expr::DivideAssign * expr )
{
visitOpAssignmentExpr( expr );
}
void ExprVisitor::visitLShiftAssignExpr( ast::expr::LShiftAssign * expr )
{
visitOpAssignmentExpr( expr );
}
void ExprVisitor::visitMinusAssignExpr( ast::expr::MinusAssign * expr )
{
visitOpAssignmentExpr( expr );
}
void ExprVisitor::visitModuloAssignExpr( ast::expr::ModuloAssign * expr )
{
visitOpAssignmentExpr( expr );
}
void ExprVisitor::visitOrAssignExpr( ast::expr::OrAssign * expr )
{
visitOpAssignmentExpr( expr );
}
void ExprVisitor::visitRShiftAssignExpr( ast::expr::RShiftAssign * expr )
{
visitOpAssignmentExpr( expr );
}
void ExprVisitor::visitTimesAssignExpr( ast::expr::TimesAssign * expr )
{
visitOpAssignmentExpr( expr );
}
void ExprVisitor::visitXorAssignExpr( ast::expr::XorAssign * expr )
{
visitOpAssignmentExpr( expr );
}
void ExprVisitor::visitAggrInitExpr( ast::expr::AggrInit * expr )
{
auto typeId = m_module.registerType( expr->getType() );
IdList initialisers;
bool allLiterals = true;
bool hasFuncInit = false;
for ( auto & init : expr->getInitialisers() )
{
initialisers.push_back( doSubmit( init.get(), allLiterals, true ) );
hasFuncInit = hasFuncInit || HasFnCall::submit( init.get() );
}
spv::Id init;
if ( allLiterals )
{
init = m_module.registerLiteral( initialisers, expr->getType() );
}
else
{
init = m_module.getIntermediateResult();
m_currentBlock.instructions.emplace_back( makeInstruction< CompositeConstructInstruction >( typeId
, init
, initialisers ) );
}
if ( expr->getIdentifier() )
{
initialiseVariable( init
, allLiterals
, hasFuncInit
, expr->getIdentifier()->getVariable()
, expr->getType() );
}
else
{
assert( allLiterals );
m_result = init;
}
m_allLiterals = false;
}
void ExprVisitor::visitArrayAccessExpr( ast::expr::ArrayAccess * expr )
{
m_allLiterals = false;
m_result = makeAccessChain( expr, m_module, m_currentBlock, m_loadedVariables );
auto typeKind = expr->getType()->getKind();
if ( m_loadVariable
&& !isImageType( typeKind )
&& !isSampledImageType( typeKind )
&& !isSamplerType( typeKind ) )
{
auto result = loadVariable( m_result
, expr->getType() );
m_module.putIntermediateResult( m_result );
m_result = result;
}
}
void ExprVisitor::visitMbrSelectExpr( ast::expr::MbrSelect * expr )
{
m_allLiterals = false;
m_result = makeAccessChain( expr, m_module, m_currentBlock, m_loadedVariables );
if ( m_loadVariable )
{
auto result = loadVariable( m_result
, expr->getType() );
m_module.putIntermediateResult( m_result );
m_result = result;
}
}
void ExprVisitor::visitCompositeConstructExpr( ast::expr::CompositeConstruct * expr )
{
IdList params;
bool allLiterals = true;
auto paramsCount = 0u;
for ( auto & arg : expr->getArgList() )
{
bool allLitsInit = true;
auto id = doSubmit( arg.get(), allLitsInit, m_loadVariable );
params.push_back( id );
allLiterals = allLiterals && allLitsInit;
paramsCount += ast::type::getComponentCount( arg->getType()->getKind() );
}
auto retCount = ast::type::getComponentCount( expr->getType()->getKind() )
* ast::type::getComponentCount( ast::type::getComponentType( expr->getType()->getKind() ) );
auto typeId = m_module.registerType( expr->getType() );
if ( paramsCount == 1u && retCount != 1u )
{
params.resize( retCount, params.back() );
paramsCount = retCount;
}
if ( allLiterals )
{
assert( paramsCount == retCount );
m_result = m_module.registerLiteral( params, expr->getType() );
}
else
{
m_result = m_module.getIntermediateResult();
m_currentBlock.instructions.emplace_back( makeInstruction< CompositeConstructInstruction >( typeId
, m_result
, params ) );
}
m_allLiterals = m_allLiterals && allLiterals;
}
void ExprVisitor::visitFnCallExpr( ast::expr::FnCall * expr )
{
IdList params;
bool allLiterals = true;
auto type = expr->getFn()->getType();
assert( type->getKind() == ast::type::Kind::eFunction );
auto fnType = std::static_pointer_cast< ast::type::Function >( type );
assert( expr->getArgList().size() == fnType->size() );
auto it = fnType->begin();
struct OutputParam
{
spv::Id src;
spv::Id dst;
ast::type::TypePtr type;
};
std::vector< OutputParam > outputParams;
for ( auto & arg : expr->getArgList() )
{
// Function parameters are pointers, hence the variables must not be loaded.
auto id = getVariableIdNoLoad( arg.get() );
allLiterals = allLiterals
&& ( arg->getKind() == ast::expr::Kind::eLiteral );
auto argTypeKind = arg->getType()->getKind();
auto ident = ast::findIdentifier( arg );
if ( ident
&& getStorageClass( ident->getVariable() ) != spv::StorageClassFunction
&& !isImageType( argTypeKind )
&& !isSampledImageType( argTypeKind )
&& !isSamplerType( argTypeKind ) )
{
// We must have a variable with function storage class.
// Hence we create a temporary variable with this storage class,
// and load the original variable into it.
auto srcId = id;
id = makeFunctionAlias( srcId, arg->getType() );
if ( ( *it )->isOutputParam() )
{
outputParams.emplace_back( OutputParam{ srcId, id, arg->getType() } );
}
}
params.push_back( id );
++it;
}
auto typeId = m_module.registerType( expr->getType() );
auto fnId = doSubmit( expr->getFn() );
params.insert( params.begin(), fnId );
m_result = m_module.getIntermediateResult();
m_currentBlock.instructions.emplace_back( makeInstruction< FunctionCallInstruction >( typeId
, m_result
, params ) );
for ( auto param : outputParams )
{
auto loadedId = m_module.loadVariable( param.dst, param.type, m_currentBlock );
m_currentBlock.instructions.emplace_back( makeInstruction< StoreInstruction >( param.src, loadedId ) );
}
m_allLiterals = m_allLiterals && allLiterals;
}
void ExprVisitor::visitIdentifierExpr( ast::expr::Identifier * expr )
{
m_allLiterals = false;
auto var = expr->getVariable();
if ( var->isMember() )
{
m_result = makeAccessChain( expr
, m_module
, m_currentBlock
, m_loadedVariables );
if ( m_loadVariable )
{
auto result = loadVariable( m_result
, expr->getType() );
m_module.putIntermediateResult( m_result );
m_result = result;
}
}
else
{
initialiseVariable( m_initialiser
, true
, m_hasFuncInit
, var
, expr->getType() );
auto kind = var->getType()->getKind();
if ( m_loadVariable
&& ( var->isLocale()
|| var->isShaderInput()
|| var->isShaderOutput()
|| var->isParam()
|| isSampledImageType( kind )
|| isImageType( kind )
|| isSamplerType( kind ) ) )
{
m_result = loadVariable( m_result
, expr->getType() );
}
}
}
void ExprVisitor::visitImageAccessCallExpr( ast::expr::ImageAccessCall * expr )
{
m_allLiterals = false;
auto isStore = expr->getImageAccess() >= ast::expr::ImageAccess::eImageStore1DF
&& expr->getImageAccess() <= ast::expr::ImageAccess::eImageStore2DMSArrayU;
auto paramType = expr->getArgList()[0]->getType();
assert( paramType->getKind() == ast::type::Kind::eImage );
auto imageVarId = doSubmit( expr->getArgList()[0].get(), false );
auto imageType = std::static_pointer_cast< ast::type::Image >( paramType );
auto intermediateId = loadVariable( imageVarId, imageType );
IdList params;
params.push_back( intermediateId );
for ( auto it = expr->getArgList().begin() + 1u; it != expr->getArgList().end(); ++it )
{
auto & arg = ( *it );
auto id = doSubmit( arg.get() );
params.push_back( id );
}
if ( isStore && imageType->getConfig().isMS )
{
// MS images image store's parameters need a bit reworking
// since in SPIR-V the sample parameter is an optional one
// and as such it has to be at the end.
auto data = params.back();
params.pop_back();
auto sample = params.back();
params.pop_back();
params.push_back( data );
params.push_back( spv::ImageOperandsSampleMask );
params.push_back( sample );
}
IntrinsicConfig config;
getSpirVConfig( expr->getImageAccess(), config );
auto op = getSpirVName( expr->getImageAccess() );
if ( isStore )
{
m_currentBlock.instructions.emplace_back( makeInstruction< ImageStoreInstruction >( params ) );
}
else if ( !config.needsTexelPointer )
{
auto typeId = m_module.registerType( expr->getType() );
m_result = m_module.getIntermediateResult();
m_currentBlock.instructions.emplace_back( makeImageAccessInstruction( typeId
, m_result
, op
, params ) );
}
else
{
IdList texelPointerParams;
uint32_t index = 0u;
texelPointerParams.push_back( imageVarId );
++index;
texelPointerParams.push_back( params[index++] );
if ( imageType->getConfig().isMS )
{
texelPointerParams.push_back( params[index++] );
}
else
{
texelPointerParams.push_back( m_module.registerLiteral( 0u ) );
}
assert( expr->getArgList()[0]->getKind() == ast::expr::Kind::eIdentifier );
auto imgParam = static_cast< ast::expr::Identifier const & >( *expr->getArgList()[0] ).getType();
assert( imgParam->getKind() == ast::type::Kind::eImage );
auto image = std::static_pointer_cast< ast::type::Image >( imgParam );
auto sampledId = m_module.registerType( m_module.getCache().getBasicType( image->getConfig().sampledType ) );
auto pointerTypeId = m_module.registerPointerType( sampledId
, spv::StorageClassImage );
auto pointerId = m_module.getIntermediateResult();
m_currentBlock.instructions.emplace_back( makeInstruction< ImageTexelPointerInstruction >( pointerTypeId
, pointerId
, texelPointerParams ) );
auto scopeId = m_module.registerLiteral( uint32_t( spv::ScopeDevice ) );
IdList accessParams;
accessParams.push_back( pointerId );
accessParams.push_back( scopeId );
if ( op == spv::OpAtomicCompareExchange )
{
auto equalMemorySemanticsId = m_module.registerLiteral( uint32_t( spv::MemorySemanticsImageMemoryMask ) );
auto unequalMemorySemanticsId = m_module.registerLiteral( uint32_t( spv::MemorySemanticsImageMemoryMask ) );
accessParams.push_back( equalMemorySemanticsId );
accessParams.push_back( unequalMemorySemanticsId );
}
else
{
auto memorySemanticsId = m_module.registerLiteral( uint32_t( spv::MemorySemanticsImageMemoryMask ) );
accessParams.push_back( memorySemanticsId );
}
if ( params.size() > index )
{
accessParams.insert( accessParams.end()
, params.begin() + index
, params.end() );
}
auto typeId = m_module.registerType( expr->getType() );
m_result = m_module.getIntermediateResult();
m_currentBlock.instructions.emplace_back( makeImageAccessInstruction( typeId
, m_result
, op
, accessParams ) );
m_module.putIntermediateResult( pointerId );
}
}
void ExprVisitor::visitInitExpr( ast::expr::Init * expr )
{
m_allLiterals = false;
m_module.registerType( expr->getType() );
bool allLiterals = true;
auto init = doSubmit( expr->getInitialiser(), allLiterals, m_loadVariable );
m_info.lvalue = true;
bool hasFuncInit = HasFnCall::submit( expr );
initialiseVariable( init
, allLiterals
, hasFuncInit
, expr->getIdentifier()->getVariable()
, expr->getType() );
}
void ExprVisitor::visitIntrinsicCallExpr( ast::expr::IntrinsicCall * expr )
{
m_allLiterals = false;
IntrinsicConfig config;
getSpirVConfig( expr->getIntrinsic(), config );
auto opCodeId = getSpirVName( expr->getIntrinsic() );
if ( !config.isExtension )
{
auto opCode = spv::Op( opCodeId );
if ( config.isAtomic )
{
handleAtomicIntrinsicCallExpr( opCode, expr );
}
else if ( opCode == spv::OpIAddCarry
|| opCode == spv::OpISubBorrow )
{
handleCarryBorrowIntrinsicCallExpr( opCode, expr );
}
else if ( opCode == spv::OpUMulExtended
|| opCode == spv::OpSMulExtended )
{
handleMulExtendedIntrinsicCallExpr( opCode, expr );
}
else
{
handleOtherIntrinsicCallExpr( opCode, expr );
}
}
else
{
handleExtensionIntrinsicCallExpr( opCodeId, expr );
}
}
void ExprVisitor::visitLiteralExpr( ast::expr::Literal * expr )
{
switch ( expr->getLiteralType() )
{
case ast::expr::LiteralType::eBool:
m_result = m_module.registerLiteral( expr->getValue< ast::expr::LiteralType::eBool >() );
break;
case ast::expr::LiteralType::eInt:
m_result = m_module.registerLiteral( expr->getValue< ast::expr::LiteralType::eInt >() );
break;
case ast::expr::LiteralType::eUInt:
m_result = m_module.registerLiteral( expr->getValue< ast::expr::LiteralType::eUInt >() );
break;
case ast::expr::LiteralType::eFloat:
m_result = m_module.registerLiteral( expr->getValue< ast::expr::LiteralType::eFloat >() );
break;
case ast::expr::LiteralType::eDouble:
m_result = m_module.registerLiteral( expr->getValue< ast::expr::LiteralType::eDouble >() );
break;
default:
assert( false && "Unsupported literal type" );
break;
}
}
void ExprVisitor::visitQuestionExpr( ast::expr::Question * expr )
{
m_allLiterals = false;
auto ctrlId = doSubmit( expr->getCtrlExpr() );
auto trueId = doSubmit( expr->getTrueExpr() );
auto falseId = doSubmit( expr->getFalseExpr() );
auto type = m_module.registerType( expr->getType() );
m_result = m_module.getIntermediateResult();
auto branches = makeOperands( ctrlId, trueId, falseId );
if ( expr->getCtrlExpr()->isSpecialisationConstant() )
{
m_currentBlock.instructions.emplace_back( makeInstruction< SpecConstantOpInstruction >( type
, m_result
, makeOperands( spv::Id( spv::OpSelect ), branches ) ) );
}
else
{
m_currentBlock.instructions.emplace_back( makeInstruction< SelectInstruction >( type
, m_result
, branches ) );
}
}
void ExprVisitor::visitSwitchCaseExpr( ast::expr::SwitchCase * expr )
{
m_result = doSubmit( expr->getLabel() );
}
void ExprVisitor::visitSwitchTestExpr( ast::expr::SwitchTest * expr )
{
m_result = doSubmit( expr->getValue() );
}
void ExprVisitor::visitSwizzleExpr( ast::expr::Swizzle * expr )
{
m_allLiterals = false;
if ( expr->getSwizzle().isOneComponent()
&& expr->getOuterExpr()->getKind() == ast::expr::Kind::eIdentifier )
{
m_result = makeAccessChain( expr, m_module, m_currentBlock, m_loadedVariables );
m_result = m_module.loadVariable( m_result, expr->getType(), m_currentBlock );
}
else
{
auto outerId = doSubmit( expr->getOuterExpr() );
auto typeId = m_module.registerType( expr->getType() );
m_result = writeShuffle( m_module
, m_currentBlock
, typeId
, outerId
, expr->getSwizzle() );
}
}
void ExprVisitor::visitTextureAccessCallExpr( ast::expr::TextureAccessCall * expr )
{
m_allLiterals = false;
IdList args;
for ( auto & arg : expr->getArgList() )
{
args.emplace_back( doSubmit( arg.get() ) );
}
auto typeId = m_module.registerType( expr->getType() );
auto kind = expr->getTextureAccess();
IntrinsicConfig config;
getSpirVConfig( kind, config );
auto op = getSpirVName( kind );
// Load the sampled image variable
auto sampledImageType = expr->getArgList()[0]->getType();
assert( sampledImageType->getKind() == ast::type::Kind::eSampledImage );
auto loadedSampleImageId = args[0];
if ( isAccessChain( expr->getArgList()[0].get() ) )
{
// Store the access chain result to a temp var
args[0] = loadVariable( args[0], sampledImageType );
}
if ( config.needsImage )
{
// We need to extract the image from the sampled image, to give it to the final instruction.
auto imageType = std::static_pointer_cast< ast::type::SampledImage >( sampledImageType )->getImageType();
auto imageTypeId = m_module.registerType( imageType );
auto imageId = m_module.getIntermediateResult();
m_currentBlock.instructions.emplace_back( makeInstruction< ImageInstruction >( imageTypeId
, imageId
, loadedSampleImageId ) );
args[0] = imageId;
}
if ( config.imageOperandsIndex )
{
assert( args.size() >= config.imageOperandsIndex );
auto mask = getMask( kind );
args.insert( args.begin() + config.imageOperandsIndex, spv::Id( mask ) );
}
m_result = m_module.getIntermediateResult();
m_currentBlock.instructions.emplace_back( makeTextureAccessInstruction( typeId
, m_result
, op
, args ) );
}
void ExprVisitor::handleCarryBorrowIntrinsicCallExpr( spv::Op opCode, ast::expr::IntrinsicCall * expr )
{
// Arg 1 is lhs.
// Arg 2 is rhs.
// Arg 3 is carry or borrow.
assert( expr->getArgList().size() == 3u );
IdList params;
params.push_back( doSubmit( expr->getArgList()[0].get() ) );
params.push_back( doSubmit( expr->getArgList()[1].get() ) );
auto resultStructTypeId = getUnsignedExtendedResultTypeId( isVectorType( expr->getType()->getKind() )
? getComponentCount( expr->getType()->getKind() )
: 1 );
auto resultCarryBorrowId = m_module.getIntermediateResult();
m_currentBlock.instructions.emplace_back( makeIntrinsicInstruction( resultStructTypeId
, resultCarryBorrowId
, opCode
, params ) );
auto & carryBorrowArg = *expr->getArgList()[2];
auto carryBorrowTypeId = m_module.registerType( carryBorrowArg.getType() );
auto intermediateId = m_module.getIntermediateResult();
m_currentBlock.instructions.emplace_back( makeInstruction< CompositeExtractInstruction >( carryBorrowTypeId
, intermediateId
, IdList{ resultCarryBorrowId, 1u } ) );
auto carryBorrowId = getVariableIdNoLoad( &carryBorrowArg );
m_currentBlock.instructions.emplace_back( makeInstruction< StoreInstruction >( carryBorrowId, intermediateId ) );
auto resultTypeId = m_module.registerType( expr->getType() );
m_result = m_module.getIntermediateResult();
m_currentBlock.instructions.emplace_back( makeInstruction< CompositeExtractInstruction >( resultTypeId
, m_result
, IdList{ resultCarryBorrowId, 0u } ) );
m_module.putIntermediateResult( intermediateId );
}
void ExprVisitor::handleMulExtendedIntrinsicCallExpr( spv::Op opCode, ast::expr::IntrinsicCall * expr )
{
// Arg 1 is lhs.
// Arg 2 is rhs.
// Arg 3 is msb.
// Arg 4 is lsb.
assert( expr->getArgList().size() == 4u );
IdList params;
params.push_back( doSubmit( expr->getArgList()[0].get() ) );
params.push_back( doSubmit( expr->getArgList()[1].get() ) );
spv::Id resultStructTypeId;
auto paramType = expr->getArgList()[0]->getType()->getKind();
if ( isSignedIntType( paramType ) )
{
resultStructTypeId = getSignedExtendedResultTypeId( isVectorType( paramType )
? getComponentCount( paramType )
: 1 );
}
else
{
resultStructTypeId = getUnsignedExtendedResultTypeId( isVectorType( paramType )
? getComponentCount( paramType )
: 1 );
}
auto resultMulExtendedId = m_module.getIntermediateResult();
m_currentBlock.instructions.emplace_back( makeIntrinsicInstruction( resultStructTypeId
, resultMulExtendedId
, opCode
, params ) );
auto & msbArg = *expr->getArgList()[2];
auto msbTypeId = m_module.registerType( msbArg.getType() );
auto intermediateMsb = m_module.getIntermediateResult();
m_currentBlock.instructions.emplace_back( makeInstruction< CompositeExtractInstruction >( msbTypeId
, intermediateMsb
, IdList{ resultMulExtendedId, 1u } ) );
auto msbId = getVariableIdNoLoad( &msbArg );
m_currentBlock.instructions.emplace_back( makeInstruction< StoreInstruction >( msbId, intermediateMsb ) );
auto & lsbArg = *expr->getArgList()[3];
auto lsbTypeId = m_module.registerType( lsbArg.getType() );
auto intermediateLsb = m_module.getIntermediateResult();
m_currentBlock.instructions.emplace_back( makeInstruction< CompositeExtractInstruction >( lsbTypeId
, intermediateLsb
, IdList{ resultMulExtendedId, 0u } ) );
auto lsbId = getVariableIdNoLoad( &lsbArg );
m_currentBlock.instructions.emplace_back( makeInstruction< StoreInstruction >( lsbId, intermediateLsb ) );
m_module.putIntermediateResult( intermediateMsb );
m_module.putIntermediateResult( intermediateLsb );
m_module.putIntermediateResult( resultMulExtendedId );
}
void ExprVisitor::handleAtomicIntrinsicCallExpr( spv::Op opCode, ast::expr::IntrinsicCall * expr )
{
IdList params;
auto save = m_loadVariable;
m_loadVariable = false;
params.push_back( doSubmit( expr->getArgList()[0].get() ) );
m_loadVariable = save;
auto scopeId = m_module.registerLiteral( uint32_t( spv::ScopeDevice ) );
auto memorySemanticsId = m_module.registerLiteral( uint32_t( spv::MemorySemanticsAcquireReleaseMask ) );
params.push_back( scopeId );
params.push_back( memorySemanticsId );
if ( expr->getIntrinsic() == ast::expr::Intrinsic::eAtomicCompSwapI
|| expr->getIntrinsic() == ast::expr::Intrinsic::eAtomicCompSwapU )
{
auto memorySemanticsUnequalId = m_module.registerLiteral( uint32_t( spv::MemorySemanticsAcquireMask ) );
params.push_back( memorySemanticsUnequalId );
}
for ( auto i = 1u; i < expr->getArgList().size(); ++i )
{
params.push_back( doSubmit( expr->getArgList()[i].get() ) );
}
auto typeId = m_module.registerType( expr->getType() );
m_result = m_module.getIntermediateResult();
m_currentBlock.instructions.emplace_back( makeIntrinsicInstruction( typeId
, m_result
, opCode
, params ) );
}
void ExprVisitor::handleExtensionIntrinsicCallExpr( spv::Id opCode, ast::expr::IntrinsicCall * expr )
{
auto intrinsic = expr->getIntrinsic();
IdList params;
if ( ( intrinsic >= ast::expr::Intrinsic::eModf1F
&& intrinsic <= ast::expr::Intrinsic::eModf4D )
|| ( intrinsic >= ast::expr::Intrinsic::eFrexp1F
&& intrinsic <= ast::expr::Intrinsic::eFrexp4D ) )
{
// For modf and frexp intrinsics, second parameter is an output parameter,
// hence we need to pass it as a pointer to the call.
assert( expr->getArgList().size() == 2u );
params.push_back( doSubmit( expr->getArgList()[0].get() ) );
auto save = m_loadVariable;
m_loadVariable = false;
params.push_back( doSubmit( expr->getArgList()[1].get() ) );
m_loadVariable = save;
}
else
{
for ( auto & arg : expr->getArgList() )
{
auto id = doSubmit( arg.get() );
params.push_back( id );
}
}
auto typeId = m_module.registerType( expr->getType() );
params.insert( params.begin(), opCode );
params.insert( params.begin(), 1u );
m_result = m_module.getIntermediateResult();
m_currentBlock.instructions.emplace_back( makeInstruction< ExtInstInstruction >( typeId
, m_result
, params ) );
}
void ExprVisitor::handleOtherIntrinsicCallExpr( spv::Op opCode, ast::expr::IntrinsicCall * expr )
{
IdList params;
for ( auto & arg : expr->getArgList() )
{
auto id = doSubmit( arg.get() );
params.push_back( id );
}
if ( opCode >= spv::OpEmitVertex
&& opCode <= spv::OpEndStreamPrimitive )
{
m_currentBlock.instructions.emplace_back( makeIntrinsicInstruction( opCode
, params ) );
}
else
{
auto typeId = m_module.registerType( expr->getType() );
m_result = m_module.getIntermediateResult();
m_currentBlock.instructions.emplace_back( makeIntrinsicInstruction( typeId
, m_result
, opCode
, params ) );
}
}
spv::Id ExprVisitor::getUnsignedExtendedResultTypeId( uint32_t count )
{
--count;
if ( !m_unsignedExtendedTypes[count] )
{
std::string name = "SDW_ExtendedResultTypeU" + std::to_string( count + 1u );
m_unsignedExtendedTypes[count] = m_module.getCache().getStruct( ast::type::MemoryLayout::eStd430, name );
auto type = count == 3
? m_module.getCache().getVec4U()
: ( count == 2
? m_module.getCache().getVec3U()
: ( count == 1
? m_module.getCache().getVec2U()
: ( m_module.getCache().getUInt() ) ) );
if ( m_unsignedExtendedTypes[count]->empty() )
{
m_unsignedExtendedTypes[count]->declMember( "result", type );
m_unsignedExtendedTypes[count]->declMember( "extended", type );
}
}
return m_module.registerType( m_unsignedExtendedTypes[count] );
}
spv::Id ExprVisitor::getSignedExtendedResultTypeId( uint32_t count )
{
--count;
if ( !m_signedExtendedTypes[count] )
{
std::string name = "SDW_ExtendedResultTypeS" + std::to_string( count + 1u );
m_signedExtendedTypes[count] = m_module.getCache().getStruct( ast::type::MemoryLayout::eStd430, name );
auto type = count == 3
? m_module.getCache().getVec4I()
: ( count == 2
? m_module.getCache().getVec3I()
: ( count == 1
? m_module.getCache().getVec2I()
: ( m_module.getCache().getInt() ) ) );
if ( m_signedExtendedTypes[count]->empty() )
{
m_signedExtendedTypes[count]->declMember( "result", type );
m_signedExtendedTypes[count]->declMember( "extended", type );
}
}
return m_module.registerType( m_signedExtendedTypes[count] );
}
spv::Id ExprVisitor::getVariableIdNoLoad( ast::expr::Expr * expr )
{
spv::Id result;
if ( isAccessChain( expr ) )
{
auto save = m_loadVariable;
m_loadVariable = false;
result = doSubmit( expr );
m_loadVariable = save;
}
else
{
auto ident = ast::findIdentifier( expr );
if ( ident )
{
auto var = ident->getVariable();
if ( var->isSpecialisationConstant()
|| var->isConstant()
|| var->isUniform()
|| var->isInputParam()
|| var->isPushConstant()
|| var->isShaderInput() )
{
m_info.lvalue = false;
m_info.rvalue = true;
}
result = m_module.registerVariable( adaptName( var->getName() )
, getStorageClass( var )
, expr->getType()
, m_info ).id;
}
else
{
result = doSubmit( expr );
}
}
return result;
}
spv::Id ExprVisitor::writeBinOpExpr( ast::expr::Kind exprKind
, ast::type::Kind lhsTypeKind
, ast::type::Kind rhsTypeKind
, spv::Id typeId
, spv::Id lhsId
, spv::Id rhsId
, bool isLhsSpecConstant )
{
auto result = m_module.getIntermediateResult();
if ( isLhsSpecConstant )
{
m_currentBlock.instructions.emplace_back( makeInstruction< SpecConstantOpInstruction >( typeId
, result
, makeBinOpOperands( exprKind
, lhsTypeKind
, rhsTypeKind
, lhsId
, rhsId ) ) );
}
else
{
m_currentBlock.instructions.emplace_back( makeBinInstruction( typeId
, result
, exprKind
, lhsTypeKind
, rhsTypeKind
, lhsId
, rhsId ) );
}
return result;
}
spv::Id ExprVisitor::loadVariable( spv::Id varId
, ast::type::TypePtr type )
{
return spirv::loadVariable( varId
, type
, m_module
, m_currentBlock
, m_loadedVariables );
}
spv::Id ExprVisitor::makeFunctionAlias( spv::Id source
, ast::type::TypePtr type )
{
VariableInfo info;
info.rvalue = true;
auto result = m_module.registerVariable( "functmp" + std::to_string( m_aliasId++ )
, spv::StorageClassFunction
, type
, info ).id;
m_currentBlock.instructions.emplace_back( makeInstruction< StoreInstruction >( result, source ) );
return result;
}
void ExprVisitor::initialiseVariable( spv::Id init
, bool allLiterals
, bool isFuncInit
, ast::var::VariablePtr var
, ast::type::TypePtr type )
{
spv::StorageClass storageClass{ getStorageClass( var ) };
if ( allLiterals
&& !var->isLoopVar()
&& !isFuncInit )
{
m_result = m_module.registerVariable( adaptName( var->getName() )
, storageClass
, type
, m_info
, init ).id;
}
else
{
m_result = m_module.registerVariable( adaptName( var->getName() )
, storageClass
, type
, m_info ).id;
if ( init )
{
m_currentBlock.instructions.emplace_back( makeInstruction< StoreInstruction >( m_result, init ) );
}
}
}
}
| 28.091257 | 133 | 0.671601 | [
"vector"
] |
174e8eb59bb28530732a8ba37d7e5bbd233ad5bc | 1,095 | cpp | C++ | lib/IsenPython/PyOutput.cpp | thfabian/Isen | c03d8e3f4590f4208ce9f4d9141169ca6133cac3 | [
"MIT"
] | 1 | 2016-07-26T17:43:44.000Z | 2016-07-26T17:43:44.000Z | lib/IsenPython/PyOutput.cpp | thfabian/Isen | c03d8e3f4590f4208ce9f4d9141169ca6133cac3 | [
"MIT"
] | null | null | null | lib/IsenPython/PyOutput.cpp | thfabian/Isen | c03d8e3f4590f4208ce9f4d9141169ca6133cac3 | [
"MIT"
] | null | null | null | /**
* _________ _______ __
* / _/ ___// ____/ | / /
* / / \__ \/ __/ / |/ /
* _/ / ___/ / /___/ /| /
* /___//____/_____/_/ |_/
*
* Isentropic model - ETH Zurich
* Copyright (C) 2016 Fabian Thuering (thfabian@student.ethz.ch)
*
* This file is distributed under the MIT Open Source License. See LICENSE.TXT for details.
*/
#include <Isen/Python/PyOutput.h>
ISEN_NAMESPACE_BEGIN
PyOutput::PyOutput(const char* file)
{
if(file)
read(file);
}
PyNameList PyOutput::getNameList() const
{
if(!output_)
throw IsenException("Output: not initialized");
return PyNameList(namelist_);
}
void PyOutput::set(std::shared_ptr<Output> output) noexcept
{
output_ = output;
namelist_ = std::make_shared<NameList>(*output_->getNameList());
}
void PyOutput::read(const char* file)
{
output_ = std::make_shared<Output>();
output_->read(std::string(file));
namelist_ = std::make_shared<NameList>(*output_->getNameList());
}
ISEN_NAMESPACE_END
| 24.333333 | 92 | 0.591781 | [
"model"
] |
175b5e86ffce7e8d8345dbd4414b281357dfb3aa | 16,655 | cpp | C++ | src/core/impl/comp_node/mem_alloc/impl.cpp | Olalaye/MegEngine | 695d24f24517536e6544b07936d189dbc031bbce | [
"Apache-2.0"
] | 1 | 2022-03-21T03:13:45.000Z | 2022-03-21T03:13:45.000Z | src/core/impl/comp_node/mem_alloc/impl.cpp | Olalaye/MegEngine | 695d24f24517536e6544b07936d189dbc031bbce | [
"Apache-2.0"
] | null | null | null | src/core/impl/comp_node/mem_alloc/impl.cpp | Olalaye/MegEngine | 695d24f24517536e6544b07936d189dbc031bbce | [
"Apache-2.0"
] | null | null | null | /**
* \file src/core/impl/comp_node/mem_alloc/impl.cpp
* MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
*
* Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
#include "megbrain_build_config.h"
#include "./impl.h"
#include "megbrain/utils/arith_helper.h"
#include <algorithm>
using namespace mgb;
using namespace mem_alloc;
/* ===================== MemAllocImplHelper ===================== */
#if !MGB_BUILD_SLIM_SERVING
std::pair<size_t, size_t> MemAllocImplHelper::get_free_left_and_right(
size_t begin_ptr, size_t end_ptr) {
MGB_LOCK_GUARD(m_mutex);
auto iter = m_free_blk_addr.lower_bound(begin_ptr);
size_t left_free = 0, right_free = 0;
if (iter != m_free_blk_addr.begin()) {
auto prev = iter;
prev--;
if (prev->first + prev->second.size == begin_ptr) {
left_free = prev->second.size;
}
}
if (iter != m_free_blk_addr.end()) {
if (iter->first == end_ptr) {
right_free = iter->second.size;
}
}
return {left_free, right_free};
}
size_t MemAllocImplHelper::get_max_block_size_available_unsafe() {
if (!m_free_blk_size.size()) {
return 0;
} else {
return m_free_blk_size.rbegin()->first.size;
}
}
size_t MemAllocImplHelper::get_max_block_size_available() {
MGB_LOCK_GUARD(m_mutex);
return get_max_block_size_available_unsafe();
}
#endif
MemAllocImplHelper::MemAddr MemAllocImplHelper::do_alloc(
size_t size, bool allow_from_parent, bool log_stat_on_error) {
mgb_assert(size);
#if !__DEPLOY_ON_XP_SP2__
m_mutex.lock();
#endif
auto iter = m_free_blk_size.lower_bound(FreeBlock{MemAddr{0, 0}, size});
if (iter == m_free_blk_size.end()) {
#if !__DEPLOY_ON_XP_SP2__
m_mutex.unlock();
#endif
if (!allow_from_parent) {
if (log_stat_on_error) {
print_memory_state();
}
mgb_throw(
MemAllocError,
"out of memory while requesting %zu bytes; you can try "
"setting MGB_CUDA_RESERVE_MEMORY to reserve all memory. "
"If there are dynamic variables, you can also try enabling "
"graph option `enable_grad_var_static_reshape` so "
"some gradient variables can be statically allocated",
size);
}
return alloc_from_parent(size);
}
size_t remain = iter->first.size - size;
auto alloc_addr = iter->first.addr;
m_free_blk_addr.erase(iter->second.aiter);
m_free_blk_size.erase(iter);
if (remain)
insert_free_unsafe({alloc_addr + size, remain});
#if !__DEPLOY_ON_XP_SP2__
m_mutex.unlock();
#endif
return alloc_addr;
}
void MemAllocImplHelper::merge_free_unsafe(FreeBlock block) {
auto iter = m_free_blk_addr.lower_bound(block.addr.addr);
// merge with previous
if (!block.addr.is_head && iter != m_free_blk_addr.begin()) {
auto iprev = iter;
--iprev;
if (iprev->first + iprev->second.size == block.addr.addr) {
block.addr.addr = iprev->first;
block.addr.is_head = iprev->second.is_head;
block.size += iprev->second.size;
m_free_blk_size.erase(iprev->second.siter);
m_free_blk_addr.erase(iprev);
}
}
// merge with next
if (iter != m_free_blk_addr.end()) {
mgb_assert(iter->first >= block.end());
if (!iter->second.is_head && block.end() == iter->first) {
block.size += iter->second.size;
m_free_blk_size.erase(iter->second.siter);
m_free_blk_addr.erase(iter);
}
}
insert_free_unsafe(block);
}
void MemAllocImplHelper::insert_free_unsafe(const FreeBlock& block) {
auto rst0 = m_free_blk_size.insert({block, {}});
auto rst1 = m_free_blk_addr.insert({block.addr.addr, {}});
mgb_assert(rst0.second & rst1.second);
rst0.first->second.aiter = rst1.first;
rst1.first->second.is_head = block.addr.is_head;
rst1.first->second.size = block.size;
rst1.first->second.siter = rst0.first;
}
void MemAllocImplHelper::print_memory_state() {
auto stat = get_free_memory();
MGB_MARK_USED_VAR(stat);
mgb_log("device memory allocator stats: %s: "
"used=%zu free={tot:%zu, min_blk:%zu, max_blk:%zu, nr:%zu}",
get_name().c_str(), get_used_memory(), stat.tot, stat.min, stat.max,
stat.nr_blk);
}
FreeMemStat MemAllocImplHelper::get_free_memory_self_unsafe() {
FreeMemStat stat{0, std::numeric_limits<size_t>::max(), 0, 0};
for (auto&& i : m_free_blk_size) {
auto size = i.first.size;
stat.tot += size;
stat.min = std::min(stat.min, size);
stat.max = std::max(stat.max, size);
++stat.nr_blk;
}
return stat;
}
FreeMemStat MemAllocImplHelper::get_free_memory() {
MGB_LOCK_GUARD(m_mutex);
return get_free_memory_self_unsafe();
}
/* ===================== StreamMemAllocImpl ===================== */
std::string StreamMemAllocImpl::get_name() const {
return ssprintf("stream allocator %d@%d", m_stream_id, m_dev_alloc->device());
}
void* StreamMemAllocImpl::alloc(size_t size) {
size = get_aligned_power2(size, m_dev_alloc->alignment());
auto addr = do_alloc(size, true);
MGB_LOCK_GUARD(m_mutex);
m_allocated_blocks[addr.addr_ptr()] = {addr.is_head, size};
return addr.addr_ptr();
}
MemAllocImplHelper::MemAddr StreamMemAllocImpl::alloc_from_parent(size_t size) {
auto addr = m_dev_alloc->alloc(size);
MGB_LOCK_GUARD(m_mutex);
m_allocated_blocks[addr.addr_ptr()] = {addr.is_head, size};
return addr;
}
void StreamMemAllocImpl::free(void* addr) {
MGB_LOCK_GUARD(m_mutex);
auto iter = m_allocated_blocks.find(addr);
mgb_assert(iter != m_allocated_blocks.end(), "releasing bad pointer: %p", addr);
FreeBlock fb{
MemAddr{iter->second.is_head, reinterpret_cast<size_t>(addr)},
iter->second.size};
m_allocated_blocks.erase(iter);
merge_free_unsafe(fb);
}
void StreamMemAllocImpl::get_mem_info(size_t& free, size_t& tot) {
auto&& stat = get_free_memory();
free = stat.tot;
auto used = get_used_memory();
tot = free + used;
}
size_t StreamMemAllocImpl::get_used_memory() {
MGB_LOCK_GUARD(m_mutex);
size_t size = 0;
for (auto&& i : m_allocated_blocks)
size += i.second.size;
return size;
}
FreeMemStat StreamMemAllocImpl::get_free_memory_dev() {
return m_dev_alloc->get_free_memory_dev();
}
/* ===================== DevMemAllocImpl ===================== */
StreamMemAlloc* DevMemAllocImpl::add_stream(StreamKey stream) {
MGB_LOCK_GUARD(m_mutex);
auto&& ptr = m_stream_alloc[stream];
if (!ptr)
ptr.reset(new StreamMemAllocImpl(this, m_stream_alloc.size() - 1));
return ptr.get();
}
MemAllocImplHelper::MemAddr DevMemAllocImpl::alloc(size_t size) {
auto addr = do_alloc(size, true);
m_used_size += size;
if (m_used_size > m_max_used_size) {
m_max_used_size = m_used_size.load();
}
return addr;
}
MemAllocImplHelper::MemAddr DevMemAllocImpl::alloc_from_parent(size_t size) {
// pre-allocate to size_upper
auto&& prconf = prealloc_config();
auto size_upper = std::max<size_t>(
std::max(size, prconf.min_req),
m_tot_allocated_from_raw * prconf.growth_factor);
size_upper = std::min(size_upper, size + prconf.max_overhead);
size_upper = get_aligned_power2(size_upper, prconf.alignment);
auto ptr = m_raw_allocator->alloc(size_upper);
if (!ptr && size_upper > size) {
// failed to allocate; do not pre-allocate and try again
size_upper = size;
ptr = m_raw_allocator->alloc(size_upper);
}
if (!ptr) {
// gather free memory from other streams on this device and try again
auto get = gather_stream_free_blk_and_release_full();
MGB_MARK_USED_VAR(get);
mgb_log("could not allocate memory on device %d; "
"try to gather free blocks from child streams, "
"got %.2fMiB(%zu bytes).",
m_device, get / 1024.0 / 1024, get);
ptr = m_raw_allocator->alloc(size_upper);
if (!ptr) {
// sync other devices in the hope that they can release memory on
// this device; then try again
auto&& runtime_policy = device_runtime_policy();
auto callback = [&runtime_policy](CompNode cn) {
if (cn.device_type() == runtime_policy->device_type()) {
int dev = cn.locator().device;
runtime_policy->device_synchronize(dev);
}
};
MGB_TRY { CompNode::foreach (callback); }
MGB_FINALLY({ m_runtime_policy->set_device(m_device); });
{
// sleep to wait for async dealloc
using namespace std::literals;
#if !__DEPLOY_ON_XP_SP2__
std::this_thread::sleep_for(0.2s);
#endif
}
get = gather_stream_free_blk_and_release_full();
mgb_log("device %d: sync all device and try to "
"allocate again: got %.2fMiB(%zu bytes).",
m_device, get / 1024.0 / 1024, get);
ptr = m_raw_allocator->alloc(size_upper);
if (!ptr) {
// try to alloc from newly gathered but unreleased (i.e. thoses
// that are not full chunks from raw allocator) chunks
//
// exception would be thrown from here
auto t = do_alloc(size, false, true);
m_used_size += size;
if (m_used_size > m_max_used_size) {
m_max_used_size = m_used_size.load();
}
return t;
}
}
}
MGB_LOCK_GUARD(m_mutex);
m_alloc_from_raw[ptr] = size_upper;
auto ptr_int = reinterpret_cast<size_t>(ptr);
if (size_upper > size) {
insert_free_unsafe({MemAddr{false, ptr_int + size}, size_upper - size});
}
m_tot_allocated_from_raw += size_upper;
return {true, ptr_int};
}
size_t DevMemAllocImpl::gather_stream_free_blk_and_release_full() {
size_t free_size = 0;
std::vector<void*> to_free_by_raw;
MGB_LOCK_GUARD(m_mutex);
auto return_full_free_blk_unsafe = [&](MemAllocImplHelper* alloc) {
auto&& free_blk_size = alloc->m_free_blk_size;
auto&& free_blk_addr = alloc->m_free_blk_addr;
using Iter = decltype(m_free_blk_size.begin());
for (Iter i = free_blk_size.begin(), inext; i != free_blk_size.end();
i = inext) {
inext = i;
++inext;
auto&& blk = i->first;
if (blk.addr.is_head) {
auto riter = m_alloc_from_raw.find(blk.addr.addr_ptr());
mgb_assert(
riter != m_alloc_from_raw.end() && blk.size <= riter->second);
if (blk.size == riter->second) {
to_free_by_raw.push_back(blk.addr.addr_ptr());
free_size += blk.size;
auto j = i->second.aiter;
free_blk_size.erase(i);
free_blk_addr.erase(j);
m_alloc_from_raw.erase(riter);
}
}
}
};
if (auto child = get_single_child_stream_unsafe()) {
MGB_LOCK_GUARD(child->m_mutex);
return_full_free_blk_unsafe(child);
mgb_assert(free_size <= m_used_size.load());
m_used_size -= free_size;
} else {
size_t gathered_size = 0;
for (auto&& pair : m_stream_alloc) {
auto ch = pair.second.get();
auto&& chmtx = ch->m_mutex;
MGB_LOCK_GUARD(chmtx);
for (auto&& i : ch->m_free_blk_size) {
merge_free_unsafe(i.first);
gathered_size += i.first.size;
}
ch->m_free_blk_addr.clear();
ch->m_free_blk_size.clear();
}
mgb_assert(gathered_size <= m_used_size.load());
m_used_size -= gathered_size;
}
return_full_free_blk_unsafe(this);
m_tot_allocated_from_raw -= free_size;
// we have to sync to ensure no kernel on the child stream still uses
// freed memory
m_runtime_policy->device_synchronize(m_device);
for (auto i : to_free_by_raw)
m_raw_allocator->free(i);
return free_size;
}
DevMemAllocImpl::DevMemAllocImpl(
int device, size_t reserve_size,
const std::shared_ptr<mem_alloc::RawAllocator>& raw_allocator,
const std::shared_ptr<mem_alloc::DeviceRuntimePolicy>& runtime_policy)
: m_device(device),
m_raw_allocator(raw_allocator),
m_runtime_policy(runtime_policy) {
if (reserve_size) {
auto ptr = m_raw_allocator->alloc(reserve_size);
mgb_throw_if(
!ptr, MemAllocError, "failed to reserve memory for %zu bytes",
reserve_size);
insert_free_unsafe(
{MemAddr{true, reinterpret_cast<size_t>(ptr)}, reserve_size});
m_alloc_from_raw[ptr] = reserve_size;
m_tot_allocated_from_raw += reserve_size;
}
}
void DevMemAllocImpl::print_memory_state() {
MemAllocImplHelper::print_memory_state();
for (auto&& i : m_stream_alloc)
i.second->print_memory_state();
}
FreeMemStat DevMemAllocImpl::get_free_memory_dev() {
MGB_LOCK_GUARD(m_mutex);
auto ret = get_free_memory_self_unsafe();
for (auto&& i : m_stream_alloc) {
MGB_LOCK_GUARD(i.second->m_mutex);
auto cur = i.second->get_free_memory_self_unsafe();
ret.tot += cur.tot;
ret.min = std::min(ret.min, cur.min);
ret.max = std::max(ret.max, cur.max);
ret.nr_blk += cur.nr_blk;
}
return ret;
}
void DevMemAllocImpl::insert_free_unsafe(const FreeBlock& block) {
if (auto child = get_single_child_stream_unsafe()) {
{
MGB_LOCK_GUARD(child->m_mutex);
child->insert_free_unsafe(block);
}
m_used_size += block.size;
if (m_used_size > m_max_used_size) {
m_max_used_size = m_used_size.load();
}
} else {
MemAllocImplHelper::insert_free_unsafe(block);
}
}
StreamMemAllocImpl* DevMemAllocImpl::get_single_child_stream_unsafe() {
if (m_stream_alloc.size() == 1) {
return m_stream_alloc.begin()->second.get();
}
return nullptr;
}
DevMemAllocImpl::~DevMemAllocImpl() {
for (auto&& i : m_alloc_from_raw)
m_raw_allocator->free(i.first);
}
std::unique_ptr<SimpleCachingAlloc> SimpleCachingAlloc::make(
std::unique_ptr<RawAllocator> raw_alloc) {
return std::make_unique<SimpleCachingAllocImpl>(std::move(raw_alloc));
}
SimpleCachingAllocImpl::SimpleCachingAllocImpl(std::unique_ptr<RawAllocator> raw_alloc)
: m_raw_alloc(std::move(raw_alloc)) {}
void* SimpleCachingAllocImpl::alloc(size_t size) {
size = get_aligned_power2(size, m_alignment);
auto&& addr = do_alloc(size, true);
auto ptr = addr.addr_ptr();
MGB_LOCK_GUARD(m_mutex);
m_allocated_blocks[ptr] = {addr.is_head, size};
m_used_size += size;
return ptr;
}
void SimpleCachingAllocImpl::free(void* ptr) {
MGB_LOCK_GUARD(m_mutex);
auto&& iter = m_allocated_blocks.find(ptr);
mgb_assert(iter != m_allocated_blocks.end(), "releasing bad pointer: %p", ptr);
auto size = iter->second.size;
FreeBlock fb{MemAddr{iter->second.is_head, reinterpret_cast<size_t>(ptr)}, size};
m_allocated_blocks.erase(iter);
merge_free_unsafe(fb);
m_used_size -= size;
}
SimpleCachingAllocImpl::~SimpleCachingAllocImpl() {
for (auto&& ptr_size : m_alloc_from_raw) {
m_raw_alloc->free(ptr_size.first);
}
}
SimpleCachingAllocImpl::MemAddr SimpleCachingAllocImpl::alloc_from_parent(size_t size) {
void* ptr = m_raw_alloc->alloc(size);
m_alloc_from_raw[ptr] = size;
return {true, reinterpret_cast<size_t>(ptr)};
}
std::string SimpleCachingAllocImpl::get_name() const {
return "SimpleCachingAllocImpl";
}
size_t SimpleCachingAllocImpl::get_used_memory() {
return m_used_size;
}
FreeMemStat SimpleCachingAllocImpl::get_free_memory_dev() {
return get_free_memory();
}
// vim: syntax=cpp.doxygen foldmethod=marker foldmarker=f{{{,f}}}
| 33.177291 | 89 | 0.626238 | [
"vector"
] |
175eb3decb1f8e72c63ae6866bcb1e1558ba1703 | 732 | cpp | C++ | POJ/1426/16336908_AC_407ms_5024kB.cpp | BakaErii/ACM_Collection | d368b15c7f1c84472424d5e61e5ebc667f589025 | [
"WTFPL"
] | null | null | null | POJ/1426/16336908_AC_407ms_5024kB.cpp | BakaErii/ACM_Collection | d368b15c7f1c84472424d5e61e5ebc667f589025 | [
"WTFPL"
] | null | null | null | POJ/1426/16336908_AC_407ms_5024kB.cpp | BakaErii/ACM_Collection | d368b15c7f1c84472424d5e61e5ebc667f589025 | [
"WTFPL"
] | null | null | null | /**
* @author Moe_Sakiya sakiya@tun.moe
* @date 2018-10-09 13:27:23
*
*/
#include <iostream>
#include <string>
#include <algorithm>
#include <set>
#include <map>
#include <vector>
#include <stack>
#include <queue>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
using namespace std;
int n;
unsigned long long int BFS(void) {
queue<unsigned long long int> que;
que.push(1);
while (!que.empty()) {
unsigned long long tmp = que.front();
que.pop();
if (tmp % n == 0)
return tmp;
que.push(tmp * 10);
que.push(tmp * 10 + 1);
}
return 0;
}
int main(void) {
ios::sync_with_stdio(false);
cin.tie(NULL);
while (~scanf("%d", &n) && n != 0) {
printf("%llu\n",BFS());
}
return 0;
} | 15.913043 | 39 | 0.620219 | [
"vector"
] |
176057ba8e8e940e7f0c0ec86586e7c8ce1ce0dc | 110,910 | cpp | C++ | recipes-clp/clp/clp/src/AbcSimplexParallel.cpp | Justin790126/meta-coinor | 0180187c583b3a6fd0a8dac7c85ac1bd89bf8cc9 | [
"MIT"
] | null | null | null | recipes-clp/clp/clp/src/AbcSimplexParallel.cpp | Justin790126/meta-coinor | 0180187c583b3a6fd0a8dac7c85ac1bd89bf8cc9 | [
"MIT"
] | null | null | null | recipes-clp/clp/clp/src/AbcSimplexParallel.cpp | Justin790126/meta-coinor | 0180187c583b3a6fd0a8dac7c85ac1bd89bf8cc9 | [
"MIT"
] | null | null | null | // Copyright (C) 2002, International Business Machines
// Corporation and others, Copyright (C) 2012, FasterCoin. All Rights Reserved.
// This code is licensed under the terms of the Eclipse Public License (EPL).
#include "CoinPragma.hpp"
#include <math.h>
#include "CoinHelperFunctions.hpp"
#include "CoinAbcHelperFunctions.hpp"
#include "AbcSimplexDual.hpp"
#include "ClpEventHandler.hpp"
#include "AbcSimplexFactorization.hpp"
#include "CoinPackedMatrix.hpp"
#include "CoinIndexedVector.hpp"
#include "CoinFloatEqual.hpp"
#include "AbcDualRowDantzig.hpp"
#include "ClpMessage.hpp"
#include "ClpLinearObjective.hpp"
#include <cfloat>
#include <cassert>
#include <string>
#include <stdio.h>
#include <iostream>
//#undef AVX2
#define _mm256_broadcast_sd(x) static_cast< __m256d >(__builtin_ia32_vbroadcastsd256(x))
#define _mm256_load_pd(x) *(__m256d *)(x)
#define _mm256_store_pd (s, x) * ((__m256d *)s) = x
//#define ABC_DEBUG 2
/* Reasons to come out:
-1 iterations etc
-2 inaccuracy
-3 slight inaccuracy (and done iterations)
+0 looks optimal (might be unbounded - but we will investigate)
+1 looks infeasible
+3 max iterations
*/
int AbcSimplexDual::whileIteratingSerial()
{
/* arrays
0 - to get tableau row and then for weights update
1 - tableau column
2 - for flip
3 - actual tableau row
*/
#ifdef CLP_DEBUG
int debugIteration = -1;
#endif
// if can't trust much and long way from optimal then relax
//if (largestPrimalError_ > 10.0)
//abcFactorization_->relaxAccuracyCheck(CoinMin(1.0e2, largestPrimalError_ / 10.0));
//else
//abcFactorization_->relaxAccuracyCheck(1.0);
// status stays at -1 while iterating, >=0 finished, -2 to invert
// status -3 to go to top without an invert
int returnCode = -1;
#define DELAYED_UPDATE
arrayForBtran_ = 0;
setUsedArray(arrayForBtran_);
arrayForFtran_ = 1;
setUsedArray(arrayForFtran_);
arrayForFlipBounds_ = 2;
setUsedArray(arrayForFlipBounds_);
arrayForTableauRow_ = 3;
setUsedArray(arrayForTableauRow_);
arrayForDualColumn_ = 4;
setUsedArray(arrayForDualColumn_);
arrayForReplaceColumn_ = 4; //4;
arrayForFlipRhs_ = 5;
setUsedArray(arrayForFlipRhs_);
dualPivotRow();
lastPivotRow_ = pivotRow_;
if (pivotRow_ >= 0) {
// we found a pivot row
createDualPricingVectorSerial();
do {
#if ABC_DEBUG
checkArrays();
#endif
/*
-1 - just move dual in values pass
0 - take iteration
1 - don't take but continue
2 - don't take and break
*/
stateOfIteration_ = 0;
returnCode = -1;
// put row of tableau in usefulArray[arrayForTableauRow_]
/*
Could
a) copy [arrayForBtran_] and start off updateWeights earlier
b) break transposeTimes into two and do after slack part
c) also think if cleaner to go all way with update but just don't do final part
*/
//upperTheta=COIN_DBL_MAX;
double saveAcceptable = acceptablePivot_;
if (largestPrimalError_ > 1.0e-5 || largestDualError_ > 1.0e-5) {
if (!abcFactorization_->pivots())
acceptablePivot_ *= 1.0e2;
else if (abcFactorization_->pivots() < 5)
acceptablePivot_ *= 1.0e1;
}
dualColumn1();
acceptablePivot_ = saveAcceptable;
if ((stateOfProblem_ & VALUES_PASS) != 0) {
// see if can just move dual
if (fabs(upperTheta_ - fabs(abcDj_[sequenceOut_])) < dualTolerance_) {
stateOfIteration_ = -1;
}
}
//usefulArray_[arrayForTableauRow_].sortPacked();
//usefulArray_[arrayForTableauRow_].print();
//usefulArray_[arrayForDualColumn_].setPackedMode(true);
//usefulArray_[arrayForDualColumn].sortPacked();
//usefulArray_[arrayForDualColumn].print();
if (!stateOfIteration_) {
// get sequenceIn_
dualPivotColumn();
if (sequenceIn_ >= 0) {
// normal iteration
// update the incoming column (and do weights)
getTableauColumnFlipAndStartReplaceSerial();
} else if (stateOfIteration_ != -1) {
stateOfIteration_ = 2;
}
}
if (!stateOfIteration_) {
// assert (stateOfIteration_!=1);
int whatNext = 0;
whatNext = housekeeping();
if (whatNext == 1) {
problemStatus_ = -2; // refactorize
} else if (whatNext == 2) {
// maximum iterations or equivalent
problemStatus_ = 3;
returnCode = 3;
stateOfIteration_ = 2;
}
if (problemStatus_ == -1) {
replaceColumnPart3();
//clearArrays(arrayForReplaceColumn_);
#if ABC_DEBUG
checkArrays();
#endif
updateDualsInDual();
abcDualRowPivot_->updatePrimalSolutionAndWeights(usefulArray_[arrayForBtran_], usefulArray_[arrayForFtran_],
movement_);
#if ABC_DEBUG
checkArrays();
#endif
} else {
abcDualRowPivot_->updateWeights2(usefulArray_[arrayForBtran_], usefulArray_[arrayForFtran_]);
//clearArrays(arrayForBtran_);
//clearArrays(arrayForFtran_);
}
} else {
if (stateOfIteration_ < 0) {
// move dual in dual values pass
theta_ = abcDj_[sequenceOut_];
updateDualsInDual();
abcDj_[sequenceOut_] = 0.0;
sequenceOut_ = -1;
}
// clear all arrays
clearArrays(-1);
//sequenceIn_=-1;
//sequenceOut_=-1;
}
// Check event
{
int status = eventHandler_->event(ClpEventHandler::endOfIteration);
if (status >= 0) {
problemStatus_ = 5;
secondaryStatus_ = ClpEventHandler::endOfIteration;
returnCode = 4;
stateOfIteration_ = 2;
}
}
// at this stage sequenceIn_ may be <0
if (sequenceIn_ < 0 && sequenceOut_ >= 0) {
// no incoming column is valid
returnCode = noPivotColumn();
}
if (stateOfIteration_ == 2) {
sequenceIn_ = -1;
break;
}
swapPrimalStuff();
if (problemStatus_ != -1) {
break;
}
// dualRow will go to virtual row pivot choice algorithm
// make sure values pass off if it should be
// use Btran array and clear inside dualPivotRow (if used)
int lastSequenceOut = sequenceOut_;
int lastDirectionOut = directionOut_;
dualPivotRow();
lastPivotRow_ = pivotRow_;
if (pivotRow_ >= 0) {
// we found a pivot row
// create as packed
createDualPricingVectorSerial();
swapDualStuff(lastSequenceOut, lastDirectionOut);
// next pivot
} else {
// no pivot row
clearArrays(-1);
returnCode = noPivotRow();
break;
}
} while (problemStatus_ == -1);
usefulArray_[arrayForTableauRow_].compact();
#if ABC_DEBUG
checkArrays();
#endif
} else {
// no pivot row on first try
clearArrays(-1);
returnCode = noPivotRow();
}
//printStuff();
clearArrays(-1);
//if (pivotRow_==-100)
//returnCode=-100; // end of values pass
return returnCode;
}
// Create dual pricing vector
void AbcSimplexDual::createDualPricingVectorSerial()
{
#ifndef NDEBUG
#if ABC_NORMAL_DEBUG > 3
checkArrays();
#endif
#endif
// we found a pivot row
if (handler_->detail(CLP_SIMPLEX_PIVOTROW, messages_) < 100) {
handler_->message(CLP_SIMPLEX_PIVOTROW, messages_)
<< pivotRow_
<< CoinMessageEol;
}
// check accuracy of weights
abcDualRowPivot_->checkAccuracy();
// get sign for finding row of tableau
// create as packed
usefulArray_[arrayForBtran_].createOneUnpackedElement(pivotRow_, -directionOut_);
abcFactorization_->updateColumnTranspose(usefulArray_[arrayForBtran_]);
sequenceIn_ = -1;
}
void AbcSimplexDual::getTableauColumnPart1Serial()
{
#if ABC_DEBUG
{
const double *work = usefulArray_[arrayForTableauRow_].denseVector();
int number = usefulArray_[arrayForTableauRow_].getNumElements();
const int *which = usefulArray_[arrayForTableauRow_].getIndices();
for (int i = 0; i < number; i++) {
if (which[i] == sequenceIn_) {
assert(alpha_ == work[i]);
break;
}
}
}
#endif
//int returnCode=0;
// update the incoming column
unpack(usefulArray_[arrayForFtran_]);
// Array[0] may be needed until updateWeights2
// and update dual weights (can do in parallel - with extra array)
alpha_ = abcDualRowPivot_->updateWeights1(usefulArray_[arrayForBtran_], usefulArray_[arrayForFtran_]);
}
int AbcSimplexDual::getTableauColumnFlipAndStartReplaceSerial()
{
// move checking stuff down into called functions
int numberFlipped;
numberFlipped = flipBounds();
// update the incoming column
getTableauColumnPart1Serial();
checkReplacePart1();
//checkReplacePart1a();
//checkReplacePart1b();
getTableauColumnPart2();
//usefulArray_[arrayForTableauRow_].compact();
// returns 3 if skip this iteration and re-factorize
/*
return code
0 - OK
2 - flag something and skip
3 - break and re-factorize
4 - break and say infeasible
*/
int returnCode = 0;
// amount primal will move
movement_ = -dualOut_ * directionOut_ / alpha_;
// see if update stable
#if ABC_NORMAL_DEBUG > 3
if ((handler_->logLevel() & 32)) {
double ft = ftAlpha_ * abcFactorization_->pivotRegion()[pivotRow_];
double diff1 = fabs(alpha_ - btranAlpha_);
double diff2 = fabs(fabs(alpha_) - fabs(ft));
double diff3 = fabs(fabs(ft) - fabs(btranAlpha_));
double largest = CoinMax(CoinMax(diff1, diff2), diff3);
printf("btran alpha %g, ftran alpha %g ftAlpha %g largest diff %g\n",
btranAlpha_, alpha_, ft, largest);
if (largest > 0.001 * fabs(alpha_)) {
printf("bad\n");
}
}
#endif
int numberPivots = abcFactorization_->pivots();
//double checkValue = 1.0e-7; // numberPivots<5 ? 1.0e-7 : 1.0e-6;
double checkValue = numberPivots ? 1.0e-7 : 1.0e-5;
// if can't trust much and long way from optimal then relax
if (largestPrimalError_ > 10.0)
checkValue = CoinMin(1.0e-4, 1.0e-8 * largestPrimalError_);
if (fabs(btranAlpha_) < 1.0e-12 || fabs(alpha_) < 1.0e-12 || fabs(btranAlpha_ - alpha_) > checkValue * (1.0 + fabs(alpha_))) {
handler_->message(CLP_DUAL_CHECK, messages_)
<< btranAlpha_
<< alpha_
<< CoinMessageEol;
// see with more relaxed criterion
double test;
if (fabs(btranAlpha_) < 1.0e-8 || fabs(alpha_) < 1.0e-8)
test = 1.0e-1 * fabs(alpha_);
else
test = 10.0 * checkValue; //1.0e-4 * (1.0 + fabs(alpha_));
bool needFlag = (fabs(btranAlpha_) < 1.0e-12 || fabs(alpha_) < 1.0e-12 || fabs(btranAlpha_ - alpha_) > test);
double derror = CoinMin(fabs(btranAlpha_ - alpha_) / (1.0 + fabs(alpha_)), 1.0) * 0.9999e7;
int error = 0;
while (derror > 1.0) {
error++;
derror *= 0.1;
}
int frequency[8] = { 99999999, 100, 10, 2, 1, 1, 1, 1 };
int newFactorFrequency = CoinMin(forceFactorization_, frequency[error]);
#if ABC_NORMAL_DEBUG > 0
if (newFactorFrequency < forceFactorization_)
printf("Error of %g after %d pivots old forceFact %d now %d\n",
fabs(btranAlpha_ - alpha_) / (1.0 + fabs(alpha_)), numberPivots,
forceFactorization_, newFactorFrequency);
#endif
if (!numberPivots && fabs(btranAlpha_ - alpha_) / (1.0 + fabs(alpha_)) > 0.5e-6
&& abcFactorization_->pivotTolerance() < 0.5)
abcFactorization_->saferTolerances(1.0, -1.03);
forceFactorization_ = newFactorFrequency;
#if ABC_NORMAL_DEBUG > 0
if (fabs(btranAlpha_ + alpha_) < 1.0e-5 * (1.0 + fabs(alpha_))) {
printf("diff (%g,%g) %g check %g\n", btranAlpha_, alpha_, fabs(btranAlpha_ - alpha_), checkValue * (1.0 + fabs(alpha_)));
}
#endif
if (numberPivots) {
if (needFlag && numberPivots < 10) {
// need to reject something
assert(sequenceOut_ >= 0);
char x = isColumn(sequenceOut_) ? 'C' : 'R';
handler_->message(CLP_SIMPLEX_FLAG, messages_)
<< x << sequenceWithin(sequenceOut_)
<< CoinMessageEol;
#if ABC_NORMAL_DEBUG > 0
printf("flag %d as alpha %g %g - after %d pivots\n", sequenceOut_,
btranAlpha_, alpha_, numberPivots);
#endif
// Make safer?
abcFactorization_->saferTolerances(1.0, -1.03);
setFlagged(sequenceOut_);
// so can't happen immediately again
sequenceOut_ = -1;
lastBadIteration_ = numberIterations_; // say be more cautious
}
// Make safer?
//if (numberPivots<5)
//abcFactorization_->saferTolerances (-0.99, -1.01);
problemStatus_ = -2; // factorize now
returnCode = -2;
stateOfIteration_ = 2;
} else {
if (needFlag) {
assert(sequenceOut_ >= 0);
// need to reject something
char x = isColumn(sequenceOut_) ? 'C' : 'R';
handler_->message(CLP_SIMPLEX_FLAG, messages_)
<< x << sequenceWithin(sequenceOut_)
<< CoinMessageEol;
#if ABC_NORMAL_DEBUG > 3
printf("flag a %g %g\n", btranAlpha_, alpha_);
#endif
setFlagged(sequenceOut_);
// so can't happen immediately again
sequenceOut_ = -1;
//abcProgress_.clearBadTimes();
lastBadIteration_ = numberIterations_; // say be more cautious
if (fabs(alpha_) < 1.0e-10 && fabs(btranAlpha_) < 1.0e-8 && numberIterations_ > 100) {
//printf("I think should declare infeasible\n");
problemStatus_ = 1;
returnCode = 1;
stateOfIteration_ = 2;
} else {
stateOfIteration_ = 1;
}
// Make safer?
if (abcFactorization_->pivotTolerance() < 0.999 && stateOfIteration_ == 1) {
// change tolerance and re-invert
abcFactorization_->saferTolerances(1.0, -1.03);
problemStatus_ = -6; // factorize now
returnCode = -2;
stateOfIteration_ = 2;
}
}
}
}
if (!stateOfIteration_) {
// check update
//int updateStatus =
/*
returns
0 - OK
1 - take iteration then re-factorize
2 - flag something and skip
3 - break and re-factorize
5 - take iteration then re-factorize because of memory
*/
int status = checkReplace();
if (status && !returnCode)
returnCode = status;
}
//clearArrays(arrayForFlipRhs_);
if (stateOfIteration_ && numberFlipped) {
//usefulArray_[arrayForTableauRow_].compact();
// move variables back
flipBack(numberFlipped);
}
// could choose average of all three
return returnCode;
}
#if ABC_PARALLEL == 1
/* Reasons to come out:
-1 iterations etc
-2 inaccuracy
-3 slight inaccuracy (and done iterations)
+0 looks optimal (might be unbounded - but we will investigate)
+1 looks infeasible
+3 max iterations
*/
int AbcSimplexDual::whileIteratingThread()
{
/* arrays
0 - to get tableau row and then for weights update
1 - tableau column
2 - for flip
3 - actual tableau row
*/
#ifdef CLP_DEBUG
int debugIteration = -1;
#endif
// if can't trust much and long way from optimal then relax
//if (largestPrimalError_ > 10.0)
//abcFactorization_->relaxAccuracyCheck(CoinMin(1.0e2, largestPrimalError_ / 10.0));
//else
//abcFactorization_->relaxAccuracyCheck(1.0);
// status stays at -1 while iterating, >=0 finished, -2 to invert
// status -3 to go to top without an invert
int returnCode = -1;
#define DELAYED_UPDATE
arrayForBtran_ = 0;
setUsedArray(arrayForBtran_);
arrayForFtran_ = 1;
setUsedArray(arrayForFtran_);
arrayForFlipBounds_ = 2;
setUsedArray(arrayForFlipBounds_);
arrayForTableauRow_ = 3;
setUsedArray(arrayForTableauRow_);
arrayForDualColumn_ = 4;
setUsedArray(arrayForDualColumn_);
arrayForReplaceColumn_ = 4; //4;
arrayForFlipRhs_ = 5;
setUsedArray(arrayForFlipRhs_);
dualPivotRow();
lastPivotRow_ = pivotRow_;
if (pivotRow_ >= 0) {
// we found a pivot row
createDualPricingVectorThread();
do {
#if ABC_DEBUG
checkArrays();
#endif
/*
-1 - just move dual in values pass
0 - take iteration
1 - don't take but continue
2 - don't take and break
*/
stateOfIteration_ = 0;
returnCode = -1;
// put row of tableau in usefulArray[arrayForTableauRow_]
/*
Could
a) copy [arrayForBtran_] and start off updateWeights earlier
b) break transposeTimes into two and do after slack part
c) also think if cleaner to go all way with update but just don't do final part
*/
//upperTheta=COIN_DBL_MAX;
double saveAcceptable = acceptablePivot_;
if (largestPrimalError_ > 1.0e-5 || largestDualError_ > 1.0e-5) {
if (!abcFactorization_->pivots())
acceptablePivot_ *= 1.0e2;
else if (abcFactorization_->pivots() < 5)
acceptablePivot_ *= 1.0e1;
}
dualColumn1();
acceptablePivot_ = saveAcceptable;
if ((stateOfProblem_ & VALUES_PASS) != 0) {
// see if can just move dual
if (fabs(upperTheta_ - fabs(abcDj_[sequenceOut_])) < dualTolerance_) {
stateOfIteration_ = -1;
}
}
//usefulArray_[arrayForTableauRow_].sortPacked();
//usefulArray_[arrayForTableauRow_].print();
//usefulArray_[arrayForDualColumn_].setPackedMode(true);
//usefulArray_[arrayForDualColumn].sortPacked();
//usefulArray_[arrayForDualColumn].print();
if (parallelMode_ != 0) {
stopStart_ = 1 + 32 * 1; // Just first thread for updateweights
startParallelStuff(2);
}
if (!stateOfIteration_) {
// get sequenceIn_
dualPivotColumn();
if (sequenceIn_ >= 0) {
// normal iteration
// update the incoming column (and do weights if serial)
getTableauColumnFlipAndStartReplaceThread();
//usleep(1000);
} else if (stateOfIteration_ != -1) {
stateOfIteration_ = 2;
}
}
if (parallelMode_ != 0) {
// do sync here
stopParallelStuff(2);
}
if (!stateOfIteration_) {
// assert (stateOfIteration_!=1);
int whatNext = 0;
whatNext = housekeeping();
if (whatNext == 1) {
problemStatus_ = -2; // refactorize
} else if (whatNext == 2) {
// maximum iterations or equivalent
problemStatus_ = 3;
returnCode = 3;
stateOfIteration_ = 2;
}
} else {
if (stateOfIteration_ < 0) {
// move dual in dual values pass
theta_ = abcDj_[sequenceOut_];
updateDualsInDual();
abcDj_[sequenceOut_] = 0.0;
sequenceOut_ = -1;
}
// clear all arrays
clearArrays(-1);
}
// at this stage sequenceIn_ may be <0
if (sequenceIn_ < 0 && sequenceOut_ >= 0) {
// no incoming column is valid
returnCode = noPivotColumn();
}
if (stateOfIteration_ == 2) {
sequenceIn_ = -1;
break;
}
if (problemStatus_ != -1) {
abcDualRowPivot_->updateWeights2(usefulArray_[arrayForBtran_], usefulArray_[arrayForFtran_]);
swapPrimalStuff();
break;
}
#if ABC_DEBUG
checkArrays();
#endif
if (stateOfIteration_ != -1) {
assert(stateOfIteration_ == 0); // if 1 why are we here
// can do these in parallel
if (parallelMode_ == 0) {
replaceColumnPart3();
updateDualsInDual();
abcDualRowPivot_->updatePrimalSolutionAndWeights(usefulArray_[arrayForBtran_], usefulArray_[arrayForFtran_],
movement_);
} else {
stopStart_ = 1 + 32 * 1;
startParallelStuff(3);
if (parallelMode_ > 1) {
stopStart_ = 2 + 32 * 2;
startParallelStuff(9);
} else {
replaceColumnPart3();
}
abcDualRowPivot_->updatePrimalSolutionAndWeights(usefulArray_[arrayForBtran_], usefulArray_[arrayForFtran_],
movement_);
}
}
#if ABC_DEBUG
checkArrays();
#endif
swapPrimalStuff();
// dualRow will go to virtual row pivot choice algorithm
// make sure values pass off if it should be
// use Btran array and clear inside dualPivotRow (if used)
int lastSequenceOut = sequenceOut_;
int lastDirectionOut = directionOut_;
// redo to test on parallelMode_
if (parallelMode_ > 1) {
stopStart_ = 2 + 32 * 2; // stop factorization update
//stopStart_=3+32*3; // stop all
stopParallelStuff(9);
}
dualPivotRow();
lastPivotRow_ = pivotRow_;
if (pivotRow_ >= 0) {
// we found a pivot row
// create as packed
createDualPricingVectorThread();
swapDualStuff(lastSequenceOut, lastDirectionOut);
// next pivot
// redo to test on parallelMode_
if (parallelMode_ != 0) {
stopStart_ = 1 + 32 * 1; // stop dual update
stopParallelStuff(3);
}
} else {
// no pivot row
// redo to test on parallelMode_
if (parallelMode_ != 0) {
stopStart_ = 1 + 32 * 1; // stop dual update
stopParallelStuff(3);
}
clearArrays(-1);
returnCode = noPivotRow();
break;
}
} while (problemStatus_ == -1);
usefulArray_[arrayForTableauRow_].compact();
#if ABC_DEBUG
checkArrays();
#endif
} else {
// no pivot row on first try
clearArrays(-1);
returnCode = noPivotRow();
}
//printStuff();
clearArrays(-1);
//if (pivotRow_==-100)
//returnCode=-100; // end of values pass
return returnCode;
}
// Create dual pricing vector
void AbcSimplexDual::createDualPricingVectorThread()
{
#ifndef NDEBUG
#if ABC_NORMAL_DEBUG > 3
checkArrays();
#endif
#endif
// we found a pivot row
if (handler_->detail(CLP_SIMPLEX_PIVOTROW, messages_) < 100) {
handler_->message(CLP_SIMPLEX_PIVOTROW, messages_)
<< pivotRow_
<< CoinMessageEol;
}
// check accuracy of weights
abcDualRowPivot_->checkAccuracy();
// get sign for finding row of tableau
// create as packed
usefulArray_[arrayForBtran_].createOneUnpackedElement(pivotRow_, -directionOut_);
abcFactorization_->updateColumnTranspose(usefulArray_[arrayForBtran_]);
sequenceIn_ = -1;
}
void AbcSimplexDual::getTableauColumnPart1Thread()
{
#if ABC_DEBUG
{
const double *work = usefulArray_[arrayForTableauRow_].denseVector();
int number = usefulArray_[arrayForTableauRow_].getNumElements();
const int *which = usefulArray_[arrayForTableauRow_].getIndices();
for (int i = 0; i < number; i++) {
if (which[i] == sequenceIn_) {
assert(alpha_ == work[i]);
break;
}
}
}
#endif
//int returnCode=0;
// update the incoming column
unpack(usefulArray_[arrayForFtran_]);
// Array[0] may be needed until updateWeights2
// and update dual weights (can do in parallel - with extra array)
if (parallelMode_ != 0) {
abcFactorization_->updateColumnFTPart1(usefulArray_[arrayForFtran_]);
// pivot element
//alpha_ = usefulArray_[arrayForFtran_].denseVector()[pivotRow_];
} else {
alpha_ = abcDualRowPivot_->updateWeights1(usefulArray_[arrayForBtran_], usefulArray_[arrayForFtran_]);
}
}
int AbcSimplexDual::getTableauColumnFlipAndStartReplaceThread()
{
// move checking stuff down into called functions
// threads 2 and 3 are available
int numberFlipped;
if (parallelMode_ == 0) {
numberFlipped = flipBounds();
// update the incoming column
getTableauColumnPart1Thread();
checkReplacePart1();
//checkReplacePart1a();
//checkReplacePart1b();
getTableauColumnPart2();
} else {
// save stopStart
int saveStopStart = stopStart_;
if (parallelMode_ > 1) {
// we can flip immediately
stopStart_ = 2 + 32 * 2; // just thread 1
startParallelStuff(8);
// update the incoming column
getTableauColumnPart1Thread();
stopStart_ = 4 + 32 * 4; // just thread 2
startParallelStuff(7);
getTableauColumnPart2();
stopStart_ = 6 + 32 * 6; // just threads 1 and 2
stopParallelStuff(8);
//ftAlpha_=threadInfo_[2].result;
} else {
// just one extra thread - do replace
// update the incoming column
getTableauColumnPart1Thread();
stopStart_ = 2 + 32 * 2; // just thread 1
startParallelStuff(7);
getTableauColumnPart2();
numberFlipped = flipBounds();
stopParallelStuff(8);
//ftAlpha_=threadInfo_[1].result;
}
stopStart_ = saveStopStart;
}
//usefulArray_[arrayForTableauRow_].compact();
// returns 3 if skip this iteration and re-factorize
/*
return code
0 - OK
2 - flag something and skip
3 - break and re-factorize
4 - break and say infeasible
*/
int returnCode = 0;
// amount primal will move
movement_ = -dualOut_ * directionOut_ / alpha_;
// see if update stable
#if ABC_NORMAL_DEBUG > 3
if ((handler_->logLevel() & 32)) {
double ft = ftAlpha_ * abcFactorization_->pivotRegion()[pivotRow_];
double diff1 = fabs(alpha_ - btranAlpha_);
double diff2 = fabs(fabs(alpha_) - fabs(ft));
double diff3 = fabs(fabs(ft) - fabs(btranAlpha_));
double largest = CoinMax(CoinMax(diff1, diff2), diff3);
printf("btran alpha %g, ftran alpha %g ftAlpha %g largest diff %g\n",
btranAlpha_, alpha_, ft, largest);
if (largest > 0.001 * fabs(alpha_)) {
printf("bad\n");
}
}
#endif
int numberPivots = abcFactorization_->pivots();
//double checkValue = 1.0e-7; // numberPivots<5 ? 1.0e-7 : 1.0e-6;
double checkValue = numberPivots ? 1.0e-7 : 1.0e-5;
// if can't trust much and long way from optimal then relax
if (largestPrimalError_ > 10.0)
checkValue = CoinMin(1.0e-4, 1.0e-8 * largestPrimalError_);
if (fabs(btranAlpha_) < 1.0e-12 || fabs(alpha_) < 1.0e-12 || fabs(btranAlpha_ - alpha_) > checkValue * (1.0 + fabs(alpha_))) {
handler_->message(CLP_DUAL_CHECK, messages_)
<< btranAlpha_
<< alpha_
<< CoinMessageEol;
// see with more relaxed criterion
double test;
if (fabs(btranAlpha_) < 1.0e-8 || fabs(alpha_) < 1.0e-8)
test = 1.0e-1 * fabs(alpha_);
else
test = 10.0 * checkValue; //1.0e-4 * (1.0 + fabs(alpha_));
bool needFlag = (fabs(btranAlpha_) < 1.0e-12 || fabs(alpha_) < 1.0e-12 || fabs(btranAlpha_ - alpha_) > test);
double derror = CoinMin(fabs(btranAlpha_ - alpha_) / (1.0 + fabs(alpha_)), 1.0) * 0.9999e7;
int error = 0;
while (derror > 1.0) {
error++;
derror *= 0.1;
}
int frequency[8] = { 99999999, 100, 10, 2, 1, 1, 1, 1 };
int newFactorFrequency = CoinMin(forceFactorization_, frequency[error]);
#if ABC_NORMAL_DEBUG > 0
if (newFactorFrequency < forceFactorization_)
printf("Error of %g after %d pivots old forceFact %d now %d\n",
fabs(btranAlpha_ - alpha_) / (1.0 + fabs(alpha_)), numberPivots,
forceFactorization_, newFactorFrequency);
#endif
if (!numberPivots && fabs(btranAlpha_ - alpha_) / (1.0 + fabs(alpha_)) > 0.5e-6
&& abcFactorization_->pivotTolerance() < 0.5)
abcFactorization_->saferTolerances(1.0, -1.03);
forceFactorization_ = newFactorFrequency;
#if ABC_NORMAL_DEBUG > 0
if (fabs(btranAlpha_ + alpha_) < 1.0e-5 * (1.0 + fabs(alpha_))) {
printf("diff (%g,%g) %g check %g\n", btranAlpha_, alpha_, fabs(btranAlpha_ - alpha_), checkValue * (1.0 + fabs(alpha_)));
}
#endif
if (numberPivots) {
if (needFlag && numberPivots < 10) {
// need to reject something
assert(sequenceOut_ >= 0);
char x = isColumn(sequenceOut_) ? 'C' : 'R';
handler_->message(CLP_SIMPLEX_FLAG, messages_)
<< x << sequenceWithin(sequenceOut_)
<< CoinMessageEol;
#if ABC_NORMAL_DEBUG > 0
printf("flag %d as alpha %g %g - after %d pivots\n", sequenceOut_,
btranAlpha_, alpha_, numberPivots);
#endif
// Make safer?
abcFactorization_->saferTolerances(1.0, -1.03);
setFlagged(sequenceOut_);
// so can't happen immediately again
sequenceOut_ = -1;
lastBadIteration_ = numberIterations_; // say be more cautious
}
// Make safer?
//if (numberPivots<5)
//abcFactorization_->saferTolerances (-0.99, -1.01);
problemStatus_ = -2; // factorize now
returnCode = -2;
stateOfIteration_ = 2;
} else {
if (needFlag) {
assert(sequenceOut_ >= 0);
// need to reject something
char x = isColumn(sequenceOut_) ? 'C' : 'R';
handler_->message(CLP_SIMPLEX_FLAG, messages_)
<< x << sequenceWithin(sequenceOut_)
<< CoinMessageEol;
#if ABC_NORMAL_DEBUG > 3
printf("flag a %g %g\n", btranAlpha_, alpha_);
#endif
setFlagged(sequenceOut_);
// so can't happen immediately again
sequenceOut_ = -1;
//abcProgress_.clearBadTimes();
lastBadIteration_ = numberIterations_; // say be more cautious
if (fabs(alpha_) < 1.0e-10 && fabs(btranAlpha_) < 1.0e-8 && numberIterations_ > 100) {
//printf("I think should declare infeasible\n");
problemStatus_ = 1;
returnCode = 1;
stateOfIteration_ = 2;
} else {
stateOfIteration_ = 1;
}
// Make safer?
if (abcFactorization_->pivotTolerance() < 0.999 && stateOfIteration_ == 1) {
// change tolerance and re-invert
abcFactorization_->saferTolerances(1.0, -1.03);
problemStatus_ = -6; // factorize now
returnCode = -2;
stateOfIteration_ = 2;
}
}
}
}
if (!stateOfIteration_) {
// check update
//int updateStatus =
/*
returns
0 - OK
1 - take iteration then re-factorize
2 - flag something and skip
3 - break and re-factorize
5 - take iteration then re-factorize because of memory
*/
int status = checkReplace();
if (status && !returnCode)
returnCode = status;
}
//clearArrays(arrayForFlipRhs_);
if (stateOfIteration_ && numberFlipped) {
//usefulArray_[arrayForTableauRow_].compact();
// move variables back
flipBack(numberFlipped);
}
// could choose average of all three
return returnCode;
}
#endif
#if ABC_PARALLEL == 2
#if ABC_NORMAL_DEBUG > 0
// for conflicts
int cilk_conflict = 0;
#endif
#ifdef EARLY_FACTORIZE
static int doEarlyFactorization(AbcSimplexDual *dual)
{
int returnCode = cilk_spawn dual->whileIteratingParallel(123456789);
CoinIndexedVector &vector = *dual->usefulArray(ABC_NUMBER_USEFUL - 1);
int status = dual->earlyFactorization()->factorize(dual, vector);
#if 0
// Is this safe
if (!status&&true) {
// do pivots if there are any
int capacity = vector.capacity();
capacity--;
int numberPivotsStored = vector.getIndices()[capacity];
status =
dual->earlyFactorization()->replaceColumns(dual,vector,
0,numberPivotsStored,false);
}
#endif
if (status) {
printf("bad early factorization in doEarly - switch off\n");
vector.setNumElements(-1);
}
cilk_sync;
return returnCode;
}
#endif
#define MOVE_UPDATE_WEIGHTS
/* Reasons to come out:
-1 iterations etc
-2 inaccuracy
-3 slight inaccuracy (and done iterations)
+0 looks optimal (might be unbounded - but we will investigate)
+1 looks infeasible
+3 max iterations
*/
int AbcSimplexDual::whileIteratingCilk()
{
/* arrays
0 - to get tableau row and then for weights update
1 - tableau column
2 - for flip
3 - actual tableau row
*/
#ifdef CLP_DEBUG
int debugIteration = -1;
#endif
// if can't trust much and long way from optimal then relax
//if (largestPrimalError_ > 10.0)
//abcFactorization_->relaxAccuracyCheck(CoinMin(1.0e2, largestPrimalError_ / 10.0));
//else
//abcFactorization_->relaxAccuracyCheck(1.0);
// status stays at -1 while iterating, >=0 finished, -2 to invert
// status -3 to go to top without an invert
int returnCode = -1;
#define DELAYED_UPDATE
arrayForBtran_ = 0;
setUsedArray(arrayForBtran_);
arrayForFtran_ = 1;
setUsedArray(arrayForFtran_);
arrayForFlipBounds_ = 2;
setUsedArray(arrayForFlipBounds_);
arrayForTableauRow_ = 3;
setUsedArray(arrayForTableauRow_);
arrayForDualColumn_ = 4;
setUsedArray(arrayForDualColumn_);
arrayForReplaceColumn_ = 6; //4;
setUsedArray(arrayForReplaceColumn_);
#ifndef MOVE_UPDATE_WEIGHTS
arrayForFlipRhs_ = 5;
setUsedArray(arrayForFlipRhs_);
#else
arrayForFlipRhs_ = 0;
// use for weights
setUsedArray(5);
#endif
dualPivotRow();
lastPivotRow_ = pivotRow_;
if (pivotRow_ >= 0) {
// we found a pivot row
createDualPricingVectorCilk();
// ABC_PARALLEL 2
#if 0
{
for (int i=0;i<numberRows_;i++) {
int iSequence=abcPivotVariable_[i];
if (lowerBasic_[i]!=lowerSaved_[iSequence]||
upperBasic_[i]!=upperSaved_[iSequence])
printf("basic l %g,%g,%g u %g,%g\n",
abcLower_[iSequence],lowerSaved_[iSequence],lowerBasic_[i],
abcUpper_[iSequence],upperSaved_[iSequence],upperBasic_[i]);
}
}
#endif
#if 0
for (int iSequence = 0; iSequence < numberTotal_; iSequence++) {
int bad=-1;
if (getFakeBound(iSequence)==noFake) {
if (abcLower_[iSequence]!=lowerSaved_[iSequence]||
abcUpper_[iSequence]!=upperSaved_[iSequence])
bad=0;
} else if (getFakeBound(iSequence)==lowerFake) {
if (abcLower_[iSequence]==lowerSaved_[iSequence]||
abcUpper_[iSequence]!=upperSaved_[iSequence])
bad=1;
} else if (getFakeBound(iSequence)==upperFake) {
if (abcLower_[iSequence]!=lowerSaved_[iSequence]||
abcUpper_[iSequence]==upperSaved_[iSequence])
bad=2;
} else {
if (abcLower_[iSequence]==lowerSaved_[iSequence]||
abcUpper_[iSequence]==upperSaved_[iSequence])
bad=3;
}
if (bad>=0)
printf("%d status %d l %g,%g u %g,%g\n",iSequence,internalStatus_[iSequence],
abcLower_[iSequence],lowerSaved_[iSequence],
abcUpper_[iSequence],upperSaved_[iSequence]);
}
#endif
int numberPivots = abcFactorization_->maximumPivots();
#ifdef EARLY_FACTORIZE
int numberEarly = 0;
if (numberPivots > 20 && (numberEarly_ & 0xffff) > 5) {
numberEarly = numberEarly_ & 0xffff;
numberPivots = CoinMax(numberPivots - numberEarly - abcFactorization_->pivots(), numberPivots / 2);
}
returnCode = whileIteratingParallel(numberPivots);
if (returnCode == -99) {
if (numberEarly) {
if (!abcEarlyFactorization_)
abcEarlyFactorization_ = new AbcSimplexFactorization(*abcFactorization_);
// create pivot list
CoinIndexedVector &vector = usefulArray_[ABC_NUMBER_USEFUL - 1];
vector.checkClear();
int *indices = vector.getIndices();
int capacity = vector.capacity();
int numberNeeded = numberRows_ + 2 * numberEarly + 1;
if (capacity < numberNeeded) {
vector.reserve(numberNeeded);
capacity = vector.capacity();
}
int numberBasic = 0;
for (int i = 0; i < numberRows_; i++) {
int iSequence = abcPivotVariable_[i];
if (iSequence < numberRows_)
indices[numberBasic++] = iSequence;
}
vector.setNumElements(numberRows_ - numberBasic);
for (int i = 0; i < numberRows_; i++) {
int iSequence = abcPivotVariable_[i];
if (iSequence >= numberRows_)
indices[numberBasic++] = iSequence;
}
assert(numberBasic == numberRows_);
indices[capacity - 1] = 0;
// could set iterations to -1 for safety
#if 0
cilk_spawn doEarlyFactorization(this);
returnCode=whileIteratingParallel(123456789);
cilk_sync;
#else
returnCode = doEarlyFactorization(this);
#endif
} else {
returnCode = whileIteratingParallel(123456789);
}
}
#else
returnCode = whileIteratingParallel(numberPivots);
#endif
usefulArray_[arrayForTableauRow_].compact();
#if ABC_DEBUG
checkArrays();
#endif
} else {
// no pivot row on first try
clearArrays(-1);
returnCode = noPivotRow();
}
//printStuff();
clearArrays(-1);
//if (pivotRow_==-100)
//returnCode=-100; // end of values pass
return returnCode;
}
// Create dual pricing vector
void AbcSimplexDual::createDualPricingVectorCilk()
{
#if CILK_CONFLICT > 0
if (cilk_conflict & 15 != 0) {
printf("cilk_conflict %d!\n", cilk_conflict);
cilk_conflict = 0;
}
#endif
#ifndef NDEBUG
#if ABC_NORMAL_DEBUG > 3
checkArrays();
#endif
#endif
// we found a pivot row
if (handler_->detail(CLP_SIMPLEX_PIVOTROW, messages_) < 100) {
handler_->message(CLP_SIMPLEX_PIVOTROW, messages_)
<< pivotRow_
<< CoinMessageEol;
}
// check accuracy of weights
abcDualRowPivot_->checkAccuracy();
// get sign for finding row of tableau
// create as packed
#if MOVE_REPLACE_PART1A > 0
if (!abcFactorization_->usingFT()) {
#endif
usefulArray_[arrayForBtran_].createOneUnpackedElement(pivotRow_, -directionOut_);
abcFactorization_->updateColumnTranspose(usefulArray_[arrayForBtran_]);
#if MOVE_REPLACE_PART1A > 0
} else {
cilk_spawn abcFactorization_->checkReplacePart1a(&usefulArray_[arrayForReplaceColumn_], pivotRow_);
usefulArray_[arrayForBtran_].createOneUnpackedElement(pivotRow_, -directionOut_);
abcFactorization_->updateColumnTransposeCpu(usefulArray_[arrayForBtran_], 1);
cilk_sync;
}
#endif
sequenceIn_ = -1;
}
void AbcSimplexDual::getTableauColumnPart1Cilk()
{
#if ABC_DEBUG
{
const double *work = usefulArray_[arrayForTableauRow_].denseVector();
int number = usefulArray_[arrayForTableauRow_].getNumElements();
const int *which = usefulArray_[arrayForTableauRow_].getIndices();
for (int i = 0; i < number; i++) {
if (which[i] == sequenceIn_) {
assert(alpha_ == work[i]);
break;
}
}
}
#endif
//int returnCode=0;
// update the incoming column
unpack(usefulArray_[arrayForFtran_]);
// Array[0] may be needed until updateWeights2
// and update dual weights (can do in parallel - with extra array)
abcFactorization_->updateColumnFTPart1(usefulArray_[arrayForFtran_]);
}
int AbcSimplexDual::getTableauColumnFlipAndStartReplaceCilk()
{
// move checking stuff down into called functions
// threads 2 and 3 are available
int numberFlipped;
//cilk
getTableauColumnPart1Cilk();
#if MOVE_REPLACE_PART1A <= 0
cilk_spawn getTableauColumnPart2();
#if MOVE_REPLACE_PART1A == 0
cilk_spawn checkReplacePart1();
#endif
numberFlipped = flipBounds();
cilk_sync;
#else
if (abcFactorization_->usingFT()) {
cilk_spawn getTableauColumnPart2();
ftAlpha_ = cilk_spawn abcFactorization_->checkReplacePart1b(&usefulArray_[arrayForReplaceColumn_], pivotRow_);
numberFlipped = flipBounds();
cilk_sync;
} else {
cilk_spawn getTableauColumnPart2();
numberFlipped = flipBounds();
cilk_sync;
}
#endif
//usefulArray_[arrayForTableauRow_].compact();
// returns 3 if skip this iteration and re-factorize
/*
return code
0 - OK
2 - flag something and skip
3 - break and re-factorize
4 - break and say infeasible
*/
int returnCode = 0;
// amount primal will move
movement_ = -dualOut_ * directionOut_ / alpha_;
// see if update stable
#if ABC_NORMAL_DEBUG > 3
if ((handler_->logLevel() & 32)) {
double ft = ftAlpha_ * abcFactorization_->pivotRegion()[pivotRow_];
double diff1 = fabs(alpha_ - btranAlpha_);
double diff2 = fabs(fabs(alpha_) - fabs(ft));
double diff3 = fabs(fabs(ft) - fabs(btranAlpha_));
double largest = CoinMax(CoinMax(diff1, diff2), diff3);
printf("btran alpha %g, ftran alpha %g ftAlpha %g largest diff %g\n",
btranAlpha_, alpha_, ft, largest);
if (largest > 0.001 * fabs(alpha_)) {
printf("bad\n");
}
}
#endif
int numberPivots = abcFactorization_->pivots();
//double checkValue = 1.0e-7; // numberPivots<5 ? 1.0e-7 : 1.0e-6;
double checkValue = numberPivots ? 1.0e-7 : 1.0e-5;
// if can't trust much and long way from optimal then relax
if (largestPrimalError_ > 10.0)
checkValue = CoinMin(1.0e-4, 1.0e-8 * largestPrimalError_);
if (fabs(btranAlpha_) < 1.0e-12 || fabs(alpha_) < 1.0e-12 || fabs(btranAlpha_ - alpha_) > checkValue * (1.0 + fabs(alpha_))) {
handler_->message(CLP_DUAL_CHECK, messages_)
<< btranAlpha_
<< alpha_
<< CoinMessageEol;
// see with more relaxed criterion
double test;
if (fabs(btranAlpha_) < 1.0e-8 || fabs(alpha_) < 1.0e-8)
test = 1.0e-1 * fabs(alpha_);
else
test = CoinMin(10.0 * checkValue, 1.0e-4 * (1.0 + fabs(alpha_)));
bool needFlag = (fabs(btranAlpha_) < 1.0e-12 || fabs(alpha_) < 1.0e-12 || fabs(btranAlpha_ - alpha_) > test);
double derror = CoinMin(fabs(btranAlpha_ - alpha_) / (1.0 + fabs(alpha_)), 1.0) * 0.9999e7;
int error = 0;
while (derror > 1.0) {
error++;
derror *= 0.1;
}
int frequency[8] = { 99999999, 100, 10, 2, 1, 1, 1, 1 };
int newFactorFrequency = CoinMin(forceFactorization_, frequency[error]);
#if ABC_NORMAL_DEBUG > 0
if (newFactorFrequency < forceFactorization_)
printf("Error of %g after %d pivots old forceFact %d now %d\n",
fabs(btranAlpha_ - alpha_) / (1.0 + fabs(alpha_)), numberPivots,
forceFactorization_, newFactorFrequency);
#endif
if (!numberPivots && fabs(btranAlpha_ - alpha_) / (1.0 + fabs(alpha_)) > 0.5e-6
&& abcFactorization_->pivotTolerance() < 0.5)
abcFactorization_->saferTolerances(1.0, -1.03);
forceFactorization_ = newFactorFrequency;
#if ABC_NORMAL_DEBUG > 0
if (fabs(btranAlpha_ + alpha_) < 1.0e-5 * (1.0 + fabs(alpha_))) {
printf("diff (%g,%g) %g check %g\n", btranAlpha_, alpha_, fabs(btranAlpha_ - alpha_), checkValue * (1.0 + fabs(alpha_)));
}
#endif
if (numberPivots) {
if (needFlag && numberPivots < 10) {
// need to reject something
assert(sequenceOut_ >= 0);
char x = isColumn(sequenceOut_) ? 'C' : 'R';
handler_->message(CLP_SIMPLEX_FLAG, messages_)
<< x << sequenceWithin(sequenceOut_)
<< CoinMessageEol;
#if ABC_NORMAL_DEBUG > 0
printf("flag %d as alpha %g %g - after %d pivots\n", sequenceOut_,
btranAlpha_, alpha_, numberPivots);
#endif
// Make safer?
abcFactorization_->saferTolerances(1.0, -1.03);
setFlagged(sequenceOut_);
// so can't happen immediately again
sequenceOut_ = -1;
lastBadIteration_ = numberIterations_; // say be more cautious
}
// Make safer?
//if (numberPivots<5)
//abcFactorization_->saferTolerances (-0.99, -1.01);
problemStatus_ = -2; // factorize now
returnCode = -2;
stateOfIteration_ = 2;
} else {
if (needFlag) {
assert(sequenceOut_ >= 0);
// need to reject something
char x = isColumn(sequenceOut_) ? 'C' : 'R';
handler_->message(CLP_SIMPLEX_FLAG, messages_)
<< x << sequenceWithin(sequenceOut_)
<< CoinMessageEol;
#if ABC_NORMAL_DEBUG > 3
printf("flag a %g %g\n", btranAlpha_, alpha_);
#endif
setFlagged(sequenceOut_);
// so can't happen immediately again
sequenceOut_ = -1;
//abcProgress_.clearBadTimes();
lastBadIteration_ = numberIterations_; // say be more cautious
if (fabs(alpha_) < 1.0e-10 && fabs(btranAlpha_) < 1.0e-8 && numberIterations_ > 100) {
//printf("I think should declare infeasible\n");
problemStatus_ = 1;
returnCode = 1;
stateOfIteration_ = 2;
} else {
stateOfIteration_ = 1;
}
// Make safer?
if (abcFactorization_->pivotTolerance() < 0.999 && stateOfIteration_ == 1) {
// change tolerance and re-invert
abcFactorization_->saferTolerances(1.0, -1.03);
problemStatus_ = -6; // factorize now
returnCode = -2;
stateOfIteration_ = 2;
}
}
}
}
if (!stateOfIteration_) {
// check update
//int updateStatus =
/*
returns
0 - OK
1 - take iteration then re-factorize
2 - flag something and skip
3 - break and re-factorize
5 - take iteration then re-factorize because of memory
*/
int status = checkReplace();
if (status && !returnCode)
returnCode = status;
}
//clearArrays(arrayForFlipRhs_);
if (stateOfIteration_ && numberFlipped) {
//usefulArray_[arrayForTableauRow_].compact();
// move variables back
flipBack(numberFlipped);
}
// could choose average of all three
return returnCode;
}
int AbcSimplexDual::whileIteratingParallel(int numberIterations)
{
int returnCode = -1;
#ifdef EARLY_FACTORIZE
int savePivot = -1;
CoinIndexedVector &early = usefulArray_[ABC_NUMBER_USEFUL - 1];
int *pivotIndices = early.getIndices();
double *pivotValues = early.denseVector();
int pivotCountPosition = early.capacity() - 1;
int numberSaved = 0;
if (numberIterations == 123456789)
savePivot = pivotCountPosition;
;
#endif
numberIterations += numberIterations_;
do {
#if ABC_DEBUG
checkArrays();
#endif
/*
-1 - just move dual in values pass
0 - take iteration
1 - don't take but continue
2 - don't take and break
*/
stateOfIteration_ = 0;
returnCode = -1;
// put row of tableau in usefulArray[arrayForTableauRow_]
/*
Could
a) copy [arrayForBtran_] and start off updateWeights earlier
b) break transposeTimes into two and do after slack part
c) also think if cleaner to go all way with update but just don't do final part
*/
//upperTheta=COIN_DBL_MAX;
double saveAcceptable = acceptablePivot_;
if (largestPrimalError_ > 1.0e-5 || largestDualError_ > 1.0e-5) {
//if ((largestPrimalError_>1.0e-5||largestDualError_>1.0e-5)&&false) {
if (!abcFactorization_->pivots())
acceptablePivot_ *= 1.0e2;
else if (abcFactorization_->pivots() < 5)
acceptablePivot_ *= 1.0e1;
}
#ifdef MOVE_UPDATE_WEIGHTS
// copy btran across
usefulArray_[5].copy(usefulArray_[arrayForBtran_]);
cilk_spawn abcDualRowPivot_->updateWeightsOnly(usefulArray_[5]);
;
#endif
dualColumn1();
acceptablePivot_ = saveAcceptable;
if ((stateOfProblem_ & VALUES_PASS) != 0) {
// see if can just move dual
if (fabs(upperTheta_ - fabs(abcDj_[sequenceOut_])) < dualTolerance_) {
stateOfIteration_ = -1;
}
}
if (!stateOfIteration_) {
#ifndef MOVE_UPDATE_WEIGHTS
cilk_spawn abcDualRowPivot_->updateWeightsOnly(usefulArray_[arrayForBtran_]);
;
#endif
// get sequenceIn_
dualPivotColumn();
//stateOfIteration_=0;
if (sequenceIn_ >= 0) {
// normal iteration
// update the incoming column
//arrayForReplaceColumn_=getAvailableArray();
getTableauColumnFlipAndStartReplaceCilk();
//usleep(1000);
} else if (stateOfIteration_ != -1) {
stateOfIteration_ = 2;
}
}
cilk_sync;
// Check event
{
int status = eventHandler_->event(ClpEventHandler::endOfIteration);
if (status >= 0) {
problemStatus_ = 5;
secondaryStatus_ = ClpEventHandler::endOfIteration;
returnCode = 4;
stateOfIteration_ = 2;
}
}
if (!stateOfIteration_) {
// assert (stateOfIteration_!=1);
int whatNext = 0;
whatNext = housekeeping();
#ifdef EARLY_FACTORIZE
if (savePivot >= 0) {
// save pivot
pivotIndices[--savePivot] = sequenceOut_;
pivotValues[savePivot] = alpha_;
pivotIndices[--savePivot] = sequenceIn_;
pivotValues[savePivot] = btranAlpha_;
numberSaved++;
}
#endif
if (whatNext == 1) {
problemStatus_ = -2; // refactorize
usefulArray_[arrayForTableauRow_].compact();
} else if (whatNext == 2) {
// maximum iterations or equivalent
problemStatus_ = 3;
returnCode = 3;
stateOfIteration_ = 2;
}
#ifdef EARLY_FACTORIZE
if (savePivot >= 0) {
// tell worker can update this
pivotIndices[pivotCountPosition] = numberSaved;
}
#endif
} else {
usefulArray_[arrayForTableauRow_].compact();
if (stateOfIteration_ < 0) {
// move dual in dual values pass
theta_ = abcDj_[sequenceOut_];
updateDualsInDual();
abcDj_[sequenceOut_] = 0.0;
sequenceOut_ = -1;
}
// clear all arrays
clearArrays(-1);
}
// at this stage sequenceIn_ may be <0
if (sequenceIn_ < 0 && sequenceOut_ >= 0) {
usefulArray_[arrayForTableauRow_].compact();
// no incoming column is valid
returnCode = noPivotColumn();
}
if (stateOfIteration_ == 2) {
usefulArray_[arrayForTableauRow_].compact();
sequenceIn_ = -1;
#ifdef ABC_LONG_FACTORIZATION
abcFactorization_->clearHiddenArrays();
#endif
break;
}
if (problemStatus_ != -1) {
#ifndef MOVE_UPDATE_WEIGHTS
abcDualRowPivot_->updateWeights2(usefulArray_[arrayForBtran_], usefulArray_[arrayForFtran_]);
#else
abcDualRowPivot_->updateWeights2(usefulArray_[5], usefulArray_[arrayForFtran_]);
#endif
#ifdef ABC_LONG_FACTORIZATION
abcFactorization_->clearHiddenArrays();
#endif
swapPrimalStuff();
break;
}
if (stateOfIteration_ == 1) {
// clear all arrays
clearArrays(-2);
#ifdef ABC_LONG_FACTORIZATION
abcFactorization_->clearHiddenArrays();
#endif
}
if (stateOfIteration_ == 0) {
// can do these in parallel
// No idea why I need this - but otherwise runs not repeatable (try again??)
//usefulArray_[3].compact();
cilk_spawn updateDualsInDual();
int lastSequenceOut;
int lastDirectionOut;
if (firstFree_ < 0) {
// can do in parallel
cilk_spawn replaceColumnPart3();
updatePrimalSolution();
swapPrimalStuff();
// dualRow will go to virtual row pivot choice algorithm
// make sure values pass off if it should be
// use Btran array and clear inside dualPivotRow (if used)
lastSequenceOut = sequenceOut_;
lastDirectionOut = directionOut_;
dualPivotRow();
cilk_sync;
} else {
// be more careful as dualPivotRow may do update
cilk_spawn replaceColumnPart3();
updatePrimalSolution();
swapPrimalStuff();
// dualRow will go to virtual row pivot choice algorithm
// make sure values pass off if it should be
// use Btran array and clear inside dualPivotRow (if used)
lastSequenceOut = sequenceOut_;
lastDirectionOut = directionOut_;
cilk_sync;
dualPivotRow();
}
lastPivotRow_ = pivotRow_;
if (pivotRow_ >= 0) {
// we found a pivot row
// create as packed
// dual->checkReplacePart1a();
createDualPricingVectorCilk();
swapDualStuff(lastSequenceOut, lastDirectionOut);
}
cilk_sync;
} else {
// after moving dual in values pass
dualPivotRow();
lastPivotRow_ = pivotRow_;
if (pivotRow_ >= 0) {
// we found a pivot row
// create as packed
createDualPricingVectorCilk();
}
}
if (pivotRow_ < 0) {
// no pivot row
clearArrays(-1);
returnCode = noPivotRow();
break;
}
if (numberIterations == numberIterations_ && problemStatus_ == -1) {
returnCode = -99;
break;
}
} while (problemStatus_ == -1);
return returnCode;
}
#if 0
void
AbcSimplexDual::whileIterating2()
{
// get sequenceIn_
dualPivotColumn();
//stateOfIteration_=0;
if (sequenceIn_ >= 0) {
// normal iteration
// update the incoming column
//arrayForReplaceColumn_=getAvailableArray();
getTableauColumnFlipAndStartReplaceCilk();
//usleep(1000);
} else if (stateOfIteration_!=-1) {
stateOfIteration_=2;
}
}
#endif
#endif
void AbcSimplexDual::updatePrimalSolution()
{
// finish doing weights
#ifndef MOVE_UPDATE_WEIGHTS
abcDualRowPivot_->updatePrimalSolutionAndWeights(usefulArray_[arrayForBtran_], usefulArray_[arrayForFtran_],
movement_);
#else
abcDualRowPivot_->updatePrimalSolutionAndWeights(usefulArray_[5], usefulArray_[arrayForFtran_],
movement_);
#endif
}
int xxInfo[6][8];
double parallelDual4(AbcSimplexDual *dual)
{
int maximumRows = dual->maximumAbcNumberRows();
//int numberTotal=dual->numberTotal();
CoinIndexedVector &update = *dual->usefulArray(dual->arrayForBtran());
CoinPartitionedVector &tableauRow = *dual->usefulArray(dual->arrayForTableauRow());
CoinPartitionedVector &candidateList = *dual->usefulArray(dual->arrayForDualColumn());
AbcMatrix *matrix = dual->abcMatrix();
// do slacks first (move before sync)
double upperTheta = dual->upperTheta();
//assert (upperTheta>-100*dual->dualTolerance()||dual->sequenceIn()>=0||dual->lastFirstFree()>=0);
#if ABC_PARALLEL
#define NUMBER_BLOCKS NUMBER_ROW_BLOCKS
int numberBlocks = CoinMin(NUMBER_BLOCKS, dual->numberCpus());
#else
#define NUMBER_BLOCKS 1
int numberBlocks = NUMBER_BLOCKS;
#endif
#if ABC_PARALLEL
if (dual->parallelMode() == 0)
numberBlocks = 1;
#endif
// see if worth using row copy
bool gotRowCopy = matrix->gotRowCopy();
int number = update.getNumElements();
assert(number);
bool useRowCopy = (gotRowCopy && (number << 2) < maximumRows);
assert(numberBlocks == matrix->numberRowBlocks());
#if ABC_PARALLEL == 1
// redo so can pass info in with void *
CoinThreadInfo *infoP = dual->threadInfoPointer();
int cpuMask = ((1 << dual->parallelMode()) - 1);
cpuMask += cpuMask << 5;
dual->setStopStart(cpuMask);
#endif
CoinThreadInfo info[NUMBER_BLOCKS];
const int *starts;
if (useRowCopy)
starts = matrix->blockStart();
else
starts = matrix->startColumnBlock();
tableauRow.setPartitions(numberBlocks, starts);
candidateList.setPartitions(numberBlocks, starts);
//printf("free sequence in %d\n",dual->freeSequenceIn());
if (useRowCopy) {
// using row copy
#if ABC_PARALLEL
if (numberBlocks > 1) {
#if ABC_PARALLEL == 2
for (int i = 0; i < numberBlocks; i++) {
info[i].stuff[1] = i;
info[i].stuff[2] = -1;
info[i].result = upperTheta;
info[i].result = cilk_spawn
matrix->dualColumn1Row(info[i].stuff[1], COIN_DBL_MAX, info[i].stuff[2],
update, tableauRow, candidateList);
}
cilk_sync;
#else
// parallel 1
for (int i = 0; i < numberBlocks; i++) {
info[i].status = 5;
info[i].stuff[1] = i;
info[i].result = upperTheta;
if (i < numberBlocks - 1) {
infoP[i] = info[i];
if (i == numberBlocks - 2)
dual->startParallelStuff(5);
}
}
info[numberBlocks - 1].stuff[1] = numberBlocks - 1;
info[numberBlocks - 1].stuff[2] = -1;
//double freeAlpha;
info[numberBlocks - 1].result = matrix->dualColumn1Row(info[numberBlocks - 1].stuff[1],
upperTheta, info[numberBlocks - 1].stuff[2],
update, tableauRow, candidateList);
dual->stopParallelStuff(5);
for (int i = 0; i < numberBlocks - 1; i++)
info[i] = infoP[i];
#endif
} else {
#endif
info[0].status = 5;
info[0].stuff[1] = 0;
info[0].result = upperTheta;
info[0].stuff[1] = 0;
info[0].stuff[2] = -1;
// worth using row copy
//assert (number>2);
info[0].result = matrix->dualColumn1Row(info[0].stuff[1],
upperTheta, info[0].stuff[2],
update, tableauRow, candidateList);
#if ABC_PARALLEL
}
#endif
} else { // end of useRowCopy
#if ABC_PARALLEL
if (numberBlocks > 1) {
#if ABC_PARALLEL == 2
// do by column
for (int i = 0; i < numberBlocks; i++) {
info[i].stuff[1] = i;
info[i].result = upperTheta;
cilk_spawn
matrix->dualColumn1Part(info[i].stuff[1], info[i].stuff[2],
info[i].result,
update, tableauRow, candidateList);
}
cilk_sync;
#else
// parallel 1
// do by column
for (int i = 0; i < numberBlocks; i++) {
info[i].status = 4;
info[i].stuff[1] = i;
info[i].result = upperTheta;
if (i < numberBlocks - 1) {
infoP[i] = info[i];
if (i == numberBlocks - 2)
dual->startParallelStuff(4);
}
}
matrix->dualColumn1Part(info[numberBlocks - 1].stuff[1], info[numberBlocks - 1].stuff[2],
info[numberBlocks - 1].result,
update, tableauRow, candidateList);
dual->stopParallelStuff(4);
for (int i = 0; i < numberBlocks - 1; i++)
info[i] = infoP[i];
#endif
} else {
#endif
info[0].status = 4;
info[0].stuff[1] = 0;
info[0].result = upperTheta;
info[0].stuff[1] = 0;
matrix->dualColumn1Part(info[0].stuff[1], info[0].stuff[2],
info[0].result,
update, tableauRow, candidateList);
#if ABC_PARALLEL
}
#endif
}
int sequenceIn[NUMBER_BLOCKS];
bool anyFree = false;
#if 0
if (useRowCopy) {
printf("Result at iteration %d slack seqIn %d upperTheta %g\n",
dual->numberIterations(),dual->freeSequenceIn(),upperTheta);
double * arrayT = tableauRow.denseVector();
int * indexT = tableauRow.getIndices();
double * arrayC = candidateList.denseVector();
int * indexC = candidateList.getIndices();
for (int i=0;i<numberBlocks;i++) {
printf("Block %d seqIn %d upperTheta %g first %d last %d firstIn %d nnz %d numrem %d\n",
i,info[i].stuff[2],info[i].result,
xxInfo[0][i],xxInfo[1][i],xxInfo[2][i],xxInfo[3][i],xxInfo[4][i]);
if (xxInfo[3][i]<-35) {
assert (xxInfo[3][i]==tableauRow.getNumElements(i));
assert (xxInfo[4][i]==candidateList.getNumElements(i));
for (int k=0;k<xxInfo[3][i];k++)
printf("T %d %d %g\n",k,indexT[k+xxInfo[2][i]],arrayT[k+xxInfo[2][i]]);
for (int k=0;k<xxInfo[4][i];k++)
printf("C %d %d %g\n",k,indexC[k+xxInfo[2][i]],arrayC[k+xxInfo[2][i]]);
}
}
}
#endif
for (int i = 0; i < numberBlocks; i++) {
sequenceIn[i] = info[i].stuff[2];
if (sequenceIn[i] >= 0)
anyFree = true;
upperTheta = CoinMin(info[i].result, upperTheta);
//assert (info[i].result>-100*dual->dualTolerance()||sequenceIn[i]>=0||dual->lastFirstFree()>=0);
}
if (anyFree) {
int *COIN_RESTRICT index = tableauRow.getIndices();
double *COIN_RESTRICT array = tableauRow.denseVector();
// search for free coming in
double bestFree = 0.0;
int bestSequence = dual->sequenceIn();
if (bestSequence >= 0)
bestFree = dual->alpha();
for (int i = 0; i < numberBlocks; i++) {
int iLook = sequenceIn[i];
if (iLook >= 0) {
// free variable - search
int start = starts[i];
int end = start + tableauRow.getNumElements(i);
for (int k = start; k < end; k++) {
if (iLook == index[k]) {
if (fabs(bestFree) < fabs(array[k])) {
bestFree = array[k];
bestSequence = iLook;
}
break;
}
}
}
}
if (bestSequence >= 0) {
double oldValue = dual->djRegion()[bestSequence];
dual->setSequenceIn(bestSequence);
dual->setAlpha(bestFree);
dual->setTheta(oldValue / bestFree);
}
}
//tableauRow.compact();
//candidateList.compact();
#if 0 //ndef NDEBUG
tableauRow.setPackedMode(true);
tableauRow.sortPacked();
candidateList.setPackedMode(true);
candidateList.sortPacked();
#endif
return upperTheta;
}
#if ABC_PARALLEL == 2
static void
parallelDual5a(AbcSimplexFactorization *factorization,
CoinIndexedVector *whichVector,
int numberCpu,
int whichCpu,
double *weights)
{
double *COIN_RESTRICT array = whichVector->denseVector();
int *COIN_RESTRICT which = whichVector->getIndices();
int numberRows = factorization->numberRows();
for (int i = whichCpu; i < numberRows; i += numberCpu) {
double value = 0.0;
array[i] = 1.0;
which[0] = i;
whichVector->setNumElements(1);
factorization->updateColumnTransposeCpu(*whichVector, whichCpu);
int number = whichVector->getNumElements();
for (int j = 0; j < number; j++) {
int k = which[j];
value += array[k] * array[k];
array[k] = 0.0;
}
weights[i] = value;
}
whichVector->setNumElements(0);
}
#endif
#if ABC_PARALLEL == 2
void parallelDual5(AbcSimplexFactorization *factorization,
CoinIndexedVector **whichVector,
int numberCpu,
int whichCpu,
double *weights)
{
if (whichCpu) {
cilk_spawn parallelDual5(factorization, whichVector, numberCpu, whichCpu - 1, weights);
parallelDual5a(factorization, whichVector[whichCpu], numberCpu, whichCpu, weights);
cilk_sync;
} else {
parallelDual5a(factorization, whichVector[whichCpu], numberCpu, whichCpu, weights);
}
}
#endif
// cilk seems a bit fragile
#define CILK_FRAGILE 1
#if CILK_FRAGILE > 1
#undef cilk_spawn
#undef cilk_sync
#define cilk_spawn
#define cilk_sync
#define ONWARD 0
#elif CILK_FRAGILE == 1
#define ONWARD 0
#else
#define ONWARD 1
#endif
// Code below is just a translation of LAPACK
#define BLOCKING1 8 // factorization strip
#define BLOCKING2 8 // dgemm recursive
#define BLOCKING3 16 // dgemm parallel
/* type
0 Left Lower NoTranspose Unit
1 Left Upper NoTranspose NonUnit
2 Left Lower Transpose Unit
3 Left Upper Transpose NonUnit
*/
static void CoinAbcDtrsmFactor(int m, int n, double *COIN_RESTRICT a, int lda)
{
assert((m & (BLOCKING8 - 1)) == 0 && (n & (BLOCKING8 - 1)) == 0);
assert(m == BLOCKING8);
// 0 Left Lower NoTranspose Unit
/* entry for column j and row i (when multiple of BLOCKING8)
is at aBlocked+j*m+i*BLOCKING8
*/
double *COIN_RESTRICT aBase2 = a;
double *COIN_RESTRICT bBase2 = aBase2 + lda * BLOCKING8;
for (int jj = 0; jj < n; jj += BLOCKING8) {
double *COIN_RESTRICT bBase = bBase2;
for (int j = jj; j < jj + BLOCKING8; j++) {
#if 0
double * COIN_RESTRICT aBase = aBase2;
for (int k=0;k<BLOCKING8;k++) {
double bValue = bBase[k];
if (bValue) {
for (int i=k+1;i<BLOCKING8;i++) {
bBase[i]-=bValue*aBase[i];
}
}
aBase+=BLOCKING8;
}
#else
// unroll - stay in registers - don't test for zeros
assert(BLOCKING8 == 8);
double bValue0 = bBase[0];
double bValue1 = bBase[1];
double bValue2 = bBase[2];
double bValue3 = bBase[3];
double bValue4 = bBase[4];
double bValue5 = bBase[5];
double bValue6 = bBase[6];
double bValue7 = bBase[7];
bValue1 -= bValue0 * a[1 + 0 * BLOCKING8];
bBase[1] = bValue1;
bValue2 -= bValue0 * a[2 + 0 * BLOCKING8];
bValue3 -= bValue0 * a[3 + 0 * BLOCKING8];
bValue4 -= bValue0 * a[4 + 0 * BLOCKING8];
bValue5 -= bValue0 * a[5 + 0 * BLOCKING8];
bValue6 -= bValue0 * a[6 + 0 * BLOCKING8];
bValue7 -= bValue0 * a[7 + 0 * BLOCKING8];
bValue2 -= bValue1 * a[2 + 1 * BLOCKING8];
bBase[2] = bValue2;
bValue3 -= bValue1 * a[3 + 1 * BLOCKING8];
bValue4 -= bValue1 * a[4 + 1 * BLOCKING8];
bValue5 -= bValue1 * a[5 + 1 * BLOCKING8];
bValue6 -= bValue1 * a[6 + 1 * BLOCKING8];
bValue7 -= bValue1 * a[7 + 1 * BLOCKING8];
bValue3 -= bValue2 * a[3 + 2 * BLOCKING8];
bBase[3] = bValue3;
bValue4 -= bValue2 * a[4 + 2 * BLOCKING8];
bValue5 -= bValue2 * a[5 + 2 * BLOCKING8];
bValue6 -= bValue2 * a[6 + 2 * BLOCKING8];
bValue7 -= bValue2 * a[7 + 2 * BLOCKING8];
bValue4 -= bValue3 * a[4 + 3 * BLOCKING8];
bBase[4] = bValue4;
bValue5 -= bValue3 * a[5 + 3 * BLOCKING8];
bValue6 -= bValue3 * a[6 + 3 * BLOCKING8];
bValue7 -= bValue3 * a[7 + 3 * BLOCKING8];
bValue5 -= bValue4 * a[5 + 4 * BLOCKING8];
bBase[5] = bValue5;
bValue6 -= bValue4 * a[6 + 4 * BLOCKING8];
bValue7 -= bValue4 * a[7 + 4 * BLOCKING8];
bValue6 -= bValue5 * a[6 + 5 * BLOCKING8];
bBase[6] = bValue6;
bValue7 -= bValue5 * a[7 + 5 * BLOCKING8];
bValue7 -= bValue6 * a[7 + 6 * BLOCKING8];
bBase[7] = bValue7;
#endif
bBase += BLOCKING8;
}
bBase2 += lda * BLOCKING8;
}
}
#define UNROLL_DTRSM 16
#define CILK_DTRSM 32
static void dtrsm0(int kkk, int first, int last,
int m, double *COIN_RESTRICT a, double *COIN_RESTRICT b)
{
int mm = CoinMin(kkk + UNROLL_DTRSM * BLOCKING8, m);
assert((last - first) % BLOCKING8 == 0);
if (last - first > CILK_DTRSM) {
int mid = ((first + last) >> 4) << 3;
cilk_spawn dtrsm0(kkk, first, mid, m, a, b);
dtrsm0(kkk, mid, last, m, a, b);
cilk_sync;
} else {
const double *COIN_RESTRICT aBaseA = a + UNROLL_DTRSM * BLOCKING8X8 + kkk * BLOCKING8;
aBaseA += (first - mm) * BLOCKING8 - BLOCKING8X8;
aBaseA += m * kkk;
for (int ii = first; ii < last; ii += BLOCKING8) {
aBaseA += BLOCKING8X8;
const double *COIN_RESTRICT aBaseB = aBaseA;
double *COIN_RESTRICT bBaseI = b + ii;
for (int kk = kkk; kk < mm; kk += BLOCKING8) {
double *COIN_RESTRICT bBase = b + kk;
const double *COIN_RESTRICT aBase2 = aBaseB; //a+UNROLL_DTRSM*BLOCKING8X8+m*kk+kkk*BLOCKING8;
//aBase2 += (ii-mm)*BLOCKING8;
//assert (aBase2==aBaseB);
aBaseB += m * BLOCKING8;
#if AVX2 != 2
#define ALTERNATE_INNER
#ifndef ALTERNATE_INNER
for (int k = 0; k < BLOCKING8; k++) {
//coin_prefetch_const(aBase2+BLOCKING8);
for (int i = 0; i < BLOCKING8; i++) {
bBaseI[i] -= bBase[k] * aBase2[i];
}
aBase2 += BLOCKING8;
}
#else
double b0 = bBaseI[0];
double b1 = bBaseI[1];
double b2 = bBaseI[2];
double b3 = bBaseI[3];
double b4 = bBaseI[4];
double b5 = bBaseI[5];
double b6 = bBaseI[6];
double b7 = bBaseI[7];
for (int k = 0; k < BLOCKING8; k++) {
//coin_prefetch_const(aBase2+BLOCKING8);
double bValue = bBase[k];
b0 -= bValue * aBase2[0];
b1 -= bValue * aBase2[1];
b2 -= bValue * aBase2[2];
b3 -= bValue * aBase2[3];
b4 -= bValue * aBase2[4];
b5 -= bValue * aBase2[5];
b6 -= bValue * aBase2[6];
b7 -= bValue * aBase2[7];
aBase2 += BLOCKING8;
}
bBaseI[0] = b0;
bBaseI[1] = b1;
bBaseI[2] = b2;
bBaseI[3] = b3;
bBaseI[4] = b4;
bBaseI[5] = b5;
bBaseI[6] = b6;
bBaseI[7] = b7;
#endif
#else
__m256d b0 = _mm256_load_pd(bBaseI);
__m256d b1 = _mm256_load_pd(bBaseI + 4);
for (int k = 0; k < BLOCKING8; k++) {
//coin_prefetch_const(aBase2+BLOCKING8);
__m256d bb = _mm256_broadcast_sd(bBase + k);
__m256d a0 = _mm256_load_pd(aBase2);
b0 -= a0 * bb;
__m256d a1 = _mm256_load_pd(aBase2 + 4);
b1 -= a1 * bb;
aBase2 += BLOCKING8;
}
//_mm256_store_pd ((bBaseI), (b0));
*reinterpret_cast< __m256d * >(bBaseI) = b0;
//_mm256_store_pd (bBaseI+4, b1);
*reinterpret_cast< __m256d * >(bBaseI + 4) = b1;
#endif
}
}
}
}
void CoinAbcDtrsm0(int m, double *COIN_RESTRICT a, double *COIN_RESTRICT b)
{
assert((m & (BLOCKING8 - 1)) == 0);
// 0 Left Lower NoTranspose Unit
for (int kkk = 0; kkk < m; kkk += UNROLL_DTRSM * BLOCKING8) {
int mm = CoinMin(m, kkk + UNROLL_DTRSM * BLOCKING8);
for (int kk = kkk; kk < mm; kk += BLOCKING8) {
const double *COIN_RESTRICT aBase2 = a + kk * (m + BLOCKING8);
double *COIN_RESTRICT bBase = b + kk;
for (int k = 0; k < BLOCKING8; k++) {
for (int i = k + 1; i < BLOCKING8; i++) {
bBase[i] -= bBase[k] * aBase2[i];
}
aBase2 += BLOCKING8;
}
for (int ii = kk + BLOCKING8; ii < mm; ii += BLOCKING8) {
double *COIN_RESTRICT bBaseI = b + ii;
for (int k = 0; k < BLOCKING8; k++) {
//coin_prefetch_const(aBase2+BLOCKING8);
for (int i = 0; i < BLOCKING8; i++) {
bBaseI[i] -= bBase[k] * aBase2[i];
}
aBase2 += BLOCKING8;
}
}
}
dtrsm0(kkk, mm, m, m, a, b);
}
}
static void dtrsm1(int kkk, int first, int last,
int m, double *COIN_RESTRICT a, double *COIN_RESTRICT b)
{
int mm = CoinMax(0, kkk - (UNROLL_DTRSM - 1) * BLOCKING8);
assert((last - first) % BLOCKING8 == 0);
if (last - first > CILK_DTRSM) {
int mid = ((first + last) >> 4) << 3;
cilk_spawn dtrsm1(kkk, first, mid, m, a, b);
dtrsm1(kkk, mid, last, m, a, b);
cilk_sync;
} else {
for (int iii = last - BLOCKING8; iii >= first; iii -= BLOCKING8) {
double *COIN_RESTRICT bBase2 = b + iii;
const double *COIN_RESTRICT aBaseA = a + BLOCKING8X8 + BLOCKING8 * iii;
for (int ii = kkk; ii >= mm; ii -= BLOCKING8) {
double *COIN_RESTRICT bBase = b + ii;
const double *COIN_RESTRICT aBase = aBaseA + m * ii;
#if AVX2 != 2
#ifndef ALTERNATE_INNER
for (int i = BLOCKING8 - 1; i >= 0; i--) {
aBase -= BLOCKING8;
//coin_prefetch_const(aBase-BLOCKING8);
for (int k = BLOCKING8 - 1; k >= 0; k--) {
bBase2[k] -= bBase[i] * aBase[k];
}
}
#else
double b0 = bBase2[0];
double b1 = bBase2[1];
double b2 = bBase2[2];
double b3 = bBase2[3];
double b4 = bBase2[4];
double b5 = bBase2[5];
double b6 = bBase2[6];
double b7 = bBase2[7];
for (int i = BLOCKING8 - 1; i >= 0; i--) {
aBase -= BLOCKING8;
//coin_prefetch_const(aBase-BLOCKING8);
double bValue = bBase[i];
b0 -= bValue * aBase[0];
b1 -= bValue * aBase[1];
b2 -= bValue * aBase[2];
b3 -= bValue * aBase[3];
b4 -= bValue * aBase[4];
b5 -= bValue * aBase[5];
b6 -= bValue * aBase[6];
b7 -= bValue * aBase[7];
}
bBase2[0] = b0;
bBase2[1] = b1;
bBase2[2] = b2;
bBase2[3] = b3;
bBase2[4] = b4;
bBase2[5] = b5;
bBase2[6] = b6;
bBase2[7] = b7;
#endif
#else
__m256d b0 = _mm256_load_pd(bBase2);
__m256d b1 = _mm256_load_pd(bBase2 + 4);
for (int i = BLOCKING8 - 1; i >= 0; i--) {
aBase -= BLOCKING8;
//coin_prefetch_const(aBase5-BLOCKING8);
__m256d bb = _mm256_broadcast_sd(bBase + i);
__m256d a0 = _mm256_load_pd(aBase);
b0 -= a0 * bb;
__m256d a1 = _mm256_load_pd(aBase + 4);
b1 -= a1 * bb;
}
//_mm256_store_pd (bBase2, b0);
*reinterpret_cast< __m256d * >(bBase2) = b0;
//_mm256_store_pd (bBase2+4, b1);
*reinterpret_cast< __m256d * >(bBase2 + 4) = b1;
#endif
}
}
}
}
void CoinAbcDtrsm1(int m, double *COIN_RESTRICT a, double *COIN_RESTRICT b)
{
assert((m & (BLOCKING8 - 1)) == 0);
// 1 Left Upper NoTranspose NonUnit
for (int kkk = m - BLOCKING8; kkk >= 0; kkk -= UNROLL_DTRSM * BLOCKING8) {
int mm = CoinMax(0, kkk - (UNROLL_DTRSM - 1) * BLOCKING8);
for (int ii = kkk; ii >= mm; ii -= BLOCKING8) {
const double *COIN_RESTRICT aBase = a + m * ii + ii * BLOCKING8;
double *COIN_RESTRICT bBase = b + ii;
for (int i = BLOCKING8 - 1; i >= 0; i--) {
bBase[i] *= aBase[i * (BLOCKING8 + 1)];
for (int k = i - 1; k >= 0; k--) {
bBase[k] -= bBase[i] * aBase[k + i * BLOCKING8];
}
}
double *COIN_RESTRICT bBase2 = bBase;
for (int iii = ii; iii > mm; iii -= BLOCKING8) {
bBase2 -= BLOCKING8;
for (int i = BLOCKING8 - 1; i >= 0; i--) {
aBase -= BLOCKING8;
coin_prefetch_const(aBase - BLOCKING8);
for (int k = BLOCKING8 - 1; k >= 0; k--) {
bBase2[k] -= bBase[i] * aBase[k];
}
}
}
}
dtrsm1(kkk, 0, mm, m, a, b);
}
}
static void dtrsm2(int kkk, int first, int last,
int m, double *COIN_RESTRICT a, double *COIN_RESTRICT b)
{
int mm = CoinMax(0, kkk - (UNROLL_DTRSM - 1) * BLOCKING8);
assert((last - first) % BLOCKING8 == 0);
if (last - first > CILK_DTRSM) {
int mid = ((first + last) >> 4) << 3;
cilk_spawn dtrsm2(kkk, first, mid, m, a, b);
dtrsm2(kkk, mid, last, m, a, b);
cilk_sync;
} else {
for (int iii = last - BLOCKING8; iii >= first; iii -= BLOCKING8) {
for (int ii = kkk; ii >= mm; ii -= BLOCKING8) {
const double *COIN_RESTRICT bBase = b + ii;
double *COIN_RESTRICT bBase2 = b + iii;
const double *COIN_RESTRICT aBase = a + ii * BLOCKING8 + m * iii + BLOCKING8X8;
for (int j = BLOCKING8 - 1; j >= 0; j -= 4) {
double bValue0 = bBase2[j];
double bValue1 = bBase2[j - 1];
double bValue2 = bBase2[j - 2];
double bValue3 = bBase2[j - 3];
bValue0 -= aBase[-1 * BLOCKING8 + 7] * bBase[7];
bValue1 -= aBase[-2 * BLOCKING8 + 7] * bBase[7];
bValue2 -= aBase[-3 * BLOCKING8 + 7] * bBase[7];
bValue3 -= aBase[-4 * BLOCKING8 + 7] * bBase[7];
bValue0 -= aBase[-1 * BLOCKING8 + 6] * bBase[6];
bValue1 -= aBase[-2 * BLOCKING8 + 6] * bBase[6];
bValue2 -= aBase[-3 * BLOCKING8 + 6] * bBase[6];
bValue3 -= aBase[-4 * BLOCKING8 + 6] * bBase[6];
bValue0 -= aBase[-1 * BLOCKING8 + 5] * bBase[5];
bValue1 -= aBase[-2 * BLOCKING8 + 5] * bBase[5];
bValue2 -= aBase[-3 * BLOCKING8 + 5] * bBase[5];
bValue3 -= aBase[-4 * BLOCKING8 + 5] * bBase[5];
bValue0 -= aBase[-1 * BLOCKING8 + 4] * bBase[4];
bValue1 -= aBase[-2 * BLOCKING8 + 4] * bBase[4];
bValue2 -= aBase[-3 * BLOCKING8 + 4] * bBase[4];
bValue3 -= aBase[-4 * BLOCKING8 + 4] * bBase[4];
bValue0 -= aBase[-1 * BLOCKING8 + 3] * bBase[3];
bValue1 -= aBase[-2 * BLOCKING8 + 3] * bBase[3];
bValue2 -= aBase[-3 * BLOCKING8 + 3] * bBase[3];
bValue3 -= aBase[-4 * BLOCKING8 + 3] * bBase[3];
bValue0 -= aBase[-1 * BLOCKING8 + 2] * bBase[2];
bValue1 -= aBase[-2 * BLOCKING8 + 2] * bBase[2];
bValue2 -= aBase[-3 * BLOCKING8 + 2] * bBase[2];
bValue3 -= aBase[-4 * BLOCKING8 + 2] * bBase[2];
bValue0 -= aBase[-1 * BLOCKING8 + 1] * bBase[1];
bValue1 -= aBase[-2 * BLOCKING8 + 1] * bBase[1];
bValue2 -= aBase[-3 * BLOCKING8 + 1] * bBase[1];
bValue3 -= aBase[-4 * BLOCKING8 + 1] * bBase[1];
bValue0 -= aBase[-1 * BLOCKING8 + 0] * bBase[0];
bValue1 -= aBase[-2 * BLOCKING8 + 0] * bBase[0];
bValue2 -= aBase[-3 * BLOCKING8 + 0] * bBase[0];
bValue3 -= aBase[-4 * BLOCKING8 + 0] * bBase[0];
bBase2[j] = bValue0;
bBase2[j - 1] = bValue1;
bBase2[j - 2] = bValue2;
bBase2[j - 3] = bValue3;
aBase -= 4 * BLOCKING8;
}
}
}
}
}
void CoinAbcDtrsm2(int m, double *COIN_RESTRICT a, double *COIN_RESTRICT b)
{
assert((m & (BLOCKING8 - 1)) == 0);
// 2 Left Lower Transpose Unit
for (int kkk = m - BLOCKING8; kkk >= 0; kkk -= UNROLL_DTRSM * BLOCKING8) {
int mm = CoinMax(0, kkk - (UNROLL_DTRSM - 1) * BLOCKING8);
for (int ii = kkk; ii >= mm; ii -= BLOCKING8) {
double *COIN_RESTRICT bBase = b + ii;
double *COIN_RESTRICT bBase2 = bBase;
const double *COIN_RESTRICT aBase = a + m * ii + (ii + BLOCKING8) * BLOCKING8;
for (int i = BLOCKING8 - 1; i >= 0; i--) {
aBase -= BLOCKING8;
for (int k = i + 1; k < BLOCKING8; k++) {
bBase2[i] -= aBase[k] * bBase2[k];
}
}
for (int iii = ii - BLOCKING8; iii >= mm; iii -= BLOCKING8) {
bBase2 -= BLOCKING8;
assert(bBase2 == b + iii);
aBase -= m * BLOCKING8;
const double *COIN_RESTRICT aBase2 = aBase + BLOCKING8X8;
for (int i = BLOCKING8 - 1; i >= 0; i--) {
aBase2 -= BLOCKING8;
for (int k = BLOCKING8 - 1; k >= 0; k--) {
bBase2[i] -= aBase2[k] * bBase[k];
}
}
}
}
dtrsm2(kkk, 0, mm, m, a, b);
}
}
#define UNROLL_DTRSM3 16
#define CILK_DTRSM3 32
static void dtrsm3(int kkk, int first, int last,
int m, double *COIN_RESTRICT a, double *COIN_RESTRICT b)
{
//int mm=CoinMin(kkk+UNROLL_DTRSM3*BLOCKING8,m);
assert((last - first) % BLOCKING8 == 0);
if (last - first > CILK_DTRSM3) {
int mid = ((first + last) >> 4) << 3;
cilk_spawn dtrsm3(kkk, first, mid, m, a, b);
dtrsm3(kkk, mid, last, m, a, b);
cilk_sync;
} else {
for (int kk = 0; kk < kkk; kk += BLOCKING8) {
for (int ii = first; ii < last; ii += BLOCKING8) {
double *COIN_RESTRICT bBase = b + ii;
double *COIN_RESTRICT bBase2 = b + kk;
const double *COIN_RESTRICT aBase = a + ii * m + kk * BLOCKING8;
for (int j = 0; j < BLOCKING8; j += 4) {
double bValue0 = bBase[j];
double bValue1 = bBase[j + 1];
double bValue2 = bBase[j + 2];
double bValue3 = bBase[j + 3];
bValue0 -= aBase[0] * bBase2[0];
bValue1 -= aBase[1 * BLOCKING8 + 0] * bBase2[0];
bValue2 -= aBase[2 * BLOCKING8 + 0] * bBase2[0];
bValue3 -= aBase[3 * BLOCKING8 + 0] * bBase2[0];
bValue0 -= aBase[1] * bBase2[1];
bValue1 -= aBase[1 * BLOCKING8 + 1] * bBase2[1];
bValue2 -= aBase[2 * BLOCKING8 + 1] * bBase2[1];
bValue3 -= aBase[3 * BLOCKING8 + 1] * bBase2[1];
bValue0 -= aBase[2] * bBase2[2];
bValue1 -= aBase[1 * BLOCKING8 + 2] * bBase2[2];
bValue2 -= aBase[2 * BLOCKING8 + 2] * bBase2[2];
bValue3 -= aBase[3 * BLOCKING8 + 2] * bBase2[2];
bValue0 -= aBase[3] * bBase2[3];
bValue1 -= aBase[1 * BLOCKING8 + 3] * bBase2[3];
bValue2 -= aBase[2 * BLOCKING8 + 3] * bBase2[3];
bValue3 -= aBase[3 * BLOCKING8 + 3] * bBase2[3];
bValue0 -= aBase[4] * bBase2[4];
bValue1 -= aBase[1 * BLOCKING8 + 4] * bBase2[4];
bValue2 -= aBase[2 * BLOCKING8 + 4] * bBase2[4];
bValue3 -= aBase[3 * BLOCKING8 + 4] * bBase2[4];
bValue0 -= aBase[5] * bBase2[5];
bValue1 -= aBase[1 * BLOCKING8 + 5] * bBase2[5];
bValue2 -= aBase[2 * BLOCKING8 + 5] * bBase2[5];
bValue3 -= aBase[3 * BLOCKING8 + 5] * bBase2[5];
bValue0 -= aBase[6] * bBase2[6];
bValue1 -= aBase[1 * BLOCKING8 + 6] * bBase2[6];
bValue2 -= aBase[2 * BLOCKING8 + 7] * bBase2[7];
bValue3 -= aBase[3 * BLOCKING8 + 6] * bBase2[6];
bValue0 -= aBase[7] * bBase2[7];
bValue1 -= aBase[1 * BLOCKING8 + 7] * bBase2[7];
bValue2 -= aBase[2 * BLOCKING8 + 6] * bBase2[6];
bValue3 -= aBase[3 * BLOCKING8 + 7] * bBase2[7];
bBase[j] = bValue0;
bBase[j + 1] = bValue1;
bBase[j + 2] = bValue2;
bBase[j + 3] = bValue3;
aBase += 4 * BLOCKING8;
}
}
}
}
}
void CoinAbcDtrsm3(int m, double *COIN_RESTRICT a, double *COIN_RESTRICT b)
{
assert((m & (BLOCKING8 - 1)) == 0);
// 3 Left Upper Transpose NonUnit
for (int kkk = 0; kkk < m; kkk += UNROLL_DTRSM3 * BLOCKING8) {
int mm = CoinMin(m, kkk + UNROLL_DTRSM3 * BLOCKING8);
dtrsm3(kkk, kkk, mm, m, a, b);
for (int ii = kkk; ii < mm; ii += BLOCKING8) {
double *COIN_RESTRICT bBase = b + ii;
for (int kk = kkk; kk < ii; kk += BLOCKING8) {
double *COIN_RESTRICT bBase2 = b + kk;
const double *COIN_RESTRICT aBase = a + ii * m + kk * BLOCKING8;
for (int i = 0; i < BLOCKING8; i++) {
for (int k = 0; k < BLOCKING8; k++) {
bBase[i] -= aBase[k] * bBase2[k];
}
aBase += BLOCKING8;
}
}
const double *COIN_RESTRICT aBase = a + ii * m + ii * BLOCKING8;
for (int i = 0; i < BLOCKING8; i++) {
for (int k = 0; k < i; k++) {
bBase[i] -= aBase[k] * bBase[k];
}
bBase[i] = bBase[i] * aBase[i];
aBase += BLOCKING8;
}
}
}
}
static void
CoinAbcDlaswp(int n, double *COIN_RESTRICT a, int lda, int start, int end, int *ipiv)
{
assert((n & (BLOCKING8 - 1)) == 0);
double *COIN_RESTRICT aThis3 = a;
for (int j = 0; j < n; j += BLOCKING8) {
for (int i = start; i < end; i++) {
int ip = ipiv[i];
if (ip != i) {
double *COIN_RESTRICT aTop = aThis3 + j * lda;
int iBias = ip / BLOCKING8;
ip -= iBias * BLOCKING8;
double *COIN_RESTRICT aNotTop = aTop + iBias * BLOCKING8X8;
iBias = i / BLOCKING8;
int i2 = i - iBias * BLOCKING8;
aTop += iBias * BLOCKING8X8;
for (int k = 0; k < BLOCKING8; k++) {
double temp = aTop[i2];
aTop[i2] = aNotTop[ip];
aNotTop[ip] = temp;
aTop += BLOCKING8;
aNotTop += BLOCKING8;
}
}
}
}
}
extern void CoinAbcDgemm(int m, int n, int k, double *COIN_RESTRICT a, int lda,
double *COIN_RESTRICT b, double *COIN_RESTRICT c
#if ABC_PARALLEL == 2
,
int parallelMode
#endif
);
static int CoinAbcDgetrf2(int m, int n, double *COIN_RESTRICT a, int *ipiv)
{
assert((m & (BLOCKING8 - 1)) == 0 && (n & (BLOCKING8 - 1)) == 0);
assert(n == BLOCKING8);
int dimension = CoinMin(m, n);
/* entry for column j and row i (when multiple of BLOCKING8)
is at aBlocked+j*m+i*BLOCKING8
*/
assert(dimension == BLOCKING8);
//printf("Dgetrf2 m=%d n=%d\n",m,n);
double *COIN_RESTRICT aThis3 = a;
for (int j = 0; j < dimension; j++) {
int pivotRow = -1;
double largest = 0.0;
double *COIN_RESTRICT aThis2 = aThis3 + j * BLOCKING8;
// this block
int pivotRow2 = -1;
for (int i = j; i < BLOCKING8; i++) {
double value = fabs(aThis2[i]);
if (value > largest) {
largest = value;
pivotRow2 = i;
}
}
// other blocks
int iBias = 0;
for (int ii = BLOCKING8; ii < m; ii += BLOCKING8) {
aThis2 += BLOCKING8 * BLOCKING8;
for (int i = 0; i < BLOCKING8; i++) {
double value = fabs(aThis2[i]);
if (value > largest) {
largest = value;
pivotRow2 = i;
iBias = ii;
}
}
}
pivotRow = pivotRow2 + iBias;
ipiv[j] = pivotRow;
if (largest) {
if (j != pivotRow) {
double *COIN_RESTRICT aTop = aThis3;
double *COIN_RESTRICT aNotTop = aThis3 + iBias * BLOCKING8;
for (int i = 0; i < n; i++) {
double value = aTop[j];
aTop[j] = aNotTop[pivotRow2];
aNotTop[pivotRow2] = value;
aTop += BLOCKING8;
aNotTop += BLOCKING8;
}
}
aThis2 = aThis3 + j * BLOCKING8;
double pivotMultiplier = 1.0 / aThis2[j];
aThis2[j] = pivotMultiplier;
// Do L
// this block
for (int i = j + 1; i < BLOCKING8; i++)
aThis2[i] *= pivotMultiplier;
// other blocks
for (int ii = BLOCKING8; ii < m; ii += BLOCKING8) {
aThis2 += BLOCKING8 * BLOCKING8;
for (int i = 0; i < BLOCKING8; i++)
aThis2[i] *= pivotMultiplier;
}
// update rest
double *COIN_RESTRICT aPut;
aThis2 = aThis3 + j * BLOCKING8;
aPut = aThis2 + BLOCKING8;
double *COIN_RESTRICT aPut2 = aPut;
// this block
for (int i = j + 1; i < BLOCKING8; i++) {
double value = aPut[j];
for (int k = j + 1; k < BLOCKING8; k++)
aPut[k] -= value * aThis2[k];
aPut += BLOCKING8;
}
// other blocks
for (int ii = BLOCKING8; ii < m; ii += BLOCKING8) {
aThis2 += BLOCKING8 * BLOCKING8;
aPut = aThis2 + BLOCKING8;
double *COIN_RESTRICT aPut2a = aPut2;
for (int i = j + 1; i < BLOCKING8; i++) {
double value = aPut2a[j];
for (int k = 0; k < BLOCKING8; k++)
aPut[k] -= value * aThis2[k];
aPut += BLOCKING8;
aPut2a += BLOCKING8;
}
}
} else {
return 1;
}
}
return 0;
}
int CoinAbcDgetrf(int m, int n, double *COIN_RESTRICT a, int lda, int *ipiv
#if ABC_PARALLEL == 2
,
int parallelMode
#endif
)
{
assert(m == n);
assert((m & (BLOCKING8 - 1)) == 0 && (n & (BLOCKING8 - 1)) == 0);
if (m < BLOCKING8) {
return CoinAbcDgetrf2(m, n, a, ipiv);
} else {
for (int j = 0; j < n; j += BLOCKING8) {
int start = j;
int newSize = CoinMin(BLOCKING8, n - j);
int end = j + newSize;
int returnCode = CoinAbcDgetrf2(m - start, newSize, a + (start * lda + start * BLOCKING8),
ipiv + start);
if (!returnCode) {
// adjust
for (int k = start; k < end; k++)
ipiv[k] += start;
// swap 0<start
CoinAbcDlaswp(start, a, lda, start, end, ipiv);
if (end < n) {
// swap >=end
CoinAbcDlaswp(n - end, a + end * lda, lda, start, end, ipiv);
CoinAbcDtrsmFactor(newSize, n - end, a + (start * lda + start * BLOCKING8), lda);
CoinAbcDgemm(n - end, n - end, newSize,
a + start * lda + end * BLOCKING8, lda,
a + end * lda + start * BLOCKING8, a + end * lda + end * BLOCKING8
#if ABC_PARALLEL == 2
,
parallelMode
#endif
);
}
} else {
return returnCode;
}
}
}
return 0;
}
void CoinAbcDgetrs(char trans, int m, double *COIN_RESTRICT a, double *COIN_RESTRICT work)
{
assert((m & (BLOCKING8 - 1)) == 0);
if (trans == 'N') {
//CoinAbcDlaswp1(work,m,ipiv);
CoinAbcDtrsm0(m, a, work);
CoinAbcDtrsm1(m, a, work);
} else {
assert(trans == 'T');
CoinAbcDtrsm3(m, a, work);
CoinAbcDtrsm2(m, a, work);
//CoinAbcDlaswp1Backwards(work,m,ipiv);
}
}
#ifdef ABC_LONG_FACTORIZATION
/// ****** Start long double version
/* type
0 Left Lower NoTranspose Unit
1 Left Upper NoTranspose NonUnit
2 Left Lower Transpose Unit
3 Left Upper Transpose NonUnit
*/
static void CoinAbcDtrsmFactor(int m, int n, long double *COIN_RESTRICT a, int lda)
{
assert((m & (BLOCKING8 - 1)) == 0 && (n & (BLOCKING8 - 1)) == 0);
assert(m == BLOCKING8);
// 0 Left Lower NoTranspose Unit
/* entry for column j and row i (when multiple of BLOCKING8)
is at aBlocked+j*m+i*BLOCKING8
*/
long double *COIN_RESTRICT aBase2 = a;
long double *COIN_RESTRICT bBase2 = aBase2 + lda * BLOCKING8;
for (int jj = 0; jj < n; jj += BLOCKING8) {
long double *COIN_RESTRICT bBase = bBase2;
for (int j = jj; j < jj + BLOCKING8; j++) {
#if 0
long double * COIN_RESTRICT aBase = aBase2;
for (int k=0;k<BLOCKING8;k++) {
long double bValue = bBase[k];
if (bValue) {
for (int i=k+1;i<BLOCKING8;i++) {
bBase[i]-=bValue*aBase[i];
}
}
aBase+=BLOCKING8;
}
#else
// unroll - stay in registers - don't test for zeros
assert(BLOCKING8 == 8);
long double bValue0 = bBase[0];
long double bValue1 = bBase[1];
long double bValue2 = bBase[2];
long double bValue3 = bBase[3];
long double bValue4 = bBase[4];
long double bValue5 = bBase[5];
long double bValue6 = bBase[6];
long double bValue7 = bBase[7];
bValue1 -= bValue0 * a[1 + 0 * BLOCKING8];
bBase[1] = bValue1;
bValue2 -= bValue0 * a[2 + 0 * BLOCKING8];
bValue3 -= bValue0 * a[3 + 0 * BLOCKING8];
bValue4 -= bValue0 * a[4 + 0 * BLOCKING8];
bValue5 -= bValue0 * a[5 + 0 * BLOCKING8];
bValue6 -= bValue0 * a[6 + 0 * BLOCKING8];
bValue7 -= bValue0 * a[7 + 0 * BLOCKING8];
bValue2 -= bValue1 * a[2 + 1 * BLOCKING8];
bBase[2] = bValue2;
bValue3 -= bValue1 * a[3 + 1 * BLOCKING8];
bValue4 -= bValue1 * a[4 + 1 * BLOCKING8];
bValue5 -= bValue1 * a[5 + 1 * BLOCKING8];
bValue6 -= bValue1 * a[6 + 1 * BLOCKING8];
bValue7 -= bValue1 * a[7 + 1 * BLOCKING8];
bValue3 -= bValue2 * a[3 + 2 * BLOCKING8];
bBase[3] = bValue3;
bValue4 -= bValue2 * a[4 + 2 * BLOCKING8];
bValue5 -= bValue2 * a[5 + 2 * BLOCKING8];
bValue6 -= bValue2 * a[6 + 2 * BLOCKING8];
bValue7 -= bValue2 * a[7 + 2 * BLOCKING8];
bValue4 -= bValue3 * a[4 + 3 * BLOCKING8];
bBase[4] = bValue4;
bValue5 -= bValue3 * a[5 + 3 * BLOCKING8];
bValue6 -= bValue3 * a[6 + 3 * BLOCKING8];
bValue7 -= bValue3 * a[7 + 3 * BLOCKING8];
bValue5 -= bValue4 * a[5 + 4 * BLOCKING8];
bBase[5] = bValue5;
bValue6 -= bValue4 * a[6 + 4 * BLOCKING8];
bValue7 -= bValue4 * a[7 + 4 * BLOCKING8];
bValue6 -= bValue5 * a[6 + 5 * BLOCKING8];
bBase[6] = bValue6;
bValue7 -= bValue5 * a[7 + 5 * BLOCKING8];
bValue7 -= bValue6 * a[7 + 6 * BLOCKING8];
bBase[7] = bValue7;
#endif
bBase += BLOCKING8;
}
bBase2 += lda * BLOCKING8;
}
}
#define UNROLL_DTRSM 16
#define CILK_DTRSM 32
static void dtrsm0(int kkk, int first, int last,
int m, long double *COIN_RESTRICT a, long double *COIN_RESTRICT b)
{
int mm = CoinMin(kkk + UNROLL_DTRSM * BLOCKING8, m);
assert((last - first) % BLOCKING8 == 0);
if (last - first > CILK_DTRSM) {
int mid = ((first + last) >> 4) << 3;
cilk_spawn dtrsm0(kkk, first, mid, m, a, b);
dtrsm0(kkk, mid, last, m, a, b);
cilk_sync;
} else {
const long double *COIN_RESTRICT aBaseA = a + UNROLL_DTRSM * BLOCKING8X8 + kkk * BLOCKING8;
aBaseA += (first - mm) * BLOCKING8 - BLOCKING8X8;
aBaseA += m * kkk;
for (int ii = first; ii < last; ii += BLOCKING8) {
aBaseA += BLOCKING8X8;
const long double *COIN_RESTRICT aBaseB = aBaseA;
long double *COIN_RESTRICT bBaseI = b + ii;
for (int kk = kkk; kk < mm; kk += BLOCKING8) {
long double *COIN_RESTRICT bBase = b + kk;
const long double *COIN_RESTRICT aBase2 = aBaseB; //a+UNROLL_DTRSM*BLOCKING8X8+m*kk+kkk*BLOCKING8;
//aBase2 += (ii-mm)*BLOCKING8;
//assert (aBase2==aBaseB);
aBaseB += m * BLOCKING8;
#if AVX2 != 2
#define ALTERNATE_INNER
#ifndef ALTERNATE_INNER
for (int k = 0; k < BLOCKING8; k++) {
//coin_prefetch_const(aBase2+BLOCKING8);
for (int i = 0; i < BLOCKING8; i++) {
bBaseI[i] -= bBase[k] * aBase2[i];
}
aBase2 += BLOCKING8;
}
#else
long double b0 = bBaseI[0];
long double b1 = bBaseI[1];
long double b2 = bBaseI[2];
long double b3 = bBaseI[3];
long double b4 = bBaseI[4];
long double b5 = bBaseI[5];
long double b6 = bBaseI[6];
long double b7 = bBaseI[7];
for (int k = 0; k < BLOCKING8; k++) {
//coin_prefetch_const(aBase2+BLOCKING8);
long double bValue = bBase[k];
b0 -= bValue * aBase2[0];
b1 -= bValue * aBase2[1];
b2 -= bValue * aBase2[2];
b3 -= bValue * aBase2[3];
b4 -= bValue * aBase2[4];
b5 -= bValue * aBase2[5];
b6 -= bValue * aBase2[6];
b7 -= bValue * aBase2[7];
aBase2 += BLOCKING8;
}
bBaseI[0] = b0;
bBaseI[1] = b1;
bBaseI[2] = b2;
bBaseI[3] = b3;
bBaseI[4] = b4;
bBaseI[5] = b5;
bBaseI[6] = b6;
bBaseI[7] = b7;
#endif
#else
__m256d b0 = _mm256_load_pd(bBaseI);
__m256d b1 = _mm256_load_pd(bBaseI + 4);
for (int k = 0; k < BLOCKING8; k++) {
//coin_prefetch_const(aBase2+BLOCKING8);
__m256d bb = _mm256_broadcast_sd(bBase + k);
__m256d a0 = _mm256_load_pd(aBase2);
b0 -= a0 * bb;
__m256d a1 = _mm256_load_pd(aBase2 + 4);
b1 -= a1 * bb;
aBase2 += BLOCKING8;
}
//_mm256_store_pd ((bBaseI), (b0));
*reinterpret_cast< __m256d * >(bBaseI) = b0;
//_mm256_store_pd (bBaseI+4, b1);
*reinterpret_cast< __m256d * >(bBaseI + 4) = b1;
#endif
}
}
}
}
void CoinAbcDtrsm0(int m, long double *COIN_RESTRICT a, long double *COIN_RESTRICT b)
{
assert((m & (BLOCKING8 - 1)) == 0);
// 0 Left Lower NoTranspose Unit
for (int kkk = 0; kkk < m; kkk += UNROLL_DTRSM * BLOCKING8) {
int mm = CoinMin(m, kkk + UNROLL_DTRSM * BLOCKING8);
for (int kk = kkk; kk < mm; kk += BLOCKING8) {
const long double *COIN_RESTRICT aBase2 = a + kk * (m + BLOCKING8);
long double *COIN_RESTRICT bBase = b + kk;
for (int k = 0; k < BLOCKING8; k++) {
for (int i = k + 1; i < BLOCKING8; i++) {
bBase[i] -= bBase[k] * aBase2[i];
}
aBase2 += BLOCKING8;
}
for (int ii = kk + BLOCKING8; ii < mm; ii += BLOCKING8) {
long double *COIN_RESTRICT bBaseI = b + ii;
for (int k = 0; k < BLOCKING8; k++) {
//coin_prefetch_const(aBase2+BLOCKING8);
for (int i = 0; i < BLOCKING8; i++) {
bBaseI[i] -= bBase[k] * aBase2[i];
}
aBase2 += BLOCKING8;
}
}
}
dtrsm0(kkk, mm, m, m, a, b);
}
}
static void dtrsm1(int kkk, int first, int last,
int m, long double *COIN_RESTRICT a, long double *COIN_RESTRICT b)
{
int mm = CoinMax(0, kkk - (UNROLL_DTRSM - 1) * BLOCKING8);
assert((last - first) % BLOCKING8 == 0);
if (last - first > CILK_DTRSM) {
int mid = ((first + last) >> 4) << 3;
cilk_spawn dtrsm1(kkk, first, mid, m, a, b);
dtrsm1(kkk, mid, last, m, a, b);
cilk_sync;
} else {
for (int iii = last - BLOCKING8; iii >= first; iii -= BLOCKING8) {
long double *COIN_RESTRICT bBase2 = b + iii;
const long double *COIN_RESTRICT aBaseA = a + BLOCKING8X8 + BLOCKING8 * iii;
for (int ii = kkk; ii >= mm; ii -= BLOCKING8) {
long double *COIN_RESTRICT bBase = b + ii;
const long double *COIN_RESTRICT aBase = aBaseA + m * ii;
#if AVX2 != 2
#ifndef ALTERNATE_INNER
for (int i = BLOCKING8 - 1; i >= 0; i--) {
aBase -= BLOCKING8;
//coin_prefetch_const(aBase-BLOCKING8);
for (int k = BLOCKING8 - 1; k >= 0; k--) {
bBase2[k] -= bBase[i] * aBase[k];
}
}
#else
long double b0 = bBase2[0];
long double b1 = bBase2[1];
long double b2 = bBase2[2];
long double b3 = bBase2[3];
long double b4 = bBase2[4];
long double b5 = bBase2[5];
long double b6 = bBase2[6];
long double b7 = bBase2[7];
for (int i = BLOCKING8 - 1; i >= 0; i--) {
aBase -= BLOCKING8;
//coin_prefetch_const(aBase-BLOCKING8);
long double bValue = bBase[i];
b0 -= bValue * aBase[0];
b1 -= bValue * aBase[1];
b2 -= bValue * aBase[2];
b3 -= bValue * aBase[3];
b4 -= bValue * aBase[4];
b5 -= bValue * aBase[5];
b6 -= bValue * aBase[6];
b7 -= bValue * aBase[7];
}
bBase2[0] = b0;
bBase2[1] = b1;
bBase2[2] = b2;
bBase2[3] = b3;
bBase2[4] = b4;
bBase2[5] = b5;
bBase2[6] = b6;
bBase2[7] = b7;
#endif
#else
__m256d b0 = _mm256_load_pd(bBase2);
__m256d b1 = _mm256_load_pd(bBase2 + 4);
for (int i = BLOCKING8 - 1; i >= 0; i--) {
aBase -= BLOCKING8;
//coin_prefetch_const(aBase5-BLOCKING8);
__m256d bb = _mm256_broadcast_sd(bBase + i);
__m256d a0 = _mm256_load_pd(aBase);
b0 -= a0 * bb;
__m256d a1 = _mm256_load_pd(aBase + 4);
b1 -= a1 * bb;
}
//_mm256_store_pd (bBase2, b0);
*reinterpret_cast< __m256d * >(bBase2) = b0;
//_mm256_store_pd (bBase2+4, b1);
*reinterpret_cast< __m256d * >(bBase2 + 4) = b1;
#endif
}
}
}
}
void CoinAbcDtrsm1(int m, long double *COIN_RESTRICT a, long double *COIN_RESTRICT b)
{
assert((m & (BLOCKING8 - 1)) == 0);
// 1 Left Upper NoTranspose NonUnit
for (int kkk = m - BLOCKING8; kkk >= 0; kkk -= UNROLL_DTRSM * BLOCKING8) {
int mm = CoinMax(0, kkk - (UNROLL_DTRSM - 1) * BLOCKING8);
for (int ii = kkk; ii >= mm; ii -= BLOCKING8) {
const long double *COIN_RESTRICT aBase = a + m * ii + ii * BLOCKING8;
long double *COIN_RESTRICT bBase = b + ii;
for (int i = BLOCKING8 - 1; i >= 0; i--) {
bBase[i] *= aBase[i * (BLOCKING8 + 1)];
for (int k = i - 1; k >= 0; k--) {
bBase[k] -= bBase[i] * aBase[k + i * BLOCKING8];
}
}
long double *COIN_RESTRICT bBase2 = bBase;
for (int iii = ii; iii > mm; iii -= BLOCKING8) {
bBase2 -= BLOCKING8;
for (int i = BLOCKING8 - 1; i >= 0; i--) {
aBase -= BLOCKING8;
coin_prefetch_const(aBase - BLOCKING8);
for (int k = BLOCKING8 - 1; k >= 0; k--) {
bBase2[k] -= bBase[i] * aBase[k];
}
}
}
}
dtrsm1(kkk, 0, mm, m, a, b);
}
}
static void dtrsm2(int kkk, int first, int last,
int m, long double *COIN_RESTRICT a, long double *COIN_RESTRICT b)
{
int mm = CoinMax(0, kkk - (UNROLL_DTRSM - 1) * BLOCKING8);
assert((last - first) % BLOCKING8 == 0);
if (last - first > CILK_DTRSM) {
int mid = ((first + last) >> 4) << 3;
cilk_spawn dtrsm2(kkk, first, mid, m, a, b);
dtrsm2(kkk, mid, last, m, a, b);
cilk_sync;
} else {
for (int iii = last - BLOCKING8; iii >= first; iii -= BLOCKING8) {
for (int ii = kkk; ii >= mm; ii -= BLOCKING8) {
const long double *COIN_RESTRICT bBase = b + ii;
long double *COIN_RESTRICT bBase2 = b + iii;
const long double *COIN_RESTRICT aBase = a + ii * BLOCKING8 + m * iii + BLOCKING8X8;
for (int j = BLOCKING8 - 1; j >= 0; j -= 4) {
long double bValue0 = bBase2[j];
long double bValue1 = bBase2[j - 1];
long double bValue2 = bBase2[j - 2];
long double bValue3 = bBase2[j - 3];
bValue0 -= aBase[-1 * BLOCKING8 + 7] * bBase[7];
bValue1 -= aBase[-2 * BLOCKING8 + 7] * bBase[7];
bValue2 -= aBase[-3 * BLOCKING8 + 7] * bBase[7];
bValue3 -= aBase[-4 * BLOCKING8 + 7] * bBase[7];
bValue0 -= aBase[-1 * BLOCKING8 + 6] * bBase[6];
bValue1 -= aBase[-2 * BLOCKING8 + 6] * bBase[6];
bValue2 -= aBase[-3 * BLOCKING8 + 6] * bBase[6];
bValue3 -= aBase[-4 * BLOCKING8 + 6] * bBase[6];
bValue0 -= aBase[-1 * BLOCKING8 + 5] * bBase[5];
bValue1 -= aBase[-2 * BLOCKING8 + 5] * bBase[5];
bValue2 -= aBase[-3 * BLOCKING8 + 5] * bBase[5];
bValue3 -= aBase[-4 * BLOCKING8 + 5] * bBase[5];
bValue0 -= aBase[-1 * BLOCKING8 + 4] * bBase[4];
bValue1 -= aBase[-2 * BLOCKING8 + 4] * bBase[4];
bValue2 -= aBase[-3 * BLOCKING8 + 4] * bBase[4];
bValue3 -= aBase[-4 * BLOCKING8 + 4] * bBase[4];
bValue0 -= aBase[-1 * BLOCKING8 + 3] * bBase[3];
bValue1 -= aBase[-2 * BLOCKING8 + 3] * bBase[3];
bValue2 -= aBase[-3 * BLOCKING8 + 3] * bBase[3];
bValue3 -= aBase[-4 * BLOCKING8 + 3] * bBase[3];
bValue0 -= aBase[-1 * BLOCKING8 + 2] * bBase[2];
bValue1 -= aBase[-2 * BLOCKING8 + 2] * bBase[2];
bValue2 -= aBase[-3 * BLOCKING8 + 2] * bBase[2];
bValue3 -= aBase[-4 * BLOCKING8 + 2] * bBase[2];
bValue0 -= aBase[-1 * BLOCKING8 + 1] * bBase[1];
bValue1 -= aBase[-2 * BLOCKING8 + 1] * bBase[1];
bValue2 -= aBase[-3 * BLOCKING8 + 1] * bBase[1];
bValue3 -= aBase[-4 * BLOCKING8 + 1] * bBase[1];
bValue0 -= aBase[-1 * BLOCKING8 + 0] * bBase[0];
bValue1 -= aBase[-2 * BLOCKING8 + 0] * bBase[0];
bValue2 -= aBase[-3 * BLOCKING8 + 0] * bBase[0];
bValue3 -= aBase[-4 * BLOCKING8 + 0] * bBase[0];
bBase2[j] = bValue0;
bBase2[j - 1] = bValue1;
bBase2[j - 2] = bValue2;
bBase2[j - 3] = bValue3;
aBase -= 4 * BLOCKING8;
}
}
}
}
}
void CoinAbcDtrsm2(int m, long double *COIN_RESTRICT a, long double *COIN_RESTRICT b)
{
assert((m & (BLOCKING8 - 1)) == 0);
// 2 Left Lower Transpose Unit
for (int kkk = m - BLOCKING8; kkk >= 0; kkk -= UNROLL_DTRSM * BLOCKING8) {
int mm = CoinMax(0, kkk - (UNROLL_DTRSM - 1) * BLOCKING8);
for (int ii = kkk; ii >= mm; ii -= BLOCKING8) {
long double *COIN_RESTRICT bBase = b + ii;
long double *COIN_RESTRICT bBase2 = bBase;
const long double *COIN_RESTRICT aBase = a + m * ii + (ii + BLOCKING8) * BLOCKING8;
for (int i = BLOCKING8 - 1; i >= 0; i--) {
aBase -= BLOCKING8;
for (int k = i + 1; k < BLOCKING8; k++) {
bBase2[i] -= aBase[k] * bBase2[k];
}
}
for (int iii = ii - BLOCKING8; iii >= mm; iii -= BLOCKING8) {
bBase2 -= BLOCKING8;
assert(bBase2 == b + iii);
aBase -= m * BLOCKING8;
const long double *COIN_RESTRICT aBase2 = aBase + BLOCKING8X8;
for (int i = BLOCKING8 - 1; i >= 0; i--) {
aBase2 -= BLOCKING8;
for (int k = BLOCKING8 - 1; k >= 0; k--) {
bBase2[i] -= aBase2[k] * bBase[k];
}
}
}
}
dtrsm2(kkk, 0, mm, m, a, b);
}
}
#define UNROLL_DTRSM3 16
#define CILK_DTRSM3 32
static void dtrsm3(int kkk, int first, int last,
int m, long double *COIN_RESTRICT a, long double *COIN_RESTRICT b)
{
//int mm=CoinMin(kkk+UNROLL_DTRSM3*BLOCKING8,m);
assert((last - first) % BLOCKING8 == 0);
if (last - first > CILK_DTRSM3) {
int mid = ((first + last) >> 4) << 3;
cilk_spawn dtrsm3(kkk, first, mid, m, a, b);
dtrsm3(kkk, mid, last, m, a, b);
cilk_sync;
} else {
for (int kk = 0; kk < kkk; kk += BLOCKING8) {
for (int ii = first; ii < last; ii += BLOCKING8) {
long double *COIN_RESTRICT bBase = b + ii;
long double *COIN_RESTRICT bBase2 = b + kk;
const long double *COIN_RESTRICT aBase = a + ii * m + kk * BLOCKING8;
for (int j = 0; j < BLOCKING8; j += 4) {
long double bValue0 = bBase[j];
long double bValue1 = bBase[j + 1];
long double bValue2 = bBase[j + 2];
long double bValue3 = bBase[j + 3];
bValue0 -= aBase[0] * bBase2[0];
bValue1 -= aBase[1 * BLOCKING8 + 0] * bBase2[0];
bValue2 -= aBase[2 * BLOCKING8 + 0] * bBase2[0];
bValue3 -= aBase[3 * BLOCKING8 + 0] * bBase2[0];
bValue0 -= aBase[1] * bBase2[1];
bValue1 -= aBase[1 * BLOCKING8 + 1] * bBase2[1];
bValue2 -= aBase[2 * BLOCKING8 + 1] * bBase2[1];
bValue3 -= aBase[3 * BLOCKING8 + 1] * bBase2[1];
bValue0 -= aBase[2] * bBase2[2];
bValue1 -= aBase[1 * BLOCKING8 + 2] * bBase2[2];
bValue2 -= aBase[2 * BLOCKING8 + 2] * bBase2[2];
bValue3 -= aBase[3 * BLOCKING8 + 2] * bBase2[2];
bValue0 -= aBase[3] * bBase2[3];
bValue1 -= aBase[1 * BLOCKING8 + 3] * bBase2[3];
bValue2 -= aBase[2 * BLOCKING8 + 3] * bBase2[3];
bValue3 -= aBase[3 * BLOCKING8 + 3] * bBase2[3];
bValue0 -= aBase[4] * bBase2[4];
bValue1 -= aBase[1 * BLOCKING8 + 4] * bBase2[4];
bValue2 -= aBase[2 * BLOCKING8 + 4] * bBase2[4];
bValue3 -= aBase[3 * BLOCKING8 + 4] * bBase2[4];
bValue0 -= aBase[5] * bBase2[5];
bValue1 -= aBase[1 * BLOCKING8 + 5] * bBase2[5];
bValue2 -= aBase[2 * BLOCKING8 + 5] * bBase2[5];
bValue3 -= aBase[3 * BLOCKING8 + 5] * bBase2[5];
bValue0 -= aBase[6] * bBase2[6];
bValue1 -= aBase[1 * BLOCKING8 + 6] * bBase2[6];
bValue2 -= aBase[2 * BLOCKING8 + 7] * bBase2[7];
bValue3 -= aBase[3 * BLOCKING8 + 6] * bBase2[6];
bValue0 -= aBase[7] * bBase2[7];
bValue1 -= aBase[1 * BLOCKING8 + 7] * bBase2[7];
bValue2 -= aBase[2 * BLOCKING8 + 6] * bBase2[6];
bValue3 -= aBase[3 * BLOCKING8 + 7] * bBase2[7];
bBase[j] = bValue0;
bBase[j + 1] = bValue1;
bBase[j + 2] = bValue2;
bBase[j + 3] = bValue3;
aBase += 4 * BLOCKING8;
}
}
}
}
}
void CoinAbcDtrsm3(int m, long double *COIN_RESTRICT a, long double *COIN_RESTRICT b)
{
assert((m & (BLOCKING8 - 1)) == 0);
// 3 Left Upper Transpose NonUnit
for (int kkk = 0; kkk < m; kkk += UNROLL_DTRSM3 * BLOCKING8) {
int mm = CoinMin(m, kkk + UNROLL_DTRSM3 * BLOCKING8);
dtrsm3(kkk, kkk, mm, m, a, b);
for (int ii = kkk; ii < mm; ii += BLOCKING8) {
long double *COIN_RESTRICT bBase = b + ii;
for (int kk = kkk; kk < ii; kk += BLOCKING8) {
long double *COIN_RESTRICT bBase2 = b + kk;
const long double *COIN_RESTRICT aBase = a + ii * m + kk * BLOCKING8;
for (int i = 0; i < BLOCKING8; i++) {
for (int k = 0; k < BLOCKING8; k++) {
bBase[i] -= aBase[k] * bBase2[k];
}
aBase += BLOCKING8;
}
}
const long double *COIN_RESTRICT aBase = a + ii * m + ii * BLOCKING8;
for (int i = 0; i < BLOCKING8; i++) {
for (int k = 0; k < i; k++) {
bBase[i] -= aBase[k] * bBase[k];
}
bBase[i] = bBase[i] * aBase[i];
aBase += BLOCKING8;
}
}
}
}
static void
CoinAbcDlaswp(int n, long double *COIN_RESTRICT a, int lda, int start, int end, int *ipiv)
{
assert((n & (BLOCKING8 - 1)) == 0);
long double *COIN_RESTRICT aThis3 = a;
for (int j = 0; j < n; j += BLOCKING8) {
for (int i = start; i < end; i++) {
int ip = ipiv[i];
if (ip != i) {
long double *COIN_RESTRICT aTop = aThis3 + j * lda;
int iBias = ip / BLOCKING8;
ip -= iBias * BLOCKING8;
long double *COIN_RESTRICT aNotTop = aTop + iBias * BLOCKING8X8;
iBias = i / BLOCKING8;
int i2 = i - iBias * BLOCKING8;
aTop += iBias * BLOCKING8X8;
for (int k = 0; k < BLOCKING8; k++) {
long double temp = aTop[i2];
aTop[i2] = aNotTop[ip];
aNotTop[ip] = temp;
aTop += BLOCKING8;
aNotTop += BLOCKING8;
}
}
}
}
}
extern void CoinAbcDgemm(int m, int n, int k, long double *COIN_RESTRICT a, int lda,
long double *COIN_RESTRICT b, long double *COIN_RESTRICT c
#if ABC_PARALLEL == 2
,
int parallelMode
#endif
);
static int CoinAbcDgetrf2(int m, int n, long double *COIN_RESTRICT a, int *ipiv)
{
assert((m & (BLOCKING8 - 1)) == 0 && (n & (BLOCKING8 - 1)) == 0);
assert(n == BLOCKING8);
int dimension = CoinMin(m, n);
/* entry for column j and row i (when multiple of BLOCKING8)
is at aBlocked+j*m+i*BLOCKING8
*/
assert(dimension == BLOCKING8);
//printf("Dgetrf2 m=%d n=%d\n",m,n);
long double *COIN_RESTRICT aThis3 = a;
for (int j = 0; j < dimension; j++) {
int pivotRow = -1;
long double largest = 0.0;
long double *COIN_RESTRICT aThis2 = aThis3 + j * BLOCKING8;
// this block
int pivotRow2 = -1;
for (int i = j; i < BLOCKING8; i++) {
long double value = fabsl(aThis2[i]);
if (value > largest) {
largest = value;
pivotRow2 = i;
}
}
// other blocks
int iBias = 0;
for (int ii = BLOCKING8; ii < m; ii += BLOCKING8) {
aThis2 += BLOCKING8 * BLOCKING8;
for (int i = 0; i < BLOCKING8; i++) {
long double value = fabsl(aThis2[i]);
if (value > largest) {
largest = value;
pivotRow2 = i;
iBias = ii;
}
}
}
pivotRow = pivotRow2 + iBias;
ipiv[j] = pivotRow;
if (largest) {
if (j != pivotRow) {
long double *COIN_RESTRICT aTop = aThis3;
long double *COIN_RESTRICT aNotTop = aThis3 + iBias * BLOCKING8;
for (int i = 0; i < n; i++) {
long double value = aTop[j];
aTop[j] = aNotTop[pivotRow2];
aNotTop[pivotRow2] = value;
aTop += BLOCKING8;
aNotTop += BLOCKING8;
}
}
aThis2 = aThis3 + j * BLOCKING8;
long double pivotMultiplier = 1.0 / aThis2[j];
aThis2[j] = pivotMultiplier;
// Do L
// this block
for (int i = j + 1; i < BLOCKING8; i++)
aThis2[i] *= pivotMultiplier;
// other blocks
for (int ii = BLOCKING8; ii < m; ii += BLOCKING8) {
aThis2 += BLOCKING8 * BLOCKING8;
for (int i = 0; i < BLOCKING8; i++)
aThis2[i] *= pivotMultiplier;
}
// update rest
long double *COIN_RESTRICT aPut;
aThis2 = aThis3 + j * BLOCKING8;
aPut = aThis2 + BLOCKING8;
long double *COIN_RESTRICT aPut2 = aPut;
// this block
for (int i = j + 1; i < BLOCKING8; i++) {
long double value = aPut[j];
for (int k = j + 1; k < BLOCKING8; k++)
aPut[k] -= value * aThis2[k];
aPut += BLOCKING8;
}
// other blocks
for (int ii = BLOCKING8; ii < m; ii += BLOCKING8) {
aThis2 += BLOCKING8 * BLOCKING8;
aPut = aThis2 + BLOCKING8;
long double *COIN_RESTRICT aPut2a = aPut2;
for (int i = j + 1; i < BLOCKING8; i++) {
long double value = aPut2a[j];
for (int k = 0; k < BLOCKING8; k++)
aPut[k] -= value * aThis2[k];
aPut += BLOCKING8;
aPut2a += BLOCKING8;
}
}
} else {
return 1;
}
}
return 0;
}
int CoinAbcDgetrf(int m, int n, long double *COIN_RESTRICT a, int lda, int *ipiv
#if ABC_PARALLEL == 2
,
int parallelMode
#endif
)
{
assert(m == n);
assert((m & (BLOCKING8 - 1)) == 0 && (n & (BLOCKING8 - 1)) == 0);
if (m < BLOCKING8) {
return CoinAbcDgetrf2(m, n, a, ipiv);
} else {
for (int j = 0; j < n; j += BLOCKING8) {
int start = j;
int newSize = CoinMin(BLOCKING8, n - j);
int end = j + newSize;
int returnCode = CoinAbcDgetrf2(m - start, newSize, a + (start * lda + start * BLOCKING8),
ipiv + start);
if (!returnCode) {
// adjust
for (int k = start; k < end; k++)
ipiv[k] += start;
// swap 0<start
CoinAbcDlaswp(start, a, lda, start, end, ipiv);
if (end < n) {
// swap >=end
CoinAbcDlaswp(n - end, a + end * lda, lda, start, end, ipiv);
CoinAbcDtrsmFactor(newSize, n - end, a + (start * lda + start * BLOCKING8), lda);
CoinAbcDgemm(n - end, n - end, newSize,
a + start * lda + end * BLOCKING8, lda,
a + end * lda + start * BLOCKING8, a + end * lda + end * BLOCKING8
#if ABC_PARALLEL == 2
,
parallelMode
#endif
);
}
} else {
return returnCode;
}
}
}
return 0;
}
void CoinAbcDgetrs(char trans, int m, long double *COIN_RESTRICT a, long double *COIN_RESTRICT work)
{
assert((m & (BLOCKING8 - 1)) == 0);
if (trans == 'N') {
//CoinAbcDlaswp1(work,m,ipiv);
CoinAbcDtrsm0(m, a, work);
CoinAbcDtrsm1(m, a, work);
} else {
assert(trans == 'T');
CoinAbcDtrsm3(m, a, work);
CoinAbcDtrsm2(m, a, work);
//CoinAbcDlaswp1Backwards(work,m,ipiv);
}
}
#endif
/* vi: softtabstop=2 shiftwidth=2 expandtab tabstop=2
*/
| 34.231481 | 128 | 0.589442 | [
"vector"
] |
1767f8923847b5f4aa53aa2a77cc9a0884075153 | 4,044 | cpp | C++ | src/UserInterface/src/Dialog/FlightDialog.cpp | till213/SkyDolly | 75caa54fa9fcbaae04b6605c3c1a68e0cb9a0c16 | [
"MIT"
] | 21 | 2021-03-01T00:19:41.000Z | 2022-02-22T02:57:19.000Z | src/UserInterface/src/Dialog/FlightDialog.cpp | till213/SkyDolly | 75caa54fa9fcbaae04b6605c3c1a68e0cb9a0c16 | [
"MIT"
] | 11 | 2021-06-20T20:16:56.000Z | 2022-03-28T19:03:34.000Z | src/UserInterface/src/Dialog/FlightDialog.cpp | till213/SkyDolly | 75caa54fa9fcbaae04b6605c3c1a68e0cb9a0c16 | [
"MIT"
] | 3 | 2021-04-06T19:06:16.000Z | 2022-01-20T21:22:39.000Z | /**
* Sky Dolly - The Black Sheep for your Flight Recordings
*
* Copyright (c) Oliver Knoll
* All rights reserved.
*
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include "FlightDialog.h"
#include "ui_FlightDialog.h"
#include <memory>
#include <QWidget>
#include <QDialog>
#include <QShortcut>
#include <QShowEvent>
#include <QHideEvent>
#include "../../../Model/src/SimVar.h"
#include "../../../Model/src/Logbook.h"
#include "../../../Model/src/Flight.h"
#include "../../../Model/src/Aircraft.h"
#include "../../../Model/src/Aircraft.h"
#include "../../../Model/src/PrimaryFlightControl.h"
#include "../../../Model/src/AircraftInfo.h"
#include "../../../Persistence/src/Service/FlightService.h"
#include "../Widget/FlightDescriptionWidget.h"
#include "../Widget/AircraftInfoWidget.h"
#include "../Widget/FlightConditionWidget.h"
#include "../Widget/FlightPlanWidget.h"
#include "FlightDialog.h"
#include "ui_FlightDialog.h"
class FlightDialogPrivate
{
public:
FlightDialogPrivate(FlightService &theFlightService) noexcept
: flightService(theFlightService),
closeDialogShortcut(nullptr)
{}
FlightService &flightService;
QShortcut *closeDialogShortcut;
};
// PUBLIC
FlightDialog::FlightDialog(FlightService &flightService, QWidget *parent) noexcept :
QDialog(parent),
d(std::make_unique<FlightDialogPrivate>(flightService)),
ui(std::make_unique<Ui::FlightDialog>())
{
ui->setupUi(this);
initUi();
frenchConnection();
}
FlightDialog::~FlightDialog() noexcept
{}
// PROTECTED
void FlightDialog::showEvent(QShowEvent *event) noexcept
{
QDialog::showEvent(event);
updateUi();
emit visibilityChanged(true);
}
void FlightDialog::hideEvent(QHideEvent *event) noexcept
{
QDialog::hideEvent(event);
emit visibilityChanged(false);
}
// PRIVATE
void FlightDialog::initUi() noexcept
{
setWindowFlags(Qt::Dialog | Qt::WindowTitleHint | Qt::WindowCloseButtonHint);
FlightDescriptionWidget *flightDescriptionWidget = new FlightDescriptionWidget(d->flightService, this);
ui->flightTab->addTab(flightDescriptionWidget, tr("&Description"));
AircraftInfoWidget *aircraftInfoWidget = new AircraftInfoWidget(this);
ui->flightTab->addTab(aircraftInfoWidget, tr("&Aircraft"));
FlightConditionWidget *flightConditionsWidget = new FlightConditionWidget(this);
ui->flightTab->addTab(flightConditionsWidget, tr("&Conditions"));
FlightPlanWidget *flightPlanWidget = new FlightPlanWidget(this);
ui->flightTab->addTab(flightPlanWidget, tr("&Flight Plan"));
ui->flightTab->setCurrentIndex(0);
// TODO DRY: "centrally" define the "F" shortcut (currently also assigned to the corresponding QAction)
d->closeDialogShortcut = new QShortcut(QKeySequence(tr("F", "Window|Flight...")), this);
}
void FlightDialog::updateUi() noexcept
{}
void FlightDialog::frenchConnection() noexcept
{
connect(d->closeDialogShortcut, &QShortcut::activated,
this, &FlightDialog::close);
}
| 32.352 | 107 | 0.73269 | [
"model"
] |
176acd1693bcb4336e4c7f1aa6e816bba0fc7fc8 | 14,007 | cc | C++ | wrspice/src/fte/save.cc | bernardventer/xictools | 4ea72c118679caed700dab3d49a8d36445acaec3 | [
"Apache-2.0"
] | 3 | 2020-01-26T14:18:52.000Z | 2020-12-09T20:07:22.000Z | wrspice/src/fte/save.cc | chris-ayala/xictools | 4ea72c118679caed700dab3d49a8d36445acaec3 | [
"Apache-2.0"
] | null | null | null | wrspice/src/fte/save.cc | chris-ayala/xictools | 4ea72c118679caed700dab3d49a8d36445acaec3 | [
"Apache-2.0"
] | 2 | 2020-01-26T14:19:02.000Z | 2021-08-14T16:33:28.000Z |
/*========================================================================*
* *
* Distributed by Whiteley Research Inc., Sunnyvale, California, USA *
* http://wrcad.com *
* Copyright (C) 2017 Whiteley Research Inc., all rights reserved. *
* Author: Stephen R. Whiteley, except as indicated. *
* *
* As fully as possible recognizing licensing terms and conditions *
* imposed by earlier work from which this work was derived, if any, *
* this work is released under the Apache License, Version 2.0 (the *
* "License"). You may not use this file except in compliance with *
* the License, and compliance with inherited licenses which are *
* specified in a sub-header below this one if applicable. A copy *
* of the License is provided with this distribution, or you may *
* obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* See the License for the specific language governing permissions *
* and limitations under the License. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, *
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES *
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON- *
* INFRINGEMENT. IN NO EVENT SHALL WHITELEY RESEARCH INCORPORATED *
* OR STEPHEN R. WHITELEY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, *
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE *
* USE OR OTHER DEALINGS IN THE SOFTWARE. *
* *
*========================================================================*
* XicTools Integrated Circuit Design System *
* *
* WRspice Circuit Simulation and Analysis Tool *
* *
*========================================================================*
$Id:$
*========================================================================*/
/***************************************************************************
JSPICE3 adaptation of Spice3e2 - Copyright (c) Stephen R. Whiteley 1992
Copyright 1990 Regents of the University of California. All rights reserved.
Authors: 1987 Wayne A. Christopher
1992 Stephen R. Whiteley
****************************************************************************/
#include "simulator.h"
#include "parser.h"
#include "runop.h"
#include "output.h"
#include "cshell.h"
#include "commands.h"
#include "toolbar.h"
#include "spnumber/hash.h"
//
// The save command handling.
//
// keywords
const char *kw_save = "save";
namespace {
// This function must match two names with or without a V() around
// them.
//
bool name_eq(const char *n1, const char *n2)
{
if (!n1 || !n2)
return (false);
const char *s = strchr(n1, '(');
if (s)
n1 = s+1;
s = strchr(n2, '(');
if (s)
n2 = s+1;
while (isspace(*n1))
n1++;
while (isspace(*n2))
n2++;
for ( ; ; n1++, n2++) {
if ((*n1 == 0 || *n1 == ')' || isspace(*n1)) &&
(*n2 == 0 || *n2 == ')' || isspace(*n2)))
return (true);
if (*n1 != *n2)
break;
}
return (false);
}
// Return true if s is one of v(, vm(, vp(, vr(, vi(, or same with i
// replacing v.
//
bool isvec(const char *cs)
{
char buf[8];
if (*cs != 'v' && *cs != 'V' && *cs != 'i' && *cs != 'I')
return (false);
strncpy(buf, cs+1, 7);
buf[7] = '\0';
char *s = buf;
for ( ; *s; s++)
if (isupper(*s))
*s = tolower(*s);
s = buf;
if (*s == '(')
return (true);
if (*(s+1) == '(' &&
(*s == 'm' || *s == 'p' || *s == 'r' || *s == 'i'))
return (true);
if (*(s+2) == '(' && *(s+1) == 'b' && *s == 'd')
return (true);
return (false);
}
}
// The save command.
//
void
CommandTab::com_save(wordlist *wl)
{
OP.saveCmd(wl);
}
// End of CommandTab functions.
void
IFoutput::saveCmd(wordlist *wl)
{
char buf[BSIZE_SP];
for ( ; wl; wl = wl->wl_next) {
if (!isvec(wl->wl_word)) {
addSave(Sp.CurCircuit(), wl->wl_word);
continue;
}
if (*wl->wl_word == 'v' || *wl->wl_word == 'V') {
// deal with forms like vxx(a,b)
char *s = strchr(wl->wl_word, '(') + 1;
while (isspace(*s))
s++;
strcpy(buf, s);
s = strchr(buf, ',');
if (!s) {
addSave(Sp.CurCircuit(), wl->wl_word);
continue;
}
char *n1 = buf;
*s++ = '\0';
while (isspace(*s))
s++;
char *n2 = s;
for (s = n1 + strlen(n1) - 1; s > n1; s--) {
if (isspace(*s))
*s = '\0';
else
break;
}
for (s = n2 + strlen(n2) - 1; s > n2; s--) {
if (isspace(*s) || *s == ')')
*s = '\0';
else
break;
}
addSave(Sp.CurCircuit(), n1);
addSave(Sp.CurCircuit(), n2);
}
else {
// deal with forms like ixx(vyy)
char *s = strchr(wl->wl_word, '(') + 1;
while (isspace(*s))
s++;
strcpy(buf, s);
char *n1 = buf;
for (s = n1 + strlen(n1) - 1; s > n1; s--) {
if (isspace(*s) || *s == ')')
*s = '\0';
else
break;
}
strcat(buf, "#branch");
addSave(Sp.CurCircuit(), n1);
}
}
ToolBar()->UpdateTrace();
}
// Save a vector.
//
void
IFoutput::addSave(sFtCirc *circuit, const char *name)
{
char *s = lstring::copy(name);
CP.Unquote(s);
for (sRunopSave *td = o_runops->saves(); td; td = td->next()) {
if (name_eq(s, td->string())) {
delete [] s;
return;
}
}
if (circuit) {
for (sRunopSave *td = circuit->saves(); td; td = td->next()) {
if (name_eq(s, td->string())) {
delete [] s;
return;
}
}
}
sRunopSave *d = new sRunopSave;
d->set_active(true);
d->set_string(s);
d->set_number(o_runops->new_count());
if (CP.GetFlag(CP_INTERACTIVE) || !circuit) {
if (o_runops->saves()) {
sRunopSave *td = o_runops->saves();
for ( ; td->next(); td = td->next()) ;
td->set_next(d);
}
else
o_runops->set_saves(d);
}
else {
if (circuit->saves()) {
sRunopSave *td = circuit->saves();
for ( ; td->next(); td = td->next()) ;
td->set_next(d);
}
else
circuit->set_saves(d);
}
}
// Fill in a list of vector names used in the runops. If there are only
// specials in the list as passed and in any db saves, save only specials,
// i.e., names starting with SpecCatchar().
//
// The .measure lines are also checked here.
//
void
IFoutput::getSaves(sFtCirc *circuit, sSaveList *saved)
{
sRunopDb *db = circuit ? &circuit->runops() : 0;
ROgen<sRunopSave> svgen(o_runops->saves(), db ? db->saves() : 0);
for (sRunopSave *d = svgen.next(); d; d = svgen.next()) {
if (d->active())
saved->add_save(d->string());
}
bool saveall = true;
sHgen gen(saved->table());
sHent *h;
while ((h = gen.next()) != 0) {
if (*h->name() != Sp.SpecCatchar()) {
saveall = false;
break;
}
}
// If there is nothing but specials in the list, saveall will be
// true, which means that all circuit vectors are automatically
// saved and the only saves we list here are the specials.
//
// However, we have the look for these the "hard way" in any case,
// since we would like to recognize cases like p(Vsrc) which map
// to @Vsrc[p]. When done, we'll go back an purge non-specials
// if saveall is true.
ROgen<sRunopTrace> tgen(o_runops->traces(), db ? db->traces() : 0);
for (sRunopTrace *d = tgen.next(); d; d = tgen.next()) {
if (d->active())
saved->list_expr(d->string());
}
ROgen<sRunopIplot> igen(o_runops->iplots(), db ? db->iplots() : 0);
for (sRunopIplot *d = igen.next(); d; d = igen.next()) {
if (d->active())
saved->list_expr(d->string());
}
ROgen<sRunopMeas> mgen(o_runops->measures(), db ? db->measures() : 0);
for (sRunopMeas *m = mgen.next(); m; m = mgen.next()) {
if (m->active()) {
if (m->prmexpr())
saved->list_expr(m->prmexpr());
for (sMpoint *pt = &m->start(); pt; pt = pt->conj()) {
saved->list_expr(pt->expr1());
saved->list_expr(pt->expr2());
}
for (sMpoint *pt = &m->end(); pt; pt = pt->conj()) {
saved->list_expr(pt->expr1());
saved->list_expr(pt->expr2());
}
for (sMfunc *f = m->funcs(); f; f = f->next())
saved->list_expr(f->expr());
for (sMfunc *f = m->finds(); f; f = f->next())
saved->list_expr(f->expr());
}
}
ROgen<sRunopStop> sgen(o_runops->stops(), db ? db->stops() : 0);
for (sRunopStop *d = sgen.next(); d; d = sgen.next()) {
if (d->active()) {
for (sMpoint *pt = &d->start(); pt; pt = pt->conj()) {
saved->list_expr(pt->expr1());
saved->list_expr(pt->expr2());
}
}
}
if (saveall)
saved->purge_non_special();
else {
// Remove all the measure result names, which may have been
// added if they are referenced by another measure. These
// vectors don't exist until the measurement is done.
mgen = ROgen<sRunopMeas>(o_runops->measures(), db ? db->measures() : 0);
for (sRunopMeas *m = mgen.next(); m; m = mgen.next())
saved->remove_save(m->result());
}
}
// End of IFoutput functions.
sSaveList::~sSaveList()
{
delete sl_tab;
}
// Return the number of words saved.
//
int
sSaveList::numsaves()
{
if (!sl_tab)
return (0);
return (sl_tab->allocated());
}
// Set the used flag for the entry name, return true if the state was
// set.
//
bool
sSaveList::set_used(const char *name, bool used)
{
if (!sl_tab)
return (false);
sHent *h = sHtab::get_ent(sl_tab, name);
if (!h)
return (false);
h->set_data((void*)(long)used);
return (true);
}
// Return 1/0 if the element name exists ant the user flag is
// set/unset. return -1 if not in table.
//
int
sSaveList::is_used(const char *name)
{
if (!sl_tab)
return (-1);
sHent *h = sHtab::get_ent(sl_tab, name);
if (!h)
return (-1);
return (h->data() != 0);
}
// Add word to the save list, if it is not already there.
//
void
sSaveList::add_save(const char *word)
{
if (!sl_tab)
sl_tab = new sHtab(sHtab::get_ciflag(CSE_NODE));
if (sHtab::get_ent(sl_tab, word))
return;
sl_tab->add(word, 0);
}
// Remove name from list, if found.
//
void
sSaveList::remove_save(const char *name)
{
if (name && sl_tab)
sl_tab->remove(name);
}
// Save all the vectors.
//
void
sSaveList::list_expr(const char *expr)
{
if (expr) {
wordlist *wl = CP.LexStringSub(expr);
if (wl) {
pnlist *pl0 = Sp.GetPtree(wl, false);
for (pnlist *pl = pl0; pl; pl = pl->next())
list_vecs(pl->node());
pnlist::destroy(pl0);
wordlist::destroy(wl);
}
}
}
// Remove all entries that are not "special", i.e., don't start with
// Sp.SpecCatchar(). The list is resized.
//
void
sSaveList::purge_non_special()
{
if (sl_tab) {
wordlist *wl0 = sHtab::wl(sl_tab);
for (wordlist *wl = wl0; wl; wl = wl->wl_next) {
if (*wl->wl_word != Sp.SpecCatchar())
sl_tab->remove(wl->wl_word);
}
wordlist::destroy(wl0);
}
}
// Go through the parse tree, and add any vector names found to the
// saves.
//
void
sSaveList::list_vecs(pnode *pn)
{
char buf[128];
if (pn->token_string()) {
if (!pn->value())
add_save(pn->token_string());
}
else if (pn->func()) {
if (!pn->func()->func()) {
if (*pn->func()->name() == 'v')
sprintf(buf, "v(%s)", pn->left()->token_string());
else
sprintf(buf, "%s", pn->left()->token_string());
add_save(buf);
}
else
list_vecs(pn->left());
}
else if (pn->oper()) {
list_vecs(pn->left());
if (pn->right())
list_vecs(pn->right());
}
}
// End of sSaveList functions.
| 29.865672 | 80 | 0.454915 | [
"vector"
] |
176e5ecc9409e076a68b35014e356c879ea09234 | 10,163 | cc | C++ | dance/anyone.cc | bobjervis/sets_in_motion | 24df9a5fbd55acd84ca072ea6b930c851bb667d9 | [
"Apache-2.0"
] | null | null | null | dance/anyone.cc | bobjervis/sets_in_motion | 24df9a5fbd55acd84ca072ea6b930c851bb667d9 | [
"Apache-2.0"
] | null | null | null | dance/anyone.cc | bobjervis/sets_in_motion | 24df9a5fbd55acd84ca072ea6b930c851bb667d9 | [
"Apache-2.0"
] | null | null | null | #include "../common/platform.h"
#include "dance.h"
#include "call.h"
#include "stored_data.h"
namespace dance {
const char* dancerSetNames[] = {
"none",
"centers",
"ends",
"very centers",
"very ends",
"$last_active",
"others",
"leaders",
"trailers",
"heads",
"sides",
"boys",
"girls",
"beaus",
"belles",
"facing across",
"facing along",
"in facing",
"out facing",
"dancer_mask",
"left AND right",
"left OR right",
"left xor RIGHT",
"not LEFT",
};
unsigned heads[] = {
0, // D_UNSPECIFIED
0, // D_2COUPLE
COUPLE_1|COUPLE_3, // D_4COUPLE
COUPLE_1|COUPLE_2|COUPLE_4|COUPLE_5, // D_6COUPLE
COUPLE_1|COUPLE_3|COUPLE_5, // D_HEXAGONAL
};
unsigned sides[] = {
0, // D_UNSPECIFIED
0, // D_2COUPLE
COUPLE_2|COUPLE_4, // D_4COUPLE
COUPLE_3|COUPLE_6, // D_6COUPLE
COUPLE_2|COUPLE_4|COUPLE_6, // D_HEXAGONAL
};
unsigned Anyone::match(const Group* dancers, const Step* step, Context* context) const {
unsigned dancerMask = dancers->dancerMask();
unsigned mask;
Rectangle r;
switch (_dancerSet) {
case LAST_ACTIVE:
return dancerMask & step->lastActiveDancersMask();
case OTHERS:
return dancerMask & ~step->lastActiveDancersMask();
case FACING_ACROSS:
case FACING_ALONG:
dancers->boundingBox(&r);
mask = 0;
for (int i = 0; i < dancers->dancerCount(); i++) {
const Dancer* d = dancers->dancer(i);
switch (d->facing) {
case RIGHT_FACING:
case LEFT_FACING:
if (r.width() > r.height()) {
if (_dancerSet == FACING_ALONG)
mask |= d->dancerMask();
} else if (r.width() < r.height()) {
if (_dancerSet == FACING_ACROSS)
mask |= d->dancerMask();
}
break;
case FRONT_FACING:
case BACK_FACING:
if (r.width() > r.height()) {
if (_dancerSet == FACING_ACROSS)
mask |= d->dancerMask();
} else if (r.width() < r.height()) {
if (_dancerSet == FACING_ALONG)
mask |= d->dancerMask();
}
break;
}
}
return mask;
case IN_FACING:
case OUT_FACING:
mask = 0;
if (dancers->geometry() == RING) {
for (int i = 0; i < dancers->dancerCount(); i++) {
const Dancer* d = dancers->dancer(i);
switch (d->facing) {
case FRONT_FACING:
if (_dancerSet == IN_FACING)
mask |= d->dancerMask();
break;
case BACK_FACING:
if (_dancerSet == OUT_FACING)
mask |= d->dancerMask();
break;
}
}
} else {
for (int i = 0; i < dancers->dancerCount(); i++) {
const Dancer* d = dancers->dancer(i);
switch (d->facing) {
case RIGHT_FACING:
if (d->x < 0) {
if (_dancerSet == IN_FACING)
mask |= d->dancerMask();
} else if (d->x > 0) {
if (_dancerSet == OUT_FACING)
mask |= d->dancerMask();
}
break;
case LEFT_FACING:
if (d->x < 0) {
if (_dancerSet == OUT_FACING)
mask |= d->dancerMask();
} else if (d->x > 0) {
if (_dancerSet == IN_FACING)
mask |= d->dancerMask();
}
break;
case FRONT_FACING:
if (d->y < 0) {
if (_dancerSet == OUT_FACING)
mask |= d->dancerMask();
} else if (d->y > 0) {
if (_dancerSet == IN_FACING)
mask |= d->dancerMask();
}
break;
case BACK_FACING:
if (d->y < 0) {
if (_dancerSet == IN_FACING)
mask |= d->dancerMask();
} else if (d->y > 0) {
if (_dancerSet == OUT_FACING)
mask |= d->dancerMask();
}
break;
}
}
}
return mask;
case LEADERS:
case TRAILERS: {
const vector<VariantTile>& forms = context->grammar()->leadersTrailers();
TileSearch tiles[MAX_DANCERS];
mask = 0;
int result = dancers->buildTiling(forms, tiles, context, null, null, TILE_ALL);
if (result <= 0)
return 0;
for (int i = 0; i < result; i++) {
const Group* d = tiles[i].dancers;
if (d->dancerCount() == 4) { // must be a box
static DancerSet classification[4][4] = {
{ // dancer 0:
TRAILERS, // RIGHT_FACING, // > caller's right side of hall
LEADERS, // BACK_FACING, // ^ back of hall
LEADERS, // LEFT_FACING, // < caller's left side of hall
TRAILERS, // FRONT_FACING, // v front of hall
},
{ // dancer 1:
LEADERS, // RIGHT_FACING, // > caller's right side of hall
LEADERS, // BACK_FACING, // ^ back of hall
TRAILERS, // LEFT_FACING, // < caller's left side of hall
TRAILERS, // FRONT_FACING, // v front of hall
},
{ // dancer 2:
TRAILERS, // RIGHT_FACING, // > caller's right side of hall
TRAILERS, // BACK_FACING, // ^ back of hall
LEADERS, // LEFT_FACING, // < caller's left side of hall
LEADERS, // FRONT_FACING, // v front of hall
},
{ // dancer 3:
LEADERS, // RIGHT_FACING, // > caller's right side of hall
TRAILERS, // BACK_FACING, // ^ back of hall
TRAILERS, // LEFT_FACING, // < caller's left side of hall
LEADERS, // FRONT_FACING, // v front of hall
},
};
for (int j = 0; j < 4; j++)
if (_dancerSet == classification[j][d->dancer(j)->facing])
mask |= d->dancer(j)->dancerMask();
} else { // must be a twosome
static DancerSet classification[2][4] = {
{ // dancer 0:
TRAILERS, // RIGHT_FACING, // > caller's right side of hall
NONE, // BACK_FACING, // ^ back of hall
LEADERS, // LEFT_FACING, // < caller's left side of hall
NONE, // FRONT_FACING, // v front of hall
},
{ // dancer 1:
LEADERS, // RIGHT_FACING, // > caller's right side of hall
NONE, // BACK_FACING, // ^ back of hall
TRAILERS, // LEFT_FACING, // < caller's left side of hall
NONE, // FRONT_FACING, // v front of hall
},
};
for (int j = 0; j < 2; j++)
if (_dancerSet == classification[j][d->dancer(j)->facing])
mask |= d->dancer(j)->dancerMask();
}
}
return dancerMask & mask;
}
case VERY_CENTERS:
case VERY_ENDS:
case CENTERS:
case ENDS: {
const vector<const Pattern*>& forms = context->grammar()->centersEnds();
for (int i = 0; i < forms.size(); i++) {
const Group* d = dancers->match(forms[i], context, null);
if (d) {
static PositionType pos[] = {
NO_POSITION, // NONE
CENTER, // CENTERS,
END, // ENDS,
VERY_CENTER, // VERY_CENTERS,
VERY_END, // VERY_ENDS
};
static PositionType altPos[] = {
NO_POSITION, // NONE
VERY_CENTER, // CENTERS,
VERY_END, // ENDS,
NO_POSITION, // VERY_CENTERS,
NO_POSITION, // VERY_ENDS
};
return dancerMask & forms[i]->formation()->extract(d, dancers, pos[_dancerSet], altPos[_dancerSet]);
}
}
} break;
case BEAUS:
case BELLES: {
unsigned mask = 0;
vector<const Dancer*> partners;
dancers->partnershipOp(_dancerSet, null, context, &partners);
for (int i = 0; i < partners.size(); i++)
mask |= partners[i]->dancerMask();
return dancerMask & mask;
}
case HEADS:
return dancerMask & heads[D_4COUPLE];
case SIDES:
return dancerMask & sides[D_4COUPLE];
case GIRLS:
return dancerMask & GIRLS_MASK;
case BOYS:
return dancerMask & BOYS_MASK;
case DANCER_MASK:
return dancerMask & _mask;
case NOT_L:
return dancerMask & ~_left->match(dancers, step, context);
case L_AND_R:
mask = _left->match(dancers, step, context);
if (mask == 0)
return 0;
return dancerMask & mask & _right->match(dancers, step, context);
case L_OR_R:
mask = _left->match(dancers, step, context);
if (mask == dancerMask)
return dancerMask;
return dancerMask & (mask | _right->match(dancers, step, context));
case L_XOR_R:
return dancerMask & (_left->match(dancers, step, context) ^ _right->match(dancers, step, context));
default:
break;
}
return 0;
}
const Term* Anyone::not(Context* context) const {
return context->stage()->newAnyone(NOT_L, 0, this, null, _level);
}
const Term* Anyone::and(const Term* operand, Context* context) const {
if (typeid(*operand) != typeid(Anyone))
return null;
const Anyone* right = (const Anyone*)operand;
Level max = _level > right->_level ? _level : right->_level;
return context->stage()->newAnyone(L_AND_R, 0, this, right, max);
}
const Term* Anyone::or(const Term* operand, Context* context) const {
if (typeid(*operand) != typeid(Anyone))
return null;
const Anyone* right = (const Anyone*)operand;
Level max = _level > right->_level ? _level : right->_level;
return context->stage()->newAnyone(L_OR_R, 0, this, right, max);
}
const Term* Anyone::xor(const Term* operand, Context* context) const {
if (typeid(*operand) != typeid(Anyone))
return null;
const Anyone* right = (const Anyone*)operand;
Level max = _level > right->_level ? _level : right->_level;
return context->stage()->newAnyone(L_XOR_R, 0, this, right, max);
}
string Anyone::label() const {
string s;
switch (_dancerSet) {
case DANCER_MASK:
for (int i = 0; i < MAX_DANCERS; i++) {
if (_mask & (1 << i))
s.printf("#%d %s ", coupleOf(i), genderNames[genderOf(i)]);
}
break;
case L_AND_R:
s = "(" + _left->label() + ")and(" + _right->label() + ")";
break;
case L_OR_R:
s = "(" + _left->label() + ")or(" + _right->label() + ")";
break;
case L_XOR_R:
s = "(" + _left->label() + ")xor(" + _right->label() + ")";
break;
case NOT_L:
s = "not(" + _left->label() + ")";
break;
default:
s = dancerSetNames[_dancerSet];
}
return s;
}
void Anyone::print(int indent) const {
if (indent)
printf("%*.*c", indent, indent, ' ');
printf("Anyone{ %s }\n", label().c_str());
}
void DancerName::print(int indent) const {
if (indent)
printf("%*.*c", indent, indent, ' ');
printf("$dancer%c\n", 'A' + _index);
}
void DancerName::token(Token* output) const {
output->type = DANCER_NAME;
output->value = _index;
}
} // namespace dance
| 26.744737 | 105 | 0.573551 | [
"geometry",
"vector"
] |
17713c97fd7eafd98761bc99ff662c0c7b1e7946 | 819 | cpp | C++ | cplusplus/RCF/demo/Server.cpp | ASMlover/study | 5878f862573061f94c5776a351e30270dfd9966a | [
"BSD-2-Clause"
] | 22 | 2015-05-18T07:04:36.000Z | 2021-08-02T03:01:43.000Z | cplusplus/RCF/demo/Server.cpp | ASMlover/study | 5878f862573061f94c5776a351e30270dfd9966a | [
"BSD-2-Clause"
] | 1 | 2017-08-31T22:13:57.000Z | 2017-09-05T15:00:25.000Z | cplusplus/RCF/demo/Server.cpp | ASMlover/study | 5878f862573061f94c5776a351e30270dfd9966a | [
"BSD-2-Clause"
] | 6 | 2015-06-06T07:16:12.000Z | 2021-07-06T13:45:56.000Z |
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
#include <RCF/RCF.hpp>
#include "MyService.hpp"
class MyServiceImpl
{
public:
// Reverses the order of strings in the vector.
void reverse(std::vector<std::string> &v)
{
std::cout << "Reversing a vector of strings...\n";
std::vector<std::string> w;
std::copy(v.rbegin(), v.rend(), std::back_inserter(w));
v.swap(w);
}
};
int main()
{
RCF::RcfInitDeinit rcfInit;
// Start a TCP server on port 50001, and expose MyServiceImpl.
MyServiceImpl myServiceImpl;
RCF::RcfServer server( RCF::TcpEndpoint("0.0.0.0", 50001) );
server.bind<MyService>(myServiceImpl);
server.start();
std::cout << "Press Enter to exit..." << std::endl;
std::cin.get();
return 0;
}
| 21 | 66 | 0.622711 | [
"vector"
] |
1776210b16ea0eaaa1dc6446749b9e59b62b68b3 | 10,658 | cc | C++ | src/generic/trilinos_preconditioners.cc | pkeuchel/oomph-lib | 37c1c61425d6b9ea1c2ddceef63a68a228af6fa4 | [
"RSA-MD"
] | 4 | 2020-11-16T12:25:09.000Z | 2021-06-29T08:53:25.000Z | src/generic/trilinos_preconditioners.cc | pkeuchel/oomph-lib | 37c1c61425d6b9ea1c2ddceef63a68a228af6fa4 | [
"RSA-MD"
] | 2 | 2020-05-05T22:41:37.000Z | 2020-05-10T14:14:17.000Z | src/generic/trilinos_preconditioners.cc | pkeuchel/oomph-lib | 37c1c61425d6b9ea1c2ddceef63a68a228af6fa4 | [
"RSA-MD"
] | 3 | 2021-01-31T14:09:20.000Z | 2021-06-07T07:20:51.000Z | // LIC// ====================================================================
// LIC// This file forms part of oomph-lib, the object-oriented,
// LIC// multi-physics finite-element library, available
// LIC// at http://www.oomph-lib.org.
// LIC//
// LIC// Copyright (C) 2006-2021 Matthias Heil and Andrew Hazel
// LIC//
// LIC// This library is free software; you can redistribute it and/or
// LIC// modify it under the terms of the GNU Lesser General Public
// LIC// License as published by the Free Software Foundation; either
// LIC// version 2.1 of the License, or (at your option) any later version.
// LIC//
// LIC// This library is distributed in the hope that it will be useful,
// LIC// but WITHOUT ANY WARRANTY; without even the implied warranty of
// LIC// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// LIC// Lesser General Public License for more details.
// LIC//
// LIC// You should have received a copy of the GNU Lesser General Public
// LIC// License along with this library; if not, write to the Free Software
// LIC// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
// LIC// 02110-1301 USA.
// LIC//
// LIC// The authors may be contacted at oomph-lib@maths.man.ac.uk.
// LIC//
// LIC//====================================================================
#include "trilinos_preconditioners.h"
namespace oomph
{
/// ////////////////////////////////////////////////////////////////////////////
/// ////////////////////////////////////////////////////////////////////////////
// functions for the TrilinosPreconditionerBase class
/// ////////////////////////////////////////////////////////////////////////////
/// ////////////////////////////////////////////////////////////////////////////
//=============================================================================
/// Static double that accumulates the preconditioner
/// solve time of all instantiations of this class. Reset
/// it manually, e.g. after every Newton solve.
//=============================================================================
double TrilinosPreconditionerBase::Cumulative_preconditioner_solve_time = 0.0;
//=============================================================================
/// Function to set up a preconditioner for the linear system
/// defined by matrix_pt. This function must be called before using
/// preconditioner_solve.
/// \b NOTE 1. matrix_pt must point to an object of class CRDoubleMatrix or
/// DistributedCRDoubleMatrix
/// This method should be called by oomph-lib solvers and preconditioners
//=============================================================================
void TrilinosPreconditionerBase::setup()
{
// clean up the memory
clean_up_memory();
#ifdef PARANOID
// check the matrix is square
if (matrix_pt()->nrow() != matrix_pt()->ncol())
{
std::ostringstream error_message;
error_message << "Preconditioners require a square matrix. "
<< "Matrix is " << matrix_pt()->nrow() << " by "
<< matrix_pt()->ncol() << std::endl;
throw OomphLibError(
error_message.str(), OOMPH_CURRENT_FUNCTION, OOMPH_EXCEPTION_LOCATION);
}
#endif
// get a pointer to the cr double matrix
CRDoubleMatrix* cr_matrix_pt = dynamic_cast<CRDoubleMatrix*>(matrix_pt());
#ifdef PARANOID
if (cr_matrix_pt == 0)
{
throw OomphLibError("Matrix must be of type CRDoubleMatrix",
OOMPH_CURRENT_FUNCTION,
OOMPH_EXCEPTION_LOCATION);
}
#endif
// build the distribution of this preconditioner
this->build_distribution(cr_matrix_pt->distribution_pt());
// create the matrices
Epetra_matrix_pt = TrilinosEpetraHelpers::create_distributed_epetra_matrix(
cr_matrix_pt, this->distribution_pt());
// set up preconditioner
setup_trilinos_preconditioner(Epetra_matrix_pt);
}
//===========================================================================
/// Function to setup a preconditioner for the linear system defined
/// by the oomph-lib oomph_matrix_pt and Epetra epetra_matrix_pt matrices.
/// This method is called by Trilinos solvers.
//===========================================================================
void TrilinosPreconditionerBase::setup(Epetra_CrsMatrix* epetra_matrix_pt)
{
// clean up old data
clean_up_memory();
// first try CRDoubleMatrix
CRDoubleMatrix* cr_matrix_pt = dynamic_cast<CRDoubleMatrix*>(matrix_pt());
if (cr_matrix_pt == 0)
{
std::ostringstream error_message;
error_message << "TrilinosSolver only work with "
<< "DistributedCRDoubleMatrix matrices" << std::endl;
throw OomphLibError(
error_message.str(), OOMPH_CURRENT_FUNCTION, OOMPH_EXCEPTION_LOCATION);
}
// setup the specific preconditioner
setup_trilinos_preconditioner(epetra_matrix_pt);
}
//=============================================================================
/// preconditioner_solve - applies the preconditioner to the vector r
/// taking distributed oomph-lib vectors (DistributedVector<double>) as
/// arguments.
//=============================================================================
void TrilinosPreconditionerBase::preconditioner_solve(const DoubleVector& r,
DoubleVector& z)
{
// Get ready to do cumulative timings
double t_start = TimingHelpers::timer();
#ifdef PARANOID
// check preconditioner data exists
if (Epetra_preconditioner_pt == 0)
{
std::ostringstream error_message;
error_message << "preconditioner_solve requires that solver data has "
<< "been set up" << std::endl;
throw OomphLibError(
error_message.str(), OOMPH_CURRENT_FUNCTION, OOMPH_EXCEPTION_LOCATION);
}
if (*this->distribution_pt() != r.distribution_pt())
{
std::ostringstream error_message;
error_message << "The rhs vector and the matrix must have the same "
<< "distribution.\n";
throw OomphLibError(
error_message.str(), OOMPH_CURRENT_FUNCTION, OOMPH_EXCEPTION_LOCATION);
}
#endif
// create Epetra version of r
Epetra_Vector* epetra_r_pt =
TrilinosEpetraHelpers::create_distributed_epetra_vector(r);
// create an empty Epetra vector for z
Epetra_Vector* epetra_z_pt =
TrilinosEpetraHelpers::create_distributed_epetra_vector(
this->distribution_pt());
// Apply preconditioner
Epetra_preconditioner_pt->ApplyInverse(*epetra_r_pt, *epetra_z_pt);
// Copy result to z
z.build(this->distribution_pt(), 0.0);
TrilinosEpetraHelpers::copy_to_oomphlib_vector(epetra_z_pt, z);
// clean up memory
delete epetra_r_pt;
delete epetra_z_pt;
// Add to cumulative solve time
double t_end = TimingHelpers::timer();
Cumulative_preconditioner_solve_time += (t_end - t_start);
}
/// ////////////////////////////////////////////////////////////////////////////
/// ////////////////////////////////////////////////////////////////////////////
// function for the TrilinosML class
/// ////////////////////////////////////////////////////////////////////////////
/// ////////////////////////////////////////////////////////////////////////////
//=============================================================================
/// (Static) default number of V cycles (one to be consistent
/// with previous default). (It's an int because Trilinos wants it to be!)
//=============================================================================
int TrilinosMLPreconditioner::Default_n_cycles = 1;
//=============================================================================
// Function to set up the ML preconditioner.
//=============================================================================
void TrilinosMLPreconditioner::setup_trilinos_preconditioner(
Epetra_CrsMatrix* epetra_matrix_pt)
{
// doc setup time
oomph_info << "Setting up TrilinosML, ";
double t_start = TimingHelpers::timer();
// create the preconditioner
Epetra_preconditioner_pt = new ML_Epetra::MultiLevelPreconditioner(
*epetra_matrix_pt, ML_parameters, true);
// doc setup time
oomph_info << "time for setup [s] : " << TimingHelpers::timer() - t_start
<< std::endl;
// oomph_info << "In here\n";
// ML_Epetra::MultiLevelPreconditioner* tmp_pt=0;
// tmp_pt=dynamic_cast<ML_Epetra::MultiLevelPreconditioner*>(
// Epetra_preconditioner_pt);
// if (tmp_pt!=0)
// {
// oomph_info << "Doing test\n";
// ML_parameters.print(*(oomph_info.stream_pt()));
// oomph_info.stream_pt()->flush();
// // tmp_pt->TestSmoothers();
// oomph_info << "Done test\n";
// }
}
/// ////////////////////////////////////////////////////////////////////////////
/// ////////////////////////////////////////////////////////////////////////////
// function for the TrilinosIFPACK
/// ////////////////////////////////////////////////////////////////////////////
/// ////////////////////////////////////////////////////////////////////////////
//=============================================================================
// Function to set up the IFPACK preconditioner.
//=============================================================================
void TrilinosIFPACKPreconditioner::setup_trilinos_preconditioner(
Epetra_CrsMatrix* epetra_matrix_pt)
{
// set up a parameter list
Teuchos::ParameterList ifpack_parameters;
ifpack_parameters.set("fact: level-of-fill", ILU_fill_level);
ifpack_parameters.set("fact: ilut level-of-fill", ILUT_fill_level);
ifpack_parameters.set("fact: absolute threshold", Absolute_threshold);
ifpack_parameters.set("fact: relative threshold", Relative_threshold);
// create the preconditioner
Ifpack ifpack_factory;
Ifpack_Preconditioner* tmp_pt =
ifpack_factory.Create(Preconditioner_type, epetra_matrix_pt, Overlap);
tmp_pt->SetParameters(ifpack_parameters);
tmp_pt->Initialize();
tmp_pt->Compute();
// Now store the pointer to the newly created Ifpack_Preconditioner
Epetra_preconditioner_pt = tmp_pt;
}
/// ////////////////////////////////////////////////////////////////////////////
/// ////////////////////////////////////////////////////////////////////////////
/// ////////////////////////////////////////////////////////////////////////////
} // namespace oomph
| 39.917603 | 82 | 0.528054 | [
"object",
"vector"
] |
1777d79a88ac8589e23a1c747010c6d65ed5f00a | 1,206 | hpp | C++ | data-structure/interval-scheduling.hpp | matumoto1234/library | a2c80516a8afe5876696c139fe0e837d8a204f69 | [
"Unlicense"
] | 2 | 2021-06-24T11:21:08.000Z | 2022-03-15T05:57:25.000Z | data-structure/interval-scheduling.hpp | matumoto1234/library | a2c80516a8afe5876696c139fe0e837d8a204f69 | [
"Unlicense"
] | 102 | 2021-10-30T21:30:00.000Z | 2022-03-26T18:39:47.000Z | data-structure/interval-scheduling.hpp | matumoto1234/library | a2c80516a8afe5876696c139fe0e837d8a204f69 | [
"Unlicense"
] | null | null | null | #pragma once
#include "./base.hpp"
#include <vector>
namespace data_structure {
// verify:https://atcoder.jp/contests/keyence2020/tasks/keyence2020_b
template <typename T>
class IntervalScheduling {
vector<pair<T, T>> intervals_;
vector<bool> used;
public:
IntervalScheduling() {}
void add_interval(T l, T r) { intervals_.emplace_back(l, r); }
int inf() { return numeric_limits<int>::max() / 2; }
void build() {
used.assign(intervals_.size(), false);
sort(intervals_.begin(), intervals_.end(), [](pair<T, T> a, pair<T, T> b) {
if (a.second != b.second) return a.second < b.second;
return a.first < b.first;
});
int last = -inf();
for (size_t i = 0; i < intervals_.size(); i++) {
auto [l, r] = intervals_[i];
if (last <= l) {
used[i] = true;
last = r;
}
}
}
bool is_used(int k) { return used[k]; }
vector<pair<T, T>> intervals() {
vector<pair<T, T>> res;
for (size_t i = 0; i < intervals_.size(); i++) {
if (!used[i]) continue;
res.emplace_back(intervals_[i]);
}
return res;
}
};
} // namespace data_structure | 23.647059 | 81 | 0.554726 | [
"vector"
] |
177a53b79e08b9ec6c7c0082ed14148bd028dc77 | 5,348 | cc | C++ | src/util/thin_image.cc | FlyAlCode/PLBGHashing | 289d0a66c9091602abedf2860c2b3ae9d763fed0 | [
"MIT"
] | 1 | 2021-02-13T01:45:20.000Z | 2021-02-13T01:45:20.000Z | src/util/thin_image.cc | FlyAlCode/PLBGHashing | 289d0a66c9091602abedf2860c2b3ae9d763fed0 | [
"MIT"
] | null | null | null | src/util/thin_image.cc | FlyAlCode/PLBGHashing | 289d0a66c9091602abedf2860c2b3ae9d763fed0 | [
"MIT"
] | null | null | null | #include "thin_image.h"
#include <opencv2/imgproc/imgproc.hpp>
void FillImageHole(const cv::Mat &input_img, cv::Mat &output_img){
input_img.copyTo(output_img);
for(int i=1; i<input_img.rows-1;i++){
for(int j=1; j<input_img.cols-1; j++){
if(input_img.at<char>(i,j)==0){
uchar up = input_img.at<uchar>(i-1,j);
uchar down = input_img.at<uchar>(i+1,j);
/*if(up==1 && down==1){
output_img.at<uchar>(i,j)=1;
}
else{
uchar left = input_img.at<uchar>(i,j-1);
uchar right = input_img.at<uchar>(i,j+1);
if(left==1 && right==1)
output_img.at<uchar>(i,j) = 1;
} */
uchar left = input_img.at<uchar>(i,j-1);
uchar right = input_img.at<uchar>(i,j+1);
if(up==1 && down==1 && right==1 && left==1)
output_img.at<uchar>(i,j) = 1;
}
}
}
}
void ThinImage(const cv::Mat & src,
cv::Mat &thined_img,
int binary_threshold,
const int maxIterations ){
cv::Mat dst;
src.copyTo(dst);
if(src.channels()==3)
cv::cvtColor(src, dst, CV_RGB2GRAY);
else
src.copyTo(dst);
cv::threshold(dst, dst, binary_threshold, 1, CV_THRESH_BINARY);
int width = src.cols;
int height = src.rows;
int count = 0;
while (true)
{
count++;
if (maxIterations != -1 && count > maxIterations)
break;
std::vector<uchar *> mFlag;
for (int i = 0; i < height; ++i)
{
uchar * p = dst.ptr<uchar>(i);
for (int j = 0; j < width; ++j)
{
uchar p1 = p[j];
if (p1 != 1) continue;
uchar p4 = (j == width - 1) ? 0 : *(p + j + 1);
uchar p8 = (j == 0) ? 0 : *(p + j - 1);
uchar p2 = (i == 0) ? 0 : *(p - dst.step + j);
uchar p3 = (i == 0 || j == width - 1) ? 0 : *(p - dst.step + j + 1);
uchar p9 = (i == 0 || j == 0) ? 0 : *(p - dst.step + j - 1);
uchar p6 = (i == height - 1) ? 0 : *(p + dst.step + j);
uchar p5 = (i == height - 1 || j == width - 1) ? 0 : *(p + dst.step + j + 1);
uchar p7 = (i == height - 1 || j == 0) ? 0 : *(p + dst.step + j - 1);
if ((p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9) >= 2 && (p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9) <= 6) {
int ap = 0;
if (p2 == 0 && p3 == 1) ++ap;
if (p3 == 0 && p4 == 1) ++ap;
if (p4 == 0 && p5 == 1) ++ap;
if (p5 == 0 && p6 == 1) ++ap;
if (p6 == 0 && p7 == 1) ++ap;
if (p7 == 0 && p8 == 1) ++ap;
if (p8 == 0 && p9 == 1) ++ap;
if (p9 == 0 && p2 == 1) ++ap;
if (ap == 1 && p2 * p4 * p6 == 0 && p4 * p6 * p8 == 0){
mFlag.push_back(p + j);
}
}
}
}
for (std::vector<uchar *>::iterator i = mFlag.begin(); i != mFlag.end(); ++i) {
**i = 0;
}
if (mFlag.empty()) {
break;
}
else {
mFlag.clear();//œ«mFlagÇå¿Õ
}
for (int i = 0; i < height; ++i) {
uchar * p = dst.ptr<uchar>(i);
for (int j = 0; j < width; ++j) {
uchar p1 = p[j];
if (p1 != 1) continue;
uchar p4 = (j == width - 1) ? 0 : *(p + j + 1);
uchar p8 = (j == 0) ? 0 : *(p + j - 1);
uchar p2 = (i == 0) ? 0 : *(p - dst.step + j);
uchar p3 = (i == 0 || j == width - 1) ? 0 : *(p - dst.step + j + 1);
uchar p9 = (i == 0 || j == 0) ? 0 : *(p - dst.step + j - 1);
uchar p6 = (i == height - 1) ? 0 : *(p + dst.step + j);
uchar p5 = (i == height - 1 || j == width - 1) ? 0 : *(p + dst.step + j + 1);
uchar p7 = (i == height - 1 || j == 0) ? 0 : *(p + dst.step + j - 1);
if ((p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9) >= 2 && (p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9) <= 6)
{
int ap = 0;
if (p2 == 0 && p3 == 1) ++ap;
if (p3 == 0 && p4 == 1) ++ap;
if (p4 == 0 && p5 == 1) ++ap;
if (p5 == 0 && p6 == 1) ++ap;
if (p6 == 0 && p7 == 1) ++ap;
if (p7 == 0 && p8 == 1) ++ap;
if (p8 == 0 && p9 == 1) ++ap;
if (p9 == 0 && p2 == 1) ++ap;
if (ap == 1 && p2 * p4 * p8 == 0 && p2 * p6 * p8 == 0) {
mFlag.push_back(p + j);
}
}
}
}
for (std::vector<uchar *>::iterator i = mFlag.begin(); i != mFlag.end(); ++i)
{
**i = 0;
}
if (mFlag.empty()) {
break;
}
else {
mFlag.clear();//œ«mFlagÇå¿Õ
}
}
dst.copyTo(thined_img);
} | 36.630137 | 115 | 0.338444 | [
"vector"
] |
177bf231bca52a32f4a7864f16f4e279c8c94524 | 12,612 | cpp | C++ | src/vehicle.cpp | jandal487/CarND-Path-Planning-Project | 189f6f6213a95cb5d2c4ed3c1c606d73b7637b0d | [
"MIT"
] | null | null | null | src/vehicle.cpp | jandal487/CarND-Path-Planning-Project | 189f6f6213a95cb5d2c4ed3c1c606d73b7637b0d | [
"MIT"
] | null | null | null | src/vehicle.cpp | jandal487/CarND-Path-Planning-Project | 189f6f6213a95cb5d2c4ed3c1c606d73b7637b0d | [
"MIT"
] | null | null | null | #include <algorithm>
#include <iostream>
#include "vehicle.h"
#include "road.h"
#include <cmath>
#include <math.h>
#include <map>
#include <string>
#include <iterator>
#include "cost.h"
// Initializes Vehicle
Vehicle::Vehicle(){}
// Initializes custom Vehicle object
Vehicle::Vehicle(int lane, float s,float d, float v_s, float a_s, string state, int target_lane) {
this->lane = lane;
this->s = s;
this->d = d;
this->v_s = v_s;
this->a_s = a_s;
this->state = state;
this->target_lane = target_lane;
}
// Destructor
Vehicle::~Vehicle() {}
// Vehile actions
vector<Vehicle> Vehicle::choose_next_state(map<int, vector<Vehicle>> predictions, float time_window) {
/**
* Here you can implement the transition_function code from the Behavior
* Planning Pseudocode classroom concept.
*
* @param A predictions map. This is a map of vehicle id keys with predicted
* vehicle trajectories as values. Trajectories are a vector of Vehicle
* objects representing the vehicle at the current timestep and one timestep
* in the future.
* @output The best (lowest cost) trajectory corresponding to the next ego
* vehicle state.
*
* Functions that will be useful:
* 1. successor_states - Uses the current state to return a vector of possible
* successor states for the finite state machine.
* 2. generate_trajectory - Returns a vector of Vehicle objects representing
* a vehicle trajectory, given a state and predictions. Note that
* trajectory vectors might have size 0 if no possible trajectory exists
* for the state.
* 3. calculate_cost - Included from cost.cpp, computes the cost for a trajectory.
*
*/
vector<string> states = successor_states();
float cost;
vector<float> costs;
vector<vector<Vehicle>> final_trajectories;
float max_dist = this->goal_s;
for (vector<string>::iterator it = states.begin(); it != states.end(); ++it) {
vector<Vehicle> trajectory = generate_trajectory(*it, predictions, time_window);
if (trajectory.size() > 1) {
cost = calculate_cost(trajectory,max_dist);
costs.push_back(cost);
final_trajectories.push_back(trajectory);
}
}
vector<float>::iterator best_cost = min_element(begin(costs), end(costs));
int best_idx = distance(begin(costs), best_cost);
return final_trajectories[best_idx];
}
vector<string> Vehicle::successor_states() {
// Provides the possible next states given the current state for the FSM
// discussed in the course, with the exception that lane changes happen
// instantaneously, so LCL and LCR can only transition back to KL.
vector<string> states;
states.push_back("KL");
string state = this->state;
if(state.compare("KL") == 0 && this->lane < 2){
states.push_back("LCR");
}
if(state.compare("KL") == 0 && this->lane > 0){
states.push_back("LCL");
}
//If state is "LCL" or "LCR", then just return "KL"
return states;
}
vector<Vehicle> Vehicle::generate_trajectory(string state, map<int, vector<Vehicle>> predictions, float time_window) {
// Given a possible next state, generate the appropriate trajectory to realize
// the next state.
vector<Vehicle> trajectory;
if (state.compare("CS") == 0) {
trajectory = constant_speed_trajectory(time_window);
} else if (state.compare("KL") == 0) {
trajectory = keep_lane_trajectory(predictions,time_window);
} else if (state.compare("LCL") == 0 || state.compare("LCR") == 0) {
trajectory = lane_change_trajectory(state, predictions,time_window);
} else if (state.compare("PLCL") == 0 || state.compare("PLCR") == 0) {
trajectory = prep_lane_change_trajectory(state, predictions,time_window);
}
return trajectory;
}
vector<float> Vehicle::get_kinematics(map<int, vector<Vehicle>> predictions, int lane, float time_window) {
// Gets next timestep kinematics (position, velocity, acceleration)
// for a given lane. Tries to choose the maximum velocity and acceleration,
// given other vehicle positions and accel/velocity constraints.
float max_pos_vel = this->max_acceleration*time_window + this->v_s;
float max_neg_vel = -this->max_acceleration*time_window + this->v_s;
float new_position;
float new_velocity;
float new_accel;
Vehicle vehicle_ahead;
Vehicle vehicle_behind;
vector<double> ahead = get_vehicle_ahead(predictions, vehicle_ahead,lane);
if (ahead[0] && max_pos_vel>vehicle_ahead.v_s) {
//must travel at the speed of traffic, regardless of preferred buffer
new_velocity = max(vehicle_ahead.v_s,max_neg_vel);
new_position = this->s + new_velocity*time_window - 0.5*this->max_acceleration*time_window*time_window;
} else {
new_velocity = min(max_pos_vel, this->target_speed);
new_position = this->s + new_velocity*time_window + 0.5*this->max_acceleration*time_window*time_window;
}
new_accel = (new_velocity - this->v_s)/time_window; //Equation: (v_1 - v_0)/t = acceleration
return{new_position, new_velocity, new_accel,ahead[0], ahead[1]};
}
vector<Vehicle> Vehicle::constant_speed_trajectory(float time_window) {
// Generate a constant speed trajectory.
float next_pos_s = s_position_at(time_window);
vector<Vehicle> trajectory = {Vehicle(this->lane, this->s,this->d, this->v_s,0,this->state,this->target_lane),
Vehicle(this->lane, next_pos_s, this->d, this->v_s,0, this->state,this->target_lane)};
return trajectory;
}
vector<Vehicle> Vehicle::keep_lane_trajectory(map<int, vector<Vehicle>> predictions, float time_window) {
// Generate a keep lane trajectory.
vector<Vehicle> trajectory = {Vehicle(this->lane, this->s,this->d, this->v_s, this->a_s, this->state, this->target_lane)};
vector<float> kinematics = get_kinematics(predictions, this->lane, time_window);
float new_s = kinematics[0];
float new_v = kinematics[1];
float new_a = kinematics[2];
trajectory.push_back(Vehicle(this->lane, new_s,this->lane*4+2, new_v, new_a,"KL",this->lane));
return trajectory;
}
vector<Vehicle> Vehicle::prep_lane_change_trajectory(string state, map<int, vector<Vehicle>> predictions, float time_window) {
// Generate a trajectory preparing for a lane change.
float new_s;
float new_v;
float new_a;
Vehicle vehicle_behind;
int new_lane = this->lane + lane_direction[state];
vector<Vehicle> trajectory = {Vehicle(this->lane, this->s,this->d, this->v_s, this->a_s,this->state,this->target_lane)};
vector<float> curr_lane_new_kinematics = get_kinematics(predictions, this->lane,time_window);
if (get_vehicle_behind(predictions, vehicle_behind,lane)[0]) {
//Keep speed of current lane so as not to collide with car behind.
new_s = curr_lane_new_kinematics[0];
new_v = curr_lane_new_kinematics[1];
new_a = curr_lane_new_kinematics[2];
} else {
vector<float> best_kinematics;
vector<float> next_lane_new_kinematics = get_kinematics(predictions, new_lane,time_window);
//Choose kinematics with lowest velocity.
if (next_lane_new_kinematics[1] < curr_lane_new_kinematics[1]) {
best_kinematics = next_lane_new_kinematics;
} else {
best_kinematics = curr_lane_new_kinematics;
}
new_s = best_kinematics[0];
new_v = best_kinematics[1];
new_a = best_kinematics[2];
}
trajectory.push_back(Vehicle(this->lane, new_s, this->d, new_v, new_a, state, this->target_lane));
return trajectory;
}
vector<Vehicle> Vehicle::lane_change_trajectory(string state, map<int, vector<Vehicle>> predictions, float time_window) {
// Generate a lane change trajectory.
int new_lane = this->lane + lane_direction[state];
float future_s = this->s_position_at(time_window);
bool car_ahead = false;
bool car_behind = false;
vector<Vehicle> trajectory;
Vehicle next_lane_vehicle;
// Check if a lane change is possible (check if another vehicle occupies that spot).
for (map<int, vector<Vehicle>>::iterator it = predictions.begin(); it != predictions.end(); ++it) {
next_lane_vehicle = it->second[0];
car_ahead = (next_lane_vehicle.s - future_s) < 5 && next_lane_vehicle.s > future_s && next_lane_vehicle.lane == new_lane;
if (car_ahead) break;
}
for (map<int, vector<Vehicle>>::iterator it = predictions.begin(); it != predictions.end(); ++it) {
next_lane_vehicle = it->second[0];
car_behind = (future_s-next_lane_vehicle.s) < 5 && next_lane_vehicle.s < future_s && next_lane_vehicle.lane == new_lane;
if (car_behind) break;
}
if(car_behind || car_ahead){
return trajectory;
}
trajectory.push_back(Vehicle(this->lane, this->s, this->d, this->v_s, this->a_s, this->state, this->target_lane));
vector<float> kinematics = get_kinematics(predictions, new_lane,time_window);
float new_d = new_lane*4+2;
trajectory.push_back(Vehicle(new_lane, kinematics[0],new_d, kinematics[1], kinematics[2], state,new_lane));
return trajectory;
}
void Vehicle::s_increment(float dt = 1) {
this->s = s_position_at(dt);
}
float Vehicle::s_position_at(float t) {
return this->s + this->v_s*t + this->max_acceleration*t*t/2.0;
}
float Vehicle::s_speed_at(float t) {
return this->v_s + this->a_s*t;
}
vector<double> Vehicle::get_vehicle_behind(map<int, vector<Vehicle>> predictions, Vehicle & rVehicle, int lane) {
// Returns a true if a vehicle is found behind the current vehicle, false
// otherwise. The passed reference rVehicle is updated if a vehicle is found.
int max_s = -1;
bool found_vehicle = false;
Vehicle temp_vehicle;
double delta_s = this->s-max_s;
for (map<int, vector<Vehicle>>::iterator it = predictions.begin(); it != predictions.end(); ++it) {
temp_vehicle = it->second[0];
int v_id=it->first;
if (temp_vehicle.lane == this->lane && temp_vehicle.s < this->s && temp_vehicle.s > max_s) {
max_s = temp_vehicle.s;
rVehicle = temp_vehicle;
found_vehicle = true;
}
}
return {found_vehicle};
}
vector<double> Vehicle::get_vehicle_ahead(map<int, vector<Vehicle>> predictions, Vehicle & rVehicle, int lane) {
// Returns a true if a vehicle is found ahead of the current vehicle, false
// otherwise. The passed reference rVehicle is updated if a vehicle is found.
int min_s = this->goal_s;
bool found_vehicle = false;
float vehicle_speed = 0;
Vehicle temp_vehicle;
double delta_s = min_s-this->s;
for (map<int, vector<Vehicle>>::iterator it = predictions.begin(); it != predictions.end(); ++it) {
int v_id = it->first;
temp_vehicle = it->second[0];
delta_s = temp_vehicle.s - this->s;
vehicle_speed = temp_vehicle.v_s;
if(v_id != -1 && temp_vehicle.lane == lane && delta_s > 0 && delta_s<30){
rVehicle = temp_vehicle;
found_vehicle = true;
break;
}
}
return {found_vehicle, delta_s, vehicle_speed};
}
vector<Vehicle> Vehicle::generate_predictions(float horizon) {
// Generates predictions for non-ego vehicles to be used in trajectory
// generation for the ego vehicle.
vector<Vehicle> predictions;
for(int i = 0; i < horizon; i++) {
float next_s = s_position_at(i);
float next_v_s = 0;
if (i < horizon-1) {
next_v_s = s_position_at(i+1) - next_s;
}
float next_a_s = 0;
if (i < horizon-2) {
next_a_s = s_speed_at(i+1) - next_v_s;
}
predictions.push_back(Vehicle(this->lane, next_s,this->d, next_v_s, next_a_s, this->state, this->target_lane));
}
return predictions;
}
void Vehicle::realize_next_state(vector<Vehicle> trajectory) {
// Sets state and kinematics for ego vehicle using the last state of the trajectory.
Vehicle next_state = trajectory[1];
this->target_lane=next_state.target_lane;
this->state = next_state.state;
this->lane = next_state.lane;
this->s = next_state.s;
this->d = next_state.d;
this->v_s = next_state.v_s;
this->a_s = next_state.a_s;
}
void Vehicle::configure(vector<float> road_data) {
// Called by simulator before simulation begins. Sets various parameters which
// will impact the ego vehicle.
target_speed = road_data[0];
lanes_available = road_data[1];
goal_s = road_data[2];
max_acceleration = road_data[3];
}
| 38.45122 | 129 | 0.679274 | [
"object",
"vector"
] |
ed00879b47a6832df659a177a14c7223a5c25266 | 16,619 | cc | C++ | internal/ceres/sparse_normal_cholesky_solver.cc | nicedone/ceres-solver-1.11.0 | bb50b160ddcbe66a731bcf4f50f5cb07f765b935 | [
"BSD-3-Clause"
] | 12 | 2016-10-08T11:47:59.000Z | 2022-01-11T13:09:24.000Z | internal/ceres/sparse_normal_cholesky_solver.cc | nicedone/ceres-solver-1.11.0 | bb50b160ddcbe66a731bcf4f50f5cb07f765b935 | [
"BSD-3-Clause"
] | 1 | 2019-05-01T07:29:55.000Z | 2019-05-01T07:29:55.000Z | internal/ceres/sparse_normal_cholesky_solver.cc | nicedone/ceres-solver-1.11.0 | bb50b160ddcbe66a731bcf4f50f5cb07f765b935 | [
"BSD-3-Clause"
] | 30 | 2016-10-09T02:59:13.000Z | 2022-01-22T10:52:14.000Z | // Ceres Solver - A fast non-linear least squares minimizer
// Copyright 2015 Google Inc. All rights reserved.
// http://ceres-solver.org/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Google Inc. nor the names of its contributors may be
// used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Author: sameeragarwal@google.com (Sameer Agarwal)
#include "ceres/sparse_normal_cholesky_solver.h"
#include <algorithm>
#include <cstring>
#include <ctime>
#include "ceres/compressed_row_sparse_matrix.h"
#include "ceres/cxsparse.h"
#include "ceres/internal/eigen.h"
#include "ceres/internal/scoped_ptr.h"
#include "ceres/linear_solver.h"
#include "ceres/suitesparse.h"
#include "ceres/triplet_sparse_matrix.h"
#include "ceres/types.h"
#include "ceres/wall_time.h"
#include "Eigen/SparseCore"
#ifdef CERES_USE_EIGEN_SPARSE
#include "Eigen/SparseCholesky"
#endif
namespace ceres {
namespace internal {
namespace {
#ifdef CERES_USE_EIGEN_SPARSE
// A templated factorized and solve function, which allows us to use
// the same code independent of whether a AMD or a Natural ordering is
// used.
template <typename SimplicialCholeskySolver, typename SparseMatrixType>
LinearSolver::Summary SimplicialLDLTSolve(
const SparseMatrixType& lhs,
const bool do_symbolic_analysis,
SimplicialCholeskySolver* solver,
double* rhs_and_solution,
EventLogger* event_logger) {
LinearSolver::Summary summary;
summary.num_iterations = 1;
summary.termination_type = LINEAR_SOLVER_SUCCESS;
summary.message = "Success.";
if (do_symbolic_analysis) {
solver->analyzePattern(lhs);
event_logger->AddEvent("Analyze");
if (solver->info() != Eigen::Success) {
summary.termination_type = LINEAR_SOLVER_FATAL_ERROR;
summary.message =
"Eigen failure. Unable to find symbolic factorization.";
return summary;
}
}
solver->factorize(lhs);
event_logger->AddEvent("Factorize");
if (solver->info() != Eigen::Success) {
summary.termination_type = LINEAR_SOLVER_FAILURE;
summary.message = "Eigen failure. Unable to find numeric factorization.";
return summary;
}
const Vector rhs = VectorRef(rhs_and_solution, lhs.cols());
VectorRef(rhs_and_solution, lhs.cols()) = solver->solve(rhs);
event_logger->AddEvent("Solve");
if (solver->info() != Eigen::Success) {
summary.termination_type = LINEAR_SOLVER_FAILURE;
summary.message = "Eigen failure. Unable to do triangular solve.";
return summary;
}
return summary;
}
#endif // CERES_USE_EIGEN_SPARSE
#ifndef CERES_NO_CXSPARSE
LinearSolver::Summary ComputeNormalEquationsAndSolveUsingCXSparse(
CompressedRowSparseMatrix* A,
double * rhs_and_solution,
EventLogger* event_logger) {
LinearSolver::Summary summary;
summary.num_iterations = 1;
summary.termination_type = LINEAR_SOLVER_SUCCESS;
summary.message = "Success.";
CXSparse cxsparse;
// Wrap the augmented Jacobian in a compressed sparse column matrix.
cs_di a_transpose = cxsparse.CreateSparseMatrixTransposeView(A);
// Compute the normal equations. J'J delta = J'f and solve them
// using a sparse Cholesky factorization. Notice that when compared
// to SuiteSparse we have to explicitly compute the transpose of Jt,
// and then the normal equations before they can be
// factorized. CHOLMOD/SuiteSparse on the other hand can just work
// off of Jt to compute the Cholesky factorization of the normal
// equations.
cs_di* a = cxsparse.TransposeMatrix(&a_transpose);
cs_di* lhs = cxsparse.MatrixMatrixMultiply(&a_transpose, a);
cxsparse.Free(a);
event_logger->AddEvent("NormalEquations");
cs_dis* factor = cxsparse.AnalyzeCholesky(lhs);
event_logger->AddEvent("Analysis");
if (factor == NULL) {
summary.termination_type = LINEAR_SOLVER_FATAL_ERROR;
summary.message = "CXSparse::AnalyzeCholesky failed.";
} else if (!cxsparse.SolveCholesky(lhs, factor, rhs_and_solution)) {
summary.termination_type = LINEAR_SOLVER_FAILURE;
summary.message = "CXSparse::SolveCholesky failed.";
}
event_logger->AddEvent("Solve");
cxsparse.Free(lhs);
cxsparse.Free(factor);
event_logger->AddEvent("TearDown");
return summary;
}
#endif // CERES_NO_CXSPARSE
} // namespace
SparseNormalCholeskySolver::SparseNormalCholeskySolver(
const LinearSolver::Options& options)
: factor_(NULL),
cxsparse_factor_(NULL),
options_(options) {
}
void SparseNormalCholeskySolver::FreeFactorization() {
if (factor_ != NULL) {
ss_.Free(factor_);
factor_ = NULL;
}
if (cxsparse_factor_ != NULL) {
cxsparse_.Free(cxsparse_factor_);
cxsparse_factor_ = NULL;
}
}
SparseNormalCholeskySolver::~SparseNormalCholeskySolver() {
FreeFactorization();
}
LinearSolver::Summary SparseNormalCholeskySolver::SolveImpl(
CompressedRowSparseMatrix* A,
const double* b,
const LinearSolver::PerSolveOptions& per_solve_options,
double * x) {
const int num_cols = A->num_cols();
VectorRef(x, num_cols).setZero();
A->LeftMultiply(b, x);
if (per_solve_options.D != NULL) {
// Temporarily append a diagonal block to the A matrix, but undo
// it before returning the matrix to the user.
scoped_ptr<CompressedRowSparseMatrix> regularizer;
if (A->col_blocks().size() > 0) {
regularizer.reset(CompressedRowSparseMatrix::CreateBlockDiagonalMatrix(
per_solve_options.D, A->col_blocks()));
} else {
regularizer.reset(new CompressedRowSparseMatrix(
per_solve_options.D, num_cols));
}
A->AppendRows(*regularizer);
}
LinearSolver::Summary summary;
switch (options_.sparse_linear_algebra_library_type) {
case SUITE_SPARSE:
summary = SolveImplUsingSuiteSparse(A, x);
break;
case CX_SPARSE:
summary = SolveImplUsingCXSparse(A, x);
break;
case EIGEN_SPARSE:
summary = SolveImplUsingEigen(A, x);
break;
default:
LOG(FATAL) << "Unknown sparse linear algebra library : "
<< options_.sparse_linear_algebra_library_type;
}
if (per_solve_options.D != NULL) {
A->DeleteRows(num_cols);
}
return summary;
}
LinearSolver::Summary SparseNormalCholeskySolver::SolveImplUsingEigen(
CompressedRowSparseMatrix* A,
double * rhs_and_solution) {
#ifndef CERES_USE_EIGEN_SPARSE
LinearSolver::Summary summary;
summary.num_iterations = 0;
summary.termination_type = LINEAR_SOLVER_FATAL_ERROR;
summary.message =
"SPARSE_NORMAL_CHOLESKY cannot be used with EIGEN_SPARSE "
"because Ceres was not built with support for "
"Eigen's SimplicialLDLT decomposition. "
"This requires enabling building with -DEIGENSPARSE=ON.";
return summary;
#else
EventLogger event_logger("SparseNormalCholeskySolver::Eigen::Solve");
// Compute the normal equations. J'J delta = J'f and solve them
// using a sparse Cholesky factorization. Notice that when compared
// to SuiteSparse we have to explicitly compute the normal equations
// before they can be factorized. CHOLMOD/SuiteSparse on the other
// hand can just work off of Jt to compute the Cholesky
// factorization of the normal equations.
if (options_.dynamic_sparsity) {
// In the case where the problem has dynamic sparsity, it is not
// worth using the ComputeOuterProduct routine, as the setup cost
// is not amortized over multiple calls to Solve.
Eigen::MappedSparseMatrix<double, Eigen::RowMajor> a(
A->num_rows(),
A->num_cols(),
A->num_nonzeros(),
A->mutable_rows(),
A->mutable_cols(),
A->mutable_values());
Eigen::SparseMatrix<double> lhs = a.transpose() * a;
Eigen::SimplicialLDLT<Eigen::SparseMatrix<double> > solver;
return SimplicialLDLTSolve(lhs,
true,
&solver,
rhs_and_solution,
&event_logger);
}
if (outer_product_.get() == NULL) {
outer_product_.reset(
CompressedRowSparseMatrix::CreateOuterProductMatrixAndProgram(
*A, &pattern_));
}
CompressedRowSparseMatrix::ComputeOuterProduct(
*A, pattern_, outer_product_.get());
// Map to an upper triangular column major matrix.
//
// outer_product_ is a compressed row sparse matrix and in lower
// triangular form, when mapped to a compressed column sparse
// matrix, it becomes an upper triangular matrix.
Eigen::MappedSparseMatrix<double, Eigen::ColMajor> lhs(
outer_product_->num_rows(),
outer_product_->num_rows(),
outer_product_->num_nonzeros(),
outer_product_->mutable_rows(),
outer_product_->mutable_cols(),
outer_product_->mutable_values());
bool do_symbolic_analysis = false;
// If using post ordering or an old version of Eigen, we cannot
// depend on a preordered jacobian, so we work with a SimplicialLDLT
// decomposition with AMD ordering.
if (options_.use_postordering ||
!EIGEN_VERSION_AT_LEAST(3, 2, 2)) {
if (amd_ldlt_.get() == NULL) {
amd_ldlt_.reset(new SimplicialLDLTWithAMDOrdering);
do_symbolic_analysis = true;
}
return SimplicialLDLTSolve(lhs,
do_symbolic_analysis,
amd_ldlt_.get(),
rhs_and_solution,
&event_logger);
}
#if EIGEN_VERSION_AT_LEAST(3,2,2)
// The common case
if (natural_ldlt_.get() == NULL) {
natural_ldlt_.reset(new SimplicialLDLTWithNaturalOrdering);
do_symbolic_analysis = true;
}
return SimplicialLDLTSolve(lhs,
do_symbolic_analysis,
natural_ldlt_.get(),
rhs_and_solution,
&event_logger);
#endif
#endif // EIGEN_USE_EIGEN_SPARSE
}
LinearSolver::Summary SparseNormalCholeskySolver::SolveImplUsingCXSparse(
CompressedRowSparseMatrix* A,
double * rhs_and_solution) {
#ifdef CERES_NO_CXSPARSE
LinearSolver::Summary summary;
summary.num_iterations = 0;
summary.termination_type = LINEAR_SOLVER_FATAL_ERROR;
summary.message =
"SPARSE_NORMAL_CHOLESKY cannot be used with CX_SPARSE "
"because Ceres was not built with support for CXSparse. "
"This requires enabling building with -DCXSPARSE=ON.";
return summary;
#else
EventLogger event_logger("SparseNormalCholeskySolver::CXSparse::Solve");
if (options_.dynamic_sparsity) {
return ComputeNormalEquationsAndSolveUsingCXSparse(A,
rhs_and_solution,
&event_logger);
}
LinearSolver::Summary summary;
summary.num_iterations = 1;
summary.termination_type = LINEAR_SOLVER_SUCCESS;
summary.message = "Success.";
// Compute the normal equations. J'J delta = J'f and solve them
// using a sparse Cholesky factorization. Notice that when compared
// to SuiteSparse we have to explicitly compute the normal equations
// before they can be factorized. CHOLMOD/SuiteSparse on the other
// hand can just work off of Jt to compute the Cholesky
// factorization of the normal equations.
if (outer_product_.get() == NULL) {
outer_product_.reset(
CompressedRowSparseMatrix::CreateOuterProductMatrixAndProgram(
*A, &pattern_));
}
CompressedRowSparseMatrix::ComputeOuterProduct(
*A, pattern_, outer_product_.get());
cs_di lhs =
cxsparse_.CreateSparseMatrixTransposeView(outer_product_.get());
event_logger.AddEvent("Setup");
// Compute symbolic factorization if not available.
if (cxsparse_factor_ == NULL) {
if (options_.use_postordering) {
cxsparse_factor_ = cxsparse_.BlockAnalyzeCholesky(&lhs,
A->col_blocks(),
A->col_blocks());
} else {
cxsparse_factor_ = cxsparse_.AnalyzeCholeskyWithNaturalOrdering(&lhs);
}
}
event_logger.AddEvent("Analysis");
if (cxsparse_factor_ == NULL) {
summary.termination_type = LINEAR_SOLVER_FATAL_ERROR;
summary.message =
"CXSparse failure. Unable to find symbolic factorization.";
} else if (!cxsparse_.SolveCholesky(&lhs,
cxsparse_factor_,
rhs_and_solution)) {
summary.termination_type = LINEAR_SOLVER_FAILURE;
summary.message = "CXSparse::SolveCholesky failed.";
}
event_logger.AddEvent("Solve");
return summary;
#endif
}
LinearSolver::Summary SparseNormalCholeskySolver::SolveImplUsingSuiteSparse(
CompressedRowSparseMatrix* A,
double * rhs_and_solution) {
#ifdef CERES_NO_SUITESPARSE
LinearSolver::Summary summary;
summary.num_iterations = 0;
summary.termination_type = LINEAR_SOLVER_FATAL_ERROR;
summary.message =
"SPARSE_NORMAL_CHOLESKY cannot be used with SUITE_SPARSE "
"because Ceres was not built with support for SuiteSparse. "
"This requires enabling building with -DSUITESPARSE=ON.";
return summary;
#else
EventLogger event_logger("SparseNormalCholeskySolver::SuiteSparse::Solve");
LinearSolver::Summary summary;
summary.termination_type = LINEAR_SOLVER_SUCCESS;
summary.num_iterations = 1;
summary.message = "Success.";
const int num_cols = A->num_cols();
cholmod_sparse lhs = ss_.CreateSparseMatrixTransposeView(A);
event_logger.AddEvent("Setup");
if (options_.dynamic_sparsity) {
FreeFactorization();
}
if (factor_ == NULL) {
if (options_.use_postordering) {
factor_ = ss_.BlockAnalyzeCholesky(&lhs,
A->col_blocks(),
A->row_blocks(),
&summary.message);
} else {
if (options_.dynamic_sparsity) {
factor_ = ss_.AnalyzeCholesky(&lhs, &summary.message);
} else {
factor_ = ss_.AnalyzeCholeskyWithNaturalOrdering(&lhs,
&summary.message);
}
}
}
event_logger.AddEvent("Analysis");
if (factor_ == NULL) {
summary.termination_type = LINEAR_SOLVER_FATAL_ERROR;
// No need to set message as it has already been set by the
// symbolic analysis routines above.
return summary;
}
summary.termination_type = ss_.Cholesky(&lhs, factor_, &summary.message);
if (summary.termination_type != LINEAR_SOLVER_SUCCESS) {
return summary;
}
cholmod_dense* rhs = ss_.CreateDenseVector(rhs_and_solution,
num_cols,
num_cols);
cholmod_dense* solution = ss_.Solve(factor_, rhs, &summary.message);
event_logger.AddEvent("Solve");
ss_.Free(rhs);
if (solution != NULL) {
memcpy(rhs_and_solution, solution->x, num_cols * sizeof(*rhs_and_solution));
ss_.Free(solution);
} else {
// No need to set message as it has already been set by the
// numeric factorization routine above.
summary.termination_type = LINEAR_SOLVER_FAILURE;
}
event_logger.AddEvent("Teardown");
return summary;
#endif
}
} // namespace internal
} // namespace ceres
| 34.125257 | 80 | 0.68867 | [
"vector"
] |
ed019ce144230a7bb343eb8e77349c036eff93b2 | 5,427 | hpp | C++ | E3T/E3T/src/Shader.hpp | oj002/Educational_3d_Toolbox | 309376a8dfcc22801482f2ee31b66982572f7424 | [
"WTFPL"
] | null | null | null | E3T/E3T/src/Shader.hpp | oj002/Educational_3d_Toolbox | 309376a8dfcc22801482f2ee31b66982572f7424 | [
"WTFPL"
] | null | null | null | E3T/E3T/src/Shader.hpp | oj002/Educational_3d_Toolbox | 309376a8dfcc22801482f2ee31b66982572f7424 | [
"WTFPL"
] | null | null | null | #pragma once
#include <string>
#include <fstream>
#include <sstream>
#include <functional>
#include <vector>
#include "Macros.hpp"
#include <glad\glad.h>
#include <glm\glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <imgui\imgui.h>
#include <imgui\imgui_impl_glfw.h>
#include <imgui\imgui_impl_opengl3.h>
#include <map>
#include <unordered_map>
namespace E3T
{
class Shader
{
public:
Shader();
~Shader() { GLCall(glDeleteProgram(m_rendererID)); }
inline void bind() const noexcept { GLCall(glUseProgram(m_rendererID)); }
inline void unbind() const noexcept { GLCall(glUseProgram(0)); }
inline void setBool(const std::string& name, bool v) { GLCall(glUniform1i(getUniformLocation(name), v)); }
inline void setBVec2(const std::string& name, const glm::bvec2& vec) { GLCall(glUniform2i(getUniformLocation(name), vec.x, vec.y)); }
inline void setBVec3(const std::string& name, const glm::bvec3& vec) { GLCall(glUniform3i(getUniformLocation(name), vec.x, vec.y, vec.z)); }
inline void setBVec4(const std::string& name, const glm::bvec4& vec) { GLCall(glUniform4i(getUniformLocation(name), vec.x, vec.y, vec.z, vec.w)); }
inline void setInt(const std::string& name, int v) { GLCall(glUniform1i(getUniformLocation(name), v)); }
inline void setIVec2(const std::string& name, const glm::ivec2& vec) { GLCall(glUniform2i(getUniformLocation(name), vec.x, vec.y)); }
inline void setIVec3(const std::string& name, const glm::ivec3& vec) { GLCall(glUniform3i(getUniformLocation(name), vec.x, vec.y, vec.z)); }
inline void setIVec4(const std::string& name, const glm::ivec4& vec) { GLCall(glUniform4i(getUniformLocation(name), vec.x, vec.y, vec.z, vec.w)); }
inline void setUInt(const std::string& name, unsigned int v) { GLCall(glUniform1ui(getUniformLocation(name), v)); }
inline void setUVec2(const std::string& name, const glm::uvec2& vec) { GLCall(glUniform2ui(getUniformLocation(name), vec.x, vec.y)); }
inline void setUVec3(const std::string& name, const glm::uvec3& vec) { GLCall(glUniform3ui(getUniformLocation(name), vec.x, vec.y, vec.z)); }
inline void setUVec4(const std::string& name, const glm::uvec4& vec) { GLCall(glUniform4ui(getUniformLocation(name), vec.x, vec.y, vec.z, vec.w)); }
inline void setFloat(const std::string& name, float v) { GLCall(glUniform1f(getUniformLocation(name), v)); }
inline void setVec2(const std::string& name, const glm::vec2& vec) { GLCall(glUniform2f(getUniformLocation(name), vec.x, vec.y)); }
inline void setVec3(const std::string& name, const glm::vec3& vec) { GLCall(glUniform3f(getUniformLocation(name), vec.x, vec.y, vec.z)); }
inline void setVec4(const std::string& name, const glm::vec4& vec) { GLCall(glUniform4f(getUniformLocation(name), vec.x, vec.y, vec.z, vec.w)); }
inline void setDouble(const std::string& name, double v) { GLCall(glUniform1d(getUniformLocation(name), v)); }
inline void setDVec2(const std::string& name, const glm::dvec2& vec) { GLCall(glUniform2d(getUniformLocation(name), vec.x, vec.y)); }
inline void setDVec3(const std::string& name, const glm::dvec3& vec) { GLCall(glUniform3d(getUniformLocation(name), vec.x, vec.y, vec.z)); }
inline void setDVec4(const std::string& name, const glm::dvec4& vec) { GLCall(glUniform4d(getUniformLocation(name), vec.x, vec.y, vec.z, vec.w)); }
inline void setMat2(const std::string& name, const glm::mat2& mat) { GLCall(glUniformMatrix2fv(getUniformLocation(name), 1, GL_FALSE, glm::value_ptr(mat))); }
inline void setMat3(const std::string& name, const glm::mat3& mat) { GLCall(glUniformMatrix3fv(getUniformLocation(name), 1, GL_FALSE, glm::value_ptr(mat))); }
inline void setMat4(const std::string& name, const glm::mat4& mat) { GLCall(glUniformMatrix4fv(getUniformLocation(name), 1, GL_FALSE, glm::value_ptr(mat))); }
void update(const char *filepath);
void render_uniforms();
private:
std::string PaseLib(const std::string &libPath);
std::string PaseShader(const char *filePath);
unsigned int CompileShader(unsigned int type, const std::string& sourc);
void CreateShader(const std::string& fragmentShader);
int getUniformLocation(const std::string& name);
struct Library
{
unsigned int id;
std::string forward_declare;
long long lastWriteTime;
};
private:
unsigned int m_rendererID;
unsigned int m_vs;
std::map<std::string, Library> m_libs;
std::unordered_map<std::string, int> m_uniformLocationCache;
std::map<std::string, std::vector<std::function<void()>>> m_imguiCalls;
#define UNIFORM_VEC(x, name) std::map<std::string, x> u_##name
UNIFORM_VEC(bool, bool);
UNIFORM_VEC(glm::tvec2<bool>, bvec2);
UNIFORM_VEC(glm::tvec3<bool>, bvec3);
UNIFORM_VEC(glm::tvec4<bool>, bvec4);
UNIFORM_VEC(int, int);
UNIFORM_VEC(glm::tvec2<int>, ivec2);
UNIFORM_VEC(glm::tvec3<int>, ivec3);
UNIFORM_VEC(glm::tvec4<int>, ivec4);
UNIFORM_VEC(unsigned int, uint);
UNIFORM_VEC(glm::tvec2<unsigned int>, uivec2);
UNIFORM_VEC(glm::tvec3<unsigned int>, uivec3);
UNIFORM_VEC(glm::tvec4<unsigned int>, uivec4);
UNIFORM_VEC(float, float);
UNIFORM_VEC(glm::tvec2<float>, vec2);
UNIFORM_VEC(glm::tvec3<float>, vec3);
UNIFORM_VEC(glm::tvec4<float>, vec4);
UNIFORM_VEC(double, double);
UNIFORM_VEC(glm::tvec2<double>, dvec2);
UNIFORM_VEC(glm::tvec3<double>, dvec3);
UNIFORM_VEC(glm::tvec4<double>, dvec4);
#undef UNIFORM_VEC
};
}
| 45.605042 | 160 | 0.714575 | [
"vector"
] |
ed01bf8b5647bd14638f3748a4f7371191f2fe42 | 6,756 | cc | C++ | chromium/device/bluetooth/bluetooth_gatt_service_unittest.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | chromium/device/bluetooth/bluetooth_gatt_service_unittest.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | chromium/device/bluetooth/bluetooth_gatt_service_unittest.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "device/bluetooth/bluetooth_gatt_service.h"
#include "build/build_config.h"
#include "device/bluetooth/bluetooth_gatt_characteristic.h"
#include "testing/gtest/include/gtest/gtest.h"
#if defined(OS_ANDROID)
#include "device/bluetooth/test/bluetooth_test_android.h"
#elif defined(OS_MACOSX)
#include "device/bluetooth/test/bluetooth_test_mac.h"
#endif
namespace device {
#if defined(OS_ANDROID) || defined(OS_MACOSX)
class BluetoothGattServiceTest : public BluetoothTest {};
#endif
#if defined(OS_ANDROID)
TEST_F(BluetoothGattServiceTest, GetIdentifier) {
InitWithFakeAdapter();
StartLowEnergyDiscoverySession();
// 2 devices to verify unique IDs across them.
BluetoothDevice* device1 = DiscoverLowEnergyDevice(3);
BluetoothDevice* device2 = DiscoverLowEnergyDevice(4);
device1->CreateGattConnection(GetGattConnectionCallback(Call::EXPECTED),
GetConnectErrorCallback(Call::NOT_EXPECTED));
device2->CreateGattConnection(GetGattConnectionCallback(Call::EXPECTED),
GetConnectErrorCallback(Call::NOT_EXPECTED));
SimulateGattConnection(device1);
SimulateGattConnection(device2);
// 2 duplicate UUIDs creating 2 service instances on each device.
std::vector<std::string> services;
std::string uuid = "00000000-0000-1000-8000-00805f9b34fb";
services.push_back(uuid);
services.push_back(uuid);
SimulateGattServicesDiscovered(device1, services);
SimulateGattServicesDiscovered(device2, services);
BluetoothGattService* service1 = device1->GetGattServices()[0];
BluetoothGattService* service2 = device1->GetGattServices()[1];
BluetoothGattService* service3 = device2->GetGattServices()[0];
BluetoothGattService* service4 = device2->GetGattServices()[1];
// All IDs are unique, even though they have the same UUID.
EXPECT_NE(service1->GetIdentifier(), service2->GetIdentifier());
EXPECT_NE(service1->GetIdentifier(), service3->GetIdentifier());
EXPECT_NE(service1->GetIdentifier(), service4->GetIdentifier());
EXPECT_NE(service2->GetIdentifier(), service3->GetIdentifier());
EXPECT_NE(service2->GetIdentifier(), service4->GetIdentifier());
EXPECT_NE(service3->GetIdentifier(), service4->GetIdentifier());
}
#endif // defined(OS_ANDROID)
#if defined(OS_ANDROID)
TEST_F(BluetoothGattServiceTest, GetUUID) {
InitWithFakeAdapter();
StartLowEnergyDiscoverySession();
BluetoothDevice* device = DiscoverLowEnergyDevice(3);
device->CreateGattConnection(GetGattConnectionCallback(Call::EXPECTED),
GetConnectErrorCallback(Call::NOT_EXPECTED));
SimulateGattConnection(device);
// Create multiple instances with the same UUID.
BluetoothUUID uuid("00000000-0000-1000-8000-00805f9b34fb");
std::vector<std::string> services;
services.push_back(uuid.canonical_value());
services.push_back(uuid.canonical_value());
SimulateGattServicesDiscovered(device, services);
// Each has the same UUID.
EXPECT_EQ(uuid, device->GetGattServices()[0]->GetUUID());
EXPECT_EQ(uuid, device->GetGattServices()[1]->GetUUID());
}
#endif // defined(OS_ANDROID)
#if defined(OS_ANDROID)
TEST_F(BluetoothGattServiceTest, GetCharacteristics_FindNone) {
InitWithFakeAdapter();
StartLowEnergyDiscoverySession();
BluetoothDevice* device = DiscoverLowEnergyDevice(3);
device->CreateGattConnection(GetGattConnectionCallback(Call::EXPECTED),
GetConnectErrorCallback(Call::NOT_EXPECTED));
SimulateGattConnection(device);
// Simulate a service, with no Characteristics:
std::vector<std::string> services;
services.push_back("00000000-0000-1000-8000-00805f9b34fb");
SimulateGattServicesDiscovered(device, services);
BluetoothGattService* service = device->GetGattServices()[0];
EXPECT_EQ(0u, service->GetCharacteristics().size());
}
#endif // defined(OS_ANDROID)
#if defined(OS_ANDROID)
TEST_F(BluetoothGattServiceTest, GetCharacteristics_and_GetCharacteristic) {
InitWithFakeAdapter();
StartLowEnergyDiscoverySession();
BluetoothDevice* device = DiscoverLowEnergyDevice(3);
device->CreateGattConnection(GetGattConnectionCallback(Call::EXPECTED),
GetConnectErrorCallback(Call::NOT_EXPECTED));
SimulateGattConnection(device);
// Simulate a service, with several Characteristics:
std::vector<std::string> services;
services.push_back("00000000-0000-1000-8000-00805f9b34fb");
SimulateGattServicesDiscovered(device, services);
BluetoothGattService* service = device->GetGattServices()[0];
std::string characteristic_uuid1 = "11111111-0000-1000-8000-00805f9b34fb";
std::string characteristic_uuid2 = "22222222-0000-1000-8000-00805f9b34fb";
std::string characteristic_uuid3 = characteristic_uuid2; // Duplicate UUID.
std::string characteristic_uuid4 = "33333333-0000-1000-8000-00805f9b34fb";
SimulateGattCharacteristic(service, characteristic_uuid1, /* properties */ 0);
SimulateGattCharacteristic(service, characteristic_uuid2, /* properties */ 0);
SimulateGattCharacteristic(service, characteristic_uuid3, /* properties */ 0);
SimulateGattCharacteristic(service, characteristic_uuid4, /* properties */ 0);
// Verify that GetCharacteristic can retrieve characteristics again by ID,
// and that the same Characteristics come back.
EXPECT_EQ(4u, service->GetCharacteristics().size());
std::string char_id1 = service->GetCharacteristics()[0]->GetIdentifier();
std::string char_id2 = service->GetCharacteristics()[1]->GetIdentifier();
std::string char_id3 = service->GetCharacteristics()[2]->GetIdentifier();
std::string char_id4 = service->GetCharacteristics()[3]->GetIdentifier();
BluetoothUUID char_uuid1 = service->GetCharacteristics()[0]->GetUUID();
BluetoothUUID char_uuid2 = service->GetCharacteristics()[1]->GetUUID();
BluetoothUUID char_uuid3 = service->GetCharacteristics()[2]->GetUUID();
BluetoothUUID char_uuid4 = service->GetCharacteristics()[3]->GetUUID();
EXPECT_EQ(char_uuid1, service->GetCharacteristic(char_id1)->GetUUID());
EXPECT_EQ(char_uuid2, service->GetCharacteristic(char_id2)->GetUUID());
EXPECT_EQ(char_uuid3, service->GetCharacteristic(char_id3)->GetUUID());
EXPECT_EQ(char_uuid4, service->GetCharacteristic(char_id4)->GetUUID());
// GetCharacteristics & GetCharacteristic return the same object for the same
// ID:
EXPECT_EQ(service->GetCharacteristics()[0],
service->GetCharacteristic(char_id1));
EXPECT_EQ(service->GetCharacteristic(char_id1),
service->GetCharacteristic(char_id1));
}
#endif // defined(OS_ANDROID)
} // namespace device
| 44.741722 | 80 | 0.761397 | [
"object",
"vector"
] |
ed01cc4cc177dd95394aa6757288c3832c095cf7 | 382 | cpp | C++ | bit-manipulation/136-single-number.cpp | gromitsun/algorithm | 5aea12139c1b98221650063b91c0d38b965047e5 | [
"MIT"
] | null | null | null | bit-manipulation/136-single-number.cpp | gromitsun/algorithm | 5aea12139c1b98221650063b91c0d38b965047e5 | [
"MIT"
] | null | null | null | bit-manipulation/136-single-number.cpp | gromitsun/algorithm | 5aea12139c1b98221650063b91c0d38b965047e5 | [
"MIT"
] | null | null | null | /*
* Runtime: 12 ms, faster than 97.37% of C++ online submissions for Single Number.
* Memory Usage: 9.8 MB, less than 30.77% of C++ online submissions for Single Number.
*/
class Solution {
public:
int singleNumber(vector<int>& nums) {
int res = 0;
for (int x : nums)
{
res ^= x;
}
return res;
}
};
| 20.105263 | 86 | 0.52356 | [
"vector"
] |
ed0470f63f9c249ead8a188e20d3fa8d53aa8aa0 | 747 | cpp | C++ | platforms/codeforces/all/codeforces_1339_A.cpp | idfumg/algorithms | 06f85c5a1d07a965df44219b5a6bf0d43a129256 | [
"MIT"
] | 2 | 2020-09-17T09:04:00.000Z | 2020-11-20T19:43:18.000Z | platforms/codeforces/all/codeforces_1339_A.cpp | idfumg/algorithms | 06f85c5a1d07a965df44219b5a6bf0d43a129256 | [
"MIT"
] | null | null | null | platforms/codeforces/all/codeforces_1339_A.cpp | idfumg/algorithms | 06f85c5a1d07a965df44219b5a6bf0d43a129256 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cassert>
#include <limits>
#include <cmath>
#include <algorithm>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <string>
#include <array>
#include <map>
#include <set>
#include <deque>
#include <list>
#include <sstream>
#include <iomanip>
#include <numeric>
#include <climits>
#include <cstring>
#include <bitset>
#include <stack>
#include <queue>
#define MOD (1e9 + 7);
#define PI (3.14159265358979323846)
using ll = int64_t;
using ull = uint64_t;
using namespace std;
[[maybe_unused]] static auto __x = [](){ios_base::sync_with_stdio(0); cin.tie(0);};
int main() {
int t; cin >> t;
for (int i = 0; i < t; ++i) {
int n; cin >> n;
cout << n << '\n';
}
}
| 18.219512 | 83 | 0.646586 | [
"vector"
] |
ed097177c56e628c1a8670d70b1215b4933cd131 | 4,974 | cpp | C++ | Source/MultiBreakpong/PongBall.cpp | Enagan/MultiBreakPong | 509fee732ab1b2bfa3fe0e3edbbd3181ec6ea878 | [
"MIT"
] | 1 | 2018-01-31T04:10:35.000Z | 2018-01-31T04:10:35.000Z | Source/MultiBreakpong/PongBall.cpp | Enagan/MultiBreakPong | 509fee732ab1b2bfa3fe0e3edbbd3181ec6ea878 | [
"MIT"
] | null | null | null | Source/MultiBreakpong/PongBall.cpp | Enagan/MultiBreakPong | 509fee732ab1b2bfa3fe0e3edbbd3181ec6ea878 | [
"MIT"
] | null | null | null | // Fill out your copyright notice in the Description page of Project Settings.
#include "MultiBreakpong.h"
#include "PongBall.h"
#include "GameFramework/ProjectileMovementComponent.h"
#include "PongStickPawn.h"
#include "Goal.h"
#include "EngineUtils.h"
#include "Kismet/KismetMathLibrary.h"
// Sets default values
APongBall::APongBall() : fBallSpeed(1000.0f), fGraceTimeAfterGoal(2.5f)
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = false;
// We want the ball to replicate to it's heart content
SetReplicateMovement(true);
SetReplicates(true);
// Fetch required resources
static ConstructorHelpers::FObjectFinder<UStaticMesh> BallBaseMesh(TEXT("/Game/StarterContent/Shapes/Shape_Sphere.Shape_Sphere"));
static ConstructorHelpers::FObjectFinder<UMaterialInterface> BallBaseMaterial(TEXT("/Game/TwinStick/Meshes/OrangeMaterial.OrangeMaterial"));
// Apply Mesh and basic mesh properties
BallMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("BallMesh"));
RootComponent = BallMesh;
BallMesh->SetStaticMesh(BallBaseMesh.Object);
BallMesh->SetMaterial(0, BallBaseMaterial.Object);
// Prepare the OnHit notification
BallMesh->SetNotifyRigidBodyCollision(true);
BallMesh->OnComponentHit.AddDynamic(this, &APongBall::OnHit);
// Use a ProjectileMovementComponent to govern the ball movement
ProjectileMovement = CreateDefaultSubobject<UProjectileMovementComponent>(TEXT("ProjectileMovement0"));
ProjectileMovement->UpdatedComponent = BallMesh;
ProjectileMovement->InitialSpeed = 0.0f;
ProjectileMovement->MaxSpeed = fBallSpeed;
ProjectileMovement->bRotationFollowsVelocity = true;
ProjectileMovement->bShouldBounce = true;
ProjectileMovement->Bounciness = 1.0f;
ProjectileMovement->Friction = 0.0f;
ProjectileMovement->BounceVelocityStopSimulatingThreshold = 0.01f;
ProjectileMovement->ProjectileGravityScale = 0.f; // No gravity
// We want a physics simulationo, but we don't want gravity, and we want to restrict movement to a plane
BallMesh->SetSimulatePhysics(true);
BallMesh->SetEnableGravity(false);
BallMesh->SetConstraintMode(EDOFMode::XYPlane);
}
void APongBall::StartMoving_Implementation()
{
// Prepare MovementDirectionAfterSpawn, to randomly start either towards the blue player or the orange player
bool RandomInitialDirection = UKismetMathLibrary::RandomBool();
MovementDirectionAfterSpawn = FVector(RandomInitialDirection ? 1.0 : -1.0, 0.0, 0.0);
// Schedule an ApplyVelocity so the beggining of the game isn't so sudden
GetWorldTimerManager().SetTimer(ReSpawnTimer, this, &APongBall::ApplyVelocityOnRespawn, fGraceTimeAfterGoal, false);
}
bool APongBall::StartMoving_Validate()
{
// Not much to validate really
return true;
}
void APongBall::OnHit(UPrimitiveComponent * HitComp, AActor * OtherActor, UPrimitiveComponent * OtherComp, FVector NormalImpulse, const FHitResult & Hit)
{
// On a Collision, we first check if we hit a Pawn
APongStickPawn* const TestIfPawn = Cast<APongStickPawn>(OtherActor);
if (TestIfPawn)
{
// If so, we get the pawns center position and we get a direction vector from it to the center of the ball
FVector CenterToCenterVec = GetActorLocation() - OtherActor->GetActorLocation();
CenterToCenterVec.Normalize();
// We then apply this direction vector multiplied by our speed to the ball
// This gives the pawn some control over the direction of the ball, by how far from center it chooses to hit the ball from
// Just like pong
BallMesh->SetPhysicsLinearVelocity(CenterToCenterVec*fBallSpeed);
// For added bells & whistles, the ball takes over the material of the pawn, so it will changes colors as it goes back and forth between the pawns
BallMesh->SetMaterial(0, OtherComp->GetMaterial(0));
// We're done with this collision event!
return;
}
// If we didn't hit a pawn, then we might have hit a goal. Check for that.
AGoal* const TestIfGoal = Cast<AGoal>(OtherActor);
if (TestIfGoal)
{
// If so, we move the ball to the position to respawn at after goal, as dictated by the goal itself
BallMesh->SetAllPhysicsPosition(TestIfGoal->GetWhereToReSpawnAfterGoal());
// We kill all kind of velocity
BallMesh->SetPhysicsLinearVelocity(FVector::ZeroVector);
BallMesh->SetPhysicsAngularVelocity(FVector::ZeroVector);
// We get the direction of movement to take after respawn
MovementDirectionAfterSpawn = TestIfGoal->GetDirectionToMoveAfterGoal();
// And we schedule an apply velocity, so that players have some breathing room between goals
GetWorldTimerManager().SetTimer(ReSpawnTimer, this, &APongBall::ApplyVelocityOnRespawn, fGraceTimeAfterGoal, false);
}
}
void APongBall::ApplyVelocityOnRespawn()
{
// Simply multiply the vector by the ballspeed
BallMesh->SetPhysicsLinearVelocity(MovementDirectionAfterSpawn*fBallSpeed);
}
| 42.87931 | 153 | 0.77121 | [
"mesh",
"object",
"vector"
] |
ed0e86da74e5aefaf8a4027ab7198c3986bceb7e | 5,186 | cpp | C++ | gst/inference_elements/common/post_processor/meta_attacher.cpp | Rasmita-Ardu/dlstreamer_gst | 88fc68cbb052e011d51fdd0195e74a38567651a8 | [
"MIT"
] | 125 | 2020-09-18T10:50:27.000Z | 2022-02-10T06:20:59.000Z | gst/inference_elements/common/post_processor/meta_attacher.cpp | msg4rajesh/dlstreamer | 88fc68cbb052e011d51fdd0195e74a38567651a8 | [
"MIT"
] | 155 | 2020-09-10T23:32:29.000Z | 2022-02-05T07:10:26.000Z | gst/inference_elements/common/post_processor/meta_attacher.cpp | msg4rajesh/dlstreamer | 88fc68cbb052e011d51fdd0195e74a38567651a8 | [
"MIT"
] | 41 | 2020-09-15T08:49:17.000Z | 2022-01-24T10:39:36.000Z | /*******************************************************************************
* Copyright (C) 2021 Intel Corporation
*
* SPDX-License-Identifier: MIT
******************************************************************************/
#include "meta_attacher.h"
#include "gva_base_inference.h"
#include "gva_tensor_meta.h"
#include "gva_utils.h"
#include "processor_types.h"
#include "inference_backend/safe_arithmetic.h"
#include <exception>
#include <memory>
using namespace post_processing;
MetaAttacher::Ptr MetaAttacher::create(int inference_type, int inference_region,
const ModelImageInputInfo &input_image_info) {
switch (inference_type) {
case GST_GVA_DETECT_TYPE:
return MetaAttacher::Ptr(new ROIToFrameAttacher(input_image_info));
case GST_GVA_INFERENCE_TYPE:
case GST_GVA_CLASSIFY_TYPE: {
switch (inference_region) {
case FULL_FRAME:
return MetaAttacher::Ptr(new TensorToFrameAttacher(input_image_info));
case ROI_LIST:
return MetaAttacher::Ptr(new TensorToROIAttacher(input_image_info));
default:
throw std::runtime_error("Unknown inference region");
}
}
default:
throw std::runtime_error("Unknown inference type");
}
}
void ROIToFrameAttacher::attach(const TensorsTable &tensors, InferenceFrames &frames) {
checkInferenceFramesAndTensorsTable(frames, tensors);
for (size_t i = 0; i < frames.size(); ++i) {
const auto &frame = frames[i];
const auto &tensor = tensors[i];
for (size_t j = 0; j < tensor.size(); ++j) {
GstStructure *detection_tensor = tensor[j];
uint32_t x_abs, y_abs, w_abs, h_abs;
gst_structure_get_uint(detection_tensor, "x_abs", &x_abs);
gst_structure_get_uint(detection_tensor, "y_abs", &y_abs);
gst_structure_get_uint(detection_tensor, "w_abs", &w_abs);
gst_structure_get_uint(detection_tensor, "h_abs", &h_abs);
const gchar *label = gst_structure_get_string(detection_tensor, "label");
GstBuffer **writable_buffer = &frame->buffer;
gva_buffer_check_and_make_writable(writable_buffer, __PRETTY_FUNCTION__);
GstVideoRegionOfInterestMeta *roi_meta =
gst_buffer_add_video_region_of_interest_meta(*writable_buffer, label, x_abs, y_abs, w_abs, h_abs);
gst_structure_remove_field(detection_tensor, "label");
gst_structure_remove_field(detection_tensor, "x_abs");
gst_structure_remove_field(detection_tensor, "y_abs");
gst_structure_remove_field(detection_tensor, "w_abs");
gst_structure_remove_field(detection_tensor, "h_abs");
if (not roi_meta)
throw std::runtime_error("Failed to add GstVideoRegionOfInterestMeta to buffer");
gst_video_region_of_interest_meta_add_param(roi_meta, detection_tensor);
}
}
}
void TensorToFrameAttacher::attach(const TensorsTable &tensors_batch, InferenceFrames &frames) {
checkInferenceFramesAndTensorsTable(frames, tensors_batch);
for (size_t i = 0; i < frames.size(); ++i) {
GstBuffer **writable_buffer = &frames[i]->buffer;
for (GstStructure *tensor_data : tensors_batch[i]) {
gva_buffer_check_and_make_writable(writable_buffer, __PRETTY_FUNCTION__);
GstGVATensorMeta *tensor = GST_GVA_TENSOR_META_ADD(*writable_buffer);
/* Tensor Meta already creates GstStructure during initialization */
/* TODO: reduce amount of GstStructures copy from loading model-proc till attaching meta */
if (tensor->data) {
gst_structure_free(tensor->data);
}
tensor->data = tensor_data;
gst_structure_set(tensor->data, "element_id", G_TYPE_STRING,
frames[i]->gva_base_inference->model_instance_id, NULL);
}
}
}
void TensorToROIAttacher::attach(const TensorsTable &tensors_batch, InferenceFrames &frames) {
checkInferenceFramesAndTensorsTable(frames, tensors_batch);
for (size_t i = 0; i < frames.size(); ++i) {
GstBuffer *buffer = frames[i]->buffer;
GstVideoRegionOfInterestMeta *roi_meta = findROIMeta(buffer, frames[i]->roi);
if (!roi_meta) {
GST_WARNING("No detection tensors were found for this buffer in case of roi-list inference.");
continue;
}
for (GstStructure *tensor_data : tensors_batch[i]) {
gst_video_region_of_interest_meta_add_param(roi_meta, tensor_data);
frames[i]->roi_classifications.push_back(tensor_data);
}
}
}
GstVideoRegionOfInterestMeta *TensorToROIAttacher::findROIMeta(GstBuffer *buffer,
const GstVideoRegionOfInterestMeta &frame_roi) {
GstVideoRegionOfInterestMeta *meta = nullptr;
gpointer state = nullptr;
while ((meta = GST_VIDEO_REGION_OF_INTEREST_META_ITERATE(buffer, &state))) {
if (sameRegion(meta, &frame_roi)) {
return meta;
}
}
return meta;
}
| 39.287879 | 114 | 0.643849 | [
"model"
] |
ed0eb8df617ff4994bd7a83cb9c682ca60623c96 | 9,147 | cpp | C++ | src/coreclr/md/runtime/liteweightstgdb.cpp | colgreen/runtime | a62588a86730435c8953e7321d1c7072ff04bb1e | [
"MIT"
] | 1 | 2022-01-09T20:51:06.000Z | 2022-01-09T20:51:06.000Z | src/coreclr/md/runtime/liteweightstgdb.cpp | DekuDesu/runtime | 84ca939dc9931e8b4d5ab4197cdc99a4621984a6 | [
"MIT"
] | null | null | null | src/coreclr/md/runtime/liteweightstgdb.cpp | DekuDesu/runtime | 84ca939dc9931e8b4d5ab4197cdc99a4621984a6 | [
"MIT"
] | null | null | null | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//*****************************************************************************
// LiteWeightStgdb.cpp
//
//
// This contains definition of class CLiteWeightStgDB. This is light weight
// read-only implementation for accessing compressed meta data format.
//
//*****************************************************************************
#include "stdafx.h" // Precompiled header.
#include "mdfileformat.h"
#include "metamodelro.h"
#include "liteweightstgdb.h"
#include "metadatatracker.h"
#include "../hotdata/export.h"
__checkReturn
HRESULT _CallInitOnMemHelper(CLiteWeightStgdb<CMiniMd> *pStgdb, ULONG cbData, LPCVOID pData)
{
return pStgdb->InitOnMem(cbData,pData);
}
//*****************************************************************************
// Open an in-memory metadata section for read
//*****************************************************************************
template <class MiniMd>
__checkReturn
HRESULT
CLiteWeightStgdb<MiniMd>::InitOnMem(
ULONG cbData, // count of bytes in pData
LPCVOID pData) // points to meta data section in memory
{
STORAGEHEADER sHdr; // Header for the storage.
PSTORAGESTREAM pStream; // Pointer to each stream.
int bFoundMd = false; // true when compressed data found.
int i; // Loop control.
HRESULT hr = S_OK;
ULONG cbStreamBuffer;
// Don't double open.
_ASSERTE((m_pvMd == NULL) && (m_cbMd == 0));
// Validate the signature of the format, or it isn't ours.
IfFailGo(MDFormat::VerifySignature((PSTORAGESIGNATURE)pData, cbData));
// Remaining buffer size behind the stream header (pStream).
cbStreamBuffer = cbData;
// Get back the first stream.
pStream = MDFormat::GetFirstStream_Verify(&sHdr, pData, &cbStreamBuffer);
if (pStream == NULL)
{
Debug_ReportError("Invalid MetaData storage signature - cannot get the first stream header.");
IfFailGo(CLDB_E_FILE_CORRUPT);
}
// Loop through each stream and pick off the ones we need.
for (i = 0; i < sHdr.GetiStreams(); i++)
{
// Do we have enough buffer to read stream header?
if (cbStreamBuffer < sizeof(*pStream))
{
Debug_ReportError("Stream header is not within MetaData block.");
IfFailGo(CLDB_E_FILE_CORRUPT);
}
// Pick off the location and size of the data.
if (pStream->GetOffset() >= cbData)
{ // Stream data are not in the buffer. Stream header is corrupted.
Debug_ReportError("Stream data are not within MetaData block.");
IfFailGo(CLDB_E_FILE_CORRUPT);
}
void *pvCurrentData = (void *)((BYTE *)pData + pStream->GetOffset());
ULONG cbCurrentData = pStream->GetSize();
// Get next stream.
PSTORAGESTREAM pNext = pStream->NextStream_Verify();
if (pNext == NULL)
{ // Stream header is corrupted.
Debug_ReportError("Invalid stream header - cannot get next stream header.");
IfFailGo(CLDB_E_FILE_CORRUPT);
}
// Range check
if ((LPBYTE)pNext > ((LPBYTE)pData + cbData))
{
Debug_ReportError("Stream header is not within MetaData block.");
IfFailGo(CLDB_E_FILE_CORRUPT);
}
// Stream end must fit into the buffer and we have to check integer overflow (stream start is already checked)
if ((((LPBYTE)pvCurrentData + cbCurrentData) < (LPBYTE)pvCurrentData) ||
(((LPBYTE)pvCurrentData + cbCurrentData) > ((LPBYTE)pData + cbData)))
{
Debug_ReportError("Stream data are not within MetaData block.");
IfFailGo(CLDB_E_FILE_CORRUPT);
}
// String pool.
if (strcmp(pStream->GetName(), STRING_POOL_STREAM_A) == 0)
{
METADATATRACKER_ONLY(MetaDataTracker::NoteSection(TBL_COUNT + MDPoolStrings, pvCurrentData, cbCurrentData, 1));
// String pool has to end with a null-terminator, therefore we don't have to check string pool content on access.
// Shrink size of the pool to the last null-terminator found.
while (cbCurrentData != 0)
{
if (((LPBYTE)pvCurrentData)[cbCurrentData - 1] == 0)
{ // We have found last null terminator
break;
}
// Shrink size of the pool
cbCurrentData--;
Debug_ReportError("String heap/pool does not end with null-terminator ... shrinking the heap.");
}
// Initialize string heap with null-terminated block of data
IfFailGo(m_MiniMd.m_StringHeap.Initialize(
MetaData::DataBlob((BYTE *)pvCurrentData, cbCurrentData),
FALSE)); // fCopyData
}
// Literal String Blob pool.
else if (strcmp(pStream->GetName(), US_BLOB_POOL_STREAM_A) == 0)
{
METADATATRACKER_ONLY(MetaDataTracker::NoteSection(TBL_COUNT + MDPoolUSBlobs, pvCurrentData, cbCurrentData, 1));
// Initialize user string heap with block of data
IfFailGo(m_MiniMd.m_UserStringHeap.Initialize(
MetaData::DataBlob((BYTE *)pvCurrentData, cbCurrentData),
FALSE)); // fCopyData
}
// GUID pool.
else if (strcmp(pStream->GetName(), GUID_POOL_STREAM_A) == 0)
{
METADATATRACKER_ONLY(MetaDataTracker::NoteSection(TBL_COUNT + MDPoolGuids, pvCurrentData, cbCurrentData, 1));
// Initialize guid heap with block of data
IfFailGo(m_MiniMd.m_GuidHeap.Initialize(
MetaData::DataBlob((BYTE *)pvCurrentData, cbCurrentData),
FALSE)); // fCopyData
}
// Blob pool.
else if (strcmp(pStream->GetName(), BLOB_POOL_STREAM_A) == 0)
{
METADATATRACKER_ONLY(MetaDataTracker::NoteSection(TBL_COUNT + MDPoolBlobs, pvCurrentData, cbCurrentData, 1));
// Initialize blob heap with block of data
IfFailGo(m_MiniMd.m_BlobHeap.Initialize(
MetaData::DataBlob((BYTE *)pvCurrentData, cbCurrentData),
FALSE)); // fCopyData
}
// Found the compressed meta data stream.
else if (strcmp(pStream->GetName(), COMPRESSED_MODEL_STREAM_A) == 0)
{
IfFailGo( m_MiniMd.InitOnMem(pvCurrentData, cbCurrentData) );
bFoundMd = true;
}
// Found the hot meta data stream
else if (strcmp(pStream->GetName(), HOT_MODEL_STREAM_A) == 0)
{
Debug_ReportError("MetaData hot stream is peresent, but ngen is not supported.");
// Ignore the stream
}
// Pick off the next stream if there is one.
pStream = pNext;
cbStreamBuffer = (ULONG)((LPBYTE)pData + cbData - (LPBYTE)pNext);
}
// If the meta data wasn't found, we can't handle this file.
if (!bFoundMd)
{
Debug_ReportError("MetaData compressed model stream #~ not found.");
IfFailGo(CLDB_E_FILE_CORRUPT);
}
else
{ // Validate sensible heaps.
IfFailGo(m_MiniMd.PostInit(0));
}
// Save off the location.
m_pvMd = pData;
m_cbMd = cbData;
ErrExit:
return hr;
} // CLiteWeightStgdb<MiniMd>::InitOnMem
template <class MiniMd>
__checkReturn
HRESULT
CLiteWeightStgdb<MiniMd>::InitHotPools(
DataBuffer hotMetaDataBuffer)
{
HRESULT hr;
MetaData::HotMetaData hotMetaData;
MetaData::HotHeapsDirectoryIterator heapsIterator;
IfFailRet(hotMetaData.Initialize(hotMetaDataBuffer));
IfFailRet(hotMetaData.GetHeapsDirectoryIterator(&heapsIterator));
for (;;)
{
MetaData::HotHeap hotHeap;
MetaData::HeapIndex hotHeapIndex;
hr = heapsIterator.GetNext(&hotHeap, &hotHeapIndex);
if (hr == S_FALSE)
{ // End of iteration
return S_OK;
}
switch (hotHeapIndex.Get())
{
case MetaData::HeapIndex::StringHeapIndex:
{
m_MiniMd.m_StringHeap.InitializeHotData(hotHeap);
break;
}
case MetaData::HeapIndex::GuidHeapIndex:
{
m_MiniMd.m_GuidHeap.InitializeHotData(hotHeap);
break;
}
case MetaData::HeapIndex::UserStringHeapIndex:
{
m_MiniMd.m_UserStringHeap.InitializeHotData(hotHeap);
break;
}
case MetaData::HeapIndex::BlobHeapIndex:
{
m_MiniMd.m_BlobHeap.InitializeHotData(hotHeap);
break;
}
default:
Debug_ReportInternalError("There's a bug in HotHeapsDirectoryIterator - it should verify the heap index.");
IfFailRet(METADATA_E_INTERNAL_ERROR);
}
}
} // CLiteWeightStgdb<MiniMd>::InitHotPools
| 37.641975 | 125 | 0.58839 | [
"model"
] |
ed12f7ec3d791058ebd5e4791ae14015425da885 | 13,768 | cpp | C++ | ANattr/src/NodeAttr.cpp | ecmwf/ecflow | 2498d0401d3d1133613d600d5c0e0a8a30b7b8eb | [
"Apache-2.0"
] | 11 | 2020-08-07T14:42:45.000Z | 2021-10-21T01:59:59.000Z | ANattr/src/NodeAttr.cpp | CoollRock/ecflow | db61dddc84d3d2c7dd6af95fd799d717c6bc2a6d | [
"Apache-2.0"
] | 10 | 2020-08-07T14:36:27.000Z | 2022-02-22T06:51:24.000Z | ANattr/src/NodeAttr.cpp | CoollRock/ecflow | db61dddc84d3d2c7dd6af95fd799d717c6bc2a6d | [
"Apache-2.0"
] | 6 | 2020-08-07T14:34:38.000Z | 2022-01-10T12:06:27.000Z | //============================================================================
// Name :
// Author : Avi
// Revision : $Revision: #67 $
//
// Copyright 2009-2020 ECMWF.
// This software is licensed under the terms of the Apache Licence version 2.0
// which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
// In applying this licence, ECMWF does not waive the privileges and immunities
// granted to it by virtue of its status as an intergovernmental organisation
// nor does it submit to any jurisdiction.
//
// Description :
//============================================================================
#include <stdexcept>
#include <sstream>
#include <boost/lexical_cast.hpp>
#include "NodeAttr.hpp"
#include "Indentor.hpp"
#include "PrintStyle.hpp"
#include "Str.hpp"
#include "Ecf.hpp"
#include "Serialization.hpp"
using namespace std;
using namespace ecf;
const std::string& Event::SET() { static const std::string SET = "set"; return SET; }
const std::string& Event::CLEAR() { static const std::string CLEAR = "clear"; return CLEAR; }
const Event& Event::EMPTY() { static const Event EVENT = Event(); return EVENT ; }
const Meter& Meter::EMPTY() { static const Meter METER = Meter(); return METER ; }
const Label& Label::EMPTY() { static const Label LABEL = Label(); return LABEL ; }
////////////////////////////////////////////////////////////////////////////////////////////
Event::Event( int number, const std::string& eventName,bool iv, bool check_name )
: n_( eventName ), number_( number ), v_( iv ), iv_(iv)
{
if ( !eventName.empty() && check_name) {
string msg;
if ( !Str::valid_name( eventName, msg ) ) {
throw std::runtime_error( "Event::Event: Invalid event name : " + msg );
}
}
}
Event::Event( const std::string& eventName, bool iv )
: n_( eventName ), v_(iv), iv_(iv)
{
if ( eventName.empty() ) {
throw std::runtime_error( "Event::Event: Invalid event name : name must be specified if no number supplied");
}
// If the eventName is a integer, then treat it as such, by setting number_ and clearing n_
// This was added after migration failed, since *python* api allowed:
// ta.add_event(1);
// ta.add_event("1");
// and when we called ecflow_client --migrate/--get it generated
// event 1
// event 1
// which then did *not* load.
//
// Test for numeric, and then casting, is ****faster***** than relying on exception alone
if ( eventName.find_first_of( Str::NUMERIC() ) == 0 ) {
try {
number_ = boost::lexical_cast< int >( eventName );
n_.clear();
return;
}
catch ( boost::bad_lexical_cast& ) {
// cast failed, a real string, carry on
}
}
string msg;
if ( !Str::valid_name( eventName, msg ) ) {
throw std::runtime_error( "Event::Event: Invalid event name : " + msg );
}
}
void Event::set_value( bool b ) {
v_ = b;
state_change_no_ = Ecf::incr_state_change_no();
#ifdef DEBUG_STATE_CHANGE_NO
std::cout << "Event::set_value\n";
#endif
}
std::string Event::name_or_number() const {
if ( n_.empty() ) {
std::stringstream ss;
ss << number_;
return ss.str();
}
return n_;
}
bool Event::operator<(const Event& rhs) const
{
if (!n_.empty() && !rhs.name().empty()) {
return n_ < rhs.name();
}
if (n_.empty() && rhs.name().empty()) {
return number_ < rhs.number();
}
return name_or_number() < rhs.name_or_number();
}
bool Event::operator==( const Event& rhs ) const {
if ( v_ != rhs.v_ ) {
#ifdef DEBUG
if (Ecf::debug_equality()) {
std::cout << "v_ != rhs.v_ (v_:" << v_ << " rhs.v_:" << rhs.v_ << ") " << toString() << "\n";
}
#endif
return false;
}
if ( number_ != rhs.number_ ) {
#ifdef DEBUG
if (Ecf::debug_equality()) {
std::cout << "number_ != rhs.number_ (number_:" << number_ << " rhs.number_:" << rhs.number_ << ") " << toString() << "\n";
}
#endif
return false;
}
if ( n_ != rhs.n_ ) {
#ifdef DEBUG
if (Ecf::debug_equality()) {
std::cout << "n_ != rhs.n_ (n_:" << n_ << " rhs.n_:" << rhs.n_ << ") " << toString() << "\n";
}
#endif
return false;
}
if ( iv_ != rhs.iv_ ) {
#ifdef DEBUG
if (Ecf::debug_equality()) {
std::cout << "iv_ != rhs.iv_ (iv_:" << iv_ << " rhs.iv_:" << rhs.iv_ << ") " << toString() << "\n";
}
#endif
return false;
}
return true;
}
bool Event::compare(const Event& rhs) const
{
if ( number_ != rhs.number_ ) {
return false;
}
if ( n_ != rhs.n_ ) {
return false;
}
return true;
}
void Event::print( std::string& os ) const {
Indentor in;
Indentor::indent( os ); write(os);
if ( !PrintStyle::defsStyle() ) {
if (iv_ != v_) { // initial value and value differ
if (v_) { os += " # " ; os += Event::SET(); }
else { os += " # " ; os += Event::CLEAR(); }
}
}
os += "\n";
}
std::string Event::toString() const {
std::string ret;
write(ret);
return ret;
}
void Event::write(std::string& ret) const
{
ret += "event ";
if ( number_ == std::numeric_limits< int >::max() ) ret += n_;
else {
ret += boost::lexical_cast<std::string>(number_);
ret += " ";
ret += n_;
}
if (iv_) ret += " set"; // initial value
}
std::string Event::dump() const {
std::stringstream ss;
ss << toString() << " value(" << v_ << ") used(" << used_ << ")";
return ss.str();
}
bool Event::isValidState( const std::string& state ) {
if ( state == Event::SET() )
return true;
if ( state == Event::CLEAR() )
return true;
return false;
}
////////////////////////////////////////////////////////////////////////////////////////////
Meter::Meter( const std::string& name, int min, int max, int colorChange, int value, bool check ) :
min_( min ), max_( max ), v_( value ), cc_( colorChange ),
n_( name )
{
if (check) {
if ( !Str::valid_name( name ) ) {
throw std::runtime_error("Meter::Meter: Invalid Meter name: " + name);
}
}
if ( min > max )
throw std::out_of_range( "Meter::Meter: Invalid Meter(name,min,max,color_change) : min must be less than max" );
if (colorChange == std::numeric_limits<int>::max()) {
cc_ = max_;
}
if (value == std::numeric_limits<int>::max()) {
v_ = min_;
}
if ( cc_ < min || cc_ > max ) {
std::stringstream ss;
ss << "Meter::Meter: Invalid Meter(name,min,max,color_change) color_change(" << cc_ << ") must be between min(" << min_ << ") and max(" << max_ << ")";
throw std::out_of_range( ss.str() );
}
}
void Meter::set_value( int v ) {
if (!isValidValue( v )) {
std::stringstream ss;
ss << "Meter::set_value(int): The meter(" << n_ << ") value must be in the range[" << min() << "->" << max() << "] but found '" << v << "'";
throw std::runtime_error( ss.str() );
}
v_ = v;
state_change_no_ = Ecf::incr_state_change_no();
#ifdef DEBUG_STATE_CHANGE_NO
std::cout << "Meter::set_value\n";
#endif
}
bool Meter::operator==( const Meter& rhs ) const {
if ( v_ != rhs.v_ ) {
return false;
}
if ( min_ != rhs.min_ ) {
return false;
}
if ( max_ != rhs.max_ ) {
return false;
}
if ( cc_ != rhs.cc_ ) {
return false;
}
if ( n_ != rhs.n_ ) {
return false;
}
return true;
}
void Meter::print( std::string& os ) const {
Indentor in;
Indentor::indent( os ) ; write(os);
if ( !PrintStyle::defsStyle() ) {
if (v_ != min_) { os += " # " ; os += boost::lexical_cast<std::string>(v_); }
}
os += "\n";
}
std::string Meter::toString() const {
std::string ret;
write(ret);
return ret;
}
void Meter::write(std::string& ret) const {
ret += "meter ";
ret += n_; ret += " ";
ret += boost::lexical_cast<std::string>(min_); ret += " ";
ret += boost::lexical_cast<std::string>(max_); ret += " ";
ret += boost::lexical_cast<std::string>(cc_);
}
std::string Meter::dump() const {
std::stringstream ss;
ss << "meter " << n_ << " min(" << min_ << ") max (" << max_
<< ") colorChange(" << cc_ << ") value(" << v_
<< ") used(" << used_ << ")";
return ss.str();
}
/////////////////////////////////////////////////////////////////////////////////////////////
Label::Label(const std::string& name, const std::string& value, const std::string& new_value, bool check_name)
: n_(name),v_(value),new_v_(new_value),state_change_no_(0)
{
if ( check_name && !Str::valid_name( n_ ) ) {
throw std::runtime_error("Label::Label: Invalid Label name :" + n_);
}
}
void Label::print( std::string& os ) const {
Indentor in;
Indentor::indent( os ) ; write(os);
if (!PrintStyle::defsStyle()) {
if (!new_v_.empty()) {
if (new_v_.find("\n") == std::string::npos) {
os += " # \"" ; os += new_v_ ; os += "\"";
}
else {
std::string value = new_v_;
Str::replaceall(value,"\n","\\n");
os += " # \"" ; os += value ; os += "\"";
}
}
}
os += "\n";
}
std::string Label::toString() const {
// parsing always STRIPS the quotes, hence add them back
std::string ret; ret.reserve(n_.size() + v_.size() + 10);
write(ret);
return ret;
}
void Label::write(std::string& ret) const {
// parsing always STRIPS the quotes, hence add them back
ret += "label ";
ret += n_;
ret += " \"";
if (v_.find("\n") == std::string::npos) ret += v_;
else {
// replace \n, otherwise re-parse will fail
std::string value = v_;
Str::replaceall(value,"\n","\\n");
ret += value;
}
ret += "\"";
}
std::string Label::dump() const {
std::stringstream ss;
ss << toString() << " : \"" << new_v_ << "\"";
return ss.str();
}
void Label::set_new_value( const std::string& l ) {
new_v_ = l;
state_change_no_ = Ecf::incr_state_change_no();
#ifdef DEBUG_STATE_CHANGE_NO
std::cout << "Label::set_new_value\n";
#endif
}
void Label::reset() {
new_v_.clear();
state_change_no_ = Ecf::incr_state_change_no();
#ifdef DEBUG_STATE_CHANGE_NO
std::cout << "Label::reset()\n";
#endif
}
void Label::parse(const std::string& line, std::vector<std::string >& lineTokens, bool parse_state)
{
parse(line,lineTokens,parse_state,n_,v_,new_v_);
}
void Label::parse(const std::string& line, std::vector<std::string >& lineTokens, bool parse_state,
std::string& the_name,std::string& the_value, std::string& the_new_value)
{
size_t line_token_size = lineTokens.size();
if ( line_token_size < 3 )
throw std::runtime_error( "Label::parse: Invalid label :" + line );
the_name = lineTokens[1];
// parsing will always STRIP single or double quotes, print will add double quotes
// label simple_label 'ecgems'
if ( line_token_size == 3 ) {
Str::removeQuotes(lineTokens[2]);
Str::removeSingleQuotes(lineTokens[2]);
the_value = lineTokens[2];
if (the_value.find("\\n") != std::string::npos) {
Str::replaceall(the_value,"\\n","\n");
}
}
else {
// label complex_label "smsfetch -F %ECF_FILES% -I %ECF_INCLUDE%" # fred
// label simple_label "fred" # "smsfetch -F %ECF_FILES% -I %ECF_INCLUDE%"
std::string value; value.reserve(line.size());
for (size_t i = 2; i < line_token_size; ++i) {
if ( lineTokens[i].at( 0 ) == '#' ) break;
if ( i != 2 ) value += " ";
value += lineTokens[i];
}
Str::removeQuotes(value);
Str::removeSingleQuotes(value);
the_value = value;
if (the_value.find("\\n") != std::string::npos) {
Str::replaceall(the_value,"\\n","\n");
}
// state
if (parse_state) {
// label name "value" # "new value"
bool comment_fnd = false;
size_t first_quote_after_comment = 0;
size_t last_quote_after_comment = 0;
for(size_t i = line.size()-1; i > 0; i--) {
if (line[i] == '#') { comment_fnd = true; break; }
if (line[i] == '"') {
if (last_quote_after_comment == 0) last_quote_after_comment = i;
first_quote_after_comment = i;
}
}
if (comment_fnd && first_quote_after_comment != last_quote_after_comment) {
std::string new_value = line.substr(first_quote_after_comment+1,last_quote_after_comment-first_quote_after_comment-1);
//std::cout << "new label = '" << new_value << "'\n";
the_new_value = new_value;
if (the_new_value.find("\\n") != std::string::npos) {
Str::replaceall(the_new_value,"\\n","\n");
}
}
}
}
}
template<class Archive>
void Label::serialize(Archive & ar)
{
ar( CEREAL_NVP(n_));
CEREAL_OPTIONAL_NVP(ar,v_, [this](){return !v_.empty();});
CEREAL_OPTIONAL_NVP(ar,new_v_, [this](){return !new_v_.empty();}); // conditionally save
}
template<class Archive>
void Event::serialize(Archive & ar)
{
CEREAL_OPTIONAL_NVP(ar,n_, [this](){return !n_.empty();});
CEREAL_OPTIONAL_NVP(ar,number_,[this](){return number_ != std::numeric_limits<int>::max();});
CEREAL_OPTIONAL_NVP(ar,v_, [this](){return v_;});
CEREAL_OPTIONAL_NVP(ar,iv_, [this](){return iv_;});
}
template<class Archive>
void Meter::serialize(Archive & ar)
{
ar( CEREAL_NVP(min_),
CEREAL_NVP(max_),
CEREAL_NVP(v_),
CEREAL_NVP(n_),
CEREAL_NVP(cc_)
);
}
CEREAL_TEMPLATE_SPECIALIZE(Label);
CEREAL_TEMPLATE_SPECIALIZE(Event);
CEREAL_TEMPLATE_SPECIALIZE(Meter);
| 28.803347 | 157 | 0.552005 | [
"vector"
] |
ed1e81469c39a650e79a5ca66f82ed7ad794af21 | 7,222 | cpp | C++ | tests/test_ndk/src.win32/cpp/net_service_internal.cpp | dios-game/dios | ce947382bcc8692ea70533d6def112a2838a9d0e | [
"MIT"
] | 1 | 2016-05-25T02:57:02.000Z | 2016-05-25T02:57:02.000Z | tests/test_ndk/src.win32/cpp/net_service_internal.cpp | dios-game/dios | ce947382bcc8692ea70533d6def112a2838a9d0e | [
"MIT"
] | null | null | null | tests/test_ndk/src.win32/cpp/net_service_internal.cpp | dios-game/dios | ce947382bcc8692ea70533d6def112a2838a9d0e | [
"MIT"
] | 1 | 2021-04-17T16:06:00.000Z | 2021-04-17T16:06:00.000Z | #include "precompiled.h"
#include "net_service_internal.h"
#include "net_connector.h"
#include "net_server.h"
// default event callback function
void defaultEventFunc(evutil_socket_t, short, void * ptr) {
timeval tv;
tv.tv_sec = 1;
tv.tv_usec = 0;
CNetService* net_service = (CNetService*)ptr;
event_add(net_service->ev(), &tv);
}
// loop thread
void * loopThreadStartFunc( void * ptr ) {
CNetService* net_service = (CNetService*)ptr;
event_base_dispatch(net_service->ev_base());
return 0;
}
// net engine
CNetService::CNetService( void ) {
ev_config_ = 0;
ev_base_ = 0;
ev_ = 0;
is_running_ = false;
}
CNetService::~CNetService( void ) {
Shutdown();
}
bool CNetService::Initialize( unsigned int recv_size ) {
// XE_NDC("NetService::Initialize");
boost::unique_lock<boost::shared_mutex> lock(running_mutex_);
if(is_running_)
{
// XE_COMPONENT_LOG( // XE_COMPONENT_LOG_LEVEL_ERROR, "net service is initialized");
return false;
}
if(recv_size == 0) {
// XE_COMPONENT_LOG(// XE_COMPONENT_LOG_LEVEL_ERROR, "recv_size cannot be 0" );
return false;
}
// tls_recv_buffer_.set_default_size(recv_size);
#ifdef WIN32
// wsa init
WSAData wsaData;
if(WSAStartup(MAKEWORD(2,2), &wsaData) != 0) {
// XE_COMPONENT_LOG( // XE_COMPONENT_LOG_LEVEL_ERROR, "net service initialize WSAStartup failed.");
return false;
}
// XE_COMPONENT_LOG( // XE_COMPONENT_LOG_LEVEL_TRACE, "wsastartup ok.");
// about thread and lock
evthread_use_windows_threads();
// XE_COMPONENT_LOG( // XE_COMPONENT_LOG_LEVEL_TRACE, "evthread_set ok.");
// get count of processors
SYSTEM_INFO sysInfo;
GetSystemInfo(&sysInfo);
// XE_COMPONENT_LOG( // XE_COMPONENT_LOG_LEVEL_TRACE, "getsysteminfo ok. numberofprocessors: %u.", sysInfo.dwNumberOfProcessors);
// event config
ev_config_ = event_config_new();
event_config_set_flag(ev_config_, EVENT_BASE_FLAG_STARTUP_IOCP);
event_config_set_num_cpus_hint(ev_config_, sysInfo.dwNumberOfProcessors);
// XE_COMPONENT_LOG( // XE_COMPONENT_LOG_LEVEL_TRACE, "event_config_set ok.");
#else
// about thread and lock
evthread_use_pthreads();
// event config
ev_config_ = event_config_new();
event_config_set_flag(ev_config_, EVENT_BASE_FLAG_EPOLL_USE_CHANGELIST);
// XE_COMPONENT_LOG(// XE_COMPONENT_LOG_LEVEL_TRACE, "event_config_set ok.");
#endif
// event base
ev_base_ = event_base_new_with_config(ev_config_);
// XE_COMPONENT_LOG( // XE_COMPONENT_LOG_LEVEL_TRACE, "event_base_new ok.");
// tv
timeval tv;
// ev token bucket cfg
tv.tv_sec = 0;
tv.tv_usec = 0;
ev_t_bucket_cfg_ = ev_token_bucket_cfg_new(EV_RATE_LIMIT_MAX, EV_RATE_LIMIT_MAX, 1024, 1024, &tv);
// XE_COMPONENT_LOG( // XE_COMPONENT_LOG_LEVEL_TRACE, "ev_token_bucket_cfg_new ok.");
// set an event
tv.tv_sec = 1;
tv.tv_usec = 0;
ev_ = evtimer_new(ev_base_, defaultEventFunc, this);
event_add(ev_, &tv);
// XE_COMPONENT_LOG( // XE_COMPONENT_LOG_LEVEL_TRACE, "event_add timer ok.");
// run loop callback
pthread_create(&loop_thread_, 0, loopThreadStartFunc, this);
// XE_COMPONENT_LOG( // XE_COMPONENT_LOG_LEVEL_TRACE, "main thread create ok.");
// start
is_running_ = true;
// XE_COMPONENT_LOG( // XE_COMPONENT_LOG_LEVEL_INFO, "Initialize Finish.");
return true;
}
bool CNetService::Shutdown( void ) {
// XE_NDC("NetService::Shutdown");
// set running flag
boost::unique_lock<boost::shared_mutex> lock(running_mutex_);
if(!is_running_)
{
// XE_COMPONENT_LOG( // XE_COMPONENT_LOG_LEVEL_ERROR, "net service is shutdowned.");
return false;
}
is_running_ = false;
// wait for all net_shut_down
net_shutdown_event_();
// XE_COMPONENT_LOG( // XE_COMPONENT_LOG_LEVEL_TRACE, "shutdown_signal_.num_slots: %d.", net_shutdown_event_.NumListeners());
while( net_shutdown_event_.NumListeners() )
{
// XE_SLEEP(2000);
// XE_COMPONENT_LOG( // XE_COMPONENT_LOG_LEVEL_TRACE, "shutdown_signal_.num_slots: %d.", net_shutdown_event_.NumListeners());
}
// leave loop;
event_base_loopexit(ev_base_, 0);
pthread_join(loop_thread_, 0);
// XE_COMPONENT_LOG( // XE_COMPONENT_LOG_LEVEL_TRACE, "waiting for thread exit.");
// free libevent object;
event_free(ev_);
event_base_free(ev_base_);
ev_token_bucket_cfg_free(ev_t_bucket_cfg_);
event_config_free(ev_config_);
// XE_COMPONENT_LOG( // XE_COMPONENT_LOG_LEVEL_TRACE, "free event environment ok.");
// XE_COMPONENT_LOG( // XE_COMPONENT_LOG_LEVEL_INFO, "Shutdown Finish.");
return true;
}
IServer::Ptr CNetService::Listen( const char * local_ip, int local_port, IConnectorSink* sink ) {
// XE_NDC("NetService::Listen");
boost::shared_lock<boost::shared_mutex> lock(running_mutex_);
if(!is_running_)
{
// XE_COMPONENT_LOG( // XE_COMPONENT_LOG_LEVEL_ERROR, "net service is shutdowned.");
return IServer::Ptr();
}
CServer::Ptr ptr(new CServer(this));
if(ptr->Init(local_ip, local_port, sink))
return ptr;
return IServer::Ptr();
}
IConnector::Ptr CNetService::Connect( const char * remote_ip, int remote_port, IConnectorSink* sink ){
// XE_NDC("NetService::Connect");
boost::shared_lock<boost::shared_mutex> lock(running_mutex_);
if(!is_running_)
{
// XE_COMPONENT_LOG( // XE_COMPONENT_LOG_LEVEL_ERROR, "net service is shutdowned.");
return IConnector::Ptr();
}
int connect_fd = socket(PF_INET, SOCK_STREAM, 0);
if(connect_fd <= 0) {
// XE_COMPONENT_LOG( // XE_COMPONENT_LOG_LEVEL_ERROR, "request socket failed.(connector(%s:%d)", remote_ip, remote_port);
return IConnector::Ptr();
}
// config address
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = inet_addr(remote_ip);
sin.sin_port = htons(remote_port);
// create connector
int result = ::connect(connect_fd, (sockaddr*)&sin, sizeof(sin));
if(result == -1) {
// XE_COMPONENT_LOG( // XE_COMPONENT_LOG_LEVEL_ERROR, "connect failed. error code: %d.(connector(%s:%d)", result, remote_ip, remote_port);
return IConnector::Ptr();
}
CConnector::Ptr ptr(new CConnector(this));
if(ptr->Init(connect_fd, sink, (struct sockaddr*)&sin))
return ptr;
return CConnector::Ptr();
}
dios::util::CEventListener CNetService::RegisterShutdownEventListener( boost::function<void()> func )
{
return net_shutdown_event_.Connect( func );
}
std::string* CNetService::recv_buffer( void )
{
// return tls_recv_buffer_.GetBuffer();
static std::string buffer;
buffer.reserve(1024);
return &buffer;
}
void CNetService::NullConnect( const char * remote_ip, int remote_port )
{
// XE_NDC("NetService::NullConnect");
int connect_fd = socket(PF_INET, SOCK_STREAM, 0);
if(connect_fd <= 0) {
// XE_COMPONENT_LOG( // XE_COMPONENT_LOG_LEVEL_ERROR, "request socket failed.(connector(%s:%d)", remote_ip, remote_port);
return;
}
// config address
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = inet_addr(remote_ip);
sin.sin_port = htons(remote_port);
// create connector
int result = ::connect(connect_fd, (sockaddr*)&sin, sizeof(sin));
if(result == -1) {
// XE_COMPONENT_LOG( // XE_COMPONENT_LOG_LEVEL_ERROR, "connect failed. error code: %d.(connector(%s:%d)", result, remote_ip, remote_port);
return;
}
CConnector::Ptr connector(new CConnector(this));
if(connector->Init(connect_fd, 0, (struct sockaddr*)&sin)){
connector->Shutdown();
}
}
| 28.772908 | 140 | 0.735807 | [
"object"
] |
ed21b3529fde94676c0765ce37553db5f0d33dfb | 8,673 | cpp | C++ | src/CommandLineParser/CommandLineParser.cpp | sebastiandaberdaku/PoCavEDT | bc4fa2d8c52d138d6eb1446f78a4162e05d97d6b | [
"BSD-3-Clause"
] | null | null | null | src/CommandLineParser/CommandLineParser.cpp | sebastiandaberdaku/PoCavEDT | bc4fa2d8c52d138d6eb1446f78a4162e05d97d6b | [
"BSD-3-Clause"
] | null | null | null | src/CommandLineParser/CommandLineParser.cpp | sebastiandaberdaku/PoCavEDT | bc4fa2d8c52d138d6eb1446f78a4162e05d97d6b | [
"BSD-3-Clause"
] | 1 | 2022-03-29T18:14:51.000Z | 2022-03-29T18:14:51.000Z | /*
* CommandLineParser.cpp
*
* Created on: Sep 6, 2014
* Author: sebastian
*/
#include "../utils/basename.h"
#include "../utils/disclaimer.h"
#include "CommandLineParser.h"
#include "CustomValidators.h"
/**
* This method parses the input command line options.
* @param argc input argc reference, i.e. the first argument of the main method
* @param argv input argv reference, i.e. the second argument of the main method
*
* @return true if all arguments are parsed correctly, false otherwise.
*/
bool CommandLineParser::parseCommandLine(int const & argc, char const * const argv[],
float & ligandRadius, float & probeRadius, float & solventRadius,
float & resolution, string & inname_protein,
string & outname_protein, string & inname_ligand,
string & outname_ligand, string & inname_radii,
float & minPocketDepth, int & topKPockets, int & topKLECavities,
int & topKPECavities, bool & hydrogen, bool & hetatm,
bool & evaluate_prediction, bool & help,
bool & version, bool & license) {
//------------------------------- command line options --------------------------------------
boost::program_options::options_description description("PoCavEDT - Protein pocket/cavity detection with Euclidean Distance Transform. Usage");
description.add_options()("help,h", "Display this help message.")
/*
* This token is used to specify the input filename. It is mandatory.
* The pqr command line token has no option name. The command line tokens which have
* no option name are called "positional options" in the boost::program_options library.
*/
("protein", boost::program_options::value<input_PDB_filename>()->required(), "Input protein PDB file.")
("ligand", boost::program_options::value<input_PDB_filename>(), "Input ligand PDB file (optional). If a candidate ligand is provided as input, the 'ligandRadius', 'probeRadius' and 'minPocketDepth' parameters will be automatically selected by the program (user input will be ignored).")
/*
* This token is used to specify the output filename.
*/
("protein_output", boost::program_options::value<filename>(), "Protein output filename. If not specified, the input protein filename (with no extension) will be used.")
("ligand_output", boost::program_options::value<filename>(), "Ligand output filename. If not specified, the input ligand filename (with no extension) will be used.")
/*
* This token is used to specify the input atom radii filename.
*/
("atom_radii", boost::program_options::value<filename>(), "File containing the radius information of each atom. If not specified, the default CHARMM22 radius values will be used.")
/*
* The -p (--probe_radius) flag is used to specify the probe radius. Default is 1.4. Optional.
*/
("ligandRadius,l", boost::program_options::value<probe_radius>()->default_value(1.4), "Ligand-sphere radius (in Å), positive floating point number (default is 1.4).")
/*
* The -p (--probe_radius) flag is used to specify the probe radius. Default is 1.4. Optional.
*/
("probeRadius,R", boost::program_options::value<probe_radius>()->default_value(4.0), "Probe-sphere radius (in Å), positive floating point number (default is 4.0). Must be greater than the ligand-sphere radius.")
("solventRadius,s", boost::program_options::value<probe_radius>()->default_value(1.4), "Solvent-sphere radius (in Å), positive floating point number (default is 1.4). Only used to compute the ligand's SES.")
/*
* The -r (--resolution) flag is used to specify the resolution of the voxel grid. Default is 4. Optional.
*/
("resolution,r", boost::program_options::value<resolution_param>()->default_value(4.0), "Resolution factor, positive floating point (default is 4.0). This value's cube determines the number of voxels per ų.")
("minPocketDepth,d", boost::program_options::value<probe_radius>(), "Minimum depth from the Probe-excluded surface of a given pocket (in Å), positive floating point number (by default it is half the probe-sphere radius).")
("topKPockets,p", boost::program_options::value<positive_int>()->default_value(3), "Number of top candidate pockets to consider, integer (default is 3). If set to -1, the program outputs all candidates.")
("topKLECavities,c", boost::program_options::value<positive_int>()->default_value(3), "Number of top candidate ligand-excluded cavities to consider, integer (default is 3). If set to -1, the program outputs all candidates.")
("topKPECavities,k", boost::program_options::value<positive_int>()->default_value(0), "Number of top candidate probe-excluded cavities to consider, integer (default is 0). If set to -1, the program outputs all candidates.")
/*
* The --hetatm flag is used to include HETATM records in the surface computation.
*/
("hetatm", "Include HETATM records in the surface computation.")
/*
* The --hetatm flag is used to include HETATM records in the surface computation.
*/
("hydrogen", "Include hydrogen atoms in the surface computation.\nNOTE: X-ray crystallography cannot resolve hydrogen atoms \
in most protein crystals, so in most PDB files, hydrogen atoms are absent. Sometimes hydrogens are added by modeling. \
Hydrogens are always present in PDB files resulting from NMR analysis, and are usually present in theoretical models.")
("evaluate_prediction", "Can be used when a candidate ligand is provided. If selected, the program will return the distance from the centers of the predicted top k pockets to the clostest ligand atom.")
/*
* The (--license) flag is used to view the program's license
* information.
*/
("license", "View license information.")
/*
* The -v (--version) flag is used to view the program's version
* information.
*/
("version,v", "Display the version number");
/*
* The input filename must be declared as positional.
*/
boost::program_options::positional_options_description p;
p.add("protein", 1);
p.add("ligand", 2);
boost::program_options::variables_map vm;
try {
//--------------------------------parsing command line options------------------------------
/*
* And it is finally specified when parsing the command line.
*/
store(boost::program_options::command_line_parser(argc, argv).options(description).positional(p).run(), vm);
if (vm.count("help")) {
cout << description;
help = true;
return true;
}
if (vm.count("version")) {
cout << "Program: " << argv[0] << ", version: " << PROGRAM_VERSION << "\n";
version = true;
return true;
}
if (vm.count("license")) {
DISCLAIMER
license = true;
return true;
}
if (vm.count("evaluate_prediction") && vm.count("ligand"))
evaluate_prediction = true;
else
evaluate_prediction = false;
if (vm.count("hetatm"))
hetatm = true;
else
hetatm = false;
if (vm.count("hydrogen"))
hydrogen = true;
else
hydrogen = false;
/*
* notify throws exceptions so we call it after the above checks
*/
notify(vm);
/* initializing variables */
inname_protein = vm["protein"].as<input_PDB_filename>().filename;
if (vm.count("protein_output")) {
outname_protein = vm["protein_output"].as<filename>().fname;
} else {
int lastindex = inname_protein.find_last_of(".");
outname_protein = basename(inname_protein.substr(0, lastindex));
}
if (vm.count("ligand")) {
inname_ligand = vm["ligand"].as<input_PDB_filename>().filename;
if (vm.count("ligand_output")) {
outname_ligand = vm["ligand_output"].as<filename>().fname;
} else {
int lastindex = inname_ligand.find_last_of(".");
outname_ligand = basename(inname_ligand.substr(0, lastindex));
}
} else {
inname_ligand = "";
outname_ligand ="";
}
if (vm.count("atom_radii")) {
inname_radii = vm["atom_radii"].as<filename>().fname;
} else {
inname_radii = "CHARMM22";
}
ligandRadius = vm["ligandRadius"].as<probe_radius>().p;
probeRadius = vm["probeRadius"].as<probe_radius>().p;
solventRadius = vm["solventRadius"].as<probe_radius>().p;
topKPockets = vm["topKPockets"].as<positive_int>().k;
topKLECavities = vm["topKLECavities"].as<positive_int>().k;
topKPECavities = vm["topKPECavities"].as<positive_int>().k;
if (vm.count("minPocketDepth")) {
minPocketDepth = vm["minPocketDepth"].as<probe_radius>().p;
} else {
minPocketDepth = 0.5 * probeRadius;
}
if (probeRadius <= ligandRadius)
throw boost::program_options::error("The ligand-probe radius must be greater than the solvent-probe radius!");
resolution = vm["resolution"].as<resolution_param>().r;
} catch (boost::program_options::error const & e) {
cerr << "error: " << e.what() << "\n";
cerr << description << "\n";
return false;
}
return true;
};
| 44.937824 | 287 | 0.700565 | [
"transform"
] |
ed26fa97218696cfcab74555bebc9c5835822177 | 1,599 | cpp | C++ | src/networks/fcnn.cpp | lsh123/yann | 4a12b7c1ee2d89d34772d647586b3018df6997db | [
"MIT"
] | 2 | 2019-08-22T18:14:44.000Z | 2020-01-01T10:25:07.000Z | src/networks/fcnn.cpp | lsh123/yann | 4a12b7c1ee2d89d34772d647586b3018df6997db | [
"MIT"
] | null | null | null | src/networks/fcnn.cpp | lsh123/yann | 4a12b7c1ee2d89d34772d647586b3018df6997db | [
"MIT"
] | null | null | null | /*
* fcnn.cpp
*
*/
#include <string>
#include <boost/assert.hpp>
#include "core/utils.h"
#include "layers/fclayer.h"
#include "fcnn.h"
using namespace std;
using namespace yann;
////////////////////////////////////////////////////////////////////////////////////////////////
//
// FullyConnectedNetwork implementation
//
yann::FullyConnectedNetwork::Params::Params() :
_input_size(0),
_output_size(0)
{
}
unique_ptr<Network>yann::FullyConnectedNetwork::create(const vector<MatrixSize> & layer_sizes)
{
YANN_CHECK_GE(layer_sizes.size(), 2); // should have at least 2 layers: input and output
auto fcnn = make_unique<Network>();
YANN_CHECK(fcnn);
for (size_t ii = 1; ii < layer_sizes.size(); ++ii) {
YANN_CHECK_GT(layer_sizes[ii - 1], 0);
YANN_CHECK_GT(layer_sizes[ii], 0);
auto layer = make_unique<FullyConnectedLayer>(layer_sizes[ii - 1], layer_sizes[ii]);
YANN_CHECK(layer);
fcnn->append_layer(std::move(layer));
}
return fcnn;
}
unique_ptr<Network>yann::FullyConnectedNetwork::create(const vector<Params> & params)
{
YANN_CHECK_GE(params.size(), 1); // should have at least 1 layer for input/output
auto fcnn = make_unique<Network>();
YANN_CHECK(fcnn);
for (const auto & param : params) {
YANN_CHECK_GT(param._input_size, 0);
YANN_CHECK_GT(param._output_size, 0);
auto layer = make_unique<FullyConnectedLayer>(param._input_size, param._output_size);
if(param._activation_function) {
layer->set_activation_function(param._activation_function);
}
fcnn->append_layer(std::move(layer));
}
return fcnn;
}
| 25.380952 | 96 | 0.66354 | [
"vector"
] |
ed26fca4e2cbb59a6d2f009622082203c910e2d5 | 18,706 | cpp | C++ | UOFinalProject/snake.cpp | SimNicolas/Snake | eeb5f1a5360a3b5277f38187f88764910ef3ccb5 | [
"Apache-2.0"
] | null | null | null | UOFinalProject/snake.cpp | SimNicolas/Snake | eeb5f1a5360a3b5277f38187f88764910ef3ccb5 | [
"Apache-2.0"
] | null | null | null | UOFinalProject/snake.cpp | SimNicolas/Snake | eeb5f1a5360a3b5277f38187f88764910ef3ccb5 | [
"Apache-2.0"
] | null | null | null | #include "snake.h"
using namespace std;
snakepart::snakepart(int col,int row)
{
x = col;
y = row;
}
snakepart::snakepart()
{
x = 0;
y = 0;
}
food::food()
{
x = 0;
y = 0;
i = 0;
// these are the basic food types
charpool[0] = '*';
charpool[1] = 'O';
charpool[2] = '&';
// this is the poison
charpool[3] = (char)219;
character = charpool[1];
}
snakeclass::snakeclass()
{
initscr();
clear();
refresh();
nodelay(stdscr,true); //if there wasn't any key pressed don't wait for keypress
keypad(stdscr,true); //init the keyboard
noecho(); //don't write
curs_set(0); //cursor invisible
getmaxyx(stdscr,termheight,termwidth);
partchar='x';
oldalchar=(char)219; // border character
etel='*';
// initialze poison
poison.i=2;
poison.character = poison.charpool[3];
// initial values
levelpoints = 500; // amount of points required to reach the next level
combo = 1;
points=0;
level = 0;
del=110000;
get=0;
increment=10000;
direction='l';
input = ' ';
pauser = ' ';
speedctrl = ' ';
srand(time(NULL));
// default size for the game window (within the larger terminal window)
width = 80;
height = 30;
}
snakeclass::~snakeclass()
{
nodelay(stdscr,false); //turn back
getch(); //wait until a key is pressed
endwin();
}
// checks conditions of leveling up;
bool snakeclass::levelcheck()
{
if (points >= levelpoints)
{
clear();
move((minheight+maxheight)/2, (minwidth+maxwidth)/2 - 24);
printw("Level %d complete! Press 'y' to go to next level", level);
placeboard();
refresh();
while (1){
input = getch();
if (input == 'y')
{
clear();
snakeclass s;
s.start(level+1,overallscore);
break;
}
}
return true;
}
else
return false;
}
void snakeclass::minspeed()
{
if (del < 10000)
{
del = 10000;
}
}
void snakeclass::maxspeed()
{
if (del > 200000)
{
del = 200000;
}
}
void snakeclass::getdefaultspeed()
{
del = 110000 - (level*10000);
}
void snakeclass::getspeed()
{
// speed increases based on level
del = del - (level*10000);
}
void snakeclass::placesnake()
{
// initial placement for snake
for(int i=0;i<5;i++)
snake.push_back(snakepart(minwidth+40+i,minheight+10));
//draw the snake
for(int i=0;i<snake.size();i++)
{
move(snake[i].y,snake[i].x);
addch(partchar);
}
}
void snakeclass::placeboard()
{
//make the game-board -- up-vertical
for(int i=minwidth;i<maxwidth-1;i++)
{
move(minheight,i);
addch(oldalchar);
}
//left-horizontal
for(int i=minheight;i<maxheight-1;i++)
{
move(i,minwidth);
addch(oldalchar);
}
//down-vertical
for(int i=minwidth;i<maxwidth-1;i++)
{
move(maxheight-2,i);
addch(oldalchar);
}
//right-horizontal
for(int i=minheight;i<maxheight-1;i++)
{
move(i,maxwidth-2);
addch(oldalchar);
}
}
// calculates the location of the board based on the dimensions of the terminal (to center it)
void snakeclass::getdimensions()
{
// if the desired game dimensions are smaller than the terminal, move to the center
// otherwise, set the max dimensions to the size of the terminal
if (termwidth > width)
{
int midwidth = termwidth/2;
maxwidth = midwidth + width/2;
minwidth = midwidth - width/2;
}
else
{
minwidth = 0;
maxwidth = termwidth;
}
if (termheight > height)
{
int midheight = termheight/2;
maxheight = midheight + height/2;
minheight = midheight - height/2;
}
else
{
minheight = 0;
maxheight = termheight;
}
}
// tracks the combo multiplier and adds points accordingly
// if the player hits the same type of food twice in a row, the combo multiplier increases, once they break the combo, it returns to 1
// the combo multiplier is multiplied by the base addition of 10 points, so a multiplier of 3 would add 30 points
void snakeclass::addpoints(){
int max = foodtrack.size(); // total size food history vector
// if the most recently acquired food matches the one previous, increase the combo multiplier, or else return it to 1.
if (foodtrack[max-1] == foodtrack[max-2])
combo++;
else
combo = 1;
// add 10 * combo multiplier to the points
points += (combo*10);
overallscore += (combo*10);
printtext();
}
void snakeclass::printtext(){
// prints out current score, combo multiplier, and current food
char curfood = ' ';
// gets the most recently eaten food (if there is one)
if (foodtrack.size() > 0){
curfood = foodtrack[foodtrack.size()-1];
}
move(maxheight-1,minwidth);
printw(" ");
move(maxheight-1,minwidth);
printw("Points: %d Combo x %d Current Food: %c",overallscore, combo, curfood);
move(maxheight-1, maxwidth-26);
printw("Next Level: %d Level: %d", (levelpoints-points),level);
}
// places new food
void snakeclass::placement()
{
place(&f);
place(&f2);
place(&poison);
}
void snakeclass::place(food *placefood)
{
//this loop runs until a valid placement location is found.
while(1)
{
// generates a random placement location
int tmpx = (rand()%(maxwidth-minwidth)+1)+minwidth;
int tmpy = (rand()%(maxheight-minheight)+1)+minheight;
// makes sure the food doesn't spawn on the snake
for(int i = 0;i < snake.size(); i++)
if(snake[i].x==tmpx && snake[i].y==tmpy)
continue;
// checks to ensure that food/poison doesn't spawn directly in front of the snake
for(int i=-3; i<3; i++)
{
for (int j=-3; j<3; j++){
if (snake[0].x == tmpx + i && snake[0].y == tmpy + j)
continue;
}
}
// makes sure the food doesn't spawn on an existing poison
for (int i = 0; i < poisontrack.size(); i++)
if (poisontrack[i].x == tmpx && poisontrack[i].y == tmpy)
continue;
// makes sure the food doesn't spawn on the edge
if(tmpx >= maxwidth-2 || tmpy >= maxheight-3)
continue;
// makes sure the food doesn't spawn on top of other food
if (tmpx == f.x && tmpy == f.y)
continue;
if (tmpx == f2.x && tmpy == f2.y)
continue;
// whichever food or poison is being placed has it's x and y set to tmpx and tmpy
placefood -> x = tmpx;
placefood -> y = tmpy;
break;
}
// if it's not poison
if (placefood -> i != 2)
{
// randomly choose from one of the 3 food characters
placefood -> character = placefood -> charpool[rand()%3];
}
// if it's poison, add the location to the poison tracking vector.
else
{
//adds the location of the poison to the poison tracker
poisontrack.push_back(*placefood);
}
// places the food on board
move(placefood -> y, placefood -> x);
addch(placefood -> character);
refresh();
}
// returns true when snake collides into game ending feature
// also handles collision with food
bool snakeclass::collision()
{
// collision with boundary
if(snake[0].x==minwidth || snake[0].x==maxwidth-1 || snake[0].y==minheight || snake[0].y==maxheight-2)
return true;
// collision with self
for(int i=2;i<snake.size();i++)
if(snake[0].x==snake[i].x && snake[0].y==snake[i].y)
return true;
// collision with poison
for (int i = 0; i < poisontrack.size(); i++)
if (snake[0].x==poisontrack[i].x && snake[0].y==poisontrack[i].y)
return true;
// collision with the food
bool foodhit = false;
// checks first food
if (snake[0].x==f.x && snake[0].y==f.y)
{
foodhit = true; // if it hits, check true
move(f2.y, f2.x);
printw(" "); // print a blank spot in the spot where food 2 was (to clear it)
foodtrack.push_back(f.character);
}
// checks second food
if (snake[0].x==f2.x && snake[0].y==f2.y)
{
foodhit = true; // if it hits, checks true
move(f.y, f.x);
printw(" "); // print a blank spot in the spot where food 1 was (to clear it)
foodtrack.push_back(f2.character);
}
// if food is hit
if(foodhit == true)
{
// increase the size of the snake
get = true;
// place new foods and poisons and allocate points
placement();
addpoints();
}else
get = false;
return false;
}
bool snakeclass::gameover()
{
// checks to see if there is a high score
savescore();
clear();
input = ' ';
//place the border
placeboard();
move((minheight+maxheight)/2,(minwidth+maxwidth)/2-4);
printw("game_over");
move((minheight+maxheight)/2+1, (minwidth+maxwidth)/2-6);
printw("play again? y/n");
refresh();
while(1)
{
if (input == 'y'){
//restart the game
return true;
}
else if (input == 'n'){
//close the game
return false;
}
input = getch();
}
}
bool snakeclass::savescore()
{
highscore h;
scores add;
add.score = overallscore;
std::vector<scores> highscores = h.load();
if (h.topscore(highscores, add) == true)
{
clear();
flushinp();
placeboard();
input = ' ';
int startrow = (minheight + maxheight) / 2 - 2;
int startcol = (minwidth + maxwidth) / 2 - 20;
move (startrow, startcol);
printw("Congratulations! You have a high score!");
move (startrow + 1, startcol);
printw("Type your initials:");
char tmpname[3];
char tmpchar;
string name = "";
flushinp();
while(strlen(tmpname) > 0)
tmpname[0] = '\0';
while (1)
{
tmpchar = getch();
if (tmpchar == ERR)
continue;
else if (tmpchar == '\n')
break;
else if (tmpchar == 8 || tmpchar == 127 || tmpchar == KEY_BACKSPACE || tmpchar == KEY_DL || tmpchar == KEY_DC || tmpchar == 7)
{
if (strlen(tmpname) > 0)
tmpname[strlen(tmpname)-1] = '\0';
}
else
strncat(tmpname,&tmpchar,1);
move(startrow+2,startcol);
printw(" ");
move(startrow+2,startcol);
printw("%s", tmpname);
if (strlen(tmpname) == 3)
break;
}
while (1)
{
move(startrow+3, startcol);
printw("Finished? y/n");
input = getch();
if (input == 'y')
{
string str(tmpname);
name = tmpname;
add.name = name;
h.save(add);
return true;
break;
}
if (input == 'n'){
savescore();
return false;
break;
}
}
}
}
void snakeclass::getkey(){
//detect key
int tmp=getch();
switch(tmp)
{
case KEY_LEFT:
if(direction != 'r')
direction = 'l';
break;
case KEY_UP:
if(direction != 'd')
direction = 'u';
break;
case KEY_DOWN:
if(direction != 'u')
direction = 'd';
break;
case KEY_RIGHT:
if(direction != 'l')
direction = 'r';
break;
case KEY_BACKSPACE:
input = 'q';
break;
case 'q':
input = 'q';
break;
case '1':
//decrease del by increment
del -= increment;
break;
case '2':
//increase del by increment
del += increment;
break;
case '3':
getdefaultspeed();
break;
case 'p':
move(maxheight-1,minwidth+41);
printw("~[ PAUSED ]~");
refresh();
while(1){
pauser = getch();
if(pauser == 'p')
{
printtext();
move(maxheight-1,minwidth+41);
printw(" ");
break;
}
else if(pauser == 'q')
{
endwin();
exit(1);
}
}
break;
}
}
void snakeclass::movesnake()
{
getkey();
//if there wasn't a collision with food
if(!get)
{
move(snake[snake.size()-1].y,snake[snake.size()-1].x);
printw(" ");
refresh();
snake.pop_back();
}
// changes direction and where the snakes are added
if(direction=='l'){
snake.insert(snake.begin(),snakepart(snake[0].x-1,snake[0].y));
}else if(direction=='r'){
snake.insert(snake.begin(),snakepart(snake[0].x+1,snake[0].y));
}else if(direction=='u'){
snake.insert(snake.begin(),snakepart(snake[0].x,snake[0].y-1));
}else if(direction=='d'){
snake.insert(snake.begin(),snakepart(snake[0].x,snake[0].y+1));
}
move(snake[0].y,snake[0].x);
addch(partchar);
refresh();
}
void snakeclass::start(int inplevel, int inpoverallscore)
{
// input level and overall score from previous level
level = inplevel;
overallscore = inpoverallscore;
// place initial snake, board, score line, speed, foods, and poison
getspeed();
getdimensions();
placeboard();
placesnake();
placement();
printtext();
refresh();
bool newgame;
bool levelup;
while(1)
{
movesnake();
if (collision())
{
newgame = gameover();
break;
}
if (input == 'q')
{
newgame = gameover(); //exit
break;
}
levelup = levelcheck();
if (levelup == true)
break;
maxspeed();
minspeed();
usleep(del); //Linux delay
}
if (newgame == true)
{
snakeclass s;
s.start(1,0);
}
else if (levelup == true)
{
start(level+1,overallscore);
}
else
{
endwin();
exit(0);
}
}
| 28.867284 | 150 | 0.408104 | [
"vector"
] |
ed2dc2a7403f60bb78a2e525aca7c707c88033c6 | 4,463 | hpp | C++ | http_server/include/testproj.hpp | kushaldalsania/haystack-cpp | 95997ae2bca9ea096dc7e61c000291f3ac08d9d7 | [
"AFL-3.0"
] | null | null | null | http_server/include/testproj.hpp | kushaldalsania/haystack-cpp | 95997ae2bca9ea096dc7e61c000291f3ac08d9d7 | [
"AFL-3.0"
] | null | null | null | http_server/include/testproj.hpp | kushaldalsania/haystack-cpp | 95997ae2bca9ea096dc7e61c000291f3ac08d9d7 | [
"AFL-3.0"
] | null | null | null | #pragma once
//
// Copyright (c) 2015, J2 Innovations
// Copyright (c) 2012 Brian Frank
// Licensed under the Academic Free License version 3.0
// History:
// 09 Sep 2014 Radu Racariu<radur@2inn.com> Ported to C++
// 06 Jun 2011 Brian Frank Creation
//
#include "server.hpp"
#include <Poco/AtomicCounter.h>
#include <Poco/RWLock.h>
#include <Poco/Timer.h>
namespace haystack
{
class Dict;
//
// TestProj provides a simple implementation of
// Server with some test entities.
//
class TestProj : public Server
{
public:
typedef boost::ptr_map<std::string, Dict> recs_t;
typedef std::map < std::string, Watch::shared_ptr > watches_t;
TestProj();
//////////////////////////////////////////////////////////////////////////
// Ops
//////////////////////////////////////////////////////////////////////////
const std::vector<const Op*>& ops();
const Op* const op(const std::string& name, bool checked = true) const;
const Dict& on_about() const;
protected:
//////////////////////////////////////////////////////////////////////////
// Reads
//////////////////////////////////////////////////////////////////////////
Dict::auto_ptr_t on_read_by_id(const Ref& id) const;
//////////////////////////////////////////////////////////////////////////
// Navigation
//////////////////////////////////////////////////////////////////////////
Grid::auto_ptr_t on_nav(const std::string& nav_id) const;
Dict::auto_ptr_t on_nav_read_by_uri(const Uri& uri) const;
//////////////////////////////////////////////////////////////////////////
// Watches
//////////////////////////////////////////////////////////////////////////
Watch::shared_ptr on_watch_open(const std::string& dis);
const std::vector<Watch::shared_ptr> on_watches();
Watch::shared_ptr on_watch(const std::string& id);
//////////////////////////////////////////////////////////////////////////
// Point Write
//////////////////////////////////////////////////////////////////////////
Grid::auto_ptr_t on_point_write_array(const Dict& rec);
void on_point_write(const Dict& rec, int level, const Val& val, const std::string& who, const Num& dur);
//////////////////////////////////////////////////////////////////////////
// History
//////////////////////////////////////////////////////////////////////////
std::vector<HisItem> on_his_read(const Dict& entity, const DateTimeRange& range);
void on_his_write(const Dict& rec, const std::vector<HisItem>& items);
//////////////////////////////////////////////////////////////////////////
// Actions
//////////////////////////////////////////////////////////////////////////
Grid::auto_ptr_t on_invoke_action(const Dict& rec, const std::string& action, const Dict& args);
public:
const_iterator begin() const;
const_iterator end() const;
private:
void add_site(const std::string& dis, const std::string& geoCity, const std::string& geoState, int area);
void add_meter(Dict& site, const std::string& dis);
void add_ahu(Dict& site, const std::string& dis);
void add_point(Dict& equip, const std::string& dis, const std::string& unit, const std::string& markers);
void on_timer(Poco::Timer& timer);
friend class TestWatch;
recs_t m_recs;
watches_t m_watches;
Poco::RWLock m_lock;
Poco::Timer m_timer;
static Dict* m_about;
static std::vector<const Op*>* m_ops;
};
class TestWatch : public Watch
{
public:
TestWatch(const TestProj& server, const std::string& dis);
const std::string id() const;
const std::string dis() const;
const int lease() const;
void lease(int);
Grid::auto_ptr_t sub(const refs_t& ids, bool checked = true);
void unsub(const refs_t& ids);
Grid::auto_ptr_t poll_changes();
Grid::auto_ptr_t poll_refresh();
void close();
bool is_open() const;
private:
const TestProj& m_server;
const std::string m_uuid;
const std::string m_dis;
refs_t m_ids;
Poco::AtomicCounter m_lease;
bool m_is_open;
};
} | 34.068702 | 113 | 0.460004 | [
"vector"
] |
ed2fdf933946575d443e9ccbae6c1f4da113ff70 | 39,978 | cpp | C++ | nfc/src/DOOM/neo/d3xp/Game_network.cpp | 1337programming/leviathan | ca9a31b45c25fd23f361d67136ae5ac6b98d2628 | [
"Apache-2.0"
] | null | null | null | nfc/src/DOOM/neo/d3xp/Game_network.cpp | 1337programming/leviathan | ca9a31b45c25fd23f361d67136ae5ac6b98d2628 | [
"Apache-2.0"
] | null | null | null | nfc/src/DOOM/neo/d3xp/Game_network.cpp | 1337programming/leviathan | ca9a31b45c25fd23f361d67136ae5ac6b98d2628 | [
"Apache-2.0"
] | null | null | null | /*
===========================================================================
Doom 3 BFG Edition GPL Source Code
Copyright (C) 1993-2012 id Software LLC, a ZeniMax Media company.
This file is part of the Doom 3 BFG Edition GPL Source Code ("Doom 3 BFG Edition Source Code").
Doom 3 BFG Edition Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Doom 3 BFG Edition Source Code 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 Doom 3 BFG Edition Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Doom 3 BFG Edition Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 BFG Edition Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
#include "../idlib/precompiled.h"
#pragma hdrstop
#include "Game_local.h"
#include "..\framework\Common_local.h"
static const int SNAP_GAMESTATE = 0;
static const int SNAP_SHADERPARMS = 1;
static const int SNAP_PORTALS = 2;
static const int SNAP_PLAYERSTATE = SNAP_PORTALS + 1;
static const int SNAP_PLAYERSTATE_END = SNAP_PLAYERSTATE + MAX_PLAYERS;
static const int SNAP_ENTITIES = SNAP_PLAYERSTATE_END;
static const int SNAP_ENTITIES_END = SNAP_ENTITIES + MAX_GENTITIES;
static const int SNAP_LAST_CLIENT_FRAME = SNAP_ENTITIES_END;
static const int SNAP_LAST_CLIENT_FRAME_END = SNAP_LAST_CLIENT_FRAME + MAX_PLAYERS;
/*
===============================================================================
Client running game code:
- entity events don't work and should not be issued
- entities should never be spawned outside idGameLocal::ClientReadSnapshot
===============================================================================
*/
idCVar net_clientSmoothing( "net_clientSmoothing", "0.8", CVAR_GAME | CVAR_FLOAT, "smooth other clients angles and position.", 0.0f, 0.95f );
idCVar net_clientSelfSmoothing( "net_clientSelfSmoothing", "0.6", CVAR_GAME | CVAR_FLOAT, "smooth self position if network causes prediction error.", 0.0f, 0.95f );
extern idCVar net_clientMaxPrediction;
idCVar cg_predictedSpawn_debug( "cg_predictedSpawn_debug", "0", CVAR_BOOL, "Debug predictive spawning of presentables" );
idCVar g_clientFire_checkLineOfSightDebug( "g_clientFire_checkLineOfSightDebug", "0", CVAR_BOOL, "" );
/*
================
idGameLocal::InitAsyncNetwork
================
*/
void idGameLocal::InitAsyncNetwork() {
eventQueue.Init();
savedEventQueue.Init();
entityDefBits = -( idMath::BitsForInteger( declManager->GetNumDecls( DECL_ENTITYDEF ) ) + 1 );
realClientTime = 0;
fast.Set( 0, 0, 0 );
slow.Set( 0, 0, 0 );
isNewFrame = true;
clientSmoothing = net_clientSmoothing.GetFloat();
lastCmdRunTimeOnClient.Zero();
lastCmdRunTimeOnServer.Zero();
usercmdLastClientMilliseconds.Zero();
}
/*
================
idGameLocal::ShutdownAsyncNetwork
================
*/
void idGameLocal::ShutdownAsyncNetwork() {
eventQueue.Shutdown();
savedEventQueue.Shutdown();
}
/*
================
idGameLocal::ServerRemapDecl
================
*/
int idGameLocal::ServerRemapDecl( int clientNum, declType_t type, int index ) {
return index;
}
/*
================
idGameLocal::ClientRemapDecl
================
*/
int idGameLocal::ClientRemapDecl( declType_t type, int index ) {
return index;
}
/*
================
idGameLocal::SyncPlayersWithLobbyUsers
================
*/
void idGameLocal::SyncPlayersWithLobbyUsers( bool initial ) {
idLobbyBase & lobby = session->GetActingGameStateLobbyBase();
if ( !lobby.IsHost() ) {
return;
}
idStaticList< lobbyUserID_t, MAX_CLIENTS > newLobbyUsers;
// First, loop over lobby users, and see if we find a lobby user that we haven't registered
for ( int i = 0; i < lobby.GetNumLobbyUsers(); i++ ) {
lobbyUserID_t lobbyUserID1 = lobby.GetLobbyUserIdByOrdinal( i );
if ( !lobbyUserID1.IsValid() ) {
continue;
}
if ( !initial && !lobby.IsLobbyUserLoaded( lobbyUserID1 ) ) {
continue;
}
// Now, see if we find this lobby user in our list
bool found = false;
for ( int j = 0; j < MAX_PLAYERS; j++ ) {
idPlayer * player = static_cast<idPlayer *>( entities[ j ] );
if ( player == NULL ) {
continue;
}
lobbyUserID_t lobbyUserID2 = lobbyUserIDs[j];
if ( lobbyUserID1 == lobbyUserID2 ) {
found = true;
break;
}
}
if ( !found ) {
// If we didn't find it, we need to create a player and assign it to this new lobby user
newLobbyUsers.Append( lobbyUserID1 );
}
}
// Validate connected players
for ( int i = 0; i < MAX_PLAYERS; i++ ) {
idPlayer * player = static_cast<idPlayer *>( entities[ i ] );
if ( player == NULL ) {
continue;
}
lobbyUserID_t lobbyUserID = lobbyUserIDs[i];
if ( !lobby.IsLobbyUserValid( lobbyUserID ) ) {
delete entities[ i ];
mpGame.DisconnectClient( i );
lobbyUserIDs[i] = lobbyUserID_t();
continue;
}
lobby.EnableSnapshotsForLobbyUser( lobbyUserID );
}
while ( newLobbyUsers.Num() > 0 ) {
// Find a free player data slot to use for this new player
int freePlayerDataIndex = -1;
for ( int i = 0; i < MAX_PLAYERS; ++i ) {
idPlayer * player = static_cast<idPlayer *>( entities[ i ] );
if ( player == NULL ) {
freePlayerDataIndex = i;
break;
}
}
if ( freePlayerDataIndex == -1 ) {
break; // No player data slots (this shouldn't happen)
}
lobbyUserID_t lobbyUserID = newLobbyUsers[0];
newLobbyUsers.RemoveIndex( 0 );
mpGame.ServerClientConnect( freePlayerDataIndex );
Printf( "client %d connected.\n", freePlayerDataIndex );
lobbyUserIDs[ freePlayerDataIndex ] = lobbyUserID;
// Clear this player's old usercmds.
common->ResetPlayerInput( freePlayerDataIndex );
common->UpdateLevelLoadPacifier();
// spawn the player
SpawnPlayer( freePlayerDataIndex );
common->UpdateLevelLoadPacifier();
ServerWriteInitialReliableMessages( freePlayerDataIndex, lobbyUserID );
}
}
/*
================
idGameLocal::ServerSendNetworkSyncCvars
================
*/
void idGameLocal::ServerSendNetworkSyncCvars() {
if ( ( cvarSystem->GetModifiedFlags() & CVAR_NETWORKSYNC ) == 0 ) {
return;
}
cvarSystem->ClearModifiedFlags( CVAR_NETWORKSYNC );
idBitMsg outMsg;
byte msgBuf[MAX_GAME_MESSAGE_SIZE];
idLobbyBase & lobby = session->GetActingGameStateLobbyBase();
outMsg.InitWrite( msgBuf, sizeof( msgBuf ) );
outMsg.BeginWriting();
idDict syncedCvars;
cvarSystem->MoveCVarsToDict( CVAR_NETWORKSYNC, syncedCvars, true );
outMsg.WriteDeltaDict( syncedCvars, NULL );
lobby.SendReliable( GAME_RELIABLE_MESSAGE_SYNCEDCVARS, outMsg, false );
idLib::Printf( "Sending networkSync cvars:\n" );
syncedCvars.Print();
}
/*
================
idGameLocal::ServerWriteInitialReliableMessages
Send reliable messages to initialize the client game up to a certain initial state.
================
*/
void idGameLocal::ServerWriteInitialReliableMessages( int clientNum, lobbyUserID_t lobbyUserID ) {
if ( clientNum == GetLocalClientNum() ) {
// We don't need to send messages to ourself
return;
}
idBitMsg outMsg;
byte msgBuf[MAX_GAME_MESSAGE_SIZE];
idLobbyBase & lobby = session->GetActingGameStateLobbyBase();
outMsg.InitWrite( msgBuf, sizeof( msgBuf ) );
outMsg.BeginWriting();
idDict syncedCvars;
cvarSystem->MoveCVarsToDict( CVAR_NETWORKSYNC, syncedCvars, true );
outMsg.WriteDeltaDict( syncedCvars, NULL );
lobby.SendReliableToLobbyUser( lobbyUserID, GAME_RELIABLE_MESSAGE_SYNCEDCVARS, outMsg );
idLib::Printf( "Sending initial networkSync cvars:\n" );
syncedCvars.Print();
// send all saved events
for ( entityNetEvent_t * event = savedEventQueue.Start(); event; event = event->next ) {
outMsg.InitWrite( msgBuf, sizeof( msgBuf ) );
outMsg.BeginWriting();
outMsg.WriteBits( event->spawnId, 32 );
outMsg.WriteByte( event->event );
outMsg.WriteLong( event->time );
outMsg.WriteBits( event->paramsSize, idMath::BitsForInteger( MAX_EVENT_PARAM_SIZE ) );
if ( event->paramsSize ) {
outMsg.WriteData( event->paramsBuf, event->paramsSize );
}
lobby.SendReliableToLobbyUser( lobbyUserID, GAME_RELIABLE_MESSAGE_EVENT, outMsg );
}
mpGame.ServerWriteInitialReliableMessages( clientNum, lobbyUserID );
}
/*
================
idGameLocal::SaveEntityNetworkEvent
================
*/
void idGameLocal::SaveEntityNetworkEvent( const idEntity *ent, int eventId, const idBitMsg *msg ) {
entityNetEvent_t * event = savedEventQueue.Alloc();
event->spawnId = GetSpawnId( ent );
event->event = eventId;
event->time = time;
if ( msg ) {
event->paramsSize = msg->GetSize();
memcpy( event->paramsBuf, msg->GetReadData(), msg->GetSize() );
} else {
event->paramsSize = 0;
}
savedEventQueue.Enqueue( event, idEventQueue::OUTOFORDER_IGNORE );
}
/*
================
idGameLocal::ServerWriteSnapshot
Write a snapshot of the current game state
================
*/
void idGameLocal::ServerWriteSnapshot( idSnapShot & ss ) {
ss.SetTime( fast.time );
byte buffer[ MAX_ENTITY_STATE_SIZE ];
idBitMsg msg;
// First write the generic game state to the snapshot
msg.InitWrite( buffer, sizeof( buffer ) );
mpGame.WriteToSnapshot( msg );
ss.S_AddObject( SNAP_GAMESTATE, ~0U, msg, "Game State" );
// Update global shader parameters
msg.InitWrite( buffer, sizeof( buffer ) );
for ( int i = 0; i < MAX_GLOBAL_SHADER_PARMS; i++ ) {
msg.WriteFloat( globalShaderParms[i] );
}
ss.S_AddObject( SNAP_SHADERPARMS, ~0U, msg, "Shader Parms" );
// update portals for opened doors
msg.InitWrite( buffer, sizeof( buffer ) );
int numPortals = gameRenderWorld->NumPortals();
msg.WriteLong( numPortals );
for ( int i = 0; i < numPortals; i++ ) {
msg.WriteBits( gameRenderWorld->GetPortalState( (qhandle_t) (i+1) ) , NUM_RENDER_PORTAL_BITS );
}
ss.S_AddObject( SNAP_PORTALS, ~0U, msg, "Portal State" );
idEntity * skyEnt = portalSkyEnt.GetEntity();
pvsHandle_t portalSkyPVS;
portalSkyPVS.i = -1;
if ( skyEnt != NULL ) {
portalSkyPVS = pvs.SetupCurrentPVS( skyEnt->GetPVSAreas(), skyEnt->GetNumPVSAreas() );
}
// Build PVS data for each player and write their player state to the snapshot as well
pvsHandle_t pvsHandles[ MAX_PLAYERS ];
for ( int i = 0; i < MAX_PLAYERS; i++ ) {
idPlayer * player = static_cast<idPlayer *>( entities[ i ] );
if ( player == NULL ) {
pvsHandles[i].i = -1;
continue;
}
idPlayer * spectated = player;
if ( player->spectating && player->spectator != i && entities[ player->spectator ] ) {
spectated = static_cast< idPlayer * >( entities[ player->spectator ] );
}
msg.InitWrite( buffer, sizeof( buffer ) );
spectated->WritePlayerStateToSnapshot( msg );
ss.S_AddObject( SNAP_PLAYERSTATE + i, ~0U, msg, "Player State" );
int sourceAreas[ idEntity::MAX_PVS_AREAS ];
int numSourceAreas = gameRenderWorld->BoundsInAreas( spectated->GetPlayerPhysics()->GetAbsBounds(), sourceAreas, idEntity::MAX_PVS_AREAS );
pvsHandles[i] = pvs.SetupCurrentPVS( sourceAreas, numSourceAreas, PVS_NORMAL );
if ( portalSkyPVS.i >= 0 ) {
pvsHandle_t tempPVS = pvs.MergeCurrentPVS( pvsHandles[i], portalSkyPVS );
pvs.FreeCurrentPVS( pvsHandles[i] );
pvsHandles[i] = tempPVS;
}
// Write the last usercmd processed by the server so that clients know
// when to stop predicting.
msg.BeginWriting();
msg.WriteLong( usercmdLastClientMilliseconds[i] );
ss.S_AddObject( SNAP_LAST_CLIENT_FRAME + i, ~0U, msg, "Last client frame" );
}
if ( portalSkyPVS.i >= 0 ) {
pvs.FreeCurrentPVS( portalSkyPVS );
}
// Add all entities to the snapshot
for ( idEntity * ent = spawnedEntities.Next(); ent != NULL; ent = ent->spawnNode.Next() ) {
if ( ent->GetSkipReplication() ) {
continue;
}
msg.InitWrite( buffer, sizeof( buffer ) );
msg.WriteBits( spawnIds[ ent->entityNumber ], 32 - GENTITYNUM_BITS );
msg.WriteBits( ent->GetType()->typeNum, idClass::GetTypeNumBits() );
msg.WriteBits( ServerRemapDecl( -1, DECL_ENTITYDEF, ent->entityDefNumber ), entityDefBits );
msg.WriteBits( ent->GetPredictedKey(), 32 );
if ( ent->fl.networkSync ) {
// write the class specific data to the snapshot
ent->WriteToSnapshot( msg );
}
ss.S_AddObject( SNAP_ENTITIES + ent->entityNumber, ~0U, msg, ent->GetName() );
}
// Free PVS handles for all the players
for ( int i = 0; i < MAX_PLAYERS; i++ ) {
if ( pvsHandles[i].i < 0 ) {
continue;
}
pvs.FreeCurrentPVS( pvsHandles[i] );
}
}
/*
================
idGameLocal::NetworkEventWarning
================
*/
void idGameLocal::NetworkEventWarning( const entityNetEvent_t *event, const char *fmt, ... ) {
char buf[1024];
int length = 0;
va_list argptr;
int entityNum = event->spawnId & ( ( 1 << GENTITYNUM_BITS ) - 1 );
int id = event->spawnId >> GENTITYNUM_BITS;
length += idStr::snPrintf( buf+length, sizeof(buf)-1-length, "event %d for entity %d %d: ", event->event, entityNum, id );
va_start( argptr, fmt );
length = idStr::vsnPrintf( buf+length, sizeof(buf)-1-length, fmt, argptr );
va_end( argptr );
idStr::Append( buf, sizeof(buf), "\n" );
common->DWarning( buf );
}
/*
================
idGameLocal::ServerProcessEntityNetworkEventQueue
================
*/
void idGameLocal::ServerProcessEntityNetworkEventQueue() {
while ( eventQueue.Start() ) {
entityNetEvent_t * event = eventQueue.Start();
if ( event->time > time ) {
break;
}
idEntityPtr< idEntity > entPtr;
if( !entPtr.SetSpawnId( event->spawnId ) ) {
NetworkEventWarning( event, "Entity does not exist any longer, or has not been spawned yet." );
} else {
idEntity * ent = entPtr.GetEntity();
assert( ent );
idBitMsg eventMsg;
eventMsg.InitRead( event->paramsBuf, sizeof( event->paramsBuf ) );
eventMsg.SetSize( event->paramsSize );
eventMsg.BeginReading();
if ( !ent->ServerReceiveEvent( event->event, event->time, eventMsg ) ) {
NetworkEventWarning( event, "unknown event" );
}
}
entityNetEvent_t* freedEvent = eventQueue.Dequeue();
verify( freedEvent == event );
eventQueue.Free( event );
}
}
/*
================
idGameLocal::ProcessReliableMessage
================
*/
void idGameLocal::ProcessReliableMessage( int clientNum, int type, const idBitMsg &msg ) {
if ( session->GetActingGameStateLobbyBase().IsPeer() ) {
ClientProcessReliableMessage( type, msg );
} else {
ServerProcessReliableMessage( clientNum, type, msg );
}
}
/*
================
idGameLocal::ServerProcessReliableMessage
================
*/
void idGameLocal::ServerProcessReliableMessage( int clientNum, int type, const idBitMsg &msg ) {
if ( clientNum < 0 ) {
return;
}
switch( type ) {
case GAME_RELIABLE_MESSAGE_CHAT:
case GAME_RELIABLE_MESSAGE_TCHAT: {
char name[128];
char text[128];
msg.ReadString( name, sizeof( name ) );
msg.ReadString( text, sizeof( text ) );
mpGame.ProcessChatMessage( clientNum, type == GAME_RELIABLE_MESSAGE_TCHAT, name, text, NULL );
break;
}
case GAME_RELIABLE_MESSAGE_VCHAT: {
int index = msg.ReadLong();
bool team = msg.ReadBits( 1 ) != 0;
mpGame.ProcessVoiceChat( clientNum, team, index );
break;
}
case GAME_RELIABLE_MESSAGE_DROPWEAPON: {
mpGame.DropWeapon( clientNum );
break;
}
case GAME_RELIABLE_MESSAGE_EVENT: {
// allocate new event
entityNetEvent_t * event = eventQueue.Alloc();
eventQueue.Enqueue( event, idEventQueue::OUTOFORDER_DROP );
event->spawnId = msg.ReadBits( 32 );
event->event = msg.ReadByte();
event->time = msg.ReadLong();
event->paramsSize = msg.ReadBits( idMath::BitsForInteger( MAX_EVENT_PARAM_SIZE ) );
if ( event->paramsSize ) {
if ( event->paramsSize > MAX_EVENT_PARAM_SIZE ) {
NetworkEventWarning( event, "invalid param size" );
return;
}
msg.ReadByteAlign();
msg.ReadData( event->paramsBuf, event->paramsSize );
}
break;
}
case GAME_RELIABLE_MESSAGE_SPECTATE: {
bool spec = msg.ReadBool();
idPlayer * player = GetClientByNum( clientNum );
if ( serverInfo.GetBool( "si_spectators" ) ) {
// never let spectators go back to game while sudden death is on
if ( mpGame.GetGameState() == idMultiplayerGame::SUDDENDEATH && !spec && player->wantSpectate ) {
// Don't allow the change
} else {
if ( player->wantSpectate && !spec ) {
player->forceRespawn = true;
}
player->wantSpectate = spec;
}
} else {
// If the server turned off si_spectators while a player is spectating, then any spectate message forces the player out of spectate mode
if ( player->wantSpectate ) {
player->forceRespawn = true;
}
player->wantSpectate = false;
}
break;
}
case GAME_RELIABLE_MESSAGE_CLIENT_HITSCAN_HIT: {
const int attackerNum = msg.ReadShort();
const int victimNum = msg.ReadShort();
idVec3 dir;
msg.ReadVectorFloat( dir );
const int damageDefIndex = msg.ReadLong();
const float damageScale = msg.ReadFloat();
const int location = msg.ReadLong();
if ( gameLocal.entities[victimNum] == NULL ) {
break;
}
if ( gameLocal.entities[attackerNum] == NULL ) {
break;
}
idPlayer & victim = static_cast< idPlayer & >( *gameLocal.entities[victimNum] );
idPlayer & attacker = static_cast< idPlayer & >( *gameLocal.entities[attackerNum] );
if ( victim.GetPhysics() == NULL ) {
break;
}
if ( attacker.weapon.GetEntity() == NULL ) {
break;
}
if ( location == INVALID_JOINT ) {
break;
}
// Line of sight check. As a basic precaution against cheating,
// the server performs a ray intersection from the client's position
// to the joint he hit on the target.
idVec3 muzzleOrigin;
idMat3 muzzleAxis;
attacker.weapon.GetEntity()->GetProjectileLaunchOriginAndAxis( muzzleOrigin, muzzleAxis );
idVec3 targetLocation = victim.GetRenderEntity()->origin + victim.GetRenderEntity()->joints[location].ToVec3() * victim.GetRenderEntity()->axis;
trace_t tr;
gameLocal.clip.Translation( tr, muzzleOrigin, targetLocation, NULL, mat3_identity, MASK_SHOT_RENDERMODEL, &attacker );
idEntity * hitEnt = gameLocal.entities[ tr.c.entityNum ];
if ( hitEnt != &victim ) {
break;
}
const idDeclEntityDef *damageDef = static_cast<const idDeclEntityDef *>( declManager->DeclByIndex( DECL_ENTITYDEF, damageDefIndex, false ) );
if ( damageDef != NULL ) {
victim.Damage( NULL, gameLocal.entities[attackerNum], dir, damageDef->GetName(), damageScale, location );
}
break;
}
default: {
Warning( "Unknown reliable message (%d) from client %d", type, clientNum );
break;
}
}
}
/*
================
idGameLocal::ClientReadSnapshot
================
*/
void idGameLocal::ClientReadSnapshot( const idSnapShot & ss ) {
if ( GetLocalClientNum() < 0 ) {
return;
}
// if prediction is off, enable local client smoothing
//localPlayer->SetSelfSmooth( dupeUsercmds > 2 );
// clear any debug lines from a previous frame
gameRenderWorld->DebugClearLines( time );
// clear any debug polygons from a previous frame
gameRenderWorld->DebugClearPolygons( time );
SelectTimeGroup( false );
// so that StartSound/StopSound doesn't risk skipping
isNewFrame = true;
// clear the snapshot entity list
snapshotEntities.Clear();
// read all entities from the snapshot
for ( int o = 0; o < ss.NumObjects(); o++ ) {
idBitMsg msg;
int snapObjectNum = ss.GetObjectMsgByIndex( o, msg );
if ( snapObjectNum < 0 ) {
assert( false );
continue;
}
if ( snapObjectNum == SNAP_GAMESTATE ) {
mpGame.ReadFromSnapshot( msg );
continue;
}
if ( snapObjectNum == SNAP_SHADERPARMS ) {
for ( int i = 0; i < MAX_GLOBAL_SHADER_PARMS; i++ ) {
globalShaderParms[i] = msg.ReadFloat();
}
continue;
}
if ( snapObjectNum == SNAP_PORTALS ) {
// update portals for opened doors
int numPortals = msg.ReadLong();
assert( numPortals == gameRenderWorld->NumPortals() );
for ( int i = 0; i < numPortals; i++ ) {
gameRenderWorld->SetPortalState( (qhandle_t) (i+1), msg.ReadBits( NUM_RENDER_PORTAL_BITS ) );
}
continue;
}
if ( snapObjectNum >= SNAP_PLAYERSTATE && snapObjectNum < SNAP_PLAYERSTATE_END ) {
int playerNumber = snapObjectNum - SNAP_PLAYERSTATE;
idPlayer * otherPlayer = static_cast< idPlayer * >( entities[ playerNumber ] );
// Don't process Player Snapshots that are disconnected.
const int lobbyIndex = session->GetActingGameStateLobbyBase().GetLobbyUserIndexFromLobbyUserID( lobbyUserIDs[ playerNumber ] );
if( lobbyIndex < 0 || session->GetActingGameStateLobbyBase().IsLobbyUserConnected( lobbyIndex ) == false ) {
continue;
}
if ( otherPlayer != NULL ) {
otherPlayer->ReadPlayerStateFromSnapshot( msg );
if ( otherPlayer != entities[ GetLocalClientNum() ] ) { // This happens when we spectate another player
idWeapon * weap = otherPlayer->weapon.GetEntity();
if ( weap && ( weap->GetRenderEntity()->bounds[0] == weap->GetRenderEntity()->bounds[1] ) ) {
// update the weapon's viewmodel bounds so that the model doesn't flicker in the spectator's view
weap->GetAnimator()->GetBounds( gameLocal.time, weap->GetRenderEntity()->bounds );
weap->UpdateVisuals();
}
}
}
continue;
}
if ( snapObjectNum >= SNAP_LAST_CLIENT_FRAME && snapObjectNum < SNAP_LAST_CLIENT_FRAME_END ) {
int playerNumber = snapObjectNum - SNAP_LAST_CLIENT_FRAME;
// Don't process Player Snapshots that are disconnected.
const int lobbyIndex = session->GetActingGameStateLobbyBase().GetLobbyUserIndexFromLobbyUserID( lobbyUserIDs[ playerNumber ] );
if( lobbyIndex < 0 || session->GetActingGameStateLobbyBase().IsLobbyUserConnected( lobbyIndex ) == false ) {
continue;
}
usercmdLastClientMilliseconds[playerNumber] = msg.ReadLong();
continue;
}
if ( snapObjectNum < SNAP_ENTITIES || snapObjectNum >= SNAP_ENTITIES_END ) {
continue;
}
int entityNumber = snapObjectNum - SNAP_ENTITIES;
if ( msg.GetSize() == 0 ) {
delete entities[entityNumber];
continue;
}
bool debug = false;
int spawnId = msg.ReadBits( 32 - GENTITYNUM_BITS );
int typeNum = msg.ReadBits( idClass::GetTypeNumBits() );
int entityDefNumber = ClientRemapDecl( DECL_ENTITYDEF, msg.ReadBits( entityDefBits ) );
const int predictedKey = msg.ReadBits( 32 );
idTypeInfo * typeInfo = idClass::GetType( typeNum );
if ( !typeInfo ) {
idLib::Error( "Unknown type number %d for entity %d with class number %d", typeNum, entityNumber, entityDefNumber );
}
// If there is no entity on this client, but the server's entity matches a predictionKey, move the client's
// predicted entity to the normal, replicated area in the entity list.
if ( entities[entityNumber] == NULL ) {
if ( predictedKey != idEntity::INVALID_PREDICTION_KEY ) {
idLib::PrintfIf( debug, "Looking for predicted key %d.\n", predictedKey );
idEntity * predictedEntity = FindPredictedEntity( predictedKey, typeInfo );
if ( predictedEntity != NULL ) {
// This presentable better be in the proper place in the list or bad things will happen if we move this presentable around
assert( predictedEntity->GetEntityNumber() >= ENTITYNUM_FIRST_NON_REPLICATED );
continue;
#if 0
idProjectile * predictedProjectile = idProjectile::CastTo( predictedEntity );
if ( predictedProjectile != NULL ) {
for ( int i = 0; i < MAX_PLAYERS; i++ ) {
if ( entities[i] == NULL ) {
continue;
}
idPlayer * player = idPlayer::CastTo( entities[i] );
if ( player != NULL ) {
if ( player->GetUniqueProjectile() == predictedProjectile ) {
// Set new spawn id
player->TrackUniqueProjectile( predictedProjectile );
}
}
}
}
idLib::PrintfIf( debug, "Found predicted EntNum old:%i new:%i spawnID:%i\n", predictedEntity->GetEntityNumber(), entityNumber, spawnId >> GENTITYNUM_BITS );
// move the entity
RemoveEntityFromHash( predictedEntity->name.c_str(), predictedEntity );
UnregisterEntity( predictedEntity );
assert( entities[predictedEntity->GetEntityNumber()] == NULL );
predictedEntity->spawnArgs.SetInt( "spawn_entnum", entityNumber );
RegisterEntity( predictedEntity, spawnId, predictedEntity->spawnArgs );
predictedEntity->SetName( "" );
// now mark us as no longer predicted
predictedEntity->BecomeReplicated();
#endif
}
//TODO make this work with non-client preditced entities
/* else {
idLib::Warning( "Could not find predicted entity - key: %d. EntityIndex: %d", predictedKey, entityNum );
} */
}
}
idEntity * ent = entities[entityNumber];
// if there is no entity or an entity of the wrong type
if ( !ent || ent->GetType()->typeNum != typeNum || ent->entityDefNumber != entityDefNumber || spawnId != spawnIds[ entityNumber ] ) {
delete ent;
spawnCount = spawnId;
if ( entityNumber < MAX_CLIENTS ) {
commonLocal.GetUCmdMgr().ResetPlayer( entityNumber );
SpawnPlayer( entityNumber );
ent = entities[ entityNumber ];
ent->FreeModelDef();
} else {
idDict args;
args.SetInt( "spawn_entnum", entityNumber );
args.Set( "name", va( "entity%d", entityNumber ) );
if ( entityDefNumber >= 0 ) {
if ( entityDefNumber >= declManager->GetNumDecls( DECL_ENTITYDEF ) ) {
Error( "server has %d entityDefs instead of %d", entityDefNumber, declManager->GetNumDecls( DECL_ENTITYDEF ) );
}
const char * classname = declManager->DeclByIndex( DECL_ENTITYDEF, entityDefNumber, false )->GetName();
args.Set( "classname", classname );
if ( !SpawnEntityDef( args, &ent ) || !entities[entityNumber] || entities[entityNumber]->GetType()->typeNum != typeNum ) {
Error( "Failed to spawn entity with classname '%s' of type '%s'", classname, typeInfo->classname );
}
} else {
ent = SpawnEntityType( *typeInfo, &args, true );
if ( !entities[entityNumber] || entities[entityNumber]->GetType()->typeNum != typeNum ) {
Error( "Failed to spawn entity of type '%s'", typeInfo->classname );
}
}
if ( ent != NULL ) {
// Fixme: for now, force all think flags on. We'll need to figure out how we want dormancy to work on clients
// (but for now since clientThink is so light weight, this is ok)
ent->BecomeActive( TH_ANIMATE );
ent->BecomeActive( TH_THINK );
ent->BecomeActive( TH_PHYSICS );
}
if ( entityNumber < MAX_CLIENTS && entityNumber >= numClients ) {
numClients = entityNumber + 1;
}
}
}
if ( ss.ObjectIsStaleByIndex( o ) ) {
if ( ent->entityNumber >= MAX_CLIENTS && ent->entityNumber < mapSpawnCount && !ent->spawnArgs.GetBool("net_dynamic", "0")) { //_D3XP
// server says it's not in PVS
// if that happens on map entities, most likely something is wrong
// I can see that moving pieces along several PVS could be a legit situation though
// this is a band aid, which means something is not done right elsewhere
common->DWarning( "map entity 0x%x (%s) is stale", ent->entityNumber, ent->name.c_str() );
} else {
ent->snapshotStale = true;
ent->FreeModelDef();
// possible fix for left over lights on CTF flag
ent->FreeLightDef();
ent->UpdateVisuals();
ent->GetPhysics()->UnlinkClip();
}
} else {
// add the entity to the snapshot list
ent->snapshotNode.AddToEnd( snapshotEntities );
int snapshotChanged = ss.ObjectChangedCountByIndex( o );
msg.SetHasChanged( ent->snapshotChanged != snapshotChanged );
ent->snapshotChanged = snapshotChanged;
ent->FlagNewSnapshot();
// read the class specific data from the snapshot
if ( msg.GetRemainingReadBits() > 0 ) {
ent->ReadFromSnapshot_Ex( msg );
ent->snapshotBits = msg.GetSize();
}
// Set after ReadFromSnapshot so we can detect coming unstale
ent->snapshotStale = false;
}
}
// process entity events
ClientProcessEntityNetworkEventQueue();
}
/*
================
idGameLocal::ClientProcessEntityNetworkEventQueue
================
*/
void idGameLocal::ClientProcessEntityNetworkEventQueue() {
while( eventQueue.Start() ) {
entityNetEvent_t * event = eventQueue.Start();
// only process forward, in order
if ( event->time > this->serverTime ) {
break;
}
idEntityPtr< idEntity > entPtr;
if( !entPtr.SetSpawnId( event->spawnId ) ) {
if( !gameLocal.entities[ event->spawnId & ( ( 1 << GENTITYNUM_BITS ) - 1 ) ] ) {
// if new entity exists in this position, silently ignore
NetworkEventWarning( event, "Entity does not exist any longer, or has not been spawned yet." );
}
} else {
idEntity * ent = entPtr.GetEntity();
assert( ent );
idBitMsg eventMsg;
eventMsg.InitRead( event->paramsBuf, sizeof( event->paramsBuf ) );
eventMsg.SetSize( event->paramsSize );
eventMsg.BeginReading();
if ( !ent->ClientReceiveEvent( event->event, event->time, eventMsg ) ) {
NetworkEventWarning( event, "unknown event" );
}
}
verify( eventQueue.Dequeue() == event );
eventQueue.Free( event );
}
}
/*
================
idGameLocal::ClientProcessReliableMessage
================
*/
void idGameLocal::ClientProcessReliableMessage( int type, const idBitMsg &msg ) {
switch( type ) {
case GAME_RELIABLE_MESSAGE_SYNCEDCVARS: {
idDict syncedCvars;
msg.ReadDeltaDict( syncedCvars, NULL );
idLib::Printf( "Got networkSync cvars:\n" );
syncedCvars.Print();
cvarSystem->ResetFlaggedVariables( CVAR_NETWORKSYNC );
cvarSystem->SetCVarsFromDict( syncedCvars );
break;
}
case GAME_RELIABLE_MESSAGE_CHAT:
case GAME_RELIABLE_MESSAGE_TCHAT: { // (client should never get a TCHAT though)
char name[128];
char text[128];
msg.ReadString( name, sizeof( name ) );
msg.ReadString( text, sizeof( text ) );
mpGame.AddChatLine( "%s^0: %s\n", name, text );
break;
}
case GAME_RELIABLE_MESSAGE_SOUND_EVENT: {
snd_evt_t snd_evt = (snd_evt_t)msg.ReadByte();
mpGame.PlayGlobalSound( -1, snd_evt );
break;
}
case GAME_RELIABLE_MESSAGE_SOUND_INDEX: {
int index = gameLocal.ClientRemapDecl( DECL_SOUND, msg.ReadLong() );
if ( index >= 0 && index < declManager->GetNumDecls( DECL_SOUND ) ) {
const idSoundShader *shader = declManager->SoundByIndex( index );
mpGame.PlayGlobalSound( -1, SND_COUNT, shader->GetName() );
}
break;
}
case GAME_RELIABLE_MESSAGE_DB: {
idMultiplayerGame::msg_evt_t msg_evt = (idMultiplayerGame::msg_evt_t)msg.ReadByte();
int parm1, parm2;
parm1 = msg.ReadByte( );
parm2 = msg.ReadByte( );
mpGame.PrintMessageEvent( msg_evt, parm1, parm2 );
break;
}
case GAME_RELIABLE_MESSAGE_EVENT: {
// allocate new event
entityNetEvent_t * event = eventQueue.Alloc();
eventQueue.Enqueue( event, idEventQueue::OUTOFORDER_IGNORE );
event->spawnId = msg.ReadBits( 32 );
event->event = msg.ReadByte();
event->time = msg.ReadLong();
event->paramsSize = msg.ReadBits( idMath::BitsForInteger( MAX_EVENT_PARAM_SIZE ) );
if ( event->paramsSize ) {
if ( event->paramsSize > MAX_EVENT_PARAM_SIZE ) {
NetworkEventWarning( event, "invalid param size" );
return;
}
msg.ReadByteAlign();
msg.ReadData( event->paramsBuf, event->paramsSize );
}
break;
}
case GAME_RELIABLE_MESSAGE_RESTART: {
MapRestart();
break;
}
case GAME_RELIABLE_MESSAGE_TOURNEYLINE: {
int line = msg.ReadByte( );
idPlayer * p = static_cast< idPlayer * >( entities[ GetLocalClientNum() ] );
if ( !p ) {
break;
}
p->tourneyLine = line;
break;
}
case GAME_RELIABLE_MESSAGE_STARTSTATE: {
mpGame.ClientReadStartState( msg );
break;
}
case GAME_RELIABLE_MESSAGE_WARMUPTIME: {
mpGame.ClientReadWarmupTime( msg );
break;
}
case GAME_RELIABLE_MESSAGE_LOBBY_COUNTDOWN: {
int timeRemaining = msg.ReadLong();
Shell_UpdateClientCountdown( timeRemaining );
break;
}
case GAME_RELIABLE_MESSAGE_RESPAWN_AVAILABLE: {
idPlayer * p = static_cast< idPlayer * >( entities[ GetLocalClientNum() ] );
if ( p ) {
p->ShowRespawnHudMessage();
}
break;
}
case GAME_RELIABLE_MESSAGE_MATCH_STARTED_TIME: {
mpGame.ClientReadMatchStartedTime( msg );
break;
}
case GAME_RELIABLE_MESSAGE_ACHIEVEMENT_UNLOCK: {
mpGame.ClientReadAchievementUnlock( msg );
break;
}
default: {
Error( "Unknown reliable message (%d) from host", type );
break;
}
}
}
/*
================
idGameLocal::ClientRunFrame
================
*/
void idGameLocal::ClientRunFrame( idUserCmdMgr & cmdMgr, bool lastPredictFrame, gameReturn_t & ret ) {
idEntity *ent;
// update the game time
previousTime = FRAME_TO_MSEC( framenum );
framenum++;
time = FRAME_TO_MSEC( framenum );
idPlayer * player = static_cast<idPlayer *>( entities[GetLocalClientNum()] );
if ( !player ) {
// service any pending events
idEvent::ServiceEvents();
return;
}
// check for local client lag
idLobbyBase & lobby = session->GetActingGameStateLobbyBase();
if ( lobby.GetPeerTimeSinceLastPacket( lobby.PeerIndexForHost() ) >= net_clientMaxPrediction.GetInteger() ) {
player->isLagged = true;
} else {
player->isLagged = false;
}
// update the real client time and the new frame flag
if ( time > realClientTime ) {
realClientTime = time;
isNewFrame = true;
} else {
isNewFrame = false;
}
slow.Set( time, previousTime, realClientTime );
fast.Set( time, previousTime, realClientTime );
// run prediction on all active entities
for( ent = activeEntities.Next(); ent != NULL; ent = ent->activeNode.Next() ) {
ent->thinkFlags |= TH_PHYSICS;
if ( ent->entityNumber != GetLocalClientNum() ) {
ent->ClientThink( netInterpolationInfo.serverGameMs, netInterpolationInfo.pct, true );
} else {
RunAllUserCmdsForPlayer( cmdMgr, ent->entityNumber );
}
}
// service any pending events
idEvent::ServiceEvents();
// show any debug info for this frame
if ( isNewFrame ) {
RunDebugInfo();
D_DrawDebugLines();
}
BuildReturnValue( ret );
}
/*
===============
idGameLocal::Tokenize
===============
*/
void idGameLocal::Tokenize( idStrList &out, const char *in ) {
char buf[ MAX_STRING_CHARS ];
char *token, *next;
idStr::Copynz( buf, in, MAX_STRING_CHARS );
token = buf;
next = strchr( token, ';' );
while ( token ) {
if ( next ) {
*next = '\0';
}
idStr::ToLower( token );
out.Append( token );
if ( next ) {
token = next + 1;
next = strchr( token, ';' );
} else {
token = NULL;
}
}
}
/*
========================
idGameLocal::FindPredictedEntity
========================
*/
idEntity * idGameLocal::FindPredictedEntity( uint32 predictedKey, idTypeInfo * type ) {
for ( idEntity * predictedEntity = activeEntities.Next(); predictedEntity != NULL; predictedEntity = predictedEntity->activeNode.Next() ) {
if ( !verify( predictedEntity != NULL ) ) {
continue;
}
if ( !predictedEntity->IsReplicated() && predictedEntity->GetPredictedKey() == predictedKey ) {
if ( predictedEntity->GetType() != type ) {
idLib::Warning("Mismatched presentable type. Predicted: %s Actual: %s", predictedEntity->GetType()->classname, type->classname );
}
return predictedEntity;
}
}
return NULL;
}
/*
========================
idGameLocal::GeneratePredictionKey
========================
*/
uint32 idGameLocal::GeneratePredictionKey( idWeapon * weapon, idPlayer * playerAttacker, int overrideKey ) {
if ( overrideKey != -1 ) {
uint32 predictedKey = overrideKey;
int peerIndex = -1;
if ( common->IsServer() ) {
peerIndex = session->GetActingGameStateLobbyBase().PeerIndexFromLobbyUser( lobbyUserIDs[ playerAttacker->entityNumber ] );
} else {
peerIndex = session->GetActingGameStateLobbyBase().PeerIndexOnHost();
}
predictedKey |= ( peerIndex << 28 );
return predictedKey;
}
uint32 predictedKey = idEntity::INVALID_PREDICTION_KEY;
int peerIndex = -1;
// Get key - fireCount or throwCount
//if ( weapon != NULL ) {
if ( common->IsClient() ) {
predictedKey = playerAttacker->GetClientFireCount();
} else {
predictedKey = playerAttacker->usercmd.fireCount;
}
//} else {
// predictedKey = ( playerAttacker->GetThrowCount() );
//}
// Get peer index
if ( common->IsServer() ) {
peerIndex = session->GetActingGameStateLobbyBase().PeerIndexFromLobbyUser( lobbyUserIDs[ playerAttacker->entityNumber ] );
} else {
peerIndex = session->GetActingGameStateLobbyBase().PeerIndexOnHost();
}
if ( cg_predictedSpawn_debug.GetBool() ) {
idLib::Printf("GeneratePredictionKey. predictedKey: %d peedIndex: %d\n", predictedKey, peerIndex );
}
predictedKey |= ( peerIndex << 28 );
return predictedKey;
}
/*
===============
idEventQueue::Alloc
===============
*/
entityNetEvent_t* idEventQueue::Alloc() {
entityNetEvent_t* event = eventAllocator.Alloc();
event->prev = NULL;
event->next = NULL;
return event;
}
/*
===============
idEventQueue::Free
===============
*/
void idEventQueue::Free( entityNetEvent_t *event ) {
// should only be called on an unlinked event!
assert( !event->next && !event->prev );
eventAllocator.Free( event );
}
/*
===============
idEventQueue::Shutdown
===============
*/
void idEventQueue::Shutdown() {
eventAllocator.Shutdown();
this->Init();
}
/*
===============
idEventQueue::Init
===============
*/
void idEventQueue::Init() {
start = NULL;
end = NULL;
}
/*
===============
idEventQueue::Dequeue
===============
*/
entityNetEvent_t* idEventQueue::Dequeue() {
entityNetEvent_t* event = start;
if ( !event ) {
return NULL;
}
start = start->next;
if ( !start ) {
end = NULL;
} else {
start->prev = NULL;
}
event->next = NULL;
event->prev = NULL;
return event;
}
/*
===============
idEventQueue::RemoveLast
===============
*/
entityNetEvent_t* idEventQueue::RemoveLast() {
entityNetEvent_t *event = end;
if ( !event ) {
return NULL;
}
end = event->prev;
if ( !end ) {
start = NULL;
} else {
end->next = NULL;
}
event->next = NULL;
event->prev = NULL;
return event;
}
/*
===============
idEventQueue::Enqueue
===============
*/
void idEventQueue::Enqueue( entityNetEvent_t *event, outOfOrderBehaviour_t behaviour ) {
if ( behaviour == OUTOFORDER_DROP ) {
// go backwards through the queue and determine if there are
// any out-of-order events
while ( end && end->time > event->time ) {
entityNetEvent_t *outOfOrder = RemoveLast();
common->DPrintf( "WARNING: new event with id %d ( time %d ) caused removal of event with id %d ( time %d ), game time = %d.\n", event->event, event->time, outOfOrder->event, outOfOrder->time, gameLocal.time );
Free( outOfOrder );
}
} else if ( behaviour == OUTOFORDER_SORT && end ) {
// NOT TESTED -- sorting out of order packets hasn't been
// tested yet... wasn't strictly necessary for
// the patch fix.
entityNetEvent_t *cur = end;
// iterate until we find a time < the new event's
while ( cur && cur->time > event->time ) {
cur = cur->prev;
}
if ( !cur ) {
// add to start
event->next = start;
event->prev = NULL;
start = event;
} else {
// insert
event->prev = cur;
event->next = cur->next;
cur->next = event;
}
return;
}
// add the new event
event->next = NULL;
event->prev = NULL;
if ( end ) {
end->next = event;
event->prev = end;
} else {
start = event;
}
end = event;
}
| 30.081264 | 366 | 0.671019 | [
"model"
] |
ed332cc02f610adb22670097ce5aa7d622ff496e | 6,277 | hpp | C++ | include/eagine/shapes/topology.hpp | ford442/oglplu2 | abf1e28d9bcd0d2348121e8640d9611a94112a83 | [
"BSL-1.0"
] | 103 | 2015-10-15T07:09:22.000Z | 2022-03-20T03:39:32.000Z | include/eagine/shapes/topology.hpp | ford442/oglplu2 | abf1e28d9bcd0d2348121e8640d9611a94112a83 | [
"BSL-1.0"
] | 11 | 2015-11-25T11:39:49.000Z | 2021-06-18T08:06:06.000Z | include/eagine/shapes/topology.hpp | ford442/oglplu2 | abf1e28d9bcd0d2348121e8640d9611a94112a83 | [
"BSL-1.0"
] | 10 | 2016-02-28T00:13:20.000Z | 2021-09-06T05:21:38.000Z | /// @file
///
/// Copyright Matus Chochlik.
/// Distributed under the Boost Software License, Version 1.0.
/// See accompanying file LICENSE_1_0.txt or copy at
/// http://www.boost.org/LICENSE_1_0.txt
///
#ifndef EAGINE_SHAPES_TOPOLOGY_HPP
#define EAGINE_SHAPES_TOPOLOGY_HPP
#include "gen_base.hpp"
#include <eagine/config/basic.hpp>
#include <eagine/flat_map.hpp>
#include <iosfwd>
#include <vector>
namespace eagine {
namespace shapes {
//------------------------------------------------------------------------------
struct topology_data;
class mesh_triangle;
/// @brief Class storing information about an edge between two mesh faces.
/// @ingroup shapes
/// @see mesh_triangle
/// @see topology
class mesh_edge {
public:
mesh_edge(
mesh_triangle& a,
std::uint8_t aeb,
std::uint8_t aee,
mesh_triangle& b,
std::uint8_t beb,
std::uint8_t bee) noexcept
: _triangles{{&a, &b}}
, _edge_indices{{aeb, aee, beb, bee}} {}
/// @brief Returns one of the two adjacent triangle faces.
/// @pre i >= 0 && i < 2
auto triangle(span_size_t i) const noexcept -> const mesh_triangle& {
EAGINE_ASSERT(i >= 0 && i < 2);
return *_triangles[std_size(i)];
}
/// @brief Returns a pair of vertex indices (0,1 or 2) defining the i-th edge.
/// @pre i >= 0 && i < 2
auto edge_vertices(span_size_t i) const noexcept
-> std::tuple<unsigned, unsigned> {
EAGINE_ASSERT(i >= 0 && i < 2);
return {
_edge_indices[std_size(2 * i)], _edge_indices[std_size(2 * i + 1)]};
}
private:
std::array<mesh_triangle*, 2> _triangles;
std::array<std::uint8_t, 4> _edge_indices;
};
//------------------------------------------------------------------------------
/// @brief Class storing information about a mesh tirangular face.
/// @ingroup shapes
/// @see mesh_edge
/// @see topology
class mesh_triangle {
public:
mesh_triangle(
std::size_t tri_idx,
unsigned a,
unsigned b,
unsigned c) noexcept
: _tri_idx{tri_idx}
, _indices{{a, b, c}} {}
/// @brief Returns the index of this triangle within the mesh.
auto index() const noexcept -> span_size_t {
return span_size(_tri_idx);
}
static auto setup_adjacent(
mesh_triangle& l,
mesh_triangle& r,
const topology_data& d) noexcept
-> std::tuple<bool, std::uint8_t, std::uint8_t, std::uint8_t, std::uint8_t>;
/// @brief Returns the v-th vertex index.
/// @pre v >= 0 && v < 3
auto vertex_index(span_size_t v) const noexcept {
EAGINE_ASSERT(v >= 0 && v < 3);
return _indices[std_size(v)];
}
/// @brief Returns the triangle adjacent through the v-th edge.
/// @pre v >= 0 && v < 3
/// @see opposite_vertex
auto adjacent_triangle(span_size_t v) const noexcept
-> const mesh_triangle* {
EAGINE_ASSERT(v >= 0 && v < 3);
return _adjacent[std_size(v)];
}
/// @brief Returns opposite vertex index (0,1 or 2) in the v-th adjacent triangle.
/// @pre v >= 0 && v < 3
/// @see adjacent_triangle
/// @see opposite_index
auto opposite_vertex(span_size_t v) const noexcept -> unsigned {
EAGINE_ASSERT(v >= 0 && v < 3);
return _opposite[std_size(v)];
}
/// @brief Returns the in-mesh index of the v-th adjacent vertex.
/// @pre v >= 0 && v < 3
/// @see opposite_vertex
/// @see adjacent_triangle
auto opposite_index(span_size_t v) const noexcept -> unsigned {
if(auto tri{adjacent_triangle(v)}) {
return extract(tri).vertex_index(opposite_vertex(v));
}
return _indices[(v + 2) % 3];
}
private:
auto curri(std::size_t i) const noexcept -> unsigned {
return _indices[i];
}
static auto prevv(std::size_t i) noexcept -> unsigned {
return (i + 2) % 3;
}
auto previ(std::size_t i) const noexcept -> unsigned {
return _indices[prevv(i)];
}
static auto nextv(std::size_t i) noexcept -> unsigned {
return (i + 1) % 3;
}
auto nexti(std::size_t i) const noexcept -> unsigned {
return _indices[nextv(i)];
}
static auto narrow(std::size_t i) noexcept -> std::uint8_t {
return limit_cast<std::uint8_t>(i);
}
std::size_t _tri_idx{~0U};
std::array<unsigned, 3> _indices{};
std::array<mesh_triangle*, 3> _adjacent{{nullptr, nullptr, nullptr}};
std::array<std::uint8_t, 3> _opposite{{0, 0, 0}};
};
//------------------------------------------------------------------------------
/// @brief Class holding information about the topology of a generated shape.
/// @ingroup shapes
/// @see mesh_edge
/// @see mesh_triangle
class topology {
public:
/// @brief Construction from a generator, drawing and attribute variant.
topology(
std::shared_ptr<generator> gen,
drawing_variant var,
vertex_attrib_variant vav)
: _gen{std::move(gen)} {
_scan_topology(var, vav);
}
/// @brief Construction from a shape generator.
topology(const std::shared_ptr<generator>& gen)
: topology{gen, gen->draw_variant(0), {vertex_attrib_kind::position}} {}
/// @brief Returns the number of triangles in the mesh.
auto triangle_count() const noexcept -> span_size_t {
return span_size(_triangles.size());
}
/// @brief Returns the i-th triangle in the mesh.
auto triangle(span_size_t i) const noexcept -> const mesh_triangle& {
return _triangles[std_size(i)];
}
auto print_dot(std::ostream& out) const -> std::ostream&;
private:
template <typename I>
static auto to_index(I i) noexcept
-> std::enable_if_t<std::is_integral_v<I>, unsigned> {
return limit_cast<unsigned>(i);
}
void _scan_topology(drawing_variant var, vertex_attrib_variant vav);
std::shared_ptr<generator> _gen;
std::vector<mesh_triangle> _triangles;
flat_map<std::tuple<unsigned, unsigned>, mesh_edge> _edges;
};
//------------------------------------------------------------------------------
} // namespace shapes
} // namespace eagine
#if !EAGINE_LINK_LIBRARY || defined(EAGINE_IMPLEMENTING_LIBRARY)
#include <eagine/shapes/topology.inl>
#endif
#endif // EAGINE_SHAPES_TOPOLOGY_HPP
| 30.470874 | 86 | 0.60427 | [
"mesh",
"shape",
"vector"
] |
ed378f02421757e76d01928d4c1170bd0bd3cb5d | 15,542 | hpp | C++ | allocore/allocore/sound/al_Ambisonics.hpp | AlloSphere-Research-Group/AlloSystem | 646bac1232d230f61dbdaaef38327de1a244b43f | [
"BSD-3-Clause"
] | 51 | 2015-02-16T02:36:27.000Z | 2021-08-30T07:22:43.000Z | allocore/allocore/sound/al_Ambisonics.hpp | AlloSphere-Research-Group/AlloSystem | 646bac1232d230f61dbdaaef38327de1a244b43f | [
"BSD-3-Clause"
] | 18 | 2015-01-24T12:52:46.000Z | 2018-03-19T23:43:27.000Z | allocore/allocore/sound/al_Ambisonics.hpp | AlloSphere-Research-Group/AlloSystem | 646bac1232d230f61dbdaaef38327de1a244b43f | [
"BSD-3-Clause"
] | 23 | 2015-01-29T17:44:02.000Z | 2019-09-22T09:04:33.000Z | #ifndef INCLUDE_AL_AMBISONICS_HPP
#define INCLUDE_AL_AMBISONICS_HPP
/* Allocore --
Multimedia / virtual environment application class library
Copyright (C) 2009. AlloSphere Research Group, Media Arts & Technology, UCSB.
Copyright (C) 2012. The Regents of the University of California.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
Neither the name of the University of California nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
File description:
Higher order Ambisonics encoding/decoding
File author(s):
Graham Wakefield, 2010, grrrwaaa@gmail.com
Lance Putnam, 2010, putnam.lance@gmail.com
Based on prior work also contributed to by:
Jorge Castellanos
Florian Hollerweger
*/
#include <stdio.h>
#include "allocore/sound/al_AudioScene.hpp"
//#define MAX_ORDER 3
/*
TODO: near-field compensation
acknowledges that the speakers are at a finite distance from the listener. This a simple Minimum Phase HP filter (on directional signals, not the W component) to deal with "proximity effect" because the speakers are 'near' the listener.
f = c / (2 * PI * d) = 54.6 / d Hz c : speed of sound 343 m/s
d : speaker distance m
Should be IIR, because it mostly affects LF.
If we pass speaker distance, then we might also want to attenuate/delay speakers for irregular layouts.
@see "Near Field filters for Higher Order Ambisonics" Fons ADRIAENSEN
http://kokkinizita.linuxaudio.org/papers/index.html
*/
/*!
A note on coordinate conventions
The cartesian coordinate system used for Ambisonics is:
+x is forward
+y is left
+z is up
The polar coordinate system is as follows:
Azimuth is the angle between the xz-plane and the source. From the listener's perspective, a positive azimuth is leftward (towards +y) and negative is rightwards (towards -y).
Elevation is the angle between the xy-plane and the source. From the listener's perspective, a positive elevation is upward (towards +z) and negative is downward (towards -z).
The cartesian coordinate system used in Allocore's OpenGL is:
+x is right
+y is up
+z is backward
The correct OpenGL to Ambisonics conversion is thus:
ambi_x = -gl_z;
ambi_y = -gl_x;
ambi_z = gl_y;
*/
namespace al{
/// Ambisonic base class
///
/// @ingroup allocore
class AmbiBase{
public:
/// @param[in] dim number of spatial dimensions (2 or 3)
/// @param[in] order highest spherical harmonic order
AmbiBase(int dim, int order);
virtual ~AmbiBase();
/// Get number dimensions
int dim() const { return mDim; }
/// Get order
int order() const { return mOrder; }
/// Get Ambisonic channel weights
const float * weights() const { return mWeights; }
/// Returns total number of Ambisonic domain (B-format) channels
int channels() const { return mChannels; }
/// Set the order
void order(int order);
/// Called whenever the number of Ambisonic channels changes
virtual void onChannelsChange(){}
static int channelsToUniformOrder(int channels);
/// Compute spherical harmonic weights based on azimuth and elevation
/// azimuth is anti-clockwise; both azimuth and elevation are in degrees
static void encodeWeightsFuMa(float * weights, int dim, int order, float azimuth, float elevation);
/// Compute spherical harmonic weights based on unit direction vector (in the listener's coordinate frame)
static void encodeWeightsFuMa(float * ws, int dim, int order, float x, float y, float z);
/// Brute force 3rd order. Weights must be of size 16.
static void encodeWeightsFuMa16(float * weights, float azimuth, float elevation);
/// (x,y,z unit vector in the listener's coordinate frame)
static void encodeWeightsFuMa16(float * ws, float x, float y, float z);
static int orderToChannels(int dim, int order);
static int orderToChannelsH(int orderH);
static int orderToChannelsV(int orderV);
static int channelsToOrder(int channels);
static int channelsToDimensions(int channels);
protected:
int mDim; // dimensions - 2d or 3d
int mOrder; // order - 0th, 1st, 2nd, or 3rd
int mChannels; // cached for efficiency
float * mWeights; // weights for each ambi channel
template<typename T>
static void resize(T *& a, int n);
};
class AmbiDecodeConfig {
public:
bool discardNegativeWeights {false};
float weightOffset {0.0};
};
/// Higher Order Ambisonic Decoding class
///
/// @ingroup allocore
class AmbiDecode : public AmbiBase{
public:
/// @param[in] dim number of spatial dimensions (2 or 3)
/// @param[in] order highest spherical harmonic order
/// @param[in] numSpeakers number of speakers
/// @param[in] flavor decoding algorithm
AmbiDecode(int dim, int order, int numSpeakers, int flavor=1);
virtual ~AmbiDecode();
/// @param[out] dec output time domain buffers (non-interleaved)
/// @param[in] enc input Ambisonic domain buffers (non-interleaved)
/// @param[in] numDecFrames number of frames in time domain buffers
virtual void decode(float * dec, const float * enc, int numDecFrames) const;
/// @param[out] dec output time domain buffer (non-interleaved buffer)
/// @param[in] enc input Ambisonic domain buffers (non-interleaved)
/// @param[in] numFrames number of frames in time domain buffers
/// @param[in] timeIndex index into enc buffer to decode
virtual void decode(float *dec, const float * enc, int numFrames, int timeIndex) const;
void setConfiguration(AmbiDecodeConfig &config) {mConfig = config;}
float decodeWeight(int speaker, int channel) const {
return /*mWeights[channel] **/ mDecodeMatrix[speaker * channels() + channel];
}
/// Returns decode flavor
int flavor() const { return mFlavor; }
/// Returns number of speakers
int numSpeakers() const { return mNumSpeakers; }
void print(FILE * fp = stdout, const char * append = "\n") const;
/// Set decoding algorithm
void flavor(int type);
/// Set number of speakers. Positions are zeroed upon resize.
void numSpeakers(int num);
void setSpeakerRadians(int index, int deviceChannel, float azimuth, float elevation, float amp=1.f);
void setSpeaker(int index, int deviceChannel, float azimuth, float elevation=0, float amp=1.f);
//void zero(); ///< Zeroes out internal ambisonic frame.
void setSpeakers(Speakers &spkrs);
// float * azimuths(); ///< Returns pointer to speaker azimuths.
// float * elevations(); ///< Returns pointer to speaker elevations.
// float * frame() const; ///< Returns pointer to ambisonic channel frame used by decode(int)
/// Get speaker
Speaker& speaker(int num) { return (*mSpeakers)[num]; }
virtual void onChannelsChange();
protected:
int mNumSpeakers;
int mFlavor; // decode flavor
float * mDecodeMatrix; // deccoding matrix for each ambi channel & speaker
// cols are channels and rows are speakers
float mWOrder[5]; // weights for each order
Speakers* mSpeakers;
//float * mPositions; // speakers' azimuths + elevations
//float * mFrame; // an ambisonic channel frame used for decode(int)
void updateChanWeights();
void resizeArrays(int numChannels, int numSpeakers);
float decode(float * encFrame, int encNumChannels, int speakerNum); // is this useful?
static float flavorWeights[4][5][5];
AmbiDecodeConfig mConfig;
};
/// Higher Order Ambisonic encoding class
///
/// @ingroup allocore
class AmbiEncode : public AmbiBase{
public:
/// @param[in] dim number of spatial dimensions (2 or 3)
/// @param[in] order highest spherical harmonic order
AmbiEncode(int dim, int order) : AmbiBase(dim, order) {}
// /// Encode input sample and set decoder frame.
// void encode (const AmbiDecode &dec, float input);
//
// /// Encode input sample and add to decoder frame.
// void encodeAdd(const AmbiDecode &dec, float input);
/// Encode a single time sample
/// @param[out] ambiChans Ambisonic domain channels (non-interleaved)
/// @param[in] numFrames number of frames in time buffer
/// @param[in] timeIndex index at which to encode time sample
/// @param[in] timeSample value of time sample
void encode(float * ambiChans, int numFrames, int timeIndex, float timeSample) const;
/// Encode buffer with constant position throughout buffer
/// @param ambiChans Ambisonic domain channels (non-interleaved)
/// @param input time-domain sample buffer to encode
/// @param numFrames number of frames to encode
void encode(float * ambiChans, const float * input, int numFrames);
/// Encode a buffer of samples
/// @param[in] ambiChans Ambisonic domain channels (non-interleaved)
/// @param[in] dir unit vector in the listener's coordinate frame)
/// @param[in] input time-domain sample buffer to encode
/// @param[in] numFrames number of frames to encode
template <class XYZ>
void encode(float * ambiChans, const XYZ * dir, const float * input, int numFrames);
/// Set spherical direction of source to be encoded
void direction(float az, float el);
/// Set Cartesian direction of source to be encoded
/// (x,y,z unit vector in the listener's coordinate frame)
void direction(float x, float y, float z);
};
/// Ambisonic coder
///
/// @ingroup allocore
class AmbisonicsSpatializer : public Spatializer {
public:
AmbisonicsSpatializer(SpeakerLayout &sl, int dim, int order, int flavor=1);
virtual void compile(Listener& l) override;
virtual void numFrames(int v) override;
virtual void prepare() override;
virtual void renderBuffer(AudioIOData& io,
const Pose& listeningPose,
const float *samples,
const int& numFrames
) override;
virtual void renderSample(AudioIOData& io, const Pose& listeningPose,
const float& sample,
const int& frameIndex) override;
void numSpeakers(int num);
void setSpeakerLayout(SpeakerLayout& sl);
void zeroAmbi();
float * ambiChans(unsigned channel=0);
// virtual void finalize(AudioIOData& io) override;
private:
AmbiDecode mDecoder;
AmbiEncode mEncoder;
std::vector<float> mAmbiDomainChannels;
Listener* mListener;
int mNumFrames;
};
// Implementation ______________________________________________________________
// AmbiBase
inline int AmbiBase::orderToChannels(int dim, int order){
int chans = orderToChannelsH(order);
return dim == 2 ? chans : chans + orderToChannelsV(order);
}
inline int AmbiBase::orderToChannelsH(int orderH){ return (orderH << 1) + 1; }
inline int AmbiBase::orderToChannelsV(int orderV){ return orderV * orderV; }
inline int AmbiBase::channelsToOrder(int channels)
{
int order = -1;
switch(channels) {
case 3:
case 4:
order = 1;
break;
case 9:
order = 2;
break;
case 16:
order = 3;
break;
default:
order = -1;
}
return order;
}
inline int AmbiBase::channelsToDimensions(int channels)
{
int dim = 3;
switch(channels) {
case 3:
dim = 2;
break;
case 4:
case 9:
case 16:
dim = 3;
break;
default:
dim = -1;
}
return dim;
}
template<typename T>
void AmbiBase::resize(T *& a, int n){
delete[] a;
a = new T[n];
memset(a, 0, n*sizeof(T));
}
// AmbiDecode
inline float AmbiDecode::decode(float * encFrame, int encNumChannels, int speakerNum){
float smp = 0;
float * dec = mDecodeMatrix + speakerNum * channels();
float * wc = mWeights;
for(int i=0; i<encNumChannels; ++i) smp += *dec++ * *wc++ * *encFrame++;
return smp;
}
//inline float AmbiDecode::decode(int speakerNum){
// return decode(mFrame, channels(), speakerNum);
//}
//inline float * AmbiDecode::azimuths(){ return mPositions; }
//inline float * AmbiDecode::elevations(){ return mPositions + mNumSpeakers; }
//inline float * AmbiDecode::frame() const { return mFrame; }
// AmbiEncode
//inline void AmbiEncode::encode(const AmbiDecode &dec, float input){
// for(int c=0; c<dec.channels(); ++c) dec.frame()[c] = weights()[c] * input;
//}
//
//inline void AmbiEncode::encodeAdd(const AmbiDecode &dec, float input){
// for(int c=0; c<dec.channels(); ++c) dec.frame()[c] += weights()[c] * input;
//}
inline void AmbiEncode::direction(float az, float el){
AmbiBase::encodeWeightsFuMa(mWeights, mDim, mOrder, az, el);
}
inline void AmbiEncode::direction(float x, float y, float z){
AmbiBase::encodeWeightsFuMa(mWeights, mDim, mOrder, x,y,z);
}
inline void AmbiEncode::encode(float * ambiChans, int numFrames, int timeIndex, float timeSample) const {
// "Iterate" through spherical harmonics using Duff's device.
// This requires only a simple jump per time sample.
#define CS(chanindex) case chanindex: ambiChans[chanindex*numFrames+timeIndex] += weights()[chanindex] * timeSample;
int ch = channels()-1;
switch(ch){
CS(15) CS(14) CS(13) CS(12) CS(11) CS(10) CS( 9) CS( 8)
CS( 7) CS( 6) CS( 5) CS( 4) CS( 3) CS( 2) CS( 1) CS( 0)
default:;
}
#undef CS
}
inline void AmbiEncode::encode(float * ambiChans, const float * input, int numFrames)
{
float * pAmbi = ambiChans; // non-interleaved ambi buffers, we can use fast pointer arithmetic
for(int c=0; c<channels(); ++c){
const float * pInput = input;
float weight = weights()[c];
for(int i=0; i<numFrames; ++i){
*pAmbi++ += weight * *pInput++;
}
}
}
template <class XYZ>
void AmbiEncode::encode(float * ambiChans, const XYZ * dir, const float * input, int numFrames){
// TODO: how can we efficiently encode a moving source?
// Changing the position recomputes ALL the spherical harmonic weights.
// Ideally we only want to change the position for each time sample.
// However, for our loops to be most efficient, we want the inner loop
// to process over time since it will have around 64-512 iterations
// while the spatial loop will have at most 16 iterations.
/* outer-space, inner-time
for(int c=0; c<channels(); ++c){
float * ambi = ambiChans[c];
//T
for(int i=0; i<numFrames; ++i){
position(pos[i][0], pos[i][1], pos[i][2]);
ambi[i] += weights()[c] * input[i];
}
}*/
// outer-time, inner-space
for(int i=0; i<numFrames; ++i){
direction(dir[i][0], dir[i][1], dir[i][2]);
encode(ambiChans, numFrames, i, input[i]);
/*for(int c=0; c<channels(); ++c){
ambiChans[c][i] += weights()[c] * input[i];
}*/
}
}
inline float * AmbisonicsSpatializer::ambiChans(unsigned channel) {
return &mAmbiDomainChannels[channel * mNumFrames];
}
} // al::
#endif
| 30.654832 | 238 | 0.715095 | [
"vector",
"3d"
] |
ed3983ee59e744efc1701adc1c689e0fb79e8d35 | 1,128 | cpp | C++ | 20160911_ABC045/b.cpp | miyalab/AtCoder | a57c8a6195463a9a8edd1c3ddd36cc56f145c60d | [
"MIT"
] | null | null | null | 20160911_ABC045/b.cpp | miyalab/AtCoder | a57c8a6195463a9a8edd1c3ddd36cc56f145c60d | [
"MIT"
] | null | null | null | 20160911_ABC045/b.cpp | miyalab/AtCoder | a57c8a6195463a9a8edd1c3ddd36cc56f145c60d | [
"MIT"
] | null | null | null | // インクルード
#include <iostream>
#include <vector>
#include <string>
#include <cmath>
#include <algorithm>
#include <iomanip>
// 名前空間省略
using namespace std;
// メイン
int main()
{
// 入出力の高速化
ios::sync_with_stdio(false);
cin.tie(nullptr);
// 表示精度変更
cout << fixed << setprecision(16);
vector<string> s(3);
for(int i=0;i<3;i++) cin >> s[i];
int check_person = 0;
vector<int> cnt(3,0);
while(1){
cnt[check_person]++;
if(cnt[check_person]>s[check_person].length()){
if(check_person == 0) cout << "A" << endl;
if(check_person == 1) cout << "B" << endl;
if(check_person == 2) cout << "C" << endl;
return 0;
}
//cout << check_person << ":" << cnt[check_person] << endl;
if(s[check_person][cnt[check_person]-1] == 'a'){
check_person = 0;
}
else if(s[check_person][cnt[check_person]-1] == 'b'){
check_person = 1;
}
else if(s[check_person][cnt[check_person]-1] == 'c'){
check_person = 2;
}
}
} | 23.5 | 68 | 0.503546 | [
"vector"
] |
ed39b4a29ff4e2339e587991658cfa29aa344756 | 3,325 | cpp | C++ | tests/unit_tests/NumericLimitTests.cpp | MatthieuHernandez/StraightforwardNeuralNetwork | e0b99a80bb1b3f76dcb08134aa0f1bc3e6b705d7 | [
"Apache-2.0"
] | 14 | 2019-08-29T07:20:19.000Z | 2022-03-22T12:51:02.000Z | tests/unit_tests/NumericLimitTests.cpp | MatthieuHernandez/StraightforwardNeuralNetwork | e0b99a80bb1b3f76dcb08134aa0f1bc3e6b705d7 | [
"Apache-2.0"
] | 7 | 2020-08-07T11:08:45.000Z | 2021-05-08T17:11:12.000Z | tests/unit_tests/NumericLimitTests.cpp | MatthieuHernandez/StraightforwardNeuralNetwork | e0b99a80bb1b3f76dcb08134aa0f1bc3e6b705d7 | [
"Apache-2.0"
] | 3 | 2020-08-07T10:53:52.000Z | 2021-02-16T22:13:22.000Z | #include "../ExtendedGTest.hpp"
#include "tools/Tools.hpp"
#include "neural_network/StraightforwardNeuralNetwork.hpp"
using namespace std;
using namespace snn;
class NumericLimitTests : public testing::Test
{
protected:
static void createData(int sizeOfTraining, int sizeOfTesting)
{
vector2D<float> trainingExpectedOutputs;
trainingExpectedOutputs.resize(sizeOfTraining);
ranges::generate(trainingExpectedOutputs, []
{
return vector<float>{tools::randomBetween(0.0f, 1.0f)};
});
vector2D<float> trainingInputData;
trainingInputData.resize(sizeOfTraining);
ranges::generate(trainingInputData, []
{
return vector<float>
{
tools::randomBetween(0.0f, 1.0f),
tools::randomBetween(0.0f, 1.0f),
tools::randomBetween(0.0f, 1.0f)
};
});
vector2D<float> testingExpectedOutputs;
testingExpectedOutputs.resize(sizeOfTesting);
ranges::generate(testingExpectedOutputs, []
{
return vector<float>{tools::randomBetween(0.0f, 1.0f)};
});
vector2D<float> testingInputData(sizeOfTesting);
testingInputData.resize(sizeOfTesting);
ranges::generate(testingInputData, []
{
return vector<float>
{
tools::randomBetween(0.0f, 1.0f),
tools::randomBetween(0.0f, 1.0f),
tools::randomBetween(0.0f, 1.0f)
};
});
data = make_unique<Data>(problem::regression,
trainingInputData,
trainingExpectedOutputs,
testingInputData,
testingExpectedOutputs);
data->setPrecision(0.3f);
}
static void testNeuralNetwork(StraightforwardNeuralNetwork& nn)
{
nn.train(*data, 1_s || 0.2_acc);
auto mae = nn.getMeanAbsoluteError();
auto acc = nn.getGlobalClusteringRate();
ASSERT_ACCURACY(acc, 0.2f);
ASSERT_MAE(mae, 1.4f);
}
static void SetUpTestSuite()
{
createData(1000, 50);
}
static unique_ptr<Data> data;
};
unique_ptr<Data> NumericLimitTests::data = nullptr;
TEST_F(NumericLimitTests, WithSigmoid)
{
StraightforwardNeuralNetwork neuralNetwork({
Input(3),
FullyConnected(6, activation::sigmoid),
FullyConnected(1, activation::sigmoid)
},
StochasticGradientDescent(0.01f, 0.99f));
testNeuralNetwork(neuralNetwork);
}
TEST_F(NumericLimitTests, WithTanh)
{
StraightforwardNeuralNetwork neuralNetwork({
Input(3),
FullyConnected(6, activation::tanh),
FullyConnected(1, activation::tanh)
},
StochasticGradientDescent(0.01f, 0.99f));
testNeuralNetwork(neuralNetwork);
} | 33.928571 | 90 | 0.524511 | [
"vector"
] |
ed3a0c76776d0263df741f0e4a89fa98eda26231 | 14,529 | hpp | C++ | src/store.hpp | xianghex/also-test | 18e3f09b77403adc73f700ea5115c19f4c293359 | [
"MIT"
] | 1 | 2019-04-01T11:43:16.000Z | 2019-04-01T11:43:16.000Z | src/store.hpp | xianghex/also-test | 18e3f09b77403adc73f700ea5115c19f4c293359 | [
"MIT"
] | null | null | null | src/store.hpp | xianghex/also-test | 18e3f09b77403adc73f700ea5115c19f4c293359 | [
"MIT"
] | null | null | null | /* also: Advanced Logic Synthesis and Optimization tool
* Copyright (C) 2019- Ningbo University, Ningbo, China
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef STORE_HPP
#define STORE_HPP
#include <alice/alice.hpp>
#include <mockturtle/mockturtle.hpp>
#include <mockturtle/io/write_verilog.hpp>
#include <fmt/format.h>
#include <kitty/kitty.hpp>
#include<mockturtle/io/write_aiger.hpp>
#include "networks/m5ig/m5ig.hpp"
#include "networks/img/img.hpp"
#include "networks/img/img_verilog_reader.hpp"
#include "core/aig2xmg.hpp"
using namespace mockturtle;
namespace alice
{
/********************************************************************
* Genral stores *
********************************************************************/
/* aiger */
ALICE_ADD_STORE( aig_network, "aig", "a", "AIG", "AIGs" )
ALICE_PRINT_STORE( aig_network, os, element )
{
os << "AIG PI/PO = " << element.num_pis() << "/" << element.num_pos() << "\n";
}
ALICE_DESCRIBE_STORE( aig_network, element )
{
return fmt::format( "{} nodes", element.size() );
}
/* mig */
ALICE_ADD_STORE( mig_network, "mig", "m", "MIG", "MIGs" )
ALICE_PRINT_STORE( mig_network, os, element )
{
os << "MIG PI/PO = " << element.num_pis() << "/" << element.num_pos() << "\n";
}
ALICE_DESCRIBE_STORE( mig_network, element )
{
return fmt::format( "{} nodes", element.size() );
}
/* xmg */
ALICE_ADD_STORE( xmg_network, "xmg", "x", "xmg", "xmgs" )
ALICE_PRINT_STORE( xmg_network, os, element )
{
os << fmt::format( " xmg i/o = {}/{} gates = {} ", element.num_pis(), element.num_pos(), element.num_gates() );
os << "\n";
}
ALICE_DESCRIBE_STORE( xmg_network, element )
{
return fmt::format( "{} nodes", element.size() );
}
/* xag */
ALICE_ADD_STORE( xag_network, "xag", "g", "xag", "xags" )
ALICE_PRINT_STORE( xag_network, os, element )
{
os << fmt::format( " xag i/o = {}/{} gates = {} ", element.num_pis(), element.num_pos(), element.num_gates() );
os << "\n";
}
ALICE_DESCRIBE_STORE( xag_network, element )
{
return fmt::format( "{} nodes", element.size() );
}
/* m5ig */
ALICE_ADD_STORE( m5ig_network, "m5ig", "r", "m5ig", "m5igs" )
ALICE_PRINT_STORE( m5ig_network, os, element )
{
os << fmt::format( " m5ig i/o = {}/{} gates = {} ", element.num_pis(), element.num_pos(), element.num_gates() );
os << "\n";
}
ALICE_DESCRIBE_STORE( m5ig_network, element )
{
return fmt::format( "{} nodes", element.size() );
}
/* img */
ALICE_ADD_STORE( img_network, "img", "i", "img", "imgs" )
ALICE_PRINT_STORE( img_network, os, element )
{
os << fmt::format( " img i/o = {}/{} gates = {} ", element.num_pis(), element.num_pos(), element.num_gates() );
os << "\n";
}
ALICE_DESCRIBE_STORE( img_network, element )
{
return fmt::format( "{} nodes", element.size() );
}
/*klut network*/
ALICE_ADD_STORE( klut_network, "lut", "l", "LUT network", "LUT networks" )
ALICE_PRINT_STORE( klut_network, os, element )
{
os << fmt::format( " klut i/o = {}/{} gates = {} ", element.num_pis(), element.num_pos(), element.num_gates() );
os << "\n";
}
ALICE_DESCRIBE_STORE( klut_network, element )
{
return fmt::format( "{} nodes", element.size() );
}
ALICE_PRINT_STORE_STATISTICS( klut_network, os, lut )
{
mockturtle::depth_view depth_lut{lut};
os << fmt::format( "LUTs i/o = {}/{} gates = {} level = {}",
lut.num_pis(), lut.num_pos(), lut.num_gates(), depth_lut.depth() );
os << "\n";
}
/* opt_network */
class optimum_network
{
public:
optimum_network() = default;
optimum_network( const kitty::dynamic_truth_table& function )
: function( function ) {}
optimum_network( kitty::dynamic_truth_table&& function )
: function( std::move( function ) ) {}
bool exists() const
{
static std::vector<std::unordered_set<kitty::dynamic_truth_table, kitty::hash<kitty::dynamic_truth_table>>> hash;
if ( function.num_vars() >= hash.size() )
{
hash.resize( function.num_vars() + 1 );
}
return !hash[function.num_vars()].insert( function ).second;
}
public: /* field access */
kitty::dynamic_truth_table function{0};
std::string network;
};
ALICE_ADD_STORE( optimum_network, "opt", "o", "network", "networks" )
ALICE_DESCRIBE_STORE( optimum_network, opt )
{
if ( opt.network.empty() )
{
return fmt::format( "{}", kitty::to_hex( opt.function ) );
}
else
{
return fmt::format( "{}, optimum network computed", kitty::to_hex( opt.function ) );
}
}
ALICE_PRINT_STORE( optimum_network, os, opt )
{
os << fmt::format( "function (hex): {}\nfunction (bin): {}\n", kitty::to_hex( opt.function ), kitty::to_binary( opt.function ) );
if ( opt.network.empty() )
{
os << "no optimum network computed\n";
}
else
{
os << fmt::format( "optimum network: {}\n", opt.network );
}
}
/********************************************************************
* Read and Write *
********************************************************************/
ALICE_ADD_FILE_TYPE( aiger, "Aiger" );
ALICE_READ_FILE( aig_network, aiger, filename, cmd )
{
aig_network aig;
if( lorina::read_aiger( filename, mockturtle::aiger_reader( aig ) ) != lorina::return_code::success )
{
std::cout << "[w] parse error\n";
}
return aig;
}
ALICE_PRINT_STORE_STATISTICS( aig_network, os, aig )
{
auto aig_copy = mockturtle::cleanup_dangling( aig );
mockturtle::depth_view depth_aig{aig_copy};
os << fmt::format( "AIG i/o = {}/{} gates = {} level = {}",
aig.num_pis(), aig.num_pos(), aig.num_gates(), depth_aig.depth() );
os << "\n";
}
ALICE_ADD_FILE_TYPE( verilog, "Verilog" );
ALICE_READ_FILE( xmg_network, verilog, filename, cmd )
{
xmg_network xmg;
if ( lorina::read_verilog( filename, mockturtle::verilog_reader( xmg ) ) != lorina::return_code::success )
{
std::cout << "[w] parse error\n";
}
return xmg;
}
ALICE_WRITE_FILE( xmg_network, verilog, xmg, filename, cmd )
{
mockturtle::write_verilog( xmg, filename );
}
ALICE_PRINT_STORE_STATISTICS( xmg_network, os, xmg )
{
auto xmg_copy = mockturtle::cleanup_dangling( xmg );
mockturtle::depth_view depth_xmg{xmg_copy};
os << fmt::format( "XMG i/o = {}/{} gates = {} level = {}",
xmg.num_pis(), xmg.num_pos(), xmg.num_gates(), depth_xmg.depth() );
os << "\n";
}
ALICE_READ_FILE( mig_network, verilog, filename, cmd )
{
mig_network mig;
if( lorina::read_verilog( filename, mockturtle::verilog_reader( mig ) ) != lorina::return_code::success )
{
std::cout << "[w] parse error\n";
}
return mig;
}
ALICE_WRITE_FILE( mig_network, verilog, mig, filename, cmd )
{
mockturtle::write_verilog( mig, filename );
}
ALICE_PRINT_STORE_STATISTICS( mig_network, os, mig )
{
auto mig_copy = mockturtle::cleanup_dangling( mig );
mockturtle::depth_view depth_mig{mig_copy};
os << fmt::format( "MIG i/o = {}/{} gates = {} level = {}",
mig.num_pis(), mig.num_pos(), mig.num_gates(), depth_mig.depth() );
os << "\n";
}
ALICE_READ_FILE( xag_network, verilog, filename, cmd )
{
xag_network xag;
if( lorina::read_verilog( filename, mockturtle::verilog_reader( xag ) ) != lorina::return_code::success )
{
std::cout << "[w] parse error\n";
}
return xag;
}
ALICE_WRITE_FILE( xag_network, verilog, xag, filename, cmd )
{
mockturtle::write_verilog( xag, filename );
}
ALICE_PRINT_STORE_STATISTICS( xag_network, os, xag )
{
auto xag_copy = mockturtle::cleanup_dangling( xag );
mockturtle::depth_view depth_xag{xag_copy};
os << fmt::format( "XAG i/o = {}/{} gates = {} level = {}",
xag.num_pis(), xag.num_pos(), xag.num_gates(), depth_xag.depth() );
os << "\n";
}
ALICE_READ_FILE( img_network, verilog, filename, cmd )
{
img_network img;
if ( lorina::read_verilog( filename, img_verilog_reader( img ) ) != lorina::return_code::success )
{
std::cout << "[w] parse error\n";
}
return img;
}
ALICE_PRINT_STORE_STATISTICS( img_network, os, img )
{
auto img_copy = mockturtle::cleanup_dangling( img );
mockturtle::depth_view depth_img{img_copy};
os << fmt::format( "IMG i/o = {}/{} gates = {} level = {}",
img.num_pis(), img.num_pos(), img.num_gates(), depth_img.depth() );
os << "\n";
}
ALICE_ADD_FILE_TYPE( bench, "BENCH" );
ALICE_READ_FILE( klut_network, bench, filename, cmd )
{
klut_network klut;
if( lorina::read_bench( filename, mockturtle::bench_reader( klut ) ) != lorina::return_code::success )
{
std::cout << "[w] parse error\n";
}
return klut;
}
ALICE_WRITE_FILE( xmg_network, bench, xmg, filename, cmd )
{
mockturtle::write_bench( xmg, filename );
}
ALICE_WRITE_FILE( mig_network, bench, mig, filename, cmd )
{
mockturtle::write_bench( mig, filename );
}
ALICE_WRITE_FILE( aig_network, bench, aig, filename, cmd )
{
mockturtle::write_bench( aig, filename );
}
ALICE_WRITE_FILE( m5ig_network, bench, m5ig, filename, cmd )
{
mockturtle::write_bench( m5ig, filename );
}
ALICE_WRITE_FILE( img_network, bench, img, filename, cmd )
{
mockturtle::write_bench( img, filename );
}
ALICE_WRITE_FILE( xag_network, bench, xag, filename, cmd )
{
mockturtle::write_bench( xag, filename );
}
ALICE_WRITE_FILE( klut_network, bench, klut, filename, cmd )
{
mockturtle::write_bench( klut, filename );
}
ALICE_WRITE_FILE(aig_network, aiger, aig, filename, cmd)
{
mockturtle::write_aiger(aig, filename);
}
/********************************************************************
* Convert from aig to mig *
********************************************************************/
ALICE_CONVERT( aig_network, element, mig_network )
{
aig_network aig = element;
/* LUT mapping */
mapping_view<aig_network, true> mapped_aig{aig};
lut_mapping_params ps;
ps.cut_enumeration_ps.cut_size = 4;
lut_mapping<mapping_view<aig_network, true>, true>( mapped_aig, ps );
/* collapse into k-LUT network */
const auto klut = *collapse_mapped_network<klut_network>( mapped_aig );
/* node resynthesis */
mig_npn_resynthesis resyn;
auto mig = node_resynthesis<mig_network>( klut, resyn );
return mig;
}
/* show */
template<>
bool can_show<aig_network>( std::string& extension, command& cmd )
{
extension = "dot";
return true;
}
template<>
void show<aig_network>( std::ostream& os, const aig_network& element, const command& cmd )
{
gate_dot_drawer<aig_network> drawer;
write_dot( element, os, drawer );
}
template<>
bool can_show<mig_network>( std::string& extension, command& cmd )
{
extension = "dot";
return true;
}
template<>
void show<mig_network>( std::ostream& os, const mig_network& element, const command& cmd )
{
gate_dot_drawer<mig_network> drawer;
write_dot( element, os, drawer );
}
template<>
bool can_show<xmg_network>( std::string& extension, command& cmd )
{
extension = "dot";
return true;
}
template<>
void show<xmg_network>( std::ostream& os, const xmg_network& element, const command& cmd )
{
gate_dot_drawer<xmg_network> drawer;
write_dot( element, os, drawer );
}
template<>
bool can_show<klut_network>( std::string& extension, command& cmd )
{
extension = "dot";
return true;
}
template<>
void show<klut_network>( std::ostream& os, const klut_network& element, const command& cmd )
{
gate_dot_drawer<klut_network> drawer;
write_dot( element, os, drawer );
}
template<>
bool can_show<xag_network>( std::string& extension, command& cmd )
{
extension = "dot";
return true;
}
template<>
void show<xag_network>( std::ostream& os, const xag_network& element, const command& cmd )
{
gate_dot_drawer<xag_network> drawer;
write_dot( element, os, drawer );
}
/********************************************************************
* Convert from aig to xmg *
********************************************************************/
ALICE_CONVERT( aig_network, element, xmg_network )
{
aig_network aig = element;
/* LUT mapping */
mapping_view<aig_network, true> mapped_aig{aig};
lut_mapping_params ps;
ps.cut_enumeration_ps.cut_size = 4;
lut_mapping<mapping_view<aig_network, true>, true>( mapped_aig, ps );
/* collapse into k-LUT network */
const auto klut = *collapse_mapped_network<klut_network>( mapped_aig );
/* node resynthesis */
xmg_npn_resynthesis resyn;
auto xmg = node_resynthesis<xmg_network>( klut, resyn );
return xmg;
}
ALICE_CONVERT( mig_network, element, xmg_network )
{
mig_network mig = element;
return also::xmg_from_mig( mig );
}
/*ALICE_CONVERT( aig_network, element, xmg_network )
{
aig_network aig = element;
return also::xmg_from_aig( aig );
}*/
}
#endif
| 27.780115 | 133 | 0.603896 | [
"vector"
] |
ed3aa1d4c7213acfde2f63ee719edab553c9bd79 | 6,206 | cpp | C++ | src/slave/containerizer/mesos/isolators/docker/volume/driver.cpp | Acidburn0zzz/mesos | 3562f95d0cd216634b53217710e60c25ff7524d1 | [
"Apache-2.0"
] | 1 | 2016-09-12T05:25:15.000Z | 2016-09-12T05:25:15.000Z | src/slave/containerizer/mesos/isolators/docker/volume/driver.cpp | Acidburn0zzz/mesos | 3562f95d0cd216634b53217710e60c25ff7524d1 | [
"Apache-2.0"
] | null | null | null | src/slave/containerizer/mesos/isolators/docker/volume/driver.cpp | Acidburn0zzz/mesos | 3562f95d0cd216634b53217710e60c25ff7524d1 | [
"Apache-2.0"
] | null | null | null | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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 <glog/logging.h>
#include <process/collect.hpp>
#include <process/io.hpp>
#include <process/subprocess.hpp>
#include <stout/stringify.hpp>
#include <stout/os/killtree.hpp>
#include "common/status_utils.hpp"
#include "slave/containerizer/mesos/isolators/docker/volume/driver.hpp"
namespace io = process::io;
using std::string;
using std::tuple;
using std::vector;
using process::Failure;
using process::Future;
using process::MONITOR;
using process::NO_SETSID;
using process::Owned;
using process::Subprocess;
namespace mesos {
namespace internal {
namespace slave {
namespace docker {
namespace volume {
constexpr Duration MOUNT_TIMEOUT = Seconds(120);
constexpr Duration UNMOUNT_TIMEOUT = Seconds(120);
Try<Owned<DriverClient>> DriverClient::create(
const std::string& dvdcli)
{
return Owned<DriverClient>(new DriverClient(dvdcli));
}
Future<string> DriverClient::mount(
const string& driver,
const string& name,
const hashmap<string, string>& options)
{
// Refer to https://github.com/emccode/dvdcli for how dvdcli works.
// TODO(gyliu513): Add `explicitcreate` if 'options' is None. Refer
// to https://github.com/emccode/dvdcli/pull/20 for detail.
vector<string> argv = {
dvdcli,
"mount",
"--volumedriver=" + driver,
"--volumename=" + name,
};
foreachpair (const string& key, const string& value, options) {
argv.push_back("--volumeopts=" + key + "=" + value);
}
string command = strings::join(
", ",
dvdcli,
strings::join(", ", argv));
VLOG(1) << "Invoking Docker Volume Driver 'mount' "
<< "command '" << command << "'";
Try<Subprocess> s = subprocess(
dvdcli,
argv,
Subprocess::PATH("/dev/null"),
Subprocess::PIPE(),
Subprocess::PIPE(),
NO_SETSID,
nullptr,
None(),
None(),
{},
None(),
MONITOR);
if (s.isError()) {
return Failure("Failed to execute '" + command + "': " + s.error());
}
return await(
s->status(),
io::read(s->out().get()),
io::read(s->err().get()))
.then([](const tuple<
Future<Option<int>>,
Future<string>,
Future<string>>& t) -> Future<string> {
Future<Option<int>> status = std::get<0>(t);
if (!status.isReady()) {
return Failure(
"Failed to get the exit status of the subprocess: " +
(status.isFailed() ? status.failure() : "discarded"));
}
if (status->isNone()) {
return Failure("Failed to reap the subprocess");
}
if (status->get() != 0) {
Future<string> error = std::get<2>(t);
if (!error.isReady()) {
return Failure(
"Unexpected termination of the subprocess: " +
WSTRINGIFY(status->get()));
}
return Failure(
"Unexpected termination of the subprocess: " + error.get());
}
Future<string> output = std::get<1>(t);
if (!output.isReady()) {
return Failure(
"Failed to read stdout from the subprocess: " +
(output.isFailed() ? output.failure() : "discarded"));
}
return output;
})
.after(MOUNT_TIMEOUT, [s](Future<string> future) -> Future<string> {
future.discard();
os::killtree(s->pid(), SIGKILL);
return Failure("'mount' timed out in " + stringify(MOUNT_TIMEOUT));
});
}
Future<Nothing> DriverClient::unmount(
const string& driver,
const string& name)
{
vector<string> argv = {
dvdcli,
"unmount",
"--volumedriver=" + driver,
"--volumename=" + name,
};
string command = strings::join(
", ",
dvdcli,
strings::join(", ", argv));
VLOG(1) << "Invoking Docker Volume Driver 'unmount' "
<< "command '" << command << "'";
Try<Subprocess> s = subprocess(
dvdcli,
argv,
Subprocess::PATH("/dev/null"),
Subprocess::PIPE(),
Subprocess::PIPE(),
NO_SETSID,
nullptr,
None(),
None(),
{},
None(),
MONITOR);
if (s.isError()) {
return Failure("Failed to execute '" + command + "': " + s.error());
}
return await(
s->status(),
io::read(s->err().get()))
.then([](const tuple<
Future<Option<int>>,
Future<string>>& t) -> Future<Nothing> {
Future<Option<int>> status = std::get<0>(t);
if (!status.isReady()) {
return Failure(
"Failed to get the exit status of the subprocess: " +
(status.isFailed() ? status.failure() : "discarded"));
}
if (status->isNone()) {
return Failure("Failed to reap the subprocess");
}
if (status->get() != 0) {
Future<string> error = std::get<1>(t);
if (!error.isReady()) {
return Failure(
"Unexpected termination of the subprocess: " +
WSTRINGIFY(status->get()));
}
return Failure(
"Unexpected termination of the subprocess: " + error.get());
}
return Nothing();
})
.after(UNMOUNT_TIMEOUT, [s](Future<Nothing> future) -> Future<Nothing> {
future.discard();
os::killtree(s->pid(), SIGKILL);
return Failure("'unmount' timed out in " + stringify(UNMOUNT_TIMEOUT));
});
}
} // namespace volume {
} // namespace docker {
} // namespace slave {
} // namespace internal {
} // namespace mesos {
| 26.408511 | 77 | 0.598292 | [
"vector"
] |
ed3b934b0b666d35f8f618ea4a8d3ac481ad8ecd | 981 | hh | C++ | src/PageSections/_Private/stringify_shape.hh | YuryBandarchuk16/hh-apidoc | 996f8a606193fb111929d9e1b48ae772b0d1b12b | [
"MIT"
] | null | null | null | src/PageSections/_Private/stringify_shape.hh | YuryBandarchuk16/hh-apidoc | 996f8a606193fb111929d9e1b48ae772b0d1b12b | [
"MIT"
] | null | null | null | src/PageSections/_Private/stringify_shape.hh | YuryBandarchuk16/hh-apidoc | 996f8a606193fb111929d9e1b48ae772b0d1b12b | [
"MIT"
] | null | null | null | <?hh // strict
/*
* Copyright (c) 2018-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
namespace Facebook\HHAPIDoc\PageSections\_Private;
use type Facebook\DefinitionFinder\ScannedShapeField;
use function Facebook\DefinitionFinder\ast_without_trivia;
use namespace HH\Lib\{C, Str, Vec};
function stringify_shape(
string $ns,
vec<ScannedShapeField> $fields,
): string {
$ret = "shape(\n";
foreach ($fields as $field) {
$ret .= ' '.stringify_expression($field->getName());
$ret .= ' => ';
$value = stringify_typehint($ns, $field->getValueType());
$lines = Str\split($value, "\n");
if (C\count($lines) === 1) {
$ret .= $lines[0];
} else {
$ret .= $lines
|> Vec\map($$, $l ==> ' '.$l)
|> Str\join($$, "\n")
|> "\n".$$;
}
$ret .= ",\n";
}
return $ret.')';
}
| 23.926829 | 67 | 0.591233 | [
"shape"
] |
ed3d8997c86f881f942299acd55ce1e7c97a6767 | 4,769 | hpp | C++ | cmdstan/stan/lib/stan_math/test/unit/math/torsten/pmx_neut_mpi_test_fixture.hpp | csetraynor/Torsten | 55b59b8068e2a539346f566ec698c755a9e3536c | [
"BSD-3-Clause"
] | null | null | null | cmdstan/stan/lib/stan_math/test/unit/math/torsten/pmx_neut_mpi_test_fixture.hpp | csetraynor/Torsten | 55b59b8068e2a539346f566ec698c755a9e3536c | [
"BSD-3-Clause"
] | null | null | null | cmdstan/stan/lib/stan_math/test/unit/math/torsten/pmx_neut_mpi_test_fixture.hpp | csetraynor/Torsten | 55b59b8068e2a539346f566ec698c755a9e3536c | [
"BSD-3-Clause"
] | null | null | null | #ifndef STAN_MATH_TORSTEN_PK_NEUT_MPI_TEST_FIXTURE_HPP
#define STAN_MATH_TORSTEN_PK_NEUT_MPI_TEST_FIXTURE_HPP
#include <stan/math/rev/mat.hpp>
#include <gtest/gtest.h>
#include <boost/numeric/odeint.hpp>
#include <test/unit/math/torsten/test_util.hpp>
#include <test/unit/math/torsten/pmx_ode_test_fixture.hpp>
#include <stan/math/torsten/dsolve/pmx_cvodes_fwd_system.hpp>
#include <stan/math/torsten/dsolve/pmx_cvodes_integrator.hpp>
#include <test/unit/math/prim/arr/functor/harmonic_oscillator.hpp>
#include <test/unit/math/prim/arr/functor/lorenz.hpp>
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
class TorstenPopulationNeutropeniaTest : public testing::Test {
void SetUp() {
// make sure memory's clean before starting each test
stan::math::recover_memory();
torsten::mpi::Envionment::init();
}
public:
TorstenPopulationNeutropeniaTest() :
f(),
nCmt(8),
nt(27),
time{ 0.000, 0.000, 0.083, 0.167, 0.250, 0.500, 0.750, 1.000, 1.500, 2.000,
3.000, 4.000, 6.000, 8.000, 12.000, 12.083, 12.167, 12.250, 12.500, 12.750,
13.000, 13.500, 14.000, 15.000, 16.000, 18.000, 20.000},
amt(nt, 0),
rate(nt, 0),
cmt(nt, 2),
evid(nt, 0),
ii(nt, 0),
addl(nt, 0),
ss(nt, 0),
theta(1, {10.74924, 16.83211, 37.33329, 98.06352, 2.001674, 119.6034, 4.787322, 0.201094, 0.000278} ),
biovar(1, std::vector<double>(nCmt, 1.0)),
tlag(1, std::vector<double>(nCmt, 0.0)),
np(8),
time_m (np * nt),
amt_m (np * nt),
rate_m (np * nt),
cmt_m (np * nt),
evid_m (np * nt),
ii_m (np * nt),
addl_m (np * nt),
ss_m (np * nt),
theta_m (np * theta.size()),
biovar_m (np * biovar.size()),
tlag_m (np * tlag.size()),
len(np)
{
SetUp();
amt[1] = 80000;
cmt[1] = 1;
evid[1] = 1;
ii[1] = 12;
addl[1] = 1;
setup_population();
}
void setup_population() {
// population data
for (int i = 0; i < np; ++i) {
for (int j = 0; j < nt; ++j) {
time_m[i * nt + j] = time[j];
amt_m [i * nt + j] = amt[j];
rate_m[i * nt + j] = rate[j];
cmt_m [i * nt + j] = cmt[j];
evid_m[i * nt + j] = evid[j];
ii_m [i * nt + j] = ii[j];
addl_m[i * nt + j] = addl[j];
ss_m [i * nt + j] = ss[j];
}
}
// population param
for (int i = 0; i < np; ++i) {
theta_m[i] = theta[0];
biovar_m[i] = biovar[0];
tlag_m[i] = tlag[0];
}
// population length
for (int i = 0; i < np; ++i) {
len[i] = nt;
}
}
/*
* setup population given length of each individual,
* so that individual data that are greater than
* given length is modified by @c std::vector::resize()
*/
void setup_population(const std::vector<int>& length) {
time_m.clear();
amt_m.clear();
rate_m.clear();
cmt_m.clear();
evid_m.clear();
ii_m.clear();
addl_m.clear();
ss_m.clear();
theta_m.clear();
biovar_m.clear();
tlag_m.clear();
// population data
for (size_t i = 0; i < length.size(); ++i) {
assert(length[i] <= nt);
for (int j = 0; j < length[i]; ++j) {
time_m.push_back(time[j]);
amt_m .push_back(amt[j]);
rate_m.push_back(rate[j]);
cmt_m .push_back(cmt[j]);
evid_m.push_back(evid[j]);
ii_m .push_back(ii[j]);
addl_m.push_back(addl[j]);
ss_m .push_back(ss[j]);
}
}
// population param
for (size_t i = 0; i < length.size(); ++i) {
for (int j = 0; j < length[i]; ++j) {
theta_m.push_back(theta[0]);
biovar_m.push_back(biovar[0]);
tlag_m.push_back(tlag[0]);
}
}
// population length
len.resize(length.size());
for (size_t i = 0; i < length.size(); ++i) {
len[i] = length[i];
}
np = length.size();
}
const TwoCptNeutModelODE f;
const int nCmt;
const int nt;
std::vector<double> time;
std::vector<double> amt;
std::vector<double> rate;
std::vector<int> cmt;
std::vector<int> evid;
std::vector<double> ii;
std::vector<int> addl;
std::vector<int> ss;
std::vector<std::vector<double> > theta;
std::vector<std::vector<double> > biovar;
std::vector<std::vector<double> > tlag;
int np;
std::vector<double> time_m ;
std::vector<double> amt_m ;
std::vector<double> rate_m ;
std::vector<int > cmt_m ;
std::vector<int > evid_m ;
std::vector<double> ii_m ;
std::vector<int > addl_m ;
std::vector<int > ss_m ;
std::vector<std::vector<double> > theta_m;
std::vector<std::vector<double> > biovar_m ;
std::vector<std::vector<double> > tlag_m ;
std::vector<int> len;
};
#endif
| 27.096591 | 106 | 0.565737 | [
"vector"
] |
ed42979f645d9e7bff8ab006a90fac4dccb35ae1 | 3,246 | cpp | C++ | RenderCore/Techniques/ModelCache.cpp | pocketgems/XLE2 | 82771e9ab1fc3b12927f1687bbe05d4f7dce8765 | [
"MIT"
] | 3 | 2018-05-17T08:39:39.000Z | 2020-12-09T13:20:26.000Z | RenderCore/Techniques/ModelCache.cpp | pocketgems/XLE2 | 82771e9ab1fc3b12927f1687bbe05d4f7dce8765 | [
"MIT"
] | null | null | null | RenderCore/Techniques/ModelCache.cpp | pocketgems/XLE2 | 82771e9ab1fc3b12927f1687bbe05d4f7dce8765 | [
"MIT"
] | 1 | 2021-11-14T08:50:15.000Z | 2021-11-14T08:50:15.000Z | // Distributed under the MIT License (See
// accompanying file "LICENSE" or the website
// http://www.opensource.org/licenses/mit-license.php)
#include "ModelCache.h"
#include "SimpleModelRenderer.h"
#include "../Assets/ModelScaffold.h"
#include "../Assets/MaterialScaffold.h"
#include "../../Assets/AssetLRUHeap.h"
#include "../../Utility/HeapUtils.h"
#include <unordered_map>
namespace RenderCore { namespace Techniques
{
using BoundingBox = std::pair<Float3, Float3>;
class ModelCache::Pimpl
{
public:
std::vector<std::pair<uint64_t, BoundingBox>> _boundingBoxes;
::Assets::AssetLRUHeap<RenderCore::Assets::ModelScaffold> _modelScaffolds;
::Assets::AssetLRUHeap<RenderCore::Assets::MaterialScaffold> _materialScaffolds;
Threading::Mutex _modelRenderersLock;
LRUCache<::Assets::AssetFuture<SimpleModelRenderer>> _modelRenderers;
std::shared_ptr<IPipelineAcceleratorPool> _pipelineAcceleratorPool;
uint32_t _reloadId;
Pimpl(const ModelCache::Config& cfg);
~Pimpl();
};
ModelCache::Pimpl::Pimpl(const ModelCache::Config& cfg)
: _modelScaffolds(cfg._modelScaffoldCount)
, _materialScaffolds(cfg._materialScaffoldCount)
, _modelRenderers(cfg._rendererCount)
, _reloadId(0)
{}
ModelCache::Pimpl::~Pimpl() {}
uint32_t ModelCache::GetReloadId() const { return _pimpl->_reloadId; }
auto ModelCache::GetModelRenderer(
StringSection<ResChar> modelFilename,
StringSection<ResChar> materialFilename) -> ::Assets::FuturePtr<SimpleModelRenderer>
{
auto hash = HashCombine(Hash64(modelFilename), Hash64(materialFilename));
::Assets::FuturePtr<SimpleModelRenderer> newFuture;
{
ScopedLock(_pimpl->_modelRenderersLock);
auto& existing = _pimpl->_modelRenderers.Get(hash);
if (existing) {
if (!::Assets::IsInvalidated(*existing))
return existing;
++_pimpl->_reloadId;
}
auto stringInitializer = ::Assets::Internal::AsString(modelFilename, materialFilename); // (used for tracking/debugging purposes)
newFuture = std::make_shared<::Assets::AssetFuture<SimpleModelRenderer>>(stringInitializer);
_pimpl->_modelRenderers.Insert(hash, newFuture);
}
auto modelScaffold = _pimpl->_modelScaffolds.Get(modelFilename);
auto materialScaffold = _pimpl->_materialScaffolds.Get(materialFilename, modelFilename);
::Assets::AutoConstructToFuture<SimpleModelRenderer>(*newFuture, _pimpl->_pipelineAcceleratorPool, modelScaffold, materialScaffold);
return newFuture;
}
auto ModelCache::GetModelScaffold(StringSection<ResChar> name) -> ::Assets::FuturePtr<RenderCore::Assets::ModelScaffold>
{
return _pimpl->_modelScaffolds.Get(name);
}
auto ModelCache::GetMaterialScaffold(StringSection<ResChar> materialName, StringSection<ResChar> modelName) -> ::Assets::FuturePtr<RenderCore::Assets::MaterialScaffold>
{
return _pimpl->_materialScaffolds.Get(materialName, modelName);
}
ModelCache::ModelCache(const std::shared_ptr<IPipelineAcceleratorPool>& pipelineAcceleratorPool, const Config& cfg)
{
_pimpl = std::make_unique<Pimpl>(cfg);
_pimpl->_pipelineAcceleratorPool = pipelineAcceleratorPool;
}
ModelCache::~ModelCache()
{}
}}
| 34.531915 | 169 | 0.735675 | [
"vector"
] |
ed42fa8ccd1c6e6f49a3232e57cc274e10591574 | 4,678 | cpp | C++ | ConversionWorker.cpp | Phitherek/oziexplorer_uiview_converter | 4036100f5438f4d692e6ae4a29586b4162bffa87 | [
"MIT"
] | null | null | null | ConversionWorker.cpp | Phitherek/oziexplorer_uiview_converter | 4036100f5438f4d692e6ae4a29586b4162bffa87 | [
"MIT"
] | null | null | null | ConversionWorker.cpp | Phitherek/oziexplorer_uiview_converter | 4036100f5438f4d692e6ae4a29586b4162bffa87 | [
"MIT"
] | null | null | null | //
// Created by phitherek on 20.11.15.
//
#include <gtkmm/textview.h>
#include <glibmm/fileutils.h>
#include <glibmm/regex.h>
#include "ConversionWorker.h"
#include "Converter.h"
#include "ConversionError.h"
#include <sstream>
#include <gtkmm/progressbar.h>
#include <iostream>
#include <chrono>
#include <thread>
ConversionWorker::ConversionWorker(): _indir(""), _outdir(""), _cont(false), _mutex(), _thread(0), _builder(0), _conversionlogbuffer(0) {}
ConversionWorker::~ConversionWorker() {
Glib::Threads::Mutex::Lock lock(_mutex);
_cont = false;
_thread->join();
_conversionlogbuffer.reset();
_builder.reset();
}
void ConversionWorker::start(Glib::RefPtr<Gtk::Builder> builder) {
_builder = builder;
_thread = Glib::Threads::Thread::create(sigc::mem_fun(*this, &ConversionWorker::run));
}
void ConversionWorker::run() {
Gtk::ProgressBar* conversionprogressbar = NULL;
Gtk::Label* conversionprogress = NULL;
Gtk::TextView* conversionlogtextview = NULL;
_builder->get_widget("conversionprogressbar", conversionprogressbar);
_builder->get_widget("conversionprogress", conversionprogress);
_builder->get_widget("conversionlogtextview", conversionlogtextview);
_conversionlogbuffer = Gtk::TextBuffer::create();
{
Glib::Threads::Mutex::Lock lock(_mutex);
if(_indir != "" && _outdir != "") {
_cont = true;
} else {
_conversionlogbuffer->insert_at_cursor("Could not start conversion: Input and output directories cannot be empty!\n");
conversionlogtextview->set_buffer(_conversionlogbuffer);
sig_done();
return;
}
}
if(_cont) {
{
Glib::Threads::Mutex::Lock lock(_mutex);
_conversionlogbuffer->insert_at_cursor("Starting conversion...\n");
conversionlogtextview->set_buffer(_conversionlogbuffer);
}
Glib::Dir dir(_indir);
std::vector<std::string> dirContents, inputs, outputs;
dirContents.assign(dir.begin(), dir.end());
for(unsigned int i = 0; i < dirContents.size(); i++) {
Glib::RefPtr<Glib::Regex> nameRegex = Glib::Regex::create("\\.map$");
if(nameRegex->match(dirContents[i])) {
inputs.push_back(dirContents[i]);
}
}
unsigned int i = 0;
while(_cont && i < inputs.size()) {
std::string input = _indir + "/" + inputs[i];
std::string output = _outdir + "/" + inputs[i];
output.replace(output.length()-3, 3, "inf");
std::stringstream status;
status.str("");
status << i+1 << "/" << inputs.size();
{
Glib::Threads::Mutex::Lock lock(_mutex);
conversionprogress->set_text(status.str());
conversionprogressbar->set_fraction(static_cast<double>(i+1)/inputs.size());
_conversionlogbuffer->insert_at_cursor("Converting file " + inputs[i] + "... ");
conversionlogtextview->set_buffer(_conversionlogbuffer);
}
Converter conv(input, output);
try {
conv.convert();
{
Glib::Threads::Mutex::Lock lock(_mutex);
_conversionlogbuffer->insert_at_cursor("Success!\n");
conversionlogtextview->set_buffer(_conversionlogbuffer);
}
} catch(ConversionError& e) {
std::string err = "";
err += "\nError! ";
err += e.what();
err += "\n";
{
Glib::Threads::Mutex::Lock lock(_mutex);
_conversionlogbuffer->insert_at_cursor(err);
conversionlogtextview->set_buffer(_conversionlogbuffer);
}
}
i++;
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
{
Glib::Threads::Mutex::Lock lock(_mutex);
if(i == inputs.size()) {
_conversionlogbuffer->insert_at_cursor("Conversion done!\n");
conversionlogtextview->set_buffer(_conversionlogbuffer);
} else {
_conversionlogbuffer->insert_at_cursor("Conversion cancelled!\n");
conversionlogtextview->set_buffer(_conversionlogbuffer);
}
}
_cont = false;
sig_done();
}
}
void ConversionWorker::cancel() {
Glib::Threads::Mutex::Lock lock(_mutex);
_cont = false;
}
bool ConversionWorker::running() {
Glib::Threads::Mutex::Lock lock(_mutex);
return _cont;
}
| 36.263566 | 138 | 0.578666 | [
"vector"
] |
ed44400870c9ff138543caf83250f3a250111fab | 13,976 | cpp | C++ | Source/UnitTests/UnitTest_Model.cpp | nTopology/lib3mf | 8ad7511c59df88376554805105def4cdacbc8e77 | [
"BSD-2-Clause"
] | 2 | 2017-04-18T05:56:37.000Z | 2018-06-27T21:52:03.000Z | Source/UnitTests/UnitTest_Model.cpp | martinweismann/lib3mf | 6332b23de0d5ec26aac8b5a53c169a54d4b60a34 | [
"BSD-2-Clause"
] | null | null | null | Source/UnitTests/UnitTest_Model.cpp | martinweismann/lib3mf | 6332b23de0d5ec26aac8b5a53c169a54d4b60a34 | [
"BSD-2-Clause"
] | null | null | null | /*++
Copyright (C) 2017 Autodesk Inc.
Copyright (C) 2015 Microsoft Corporation (Original Author)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Abstract:
UnitTest_Model.cpp: Defines Unittests for the model class
--*/
#include "CppUnitTest.h"
#include "Model\Classes\NMR_Model.h"
#include "Model\Reader\NMR_ModelReader_3MF_Native.h"
#include "Model\Writer\NMR_ModelWriter_3MF_Native.h"
#include "Common\Mesh\NMR_Mesh.h"
#include "Common\MeshExport\NMR_MeshExporter_STL.h"
#include "Model\Classes\NMR_ModelBuildItem.h"
#include "Model\Classes\NMR_ModelMeshObject.h"
#include "Model\Classes\NMR_ModelObject.h"
#include "Common\NMR_Exception.h"
#include "Model\Classes\NMR_ModelTextureAttachment.h"
#ifdef NMR_COM_NATIVE
#include "Model\Reader\NMR_ModelReader_3MF_OPC.h"
#include "Model\Writer\NMR_ModelWriter_3MF_OPC.h"
#include "Common\Platform\NMR_ExportStream_COM.h"
#include "Common\Platform\NMR_ImportStream_COM.h"
#define IMPORTSTREAM CImportStream_COM
#define EXPORTSTREAM CExportStream_COM
#define WRITER CModelWriter_3MF_OPC
#define READER CModelReader_3MF_OPC
#else
#include "Model\Reader\NMR_ModelReader_3MF_Native.h"
#include "Model\Writer\NMR_ModelWriter_3MF_Native.h"
#include "Common\Platform\NMR_ExportStream_GCC_Native.h"
#include "Common\Platform\NMR_ImportStream_GCC_Native.h"
#define IMPORTSTREAM CImportStream_GCC_Native
#define EXPORTSTREAM CExportStream_GCC_Native
#define WRITER CModelWriter_3MF_Native
#define READER CModelReader_3MF_Native
#endif
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace NMR
{
TEST_CLASS(ModelTest)
{
private:
static const std::wstring sInPath;
static const std::wstring sOutPath;
public:
const double EPS_TOL = 1e-5;
TEST_METHOD(Model_3MFBox)
{
PModel pModel = std::make_shared<CModel> ();
PModelReader pModelReader = std::make_shared<READER> (pModel);
PImportStream pImportStream = std::make_shared<IMPORTSTREAM>((sInPath + L"Box.3mf").c_str());
pModelReader->readStream(pImportStream);
CMesh Mesh;
pModel->mergeToMesh(&Mesh);
PExportStream pExportStream(new EXPORTSTREAM((sOutPath + L"output_3mfbox.stl").c_str()));
PMeshExporter pExporter(new CMeshExporter_STL(pExportStream));
pExporter->exportMesh(&Mesh, NULL);
}
TEST_METHOD(Model_3MFBox10)
{
PModel pModel = std::make_shared<CModel>();
PModelReader pModelReader = std::make_shared<READER>(pModel);
PImportStream pImportStream = std::make_shared<IMPORTSTREAM>((sInPath + L"cube10.3mf").c_str());
pModelReader->readStream(pImportStream);
PModelWriter pModelWriter = std::make_shared<WRITER>(pModel);
PExportStream pExportStream = std::make_shared<EXPORTSTREAM>((sOutPath + L"output_3mfcube10.3mf").c_str());
pModelWriter->exportToStream(pExportStream);
}
TEST_METHOD(Model_3MFModel093)
{
PModel pModel = std::make_shared<CModel>();
PModelReader pModelReader = std::make_shared<READER>(pModel);
PImportStream pImportStream = std::make_shared<IMPORTSTREAM>((sInPath + L"track093.3mf").c_str());
pModelReader->readStream(pImportStream);
PModelWriter pModelWriter = std::make_shared<WRITER>(pModel);
PExportStream pExportStream = std::make_shared<EXPORTSTREAM>((sOutPath + L"output_track093.3mf").c_str());
pModelWriter->exportToStream(pExportStream);
}
TEST_METHOD(Model_3MFColor093)
{
PModel pModel = std::make_shared<CModel>();
PModelReader pModelReader = std::make_shared<READER>(pModel);
PImportStream pImportStream = std::make_shared<IMPORTSTREAM>((sInPath + L"Color_093.3mf").c_str());
pModelReader->readStream(pImportStream);
PModelWriter pModelWriter = std::make_shared<WRITER>(pModel);
PExportStream pExportStream = std::make_shared<EXPORTSTREAM>((sOutPath + L"output_color093.3mf").c_str());
pModelWriter->exportToStream(pExportStream);
}
TEST_METHOD(Model_3MFTexture093)
{
PModel pModel = std::make_shared<CModel>();
PModelReader pModelReader = std::make_shared<READER>(pModel);
PImportStream pImportStream = std::make_shared<IMPORTSTREAM>((sInPath + L"Texture_093.3mf").c_str());
pModelReader->readStream(pImportStream);
PModelWriter pModelWriter = std::make_shared<WRITER>(pModel);
PExportStream pExportStream = std::make_shared<EXPORTSTREAM>((sOutPath + L"output_texture093.3mf").c_str());
pModelWriter->exportToStream(pExportStream);
}
TEST_METHOD(Model_3MFBase1)
{
PModel pModel = std::make_shared<CModel>();
PModelReader pModelReader = std::make_shared<READER>(pModel);
PImportStream pImportStream = std::make_shared<IMPORTSTREAM>((sInPath+L"3mfbase1_cube.3mf").c_str());
pModelReader->readStream(pImportStream);
PModelWriter pModelWriter = std::make_shared<WRITER>(pModel);
PExportStream pExportStream = std::make_shared<EXPORTSTREAM>((sOutPath + L"output_3mfbase1.3mf").c_str());
pModelWriter->exportToStream(pExportStream);
}
TEST_METHOD(Model_3MFBase2)
{
PModel pModel = std::make_shared<CModel>();
PModelReader pModelReader = std::make_shared<READER>(pModel);
PImportStream pImportStream = std::make_shared<IMPORTSTREAM>((sInPath+L"3mfbase2_material093.3mf").c_str());
pModelReader->readStream(pImportStream);
PModelWriter pModelWriter = std::make_shared<WRITER>(pModel);
PExportStream pExportStream = std::make_shared<EXPORTSTREAM>((sOutPath + L"output_3mfbase2.3mf").c_str());
pModelWriter->exportToStream(pExportStream);
}
//TEST_METHOD(Model_3MFBase3)
//{
// PModel pModel = std::make_shared<CModel>();
// PModelReader pModelReader = std::make_shared<READER>(pModel);
// PImportStream pImportStream = std::make_shared<IMPORTSTREAM>((sInPath + L"3mfbase3_MaterialAndTexture093.3mf").c_str());
// pModelReader->readStream(pImportStream);
// PModelWriter pModelWriter = std::make_shared<CModelWriter_3MF_OPC>(pModel);
// PExportStream pExportStream = std::make_shared<EXPORTSTREAM>((sOutPath + L"output_3mfbase3.3mf").c_str());
// pModelWriter->exportToStream(pExportStream);
//}
TEST_METHOD(Model_3MFBase4)
{
PModel pModel = std::make_shared<CModel>();
#ifdef NMR_COM_NATIVE
PModelReader pModelReader = std::make_shared<READER>(pModel);
PImportStream pImportStream = std::make_shared<IMPORTSTREAM>((sInPath + L"3mfbase4_Mesh1.3mf").c_str());
#else
PModelReader pModelReader = std::make_shared<READER>(pModel);
PImportStream pImportStream = std::make_shared<IMPORTSTREAM>((sInPath + L"3mfbase4_Mesh1.3mf").c_str());
#endif
pModelReader->readStream(pImportStream);
PModelWriter pModelWriter = std::make_shared<WRITER>(pModel);
PExportStream pExportStream = std::make_shared<EXPORTSTREAM>((sOutPath + L"output_3mfbase4.3mf").c_str());
pModelWriter->exportToStream(pExportStream);
}
TEST_METHOD(Model_3MFBase5)
{
PModel pModel = std::make_shared<CModel>();
PModelReader pModelReader = std::make_shared<READER>(pModel);
PImportStream pImportStream = std::make_shared<IMPORTSTREAM>((sInPath + L"3mfbase5_texture093.3mf").c_str());
pModelReader->readStream(pImportStream);
PModelWriter pModelWriter = std::make_shared<WRITER>(pModel);
PExportStream pExportStream = std::make_shared<EXPORTSTREAM>((sOutPath + L"output_3mfbase5.3mf").c_str());
pModelWriter->exportToStream(pExportStream);
}
TEST_METHOD(Model_3MFBase8)
{
PModel pModel = std::make_shared<CModel>();
PModelReader pModelReader = std::make_shared<READER>(pModel);
PImportStream pImportStream = std::make_shared<IMPORTSTREAM>((sInPath + L"3mfbase8_VertexTet1.3mf").c_str());
pModelReader->readStream(pImportStream);
PModelWriter pModelWriter = std::make_shared<WRITER>(pModel);
PExportStream pExportStream = std::make_shared<EXPORTSTREAM>((sOutPath + L"output_3mfbase8.3mf").c_str());
pModelWriter->exportToStream(pExportStream);
}
TEST_METHOD(Model_3MFBase9)
{
PModel pModel = std::make_shared<CModel>();
PModelReader pModelReader = std::make_shared<READER>(pModel);
PImportStream pImportStream = std::make_shared<IMPORTSTREAM>((sInPath + L"3mfbase9_ladybug.3mf").c_str());
pModelReader->readStream(pImportStream);
PModelWriter pModelWriter = std::make_shared<WRITER>(pModel);
PExportStream pExportStream = std::make_shared<EXPORTSTREAM>((sOutPath + L"output_3mfbase9.3mf").c_str());
pModelWriter->exportToStream(pExportStream);
}
TEST_METHOD(Model_3MFBase10)
{
PModel pModel = std::make_shared<CModel>();
PModelReader pModelReader = std::make_shared<READER>(pModel);
PImportStream pImportStream = std::make_shared<IMPORTSTREAM>((sInPath + L"3mfbase10_box.3mf").c_str());
pModelReader->readStream(pImportStream);
PModelWriter pModelWriter = std::make_shared<WRITER>(pModel);
PExportStream pExportStream = std::make_shared<EXPORTSTREAM>((sOutPath + L"output_3mfbase10.3mf").c_str());
pModelWriter->exportToStream(pExportStream);
}
TEST_METHOD(Model_3MFBase11)
{
PModel pModel = std::make_shared<CModel>();
PModelReader pModelReader = std::make_shared<READER>(pModel);
PImportStream pImportStream = std::make_shared<IMPORTSTREAM>((sInPath + L"3mfbase11_AdjMount.3mf").c_str());
pModelReader->readStream(pImportStream);
PModelWriter pModelWriter = std::make_shared<WRITER>(pModel);
PExportStream pExportStream = std::make_shared<EXPORTSTREAM>((sOutPath + L"output_3mfbase11.3mf").c_str());
pModelWriter->exportToStream(pExportStream);
}
TEST_METHOD(Model_3MFBase12)
{
PModel pModel = std::make_shared<CModel>();
PModelReader pModelReader = std::make_shared<READER>(pModel);
PImportStream pImportStream = std::make_shared<IMPORTSTREAM>((sInPath + L"3mfbase12_holed_cube.3mf").c_str());
pModelReader->readStream(pImportStream);
PModelWriter pModelWriter = std::make_shared<WRITER>(pModel);
PExportStream pExportStream = std::make_shared<EXPORTSTREAM>((sOutPath + L"output_3mfbase12.3mf").c_str());
pModelWriter->exportToStream(pExportStream);
}
TEST_METHOD(Model_3MFBase13)
{
PModel pModel = std::make_shared<CModel>();
PModelReader pModelReader = std::make_shared<READER>(pModel);
PImportStream pImportStream = std::make_shared<IMPORTSTREAM>((sInPath + L"3mfbase13_holed_cube_support.3mf").c_str());
pModelReader->readStream(pImportStream);
PModelWriter pModelWriter = std::make_shared<WRITER>(pModel);
PExportStream pExportStream = std::make_shared<EXPORTSTREAM>((sOutPath + L"output_3mfbase13.3mf").c_str());
pModelWriter->exportToStream(pExportStream);
}
TEST_METHOD(Model_3MFBase14)
{
PModel pModel = std::make_shared<CModel>();
PModelReader pModelReader = std::make_shared<READER>(pModel);
PImportStream pImportStream = std::make_shared<IMPORTSTREAM>((sInPath + L"3mfbase14_materialandcolor2.3mf").c_str());
pModelReader->readStream(pImportStream);
PModelWriter pModelWriter = std::make_shared<WRITER>(pModel);
PExportStream pExportStream = std::make_shared<EXPORTSTREAM>((sOutPath + L"output_3mfbase14.3mf").c_str());
pModelWriter->exportToStream(pExportStream);
}
TEST_METHOD(Model_3MFModel100_TexCube)
{
PModel pModel = std::make_shared<CModel>();
PModelReader pModelReader = std::make_shared<READER>(pModel);
PImportStream pImportStream = std::make_shared<IMPORTSTREAM>((sInPath + L"texcube.3mf").c_str());
pModelReader->readStream(pImportStream);
nfUint32 nAttachmentCount = pModel->getAttachmentCount();
Assert::IsTrue(nAttachmentCount == 2);
PImportStream pTexStream = pModel->getModelAttachment(0)->getStream();
Assert::IsTrue(pTexStream.get() != nullptr);
nfUint64 nTexture0Size = pTexStream->retrieveSize();
Assert::IsTrue(nTexture0Size == 0x158d);
PModelWriter pModelWriter = std::make_shared<WRITER>(pModel);
PExportStream pExportStream = std::make_shared<EXPORTSTREAM>((sOutPath + L"output_texcube.3mf").c_str());
pModelWriter->exportToStream(pExportStream);
}
TEST_METHOD(Model_3MFTexture)
{
PModel pModel = std::make_shared<CModel>();
PModelReader_3MF pModelReader = std::make_shared<READER>(pModel);
PImportStream pImportStream = std::make_shared<IMPORTSTREAM>((sInPath + L"Texture.3mf").c_str());
pModelReader->readStream(pImportStream);
CMesh Mesh;
pModel->mergeToMesh(&Mesh);
PExportStream pExportStream(new EXPORTSTREAM((sOutPath + L"output_3mftexture.stl").c_str()));
PMeshExporter pExporter(new CMeshExporter_STL(pExportStream));
pExporter->exportMesh(&Mesh, NULL);
PModelWriter pModelWriter = std::make_shared<WRITER>(pModel);
PExportStream p3MFExportStream(new EXPORTSTREAM((sOutPath + L"output_3mftexture.3mf").c_str()));
pModelWriter->exportToStream(p3MFExportStream);
}
};
const std::wstring ModelTest::sInPath = L"../../TestFiles/VS_UnitTests/";
const std::wstring ModelTest::sOutPath = L"../TestOutput/";
} | 41.227139 | 125 | 0.766171 | [
"mesh",
"model"
] |
ed447a6ee383c4ca62ff24721d6d6501ed9bdba4 | 85,464 | cpp | C++ | modules/dynamic_modules/fulltick/fulltick.cpp | mykeels/simple | 3074fa32a8d1e8e691ffa1dc48b2767898bc943c | [
"MIT"
] | 2 | 2018-04-12T11:55:13.000Z | 2018-11-21T06:51:42.000Z | modules/dynamic_modules/fulltick/fulltick.cpp | mykeels/simple | 3074fa32a8d1e8e691ffa1dc48b2767898bc943c | [
"MIT"
] | 1 | 2018-09-24T22:09:59.000Z | 2018-09-24T22:10:41.000Z | modules/dynamic_modules/fulltick/fulltick.cpp | appcypher/simple | 7fad63106d7537708b17df2bf12f193c8271ab97 | [
"MIT"
] | 1 | 2018-11-21T06:51:48.000Z | 2018-11-21T06:51:48.000Z | #include "fulltick_delegate.cpp"
/** the callback class for fulltick library **/
CallbackStruct::CallbackStruct(void *the_pointer, String *the_block, Fl_Widget *the_widget) {
pointer = the_pointer ;
block = the_block ;
widget = the_widget ;
}
/** the callback delegate for the fulltick library **/
static void SimpleCallBack(Fl_Widget*, void* callback_struct) {
CallbackStruct *cbs = (CallbackStruct *) callback_struct ;
simple_vm_runcode((VM *) cbs->pointer,simple_string_get(cbs->block));
}
/** might be needed later for key listeners **/
int MyWindow::handle(int msg) {
return msg;
}
extern "C" {
SIMPLE_API void init_simple_module(SimpleState *sState)
{
init_full_tick(sState);
}
}
SIMPLE_BLOCK(test_gui)
{
if ( SIMPLE_API_PARACOUNT != 1 ) {
SIMPLE_API_ERROR(SIMPLE_API_MISS1PARA);
return ;
}
if ( SIMPLE_API_ISSTRING(1) ) {
Fl_Window *window = new Fl_Window(340,180);
Fl_Box *box = new Fl_Box(20,40,300,100,SIMPLE_API_GETSTRING(1));
box->box(FL_UP_BOX);
box->labelfont(FL_BOLD+FL_ITALIC);
box->labelsize(36);
box->labeltype(FL_SHADOW_LABEL);
window->end();
window->show();
int ret = Fl::run();
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
/** FAPP **/
SIMPLE_BLOCK(run_fulltick)
{
if ( SIMPLE_API_PARACOUNT != 0 ) {
SIMPLE_API_ERROR(FULLTICK_NOPARAM);
return ;
} SIMPLE_API_RETNUMBER(Fl::run());
}
SIMPLE_BLOCK(set_scheme)
{
if ( SIMPLE_API_PARACOUNT != 1 ) {
SIMPLE_API_ERROR(FULLTICK_MISING1PARAM);
return ;
}
if ( SIMPLE_API_ISSTRING(1) ) {
Fl::scheme(simple_string_new_gc(((VM*)pointer)->sState,SIMPLE_API_GETSTRING(1))->str);
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
/** FWIDGETS **/
SIMPLE_BLOCK(resizable_object)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISPOINTER(2) ) {
Fl_Group * group = (Fl_Group* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
Fl_Widget * widget = (Fl_Widget* ) SIMPLE_API_GETCPOINTER(2,"SIMPLE_FLTK_");
group->resizable(widget);
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(set_widget_background)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Widget *window = (Fl_Widget* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
window->color(((Fl_Color) SIMPLE_API_GETNUMBER(2)));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(set_label_color)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Widget *window = (Fl_Widget* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
window->labelcolor(((Fl_Color) SIMPLE_API_GETNUMBER(2)));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(set_label_size)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Widget *window = (Fl_Widget* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
window->labelsize((int)SIMPLE_API_GETNUMBER(2));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(set_label_type)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Widget *widget = (Fl_Widget* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
if (_FL_SHADOW_LABEL == ((Fl_Labeltype)(int)SIMPLE_API_GETNUMBER(2)))
widget->labeltype(FL_SHADOW_LABEL);
else if ((FL_NORMAL_LABEL == ((Fl_Labeltype)(int)SIMPLE_API_GETNUMBER(2))))
widget->labeltype(FL_SYMBOL_LABEL);
else if ((_FL_ENGRAVED_LABEL == ((Fl_Labeltype)(int)SIMPLE_API_GETNUMBER(2))))
widget->labeltype(FL_ENGRAVED_LABEL);
else if ((_FL_EMBOSSED_LABEL == ((Fl_Labeltype)(int)SIMPLE_API_GETNUMBER(2))))
widget->labeltype(FL_EMBOSSED_LABEL);
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(set_label_font)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Widget *window = (Fl_Widget* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
window->labelfont((int)SIMPLE_API_GETNUMBER(2));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(set_label)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISSTRING(2) ) {
Fl_Widget *window = (Fl_Widget* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
window->copy_label(SIMPLE_API_GETSTRING(2));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(get_label)
{
if ( SIMPLE_API_PARACOUNT != 1) {
SIMPLE_API_ERROR(FULLTICK_MISING1PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) ) {
Fl_Widget *widget = (Fl_Widget* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
if ((char*)widget->label() != NULL ) {
SIMPLE_API_RETSTRING((char*)widget->label());
} else {
SIMPLE_API_RETSTRING("");
}
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(set_size)
{
if ( SIMPLE_API_PARACOUNT != 3 ) {
SIMPLE_API_ERROR(FULLTICK_MISING3PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) && SIMPLE_API_ISNUMBER(3) ) {
Fl_Widget *window = (Fl_Widget* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
window->size((int)SIMPLE_API_GETNUMBER(2),(int)SIMPLE_API_GETNUMBER(3));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(set_tooltip)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISSTRING(2) ) {
Fl_Widget *window = (Fl_Widget* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
String* tooltip = simple_string_new_gc(((VM*)pointer)->sState,SIMPLE_API_GETSTRING(2));
window->tooltip(tooltip->str);
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(set_visibility)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Widget *object = (Fl_Widget* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
if (SIMPLE_API_GETNUMBER(2) == 0) {
object->hide();
} else if (SIMPLE_API_GETNUMBER(2) == 1) {
object->show();
} else if (SIMPLE_API_GETNUMBER(2) == 2) {
Fl_Window* object = (Fl_Window* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
object->iconize();
}
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(on_click)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISCPOINTER(1) ) {
Fl_Widget *widget = (Fl_Widget* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
String * str = simple_string_new_gc(((VM *) pointer)->sState,SIMPLE_API_GETSTRING(2));
CallbackStruct *cbs = new CallbackStruct(pointer, str, widget);
widget->callback(SimpleCallBack,cbs);
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(activate_deactivate_widget)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISCPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Widget *widget = (Fl_Widget* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
if (SIMPLE_API_GETNUMBER(2) == 1) {
widget->activate();
} else {
widget->deactivate();
}
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(add_widget)
{
if ( SIMPLE_API_PARACOUNT != 3 ) {
SIMPLE_API_ERROR(FULLTICK_MISING3PARAM);
return ;
}
if ( SIMPLE_API_ISCPOINTER(1) && SIMPLE_API_ISCPOINTER(2) && SIMPLE_API_ISNUMBER(3)) {
Fl_Group *window = (Fl_Group* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
if ( (int)SIMPLE_API_GETNUMBER(3) == 1) {
window->add_resizable(*((Fl_Group* ) SIMPLE_API_GETCPOINTER(2,"SIMPLE_FLTK_")));
} else {
window->add(((Fl_Group* ) SIMPLE_API_GETCPOINTER(2,"SIMPLE_FLTK_")));
}
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(redraw_widget)
{
if ( SIMPLE_API_PARACOUNT != 1 ) {
SIMPLE_API_ERROR(FULLTICK_MISING1PARAM);
return ;
}
if ( SIMPLE_API_ISCPOINTER(1) ) {
Fl_Widget *widget = (Fl_Widget* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
widget->redraw();
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(redraw_widget_parent)
{
if ( SIMPLE_API_PARACOUNT != 1 ) {
SIMPLE_API_ERROR(FULLTICK_MISING1PARAM);
return ;
}
if ( SIMPLE_API_ISCPOINTER(1) ) {
Fl_Widget *widget = (Fl_Widget* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
widget->parent()->redraw();
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(get_parent_widget)
{
if ( SIMPLE_API_PARACOUNT != 1 ) {
SIMPLE_API_ERROR(FULLTICK_MISING1PARAM);
return ;
}
if ( SIMPLE_API_ISCPOINTER(1) ) {
Fl_Widget *widget = (Fl_Widget* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
Fl_Widget *parent_widget = widget->parent();
SIMPLE_API_RETCPOINTER(parent_widget,"SIMPLE_FLTK_");
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(set_position)
{
if ( SIMPLE_API_PARACOUNT != 3 ) {
SIMPLE_API_ERROR(FULLTICK_MISING3PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) && SIMPLE_API_ISNUMBER(3) ) {
Fl_Widget *widget = (Fl_Widget* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
widget->position((int)SIMPLE_API_GETNUMBER(2),(int)SIMPLE_API_GETNUMBER(3));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(widget_box)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING3PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Widget *widget = (Fl_Widget* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
if ((int)SIMPLE_API_GETNUMBER(2)==-1) {
SIMPLE_API_RETNUMBER(widget->box());
} else {
widget->box(((Fl_Boxtype)(int)SIMPLE_API_GETNUMBER(2)));
}
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
/** FWINDOW **/
SIMPLE_BLOCK(init_window)
{
if ( SIMPLE_API_PARACOUNT != 4 ) {
SIMPLE_API_ERROR(FULLTICK_MISING6PARAM);
return ;
}
if ( SIMPLE_API_ISNUMBER(1) && SIMPLE_API_ISNUMBER(2) && SIMPLE_API_ISSTRING(3) && SIMPLE_API_ISNUMBER(4)) {
Fl_Window *window = new Fl_Window((int)SIMPLE_API_GETNUMBER(1),(int)SIMPLE_API_GETNUMBER(2), simple_string_new_gc(((VM*)pointer)->sState,SIMPLE_API_GETSTRING(3))->str);
if (SIMPLE_API_GETNUMBER(4) == 1)
{
Fl_Window& reswindow = *window; reswindow.resizable(&reswindow);
}
window->end();
SIMPLE_API_RETCPOINTER(window,"SIMPLE_FLTK_");
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(show_window)
{
if ( SIMPLE_API_PARACOUNT != 1 ) {
SIMPLE_API_ERROR(FULLTICK_MISING1PARAM);
return ;
}
if ( SIMPLE_API_ISCPOINTER(1) ) {
Fl_Window& window = *((Fl_Window* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_"));
window.show();
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(full_screen)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2)) {
Fl_Window *window = (Fl_Window* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
if ((int)SIMPLE_API_GETNUMBER(2) == 1 ) {
window->fullscreen();
} else {
window->fullscreen_off();
}
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(window_border)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2)) {
Fl_Window *window = (Fl_Window* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
window->border((int)SIMPLE_API_GETNUMBER(2));
int windowx = window->x(), windowy = window->y();
window->hide(); window->show(); window->position(windowx, windowy);
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(set_window_icon)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Window *window = (Fl_Window* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
//window->icon((char*)LoadIcon(fl_display, MAKEINTRESOURCE(101)));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
/** FBOX/FPANEL **/
SIMPLE_BLOCK(init_box)
{
if ( SIMPLE_API_PARACOUNT != 4 ) {
SIMPLE_API_ERROR(FULLTICK_MISING4PARAM);
return ;
}
if ( SIMPLE_API_ISNUMBER(1) && SIMPLE_API_ISNUMBER(2) && SIMPLE_API_ISNUMBER(3) && SIMPLE_API_ISNUMBER(4)) {
Fl_Box *box = new Fl_Box((int)SIMPLE_API_GETNUMBER(1),(int)SIMPLE_API_GETNUMBER(2),(int)SIMPLE_API_GETNUMBER(3),(int)SIMPLE_API_GETNUMBER(4));
SIMPLE_API_RETCPOINTER(box,"SIMPLE_FLTK_");
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(set_box_type)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISCPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Box *box = ((Fl_Box* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_"));
box->box((Fl_Boxtype)(int)SIMPLE_API_GETNUMBER(2));
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
/** GROUP **/
SIMPLE_BLOCK(init_group)
{
if ( SIMPLE_API_PARACOUNT != 4 ) {
SIMPLE_API_ERROR(FULLTICK_MISING4PARAM);
return ;
}
if ( SIMPLE_API_ISNUMBER(1) && SIMPLE_API_ISNUMBER(2) && SIMPLE_API_ISNUMBER(3) && SIMPLE_API_ISNUMBER(4)) {
Fl_Group *group = new Fl_Group((int)SIMPLE_API_GETNUMBER(1),(int)SIMPLE_API_GETNUMBER(2),(int)SIMPLE_API_GETNUMBER(3),(int)SIMPLE_API_GETNUMBER(4));
SIMPLE_API_RETCPOINTER(group,"SIMPLE_FLTK_");
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(group_begin)
{
if ( SIMPLE_API_PARACOUNT != 1 ) {
SIMPLE_API_ERROR(FULLTICK_MISING1PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) ) {
Fl_Group *group = (Fl_Group* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
group->begin();
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(group_children)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Group *group = (Fl_Group* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
if ((int)SIMPLE_API_GETNUMBER(2)==-1) {
SIMPLE_API_RETNUMBER(group->children());
} else {
SIMPLE_API_RETCPOINTER(group->child((int)SIMPLE_API_GETNUMBER(2)),"SIMPLE_FLTK_");
}
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(group_clear)
{
if ( SIMPLE_API_PARACOUNT != 1 ) {
SIMPLE_API_ERROR(FULLTICK_MISING1PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) ) {
Fl_Group *group = (Fl_Group* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
group->clear();
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(group_clip_children)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Group *group = (Fl_Group* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
if ((int)SIMPLE_API_GETNUMBER(2)==-1) {
SIMPLE_API_RETNUMBER(group->clip_children());
} else {
group->clip_children((int)SIMPLE_API_GETNUMBER(2));
}
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(group_end)
{
if ( SIMPLE_API_PARACOUNT != 1 ) {
SIMPLE_API_ERROR(FULLTICK_MISING1PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) ) {
Fl_Group *group = (Fl_Group* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
group->end();
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(group_find)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISPOINTER(2) ) {
Fl_Group *group = (Fl_Group* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
SIMPLE_API_RETNUMBER(group->find((Fl_Widget* ) SIMPLE_API_GETCPOINTER(2,"SIMPLE_FLTK_"))-1);
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(group_focus)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISPOINTER(2) ) {
Fl_Group *group = (Fl_Group* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
group->focus((Fl_Widget* ) SIMPLE_API_GETCPOINTER(2,"SIMPLE_FLTK_"));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(group_init_sizes)
{
if ( SIMPLE_API_PARACOUNT != 1 ) {
SIMPLE_API_ERROR(FULLTICK_MISING1PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) ) {
Fl_Group *group = (Fl_Group* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
group->init_sizes();
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(group_insert)
{
if ( SIMPLE_API_PARACOUNT != 4 ) {
SIMPLE_API_ERROR(FULLTICK_MISING4PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISPOINTER(2) && SIMPLE_API_ISNUMBER(3)) {
Fl_Group *group = (Fl_Group* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
if ((int)SIMPLE_API_GETNUMBER(3)==-1) {
group->insert(*((Fl_Widget* ) SIMPLE_API_GETCPOINTER(2,"SIMPLE_FLTK_")),(Fl_Widget* ) SIMPLE_API_GETCPOINTER(4,"SIMPLE_FLTK_"));
} else {
group->insert(*((Fl_Widget* ) SIMPLE_API_GETCPOINTER(2,"SIMPLE_FLTK_")),(int)SIMPLE_API_GETNUMBER(3));
}
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(group_remove)
{
if ( SIMPLE_API_PARACOUNT != 3 ) {
SIMPLE_API_ERROR(FULLTICK_MISING3PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2)) {
Fl_Group *group = (Fl_Group* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
if ((int)SIMPLE_API_GETNUMBER(2)==-1) {
group->remove((Fl_Widget* ) SIMPLE_API_GETCPOINTER(3,"SIMPLE_FLTK_"));
} else {
group->remove((int)SIMPLE_API_GETNUMBER(2));
}
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
/** FLABEL **/
SIMPLE_BLOCK(set_size_with_label)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Widget *widget = (Fl_Widget* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
int wi=0, hi=0; fl_font(widget->labelfont(), widget->labelsize());
fl_measure(widget->label(), wi,hi);
widget->size(wi+(int)SIMPLE_API_GETNUMBER(2),hi+(int)SIMPLE_API_GETNUMBER(2));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
/** FBUTTON (s) **/
SIMPLE_BLOCK(init_button)
{
if ( SIMPLE_API_PARACOUNT != 4 ) {
SIMPLE_API_ERROR(FULLTICK_MISING4PARAM);
return ;
}
if ( SIMPLE_API_ISNUMBER(1) && SIMPLE_API_ISNUMBER(2) && SIMPLE_API_ISNUMBER(3) && SIMPLE_API_ISNUMBER(4)) {
Fl_Button *button = new Fl_Button((int)SIMPLE_API_GETNUMBER(1),(int)SIMPLE_API_GETNUMBER(2),(int)SIMPLE_API_GETNUMBER(3),(int)SIMPLE_API_GETNUMBER(4));
SIMPLE_API_RETCPOINTER(button,"SIMPLE_FLTK_");
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(init_return_button)
{
if ( SIMPLE_API_PARACOUNT != 4 ) {
SIMPLE_API_ERROR(FULLTICK_MISING4PARAM);
return ;
}
if ( SIMPLE_API_ISNUMBER(1) && SIMPLE_API_ISNUMBER(2) && SIMPLE_API_ISNUMBER(3) && SIMPLE_API_ISNUMBER(4)) {
Fl_Return_Button *button = new Fl_Return_Button((int)SIMPLE_API_GETNUMBER(1),(int)SIMPLE_API_GETNUMBER(2),(int)SIMPLE_API_GETNUMBER(3),(int)SIMPLE_API_GETNUMBER(4));
SIMPLE_API_RETCPOINTER(button,"SIMPLE_FLTK_");
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(init_repeat_button)
{
if ( SIMPLE_API_PARACOUNT != 4 ) {
SIMPLE_API_ERROR(FULLTICK_MISING4PARAM);
return ;
}
if ( SIMPLE_API_ISNUMBER(1) && SIMPLE_API_ISNUMBER(2) && SIMPLE_API_ISNUMBER(3) && SIMPLE_API_ISNUMBER(4)) {
Fl_Repeat_Button *button = new Fl_Repeat_Button((int)SIMPLE_API_GETNUMBER(1),(int)SIMPLE_API_GETNUMBER(2),(int)SIMPLE_API_GETNUMBER(3),(int)SIMPLE_API_GETNUMBER(4));
SIMPLE_API_RETCPOINTER(button,"SIMPLE_FLTK_");
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(init_light_button)
{
if ( SIMPLE_API_PARACOUNT != 4 ) {
SIMPLE_API_ERROR(FULLTICK_MISING4PARAM);
return ;
}
if ( SIMPLE_API_ISNUMBER(1) && SIMPLE_API_ISNUMBER(2) && SIMPLE_API_ISNUMBER(3) && SIMPLE_API_ISNUMBER(4)) {
Fl_Light_Button *button = new Fl_Light_Button((int)SIMPLE_API_GETNUMBER(1),(int)SIMPLE_API_GETNUMBER(2),(int)SIMPLE_API_GETNUMBER(3),(int)SIMPLE_API_GETNUMBER(4));
SIMPLE_API_RETCPOINTER(button,"SIMPLE_FLTK_");
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(init_round_button)
{
if ( SIMPLE_API_PARACOUNT != 4 ) {
SIMPLE_API_ERROR(FULLTICK_MISING4PARAM);
return ;
}
if ( SIMPLE_API_ISNUMBER(1) && SIMPLE_API_ISNUMBER(2) && SIMPLE_API_ISNUMBER(3) && SIMPLE_API_ISNUMBER(4)) {
Fl_Round_Button *button = new Fl_Round_Button((int)SIMPLE_API_GETNUMBER(1),(int)SIMPLE_API_GETNUMBER(2),(int)SIMPLE_API_GETNUMBER(3),(int)SIMPLE_API_GETNUMBER(4));
SIMPLE_API_RETCPOINTER(button,"SIMPLE_FLTK_");
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(init_check_button)
{
if ( SIMPLE_API_PARACOUNT != 4 ) {
SIMPLE_API_ERROR(FULLTICK_MISING4PARAM);
return ;
}
if ( SIMPLE_API_ISNUMBER(1) && SIMPLE_API_ISNUMBER(2) && SIMPLE_API_ISNUMBER(3) && SIMPLE_API_ISNUMBER(4)) {
Fl_Check_Button *button = new Fl_Check_Button((int)SIMPLE_API_GETNUMBER(1),(int)SIMPLE_API_GETNUMBER(2),(int)SIMPLE_API_GETNUMBER(3),(int)SIMPLE_API_GETNUMBER(4));
SIMPLE_API_RETCPOINTER(button,"SIMPLE_FLTK_");
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(init_toggle_button)
{
if ( SIMPLE_API_PARACOUNT != 4 ) {
SIMPLE_API_ERROR(FULLTICK_MISING4PARAM);
return ;
}
if ( SIMPLE_API_ISNUMBER(1) && SIMPLE_API_ISNUMBER(2) && SIMPLE_API_ISNUMBER(3) && SIMPLE_API_ISNUMBER(4)) {
Fl_Toggle_Button *button = new Fl_Toggle_Button((int)SIMPLE_API_GETNUMBER(1),(int)SIMPLE_API_GETNUMBER(2),(int)SIMPLE_API_GETNUMBER(3),(int)SIMPLE_API_GETNUMBER(4));
SIMPLE_API_RETCPOINTER(button,"SIMPLE_FLTK_");
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(set_button_down_box)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISCPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Button *box = ((Fl_Button* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_"));
box->down_box((Fl_Boxtype)(int)SIMPLE_API_GETNUMBER(2));
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(set_button_down_color)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Button *button = (Fl_Button* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
button->down_color(((Fl_Color) SIMPLE_API_GETNUMBER(2)));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(set_button_only)
{
if ( SIMPLE_API_PARACOUNT != 1 ) {
SIMPLE_API_ERROR(FULLTICK_MISING1PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) ) {
Fl_Button *button = (Fl_Button* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
button->setonly();
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(set_button_shortcut)
{
if ( SIMPLE_API_PARACOUNT != 3 ) {
SIMPLE_API_ERROR(FULLTICK_MISING3PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Button *button = (Fl_Button* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
if (((int)SIMPLE_API_GETNUMBER(2)) == 1) {
button->shortcut(((int)SIMPLE_API_GETNUMBER(3)));
} else {
button->shortcut(((char *)SIMPLE_API_GETSTRING(3)));
}
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(set_button_value)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Button *button = (Fl_Button* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
button->value(((int) SIMPLE_API_GETNUMBER(2)));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(get_button_value)
{
if ( SIMPLE_API_PARACOUNT != 1 ) {
SIMPLE_API_ERROR(FULLTICK_MISING1PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) ) {
Fl_Button *button = (Fl_Button* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
SIMPLE_API_RETNUMBER(button->value());
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
/** FINPUT/FTEXT (s) **/
SIMPLE_BLOCK(init_input)
{
if ( SIMPLE_API_PARACOUNT != 4 ) {
SIMPLE_API_ERROR(FULLTICK_MISING4PARAM);
return ;
}
if ( SIMPLE_API_ISNUMBER(1) && SIMPLE_API_ISNUMBER(2) && SIMPLE_API_ISNUMBER(3) && SIMPLE_API_ISNUMBER(4)) {
Fl_Input *input = new Fl_Input((int)SIMPLE_API_GETNUMBER(1),(int)SIMPLE_API_GETNUMBER(2),(int)SIMPLE_API_GETNUMBER(3),(int)SIMPLE_API_GETNUMBER(4));
SIMPLE_API_RETCPOINTER(input,"SIMPLE_FLTK_");
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(init_float_input)
{
if ( SIMPLE_API_PARACOUNT != 4 ) {
SIMPLE_API_ERROR(FULLTICK_MISING4PARAM);
return ;
}
if ( SIMPLE_API_ISNUMBER(1) && SIMPLE_API_ISNUMBER(2) && SIMPLE_API_ISNUMBER(3) && SIMPLE_API_ISNUMBER(4)) {
Fl_Float_Input *input = new Fl_Float_Input((int)SIMPLE_API_GETNUMBER(1),(int)SIMPLE_API_GETNUMBER(2),(int)SIMPLE_API_GETNUMBER(3),(int)SIMPLE_API_GETNUMBER(4));
SIMPLE_API_RETCPOINTER(input,"SIMPLE_FLTK_");
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(init_int_input)
{
if ( SIMPLE_API_PARACOUNT != 4 ) {
SIMPLE_API_ERROR(FULLTICK_MISING4PARAM);
return ;
}
if ( SIMPLE_API_ISNUMBER(1) && SIMPLE_API_ISNUMBER(2) && SIMPLE_API_ISNUMBER(3) && SIMPLE_API_ISNUMBER(4)) {
Fl_Int_Input *input = new Fl_Int_Input((int)SIMPLE_API_GETNUMBER(1),(int)SIMPLE_API_GETNUMBER(2),(int)SIMPLE_API_GETNUMBER(3),(int)SIMPLE_API_GETNUMBER(4));
SIMPLE_API_RETCPOINTER(input,"SIMPLE_FLTK_");
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(init_secret_input)
{
if ( SIMPLE_API_PARACOUNT != 4 ) {
SIMPLE_API_ERROR(FULLTICK_MISING4PARAM);
return ;
}
if ( SIMPLE_API_ISNUMBER(1) && SIMPLE_API_ISNUMBER(2) && SIMPLE_API_ISNUMBER(3) && SIMPLE_API_ISNUMBER(4)) {
Fl_Secret_Input *input = new Fl_Secret_Input((int)SIMPLE_API_GETNUMBER(1),(int)SIMPLE_API_GETNUMBER(2),(int)SIMPLE_API_GETNUMBER(3),(int)SIMPLE_API_GETNUMBER(4));
SIMPLE_API_RETCPOINTER(input,"SIMPLE_FLTK_");
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(init_multiline_input)
{
if ( SIMPLE_API_PARACOUNT != 4 ) {
SIMPLE_API_ERROR(FULLTICK_MISING4PARAM);
return ;
}
if ( SIMPLE_API_ISNUMBER(1) && SIMPLE_API_ISNUMBER(2) && SIMPLE_API_ISNUMBER(3) && SIMPLE_API_ISNUMBER(4)) {
Fl_Multiline_Input *input = new Fl_Multiline_Input((int)SIMPLE_API_GETNUMBER(1),(int)SIMPLE_API_GETNUMBER(2),(int)SIMPLE_API_GETNUMBER(3),(int)SIMPLE_API_GETNUMBER(4));
SIMPLE_API_RETCPOINTER(input,"SIMPLE_FLTK_");
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(input_copy)
{
if ( SIMPLE_API_PARACOUNT != 3 ) {
SIMPLE_API_ERROR(FULLTICK_MISING3PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) && SIMPLE_API_ISNUMBER(3) ) {
Fl_Input_ *input = (Fl_Input_* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
if (SIMPLE_API_GETNUMBER(3) == 1) {
SIMPLE_API_RETNUMBER(input->copy((int)SIMPLE_API_GETNUMBER(2)));
} else {
SIMPLE_API_RETNUMBER(input->copy_cuts());
}
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(input_cut)
{
if ( SIMPLE_API_PARACOUNT != 4 ) {
SIMPLE_API_ERROR(FULLTICK_MISING4PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) && SIMPLE_API_ISNUMBER(3) && SIMPLE_API_ISNUMBER(4)) {
Fl_Input_ *input = (Fl_Input_* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
if (SIMPLE_API_GETNUMBER(4) == 1) {
SIMPLE_API_RETNUMBER(input->cut());
} else if (SIMPLE_API_GETNUMBER(4) == 2) {
SIMPLE_API_RETNUMBER(input->cut((int)SIMPLE_API_GETNUMBER(2)));
} else {
SIMPLE_API_RETNUMBER(input->cut((int)SIMPLE_API_GETNUMBER(2),(int)SIMPLE_API_GETNUMBER(3)));
}
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(set_input_cursor_color)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Input_ *input = (Fl_Input_* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
input->cursor_color(((Fl_Color) SIMPLE_API_GETNUMBER(2)));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(get_input_index)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Input_ *input = (Fl_Input_* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
SIMPLE_API_RETSTRING((const char*)input->index((int) SIMPLE_API_GETNUMBER(2)));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(input_insert)
{
if ( SIMPLE_API_PARACOUNT != 3 ) {
SIMPLE_API_ERROR(FULLTICK_MISING3PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISSTRING(2) && SIMPLE_API_ISNUMBER(3)) {
Fl_Input_ *input = (Fl_Input_* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
if ((int)SIMPLE_API_GETNUMBER(3) == -1) {
input->insert((const char*) SIMPLE_API_GETSTRING(2));
} else {
input->insert((const char*) SIMPLE_API_GETSTRING(2), (int)SIMPLE_API_GETNUMBER(3));
}
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(input_mark)
{
if ( SIMPLE_API_PARACOUNT != 3 ) {
SIMPLE_API_ERROR(FULLTICK_MISING3PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) && SIMPLE_API_ISNUMBER(3)) {
Fl_Input_ *input = (Fl_Input_* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
if ((int)SIMPLE_API_GETNUMBER(3) == 1) {
SIMPLE_API_RETNUMBER(input->mark());
} else {
SIMPLE_API_RETNUMBER(input->mark((int)SIMPLE_API_GETNUMBER(2)));
}
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(input_maximum_size)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2)) {
Fl_Input_ *input = (Fl_Input_* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
input->maximum_size((int)SIMPLE_API_GETNUMBER(2));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(input_position)
{
if ( SIMPLE_API_PARACOUNT != 4 ) {
SIMPLE_API_ERROR(FULLTICK_MISING4PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) && SIMPLE_API_ISNUMBER(3) && SIMPLE_API_ISNUMBER(4)) {
Fl_Input_ *input = (Fl_Input_* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
if ((int)SIMPLE_API_GETNUMBER(4) == 1) {
SIMPLE_API_RETNUMBER(input->position());
} else if ((int)SIMPLE_API_GETNUMBER(4) == 0) {
SIMPLE_API_RETNUMBER(input->position((int)SIMPLE_API_GETNUMBER(2),(int)SIMPLE_API_GETNUMBER(3)));
} else {
SIMPLE_API_RETNUMBER(input->position((int)SIMPLE_API_GETNUMBER(2)));
}
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(input_read_only)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2)) {
Fl_Input_ *input = (Fl_Input_* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
input->readonly((int)SIMPLE_API_GETNUMBER(2));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(input_replace)
{
if ( SIMPLE_API_PARACOUNT != 4 ) {
SIMPLE_API_ERROR(FULLTICK_MISING4PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) && SIMPLE_API_ISNUMBER(3) && SIMPLE_API_ISSTRING(4)) {
Fl_Input_ *input = (Fl_Input_* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
input->replace((int)SIMPLE_API_GETNUMBER(2),(int)SIMPLE_API_GETNUMBER(3),SIMPLE_API_GETSTRING(4));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(input_shortcut)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Input_ *input = (Fl_Input_* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
input->shortcut(((int)SIMPLE_API_GETNUMBER(2)));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(input_size)
{
if ( SIMPLE_API_PARACOUNT != 1 ) {
SIMPLE_API_ERROR(FULLTICK_MISING1PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) ) {
Fl_Input_ *input = (Fl_Input_* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
SIMPLE_API_RETNUMBER(input->size());
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(input_static_value)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISSTRING(2) ) {
Fl_Input_ *input = (Fl_Input_* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
input->static_value(SIMPLE_API_GETSTRING(2));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(input_tab_nav)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Input_ *input = (Fl_Input_* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
input->tab_nav((int)SIMPLE_API_GETNUMBER(2));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(input_text_color)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Input_ *input = (Fl_Input_* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
input->textcolor(((Fl_Color) SIMPLE_API_GETNUMBER(2)));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(input_text_font)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Input_ *input = (Fl_Input_* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
input->textfont((Fl_Font)SIMPLE_API_GETNUMBER(2));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(input_text_size)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Input_ *input = (Fl_Input_* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
input->textsize((Fl_Fontsize)SIMPLE_API_GETNUMBER(2));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(input_value)
{
if ( SIMPLE_API_PARACOUNT != 3 ) {
SIMPLE_API_ERROR(FULLTICK_MISING3PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) && SIMPLE_API_ISSTRING(3)) {
Fl_Input_ *input = (Fl_Input_* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
if (((int)SIMPLE_API_GETNUMBER(2)) == 1) {
SIMPLE_API_RETSTRING(input->value());
} else {
input->value(SIMPLE_API_GETSTRING(3));
}
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(input_undo)
{
if ( SIMPLE_API_PARACOUNT != 1 ) {
SIMPLE_API_ERROR(FULLTICK_MISING1PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) ) {
Fl_Input_ *input = (Fl_Input_* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
input->undo();
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(input_wrap)
{
if ( SIMPLE_API_PARACOUNT != 3 ) {
SIMPLE_API_ERROR(FULLTICK_MISING3PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) && SIMPLE_API_ISNUMBER(3)) {
Fl_Input_ *input = (Fl_Input_* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
if (((int)SIMPLE_API_GETNUMBER(2)) == 1) {
SIMPLE_API_RETNUMBER(input->wrap());
} else {
input->wrap((int)SIMPLE_API_GETNUMBER(3));
}
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
/** FMENU/FMENUBAR **/
SIMPLE_BLOCK(init_menu_bar)
{
if ( SIMPLE_API_PARACOUNT != 4 ) {
SIMPLE_API_ERROR(FULLTICK_MISING4PARAM);
return ;
}
if ( SIMPLE_API_ISNUMBER(1) && SIMPLE_API_ISNUMBER(2) && SIMPLE_API_ISNUMBER(3) && SIMPLE_API_ISNUMBER(4)) {
Fl_Menu_Bar *menu_bar = new Fl_Menu_Bar((int)SIMPLE_API_GETNUMBER(1),(int)SIMPLE_API_GETNUMBER(2),(int)SIMPLE_API_GETNUMBER(3),(int)SIMPLE_API_GETNUMBER(4));
SIMPLE_API_RETCPOINTER(menu_bar,"SIMPLE_FLTK_");
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(init_menu_button)
{
if ( SIMPLE_API_PARACOUNT != 4 ) {
SIMPLE_API_ERROR(FULLTICK_MISING4PARAM);
return ;
}
if ( SIMPLE_API_ISNUMBER(1) && SIMPLE_API_ISNUMBER(2) && SIMPLE_API_ISNUMBER(3) && SIMPLE_API_ISNUMBER(4)) {
Fl_Menu_Button *menu_button = new Fl_Menu_Button((int)SIMPLE_API_GETNUMBER(1),(int)SIMPLE_API_GETNUMBER(2),(int)SIMPLE_API_GETNUMBER(3),(int)SIMPLE_API_GETNUMBER(4));
SIMPLE_API_RETCPOINTER(menu_button,"SIMPLE_FLTK_");
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(menu_add)
{
if ( SIMPLE_API_PARACOUNT != 3 ) {
SIMPLE_API_ERROR(FULLTICK_MISING3PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISSTRING(2) && SIMPLE_API_ISNUMBER(3)) {
Fl_Menu_ *menu = (Fl_Menu_* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
menu->add(SIMPLE_API_GETSTRING(2),0, 0, 0, ((int)SIMPLE_API_GETNUMBER(3)));
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(menu_clear)
{
if ( SIMPLE_API_PARACOUNT != 3 ) {
SIMPLE_API_ERROR(FULLTICK_MISING3PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) && SIMPLE_API_ISNUMBER(3)) {
Fl_Menu_ *menu = (Fl_Menu_* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
if (((int)SIMPLE_API_GETNUMBER(2)) == 1) {
menu->clear_submenu(((int)SIMPLE_API_GETNUMBER(3)));
} else {
menu->clear();
}
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(menu_down_box)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Menu_ *menu = (Fl_Menu_* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
menu->down_box((Fl_Boxtype)(int)SIMPLE_API_GETNUMBER(2));
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(menu_selection_color)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Menu_ *menu = (Fl_Menu_* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
menu->down_color((Fl_Color)SIMPLE_API_GETNUMBER(2));
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(menu_find_menu_item)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISSTRING(2) ) {
Fl_Menu_ *menu = (Fl_Menu_* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
Fl_Menu_Item *menu_item = (Fl_Menu_Item*)menu->find_item(SIMPLE_API_GETSTRING(2)) ;
SIMPLE_API_RETCPOINTER(menu_item,"SIMPLE_FLTK_");
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(menu_global)
{
if ( SIMPLE_API_PARACOUNT != 1 ) {
SIMPLE_API_ERROR(FULLTICK_MISING1PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) ) {
Fl_Menu_ *menu = (Fl_Menu_* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
menu->global();
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(menu_insert)
{
if ( SIMPLE_API_PARACOUNT != 3 ) {
SIMPLE_API_ERROR(FULLTICK_MISING3PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) && SIMPLE_API_ISSTRING(3)) {
Fl_Menu_ *menu = (Fl_Menu_* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
menu->insert((int)SIMPLE_API_GETNUMBER(2),SIMPLE_API_GETSTRING(3),0,0);
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(menu_selected_menu_item_value)
{
if ( SIMPLE_API_PARACOUNT != 1 ) {
SIMPLE_API_ERROR(FULLTICK_MISING1PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) ) {
Fl_Menu_ *menu = (Fl_Menu_* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
char picked[80];
menu->item_pathname(picked, sizeof(picked)-1);
SIMPLE_API_RETSTRING(picked);
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(menu_mode)
{
if ( SIMPLE_API_PARACOUNT != 3 ) {
SIMPLE_API_ERROR(FULLTICK_MISING1PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) && SIMPLE_API_ISNUMBER(3)) {
Fl_Menu_ *menu = (Fl_Menu_* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
if (((int)SIMPLE_API_GETNUMBER(3)) == -101) {
SIMPLE_API_RETNUMBER(menu->mode(((int)SIMPLE_API_GETNUMBER(2))));
} else {
menu->mode(((int)SIMPLE_API_GETNUMBER(2)), (int) SIMPLE_API_GETNUMBER(3));
}
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(menu_last_selected_menu_item)
{
if ( SIMPLE_API_PARACOUNT != 1 ) {
SIMPLE_API_ERROR(FULLTICK_MISING1PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) ) {
Fl_Menu_ *menu = (Fl_Menu_* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
SIMPLE_API_RETCPOINTER((Fl_Menu_Item*)menu->mvalue(),"SIMPLE_FLTK_");
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(menu_remove)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Menu_ *menu = (Fl_Menu_* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
menu->remove((int)SIMPLE_API_GETNUMBER(2));
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(menu_replace)
{
if ( SIMPLE_API_PARACOUNT != 3 ) {
SIMPLE_API_ERROR(FULLTICK_MISING3PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) && SIMPLE_API_ISSTRING(3)) {
Fl_Menu_ *menu = (Fl_Menu_* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
menu->replace((int)SIMPLE_API_GETNUMBER(2),SIMPLE_API_GETSTRING(3));
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(menu_setonly)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISPOINTER(2) ) {
Fl_Menu_ *menu = (Fl_Menu_* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
Fl_Menu_Item *menuitem = (Fl_Menu_Item* ) SIMPLE_API_GETCPOINTER(2,"SIMPLE_FLTK_");
menu->setonly(menuitem);
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(menu_shortcut)
{
if ( SIMPLE_API_PARACOUNT != 3 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) && SIMPLE_API_ISNUMBER(3)) {
Fl_Menu_ *menu = (Fl_Menu_* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
menu->shortcut((int)SIMPLE_API_GETNUMBER(2),(int)SIMPLE_API_GETNUMBER(3));
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(menu_size)
{
if ( SIMPLE_API_PARACOUNT != 1 ) {
SIMPLE_API_ERROR(FULLTICK_MISING1PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) ) {
Fl_Menu_ *menu = (Fl_Menu_* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
SIMPLE_API_RETNUMBER(menu->size());
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(menu_text)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Menu_ *menu = (Fl_Menu_* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
if (((int)SIMPLE_API_GETNUMBER(2)) == -101) {
SIMPLE_API_RETSTRING(menu->text());
} else {
SIMPLE_API_RETSTRING(menu->text((int)SIMPLE_API_GETNUMBER(2)));
}
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(menu_text_color)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Menu_ *menu = (Fl_Menu_* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
menu->textcolor(((Fl_Color) SIMPLE_API_GETNUMBER(2)));
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(menu_text_font)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Menu_ *menu = (Fl_Menu_* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
menu->textfont((Fl_Font)SIMPLE_API_GETNUMBER(2));
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(menu_text_size)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Menu_ *menu = (Fl_Menu_* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
menu->textsize((int)SIMPLE_API_GETNUMBER(2));
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(menu_value)
{
if ( SIMPLE_API_PARACOUNT != 3 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Menu_ *menu = (Fl_Menu_* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
if ((int)SIMPLE_API_GETNUMBER(2)==-1) {
SIMPLE_API_RETNUMBER(menu->value());
} else if ((int)SIMPLE_API_GETNUMBER(2)==-101) {
SIMPLE_API_RETNUMBER(menu->value(((Fl_Menu_Item* ) SIMPLE_API_GETCPOINTER(3,"SIMPLE_FLTK_"))));
} else {
SIMPLE_API_RETNUMBER(menu->value((int)SIMPLE_API_GETNUMBER(2)));
}
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
/** FMENUITEM **/
SIMPLE_BLOCK(menu_item_callback)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISCPOINTER(1) ) {
Fl_Menu_Item *menuitem = (Fl_Menu_Item* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
String * str = simple_string_new_gc(((VM *) pointer)->sState,SIMPLE_API_GETSTRING(2));
CallbackStruct *cbs = new CallbackStruct(pointer, str, (Fl_Widget*) menuitem);
menuitem->callback(SimpleCallBack,cbs);
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
/** BROWSERS(LISTBOX) **/
SIMPLE_BLOCK(listbox_type)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Browser *widget = (Fl_Browser* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
widget->type((int)SIMPLE_API_GETNUMBER(2));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(listbox_value)
{
if ( SIMPLE_API_PARACOUNT != 3 ) {
SIMPLE_API_ERROR(FULLTICK_MISING3PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Browser *widget = (Fl_Browser* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
if ((int)SIMPLE_API_GETNUMBER(2) == 1) {
widget->value((int)SIMPLE_API_GETNUMBER(3) + 1);
} else {
SIMPLE_API_RETNUMBER(widget->value() - 1);
}
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(listbox_text)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Browser *widget = (Fl_Browser* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
if (widget->text((int)SIMPLE_API_GETNUMBER(2) + 1)==NULL){
SIMPLE_API_RETSTRING("");
} else {
SIMPLE_API_RETSTRING(widget->text((int)SIMPLE_API_GETNUMBER(2) + 1));
}
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
/** FILEBROWSER **/
SIMPLE_BLOCK(init_file_listbox)
{
if ( SIMPLE_API_PARACOUNT != 4 ) {
SIMPLE_API_ERROR(FULLTICK_MISING4PARAM);
return ;
}
if ( SIMPLE_API_ISNUMBER(1) && SIMPLE_API_ISNUMBER(2) && SIMPLE_API_ISNUMBER(3) && SIMPLE_API_ISNUMBER(4)) {
Fl_File_Browser *widget = new Fl_File_Browser((int)SIMPLE_API_GETNUMBER(1),(int)SIMPLE_API_GETNUMBER(2),(int)SIMPLE_API_GETNUMBER(3),(int)SIMPLE_API_GETNUMBER(4));
SIMPLE_API_RETCPOINTER(widget,"SIMPLE_FLTK_");
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(file_listbox_load)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISSTRING(2) ) {
Fl_File_Browser *widget = (Fl_File_Browser* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
widget->load(SIMPLE_API_GETSTRING(2));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(file_listbox_file_type)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_File_Browser *widget = (Fl_File_Browser* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
widget->filetype((int)SIMPLE_API_GETNUMBER(2));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(file_listbox_filter)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISSTRING(2) ) {
Fl_File_Browser *widget = (Fl_File_Browser* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
widget->filter(SIMPLE_API_GETSTRING(2));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(file_listbox_icon_size)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_File_Browser *widget = (Fl_File_Browser* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
widget->iconsize((uchar)(int)SIMPLE_API_GETNUMBER(2));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
/** FILECHOOSER**/
SIMPLE_BLOCK(init_file_chooser)
{
if ( SIMPLE_API_PARACOUNT != 4 ) {
SIMPLE_API_ERROR(FULLTICK_MISING4PARAM);
return ;
}
if ( SIMPLE_API_ISSTRING(1) && SIMPLE_API_ISSTRING(2) && SIMPLE_API_ISNUMBER(3) && SIMPLE_API_ISSTRING(4)) {
Fl_File_Chooser *widget = new Fl_File_Chooser(SIMPLE_API_GETSTRING(1),SIMPLE_API_GETSTRING(2),(int)SIMPLE_API_GETNUMBER(3),simple_string_new_gc(((VM*)pointer)->sState,SIMPLE_API_GETSTRING(4))->str);
SIMPLE_API_RETCPOINTER(widget,"SIMPLE_FLTK_");
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(show_file_chooser)
{
if ( SIMPLE_API_PARACOUNT != 1 ) {
SIMPLE_API_ERROR(FULLTICK_MISING1PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1)) {
Fl_File_Chooser *widget = (Fl_File_Chooser* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
widget->show(); Fl::wait();
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(file_chooser_color)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_File_Chooser *widget = (Fl_File_Chooser* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
widget->textcolor(((Fl_Color) SIMPLE_API_GETNUMBER(2)));
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(file_chooser_count)
{
if ( SIMPLE_API_PARACOUNT != 1 ) {
SIMPLE_API_ERROR(FULLTICK_MISING1PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) ) {
Fl_File_Chooser *widget = (Fl_File_Chooser* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
SIMPLE_API_RETNUMBER(widget->count());
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(file_chooser_directory)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISSTRING(2) ) {
Fl_File_Chooser *widget = (Fl_File_Chooser* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
widget->directory(SIMPLE_API_GETSTRING(2));
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(file_chooser_filter)
{
if ( SIMPLE_API_PARACOUNT != 3 ) {
SIMPLE_API_ERROR(FULLTICK_MISING3PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) && SIMPLE_API_ISSTRING(3) ) {
Fl_File_Chooser *widget = (Fl_File_Chooser* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
if ((int)SIMPLE_API_GETNUMBER(2) == -1) {
SIMPLE_API_RETNUMBER(widget->filter_value());
} else if ((int)SIMPLE_API_GETNUMBER(2) == -2){
widget->filter(SIMPLE_API_GETSTRING(3));
} else {
widget->filter_value((int)SIMPLE_API_GETNUMBER(2));
}
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(hide_file_chooser)
{
if ( SIMPLE_API_PARACOUNT != 1 ) {
SIMPLE_API_ERROR(FULLTICK_MISING1PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) ) {
Fl_File_Chooser *widget = (Fl_File_Chooser* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
widget->hide();
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(file_chooser_iconsize)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_File_Chooser *widget = (Fl_File_Chooser* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
widget->iconsize((uchar)SIMPLE_API_GETNUMBER(2));
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(file_chooser_label)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISSTRING(2) ) {
Fl_File_Chooser *widget = (Fl_File_Chooser* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
widget->label(simple_string_new_gc(((VM*)pointer)->sState,SIMPLE_API_GETSTRING(2))->str);
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(file_chooser_ok_label)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISSTRING(2) ) {
Fl_File_Chooser *widget = (Fl_File_Chooser* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
widget->ok_label(simple_string_new_gc(((VM*)pointer)->sState,SIMPLE_API_GETSTRING(2))->str);
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(file_chooser_preview)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_File_Chooser *widget = (Fl_File_Chooser* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
widget->preview((int)SIMPLE_API_GETNUMBER(2));
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(file_chooser_rescan)
{
if ( SIMPLE_API_PARACOUNT != 1 ) {
SIMPLE_API_ERROR(FULLTICK_MISING1PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) ) {
Fl_File_Chooser *widget = (Fl_File_Chooser* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
widget->rescan();
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(file_chooser_is_shown)
{
if ( SIMPLE_API_PARACOUNT != 1 ) {
SIMPLE_API_ERROR(FULLTICK_MISING1PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) ) {
Fl_File_Chooser *widget = (Fl_File_Chooser* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
SIMPLE_API_RETNUMBER(widget->shown());
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(file_chooser_wait)
{
if ( SIMPLE_API_PARACOUNT != 1 ) {
SIMPLE_API_ERROR(FULLTICK_MISING1PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) ) {
Fl_File_Chooser *widget = (Fl_File_Chooser* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
while(widget->shown()){ Fl::wait(); }
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(file_chooser_value)
{
if ( SIMPLE_API_PARACOUNT != 3 ) {
SIMPLE_API_ERROR(FULLTICK_MISING3PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2)) {
Fl_File_Chooser *widget = (Fl_File_Chooser* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
if ((int)SIMPLE_API_GETNUMBER(2)==1) {
widget->value(SIMPLE_API_GETSTRING(3));
} else {
if (widget->value()==NULL){
SIMPLE_API_RETSTRING("");
} else {
SIMPLE_API_RETSTRING(widget->value());
}
}
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(file_chooser_get_directory)
{
if ( SIMPLE_API_PARACOUNT != 1 ) {
SIMPLE_API_ERROR(FULLTICK_MISING1PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) ) {
Fl_File_Chooser *widget = (Fl_File_Chooser* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
SIMPLE_API_RETSTRING(widget->directory());
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
/* FTEXTDISPLAY */
SIMPLE_BLOCK(init_text_display)
{
if ( SIMPLE_API_PARACOUNT != 4 ) {
SIMPLE_API_ERROR(FULLTICK_MISING4PARAM);
return ;
}
if ( SIMPLE_API_ISNUMBER(1) && SIMPLE_API_ISNUMBER(2) && SIMPLE_API_ISNUMBER(3) && SIMPLE_API_ISNUMBER(4)) {
Fl_Text_Display *widget = new Fl_Text_Display((int)SIMPLE_API_GETNUMBER(1),(int)SIMPLE_API_GETNUMBER(2),(int)SIMPLE_API_GETNUMBER(3),(int)SIMPLE_API_GETNUMBER(4));
SIMPLE_API_RETCPOINTER(widget,"SIMPLE_FLTK_");
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(text_display_buffer)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISPOINTER(2) ) {
Fl_Text_Display *widget = (Fl_Text_Display* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
widget->buffer((Fl_Text_Buffer*)SIMPLE_API_GETCPOINTER(2,"SIMPLE_FLTK_"));
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(text_display_column_to_x)
{
if ( SIMPLE_API_PARACOUNT != 3 ) {
SIMPLE_API_ERROR(FULLTICK_MISING3PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) && SIMPLE_API_ISNUMBER(3)) {
Fl_Text_Display *widget = (Fl_Text_Display* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
if ((int)SIMPLE_API_GETNUMBER(2)==1) {
SIMPLE_API_RETNUMBER(widget->col_to_x(SIMPLE_API_GETNUMBER(3)));
} else {
SIMPLE_API_RETNUMBER((int)widget->x_to_col(SIMPLE_API_GETNUMBER(3)));
}
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(text_display_count_lines)
{
if ( SIMPLE_API_PARACOUNT != 4 ) {
SIMPLE_API_ERROR(FULLTICK_MISING4PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) && SIMPLE_API_ISNUMBER(3) && SIMPLE_API_ISNUMBER(4)) {
Fl_Text_Display *widget = (Fl_Text_Display* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
bool condition = false ;
if ((int)SIMPLE_API_GETNUMBER(4)==1) {
condition = true ;
}
SIMPLE_API_RETNUMBER(widget->count_lines((int)SIMPLE_API_GETNUMBER(2),(int)SIMPLE_API_GETNUMBER(3),condition));
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(text_display_cursor_color)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Text_Display *widget = (Fl_Text_Display * ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
widget->cursor_color(((Fl_Color) SIMPLE_API_GETNUMBER(2)));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(text_display_cursor_style)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Text_Display *widget = (Fl_Text_Display * ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
widget->cursor_style(((int) SIMPLE_API_GETNUMBER(2)));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(text_display_cursor_visibility)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Text_Display *widget = (Fl_Text_Display * ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
if ((int)SIMPLE_API_GETNUMBER(2)==-1) {
widget->hide_cursor();
} else {
widget->show_cursor(((int)SIMPLE_API_GETNUMBER(2)));
}
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(text_display_in_selection)
{
if ( SIMPLE_API_PARACOUNT != 3 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) && SIMPLE_API_ISNUMBER(3)) {
Fl_Text_Display *widget = (Fl_Text_Display * ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
SIMPLE_API_RETNUMBER(widget->in_selection(((int)SIMPLE_API_GETNUMBER(2)),((int)SIMPLE_API_GETNUMBER(3))));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(text_display_insert)
{
if ( SIMPLE_API_PARACOUNT != 3 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) && SIMPLE_API_ISSTRING(3)) {
Fl_Text_Display *widget = (Fl_Text_Display * ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
if ((int)SIMPLE_API_GETNUMBER(2)==-1) {
widget->insert(SIMPLE_API_GETSTRING(3));
} else if ((int)SIMPLE_API_GETNUMBER(2)==-2) {
SIMPLE_API_RETNUMBER(widget->insert_position());
} else {
widget->insert_position((int)SIMPLE_API_GETNUMBER(2));
}
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(text_display_line_start_end)
{
if ( SIMPLE_API_PARACOUNT != 3 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) && SIMPLE_API_ISNUMBER(3)) {
Fl_Text_Display *widget = (Fl_Text_Display * ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
if ((int)SIMPLE_API_GETNUMBER(3)==-1) {
SIMPLE_API_RETNUMBER(widget->line_start((int)SIMPLE_API_GETNUMBER(2)));
} else {
bool condition = false ;
if ((int)SIMPLE_API_GETNUMBER(3)==1) {
condition = true ;
}
SIMPLE_API_RETNUMBER(widget->line_end((int)SIMPLE_API_GETNUMBER(2),condition));
}
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(text_display_line_number_align)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Text_Display *widget = (Fl_Text_Display * ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
widget->linenumber_align(((Fl_Align) ((int)SIMPLE_API_GETNUMBER(2))));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(text_display_line_number_bg_color)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Text_Display *widget = (Fl_Text_Display * ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
widget->linenumber_bgcolor(((Fl_Color) (int)SIMPLE_API_GETNUMBER(2)));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(text_display_line_number_fg_color)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Text_Display *widget = (Fl_Text_Display * ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
widget->linenumber_fgcolor(((Fl_Color) (int)SIMPLE_API_GETNUMBER(2)));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(text_display_line_number_font)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Text_Display *widget = (Fl_Text_Display * ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
widget->linenumber_font(((Fl_Font) (int)SIMPLE_API_GETNUMBER(2)));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(text_display_line_number_format)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISSTRING(2) ) {
Fl_Text_Display *widget = (Fl_Text_Display * ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
widget->linenumber_format(SIMPLE_API_GETSTRING(2));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(text_display_line_number_font_size)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Text_Display *widget = (Fl_Text_Display * ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
widget->linenumber_size(((Fl_Fontsize) (int)SIMPLE_API_GETNUMBER(2)));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(text_display_line_number_width)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Text_Display *widget = (Fl_Text_Display * ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
widget->linenumber_width(((int) SIMPLE_API_GETNUMBER(2)));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(text_display_move)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Text_Display *widget = (Fl_Text_Display * ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
if (((int) SIMPLE_API_GETNUMBER(2))==1) {
widget->move_down();
} else if (((int) SIMPLE_API_GETNUMBER(2))==2) {
widget->move_left();
} else if (((int) SIMPLE_API_GETNUMBER(2))==3) {
widget->move_right();
} else {
widget->move_up();
}
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(text_display_next_word)
{
if ( SIMPLE_API_PARACOUNT != 1 ) {
SIMPLE_API_ERROR(FULLTICK_MISING1PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) ) {
Fl_Text_Display *widget = (Fl_Text_Display * ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
widget->next_word();
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(text_display_overstrike)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISSTRING(2) ) {
Fl_Text_Display *widget = (Fl_Text_Display * ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
widget->overstrike(SIMPLE_API_GETSTRING(2));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(text_display_position_style)
{
if ( SIMPLE_API_PARACOUNT != 4 ) {
SIMPLE_API_ERROR(FULLTICK_MISING4PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) && SIMPLE_API_ISNUMBER(3) && SIMPLE_API_ISNUMBER(4) ) {
Fl_Text_Display *widget = (Fl_Text_Display * ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
SIMPLE_API_RETNUMBER(widget->position_style((int)SIMPLE_API_GETNUMBER(2),(int)SIMPLE_API_GETNUMBER(3),(int)SIMPLE_API_GETNUMBER(4)));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(text_display_position_to_xy)
{
if ( SIMPLE_API_PARACOUNT != 4 ) {
SIMPLE_API_ERROR(FULLTICK_MISING4PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) && SIMPLE_API_ISNUMBER(3) && SIMPLE_API_ISNUMBER(4) ) {
Fl_Text_Display *widget = (Fl_Text_Display * ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
int *x = 0 ; x += + (int)SIMPLE_API_GETNUMBER(3) ;
int *y = 0 ; y += + (int)SIMPLE_API_GETNUMBER(4) ;
SIMPLE_API_RETNUMBER(widget->position_to_xy((int)SIMPLE_API_GETNUMBER(2),x,y));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(text_display_previous_word)
{
if ( SIMPLE_API_PARACOUNT != 1 ) {
SIMPLE_API_ERROR(FULLTICK_MISING1PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) ) {
Fl_Text_Display *widget = (Fl_Text_Display * ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
widget->previous_word();
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(text_display_redisplay_range)
{
if ( SIMPLE_API_PARACOUNT != 3 ) {
SIMPLE_API_ERROR(FULLTICK_MISING3PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) && SIMPLE_API_ISNUMBER(3) ) {
Fl_Text_Display *widget = (Fl_Text_Display * ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
widget->redisplay_range((int)SIMPLE_API_GETNUMBER(2),(int)SIMPLE_API_GETNUMBER(3));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(text_display_rewind_lines)
{
if ( SIMPLE_API_PARACOUNT != 3 ) {
SIMPLE_API_ERROR(FULLTICK_MISING3PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) && SIMPLE_API_ISNUMBER(3) ) {
Fl_Text_Display *widget = (Fl_Text_Display * ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
widget->rewind_lines((int)SIMPLE_API_GETNUMBER(2),(int)SIMPLE_API_GETNUMBER(3));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(text_display_scroll)
{
if ( SIMPLE_API_PARACOUNT != 3 ) {
SIMPLE_API_ERROR(FULLTICK_MISING3PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) && SIMPLE_API_ISNUMBER(3) ) {
Fl_Text_Display *widget = (Fl_Text_Display * ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
widget->scroll((int)SIMPLE_API_GETNUMBER(2),(int)SIMPLE_API_GETNUMBER(3));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(text_display_scroll_bar_align)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Text_Display *widget = (Fl_Text_Display * ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
widget->scrollbar_align(((Fl_Align) ((int)SIMPLE_API_GETNUMBER(2))));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(text_display_scroll_bar_width)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Text_Display *widget = (Fl_Text_Display * ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
widget->scrollbar_width((int)SIMPLE_API_GETNUMBER(2));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(text_display_show_insert_position)
{
if ( SIMPLE_API_PARACOUNT != 1 ) {
SIMPLE_API_ERROR(FULLTICK_MISING1PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) ) {
Fl_Text_Display *widget = (Fl_Text_Display * ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
widget->show_insert_position();
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(text_display_skip_lines)
{
if ( SIMPLE_API_PARACOUNT != 4 ) {
SIMPLE_API_ERROR(FULLTICK_MISING4PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) && SIMPLE_API_ISNUMBER(3) && SIMPLE_API_ISNUMBER(4)) {
Fl_Text_Display *widget = (Fl_Text_Display * ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
bool condition = false ;
if ((int)SIMPLE_API_GETNUMBER(4)==1) {
condition = true ;
}
SIMPLE_API_RETNUMBER(widget->skip_lines((int)SIMPLE_API_GETNUMBER(2),(int)SIMPLE_API_GETNUMBER(3),condition));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(text_display_text_color)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Text_Display *widget = (Fl_Text_Display * ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
widget->textcolor(((Fl_Color) (int)SIMPLE_API_GETNUMBER(2)));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(text_display_text_font)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Text_Display *widget = (Fl_Text_Display * ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
widget->textfont(((Fl_Font) SIMPLE_API_GETNUMBER(2)));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(text_display_text_font_size)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Text_Display *widget = (Fl_Text_Display * ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
widget->textsize(((Fl_Fontsize) SIMPLE_API_GETNUMBER(2)));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(text_display_word_end)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Text_Display *widget = (Fl_Text_Display * ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
SIMPLE_API_RETNUMBER(widget->word_end(((int) SIMPLE_API_GETNUMBER(2))));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(text_display_word_start)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Text_Display *widget = (Fl_Text_Display * ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
SIMPLE_API_RETNUMBER(widget->word_start(((int) SIMPLE_API_GETNUMBER(2))));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(text_display_wrap_mode)
{
if ( SIMPLE_API_PARACOUNT != 3 ) {
SIMPLE_API_ERROR(FULLTICK_MISING3PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) && SIMPLE_API_ISNUMBER(3) ) {
Fl_Text_Display *widget = (Fl_Text_Display * ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
widget->wrap_mode((int) SIMPLE_API_GETNUMBER(2),(int) SIMPLE_API_GETNUMBER(3));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(text_display_wrapped_column)
{
if ( SIMPLE_API_PARACOUNT != 3 ) {
SIMPLE_API_ERROR(FULLTICK_MISING3PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) && SIMPLE_API_ISNUMBER(3) ) {
Fl_Text_Display *widget = (Fl_Text_Display * ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
SIMPLE_API_RETNUMBER(widget->wrapped_column((int) SIMPLE_API_GETNUMBER(2),(int) SIMPLE_API_GETNUMBER(3)));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
SIMPLE_BLOCK(text_display_wrapped_row)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Text_Display *widget = (Fl_Text_Display * ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
SIMPLE_API_RETNUMBER(widget->wrapped_row((int) SIMPLE_API_GETNUMBER(2)));
} else {
SIMPLE_API_ERROR(FULLTICK_WRONGPARAM);
}
}
/* FTEXTEDITOR */
SIMPLE_BLOCK(init_text_editor)
{
if ( SIMPLE_API_PARACOUNT != 4 ) {
SIMPLE_API_ERROR(FULLTICK_MISING4PARAM);
return ;
}
if ( SIMPLE_API_ISNUMBER(1) && SIMPLE_API_ISNUMBER(2) && SIMPLE_API_ISNUMBER(3) && SIMPLE_API_ISNUMBER(4)) {
Fl_Text_Editor *widget = new Fl_Text_Editor((int)SIMPLE_API_GETNUMBER(1),(int)SIMPLE_API_GETNUMBER(2),(int)SIMPLE_API_GETNUMBER(3),(int)SIMPLE_API_GETNUMBER(4));
SIMPLE_API_RETCPOINTER(widget,"SIMPLE_FLTK_");
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
/* FTEXTBUFFER */
SIMPLE_BLOCK(init_text_buffer)
{
if ( SIMPLE_API_PARACOUNT != 0 ) {
SIMPLE_API_ERROR(FULLTICK_MISING4PARAM);
return ;
}
Fl_Text_Buffer *buff = new Fl_Text_Buffer();
SIMPLE_API_RETCPOINTER(buff,"SIMPLE_FLTK_");
}
SIMPLE_BLOCK(text_buffer_text)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISSTRING(2) ) {
Fl_Text_Buffer *buffer = (Fl_Text_Buffer* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
buffer->text(SIMPLE_API_GETSTRING(2));
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
/* FVALUATOR */
SIMPLE_BLOCK(valuator_bound)
{
if ( SIMPLE_API_PARACOUNT != 3 ) {
SIMPLE_API_ERROR(FULLTICK_MISING3PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) && SIMPLE_API_ISNUMBER(3)) {
Fl_Valuator *valuator = (Fl_Valuator* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
valuator->bounds((double)SIMPLE_API_GETNUMBER(2),(double)SIMPLE_API_GETNUMBER(3));
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(valuator_clamp)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Valuator *valuator = (Fl_Valuator* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
valuator->clamp((double)SIMPLE_API_GETNUMBER(2));
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
/* FADJUSTER */
SIMPLE_BLOCK(init_adjuster)
{
if ( SIMPLE_API_PARACOUNT != 4 ) {
SIMPLE_API_ERROR(FULLTICK_MISING4PARAM);
return ;
}
if ( SIMPLE_API_ISNUMBER(1) && SIMPLE_API_ISNUMBER(2) && SIMPLE_API_ISNUMBER(3) && SIMPLE_API_ISNUMBER(4)) {
Fl_Adjuster *adjuster = new Fl_Adjuster((int)SIMPLE_API_GETNUMBER(1),(int)SIMPLE_API_GETNUMBER(2),(int)SIMPLE_API_GETNUMBER(3),(int)SIMPLE_API_GETNUMBER(4));
SIMPLE_API_RETCPOINTER(adjuster,"SIMPLE_FLTK_");
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_BLOCK(adjuster_soft)
{
if ( SIMPLE_API_PARACOUNT != 2 ) {
SIMPLE_API_ERROR(FULLTICK_MISING2PARAM);
return ;
}
if ( SIMPLE_API_ISPOINTER(1) && SIMPLE_API_ISNUMBER(2) ) {
Fl_Adjuster *adjuster = (Fl_Adjuster* ) SIMPLE_API_GETCPOINTER(1,"SIMPLE_FLTK_");
adjuster->soft((int) SIMPLE_API_GETNUMBER(2));
} else {
SIMPLE_API_ERROR(SIMPLE_API_BADPARATYPE);
}
}
SIMPLE_API void init_full_tick(SimpleState *sState)
{
register_block("__test_gui",test_gui);
/** FAPP **/
register_block("__run_fulltick",run_fulltick);
register_block("__set_scheme",set_scheme);
/** FWIDGETS **/
register_block("__resizable",resizable_object);
register_block("__set_bg",set_widget_background);
register_block("__set_label",set_label);
register_block("__get_label",get_label);
register_block("__set_label_color",set_label_color);
register_block("__set_label_size",set_label_size);
register_block("__set_label_type",set_label_type);
register_block("__set_label_font",set_label_font);
register_block("__set_size",set_size);
register_block("__set_position",set_position);
register_block("__set_tooltip",set_tooltip);
register_block("__set_visibility",set_visibility);
register_block("__on_click",on_click);
register_block("__add_widget",add_widget);
register_block("__activate_deactivate_widget",activate_deactivate_widget);
register_block("__redraw_widget",redraw_widget);
register_block("__redraw_widget_parent",redraw_widget_parent);
register_block("__get_parent_widget",get_parent_widget);
register_block("__widget_box",widget_box);
/** WINDOW **/
register_block("__init_window",init_window);
register_block("__show_window",show_window);
register_block("__full_screen",full_screen);
register_block("__window_border",window_border);
register_block("__set_window_icon",set_window_icon);
/** BOX/PANEL **/
register_block("__init_box",init_box);
register_block("__set_box_type",set_box_type);
/** GROUP **/
register_block("__init_group",init_group);
register_block("__group_begin",group_begin);
register_block("__group_children",group_children);
register_block("__group_clear",group_clear);
register_block("__group_clip_children",group_clip_children);
register_block("__group_end",group_end);
register_block("__group_find",group_find);
register_block("__group_focus",group_focus);
register_block("__group_init_sizes",group_init_sizes);
register_block("__group_insert",group_insert);
register_block("__group_remove",group_remove);
register_block("__group_resize",resizable_object);
/** LABEL **/
register_block("__set_size_with_label",set_size_with_label);
/** FBUTTON (s) **/
register_block("__init_button",init_button);
register_block("__init_return_button",init_return_button);
register_block("__init_repeat_button",init_repeat_button);
register_block("__init_light_button",init_light_button);
register_block("__init_round_button",init_round_button);
register_block("__init_check_button",init_check_button);
register_block("__init_toggle_button",init_toggle_button);
register_block("__set_button_down_box",set_button_down_box);
register_block("__set_button_down_color",set_button_down_color);
register_block("__set_button_only",set_button_only);
register_block("__set_button_shortcut",set_button_shortcut);
register_block("__set_button_value",set_button_value);
register_block("__get_button_value",get_button_value);
/** INPUT/FTEXT (s) **/
register_block("__init_input",init_input);
register_block("__init_float_input",init_float_input);
register_block("__init_int_input",init_int_input);
register_block("__init_secret_input",init_secret_input);
register_block("__init_multiline_input",init_multiline_input);
register_block("__input_copy",input_copy);
register_block("__input_cut",input_cut);
register_block("__set_input_cursor_color",set_input_cursor_color);
register_block("__get_input_index",get_input_index);
register_block("__input_insert",input_insert);
register_block("__input_mark",input_mark);
register_block("__input_maximum_size",input_maximum_size);
register_block("__input_position",input_position);
register_block("__input_read_only",input_read_only);
register_block("__input_replace",input_replace);
register_block("__input_shortcut",input_shortcut);
register_block("__input_size",input_size);
register_block("__input_static_value",input_static_value);
register_block("__input_tab_nav",input_tab_nav);
register_block("__input_text_color",input_text_color);
register_block("__input_text_font",input_text_font);
register_block("__input_text_size",input_text_size);
register_block("__input_value",input_value);
register_block("__input_undo",input_undo);
register_block("__input_wrap",input_wrap);
/** MENU/MENUBAR **/
register_block("__init_menu_bar",init_menu_bar);
register_block("__init_menu_button",init_menu_button);
register_block("__menu_add",menu_add);
register_block("__menu_clear",menu_clear);
register_block("__menu_down_box",menu_down_box);
register_block("__menu_selection_color",menu_selection_color);
register_block("__menu_find_menu_item",menu_find_menu_item);
register_block("__menu_global",menu_global);
register_block("__menu_insert",menu_insert);
register_block("__menu_selected_menu_item_value",menu_selected_menu_item_value);
register_block("__menu_mode",menu_mode);
register_block("__menu_last_selected_menu_item",menu_last_selected_menu_item);
register_block("__menu_remove",menu_remove);
register_block("__menu_replace",menu_replace);
register_block("__menu_setonly",menu_setonly);
register_block("__menu_shortcut",menu_shortcut);
register_block("__menu_size",menu_size);
register_block("__menu_text",menu_text);
register_block("__menu_text_color",menu_text_color);
register_block("__menu_text_font",menu_text_font);
register_block("__menu_text_size",menu_text_size);
register_block("__menu_value",menu_value);
/** MENUITEM **/
register_block("__menu_item_callback",menu_item_callback);
/** BROWSERS(LISTBOX) **/
register_block("__listbox_type",listbox_type);
register_block("__listbox_value",listbox_value);
register_block("__listbox_text",listbox_text);
/** FILEBROWSER **/
register_block("__init_file_listbox",init_file_listbox);
register_block("__file_listbox_load",file_listbox_load);
register_block("__file_listbox_file_type",file_listbox_file_type);
register_block("__file_listbox_filter",file_listbox_filter);
register_block("__file_listbox_icon_size",file_listbox_icon_size);
/** FILECHOOSER **/
register_block("__init_file_chooser",init_file_chooser);
register_block("__show_file_chooser",show_file_chooser);
register_block("__file_chooser_color",file_chooser_color);
register_block("__file_chooser_count",file_chooser_count);
register_block("__file_chooser_directory",file_chooser_directory);
register_block("__file_chooser_filter",file_chooser_filter);
register_block("__hide_file_chooser",hide_file_chooser);
register_block("__file_chooser_iconsize",file_chooser_iconsize);
register_block("__file_chooser_label",file_chooser_label);
register_block("__file_chooser_ok_label",file_chooser_ok_label);
register_block("__file_chooser_preview",file_chooser_preview);
register_block("__file_chooser_rescan",file_chooser_rescan);
register_block("__file_chooser_is_shown",file_chooser_is_shown);
register_block("__file_chooser_wait",file_chooser_wait);
register_block("__file_chooser_value",file_chooser_value);
register_block("__file_chooser_get_directory",file_chooser_get_directory);
/** FTEXTDISPLAY **/
register_block("__init_text_display",init_text_display);
register_block("__text_display_buffer",text_display_buffer);
register_block("__text_display_scroll_bar_width",text_display_scroll_bar_width);
register_block("__text_display_column_to_x",text_display_column_to_x);
register_block("__text_display_count_lines",text_display_count_lines);
register_block("__text_display_cursor_color",text_display_cursor_color);
register_block("__text_display_cursor_style",text_display_cursor_style);
register_block("__text_display_cursor_visibility",text_display_cursor_visibility);
register_block("__text_display_in_selection",text_display_in_selection);
register_block("__text_display_insert",text_display_insert);
register_block("__text_display_line_start_end",text_display_line_start_end);
register_block("__text_display_line_number_width",text_display_line_number_width);
register_block("__text_display_line_number_align",text_display_line_number_align);
register_block("__text_display_line_number_bg_color",text_display_line_number_bg_color);
register_block("__text_display_line_number_fg_color",text_display_line_number_fg_color);
register_block("__text_display_line_number_font",text_display_line_number_font);
register_block("__text_display_line_number_format",text_display_line_number_format);
register_block("__text_display_line_number_font_size",text_display_line_number_font_size);
register_block("__text_display_move",text_display_move);
register_block("__text_display_next_word",text_display_next_word);
register_block("__text_display_overstrike",text_display_overstrike);
register_block("__text_display_position_style",text_display_position_style);
register_block("__text_display_position_to_xy",text_display_position_to_xy);
register_block("__text_display_previous_word",text_display_previous_word);
register_block("__text_display_redisplay_range",text_display_redisplay_range);
//before this
register_block("__text_display_text_color",text_display_text_color);
/** FTEXTEDITOR **/
register_block("__init_text_editor",init_text_editor);
/** FTEXTBUFFER **/
register_block("__init_text_buffer",init_text_buffer);
register_block("__text_buffer_text",text_buffer_text);
/** FVALUATOR **/
register_block("__valuator_bound",valuator_bound);
register_block("__valuator_clamp",valuator_clamp);
/** FADJUSTER **/
register_block("__init_adjuster",init_adjuster);
register_block("__adjuster_soft",adjuster_soft);
} | 30.029515 | 200 | 0.746934 | [
"object"
] |
ed479a80ad8ea2fb07f572382f1d2fd26d8e1331 | 5,281 | cpp | C++ | src/ReadGraph.cpp | ekg/shasta | e2fd3c3d79fb4cafe77c62f6af2fef46f7a04b01 | [
"BSD-3-Clause"
] | null | null | null | src/ReadGraph.cpp | ekg/shasta | e2fd3c3d79fb4cafe77c62f6af2fef46f7a04b01 | [
"BSD-3-Clause"
] | null | null | null | src/ReadGraph.cpp | ekg/shasta | e2fd3c3d79fb4cafe77c62f6af2fef46f7a04b01 | [
"BSD-3-Clause"
] | null | null | null | // Shasta.
#include "ReadGraph.hpp"
using namespace ChanZuckerberg;
using namespace shasta;
// Boost libraries.
#include <boost/graph/graphviz.hpp>
// Standard library.
#include "fstream.hpp"
#include <queue>
const uint32_t ReadGraph::infiniteDistance = std::numeric_limits<uint32_t>::max();
void RawReadGraph::Visitor::examine_edge(edge_descriptor e, const RawReadGraph& constGraph)
{
RawReadGraph& graph = const_cast<RawReadGraph&>(constGraph);
const vertex_descriptor v0 = source(e, graph);
const vertex_descriptor v1 = target(e, graph);
const bool isSameStrand = graph[e].isSameStrand;
const uint8_t strand0 = graph[v0].strand;
CZI_ASSERT(strand0 != undiscovered);
const uint8_t strand1 = isSameStrand ? strand0 : ((~strand0) & 1);
if(graph[v1].strand == undiscovered) {
graph[v1].strand = strand1;
} else {
if(graph[v1].strand != strand1) {
crossStrandEdges.push_back(e);
// cout << "Edge " << v0 << " " << v1 << " " << int(isSameStrand) <<
// " marked as cross-strand." << endl;
}
}
}
// Write the graph in Graphviz format.
void RawReadGraph::write(const string& fileName) const
{
ofstream outputFileStream(fileName);
if(!outputFileStream) {
throw runtime_error("Error opening " + fileName);
}
write(outputFileStream);
}
void RawReadGraph::write(ostream& s) const
{
Writer writer(*this);
boost::write_graphviz(s, *this, writer, writer, writer);
}
RawReadGraph::Writer::Writer(const RawReadGraph& graph) :
graph(graph)
{
}
void RawReadGraph::Writer::operator()(std::ostream& s) const
{
s << "layout=sfdp;\n";
s << "ratio=expand;\n";
}
void RawReadGraph::Writer::operator()(std::ostream& s, vertex_descriptor v) const
{
}
void RawReadGraph::Writer::operator()(std::ostream& s, edge_descriptor e) const
{
const vertex_descriptor v0 = source(e, graph);
const vertex_descriptor v1 = target(e, graph);
if(graph[e].isSameStrand != (graph[v0].strand==graph[v1].strand)) {
s << "[color=red]";
}
}
// Compute a shortest path, disregarding edges flagged as cross-strand edges.
void ReadGraph::computeShortPath(
OrientedReadId orientedReadId0,
OrientedReadId orientedReadId1,
size_t maxDistance,
// Edge ids of the shortest path starting at orientedReadId0 and
// ending at orientedReadId1.
vector<uint32_t>& path,
// Work areas.
vector<uint32_t>& distance, // One per vertex, equals infiniteDistance before and after.
vector<OrientedReadId>& reachedVertices, // For which distance is not infiniteDistance.
vector<uint32_t>& parentEdges // One per vertex
)
{
const bool debug = false;
if(debug) {
cout << "Looking for a shortest path between " << orientedReadId0 <<
" " << orientedReadId1 << endl;
}
path.clear();
// Initialize the BFS.
std::queue<OrientedReadId> queuedVertices;
queuedVertices.push(orientedReadId0);
distance[orientedReadId0.getValue()] = 0;
reachedVertices.clear();
reachedVertices.push_back(orientedReadId0);
// Do the BFS.
while(!queuedVertices.empty()) {
// Dequeue a vertex.
const OrientedReadId vertex0 = queuedVertices.front();
queuedVertices.pop();
const uint32_t distance0 = distance[vertex0.getValue()];
const uint32_t distance1 = distance0 + 1;
if(debug) {
cout << "Dequeued " << vertex0 << " at distance " << distance0 << endl;
}
// Loop over adjacent vertices.
bool pathFound = false;
for(const uint32_t edgeId: connectivity[vertex0.getValue()]) {
const Edge& edge = edges[edgeId];
if(edge.crossesStrands) {
continue;
}
const OrientedReadId vertex1 = edge.getOther(vertex0);
// If we did not encounter this vertex before, process it.
if(distance[vertex1.getValue()] == infiniteDistance) {
distance[vertex1.getValue()] = distance1;
reachedVertices.push_back(vertex1);
parentEdges[vertex1.getValue()] = edgeId;
if(distance1 < maxDistance) {
if(debug) {
cout << "Enqueued " << vertex1 << endl;
}
queuedVertices.push(vertex1);
}
}
// If we reached orientedReadId1, construct the path.
if(vertex1 == orientedReadId1) {
pathFound = true;
// We have already cleared the path above.
OrientedReadId vertex = vertex1;
while(vertex != orientedReadId0) {
const uint32_t edgeId = parentEdges[vertex.getValue()];
path.push_back(edgeId);
vertex = edges[edgeId].getOther(vertex);
}
std::reverse(path.begin(), path.end());
break;
}
}
if(pathFound) {
break;
}
}
// Clean up.
for(const OrientedReadId orientedReadId: reachedVertices) {
distance[orientedReadId.getValue()] = infiniteDistance;
}
reachedVertices.clear();
}
| 28.857923 | 93 | 0.607461 | [
"vector"
] |
ed484e5611034fc7514260a7b58c59a5c89a59a7 | 2,312 | cpp | C++ | src/pyhookv.cpp | philkr/pyhookv | 05fb5b718adad32565e42d6f5c4ec769cd096b64 | [
"BSD-2-Clause"
] | 8 | 2018-06-26T02:38:37.000Z | 2021-08-02T06:41:36.000Z | src/pyhookv.cpp | philkr/pyhookv | 05fb5b718adad32565e42d6f5c4ec769cd096b64 | [
"BSD-2-Clause"
] | null | null | null | src/pyhookv.cpp | philkr/pyhookv | 05fb5b718adad32565e42d6f5c4ec769cd096b64 | [
"BSD-2-Clause"
] | 4 | 2018-07-19T06:57:08.000Z | 2021-11-03T15:55:57.000Z | #define NOMINMAX
#define _CRT_SECURE_NO_WARNINGS
#include <windows.h>
#include "scripthook\main.h"
#include "scripthook\enums.h"
#include "scripthook\natives.h"
#include "pybind11/pybind11.h"
#include "pybind11/embed.h"
#include "pybind11/stl.h"
namespace py = pybind11;
void defEnums(py::module m);
void defNatives(py::module m);
py::function main_cb;
static bool running = 1;
static void scriptMain() {
while (running) {
if (main_cb) {
try {
py::gil_scoped_acquire acquire;
main_cb();
}
catch (...) {
}
}
WAIT(0);
}
TERMINATE();
}
PYBIND11_MODULE(pyhookv, m) {
m.doc() = "Python ScriptHookV interface";
defEnums(m);
defNatives(m);
m.def("main_cb", []() { return main_cb; });
m.def("set_main_cb", [](py::object f) { main_cb = f; });
m.def("wait", WAIT, py::call_guard<py::gil_scoped_release>());
{
class V {};
py::class_<V> egv(m, "game_version");
egv.def_property_readonly_static("Unknown", []() { return -1; });
egv.def_property_readonly_static("current", []() { return (int)getGameVersion(); });
const char * versions[] = { "v1_0_335_2_Steam","v1_0_335_2_NoSteam","v1_0_350_1_Steam","v1_0_350_2_NoSteam","v1_0_372_2_Steam","v1_0_372_2_NoSteam","v1_0_393_2_Steam","v1_0_393_2_NoSteam","v1_0_393_4_Steam","v1_0_393_4_NoSteam","v1_0_463_1_Steam","v1_0_463_1_NoSteam","v1_0_505_2_Steam","v1_0_505_2_NoSteam","v1_0_573_1_Steam","v1_0_573_1_NoSteam","v1_0_617_1_Steam","v1_0_617_1_NoSteam","v1_0_678_1_Steam","v1_0_678_1_NoSteam","v1_0_757_2_Steam","v1_0_757_2_NoSteam","v1_0_757_3_Steam","v1_0_757_4_NoSteam","v1_0_791_2_Steam","v1_0_791_2_NoSteam","v1_0_877_1_Steam","v1_0_877_1_NoSteam","v1_0_944_2_Steam","v1_0_944_2_NoSteam","v1_0_1011_1_Steam","v1_0_1011_1_NoSteam","v1_0_1032_1_Steam","v1_0_1032_1_NoSteam","v1_0_1103_2_Steam","v1_0_1103_2_NoSteam","v1_0_1180_2_Steam","v1_0_1180_2_NoSteam","v1_0_1290_1_Steam","v1_0_1290_1_NoSteam","v1_0_1365_1_Steam","v1_0_1365_1_NoSteam" };
for (int i = 0; i < sizeof(versions)/sizeof(*versions); i++)
egv.def_property_readonly_static(versions[i], [i]() { return i; });
}
}
BOOL WINAPI DllMain(HINSTANCE hInst, DWORD reason, LPVOID) {
if (reason == DLL_PROCESS_ATTACH) {
scriptRegister(hInst, scriptMain);
}
if (reason == DLL_PROCESS_DETACH) {
running = 0;
scriptUnregister(hInst);
}
return TRUE;
}
| 36.125 | 884 | 0.732699 | [
"object"
] |
ed56c75c6c6bd05b6690aa168e54a90d37b1610c | 1,042 | cpp | C++ | Algorithms/0265.Paint_House_II.cpp | metehkaya/LeetCode | 52f4a1497758c6f996d515ced151e8783ae4d4d2 | [
"MIT"
] | 2 | 2020-07-20T06:40:22.000Z | 2021-11-20T01:23:26.000Z | Problems/LeetCode/Problems/0265.Paint_House_II.cpp | metehkaya/Algo-Archive | 03b5fdcf06f84a03125c57762c36a4e03ca6e756 | [
"MIT"
] | null | null | null | Problems/LeetCode/Problems/0265.Paint_House_II.cpp | metehkaya/Algo-Archive | 03b5fdcf06f84a03125c57762c36a4e03ca6e756 | [
"MIT"
] | null | null | null | class Solution {
public:
int minCostII(vector<vector<int>>& ar) {
int n = ar.size();
if(n == 0)
return 0;
int k = ar[0].size();
int dp[n][k];
for( int i = 0 ; i < k ; i++ )
dp[0][i] = ar[0][i];
for( int i = 1 ; i < n ; i++ ) {
int best1 = 0 , best2 = -1;
for( int j = 1 ; j < k ; j++ ) {
if(dp[i-1][j] <= dp[i-1][best1]) {
best2 = best1;
best1 = j;
}
else if(best2 == -1 || dp[i-1][j] <= dp[i-1][best2])
best2 = j;
}
for( int j = 0 ; j < k ; j++ ) {
if(best1 != j)
dp[i][j] = dp[i-1][best1] + ar[i][j];
else
dp[i][j] = dp[i-1][best2] + ar[i][j];
}
}
int best = 0;
for( int i = 1 ; i < k ; i++ )
if(dp[n-1][i] < dp[n-1][best])
best = i;
return dp[n-1][best];
}
}; | 30.647059 | 68 | 0.304223 | [
"vector"
] |
ed5781f99ba25b9caf2401be0e381c07dfdfaaf0 | 9,177 | cpp | C++ | src/FeatureHandling/src/OrFastDetector.cpp | makra89/Visual-Odometry-Cpp | fc1cb8741430f6bf16185d8416eb421422e54ad5 | [
"BSD-3-Clause"
] | 7 | 2021-03-08T13:18:52.000Z | 2022-01-15T13:39:49.000Z | src/FeatureHandling/src/OrFastDetector.cpp | makra89/Visual-Odometry-Cpp | fc1cb8741430f6bf16185d8416eb421422e54ad5 | [
"BSD-3-Clause"
] | 17 | 2020-01-21T23:11:31.000Z | 2021-03-03T19:49:05.000Z | src/FeatureHandling/src/OrFastDetector.cpp | makra89/Visual-Odometry-Cpp | fc1cb8741430f6bf16185d8416eb421422e54ad5 | [
"BSD-3-Clause"
] | 3 | 2020-05-26T06:52:53.000Z | 2021-09-12T22:41:16.000Z | /* This file is part of the Visual-Odometry-Cpp project.
* It is subject to the license terms in the LICENSE file
* found in the top-level directory of this distribution.
*
* Copyright (C) 2020 Manuel Kraus
*/
#include <Vocpp_FeatureHandling/OrFastDetector.h>
#include <Vocpp_Utils/ImageProcessingUtils.h>
#include <Vocpp_Utils/TracingImpl.h>
#include<opencv2/imgproc/imgproc.hpp>
namespace VOCPP
{
namespace FeatureHandling
{
// The version of the FAST feature detector used here uses a ring of 16 pixels around the center pixel (radius = 3 --> diameter 7)
const uint32_t OrientedFastDetector::s_featureSize = 7U;
OrientedFastDetector::OrientedFastDetector(const double& in_intDiffTresh, const uint32_t& in_numPixelsAboveThresh,
const uint32_t& in_harrisBlockSize, const uint32_t& in_distToEdges) :
m_intDiffTresh(in_intDiffTresh),
m_numPixelsAboveThresh(in_numPixelsAboveThresh),
m_harrisBlockSize(in_harrisBlockSize),
m_distToEdges(in_distToEdges),
m_harrisDetector()
{
}
bool OrientedFastDetector::ExtractFeatures(const Frame& in_frame, const uint32_t& in_maxNumFeatures, std::vector<Feature>& out_features)
{
bool ret = true;
// Reserve memory for maximum number of features
out_features.reserve(in_maxNumFeatures);
if (in_frame.GetImage().dims != 2)
{
ret = false;
VOCPP_TRACE_ERROR("[OrientedFastDetector]: Non-grayscale image has been provided")
}
else
{
cv::Mat1d harrisScore = cv::Mat1d::zeros(in_frame.GetImage().rows, in_frame.GetImage().cols);
for (int32_t i = m_distToEdges; i < in_frame.GetImage().rows - static_cast<int32_t>(m_distToEdges); i++)
{
double* rowPtr = harrisScore.ptr<double>(i);
for (int32_t j = m_distToEdges; j < in_frame.GetImage().cols - static_cast<int32_t>(m_distToEdges); j++)
{
const int32_t score = CheckIntensities(in_frame.GetImage(), j, i, in_frame.GetImage().cols, in_frame.GetImage().rows);
if (score >= static_cast<int32_t>(m_numPixelsAboveThresh))
{
rowPtr[j] = m_harrisDetector.ComputeScore(in_frame.GetImage(), j, i, m_harrisBlockSize);
}
}
}
// Thin out neighbouring features, we use such a radius that features do not overlap
// with respect to the pixels checked by the FAST detector
std::vector<Utils::LocalMaximum> localMax;
localMax.reserve(in_maxNumFeatures);
Utils::ExtractLocalMaxima(harrisScore, (s_featureSize - 1), localMax);
// Sort according to feature response and throw away weakest features if we have more than we need
std::sort(localMax.begin(), localMax.end(), std::greater<Utils::LocalMaximum>());
if (localMax.size() > in_maxNumFeatures)
{
localMax.resize(in_maxNumFeatures);
}
// Calculate orientation for all surviving features
uint32_t featureId = 0U;
uint32_t maxId = 0U;
for (uint32_t idx = 0U; idx < localMax.size(); idx++)
{
cv::Mat1d patch = cv::Mat1d::zeros(s_featureSize, s_featureSize);
bool patchExtractSuccess = Utils::ExtractImagePatchAroundPixelPos(in_frame.GetImage(), patch, (s_featureSize - 1) / 2,
static_cast<int32_t>(localMax[idx].posX), static_cast<int32_t>(localMax[idx].posY));
// Calculate angle if successful and create feature
if (patchExtractSuccess)
{
cv::Moments patchMoments = cv::moments(patch);
const double centroidX = static_cast<double>(patchMoments.m10 / patchMoments.m00);
const double centroidY = static_cast<double>(patchMoments.m01 / patchMoments.m00);
const double vecX = centroidX - (s_featureSize - 1) / 2;
const double vecY = centroidY - (s_featureSize - 1) / 2;
double angle = static_cast<double>(std::atan2(vecY, vecX));
Feature feat = { featureId, in_frame.GetId(), localMax[idx].posX, localMax[idx].posY, localMax[idx].value, angle, static_cast<double>(s_featureSize) };
out_features.push_back(feat);
featureId++;
}
maxId++;
}
}
return ret;
}
int32_t OrientedFastDetector::CheckIntensities(const cv::Mat1d& in_image, const int32_t& in_coordX, const int32_t& in_coordY,
const int32_t& in_imgWidth, const int32_t& in_imgHeight)
{
int32_t ret = 0;
const double nucleusInt = in_image(in_coordY, in_coordX);
// Remove pixels with very small intensity
if (nucleusInt < (10.0F / 255.0F))
{
return 0;
}
// Remove pixels with very high intensity
if (nucleusInt > (250.0F / 255.0F))
{
return 0;
}
// Pixel 1
int32_t passLower = (in_image(in_coordY - 3, in_coordX) + m_intDiffTresh) < nucleusInt ? 1 : 0;
// Pixel 5
if ((in_image(in_coordY, in_coordX + 3) + m_intDiffTresh) < nucleusInt) passLower++;
// Pixel 9
if ((in_image(in_coordY + 3, in_coordX) + m_intDiffTresh) < nucleusInt) passLower++;
// Pixel 13
if ((in_image(in_coordY, in_coordX - 3) + m_intDiffTresh) < nucleusInt) passLower++;
if (passLower < 3)
{
int32_t passHigher = (in_image(in_coordY - 3, in_coordX) - m_intDiffTresh) > nucleusInt ? 1 : 0;
// Pixel 5
if ((in_image(in_coordY, in_coordX + 3) - m_intDiffTresh) > nucleusInt) passHigher++;
// Pixel 9
if ((in_image(in_coordY + 3, in_coordX) - m_intDiffTresh) > nucleusInt) passHigher++;
// Pixel 13
if ((in_image(in_coordY, in_coordX - 3) - m_intDiffTresh) > nucleusInt) passHigher++;
if (passHigher >= 3)
{
ret = CheckAll(in_image, in_coordX, in_coordY, 0, passHigher);
}
}
else
{
ret = CheckAll(in_image, in_coordX, in_coordY, passLower, 0);
}
return ret;
}
int32_t OrientedFastDetector::CheckAll(const cv::Mat1d& in_image, const int32_t& in_coordX, const int32_t& in_coordY, const int32_t& in_passLower, const int32_t& in_passHigher)
{
const double nucleusInt = in_image(in_coordY, in_coordX);
int32_t score = 0;
if (in_passLower > 0)
{
score = in_passLower;
// Pixel 2
if ((in_image(in_coordY - 3, in_coordX + 1) + m_intDiffTresh) < nucleusInt) score++;
// Pixel 3
if ((in_image(in_coordY - 2, in_coordX + 2) + m_intDiffTresh) < nucleusInt) score++;
// Pixel 4
if ((in_image(in_coordY - 1, in_coordX + 3) + m_intDiffTresh) < nucleusInt) score++;
// Pixel 6
if ((in_image(in_coordY + 1, in_coordX + 3) + m_intDiffTresh) < nucleusInt) score++;
// Pixel 7
if ((in_image(in_coordY + 2, in_coordX + 2) + m_intDiffTresh) < nucleusInt) score++;
// Pixel 8
if ((in_image(in_coordY + 3, in_coordX + 1) + m_intDiffTresh) < nucleusInt) score++;
// Pixel 10
if ((in_image(in_coordY + 3, in_coordX - 1) + m_intDiffTresh) < nucleusInt) score++;
// Pixel 11
if ((in_image(in_coordY + 2, in_coordX - 2) + m_intDiffTresh) < nucleusInt) score++;
// Pixel 12
if ((in_image(in_coordY + 1, in_coordX - 3) + m_intDiffTresh) < nucleusInt) score++;
// Pixel 14
if ((in_image(in_coordY - 1, in_coordX - 3) + m_intDiffTresh) < nucleusInt) score++;
// Pixel 15
if ((in_image(in_coordY - 2, in_coordX - 2) + m_intDiffTresh) < nucleusInt) score++;
// Pixel 16
if ((in_image(in_coordY - 3, in_coordX - 1) + m_intDiffTresh) < nucleusInt) score++;
}
else if(in_passHigher > 0)
{
score = in_passHigher;
// Pixel 2
if ((in_image(in_coordY - 3, in_coordX + 1) - m_intDiffTresh) > nucleusInt) score++;
// Pixel 3
if ((in_image(in_coordY - 2, in_coordX + 2) - m_intDiffTresh) > nucleusInt) score++;
// Pixel 4
if ((in_image(in_coordY - 1, in_coordX + 3) - m_intDiffTresh) > nucleusInt) score++;
// Pixel 6
if ((in_image(in_coordY + 1, in_coordX + 3) - m_intDiffTresh) > nucleusInt) score++;
// Pixel 7
if ((in_image(in_coordY + 2, in_coordX + 2) - m_intDiffTresh) > nucleusInt) score++;
// Pixel 8
if ((in_image(in_coordY + 3, in_coordX + 1) - m_intDiffTresh) > nucleusInt) score++;
// Pixel 10
if ((in_image(in_coordY + 3, in_coordX - 1) - m_intDiffTresh) > nucleusInt) score++;
// Pixel 11
if ((in_image(in_coordY + 2, in_coordX - 2) - m_intDiffTresh) > nucleusInt) score++;
// Pixel 12
if ((in_image(in_coordY + 1, in_coordX - 3) - m_intDiffTresh) > nucleusInt) score++;
// Pixel 14
if ((in_image(in_coordY - 1, in_coordX - 3) - m_intDiffTresh) > nucleusInt) score++;
// Pixel 15
if ((in_image(in_coordY - 2, in_coordX - 2) - m_intDiffTresh) > nucleusInt) score++;
// Pixel 16
if ((in_image(in_coordY - 3, in_coordX - 1) - m_intDiffTresh) > nucleusInt) score++;
}
return score;
}
} //namespace FeatureHandling
} //namespace VOCPP
| 41.90411 | 176 | 0.627547 | [
"vector"
] |
ed5d543a3a2568ac824fc9d8a110eccb9928e5e8 | 8,596 | cpp | C++ | src/Magnum/Shaders/Test/MeshVisualizerGL_Test.cpp | Anon1428/magnum | 384e148c24293f513df69e6c03f94a2d4a1e3b6a | [
"MIT"
] | 1 | 2022-03-02T19:44:27.000Z | 2022-03-02T19:44:27.000Z | src/Magnum/Shaders/Test/MeshVisualizerGL_Test.cpp | Anon1428/magnum | 384e148c24293f513df69e6c03f94a2d4a1e3b6a | [
"MIT"
] | null | null | null | src/Magnum/Shaders/Test/MeshVisualizerGL_Test.cpp | Anon1428/magnum | 384e148c24293f513df69e6c03f94a2d4a1e3b6a | [
"MIT"
] | null | null | null | /*
This file is part of Magnum.
Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019,
2020, 2021, 2022 Vladimír Vondruš <mosra@centrum.cz>
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <sstream>
#include <Corrade/TestSuite/Tester.h>
#include <Corrade/Utility/DebugStl.h>
#include "Magnum/Shaders/MeshVisualizerGL.h"
namespace Magnum { namespace Shaders { namespace Test { namespace {
/* There's an underscore between GL and Test to disambiguate from GLTest, which
is a common suffix used to mark tests that need a GL context. Ugly, I know. */
struct MeshVisualizerGL_Test: TestSuite::Tester {
explicit MeshVisualizerGL_Test();
void constructNoCreate2D();
void constructNoCreate3D();
void constructCopy2D();
void constructCopy3D();
void vertexIndexSameAsObjectId();
void debugFlag2D();
void debugFlag3D();
void debugFlags2D();
void debugFlags3D();
#ifndef MAGNUM_TARGET_GLES2
void debugFlagsSupersets2D();
void debugFlagsSupersets3D();
#endif
};
MeshVisualizerGL_Test::MeshVisualizerGL_Test() {
addTests({
&MeshVisualizerGL_Test::constructNoCreate2D,
&MeshVisualizerGL_Test::constructNoCreate3D,
&MeshVisualizerGL_Test::constructCopy2D,
&MeshVisualizerGL_Test::constructCopy3D,
&MeshVisualizerGL_Test::vertexIndexSameAsObjectId,
&MeshVisualizerGL_Test::debugFlag2D,
&MeshVisualizerGL_Test::debugFlag3D,
&MeshVisualizerGL_Test::debugFlags2D,
&MeshVisualizerGL_Test::debugFlags3D,
#ifndef MAGNUM_TARGET_GLES2
&MeshVisualizerGL_Test::debugFlagsSupersets2D,
&MeshVisualizerGL_Test::debugFlagsSupersets3D,
#endif
});
}
void MeshVisualizerGL_Test::constructNoCreate2D() {
{
MeshVisualizerGL2D shader{NoCreate};
CORRADE_COMPARE(shader.id(), 0);
CORRADE_COMPARE(shader.flags(), MeshVisualizerGL2D::Flags{});
}
CORRADE_VERIFY(true);
}
void MeshVisualizerGL_Test::constructNoCreate3D() {
{
MeshVisualizerGL3D shader{NoCreate};
CORRADE_COMPARE(shader.id(), 0);
CORRADE_COMPARE(shader.flags(), MeshVisualizerGL3D::Flags{});
}
CORRADE_VERIFY(true);
}
void MeshVisualizerGL_Test::constructCopy2D() {
CORRADE_VERIFY(!std::is_copy_constructible<MeshVisualizerGL2D>{});
CORRADE_VERIFY(!std::is_copy_assignable<MeshVisualizerGL2D>{});
}
void MeshVisualizerGL_Test::constructCopy3D() {
CORRADE_VERIFY(!std::is_copy_constructible<MeshVisualizerGL3D>{});
CORRADE_VERIFY(!std::is_copy_assignable<MeshVisualizerGL3D>{});
}
void MeshVisualizerGL_Test::vertexIndexSameAsObjectId() {
#ifdef MAGNUM_TARGET_GLES2
CORRADE_SKIP("Object ID is not available on ES2.");
#else
CORRADE_COMPARE(MeshVisualizerGL2D::VertexIndex::Location, GenericGL2D::ObjectId::Location);
CORRADE_COMPARE(MeshVisualizerGL3D::VertexIndex::Location, GenericGL3D::ObjectId::Location);
#endif
}
void MeshVisualizerGL_Test::debugFlag2D() {
std::ostringstream out;
Debug{&out} << MeshVisualizerGL2D::Flag::Wireframe << MeshVisualizerGL2D::Flag(0xbad00000);
CORRADE_COMPARE(out.str(), "Shaders::MeshVisualizerGL2D::Flag::Wireframe Shaders::MeshVisualizerGL2D::Flag(0xbad00000)\n");
}
void MeshVisualizerGL_Test::debugFlag3D() {
std::ostringstream out;
Debug{&out} << MeshVisualizerGL3D::Flag::Wireframe << MeshVisualizerGL3D::Flag(0xbad00000);
CORRADE_COMPARE(out.str(), "Shaders::MeshVisualizerGL3D::Flag::Wireframe Shaders::MeshVisualizerGL3D::Flag(0xbad00000)\n");
}
void MeshVisualizerGL_Test::debugFlags2D() {
std::ostringstream out;
Debug{&out} << (MeshVisualizerGL2D::Flag::Wireframe|MeshVisualizerGL2D::Flag::NoGeometryShader) << MeshVisualizerGL2D::Flags{};
#if !defined(MAGNUM_TARGET_GLES2) && !defined(MAGNUM_TARGET_WEBGL)
CORRADE_COMPARE(out.str(), "Shaders::MeshVisualizerGL2D::Flag::Wireframe|Shaders::MeshVisualizerGL2D::Flag::NoGeometryShader Shaders::MeshVisualizerGL2D::Flags{}\n");
#else
CORRADE_COMPARE(out.str(), "Shaders::MeshVisualizerGL2D::Flag::Wireframe Shaders::MeshVisualizerGL2D::Flags{}\n");
#endif
}
void MeshVisualizerGL_Test::debugFlags3D() {
std::ostringstream out;
Debug{&out} << (MeshVisualizerGL3D::Flag::Wireframe|MeshVisualizerGL3D::Flag::NoGeometryShader) << MeshVisualizerGL3D::Flags{};
#if !defined(MAGNUM_TARGET_GLES2) && !defined(MAGNUM_TARGET_WEBGL)
CORRADE_COMPARE(out.str(), "Shaders::MeshVisualizerGL3D::Flag::Wireframe|Shaders::MeshVisualizerGL3D::Flag::NoGeometryShader Shaders::MeshVisualizerGL3D::Flags{}\n");
#else
CORRADE_COMPARE(out.str(), "Shaders::MeshVisualizerGL3D::Flag::Wireframe Shaders::MeshVisualizerGL3D::Flags{}\n");
#endif
}
#ifndef MAGNUM_TARGET_GLES2
void MeshVisualizerGL_Test::debugFlagsSupersets2D() {
/* InstancedObjectId and ObjectIdTexture are a superset of ObjectId so only
one should be printed, but if there are both then both should be */
{
std::ostringstream out;
Debug{&out} << (MeshVisualizerGL2D::Flag::ObjectId|MeshVisualizerGL2D::Flag::InstancedObjectId);
CORRADE_COMPARE(out.str(), "Shaders::MeshVisualizerGL2D::Flag::InstancedObjectId\n");
} {
std::ostringstream out;
Debug{&out} << (MeshVisualizerGL2D::Flag::ObjectId|MeshVisualizerGL2D::Flag::ObjectIdTexture);
CORRADE_COMPARE(out.str(), "Shaders::MeshVisualizerGL2D::Flag::ObjectIdTexture\n");
} {
std::ostringstream out;
Debug{&out} << (MeshVisualizerGL2D::Flag::ObjectId|MeshVisualizerGL2D::Flag::InstancedObjectId|MeshVisualizerGL2D::Flag::ObjectIdTexture);
CORRADE_COMPARE(out.str(), "Shaders::MeshVisualizerGL2D::Flag::InstancedObjectId|Shaders::MeshVisualizerGL2D::Flag::ObjectIdTexture\n");
}
/* MultiDraw is a superset of UniformBuffers so only one should be printed */
{
std::ostringstream out;
Debug{&out} << (MeshVisualizerGL2D::Flag::MultiDraw|MeshVisualizerGL2D::Flag::UniformBuffers);
CORRADE_COMPARE(out.str(), "Shaders::MeshVisualizerGL2D::Flag::MultiDraw\n");
}
}
void MeshVisualizerGL_Test::debugFlagsSupersets3D() {
/* InstancedObjectId and ObjectIdTexture are a superset of ObjectId so only
one should be printed, but if there are both then both should be */
{
std::ostringstream out;
Debug{&out} << (MeshVisualizerGL3D::Flag::ObjectId|MeshVisualizerGL3D::Flag::InstancedObjectId);
CORRADE_COMPARE(out.str(), "Shaders::MeshVisualizerGL3D::Flag::InstancedObjectId\n");
} {
std::ostringstream out;
Debug{&out} << (MeshVisualizerGL3D::Flag::ObjectId|MeshVisualizerGL3D::Flag::ObjectIdTexture);
CORRADE_COMPARE(out.str(), "Shaders::MeshVisualizerGL3D::Flag::ObjectIdTexture\n");
} {
std::ostringstream out;
Debug{&out} << (MeshVisualizerGL3D::Flag::ObjectId|MeshVisualizerGL3D::Flag::InstancedObjectId|MeshVisualizerGL3D::Flag::ObjectIdTexture);
CORRADE_COMPARE(out.str(), "Shaders::MeshVisualizerGL3D::Flag::InstancedObjectId|Shaders::MeshVisualizerGL3D::Flag::ObjectIdTexture\n");
}
/* MultiDraw is a superset of UniformBuffers so only one should be printed */
{
std::ostringstream out;
Debug{&out} << (MeshVisualizerGL3D::Flag::MultiDraw|MeshVisualizerGL3D::Flag::UniformBuffers);
CORRADE_COMPARE(out.str(), "Shaders::MeshVisualizerGL3D::Flag::MultiDraw\n");
}
}
#endif
}}}}
CORRADE_TEST_MAIN(Magnum::Shaders::Test::MeshVisualizerGL_Test)
| 41.326923 | 170 | 0.728362 | [
"object"
] |
ed5fc723fb5b5d45db101e44c42a2c840b2ffacf | 75,679 | cpp | C++ | asm.cpp | mras0/AmiEmu | 90288e431e6442c9201621368d3e98a987b80663 | [
"MIT"
] | 4 | 2021-09-27T16:04:10.000Z | 2021-10-24T02:05:22.000Z | asm.cpp | mras0/AmiEmu | 90288e431e6442c9201621368d3e98a987b80663 | [
"MIT"
] | null | null | null | asm.cpp | mras0/AmiEmu | 90288e431e6442c9201621368d3e98a987b80663 | [
"MIT"
] | null | null | null | #include "asm.h"
#include "instruction.h"
#include "ioutil.h"
#include "disasm.h"
#include "memory.h"
#include <sstream>
#include <stdexcept>
#include <unordered_map>
#include <map>
#include <vector>
#include <string>
#include <cassert>
#include <iostream>
#include <algorithm>
#include <memory>
constexpr uint8_t opsize_mask_none = 0;
constexpr uint8_t opsize_mask_b = 1 << 0;
constexpr uint8_t opsize_mask_w = 1 << 1;
constexpr uint8_t opsize_mask_l = 1 << 2;
constexpr uint8_t opsize_mask_bw = opsize_mask_b | opsize_mask_w;
constexpr uint8_t opsize_mask_bl = opsize_mask_b | opsize_mask_l;
constexpr uint8_t opsize_mask_wl = opsize_mask_w | opsize_mask_l;
constexpr uint8_t opsize_mask_bwl = opsize_mask_b | opsize_mask_w | opsize_mask_l;
constexpr bool range8(uint32_t val)
{
return static_cast<int32_t>(val) >= -128 && static_cast<int32_t>(val) <= 127;
}
constexpr bool range16(uint32_t val)
{
return static_cast<int32_t>(val) >= -32768 && static_cast<int32_t>(val) <= 32767;
}
#define WITH_CC(X, prefix, tname, fname, m, d, no) \
X(tname , m, d, no) \
X(fname , m, d, no) \
X(prefix##HI , m, d, no) \
X(prefix##LS , m, d, no) \
X(prefix##CC , m, d, no) \
X(prefix##CS , m, d, no) \
X(prefix##NE , m, d, no) \
X(prefix##EQ , m, d, no) \
X(prefix##VC , m, d, no) \
X(prefix##VS , m, d, no) \
X(prefix##PL , m, d, no) \
X(prefix##MI , m, d, no) \
X(prefix##GE , m, d, no) \
X(prefix##LT , m, d, no) \
X(prefix##GT , m, d, no) \
X(prefix##LE , m, d, no)
#define INSTRUCTIONS(X) \
X(ABCD , b , b , 2) \
X(ADD , bwl , w , 2) \
X(ADDQ , bwl , w , 2) \
X(ADDX , bwl , w , 2) \
X(AND , bwl , w , 2) \
X(ASL , bwl , w , 3) \
X(ASR , bwl , w , 3) \
X(BCHG , bl , none , 2) \
X(BCLR , bl , none , 2) \
X(BSET , bl , none , 2) \
X(BTST , bl , none , 2) \
WITH_CC(X, B, BRA, BSR, bw, none, 1) \
X(CHK , w , w , 2) \
X(CLR , bwl , w , 1) \
X(CMP , bwl , w , 2) \
X(CMPM , bwl , w , 2) \
WITH_CC(X, DB, DBT, DBF, w, w, 2) \
X(DIVS , w , w , 2) \
X(DIVU , w , w , 2) \
X(EOR , bwl , w , 2) \
X(EXT , wl , w , 1) \
X(EXG , l , none , 2) \
X(ILLEGAL , none , none , 0) \
X(JMP , none , none , 1) \
X(JSR , none , none , 1) \
X(LEA , l , l , 2) \
X(LINK , w , w , 2) \
X(LSL , bwl , w , 3) \
X(LSR , bwl , w , 3) \
X(MOVE , bwl , w , 2) \
X(MOVEM , wl , w , 2) \
X(MOVEP , wl , w , 2) \
X(MOVEQ , l , l , 2) \
X(MULS , w , w , 2) \
X(MULU , w , w , 2) \
X(NBCD , b , b , 1) \
X(NEG , bwl , w , 1) \
X(NEGX , bwl , w , 1) \
X(NOP , none , none , 0) \
X(NOT , bwl , w , 1) \
X(OR , bwl , w , 2) \
X(PEA , l , l , 1) \
X(RESET , none , none , 0) \
X(ROL , bwl , w , 3) \
X(ROR , bwl , w , 3) \
X(ROXL , bwl , w , 3) \
X(ROXR , bwl , w , 3) \
X(RTE , none , none , 0) \
X(RTR , none , none , 0) \
X(RTS , none , none , 0) \
X(SBCD , b , b , 2) \
WITH_CC(X, S, ST, SF, b, b, 1) \
X(STOP , none , none , 1) \
X(SUB , bwl , w , 2) \
X(SUBX , bwl , w , 2) \
X(SUBQ , bwl , w , 2) \
X(SWAP , w , w , 1) \
X(TAS , b , b , 1) \
X(TRAP , none , none , 1) \
X(TRAPV , none , none , 0) \
X(TST , bwl , w , 1) \
X(UNLK , none , none , 1) \
#define TOKENS(X) \
X(size_b , ".B" ) \
X(size_s , ".S" ) \
X(size_w , ".W" ) \
X(size_l , ".L" ) \
X(d0 , "D0" ) \
X(d1 , "D1" ) \
X(d2 , "D2" ) \
X(d3 , "D3" ) \
X(d4 , "D4" ) \
X(d5 , "D5" ) \
X(d6 , "D6" ) \
X(d7 , "D7" ) \
X(a0 , "A0" ) \
X(a1 , "A1" ) \
X(a2 , "A2" ) \
X(a3 , "A3" ) \
X(a4 , "A4" ) \
X(a5 , "A5" ) \
X(a6 , "A6" ) \
X(a7 , "A7" ) \
X(usp , "USP" ) \
X(pc , "PC" ) \
X(sr , "SR" ) \
X(ccr , "CCR" ) \
X(dc , "DC" ) \
X(even , "EVEN" ) \
X(equ , "EQU" ) \
X(org , "ORG" ) \
X(rs , "RS" ) \
X(rsreset , "RSRESET" ) \
X(rsset , "RSSET" ) \
X(ifeq , "IFEQ" ) \
X(ifne , "IFNE" ) \
X(else_ , "ELSE" ) \
X(endc , "ENDC" ) \
X(cnop , "CNOP" ) \
enum class token_type {
eof,
whitespace,
newline,
number,
// 33 ... 127 reserved for operators
hash = '#',
quote = '\'',
lparen = '(',
rparen = ')',
plus = '+',
comma = ',',
minus = '-',
slash = '/',
colon = ':',
equal = '=',
last_operator = 127,
string,
#define DEF_TOKEN(n, t) n,
TOKENS(DEF_TOKEN)
#undef DEF_TOKEN
instruction_start_minus_1,
#define TOKEN_INST(n, m, d, no) n,
INSTRUCTIONS(TOKEN_INST)
#undef TOKEN_INST
identifier_start,
};
constexpr bool is_branch_inst(token_type tt)
{
return tt >= token_type::BRA && tt <= token_type::BLE;
}
constexpr bool is_cond_token(token_type tt)
{
switch (tt) {
case token_type::ifeq:
case token_type::ifne:
case token_type::else_:
case token_type::endc:
return true;
}
return false;
}
constexpr bool eval_cond(token_type tt, int32_t val)
{
switch (tt) {
case token_type::ifeq:
return val == 0;
case token_type::ifne:
return val != 0;
}
throw std::runtime_error { "Invalid condition type in eval_cond" };
}
constexpr struct instruction_info_type {
token_type type;
const char* const name;
uint8_t opsize_mask;
opsize default_size;
uint8_t num_operands;
} instruction_info[] = {
#define INSTRUCTION_INFO(name, osize_mask, def_size, num_oper) { token_type::name, #name, opsize_mask_##osize_mask, opsize::def_size, num_oper },
INSTRUCTIONS(INSTRUCTION_INFO)
#undef INSTRUCTION_INFO
};
#define ASSEMBLER_ERROR(...) \
do { \
std::ostringstream oss; \
oss << "Error in line " << line_ << " column " << col_ << ": " << __VA_ARGS__ << " in function " << __func__ << " line " << __LINE__; \
throw std::runtime_error { oss.str() }; \
} while (0)
class assembler {
public:
explicit assembler(uint32_t start_pc, const char* text, const std::vector<std::pair<const char*, uint32_t>>& predefines)
: pc_ { start_pc }
, input_ { text }
{
for (const auto& [name, val] : predefines) {
auto tt = make_identifier(name);
if (tt < token_type::identifier_start)
ASSEMBLER_ERROR("Invalid predefined identifier " << name);
auto& ii = identifier_info(tt);
if (ii.has_value)
ASSEMBLER_ERROR("Redefinition of " << ii.id);
ii.has_value = true;
ii.value = val;
}
}
std::vector<uint8_t> process()
{
bool dont_get_token = false;
do {
const bool start_of_line = col_ == 1;
if (dont_get_token)
dont_get_token = false;
else
get_token();
if (token_type_ == token_type::whitespace || token_type_ == token_type::newline) {
continue;
} else if (token_type_ == token_type::eof) {
break;
}
// In disabled block?
if (in_disabled_block() && !is_cond_token(token_type_)) {
while (token_type_ != token_type::eof && token_type_ != token_type::newline)
get_token();
dont_get_token = true;
continue;
}
if (is_identifier(token_type_)) {
const auto l = token_type_;
get_token();
if (token_type_ == token_type::colon) {
get_token();
} else {
if (token_type_ == token_type::whitespace) {
dont_get_token = true;
skip_whitespace();
}
if (token_type_ == token_type::equal || token_type_ == token_type::equ) {
get_token();
skip_whitespace();
auto& ii = identifier_info(l);
if (ii.has_value)
ASSEMBLER_ERROR("Redefinition of " << ii.id);
else if (!ii.fixups.empty())
ASSEMBLER_ERROR("Invalid definition for " << ii.id << " (previously referenced)");
ii.has_value = true;
auto val = process_number();
if (val.has_fixups())
ASSEMBLER_ERROR("Invalid definition for " << ii.id << "(needs fixups)");
ii.value = val.val;
skip_to_eol();
dont_get_token = false;
continue;
} else if (token_type_ == token_type::rs) {
auto& ii = identifier_info(l);
if (ii.has_value)
ASSEMBLER_ERROR("Redefinition of " << ii.id);
else if (!ii.fixups.empty())
ASSEMBLER_ERROR("Invalid definition for " << ii.id << " (previously referenced)");
ii.has_value = true;
ii.value = process_rs();
skip_to_eol();
dont_get_token = false;
continue;
}
if (!start_of_line)
ASSEMBLER_ERROR("Expected instruction got " << token_type_string(l));
}
auto& ii = identifier_info(l);
if (ii.has_value) {
ASSEMBLER_ERROR("Redefinition of " << ii.id);
}
if (ii.id.find_first_of('.') == std::string::npos)
last_global_ = ii.id;
ii.has_value = true;
ii.value = pc_;
for (const auto& f : ii.fixups) {
auto it = pending_fixups_.find(f.offset);
if (it == pending_fixups_.end())
ASSEMBLER_ERROR("Invalid fixup for " << ii.id);
if (it->second.size != f.size)
ASSEMBLER_ERROR("Size mismatch for " << ii.id << " expected size " << opsize_bytes(it->second.size) << " got " << opsize_bytes(f.size));
it->second.value += f.negate ? -static_cast<int32_t>(ii.value) : ii.value;
}
ii.fixups.clear();
} else if (is_instruction(token_type_)) {
// Strictly legal, but 99.99% of the time not what's wanted
if (pc_ & 1)
ASSEMBLER_ERROR("Assembling instruction at odd address");
const auto inst = token_type_;
get_token();
process_instruction(inst);
} else if (token_type_ == token_type::dc) {
process_dc();
} else if (token_type_ == token_type::rs) {
process_rs();
} else if (token_type_ == token_type::even) {
if (pc_ & 1) {
result_.push_back(0);
++pc_;
}
} else if (token_type_ == token_type::cnop) {
get_token();
const auto offset = get_constant_expr();
skip_whitespace();
expect(token_type::comma);
skip_whitespace();
const auto alignment = get_constant_expr();
skip_to_eol();
auto extra = offset + (pc_ % alignment ? alignment - pc_ % alignment : 0);
while (extra--) {
result_.push_back(0);
++pc_;
}
} else if (token_type_ == token_type::org) {
get_token();
pc_ = get_constant_expr();
skip_to_eol();
} else if (token_type_ == token_type::rsreset) {
rs_value_ = 0;
} else if (token_type_ == token_type::rsset) {
get_token();
rs_value_ = get_constant_expr();
skip_to_eol();
} else if (token_type_ == token_type::ifeq || token_type_ == token_type::ifne) {
cond_state c;
c.line = line_;
const auto type = token_type_;
get_token();
const auto val = get_constant_expr();
skip_to_eol();
if (!conds_.empty() && !(conds_.back().state & cond_state::state_active))
c.state = cond_state::state_was_active; // In disabled block
else
c.state = eval_cond(type, val) ? cond_state::state_active | cond_state::state_was_active : 0;
conds_.push_back(c);
} else if (token_type_ == token_type::else_) {
if (conds_.empty())
ASSEMBLER_ERROR("else without matching if");
auto& c = conds_.back();
if (c.state & cond_state::state_else_seen)
ASSEMBLER_ERROR("multiple else statements for condition started on line " << c.line);
c.state |= cond_state::state_else_seen;
if (c.state & cond_state::state_was_active)
c.state &= ~cond_state::state_active;
else
c.state |= cond_state::state_active | cond_state::state_was_active;
} else if (token_type_ == token_type::endc) {
if (conds_.empty())
ASSEMBLER_ERROR("endc without matching if");
conds_.pop_back();
} else {
ASSEMBLER_ERROR("Unexpected token: " << token_type_string(token_type_));
}
} while (token_type_ != token_type::eof);
for (const auto& i : identifier_info_) {
if (!i->has_value || !i->fixups.empty()) {
ASSEMBLER_ERROR(i->id << " referenced but not defined");
}
}
// Apply fixups. Delayed until here to allow full 32-bit intermediate values.
for (const auto& [offset, f] : pending_fixups_) {
//std::cout << "Applying fixup offset=$" << hexfmt(offset) << " " << token_type_string(f.inst) << " line " << f.line << " value $" << hexfmt(f.value) << "\n";
switch (f.size) {
case opsize::none:
assert(false);
ASSEMBLER_ERROR("Internal error");
case opsize::b:
assert(offset & 1);
if (!range8(f.value) || (!f.value && is_branch_inst(f.inst)))
ASSEMBLER_ERROR("Value ($" << hexfmt(f.value) << ") of out 8-bit range in line " << f.line << " for " << token_type_string(f.inst) );
result_[offset] = static_cast<uint8_t>(f.value);
break;
case opsize::w:
assert(!(offset & 1));
if (!range16(f.value))
ASSEMBLER_ERROR("Value ($" << hexfmt(f.value) << ") of out 16-bit range in line " << f.line << " for " << token_type_string(f.inst));
put_u16(&result_[offset], static_cast<uint16_t>(f.value));
break;
case opsize::l:
assert(!(offset & 1));
put_u32(&result_[offset], f.value);
break;
}
}
if (!conds_.empty())
ASSEMBLER_ERROR("Unterminated condition started at line " << conds_[0].line);
return std::move(result_);
}
private:
std::unordered_map<std::string, token_type> id_map_ = {
#define INST_ID_INIT(n, m, d, no) { #n, token_type::n },
INSTRUCTIONS(INST_ID_INIT)
#undef INST_ID_INIT
#define TOKEN_ID_INIT(n, t) { t, token_type::n },
TOKENS(TOKEN_ID_INIT)
#undef TOKEN_ID_INIT
// Synonyms
{ "SP", token_type::a7 },
};
struct fixup_type {
opsize size;
bool negate;
uint32_t offset;
};
struct pending_fixup {
token_type inst;
uint32_t line;
opsize size;
uint32_t value;
};
struct identifier_info_type {
std::string id;
bool has_value;
uint32_t value;
std::vector<fixup_type> fixups;
};
struct cond_state {
static constexpr uint8_t state_active = 1;
static constexpr uint8_t state_was_active = 2;
static constexpr uint8_t state_else_seen = 4;
uint32_t line;
uint8_t state;
};
std::vector<std::unique_ptr<identifier_info_type>> identifier_info_;
std::map<uint32_t, pending_fixup> pending_fixups_;
std::vector<uint8_t> result_;
uint32_t pc_;
const char* input_;
uint32_t line_ = 1;
uint32_t col_ = 1;
std::string last_global_;
token_type token_type_ = token_type::eof;
std::string token_text_;
uint32_t token_number_ = 0;
uint32_t rs_value_ = 0; // TODO: In vasm this value can be referenced as __RS
std::vector<cond_state> conds_;
static constexpr bool is_instruction(token_type t)
{
return static_cast<uint32_t>(t) > static_cast<uint32_t>(token_type::instruction_start_minus_1) && static_cast<uint32_t>(t) < static_cast<uint32_t>(token_type::identifier_start);
}
static constexpr bool is_identifier(token_type t)
{
return static_cast<uint32_t>(t) >= static_cast<uint32_t>(token_type::identifier_start);
}
static constexpr bool is_register(token_type t)
{
return static_cast<uint32_t>(t) >= static_cast<uint32_t>(token_type::d0) && static_cast<uint32_t>(t) <= static_cast<uint32_t>(token_type::a7);
}
static constexpr bool is_data_register(token_type t)
{
return static_cast<uint32_t>(t) >= static_cast<uint32_t>(token_type::d0) && static_cast<uint32_t>(t) <= static_cast<uint32_t>(token_type::d7);
}
static constexpr bool is_address_register(token_type t)
{
return static_cast<uint32_t>(t) >= static_cast<uint32_t>(token_type::a0) && static_cast<uint32_t>(t) <= static_cast<uint32_t>(token_type::a7);
}
identifier_info_type& identifier_info(token_type t)
{
const auto id_idx = static_cast<uint32_t>(t) - static_cast<uint32_t>(token_type::identifier_start);
assert(id_idx < identifier_info_.size());
return *identifier_info_[id_idx];
}
bool in_disabled_block()
{
return !conds_.empty() && !(conds_.back().state & cond_state::state_active);
}
std::string token_type_string(token_type tt)
{
switch (tt) {
case token_type::eof:
return "EOF";
case token_type::whitespace:
return "WHITESPACE";
case token_type::newline:
return "NEWLINE";
case token_type::number:
return "NUMBER";
case token_type::string:
return "STRING";
#define CASE_INST_TOKEN(n, m, d, no) case token_type::n: return #n;
INSTRUCTIONS(CASE_INST_TOKEN)
#undef CASE_INST_TOKEN
#define CASE_TOKEN(n, t) case token_type::n: return t;
TOKENS(CASE_TOKEN)
#undef CASE_TOKEN
default:
const auto ti = static_cast<uint32_t>(tt);
if (ti >= 33 && ti <= 127) {
std::ostringstream oss;
oss << "OPERATOR \"" << static_cast<char>(ti) << "\"";
return oss.str();
}
const auto id_idx = ti - static_cast<uint32_t>(token_type::identifier_start);
if (id_idx < identifier_info_.size()) {
std::ostringstream oss;
oss << "INDENTIFIER \"" << identifier_info_[id_idx]->id << "\"";
return oss.str();
}
ASSEMBLER_ERROR("Unknown token type: " << ti);
}
}
token_type make_identifier(const char* text)
{
std::string uc = toupper_str(text);
if (auto it = id_map_.find(uc); it != id_map_.end())
return it->second;
// Don't define new identifiers in disabled block
if (in_disabled_block())
return token_type::whitespace; // Hmm...
if (uc[0] == '.') {
if (last_global_.empty())
ASSEMBLER_ERROR("Local label outside function");
uc = last_global_ + uc;
// Lookup again
if (auto it = id_map_.find(uc); it != id_map_.end())
return it->second;
}
const uint32_t id = static_cast<uint32_t>(identifier_info_.size()) + static_cast<uint32_t>(token_type::identifier_start);
id_map_[uc] = static_cast<token_type>(id);
auto ii = std::make_unique<identifier_info_type>();
ii->id = std::move(uc);
identifier_info_.push_back(std::move(ii));
return static_cast<token_type>(id);
}
uint32_t read_number(uint8_t base)
{
uint32_t n = 0;
bool any = false;
for (;;) {
const char c = *input_;
uint32_t v = 0;
if (c >= '0' && c <= '9') {
v = c - '0';
} else if (c >= 'A' && c <= 'F') {
v = c - 'A' + 10;
} else if (c >= 'a' && c <= 'f') {
v = c - 'a' + 10;
} else {
break;
}
if (n * base < n)
ASSEMBLER_ERROR("Number is too large");
if (v >= base)
ASSEMBLER_ERROR("Digit out of range for base " << static_cast<int>(base));
++col_;
++input_;
n = n * base + v;
any = true;
}
if (!any)
ASSEMBLER_ERROR("No digits in number");
return n;
}
void get_token()
{
const char c = *input_++;
token_text_ = c;
token_number_ = 0;
++col_;
switch (c) {
case '\0':
token_type_ = token_type::eof;
return;
case '\n':
token_type_ = token_type::newline;
++line_;
col_ = 1;
return;
case ';':
while (*input_ && *input_ != '\n')
++input_;
token_type_ = token_type::whitespace;
return;
case '#':
case '(':
case ')':
case '+':
case ',':
case '-':
case '/':
case ':':
//case '<':
case '=':
//case '>':
//case '?':
token_type_ = static_cast<token_type>(c);
return;
case '$':
token_type_ = token_type::number;
token_number_ = read_number(16);
return;
}
if (c == '\'') {
token_text_ = "";
for (bool quote = false; *input_ != '\'' || quote; ++input_, ++col_) {
const auto ch = *input_;
if (!ch || ch == '\n')
ASSEMBLER_ERROR("Unterminted string literal");
if (!quote) {
if (ch == '\\')
quote = true;
else
token_text_ += ch;
continue;
}
quote = false;
switch (ch) {
case 'n':
token_text_ += '\n';
continue;
case 'r':
token_text_ += '\r';
continue;
case 't':
token_text_ += '\t';
continue;
case '\'':
token_text_ += '\'';
continue;
case '"':
token_text_ += '\"';
continue;
case '\\':
token_text_ += '\\';
continue;
case 'x': {
++input_;
++col_;
auto n = read_number(16);
if (n > 255)
ASSEMBLER_ERROR("Character too large $" << hexfmt(n));
token_text_ += static_cast<char>(n);
// Undo increment in looop
--col_;
--input_;
continue;
}
case '0': case '1': case '2': case '3':
case '4': case '5': case '6': case '7': {
auto n = read_number(8);
if (n > 255)
ASSEMBLER_ERROR("Octal character too large $" << hexfmt(n));
token_text_ += static_cast<char>(n);
// Undo increment in looop
--col_;
--input_;
continue;
}
default:
ASSEMBLER_ERROR("Invalid escape sequence \\" << ch);
}
}
++input_; // Skip end quote
++col_;
token_type_ = token_type::string;
return;
}
if (c >= '0' && c <= '9') {
--input_;
--col_;
token_type_ = token_type::number;
token_number_ = read_number(10);
return;
}
if (isalpha(c) || c == '_' || c == '.') {
while (isalnum(*input_) || *input_ == '_') {
token_text_ += *input_++;
++col_;
}
token_type_ = make_identifier(token_text_.c_str());
return;
}
if (isspace(c)) {
token_type_ = token_type::whitespace;
if (c == '\t') {
--col_;
col_ += 8 - (col_ - 1) % 8;
}
while (isspace(*input_) && *input_ != '\n') {
if (*input_ == '\t')
col_ += 8 - (col_ - 1) % 8;
else
++col_;
token_text_ += *input_++;
}
return;
}
ASSEMBLER_ERROR("Invalid character: " << c);
}
void expect(token_type expected)
{
if (token_type_ != expected)
ASSEMBLER_ERROR("Expected " << token_type_string(expected) << " got " << token_type_string(token_type_));
get_token();
}
void skip_whitespace()
{
while (token_type_ == token_type::whitespace)
get_token();
}
void skip_to_eol()
{
for (;;) {
if (token_type_ == token_type::eof || token_type_ == token_type::newline)
return;
expect(token_type::whitespace);
}
}
struct ea_result {
uint8_t type;
uint32_t val = 0;
uint32_t saved_val = 0;
std::vector<std::pair<identifier_info_type*,bool>> fixups;
bool has_fixups() const
{
return !fixups.empty();
}
};
void add_fixups(const ea_result& r, token_type inst, opsize osize, uint32_t offset)
{
if (r.fixups.empty())
return;
if (!pending_fixups_.insert({ offset, pending_fixup { inst, line_, osize, r.saved_val } }).second)
ASSEMBLER_ERROR("Fixups already exist");
assert(!!(offset & 1) == (osize == opsize::b));
for (auto [ii, negate] : r.fixups)
ii->fixups.push_back(fixup_type { osize, negate, offset });
}
void convert_string_to_number()
{
if (token_type_ != token_type::string)
return;
const auto l = token_text_.length();
if (l == 0 || l > 4)
ASSEMBLER_ERROR("String is not a valid number: '" << token_text_ << "'");
token_type_ = token_type::number;
token_number_ = 0;
for (size_t i = 0; i < l; ++i) {
token_number_ <<= 8;
token_number_ |= static_cast<uint8_t>(token_text_[i]);
}
}
ea_result process_number(bool neg = false)
{
// TODO: More aritmetic
ea_result res {};
if (token_type_ == token_type::minus) {
if (neg)
ASSEMBLER_ERROR("Double minus not allowed");
neg = true;
get_token();
}
convert_string_to_number();
if (token_type_ == token_type::number) {
res.val = neg ? -static_cast<int32_t>(token_number_) : token_number_;
get_token();
} else if (is_identifier(token_type_)) {
auto& ii = identifier_info(token_type_);
if (ii.has_value) {
res.val = neg ? -static_cast<int32_t>(ii.value) : ii.value;
} else {
res.val = 0;
res.fixups.push_back({ &ii, neg });
}
get_token();
} else {
ASSEMBLER_ERROR("Expected number or identifier got " << token_type_string(token_type_));
}
// Only support very simple aritmetic for now
while (token_type_ == token_type::minus || token_type_ == token_type::plus) {
const auto saved_token = token_type_;
get_token();
convert_string_to_number();
uint32_t val = 0;
if (token_type_ == token_type::number) {
val = token_number_;
get_token();
} else if (is_identifier(token_type_)) {
auto& ii = identifier_info(token_type_);
if (ii.has_value) {
val = ii.value;
} else {
res.fixups.push_back({ &ii, saved_token == token_type::minus });
}
get_token();
} else {
ASSEMBLER_ERROR("Expected number or identifier got " << token_type_string(token_type_));
}
if (saved_token == token_type::minus)
res.val -= val;
else
res.val += val;
}
res.saved_val = res.val;
return res;
}
uint8_t process_areg()
{
if (!is_address_register(token_type_))
ASSEMBLER_ERROR("Address register expected got " << token_type_string(token_type_));
const auto reg = static_cast<uint8_t>(static_cast<uint32_t>(token_type_) - static_cast<uint32_t>(token_type::a0));
get_token();
return reg;
}
uint8_t process_reg()
{
if (!is_register(token_type_))
ASSEMBLER_ERROR("Register expected got " << token_type_string(token_type_));
const auto reg = static_cast<uint8_t>(static_cast<uint32_t>(token_type_) - static_cast<uint32_t>(token_type::d0));
get_token();
return reg;
}
ea_result process_ea()
{
skip_whitespace();
bool neg = false;
uint8_t reg = 0;
ea_result res {};
if (token_type_ == token_type::hash) {
get_token();
res = process_number();
res.type = ea_immediate;
return res;
} else if (token_type_ == token_type::minus) {
get_token();
if (token_type_ != token_type::lparen) {
neg = true;
goto number;
}
get_token();
res.type = ea_m_A_ind_pre << ea_m_shift | process_areg();
expect(token_type::rparen);
return res;
} else if (token_type_ == token_type::lparen) {
get_token();
reg = process_areg();
if (token_type_ == token_type::comma)
goto has_reg;
res.type = ea_m_A_ind << ea_m_shift | reg;
expect(token_type::rparen);
if (token_type_ == token_type::plus) {
res.type = ea_m_A_ind_post << ea_m_shift | (res.type & 7);
get_token();
}
return res;
} else if (token_type_ == token_type::number || is_identifier(token_type_)) {
number:
res = process_number(neg);
if (token_type_ == token_type::lparen) {
get_token();
if (token_type_ == token_type::pc) {
reg = 0xff;
res.val -= pc_ + 2;
res.saved_val = res.val;
get_token();
} else {
reg = process_areg();
if (!res.has_fixups() && !range16(res.val))
ASSEMBLER_ERROR(static_cast<int32_t>(res.val) << " is out of range for 16-bit displacement");
}
has_reg:
if (token_type_ == token_type::rparen) {
get_token();
if (reg == 0xff)
res.type = ea_m_Other << ea_m_shift | ea_other_pc_disp16;
else
res.type = ea_m_A_ind_disp16 << ea_m_shift | reg;
return res;
}
expect(token_type::comma);
const auto reg2 = process_reg();
const bool l = token_type_ == token_type::size_l;
if (token_type_ == token_type::size_w || token_type_ == token_type::size_l)
get_token();
expect(token_type::rparen);
if (reg == 0xff)
res.type = ea_m_Other << ea_m_shift | ea_other_pc_index;
else {
res.type = ea_m_A_ind_index << ea_m_shift | reg;
}
if (!res.has_fixups() && !range8(res.val))
ASSEMBLER_ERROR(static_cast<int32_t>(res.val) << " is out of range for 8-bit displacement");
res.val = (res.val & 0xff) | (reg2 & 8 ? 0x8000 : 0) | (reg2 & 7) << 12 | (l ? 0x800 : 0);
return res;
}
res.type = ea_m_Other << ea_m_shift | ea_other_abs_l;
if (token_type_ == token_type::size_l) {
get_token();
} else if (token_type_ == token_type::size_w) {
get_token();
res.type = ea_m_Other << ea_m_shift | ea_other_abs_w;
if (!range16(res.val))
ASSEMBLER_ERROR(static_cast<int32_t>(res.val) << " is out of range for 16-bit absolute address");
}
return res;
} else if (is_register(token_type_)) {
res.type = static_cast<uint8_t>(static_cast<uint32_t>(token_type_) - static_cast<uint32_t>(token_type::d0));
get_token();
if (token_type_ == token_type::minus || token_type_ == token_type::slash) {
// register list
auto first = res.type;
res.type = ea_reglist;
res.val = 0;
for (;;) {
if (token_type_ == token_type::slash) {
if (first <= 15) {
res.val |= 1 << first;
}
first = 0xff;
get_token();
} else if (token_type_ == token_type::minus) {
if (first > 15)
ASSEMBLER_ERROR("Invalid register list");
get_token();
if (!is_register(token_type_))
ASSEMBLER_ERROR("Invalid register list");
const auto last = static_cast<uint8_t>(static_cast<uint32_t>(token_type_) - static_cast<uint32_t>(token_type::d0));
if (last <= first)
ASSEMBLER_ERROR("Invalid order in register list");
for (auto r = first; r <= last; ++r)
res.val |= 1 << r;
first = 0xff;
get_token();
} else if (is_register(token_type_)) {
if (first != 0xff)
ASSEMBLER_ERROR("Invalid register list");
first = static_cast<uint8_t>(static_cast<uint32_t>(token_type_) - static_cast<uint32_t>(token_type::d0));
get_token();
} else {
break;
}
}
if (first <= 15)
res.val |= 1 << first;
}
return res;
} else if (token_type_ == token_type::sr) {
get_token();
return ea_result { .type = ea_sr };
} else if (token_type_ == token_type::ccr) {
get_token();
return ea_result { .type = ea_ccr };
} else if (token_type_ == token_type::usp) {
get_token();
return ea_result { .type = ea_usp };
}
ASSEMBLER_ERROR("Unexpected token: " << token_type_string(token_type_));
}
bool check_special_reg_size(const ea_result& ea, bool explicit_size, opsize& osize)
{
if (ea.type == ea_sr) {
if (osize == opsize::none || !explicit_size)
osize = opsize::w;
else if (osize != opsize::w)
ASSEMBLER_ERROR("SR is word sized");
return true;
} else if (ea.type == ea_ccr) {
if (osize == opsize::none || !explicit_size)
osize = opsize::b;
else if (osize != opsize::b)
ASSEMBLER_ERROR("CCR is byte sized");
return true;
}
return false;
}
void process_instruction(token_type inst)
{
auto info = instruction_info[static_cast<uint32_t>(inst) - static_cast<uint32_t>(token_type::instruction_start_minus_1) - 1];
ea_result ea[2] = {};
auto osize = info.default_size;
bool explicit_size = true;
if (info.num_operands == 0) {
assert(info.opsize_mask == opsize_mask_none);
goto operands_done;
}
// Allow Bxx.s as synonym for Bxx.b
if (is_branch_inst(inst) && token_type_ == token_type::size_s) {
get_token();
osize = opsize::b;
} else {
osize = get_opsize();
}
if (osize == opsize::b) {
if (!(info.opsize_mask & opsize_mask_b))
ASSEMBLER_ERROR("Byte size not allowed for " << info.name);
} else if (osize == opsize::w) {
if (!(info.opsize_mask & opsize_mask_w))
ASSEMBLER_ERROR("Word size not allowed for " << info.name);
} else if (osize == opsize::l) {
if (!(info.opsize_mask & opsize_mask_l))
ASSEMBLER_ERROR("Long size not allowed for " << info.name);
} else {
osize = info.default_size;
explicit_size = false;
}
for (uint8_t arg = 0; arg < info.num_operands; ++arg) {
expect(arg == 0 ? token_type::whitespace : token_type::comma);
ea[arg] = process_ea();
if (ea[arg].type == ea_reglist && inst != token_type::MOVEM)
ASSEMBLER_ERROR("Register list not allowed for " + std::string { info.name });
if (info.num_operands == 3) {
if (token_type_ == token_type::comma) {
info.num_operands = 2;
} else {
info.num_operands = 1;
break;
}
}
}
operands_done:
skip_to_eol();
uint16_t iwords[max_instruction_words];
uint8_t iword_cnt = 1;
switch (inst) {
case token_type::ABCD:
iwords[0] = encode_abcd_sbcd(info, ea, false);
break;
case token_type::ADD:
iwords[0] = encode_add_sub_cmp(info, ea, osize, 0x0600, 0xD000);
break;
case token_type::ADDQ:
iwords[0] = encode_addsub_q(info, ea, osize, false);
break;
case token_type::ADDX:
iwords[0] = encode_addsub_x(info, ea, osize, false);
goto done;
case token_type::AND:
if (check_special_reg_size(ea[1], explicit_size, osize)) {
// ANDI to SR/CCR
if (ea[0].type != ea_immediate)
ASSEMBLER_ERROR("Immediate required as first argument");
iwords[0] = ea[1].type == ea_sr ? 0x027c : 0x023c;
} else {
iwords[0] = encode_binop(info, ea, osize, 0x0200, 0xC000);
}
break;
case token_type::ASL:
iwords[0] = encode_shift_rotate(info, ea, osize, 0b00, true);
break;
case token_type::ASR:
iwords[0] = encode_shift_rotate(info, ea, osize, 0b00, false);
break;
case token_type::BCHG:
iwords[0] = encode_bitop(info, ea, osize, 0x0840, 0x0140);
break;
case token_type::BCLR:
iwords[0] = encode_bitop(info, ea, osize, 0x0880, 0x0180);
break;
case token_type::BSET:
iwords[0] = encode_bitop(info, ea, osize, 0x08C0, 0x01C0);
break;
case token_type::BTST:
iwords[0] = encode_bitop(info, ea, osize, 0x0800, 0x0100);
break;
case token_type::BRA:
case token_type::BSR:
case token_type::BHI:
case token_type::BLS:
case token_type::BCC:
case token_type::BCS:
case token_type::BNE:
case token_type::BEQ:
case token_type::BVC:
case token_type::BVS:
case token_type::BPL:
case token_type::BMI:
case token_type::BGE:
case token_type::BLT:
case token_type::BGT:
case token_type::BLE:
{
int32_t disp = handle_disp_bw(info, ea[0], osize);
iwords[0] = 0x6000 | (static_cast<uint16_t>(inst) - static_cast<uint16_t>(token_type::BRA)) << 8;
if (osize == opsize::b)
iwords[0] |= disp & 0xff;
else
iwords[iword_cnt++] = disp & 0xffff;
goto done;
}
case token_type::CHK:
if (ea[0].type > ea_immediate || ea[1].type > ea_immediate || ea[0].type >> ea_m_shift == ea_m_An)
ASSEMBLER_ERROR("Invalid source operand for " << info.name);
if (ea[1].type >> ea_m_shift != ea_m_Dn)
ASSEMBLER_ERROR("Destination must be data register for " << info.name);
iwords[0] = 0x4180 | (ea[1].type & 7) << 9 | (ea[0].type & 0x3f);
break;
case token_type::CLR:
iwords[0] = encode_unary(info, ea[0], osize, 0x4200);
break;
case token_type::CMP:
if ((ea[1].type >> ea_m_shift > ea_m_An) && ea[0].type != ea_immediate) {
ASSEMBLER_ERROR("Destination of CMP must be register");
}
iwords[0] = encode_add_sub_cmp(info, ea, osize, 0x0C00, 0xB000);
break;
case token_type::CMPM: {
if (ea[0].type >> ea_m_shift != ea_m_A_ind_post)
ASSEMBLER_ERROR("First operand must be address register in postincrement addressing mode");
if (ea[1].type >> ea_m_shift != ea_m_A_ind_post)
ASSEMBLER_ERROR("Second operand must be address register in postincrement addressing mode");
constexpr uint8_t size_encoding[4] = { 0b00, 0b00, 0b01, 0b10 };
iwords[0] = 0xb108 | (ea[1].type & 7) << 9 | size_encoding[static_cast<uint8_t>(osize)] << 6 | (ea[0].type & 7);
goto done;
}
case token_type::DBT:
case token_type::DBF:
case token_type::DBHI:
case token_type::DBLS:
case token_type::DBCC:
case token_type::DBCS:
case token_type::DBNE:
case token_type::DBEQ:
case token_type::DBVC:
case token_type::DBVS:
case token_type::DBPL:
case token_type::DBMI:
case token_type::DBGE:
case token_type::DBLT:
case token_type::DBGT:
case token_type::DBLE: {
if (ea[0].type >> ea_m_shift != ea_m_Dn)
ASSEMBLER_ERROR("First operand to " << info.name << " must be a data register");
if (ea[1].type >> ea_m_shift != ea_m_Other || (ea[1].type & 7) != ea_other_abs_l)
ASSEMBLER_ERROR("Unsupported operand to " << info.name << ": " << ea_string(ea[1].type));
const int32_t disp = ea[1].val - (pc_ + 2);
ea[1].saved_val = disp;
if (ea[1].has_fixups())
add_fixups(ea[1], inst, opsize::w, static_cast<uint32_t>(result_.size() + 2));
else if (!range16(disp))
ASSEMBLER_ERROR("Displacement " << disp << " is out of range");
iwords[0] = 0x50c8 | (static_cast<uint16_t>(inst) - static_cast<uint16_t>(token_type::DBT)) << 8 | (ea[0].type & 7);
iwords[iword_cnt++] = disp & 0xffff;
goto done;
}
case token_type::DIVS:
iwords[0] = encode_muldiv(info, ea, true, false);
break;
case token_type::DIVU:
iwords[0] = encode_muldiv(info, ea, false, false);
break;
case token_type::EOR:
if (check_special_reg_size(ea[1], explicit_size, osize)) {
// EORI to SR/CCR
if (ea[0].type != ea_immediate)
ASSEMBLER_ERROR("Immediate required as first argument");
iwords[0] = ea[1].type == ea_sr ? 0x0a7c : 0x0a3c;
} else {
iwords[0] = encode_binop(info, ea, osize, 0x0A00, 0xB000);
}
break;
case token_type::EXG: {
const uint8_t e0t = ea[0].type >> ea_m_shift;
const uint8_t e1t = ea[1].type >> ea_m_shift;
if (e0t != ea_m_Dn && e0t != ea_m_An)
ASSEMBLER_ERROR("Invalid first operand for EXG");
if (e1t != ea_m_Dn && e1t != ea_m_An)
ASSEMBLER_ERROR("Invalid second operand for EXG");
iwords[0] = 0xc100 | (ea[0].type & 7) << 9 | (ea[1].type & 7);
if (e0t == ea_m_Dn && e1t == ea_m_Dn)
iwords[0] |= 0b01000 << 3;
else if (e0t == ea_m_An && e1t == ea_m_An)
iwords[0] |= 0b01001 << 3;
else
iwords[0] |= 0b10001 << 3;
goto done;
}
case token_type::EXT:
assert(osize == opsize::w || osize == opsize::l);
if (ea[0].type >> ea_m_shift != ea_m_Dn)
ASSEMBLER_ERROR("Invalid operand to EXT");
iwords[0] = 0x4800 | (osize == opsize::w ? 0b010 : 0b011) << 6 | (ea[0].type & 7);
goto done;
case token_type::ILLEGAL:
iwords[0] = 0x4afc;
break;
case token_type::JMP:
iwords[0] = encode_ea_instruction(info, ea[0], 0x4ec0);
break;
case token_type::JSR:
iwords[0] = encode_ea_instruction(info, ea[0], 0x4e80);
break;
case token_type::LEA:
assert(osize == opsize::l);
if (ea[1].type >> ea_m_shift != ea_m_An)
ASSEMBLER_ERROR("Destination register must be address register for LEA");
iwords[0] = encode_ea_instruction(info, ea[0], 0x41c0 | (ea[1].type & 7) << 9);
break;
case token_type::LINK:
if (ea[0].type >> ea_m_shift != ea_m_An)
ASSEMBLER_ERROR("First operand must be address register");
if (ea[1].type != ea_immediate)
ASSEMBLER_ERROR("Second operand must be immediate");
iwords[0] = 0x4e50 | (ea[0].type & 7);
break;
case token_type::LSL:
iwords[0] = encode_shift_rotate(info, ea, osize, 0b01, true);
break;
case token_type::LSR:
iwords[0] = encode_shift_rotate(info, ea, osize, 0b01, false);
break;
case token_type::MOVE: {
// Unlike ANDI/EORI/ORI to CCR, MOVE to/from CCR is word sized
// Note: MOVE to CCR is 68010+ only
if ((ea[1].type >> ea_m_shift == ea_m_Other) && (ea[1].type & ea_xn_mask) > ea_other_abs_l)
ASSEMBLER_ERROR("Invalid destination for MOVE");
if (ea[0].type == ea_sr || ea[0].type == ea_ccr) {
if (osize != opsize::w)
ASSEMBLER_ERROR("Operation must be word sized");
if (ea[1].type > ea_immediate || ea[1].type >> ea_m_shift == ea_m_An || (ea[1].type >> ea_m_shift == ea_m_Other && (ea[1].type & 7) > ea_other_abs_l))
ASSEMBLER_ERROR("Invalid operand");
iwords[0] = (ea[1].type == ea_sr ? 0x42c0 : 0x40c0) | (ea[1].type & 0x3f);
} else if (ea[1].type == ea_sr || ea[1].type == ea_ccr) {
if (osize != opsize::w)
ASSEMBLER_ERROR("Operation must be word sized");
if (ea[0].type > ea_immediate || ea[0].type >> ea_m_shift == ea_m_An)
ASSEMBLER_ERROR("Invalid operand");
iwords[0] = (ea[1].type == ea_sr ? 0x46c0 : 0x44c0) | (ea[0].type & 0x3f);
} else if (ea[0].type == ea_usp) {
if (ea[1].type >> ea_m_shift != ea_m_An)
ASSEMBLER_ERROR("Destination must be address register");
if (explicit_size && osize != opsize::l)
ASSEMBLER_ERROR("Invalid operation size");
iwords[0] = 0x4e68 | (ea[1].type & 7);
} else if (ea[1].type == ea_usp) {
if (ea[0].type >> ea_m_shift != ea_m_An)
ASSEMBLER_ERROR("Source must be address register");
if (explicit_size && osize != opsize::l)
ASSEMBLER_ERROR("Invalid operation size");
iwords[0] = 0x4e60 | (ea[0].type & 7);
} else {
constexpr uint8_t size_encoding[4] = { 0b00, 0b01, 0b11, 0b10 };
const auto sz = size_encoding[static_cast<uint8_t>(osize)];
iwords[0] = sz << 12 | (ea[1].type & 7) << 9 | (ea[1].type & (7 << 3)) << (6 - 3) | ea[0].type;
}
break;
}
case token_type::MOVEM: {
iwords[0] = 0x4880;
if (ea[0].type == ea_reglist || ea[0].type >> ea_m_shift <= ea_m_An) {
// Reg-to-mem
if (ea[0].type != ea_reglist) {
ea[0].val = 1 << ea[0].type;
ea[0].type = ea_reglist;
}
if (ea[1].type >= ea_immediate || ea[1].type >> ea_m_shift <= ea_m_An || ea[1].type >> ea_m_shift == ea_m_A_ind_post || (ea[1].type >> ea_m_shift == ea_m_Other && (ea[1].type & 7) > ea_other_abs_l))
ASSEMBLER_ERROR("Invalid destination for MOVEM");
uint16_t rl = static_cast<uint16_t>(ea[0].val);
if (ea[1].type >> ea_m_shift == ea_m_A_ind_pre) {
// Reverse bits
rl = ((rl >> 1) & 0x55555) | ((rl & 0x5555) << 1);
rl = ((rl >> 2) & 0x33333) | ((rl & 0x3333) << 2);
rl = ((rl >> 4) & 0xf0f0f) | ((rl & 0x0f0f) << 4);
rl = ((rl >> 8) & 0xf00ff) | ((rl & 0x00ff) << 8);
}
iwords[0] |= ea[1].type & 0x3f;
iwords[iword_cnt++] = rl;
} else if (ea[1].type == ea_reglist || ea[1].type >> ea_m_shift <= ea_m_An) {
// Mem-to-reg
if (ea[1].type != ea_reglist) {
ea[1].val = 1 << ea[1].type;
ea[1].type = ea_reglist;
}
// TODO: Check invalid
if ((ea[0].type >> ea_m_shift == ea_m_Other) && ((ea[0].type & 7) == ea_other_pc_disp16 || (ea[0].type & 7) == ea_other_pc_index))
ea[0].val -= 2;
iwords[0] |= 1 << 10;
iwords[0] |= ea[0].type & 0x3f;
iwords[iword_cnt++] = static_cast<uint16_t>(ea[1].val);
} else {
ASSEMBLER_ERROR("Invalid operands to MOVEM");
}
if (osize == opsize::l)
iwords[0] |= 1 << 6;
break;
}
case token_type::MOVEP: {
// TODO: Turn (An) into 0(An) automatically
const uint16_t mode = 1 << 8 | (osize == opsize::l ? 1 << 6 : 0);
if (ea[0].type >> ea_m_shift == ea_m_Dn && ea[1].type >> ea_m_shift == ea_m_A_ind_disp16) {
iwords[0] = (ea[0].type & 7) << 9 | 1 << 7 | mode | 1 << 3 | (ea[1].type & 7);
} else if (ea[0].type >> ea_m_shift == ea_m_A_ind_disp16 && ea[1].type >> ea_m_shift == ea_m_Dn) {
iwords[0] = (ea[1].type & 7) << 9 | mode | 1 << 3 | (ea[0].type & 7);
} else {
ASSEMBLER_ERROR("Invalid operands for MOVEP");
}
break;
}
case token_type::MOVEQ: {
if (ea[0].type != ea_immediate || ea[0].has_fixups() || ea[1].type >> ea_m_shift != ea_m_Dn)
ASSEMBLER_ERROR("Invalid operands to MOVEQ");
if (!range8(ea[0].val))
ASSEMBLER_ERROR("Immediate out of 8-bit range for MOVEQ: " << ea[0].val);
iwords[0] = 0x7000 | (ea[1].type & 7) << 9 | (ea[0].val & 0xff);
goto done;
}
case token_type::MULS:
iwords[0] = encode_muldiv(info, ea, true, true);
break;
case token_type::MULU:
iwords[0] = encode_muldiv(info, ea, false, true);
break;
case token_type::NBCD:
assert(osize == opsize::b);
iwords[0] = encode_unary(info, ea[0], opsize::b, 0x4800);
break;
case token_type::NEG:
iwords[0] = encode_unary(info, ea[0], osize, 0x4400);
break;
case token_type::NEGX:
iwords[0] = encode_unary(info, ea[0], osize, 0x4000);
break;
case token_type::NOP:
iwords[0] = 0x4e71;
break;
case token_type::NOT:
iwords[0] = encode_unary(info, ea[0], osize, 0x4600);
break;
case token_type::OR:
if (check_special_reg_size(ea[1], explicit_size, osize)) {
// ORI to SR/CCR
if (ea[0].type != ea_immediate)
ASSEMBLER_ERROR("Immediate required as first argument");
iwords[0] = ea[1].type == ea_sr ? 0x007c : 0x003c;
} else {
iwords[0] = encode_binop(info, ea, osize, 0x0000, 0x8000);
}
break;
case token_type::PEA:
assert(osize == opsize::l);
iwords[0] = encode_ea_instruction(info, ea[0], 0x4840);
break;
case token_type::RESET:
iwords[0] = 0x4e70;
break;
case token_type::ROL:
iwords[0] = encode_shift_rotate(info, ea, osize, 0b11, true);
break;
case token_type::ROR:
iwords[0] = encode_shift_rotate(info, ea, osize, 0b11, false);
break;
case token_type::ROXL:
iwords[0] = encode_shift_rotate(info, ea, osize, 0b10, true);
break;
case token_type::ROXR:
iwords[0] = encode_shift_rotate(info, ea, osize, 0b10, false);
break;
case token_type::RTE:
iwords[0] = 0x4e73;
break;
case token_type::RTR:
iwords[0] = 0x4e77;
break;
case token_type::RTS:
iwords[0] = 0x4e75;
break;
case token_type::SBCD:
iwords[0] = encode_abcd_sbcd(info, ea, true);
break;
case token_type::ST:
case token_type::SF:
case token_type::SHI:
case token_type::SLS:
case token_type::SCC:
case token_type::SCS:
case token_type::SNE:
case token_type::SEQ:
case token_type::SVC:
case token_type::SVS:
case token_type::SPL:
case token_type::SMI:
case token_type::SGE:
case token_type::SLT:
case token_type::SGT:
case token_type::SLE: {
if (ea[0].type >> ea_m_shift == ea_m_An || ea[0].type >= ea_immediate)
ASSEMBLER_ERROR("Invalid operand to " << info.name);
iwords[0] = 0x50c0 | (static_cast<uint16_t>(inst) - static_cast<uint16_t>(token_type::ST)) << 8 | (ea[0].type & 0x3f);
break;
}
case token_type::STOP:
if (ea[0].type != ea_immediate)
ASSEMBLER_ERROR("Expeceted immediate for STOP");
iwords[0] = 0x4e72;
break;
case token_type::SUB:
iwords[0] = encode_add_sub_cmp(info, ea, osize, 0x0400, 0x9000);
break;
case token_type::SUBQ:
iwords[0] = encode_addsub_q(info, ea, osize, true);
break;
case token_type::SUBX:
iwords[0] = encode_addsub_x(info, ea, osize, true);
goto done;
case token_type::SWAP:
assert(osize == opsize::w && info.num_operands == 1);
if (ea[0].type >> ea_m_shift != ea_m_Dn)
ASSEMBLER_ERROR("Invalid operand to SWAP");
iwords[0] = 0x4840 | (ea[0].type & 7);
goto done;
case token_type::TAS:
if (ea[0].type >> ea_m_shift == ea_m_An || ea[0].type >= ea_immediate)
ASSEMBLER_ERROR("Invalid operand to " << info.name);
iwords[0] = 0x4ac0 | (ea[0].type & 0x3f);
break;
case token_type::TRAP:
if (ea[0].type != ea_immediate)
ASSEMBLER_ERROR("Invalid operand to TRAP");
if (ea[0].val > 15)
ASSEMBLER_ERROR("TRAP vector out of 4-bit range");
iwords[0] = 0x4e40 | (ea[0].val & 15);
goto done;
case token_type::TRAPV:
iwords[0] = 0x4e76;
goto done;
case token_type::TST:
iwords[0] = encode_unary(info, ea[0], osize, 0x4A00);
break;
case token_type::UNLK:
if (ea[0].type >> ea_m_shift != ea_m_An)
ASSEMBLER_ERROR("Operand must be address register");
iwords[0] = 0x4e58 | (ea[0].type & 7);
break;
default:
ASSEMBLER_ERROR("TODO: Encode " << info.name);
}
for (uint8_t arg = 0; arg < info.num_operands; ++arg) {
uint32_t ofs = static_cast<uint32_t>(result_.size() + iword_cnt * 2);
switch (ea[arg].type >> ea_m_shift) {
case ea_m_Dn:
case ea_m_An:
case ea_m_A_ind:
case ea_m_A_ind_post:
case ea_m_A_ind_pre:
assert(!ea[arg].has_fixups());
break;
case ea_m_A_ind_disp16: // (d16, An)
add_fixups(ea[arg], inst, opsize::w, ofs);
iwords[iword_cnt++] = static_cast<uint16_t>(ea[arg].val);
break;
case ea_m_A_ind_index: // (d8, An, Xn)
assert(!ea[arg].has_fixups());
iwords[iword_cnt++] = static_cast<uint16_t>(ea[arg].val);
break;
case ea_m_Other:
switch (ea[arg].type & 7) {
case ea_other_abs_w:
add_fixups(ea[arg], inst, opsize::w, ofs);
iwords[iword_cnt++] = static_cast<uint16_t>(ea[arg].val);
break;
case ea_other_abs_l:
add_fixups(ea[arg], inst, opsize::l, ofs);
iwords[iword_cnt++] = static_cast<uint16_t>(ea[arg].val >> 16);
iwords[iword_cnt++] = static_cast<uint16_t>(ea[arg].val);
break;
case ea_other_pc_disp16: // (d16, PC)
add_fixups(ea[arg], inst, opsize::w, ofs);
iwords[iword_cnt++] = static_cast<uint16_t>(ea[arg].val);
break;
case ea_other_pc_index: // (d8, PC, Xn)
add_fixups(ea[arg], inst, opsize::b, ofs + 1);
iwords[iword_cnt++] = static_cast<uint16_t>(ea[arg].val);
break;
case ea_other_imm:
if (ea[arg].has_fixups()) {
assert(osize != opsize::none);
if (osize == opsize::b)
++ofs;
add_fixups(ea[arg], inst, osize, ofs);
}
if (osize == opsize::l)
iwords[iword_cnt++] = static_cast<uint16_t>(ea[arg].val >> 16);
else if (osize == opsize::b)
ea[arg].val &= 0xff;
iwords[iword_cnt++] = static_cast<uint16_t>(ea[arg].val);
break;
default:
ASSEMBLER_ERROR("TODO: Encoding for " << ea_string(ea[arg].type));
}
break;
default:
if (ea[arg].type == ea_sr || ea[arg].type == ea_ccr || ea[arg].type == ea_usp || ea[arg].type == ea_reglist)
break;
ASSEMBLER_ERROR("TODO: Encoding for " << ea_string(ea[arg].type));
}
}
done:
for (uint8_t i = 0; i < iword_cnt; ++i) {
result_.push_back(static_cast<uint8_t>(iwords[i] >> 8));
result_.push_back(static_cast<uint8_t>(iwords[i]));
pc_ += 2;
}
}
opsize get_opsize()
{
opsize osize = opsize::none;
if (token_type_ == token_type::size_b) {
osize = opsize::b;
get_token();
} else if (token_type_ == token_type::size_w) {
osize = opsize::w;
get_token();
} else if (token_type_ == token_type::size_l) {
osize = opsize::l;
get_token();
}
return osize;
}
void process_dc()
{
get_token();
const opsize osize = get_opsize();
if (osize == opsize::none)
ASSEMBLER_ERROR("Size required for DC");
expect(token_type::whitespace);
for (;;) {
if (token_type_ == token_type::string && osize == opsize::b) {
for (size_t i = 0, l = token_text_.length(); i < l; ++i) {
result_.push_back(token_text_[i]);
++pc_;
}
get_token();
} else {
auto num = process_number();
add_fixups(num, token_type::dc, osize, static_cast<uint32_t>(result_.size()));
if (osize == opsize::b) {
result_.push_back(static_cast<uint8_t>(num.val));
++pc_;
} else if (osize == opsize::w) {
result_.push_back(static_cast<uint8_t>(num.val >> 8));
result_.push_back(static_cast<uint8_t>(num.val));
pc_ += 2;
} else {
result_.push_back(static_cast<uint8_t>(num.val >> 24));
result_.push_back(static_cast<uint8_t>(num.val >> 16));
result_.push_back(static_cast<uint8_t>(num.val >> 8));
result_.push_back(static_cast<uint8_t>(num.val));
pc_ += 4;
}
}
skip_whitespace();
if (token_type_ != token_type::comma)
break;
get_token();
skip_whitespace();
}
skip_to_eol();
}
uint32_t get_constant_expr()
{
skip_whitespace();
const auto val = process_number();
if (!val.fixups.empty())
ASSEMBLER_ERROR("Expected constant expression");
return val.val;
}
uint32_t process_rs()
{
const auto ret = rs_value_;
get_token();
const opsize osize = get_opsize();
if (osize == opsize::none)
ASSEMBLER_ERROR("Size required for RS");
skip_whitespace();
rs_value_ += get_constant_expr() * opsize_bytes(osize);
return ret;
}
uint16_t encode_add_sub_cmp(const instruction_info_type& info, const ea_result* ea, opsize osize, uint16_t imm_code, uint16_t normal_code)
{
if (ea[0].type > ea_immediate || ea[1].type > ea_immediate)
ASSEMBLER_ERROR("Invalid operand to " << info.name);
if (ea[1].type >> ea_m_shift == ea_m_An) {
if (osize == opsize::b)
ASSEMBLER_ERROR("Only word/long operations allowed with address destination");
return normal_code | 0x00C0 | (ea[1].type & 7) << 9 | (osize == opsize::l ? 0x100 : 0x000) | (ea[0].type & 0x3f);
}
return encode_binop(info, ea, osize, imm_code, normal_code);
}
uint16_t encode_binop(const instruction_info_type& info, const ea_result* ea, opsize osize, uint16_t imm_code, uint16_t normal_code)
{
constexpr uint8_t size_encoding[4] = { 0b00, 0b00, 0b01, 0b10 };
if (ea[0].type > ea_immediate || ea[1].type > ea_immediate)
ASSEMBLER_ERROR("Invalid operand to " << info.name);
if (/*ea[0].type >> ea_m_shift == ea_m_An || */ ea[1].type >> ea_m_shift == ea_m_An)
ASSEMBLER_ERROR("Address register not allowed for " << info.name);
if (ea[0].type == ea_immediate)
return imm_code | size_encoding[static_cast<uint8_t>(osize)] << 6 | (ea[1].type & 0x3f);
if (ea[0].type >> ea_m_shift != ea_m_Dn && ea[1].type >> ea_m_shift != ea_m_Dn)
ASSEMBLER_ERROR("Unsupported operands to " << info.name);
uint8_t eaidx;
if (imm_code == 0x0A00) {
// EOR (as opposed to CMP)
eaidx = ea[0].type >> ea_m_shift == ea_m_Dn ? 1 : 0;
} else {
eaidx = ea[1].type >> ea_m_shift == ea_m_Dn ? 0 : 1;
}
return normal_code | (ea[!eaidx].type & 7) << 9 | eaidx << 8 | size_encoding[static_cast<uint8_t>(osize)] << 6 | (ea[eaidx].type & 0x3f);
}
uint16_t encode_bitop(const instruction_info_type& info, const ea_result* ea, opsize& osize, uint16_t imm_code, uint16_t dn_code)
{
if (ea[0].type > ea_immediate || ea[1].type > ea_immediate)
ASSEMBLER_ERROR("Invalid operand to " << info.name);
if (ea[1].type >> ea_m_shift == ea_m_An)
ASSEMBLER_ERROR("Address register not allowed for " << info.name);
if (ea[1].type >> ea_m_shift == ea_m_Dn) {
if (osize == opsize::b)
ASSEMBLER_ERROR("Data register destination to " << info.name << " always has long size");
assert(osize == opsize::l || osize == opsize::none);
} else {
if (osize == opsize::l)
ASSEMBLER_ERROR("Memory destination to " << info.name << " always has byte size");
assert(osize == opsize::b || osize == opsize::none);
}
if (ea[0].type == ea_immediate) {
osize = opsize::b; // For encoding of the immediate
return imm_code | (ea[1].type & 0x3f);
} else if (ea[0].type >> ea_m_shift == ea_m_Dn) {
return dn_code | (ea[0].type & 7) << 9 | (ea[1].type & 0x3f);
} else {
ASSEMBLER_ERROR("First operand to " << info.name << " is illegal");
}
}
uint16_t encode_unary(const instruction_info_type& info, const ea_result& ea, opsize osize, uint16_t opcode)
{
if (ea.type >> ea_m_shift == ea_m_An)
ASSEMBLER_ERROR("Address register not allowed for " << info.name);
if (ea.type >> ea_m_shift == ea_m_Other && ((ea.type & 7) == ea_other_imm || (ea.type & 7) == ea_other_pc_disp16 || (ea.type & 7) == ea_other_pc_index))
ASSEMBLER_ERROR("Invalid operand to " << info.name);
if (ea.type > ea_immediate)
ASSEMBLER_ERROR("Invalid operand to " << info.name);
constexpr uint8_t size_encoding[4] = { 0b00, 0b00, 0b01, 0b10 };
return opcode | size_encoding[static_cast<uint8_t>(osize)] << 6 | (ea.type & 0x3f);
}
uint16_t encode_ea_instruction(const instruction_info_type& info, const ea_result& ea, uint16_t opcode)
{
if (ea.type >= ea_immediate)
ASSEMBLER_ERROR("Invalid operand to " << info.name);
switch (ea.type >> ea_m_shift) {
case ea_m_Dn:
case ea_m_An:
case ea_m_A_ind_post:
case ea_m_A_ind_pre:
ASSEMBLER_ERROR("Invalid operand to " << info.name);
default:
break;
}
return opcode | (ea.type & 0x3f);
}
uint16_t encode_addsub_q(const instruction_info_type& info, ea_result* ea, opsize osize, bool is_sub)
{
if (ea[0].type != ea_immediate)
ASSEMBLER_ERROR("Source operand for " << info.name << " must be immediate");
if (ea[0].val < 1 || ea[0].val > 8)
ASSEMBLER_ERROR("Immediate out of range for " << info.name);
if (osize == opsize::b && ea[1].type >> ea_m_shift == ea_m_An)
ASSEMBLER_ERROR("Byte size not allowed for address register destination for " << info.name);
if (ea[1].type > ea_immediate)
ASSEMBLER_ERROR("Invalid operand to " << info.name);
ea[0].type = 0; // Don't encode the immediate
constexpr uint8_t size_encoding[4] = { 0b00, 0b00, 0b01, 0b10 };
return 0x5000 | (ea[0].val & 7) << 9 | is_sub << 8 | size_encoding[static_cast<uint8_t>(osize)] << 6 | (ea[1].type & 0x3f);
}
int32_t handle_disp_bw(const instruction_info_type& info, ea_result& ea, opsize& osize)
{
if (ea.type >> ea_m_shift != ea_m_Other || (ea.type & 7) != ea_other_abs_l)
ASSEMBLER_ERROR("Unsupported operand to " << info.name << ": " << ea_string(ea.type));
const int32_t disp = ea.val - (pc_ + 2);
if (ea.has_fixups()) {
const uint32_t ofs = static_cast<uint32_t>(result_.size());
ea.saved_val = disp;
if (osize == opsize::none || osize == opsize::w)
add_fixups(ea, info.type, opsize::w, ofs + 2);
else
add_fixups(ea, info.type, opsize::b, ofs + 1);
} else {
if (disp == 0 || !range8(disp)) {
if (osize == opsize::b)
ASSEMBLER_ERROR("Displacement " << disp << " is out of range for byte size");
if (!range16(disp))
ASSEMBLER_ERROR("Displacement " << disp << " is out of range");
osize = opsize::w;
} else if (osize == opsize::none)
osize = opsize::b;
}
return disp;
}
uint16_t encode_addsub_x(const instruction_info_type& info, const ea_result* ea, opsize osize, bool is_sub)
{
bool memop = false;
if (ea[0].type >> ea_m_shift == ea_m_Dn && ea[1].type >> ea_m_shift == ea_m_Dn) {
// OK
} else if (ea[0].type >> ea_m_shift == ea_m_A_ind_pre && ea[1].type >> ea_m_shift == ea_m_A_ind_pre) {
memop = true;
} else {
ASSEMBLER_ERROR("Invalid operands to " << info.name);
}
constexpr uint8_t size_encoding[4] = { 0b00, 0b00, 0b01, 0b10 };
return 0x9100 | (!is_sub) << 14 | (ea[1].type & 7) << 9 | size_encoding[static_cast<uint8_t>(osize)] << 6 | memop << 3 | (ea[0].type & 7);
}
uint16_t encode_abcd_sbcd(const instruction_info_type& info, const ea_result* ea, bool is_sub)
{
bool memop = false;
if (ea[0].type >> ea_m_shift == ea_m_Dn && ea[1].type >> ea_m_shift == ea_m_Dn) {
// OK
} else if (ea[0].type >> ea_m_shift == ea_m_A_ind_pre && ea[1].type >> ea_m_shift == ea_m_A_ind_pre) {
memop = true;
} else {
ASSEMBLER_ERROR("Invalid operands to " << info.name);
}
return 0x8100 | (!is_sub) << 14 | (ea[1].type & 7) << 9 | memop << 3 | (ea[0].type & 7);
}
uint16_t encode_muldiv(const instruction_info_type& info, const ea_result* ea, bool is_signed, bool is_mul)
{
if (ea[0].type > ea_immediate || ea[1].type > ea_immediate || ea[0].type >> ea_m_shift == ea_m_An)
ASSEMBLER_ERROR("Invalid source operand for " << info.name);
if (ea[1].type >> ea_m_shift != ea_m_Dn)
ASSEMBLER_ERROR("Destination must be data register for " << info.name);
return 0x80c0 | is_mul << 14 | (ea[1].type & 7) << 9 | is_signed << 8 | (ea[0].type & 0x3f);
}
uint16_t encode_shift_rotate(const instruction_info_type& info, ea_result* ea, opsize osize, uint8_t code, bool left)
{
if (info.num_operands == 1) {
if (osize != opsize::w)
ASSEMBLER_ERROR("Must be word size for one-argument version of " << info.name);
if (ea[0].type >> ea_m_shift <= ea_m_An || ea[0].type >= ea_immediate)
ASSEMBLER_ERROR("Invalid operand for " << info.name);
return 0xe000 | code << 9 | left << 8 | 0b11 << 6 | (ea[0].type & 0x3f);
} else if (ea[1].type >> ea_m_shift != ea_m_Dn) {
ASSEMBLER_ERROR("Destination must be data register for " << info.name);
}
constexpr uint8_t size_encoding[4] = { 0b00, 0b00, 0b01, 0b10 };
const uint16_t op = 0xe000 | left << 8 | size_encoding[static_cast<uint8_t>(osize)] << 6 | code << 3 | (ea[1].type & 7);
if (ea[0].type >> ea_m_shift == ea_m_Dn) {
return op | (ea[0].type & 7) << 9 | 1 << 5;
} else if (ea[0].type == ea_immediate) {
if (ea[0].val < 1 || ea[0].val > 8)
ASSEMBLER_ERROR("Immediate out of range for " << info.name);
ea[0].type = 0; // Don't encode the immediate
return op | (ea[0].val & 7) << 9;
} else {
ASSEMBLER_ERROR("Invalid source operand for " << info.name);
}
}
};
std::vector<uint8_t> assemble(uint32_t start_pc, const char* code, const std::vector<std::pair<const char*, uint32_t>>& predefines)
{
assembler a { start_pc, code, predefines };
return a.process();
}
| 39.601779 | 214 | 0.487374 | [
"vector"
] |
ed61426a7975266a692d8a460615b80a6a809cca | 942 | cpp | C++ | C++/maximum-vacation-days.cpp | jaiskid/LeetCode-Solutions | a8075fd69087c5463f02d74e6cea2488fdd4efd1 | [
"MIT"
] | 3,269 | 2018-10-12T01:29:40.000Z | 2022-03-31T17:58:41.000Z | C++/maximum-vacation-days.cpp | pnandini/LeetCode | e746c3298be96dec8e160da9378940568ef631b1 | [
"MIT"
] | 53 | 2018-12-16T22:54:20.000Z | 2022-02-25T08:31:20.000Z | C++/maximum-vacation-days.cpp | pnandini/LeetCode | e746c3298be96dec8e160da9378940568ef631b1 | [
"MIT"
] | 1,236 | 2018-10-12T02:51:40.000Z | 2022-03-30T13:30:37.000Z | // Time: O(n^2 * k)
// Space: O(k)
class Solution {
public:
int maxVacationDays(vector<vector<int>>& flights, vector<vector<int>>& days) {
if (days.empty() || flights.empty()) {
return 0;
}
vector<vector<int>> dp(2, vector<int>(days.size()));
for (int week = days[0].size() - 1; week >= 0; --week) {
for (int cur_city = 0; cur_city < days.size(); ++cur_city) {
dp[week % 2][cur_city] = days[cur_city][week] + dp[(week + 1) % 2][cur_city];
for (int dest_city = 0; dest_city < days.size(); ++dest_city) {
if (flights[cur_city][dest_city] == 1) {
dp[week % 2][cur_city] = max(dp[week % 2][cur_city],
days[dest_city][week] + dp[(week + 1) % 2][dest_city]);
}
}
}
}
return dp[0][0];
}
};
| 37.68 | 108 | 0.444798 | [
"vector"
] |
ed647b6115e17035b41da06e1fdde91131c5328f | 27,843 | cc | C++ | main/lsp/LSPTypechecker.cc | streeter/sorbet | 893f8e5cf39d1de4fead40e5fa0c125e60944e78 | [
"Apache-2.0"
] | null | null | null | main/lsp/LSPTypechecker.cc | streeter/sorbet | 893f8e5cf39d1de4fead40e5fa0c125e60944e78 | [
"Apache-2.0"
] | null | null | null | main/lsp/LSPTypechecker.cc | streeter/sorbet | 893f8e5cf39d1de4fead40e5fa0c125e60944e78 | [
"Apache-2.0"
] | null | null | null | #include "main/lsp/LSPTypechecker.h"
#include "absl/synchronization/mutex.h"
#include "absl/synchronization/notification.h"
#include "ast/treemap/treemap.h"
#include "common/concurrency/ConcurrentQueue.h"
#include "common/sort.h"
#include "common/typecase.h"
#include "core/ErrorQueue.h"
#include "core/Unfreeze.h"
#include "core/lsp/PreemptionTaskManager.h"
#include "core/lsp/TypecheckEpochManager.h"
#include "main/lsp/DefLocSaver.h"
#include "main/lsp/ErrorFlusherLSP.h"
#include "main/lsp/ErrorReporter.h"
#include "main/lsp/LSPMessage.h"
#include "main/lsp/LSPOutput.h"
#include "main/lsp/LocalVarFinder.h"
#include "main/lsp/LocalVarSaver.h"
#include "main/lsp/ShowOperation.h"
#include "main/lsp/UndoState.h"
#include "main/lsp/json_types.h"
#include "main/pipeline/pipeline.h"
namespace sorbet::realmain::lsp {
using namespace std;
namespace {
class ErrorCollector final : public core::ErrorFlusher {
public:
std::vector<std::unique_ptr<core::Error>> collectedErrors;
ErrorCollector() = default;
~ErrorCollector() = default;
void flushErrors(spdlog::logger &logger, const core::GlobalState &gs, core::FileRef file,
std::vector<std::unique_ptr<core::ErrorQueueMessage>> errors) override {
for (auto &error : errors) {
if (error->kind == core::ErrorQueueMessage::Kind::Error) {
if (error->error->isSilenced) {
continue;
}
collectedErrors.emplace_back(move(error->error));
}
}
}
};
void sendTypecheckInfo(const LSPConfiguration &config, const core::GlobalState &gs, SorbetTypecheckRunStatus status,
bool isFastPath, std::vector<core::FileRef> filesTypechecked) {
if (config.getClientConfig().enableTypecheckInfo) {
auto sorbetTypecheckInfo =
make_unique<SorbetTypecheckRunInfo>(status, isFastPath, config.frefsToPaths(gs, filesTypechecked));
config.output->write(make_unique<LSPMessage>(
make_unique<NotificationMessage>("2.0", LSPMethod::SorbetTypecheckRunInfo, move(sorbetTypecheckInfo))));
}
}
// In debug builds, asserts that we have not accidentally taken the fast path after a change to the set of
// methods in a file.
bool validateMethodHashesHaveSameMethods(const std::vector<std::pair<core::NameHash, u4>> &a,
const std::vector<std::pair<core::NameHash, u4>> &b) {
if (a.size() != b.size()) {
return false;
}
pair<core::NameHash, u4> previousHash; // Initializes to <0, 0>.
auto bIt = b.begin();
for (const auto &methodA : a) {
const auto &methodB = *bIt;
if (methodA.first != methodB.first) {
return false;
}
// Enforce that hashes are sorted in ascending order.
if (methodA < previousHash) {
return false;
}
previousHash = methodA;
bIt++;
}
return true;
}
} // namespace
LSPTypechecker::LSPTypechecker(std::shared_ptr<const LSPConfiguration> config,
shared_ptr<core::lsp::PreemptionTaskManager> preemptManager)
: typecheckerThreadId(this_thread::get_id()), config(move(config)), preemptManager(move(preemptManager)),
errorReporter(make_shared<ErrorReporter>(this->config)) {}
LSPTypechecker::~LSPTypechecker() {}
void LSPTypechecker::initialize(LSPFileUpdates updates, WorkerPool &workers) {
ENFORCE(this_thread::get_id() == typecheckerThreadId, "Typechecker can only be used from the typechecker thread.");
ENFORCE(!this->initialized);
// We should always initialize with epoch 0.
ENFORCE(updates.epoch == 0);
this->initialized = true;
indexed = move(updates.updatedFileIndexes);
// Initialization typecheck is not cancelable.
// TODO(jvilk): Make it preemptible.
auto committed = false;
{
ErrorEpoch epoch(*errorReporter, updates.epoch, {});
committed = runSlowPath(move(updates), workers, /* cancelable */ false);
epoch.committed = committed;
}
ENFORCE(committed);
}
bool LSPTypechecker::typecheck(LSPFileUpdates updates, WorkerPool &workers,
vector<unique_ptr<Timer>> diagnosticLatencyTimers) {
ENFORCE(this_thread::get_id() == typecheckerThreadId, "Typechecker can only be used from the typechecker thread.");
ENFORCE(this->initialized);
if (updates.canceledSlowPath) {
// This update canceled the last slow path, so we should have undo state to restore to go to the point _before_
// that slow path. This should always be the case, but let's not crash release builds.
ENFORCE(cancellationUndoState != nullptr);
if (cancellationUndoState != nullptr) {
// Restore the previous globalState
cancellationUndoState->restore(gs, indexed, indexedFinalGS);
// Prune the new files from list of files to be re-typechecked
vector<core::FileRef> oldFilesWithErrors;
u4 maxFileId = gs->getFiles().size();
for (auto &file : errorReporter->filesWithErrorsSince(cancellationUndoState->epoch)) {
if (file.id() < maxFileId) {
oldFilesWithErrors.push_back(file);
}
}
cancellationUndoState = nullptr;
auto fastPathDecision = updates.canTakeFastPath;
// Retypecheck all of the files that previously had errors.
updates.mergeOlder(getNoopUpdate(oldFilesWithErrors));
// The merge operation resets `fastPathDecision`, but we know that retypechecking unchanged files
// has no influence on the fast path decision.
updates.canTakeFastPath = fastPathDecision;
} else {
config->logger->debug("[Typechecker] Error: UndoState is missing for update that canceled slow path!");
}
}
vector<core::FileRef> filesTypechecked;
bool committed = true;
const bool isFastPath = updates.canTakeFastPath;
sendTypecheckInfo(*config, *gs, SorbetTypecheckRunStatus::Started, isFastPath, {});
{
ErrorEpoch epoch(*errorReporter, updates.epoch, move(diagnosticLatencyTimers));
if (isFastPath) {
filesTypechecked =
runFastPath(updates, workers, make_shared<ErrorFlusherLSP>(updates.epoch, errorReporter));
commitFileUpdates(updates, /* cancelable */ false);
prodCategoryCounterInc("lsp.updates", "fastpath");
} else {
committed = runSlowPath(move(updates), workers, /* cancelable */ true);
}
epoch.committed = committed;
}
sendTypecheckInfo(*config, *gs, committed ? SorbetTypecheckRunStatus::Ended : SorbetTypecheckRunStatus::Cancelled,
isFastPath, move(filesTypechecked));
return committed;
}
vector<core::FileRef> LSPTypechecker::runFastPath(LSPFileUpdates &updates, WorkerPool &workers,
shared_ptr<core::ErrorFlusher> errorFlusher) const {
ENFORCE(this_thread::get_id() == typecheckerThreadId, "Typechecker can only be used from the typechecker thread.");
ENFORCE(this->initialized);
// We assume gs is a copy of initialGS, which has had the inferencer & resolver run.
ENFORCE(gs->lspTypecheckCount > 0,
"Tried to run fast path with a GlobalState object that never had inferencer and resolver runs.");
// This property is set to 'true' in tests only if the update is expected to take the slow path and get cancelled.
ENFORCE(!updates.cancellationExpected);
ENFORCE(updates.preemptionsExpected == 0);
// This path only works for fast path updates.
ENFORCE(updates.canTakeFastPath);
Timer timeit(config->logger, "fast_path");
vector<core::FileRef> subset;
vector<core::NameHash> changedHashes;
// Replace error queue with one that is owned by this thread.
gs->errorQueue = make_shared<core::ErrorQueue>(gs->errorQueue->logger, gs->errorQueue->tracer, errorFlusher);
{
vector<pair<core::NameHash, u4>> changedMethodHashes;
for (auto &f : updates.updatedFiles) {
auto fref = gs->findFileByPath(f->path());
// We don't support new files on the fast path. This enforce failing indicates a bug in our fast/slow
// path logic in LSPPreprocessor.
ENFORCE(fref.exists());
ENFORCE(f->getFileHash() != nullptr);
if (fref.exists()) {
// Update to existing file on fast path
ENFORCE(fref.data(*gs).getFileHash() != nullptr);
const auto &oldMethodHashes = fref.data(*gs).getFileHash()->definitions.methodHashes;
const auto &newMethodHashes = f->getFileHash()->definitions.methodHashes;
// Both oldHash and newHash should have the same methods, since this is the fast path!
ENFORCE(validateMethodHashesHaveSameMethods(oldMethodHashes, newMethodHashes),
"definitionHash should have failed");
// Find which hashes changed. Note: methodHashes are sorted, so set_difference should work.
// This will insert two entries into `changedMethodHashes` for each changed method, but they will get
// deduped later.
set_difference(oldMethodHashes.begin(), oldMethodHashes.end(), newMethodHashes.begin(),
newMethodHashes.end(), inserter(changedMethodHashes, changedMethodHashes.begin()));
gs = core::GlobalState::replaceFile(move(gs), fref, f);
// If file doesn't have a typed: sigil, then we need to ensure it's typechecked using typed: false.
fref.data(*gs).strictLevel = pipeline::decideStrictLevel(*gs, fref, config->opts);
subset.emplace_back(fref);
}
}
changedHashes.reserve(changedMethodHashes.size());
for (auto &changedMethodHash : changedMethodHashes) {
changedHashes.push_back(changedMethodHash.first);
}
core::NameHash::sortAndDedupe(changedHashes);
}
int i = -1;
// N.B.: We'll iterate over the changed files, too, but it's benign if we re-add them since we dedupe `subset`.
for (auto &oldFile : gs->getFiles()) {
i++;
if (oldFile == nullptr) {
continue;
}
ENFORCE(oldFile->getFileHash() != nullptr);
const auto &oldHash = *oldFile->getFileHash();
vector<core::NameHash> intersection;
std::set_intersection(changedHashes.begin(), changedHashes.end(), oldHash.usages.sends.begin(),
oldHash.usages.sends.end(), std::back_inserter(intersection));
if (!intersection.empty()) {
auto ref = core::FileRef(i);
config->logger->debug("Added {} to update set as used a changed method",
!ref.exists() ? "" : ref.data(*gs).path());
subset.emplace_back(ref);
}
}
// Remove any duplicate files.
fast_sort(subset);
subset.resize(std::distance(subset.begin(), std::unique(subset.begin(), subset.end())));
config->logger->debug("Taking fast path");
ENFORCE(gs->errorQueue->isEmpty());
vector<ast::ParsedFile> updatedIndexed;
for (auto &f : subset) {
// TODO(jvilk): We don't need to re-index files that didn't change.
auto t = pipeline::indexOne(config->opts, *gs, f);
updatedIndexed.emplace_back(ast::ParsedFile{t.tree->deepCopy(), t.file});
updates.updatedFinalGSFileIndexes.push_back(move(t));
}
ENFORCE(gs->lspQuery.isEmpty());
auto resolved = pipeline::incrementalResolve(*gs, move(updatedIndexed), config->opts);
pipeline::typecheck(gs, move(resolved), config->opts, workers);
gs->lspTypecheckCount++;
return subset;
}
namespace {
pair<unique_ptr<core::GlobalState>, ast::ParsedFile>
updateFile(unique_ptr<core::GlobalState> gs, const shared_ptr<core::File> &file, const options::Options &opts) {
core::FileRef fref = gs->findFileByPath(file->path());
if (fref.exists()) {
gs = core::GlobalState::replaceFile(move(gs), fref, file);
} else {
fref = gs->enterFile(file);
}
fref.data(*gs).strictLevel = pipeline::decideStrictLevel(*gs, fref, opts);
return make_pair(move(gs), pipeline::indexOne(opts, *gs, fref));
}
} // namespace
bool LSPTypechecker::copyIndexed(WorkerPool &workers, const UnorderedSet<int> &ignore,
vector<ast::ParsedFile> &out) const {
auto &logger = *config->logger;
Timer timeit(logger, "slow_path.copy_indexes");
shared_ptr<ConcurrentBoundedQueue<int>> fileq = make_shared<ConcurrentBoundedQueue<int>>(indexed.size());
for (int i = 0; i < indexed.size(); i++) {
auto copy = i;
fileq->push(move(copy), 1);
}
const auto &epochManager = *gs->epochManager;
shared_ptr<BlockingBoundedQueue<vector<ast::ParsedFile>>> resultq =
make_shared<BlockingBoundedQueue<vector<ast::ParsedFile>>>(indexed.size());
workers.multiplexJob("copyParsedFiles", [fileq, resultq, &indexed = this->indexed, &ignore, &epochManager]() {
vector<ast::ParsedFile> threadResult;
int processedByThread = 0;
int job;
{
for (auto result = fileq->try_pop(job); !result.done(); result = fileq->try_pop(job)) {
if (result.gotItem()) {
processedByThread++;
// Stop if typechecking was canceled.
if (!epochManager.wasTypecheckingCanceled()) {
const auto &tree = indexed[job];
// Note: indexed entries for payload files don't have any contents.
if (tree.tree && !ignore.contains(tree.file.id())) {
threadResult.emplace_back(ast::ParsedFile{tree.tree->deepCopy(), tree.file});
}
}
}
}
}
if (processedByThread > 0) {
resultq->push(move(threadResult), processedByThread);
}
});
{
vector<ast::ParsedFile> threadResult;
out.reserve(indexed.size());
for (auto result = resultq->wait_pop_timed(threadResult, WorkerPool::BLOCK_INTERVAL(), logger); !result.done();
result = resultq->wait_pop_timed(threadResult, WorkerPool::BLOCK_INTERVAL(), logger)) {
if (result.gotItem()) {
for (auto © : threadResult) {
out.push_back(move(copy));
}
}
}
}
return !epochManager.wasTypecheckingCanceled();
}
bool LSPTypechecker::runSlowPath(LSPFileUpdates updates, WorkerPool &workers, bool cancelable) {
ENFORCE(this_thread::get_id() == typecheckerThreadId,
"runSlowPath can only be called from the typechecker thread.");
auto &logger = config->logger;
unique_ptr<ShowOperation> slowPathOp = make_unique<ShowOperation>(*config, "SlowPathBlocking", "Typechecking...");
Timer timeit(logger, "slow_path");
ENFORCE(!updates.canTakeFastPath || config->disableFastPath);
ENFORCE(updates.updatedGS.has_value());
if (!updates.updatedGS.has_value()) {
Exception::raise("runSlowPath called with an update that lacks an updated global state.");
}
logger->debug("Taking slow path");
auto finalGS = move(updates.updatedGS.value());
const u4 epoch = updates.epoch;
// Replace error queue with one that is owned by this thread.
finalGS->errorQueue = make_shared<core::ErrorQueue>(finalGS->errorQueue->logger, finalGS->errorQueue->tracer,
make_shared<ErrorFlusherLSP>(epoch, errorReporter));
auto &epochManager = *finalGS->epochManager;
// Note: Commits can only be canceled if this edit is cancelable, LSP is running across multiple threads, and the
// cancelation feature is enabled.
const bool committed = epochManager.tryCommitEpoch(*finalGS, epoch, cancelable, preemptManager, [&]() -> void {
UnorderedSet<int> updatedFiles;
vector<ast::ParsedFile> indexedCopies;
// Index the updated files using finalGS.
{
core::UnfreezeFileTable fileTableAccess(*finalGS);
for (auto &file : updates.updatedFiles) {
auto pair = updateFile(move(finalGS), file, config->opts);
finalGS = move(pair.first);
auto &ast = pair.second;
if (ast.tree) {
indexedCopies.emplace_back(ast::ParsedFile{ast.tree->deepCopy(), ast.file});
updatedFiles.insert(ast.file.id());
}
updates.updatedFinalGSFileIndexes.push_back(move(ast));
}
}
// Before making preemption or cancelation possible, pre-commit the changes from this slow path so that
// preempted queries can use them and the code after this lambda can assume that this step happened.
updates.updatedGS = move(finalGS);
commitFileUpdates(updates, cancelable);
// We use `gs` rather than the moved `finalGS` from this point forward.
// Copy the indexes of unchanged files.
if (!copyIndexed(workers, updatedFiles, indexedCopies)) {
// Canceled.
return;
}
ENFORCE(gs->lspQuery.isEmpty());
if (gs->sleepInSlowPath) {
Timer::timedSleep(3000ms, *logger, "slow_path.resolve.sleep");
}
auto maybeResolved = pipeline::resolve(gs, move(indexedCopies), config->opts, workers, config->skipConfigatron);
if (!maybeResolved.hasResult()) {
return;
}
auto &resolved = maybeResolved.result();
for (auto &tree : resolved) {
ENFORCE(tree.file.exists());
}
if (gs->sleepInSlowPath) {
Timer::timedSleep(3000ms, *logger, "slow_path.typecheck.sleep");
}
// Inform the fast path that this global state is OK for typechecking as resolution has completed.
gs->lspTypecheckCount++;
// TODO(jvilk): Remove conditional once initial typecheck is preemptible.
if (cancelable) {
// Inform users that Sorbet should be responsive now.
// Explicitly end previous operation before beginning next operation.
slowPathOp = nullptr;
slowPathOp = make_unique<ShowOperation>(*config, "SlowPathNonBlocking", "Typechecking in background");
}
// Report how long the slow path blocks preemption.
timeit.clone("slow_path.blocking_time");
// [Test only] Wait for a preemption if one is expected.
while (updates.preemptionsExpected > 0) {
while (!preemptManager->tryRunScheduledPreemptionTask(*gs)) {
Timer::timedSleep(1ms, *logger, "slow_path.expected_preemption.sleep");
}
updates.preemptionsExpected--;
}
// [Test only] Wait for a cancellation if one is expected.
if (updates.cancellationExpected) {
while (!epochManager.wasTypecheckingCanceled()) {
Timer::timedSleep(1ms, *logger, "slow_path.expected_cancellation.sleep");
}
return;
}
pipeline::typecheck(gs, move(resolved), config->opts, workers, cancelable, preemptManager);
});
// Note: `gs` now holds the value of `finalGS`.
gs->lspQuery = core::lsp::Query::noQuery();
if (committed) {
prodCategoryCounterInc("lsp.updates", "slowpath");
timeit.setTag("canceled", "false");
// No need to keep around cancelation state!
cancellationUndoState = nullptr;
logger->debug("[Typechecker] Typecheck run for epoch {} successfully finished.", updates.epoch);
} else {
prodCategoryCounterInc("lsp.updates", "slowpath_canceled");
timeit.setTag("canceled", "true");
// Update responsible will use state in `cancellationUndoState` to restore typechecker to the point before
// this slow path.
ENFORCE(cancelable);
logger->debug("[Typechecker] Typecheck run for epoch {} was canceled.", updates.epoch);
}
return committed;
}
void LSPTypechecker::commitFileUpdates(LSPFileUpdates &updates, bool couldBeCanceled) {
// The fast path cannot be canceled.
ENFORCE(!(updates.canTakeFastPath && couldBeCanceled));
if (couldBeCanceled) {
ENFORCE(updates.updatedGS.has_value());
cancellationUndoState = make_unique<UndoState>(move(gs), std::move(indexedFinalGS), updates.epoch);
}
// Clear out state associated with old finalGS.
if (!updates.canTakeFastPath) {
indexedFinalGS.clear();
}
int i = -1;
ENFORCE(updates.updatedFileIndexes.size() == updates.updatedFiles.size());
for (auto &ast : updates.updatedFileIndexes) {
i++;
const int id = ast.file.id();
if (id >= indexed.size()) {
indexed.resize(id + 1);
}
if (cancellationUndoState != nullptr) {
// Move the evicted values before they get replaced.
cancellationUndoState->recordEvictedState(move(indexed[id]));
}
indexed[id] = move(ast);
}
for (auto &ast : updates.updatedFinalGSFileIndexes) {
indexedFinalGS[ast.file.id()] = move(ast);
}
if (updates.updatedGS.has_value()) {
ENFORCE(!updates.canTakeFastPath);
gs = move(updates.updatedGS.value());
} else {
ENFORCE(updates.canTakeFastPath);
}
}
unique_ptr<core::GlobalState> LSPTypechecker::destroy() {
return move(gs);
}
namespace {
void tryApplyLocalVarSaver(const core::GlobalState &gs, vector<ast::ParsedFile> &indexedCopies) {
if (gs.lspQuery.kind != core::lsp::Query::Kind::VAR) {
return;
}
for (auto &t : indexedCopies) {
LocalVarSaver localVarSaver;
core::Context ctx(gs, core::Symbols::root(), t.file);
t.tree = ast::TreeMap::apply(ctx, localVarSaver, move(t.tree));
}
}
void tryApplyDefLocSaver(const core::GlobalState &gs, vector<ast::ParsedFile> &indexedCopies) {
if (gs.lspQuery.kind != core::lsp::Query::Kind::LOC && gs.lspQuery.kind != core::lsp::Query::Kind::SYMBOL) {
return;
}
for (auto &t : indexedCopies) {
DefLocSaver defLocSaver;
core::Context ctx(gs, core::Symbols::root(), t.file);
t.tree = ast::TreeMap::apply(ctx, defLocSaver, move(t.tree));
}
}
} // namespace
LSPQueryResult LSPTypechecker::query(const core::lsp::Query &q, const std::vector<core::FileRef> &filesForQuery,
WorkerPool &workers) const {
ENFORCE(this_thread::get_id() == typecheckerThreadId, "Typechecker can only be used from the typechecker thread.");
// We assume gs is a copy of initialGS, which has had the inferencer & resolver run.
ENFORCE(gs->lspTypecheckCount > 0,
"Tried to run a query with a GlobalState object that never had inferencer and resolver runs.");
// Replace error queue with one that is owned by this thread.
// TODO: Replace with an error flusher for queries
gs->errorQueue = make_shared<core::ErrorQueue>(gs->errorQueue->logger, gs->errorQueue->tracer,
make_shared<ErrorFlusherLSP>(0, errorReporter));
gs->errorQueue->ignoreFlushes = true;
Timer timeit(config->logger, "query");
prodCategoryCounterInc("lsp.updates", "query");
ENFORCE(gs->errorQueue->isEmpty());
ENFORCE(gs->lspQuery.isEmpty());
gs->lspQuery = q;
auto resolved = getResolved(filesForQuery);
tryApplyDefLocSaver(*gs, resolved);
tryApplyLocalVarSaver(*gs, resolved);
pipeline::typecheck(gs, move(resolved), config->opts, workers);
auto errorsAndQueryResponses = gs->errorQueue->drainWithQueryResponses();
gs->lspTypecheckCount++;
gs->lspQuery = core::lsp::Query::noQuery();
// Drops any errors discovered during the query on the floor.
return LSPQueryResult{move(errorsAndQueryResponses.second)};
}
LSPFileUpdates LSPTypechecker::getNoopUpdate(std::vector<core::FileRef> frefs) const {
LSPFileUpdates noop;
noop.canTakeFastPath = true;
// Epoch isn't important for this update.
noop.epoch = 0;
for (auto fref : frefs) {
ENFORCE(fref.exists());
ENFORCE(fref.id() < indexed.size());
auto &index = indexed[fref.id()];
noop.updatedFileIndexes.push_back({index.tree->deepCopy(), index.file});
noop.updatedFiles.push_back(gs->getFiles()[fref.id()]);
}
return noop;
}
std::vector<std::unique_ptr<core::Error>> LSPTypechecker::retypecheck(vector<core::FileRef> frefs,
WorkerPool &workers) const {
LSPFileUpdates updates = getNoopUpdate(move(frefs));
auto errorCollector = make_shared<ErrorCollector>();
runFastPath(updates, workers, errorCollector);
return move(errorCollector->collectedErrors);
}
const ast::ParsedFile &LSPTypechecker::getIndexed(core::FileRef fref) const {
const auto id = fref.id();
auto treeFinalGS = indexedFinalGS.find(id);
if (treeFinalGS != indexedFinalGS.end()) {
return treeFinalGS->second;
}
ENFORCE(id < indexed.size());
return indexed[id];
}
vector<ast::ParsedFile> LSPTypechecker::getResolved(const vector<core::FileRef> &frefs) const {
ENFORCE(this_thread::get_id() == typecheckerThreadId, "Typechecker can only be used from the typechecker thread.");
vector<ast::ParsedFile> updatedIndexed;
for (auto fref : frefs) {
auto &indexed = getIndexed(fref);
if (indexed.tree) {
updatedIndexed.emplace_back(ast::ParsedFile{indexed.tree->deepCopy(), indexed.file});
}
}
return pipeline::incrementalResolve(*gs, move(updatedIndexed), config->opts);
}
const core::GlobalState &LSPTypechecker::state() const {
ENFORCE(this_thread::get_id() == typecheckerThreadId, "Typechecker can only be used from the typechecker thread.");
return *gs;
}
void LSPTypechecker::changeThread() {
auto newId = this_thread::get_id();
ENFORCE(newId != typecheckerThreadId);
typecheckerThreadId = newId;
}
LSPTypecheckerDelegate::LSPTypecheckerDelegate(WorkerPool &workers, LSPTypechecker &typechecker)
: typechecker(typechecker), workers(workers) {}
void LSPTypecheckerDelegate::typecheckOnFastPath(LSPFileUpdates updates,
vector<unique_ptr<Timer>> diagnosticLatencyTimers) {
if (!updates.canTakeFastPath) {
Exception::raise("Tried to typecheck a slow path edit on the fast path.");
}
auto committed = typechecker.typecheck(move(updates), workers, move(diagnosticLatencyTimers));
// Fast path edits can't be canceled.
ENFORCE(committed);
}
std::vector<std::unique_ptr<core::Error>> LSPTypecheckerDelegate::retypecheck(std::vector<core::FileRef> frefs) const {
return typechecker.retypecheck(frefs, workers);
}
LSPQueryResult LSPTypecheckerDelegate::query(const core::lsp::Query &q,
const std::vector<core::FileRef> &filesForQuery) const {
return typechecker.query(q, filesForQuery, workers);
}
const ast::ParsedFile &LSPTypecheckerDelegate::getIndexed(core::FileRef fref) const {
return typechecker.getIndexed(fref);
}
std::vector<ast::ParsedFile> LSPTypecheckerDelegate::getResolved(const std::vector<core::FileRef> &frefs) const {
return typechecker.getResolved(frefs);
}
const core::GlobalState &LSPTypecheckerDelegate::state() const {
return typechecker.state();
}
} // namespace sorbet::realmain::lsp
| 43.369159 | 120 | 0.64307 | [
"object",
"vector"
] |
ed6944f4ac10b0ae8ca46a362b917179381ea8ae | 12,901 | hpp | C++ | include/cascade/object.hpp | yw2399/cascade | 5aa0e750851affc0583bea125fa5d6714ca07d97 | [
"BSD-3-Clause"
] | 21 | 2020-09-07T20:57:00.000Z | 2022-03-30T18:18:37.000Z | include/cascade/object.hpp | yw2399/cascade | 5aa0e750851affc0583bea125fa5d6714ca07d97 | [
"BSD-3-Clause"
] | 17 | 2020-09-10T11:09:08.000Z | 2021-12-28T04:56:23.000Z | include/cascade/object.hpp | yw2399/cascade | 5aa0e750851affc0583bea125fa5d6714ca07d97 | [
"BSD-3-Clause"
] | 17 | 2020-09-10T11:00:13.000Z | 2022-02-26T22:00:27.000Z | #pragma once
#include <chrono>
#include <iostream>
#include <map>
#include <memory>
#include <string.h>
#include <string>
#include <time.h>
#include <vector>
#include <optional>
#include <tuple>
#include <derecho/conf/conf.hpp>
#include <derecho/core/derecho.hpp>
#include <derecho/mutils-serialization/SerializationSupport.hpp>
#include <derecho/persistent/Persistent.hpp>
#include <cascade/cascade.hpp>
using std::cout;
using std::endl;
using namespace persistent;
using namespace std::chrono_literals;
namespace derecho{
namespace cascade{
class Blob : public mutils::ByteRepresentable {
public:
const char* bytes;
std::size_t size;
bool is_emplaced;
// constructor - copy to own the data
Blob(const char* const b, const decltype(size) s);
Blob(const char* b, const decltype(size) s, bool temporary);
// copy constructor - copy to own the data
Blob(const Blob& other);
// move constructor - accept the memory from another object
Blob(Blob&& other);
// default constructor - no data at all
Blob();
// destructor
virtual ~Blob();
// move evaluator:
Blob& operator=(Blob&& other);
// copy evaluator:
Blob& operator=(const Blob& other);
// serialization/deserialization supports
std::size_t to_bytes(char* v) const;
std::size_t bytes_size() const;
void post_object(const std::function<void(char const* const, std::size_t)>& f) const;
void ensure_registered(mutils::DeserializationManager&) {}
static std::unique_ptr<Blob> from_bytes(mutils::DeserializationManager*, const char* const v);
static mutils::context_ptr<Blob> from_bytes_noalloc(
mutils::DeserializationManager* ctx,
const char* const v);
static mutils::context_ptr<Blob> from_bytes_noalloc_const(
mutils::DeserializationManager* ctx,
const char* const v);
};
#define INVALID_UINT64_OBJECT_KEY (0xffffffffffffffffLLU)
class ObjectWithUInt64Key : public mutils::ByteRepresentable,
public ICascadeObject<uint64_t>,
public IKeepTimestamp,
public IVerifyPreviousVersion
#ifdef ENABLE_EVALUATION
, public IHasMessageID
#endif
{
public:
#ifdef ENABLE_EVALUATION
mutable uint64_t message_id;
#endif
mutable persistent::version_t version;
mutable uint64_t timestamp_us;
mutable persistent::version_t previous_version; // previous version, INVALID_VERSION for the first version
mutable persistent::version_t previous_version_by_key; // previous version by key, INVALID_VERSION for the first value of the key.
uint64_t key; // object_id
Blob blob; // the object
// bool operator==(const ObjectWithUInt64Key& other);
// constructor 0 : copy constructor
ObjectWithUInt64Key(const uint64_t _key,
const Blob& _blob);
// constructor 0.5 : copy/emplace constructor
ObjectWithUInt64Key(
#ifdef ENABLE_EVALUATION
const uint64_t _message_id,
#endif
const persistent::version_t _version,
const uint64_t _timestamp_us,
const persistent::version_t _previous_version,
const persistent::version_t _previous_version_by_key,
const uint64_t _key,
const Blob& _blob,
bool is_emplaced = false);
// constructor 1 : copy constructor
ObjectWithUInt64Key(const uint64_t _key,
const char* const _b,
const std::size_t _s);
// constructor 1.5 : copy constructor
ObjectWithUInt64Key(
#ifdef ENABLE_EVALUATION
const uint64_t _message_id,
#endif
const persistent::version_t _version,
const uint64_t _timestamp_us,
const persistent::version_t _previous_version,
const persistent::version_t _previous_version_by_key,
const uint64_t _key,
const char* const _b,
const std::size_t _s);
// TODO: we need a move version for the deserializer.
// constructor 2 : move constructor
ObjectWithUInt64Key(ObjectWithUInt64Key&& other);
// constructor 3 : copy constructor
ObjectWithUInt64Key(const ObjectWithUInt64Key& other);
// constructor 4 : default invalid constructor
ObjectWithUInt64Key();
virtual const uint64_t& get_key_ref() const override;
virtual bool is_null() const override;
virtual bool is_valid() const override;
virtual void set_version(persistent::version_t ver) const override;
virtual persistent::version_t get_version() const override;
virtual void set_timestamp(uint64_t ts_us) const override;
virtual uint64_t get_timestamp() const override;
virtual void set_previous_version(persistent::version_t prev_ver, persistent::version_t prev_ver_by_key) const override;
virtual bool verify_previous_version(persistent::version_t prev_ver, persistent::version_t prev_ver_by_key) const override;
#ifdef ENABLE_EVALUATION
virtual void set_message_id(uint64_t id) const override;
virtual uint64_t get_message_id() const override;
#endif
// Deprecated: the default no_alloc deserializers are NOT zero-copy!!!
// DEFAULT_SERIALIZATION_SUPPORT(ObjectWithUInt64Key, version, timestamp_us, previous_version, previous_version_by_key, key, blob);
std::size_t to_bytes(char* v) const;
std::size_t bytes_size() const;
void post_object(const std::function<void(char const* const, std::size_t)>& f) const;
void ensure_registerd(mutils::DeserializationManager&) {}
static std::unique_ptr<ObjectWithUInt64Key> from_bytes(mutils::DeserializationManager*, const char* const v);
static mutils::context_ptr<ObjectWithUInt64Key> from_bytes_noalloc(
mutils::DeserializationManager* ctx,
const char* const v);
static mutils::context_ptr<const ObjectWithUInt64Key> from_bytes_noalloc_const(
mutils::DeserializationManager* ctx,
const char* const v);
// IK and IV for volatile cascade store
static uint64_t IK;
static ObjectWithUInt64Key IV;
};
inline std::ostream& operator<<(std::ostream& out, const Blob& b) {
out << "[size:" << b.size << ", data:" << std::hex;
if(b.size > 0) {
uint32_t i = 0;
for(i = 0; i < 8 && i < b.size; i++) {
out << " " << b.bytes[i];
}
if(i < b.size) {
out << "...";
}
}
out << std::dec << "]";
return out;
}
inline std::ostream& operator<<(std::ostream& out, const ObjectWithUInt64Key& o) {
out << "ObjectWithUInt64Key{ver: 0x" << std::hex << o.version << std::dec
<< ", ts(us): " << o.timestamp_us
<< ", prev_ver: " << std::hex << o.previous_version << std::dec
<< ", prev_ver_by_key: " << std::hex << o.previous_version_by_key << std::dec
<< ", id:" << o.key
<< ", data:" << o.blob << "}";
return out;
}
class ObjectWithStringKey : public mutils::ByteRepresentable,
public ICascadeObject<std::string>,
public IKeepTimestamp,
public IVerifyPreviousVersion
#ifdef ENABLE_EVALUATION
,public IHasMessageID
#endif
{
public:
#ifdef ENABLE_EVALUATION
mutable uint64_t message_id;
#endif
mutable persistent::version_t version; // object version
mutable uint64_t timestamp_us; // timestamp in microsecond
mutable persistent::version_t previous_version; // previous version, INVALID_VERSION for the first version.
mutable persistent::version_t previous_version_by_key; // previous version by key, INVALID_VERSION for the first value of the key.
std::string key; // object_id
Blob blob; // the object data
// bool operator==(const ObjectWithStringKey& other);
// constructor 0 : copy constructor
ObjectWithStringKey(const std::string& _key,
const Blob& _blob);
// constructor 0.5 : copy/in-place constructor
ObjectWithStringKey(
#ifdef ENABLE_EVALUATION
const uint64_t message_id,
#endif
const persistent::version_t _version,
const uint64_t _timestamp_us,
const persistent::version_t _previous_version,
const persistent::version_t _previous_version_by_key,
const std::string& _key,
const Blob& _blob,
bool is_emplaced = false);
// constructor 1 : copy consotructor
ObjectWithStringKey(const std::string& _key,
const char* const _b,
const std::size_t _s);
// constructor 1.5 : copy constructor
ObjectWithStringKey(
#ifdef ENABLE_EVALUATION
const uint64_t message_id,
#endif
const persistent::version_t _version,
const uint64_t _timestamp_us,
const persistent::version_t _previous_version,
const persistent::version_t _previous_version_by_key,
const std::string& _key,
const char* const _b,
const std::size_t _s);
// TODO: we need a move version for the deserializer.
// constructor 2 : move constructor
ObjectWithStringKey(ObjectWithStringKey&& other);
// constructor 3 : copy constructor
ObjectWithStringKey(const ObjectWithStringKey& other);
// constructor 4 : default invalid constructor
ObjectWithStringKey();
virtual const std::string& get_key_ref() const override;
virtual bool is_null() const override;
virtual bool is_valid() const override;
virtual void set_version(persistent::version_t ver) const override;
virtual persistent::version_t get_version() const override;
virtual void set_timestamp(uint64_t ts_us) const override;
virtual uint64_t get_timestamp() const override;
virtual void set_previous_version(persistent::version_t prev_ver, persistent::version_t perv_ver_by_key) const override;
virtual bool verify_previous_version(persistent::version_t prev_ver, persistent::version_t perv_ver_by_key) const override;
#ifdef ENABLE_EVALUATION
virtual void set_message_id(uint64_t id) const override;
virtual uint64_t get_message_id() const override;
#endif
// DEFAULT_SERIALIZATION_SUPPORT(ObjectWithStringKey, version, timestamp_us, previous_version, previous_version_by_key, key, blob);
std::size_t to_bytes(char* v) const;
std::size_t bytes_size() const;
void post_object(const std::function<void(char const* const, std::size_t)>& f) const;
void ensure_registerd(mutils::DeserializationManager&) {}
static std::unique_ptr<ObjectWithStringKey> from_bytes(mutils::DeserializationManager*, const char* const v);
static mutils::context_ptr<ObjectWithStringKey> from_bytes_noalloc(
mutils::DeserializationManager* ctx,
const char* const v);
static mutils::context_ptr<const ObjectWithStringKey> from_bytes_noalloc_const(
mutils::DeserializationManager* ctx,
const char* const v);
// IK and IV for volatile cascade store
static std::string IK;
static ObjectWithStringKey IV;
};
inline std::ostream& operator<<(std::ostream& out, const ObjectWithStringKey& o) {
out << "ObjectWithStringKey{"
#ifdef ENABLE_EVALUATION
<< "msg_id: " << o.message_id
#endif
<< "ver: 0x" << std::hex << o.version << std::dec
<< ", ts: " << o.timestamp_us
<< ", prev_ver: " << std::hex << o.previous_version << std::dec
<< ", prev_ver_by_key: " << std::hex << o.previous_version_by_key << std::dec
<< ", id:" << o.key
<< ", data:" << o.blob << "}";
return out;
}
/**
template <typename KT, typename VT, KT* IK, VT* IV>
std::enable_if_t<std::disjunction<std::is_same<ObjectWithStringKey,VT>,std::is_same<ObjectWithStringKey,VT>>::value, VT> create_null_object_cb(const KT& key) {
return VT(key,Blob{});
}
**/
} // namespace cascade
} // namespace derecho
| 39.57362 | 159 | 0.627316 | [
"object",
"vector"
] |
ed6c321e554a5b77731a84806dc0430e0f423388 | 2,261 | cpp | C++ | src/Simulation.cpp | IreneGR92/Group-augmentation-Basic | 9225c44e6608981d25b45e5575fd9922a358d1e0 | [
"MIT"
] | 1 | 2018-12-22T08:49:09.000Z | 2018-12-22T08:49:09.000Z | src/Simulation.cpp | IreneGR92/Group-augmentation-Basic | 9225c44e6608981d25b45e5575fd9922a358d1e0 | [
"MIT"
] | null | null | null | src/Simulation.cpp | IreneGR92/Group-augmentation-Basic | 9225c44e6608981d25b45e5575fd9922a358d1e0 | [
"MIT"
] | 1 | 2018-12-22T08:49:10.000Z | 2018-12-22T08:49:10.000Z |
#include "Simulation.h"
#include <iostream>
#include <cassert>
#include "Simulation.h"
#include "stats/Statistics.h"
#include <vector>
Simulation::Simulation(const int replica)
: replica(replica),
population(),
parameters(Parameters::instance()) {
}
void Simulation::run() {
// Output file
auto *statistics = new Statistics();
statistics->calculateStatistics(population);
statistics->printHeadersToConsole();
statistics->printToConsole(generation, population.getDeaths());
// statistics->printToFile(replica, generation, population.getDeaths(), newBreederFloater, newBreederHelper, inheritance);
delete statistics;
for (generation = 1; generation <= Parameters::instance()->getNumGenerations(); generation++) {
statistics = new Statistics();
population.reset();
population.reassignFloaters();
population.disperse(generation);
population.help();
population.survival();
if (generation % parameters->getSkip() == 0) {
//Calculate stats
statistics->calculateStatistics(population);
//Print last generation
if (generation == 10000 ||
generation == 25000 ||
generation == parameters->getNumGenerations() / 2 ||
generation == parameters->getNumGenerations()) {
statistics->printToFileLastGeneration(this, population);
}
}
population.mortality();
population.newBreeder();
// Print main file (separately since we need values of deaths, newBreederFloater, newBreederHelper and inheritance to be calculated)
if (generation % parameters->getSkip() == 0) {
statistics->printToConsole(generation, population.getDeaths());
statistics->printToFile(replica, generation, population.getDeaths(), population.getNewBreederFloater(), population.getNewBreederHelper(), population.getInheritance());
}
delete statistics;
population.increaseAge();
population.reproduce(generation);
}
}
const int Simulation::getReplica() const {
return replica;
}
int Simulation::getGeneration() const {
return generation;
}
| 25.988506 | 179 | 0.647059 | [
"vector"
] |
ed6fc87a737c6978893b2bbc8a71a65d17bd0787 | 3,731 | cpp | C++ | src/planner/vectorfield/MoveEndEffectorOffsetVectorField.cpp | personalrobotics/r3 | 1303e3f3ef99a0c2249abc7415d19113f0026565 | [
"BSD-3-Clause"
] | 181 | 2016-04-22T15:11:23.000Z | 2022-03-26T12:51:08.000Z | src/planner/vectorfield/MoveEndEffectorOffsetVectorField.cpp | personalrobotics/r3 | 1303e3f3ef99a0c2249abc7415d19113f0026565 | [
"BSD-3-Clause"
] | 514 | 2016-04-20T04:29:51.000Z | 2022-02-10T19:46:21.000Z | src/planner/vectorfield/MoveEndEffectorOffsetVectorField.cpp | personalrobotics/r3 | 1303e3f3ef99a0c2249abc7415d19113f0026565 | [
"BSD-3-Clause"
] | 31 | 2017-03-17T09:53:02.000Z | 2022-03-23T10:35:05.000Z | #include "aikido/planner/vectorfield/MoveEndEffectorOffsetVectorField.hpp"
#include <dart/dynamics/BodyNode.hpp>
#include <dart/math/MathTypes.hpp>
#include <dart/optimizer/Function.hpp>
#include <dart/optimizer/Problem.hpp>
#include "aikido/planner/vectorfield/VectorFieldUtil.hpp"
#include "detail/VectorFieldPlannerExceptions.hpp"
namespace aikido {
namespace planner {
namespace vectorfield {
//==============================================================================
MoveEndEffectorOffsetVectorField::MoveEndEffectorOffsetVectorField(
aikido::statespace::dart::ConstMetaSkeletonStateSpacePtr stateSpace,
::dart::dynamics::MetaSkeletonPtr metaskeleton,
::dart::dynamics::ConstBodyNodePtr bn,
const Eigen::Vector3d& direction,
double minDistance,
double maxDistance,
double positionTolerance,
double angularTolerance,
double maxStepSize,
double jointLimitPadding)
: BodyNodePoseVectorField(
stateSpace, metaskeleton, bn, maxStepSize, jointLimitPadding)
, mDirection(direction)
, mMinDistance(minDistance)
, mMaxDistance(maxDistance)
, mPositionTolerance(positionTolerance)
, mAngularTolerance(angularTolerance)
, mStartPose(bn->getTransform())
{
if (mMinDistance < 0)
throw std::invalid_argument("Minimum distance must be non-negative.");
if (mDirection.norm() == 0)
throw std::invalid_argument("Direction must be non-zero");
if (mMaxDistance < mMinDistance)
throw std::invalid_argument("Max distance is less than minimum distance.");
if (mPositionTolerance < 0)
throw std::invalid_argument("Position tolerance is negative");
if (mAngularTolerance < 0)
throw std::invalid_argument("Angular tolerance is negative");
// Normalize the direction vector
mDirection.normalize();
}
//==============================================================================
bool MoveEndEffectorOffsetVectorField::evaluateCartesianVelocity(
const Eigen::Isometry3d& pose, Eigen::Vector6d& cartesianVelocity) const
{
using aikido::planner::vectorfield::computeGeodesicError;
using ::dart::math::logMap;
Eigen::Vector6d desiredTwist = computeGeodesicTwist(pose, mStartPose);
desiredTwist.tail<3>() = mDirection;
cartesianVelocity = desiredTwist;
return true;
}
//==============================================================================
VectorFieldPlannerStatus
MoveEndEffectorOffsetVectorField::evaluateCartesianStatus(
const Eigen::Isometry3d& pose) const
{
using aikido::planner::vectorfield::computeGeodesicError;
// Check for deviation from the straight-line trajectory.
const Eigen::Vector4d geodesicError = computeGeodesicError(mStartPose, pose);
const double orientationError = geodesicError[0];
const Eigen::Vector3d positionError = geodesicError.tail<3>();
double movedDistance = positionError.transpose() * mDirection;
double positionDeviation
= (positionError - movedDistance * mDirection).norm();
if (fabs(orientationError) > mAngularTolerance)
{
dtwarn << "Deviated from orientation constraint.";
return VectorFieldPlannerStatus::TERMINATE;
}
if (positionDeviation > mPositionTolerance)
{
dtwarn << "Deviated from straight line constraint.";
return VectorFieldPlannerStatus::TERMINATE;
}
// if larger than max distance, terminate
// if larger than min distance, cache and continue
// if smaller than min distance, continue
if (movedDistance > mMaxDistance)
{
return VectorFieldPlannerStatus::TERMINATE;
}
else if (movedDistance >= mMinDistance)
{
return VectorFieldPlannerStatus::CACHE_AND_CONTINUE;
}
return VectorFieldPlannerStatus::CONTINUE;
}
} // namespace vectorfield
} // namespace planner
} // namespace aikido
| 33.918182 | 80 | 0.713482 | [
"vector"
] |
142e4bd6a18871c1da05fed946f159202ae6ab20 | 10,367 | cpp | C++ | src/db/timing/spef/net_parasitics.cpp | lbz007/rectanglequery | 59d6eb007bf65480fa3e9245542d0b6071f81831 | [
"BSD-3-Clause"
] | null | null | null | src/db/timing/spef/net_parasitics.cpp | lbz007/rectanglequery | 59d6eb007bf65480fa3e9245542d0b6071f81831 | [
"BSD-3-Clause"
] | null | null | null | src/db/timing/spef/net_parasitics.cpp | lbz007/rectanglequery | 59d6eb007bf65480fa3e9245542d0b6071f81831 | [
"BSD-3-Clause"
] | null | null | null | /**
* @file net_parasitics.cpp
* @date 2020-11-02
* @brief
*
* Copyright (C) 2020 NIIC EDA
*
* All rights reserved.
*
* This software may be modified and distributed under the terms
*
* of the BSD license. See the LICENSE file for details.
*/
#include "db/timing/spef/net_parasitics.h"
#include <iostream>
#include <map>
#include <unordered_set>
#include "db/core/db.h"
#include "db/core/timing.h"
#include "util/stream.h"
#include "util/util_mem.h"
#ifndef NDEBUG
extern uint32_t net_with_bid_;
extern uint32_t valid_net_;
extern uint32_t net_with_loop_;
extern uint32_t res_number;
extern uint32_t xcap_number;
#endif
namespace open_edi {
namespace db {
static const uint32_t RESERVED_SIZE = 32;
NetParasitics::NetParasitics()
: NetParasitics::BaseType(),
net_id_(UNINIT_OBJECT_ID),
container_id_(UNINIT_OBJECT_ID),
total_cap_(0.0) {
setObjectType(ObjectType::kObjectTypeNetParasitics);
}
NetParasitics::~NetParasitics() {
}
DNetParasitics::DNetParasitics()
: NetParasitics() {
gcaps_.reserve(RESERVED_SIZE);
xcaps_.reserve(RESERVED_SIZE);
resistors_.reserve(2 * RESERVED_SIZE);
node_coordinates_ = nullptr;
setObjectType(ObjectType::kObjectTypeDNetParasitics);
}
void DNetParasitics::addCouplingCap(NodeID this_node, Net* that_net, NodeID that_node,
float capValue) {
Timing *timingdb = getTimingLib();
if (timingdb) {
xcaps_.push_back(ParasiticXCap(this_node, that_net, that_node, capValue));
}
}
void DNetParasitics::addResistor(NodeID node1Id, NodeID node2Id, float resValue) {
Timing *timingdb = getTimingLib();
if (timingdb) {
resistors_.push_back(ParasiticResistor(node1Id, node2Id, resValue));
}
}
void DNetParasitics::postProcess() {
gcaps_.shrink_to_fit();
xcaps_.shrink_to_fit();
resistors_.shrink_to_fit();
if (node_coordinates_)
node_coordinates_->shrink_to_fit();
}
DNetParasitics::~DNetParasitics() {
destroy();
}
void DNetParasitics::setNodeCoordinate(NodeID id, float x, float y) {
if (node_coordinates_ == nullptr)
node_coordinates_ = new std::vector<NodeCoordinate>();
int request_size = id + 1;
if (request_size > node_coordinates_->capacity())
node_coordinates_->reserve(request_size * 1.5);
if (request_size > node_coordinates_->size())
node_coordinates_->resize(request_size);
(*node_coordinates_)[id].x = x;
(*node_coordinates_)[id].y = y;
}
void DNetParasitics::scale(float cap_scale, float res_scal, float /*induct_scale*/) {
for (auto& cap : gcaps_)
cap *= cap_scale;
for (auto& xcap : xcaps_)
xcap.setCapacitance(xcap.getCapacitance() * cap_scale);
for (auto& res : resistors_) {
res.setResistance(res.getResistance() * res_scal);
}
}
void DNetParasitics::setNetId(ObjectId netId, PinIdMap &pin_id_map) {
NetParasitics::setNetId(netId);
auto net = Object::addr<Net>(netId);
auto pin_array = net->getPinArray();
Timing *timingdb = getTimingLib();
if (timingdb && pin_array) {
for (auto pin_id : (*pin_array)) {
auto pin_ptr = Object::addr<Pin>(pin_id);
// DUMMY_CAP for now, will set cap val later
auto id = addGroundCap(DUMMY_CAP);
pin_id_map[pin_ptr] = id;
}
}
}
void DNetParasitics::destroy() {
if (node_coordinates_) {
node_coordinates_->clear();
delete node_coordinates_;
node_coordinates_ = nullptr;
}
}
RNetParasitics::RNetParasitics()
: NetParasitics(),
c2_(0.0),
r1_(0.0),
c1_(0.0) {
setObjectType(ObjectType::kObjectTypeRNetParasitics);
}
/**
* @brief Construct a new DNetGraphProcessor::DNetGraphProcessor object
*
* @param dnet
*/
DNetGraphProcessor::DNetGraphProcessor(const DNetParasitics &dnet) {
// build cpas vector
auto gcaps = dnet.getGroundCaps();
caps_.reserve(gcaps.size());
for (auto cap : gcaps) {
caps_.push_back(cap);
}
// build coordinates vector
auto node_coordinates = dnet.getNodeCoordinates();
if (node_coordinates) {
coordinates_.reserve(node_coordinates->size());
for (auto coordinate : *node_coordinates) {
coordinates_.push_back(coordinate);
}
}
// handle pin node and add out and bidir to roots
auto net = Object::addr<Net>(dnet.getNetId());
auto pin_array = net->getPinArray();
NodeID node_id = 0;
if (pin_array) {
for (const auto &pin_id : (*pin_array)) {
auto pin = Object::addr<Pin>(pin_id);
if (pin->getDirection() == SignalDirection::kOutput ||
pin->getDirection() == SignalDirection::kInout) {
roots_.push_back(node_id);
}
pin_to_id_[pin] = node_id;
++node_id;
}
}
// build adjacent_map_
auto &&resistors = dnet.getResistors();
for (const auto &r : resistors) {
NodeID node1_id = r.getNode1Id();
NodeID node2_id = r.getNode2Id();
addAdjacentEdge(node1_id, &r);
addAdjacentEdge(node2_id, &r);
}
}
void DNetGraphProcessor::addAdjacentEdge(NodeID from, const ParasiticResistor *resistance) {
auto iter = adjacent_map_.find(from);
if (iter == adjacent_map_.end()) {
adjacent_map_[from] = {resistance};
} else {
iter->second.push_back(resistance);
}
}
/**
* @brief get RC tree
*
* @param pin
* @return std::vector<OptParaNode>
*/
std::vector<OptParaNode> DNetGraphProcessor::getRcTree(Pin *pin) const {
bool has_loop = false;
auto node_size = caps_.size();
auto coordinates_size = coordinates_.size();
auto it = pin_to_id_.find(pin);
auto net = pin->getNet();
auto pins = net->getPinArray();
auto pin_size = pins->getSize();
auto getCoordinateX = [&](NodeID id)->float {
return (id < coordinates_.size() ? coordinates_[id].x : DUMMY_COORDINATE);
};
auto getCoordinateY = [&](NodeID id)->float {
return (id < coordinates_.size() ? coordinates_[id].y : DUMMY_COORDINATE);
};
if (it == pin_to_id_.end()) {
assert(false);
return {};
}
auto root = it->second;
std::vector<OptParaNode> tree;
std::unordered_set<const ParasiticResistor*> visited_r;
std::vector<size_t> node_to_index(node_size, SIZE_MAX);
std::vector<NodeID> index_to_node(node_size, INVALID_NODE_ID);
tree.reserve(node_size);
node_to_index[root] = 0;
index_to_node[0] = root;
tree.push_back({0, 0, caps_[root], getCoordinateX(root), getCoordinateY(root), pin});
for (size_t i = 0; i < tree.size(); ++i) {
// To reduce runtime, using pre-reversed vector to do queueing.
NodeID node = index_to_node[i];
auto res_it = adjacent_map_.find(node);
if (res_it == adjacent_map_.end()) {
continue;
} else {
auto resistances = res_it->second;
for (auto res : resistances) {
if (visited_r.count(res)) {
continue;
}
visited_r.insert(res);
auto next_node = node == res->getNode1Id()?res->getNode2Id():res->getNode1Id();
#ifndef NDEBUG
if (node_to_index[next_node] != SIZE_MAX) {
// already visted
has_loop = true;
continue;
}
if (has_loop) {
std::cout << "HAS LOOP!!!" << std::endl;
std::cout << net->getName() << std:: endl;
++net_with_loop_;
}
#endif
if (next_node < pin_size) {
pin = Object::addr<Pin>((*pins)[next_node]);
} else {
pin = nullptr;
}
tree.push_back({i, /* parent_node */
res->getResistance(), /* resistance */
caps_[next_node],
getCoordinateX(next_node),
getCoordinateY(next_node),
pin
});
node_to_index[next_node] = tree.size() - 1;
index_to_node[tree.size() - 1] = next_node;
}
}
}
return tree;
}
/**
* @brief get RC forest
*
* @param net
* @return std::vector<std::vector<OptParaNode>>
*/
std::vector<std::vector<OptParaNode>> DNetGraphProcessor::getForest(const Net* net) const {
std::vector<std::vector<OptParaNode>> parasitic_forest;
auto node_size = caps_.size();
auto pins = net->getPinArray();
if (!pins) {
return {};
}
auto pin_size = pins->getSize();
Pin *pin = nullptr;
#ifndef NDEBUG
bool has_loop = false;
++valid_net_;
#endif
if (roots_.empty()) {
return {};
}
for (auto root : roots_) {
assert(root < pin_size);
auto tree = getRcTree(Object::addr<Pin>((*pins)[root]));
assert(selfCheck(net, tree));
parasitic_forest.push_back(std::move(tree));
}
return parasitic_forest;
}
bool DNetGraphProcessor::selfCheck(const Net *net, const std::vector<OptParaNode> &tree) const {
bool ok = true;
auto size = tree.size();
auto pins = net->getPinArray();
auto pin_size = pins->getSize();
size_t tree_pin_size = 0;
for (int index = 0; index < tree.size(); ++index) {
if (tree[index].parent >= size) {
std::cout << "Node index out of boundary!" << std::endl
<< " index: " << index << " parent: " << tree[index].parent << std::endl;
ok = false;
}
if (tree[index].pin) {
++tree_pin_size;
}
}
if (tree_pin_size != pin_size) {
std::cout << "Pin size mismatch! net pins:" << pin_size << " tree pin: " << tree_pin_size
<< std::endl;
assert(false);
ok = false;
}
// if (tree.size() < 2) {
// std::cout << "Pin size less than 2!" << std::endl;
// ok = false;
// }
if (!ok) {
std::cout << " Net name: " << net->getName() << std::endl;
}
return ok;
}
} // namespace db
} // namespace open_edi
| 29.202817 | 97 | 0.586959 | [
"object",
"vector"
] |
143047c55b6f62257c4851efa630ebf7f75d6056 | 2,524 | cpp | C++ | services/call/src/ims_call.cpp | openharmony-gitee-mirror/telephony_call_manager | c24bda5ddd9baeb4987a29b20224ffa2aa9faef6 | [
"Apache-2.0"
] | null | null | null | services/call/src/ims_call.cpp | openharmony-gitee-mirror/telephony_call_manager | c24bda5ddd9baeb4987a29b20224ffa2aa9faef6 | [
"Apache-2.0"
] | null | null | null | services/call/src/ims_call.cpp | openharmony-gitee-mirror/telephony_call_manager | c24bda5ddd9baeb4987a29b20224ffa2aa9faef6 | [
"Apache-2.0"
] | 1 | 2021-09-13T11:17:20.000Z | 2021-09-13T11:17:20.000Z | /*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* 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 "ims_call.h"
#include "call_manager_errors.h"
#include "telephony_log_wrapper.h"
namespace OHOS {
namespace Telephony {
IMSCall::IMSCall() {}
IMSCall::~IMSCall() {}
void IMSCall::OutCallInit(const CallReportInfo &info, AppExecFwk::PacMap &extras, int32_t callId)
{
InitCarrierOutCallInfo(info, extras, callId);
callType_ = CallType::TYPE_IMS;
}
void IMSCall::InCallInit(const CallReportInfo &info, int32_t callId)
{
InitCarrierInCallInfo(info, callId);
callType_ = CallType::TYPE_IMS;
}
int32_t IMSCall::DialingProcess()
{
return CarrierDialingProcess();
}
int32_t IMSCall::AnswerCall(int32_t videoState)
{
return CarrierAcceptCall(videoState);
}
int32_t IMSCall::RejectCall(bool isSendSms, std::string &content)
{
return CarrierRejectCall(isSendSms, content);
}
int32_t IMSCall::HangUpCall()
{
return CarrierHangUpCall();
}
int32_t IMSCall::HoldCall()
{
return CarrierHoldCall();
}
int32_t IMSCall::UnHoldCall()
{
return CarrierUnHoldCall();
}
int32_t IMSCall::SwitchCall()
{
return CarrierSwitchCall();
}
void IMSCall::GetCallAttributeInfo(CallAttributeInfo &info)
{
GetCallAttributeCarrierInfo(info);
}
int32_t IMSCall::CombineConference()
{
return TELEPHONY_SUCCESS;
}
int32_t IMSCall::CanCombineConference()
{
return TELEPHONY_SUCCESS;
}
int32_t IMSCall::SubCallCombineToConference()
{
return TELEPHONY_SUCCESS;
}
int32_t IMSCall::SubCallSeparateFromConference()
{
return TELEPHONY_SUCCESS;
}
int32_t IMSCall::CanSeparateConference()
{
return TELEPHONY_SUCCESS;
}
int32_t IMSCall::GetMainCallId()
{
return TELEPHONY_SUCCESS;
}
std::vector<std::u16string> IMSCall::GetSubCallIdList()
{
std::vector<std::u16string> vec;
return vec;
}
std::vector<std::u16string> IMSCall::GetCallIdListForConference()
{
std::vector<std::u16string> vec;
return vec;
}
} // namespace Telephony
} // namespace OHOS
| 20.688525 | 97 | 0.738906 | [
"vector"
] |
1430debc5b0c1f41c64ed57e9ad0e4e12506a346 | 15,296 | cpp | C++ | tess-two/jni/com_googlecode_tesseract_android/src/ccmain/cube_control.cpp | andyfuturex/tess-two | db698d0e4a13af1cfef593a246e0398d1c7c1ccb | [
"Apache-2.0"
] | 10 | 2016-03-10T11:43:56.000Z | 2020-01-23T13:30:39.000Z | tess-two/jni/com_googlecode_tesseract_android/src/ccmain/cube_control.cpp | andyfuturex/tess-two | db698d0e4a13af1cfef593a246e0398d1c7c1ccb | [
"Apache-2.0"
] | 1 | 2019-02-12T15:39:10.000Z | 2019-02-12T15:47:52.000Z | tess-two/jni/com_googlecode_tesseract_android/src/ccmain/cube_control.cpp | andyfuturex/tess-two | db698d0e4a13af1cfef593a246e0398d1c7c1ccb | [
"Apache-2.0"
] | 9 | 2016-04-09T14:18:21.000Z | 2019-10-04T06:30:33.000Z | /******************************************************************
* File: cube_control.cpp
* Description: Tesseract class methods for invoking cube convolutional
* neural network word recognizer.
* Author: Raquel Romano
* Created: September 2009
*
**********************************************************************/
// Include automatically generated configuration file if running autoconf.
#ifdef HAVE_CONFIG_H
#include "config_auto.h"
#endif
#include "allheaders.h"
#include "cube_object.h"
#include "cube_reco_context.h"
#include "tesseractclass.h"
#include "tesseract_cube_combiner.h"
namespace tesseract {
/**
* @name convert_prob_to_tess_certainty
*
* Normalize a probability in the range [0.0, 1.0] to a tesseract
* certainty in the range [-20.0, 0.0]
*/
static float convert_prob_to_tess_certainty(float prob) {
return (prob - 1.0) * 20.0;
}
/**
* @name char_box_to_tbox
*
* Create a TBOX from a character bounding box. If nonzero, the
* x_offset accounts for any additional padding of the word box that
* should be taken into account.
*
*/
TBOX char_box_to_tbox(Box* char_box, TBOX word_box, int x_offset) {
l_int32 left;
l_int32 top;
l_int32 width;
l_int32 height;
l_int32 right;
l_int32 bottom;
boxGetGeometry(char_box, &left, &top, &width, &height);
left += word_box.left() - x_offset;
right = left + width;
top = word_box.bottom() + word_box.height() - top;
bottom = top - height;
return TBOX(left, bottom, right, top);
}
/**
* @name extract_cube_state
*
* Extract CharSamp objects and character bounding boxes from the
* CubeObject's state. The caller should free both structres.
*
*/
bool Tesseract::extract_cube_state(CubeObject* cube_obj,
int* num_chars,
Boxa** char_boxes,
CharSamp*** char_samples) {
if (!cube_obj) {
if (cube_debug_level > 0) {
tprintf("Cube WARNING (extract_cube_state): Invalid cube object "
"passed to extract_cube_state\n");
}
return false;
}
// Note that the CubeObject accessors return either the deslanted or
// regular objects search object or beam search object, whichever
// was used in the last call to Recognize()
CubeSearchObject* cube_search_obj = cube_obj->SrchObj();
if (!cube_search_obj) {
if (cube_debug_level > 0) {
tprintf("Cube WARNING (Extract_cube_state): Could not retrieve "
"cube's search object in extract_cube_state.\n");
}
return false;
}
BeamSearch *beam_search_obj = cube_obj->BeamObj();
if (!beam_search_obj) {
if (cube_debug_level > 0) {
tprintf("Cube WARNING (Extract_cube_state): Could not retrieve "
"cube's beam search object in extract_cube_state.\n");
}
return false;
}
// Get the character samples and bounding boxes by backtracking
// through the beam search path
int best_node_index = beam_search_obj->BestPresortedNodeIndex();
*char_samples = beam_search_obj->BackTrack(
cube_search_obj, best_node_index, num_chars, NULL, char_boxes);
if (!*char_samples)
return false;
return true;
}
/**
* @name create_cube_box_word
*
* Fill the given BoxWord with boxes from character bounding
* boxes. The char_boxes have local coordinates w.r.t. the
* word bounding box, i.e., the left-most character bbox of each word
* has (0,0) left-top coord, but the BoxWord must be defined in page
* coordinates.
*/
bool Tesseract::create_cube_box_word(Boxa *char_boxes,
int num_chars,
TBOX word_box,
BoxWord* box_word) {
if (!box_word) {
if (cube_debug_level > 0) {
tprintf("Cube WARNING (create_cube_box_word): Invalid box_word.\n");
}
return false;
}
// Find the x-coordinate of left-most char_box, which could be
// nonzero if the word image was padded before recognition took place.
int x_offset = -1;
for (int i = 0; i < num_chars; ++i) {
Box* char_box = boxaGetBox(char_boxes, i, L_CLONE);
if (x_offset < 0 || char_box->x < x_offset) {
x_offset = char_box->x;
}
boxDestroy(&char_box);
}
for (int i = 0; i < num_chars; ++i) {
Box* char_box = boxaGetBox(char_boxes, i, L_CLONE);
TBOX tbox = char_box_to_tbox(char_box, word_box, x_offset);
boxDestroy(&char_box);
box_word->InsertBox(i, tbox);
}
return true;
}
/**
* @name init_cube_objects
*
* Instantiates Tesseract object's CubeRecoContext and TesseractCubeCombiner.
* Returns false if cube context could not be created or if load_combiner is
* true, but the combiner could not be loaded.
*/
bool Tesseract::init_cube_objects(bool load_combiner,
TessdataManager *tessdata_manager) {
ASSERT_HOST(cube_cntxt_ == NULL);
ASSERT_HOST(tess_cube_combiner_ == NULL);
// Create the cube context object
cube_cntxt_ = CubeRecoContext::Create(this, tessdata_manager, &unicharset);
if (cube_cntxt_ == NULL) {
if (cube_debug_level > 0) {
tprintf("Cube WARNING (Tesseract::init_cube_objects()): Failed to "
"instantiate CubeRecoContext\n");
}
return false;
}
// Create the combiner object and load the combiner net for target languages.
if (load_combiner) {
tess_cube_combiner_ = new tesseract::TesseractCubeCombiner(cube_cntxt_);
if (!tess_cube_combiner_ || !tess_cube_combiner_->LoadCombinerNet()) {
delete cube_cntxt_;
cube_cntxt_ = NULL;
if (tess_cube_combiner_ != NULL) {
delete tess_cube_combiner_;
tess_cube_combiner_ = NULL;
}
if (cube_debug_level > 0)
tprintf("Cube ERROR (Failed to instantiate TesseractCubeCombiner\n");
return false;
}
}
return true;
}
/**
* @name run_cube_combiner
*
* Iterates through tesseract's results and calls cube on each word,
* combining the results with the existing tesseract result.
*/
void Tesseract::run_cube_combiner(PAGE_RES *page_res) {
if (page_res == NULL || tess_cube_combiner_ == NULL)
return;
PAGE_RES_IT page_res_it(page_res);
// Iterate through the word results and call cube on each word.
for (page_res_it.restart_page(); page_res_it.word () != NULL;
page_res_it.forward()) {
BLOCK* block = page_res_it.block()->block;
if (block->poly_block() != NULL && !block->poly_block()->IsText())
continue; // Don't deal with non-text blocks.
WERD_RES* word = page_res_it.word();
// Skip cube entirely if tesseract's certainty is greater than threshold.
int combiner_run_thresh = convert_prob_to_tess_certainty(
cube_cntxt_->Params()->CombinerRunThresh());
if (word->best_choice->certainty() >= combiner_run_thresh) {
continue;
}
// Use the same language as Tesseract used for the word.
Tesseract* lang_tess = word->tesseract;
// Setup a trial WERD_RES in which to classify with cube.
WERD_RES cube_word;
cube_word.InitForRetryRecognition(*word);
cube_word.SetupForRecognition(lang_tess->unicharset, this, BestPix(),
OEM_CUBE_ONLY,
NULL, false, false, false,
page_res_it.row()->row,
page_res_it.block()->block);
CubeObject *cube_obj = lang_tess->cube_recognize_word(
page_res_it.block()->block, &cube_word);
if (cube_obj != NULL)
lang_tess->cube_combine_word(cube_obj, &cube_word, word);
delete cube_obj;
}
}
/**
* @name cube_word_pass1
*
* Recognizes a single word using (only) cube. Compatible with
* Tesseract's classify_word_pass1/classify_word_pass2.
*/
void Tesseract::cube_word_pass1(BLOCK* block, ROW *row, WERD_RES *word) {
CubeObject *cube_obj = cube_recognize_word(block, word);
delete cube_obj;
}
/**
* @name cube_recognize_word
*
* Cube recognizer to recognize a single word as with classify_word_pass1
* but also returns the cube object in case the combiner is needed.
*/
CubeObject* Tesseract::cube_recognize_word(BLOCK* block, WERD_RES* word) {
if (!cube_binary_ || !cube_cntxt_) {
if (cube_debug_level > 0 && !cube_binary_)
tprintf("Tesseract::run_cube(): NULL binary image.\n");
word->SetupFake(unicharset);
return NULL;
}
TBOX word_box = word->word->bounding_box();
if (block != NULL && (block->re_rotation().x() != 1.0f ||
block->re_rotation().y() != 0.0f)) {
// TODO(rays) We have to rotate the bounding box to get the true coords.
// This will be achieved in the future via DENORM.
// In the mean time, cube can't process this word.
if (cube_debug_level > 0) {
tprintf("Cube can't process rotated word at:");
word_box.print();
}
word->SetupFake(unicharset);
return NULL;
}
CubeObject* cube_obj = new tesseract::CubeObject(
cube_cntxt_, cube_binary_, word_box.left(),
pixGetHeight(cube_binary_) - word_box.top(),
word_box.width(), word_box.height());
if (!cube_recognize(cube_obj, block, word)) {
delete cube_obj;
return NULL;
}
return cube_obj;
}
/**
* @name cube_combine_word
*
* Combines the cube and tesseract results for a single word, leaving the
* result in tess_word.
*/
void Tesseract::cube_combine_word(CubeObject* cube_obj, WERD_RES* cube_word,
WERD_RES* tess_word) {
float combiner_prob = tess_cube_combiner_->CombineResults(tess_word,
cube_obj);
// If combiner probability is greater than tess/cube combiner
// classifier threshold, i.e. tesseract wins, then just return the
// tesseract result unchanged, as the combiner knows nothing about how
// correct the answer is. If cube and tesseract agree, then improve the
// scores before returning.
WERD_CHOICE* tess_best = tess_word->best_choice;
WERD_CHOICE* cube_best = cube_word->best_choice;
if (cube_debug_level || classify_debug_level) {
tprintf("Combiner prob = %g vs threshold %g\n",
combiner_prob, cube_cntxt_->Params()->CombinerClassifierThresh());
}
if (combiner_prob >=
cube_cntxt_->Params()->CombinerClassifierThresh()) {
if (tess_best->unichar_string() == cube_best->unichar_string()) {
// Cube and tess agree, so improve the scores.
tess_best->set_rating(tess_best->rating() / 2);
tess_best->set_certainty(tess_best->certainty() / 2);
}
return;
}
// Cube wins.
// It is better for the language combiner to have all tesseract scores,
// so put them in the cube result.
cube_best->set_rating(tess_best->rating());
cube_best->set_certainty(tess_best->certainty());
if (cube_debug_level || classify_debug_level) {
tprintf("Cube INFO: tesseract result replaced by cube: %s -> %s\n",
tess_best->unichar_string().string(),
cube_best->unichar_string().string());
}
tess_word->ConsumeWordResults(cube_word);
}
/**
* @name cube_recognize
*
* Call cube on the current word, and write the result to word.
* Sets up a fake result and returns false if something goes wrong.
*/
bool Tesseract::cube_recognize(CubeObject *cube_obj, BLOCK* block,
WERD_RES *word) {
// Run cube
WordAltList *cube_alt_list = cube_obj->RecognizeWord();
if (!cube_alt_list || cube_alt_list->AltCount() <= 0) {
if (cube_debug_level > 0) {
tprintf("Cube returned nothing for word at:");
word->word->bounding_box().print();
}
word->SetupFake(unicharset);
return false;
}
// Get cube's best result and its probability, mapped to tesseract's
// certainty range
char_32 *cube_best_32 = cube_alt_list->Alt(0);
double cube_prob = CubeUtils::Cost2Prob(cube_alt_list->AltCost(0));
float cube_certainty = convert_prob_to_tess_certainty(cube_prob);
string cube_best_str;
CubeUtils::UTF32ToUTF8(cube_best_32, &cube_best_str);
// Retrieve Cube's character bounding boxes and CharSamples,
// corresponding to the most recent call to RecognizeWord().
Boxa *char_boxes = NULL;
CharSamp **char_samples = NULL;;
int num_chars;
if (!extract_cube_state(cube_obj, &num_chars, &char_boxes, &char_samples)
&& cube_debug_level > 0) {
tprintf("Cube WARNING (Tesseract::cube_recognize): Cannot extract "
"cube state.\n");
word->SetupFake(unicharset);
return false;
}
// Convert cube's character bounding boxes to a BoxWord.
BoxWord cube_box_word;
TBOX tess_word_box = word->word->bounding_box();
if (word->denorm.block() != NULL)
tess_word_box.rotate(word->denorm.block()->re_rotation());
bool box_word_success = create_cube_box_word(char_boxes, num_chars,
tess_word_box,
&cube_box_word);
boxaDestroy(&char_boxes);
if (!box_word_success) {
if (cube_debug_level > 0) {
tprintf("Cube WARNING (Tesseract::cube_recognize): Could not "
"create cube BoxWord\n");
}
word->SetupFake(unicharset);
return false;
}
// Fill tesseract result's fields with cube results
fill_werd_res(cube_box_word, cube_best_str.c_str(), word);
// Create cube's best choice.
BLOB_CHOICE** choices = new BLOB_CHOICE*[num_chars];
for (int i = 0; i < num_chars; ++i) {
UNICHAR_ID uch_id =
cube_cntxt_->CharacterSet()->UnicharID(char_samples[i]->StrLabel());
choices[i] = new BLOB_CHOICE(uch_id, -cube_certainty, cube_certainty,
-1, 0.0f, 0.0f, 0.0f, BCC_STATIC_CLASSIFIER);
}
word->FakeClassifyWord(num_chars, choices);
// within a word, cube recognizes the word in reading order.
word->best_choice->set_unichars_in_script_order(true);
delete [] choices;
delete [] char_samples;
// Some sanity checks
ASSERT_HOST(word->best_choice->length() == word->reject_map.length());
if (cube_debug_level || classify_debug_level) {
tprintf("Cube result: %s r=%g, c=%g\n",
word->best_choice->unichar_string().string(),
word->best_choice->rating(),
word->best_choice->certainty());
}
return true;
}
/**
* @name fill_werd_res
*
* Fill Tesseract's word result fields with cube's.
*
*/
void Tesseract::fill_werd_res(const BoxWord& cube_box_word,
const char* cube_best_str,
WERD_RES* tess_werd_res) {
delete tess_werd_res->box_word;
tess_werd_res->box_word = new BoxWord(cube_box_word);
tess_werd_res->box_word->ClipToOriginalWord(tess_werd_res->denorm.block(),
tess_werd_res->word);
// Fill text and remaining fields
tess_werd_res->word->set_text(cube_best_str);
tess_werd_res->tess_failed = FALSE;
tess_werd_res->tess_accepted = tess_acceptable_word(tess_werd_res);
// There is no output word, so we can' call AdaptableWord, but then I don't
// think we need to. Fudge the result with accepted.
tess_werd_res->tess_would_adapt = tess_werd_res->tess_accepted;
// Set word to done, i.e., ignore all of tesseract's tests for rejection
tess_werd_res->done = tess_werd_res->tess_accepted;
}
} // namespace tesseract
| 35.325635 | 79 | 0.659519 | [
"object"
] |
14321413280fbdb853d0af275e92f86976ade9cb | 8,094 | cpp | C++ | dev/Code/CryEngine/CryAction/VehicleSystem/ScriptBind_VehicleSeat.cpp | crazyskateface/lumberyard | 164512f8d415d6bdf37e195af319ffe5f96a8f0b | [
"AML"
] | 5 | 2018-08-17T21:05:55.000Z | 2021-04-17T10:48:26.000Z | dev/Code/CryEngine/CryAction/VehicleSystem/ScriptBind_VehicleSeat.cpp | JulianoCristian/Lumberyard-3 | dc523dd780f3cd1874251181b7cf6848b8db9959 | [
"AML"
] | null | null | null | dev/Code/CryEngine/CryAction/VehicleSystem/ScriptBind_VehicleSeat.cpp | JulianoCristian/Lumberyard-3 | dc523dd780f3cd1874251181b7cf6848b8db9959 | [
"AML"
] | 5 | 2017-12-05T16:36:00.000Z | 2021-04-27T06:33:54.000Z | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
// Description : Script Binding for the Vehicle Seat
#include "StdAfx.h"
#include "CryString.h"
#include <IActionMapManager.h>
#include <ICryAnimation.h>
#include "IGameFramework.h"
#include "IActorSystem.h"
#include <vector>
#include <Cry_Math.h>
#include <IShader.h>
#include <IRenderAuxGeom.h>
#include <Cry_GeoOverlap.h>
#include "VehicleSystem.h"
#include "VehicleSeat.h"
#include "ScriptBind_VehicleSeat.h"
#include "Vehicle.h"
#include "VehicleSeatActionWeapons.h"
//------------------------------------------------------------------------
// macro for retrieving vehicle and entity
#undef GET_ENTITY
#define GET_ENTITY IVehicle * pVehicle = GetVehicle(pH); CRY_ASSERT(pVehicle); \
IEntity* pEntity = pVehicle->GetEntity(); \
if (!pEntity) {return pH->EndFunction(); }
//------------------------------------------------------------------------
CScriptBind_VehicleSeat::CScriptBind_VehicleSeat(ISystem* pSystem, IGameFramework* pGameFW)
{
m_pVehicleSystem = pGameFW->GetIVehicleSystem();
Init(gEnv->pScriptSystem, gEnv->pSystem, 1);
RegisterMethods();
RegisterGlobals();
}
//------------------------------------------------------------------------
CScriptBind_VehicleSeat::~CScriptBind_VehicleSeat()
{
}
//------------------------------------------------------------------------
void CScriptBind_VehicleSeat::RegisterGlobals()
{
}
//------------------------------------------------------------------------
void CScriptBind_VehicleSeat::RegisterMethods()
{
#undef SCRIPT_REG_CLASSNAME
#define SCRIPT_REG_CLASSNAME &CScriptBind_VehicleSeat::
SCRIPT_REG_TEMPLFUNC(Reset, "");
SCRIPT_REG_TEMPLFUNC(IsFree, "actor");
SCRIPT_REG_TEMPLFUNC(IsDriver, "");
SCRIPT_REG_TEMPLFUNC(IsGunner, "");
SCRIPT_REG_TEMPLFUNC(GetWeaponCount, "");
SCRIPT_REG_TEMPLFUNC(GetWeaponId, "index");
SCRIPT_REG_TEMPLFUNC(SetAIWeapon, "weaponId");
SCRIPT_REG_TEMPLFUNC(GetPassengerId, "");
}
//------------------------------------------------------------------------
void CScriptBind_VehicleSeat::AttachTo(IVehicle* pVehicle, TVehicleSeatId seatId)
{
IScriptTable* pScriptTable = pVehicle->GetEntity()->GetScriptTable();
if (!pScriptTable || seatId == InvalidVehicleSeatId)
{
return;
}
SmartScriptTable seatsTable;
if (!pScriptTable->GetValue("Seats", seatsTable))
{
CRY_ASSERT(!"cannot read the seats table");
return;
}
SmartScriptTable seatTable(gEnv->pScriptSystem);
SmartScriptTable thisTable(gEnv->pScriptSystem);
thisTable->SetValue("vehicleId", ScriptHandle(pVehicle->GetEntityId()));
thisTable->SetValue("seatId", (int)seatId);
thisTable->Delegate(GetMethodsTable());
seatTable->SetValue("seat", thisTable);
if (IVehicleSeat* pSeat = pVehicle->GetSeatById(seatId))
{
seatTable->SetValue("isDriver", pSeat->IsDriver());
}
seatsTable->SetAt(seatId, seatTable);
}
//------------------------------------------------------------------------
CVehicleSeat* CScriptBind_VehicleSeat::GetVehicleSeat(IFunctionHandler* pH)
{
ScriptHandle handle;
int seatId = 0;
SmartScriptTable table;
if (pH->GetSelf(table))
{
if (table->GetValue("vehicleId", handle) && table->GetValue("seatId", seatId))
{
CVehicle* pVehicle = (CVehicle*)m_pVehicleSystem->GetVehicle((EntityId)handle.n);
if (pVehicle)
{
return (CVehicleSeat*)pVehicle->GetSeatById((TVehicleSeatId)seatId);
}
}
}
return 0;
}
//------------------------------------------------------------------------
int CScriptBind_VehicleSeat::Reset(IFunctionHandler* pH)
{
CVehicleSeat* pVehicleSeat = GetVehicleSeat(pH);
if (pVehicleSeat)
{
pVehicleSeat->Reset();
}
return pH->EndFunction();
}
//------------------------------------------------------------------------
int CScriptBind_VehicleSeat::GetWeaponId(IFunctionHandler* pH, int weaponIndex)
{
// returns Weapon Id 02/11/05 Tetsuji
const CVehicleSeat* pVehicleSeat = GetVehicleSeat(pH);
int weaponCounter = 1;
if (pVehicleSeat)
{
const TVehicleSeatActionVector& seatActions = pVehicleSeat->GetSeatActions();
for (TVehicleSeatActionVector::const_iterator ite = seatActions.begin(), end = seatActions.end(); ite != end; ++ite)
{
IVehicleSeatAction* pSeatAction = ite->pSeatAction;
if (CVehicleSeatActionWeapons* pSeatWeapons = CAST_VEHICLEOBJECT(CVehicleSeatActionWeapons, pSeatAction))
{
if ((weaponCounter == weaponIndex) && (pSeatWeapons->GetWeaponCount() > 0))
{
ScriptHandle weaponHandle;
weaponHandle.n = pSeatWeapons->GetWeaponEntityId(0);
return pH->EndFunction(weaponHandle);
}
weaponCounter++;
}
}
}
return pH->EndFunction();
}
//------------------------------------------------------------------------
int CScriptBind_VehicleSeat::GetWeaponCount(IFunctionHandler* pH)
{
const CVehicleSeat* pVehicleSeat = GetVehicleSeat(pH);
int weaponCount = 0;
if (pVehicleSeat)
{
const TVehicleSeatActionVector& seatActions = pVehicleSeat->GetSeatActions();
for (TVehicleSeatActionVector::const_iterator ite = seatActions.begin(), end = seatActions.end(); ite != end; ++ite)
{
IVehicleSeatAction* pSeatAction = ite->pSeatAction;
if (CAST_VEHICLEOBJECT(CVehicleSeatActionWeapons, pSeatAction))
{
weaponCount++;
}
}
}
return pH->EndFunction(weaponCount);
}
//------------------------------------------------------------------------
int CScriptBind_VehicleSeat::SetAIWeapon(IFunctionHandler* pH, ScriptHandle weaponHandle)
{
if (CVehicleSeat* pVehicleSeat = GetVehicleSeat(pH))
{
pVehicleSeat->SetAIWeaponId((EntityId)weaponHandle.n);
return pH->EndFunction(true);
}
return pH->EndFunction(false);
}
//------------------------------------------------------------------------
int CScriptBind_VehicleSeat::IsFree(IFunctionHandler* pH, ScriptHandle actorHandle)
{
if (CVehicleSeat* pVehicleSeat = GetVehicleSeat(pH))
{
IActor* pActor = CCryAction::GetCryAction()->GetIActorSystem()->GetActor((EntityId)actorHandle.n);
return pH->EndFunction(pVehicleSeat->IsFree(pActor));
}
return pH->EndFunction(false);
}
//------------------------------------------------------------------------
int CScriptBind_VehicleSeat::IsDriver(IFunctionHandler* pH)
{
if (CVehicleSeat* pVehicleSeat = GetVehicleSeat(pH))
{
return pH->EndFunction(pVehicleSeat->IsDriver());
}
return pH->EndFunction(false);
}
//------------------------------------------------------------------------
int CScriptBind_VehicleSeat::IsGunner(IFunctionHandler* pH)
{
if (CVehicleSeat* pVehicleSeat = GetVehicleSeat(pH))
{
return pH->EndFunction(pVehicleSeat->IsGunner());
}
return pH->EndFunction(false);
}
//------------------------------------------------------------------------
int CScriptBind_VehicleSeat::GetPassengerId(IFunctionHandler* pH)
{
if (CVehicleSeat* pVehicleSeat = GetVehicleSeat(pH))
{
return pH->EndFunction(ScriptHandle(pVehicleSeat->GetPassenger()));
}
return pH->EndFunction();
}
| 31.011494 | 124 | 0.587225 | [
"vector"
] |
1433e1ca1512252553d0bdc23ad35ea4a7c34666 | 1,007 | hpp | C++ | src/include/duckdb/storage/table/append_state.hpp | pachamaltese/duckdb | 81a0e923fd9d061f79c97aec05b41dfa26cf8581 | [
"MIT"
] | 1 | 2021-09-15T10:29:20.000Z | 2021-09-15T10:29:20.000Z | src/include/duckdb/storage/table/append_state.hpp | pachamaltese/duckdb | 81a0e923fd9d061f79c97aec05b41dfa26cf8581 | [
"MIT"
] | null | null | null | src/include/duckdb/storage/table/append_state.hpp | pachamaltese/duckdb | 81a0e923fd9d061f79c97aec05b41dfa26cf8581 | [
"MIT"
] | null | null | null | //===----------------------------------------------------------------------===//
// DuckDB
//
// duckdb/storage/table/append_state.hpp
//
//
//===----------------------------------------------------------------------===//
#pragma once
#include "duckdb/common/common.hpp"
#include "duckdb/storage/storage_lock.hpp"
#include "duckdb/storage/buffer/buffer_handle.hpp"
namespace duckdb {
class UpdateSegment;
class TransientSegment;
class ValiditySegment;
struct ColumnAppendState {
//! The current segment of the append
TransientSegment *current;
//! The update segment to append to
UpdateSegment *updates;
//! Child append states
vector<ColumnAppendState> child_appends;
//! The write lock that is held by the append
unique_ptr<StorageLockKey> lock;
};
struct IndexLock {
unique_lock<mutex> index_lock;
};
struct TableAppendState {
unique_lock<mutex> append_lock;
unique_ptr<ColumnAppendState[]> states;
row_t row_start;
row_t current_row;
};
} // namespace duckdb
| 23.418605 | 80 | 0.625621 | [
"vector"
] |
1434d660d3b93d7d44059ae9f171cd30f220eae8 | 3,675 | cc | C++ | RecoMuon/MuonIdentification/plugins/CosmicsMuonIdProducer.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 852 | 2015-01-11T21:03:51.000Z | 2022-03-25T21:14:00.000Z | RecoMuon/MuonIdentification/plugins/CosmicsMuonIdProducer.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 30,371 | 2015-01-02T00:14:40.000Z | 2022-03-31T23:26:05.000Z | RecoMuon/MuonIdentification/plugins/CosmicsMuonIdProducer.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 3,240 | 2015-01-02T05:53:18.000Z | 2022-03-31T17:24:21.000Z | #include <string>
#include <vector>
#include "DataFormats/Common/interface/ValueMap.h"
#include "DataFormats/MuonReco/interface/MuonFwd.h"
#include "DataFormats/MuonReco/interface/Muon.h"
#include "DataFormats/TrackReco/interface/Track.h"
#include "RecoMuon/MuonIdentification/interface/MuonCosmicsId.h"
#include "FWCore/Framework/interface/stream/EDProducer.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/EventSetup.h"
#include "FWCore/Framework/interface/Frameworkfwd.h"
#include "FWCore/Framework/interface/MakerMacros.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "RecoMuon/MuonIdentification/interface/MuonCosmicCompatibilityFiller.h"
class CosmicsMuonIdProducer : public edm::stream::EDProducer<> {
public:
CosmicsMuonIdProducer(const edm::ParameterSet& iConfig)
: inputMuonCollection_(iConfig.getParameter<edm::InputTag>("muonCollection")),
inputTrackCollections_(iConfig.getParameter<std::vector<edm::InputTag>>("trackCollections")) {
edm::ConsumesCollector iC = consumesCollector();
compatibilityFiller_ =
new MuonCosmicCompatibilityFiller(iConfig.getParameter<edm::ParameterSet>("CosmicCompFillerParameters"), iC);
produces<edm::ValueMap<unsigned int>>().setBranchAlias("cosmicsVeto");
produces<edm::ValueMap<reco::MuonCosmicCompatibility>>().setBranchAlias("cosmicCompatibility");
muonToken_ = consumes<reco::MuonCollection>(inputMuonCollection_);
for (unsigned int i = 0; i < inputTrackCollections_.size(); ++i)
trackTokens_.push_back(consumes<reco::TrackCollection>(inputTrackCollections_.at(i)));
}
~CosmicsMuonIdProducer() override {
if (compatibilityFiller_)
delete compatibilityFiller_;
}
private:
void produce(edm::Event&, const edm::EventSetup&) override;
edm::InputTag inputMuonCollection_;
std::vector<edm::InputTag> inputTrackCollections_;
edm::EDGetTokenT<reco::MuonCollection> muonToken_;
std::vector<edm::EDGetTokenT<reco::TrackCollection>> trackTokens_;
MuonCosmicCompatibilityFiller* compatibilityFiller_;
};
void CosmicsMuonIdProducer::produce(edm::Event& iEvent, const edm::EventSetup& iSetup) {
edm::Handle<reco::MuonCollection> muons;
iEvent.getByToken(muonToken_, muons);
// reserve some space
std::vector<unsigned int> values;
values.reserve(muons->size());
std::vector<reco::MuonCosmicCompatibility> compValues;
compValues.reserve(muons->size());
for (reco::MuonCollection::const_iterator muon = muons->begin(); muon != muons->end(); ++muon) {
unsigned int foundPartner(0);
if (muon->innerTrack().isNonnull()) {
for (unsigned int i = 0; i < inputTrackCollections_.size(); ++i) {
edm::Handle<reco::TrackCollection> tracks;
iEvent.getByToken(trackTokens_.at(i), tracks);
if (muonid::findOppositeTrack(tracks, *muon->innerTrack()).isNonnull()) {
foundPartner = i + 1;
break;
}
}
}
values.push_back(foundPartner);
compValues.push_back(compatibilityFiller_->fillCompatibility(*muon, iEvent, iSetup));
}
// create and fill value map
auto out = std::make_unique<edm::ValueMap<unsigned int>>();
edm::ValueMap<unsigned int>::Filler filler(*out);
filler.insert(muons, values.begin(), values.end());
filler.fill();
auto outC = std::make_unique<edm::ValueMap<reco::MuonCosmicCompatibility>>();
edm::ValueMap<reco::MuonCosmicCompatibility>::Filler fillerC(*outC);
fillerC.insert(muons, compValues.begin(), compValues.end());
fillerC.fill();
// put value map into event
iEvent.put(std::move(out));
iEvent.put(std::move(outC));
}
DEFINE_FWK_MODULE(CosmicsMuonIdProducer);
| 39.516129 | 117 | 0.74068 | [
"vector"
] |
1439705c7abba5ded77669f5f45224e22b2b10ed | 8,639 | hpp | C++ | libs/muddle/include/muddle/muddle_interface.hpp | devjsc/ledger | 5681480faf6e2aeee577f149c17745d6ab4d4ab3 | [
"Apache-2.0"
] | 1 | 2019-09-11T09:46:04.000Z | 2019-09-11T09:46:04.000Z | libs/muddle/include/muddle/muddle_interface.hpp | devjsc/ledger | 5681480faf6e2aeee577f149c17745d6ab4d4ab3 | [
"Apache-2.0"
] | null | null | null | libs/muddle/include/muddle/muddle_interface.hpp | devjsc/ledger | 5681480faf6e2aeee577f149c17745d6ab4d4ab3 | [
"Apache-2.0"
] | 1 | 2019-09-19T12:38:46.000Z | 2019-09-19T12:38:46.000Z | #pragma once
//------------------------------------------------------------------------------
//
// Copyright 2018-2019 Fetch.AI Limited
//
// 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 "muddle/address.hpp"
#include "muddle/peer_selection_mode.hpp"
#include "network/uri.hpp"
#include <cstdint>
#include <memory>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
namespace fetch {
namespace crypto {
class Prover;
class Identity;
} // namespace crypto
namespace network {
class NetworkManager;
}
namespace muddle {
class MuddleEndpoint;
class NetworkId;
class MuddleInterface
{
public:
enum class Confidence
{
DEFAULT,
WHITELIST,
BLACKLIST
};
using Peers = std::unordered_set<std::string>;
using Uris = std::unordered_set<network::Uri>;
using Ports = std::vector<uint16_t>;
using PortMapping = std::unordered_map<uint16_t, uint16_t>;
using Addresses = std::unordered_set<Address>;
using ConfidenceMap = std::unordered_map<Address, Confidence>;
using AddressHints = std::unordered_map<Address, network::Uri>;
// Construction / Destruction
MuddleInterface() = default;
virtual ~MuddleInterface() = default;
/// @name Muddle Setup
/// @{
/**
* Start the muddle instance connecting to the initial set of peers and listing on the specified
* set of ports
*
* @param peers The initial set of peers that muddle should connect to
* @param ports The set of ports to listen on. Zero signals a random port
* @return true if successful, otherwise false
*/
virtual bool Start(Peers const &peers, Ports const &ports) = 0;
/**
* Start the muddle instance connecting to the initial set of peers and listing on the specified
* set of ports
*
* @param peers The initial set of peers that muddle should connect to
* @param ports The set of ports to listen on. Zero signals a random port
* @return true if successful, otherwise false
*/
virtual bool Start(Uris const &peers, Ports const &ports) = 0;
/**
* Start the muddle instance connecting to the initial set of peers and listing on the specified
* set of ports
*
* @param peers The initial set of peers that muddle should connect to
* @param port_mapping The maps
* @return true if successful, otherwise false
*/
virtual bool Start(Uris const &peers, PortMapping const &port_mapping) = 0;
/**
* Start the muddle instance listing on the specified set of ports
*
* @param ports The set of ports to listen on. Zero signals a random port
* @return true if successful, otherwise false
*/
virtual bool Start(Ports const &ports) = 0;
/**
* Stop the muddle instance, this will cause all the connected to close
*/
virtual void Stop() = 0;
/**
* Get the endpoint interface for this muddle instance/
*
* @return The endpoint pointer
*/
virtual MuddleEndpoint &GetEndpoint() = 0;
/// @}
/// @name Muddle Status
/// @{
/**
* Get the associated network for this muddle instance
*
* @return The current network
*/
virtual NetworkId const &GetNetwork() const = 0;
/**
* Get the address of this muddle node
*
* @return The address of the node
*/
virtual Address const &GetAddress() const = 0;
/**
* Get the external address of the muddle
*
* @return The external address of the node
*/
virtual std::string const &GetExternalAddress() const = 0;
/**
* Get the set of ports that the server is currently listening on
*
* @return The set of server ports
*/
virtual Ports GetListeningPorts() const = 0;
/**
* Get the set of addresses to whom this node is directly connected to
*
* @return The set of addresses
*/
virtual Addresses GetDirectlyConnectedPeers() const = 0;
/**
* Get the set of addresses of peers that are connected directly to this node
*
* @return The set of addresses
*/
virtual Addresses GetIncomingConnectedPeers() const = 0;
/**
* Get the set of addresses of peers that we are directly connected to
*
* @return The set of peers
*/
virtual Addresses GetOutgoingConnectedPeers() const = 0;
/**
* Get the number of peers that are directly connected to this node
*
* @return The number of directly connected peers
*/
virtual std::size_t GetNumDirectlyConnectedPeers() const = 0;
/**
* Determine if we are directly connected to the specified address
*
* @param address The address to check
* @return true if directly connected, otherwise false
*/
virtual bool IsDirectlyConnected(Address const &address) const = 0;
/// @}
/// @name Peer Control
/// @{
/**
* Query the current peer selection mode for this muddle
*
* @return The current mode
*/
virtual PeerSelectionMode GetPeerSelectionMode() const = 0;
/**
* Update the current peer selection mode for this muddle
* @param mode
*/
virtual void SetPeerSelectionMode(PeerSelectionMode mode) = 0;
/**
* Get the set of addresses that have been requested to connect to
*
* @return The set of addresses
*/
virtual Addresses GetRequestedPeers() const = 0;
/**
* Request that muddle attempts to connect to the specified address
*
* @param address The requested address to connect to
*/
virtual void ConnectTo(Address const &address) = 0;
/**
* Request that muddle attempts to connect to the specified set of addresses
*
* @param addresses The set of addresses
*/
virtual void ConnectTo(Addresses const &addresses) = 0;
/**
* Connect to a specified address with the provided URI hint
*
* @param address The address to connect to
* @param uri_hint The hint to the connection URI
*/
virtual void ConnectTo(Address const &address, network::Uri const &uri_hint) = 0;
/**
* Connect to the specified addresses with the provided connection hints
*
* @param address_hints The map of address => URI hint
*/
virtual void ConnectTo(AddressHints const &address_hints) = 0;
/**
* Request that muddle disconnected from the specified address
*
* @param address The requested address to disconnect from
*/
virtual void DisconnectFrom(Address const &address) = 0;
/**
* Request that muddle disconnects from the specified set of addresses
*
* @param addresses The set of addresses
*/
virtual void DisconnectFrom(Addresses const &addresses) = 0;
/**
* Update the confidence for a specified address to specified level
*
* @param address The address to be updated
* @param confidence The confidence level to be set
*/
virtual void SetConfidence(Address const &address, Confidence confidence) = 0;
/**
* Update the confidence for all the specified addresses with the specified level
*
* @param addresses The set of addresses to update
* @param confidence The confidence level to be used
*/
virtual void SetConfidence(Addresses const &addresses, Confidence confidence) = 0;
/**
* Update a map of address to confidence level
*
* @param map The map of address to confidence level
*/
virtual void SetConfidence(ConfidenceMap const &map) = 0;
/// @}
};
using MuddlePtr = std::shared_ptr<MuddleInterface>;
using ProverPtr = std::shared_ptr<crypto::Prover>;
// creation
MuddlePtr CreateMuddle(NetworkId const &network, ProverPtr certificate,
network::NetworkManager const &nm, std::string const &external_address);
MuddlePtr CreateMuddle(char const network[4], ProverPtr certificate,
network::NetworkManager const &nm, std::string const &external_address);
MuddlePtr CreateMuddle(NetworkId const &network, network::NetworkManager const &nm,
std::string const &external_address);
MuddlePtr CreateMuddle(char const network[4], network::NetworkManager const &nm,
std::string const &external_address);
} // namespace muddle
} // namespace fetch
| 28.989933 | 98 | 0.676351 | [
"vector"
] |
143aade4b66696ad4fde531ee5d970df96cac0a3 | 12,046 | cxx | C++ | linux_packages/source/hypre-2.9.0b/src/FEI_mv/femli/mli_solver_mls.cxx | pangkeji/warp3d | 8b273b337e557f734298940a63291697cd561d02 | [
"NCSA"
] | 75 | 2015-07-06T18:14:20.000Z | 2022-01-24T02:54:32.000Z | src/ilPSP/layer_0/3rd_party/Hypre2.9.0b/src/FEI_mv/femli/mli_solver_mls.cxx | leyel/BoSSS | 39f58a1a64a55e44f51384022aada20a5b425230 | [
"Apache-2.0"
] | 15 | 2017-04-07T18:09:58.000Z | 2022-02-28T01:48:33.000Z | src/ilPSP/layer_0/3rd_party/Hypre2.9.0b/src/FEI_mv/femli/mli_solver_mls.cxx | leyel/BoSSS | 39f58a1a64a55e44f51384022aada20a5b425230 | [
"Apache-2.0"
] | 41 | 2015-05-24T23:24:54.000Z | 2021-12-13T22:07:45.000Z | /*BHEADER**********************************************************************
* Copyright (c) 2008, Lawrence Livermore National Security, LLC.
* Produced at the Lawrence Livermore National Laboratory.
* This file is part of HYPRE. See file COPYRIGHT for details.
*
* HYPRE is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License (as published by the Free
* Software Foundation) version 2.1 dated February 1999.
*
* $Revision: 1.1 $
***********************************************************************EHEADER*/
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <math.h>
#include "mli_solver_mls.h"
#include "_hypre_parcsr_mv.h"
#define hmin(x,y) (((x) < (y)) ? (x) : (y))
/******************************************************************************
* constructor
*---------------------------------------------------------------------------*/
MLI_Solver_MLS::MLI_Solver_MLS(char *name) : MLI_Solver(name)
{
Amat_ = NULL;
Vtemp_ = NULL;
Wtemp_ = NULL;
Ytemp_ = NULL;
maxEigen_ = 0.0;
mlsDeg_ = 1;
mlsBoost_ = 1.1;
mlsOver_ = 1.1;
for ( int i = 0; i < 5; i++ ) mlsOm_[i] = 0.0;
mlsOm2_ = 1.8;
for ( int j = 0; j < 5; j++ ) mlsCf_[j] = 0.0;
zeroInitialGuess_ = 0;
}
/******************************************************************************
* destructor
*---------------------------------------------------------------------------*/
MLI_Solver_MLS::~MLI_Solver_MLS()
{
Amat_ = NULL;
if ( Vtemp_ != NULL ) delete Vtemp_;
if ( Wtemp_ != NULL ) delete Wtemp_;
if ( Ytemp_ != NULL ) delete Ytemp_;
}
/******************************************************************************
* set up the smoother
* (This setup is modified from Marian Brezina's code in ML)
*---------------------------------------------------------------------------*/
int MLI_Solver_MLS::setup(MLI_Matrix *mat)
{
int i, j, nGrid, MAX_DEG=5, nSamples=20000;
double cosData0, cosData1, coord, *ritzValues;
double sample, gridStep, rho, rho2;
double pi=4.e0 * atan(1.e0); /* 3.141592653589793115998e0; */
/*-----------------------------------------------------------------
* check that proper spectral radius is passed in
*-----------------------------------------------------------------*/
Amat_ = mat;
if ( maxEigen_ <= 0.0 )
{
ritzValues = new double[2];
MLI_Utils_ComputeExtremeRitzValues( (hypre_ParCSRMatrix *)
Amat_->getMatrix(), ritzValues, 0 );
maxEigen_ = ritzValues[0];
delete [] ritzValues;
}
/*-----------------------------------------------------------------
* compute the coefficients
*-----------------------------------------------------------------*/
for ( i = 0; i < MAX_DEG; i++ ) mlsOm_[i] = 0.e0;
rho = mlsOver_ * maxEigen_;
cosData1 = 1.e0 / (2.e0 * (double) mlsDeg_ + 1.e0);
for ( i = 0; i < mlsDeg_; i++ )
{
cosData0 = (2.0 * (double) i + 2.0) * pi;
mlsOm_[i] = 2.e0 / (rho * (1.e0 - cos(cosData0 * cosData1)));
}
mlsCf_[0] = mlsOm_[0] + mlsOm_[1] + mlsOm_[2] + mlsOm_[3] + mlsOm_[4];
mlsCf_[1] = -(mlsOm_[0]*mlsOm_[1] + mlsOm_[0]*mlsOm_[2]
+ mlsOm_[0]*mlsOm_[3] + mlsOm_[0]*mlsOm_[4]
+ mlsOm_[1]*mlsOm_[2] + mlsOm_[1]*mlsOm_[3]
+ mlsOm_[1]*mlsOm_[4] + mlsOm_[2]*mlsOm_[3]
+ mlsOm_[2]*mlsOm_[4] + mlsOm_[3]*mlsOm_[4]);
mlsCf_[2] = +(mlsOm_[0]*mlsOm_[1]*mlsOm_[2] + mlsOm_[0]*mlsOm_[1]*mlsOm_[3]
+ mlsOm_[0]*mlsOm_[1]*mlsOm_[4] + mlsOm_[0]*mlsOm_[2]*mlsOm_[3]
+ mlsOm_[0]*mlsOm_[2]*mlsOm_[4] + mlsOm_[0]*mlsOm_[3]*mlsOm_[4]
+ mlsOm_[1]*mlsOm_[2]*mlsOm_[3] + mlsOm_[1]*mlsOm_[2]*mlsOm_[4]
+ mlsOm_[1]*mlsOm_[3]*mlsOm_[4] + mlsOm_[2]*mlsOm_[3]*mlsOm_[4]);
mlsCf_[3] = -(mlsOm_[0]*mlsOm_[1]*mlsOm_[2]*mlsOm_[3]
+ mlsOm_[0]*mlsOm_[1]*mlsOm_[2]*mlsOm_[4]
+ mlsOm_[0]*mlsOm_[1]*mlsOm_[3]*mlsOm_[4]
+ mlsOm_[0]*mlsOm_[2]*mlsOm_[3]*mlsOm_[4]
+ mlsOm_[1]*mlsOm_[2]*mlsOm_[3]*mlsOm_[4]);
mlsCf_[4] = mlsOm_[0] * mlsOm_[1] * mlsOm_[2] * mlsOm_[3] * mlsOm_[4];
if ( mlsDeg_> 1 )
{
gridStep = rho / (double) nSamples;
nGrid = (int) hmin(((int)(rho/gridStep))+1, nSamples);
rho2 = 0.e0;
for ( i = 0; i < nGrid-1; i++ )
{
coord = (double)(i+1) * gridStep;
sample = 1.e0 - mlsOm_[0] * coord;
for ( j = 1; j < mlsDeg_; j++)
sample *= (1.0 - mlsOm_[j] * coord);
sample *= sample * coord;
if (sample > rho2) rho2 = sample;
}
}
else rho2 = 4.0 / ( 27.0 * mlsOm_[0] );
if ( mlsDeg_ < 2) mlsBoost_ = 1.019e0;
else mlsBoost_ = 1.025e0;
rho2 *= mlsBoost_;
mlsOm2_ = 2.e0 / rho2;
/*-----------------------------------------------------------------
* allocate temporary vectors
*-----------------------------------------------------------------*/
if ( Vtemp_ != NULL ) delete Vtemp_;
if ( Wtemp_ != NULL ) delete Wtemp_;
if ( Ytemp_ != NULL ) delete Ytemp_;
Vtemp_ = mat->createVector();
Wtemp_ = mat->createVector();
Ytemp_ = mat->createVector();
return 0;
}
/******************************************************************************
* apply function
*---------------------------------------------------------------------------*/
int MLI_Solver_MLS::solve(MLI_Vector *fIn, MLI_Vector *uIn)
{
int i, localNRows, deg;
double omega, coef, *uData;
double *VtempData, *WtempData, *YtempData;
hypre_ParCSRMatrix *A;
hypre_CSRMatrix *ADiag;
hypre_ParVector *Vtemp, *Wtemp, *Ytemp, *f, *u;
/*-----------------------------------------------------------------
* check that proper spectral radius is passed in
*-----------------------------------------------------------------*/
if ( maxEigen_ <= 0.0 )
{
printf("MLI_Solver_MLS::solver ERROR - maxEigen <= 0.\n");
exit(1);
}
/*-----------------------------------------------------------------
* fetch machine and smoother parameters
*-----------------------------------------------------------------*/
A = (hypre_ParCSRMatrix *) Amat_->getMatrix();
ADiag = hypre_ParCSRMatrixDiag(A);
localNRows = hypre_CSRMatrixNumRows(ADiag);
f = (hypre_ParVector *) fIn->getVector();
u = (hypre_ParVector *) uIn->getVector();
uData = hypre_VectorData(hypre_ParVectorLocalVector(u));
/*-----------------------------------------------------------------
* create temporary vector
*-----------------------------------------------------------------*/
Vtemp = (hypre_ParVector *) Vtemp_->getVector();
Wtemp = (hypre_ParVector *) Wtemp_->getVector();
Ytemp = (hypre_ParVector *) Ytemp_->getVector();
VtempData = hypre_VectorData(hypre_ParVectorLocalVector(Vtemp));
WtempData = hypre_VectorData(hypre_ParVectorLocalVector(Wtemp));
YtempData = hypre_VectorData(hypre_ParVectorLocalVector(Ytemp));
/*-----------------------------------------------------------------
* Perform MLS iterations
*-----------------------------------------------------------------*/
/* compute Vtemp = f - A u */
hypre_ParVectorCopy(f,Vtemp);
if ( zeroInitialGuess_ != 0 )
{
hypre_ParCSRMatrixMatvec(-1.0, A, u, 1.0, Vtemp);
zeroInitialGuess_ = 0;
}
if ( mlsDeg_ == 1 )
{
coef = mlsCf_[0] * mlsOver_;
/* u = u + coef * Vtemp */
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < localNRows; i++) uData[i] += (coef * VtempData[i]);
/* compute residual Vtemp = A u - f */
hypre_ParVectorCopy(f,Vtemp);
hypre_ParCSRMatrixMatvec(1.0, A, u, -1.0, Vtemp);
/* compute residual Wtemp = (I - omega * A)^deg Vtemp */
hypre_ParVectorCopy(Vtemp,Wtemp);
for ( deg = 0; deg < mlsDeg_; deg++ )
{
omega = mlsOm_[deg];
hypre_ParCSRMatrixMatvec(1.0, A, Wtemp, 0.0, Vtemp);
for (i = 0; i < localNRows; i++)
WtempData[i] -= (omega * VtempData[i]);
}
/* compute residual Vtemp = (I - omega * A)^deg Wtemp */
hypre_ParVectorCopy(Wtemp,Vtemp);
for ( deg = mlsDeg_-1; deg > -1; deg-- )
{
omega = mlsOm_[deg];
hypre_ParCSRMatrixMatvec(1.0, A, Vtemp, 0.0, Wtemp);
for (i = 0; i < localNRows; i++)
VtempData[i] -= (omega * WtempData[i]);
}
/* compute u = u - coef * Vtemp */
coef = mlsOver_ * mlsOm2_;
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < localNRows; i++) uData[i] -= ( coef * VtempData[i] );
}
else
{
/* Ytemp = coef * Vtemp */
coef = mlsCf_[0];
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < localNRows; i++) YtempData[i] = (coef * VtempData[i]);
/* Wtemp = coef * Vtemp */
for ( deg = 1; deg < deg; deg++ )
{
hypre_ParCSRMatrixMatvec(1.0, A, Vtemp, 0.0, Wtemp);
hypre_ParVectorCopy(Wtemp,Vtemp);
coef = mlsCf_[deg];
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < localNRows; i++)
YtempData[i] += ( coef * WtempData[i] );
}
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < localNRows; i++) uData[i] += (mlsOver_ * YtempData[i]);
/* compute residual Vtemp = A u - f */
hypre_ParVectorCopy(f,Vtemp);
hypre_ParCSRMatrixMatvec(1.0, A, u, -1.0, Vtemp);
/* compute residual Wtemp = (I - omega * A)^deg Vtemp */
hypre_ParVectorCopy(Vtemp,Wtemp);
for ( deg = 0; deg < mlsDeg_; deg++ )
{
omega = mlsOm_[deg];
hypre_ParCSRMatrixMatvec(1.0, A, Wtemp, 0.0, Vtemp);
for (i = 0; i < localNRows; i++)
WtempData[i] -= (omega * VtempData[i]);
}
/* compute residual Vtemp = (I - omega * A)^deg Wtemp */
hypre_ParVectorCopy(Wtemp,Vtemp);
for ( deg = mlsDeg_-1; deg > -1; deg-- )
{
omega = mlsOm_[deg];
hypre_ParCSRMatrixMatvec(1.0, A, Vtemp, 0.0, Wtemp);
for (i = 0; i < localNRows; i++)
VtempData[i] -= (omega * WtempData[i]);
}
/* compute u = u - coef * Vtemp */
coef = mlsOver_ * mlsOm2_;
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < localNRows; i++) uData[i] -= ( coef * VtempData[i] );
}
return(0);
}
/******************************************************************************
* set MLS parameters
*---------------------------------------------------------------------------*/
int MLI_Solver_MLS::setParams( char *paramString, int argc, char **argv )
{
if ( !strcmp(paramString, "maxEigen") )
{
if ( argc != 1 )
{
printf("MLI_Solver_MLS::setParams ERROR : needs 1 or 2 args.\n");
return 1;
}
maxEigen_ = *(double*) argv[0];
if ( maxEigen_ < 0.0 )
{
printf("MLI_Solver_MLS::setParams ERROR - maxEigen <= 0 (%e)\n",
maxEigen_);
maxEigen_ = 0.0;
return 1;
}
}
else if ( !strcmp(paramString, "zeroInitialGuess") )
{
zeroInitialGuess_ = 1;
}
return 0;
}
/******************************************************************************
* set MLS parameters
*---------------------------------------------------------------------------*/
int MLI_Solver_MLS::setParams( double eigen )
{
if ( maxEigen_ <= 0.0 )
{
printf("MLI_Solver_MLS::setParams WARNING - maxEigen <= 0.\n");
return 1;
}
maxEigen_ = eigen;
return 0;
}
| 32.733696 | 81 | 0.471277 | [
"vector"
] |
14431cfaaf8f84399523bf9effd3617bf9b8bed9 | 5,181 | cpp | C++ | src/xtd.drawing.native.wxwidgets/src/xtd/drawing/native/wxwidgets/font_family.cpp | ExternalRepositories/xtd | 5889d69900ad22a00fcb640d7850a1d599cf593a | [
"MIT"
] | null | null | null | src/xtd.drawing.native.wxwidgets/src/xtd/drawing/native/wxwidgets/font_family.cpp | ExternalRepositories/xtd | 5889d69900ad22a00fcb640d7850a1d599cf593a | [
"MIT"
] | null | null | null | src/xtd.drawing.native.wxwidgets/src/xtd/drawing/native/wxwidgets/font_family.cpp | ExternalRepositories/xtd | 5889d69900ad22a00fcb640d7850a1d599cf593a | [
"MIT"
] | null | null | null | #include <algorithm>
#include <cmath>
#include <xtd/convert_string.h>
#define __XTD_DRAWING_NATIVE_LIBRARY__
#include <xtd/drawing/native/font.h>
#include <xtd/drawing/native/font_family.h>
#undef __XTD_DRAWING_NATIVE_LIBRARY__
#include <wx/app.h>
#include <wx/colour.h>
#include <wx/fontenum.h>
#include <wx/dcscreen.h>
using namespace xtd;
using namespace xtd::drawing::native;
namespace {
#if defined(__APPLE__)
float pixel_to_native_font_graphics_untit(float size) {
return size; // font is in points
}
#else
float pixel_to_native_font_graphics_untit(float size) {
auto dpi = 72;
if (wxTheApp) {
wxScreenDC hdc;
dpi = hdc.GetPPI().GetHeight();
}
return size / 96.0f * dpi; // font is in pixels and not in points
}
#endif
}
intptr_t font_family::create(const ustring& name) {
if (name == ".AppleSystemUIFont") return reinterpret_cast<intptr_t>(new ustring(name));
return wxFontEnumerator::IsValidFacename(name) ? reinterpret_cast<intptr_t>(new ustring(name)) : 0;
}
void font_family::destroy(intptr_t font_family) {
delete reinterpret_cast<ustring*>(font_family);
}
ustring font_family::generic_serif_name() {
/*
wxFontInfo font_info;
font_info.Family(wxFONTFAMILY_ROMAN);
wxFont font(font_info);
return font.GetFaceName().c_str().AsWChar();
*/
#if defined(__WXMSW__)
return L"Times New Roman";
#elif defined(__APPLE__)
return L"Times New Roman";
#elif defined(__WXGTK__)
return L"Serif";
#else
return L"Serif";
#endif
}
ustring font_family::generic_sans_serif_name() {
/*
wxFontInfo font_info;
font_info.Family(wxFONTFAMILY_SWISS);
wxFont font(font_info);
return font.GetFaceName().c_str().AsWChar();
*/
#if defined(__WXMSW__)
return L"Microsoft Sans Serif";
#elif defined(__APPLE__)
return L"Arial";
#elif defined(__WXGTK__)
return L"Sans";
#else
return L"Sans";
#endif
}
ustring font_family::generic_monospace_name() {
/*
wxFontInfo font_info;
font_info.Family(wxFONTFAMILY_TELETYPE);
wxFont font(font_info);
return font.GetFaceName().c_str().AsWChar();
*/
#if defined(__WXMSW__)
return L"Courier New";
#elif defined(__APPLE__)
return L"Courier";
#elif defined(__WXGTK__)
return L"Monospace";
#else
return L"Monospace";
#endif
}
std::vector<ustring> font_family::installed_font_families() {
std::vector<ustring> families;
for (const wxString& name : wxFontEnumerator::GetFacenames())
if (name[0] != '@') families.push_back(name.c_str().AsWChar());
std::sort(families.begin(), families.end());
return families;
}
int32_t font_family::get_cell_ascent(intptr_t font_family, int32_t em_height, bool bold, bool italic, bool underline, bool strikeout) {
if (!wxTheApp) return em_height;
wxScreenDC hdc;
wxFont font(pixel_to_native_font_graphics_untit(em_height), wxFontFamily::wxFONTFAMILY_DEFAULT, italic ? wxFontStyle::wxFONTSTYLE_ITALIC : wxFontStyle::wxFONTSTYLE_NORMAL, bold ? wxFontWeight::wxFONTWEIGHT_BOLD : wxFontWeight::wxFONTWEIGHT_NORMAL, underline, convert_string::to_wstring(*reinterpret_cast<ustring*>(font_family)));
font.SetStrikethrough(strikeout);
wxFont default_font = hdc.GetFont();
hdc.SetFont(font);
wxFontMetrics metrics = hdc.GetFontMetrics();
hdc.SetFont(default_font);
return std::round(static_cast<double>(metrics.ascent) / metrics.height * em_height);
}
int32_t font_family::get_cell_descent(intptr_t font_family, int32_t em_height, bool bold, bool italic, bool underline, bool strikeout) {
if (!wxTheApp) return 0;
wxScreenDC hdc;
wxFont font(pixel_to_native_font_graphics_untit(em_height), wxFontFamily::wxFONTFAMILY_DEFAULT, italic ? wxFontStyle::wxFONTSTYLE_ITALIC : wxFontStyle::wxFONTSTYLE_NORMAL, bold ? wxFontWeight::wxFONTWEIGHT_BOLD : wxFontWeight::wxFONTWEIGHT_NORMAL, underline, convert_string::to_wstring(*reinterpret_cast<ustring*>(font_family)));
font.SetStrikethrough(strikeout);
wxFont default_font = hdc.GetFont();
hdc.SetFont(font);
wxFontMetrics metrics = hdc.GetFontMetrics();
hdc.SetFont(default_font);
return std::round(static_cast<double>(metrics.descent) / metrics.height * em_height);
}
int32_t font_family::get_line_spacing(intptr_t font_family, int32_t em_height, bool bold, bool italic, bool underline, bool strikeout) {
if (!wxTheApp) return em_height;
wxScreenDC hdc;
wxFont font(pixel_to_native_font_graphics_untit(em_height), wxFontFamily::wxFONTFAMILY_DEFAULT, italic ? wxFontStyle::wxFONTSTYLE_ITALIC : wxFontStyle::wxFONTSTYLE_NORMAL, bold ? wxFontWeight::wxFONTWEIGHT_BOLD : wxFontWeight::wxFONTWEIGHT_NORMAL, underline, convert_string::to_wstring(*reinterpret_cast<ustring*>(font_family)));
font.SetStrikethrough(strikeout);
wxFont default_font = hdc.GetFont();
hdc.SetFont(font);
wxFontMetrics metrics = hdc.GetFontMetrics();
hdc.SetFont(default_font);
return std::round(static_cast<double>(metrics.height + metrics.externalLeading) / metrics.height * em_height);
}
ustring font_family::get_name(intptr_t font_family, int32_t language) {
return *reinterpret_cast<ustring*>(font_family);
}
bool font_family::is_style_avaible(intptr_t font_family, bool bold, bool italic, bool underline, bool strikeout) {
return true;
}
| 35.244898 | 331 | 0.762787 | [
"vector"
] |
1444069264c42f3fd1676d7aed862d7f329ce5e9 | 5,448 | cpp | C++ | src/Base/FileFormats/PincoFormat/PincoFormatDataStore.cpp | PhilipVinc/PincoSimulator | 562192cf3b09d0e67be7e6fee67ff9b59fbc3fd3 | [
"MIT"
] | 1 | 2017-10-23T13:22:01.000Z | 2017-10-23T13:22:01.000Z | src/Base/FileFormats/PincoFormat/PincoFormatDataStore.cpp | PhilipVinc/PincoSimulator | 562192cf3b09d0e67be7e6fee67ff9b59fbc3fd3 | [
"MIT"
] | null | null | null | src/Base/FileFormats/PincoFormat/PincoFormatDataStore.cpp | PhilipVinc/PincoSimulator | 562192cf3b09d0e67be7e6fee67ff9b59fbc3fd3 | [
"MIT"
] | null | null | null | //
// PincoFormatDataStore.cpp
// TWMC++
//
// Created by Filippo Vicentini on 22/09/17.
// Copyright © 2017 Filippo Vicentini. All rights reserved.
//
#include "PincoFormatDataStore.hpp"
#include "ChunkFileSet.hpp"
#include "ChunkRegister.hpp"
#include "Base/TaskResults.hpp"
#include <algorithm>
#include <memory>
using namespace std;
PincoFormatDataStore::PincoFormatDataStore(const Settings* settings,
std::string folderName) :
DataStore(settings, folderName)
{
chunkRootPath = dataStoreBasePath + "/";
cRegister = new ChunkRegister(chunkRootPath + "_register.bin");
chunkIds = cRegister->GetUsedChunkIds();
cachedWriteChunk = nullptr;
}
PincoFormatDataStore::~PincoFormatDataStore()
{
for (auto it=chunkFileSets.begin(); it != chunkFileSets.end(); it++)
{
delete it->second;
}
delete cRegister;
}
size_t PincoFormatDataStore::NewChunkId()
{
size_t maxUsedId = *std::max_element(chunkIds.begin(), chunkIds.end());
maxUsedId ++;
return maxUsedId;
}
void PincoFormatDataStore::CreateNewChunk()
{
size_t id = NewChunkId();
ChunkFileSet* chunk = new ChunkFileSet(chunkRootPath , datasetN, id);
chunk->SetMinChunkSize(idealFileSize);
chunkIds.insert(id);
chunkFileSets[id] = chunk;
cachedWriteChunk = chunk;
}
ChunkFileSet* PincoFormatDataStore::GetWritableChunk()
{
if (cachedWriteChunk != nullptr && !cachedWriteChunk->IsChunkBig())
{
return cachedWriteChunk;
}
CreateNewChunk();
return cachedWriteChunk;
}
ChunkFileSet* PincoFormatDataStore::Chunk(size_t chunkId, bool load) {
if (chunkIds.count(chunkId) == 0) {
cerr << "ERROR" << endl;
} // else
if (chunkFileSets.count(chunkId) == 1) {
return chunkFileSets[chunkId];
} else {
ChunkFileSet* chunk = new ChunkFileSet(chunkRootPath , datasetN, chunkId, load);
chunkFileSets[chunkId] = chunk;
return chunk;
}
}
void PincoFormatDataStore::Initialise(std::unique_ptr<TaskResults> const& results) {
datasetN = results->NumberOfDataSets();
if (!cRegister->registerInitialized) { cRegister->InitializeRegisterHeader(results);}
initialised = true;
}
void PincoFormatDataStore::StoreDataSimple(std::unique_ptr<TaskResults> const& results)
{
if (!initialised) { Initialise(results);};
ChunkFileSet * cnk = GetWritableChunk();
size_t offset = cnk->WriteToChunk(results, DatasetNamesInRegister());
cRegister->RegisterStoredData(results, cnk->GetId(), offset, Settings::SaveSettings::saveIdFiles);
}
void PincoFormatDataStore::StoreData(std::unique_ptr<TaskResults> const& results)
{
if (!initialised) { Initialise(results);};
ChunkFileSet * cnk = GetWritableChunk();
size_t offset = cnk->WriteToChunk(results, DatasetNamesInRegister());
cRegister->RegisterStoredData(results, cnk->GetId(), offset);
}
void PincoFormatDataStore::ProvideDatasetNames(vector<string> names)
{
datasetN = names.size();
}
void PincoFormatDataStore::LoadListOfStoredDataEvents()
{
// TODO
return;
}
const std::set<size_t>& PincoFormatDataStore::UsedIds()
{
return cRegister->GetSavedTasksIds();
}
std::unique_ptr<TaskResults> PincoFormatDataStore::LoadResult(size_t trajId, bool lastFrameOnly)
{
if (!initialised)
datasetN = cRegister->datasetNames.size();
std::unique_ptr<TaskResults> result(nullptr); //TODO*/
if (lastFrameOnly) {
ChunkRegister::RegisterEntry *regEntry = cRegister->GetFinalEntryById(trajId);
ChunkFileSet *cnk = Chunk(regEntry->chunk_id);
std::vector<std::tuple<void *, size_t, size_t>> data = cnk->ReadEntry(regEntry->chunk_offset, lastFrameOnly);
result = ResultsFactory::makeUniqueNewInstance("TWMC"); //TODO
result->SetId(regEntry->traj_id);
result->DeSerializeExtraData(regEntry->additionalData, 2); //TODO hardcoded 2
int i = 0;
for (auto d : data) {
result->AddDataset(cRegister->datasetNames[i],
std::make_tuple<const void *, size_t>(std::get<0>(d), std::move(std::get<1>(d))),
std::get<2>(d), cRegister->dimensionalityData[i]); //TODO*/
i++;
delete[] static_cast<char *>(std::get<0>(d));
}
} else {
std::vector<ChunkRegister::RegisterEntry*> entries = cRegister->GetEntryById(trajId);
for (auto entry: entries) {
ChunkFileSet *cnk = Chunk(entry->chunk_id, true);
std::vector<std::tuple<void *, size_t, size_t>> data = cnk->ReadEntry(entry->chunk_offset);
std::unique_ptr<TaskResults> newResult = ResultsFactory::makeUniqueNewInstance("TWMC"); //TODO
newResult->SetId(entry->traj_id);
newResult->DeSerializeExtraData(entry->additionalData, 2); //TODO hardcoded 2
int i = 0;
for (auto d : data) {
newResult->AddDataset(cRegister->datasetNames[i],
std::make_tuple<const void *, size_t>(std::get<0>(d), std::move(std::get<1>(d))),
std::get<2>(d), cRegister->dimensionalityData[i]); //TODO*/
i++;
delete[] static_cast<char *>(std::get<0>(d));
}
if (result)
result->AppendResult(std::move(newResult));
else
result = std::move(newResult);
}
}
return result;
}
| 30.606742 | 117 | 0.650147 | [
"vector"
] |
144654bb0c4a0cfba3f0d6fdfc70a989b1d899c3 | 1,079 | cpp | C++ | src/_leetcode/leet_350.cpp | turesnake/leetPractice | a87b9b90eb8016038d7e5d3ad8e50e4ceb54d69b | [
"MIT"
] | null | null | null | src/_leetcode/leet_350.cpp | turesnake/leetPractice | a87b9b90eb8016038d7e5d3ad8e50e4ceb54d69b | [
"MIT"
] | null | null | null | src/_leetcode/leet_350.cpp | turesnake/leetPractice | a87b9b90eb8016038d7e5d3ad8e50e4ceb54d69b | [
"MIT"
] | null | null | null | /*
* ====================== leet_350.cpp ==========================
* -- tpr --
* CREATE -- 2020.07.13
* MODIFY --
* ----------------------------------------------------------
* 350. 两个数组的交集 II
*/
#include "innLeet.h"
#include "TreeNode1.h"
#include "ListNode.h"
namespace leet_350 {//~
// 73% 7%
class S{
public:
std::vector<int> intersect( std::vector<int>& nums1, std::vector<int>& nums2) {
std::unordered_map<int,int> umap {};
for( int i : nums1 ){
umap[i]++;
}
std::vector<int> outs {};
for( int i : nums2 ){
if( umap.count(i)>0 ){
outs.push_back(i);
umap.at(i)--;
if( umap.at(i)==0 ){
umap.erase(i);
}
}
}
return outs;
}
};
//=========================================================//
void main_(){
debug::log( "\n~~~~ leet: 89 :end ~~~~\n" );
}
}//~
| 18.929825 | 83 | 0.318814 | [
"vector"
] |
14484fc6cd3b5ed975aa76245f60fdd1f5905a7d | 2,171 | hpp | C++ | include/gold/button.hpp | josiest/gold | 140d7c92fce8548b8a4cc6d2eda4be5b12e32975 | [
"MIT"
] | null | null | null | include/gold/button.hpp | josiest/gold | 140d7c92fce8548b8a4cc6d2eda4be5b12e32975 | [
"MIT"
] | null | null | null | include/gold/button.hpp | josiest/gold | 140d7c92fce8548b8a4cc6d2eda4be5b12e32975 | [
"MIT"
] | null | null | null | #pragma once
// frameworks
#include <SDL.h>
// resource handlers
#include "gold/serialization.hpp" // unqiue_texture
// data types
#include "gold/widget.hpp"
#include <cstdint>
namespace au {
class button : public itext_widget {
public:
button() = delete;
button(SDL_Renderer * renderer, SDL_Rect const & bounds,
std::uint32_t border_thickness, std::uint32_t padding,
SDL_Color const & standard_color, SDL_Color const & hover_color,
SDL_Color const & click_color, SDL_Color const & fill_color,
TTF_Font * font, std::string const & text);
inline bool operator !() const { return not _content; }
// interface methods
inline SDL_Rect bounds() const { return _bounds; }
void render(SDL_Renderer * renderer);
inline std::size_t id() const { return _id; }
inline bool is_active() const { return _active; }
void activate() { _active = true; }
void deactivate() { _active = false; }
inline std::string get_text() const { return _text; }
void set_text(std::string const & text);
private:
static std::size_t constexpr _seed = 7878831530993720721u;
static std::size_t _next_id;
std::size_t const _id;
SDL_Renderer * _renderer;
SDL_Rect _bounds;
int _border_thickness;
int _padding;
SDL_Color _standard_color;
SDL_Color _hover_color;
SDL_Color _click_color;
SDL_Color _fill_color;
TTF_Font * _font;
std::string _text;
unique_texture _content;
bool _active;
// render text using the object's font
SDL_Texture * _render_text(std::string const & text);
// get the bounding rect of the button inside the border
SDL_Rect _inner_bounds() const;
// get the maximum bounding rect for the inner content
SDL_Rect _max_content_bounds() const;
// get the bounding rect to draw the texture to
SDL_Rect _content_bounds() const;
// get the raw bounding rect of the texture
SDL_Rect _texture_bounds() const;
// determine if the mouse is in the bounds of this button
bool _mouse_in_bounds() const;
// determine of the mouse was clicked
bool _mouse_clicked() const;
};
}
| 26.47561 | 75 | 0.68678 | [
"render",
"object"
] |
144993c6e6788fada28a395b712042471db05492 | 892 | cpp | C++ | cpp/boost/container/vector_move_container/main.cpp | kanganabhargava/learning-c-cpp | 4beff4d800650d100b575a4067cc0e654a330f79 | [
"MIT"
] | 10 | 2018-06-14T07:21:15.000Z | 2022-02-13T14:46:42.000Z | cpp/boost/container/vector_move_container/main.cpp | kanganabhargava/learning-c-cpp | 4beff4d800650d100b575a4067cc0e654a330f79 | [
"MIT"
] | null | null | null | cpp/boost/container/vector_move_container/main.cpp | kanganabhargava/learning-c-cpp | 4beff4d800650d100b575a4067cc0e654a330f79 | [
"MIT"
] | 5 | 2019-01-10T14:10:11.000Z | 2020-12-08T09:54:30.000Z | #include <boost/container/vector.hpp>
#include <boost/move/utility_core.hpp>
#include <cassert>
// Non-copyable class
class non_copyable {
BOOST_MOVABLE_BUT_NOT_COPYABLE(non_copyable)
public:
non_copyable() {}
non_copyable(BOOST_RV_REF(non_copyable)) {}
non_copyable& operator=(BOOST_RV_REF(non_copyable)) {
return *this;
}
};
int main() {
using namespace boost::container;
// Store non-copyable objects in a vector
vector<non_copyable> v;
non_copyable nc;
v.push_back(boost::move(nc));
assert(v.size() == 1);
// Reserve no longer needs copy-constructible
v.reserve(100);
assert(v.capacity() >= 100);
// This resize overload only needs movable and default constructible
v.resize(200);
assert(v.size() == 200);
// Containers are also movable
vector<non_copyable> v_other(boost::move(v));
assert(v_other.size() == 200);
assert(v.empty());
return 0;
} | 22.3 | 69 | 0.713004 | [
"vector"
] |
144a1ea575d1e8b3b93aca9a128d9da9b435d8d2 | 7,749 | cpp | C++ | jn.cpp | katahiromz/JapaneseNumber | 6adaed627250a383b4596f808c110d4eed1d55cf | [
"MIT"
] | null | null | null | jn.cpp | katahiromz/JapaneseNumber | 6adaed627250a383b4596f808c110d4eed1d55cf | [
"MIT"
] | null | null | null | jn.cpp | katahiromz/JapaneseNumber | 6adaed627250a383b4596f808c110d4eed1d55cf | [
"MIT"
] | null | null | null | #ifdef _WIN32
#include <windows.h>
#include <mmsystem.h>
#endif
#include "jn.hpp"
#include <vector>
#include <cstdlib>
#include <cstring>
#include "resource.h"
const char *JN_wide_to_ansi(int codepage, const wchar_t *str)
{
static char s_buf[1024];
WideCharToMultiByte(codepage, 0, str, -1, s_buf, ARRAYSIZE(s_buf), NULL, NULL);
return s_buf;
}
struct DATA
{
long long value;
int nWaveID;
int nHiraID;
int nKataID;
int nKanjiID;
std::wstring hiragana;
std::wstring katakana;
std::wstring kanji;
};
#define DEFINE_DATA(value, wave_id, hira_id, kata_id, kanji_id, higa, kata, kanji, wave_file) \
{ value, wave_id, hira_id, kata_id, kanji_id },
static DATA s_data[] =
{
#include "data.h"
};
wchar_t *JN_load_string(int nID)
{
static int s_index = 0;
const int cchBuffMax = 1024;
static wchar_t s_sz[4][cchBuffMax];
wchar_t *pszBuff = s_sz[s_index];
s_index = (s_index + 1) % ARRAYSIZE(s_sz);
pszBuff[0] = 0;
LoadStringW(NULL, nID, pszBuff, cchBuffMax);
return pszBuff;
}
bool JN_init(void)
{
size_t i, count = ARRAYSIZE(s_data);
for (i = 0; i < count; ++i)
{
s_data[i].hiragana = JN_load_string(s_data[i].nHiraID);
s_data[i].katakana = JN_load_string(s_data[i].nKataID);
s_data[i].kanji = JN_load_string(s_data[i].nKanjiID);
}
return true;
}
int JN_find_hiragana(int nHiraID)
{
size_t i, count = ARRAYSIZE(s_data);
for (i = 0; i < count; ++i)
{
if (s_data[i].nHiraID == nHiraID)
return (int)i;
}
return -1;
}
int JN_find_katakana(int nKataID)
{
size_t i, count = ARRAYSIZE(s_data);
for (i = 0; i < count; ++i)
{
if (s_data[i].nKataID == nKataID)
return (int)i;
}
return -1;
}
int JN_find_kansuuji(int nKanjiID)
{
size_t i, count = ARRAYSIZE(s_data);
for (i = 0; i < count; ++i)
{
if (s_data[i].nKanjiID == nKanjiID)
return (int)i;
}
return -1;
}
std::wstring JN_get_hiragana(int nHiraID)
{
int index = JN_find_hiragana(nHiraID);
if (index != -1)
return s_data[index].hiragana;
return L"";
}
std::wstring JN_get_katakana(int nKataID)
{
int index = JN_find_katakana(nKataID);
if (index != -1)
return s_data[index].katakana;
return L"";
}
std::wstring JN_get_kansuuji(int nKanjiID)
{
int index = JN_find_kansuuji(nKanjiID);
if (index != -1)
return s_data[index].kanji;
return L"";
}
std::wstring JN_get_kansuuji_number(long long number, bool zero_is_omitted)
{
std::wstring ret;
if (number > 999999999999999999)
{
return JN_load_string(IDS_INVALID);
}
if (number < 0)
{
ret += JN_load_string(IDS_KATAKANA_MINUS);
ret += JN_get_kansuuji_number(-number, zero_is_omitted);
return ret;
}
if (number == 0)
{
if (!zero_is_omitted)
ret += JN_load_string(IDS_KANJI_0);
return ret;
}
if (number >= KEI)
{
ret += JN_get_kansuuji_number(number / KEI, zero_is_omitted);
ret += JN_load_string(IDS_KANJI_KEI);
ret += JN_get_kansuuji_number(number % KEI, true);
return ret;
}
if (number >= CHOU)
{
ret += JN_get_kansuuji_number(number / CHOU, zero_is_omitted);
ret += JN_load_string(IDS_KANJI_CHOU);
ret += JN_get_kansuuji_number(number % CHOU, true);
return ret;
}
if (number >= OKU)
{
ret += JN_get_kansuuji_number(number / OKU, zero_is_omitted);
ret += JN_load_string(IDS_KANJI_OKU);
ret += JN_get_kansuuji_number(number % OKU, true);
return ret;
}
if (number >= MAN)
{
ret += JN_get_kansuuji_number(number / MAN, zero_is_omitted);
ret += JN_load_string(IDS_KANJI_MAN);
ret += JN_get_kansuuji_number(number % MAN, true);
return ret;
}
if (number >= SEN)
{
ret += JN_load_string(IDS_KANJI_SEN_1 + (int)(number / SEN) - 1);
ret += JN_get_kansuuji_number(number % SEN, true);
return ret;
}
if (number >= HYAKU)
{
ret += JN_load_string(IDS_KANJI_100 + (int)(number / HYAKU) - 1);
ret += JN_get_kansuuji_number(number % HYAKU, true);
return ret;
}
if (number >= 20)
{
ret += JN_load_string(IDS_KANJI_20 + (int)(number / JUU) - 2);
ret += JN_get_kansuuji_number(number % JUU, true);
return ret;
}
ret += JN_load_string(IDS_KANJI_1 + (int)number - 1);
return ret;
}
int JN_longest_match_hiragana(const wchar_t *str)
{
int maxi = -1;
size_t i, maxlen = 0, count = ARRAYSIZE(s_data);
for (i = 0; i < count; ++i)
{
size_t len = s_data[i].hiragana.size();
if (std::memcmp(s_data[i].hiragana.c_str(), str, len * sizeof(wchar_t)) == 0)
{
if (maxlen < len)
{
maxi = (int)i;
maxlen = len;
}
}
}
return maxi;
}
int JN_longest_match_katakana(const wchar_t *str)
{
int maxi = -1;
size_t i, maxlen = 0, count = ARRAYSIZE(s_data);
for (i = 0; i < count; ++i)
{
size_t len = s_data[i].katakana.size();
if (std::memcmp(s_data[i].katakana.c_str(), str, len * sizeof(wchar_t)) == 0)
{
if (maxlen < len)
{
maxi = (int)i;
maxlen = len;
}
}
}
return maxi;
}
int JN_longest_match_kanji(const wchar_t *str)
{
int maxi = -1;
size_t i, maxlen = 0, count = ARRAYSIZE(s_data);
for (i = 0; i < count; ++i)
{
size_t len = s_data[i].kanji.size();
if (std::memcmp(s_data[i].kanji.c_str(), str, len * sizeof(wchar_t)) == 0)
{
if (maxlen < len)
{
maxi = (int)i;
maxlen = len;
}
}
}
return maxi;
}
std::wstring JN_get_hiragana_number(long long number, bool zero_is_omitted)
{
if (number > 999999999999999999)
{
return JN_load_string(IDS_INVALID);
}
std::wstring kanji = JN_get_kansuuji_number(number, false);
std::wstring hiragana;
const wchar_t *pch = kanji.c_str();
while (*pch)
{
int i = JN_longest_match_kanji(pch);
hiragana += s_data[i].hiragana;
pch += s_data[i].kanji.size();
}
return hiragana;
}
std::wstring JN_get_katakana_number(long long number, bool zero_is_omitted)
{
if (number > 999999999999999999)
{
return JN_load_string(IDS_INVALID);
}
std::wstring kanji = JN_get_kansuuji_number(number, false);
std::wstring katakana;
const wchar_t *pch = kanji.c_str();
while (*pch)
{
int i = JN_longest_match_kanji(pch);
katakana += s_data[i].katakana;
pch += s_data[i].kanji.size();
}
return katakana;
}
void JN_speak_japanese_number(long long number)
{
std::wstring hiragana = JN_get_hiragana_number(number, false);
const wchar_t *pch = hiragana.c_str();
std::vector<int> waves;
while (*pch)
{
int i = JN_longest_match_hiragana(pch);
waves.push_back(i);
pch += s_data[i].hiragana.size();
}
for (auto i : waves)
{
PlaySound(MAKEINTRESOURCE(s_data[i].nWaveID),
GetModuleHandle(NULL),
SND_SYNC | SND_NODEFAULT | SND_NOSTOP | SND_RESOURCE);
}
}
| 25.159091 | 96 | 0.557749 | [
"vector"
] |
14574c62da2d0a2c60177a752882038b0a71fa6b | 23,275 | cpp | C++ | it2nsf/source/toadloader.cpp | mukunda-/it2nsf | 62765a9627b7be45d570d444057f37585f0406d8 | [
"BSD-3-Clause"
] | 5 | 2015-07-13T00:58:07.000Z | 2022-03-20T16:49:47.000Z | it2nsf/source/toadloader.cpp | mukunda-/it2nsf | 62765a9627b7be45d570d444057f37585f0406d8 | [
"BSD-3-Clause"
] | 1 | 2018-05-12T20:43:32.000Z | 2018-05-12T20:43:32.000Z | it2nsf/source/toadloader.cpp | mukunda-/it2nsf | 62765a9627b7be45d570d444057f37585f0406d8 | [
"BSD-3-Clause"
] | 3 | 2018-05-12T18:36:18.000Z | 2018-07-10T14:35:42.000Z | /*********************************************************************************************
* IT2NSF
*
* Copyright (C) 2009, mukunda, coda, madbrain, reduz
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the owners nor the names of its contributors may be used to endorse
* or promote products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*********************************************************************************************/
#include "toad.h"
#include "io.h"
namespace ToadLoader {
namespace {
template<typename T>
static void deletePtrVector(std::vector<T *> &vecs) {
for (typename std::vector<T *>::iterator iter = vecs.begin(), ending = vecs.end();
iter != ending;
iter++) {
if (*iter)
delete (*iter);
}
vecs.clear();
}
void copyFstr(char *dest, const char *source, int length) {
dest[length - 1] = 0;
length--;
bool remaining = true;
for (int i = 0; i < length; i++) {
if (remaining) {
if (source[i]) {
dest[i] = source[i];
} else {
remaining = false;
dest[i] = 0;
}
} else {
dest[i] = 0;
}
}
}
}
Bank::Bank(const std::vector<const char *> &files) {
for (u32 i = 0; i < files.size(); i++) {
addModule(files[i]);
}
}
Bank::~Bank() {
deletePtrVector<Module>(modules);
}
void Bank::addModule(const char *filename) {
Module *m = new Module();
m->load(filename);
modules.push_back(m);
}
Module::Module() {
for (int i = 0; i < 26; i++) title[i] = 0;
patternHighlight = 0; //?
length = 0;
cwtv = 0x0214;
cmwt = 0x0214;
flgStereo = true;
instrumentMode = true;
vol0MixOptimizations = false;
linearSlides = true;
oldEffects = false;
gxxCompat = true;
globalVolume = 128;
mixingVolume = 80;
initialSpeed = 6;
initialTempo = 125;
sep = 128; //?
PWD = 0;
messageLength = 0;
message = 0;
for (int i = 0; i < 64; i++) {
channelPan[i] = 0;
channelVolume[i] = 0;
}
for (int i = 0; i < 256; i++)
orders[i] = 0;
}
Module::~Module() {
deletePtrVector<Instrument>(instruments);
deletePtrVector<Sample>(samples);
deletePtrVector<Pattern>(patterns);
if (message)
delete[] message;
}
void Module::load(const char *pFilename) {
IO::File file(pFilename, IO::MODE_READ);
filename = pFilename;
// skip "IMPM" string
file.skip(4);
// read title
for (int i = 0; i < 26; i++)
title[i] = file.read8();
title[26] = 0;
patternHighlight = file.read16();
length = file.read16();
int instrumentCount = file.read16();
int sampleCount = file.read16();
int patternCount = file.read16();
cwtv = file.read16();
cmwt = file.read16();
{ // read flags
int flags = file.read16();
flgStereo = !!(flags & 1);
vol0MixOptimizations = !!(flags & 2);
instrumentMode = !!(flags & 4);
linearSlides = !!(flags & 8);
oldEffects = !!(flags & 16);
gxxCompat = !!(flags & 32);
}
int special = file.read16();
globalVolume = file.read8();
mixingVolume = file.read8();
initialSpeed = file.read8();
initialTempo = file.read8();
sep = file.read8();
PWD = file.read8();
messageLength = file.read16();
u32 messageOffset = file.read32();
file.skip(4); // reserved
for (int i = 0; i < 64; i++)
channelPan[i] = file.read8();
for (int i = 0; i < 64; i++)
channelVolume[i] = file.read8();
bool foundend = false;
int actualLength = length;
for (int i = 0; i < 256; i++) {
orders[i] = i < length ? file.read8() : 255;
if (orders[i] == 255 && !foundend) {
foundend = true;
actualLength = i + 1;
}
}
length = actualLength;
u32 *instrTable = new u32[instrumentCount + 1];
u32 *sampleTable = new u32[sampleCount + 1];
u32 *patternTable = new u32[patternCount + 1];
for (int i = 0; i < instrumentCount; i++)
instrTable[i] = file.read32();
for (int i = 0; i < sampleCount; i++)
sampleTable[i] = file.read32();
for (int i = 0; i < patternCount; i++)
patternTable[i] = file.read32();
for (int i = 0; i < instrumentCount; i++) {
if (instrTable[i]) {
file.seek(instrTable[i]);
Instrument *ins = new Instrument();
ins->load(file);
instruments.push_back(ins);
} else {
instruments.push_back(0);
}
}
for (int i = 0; i < sampleCount; i++) {
if (sampleTable[i]) {
file.seek(sampleTable[i]);
Sample *smp = new Sample();
smp->load(file);
samples.push_back(smp);
} else {
samples.push_back(0);
}
}
for (int i = 0; i < patternCount; i++) {
if (patternTable[i]) {
file.seek(patternTable[i]);
Pattern *p = new Pattern();
p->load(file);
patterns.push_back(p);
} else {
patterns.push_back(0);
}
}
if (special & 1) {
message = new char[messageLength + 2];
file.seek(messageOffset);
message[messageLength] = 0;
for (int i = 0; i < messageLength; i++)
message[i] = file.read8();
} else {
message = 0;
}
delete[] instrTable;
delete[] sampleTable;
delete[] patternTable;
}
void Module::save(const char *filename) {
IO::File file(filename, IO::MODE_WRITE);
file.writeAscii("IMPM");
file.writeAsciiF(title, 25);
file.write8(0);
file.write16(patternHighlight);
file.write16(length);
file.write16(instruments.size());
file.write16(samples.size());
file.write16(patterns.size());
file.write16(cwtv);
file.write16(cmwt);
file.write16(buildFlags());
file.write16(message ? 1 : 0);
file.write8(globalVolume);
file.write8(mixingVolume);
file.write8(initialSpeed);
file.write8(initialTempo);
file.write8(sep);
file.write8(PWD);
file.write16(messageLength);
u32 pointerToMessageOffset = file.tell();
file.write32(0); //message offset fill in later
file.write32(0); // reserved
for (int i = 0; i < 64; i++)
file.write8(channelPan[i]);
for (int i = 0; i < 64; i++)
file.write8(channelVolume[i]);
for (int i = 0; i < length; i++)
file.write8(orders[i]);
u32 pointerToInstrumentTable = file.tell();
for (u32 i = 0; i < instruments.size(); i++)
file.write32(0);
u32 pointerToSampleTable = file.tell();
for (u32 i = 0; i < samples.size(); i++)
file.write32(0);
u32 pointerToPatternTable = file.tell();
for (u32 i = 0; i < patterns.size(); i++)
file.write32(0);
u32 messageOffset = file.tell();
if (message) {
file.writeBytes((const u8 *) message, messageLength);
}
// export instruments
std::vector <u32> insPointers;
for (u32 i = 0; i < instruments.size(); i++) {
if (instruments[i]) {
insPointers.push_back(file.tell());
instruments[i]->save(file);
} else {
insPointers.push_back(0);
}
}
std::vector <u32> smplPointers;
for (u32 i = 0; i < samples.size(); i++) {
if (samples[i]) {
smplPointers.push_back(file.tell());
samples[i]->save(file);
} else {
smplPointers.push_back(0);
}
}
std::vector <u32> patPointers;
for (u32 i = 0; i < patterns.size(); i++) {
if (patterns[i]) {
patPointers.push_back(file.tell());
patterns[i]->save(file);
} else {
patPointers.push_back(0);
}
}
std::vector <u32> smpDataPointers;
for (u32 i = 0; i < samples.size(); i++) {
if (samples[i]) {
smpDataPointers.push_back(file.tell());
samples[i]->data.save(file);
} else {
smpDataPointers.push_back(0);
}
}
file.seek(pointerToMessageOffset);
file.write32(messageOffset);
file.seek(pointerToInstrumentTable);
for (u32 i = 0; i < instruments.size(); i++)
file.write32(insPointers[i]);
file.seek(pointerToSampleTable);
for (u32 i = 0; i < samples.size(); i++)
file.write32(smplPointers[i]);
file.seek(pointerToPatternTable);
for (u32 i = 0; i < patterns.size(); i++)
file.write32(patPointers[i]);
for (u32 i = 0; i < samples.size(); i++) {
if (smplPointers[i]) {
file.seek(smplPointers[i] + 0x48);
file.write32(smpDataPointers[i]);
}
}
}
void Module::purgeInstruments() {
deletePtrVector<Instrument>(instruments);
instruments.clear();
// deletePtrVector<Sample>( samples );
// deletePtrVector<Pattern>( patterns );
}
void Module::purgeMarkedSamples(const char *marker) {
for (u32 i = 0; i < samples.size(); i++) {
if (samples[i]) {
if (samples[i]->testNameMarker(marker)) {
delete samples[i];
samples[i] = 0;
}
}
}
trimSampleVector();
}
void Module::trimSampleVector() {
if (samples.empty())
return;
for (int i = (int) samples.size() - 1;; i--) {
if (i >= 0) {
if (!samples[i]) {
samples.pop_back();
} else {
break;
}
} else {
break;
}
}
}
u8 Module::buildFlags() {
int flags = 0;
if (flgStereo) flags |= 1;
if (vol0MixOptimizations) flags |= 2;
if (instrumentMode) flags |= 4;
if (linearSlides) flags |= 8;
if (oldEffects) flags |= 16;
if (gxxCompat) flags |= 32;
return flags;
}
void Module::setTitle(const char *text) {
copyFstr(title, text, 27);
}
Instrument::Instrument() {
for (int i = 0; i < 27; i++) name[i] = 0;
for (int i = 0; i < 13; i++) DOSFilename[i] = 0;
newNoteAction = 0;
duplicateCheckType = 0;
duplicateCheckAction = 0;
fadeout = 0;
PPS = 0;
PPC = 60;
globalVolume = 128;
defaultPan = 32 | 128;
randomVolume = 0;
randomPanning = 0;
trackerVersion = 0x0214;
initialFilterCutoff = 0;
initialFilterResonance = 0;
midiChannel = 0;
midiProgram = 0;
midiBank = 0;
for (int i = 0; i < 120; i++) {
notemap[i].note = i;
notemap[i].sample = 0;
}
}
void Instrument::load(IO::File &file) {
file.skip(4); // "IMPI"
DOSFilename[12] = 0;
for (int i = 0; i < 12; i++)
DOSFilename[i] = file.read8();
file.skip(1); // 00h
newNoteAction = file.read8();
duplicateCheckType = file.read8();
duplicateCheckAction = file.read8();
fadeout = file.read16();
PPS = file.read8();
PPC = file.read8();
globalVolume = file.read8();
defaultPan = file.read8();
randomVolume = file.read8();
randomPanning = file.read8();
trackerVersion = file.read16();
int numberOfSamples = file.read8();
file.read8(); // unused
name[26] = 0;
for (int i = 0; i < 26; i++)
name[i] = file.read8();
initialFilterCutoff = file.read8();
initialFilterResonance = file.read8();
midiChannel = file.read8();
midiProgram = file.read8();
midiBank = file.read16();
for (int i = 0; i < 120; i++) {
notemap[i].note = file.read8();
notemap[i].sample = file.read8();
}
volumeEnvelope.load(file);
panningEnvelope.load(file);
pitchEnvelope.load(file);
}
void Instrument::save(IO::File &file) {
file.writeAscii("IMPI");
file.writeAsciiF(DOSFilename, 12);
file.write8(0);
file.write8(newNoteAction);
file.write8(duplicateCheckType);
file.write8(duplicateCheckAction);
file.write16(fadeout);
file.write8(PPS);
file.write8(PPC);
file.write8(globalVolume);
file.write8(defaultPan);
file.write8(randomVolume);
file.write8(randomPanning);
file.write16(trackerVersion);
file.write8(1); // NoS (ignored right?)
file.write8(0); // reserved
file.writeAsciiF(name, 26);
file.write8(initialFilterCutoff);
file.write8(initialFilterResonance);
file.write8(midiChannel);
file.write8(midiProgram);
file.write16(midiBank);
for (int i = 0; i < 120; i++) {
file.write8(notemap[i].note);
file.write8(notemap[i].sample);
}
volumeEnvelope.save(file);
panningEnvelope.save(file);
pitchEnvelope.save(file);
file.write32(0); // waste 7 bytes (?)
file.write16(0);
file.write8(0);
}
void Instrument::setName(const char *text) {
copyFstr(name, text, 27);
}
Envelope::Envelope() {
enabled = false;
loop = false;
sustain = false;
isFilter = false;
length = 2;
loopStart = 0;
loopEnd = 0;
sustainStart = 0;
sustainEnd = 0;
nodes[0].x = 0;
nodes[1].x = 4;
nodes[0].y = 32;
nodes[1].y = 32;
for (int i = 2; i < 25; i++) {
nodes[i].x = 0;
nodes[i].y = 0;
}
}
void Envelope::load(IO::File &file) {
u8 FLG = file.read8();
enabled = !!(FLG & 1);
loop = !!(FLG & 2);
sustain = !!(FLG & 4);
isFilter = !!(FLG & 128);
length = file.read8();
loopStart = file.read8();
loopEnd = file.read8();
sustainStart = file.read8();
sustainEnd = file.read8();
for (int i = 0; i < 25; i++) {
nodes[i].y = file.read8();
nodes[i].x = file.read16();
}
file.read8(); // reserved
}
void Envelope::save(IO::File &file) {
file.write8(buildFlags());
file.write8(length);
file.write8(loopStart);
file.write8(loopEnd);
file.write8(sustainStart);
file.write8(sustainEnd);
for (int i = 0; i < 25; i++) {
file.write8(nodes[i].y);
file.write16(nodes[i].x);
}
file.write8(0);
}
u8 Envelope::buildFlags() {
int flags = 0;
flags |= enabled ? 1 : 0;
flags |= loop ? 2 : 0;
flags |= sustain ? 4 : 0;
flags |= isFilter ? 128 : 0;
return flags;
}
Sample::Sample() {
for (int i = 0; i < 27; i++) name[i] = 0;
for (int i = 0; i < 13; i++) DOSFilename[i] = 0;
globalVolume = 64;
defaultVolume = 64;
defaultPanning = 32;
vibratoSpeed = 0;
vibratoDepth = 0;
vibratoForm = 0;
vibratoRate = 0;
}
void Sample::load(IO::File &file) {
file.skip(4); // IMPS
DOSFilename[12] = 0;
for (int i = 0; i < 12; i++)
DOSFilename[i] = file.read8();
file.skip(1); // 00h
globalVolume = file.read8();
u8 flags = file.read8();
bool hasSample = !!(flags & 1);
data.bits16 = !!(flags & 2);
data.stereo = !!(flags & 4);
data.compressed = !!(flags & 8);
data.loop = !!(flags & 16);
data.sustain = !!(flags & 32);
data.bidiLoop = !!(flags & 64);
data.bidiSustain = !!(flags & 128);
defaultVolume = file.read8();
name[26] = 0;
for (int i = 0; i < 26; i++)
name[i] = file.read8();
int convert = file.read8();
defaultPanning = file.read8();
data.length = file.read32();
data.loopStart = file.read32();
data.loopEnd = file.read32();
centerFreq = file.read32();
data.sustainStart = file.read32();
data.sustainEnd = file.read32();
u32 samplePointer = file.read32();
vibratoSpeed = file.read8();
vibratoDepth = file.read8();
vibratoRate = file.read8();
vibratoForm = file.read8();
file.seek(samplePointer);
data.load(file, convert);
}
void Sample::save(IO::File &file) {
file.writeAscii("IMPS");
file.writeAsciiF(DOSFilename, 12);
file.write8(0);
file.write8(globalVolume);
file.write8(buildFlags());
file.write8(defaultVolume);
file.writeAsciiF(name, 26);
file.write8(1); // signed sample
file.write8(defaultPanning);
file.write32(data.length);
file.write32(data.loopStart);
file.write32(data.loopEnd);
file.write32(centerFreq);
file.write32(data.sustainStart);
file.write32(data.sustainEnd);
file.write32(0); // reserve sample pointer
file.write8(vibratoSpeed);
file.write8(vibratoDepth);
file.write8(vibratoRate);
file.write8(vibratoForm);
}
u8 Sample::buildFlags() {
int flags = 0;
if (data.length) flags |= 1;
if (data.bits16) flags |= 2;
if (data.loop) flags |= 16;
if (data.sustain) flags |= 32;
if (data.bidiLoop) flags |= 64;
if (data.bidiSustain) flags |= 128;
return flags;
}
bool Sample::testNameMarker(const char *str) {
int matches = 0;
for (int i = 0; i < 27; i++) {
if (name[i] == str[matches]) {
matches++;
if (str[matches] == 0) return true;
} else {
matches = 0;
}
}
return false;
}
void Sample::setName(const char *text) {
copyFstr(name, text, 27);
}
SampleData::SampleData() {
bits16 = false;
stereo = false;
length = 0;
loopStart = 0;
loopEnd = 0;
sustainStart = 0;
sustainEnd = 0;
loop = false;
sustain = false;
bidiLoop = false;
bidiSustain = false;
data8 = 0;
}
SampleData::~SampleData() {
if (data8) {
if (bits16)
delete[] data16;
else
delete[] data8;
}
}
void SampleData::load(IO::File &file, int convert) {
if (!compressed) {
// subtract offset for unsigned samples
int offset = (convert & 1) ? 0 : (bits16 ? -32768 : -128);
// signed samples
if (bits16) {
data16 = new s16[length];
for (int i = 0; i < length; i++) {
data16[i] = file.read16() + offset;
}
} else {
data8 = new s8[length];
for (int i = 0; i < length; i++) {
data8[i] = file.read8() + offset;
}
}
} else {
// TODO : accept compressed samples.
}
}
void SampleData::save(IO::File &file) {
for (int i = 0; i < length; i++) {
if (bits16) {
file.write16(data16[i]);
} else {
file.write8(data8[i]);
}
}
}
Pattern::Pattern() {
rows = 64;
data = new u8[rows];
for (int i = 0; i < rows; i++) {
data[i] = 0;
}
dataLength = 64;
}
Pattern::~Pattern() {
deleteData();
}
void Pattern::deleteData() {
rows = 0;
if (data)
delete[] data;
dataLength = 0;
}
void Pattern::load(IO::File &file) {
deleteData();
dataLength = file.read16();
rows = file.read16();
file.skip(4); // reserved
data = new u8[dataLength];
for (int i = 0; i < dataLength; i++) {
data[i] = file.read8();
}
}
void Pattern::save(IO::File &file) {
file.write16(dataLength);
file.write16(rows);
file.write32(0); // reserved
file.writeBytes(data, dataLength);
}
//-----------------------------------------------------------------------------
};
//-----------------------------------------------------------------------------
| 28.770087 | 135 | 0.484168 | [
"vector"
] |
1457673677571d693ad34b77dd400efc404464c0 | 3,362 | hpp | C++ | include/types.hpp | mrityunjay-tripathi/qpp | 68c76a1f4f2dd85b453521326b2186dece498cbd | [
"MIT"
] | null | null | null | include/types.hpp | mrityunjay-tripathi/qpp | 68c76a1f4f2dd85b453521326b2186dece498cbd | [
"MIT"
] | null | null | null | include/types.hpp | mrityunjay-tripathi/qpp | 68c76a1f4f2dd85b453521326b2186dece498cbd | [
"MIT"
] | null | null | null | /*
* This file is part of Quantum++.
*
* Copyright (c) 2013 - 2021 softwareQ Inc. All rights reserved.
*
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* \file types.hpp
* \brief Type aliases
*/
#ifndef TYPES_HPP_
#define TYPES_HPP_
namespace qpp {
/**
* \brief Non-negative integer index, make sure you use an unsigned type
*/
using idx = std::size_t;
/**
* \brief Big integer
*/
using bigint = long long int;
/**
* \brief Complex number in double precision
*/
using cplx = std::complex<double>;
/**
* \brief Complex (double precision) dynamic Eigen column vector
*/
using ket = Eigen::VectorXcd;
/**
* \brief Complex (double precision) dynamic Eigen row vector
*/
using bra = Eigen::RowVectorXcd;
/**
* \brief Complex (double precision) dynamic Eigen matrix
*/
using cmat = Eigen::MatrixXcd;
/**
* \brief Real (double precision) dynamic Eigen matrix
*/
using dmat = Eigen::MatrixXd;
/**
* \brief Dynamic Eigen matrix over the field specified by \a Scalar
*
* Example:
* \code
* // type of mat is Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic>
* dyn_mat<float> mat(2, 3);
* \endcode
*/
template <typename Scalar> // Eigen::MatrixX_type (where type = Scalar)
using dyn_mat = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>;
/**
* \brief Dynamic Eigen column vector over the field specified by \a Scalar
*
* Example:
* \code
* // type of col_vect is Eigen::Matrix<float, Eigen::Dynamic, 1>
* dyn_col_vect<float> col_vect(2);
* \endcode
*/
template <typename Scalar> // Eigen::VectorX_type (where type = Scalar)
using dyn_col_vect = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;
/**
* \brief Dynamic Eigen row vector over the field specified by \a Scalar
*
* Example:
* \code
* // type of row_vect is Eigen::Matrix<float, 1, Eigen::Dynamic>
* dyn_row_vect<float> row_vect(3);
* \endcode
*/
template <typename Scalar> // Eigen::RowVectorX_type (where type = Scalar)
using dyn_row_vect = Eigen::Matrix<Scalar, 1, Eigen::Dynamic>;
/**
* \brief Matrix type deduced from Derived
*/
template <typename Derived>
using deduced_mat =
typename std::decay<decltype(std::declval<Derived>().eval())>::type;
/**
* \brief Quantumly-accessible Random Access Memory (qRAM)
*/
using qram = std::vector<idx>;
} /* namespace qpp */
#endif /* TYPES_HPP_ */
| 27.557377 | 80 | 0.709399 | [
"vector"
] |
145d894fd930a6203f2865dc9e4ac0e2928ab82c | 328 | hpp | C++ | include/UncompressedVoxel.hpp | basticirca/libpcc | 307792d24ad75bed70872f0145b121377adae93f | [
"MIT"
] | 2 | 2018-09-22T12:48:18.000Z | 2019-04-02T08:55:44.000Z | include/UncompressedVoxel.hpp | basticirca/libpcc | 307792d24ad75bed70872f0145b121377adae93f | [
"MIT"
] | null | null | null | include/UncompressedVoxel.hpp | basticirca/libpcc | 307792d24ad75bed70872f0145b121377adae93f | [
"MIT"
] | 3 | 2019-05-04T04:21:39.000Z | 2020-12-01T00:59:13.000Z | #ifndef LIBPCC_UNCOMPRESSEDVOXEL_HPP
#define LIBPCC_UNCOMPRESSEDVOXEL_HPP
/**
* Data transfer object to define basic (property) layout of a voxel.
* Offers a 3D position as well as an 8 bit rgba-color.
*/
struct UncompressedVoxel {
float pos[3];
unsigned char color_rgba[4];
};
#endif //LIBPCC_UNCOMPRESSEDVOXEL_HPP
| 23.428571 | 69 | 0.759146 | [
"object",
"3d"
] |
1465be20f79129506e883a0a9ca98a6c2160b83d | 7,663 | cpp | C++ | Source/Plugins/TeD3D11RenderAPI/TeD3D11GpuProgram.cpp | GameDevery/TweedeFrameworkRedux | 69a28fe171db33d00066b97b9b6bf89f6ef3e3a4 | [
"MIT"
] | 57 | 2019-09-02T01:10:37.000Z | 2022-01-11T06:28:10.000Z | Source/Plugins/TeD3D11RenderAPI/TeD3D11GpuProgram.cpp | GameDevery/TweedeFrameworkRedux | 69a28fe171db33d00066b97b9b6bf89f6ef3e3a4 | [
"MIT"
] | null | null | null | Source/Plugins/TeD3D11RenderAPI/TeD3D11GpuProgram.cpp | GameDevery/TweedeFrameworkRedux | 69a28fe171db33d00066b97b9b6bf89f6ef3e3a4 | [
"MIT"
] | 6 | 2020-02-29T17:19:30.000Z | 2021-10-30T04:29:22.000Z | #include "TeD3D11GpuProgram.h"
#include "TeD3D11Device.h"
//#include "RenderAPI/TeGpuParams.h"
#include "TeD3D11RenderAPI.h"
#include "RenderAPI/TeGpuProgramManager.h"
#include "RenderAPI/TeHardwareBufferManager.h"
#include <regex>
namespace te
{
UINT32 D3D11GpuProgram::GlobalProgramId = 0;
D3D11GpuProgram::D3D11GpuProgram(const GPU_PROGRAM_DESC& desc, GpuDeviceFlags deviceMask)
: GpuProgram(desc, deviceMask)
{
assert((deviceMask == GDF_DEFAULT || deviceMask == GDF_PRIMARY) && "Multiple GPUs not supported natively on DirectX 11.");
}
D3D11GpuProgram::~D3D11GpuProgram()
{
_inputDeclaration = nullptr;
}
void D3D11GpuProgram::Initialize()
{
if (!IsSupported())
{
_status.Successful = false;
_status.Message = "Specified program is not supported by the current render system.";
GpuProgram::Initialize();
return;
}
if (!_bytecode || _bytecode->CompilerId != DIRECTX_COMPILER_ID)
{
GPU_PROGRAM_DESC desc;
desc.Type = _type;
desc.EntryPoint = _entryPoint;
desc.Source = _source;
desc.Language = "hlsl";
desc.IncludePath = _includePath;
desc.FilePath = _filePath;
_bytecode = CompileBytecode(desc);
}
_status.Message = _bytecode->Message;
_status.Successful = _bytecode->Instructions.Data != nullptr;
if (_status.Successful)
{
_parametersDesc = _bytecode->ParamDesc;
D3D11RenderAPI* rapi = static_cast<D3D11RenderAPI*>(RenderAPI::InstancePtr());
LoadFromMicrocode(rapi->GetPrimaryDevice(), _bytecode->Instructions);
if (_type == GPT_VERTEX_PROGRAM)
{
_inputDeclaration = HardwareBufferManager::Instance().CreateVertexDeclaration(_bytecode->VertexInput);
}
}
_programId = GlobalProgramId++;
GpuProgram::Initialize();
}
D3D11GpuVertexProgram::D3D11GpuVertexProgram(const GPU_PROGRAM_DESC& desc, GpuDeviceFlags deviceMask)
: D3D11GpuProgram(desc, deviceMask)
, _vertexShader(nullptr)
{ }
D3D11GpuVertexProgram::~D3D11GpuVertexProgram()
{
SAFE_RELEASE(_vertexShader);
}
void D3D11GpuVertexProgram::LoadFromMicrocode(D3D11Device& device, const DataBlob& microcode)
{
HRESULT hr = device.GetD3D11Device()->CreateVertexShader(
microcode.Data, microcode.Size, device.GetClassLinkage(), &_vertexShader);
if (FAILED(hr) || device.HasError())
{
String errorDescription = device.GetErrorDescription();
TE_ASSERT_ERROR(false, "Cannot create D3D11 vertex shader from microcode\nError Description: " + errorDescription);
}
}
ID3D11VertexShader* D3D11GpuVertexProgram::GetVertexShader() const
{
return _vertexShader;
}
D3D11GpuPixelProgram::D3D11GpuPixelProgram(const GPU_PROGRAM_DESC& desc, GpuDeviceFlags deviceMask)
: D3D11GpuProgram(desc, deviceMask)
, _pixelShader(nullptr)
{ }
D3D11GpuPixelProgram::~D3D11GpuPixelProgram()
{
SAFE_RELEASE(_pixelShader);
}
void D3D11GpuPixelProgram::LoadFromMicrocode(D3D11Device& device, const DataBlob& microcode)
{
HRESULT hr = device.GetD3D11Device()->CreatePixelShader(
microcode.Data, microcode.Size, device.GetClassLinkage(), &_pixelShader);
if (FAILED(hr) || device.HasError())
{
String errorDescription = device.GetErrorDescription();
TE_ASSERT_ERROR(false, "Cannot create D3D11 pixel shader from microcode.\nError Description: " + errorDescription);
}
}
ID3D11PixelShader* D3D11GpuPixelProgram::GetPixelShader() const
{
return _pixelShader;
}
D3D11GpuGeometryProgram::D3D11GpuGeometryProgram(const GPU_PROGRAM_DESC& desc, GpuDeviceFlags deviceMask)
: D3D11GpuProgram(desc, deviceMask)
, _geometryShader(nullptr)
{ }
D3D11GpuGeometryProgram::~D3D11GpuGeometryProgram()
{
SAFE_RELEASE(_geometryShader);
}
void D3D11GpuGeometryProgram::LoadFromMicrocode(D3D11Device& device, const DataBlob& microcode)
{
HRESULT hr = device.GetD3D11Device()->CreateGeometryShader(
microcode.Data, microcode.Size, device.GetClassLinkage(), &_geometryShader);
if (FAILED(hr) || device.HasError())
{
String errorDescription = device.GetErrorDescription();
TE_ASSERT_ERROR(false, "Cannot create D3D11 geometry shader from microcode.\nError Description: " + errorDescription);
}
}
ID3D11GeometryShader* D3D11GpuGeometryProgram::GetGeometryShader() const
{
return _geometryShader;
}
D3D11GpuDomainProgram::D3D11GpuDomainProgram(const GPU_PROGRAM_DESC& desc, GpuDeviceFlags deviceMask)
: D3D11GpuProgram(desc, deviceMask)
, _domainShader(nullptr)
{ }
D3D11GpuDomainProgram::~D3D11GpuDomainProgram()
{
SAFE_RELEASE(_domainShader);
}
void D3D11GpuDomainProgram::LoadFromMicrocode(D3D11Device& device, const DataBlob& microcode)
{
HRESULT hr = device.GetD3D11Device()->CreateDomainShader(
microcode.Data, microcode.Size, device.GetClassLinkage(), &_domainShader);
if (FAILED(hr) || device.HasError())
{
String errorDescription = device.GetErrorDescription();
TE_ASSERT_ERROR(false, "Cannot create D3D11 domain shader from microcode.\nError Description: " + errorDescription);
}
}
ID3D11DomainShader* D3D11GpuDomainProgram::GetDomainShader() const
{
return _domainShader;
}
D3D11GpuHullProgram::D3D11GpuHullProgram(const GPU_PROGRAM_DESC& desc, GpuDeviceFlags deviceMask)
: D3D11GpuProgram(desc, deviceMask)
, _hullShader(nullptr)
{ }
D3D11GpuHullProgram::~D3D11GpuHullProgram()
{
SAFE_RELEASE(_hullShader);
}
void D3D11GpuHullProgram::LoadFromMicrocode(D3D11Device& device, const DataBlob& microcode)
{
// Create the shader
HRESULT hr = device.GetD3D11Device()->CreateHullShader(
microcode.Data, microcode.Size, device.GetClassLinkage(), &_hullShader);
if (FAILED(hr) || device.HasError())
{
String errorDescription = device.GetErrorDescription();
TE_ASSERT_ERROR(false, "Cannot create D3D11 hull shader from microcode.\nError Description: " + errorDescription);
}
}
ID3D11HullShader* D3D11GpuHullProgram::GetHullShader() const
{
return _hullShader;
}
D3D11GpuComputeProgram::D3D11GpuComputeProgram(const GPU_PROGRAM_DESC& desc, GpuDeviceFlags deviceMask)
: D3D11GpuProgram(desc, deviceMask), _computeShader(nullptr)
{ }
D3D11GpuComputeProgram::~D3D11GpuComputeProgram()
{
SAFE_RELEASE(_computeShader);
}
void D3D11GpuComputeProgram::LoadFromMicrocode(D3D11Device& device, const DataBlob& microcode)
{
HRESULT hr = device.GetD3D11Device()->CreateComputeShader(
microcode.Data, microcode.Size, device.GetClassLinkage(), &_computeShader);
if (FAILED(hr) || device.HasError())
{
String errorDescription = device.GetErrorDescription();
TE_ASSERT_ERROR(false, "Cannot create D3D11 compute shader from microcode.\nError Description: " + errorDescription);
}
}
ID3D11ComputeShader* D3D11GpuComputeProgram::GetComputeShader() const
{
return _computeShader;
}
}
| 33.17316 | 130 | 0.667624 | [
"geometry",
"render"
] |
146de492a65d833fe2a1bd85b259cb34ff64d09e | 6,589 | cpp | C++ | VelocityCalibration/estimateVelocity.cpp | kdulski/j-pet-framework-examples | ab2592a2c6cf8f901f5732f8878b750b9a7b6a49 | [
"Apache-2.0"
] | 2 | 2017-12-12T16:51:06.000Z | 2021-11-04T08:01:34.000Z | VelocityCalibration/estimateVelocity.cpp | kdulski/j-pet-framework-examples | ab2592a2c6cf8f901f5732f8878b750b9a7b6a49 | [
"Apache-2.0"
] | 89 | 2016-07-23T22:12:09.000Z | 2022-01-19T13:21:29.000Z | VelocityCalibration/estimateVelocity.cpp | kdulski/j-pet-framework-examples | ab2592a2c6cf8f901f5732f8878b750b9a7b6a49 | [
"Apache-2.0"
] | 34 | 2016-06-18T17:47:35.000Z | 2021-04-27T12:18:00.000Z | #include <iostream>
#include <vector>
#include <utility>
#include <fstream>
#include <sstream>
#include "TGraph.h"
#include "TCanvas.h"
#include "TF1.h"
#include "TStyle.h"
#include "TGraphErrors.h"
#include <map>
#include <algorithm>
std::vector< std::pair<int,double> > takeData(const std::string file, const char thresholdLabel);
std::pair<double,double> plotVelocity(std::vector<double> positions, std::vector<double> means, int strip, std::vector<double> errors, char thresholdLabel);
struct positionData{
double positionValue;
double deltaT;
double deltaTError;
};
struct thresholdData{
char thresholdLabel;
std::vector<positionData> positions;
};
struct scintData{
int ID;
std::vector<thresholdData> thrData;
};
std::vector<scintData> takeData(const std::string file);
void velocityCalc(std::vector<scintData>& data, const std::string& outPath);
void parserTest(std::vector<scintData>& data, const char thrLabel);
int main(int argc, char** argv)
{
gStyle->SetOptFit(1);
std::vector<scintData> data;
std::string outPath = "";
if(argc == 1)
{
data = takeData("results.txt");
}
else if (argc == 2)
{
data = takeData(std::string(argv[1]));
}
else if (argc == 3)
{
data = takeData(std::string(argv[1]));
outPath = argv[2];
}
if(data.size() == 0 )
{
std::cout<<"Error while opening input file"<<std::endl;
return 1;
}
velocityCalc( data , outPath);
return 0;
}
void parserTest(std::vector<scintData>& data, const char thrLabel)
{
for(auto scintillator : data)
{
std::cout << scintillator.ID;
for(auto threshold : scintillator.thrData)
{
if( thrLabel == threshold.thresholdLabel )
{
std::cout << "\t" << threshold.thresholdLabel;
for( auto position : threshold.positions )
{
std::cout << "\t" << position.positionValue << "\t" << position.deltaT << "\t" << position.deltaTError <<std::endl;
}
}
}
}
}
void velocityCalc(std::vector<scintData>& data, const std::string& outPath)
{
std::map<char, int> thresholdLabelToInt = {{'a', 1}, {'b',2}, {'c',3}, {'d',4}};
std::ofstream results;
std::string title = outPath+"EffVelocities";
title+= ".txt";
results.open( title.c_str() );
for(const auto& scintillator : data)
{
for(const auto& threshold : scintillator.thrData)
{
std::vector<double> positionsForFit;
std::vector<double> timesForFit;
std::vector<double> errorsForFit;
for(const auto& position : threshold.positions )
{
positionsForFit.push_back( position.positionValue );
timesForFit.push_back( position.deltaT );
errorsForFit.push_back( position.deltaTError);
}
std::pair<double,double> velocity = plotVelocity( positionsForFit, timesForFit, scintillator.ID, errorsForFit, threshold.thresholdLabel);
int layer = 0, layerReset = 0;
if( scintillator.ID < 49 )
{
layer = 1;
}
else if( scintillator.ID > 48 && scintillator.ID < 97 )
{
layer = 2;
layerReset = 48;
}
else
{
layer = 3;
layerReset = 96;
}
results << layer << "\t" << scintillator.ID - layerReset << "\tA\t" << thresholdLabelToInt[threshold.thresholdLabel];
results << "\t" << velocity.first << "\t" << velocity.second;
results << "\t0\t0\t0\t0\t0\t0" << std::endl;
results << layer << "\t" << scintillator.ID - layerReset << "\tB\t" << thresholdLabelToInt[threshold.thresholdLabel];
results << "\t" << velocity.first << "\t" << velocity.second;
results << "\t0\t0\t0\t0\t0\t0" << std::endl;
}
}
results.close();
}
std::pair<double,double> plotVelocity(std::vector<double> positions, std::vector<double> means, int strip, std::vector<double> errors, char thresholdLabel)
{
TCanvas* c = new TCanvas();
TGraphErrors* vGraph = new TGraphErrors(positions.size(), &means[0], &positions[0], 0, &errors[0] );
vGraph->SetMarkerStyle(20);
vGraph->SetMarkerSize(1);
vGraph->Draw("AP");
vGraph->Fit("pol1");
TF1* fit = vGraph->GetFunction("pol1");
std::stringstream buf;
buf << strip << "_" << thresholdLabel;
c->SaveAs( (buf.str() + ".png").c_str() );
std::pair<double,double> resultOfFit = std::make_pair<double,double> ( (fit->GetParameter(1))*-0.2, (fit->GetParError(1))*-0.2 );
return resultOfFit;
}
bool ifScintillatorIsIn( std::vector<scintData>& data, int ID)
{
for( auto scintillator : data )
{
if( ID == scintillator.ID )
return true;
}
return false;
}
int findScintillatorIn( std::vector<scintData>& data, int ID)
{
for( unsigned int i = 0; i < data.size(); i++ )
{
if( ID == data[i].ID )
return i;
}
return -1;
}
bool ifThresholdIsIn( scintData& data, char label)
{
return std::any_of(data.thrData.begin(), data.thrData.end(), [label]( const thresholdData& thr) {return label == thr.thresholdLabel; });
}
int findThresholdIn( scintData& data, char label)
{
for( unsigned int i = 0; i < data.thrData.size(); i++ )
{
if( label == data.thrData[i].thresholdLabel )
return i;
}
return -1;
}
std::vector<scintData> takeData(const std::string file){
std::ifstream dataFile;
dataFile.open(file.c_str());
if( !dataFile.good() )
{
std::exit(1);
}
std::vector< scintData > allData;
double position = 999;
char thrLabel = 'z';
double chi2 = 99;
int degrees = 0;
int ID = 0;
double mean = 999;
double meanError = 0;
while( dataFile >> ID >> position >> thrLabel >> mean >> meanError >> chi2 >> degrees )
{
//IF ID IS IN ALLDATA
if ( ifScintillatorIsIn(allData, ID) )
{
//FILL THIS SCINTILLATOR WITH ADDITIONAL INFO
int scintIndex = findScintillatorIn(allData, ID);
positionData pos;
pos.positionValue = position;
pos.deltaT = mean;
pos.deltaTError = meanError;
//IF THR IS IN SCINTILLATOR
if( ifThresholdIsIn( allData[scintIndex], thrLabel ) )
{
int thrIndex = findThresholdIn( allData[scintIndex], thrLabel );
allData[ scintIndex ].thrData[thrIndex].positions.push_back(pos);
}
else
{
//ELSE MAKE A NEW THRESHOLD AND FILL
thresholdData thr;
thr.thresholdLabel = thrLabel;
thr.positions.push_back(pos);
allData[ scintIndex ].thrData.push_back(thr);
}
}
else{
//ELSE MAKE NEW SCINTILLATOR AND FILL
positionData pos;
pos.positionValue = position;
pos.deltaT = mean;
pos.deltaTError = meanError;
thresholdData thr;
thr.thresholdLabel = thrLabel;
thr.positions.push_back(pos);
scintData scintillator;
scintillator.ID = ID;
scintillator.thrData.push_back(thr);
// FILL THRESHOLD AND POSITION
allData.push_back(scintillator);
}
}
return allData;
}
| 25.148855 | 156 | 0.656701 | [
"vector"
] |
146f9431204f454305a8c67f29c7d687cf48fff1 | 360 | cpp | C++ | test/maths/intersection.test.cpp | guillaume-haerinck/voxel-editor | 78c2db3e7f33a1944ef6202c8ae33f4008695153 | [
"MIT"
] | 7 | 2019-12-30T21:01:06.000Z | 2022-02-24T07:41:52.000Z | test/maths/intersection.test.cpp | guillaume-haerinck/voxel-editor | 78c2db3e7f33a1944ef6202c8ae33f4008695153 | [
"MIT"
] | null | null | null | test/maths/intersection.test.cpp | guillaume-haerinck/voxel-editor | 78c2db3e7f33a1944ef6202c8ae33f4008695153 | [
"MIT"
] | 1 | 2020-04-26T22:02:29.000Z | 2020-04-26T22:02:29.000Z | #include <catch2/catch.hpp>
#include <glm/glm.hpp>
#include "maths/intersection.h"
SCENARIO("Intersection functions should say when an object intersect another and give the point of intersection", "[intersection]") {
GIVEN("Blabla") {
WHEN("blabla") {
THEN("blabla") {
REQUIRE(true);
}
}
}
}
| 21.176471 | 133 | 0.586111 | [
"object"
] |
146fdcbbe003c296861e9829f9471bba94dc5a2d | 655 | cpp | C++ | Dataset/Leetcode/train/112/34.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/train/112/34.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/train/112/34.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | class Solution {
public:
void dfs(TreeNode * root, vector<int>&result,int sum){
sum += root->val;
if(!root->left && !root->right){ //如果是叶子节点
result.push_back(sum);
return;
}
if(root->left)
dfs(root->left, result,sum);
if(root->right)
dfs(root->right,result,sum);
}
bool XXX(TreeNode* root, int targetSum) {
if(!root)
return false;
vector<int> cur;
int sum = 0;
dfs(root,cur,sum);
for(int a : cur){
if(a == targetSum)
return true;
}
return false;
}
};
| 23.392857 | 58 | 0.464122 | [
"vector"
] |
1475eabee1e9a5f95e4eb8009dd07469f80bcfd5 | 13,951 | cc | C++ | src/trace_processor/dynamic/experimental_flamegraph_generator.cc | SolaceDev/perfetto | cf4922dea8779ff37f641b2e5b652f71509320dc | [
"Apache-2.0"
] | null | null | null | src/trace_processor/dynamic/experimental_flamegraph_generator.cc | SolaceDev/perfetto | cf4922dea8779ff37f641b2e5b652f71509320dc | [
"Apache-2.0"
] | null | null | null | src/trace_processor/dynamic/experimental_flamegraph_generator.cc | SolaceDev/perfetto | cf4922dea8779ff37f641b2e5b652f71509320dc | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2020 The Android Open Source Project
*
* 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 "src/trace_processor/dynamic/experimental_flamegraph_generator.h"
#include <unordered_set>
#include "perfetto/ext/base/string_splitter.h"
#include "perfetto/ext/base/string_utils.h"
#include "src/trace_processor/importers/proto/heap_graph_tracker.h"
#include "src/trace_processor/importers/proto/heap_profile_tracker.h"
#include "src/trace_processor/types/trace_processor_context.h"
namespace perfetto {
namespace trace_processor {
namespace {
ExperimentalFlamegraphGenerator::ProfileType extractProfileType(
std::string& profile_name) {
if (profile_name == "graph") {
return ExperimentalFlamegraphGenerator::ProfileType::kGraph;
}
if (profile_name == "native") {
return ExperimentalFlamegraphGenerator::ProfileType::kNative;
}
if (profile_name == "perf") {
return ExperimentalFlamegraphGenerator::ProfileType::kPerf;
}
PERFETTO_FATAL("Could not recognize profile type: %s.", profile_name.c_str());
}
bool IsValidTimestampOp(int op) {
return op == SQLITE_INDEX_CONSTRAINT_EQ || op == SQLITE_INDEX_CONSTRAINT_GT ||
op == SQLITE_INDEX_CONSTRAINT_LE || op == SQLITE_INDEX_CONSTRAINT_LT ||
op == SQLITE_INDEX_CONSTRAINT_GE;
}
bool IsValidFilterOp(FilterOp filterOp) {
return filterOp == FilterOp::kEq || filterOp == FilterOp::kGt ||
filterOp == FilterOp::kLe || filterOp == FilterOp::kLt ||
filterOp == FilterOp::kGe;
}
// For filtering, this method uses the same constraints as
// ExperimentalFlamegraphGenerator::ValidateConstraints and should therefore
// be kept in sync.
ExperimentalFlamegraphGenerator::InputValues GetFlamegraphInputValues(
const std::vector<Constraint>& cs) {
using T = tables::ExperimentalFlamegraphNodesTable;
auto ts_fn = [](const Constraint& c) {
return c.col_idx == static_cast<uint32_t>(T::ColumnIndex::ts) &&
IsValidFilterOp(c.op);
};
auto upid_fn = [](const Constraint& c) {
return c.col_idx == static_cast<uint32_t>(T::ColumnIndex::upid) &&
c.op == FilterOp::kEq;
};
auto upid_group_fn = [](const Constraint& c) {
return c.col_idx == static_cast<uint32_t>(T::ColumnIndex::upid_group) &&
c.op == FilterOp::kEq;
};
auto profile_type_fn = [](const Constraint& c) {
return c.col_idx == static_cast<uint32_t>(T::ColumnIndex::profile_type) &&
c.op == FilterOp::kEq;
};
auto focus_str_fn = [](const Constraint& c) {
return c.col_idx == static_cast<uint32_t>(T::ColumnIndex::focus_str) &&
c.op == FilterOp::kEq;
};
auto ts_it = std::find_if(cs.begin(), cs.end(), ts_fn);
auto upid_it = std::find_if(cs.begin(), cs.end(), upid_fn);
auto upid_group_it = std::find_if(cs.begin(), cs.end(), upid_group_fn);
auto profile_type_it = std::find_if(cs.begin(), cs.end(), profile_type_fn);
auto focus_str_it = std::find_if(cs.begin(), cs.end(), focus_str_fn);
// We should always have valid iterators here because BestIndex should only
// allow the constraint set to be chosen when we have an equality constraint
// on upid and a constraint on ts.
PERFETTO_CHECK(ts_it != cs.end());
PERFETTO_CHECK(upid_it != cs.end() || upid_group_it != cs.end());
PERFETTO_CHECK(profile_type_it != cs.end());
std::string profile_name(profile_type_it->value.AsString());
ExperimentalFlamegraphGenerator::ProfileType profile_type =
extractProfileType(profile_name);
int64_t ts = -1;
std::vector<TimeConstraints> time_constraints = {};
for (; ts_it != cs.end(); ts_it++) {
if (ts_it->col_idx != static_cast<uint32_t>(T::ColumnIndex::ts)) {
continue;
}
if (profile_type == ExperimentalFlamegraphGenerator::ProfileType::kPerf) {
PERFETTO_CHECK(ts_it->op != FilterOp::kEq);
time_constraints.push_back(
TimeConstraints{ts_it->op, ts_it->value.AsLong()});
} else {
PERFETTO_CHECK(ts_it->op == FilterOp::kEq);
ts = ts_it->value.AsLong();
}
}
base::Optional<UniquePid> upid;
base::Optional<std::string> upid_group;
if (upid_it != cs.end()) {
upid = static_cast<UniquePid>(upid_it->value.AsLong());
} else {
upid_group = upid_group_it->value.AsString();
}
std::string focus_str =
focus_str_it != cs.end() ? focus_str_it->value.AsString() : "";
return ExperimentalFlamegraphGenerator::InputValues{
profile_type, ts, std::move(time_constraints),
upid, upid_group, focus_str};
}
class Matcher {
public:
explicit Matcher(const std::string& str) : focus_str_(base::ToLower(str)) {}
Matcher(const Matcher&) = delete;
Matcher& operator=(const Matcher&) = delete;
bool matches(const std::string& s) const {
// TODO(149833691): change to regex.
// We cannot use regex.h (does not exist in windows) or std regex (throws
// exceptions).
return base::Contains(base::ToLower(s), focus_str_);
}
private:
const std::string focus_str_;
};
enum class FocusedState {
kNotFocused,
kFocusedPropagating,
kFocusedNotPropagating,
};
using tables::ExperimentalFlamegraphNodesTable;
std::vector<FocusedState> ComputeFocusedState(
const ExperimentalFlamegraphNodesTable& table,
const Matcher& focus_matcher) {
// Each row corresponds to a node in the flame chart tree with its parent
// ptr. Root trees (no parents) will have a null parent ptr.
std::vector<FocusedState> focused(table.row_count());
for (uint32_t i = 0; i < table.row_count(); ++i) {
auto parent_id = table.parent_id()[i];
// Constraint: all descendants MUST come after their parents.
PERFETTO_DCHECK(!parent_id.has_value() || *parent_id < table.id()[i]);
if (focus_matcher.matches(table.name().GetString(i).ToStdString())) {
// Mark as focused
focused[i] = FocusedState::kFocusedPropagating;
auto current = parent_id;
// Mark all parent nodes as focused
while (current.has_value()) {
auto current_idx = *table.id().IndexOf(*current);
if (focused[current_idx] != FocusedState::kNotFocused) {
// We have already visited these nodes, skip
break;
}
focused[current_idx] = FocusedState::kFocusedNotPropagating;
current = table.parent_id()[current_idx];
}
} else if (parent_id.has_value() &&
focused[*table.id().IndexOf(*parent_id)] ==
FocusedState::kFocusedPropagating) {
// Focus cascades downwards.
focused[i] = FocusedState::kFocusedPropagating;
} else {
focused[i] = FocusedState::kNotFocused;
}
}
return focused;
}
struct CumulativeCounts {
int64_t size;
int64_t count;
int64_t alloc_size;
int64_t alloc_count;
};
std::unique_ptr<tables::ExperimentalFlamegraphNodesTable> FocusTable(
TraceStorage* storage,
std::unique_ptr<ExperimentalFlamegraphNodesTable> in,
const std::string& focus_str) {
if (in->row_count() == 0 || focus_str.empty()) {
return in;
}
std::vector<FocusedState> focused_state =
ComputeFocusedState(*in, Matcher(focus_str));
std::unique_ptr<ExperimentalFlamegraphNodesTable> tbl(
new tables::ExperimentalFlamegraphNodesTable(
storage->mutable_string_pool(), nullptr));
// Recompute cumulative counts
std::vector<CumulativeCounts> node_to_cumulatives(in->row_count());
for (int64_t idx = in->row_count() - 1; idx >= 0; --idx) {
auto i = static_cast<uint32_t>(idx);
if (focused_state[i] == FocusedState::kNotFocused) {
continue;
}
auto& cumulatives = node_to_cumulatives[i];
cumulatives.size += in->size()[i];
cumulatives.count += in->count()[i];
cumulatives.alloc_size += in->alloc_size()[i];
cumulatives.alloc_count += in->alloc_count()[i];
auto parent_id = in->parent_id()[i];
if (parent_id.has_value()) {
auto& parent_cumulatives =
node_to_cumulatives[*in->id().IndexOf(*parent_id)];
parent_cumulatives.size += cumulatives.size;
parent_cumulatives.count += cumulatives.count;
parent_cumulatives.alloc_size += cumulatives.alloc_size;
parent_cumulatives.alloc_count += cumulatives.alloc_count;
}
}
// Mapping between the old rows ('node') to the new identifiers.
std::vector<ExperimentalFlamegraphNodesTable::Id> node_to_id(in->row_count());
for (uint32_t i = 0; i < in->row_count(); ++i) {
if (focused_state[i] == FocusedState::kNotFocused) {
continue;
}
tables::ExperimentalFlamegraphNodesTable::Row alloc_row{};
// We must reparent the rows as every insertion will get its own
// identifier.
auto original_parent_id = in->parent_id()[i];
if (original_parent_id.has_value()) {
auto original_idx = *in->id().IndexOf(*original_parent_id);
alloc_row.parent_id = node_to_id[original_idx];
}
alloc_row.ts = in->ts()[i];
alloc_row.upid = in->upid()[i];
alloc_row.profile_type = in->profile_type()[i];
alloc_row.depth = in->depth()[i];
alloc_row.name = in->name()[i];
alloc_row.map_name = in->map_name()[i];
alloc_row.count = in->count()[i];
alloc_row.size = in->size()[i];
alloc_row.alloc_count = in->alloc_count()[i];
alloc_row.alloc_size = in->alloc_size()[i];
const auto& cumulative = node_to_cumulatives[i];
alloc_row.cumulative_count = cumulative.count;
alloc_row.cumulative_size = cumulative.size;
alloc_row.cumulative_alloc_count = cumulative.alloc_count;
alloc_row.cumulative_alloc_size = cumulative.alloc_size;
node_to_id[i] = tbl->Insert(alloc_row).id;
}
return tbl;
}
} // namespace
ExperimentalFlamegraphGenerator::ExperimentalFlamegraphGenerator(
TraceProcessorContext* context)
: context_(context) {}
ExperimentalFlamegraphGenerator::~ExperimentalFlamegraphGenerator() = default;
// For filtering, this method uses the same constraints as
// ExperimentalFlamegraphGenerator::GetFlamegraphInputValues and should
// therefore be kept in sync.
util::Status ExperimentalFlamegraphGenerator::ValidateConstraints(
const QueryConstraints& qc) {
using T = tables::ExperimentalFlamegraphNodesTable;
const auto& cs = qc.constraints();
auto ts_fn = [](const QueryConstraints::Constraint& c) {
return c.column == static_cast<int>(T::ColumnIndex::ts) &&
IsValidTimestampOp(c.op);
};
bool has_ts_cs = std::find_if(cs.begin(), cs.end(), ts_fn) != cs.end();
auto upid_fn = [](const QueryConstraints::Constraint& c) {
return c.column == static_cast<int>(T::ColumnIndex::upid) &&
c.op == SQLITE_INDEX_CONSTRAINT_EQ;
};
bool has_upid_cs = std::find_if(cs.begin(), cs.end(), upid_fn) != cs.end();
auto upid_group_fn = [](const QueryConstraints::Constraint& c) {
return c.column == static_cast<int>(T::ColumnIndex::upid_group) &&
c.op == SQLITE_INDEX_CONSTRAINT_EQ;
};
bool has_upid_group_cs =
std::find_if(cs.begin(), cs.end(), upid_group_fn) != cs.end();
auto profile_type_fn = [](const QueryConstraints::Constraint& c) {
return c.column == static_cast<int>(T::ColumnIndex::profile_type) &&
c.op == SQLITE_INDEX_CONSTRAINT_EQ;
};
bool has_profile_type_cs =
std::find_if(cs.begin(), cs.end(), profile_type_fn) != cs.end();
return has_ts_cs && (has_upid_cs || has_upid_group_cs) && has_profile_type_cs
? util::OkStatus()
: util::ErrStatus("Failed to find required constraints");
}
std::unique_ptr<Table> ExperimentalFlamegraphGenerator::ComputeTable(
const std::vector<Constraint>& cs,
const std::vector<Order>&,
const BitVector&) {
// Get the input column values and compute the flamegraph using them.
auto values = GetFlamegraphInputValues(cs);
std::unique_ptr<tables::ExperimentalFlamegraphNodesTable> table;
if (values.profile_type == ProfileType::kGraph) {
auto* tracker = HeapGraphTracker::GetOrCreate(context_);
table = tracker->BuildFlamegraph(values.ts, *values.upid);
} else if (values.profile_type == ProfileType::kNative) {
table = BuildNativeHeapProfileFlamegraph(context_->storage.get(),
*values.upid, values.ts);
} else if (values.profile_type == ProfileType::kPerf) {
table = BuildNativeCallStackSamplingFlamegraph(
context_->storage.get(), values.upid, values.upid_group,
values.time_constraints);
}
if (!values.focus_str.empty()) {
table =
FocusTable(context_->storage.get(), std::move(table), values.focus_str);
// The pseudocolumns must be populated because as far as SQLite is
// concerned these are equality constraints.
auto focus_id =
context_->storage->InternString(base::StringView(values.focus_str));
for (uint32_t i = 0; i < table->row_count(); ++i) {
table->mutable_focus_str()->Set(i, focus_id);
}
}
// We need to explicitly std::move as clang complains about a bug in old
// compilers otherwise (-Wreturn-std-move-in-c++11).
return std::move(table);
}
Table::Schema ExperimentalFlamegraphGenerator::CreateSchema() {
return tables::ExperimentalFlamegraphNodesTable::Schema();
}
std::string ExperimentalFlamegraphGenerator::TableName() {
return "experimental_flamegraph";
}
uint32_t ExperimentalFlamegraphGenerator::EstimateRowCount() {
// TODO(lalitm): return a better estimate here when possible.
return 1024;
}
} // namespace trace_processor
} // namespace perfetto
| 37.202667 | 80 | 0.691922 | [
"vector"
] |
148560d968b422887fafd668a98b40d48dbc5dde | 2,159 | cpp | C++ | examples/manual/rotate.cpp | isabella232/stdcxx | b0b0cab391b7b1f2d17ef4342aeee6b792bde63c | [
"Apache-2.0"
] | 53 | 2015-01-13T05:46:43.000Z | 2022-02-24T23:46:04.000Z | examples/manual/rotate.cpp | mann-patel/stdcxx | a22c5192f4b2a8b0b27d3588ea8f6d1faf8b037a | [
"Apache-2.0"
] | 1 | 2021-11-04T12:35:39.000Z | 2021-11-04T12:35:39.000Z | examples/manual/rotate.cpp | isabella232/stdcxx | b0b0cab391b7b1f2d17ef4342aeee6b792bde63c | [
"Apache-2.0"
] | 33 | 2015-07-09T13:31:00.000Z | 2021-11-04T12:12:20.000Z | /**************************************************************************
*
* rotate.cpp - Example program of rotate algorithm.
*
* $Id$
*
***************************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you 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.
*
* Copyright 1994-2006 Rogue Wave Software.
*
**************************************************************************/
#include <algorithm> // for rotate
#include <iostream> // for cout, endl
#include <iterator> // for ostream_iterator
#include <vector> // for vector
#include <examples.h>
int main ()
{
typedef std::vector<int, std::allocator<int> > Vector;
// Initialize a vector with an array of integers.
const Vector::value_type arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Vector v (arr + 0, arr + sizeof arr / sizeof *arr);
typedef std::ostream_iterator<int, char, std::char_traits<char> > Iter;
// Print out elements in original (sorted) order.
std::cout << "Elements before rotate: \n ";
std::copy (v.begin (), v.end (), Iter (std::cout, " "));
// Rotate the elements.
std::rotate (v.begin (), v.begin () + 4, v.end ());
// Print out the rotated elements.
std::cout << "\n\nElements after rotate: \n ";
std::copy (v.begin (), v.end (), Iter (std::cout, " "));
std::cout << std::endl;
return 0;
}
| 35.393443 | 76 | 0.580361 | [
"vector"
] |
148d0bfdd7cde8709c61959229f1f48d34e03b5a | 17,192 | cpp | C++ | flowsnake.cpp | phma/flowbound | d1bd12aeb77964b33ba0fc4595125027ceb447b8 | [
"Apache-2.0"
] | null | null | null | flowsnake.cpp | phma/flowbound | d1bd12aeb77964b33ba0fc4595125027ceb447b8 | [
"Apache-2.0"
] | null | null | null | flowsnake.cpp | phma/flowbound | d1bd12aeb77964b33ba0fc4595125027ceb447b8 | [
"Apache-2.0"
] | null | null | null | /******************************************************/
/* */
/* flowsnake.cpp - flowsnake */
/* */
/******************************************************/
/* Copyright 2020,2021 Pierre Abbat
* Licensed under the Apache License, Version 2.0.
*/
#include <iostream>
#include <cassert>
#include <array>
#include "flowsnake.h"
using namespace std;
const Eisenstein flowBase(2,-1);
const Eisenstein flowBaseConj(3,1);
const Eisenstein limbBase(-25539,25807);
const FlowNumber flowOne("1"),deg60("2");
vector<Segment> boundary;
vector<uint32_t> additionTable,multiplicationTable,negationTable;
/* In these tables, the digits 0 and 1 represent themselves, but 2 is 1+ω,
* 3 is ω, and so around the circle.
*/
const char aTable[7][7]=
{
0,1,2,3,4,5,6, // 0, 1, 2, 3, 4, 5, 6
1,10,19,2,0,6,11, // 1,13,25, 2, 0, 6,14
2,19,18,27,3,0,1, // 2,25,24,36, 3, 0, 1
3,2,27,26,29,4,0, // 3, 2,36,35,41, 4, 0
4,0,3,29,34,37,5, // 4, 0, 3,41,46,52, 5
5,6,0,4,37,36,45, // 5, 6, 0, 4,52,51,63
6,11,1,0,5,45,44 // 6,14, 1, 0, 5,63,62
};
const char mTable[7][7]=
{
0,0,0,0,0,0,0,
0,1,2,3,4,5,6,
0,2,3,4,5,6,1,
0,3,4,5,6,1,2,
0,4,5,6,1,2,3,
0,5,6,1,2,3,4,
0,6,1,2,3,4,5
};
const int pow7[]={1,7,49,343,2401,16807,117649,823543,5764801,40353607,282475249,1977326743};
void init()
{
boundary.clear();
boundary.push_back(Segment(Eisenstein(1,-1),Eisenstein(2,1),0));
}
void refine()
{
vector<Segment> newbdy;
int i;
Eisenstein diff,p0,p1,p2,p3;
mpz_class along;
for (i=0;i<boundary.size();i++)
{
diff=(boundary[i].b-boundary[i].a)*flowBaseConj;
p0=boundary[i].a*7;
p3=boundary[i].b*7;
p1=p0+diff;
p2=p3-diff;
along=boundary[i].l*3;
newbdy.push_back(Segment(p0,p1,along));
newbdy.push_back(Segment(p1,p2,along+1));
newbdy.push_back(Segment(p2,p3,along+2));
}
swap(boundary,newbdy);
}
void prune()
{
vector<Segment> newbdy;
int i;
Eisenstein diff;
mpz_class max,lensq,cutoff;
for (i=0;i<boundary.size();i++)
{
if (boundary[i].a.cartx()>max)
max=boundary[i].a.cartx();
if (boundary[i].a.cartx()>max)
max=boundary[i].a.cartx();
}
diff=boundary[0].b-boundary[0].a;
lensq=diff.norm();
cutoff=max-sqrt(4*lensq.get_d());
for (i=0;i<boundary.size();i++)
if (boundary[i].a.cartx()>=cutoff || boundary[i].b.cartx()>=cutoff)
newbdy.push_back(boundary[i]);
swap(boundary,newbdy);
}
string toBase7(mpz_class n)
{
int i;
mpz_class rem;
string ret;
while (n || ret.length()==0)
{
rem=n%7;
n/=7;
ret=(char)('0'+rem.get_si())+ret;
}
return ret;
}
string toBase9(mpz_class n)
{
int i;
mpz_class rem;
string ret;
while (n || ret.length()==0)
{
rem=n%9;
n/=9;
ret=(char)('0'+rem.get_si())+ret;
}
return ret;
}
int add343(int a,int b)
{
int aDig[3],bDig[3],resDig[4];
int i,carry,res=0;
for (i=0;i<3;i++)
{
aDig[i]=a%7;
a/=7;
bDig[i]=b%7;
b/=7;
resDig[i]=0;
}
resDig[3]=0;
for (i=0;i<3;i++)
{
carry=0;
resDig[i]=aTable[aDig[i]][resDig[i]];
if (resDig[i]>6)
{
carry=resDig[i]/7;
resDig[i]%=7;
}
resDig[i]=aTable[bDig[i]][resDig[i]];
if (resDig[i]>6)
{ // Adding three digits cannot produce more than a two-digit number.
carry=aTable[carry][resDig[i]/7];
resDig[i]%=7;
}
resDig[i+1]=carry;
}
for (i=3;i>=0;i--)
res=7*res+resDig[i];
return res;
}
int mul343(int a,int b)
{
int aDig[3],bDig[3],prods[3][3],resDig[6];
int i,j,k,carry,res=0;
for (i=0;i<3;i++)
{
aDig[i]=a%7;
a/=7;
bDig[i]=b%7;
b/=7;
resDig[i]=resDig[i+3]=0;
}
for (i=0;i<3;i++)
for (j=0;j<3;j++)
prods[i][j]=mTable[aDig[i]][bDig[j]];
for (i=0;i<3;i++)
{
for (j=0;j<3;j++)
{
k=i+j;
resDig[k]=aTable[resDig[k]][prods[i][j]];
while (resDig[k]>=7)
{
carry=resDig[k]/7;
resDig[k]%=7;
k++;
resDig[k]=aTable[resDig[k]][carry];
}
}
}
for (i=5;i>=0;i--)
res=7*res+resDig[i];
return res;
}
uint32_t negateLimb(uint32_t a)
{
uint32_t hi,lo;
uint32_t ret=0;
hi=a/pow7[6];
lo=a%pow7[6];
ret=negationTable[hi]*pow7[6]+negationTable[lo];
return ret;
}
array<uint32_t,2> addLimbs(uint32_t a,uint32_t b)
{
int aDig[4],bDig[4],resDig[4];
int i,carry;
array<uint32_t,2> res;
for (i=0;i<4;i++)
{
aDig[i]=a%343;
bDig[i]=b%343;
a/=343;
b/=343;
resDig[i]=0;
}
for (i=0;i<4;i++)
{
carry=0;
resDig[i]=additionTable[aDig[i]*343+resDig[i]];
if (resDig[i]>342)
{
carry=resDig[i]/343;
resDig[i]%=343;
}
resDig[i]=additionTable[bDig[i]*343+resDig[i]];
if (resDig[i]>342)
{ // Adding three digits cannot produce more than a two-digit number.
carry=additionTable[carry*343+resDig[i]/343];
resDig[i]%=343;
}
assert(carry<343);
resDig[i+1]=carry;
}
res[1]=resDig[3]/49;
res[0]=0;
resDig[3]%=49;
for (i=3;i>=0;i--)
res[0]=343*res[0]+resDig[i];
return res;
}
array<uint32_t,2> mulLimbs(uint32_t a,uint32_t b)
{
int aDig[4],bDig[4],prods[4][4],resDig[8];
int i,j,k,carry,carry2=0;
array<uint32_t,2> res;
for (i=0;i<4;i++)
{
aDig[i]=a%343;
a/=343;
bDig[i]=b%343;
b/=343;
resDig[i]=resDig[i+4]=0;
}
for (i=0;i<4;i++)
for (j=0;j<4;j++)
prods[i][j]=multiplicationTable[aDig[i]*343+bDig[j]];
for (i=0;i<4;i++)
{
for (j=0;j<4;j++)
{
k=i+j;
resDig[k]=additionTable[resDig[k]*343+prods[i][j]%343];
resDig[k+1]=additionTable[resDig[k+1]*343+prods[i][j]/343];
while (resDig[k]>=343 || resDig[k+1]>=343 || carry2)
{
carry=additionTable[carry2*343+resDig[k]/343];
resDig[k]%=343;
k++;
carry2=resDig[k]/343;
resDig[k]=additionTable[(resDig[k]%343)*343+carry];
}
}
}
res[1]=0;
assert(resDig[7]<7);
for (i=7;i>=4;i--) // 76665554443 33222111000
res[1]=343*res[1]+resDig[i];
res[1]=7*res[1]+resDig[3]/49;
res[0]=resDig[3]%49;
for (i=2;i>=0;i--)
res[0]=343*res[0]+resDig[i];
return res;
}
Eisenstein limbToEisenstein(uint32_t n)
{
int i,dig;
Eisenstein ret,powBase=1;
while (n)
{
dig=n%7;
n/=7;
if (dig)
ret+=powBase*root1[dig-1];
powBase*=flowBase;
}
return ret;
}
void fillTables()
{
int i,j,neg,pos;
for (i=0;i<343;i++)
for (j=0;j<343;j++)
{
additionTable.push_back(add343(i,j));
multiplicationTable.push_back(mul343(i,j));
}
additionTable.shrink_to_fit();
multiplicationTable.shrink_to_fit();
for (i=0;i<pow7[6];i++)
{
for (neg=j=0,pos=i;j<6;j++)
{
neg*=7;
if (pos>=pow7[5] && pos<pow7[5]*4)
neg+=pos/pow7[5]+3;
if (pos>=pow7[5]*4)
neg+=pos/pow7[5]-3;
pos=(pos%pow7[5])*7;
}
negationTable.push_back(neg);
}
negationTable.shrink_to_fit();
}
void testTables()
{
int i,j,k;
vector<int> realInts,upOneInts;
array<uint32_t,2> intRes,left,right;
for (i=270;i<343;i=additionTable[i*343+1])
{
realInts.push_back(i);
cout<<toBase7(mpz_class(i))<<' ';
}
cout<<'\n';
for (i=269;i<343;i=additionTable[i*343+1])
{
upOneInts.push_back(i);
cout<<toBase7(mpz_class(i))<<' ';
}
cout<<'\n'<<realInts.size()<<" integers with up to three digits\n";
for (i=0;i<realInts.size();i++)
for (j=0;j<upOneInts.size();j++)
assert(limbToEisenstein(multiplicationTable[realInts[i]*343+upOneInts[j]])==
limbToEisenstein(realInts[i])*limbToEisenstein(upOneInts[j]));
// Test associativity of multiplication with intermediate results up to 7**11
assert(mulLimbs(2667,2736)[0]==mulLimbs(2736,2667)[0]);
assert(mulLimbs(16260,2736)[0]==mulLimbs(2736,16260)[0]);
assert(mulLimbs(2667,39302898)[0]==mulLimbs(39302898,2667)[0]);
assert(mulLimbs(16260,11137910)[0]==mulLimbs(11137910,16260)[0]);
mulLimbs(5472,15718);
for (i=0;i<16384;i+=381)
for (j=0;j<117649;j+=2736)
for (k=0;k<16807;k+=542)
{
intRes=mulLimbs(i,j);
left=mulLimbs(intRes[0],k);
intRes=mulLimbs(j,k);
right=mulLimbs(i,intRes[0]);
assert(left[0]==right[0]);
assert(left[1]==right[1]);
}
// Test associativity of addition
for (i=0;i<282475249;i+=1478928)
for (j=0;j<282475249;j+=1870697)
for (k=0;k<282475249;k+=1578074)
{
intRes=addLimbs(i,j);
left=addLimbs(intRes[0],k);
intRes=addLimbs(j,k);
right=addLimbs(i,intRes[0]);
assert(left[0]==right[0]);
assert(left[1]==right[1]);
}
}
FlowNumber::FlowNumber()
{
exponent=0;
}
FlowNumber::FlowNumber(std::string a)
{
size_t i,l;
size_t len=a.find_first_not_of("0123456.");
if (len<a.length())
a.erase(len);
size_t point=a.find('.');
if (point>a.length())
point=a.length();
limbs.resize((point+10)/11+(a.length()-point+9)/11);
exponent=-((a.length()-point+9)/11);
for (i=0;i<a.length();i++)
{
if (i<point)
l=(point-i-1)/11-exponent;
else
l=-((i-point-1)/11)-exponent-1;
if (a[i]!='.')
limbs[l]=limbs[l]*7+a[i]-'0';
}
for (;i>point && (i-point-1)%11;i++)
limbs[0]*=7;
normalize();
}
int FlowNumber::precision=44;
bool FlowNumber::precType=false;
void FlowNumber::setPrecision(int p,bool t)
/* If t, p is the number of significant digits in the result of division.
* If !t, p is the number of digits after the radix point.
*/
{
if (t && p<0)
p=0;
precision=p;
precType=t;
}
string FlowNumber::toString()
{
int i,j;
string ret;
for (i=limbs.size()-1;i>=0;i--)
for (j=10;j>=0;j--)
ret+=(char)'0'+(limbs[i]/pow7[j])%7;
for (i=0;i<exponent;i++)
ret+="00000000000";
while (ret.length()/11+exponent<0)
ret="00000000000"+ret;
if (exponent>=0)
ret+='.';
else
ret.insert(ret.length()+11*exponent,".");
ret.erase(0,ret.find_first_not_of('0'));
ret.erase(ret.find_last_not_of('0')+1);
if (ret[0]=='.')
ret="0"+ret;
if (ret[ret.length()-1]=='.')
ret.erase(ret.length()-1);
return ret;
}
void FlowNumber::normalize()
{
int i;
for (i=0;i<limbs.size() && limbs[i]==0;i++);
exponent+=i;
if (i)
{
memmove(&limbs[0],&limbs[1],sizeof(limbs[0])*(limbs.size()-i));
memset(&limbs[limbs.size()-i],0,sizeof(limbs[0])*i);
}
for (i=limbs.size()-1;i>=0 && limbs[i]==0;i--);
limbs.resize(i+1);
if (limbs.size()==0)
exponent=0;
}
FlowNumber::operator complex<double>() const
{
int i;
Eisenstein acc;
for (i=limbs.size()-1;i>=0;i--)
acc=acc*limbBase+limbToEisenstein(limbs[i]);
return (complex<double>)acc*pow((complex<double>)limbBase,exponent);
}
array<int,3> FlowNumber::msd() const
/* Returns the most significant digit in [0], and its position in [1], and
* the position of the least significant digit in [2].
* Position is absolute; e.g. if passed 0.00012350000, it returns
* {1,-4,-7}. The number must be normalized.
*/
{
array<int,3> ret;
if (limbs.size())
{
ret[0]=limbs[0];
ret[2]=exponent*11;
if (ret[0]%pow7[8]==0)
{
ret[0]/=pow7[8];
ret[2]+=8;
}
if (ret[0]%pow7[4]==0)
{
ret[0]/=pow7[4];
ret[2]+=4;
}
if (ret[0]%pow7[2]==0)
{
ret[0]/=pow7[2];
ret[2]+=2;
}
if (ret[0]%pow7[1]==0)
{
ret[0]/=pow7[1];
ret[2]+=1;
}
ret[0]=limbs.back();
ret[1]=(limbs.size()+exponent-1)*11;
if (ret[0]>=pow7[8])
{
ret[0]/=pow7[8];
ret[1]+=8;
}
if (ret[0]>=pow7[4])
{
ret[0]/=pow7[4];
ret[1]+=4;
}
if (ret[0]>=pow7[2])
{
ret[0]/=pow7[2];
ret[1]+=2;
}
if (ret[0]>=pow7[1])
{
ret[0]/=pow7[1];
ret[1]+=1;
}
}
else
{
ret[0]=ret[1]=0;
ret[2]=11;
}
return ret;
}
FlowNumber operator+(const FlowNumber &l,const FlowNumber &r)
{
int highExp,i,j;
FlowNumber ret;
array<uint32_t,2> resLimb;
ret.exponent=min(l.exponent,r.exponent);
highExp=max((signed)(l.exponent+l.limbs.size()),(signed)(r.exponent+r.limbs.size()))+1;
ret.limbs.resize(highExp-ret.exponent);
for (i=ret.exponent;i<highExp;i++)
{
if (i>=l.exponent && i<(signed)(l.exponent+l.limbs.size()))
{
resLimb=addLimbs(ret.limbs[i-ret.exponent],l.limbs[i-l.exponent]);
ret.limbs[i-ret.exponent]=resLimb[0];
j=i;
while (resLimb[1])
{
j++;
resLimb=addLimbs(resLimb[1],ret.limbs[j-ret.exponent]);
ret.limbs[j-ret.exponent]=resLimb[0];
}
}
if (i>=r.exponent && i<(signed)(r.exponent+r.limbs.size()))
{
resLimb=addLimbs(ret.limbs[i-ret.exponent],r.limbs[i-r.exponent]);
ret.limbs[i-ret.exponent]=resLimb[0];
j=i;
while (resLimb[1])
{
j++;
resLimb=addLimbs(resLimb[1],ret.limbs[j-ret.exponent]);
ret.limbs[j-ret.exponent]=resLimb[0];
}
}
}
ret.normalize();
return ret;
}
FlowNumber operator-(const FlowNumber &l,const FlowNumber &r)
{
int highExp,i,j;
FlowNumber ret;
array<uint32_t,2> resLimb;
ret.exponent=min(l.exponent,r.exponent);
highExp=max((signed)(l.exponent+l.limbs.size()),(signed)(r.exponent+r.limbs.size()))+1;
ret.limbs.resize(highExp-ret.exponent);
for (i=ret.exponent;i<highExp;i++)
{
if (i>=l.exponent && i<(signed)(l.exponent+l.limbs.size()))
{
resLimb=addLimbs(ret.limbs[i-ret.exponent],l.limbs[i-l.exponent]);
ret.limbs[i-ret.exponent]=resLimb[0];
j=i;
while (resLimb[1])
{
j++;
resLimb=addLimbs(resLimb[1],ret.limbs[j-ret.exponent]);
ret.limbs[j-ret.exponent]=resLimb[0];
}
}
if (i>=r.exponent && i<(signed)(r.exponent+r.limbs.size()))
{
resLimb=addLimbs(ret.limbs[i-ret.exponent],negateLimb(r.limbs[i-r.exponent]));
ret.limbs[i-ret.exponent]=resLimb[0];
j=i;
while (resLimb[1])
{
j++;
resLimb=addLimbs(resLimb[1],ret.limbs[j-ret.exponent]);
ret.limbs[j-ret.exponent]=resLimb[0];
}
}
}
ret.normalize();
return ret;
}
FlowNumber operator*(const FlowNumber &l,const FlowNumber &r)
{
int i,j,k;
FlowNumber ret;
array<uint32_t,2> resLimb,prodLimb;
ret.exponent=l.exponent+r.exponent;
ret.limbs.resize(l.limbs.size()+r.limbs.size());
for (i=0;i<l.limbs.size();i++)
for (j=0;j<r.limbs.size();j++)
{
prodLimb=mulLimbs(l.limbs[i],r.limbs[j]);
k=i+j;
resLimb=addLimbs(prodLimb[0],ret.limbs[k]);
ret.limbs[k]=resLimb[0];
while (resLimb[1])
{
k++;
resLimb=addLimbs(resLimb[1],ret.limbs[k]);
ret.limbs[k]=resLimb[0];
}
k=i+j+1;
resLimb=addLimbs(prodLimb[1],ret.limbs[k]);
ret.limbs[k]=resLimb[0];
while (resLimb[1])
{
k++;
resLimb=addLimbs(resLimb[1],ret.limbs[k]);
ret.limbs[k]=resLimb[0];
}
}
ret.normalize();
return ret;
}
FlowNumber operator/(FlowNumber l,const FlowNumber &r)
{
int i,j,k;
int lastPosition,divisorSize,samePosCount=0,prevPos;
int quotDigit[6]; // quotDigit[0] is for when msd(l) is 1
FlowNumber ret,nextDigit(flowOne);
FlowNumber multiples[6];
array<int,3> hiDigit;
hiDigit=r.msd();
if (hiDigit[0]==0)
throw runtime_error("Divide by zero");
divisorSize=hiDigit[1];
quotDigit[5]=7-hiDigit[0];
j=5;
for (i=4;i>=0;i--)
{
quotDigit[i]=quotDigit[i+1]-1;
if (quotDigit[i]==0)
quotDigit[i]=6;
if (quotDigit[i]==4) // When quotDigit is 4, which means -1, add the dividend
j=i;
}
multiples[j]=r;
for (i=0;i<5;i++)
multiples[(i+j+1)%6]=multiples[(i+j)%6]*deg60;
lastPosition=-FlowNumber::precision;
while (true)
{
hiDigit=l.msd();
if (hiDigit[1]==prevPos)
{
samePosCount++;
if (samePosCount>=6)
hiDigit[1]--;
}
else
{
samePosCount=0;
prevPos=hiDigit[1];
}
if (hiDigit[0]==0 || hiDigit[1]-divisorSize<lastPosition)
break;
nextDigit.limbs[0]=quotDigit[hiDigit[0]-1];
ret=ret+(nextDigit<<(hiDigit[1]-divisorSize));
l=l+(multiples[hiDigit[0]-1]<<(hiDigit[1]-divisorSize));
}
return ret;
}
FlowNumber operator<<(const FlowNumber &l,int n)
{
FlowNumber ret;
int limbShift,digShift,i;
digShift=n%11;
if (digShift<0)
digShift+=11;
limbShift=(n-digShift)/11;
ret.limbs.resize(l.limbs.size()+1);
for (i=0;i<l.limbs.size();i++)
{
ret.limbs[i]+=(l.limbs[i]%pow7[11-digShift])*pow7[digShift];
ret.limbs[i+1]+=(l.limbs[i]/pow7[11-digShift]);
}
ret.exponent=l.exponent+limbShift;
ret.normalize();
return ret;
}
FlowNumber complexToFlowNumber(complex<double> z)
{
int i,n,j,xp=0,sz;
bool stop=false;
FlowNumber inc;
vector<FlowNumber> approx;
vector<double> diff;
if (z!=0.)
xp=lrint(log(norm(z))/log(7))+2;
n=xp;
approx.push_back(FlowNumber());
diff.push_back(abs((complex<double>)approx[0]-z));
while (!stop)
{
inc=flowOne<<xp;
sz=approx.size();
for (i=0;i<sz;i++)
for (j=0;j<6;j++)
{
approx.push_back(approx[i]+inc);
diff.push_back(abs((complex<double>)approx.back()-z));
inc=inc*deg60;
}
for (i=0;i<approx.size();i++)
for (j=i-1;j>=0;j--)
if (diff[j]>diff[j+1])
{
swap(diff[j],diff[j+1]);
swap(approx[j],approx[j+1]);
}
if (diff[0]==0 || n-xp>44)
stop=true;
diff.resize(4);
approx.resize(4);
xp--;
}
return approx[0];
}
| 22.801061 | 93 | 0.576489 | [
"vector"
] |
148e026a0da286de7c85cf96d3cb7f7f645210e3 | 463 | cpp | C++ | codes/c++/122.cpp | YuanweiZHANG/Leetcode | 14a083528431bc65ada8f8265a5ef9d0fae40ecd | [
"MIT"
] | null | null | null | codes/c++/122.cpp | YuanweiZHANG/Leetcode | 14a083528431bc65ada8f8265a5ef9d0fae40ecd | [
"MIT"
] | null | null | null | codes/c++/122.cpp | YuanweiZHANG/Leetcode | 14a083528431bc65ada8f8265a5ef9d0fae40ecd | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
/**
* 2020-04-05
* Veronica
*/
class Solution {
public:
int maxProfit(vector<int>& prices) {
int days = prices.size(), profit = 0;
for (int i = 1; i < days; ++i) {
if (prices[i] > prices[i - 1])
profit += prices[i] - prices[i - 1];
}
return profit;
}
};
int main() {
Solution solution;
vector<int> prices = { 7,1,5,3,6,4 };
cout << solution.maxProfit(prices) << endl;
return 0;
} | 16.535714 | 44 | 0.598272 | [
"vector"
] |
148eb55e41c1b8126e505bfbe2a6a2e8fcb7c021 | 85,560 | hh | C++ | MUSIC/solver.hh | NERSC/cosmoflow-sims | 04701369e2dc07d5c9ea1c82bd1ddbd6ef45636e | [
"BSD-3-Clause-LBNL"
] | null | null | null | MUSIC/solver.hh | NERSC/cosmoflow-sims | 04701369e2dc07d5c9ea1c82bd1ddbd6ef45636e | [
"BSD-3-Clause-LBNL"
] | null | null | null | MUSIC/solver.hh | NERSC/cosmoflow-sims | 04701369e2dc07d5c9ea1c82bd1ddbd6ef45636e | [
"BSD-3-Clause-LBNL"
] | 2 | 2018-09-18T22:51:28.000Z | 2019-09-06T09:55:58.000Z | /*
* solver.h
* GravitySolver
*
* Created by Oliver Hahn on 1/20/10.
* Copyright 2010 KIPAC/Stanford University. All rights reserved.
*
*/
#ifndef __SOLVER_HH
#define __SOLVER_HH
#include <cmath>
#include <iostream>
#include "mesh.hh"
#define BEGIN_MULTIGRID_NAMESPACE namespace multigrid {
#define END_MULTIGRID_NAMESPACE }
BEGIN_MULTIGRID_NAMESPACE
namespace opt {
enum smtype { sm_jacobi, sm_gauss_seidel, sm_sor };
}
template< class S, class O, typename T=double >
class solver
{
public:
typedef S scheme;
typedef O mgop;
protected:
scheme m_scheme;
mgop m_gridop;
unsigned m_npresmooth, m_npostsmooth;
opt::smtype m_smoother;
unsigned m_ilevelmin;
const static bool m_bperiodic = true;
GridHierarchy<T> *m_pu, *m_pf, *m_pfsave;
GridHierarchy<bool> *m_pmask;
const MeshvarBnd<T> *m_pubnd;
double compute_error( const MeshvarBnd<T>& u, const MeshvarBnd<T>& unew );
double compute_error( const GridHierarchy<T>& uh, const GridHierarchy<T>& uhnew, bool verbose );
protected:
void Jacobi( T h, MeshvarBnd<T>* u, const MeshvarBnd<T>* f );
void GaussSeidel( T h, MeshvarBnd<T>* u, const MeshvarBnd<T>* f );
void SOR( T h, MeshvarBnd<T>* u, const MeshvarBnd<T>* f );
void twoGrid( unsigned ilevel );
void interp_coarse_fine( unsigned ilevel, MeshvarBnd<T>& coarse, MeshvarBnd<T>& fine, bool bcf=true );
void setBC( unsigned ilevel );
void make_periodic( MeshvarBnd<T> *u );
void interp_cubic( MeshvarBnd<T>& coarse, MeshvarBnd<T>& fine, int itop, int jtop, int ktop, int i, int j, int k );
void interp_coarse_fine_cubic( unsigned ilevel, MeshvarBnd<T>& coarse, MeshvarBnd<T>& fine, bool bcf );
public:
solver( GridHierarchy<T>& f, //const MeshvarBnd<T>& uBC_top,
opt::smtype smoother, unsigned npresmooth, unsigned npostsmooth );
~solver()
{ delete m_pmask; }
double solve( GridHierarchy<T>& u, double accuracy, double h=-1.0, bool verbose=false );
double solve( GridHierarchy<T>& u, double accuracy, bool verbose=false )
{
return this->solve ( u, accuracy, -1.0, verbose );
}
};
template< class S, class O, typename T >
solver<S,O,T>::solver( GridHierarchy<T>& f, //const MeshvarBnd<T>& ubnd,
opt::smtype smoother, unsigned npresmooth, unsigned npostsmooth )
: m_scheme(), m_gridop(), m_npresmooth( npresmooth ), m_npostsmooth( npostsmooth ),
m_smoother( smoother ), m_ilevelmin( f.levelmin() ), m_pf( &f )//, m_pubnd( &ubnd )
{
//... initialize the refinement mask
m_pmask = new GridHierarchy<bool>( f.m_nbnd );
m_pmask->create_base_hierarchy(f.levelmin());
for( unsigned ilevel=f.levelmin()+1; ilevel<=f.levelmax(); ++ilevel )
{
meshvar_bnd* pf = f.get_grid(ilevel);
m_pmask->add_patch( pf->offset(0), pf->offset(1), pf->offset(2), pf->size(0), pf->size(1), pf->size(2) );
}
m_pmask->zero();
for( unsigned ilevel=0; ilevel<f.levelmin(); ++ilevel )
{
MeshvarBnd<T> *pf = f.get_grid(ilevel);
for( int ix=0; ix < (int)pf->size(0); ++ix )
for( int iy=0; iy < (int)pf->size(1); ++iy )
for( int iz=0; iz < (int)pf->size(2); ++iz )
(*m_pmask->get_grid(ilevel))(ix,iy,iz) = true;
}
for( unsigned ilevel=m_ilevelmin; ilevel<f.levelmax(); ++ilevel )
{
MeshvarBnd<T>* pf = f.get_grid(ilevel+1);//, *pfc = f.get_grid(ilevel);
for( int ix=pf->offset(0); ix < (int)(pf->offset(0)+pf->size(0)/2); ++ix )
for( int iy=pf->offset(1); iy < (int)(pf->offset(1)+pf->size(1)/2); ++iy )
for( int iz=pf->offset(2); iz < (int)(pf->offset(2)+pf->size(2)/2); ++iz )
(*m_pmask->get_grid(ilevel))(ix,iy,iz) = true;
}
}
template< class S, class O, typename T >
void solver<S,O,T>::Jacobi( T h, MeshvarBnd<T> *u, const MeshvarBnd<T>* f )
{
int
nx = u->size(0),
ny = u->size(1),
nz = u->size(2);
double
c0 = -1.0/m_scheme.ccoeff(),
h2 = h*h;
MeshvarBnd<T> uold(*u);
double alpha = 0.95, ialpha = 1.0-alpha;
#pragma omp parallel for
for( int ix=0; ix<nx; ++ix )
for( int iy=0; iy<ny; ++iy )
for( int iz=0; iz<nz; ++iz )
(*u)(ix,iy,iz) = ialpha * uold(ix,iy,iz) + alpha * (m_scheme.rhs( uold, ix, iy, iz ) + h2 * (*f)(ix,iy,iz))*c0;
}
template< class S, class O, typename T >
void solver<S,O,T>::SOR( T h, MeshvarBnd<T> *u, const MeshvarBnd<T>* f )
{
int
nx = u->size(0),
ny = u->size(1),
nz = u->size(2);
double
c0 = -1.0/m_scheme.ccoeff(),
h2 = h*h;
MeshvarBnd<T> uold(*u);
double
alpha = 1.2,
//alpha = 2 / (1 + 4 * atan(1.0) / double(u->size(0)))-1.0,
ialpha = 1.0-alpha;
//std::cerr << "omega_opt = " << alpha << std::endl;
#pragma omp parallel for
for( int ix=0; ix<nx; ++ix )
for( int iy=0; iy<ny; ++iy )
for( int iz=0; iz<nz; ++iz )
if( (ix+iy+iz)%2==0 )
(*u)(ix,iy,iz) = ialpha * uold(ix,iy,iz) + alpha * (m_scheme.rhs( uold, ix, iy, iz ) + h2 * (*f)(ix,iy,iz))*c0;
#pragma omp parallel for
for( int ix=0; ix<nx; ++ix )
for( int iy=0; iy<ny; ++iy )
for( int iz=0; iz<nz; ++iz )
if( (ix+iy+iz)%2!=0 )
(*u)(ix,iy,iz) = ialpha * uold(ix,iy,iz) + alpha * (m_scheme.rhs( *u, ix, iy, iz ) + h2 * (*f)(ix,iy,iz))*c0;
}
template< class S, class O, typename T >
void solver<S,O,T>::GaussSeidel( T h, MeshvarBnd<T>* u, const MeshvarBnd<T>* f )
{
int
nx = u->size(0),
ny = u->size(1),
nz = u->size(2);
T
c0 = -1.0/m_scheme.ccoeff(),
h2 = h*h;
for( int color=0; color < 2; ++color )
#pragma omp parallel for
for( int ix=0; ix<nx; ++ix )
for( int iy=0; iy<ny; ++iy )
for( int iz=0; iz<nz; ++iz )
if( (ix+iy+iz)%2 == color )
(*u)(ix,iy,iz) = (m_scheme.rhs( *u, ix, iy, iz ) + h2 * (*f)(ix,iy,iz))*c0;
}
template< class S, class O, typename T >
void solver<S,O,T>::twoGrid( unsigned ilevel )
{
MeshvarBnd<T> *uf, *uc, *ff, *fc;
T
h = 1.0/(pow(2.0,ilevel)),
c0 = -1.0/m_scheme.ccoeff(),
h2 = h*h;
uf = m_pu->get_grid(ilevel);
ff = m_pf->get_grid(ilevel);
uc = m_pu->get_grid(ilevel-1);
fc = m_pf->get_grid(ilevel-1);
int
nx = uf->size(0),
ny = uf->size(1),
nz = uf->size(2);
if( m_bperiodic && ilevel <= m_ilevelmin)
make_periodic( uf );
else if(!m_bperiodic)
setBC( ilevel );
//... do smoothing sweeps with specified solver
for( unsigned i=0; i<m_npresmooth; ++i ){
if( ilevel > m_ilevelmin )
interp_coarse_fine(ilevel, *uc, *uf );
if( m_smoother == opt::sm_gauss_seidel )
GaussSeidel( h, uf, ff );
else if( m_smoother == opt::sm_jacobi )
Jacobi( h, uf, ff);
else if( m_smoother == opt::sm_sor )
SOR( h, uf, ff );
if( m_bperiodic && ilevel <= m_ilevelmin )
make_periodic( uf );
}
m_gridop.restrict( *uf, *uc );
//... essential!!
if( m_bperiodic && ilevel <= m_ilevelmin )
make_periodic( uc );
else if( m_bperiodic )
interp_coarse_fine(ilevel,*uc,*uf);
meshvar_bnd Lu(*uf,false);
Lu.zero();
#pragma omp parallel for
for( int ix=0; ix<nx; ++ix )
for( int iy=0; iy<ny; ++iy )
for( int iz=0; iz<nz; ++iz )
Lu(ix,iy,iz) = m_scheme.apply( (*uf), ix, iy, iz )/h2;
meshvar_bnd tLu(*uc,false);
//... restrict Lu
m_gridop.restrict( Lu, tLu );
Lu.deallocate();
//... restrict source term
m_gridop.restrict( *ff, *fc );
//... compute RHS tau-correction
#pragma omp parallel for schedule(dynamic)
for( int ix=0; ix<(int)uc->size(0); ++ix )
for( int iy=0; iy<(int)uc->size(1); ++iy )
for( int iz=0; iz<(int)uc->size(2); ++iz )
if( (*m_pmask->get_grid(ilevel-1))(ix,iy,iz) == true )
(*fc)(ix,iy,iz) += ((tLu( ix, iy, iz ) - (m_scheme.apply( *uc, ix, iy, iz )/(4.0*h2))));
tLu.deallocate();
meshvar_bnd ucsave(*uc,true);
//... have we reached the end of the recursion or do we need to go up one level?
if( ilevel == 1 )
if( m_bperiodic )
(*uc)(0,0,0) = 0.0;
else
(*uc)(0,0,0) = (m_scheme.rhs( (*uc), 0, 0, 0 ) + 4.0 * h2 * (*fc)(0,0,0))*c0;
else
twoGrid( ilevel-1 );
meshvar_bnd cc(*uc,false);
//... compute correction on coarse grid
#pragma omp parallel for
for( int ix=0; ix<(int)cc.size(0); ++ix )
for( int iy=0; iy<(int)cc.size(1); ++iy )
for( int iz=0; iz<(int)cc.size(2); ++iz )
cc(ix,iy,iz) = (*uc)(ix,iy,iz) - ucsave(ix,iy,iz);
ucsave.deallocate();
//... prolongate correction to fine grid
meshvar_bnd cf(*uf,false);
m_gridop.prolong( cc, cf );
cc.deallocate();
#pragma omp parallel for
for( int ix=0; ix<nx; ++ix )
for( int iy=0; iy<ny; ++iy )
for( int iz=0; iz<nz; ++iz )
(*uf)(ix,iy,iz) += cf(ix,iy,iz);
cf.deallocate();
//... interpolate and apply coarse-fine boundary conditions on fine level
if( m_bperiodic && ilevel <= m_ilevelmin )
make_periodic( uf );
else if(!m_bperiodic)
setBC( ilevel );
//if( ilevel > m_ilevelmin )
// interp_coarse_fine(ilevel, *uc, *uf );
//... do smoothing sweeps with specified solver
for( unsigned i=0; i<m_npostsmooth; ++i ){
if( ilevel > m_ilevelmin )
interp_coarse_fine(ilevel, *uc, *uf );
if( m_smoother == opt::sm_gauss_seidel )
GaussSeidel( h, uf, ff );
else if( m_smoother == opt::sm_jacobi )
Jacobi( h, uf, ff);
else if( m_smoother == opt::sm_sor )
SOR( h, uf, ff );
if( m_bperiodic && ilevel <= m_ilevelmin )
make_periodic( uf );
}
}
template< class S, class O, typename T >
double solver<S,O,T>::compute_error( const MeshvarBnd<T>& u, const MeshvarBnd<T>& unew )
{
int
nx = u.size(0),
ny = u.size(1),
nz = u.size(2);
double err = 0.0;
unsigned count = 0;
#pragma omp parallel for reduction(+:err,count)
for( int ix=0; ix<nx; ++ix )
for( int iy=0; iy<ny; ++iy )
for( int iz=0; iz<nz; ++iz )
if( fabs(unew(ix,iy,iz)) > 0.0 )//&& u(ix,iy,iz) != unew(ix,iy,iz) )
{
err += fabs(1.0 - u(ix,iy,iz)/unew(ix,iy,iz));
++count;
}
if( count != 0 )
err /= count;
return err;
}
template< class S, class O, typename T >
double solver<S,O,T>::compute_error( const GridHierarchy<T>& uh, const GridHierarchy<T>& uhnew, bool verbose )
{
double maxerr = 0.0;
for( unsigned ilevel=uh.levelmin(); ilevel <= uh.levelmax(); ++ilevel )
{
double err = 0.0;
err = compute_error( *uh.get_grid(ilevel), *uhnew.get_grid(ilevel) );
if( verbose )
std::cout << " Level " << std::setw(6) << ilevel << ", Error = " << err << std::endl;
maxerr = std::max(maxerr,err);
}
return maxerr;
}
template< class S, class O, typename T >
double solver<S,O,T>::solve( GridHierarchy<T>& uh, double acc, double h, bool verbose )
{
double err;
GridHierarchy<T> uhnew(uh);//, fsave(*m_pf);
m_pu = &uh;
unsigned niter = 0;
//... iterate ...//
while (true)
{
twoGrid( uh.levelmax() );
err = compute_error( *m_pu, uhnew, verbose );
++niter;
if( verbose ){
std::cout << "--> Step No. " << std::setw(3) << niter << ", Max Err = " << err << std::endl;
std::cout << "-------------------------------------------------------------\n";
}
if( (niter > 1) && ((err < acc) || (niter > 20)) )
break;
uhnew = *m_pu;
//*m_pf = fsave;
}
if( err > acc )
std::cout << "Error : no convergence in Poisson solver" << std::endl;
else if( verbose )
std::cout << " - Converged in " << niter << " steps to req. acc. of " << acc << std::endl;
//uh = uhnew;
//*m_pf = fsave;
return err;
}
inline double interp2( double x1, double x2, double x3, double f1, double f2, double f3, double x )
{
double a,b,c;
a = (x1 * f3 - x3 * f1 - x2 * f3 - x1 * f2 + x2 * f1 + x3 * f2) / (x1 * x3 * x3 - x2 * x3 * x3 + x2 * x1 * x1 - x3 * x1 * x1 + x3 * x2 * x2 - x1 * x2 * x2);
b = -(x1 * x1 * f3 - x1 * x1 * f2 - f1 * x3 * x3 + f2 * x3 * x3 - x2 * x2 * f3 + f1 * x2 * x2) / (x1 - x2) / (x1 * x2 - x1 * x3 + x3 * x3 - x2 * x3);
c = (x1 * x1 * x2 * f3 - x1 * x1 * x3 * f2 - x2 * x2 * x1 * f3 + f2 * x1 * x3 * x3 + x2 * x2 * x3 * f1 - f1 * x2 * x3 * x3) / (x1 - x2) / (x1 * x2 - x1 * x3 + x3 * x3 - x2 * x3);
return a*x*x+b*x+c;
}
inline double interp2( double fleft, double fcenter, double fright, double x )
{
double a,b,c;
a = 0.5*(fleft+fright)-fcenter;
b = 0.5*(fright-fleft);
c = fcenter;
return a*x*x+b*x+c;
}
inline double interp2left( double fleft, double fcenter, double fright )
{
double a,b,c;
a = (6.0*fright-10.0*fcenter+4.0*fleft)/15.0;
b = (-4.0*fleft+9.0*fright-5.0*fcenter)/15.0;
c = fcenter;
return a-b+c;
}
inline double interp2right( double fleft, double fcenter, double fright )
{
double a,b,c;
a = (6.0*fleft-10.0*fcenter+4.0*fright)/15.0;
b = (4.0*fright-9.0*fleft+5.0*fcenter)/15.0;
c = fcenter;
return a+b+c;
}
template< class S, class O, typename T >
void solver<S,O,T>::interp_cubic( MeshvarBnd<T>& coarse, MeshvarBnd<T>& fine, int i, int j, int k, int itop, int jtop, int ktop )
{
MeshvarBnd<T> &u = fine;
MeshvarBnd<T> &utop = coarse;
/*
u(i+0,j+0,k+0) = ( -125.*utop(itop-2,jtop-2,ktop-2) +875.*utop(itop-2,jtop-2,ktop-1) +2625.*utop(itop-2,jtop-2,ktop)
-175.*utop(itop-2,jtop-2,ktop+1) +875.*utop(itop-2,jtop-1,ktop-2) -6125.*utop(itop-2,jtop-1,ktop-1)
-18375.*utop(itop-2,jtop-1,ktop) +1225.*utop(itop-2,jtop-1,ktop+1) +2625.*utop(itop-2,jtop,ktop-2)
-18375.*utop(itop-2,jtop,ktop-1) -55125.*utop(itop-2,jtop,ktop) +3675.*utop(itop-2,jtop,ktop+1)
-175.*utop(itop-2,jtop+1,ktop-2) +1225.*utop(itop-2,jtop+1,ktop-1) +3675.*utop(itop-2,jtop+1,ktop)
-245.*utop(itop-2,jtop+1,ktop+1) +875.*utop(itop-1,jtop-2,ktop-2) -6125.*utop(itop-1,jtop-2,ktop-1)
-18375.*utop(itop-1,jtop-2,ktop) +1225.*utop(itop-1,jtop-2,ktop+1) -6125.*utop(itop-1,jtop-1,ktop-2)
+42875.*utop(itop-1,jtop-1,ktop-1) +128625.*utop(itop-1,jtop-1,ktop) -8575.*utop(itop-1,jtop-1,ktop+1)
-18375.*utop(itop-1,jtop,ktop-2) +128625.*utop(itop-1,jtop,ktop-1) +385875.*utop(itop-1,jtop,ktop)
-25725.*utop(itop-1,jtop,ktop+1) +1225.*utop(itop-1,jtop+1,ktop-2) -8575.*utop(itop-1,jtop+1,ktop-1)
-25725.*utop(itop-1,jtop+1,ktop) +1715.*utop(itop-1,jtop+1,ktop+1) +2625.*utop(itop,jtop-2,ktop-2)
-18375.*utop(itop,jtop-2,ktop-1) -55125.*utop(itop,jtop-2,ktop) +3675.*utop(itop,jtop-2,ktop+1)
-18375.*utop(itop,jtop-1,ktop-2) +128625.*utop(itop,jtop-1,ktop-1) +385875.*utop(itop,jtop-1,ktop)
-25725.*utop(itop,jtop-1,ktop+1) -55125.*utop(itop,jtop,ktop-2) +385875.*utop(itop,jtop,ktop-1)
+1157625.*utop(itop,jtop,ktop) -77175.*utop(itop,jtop,ktop+1) +3675.*utop(itop,jtop+1,ktop-2)
-25725.*utop(itop,jtop+1,ktop-1) -77175.*utop(itop,jtop+1,ktop) +5145.*utop(itop,jtop+1,ktop+1)
-175.*utop(itop+1,jtop-2,ktop-2) +1225.*utop(itop+1,jtop-2,ktop-1) +3675.*utop(itop+1,jtop-2,ktop)
-245.*utop(itop+1,jtop-2,ktop+1) +1225.*utop(itop+1,jtop-1,ktop-2) -8575.*utop(itop+1,jtop-1,ktop-1)
-25725.*utop(itop+1,jtop-1,ktop) +1715.*utop(itop+1,jtop-1,ktop+1) +3675.*utop(itop+1,jtop,ktop-2)
-25725.*utop(itop+1,jtop,ktop-1) -77175.*utop(itop+1,jtop,ktop) +5145.*utop(itop+1,jtop,ktop+1)
-245.*utop(itop+1,jtop+1,ktop-2) +1715.*utop(itop+1,jtop+1,ktop-1) +5145.*utop(itop+1,jtop+1,ktop)
-343.*utop(itop+1,jtop+1,ktop+1) )/2097152.;
u(i+0,j+0,k+1) = ( -175.*utop(itop-2,jtop-2,ktop-1) +2625.*utop(itop-2,jtop-2,ktop) +875.*utop(itop-2,jtop-2,ktop+1)
-125.*utop(itop-2,jtop-2,ktop+2) +1225.*utop(itop-2,jtop-1,ktop-1) -18375.*utop(itop-2,jtop-1,ktop)
-6125.*utop(itop-2,jtop-1,ktop+1) +875.*utop(itop-2,jtop-1,ktop+2) +3675.*utop(itop-2,jtop,ktop-1)
-55125.*utop(itop-2,jtop,ktop) -18375.*utop(itop-2,jtop,ktop+1) +2625.*utop(itop-2,jtop,ktop+2)
-245.*utop(itop-2,jtop+1,ktop-1) +3675.*utop(itop-2,jtop+1,ktop) +1225.*utop(itop-2,jtop+1,ktop+1)
-175.*utop(itop-2,jtop+1,ktop+2) +1225.*utop(itop-1,jtop-2,ktop-1) -18375.*utop(itop-1,jtop-2,ktop)
-6125.*utop(itop-1,jtop-2,ktop+1) +875.*utop(itop-1,jtop-2,ktop+2) -8575.*utop(itop-1,jtop-1,ktop-1)
+128625.*utop(itop-1,jtop-1,ktop) +42875.*utop(itop-1,jtop-1,ktop+1) -6125.*utop(itop-1,jtop-1,ktop+2)
-25725.*utop(itop-1,jtop,ktop-1) +385875.*utop(itop-1,jtop,ktop) +128625.*utop(itop-1,jtop,ktop+1)
-18375.*utop(itop-1,jtop,ktop+2) +1715.*utop(itop-1,jtop+1,ktop-1) -25725.*utop(itop-1,jtop+1,ktop)
-8575.*utop(itop-1,jtop+1,ktop+1) +1225.*utop(itop-1,jtop+1,ktop+2) +3675.*utop(itop,jtop-2,ktop-1)
-55125.*utop(itop,jtop-2,ktop) -18375.*utop(itop,jtop-2,ktop+1) +2625.*utop(itop,jtop-2,ktop+2)
-25725.*utop(itop,jtop-1,ktop-1) +385875.*utop(itop,jtop-1,ktop) +128625.*utop(itop,jtop-1,ktop+1)
-18375.*utop(itop,jtop-1,ktop+2) -77175.*utop(itop,jtop,ktop-1) +1157625.*utop(itop,jtop,ktop)
+385875.*utop(itop,jtop,ktop+1) -55125.*utop(itop,jtop,ktop+2) +5145.*utop(itop,jtop+1,ktop-1)
-77175.*utop(itop,jtop+1,ktop) -25725.*utop(itop,jtop+1,ktop+1) +3675.*utop(itop,jtop+1,ktop+2)
-245.*utop(itop+1,jtop-2,ktop-1) +3675.*utop(itop+1,jtop-2,ktop) +1225.*utop(itop+1,jtop-2,ktop+1)
-175.*utop(itop+1,jtop-2,ktop+2) +1715.*utop(itop+1,jtop-1,ktop-1) -25725.*utop(itop+1,jtop-1,ktop)
-8575.*utop(itop+1,jtop-1,ktop+1) +1225.*utop(itop+1,jtop-1,ktop+2) +5145.*utop(itop+1,jtop,ktop-1)
-77175.*utop(itop+1,jtop,ktop) -25725.*utop(itop+1,jtop,ktop+1) +3675.*utop(itop+1,jtop,ktop+2)
-343.*utop(itop+1,jtop+1,ktop-1) +5145.*utop(itop+1,jtop+1,ktop) +1715.*utop(itop+1,jtop+1,ktop+1)
-245.*utop(itop+1,jtop+1,ktop+2) )/2097152.;
u(i+0,j+1,k+0) = ( -175.*utop(itop-2,jtop-1,ktop-2) +1225.*utop(itop-2,jtop-1,ktop-1) +3675.*utop(itop-2,jtop-1,ktop)
-245.*utop(itop-2,jtop-1,ktop+1) +2625.*utop(itop-2,jtop,ktop-2) -18375.*utop(itop-2,jtop,ktop-1)
-55125.*utop(itop-2,jtop,ktop) +3675.*utop(itop-2,jtop,ktop+1) +875.*utop(itop-2,jtop+1,ktop-2)
-6125.*utop(itop-2,jtop+1,ktop-1) -18375.*utop(itop-2,jtop+1,ktop) +1225.*utop(itop-2,jtop+1,ktop+1)
-125.*utop(itop-2,jtop+2,ktop-2) +875.*utop(itop-2,jtop+2,ktop-1) +2625.*utop(itop-2,jtop+2,ktop)
-175.*utop(itop-2,jtop+2,ktop+1) +1225.*utop(itop-1,jtop-1,ktop-2) -8575.*utop(itop-1,jtop-1,ktop-1)
-25725.*utop(itop-1,jtop-1,ktop) +1715.*utop(itop-1,jtop-1,ktop+1) -18375.*utop(itop-1,jtop,ktop-2)
+128625.*utop(itop-1,jtop,ktop-1) +385875.*utop(itop-1,jtop,ktop) -25725.*utop(itop-1,jtop,ktop+1)
-6125.*utop(itop-1,jtop+1,ktop-2) +42875.*utop(itop-1,jtop+1,ktop-1) +128625.*utop(itop-1,jtop+1,ktop)
-8575.*utop(itop-1,jtop+1,ktop+1) +875.*utop(itop-1,jtop+2,ktop-2) -6125.*utop(itop-1,jtop+2,ktop-1)
-18375.*utop(itop-1,jtop+2,ktop) +1225.*utop(itop-1,jtop+2,ktop+1) +3675.*utop(itop,jtop-1,ktop-2)
-25725.*utop(itop,jtop-1,ktop-1) -77175.*utop(itop,jtop-1,ktop) +5145.*utop(itop,jtop-1,ktop+1)
-55125.*utop(itop,jtop,ktop-2) +385875.*utop(itop,jtop,ktop-1) +1157625.*utop(itop,jtop,ktop)
-77175.*utop(itop,jtop,ktop+1) -18375.*utop(itop,jtop+1,ktop-2) +128625.*utop(itop,jtop+1,ktop-1)
+385875.*utop(itop,jtop+1,ktop) -25725.*utop(itop,jtop+1,ktop+1) +2625.*utop(itop,jtop+2,ktop-2)
-18375.*utop(itop,jtop+2,ktop-1) -55125.*utop(itop,jtop+2,ktop) +3675.*utop(itop,jtop+2,ktop+1)
-245.*utop(itop+1,jtop-1,ktop-2) +1715.*utop(itop+1,jtop-1,ktop-1) +5145.*utop(itop+1,jtop-1,ktop)
-343.*utop(itop+1,jtop-1,ktop+1) +3675.*utop(itop+1,jtop,ktop-2) -25725.*utop(itop+1,jtop,ktop-1)
-77175.*utop(itop+1,jtop,ktop) +5145.*utop(itop+1,jtop,ktop+1) +1225.*utop(itop+1,jtop+1,ktop-2)
-8575.*utop(itop+1,jtop+1,ktop-1) -25725.*utop(itop+1,jtop+1,ktop) +1715.*utop(itop+1,jtop+1,ktop+1)
-175.*utop(itop+1,jtop+2,ktop-2) +1225.*utop(itop+1,jtop+2,ktop-1) +3675.*utop(itop+1,jtop+2,ktop)
-245.*utop(itop+1,jtop+2,ktop+1) )/2097152.;
u(i+0,j+1,k+1) = ( -245.*utop(itop-2,jtop-1,ktop-1) +3675.*utop(itop-2,jtop-1,ktop) +1225.*utop(itop-2,jtop-1,ktop+1)
-175.*utop(itop-2,jtop-1,ktop+2) +3675.*utop(itop-2,jtop,ktop-1) -55125.*utop(itop-2,jtop,ktop)
-18375.*utop(itop-2,jtop,ktop+1) +2625.*utop(itop-2,jtop,ktop+2) +1225.*utop(itop-2,jtop+1,ktop-1)
-18375.*utop(itop-2,jtop+1,ktop) -6125.*utop(itop-2,jtop+1,ktop+1) +875.*utop(itop-2,jtop+1,ktop+2)
-175.*utop(itop-2,jtop+2,ktop-1) +2625.*utop(itop-2,jtop+2,ktop) +875.*utop(itop-2,jtop+2,ktop+1)
-125.*utop(itop-2,jtop+2,ktop+2) +1715.*utop(itop-1,jtop-1,ktop-1) -25725.*utop(itop-1,jtop-1,ktop)
-8575.*utop(itop-1,jtop-1,ktop+1) +1225.*utop(itop-1,jtop-1,ktop+2) -25725.*utop(itop-1,jtop,ktop-1)
+385875.*utop(itop-1,jtop,ktop) +128625.*utop(itop-1,jtop,ktop+1) -18375.*utop(itop-1,jtop,ktop+2)
-8575.*utop(itop-1,jtop+1,ktop-1) +128625.*utop(itop-1,jtop+1,ktop) +42875.*utop(itop-1,jtop+1,ktop+1)
-6125.*utop(itop-1,jtop+1,ktop+2) +1225.*utop(itop-1,jtop+2,ktop-1) -18375.*utop(itop-1,jtop+2,ktop)
-6125.*utop(itop-1,jtop+2,ktop+1) +875.*utop(itop-1,jtop+2,ktop+2) +5145.*utop(itop,jtop-1,ktop-1)
-77175.*utop(itop,jtop-1,ktop) -25725.*utop(itop,jtop-1,ktop+1) +3675.*utop(itop,jtop-1,ktop+2)
-77175.*utop(itop,jtop,ktop-1) +1157625.*utop(itop,jtop,ktop) +385875.*utop(itop,jtop,ktop+1)
-55125.*utop(itop,jtop,ktop+2) -25725.*utop(itop,jtop+1,ktop-1) +385875.*utop(itop,jtop+1,ktop)
+128625.*utop(itop,jtop+1,ktop+1) -18375.*utop(itop,jtop+1,ktop+2) +3675.*utop(itop,jtop+2,ktop-1)
-55125.*utop(itop,jtop+2,ktop) -18375.*utop(itop,jtop+2,ktop+1) +2625.*utop(itop,jtop+2,ktop+2)
-343.*utop(itop+1,jtop-1,ktop-1) +5145.*utop(itop+1,jtop-1,ktop) +1715.*utop(itop+1,jtop-1,ktop+1)
-245.*utop(itop+1,jtop-1,ktop+2) +5145.*utop(itop+1,jtop,ktop-1) -77175.*utop(itop+1,jtop,ktop)
-25725.*utop(itop+1,jtop,ktop+1) +3675.*utop(itop+1,jtop,ktop+2) +1715.*utop(itop+1,jtop+1,ktop-1)
-25725.*utop(itop+1,jtop+1,ktop) -8575.*utop(itop+1,jtop+1,ktop+1) +1225.*utop(itop+1,jtop+1,ktop+2)
-245.*utop(itop+1,jtop+2,ktop-1) +3675.*utop(itop+1,jtop+2,ktop) +1225.*utop(itop+1,jtop+2,ktop+1)
-175.*utop(itop+1,jtop+2,ktop+2) )/2097152.;
u(i+1,j+0,k+0) = ( -175.*utop(itop-1,jtop-2,ktop-2) +1225.*utop(itop-1,jtop-2,ktop-1) +3675.*utop(itop-1,jtop-2,ktop)
-245.*utop(itop-1,jtop-2,ktop+1) +1225.*utop(itop-1,jtop-1,ktop-2) -8575.*utop(itop-1,jtop-1,ktop-1)
-25725.*utop(itop-1,jtop-1,ktop) +1715.*utop(itop-1,jtop-1,ktop+1) +3675.*utop(itop-1,jtop,ktop-2)
-25725.*utop(itop-1,jtop,ktop-1) -77175.*utop(itop-1,jtop,ktop) +5145.*utop(itop-1,jtop,ktop+1)
-245.*utop(itop-1,jtop+1,ktop-2) +1715.*utop(itop-1,jtop+1,ktop-1) +5145.*utop(itop-1,jtop+1,ktop)
-343.*utop(itop-1,jtop+1,ktop+1) +2625.*utop(itop,jtop-2,ktop-2) -18375.*utop(itop,jtop-2,ktop-1)
-55125.*utop(itop,jtop-2,ktop) +3675.*utop(itop,jtop-2,ktop+1) -18375.*utop(itop,jtop-1,ktop-2)
+128625.*utop(itop,jtop-1,ktop-1) +385875.*utop(itop,jtop-1,ktop) -25725.*utop(itop,jtop-1,ktop+1)
-55125.*utop(itop,jtop,ktop-2) +385875.*utop(itop,jtop,ktop-1) +1157625.*utop(itop,jtop,ktop)
-77175.*utop(itop,jtop,ktop+1) +3675.*utop(itop,jtop+1,ktop-2) -25725.*utop(itop,jtop+1,ktop-1)
-77175.*utop(itop,jtop+1,ktop) +5145.*utop(itop,jtop+1,ktop+1) +875.*utop(itop+1,jtop-2,ktop-2)
-6125.*utop(itop+1,jtop-2,ktop-1) -18375.*utop(itop+1,jtop-2,ktop) +1225.*utop(itop+1,jtop-2,ktop+1)
-6125.*utop(itop+1,jtop-1,ktop-2) +42875.*utop(itop+1,jtop-1,ktop-1) +128625.*utop(itop+1,jtop-1,ktop)
-8575.*utop(itop+1,jtop-1,ktop+1) -18375.*utop(itop+1,jtop,ktop-2) +128625.*utop(itop+1,jtop,ktop-1)
+385875.*utop(itop+1,jtop,ktop) -25725.*utop(itop+1,jtop,ktop+1) +1225.*utop(itop+1,jtop+1,ktop-2)
-8575.*utop(itop+1,jtop+1,ktop-1) -25725.*utop(itop+1,jtop+1,ktop) +1715.*utop(itop+1,jtop+1,ktop+1)
-125.*utop(itop+2,jtop-2,ktop-2) +875.*utop(itop+2,jtop-2,ktop-1) +2625.*utop(itop+2,jtop-2,ktop)
-175.*utop(itop+2,jtop-2,ktop+1) +875.*utop(itop+2,jtop-1,ktop-2) -6125.*utop(itop+2,jtop-1,ktop-1)
-18375.*utop(itop+2,jtop-1,ktop) +1225.*utop(itop+2,jtop-1,ktop+1) +2625.*utop(itop+2,jtop,ktop-2)
-18375.*utop(itop+2,jtop,ktop-1) -55125.*utop(itop+2,jtop,ktop) +3675.*utop(itop+2,jtop,ktop+1)
-175.*utop(itop+2,jtop+1,ktop-2) +1225.*utop(itop+2,jtop+1,ktop-1) +3675.*utop(itop+2,jtop+1,ktop)
-245.*utop(itop+2,jtop+1,ktop+1) )/2097152.;
u(i+1,j+0,k+1) = ( -245.*utop(itop-1,jtop-2,ktop-1) +3675.*utop(itop-1,jtop-2,ktop) +1225.*utop(itop-1,jtop-2,ktop+1) -175.*utop(itop-1,jtop-2,ktop+2) +1715.*utop(itop-1,jtop-1,ktop-1) -25725.*utop(itop-1,jtop-1,ktop) -8575.*utop(itop-1,jtop-1,ktop+1) +1225.*utop(itop-1,jtop-1,ktop+2) +5145.*utop(itop-1,jtop,ktop-1) -77175.*utop(itop-1,jtop,ktop) -25725.*utop(itop-1,jtop,ktop+1) +3675.*utop(itop-1,jtop,ktop+2) -343.*utop(itop-1,jtop+1,ktop-1) +5145.*utop(itop-1,jtop+1,ktop) +1715.*utop(itop-1,jtop+1,ktop+1) -245.*utop(itop-1,jtop+1,ktop+2) +3675.*utop(itop,jtop-2,ktop-1) -55125.*utop(itop,jtop-2,ktop) -18375.*utop(itop,jtop-2,ktop+1) +2625.*utop(itop,jtop-2,ktop+2) -25725.*utop(itop,jtop-1,ktop-1) +385875.*utop(itop,jtop-1,ktop) +128625.*utop(itop,jtop-1,ktop+1) -18375.*utop(itop,jtop-1,ktop+2) -77175.*utop(itop,jtop,ktop-1) +1157625.*utop(itop,jtop,ktop) +385875.*utop(itop,jtop,ktop+1) -55125.*utop(itop,jtop,ktop+2) +5145.*utop(itop,jtop+1,ktop-1) -77175.*utop(itop,jtop+1,ktop) -25725.*utop(itop,jtop+1,ktop+1) +3675.*utop(itop,jtop+1,ktop+2) +1225.*utop(itop+1,jtop-2,ktop-1) -18375.*utop(itop+1,jtop-2,ktop) -6125.*utop(itop+1,jtop-2,ktop+1) +875.*utop(itop+1,jtop-2,ktop+2) -8575.*utop(itop+1,jtop-1,ktop-1) +128625.*utop(itop+1,jtop-1,ktop) +42875.*utop(itop+1,jtop-1,ktop+1) -6125.*utop(itop+1,jtop-1,ktop+2) -25725.*utop(itop+1,jtop,ktop-1) +385875.*utop(itop+1,jtop,ktop) +128625.*utop(itop+1,jtop,ktop+1) -18375.*utop(itop+1,jtop,ktop+2) +1715.*utop(itop+1,jtop+1,ktop-1) -25725.*utop(itop+1,jtop+1,ktop) -8575.*utop(itop+1,jtop+1,ktop+1) +1225.*utop(itop+1,jtop+1,ktop+2) -175.*utop(itop+2,jtop-2,ktop-1) +2625.*utop(itop+2,jtop-2,ktop) +875.*utop(itop+2,jtop-2,ktop+1) -125.*utop(itop+2,jtop-2,ktop+2) +1225.*utop(itop+2,jtop-1,ktop-1) -18375.*utop(itop+2,jtop-1,ktop) -6125.*utop(itop+2,jtop-1,ktop+1) +875.*utop(itop+2,jtop-1,ktop+2) +3675.*utop(itop+2,jtop,ktop-1) -55125.*utop(itop+2,jtop,ktop) -18375.*utop(itop+2,jtop,ktop+1) +2625.*utop(itop+2,jtop,ktop+2) -245.*utop(itop+2,jtop+1,ktop-1) +3675.*utop(itop+2,jtop+1,ktop) +1225.*utop(itop+2,jtop+1,ktop+1) -175.*utop(itop+2,jtop+1,ktop+2) )/2097152.;
u(i+1,j+1,k+0) = ( -245.*utop(itop-1,jtop-1,ktop-2) +1715.*utop(itop-1,jtop-1,ktop-1) +5145.*utop(itop-1,jtop-1,ktop) -343.*utop(itop-1,jtop-1,ktop+1) +3675.*utop(itop-1,jtop,ktop-2) -25725.*utop(itop-1,jtop,ktop-1) -77175.*utop(itop-1,jtop,ktop) +5145.*utop(itop-1,jtop,ktop+1) +1225.*utop(itop-1,jtop+1,ktop-2) -8575.*utop(itop-1,jtop+1,ktop-1) -25725.*utop(itop-1,jtop+1,ktop) +1715.*utop(itop-1,jtop+1,ktop+1) -175.*utop(itop-1,jtop+2,ktop-2) +1225.*utop(itop-1,jtop+2,ktop-1) +3675.*utop(itop-1,jtop+2,ktop) -245.*utop(itop-1,jtop+2,ktop+1) +3675.*utop(itop,jtop-1,ktop-2) -25725.*utop(itop,jtop-1,ktop-1) -77175.*utop(itop,jtop-1,ktop) +5145.*utop(itop,jtop-1,ktop+1) -55125.*utop(itop,jtop,ktop-2) +385875.*utop(itop,jtop,ktop-1) +1157625.*utop(itop,jtop,ktop) -77175.*utop(itop,jtop,ktop+1) -18375.*utop(itop,jtop+1,ktop-2) +128625.*utop(itop,jtop+1,ktop-1) +385875.*utop(itop,jtop+1,ktop) -25725.*utop(itop,jtop+1,ktop+1) +2625.*utop(itop,jtop+2,ktop-2) -18375.*utop(itop,jtop+2,ktop-1) -55125.*utop(itop,jtop+2,ktop) +3675.*utop(itop,jtop+2,ktop+1) +1225.*utop(itop+1,jtop-1,ktop-2) -8575.*utop(itop+1,jtop-1,ktop-1) -25725.*utop(itop+1,jtop-1,ktop) +1715.*utop(itop+1,jtop-1,ktop+1) -18375.*utop(itop+1,jtop,ktop-2) +128625.*utop(itop+1,jtop,ktop-1) +385875.*utop(itop+1,jtop,ktop) -25725.*utop(itop+1,jtop,ktop+1) -6125.*utop(itop+1,jtop+1,ktop-2) +42875.*utop(itop+1,jtop+1,ktop-1) +128625.*utop(itop+1,jtop+1,ktop) -8575.*utop(itop+1,jtop+1,ktop+1) +875.*utop(itop+1,jtop+2,ktop-2) -6125.*utop(itop+1,jtop+2,ktop-1) -18375.*utop(itop+1,jtop+2,ktop) +1225.*utop(itop+1,jtop+2,ktop+1) -175.*utop(itop+2,jtop-1,ktop-2) +1225.*utop(itop+2,jtop-1,ktop-1) +3675.*utop(itop+2,jtop-1,ktop) -245.*utop(itop+2,jtop-1,ktop+1) +2625.*utop(itop+2,jtop,ktop-2) -18375.*utop(itop+2,jtop,ktop-1) -55125.*utop(itop+2,jtop,ktop) +3675.*utop(itop+2,jtop,ktop+1) +875.*utop(itop+2,jtop+1,ktop-2) -6125.*utop(itop+2,jtop+1,ktop-1) -18375.*utop(itop+2,jtop+1,ktop) +1225.*utop(itop+2,jtop+1,ktop+1) -125.*utop(itop+2,jtop+2,ktop-2) +875.*utop(itop+2,jtop+2,ktop-1) +2625.*utop(itop+2,jtop+2,ktop) -175.*utop(itop+2,jtop+2,ktop+1) )/2097152.;
u(i+1,j+1,k+1) = ( -343.*utop(itop-1,jtop-1,ktop-1) +5145.*utop(itop-1,jtop-1,ktop) +1715.*utop(itop-1,jtop-1,ktop+1) -245.*utop(itop-1,jtop-1,ktop+2) +5145.*utop(itop-1,jtop,ktop-1) -77175.*utop(itop-1,jtop,ktop) -25725.*utop(itop-1,jtop,ktop+1) +3675.*utop(itop-1,jtop,ktop+2) +1715.*utop(itop-1,jtop+1,ktop-1) -25725.*utop(itop-1,jtop+1,ktop) -8575.*utop(itop-1,jtop+1,ktop+1) +1225.*utop(itop-1,jtop+1,ktop+2) -245.*utop(itop-1,jtop+2,ktop-1) +3675.*utop(itop-1,jtop+2,ktop) +1225.*utop(itop-1,jtop+2,ktop+1) -175.*utop(itop-1,jtop+2,ktop+2) +5145.*utop(itop,jtop-1,ktop-1) -77175.*utop(itop,jtop-1,ktop) -25725.*utop(itop,jtop-1,ktop+1) +3675.*utop(itop,jtop-1,ktop+2) -77175.*utop(itop,jtop,ktop-1) +1157625.*utop(itop,jtop,ktop) +385875.*utop(itop,jtop,ktop+1) -55125.*utop(itop,jtop,ktop+2) -25725.*utop(itop,jtop+1,ktop-1) +385875.*utop(itop,jtop+1,ktop) +128625.*utop(itop,jtop+1,ktop+1) -18375.*utop(itop,jtop+1,ktop+2) +3675.*utop(itop,jtop+2,ktop-1) -55125.*utop(itop,jtop+2,ktop) -18375.*utop(itop,jtop+2,ktop+1) +2625.*utop(itop,jtop+2,ktop+2) +1715.*utop(itop+1,jtop-1,ktop-1) -25725.*utop(itop+1,jtop-1,ktop) -8575.*utop(itop+1,jtop-1,ktop+1) +1225.*utop(itop+1,jtop-1,ktop+2) -25725.*utop(itop+1,jtop,ktop-1) +385875.*utop(itop+1,jtop,ktop) +128625.*utop(itop+1,jtop,ktop+1) -18375.*utop(itop+1,jtop,ktop+2) -8575.*utop(itop+1,jtop+1,ktop-1) +128625.*utop(itop+1,jtop+1,ktop) +42875.*utop(itop+1,jtop+1,ktop+1) -6125.*utop(itop+1,jtop+1,ktop+2) +1225.*utop(itop+1,jtop+2,ktop-1) -18375.*utop(itop+1,jtop+2,ktop) -6125.*utop(itop+1,jtop+2,ktop+1) +875.*utop(itop+1,jtop+2,ktop+2) -245.*utop(itop+2,jtop-1,ktop-1) +3675.*utop(itop+2,jtop-1,ktop) +1225.*utop(itop+2,jtop-1,ktop+1) -175.*utop(itop+2,jtop-1,ktop+2) +3675.*utop(itop+2,jtop,ktop-1) -55125.*utop(itop+2,jtop,ktop) -18375.*utop(itop+2,jtop,ktop+1) +2625.*utop(itop+2,jtop,ktop+2) +1225.*utop(itop+2,jtop+1,ktop-1) -18375.*utop(itop+2,jtop+1,ktop) -6125.*utop(itop+2,jtop+1,ktop+1) +875.*utop(itop+2,jtop+1,ktop+2) -175.*utop(itop+2,jtop+2,ktop-1) +2625.*utop(itop+2,jtop+2,ktop) +875.*utop(itop+2,jtop+2,ktop+1) -125.*utop(itop+2,jtop+2,ktop+2) )/2097152.;
*/
u(i+0,j+0,k+0) = ( -1.060835e-05*utop(itop-2,jtop-2,ktop-2) +9.901123e-05*utop(itop-2,jtop-2,ktop-1) +4.455505e-04*utop(itop-2,jtop-2,ktop) -5.940674e-05*utop(itop-2,jtop-2,ktop+1) +8.250936e-06*utop(itop-2,jtop-2,ktop+2) +9.901123e-05*utop(itop-2,jtop-1,ktop-2) -9.241048e-04*utop(itop-2,jtop-1,ktop-1) -4.158472e-03*utop(itop-2,jtop-1,ktop) +5.544629e-04*utop(itop-2,jtop-1,ktop+1) -7.700874e-05*utop(itop-2,jtop-1,ktop+2) +4.455505e-04*utop(itop-2,jtop,ktop-2) -4.158472e-03*utop(itop-2,jtop,ktop-1) -1.871312e-02*utop(itop-2,jtop,ktop) +2.495083e-03*utop(itop-2,jtop,ktop+1) -3.465393e-04*utop(itop-2,jtop,ktop+2) -5.940674e-05*utop(itop-2,jtop+1,ktop-2) +5.544629e-04*utop(itop-2,jtop+1,ktop-1) +2.495083e-03*utop(itop-2,jtop+1,ktop) -3.326777e-04*utop(itop-2,jtop+1,ktop+1) +4.620524e-05*utop(itop-2,jtop+1,ktop+2) +8.250936e-06*utop(itop-2,jtop+2,ktop-2) -7.700874e-05*utop(itop-2,jtop+2,ktop-1) -3.465393e-04*utop(itop-2,jtop+2,ktop) +4.620524e-05*utop(itop-2,jtop+2,ktop+1) -6.417395e-06*utop(itop-2,jtop+2,ktop+2) +9.901123e-05*utop(itop-1,jtop-2,ktop-2) -9.241048e-04*utop(itop-1,jtop-2,ktop-1) -4.158472e-03*utop(itop-1,jtop-2,ktop) +5.544629e-04*utop(itop-1,jtop-2,ktop+1) -7.700874e-05*utop(itop-1,jtop-2,ktop+2) -9.241048e-04*utop(itop-1,jtop-1,ktop-2) +8.624978e-03*utop(itop-1,jtop-1,ktop-1) +3.881240e-02*utop(itop-1,jtop-1,ktop) -5.174987e-03*utop(itop-1,jtop-1,ktop+1) +7.187482e-04*utop(itop-1,jtop-1,ktop+2) -4.158472e-03*utop(itop-1,jtop,ktop-2) +3.881240e-02*utop(itop-1,jtop,ktop-1) +1.746558e-01*utop(itop-1,jtop,ktop) -2.328744e-02*utop(itop-1,jtop,ktop+1) +3.234367e-03*utop(itop-1,jtop,ktop+2) +5.544629e-04*utop(itop-1,jtop+1,ktop-2) -5.174987e-03*utop(itop-1,jtop+1,ktop-1) -2.328744e-02*utop(itop-1,jtop+1,ktop) +3.104992e-03*utop(itop-1,jtop+1,ktop+1) -4.312489e-04*utop(itop-1,jtop+1,ktop+2) -7.700874e-05*utop(itop-1,jtop+2,ktop-2) +7.187482e-04*utop(itop-1,jtop+2,ktop-1) +3.234367e-03*utop(itop-1,jtop+2,ktop) -4.312489e-04*utop(itop-1,jtop+2,ktop+1) +5.989568e-05*utop(itop-1,jtop+2,ktop+2) +4.455505e-04*utop(itop,jtop-2,ktop-2) -4.158472e-03*utop(itop,jtop-2,ktop-1) -1.871312e-02*utop(itop,jtop-2,ktop) +2.495083e-03*utop(itop,jtop-2,ktop+1) -3.465393e-04*utop(itop,jtop-2,ktop+2) -4.158472e-03*utop(itop,jtop-1,ktop-2) +3.881240e-02*utop(itop,jtop-1,ktop-1) +1.746558e-01*utop(itop,jtop-1,ktop) -2.328744e-02*utop(itop,jtop-1,ktop+1) +3.234367e-03*utop(itop,jtop-1,ktop+2) -1.871312e-02*utop(itop,jtop,ktop-2) +1.746558e-01*utop(itop,jtop,ktop-1) +7.859512e-01*utop(itop,jtop,ktop) -1.047935e-01*utop(itop,jtop,ktop+1) +1.455465e-02*utop(itop,jtop,ktop+2) +2.495083e-03*utop(itop,jtop+1,ktop-2) -2.328744e-02*utop(itop,jtop+1,ktop-1) -1.047935e-01*utop(itop,jtop+1,ktop) +1.397246e-02*utop(itop,jtop+1,ktop+1) -1.940620e-03*utop(itop,jtop+1,ktop+2) -3.465393e-04*utop(itop,jtop+2,ktop-2) +3.234367e-03*utop(itop,jtop+2,ktop-1) +1.455465e-02*utop(itop,jtop+2,ktop) -1.940620e-03*utop(itop,jtop+2,ktop+1) +2.695306e-04*utop(itop,jtop+2,ktop+2) -5.940674e-05*utop(itop+1,jtop-2,ktop-2) +5.544629e-04*utop(itop+1,jtop-2,ktop-1) +2.495083e-03*utop(itop+1,jtop-2,ktop) -3.326777e-04*utop(itop+1,jtop-2,ktop+1) +4.620524e-05*utop(itop+1,jtop-2,ktop+2) +5.544629e-04*utop(itop+1,jtop-1,ktop-2) -5.174987e-03*utop(itop+1,jtop-1,ktop-1) -2.328744e-02*utop(itop+1,jtop-1,ktop) +3.104992e-03*utop(itop+1,jtop-1,ktop+1) -4.312489e-04*utop(itop+1,jtop-1,ktop+2) +2.495083e-03*utop(itop+1,jtop,ktop-2) -2.328744e-02*utop(itop+1,jtop,ktop-1) -1.047935e-01*utop(itop+1,jtop,ktop) +1.397246e-02*utop(itop+1,jtop,ktop+1) -1.940620e-03*utop(itop+1,jtop,ktop+2) -3.326777e-04*utop(itop+1,jtop+1,ktop-2) +3.104992e-03*utop(itop+1,jtop+1,ktop-1) +1.397246e-02*utop(itop+1,jtop+1,ktop) -1.862995e-03*utop(itop+1,jtop+1,ktop+1) +2.587494e-04*utop(itop+1,jtop+1,ktop+2) +4.620524e-05*utop(itop+1,jtop+2,ktop-2) -4.312489e-04*utop(itop+1,jtop+2,ktop-1) -1.940620e-03*utop(itop+1,jtop+2,ktop) +2.587494e-04*utop(itop+1,jtop+2,ktop+1) -3.593741e-05*utop(itop+1,jtop+2,ktop+2) +8.250936e-06*utop(itop+2,jtop-2,ktop-2) -7.700874e-05*utop(itop+2,jtop-2,ktop-1) -3.465393e-04*utop(itop+2,jtop-2,ktop) +4.620524e-05*utop(itop+2,jtop-2,ktop+1) -6.417395e-06*utop(itop+2,jtop-2,ktop+2) -7.700874e-05*utop(itop+2,jtop-1,ktop-2) +7.187482e-04*utop(itop+2,jtop-1,ktop-1) +3.234367e-03*utop(itop+2,jtop-1,ktop) -4.312489e-04*utop(itop+2,jtop-1,ktop+1) +5.989568e-05*utop(itop+2,jtop-1,ktop+2) -3.465393e-04*utop(itop+2,jtop,ktop-2) +3.234367e-03*utop(itop+2,jtop,ktop-1) +1.455465e-02*utop(itop+2,jtop,ktop) -1.940620e-03*utop(itop+2,jtop,ktop+1) +2.695306e-04*utop(itop+2,jtop,ktop+2) +4.620524e-05*utop(itop+2,jtop+1,ktop-2) -4.312489e-04*utop(itop+2,jtop+1,ktop-1) -1.940620e-03*utop(itop+2,jtop+1,ktop) +2.587494e-04*utop(itop+2,jtop+1,ktop+1) -3.593741e-05*utop(itop+2,jtop+1,ktop+2) -6.417395e-06*utop(itop+2,jtop+2,ktop-2) +5.989568e-05*utop(itop+2,jtop+2,ktop-1) +2.695306e-04*utop(itop+2,jtop+2,ktop) -3.593741e-05*utop(itop+2,jtop+2,ktop+1) +4.991307e-06*utop(itop+2,jtop+2,ktop+2));
u(i+0,j+0,k+1) = ( +8.250936e-06*utop(itop-2,jtop-2,ktop-2) -5.940674e-05*utop(itop-2,jtop-2,ktop-1) +4.455505e-04*utop(itop-2,jtop-2,ktop) +9.901123e-05*utop(itop-2,jtop-2,ktop+1) -1.060835e-05*utop(itop-2,jtop-2,ktop+2) -7.700874e-05*utop(itop-2,jtop-1,ktop-2) +5.544629e-04*utop(itop-2,jtop-1,ktop-1) -4.158472e-03*utop(itop-2,jtop-1,ktop) -9.241048e-04*utop(itop-2,jtop-1,ktop+1) +9.901123e-05*utop(itop-2,jtop-1,ktop+2) -3.465393e-04*utop(itop-2,jtop,ktop-2) +2.495083e-03*utop(itop-2,jtop,ktop-1) -1.871312e-02*utop(itop-2,jtop,ktop) -4.158472e-03*utop(itop-2,jtop,ktop+1) +4.455505e-04*utop(itop-2,jtop,ktop+2) +4.620524e-05*utop(itop-2,jtop+1,ktop-2) -3.326777e-04*utop(itop-2,jtop+1,ktop-1) +2.495083e-03*utop(itop-2,jtop+1,ktop) +5.544629e-04*utop(itop-2,jtop+1,ktop+1) -5.940674e-05*utop(itop-2,jtop+1,ktop+2) -6.417395e-06*utop(itop-2,jtop+2,ktop-2) +4.620524e-05*utop(itop-2,jtop+2,ktop-1) -3.465393e-04*utop(itop-2,jtop+2,ktop) -7.700874e-05*utop(itop-2,jtop+2,ktop+1) +8.250936e-06*utop(itop-2,jtop+2,ktop+2) -7.700874e-05*utop(itop-1,jtop-2,ktop-2) +5.544629e-04*utop(itop-1,jtop-2,ktop-1) -4.158472e-03*utop(itop-1,jtop-2,ktop) -9.241048e-04*utop(itop-1,jtop-2,ktop+1) +9.901123e-05*utop(itop-1,jtop-2,ktop+2) +7.187482e-04*utop(itop-1,jtop-1,ktop-2) -5.174987e-03*utop(itop-1,jtop-1,ktop-1) +3.881240e-02*utop(itop-1,jtop-1,ktop) +8.624978e-03*utop(itop-1,jtop-1,ktop+1) -9.241048e-04*utop(itop-1,jtop-1,ktop+2) +3.234367e-03*utop(itop-1,jtop,ktop-2) -2.328744e-02*utop(itop-1,jtop,ktop-1) +1.746558e-01*utop(itop-1,jtop,ktop) +3.881240e-02*utop(itop-1,jtop,ktop+1) -4.158472e-03*utop(itop-1,jtop,ktop+2) -4.312489e-04*utop(itop-1,jtop+1,ktop-2) +3.104992e-03*utop(itop-1,jtop+1,ktop-1) -2.328744e-02*utop(itop-1,jtop+1,ktop) -5.174987e-03*utop(itop-1,jtop+1,ktop+1) +5.544629e-04*utop(itop-1,jtop+1,ktop+2) +5.989568e-05*utop(itop-1,jtop+2,ktop-2) -4.312489e-04*utop(itop-1,jtop+2,ktop-1) +3.234367e-03*utop(itop-1,jtop+2,ktop) +7.187482e-04*utop(itop-1,jtop+2,ktop+1) -7.700874e-05*utop(itop-1,jtop+2,ktop+2) -3.465393e-04*utop(itop,jtop-2,ktop-2) +2.495083e-03*utop(itop,jtop-2,ktop-1) -1.871312e-02*utop(itop,jtop-2,ktop) -4.158472e-03*utop(itop,jtop-2,ktop+1) +4.455505e-04*utop(itop,jtop-2,ktop+2) +3.234367e-03*utop(itop,jtop-1,ktop-2) -2.328744e-02*utop(itop,jtop-1,ktop-1) +1.746558e-01*utop(itop,jtop-1,ktop) +3.881240e-02*utop(itop,jtop-1,ktop+1) -4.158472e-03*utop(itop,jtop-1,ktop+2) +1.455465e-02*utop(itop,jtop,ktop-2) -1.047935e-01*utop(itop,jtop,ktop-1) +7.859512e-01*utop(itop,jtop,ktop) +1.746558e-01*utop(itop,jtop,ktop+1) -1.871312e-02*utop(itop,jtop,ktop+2) -1.940620e-03*utop(itop,jtop+1,ktop-2) +1.397246e-02*utop(itop,jtop+1,ktop-1) -1.047935e-01*utop(itop,jtop+1,ktop) -2.328744e-02*utop(itop,jtop+1,ktop+1) +2.495083e-03*utop(itop,jtop+1,ktop+2) +2.695306e-04*utop(itop,jtop+2,ktop-2) -1.940620e-03*utop(itop,jtop+2,ktop-1) +1.455465e-02*utop(itop,jtop+2,ktop) +3.234367e-03*utop(itop,jtop+2,ktop+1) -3.465393e-04*utop(itop,jtop+2,ktop+2) +4.620524e-05*utop(itop+1,jtop-2,ktop-2) -3.326777e-04*utop(itop+1,jtop-2,ktop-1) +2.495083e-03*utop(itop+1,jtop-2,ktop) +5.544629e-04*utop(itop+1,jtop-2,ktop+1) -5.940674e-05*utop(itop+1,jtop-2,ktop+2) -4.312489e-04*utop(itop+1,jtop-1,ktop-2) +3.104992e-03*utop(itop+1,jtop-1,ktop-1) -2.328744e-02*utop(itop+1,jtop-1,ktop) -5.174987e-03*utop(itop+1,jtop-1,ktop+1) +5.544629e-04*utop(itop+1,jtop-1,ktop+2) -1.940620e-03*utop(itop+1,jtop,ktop-2) +1.397246e-02*utop(itop+1,jtop,ktop-1) -1.047935e-01*utop(itop+1,jtop,ktop) -2.328744e-02*utop(itop+1,jtop,ktop+1) +2.495083e-03*utop(itop+1,jtop,ktop+2) +2.587494e-04*utop(itop+1,jtop+1,ktop-2) -1.862995e-03*utop(itop+1,jtop+1,ktop-1) +1.397246e-02*utop(itop+1,jtop+1,ktop) +3.104992e-03*utop(itop+1,jtop+1,ktop+1) -3.326777e-04*utop(itop+1,jtop+1,ktop+2) -3.593741e-05*utop(itop+1,jtop+2,ktop-2) +2.587494e-04*utop(itop+1,jtop+2,ktop-1) -1.940620e-03*utop(itop+1,jtop+2,ktop) -4.312489e-04*utop(itop+1,jtop+2,ktop+1) +4.620524e-05*utop(itop+1,jtop+2,ktop+2) -6.417395e-06*utop(itop+2,jtop-2,ktop-2) +4.620524e-05*utop(itop+2,jtop-2,ktop-1) -3.465393e-04*utop(itop+2,jtop-2,ktop) -7.700874e-05*utop(itop+2,jtop-2,ktop+1) +8.250936e-06*utop(itop+2,jtop-2,ktop+2) +5.989568e-05*utop(itop+2,jtop-1,ktop-2) -4.312489e-04*utop(itop+2,jtop-1,ktop-1) +3.234367e-03*utop(itop+2,jtop-1,ktop) +7.187482e-04*utop(itop+2,jtop-1,ktop+1) -7.700874e-05*utop(itop+2,jtop-1,ktop+2) +2.695306e-04*utop(itop+2,jtop,ktop-2) -1.940620e-03*utop(itop+2,jtop,ktop-1) +1.455465e-02*utop(itop+2,jtop,ktop) +3.234367e-03*utop(itop+2,jtop,ktop+1) -3.465393e-04*utop(itop+2,jtop,ktop+2) -3.593741e-05*utop(itop+2,jtop+1,ktop-2) +2.587494e-04*utop(itop+2,jtop+1,ktop-1) -1.940620e-03*utop(itop+2,jtop+1,ktop) -4.312489e-04*utop(itop+2,jtop+1,ktop+1) +4.620524e-05*utop(itop+2,jtop+1,ktop+2) +4.991307e-06*utop(itop+2,jtop+2,ktop-2) -3.593741e-05*utop(itop+2,jtop+2,ktop-1) +2.695306e-04*utop(itop+2,jtop+2,ktop) +5.989568e-05*utop(itop+2,jtop+2,ktop+1) -6.417395e-06*utop(itop+2,jtop+2,ktop+2));
u(i+0,j+1,k+0) = ( +8.250936e-06*utop(itop-2,jtop-2,ktop-2) -7.700874e-05*utop(itop-2,jtop-2,ktop-1) -3.465393e-04*utop(itop-2,jtop-2,ktop) +4.620524e-05*utop(itop-2,jtop-2,ktop+1) -6.417395e-06*utop(itop-2,jtop-2,ktop+2) -5.940674e-05*utop(itop-2,jtop-1,ktop-2) +5.544629e-04*utop(itop-2,jtop-1,ktop-1) +2.495083e-03*utop(itop-2,jtop-1,ktop) -3.326777e-04*utop(itop-2,jtop-1,ktop+1) +4.620524e-05*utop(itop-2,jtop-1,ktop+2) +4.455505e-04*utop(itop-2,jtop,ktop-2) -4.158472e-03*utop(itop-2,jtop,ktop-1) -1.871312e-02*utop(itop-2,jtop,ktop) +2.495083e-03*utop(itop-2,jtop,ktop+1) -3.465393e-04*utop(itop-2,jtop,ktop+2) +9.901123e-05*utop(itop-2,jtop+1,ktop-2) -9.241048e-04*utop(itop-2,jtop+1,ktop-1) -4.158472e-03*utop(itop-2,jtop+1,ktop) +5.544629e-04*utop(itop-2,jtop+1,ktop+1) -7.700874e-05*utop(itop-2,jtop+1,ktop+2) -1.060835e-05*utop(itop-2,jtop+2,ktop-2) +9.901123e-05*utop(itop-2,jtop+2,ktop-1) +4.455505e-04*utop(itop-2,jtop+2,ktop) -5.940674e-05*utop(itop-2,jtop+2,ktop+1) +8.250936e-06*utop(itop-2,jtop+2,ktop+2) -7.700874e-05*utop(itop-1,jtop-2,ktop-2) +7.187482e-04*utop(itop-1,jtop-2,ktop-1) +3.234367e-03*utop(itop-1,jtop-2,ktop) -4.312489e-04*utop(itop-1,jtop-2,ktop+1) +5.989568e-05*utop(itop-1,jtop-2,ktop+2) +5.544629e-04*utop(itop-1,jtop-1,ktop-2) -5.174987e-03*utop(itop-1,jtop-1,ktop-1) -2.328744e-02*utop(itop-1,jtop-1,ktop) +3.104992e-03*utop(itop-1,jtop-1,ktop+1) -4.312489e-04*utop(itop-1,jtop-1,ktop+2) -4.158472e-03*utop(itop-1,jtop,ktop-2) +3.881240e-02*utop(itop-1,jtop,ktop-1) +1.746558e-01*utop(itop-1,jtop,ktop) -2.328744e-02*utop(itop-1,jtop,ktop+1) +3.234367e-03*utop(itop-1,jtop,ktop+2) -9.241048e-04*utop(itop-1,jtop+1,ktop-2) +8.624978e-03*utop(itop-1,jtop+1,ktop-1) +3.881240e-02*utop(itop-1,jtop+1,ktop) -5.174987e-03*utop(itop-1,jtop+1,ktop+1) +7.187482e-04*utop(itop-1,jtop+1,ktop+2) +9.901123e-05*utop(itop-1,jtop+2,ktop-2) -9.241048e-04*utop(itop-1,jtop+2,ktop-1) -4.158472e-03*utop(itop-1,jtop+2,ktop) +5.544629e-04*utop(itop-1,jtop+2,ktop+1) -7.700874e-05*utop(itop-1,jtop+2,ktop+2) -3.465393e-04*utop(itop,jtop-2,ktop-2) +3.234367e-03*utop(itop,jtop-2,ktop-1) +1.455465e-02*utop(itop,jtop-2,ktop) -1.940620e-03*utop(itop,jtop-2,ktop+1) +2.695306e-04*utop(itop,jtop-2,ktop+2) +2.495083e-03*utop(itop,jtop-1,ktop-2) -2.328744e-02*utop(itop,jtop-1,ktop-1) -1.047935e-01*utop(itop,jtop-1,ktop) +1.397246e-02*utop(itop,jtop-1,ktop+1) -1.940620e-03*utop(itop,jtop-1,ktop+2) -1.871312e-02*utop(itop,jtop,ktop-2) +1.746558e-01*utop(itop,jtop,ktop-1) +7.859512e-01*utop(itop,jtop,ktop) -1.047935e-01*utop(itop,jtop,ktop+1) +1.455465e-02*utop(itop,jtop,ktop+2) -4.158472e-03*utop(itop,jtop+1,ktop-2) +3.881240e-02*utop(itop,jtop+1,ktop-1) +1.746558e-01*utop(itop,jtop+1,ktop) -2.328744e-02*utop(itop,jtop+1,ktop+1) +3.234367e-03*utop(itop,jtop+1,ktop+2) +4.455505e-04*utop(itop,jtop+2,ktop-2) -4.158472e-03*utop(itop,jtop+2,ktop-1) -1.871312e-02*utop(itop,jtop+2,ktop) +2.495083e-03*utop(itop,jtop+2,ktop+1) -3.465393e-04*utop(itop,jtop+2,ktop+2) +4.620524e-05*utop(itop+1,jtop-2,ktop-2) -4.312489e-04*utop(itop+1,jtop-2,ktop-1) -1.940620e-03*utop(itop+1,jtop-2,ktop) +2.587494e-04*utop(itop+1,jtop-2,ktop+1) -3.593741e-05*utop(itop+1,jtop-2,ktop+2) -3.326777e-04*utop(itop+1,jtop-1,ktop-2) +3.104992e-03*utop(itop+1,jtop-1,ktop-1) +1.397246e-02*utop(itop+1,jtop-1,ktop) -1.862995e-03*utop(itop+1,jtop-1,ktop+1) +2.587494e-04*utop(itop+1,jtop-1,ktop+2) +2.495083e-03*utop(itop+1,jtop,ktop-2) -2.328744e-02*utop(itop+1,jtop,ktop-1) -1.047935e-01*utop(itop+1,jtop,ktop) +1.397246e-02*utop(itop+1,jtop,ktop+1) -1.940620e-03*utop(itop+1,jtop,ktop+2) +5.544629e-04*utop(itop+1,jtop+1,ktop-2) -5.174987e-03*utop(itop+1,jtop+1,ktop-1) -2.328744e-02*utop(itop+1,jtop+1,ktop) +3.104992e-03*utop(itop+1,jtop+1,ktop+1) -4.312489e-04*utop(itop+1,jtop+1,ktop+2) -5.940674e-05*utop(itop+1,jtop+2,ktop-2) +5.544629e-04*utop(itop+1,jtop+2,ktop-1) +2.495083e-03*utop(itop+1,jtop+2,ktop) -3.326777e-04*utop(itop+1,jtop+2,ktop+1) +4.620524e-05*utop(itop+1,jtop+2,ktop+2) -6.417395e-06*utop(itop+2,jtop-2,ktop-2) +5.989568e-05*utop(itop+2,jtop-2,ktop-1) +2.695306e-04*utop(itop+2,jtop-2,ktop) -3.593741e-05*utop(itop+2,jtop-2,ktop+1) +4.991307e-06*utop(itop+2,jtop-2,ktop+2) +4.620524e-05*utop(itop+2,jtop-1,ktop-2) -4.312489e-04*utop(itop+2,jtop-1,ktop-1) -1.940620e-03*utop(itop+2,jtop-1,ktop) +2.587494e-04*utop(itop+2,jtop-1,ktop+1) -3.593741e-05*utop(itop+2,jtop-1,ktop+2) -3.465393e-04*utop(itop+2,jtop,ktop-2) +3.234367e-03*utop(itop+2,jtop,ktop-1) +1.455465e-02*utop(itop+2,jtop,ktop) -1.940620e-03*utop(itop+2,jtop,ktop+1) +2.695306e-04*utop(itop+2,jtop,ktop+2) -7.700874e-05*utop(itop+2,jtop+1,ktop-2) +7.187482e-04*utop(itop+2,jtop+1,ktop-1) +3.234367e-03*utop(itop+2,jtop+1,ktop) -4.312489e-04*utop(itop+2,jtop+1,ktop+1) +5.989568e-05*utop(itop+2,jtop+1,ktop+2) +8.250936e-06*utop(itop+2,jtop+2,ktop-2) -7.700874e-05*utop(itop+2,jtop+2,ktop-1) -3.465393e-04*utop(itop+2,jtop+2,ktop) +4.620524e-05*utop(itop+2,jtop+2,ktop+1) -6.417395e-06*utop(itop+2,jtop+2,ktop+2));
u(i+0,j+1,k+1) = ( -6.417395e-06*utop(itop-2,jtop-2,ktop-2) +4.620524e-05*utop(itop-2,jtop-2,ktop-1) -3.465393e-04*utop(itop-2,jtop-2,ktop) -7.700874e-05*utop(itop-2,jtop-2,ktop+1) +8.250936e-06*utop(itop-2,jtop-2,ktop+2) +4.620524e-05*utop(itop-2,jtop-1,ktop-2) -3.326777e-04*utop(itop-2,jtop-1,ktop-1) +2.495083e-03*utop(itop-2,jtop-1,ktop) +5.544629e-04*utop(itop-2,jtop-1,ktop+1) -5.940674e-05*utop(itop-2,jtop-1,ktop+2) -3.465393e-04*utop(itop-2,jtop,ktop-2) +2.495083e-03*utop(itop-2,jtop,ktop-1) -1.871312e-02*utop(itop-2,jtop,ktop) -4.158472e-03*utop(itop-2,jtop,ktop+1) +4.455505e-04*utop(itop-2,jtop,ktop+2) -7.700874e-05*utop(itop-2,jtop+1,ktop-2) +5.544629e-04*utop(itop-2,jtop+1,ktop-1) -4.158472e-03*utop(itop-2,jtop+1,ktop) -9.241048e-04*utop(itop-2,jtop+1,ktop+1) +9.901123e-05*utop(itop-2,jtop+1,ktop+2) +8.250936e-06*utop(itop-2,jtop+2,ktop-2) -5.940674e-05*utop(itop-2,jtop+2,ktop-1) +4.455505e-04*utop(itop-2,jtop+2,ktop) +9.901123e-05*utop(itop-2,jtop+2,ktop+1) -1.060835e-05*utop(itop-2,jtop+2,ktop+2) +5.989568e-05*utop(itop-1,jtop-2,ktop-2) -4.312489e-04*utop(itop-1,jtop-2,ktop-1) +3.234367e-03*utop(itop-1,jtop-2,ktop) +7.187482e-04*utop(itop-1,jtop-2,ktop+1) -7.700874e-05*utop(itop-1,jtop-2,ktop+2) -4.312489e-04*utop(itop-1,jtop-1,ktop-2) +3.104992e-03*utop(itop-1,jtop-1,ktop-1) -2.328744e-02*utop(itop-1,jtop-1,ktop) -5.174987e-03*utop(itop-1,jtop-1,ktop+1) +5.544629e-04*utop(itop-1,jtop-1,ktop+2) +3.234367e-03*utop(itop-1,jtop,ktop-2) -2.328744e-02*utop(itop-1,jtop,ktop-1) +1.746558e-01*utop(itop-1,jtop,ktop) +3.881240e-02*utop(itop-1,jtop,ktop+1) -4.158472e-03*utop(itop-1,jtop,ktop+2) +7.187482e-04*utop(itop-1,jtop+1,ktop-2) -5.174987e-03*utop(itop-1,jtop+1,ktop-1) +3.881240e-02*utop(itop-1,jtop+1,ktop) +8.624978e-03*utop(itop-1,jtop+1,ktop+1) -9.241048e-04*utop(itop-1,jtop+1,ktop+2) -7.700874e-05*utop(itop-1,jtop+2,ktop-2) +5.544629e-04*utop(itop-1,jtop+2,ktop-1) -4.158472e-03*utop(itop-1,jtop+2,ktop) -9.241048e-04*utop(itop-1,jtop+2,ktop+1) +9.901123e-05*utop(itop-1,jtop+2,ktop+2) +2.695306e-04*utop(itop,jtop-2,ktop-2) -1.940620e-03*utop(itop,jtop-2,ktop-1) +1.455465e-02*utop(itop,jtop-2,ktop) +3.234367e-03*utop(itop,jtop-2,ktop+1) -3.465393e-04*utop(itop,jtop-2,ktop+2) -1.940620e-03*utop(itop,jtop-1,ktop-2) +1.397246e-02*utop(itop,jtop-1,ktop-1) -1.047935e-01*utop(itop,jtop-1,ktop) -2.328744e-02*utop(itop,jtop-1,ktop+1) +2.495083e-03*utop(itop,jtop-1,ktop+2) +1.455465e-02*utop(itop,jtop,ktop-2) -1.047935e-01*utop(itop,jtop,ktop-1) +7.859512e-01*utop(itop,jtop,ktop) +1.746558e-01*utop(itop,jtop,ktop+1) -1.871312e-02*utop(itop,jtop,ktop+2) +3.234367e-03*utop(itop,jtop+1,ktop-2) -2.328744e-02*utop(itop,jtop+1,ktop-1) +1.746558e-01*utop(itop,jtop+1,ktop) +3.881240e-02*utop(itop,jtop+1,ktop+1) -4.158472e-03*utop(itop,jtop+1,ktop+2) -3.465393e-04*utop(itop,jtop+2,ktop-2) +2.495083e-03*utop(itop,jtop+2,ktop-1) -1.871312e-02*utop(itop,jtop+2,ktop) -4.158472e-03*utop(itop,jtop+2,ktop+1) +4.455505e-04*utop(itop,jtop+2,ktop+2) -3.593741e-05*utop(itop+1,jtop-2,ktop-2) +2.587494e-04*utop(itop+1,jtop-2,ktop-1) -1.940620e-03*utop(itop+1,jtop-2,ktop) -4.312489e-04*utop(itop+1,jtop-2,ktop+1) +4.620524e-05*utop(itop+1,jtop-2,ktop+2) +2.587494e-04*utop(itop+1,jtop-1,ktop-2) -1.862995e-03*utop(itop+1,jtop-1,ktop-1) +1.397246e-02*utop(itop+1,jtop-1,ktop) +3.104992e-03*utop(itop+1,jtop-1,ktop+1) -3.326777e-04*utop(itop+1,jtop-1,ktop+2) -1.940620e-03*utop(itop+1,jtop,ktop-2) +1.397246e-02*utop(itop+1,jtop,ktop-1) -1.047935e-01*utop(itop+1,jtop,ktop) -2.328744e-02*utop(itop+1,jtop,ktop+1) +2.495083e-03*utop(itop+1,jtop,ktop+2) -4.312489e-04*utop(itop+1,jtop+1,ktop-2) +3.104992e-03*utop(itop+1,jtop+1,ktop-1) -2.328744e-02*utop(itop+1,jtop+1,ktop) -5.174987e-03*utop(itop+1,jtop+1,ktop+1) +5.544629e-04*utop(itop+1,jtop+1,ktop+2) +4.620524e-05*utop(itop+1,jtop+2,ktop-2) -3.326777e-04*utop(itop+1,jtop+2,ktop-1) +2.495083e-03*utop(itop+1,jtop+2,ktop) +5.544629e-04*utop(itop+1,jtop+2,ktop+1) -5.940674e-05*utop(itop+1,jtop+2,ktop+2) +4.991307e-06*utop(itop+2,jtop-2,ktop-2) -3.593741e-05*utop(itop+2,jtop-2,ktop-1) +2.695306e-04*utop(itop+2,jtop-2,ktop) +5.989568e-05*utop(itop+2,jtop-2,ktop+1) -6.417395e-06*utop(itop+2,jtop-2,ktop+2) -3.593741e-05*utop(itop+2,jtop-1,ktop-2) +2.587494e-04*utop(itop+2,jtop-1,ktop-1) -1.940620e-03*utop(itop+2,jtop-1,ktop) -4.312489e-04*utop(itop+2,jtop-1,ktop+1) +4.620524e-05*utop(itop+2,jtop-1,ktop+2) +2.695306e-04*utop(itop+2,jtop,ktop-2) -1.940620e-03*utop(itop+2,jtop,ktop-1) +1.455465e-02*utop(itop+2,jtop,ktop) +3.234367e-03*utop(itop+2,jtop,ktop+1) -3.465393e-04*utop(itop+2,jtop,ktop+2) +5.989568e-05*utop(itop+2,jtop+1,ktop-2) -4.312489e-04*utop(itop+2,jtop+1,ktop-1) +3.234367e-03*utop(itop+2,jtop+1,ktop) +7.187482e-04*utop(itop+2,jtop+1,ktop+1) -7.700874e-05*utop(itop+2,jtop+1,ktop+2) -6.417395e-06*utop(itop+2,jtop+2,ktop-2) +4.620524e-05*utop(itop+2,jtop+2,ktop-1) -3.465393e-04*utop(itop+2,jtop+2,ktop) -7.700874e-05*utop(itop+2,jtop+2,ktop+1) +8.250936e-06*utop(itop+2,jtop+2,ktop+2));
u(i+1,j+0,k+0) = ( +8.250936e-06*utop(itop-2,jtop-2,ktop-2) -7.700874e-05*utop(itop-2,jtop-2,ktop-1) -3.465393e-04*utop(itop-2,jtop-2,ktop) +4.620524e-05*utop(itop-2,jtop-2,ktop+1) -6.417395e-06*utop(itop-2,jtop-2,ktop+2) -7.700874e-05*utop(itop-2,jtop-1,ktop-2) +7.187482e-04*utop(itop-2,jtop-1,ktop-1) +3.234367e-03*utop(itop-2,jtop-1,ktop) -4.312489e-04*utop(itop-2,jtop-1,ktop+1) +5.989568e-05*utop(itop-2,jtop-1,ktop+2) -3.465393e-04*utop(itop-2,jtop,ktop-2) +3.234367e-03*utop(itop-2,jtop,ktop-1) +1.455465e-02*utop(itop-2,jtop,ktop) -1.940620e-03*utop(itop-2,jtop,ktop+1) +2.695306e-04*utop(itop-2,jtop,ktop+2) +4.620524e-05*utop(itop-2,jtop+1,ktop-2) -4.312489e-04*utop(itop-2,jtop+1,ktop-1) -1.940620e-03*utop(itop-2,jtop+1,ktop) +2.587494e-04*utop(itop-2,jtop+1,ktop+1) -3.593741e-05*utop(itop-2,jtop+1,ktop+2) -6.417395e-06*utop(itop-2,jtop+2,ktop-2) +5.989568e-05*utop(itop-2,jtop+2,ktop-1) +2.695306e-04*utop(itop-2,jtop+2,ktop) -3.593741e-05*utop(itop-2,jtop+2,ktop+1) +4.991307e-06*utop(itop-2,jtop+2,ktop+2) -5.940674e-05*utop(itop-1,jtop-2,ktop-2) +5.544629e-04*utop(itop-1,jtop-2,ktop-1) +2.495083e-03*utop(itop-1,jtop-2,ktop) -3.326777e-04*utop(itop-1,jtop-2,ktop+1) +4.620524e-05*utop(itop-1,jtop-2,ktop+2) +5.544629e-04*utop(itop-1,jtop-1,ktop-2) -5.174987e-03*utop(itop-1,jtop-1,ktop-1) -2.328744e-02*utop(itop-1,jtop-1,ktop) +3.104992e-03*utop(itop-1,jtop-1,ktop+1) -4.312489e-04*utop(itop-1,jtop-1,ktop+2) +2.495083e-03*utop(itop-1,jtop,ktop-2) -2.328744e-02*utop(itop-1,jtop,ktop-1) -1.047935e-01*utop(itop-1,jtop,ktop) +1.397246e-02*utop(itop-1,jtop,ktop+1) -1.940620e-03*utop(itop-1,jtop,ktop+2) -3.326777e-04*utop(itop-1,jtop+1,ktop-2) +3.104992e-03*utop(itop-1,jtop+1,ktop-1) +1.397246e-02*utop(itop-1,jtop+1,ktop) -1.862995e-03*utop(itop-1,jtop+1,ktop+1) +2.587494e-04*utop(itop-1,jtop+1,ktop+2) +4.620524e-05*utop(itop-1,jtop+2,ktop-2) -4.312489e-04*utop(itop-1,jtop+2,ktop-1) -1.940620e-03*utop(itop-1,jtop+2,ktop) +2.587494e-04*utop(itop-1,jtop+2,ktop+1) -3.593741e-05*utop(itop-1,jtop+2,ktop+2) +4.455505e-04*utop(itop,jtop-2,ktop-2) -4.158472e-03*utop(itop,jtop-2,ktop-1) -1.871312e-02*utop(itop,jtop-2,ktop) +2.495083e-03*utop(itop,jtop-2,ktop+1) -3.465393e-04*utop(itop,jtop-2,ktop+2) -4.158472e-03*utop(itop,jtop-1,ktop-2) +3.881240e-02*utop(itop,jtop-1,ktop-1) +1.746558e-01*utop(itop,jtop-1,ktop) -2.328744e-02*utop(itop,jtop-1,ktop+1) +3.234367e-03*utop(itop,jtop-1,ktop+2) -1.871312e-02*utop(itop,jtop,ktop-2) +1.746558e-01*utop(itop,jtop,ktop-1) +7.859512e-01*utop(itop,jtop,ktop) -1.047935e-01*utop(itop,jtop,ktop+1) +1.455465e-02*utop(itop,jtop,ktop+2) +2.495083e-03*utop(itop,jtop+1,ktop-2) -2.328744e-02*utop(itop,jtop+1,ktop-1) -1.047935e-01*utop(itop,jtop+1,ktop) +1.397246e-02*utop(itop,jtop+1,ktop+1) -1.940620e-03*utop(itop,jtop+1,ktop+2) -3.465393e-04*utop(itop,jtop+2,ktop-2) +3.234367e-03*utop(itop,jtop+2,ktop-1) +1.455465e-02*utop(itop,jtop+2,ktop) -1.940620e-03*utop(itop,jtop+2,ktop+1) +2.695306e-04*utop(itop,jtop+2,ktop+2) +9.901123e-05*utop(itop+1,jtop-2,ktop-2) -9.241048e-04*utop(itop+1,jtop-2,ktop-1) -4.158472e-03*utop(itop+1,jtop-2,ktop) +5.544629e-04*utop(itop+1,jtop-2,ktop+1) -7.700874e-05*utop(itop+1,jtop-2,ktop+2) -9.241048e-04*utop(itop+1,jtop-1,ktop-2) +8.624978e-03*utop(itop+1,jtop-1,ktop-1) +3.881240e-02*utop(itop+1,jtop-1,ktop) -5.174987e-03*utop(itop+1,jtop-1,ktop+1) +7.187482e-04*utop(itop+1,jtop-1,ktop+2) -4.158472e-03*utop(itop+1,jtop,ktop-2) +3.881240e-02*utop(itop+1,jtop,ktop-1) +1.746558e-01*utop(itop+1,jtop,ktop) -2.328744e-02*utop(itop+1,jtop,ktop+1) +3.234367e-03*utop(itop+1,jtop,ktop+2) +5.544629e-04*utop(itop+1,jtop+1,ktop-2) -5.174987e-03*utop(itop+1,jtop+1,ktop-1) -2.328744e-02*utop(itop+1,jtop+1,ktop) +3.104992e-03*utop(itop+1,jtop+1,ktop+1) -4.312489e-04*utop(itop+1,jtop+1,ktop+2) -7.700874e-05*utop(itop+1,jtop+2,ktop-2) +7.187482e-04*utop(itop+1,jtop+2,ktop-1) +3.234367e-03*utop(itop+1,jtop+2,ktop) -4.312489e-04*utop(itop+1,jtop+2,ktop+1) +5.989568e-05*utop(itop+1,jtop+2,ktop+2) -1.060835e-05*utop(itop+2,jtop-2,ktop-2) +9.901123e-05*utop(itop+2,jtop-2,ktop-1) +4.455505e-04*utop(itop+2,jtop-2,ktop) -5.940674e-05*utop(itop+2,jtop-2,ktop+1) +8.250936e-06*utop(itop+2,jtop-2,ktop+2) +9.901123e-05*utop(itop+2,jtop-1,ktop-2) -9.241048e-04*utop(itop+2,jtop-1,ktop-1) -4.158472e-03*utop(itop+2,jtop-1,ktop) +5.544629e-04*utop(itop+2,jtop-1,ktop+1) -7.700874e-05*utop(itop+2,jtop-1,ktop+2) +4.455505e-04*utop(itop+2,jtop,ktop-2) -4.158472e-03*utop(itop+2,jtop,ktop-1) -1.871312e-02*utop(itop+2,jtop,ktop) +2.495083e-03*utop(itop+2,jtop,ktop+1) -3.465393e-04*utop(itop+2,jtop,ktop+2) -5.940674e-05*utop(itop+2,jtop+1,ktop-2) +5.544629e-04*utop(itop+2,jtop+1,ktop-1) +2.495083e-03*utop(itop+2,jtop+1,ktop) -3.326777e-04*utop(itop+2,jtop+1,ktop+1) +4.620524e-05*utop(itop+2,jtop+1,ktop+2) +8.250936e-06*utop(itop+2,jtop+2,ktop-2) -7.700874e-05*utop(itop+2,jtop+2,ktop-1) -3.465393e-04*utop(itop+2,jtop+2,ktop) +4.620524e-05*utop(itop+2,jtop+2,ktop+1) -6.417395e-06*utop(itop+2,jtop+2,ktop+2));
u(i+1,j+0,k+1) = ( -6.417395e-06*utop(itop-2,jtop-2,ktop-2) +4.620524e-05*utop(itop-2,jtop-2,ktop-1) -3.465393e-04*utop(itop-2,jtop-2,ktop) -7.700874e-05*utop(itop-2,jtop-2,ktop+1) +8.250936e-06*utop(itop-2,jtop-2,ktop+2) +5.989568e-05*utop(itop-2,jtop-1,ktop-2) -4.312489e-04*utop(itop-2,jtop-1,ktop-1) +3.234367e-03*utop(itop-2,jtop-1,ktop) +7.187482e-04*utop(itop-2,jtop-1,ktop+1) -7.700874e-05*utop(itop-2,jtop-1,ktop+2) +2.695306e-04*utop(itop-2,jtop,ktop-2) -1.940620e-03*utop(itop-2,jtop,ktop-1) +1.455465e-02*utop(itop-2,jtop,ktop) +3.234367e-03*utop(itop-2,jtop,ktop+1) -3.465393e-04*utop(itop-2,jtop,ktop+2) -3.593741e-05*utop(itop-2,jtop+1,ktop-2) +2.587494e-04*utop(itop-2,jtop+1,ktop-1) -1.940620e-03*utop(itop-2,jtop+1,ktop) -4.312489e-04*utop(itop-2,jtop+1,ktop+1) +4.620524e-05*utop(itop-2,jtop+1,ktop+2) +4.991307e-06*utop(itop-2,jtop+2,ktop-2) -3.593741e-05*utop(itop-2,jtop+2,ktop-1) +2.695306e-04*utop(itop-2,jtop+2,ktop) +5.989568e-05*utop(itop-2,jtop+2,ktop+1) -6.417395e-06*utop(itop-2,jtop+2,ktop+2) +4.620524e-05*utop(itop-1,jtop-2,ktop-2) -3.326777e-04*utop(itop-1,jtop-2,ktop-1) +2.495083e-03*utop(itop-1,jtop-2,ktop) +5.544629e-04*utop(itop-1,jtop-2,ktop+1) -5.940674e-05*utop(itop-1,jtop-2,ktop+2) -4.312489e-04*utop(itop-1,jtop-1,ktop-2) +3.104992e-03*utop(itop-1,jtop-1,ktop-1) -2.328744e-02*utop(itop-1,jtop-1,ktop) -5.174987e-03*utop(itop-1,jtop-1,ktop+1) +5.544629e-04*utop(itop-1,jtop-1,ktop+2) -1.940620e-03*utop(itop-1,jtop,ktop-2) +1.397246e-02*utop(itop-1,jtop,ktop-1) -1.047935e-01*utop(itop-1,jtop,ktop) -2.328744e-02*utop(itop-1,jtop,ktop+1) +2.495083e-03*utop(itop-1,jtop,ktop+2) +2.587494e-04*utop(itop-1,jtop+1,ktop-2) -1.862995e-03*utop(itop-1,jtop+1,ktop-1) +1.397246e-02*utop(itop-1,jtop+1,ktop) +3.104992e-03*utop(itop-1,jtop+1,ktop+1) -3.326777e-04*utop(itop-1,jtop+1,ktop+2) -3.593741e-05*utop(itop-1,jtop+2,ktop-2) +2.587494e-04*utop(itop-1,jtop+2,ktop-1) -1.940620e-03*utop(itop-1,jtop+2,ktop) -4.312489e-04*utop(itop-1,jtop+2,ktop+1) +4.620524e-05*utop(itop-1,jtop+2,ktop+2) -3.465393e-04*utop(itop,jtop-2,ktop-2) +2.495083e-03*utop(itop,jtop-2,ktop-1) -1.871312e-02*utop(itop,jtop-2,ktop) -4.158472e-03*utop(itop,jtop-2,ktop+1) +4.455505e-04*utop(itop,jtop-2,ktop+2) +3.234367e-03*utop(itop,jtop-1,ktop-2) -2.328744e-02*utop(itop,jtop-1,ktop-1) +1.746558e-01*utop(itop,jtop-1,ktop) +3.881240e-02*utop(itop,jtop-1,ktop+1) -4.158472e-03*utop(itop,jtop-1,ktop+2) +1.455465e-02*utop(itop,jtop,ktop-2) -1.047935e-01*utop(itop,jtop,ktop-1) +7.859512e-01*utop(itop,jtop,ktop) +1.746558e-01*utop(itop,jtop,ktop+1) -1.871312e-02*utop(itop,jtop,ktop+2) -1.940620e-03*utop(itop,jtop+1,ktop-2) +1.397246e-02*utop(itop,jtop+1,ktop-1) -1.047935e-01*utop(itop,jtop+1,ktop) -2.328744e-02*utop(itop,jtop+1,ktop+1) +2.495083e-03*utop(itop,jtop+1,ktop+2) +2.695306e-04*utop(itop,jtop+2,ktop-2) -1.940620e-03*utop(itop,jtop+2,ktop-1) +1.455465e-02*utop(itop,jtop+2,ktop) +3.234367e-03*utop(itop,jtop+2,ktop+1) -3.465393e-04*utop(itop,jtop+2,ktop+2) -7.700874e-05*utop(itop+1,jtop-2,ktop-2) +5.544629e-04*utop(itop+1,jtop-2,ktop-1) -4.158472e-03*utop(itop+1,jtop-2,ktop) -9.241048e-04*utop(itop+1,jtop-2,ktop+1) +9.901123e-05*utop(itop+1,jtop-2,ktop+2) +7.187482e-04*utop(itop+1,jtop-1,ktop-2) -5.174987e-03*utop(itop+1,jtop-1,ktop-1) +3.881240e-02*utop(itop+1,jtop-1,ktop) +8.624978e-03*utop(itop+1,jtop-1,ktop+1) -9.241048e-04*utop(itop+1,jtop-1,ktop+2) +3.234367e-03*utop(itop+1,jtop,ktop-2) -2.328744e-02*utop(itop+1,jtop,ktop-1) +1.746558e-01*utop(itop+1,jtop,ktop) +3.881240e-02*utop(itop+1,jtop,ktop+1) -4.158472e-03*utop(itop+1,jtop,ktop+2) -4.312489e-04*utop(itop+1,jtop+1,ktop-2) +3.104992e-03*utop(itop+1,jtop+1,ktop-1) -2.328744e-02*utop(itop+1,jtop+1,ktop) -5.174987e-03*utop(itop+1,jtop+1,ktop+1) +5.544629e-04*utop(itop+1,jtop+1,ktop+2) +5.989568e-05*utop(itop+1,jtop+2,ktop-2) -4.312489e-04*utop(itop+1,jtop+2,ktop-1) +3.234367e-03*utop(itop+1,jtop+2,ktop) +7.187482e-04*utop(itop+1,jtop+2,ktop+1) -7.700874e-05*utop(itop+1,jtop+2,ktop+2) +8.250936e-06*utop(itop+2,jtop-2,ktop-2) -5.940674e-05*utop(itop+2,jtop-2,ktop-1) +4.455505e-04*utop(itop+2,jtop-2,ktop) +9.901123e-05*utop(itop+2,jtop-2,ktop+1) -1.060835e-05*utop(itop+2,jtop-2,ktop+2) -7.700874e-05*utop(itop+2,jtop-1,ktop-2) +5.544629e-04*utop(itop+2,jtop-1,ktop-1) -4.158472e-03*utop(itop+2,jtop-1,ktop) -9.241048e-04*utop(itop+2,jtop-1,ktop+1) +9.901123e-05*utop(itop+2,jtop-1,ktop+2) -3.465393e-04*utop(itop+2,jtop,ktop-2) +2.495083e-03*utop(itop+2,jtop,ktop-1) -1.871312e-02*utop(itop+2,jtop,ktop) -4.158472e-03*utop(itop+2,jtop,ktop+1) +4.455505e-04*utop(itop+2,jtop,ktop+2) +4.620524e-05*utop(itop+2,jtop+1,ktop-2) -3.326777e-04*utop(itop+2,jtop+1,ktop-1) +2.495083e-03*utop(itop+2,jtop+1,ktop) +5.544629e-04*utop(itop+2,jtop+1,ktop+1) -5.940674e-05*utop(itop+2,jtop+1,ktop+2) -6.417395e-06*utop(itop+2,jtop+2,ktop-2) +4.620524e-05*utop(itop+2,jtop+2,ktop-1) -3.465393e-04*utop(itop+2,jtop+2,ktop) -7.700874e-05*utop(itop+2,jtop+2,ktop+1) +8.250936e-06*utop(itop+2,jtop+2,ktop+2));
u(i+1,j+1,k+0) = ( -6.417395e-06*utop(itop-2,jtop-2,ktop-2) +5.989568e-05*utop(itop-2,jtop-2,ktop-1) +2.695306e-04*utop(itop-2,jtop-2,ktop) -3.593741e-05*utop(itop-2,jtop-2,ktop+1) +4.991307e-06*utop(itop-2,jtop-2,ktop+2) +4.620524e-05*utop(itop-2,jtop-1,ktop-2) -4.312489e-04*utop(itop-2,jtop-1,ktop-1) -1.940620e-03*utop(itop-2,jtop-1,ktop) +2.587494e-04*utop(itop-2,jtop-1,ktop+1) -3.593741e-05*utop(itop-2,jtop-1,ktop+2) -3.465393e-04*utop(itop-2,jtop,ktop-2) +3.234367e-03*utop(itop-2,jtop,ktop-1) +1.455465e-02*utop(itop-2,jtop,ktop) -1.940620e-03*utop(itop-2,jtop,ktop+1) +2.695306e-04*utop(itop-2,jtop,ktop+2) -7.700874e-05*utop(itop-2,jtop+1,ktop-2) +7.187482e-04*utop(itop-2,jtop+1,ktop-1) +3.234367e-03*utop(itop-2,jtop+1,ktop) -4.312489e-04*utop(itop-2,jtop+1,ktop+1) +5.989568e-05*utop(itop-2,jtop+1,ktop+2) +8.250936e-06*utop(itop-2,jtop+2,ktop-2) -7.700874e-05*utop(itop-2,jtop+2,ktop-1) -3.465393e-04*utop(itop-2,jtop+2,ktop) +4.620524e-05*utop(itop-2,jtop+2,ktop+1) -6.417395e-06*utop(itop-2,jtop+2,ktop+2) +4.620524e-05*utop(itop-1,jtop-2,ktop-2) -4.312489e-04*utop(itop-1,jtop-2,ktop-1) -1.940620e-03*utop(itop-1,jtop-2,ktop) +2.587494e-04*utop(itop-1,jtop-2,ktop+1) -3.593741e-05*utop(itop-1,jtop-2,ktop+2) -3.326777e-04*utop(itop-1,jtop-1,ktop-2) +3.104992e-03*utop(itop-1,jtop-1,ktop-1) +1.397246e-02*utop(itop-1,jtop-1,ktop) -1.862995e-03*utop(itop-1,jtop-1,ktop+1) +2.587494e-04*utop(itop-1,jtop-1,ktop+2) +2.495083e-03*utop(itop-1,jtop,ktop-2) -2.328744e-02*utop(itop-1,jtop,ktop-1) -1.047935e-01*utop(itop-1,jtop,ktop) +1.397246e-02*utop(itop-1,jtop,ktop+1) -1.940620e-03*utop(itop-1,jtop,ktop+2) +5.544629e-04*utop(itop-1,jtop+1,ktop-2) -5.174987e-03*utop(itop-1,jtop+1,ktop-1) -2.328744e-02*utop(itop-1,jtop+1,ktop) +3.104992e-03*utop(itop-1,jtop+1,ktop+1) -4.312489e-04*utop(itop-1,jtop+1,ktop+2) -5.940674e-05*utop(itop-1,jtop+2,ktop-2) +5.544629e-04*utop(itop-1,jtop+2,ktop-1) +2.495083e-03*utop(itop-1,jtop+2,ktop) -3.326777e-04*utop(itop-1,jtop+2,ktop+1) +4.620524e-05*utop(itop-1,jtop+2,ktop+2) -3.465393e-04*utop(itop,jtop-2,ktop-2) +3.234367e-03*utop(itop,jtop-2,ktop-1) +1.455465e-02*utop(itop,jtop-2,ktop) -1.940620e-03*utop(itop,jtop-2,ktop+1) +2.695306e-04*utop(itop,jtop-2,ktop+2) +2.495083e-03*utop(itop,jtop-1,ktop-2) -2.328744e-02*utop(itop,jtop-1,ktop-1) -1.047935e-01*utop(itop,jtop-1,ktop) +1.397246e-02*utop(itop,jtop-1,ktop+1) -1.940620e-03*utop(itop,jtop-1,ktop+2) -1.871312e-02*utop(itop,jtop,ktop-2) +1.746558e-01*utop(itop,jtop,ktop-1) +7.859512e-01*utop(itop,jtop,ktop) -1.047935e-01*utop(itop,jtop,ktop+1) +1.455465e-02*utop(itop,jtop,ktop+2) -4.158472e-03*utop(itop,jtop+1,ktop-2) +3.881240e-02*utop(itop,jtop+1,ktop-1) +1.746558e-01*utop(itop,jtop+1,ktop) -2.328744e-02*utop(itop,jtop+1,ktop+1) +3.234367e-03*utop(itop,jtop+1,ktop+2) +4.455505e-04*utop(itop,jtop+2,ktop-2) -4.158472e-03*utop(itop,jtop+2,ktop-1) -1.871312e-02*utop(itop,jtop+2,ktop) +2.495083e-03*utop(itop,jtop+2,ktop+1) -3.465393e-04*utop(itop,jtop+2,ktop+2) -7.700874e-05*utop(itop+1,jtop-2,ktop-2) +7.187482e-04*utop(itop+1,jtop-2,ktop-1) +3.234367e-03*utop(itop+1,jtop-2,ktop) -4.312489e-04*utop(itop+1,jtop-2,ktop+1) +5.989568e-05*utop(itop+1,jtop-2,ktop+2) +5.544629e-04*utop(itop+1,jtop-1,ktop-2) -5.174987e-03*utop(itop+1,jtop-1,ktop-1) -2.328744e-02*utop(itop+1,jtop-1,ktop) +3.104992e-03*utop(itop+1,jtop-1,ktop+1) -4.312489e-04*utop(itop+1,jtop-1,ktop+2) -4.158472e-03*utop(itop+1,jtop,ktop-2) +3.881240e-02*utop(itop+1,jtop,ktop-1) +1.746558e-01*utop(itop+1,jtop,ktop) -2.328744e-02*utop(itop+1,jtop,ktop+1) +3.234367e-03*utop(itop+1,jtop,ktop+2) -9.241048e-04*utop(itop+1,jtop+1,ktop-2) +8.624978e-03*utop(itop+1,jtop+1,ktop-1) +3.881240e-02*utop(itop+1,jtop+1,ktop) -5.174987e-03*utop(itop+1,jtop+1,ktop+1) +7.187482e-04*utop(itop+1,jtop+1,ktop+2) +9.901123e-05*utop(itop+1,jtop+2,ktop-2) -9.241048e-04*utop(itop+1,jtop+2,ktop-1) -4.158472e-03*utop(itop+1,jtop+2,ktop) +5.544629e-04*utop(itop+1,jtop+2,ktop+1) -7.700874e-05*utop(itop+1,jtop+2,ktop+2) +8.250936e-06*utop(itop+2,jtop-2,ktop-2) -7.700874e-05*utop(itop+2,jtop-2,ktop-1) -3.465393e-04*utop(itop+2,jtop-2,ktop) +4.620524e-05*utop(itop+2,jtop-2,ktop+1) -6.417395e-06*utop(itop+2,jtop-2,ktop+2) -5.940674e-05*utop(itop+2,jtop-1,ktop-2) +5.544629e-04*utop(itop+2,jtop-1,ktop-1) +2.495083e-03*utop(itop+2,jtop-1,ktop) -3.326777e-04*utop(itop+2,jtop-1,ktop+1) +4.620524e-05*utop(itop+2,jtop-1,ktop+2) +4.455505e-04*utop(itop+2,jtop,ktop-2) -4.158472e-03*utop(itop+2,jtop,ktop-1) -1.871312e-02*utop(itop+2,jtop,ktop) +2.495083e-03*utop(itop+2,jtop,ktop+1) -3.465393e-04*utop(itop+2,jtop,ktop+2) +9.901123e-05*utop(itop+2,jtop+1,ktop-2) -9.241048e-04*utop(itop+2,jtop+1,ktop-1) -4.158472e-03*utop(itop+2,jtop+1,ktop) +5.544629e-04*utop(itop+2,jtop+1,ktop+1) -7.700874e-05*utop(itop+2,jtop+1,ktop+2) -1.060835e-05*utop(itop+2,jtop+2,ktop-2) +9.901123e-05*utop(itop+2,jtop+2,ktop-1) +4.455505e-04*utop(itop+2,jtop+2,ktop) -5.940674e-05*utop(itop+2,jtop+2,ktop+1) +8.250936e-06*utop(itop+2,jtop+2,ktop+2));
u(i+1,j+1,k+1) = ( +4.991307e-06*utop(itop-2,jtop-2,ktop-2) -3.593741e-05*utop(itop-2,jtop-2,ktop-1) +2.695306e-04*utop(itop-2,jtop-2,ktop) +5.989568e-05*utop(itop-2,jtop-2,ktop+1) -6.417395e-06*utop(itop-2,jtop-2,ktop+2) -3.593741e-05*utop(itop-2,jtop-1,ktop-2) +2.587494e-04*utop(itop-2,jtop-1,ktop-1) -1.940620e-03*utop(itop-2,jtop-1,ktop) -4.312489e-04*utop(itop-2,jtop-1,ktop+1) +4.620524e-05*utop(itop-2,jtop-1,ktop+2) +2.695306e-04*utop(itop-2,jtop,ktop-2) -1.940620e-03*utop(itop-2,jtop,ktop-1) +1.455465e-02*utop(itop-2,jtop,ktop) +3.234367e-03*utop(itop-2,jtop,ktop+1) -3.465393e-04*utop(itop-2,jtop,ktop+2) +5.989568e-05*utop(itop-2,jtop+1,ktop-2) -4.312489e-04*utop(itop-2,jtop+1,ktop-1) +3.234367e-03*utop(itop-2,jtop+1,ktop) +7.187482e-04*utop(itop-2,jtop+1,ktop+1) -7.700874e-05*utop(itop-2,jtop+1,ktop+2) -6.417395e-06*utop(itop-2,jtop+2,ktop-2) +4.620524e-05*utop(itop-2,jtop+2,ktop-1) -3.465393e-04*utop(itop-2,jtop+2,ktop) -7.700874e-05*utop(itop-2,jtop+2,ktop+1) +8.250936e-06*utop(itop-2,jtop+2,ktop+2) -3.593741e-05*utop(itop-1,jtop-2,ktop-2) +2.587494e-04*utop(itop-1,jtop-2,ktop-1) -1.940620e-03*utop(itop-1,jtop-2,ktop) -4.312489e-04*utop(itop-1,jtop-2,ktop+1) +4.620524e-05*utop(itop-1,jtop-2,ktop+2) +2.587494e-04*utop(itop-1,jtop-1,ktop-2) -1.862995e-03*utop(itop-1,jtop-1,ktop-1) +1.397246e-02*utop(itop-1,jtop-1,ktop) +3.104992e-03*utop(itop-1,jtop-1,ktop+1) -3.326777e-04*utop(itop-1,jtop-1,ktop+2) -1.940620e-03*utop(itop-1,jtop,ktop-2) +1.397246e-02*utop(itop-1,jtop,ktop-1) -1.047935e-01*utop(itop-1,jtop,ktop) -2.328744e-02*utop(itop-1,jtop,ktop+1) +2.495083e-03*utop(itop-1,jtop,ktop+2) -4.312489e-04*utop(itop-1,jtop+1,ktop-2) +3.104992e-03*utop(itop-1,jtop+1,ktop-1) -2.328744e-02*utop(itop-1,jtop+1,ktop) -5.174987e-03*utop(itop-1,jtop+1,ktop+1) +5.544629e-04*utop(itop-1,jtop+1,ktop+2) +4.620524e-05*utop(itop-1,jtop+2,ktop-2) -3.326777e-04*utop(itop-1,jtop+2,ktop-1) +2.495083e-03*utop(itop-1,jtop+2,ktop) +5.544629e-04*utop(itop-1,jtop+2,ktop+1) -5.940674e-05*utop(itop-1,jtop+2,ktop+2) +2.695306e-04*utop(itop,jtop-2,ktop-2) -1.940620e-03*utop(itop,jtop-2,ktop-1) +1.455465e-02*utop(itop,jtop-2,ktop) +3.234367e-03*utop(itop,jtop-2,ktop+1) -3.465393e-04*utop(itop,jtop-2,ktop+2) -1.940620e-03*utop(itop,jtop-1,ktop-2) +1.397246e-02*utop(itop,jtop-1,ktop-1) -1.047935e-01*utop(itop,jtop-1,ktop) -2.328744e-02*utop(itop,jtop-1,ktop+1) +2.495083e-03*utop(itop,jtop-1,ktop+2) +1.455465e-02*utop(itop,jtop,ktop-2) -1.047935e-01*utop(itop,jtop,ktop-1) +7.859512e-01*utop(itop,jtop,ktop) +1.746558e-01*utop(itop,jtop,ktop+1) -1.871312e-02*utop(itop,jtop,ktop+2) +3.234367e-03*utop(itop,jtop+1,ktop-2) -2.328744e-02*utop(itop,jtop+1,ktop-1) +1.746558e-01*utop(itop,jtop+1,ktop) +3.881240e-02*utop(itop,jtop+1,ktop+1) -4.158472e-03*utop(itop,jtop+1,ktop+2) -3.465393e-04*utop(itop,jtop+2,ktop-2) +2.495083e-03*utop(itop,jtop+2,ktop-1) -1.871312e-02*utop(itop,jtop+2,ktop) -4.158472e-03*utop(itop,jtop+2,ktop+1) +4.455505e-04*utop(itop,jtop+2,ktop+2) +5.989568e-05*utop(itop+1,jtop-2,ktop-2) -4.312489e-04*utop(itop+1,jtop-2,ktop-1) +3.234367e-03*utop(itop+1,jtop-2,ktop) +7.187482e-04*utop(itop+1,jtop-2,ktop+1) -7.700874e-05*utop(itop+1,jtop-2,ktop+2) -4.312489e-04*utop(itop+1,jtop-1,ktop-2) +3.104992e-03*utop(itop+1,jtop-1,ktop-1) -2.328744e-02*utop(itop+1,jtop-1,ktop) -5.174987e-03*utop(itop+1,jtop-1,ktop+1) +5.544629e-04*utop(itop+1,jtop-1,ktop+2) +3.234367e-03*utop(itop+1,jtop,ktop-2) -2.328744e-02*utop(itop+1,jtop,ktop-1) +1.746558e-01*utop(itop+1,jtop,ktop) +3.881240e-02*utop(itop+1,jtop,ktop+1) -4.158472e-03*utop(itop+1,jtop,ktop+2) +7.187482e-04*utop(itop+1,jtop+1,ktop-2) -5.174987e-03*utop(itop+1,jtop+1,ktop-1) +3.881240e-02*utop(itop+1,jtop+1,ktop) +8.624978e-03*utop(itop+1,jtop+1,ktop+1) -9.241048e-04*utop(itop+1,jtop+1,ktop+2) -7.700874e-05*utop(itop+1,jtop+2,ktop-2) +5.544629e-04*utop(itop+1,jtop+2,ktop-1) -4.158472e-03*utop(itop+1,jtop+2,ktop) -9.241048e-04*utop(itop+1,jtop+2,ktop+1) +9.901123e-05*utop(itop+1,jtop+2,ktop+2) -6.417395e-06*utop(itop+2,jtop-2,ktop-2) +4.620524e-05*utop(itop+2,jtop-2,ktop-1) -3.465393e-04*utop(itop+2,jtop-2,ktop) -7.700874e-05*utop(itop+2,jtop-2,ktop+1) +8.250936e-06*utop(itop+2,jtop-2,ktop+2) +4.620524e-05*utop(itop+2,jtop-1,ktop-2) -3.326777e-04*utop(itop+2,jtop-1,ktop-1) +2.495083e-03*utop(itop+2,jtop-1,ktop) +5.544629e-04*utop(itop+2,jtop-1,ktop+1) -5.940674e-05*utop(itop+2,jtop-1,ktop+2) -3.465393e-04*utop(itop+2,jtop,ktop-2) +2.495083e-03*utop(itop+2,jtop,ktop-1) -1.871312e-02*utop(itop+2,jtop,ktop) -4.158472e-03*utop(itop+2,jtop,ktop+1) +4.455505e-04*utop(itop+2,jtop,ktop+2) -7.700874e-05*utop(itop+2,jtop+1,ktop-2) +5.544629e-04*utop(itop+2,jtop+1,ktop-1) -4.158472e-03*utop(itop+2,jtop+1,ktop) -9.241048e-04*utop(itop+2,jtop+1,ktop+1) +9.901123e-05*utop(itop+2,jtop+1,ktop+2) +8.250936e-06*utop(itop+2,jtop+2,ktop-2) -5.940674e-05*utop(itop+2,jtop+2,ktop-1) +4.455505e-04*utop(itop+2,jtop+2,ktop) +9.901123e-05*utop(itop+2,jtop+2,ktop+1) -1.060835e-05*utop(itop+2,jtop+2,ktop+2));
}
template< class S, class O, typename T >
void solver<S,O,T>::interp_coarse_fine_cubic( unsigned ilevel, MeshvarBnd<T>& coarse, MeshvarBnd<T>& fine, bool bcf=false )
{
MeshvarBnd<T> *u = &fine;
MeshvarBnd<T> *utop = &coarse;
bcf = true;
int
xoff = u->offset(0),
yoff = u->offset(1),
zoff = u->offset(2);
//... don't do anything if we are not an additional refinement region
if( ilevel <= m_ilevelmin )
return;
int
nx = u->size(0),
ny = u->size(1),
nz = u->size(2);
for( int j=0; j<ny; ++j )
for( int k=0; k<nz; ++k )
{
int jtop = (int)(0.5*(double)(j))+yoff;
int ktop = (int)(0.5*(double)(k))+zoff;
interp_cubic( coarse, fine, -2, j, k, xoff-1, jtop, ktop );
interp_cubic( coarse, fine, nz, j, k, xoff+nz/2, jtop, ktop );
}
for( int i=0; i<nx; ++i )
for( int k=0; k<nz; ++k )
{
int itop = (int)(0.5*(double)(i))+xoff;
int ktop = (int)(0.5*(double)(k))+zoff;
interp_cubic( coarse, fine, i, -2, k, itop, yoff-1, ktop );
interp_cubic( coarse, fine, i, ny, k, itop, yoff+ny/2, ktop );
}
for( int i=0; i<nx; ++i )
for( int j=0; j<ny; ++j )
{
int itop = (int)(0.5*(double)(i))+xoff;
int jtop = (int)(0.5*(double)(j))+yoff;
interp_cubic( coarse, fine, i, j, -2, itop, jtop, zoff-1 );
interp_cubic( coarse, fine, i, j, nz, itop, jtop, zoff+nz/2 );
}
}
template< class S, class O, typename T >
void solver<S,O,T>::interp_coarse_fine( unsigned ilevel, MeshvarBnd<T>& coarse, MeshvarBnd<T>& fine, bool bcf )
{
MeshvarBnd<T> *u = &fine;
MeshvarBnd<T> *utop = &coarse;
bcf = true;;
//bcf = false;
int
xoff = u->offset(0),
yoff = u->offset(1),
zoff = u->offset(2);
//... don't do anything if we are not an additional refinement region
if( xoff == 0 && yoff == 0 && zoff == 0 )
return;
int
nx = u->size(0),
ny = u->size(1),
nz = u->size(2);
//... set boundary condition for fine grid
#pragma omp parallel for schedule(dynamic)
for( int ix=-1; ix<=nx; ++ix )
for( int iy=-1; iy<=ny; ++iy )
for( int iz=-1; iz<=nz; ++iz )
{
bool xbnd=(ix==-1||ix==nx),ybnd=(iy==-1||iy==ny),zbnd=(iz==-1||iz==nz);
//if(ix==-1||ix==nx||iy==-1||iy==ny||iz==-1||iz==nz)
if( xbnd || ybnd || zbnd )
//if( xbnd ^ ybnd ^ zbnd )
{
//... only deal with proper ghostzones
if( (xbnd&&ybnd) || (xbnd&&zbnd) || (ybnd&&zbnd) || (xbnd&&ybnd&&zbnd))
continue;
/*int ixtop = (int)(0.5*(double)(ix+2*xoff)+1e-3);
int iytop = (int)(0.5*(double)(iy+2*yoff)+1e-3);
int iztop = (int)(0.5*(double)(iz+2*zoff)+1e-3);*/
int ixtop = (int)(0.5*(double)(ix))+xoff;
int iytop = (int)(0.5*(double)(iy))+yoff;
int iztop = (int)(0.5*(double)(iz))+zoff;
if( ix==-1 ) ixtop=xoff-1;
if( iy==-1 ) iytop=yoff-1;
if( iz==-1 ) iztop=zoff-1;
double ustar1, ustar2, ustar3, uhat;
double fac = 0.5;//0.25;
double flux;;
if( ix == -1 && iy%2==0 && iz%2==0 )
{
flux = 0.0;
for( int j=0;j<=1;j++)
for( int k=0;k<=1;k++)
{
ustar1 = interp2( (*utop)(ixtop,iytop-1,iztop-1),(*utop)(ixtop,iytop,iztop-1),(*utop)(ixtop,iytop+1,iztop-1), fac*((double)j-0.5) );
ustar2 = interp2( (*utop)(ixtop,iytop-1,iztop),(*utop)(ixtop,iytop,iztop),(*utop)(ixtop,iytop+1,iztop), fac*((double)j-0.5) );
ustar3 = interp2( (*utop)(ixtop,iytop-1,iztop+1),(*utop)(ixtop,iytop,iztop+1),(*utop)(ixtop,iytop+1,iztop+1), fac*((double)j-0.5) );
uhat = interp2( /*-1.0, 0.0, 1.0, */ustar1, ustar2, ustar3, fac*((double)k-0.5) );
//(*u)(ix,iy+j,iz+k) = 0.0;//(*utop)(ixtop,iytop,iztop);//interp2( -1.5, 0.0, 1.0, uhat, (*u)(ix+1,iy+j,iz+k), (*u)(ix+2,iy+j,iz+k), -1.0 );
(*u)(ix,iy+j,iz+k) = interp2left( uhat, (*u)(ix+1,iy+j,iz+k), (*u)(ix+2,iy+j,iz+k) );
flux += ((*u)(ix+1,iy+j,iz+k)-(*u)(ix,iy+j,iz+k));
}
flux /= 4.0;
double dflux = ((*utop)(ixtop+1,iytop,iztop)-(*utop)(ixtop,iytop,iztop))/2.0 - flux;
//dflux *= 2.0;
if( bcf )
for( int j=0;j<=1;j++)
for( int k=0;k<=1;k++)
(*u)(ix,iy+j,iz+k) -= dflux;
else
(*utop)(ixtop,iytop,iztop) = (*utop)(ixtop+1,iytop,iztop) - 2.0*flux;
}
// right boundary
if( ix == nx && iy%2==0 && iz%2==0 )
{
flux = 0.0;
for( int j=0;j<=1;j++)
for( int k=0;k<=1;k++)
{
ustar1 = interp2( (*utop)(ixtop,iytop-1,iztop-1),(*utop)(ixtop,iytop,iztop-1),(*utop)(ixtop,iytop+1,iztop-1), fac*((double)j-0.5) );
ustar2 = interp2( (*utop)(ixtop,iytop-1,iztop),(*utop)(ixtop,iytop,iztop),(*utop)(ixtop,iytop+1,iztop), fac*((double)j-0.5) );
ustar3 = interp2( (*utop)(ixtop,iytop-1,iztop+1),(*utop)(ixtop,iytop,iztop+1),(*utop)(ixtop,iytop+1,iztop+1), fac*((double)j-0.5) );
uhat = interp2( -1.0, 0.0, 1.0, ustar1, ustar2, ustar3, fac*((double)k-0.5) );
//(*u)(ix,iy+j,iz+k) = 0.0;(*utop)(ixtop,iytop,iztop);//interp2( 1.5, 0.0, -1.0, uhat, (*u)(ix-1,iy+j,iz+k), (*u)(ix-2,iy+j,iz+k), 1.0 );
(*u)(ix,iy+j,iz+k) = interp2right( (*u)(ix-2,iy+j,iz+k), (*u)(ix-1,iy+j,iz+k), uhat );
flux += ((*u)(ix,iy+j,iz+k)-(*u)(ix-1,iy+j,iz+k));
}
flux /= 4.0;
double dflux = ((*utop)(ixtop,iytop,iztop)-(*utop)(ixtop-1,iytop,iztop))/2.0 - flux;
//dflux *= 2.0;
if( bcf )
for( int j=0;j<=1;j++)
for( int k=0;k<=1;k++)
(*u)(ix,iy+j,iz+k) += dflux;
else
(*utop)(ixtop,iytop,iztop) = (*utop)(ixtop-1,iytop,iztop) + 2.0*flux;
}
// bottom boundary
if( iy == -1 && ix%2==0 && iz%2==0 )
{
flux = 0.0;
for( int j=0;j<=1;j++)
for( int k=0;k<=1;k++)
{
ustar1 = interp2( (*utop)(ixtop-1,iytop,iztop-1),(*utop)(ixtop,iytop,iztop-1),(*utop)(ixtop+1,iytop,iztop-1), fac*(j-0.5) );
ustar2 = interp2( (*utop)(ixtop-1,iytop,iztop),(*utop)(ixtop,iytop,iztop),(*utop)(ixtop+1,iytop,iztop), fac*(j-0.5) );
ustar3 = interp2( (*utop)(ixtop-1,iytop,iztop+1),(*utop)(ixtop,iytop,iztop+1),(*utop)(ixtop+1,iytop,iztop+1), fac*(j-0.5) );
uhat = interp2( -1.0, 0.0, 1.0, ustar1, ustar2, ustar3, fac*((double)k-0.5) );
//(*u)(ix+j,iy,iz+k) = 0.0;(*utop)(ixtop,iytop,iztop);//interp2( -1.5, 0.0, 1.0, uhat, (*u)(ix+j,iy+1,iz+k), (*u)(ix+j,iy+2,iz+k), -1.0 );
(*u)(ix+j,iy,iz+k) = interp2left( uhat, (*u)(ix+j,iy+1,iz+k), (*u)(ix+j,iy+2,iz+k) );
flux += ((*u)(ix+j,iy+1,iz+k)-(*u)(ix+j,iy,iz+k));
}
flux /= 4.0;
//(*utop)(ixtop,iytop,iztop) = (*utop)(ixtop,iytop+1,iztop) - flux;
double dflux = ((*utop)(ixtop,iytop+1,iztop)-(*utop)(ixtop,iytop,iztop))/2.0 - flux;
//dflux *= 2.0;
if( bcf )
for( int j=0;j<=1;j++)
for( int k=0;k<=1;k++)
(*u)(ix+j,iy,iz+k) -= dflux;
else
(*utop)(ixtop,iytop,iztop) = (*utop)(ixtop,iytop+1,iztop) - 2.0*flux;
}
// top boundary
if( iy == ny && ix%2==0 && iz%2==0 )
{
flux = 0.0;
for( int j=0;j<=1;j++)
for( int k=0;k<=1;k++)
{
ustar1 = interp2( (*utop)(ixtop-1,iytop,iztop-1),(*utop)(ixtop,iytop,iztop-1),(*utop)(ixtop+1,iytop,iztop-1), fac*(j-0.5) );
ustar2 = interp2( (*utop)(ixtop-1,iytop,iztop),(*utop)(ixtop,iytop,iztop),(*utop)(ixtop+1,iytop,iztop), fac*(j-0.5) );
ustar3 = interp2( (*utop)(ixtop-1,iytop,iztop+1),(*utop)(ixtop,iytop,iztop+1),(*utop)(ixtop+1,iytop,iztop+1), fac*(j-0.5) );
uhat = interp2( -1.0, 0.0, 1.0, ustar1, ustar2, ustar3, fac*((double)k-0.5) );
//(*u)(ix+j,iy,iz+k) = 0.0;(*utop)(ixtop,iytop,iztop);//interp2( 1.5, 0.0, -1.0, uhat, (*u)(ix+j,iy-1,iz+k), (*u)(ix+j,iy-2,iz+k), 1.0 );
(*u)(ix+j,iy,iz+k) = interp2right( (*u)(ix+j,iy-2,iz+k), (*u)(ix+j,iy-1,iz+k), uhat );
flux += ((*u)(ix+j,iy,iz+k)-(*u)(ix+j,iy-1,iz+k));
}
flux /= 4.0;
//(*utop)(ixtop,iytop,iztop) = (*utop)(ixtop,iytop-1,iztop) + flux;
double dflux = ((*utop)(ixtop,iytop,iztop)-(*utop)(ixtop,iytop-1,iztop))/2.0 - flux;
//dflux *= 2.0;
if( bcf )
for( int j=0;j<=1;j++)
for( int k=0;k<=1;k++)
(*u)(ix+j,iy,iz+k) += dflux;
else
(*utop)(ixtop,iytop,iztop) = (*utop)(ixtop,iytop-1,iztop) + 2.0*flux;
}
// front boundary
if( iz == -1 && ix%2==0 && iy%2==0 )
{
flux = 0.0;
for( int j=0;j<=1;j++)
for( int k=0;k<=1;k++)
{
ustar1 = interp2( (*utop)(ixtop-1,iytop-1,iztop),(*utop)(ixtop,iytop-1,iztop),(*utop)(ixtop+1,iytop-1,iztop), fac*(j-0.5) );
ustar2 = interp2( (*utop)(ixtop-1,iytop,iztop),(*utop)(ixtop,iytop,iztop),(*utop)(ixtop+1,iytop,iztop), fac*(j-0.5) );
ustar3 = interp2( (*utop)(ixtop-1,iytop+1,iztop),(*utop)(ixtop,iytop+1,iztop),(*utop)(ixtop+1,iytop+1,iztop), fac*(j-0.5) );
uhat = interp2( -1.0, 0.0, 1.0, ustar1, ustar2, ustar3, fac*((double)k-0.5) );
//(*u)(ix+j,iy+k,iz) = 0.0;(*utop)(ixtop,iytop,iztop);//interp2( -1.5, 0.0, 1.0, uhat, (*u)(ix+j,iy+k,iz+1), (*u)(ix+j,iy+k,iz+2), -1.0 );
(*u)(ix+j,iy+k,iz) = interp2left( uhat, (*u)(ix+j,iy+k,iz+1), (*u)(ix+j,iy+k,iz+2) );
flux += ((*u)(ix+j,iy+k,iz+1)-(*u)(ix+j,iy+k,iz));
}
flux /= 4.0;
//(*utop)(ixtop,iytop,iztop) = (*utop)(ixtop,iytop,iztop+1) - flux;
double dflux = ((*utop)(ixtop,iytop,iztop+1)-(*utop)(ixtop,iytop,iztop))/2.0 - flux;
//dflux *= 2.0;
if( bcf )
for( int j=0;j<=1;j++)
for( int k=0;k<=1;k++)
(*u)(ix+j,iy+k,iz) -= dflux;
else
(*utop)(ixtop,iytop,iztop) = (*utop)(ixtop,iytop,iztop+1) - 2.0*flux;
}
// back boundary
if( iz == nz && ix%2==0 && iy%2==0 )
{
flux = 0.0;
for( int j=0;j<=1;j++)
for( int k=0;k<=1;k++)
{
ustar1 = interp2( (*utop)(ixtop-1,iytop-1,iztop),(*utop)(ixtop,iytop-1,iztop),(*utop)(ixtop+1,iytop-1,iztop), fac*(j-0.5) );
ustar2 = interp2( (*utop)(ixtop-1,iytop,iztop),(*utop)(ixtop,iytop,iztop),(*utop)(ixtop+1,iytop,iztop), fac*(j-0.5) );
ustar3 = interp2( (*utop)(ixtop-1,iytop+1,iztop),(*utop)(ixtop,iytop+1,iztop),(*utop)(ixtop+1,iytop+1,iztop), fac*(j-0.5) );
uhat = interp2( -1.0, 0.0, 1.0, ustar1, ustar2, ustar3, fac*((double)k-0.5) );
//(*u)(ix+j,iy+k,iz) = 0.0;(*utop)(ixtop,iytop,iztop);//interp2( 1.5, 0.0, -1.0, uhat, (*u)(ix+j,iy+k,iz-1), (*u)(ix+j,iy+k,iz-2), 1.0 );
(*u)(ix+j,iy+k,iz) = interp2right( (*u)(ix+j,iy+k,iz-2), (*u)(ix+j,iy+k,iz-1), uhat );
flux += ((*u)(ix+j,iy+k,iz)-(*u)(ix+j,iy+k,iz-1));
}
flux /= 4.0;
//(*utop)(ixtop,iytop,iztop) = (*utop)(ixtop,iytop,iztop-1) + flux;
double dflux = ((*utop)(ixtop,iytop,iztop)-(*utop)(ixtop,iytop,iztop-1))/2.0 - flux;
//dflux *= 2.0;
if( bcf )
for( int j=0;j<=1;j++)
for( int k=0;k<=1;k++)
(*u)(ix+j,iy+k,iz) += dflux;
else
(*utop)(ixtop,iytop,iztop) = (*utop)(ixtop,iytop,iztop-1) + 2.0*flux;
}
}
}
}
#if 1
template< class S, class O, typename T >
void solver<S,O,T>::setBC( unsigned ilevel )
{
//... set only on level before additional refinement starts
//if( ilevel == m_ilevelmin )
if( ilevel == m_ilevelmin )
{
MeshvarBnd<T> *u = m_pu->get_grid(ilevel);
//int nbnd = u->m_nbnd,
int
nx = u->size(0),
ny = u->size(1),
nz = u->size(2);
/*for( int ix=-nbnd; ix<nx+nbnd; ++ix )
for( int iy=-nbnd; iy<ny+nbnd; ++iy )
for( int iz=-nbnd; iz<nz+nbnd; ++iz )
if( ix<0||ix>=nx||iy<0||iy>=ny||iz<0||iz>=nz )
(*u)(ix,iy,iz) = (*m_pubnd)(ix,iy,iz);*/
for( int iy=0; iy<ny; ++iy )
for( int iz=0; iz<nz; ++iz )
{
(*u)(-1,iy,iz) = 2.0*(*m_pubnd)(-1,iy,iz) - (*u)(0,iy,iz);
(*u)(nx,iy,iz) = 2.0*(*m_pubnd)(nx,iy,iz) - (*u)(nx-1,iy,iz);;
}
for( int ix=0; ix<nx; ++ix )
for( int iz=0; iz<nz; ++iz )
{
(*u)(ix,-1,iz) = 2.0*(*m_pubnd)(ix,-1,iz) - (*u)(ix,0,iz);
(*u)(ix,ny,iz) = 2.0*(*m_pubnd)(ix,ny,iz) - (*u)(ix,ny-1,iz);
}
for( int ix=0; ix<nx; ++ix )
for( int iy=0; iy<ny; ++iy )
{
(*u)(ix,iy,-1) = 2.0*(*m_pubnd)(ix,iy,-1) - (*u)(ix,iy,0);
(*u)(ix,iy,nz) = 2.0*(*m_pubnd)(ix,iy,nz) - (*u)(ix,iy,nz-1);
}
}/*else if( ilevel < m_ilevelmin ) {
MeshvarBnd<T> *u = m_pu->get_grid(ilevel);
int nbnd = u->m_nbnd,
nx = u->size(0),
ny = u->size(1),
nz = u->size(2);
for( int ix=-nbnd; ix<nx+nbnd; ++ix )
for( int iy=-nbnd; iy<ny+nbnd; ++iy )
for( int iz=-nbnd; iz<nz+nbnd; ++iz )
if( ix<0||ix>=nx||iy<0||iy>=ny||iz<0||iz>=nz )
(*u)(ix,iy,iz) = 0.0;
}*/
}
#else
//... enforce periodic boundary conditions
template< class S, class O, typename T >
void solver<S,O,T>::setBC( unsigned ilevel )
{
MeshvarBnd<T> *u = m_pu->get_grid(ilevel);
//... set only on level before additional refinement starts
if( ilevel <= m_ilevelmin )
{
int nbnd = u->m_nbnd,
nx = u->size(0),
ny = u->size(1),
nz = u->size(2);
//(*u)(0,0,0) = 0.0;
double sum = 0.0;
for( int ix=0; ix<nx; ++ix )
for( int iy=0; iy<ny; ++iy )
for( int iz=0; iz<nz; ++iz )
sum += (*u)(ix,iy,iz);
sum /= (nx*ny*nz);
for( int ix=0; ix<nx; ++ix )
for( int iy=0; iy<ny; ++iy )
for( int iz=0; iz<nz; ++iz )
(*u)(ix,iy,iz) -= sum;
for( int iy=0; iy<ny; ++iy )
for( int iz=0; iz<nz; ++iz )
{
(*u)(-1,iy,iz) = (*u)(nx-1,iy,iz);
(*u)(nx,iy,iz) = (*u)(0,iy,iz);
}
for( int ix=0; ix<nx; ++ix )
for( int iz=0; iz<nz; ++iz )
{
(*u)(ix,-1,iz) = (*u)(ix,ny-1,iz);
(*u)(ix,ny,iz) = (*u)(ix,0,iz);
}
for( int ix=0; ix<nx; ++ix )
for( int iy=0; iy<ny; ++iy )
{
(*u)(ix,iy,-1) = (*u)(ix,iy,nz-1);
(*u)(ix,iy,nz) = (*u)(ix,iy,0);
}
}
}
#endif
//... enforce periodic boundary conditions
template< class S, class O, typename T >
void solver<S,O,T>::make_periodic( MeshvarBnd<T> *u )
{
int
nx = u->size(0),
ny = u->size(1),
nz = u->size(2);
#pragma omp parallel
{
if( u->offset(0) == 0 )
for( int iy=0; iy<ny; ++iy )
for( int iz=0; iz<nz; ++iz )
{
(*u)(-1,iy,iz) = (*u)(nx-1,iy,iz);
(*u)(nx,iy,iz) = (*u)(0,iy,iz);
}
if( u->offset(1) == 0 )
for( int ix=0; ix<nx; ++ix )
for( int iz=0; iz<nz; ++iz )
{
(*u)(ix,-1,iz) = (*u)(ix,ny-1,iz);
(*u)(ix,ny,iz) = (*u)(ix,0,iz);
}
if( u->offset(2) == 0 )
for( int ix=0; ix<nx; ++ix )
for( int iy=0; iy<ny; ++iy )
{
(*u)(ix,iy,-1) = (*u)(ix,iy,nz-1);
(*u)(ix,iy,nz) = (*u)(ix,iy,0);
}
}
}
END_MULTIGRID_NAMESPACE
#endif
| 77.011701 | 4,996 | 0.64252 | [
"mesh"
] |
149606c121f483041afd9c88e5b6acc11b93f42e | 4,509 | cpp | C++ | src/classifier/classifier.cpp | amtf1683/U-Net | ec203834f1d0ffbbcffea6d7c3e3113c32a20fbc | [
"MIT"
] | 3 | 2020-08-19T09:20:26.000Z | 2020-11-19T10:11:24.000Z | src/classifier/classifier.cpp | hyterazzb/U-Net | ec203834f1d0ffbbcffea6d7c3e3113c32a20fbc | [
"MIT"
] | null | null | null | src/classifier/classifier.cpp | hyterazzb/U-Net | ec203834f1d0ffbbcffea6d7c3e3113c32a20fbc | [
"MIT"
] | 1 | 2022-02-24T07:58:50.000Z | 2022-02-24T07:58:50.000Z | #include "classifier.h"
#include <algorithm>
#include <iostream>
#include "opencv2/imgproc.hpp"
#include "opencv2/opencv.hpp"
namespace mirror {
Classifier::Classifier() {
labels_.clear();
initialized_ = false;
topk_ = 5;
}
Classifier::~Classifier() {
classifier_interpreter_->releaseModel();
classifier_interpreter_->releaseSession(classifier_sess_);
}
int Classifier::Init(const char* root_path) {
std::cout << "start Init." << std::endl;
std::string model_file = std::string(root_path) + "/unet_e300_755_475_pruned.mnn";
std::cout << "4234242342342:" << model_file << std::endl;
classifier_interpreter_ = std::shared_ptr<MNN::Interpreter>(MNN::Interpreter::createFromFile(model_file.c_str()));
if (!classifier_interpreter_ || LoadLabels(root_path) != 0) {
std::cout << "load model failed." << std::endl;
return 10000;
}
MNN::ScheduleConfig schedule_config;
schedule_config.type = MNN_FORWARD_CPU;
schedule_config.numThread = 1;
MNN::BackendConfig backend_config;
backend_config.precision = MNN::BackendConfig::Precision_High;
schedule_config.backendConfig = &backend_config;
classifier_sess_ = classifier_interpreter_->createSession(schedule_config);
input_tensor_ = classifier_interpreter_->getSessionInput(classifier_sess_, nullptr);
classifier_interpreter_->resizeTensor(input_tensor_, {1, 3, inputSize_.height, inputSize_.width});
classifier_interpreter_->resizeSession(classifier_sess_);
std::cout << "End Init." << std::endl;
initialized_ = true;
return 0;
}
int Classifier::Classify(const cv::Mat& img_src, std::vector<ImageInfo>* images) {
std::cout << "start classify." << std::endl;
images->clear();
if (!initialized_) {
std::cout << "model uninitialized." << std::endl;
return 10000;
}
if (img_src.empty()) {
std::cout << "input empty." << std::endl;
return 10001;
}
cv::Mat img_resized;
cv::resize(img_src.clone(), img_resized, inputSize_);
std::shared_ptr<MNN::CV::ImageProcess> pretreat(
MNN::CV::ImageProcess::create(MNN::CV::BGR, MNN::CV::RGB, meanVals, 3, normVals, 3)
);
pretreat->convert((uint8_t*)img_resized.data, inputSize_.width, inputSize_.height, img_resized.step[0], input_tensor_);
// forward
classifier_interpreter_->runSession(classifier_sess_);
// get output
// mobilenet: "classifierV1/Predictions/Reshape_1"
MNN::Tensor* output_score = classifier_interpreter_->getSessionOutput(classifier_sess_, nullptr);
printf("output_tensor_chaneel:%d width:%d height:%d\n", output_score->channel(), output_score->width(), output_score->height());
// copy to host
MNN::Tensor score_host(output_score, output_score->getDimensionType());
output_score->copyToHostTensor(&score_host);
auto score_ptr = score_host.host<float>();
// for(int i = 0; i < 476*756; i++)
// {
// printf("score_ptr[%d]:%f\n", i, score_ptr[i]);
// }
uchar * temp_buffer = NULL;
temp_buffer = (uchar* )malloc(476*756);
memset(temp_buffer, 0, 476*756);
for(int i = 0; i < 476*756; i++)
{
temp_buffer[i] = (uchar)(score_ptr[i]*255);
}
cv::Mat out_mat(476,756,CV_8UC1);
out_mat.data = temp_buffer;
cv::imwrite("unet_output.jpg", out_mat);
return 0;
std::vector<std::pair<float, int>> scores;
for (int i = 0; i < 1000; ++i) {
float score = score_ptr[i];
scores.push_back(std::make_pair(score, i));
}
std::partial_sort(scores.begin(), scores.begin() + topk_, scores.end(), std::greater< std::pair<float, int> >());
for (int i = 0; i < topk_; ++i) {
ImageInfo image_info;
image_info.label_ = labels_[scores[i].second];
image_info.score_ = scores[i].first;
images->push_back(image_info);
}
std::cout << "end classify." << std::endl;
return 0;
}
int Classifier::LoadLabels(const char* root_path) {
std::string label_file = std::string(root_path) + "/label.txt";
FILE* fp = fopen(label_file.c_str(), "r");
while (!feof(fp)) {
char str[1024];
if (fgets(str, 1024, fp) == nullptr) continue;
std::string str_s(str);
if (str_s.length() > 0) {
for (int i = 0; i < str_s.length(); i++) {
if (str_s[i] == ' ') {
std::string strr = str_s.substr(i, str_s.length() - i - 1);
labels_.push_back(strr);
i = str_s.length();
}
}
}
}
return 0;
}
}
| 31.3125 | 132 | 0.643602 | [
"vector",
"model"
] |
149654e2c27bbe796542b6ae9b8eb832f82f0b54 | 7,817 | hpp | C++ | indexed_bzip2/BitReader.hpp | hyanwong/indexed_bzip2 | 95881dda01804214c81f8918e6f0fc73e9b39911 | [
"MIT"
] | null | null | null | indexed_bzip2/BitReader.hpp | hyanwong/indexed_bzip2 | 95881dda01804214c81f8918e6f0fc73e9b39911 | [
"MIT"
] | null | null | null | indexed_bzip2/BitReader.hpp | hyanwong/indexed_bzip2 | 95881dda01804214c81f8918e6f0fc73e9b39911 | [
"MIT"
] | null | null | null | #pragma once
#include <stdint.h>
#include <stdio.h>
#include <cassert>
#include <cstddef>
#include <stdexcept>
#include <sstream>
#include <string>
#include <vector>
#include <unistd.h>
#include <sys/stat.h>
#include "FileReader.hpp"
class BitReader :
public FileReader
{
public:
static constexpr size_t IOBUF_SIZE = 4096;
static constexpr int NO_FILE = -1;
public:
explicit
BitReader( std::string filePath ) :
m_file( fopen( filePath.c_str(), "rb" ) )
{
init();
}
explicit
BitReader( int fileDescriptor ) :
m_file( fdopen( dup( fileDescriptor ), "rb" ) )
{
init();
}
BitReader( const uint8_t* buffer,
size_t size ) :
m_fileSizeBytes( size ),
m_inbuf( buffer, buffer + size )
{}
BitReader( BitReader&& ) = default;
/**
* Copy constructor opens a new independent file descriptor and pointer.
*/
BitReader( const BitReader& other ) :
m_file( other.m_file == nullptr ? nullptr : fdopen( dup( ::fileno( other.m_file ) ), "rb" ) )
{}
/**
* Reassignment would have to close the old file and open a new.
* Reusing the same file reader for a different file seems error prone.
* If you really want that, just create a new object.
*/
BitReader& operator=( const BitReader& ) = delete;
BitReader& operator=( BitReader&& ) = delete;
~BitReader()
{
if ( m_file != nullptr ) {
fclose( m_file );
}
}
bool
eof() const override
{
return m_seekable ? tell() >= size() : !m_lastReadSuccessful;
}
bool
seekable() const override
{
return m_seekable;
}
void
close() override
{
fclose( fp() );
m_file = nullptr;
m_inbuf.clear();
}
bool
closed() const override
{
return ( m_file == nullptr ) && m_inbuf.empty();
}
uint32_t
read( uint8_t );
/**
* @return current position / number of bits already read.
*/
size_t
tell() const override
{
if ( m_seekable ) {
return ( ftell( fp() ) - m_inbuf.size() + m_inbufPos ) * 8ULL - m_inbufBitCount;
}
return m_readBitsCount;
}
FILE*
fp() const
{
return m_file;
}
int
fileno() const override
{
if ( m_file == nullptr ) {
throw std::invalid_argument( "The file is not open!" );
}
return ::fileno( m_file );
}
size_t
seek( long long int offsetBits,
int origin = SEEK_SET ) override;
size_t
size() const override
{
return m_fileSizeBytes * 8;
}
private:
void
init()
{
struct stat fileStats;
fstat( fileno(), &fileStats );
m_seekable = !S_ISFIFO( fileStats.st_mode );
m_fileSizeBytes = fileStats.st_size;
if ( m_seekable ) {
fseek( fp(), 0, SEEK_SET );
}
}
private:
FILE* m_file = nullptr;
bool m_seekable = true;
size_t m_fileSizeBytes = 0;
std::vector<uint8_t> m_inbuf;
uint32_t m_inbufPos = 0; /** stores current position of first valid byte in buffer */
bool m_lastReadSuccessful = true;
public:
/**
* Bit buffer stores the last read bits from m_inbuf.
* The bits are to be read from left to right. This means that not the least significant n bits
* are to be returned on read but the most significant.
* E.g. return 3 bits of 1011 1001 should return 101 not 001
*/
uint32_t m_inbufBits = 0;
uint8_t m_inbufBitCount = 0; // size of bitbuffer in bits
size_t m_readBitsCount = 0;
};
inline uint32_t
BitReader::read( const uint8_t bits_wanted )
{
uint32_t bits = 0;
assert( bits_wanted <= sizeof( bits ) * 8 );
m_readBitsCount += bits_wanted;
// If we need to get more data from the byte buffer, do so. (Loop getting
// one byte at a time to enforce endianness and avoid unaligned access.)
auto bitsNeeded = bits_wanted;
while ( m_inbufBitCount < bitsNeeded ) {
// If we need to read more data from file into byte buffer, do so
if ( m_inbufPos == m_inbuf.size() ) {
m_inbuf.resize( IOBUF_SIZE );
const auto nBytesRead = fread( m_inbuf.data(), 1, m_inbuf.size(), m_file );
if ( nBytesRead < m_inbuf.size() ) {
m_lastReadSuccessful = false;
}
if ( nBytesRead <= 0 ) {
// this will also happen for invalid file descriptor -1
std::stringstream msg;
msg
<< "[BitReader] Not enough data to read!\n"
<< " File pointer: " << (void*)m_file << "\n"
<< " File position: " << ftell( m_file ) << "\n"
<< " Input buffer size: " << m_inbuf.size() << "\n"
<< "\n";
throw std::domain_error( msg.str() );
}
m_inbuf.resize( nBytesRead );
m_inbufPos = 0;
}
// Avoid 32-bit overflow (dump bit buffer to top of output)
if ( m_inbufBitCount >= 24 ) {
bits = m_inbufBits & ( ( 1 << m_inbufBitCount ) - 1 );
bitsNeeded -= m_inbufBitCount;
bits <<= bitsNeeded;
m_inbufBitCount = 0;
}
// Grab next 8 bits of input from buffer.
m_inbufBits = ( m_inbufBits << 8 ) | m_inbuf[m_inbufPos++];
m_inbufBitCount += 8;
}
// Calculate result
m_inbufBitCount -= bitsNeeded;
bits |= ( m_inbufBits >> m_inbufBitCount ) & ( ( 1 << bitsNeeded ) - 1 );
assert( bits == ( bits & ( ~0L >> ( 32 - bits_wanted ) ) ) );
return bits;
}
inline size_t
BitReader::seek( long long int offsetBits,
int origin )
{
switch ( origin )
{
case SEEK_CUR:
offsetBits = tell() + offsetBits;
break;
case SEEK_SET:
break;
case SEEK_END:
offsetBits = size() + offsetBits;
break;
}
if ( static_cast<size_t>( offsetBits ) == tell() ) {
return offsetBits;
}
if ( offsetBits < 0 ) {
throw std::invalid_argument( "Effective offset is before file start!" );
}
if ( static_cast<size_t>( offsetBits ) >= size() ) {
throw std::invalid_argument( "Effective offset is after file end!" );
}
if ( !m_seekable ) {
throw std::invalid_argument( "File is not seekable!" );
}
const size_t bytesToSeek = offsetBits >> 3;
const size_t subBitsToSeek = offsetBits & 7;
m_inbuf.clear();
m_inbufPos = 0;
m_inbufBits = 0;
m_inbufBitCount = 0;
if ( m_file == nullptr ) {
if ( bytesToSeek >= m_inbuf.size() ) {
std::stringstream msg;
msg << "[BitReader] Could not seek to specified byte " << bytesToSeek;
std::invalid_argument( msg.str() );
}
m_inbufPos = bytesToSeek;
if ( subBitsToSeek > 0 ) {
m_inbufBitCount = 8 - subBitsToSeek;
m_inbufBits = m_inbuf[m_inbufPos++];
}
} else {
const auto returnCodeSeek = fseek( m_file, bytesToSeek, SEEK_SET );
if ( subBitsToSeek > 0 ) {
m_inbufBitCount = 8 - subBitsToSeek;
m_inbufBits = fgetc( m_file );
}
if ( ( returnCodeSeek != 0 ) || feof( m_file ) || ferror( m_file ) ) {
std::stringstream msg;
msg << "[BitReader] Could not seek to specified byte " << bytesToSeek
<< " subbit " << subBitsToSeek << ", feof: " << feof( m_file ) << ", ferror: " << ferror( m_file )
<< ", returnCodeSeek: " << returnCodeSeek;
throw std::invalid_argument( msg.str() );
}
}
return offsetBits;
}
| 26.231544 | 110 | 0.552642 | [
"object",
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.