hexsha stringlengths 40 40 | size int64 22 2.4M | ext stringclasses 5
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 260 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 78 | 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 260 | max_issues_repo_name stringlengths 5 109 | 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 260 | max_forks_repo_name stringlengths 5 109 | 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 22 2.4M | avg_line_length float64 5 169k | max_line_length int64 5 786k | alphanum_fraction float64 0.06 0.95 | matches listlengths 1 11 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e564a24d5577d40e9efbdef69aab9ce617ca8016 | 1,469 | h | C | src/Linear/ObjectiveFunction.h | alibabach/deformabletracker | 1ef5631f7d91488da27abd83b468e2668670ad9d | [
"BSD-2-Clause-FreeBSD"
] | 29 | 2015-09-07T17:51:22.000Z | 2022-01-14T08:48:11.000Z | src/Linear/ObjectiveFunction.h | alibabach/deformabletracker | 1ef5631f7d91488da27abd83b468e2668670ad9d | [
"BSD-2-Clause-FreeBSD"
] | 1 | 2017-12-07T07:58:19.000Z | 2017-12-07T09:26:39.000Z | src/Linear/ObjectiveFunction.h | alibabach/deformabletracker | 1ef5631f7d91488da27abd83b468e2668670ad9d | [
"BSD-2-Clause-FreeBSD"
] | 5 | 2016-08-10T05:16:18.000Z | 2020-12-30T20:13:31.000Z | //////////////////////////////////////////////////////////////////////////
// Author : Ngo Tien Dat
// Email : dat.ngo@epfl.ch
// Organization : EPFL
// Purpose : Objective function f: R^m --> R^n
// f(x) = A*x - b
// Used to pass function as parameter into an algorithm
// Date : 26 March 2012
//////////////////////////////////////////////////////////////////////////
#pragma once
#include "Function.h"
class ObjectiveFunction : public Function
{
private:
const arma::mat& MP; // Matrix MP that compute projection error MP*x
// We use const & to avoid deep object copying
float alpha;
arma::vec xPrev;
bool useTemporal; // Use temporal consistency or not
public:
// Constructor that initializes the reference variable MP.
// xPrev is initialized to avoid error messages, it is not used in this function.
ObjectiveFunction (const arma::mat& MPmat);
// Constructor that initializes the reference variable MP and
// take temporal consistency constraints as an objective too
// MP * x = 0
// alpha * I * (x - xPrev) = 0
ObjectiveFunction (const arma::mat& MPmat, const float alpha, const arma::vec& xPrev);
// Implement the pure virtual function declared in the parent class
// Update F and J
// This objective function has the form F = A * x
virtual void Evaluate(const arma::vec& x );
};
| 29.38 | 89 | 0.562968 | [
"object"
] |
e56dcdbde14de06f0d00914b2549fdc47109fe9d | 1,053 | h | C | progressivebuffer.h | kevinlul/ygopro-core | 0006d49bbcdf4ff35e850dc2593f5bdae1f98270 | [
"MIT"
] | null | null | null | progressivebuffer.h | kevinlul/ygopro-core | 0006d49bbcdf4ff35e850dc2593f5bdae1f98270 | [
"MIT"
] | null | null | null | progressivebuffer.h | kevinlul/ygopro-core | 0006d49bbcdf4ff35e850dc2593f5bdae1f98270 | [
"MIT"
] | null | null | null | /*
* progressivebuffer.h
*
* Created on: 16/3/2019
* Author: edo9300
*/
#ifndef PROGRESSIVEBUFFER_H_
#define PROGRESSIVEBUFFER_H_
#include <cmath>
#include <vector>
class ProgressiveBuffer {
public:
std::vector<uint8_t> data;
ProgressiveBuffer() {};
void clear() {
data.clear();
}
template<class T>
T& at(const size_t _Pos) {
auto valsize = sizeof(T);
size_t size = (_Pos + 1) * valsize;
if(data.size() < size)
data.resize(size);
return *(T*)(data.data() + _Pos * valsize);
}
bool bitGet(const size_t _Pos) {
int pos = std::floor(_Pos / 8);
int index = _Pos % 8;
size_t size = pos + 1;
if(data.size() < size) {
data.resize(size);
return false;
}
return !!(data[pos] & (1 << index));
}
void bitSet(const size_t _Pos, bool set = true) {
int pos = std::floor(_Pos / 8);
int index = _Pos % 8;
size_t size = pos + 1;
if(data.size() < size) {
data.resize(size);
}
if(set)
data[pos] |= (1 << index);
else {
data[pos] &= ~(1 << index);
}
}
};
#endif /* PROGRESSIVEBUFFER_H_ */
| 18.473684 | 50 | 0.60019 | [
"vector"
] |
e56edba187ebbf68ddc479b0d47a7c09c0a806e0 | 9,269 | c | C | ext/libxml/ruby_xml_schema.c | d-hansen/libxml-ruby | 1aef72acaad091ac6d112d607527dc870c6a5a03 | [
"MIT"
] | null | null | null | ext/libxml/ruby_xml_schema.c | d-hansen/libxml-ruby | 1aef72acaad091ac6d112d607527dc870c6a5a03 | [
"MIT"
] | null | null | null | ext/libxml/ruby_xml_schema.c | d-hansen/libxml-ruby | 1aef72acaad091ac6d112d607527dc870c6a5a03 | [
"MIT"
] | null | null | null | #include "ruby_libxml.h"
#define LIBXML_OUTPUT_ENABLED
#define DUMP_CONTENT_MODEL
#include "ruby_xml_schema.h"
#include "ruby_xml_schema_type.h"
#include "ruby_xml_schema_element.h"
#include "ruby_xml_schema_attribute.h"
#include "ruby_xml_schema_facet.h"
/*
* Document-class: LibXML::XML::Schema
*
* The XML::Schema class is used to prepare XML Schemas for validation of xml
* documents.
*
* Schemas can be created from XML documents, strinings or URIs using the
* corresponding methods (new for URIs).
*
* Once a schema is prepared, an XML document can be validated by the
* XML::Document#validate_schema method providing the XML::Schema object
* as parameter. The method return true if the document validates, false
* otherwise.
*
* Basic usage:
*
* # parse schema as xml document
* schema_document = XML::Document.file('schema.rng')
*
* # prepare schema for validation
* schema = XML::Schema.document(schema_document)
*
* # parse xml document to be validated
* instance = XML::Document.file('instance.xml')
*
* # validate
* instance.validate_schema(schema)
*/
VALUE cXMLSchema;
static void rxml_schema_free(xmlSchemaPtr xschema)
{
xmlSchemaFree(xschema);
}
VALUE rxml_wrap_schema(xmlSchemaPtr xschema)
{
VALUE result;
if (!xschema)
rb_raise(rb_eArgError, "XML::Schema is required!");
result = Data_Wrap_Struct(cXMLSchema, NULL, rxml_schema_free, xschema);
/*
* Create these as instance variables to provide the output of inspect/to_str some
* idea of what schema this class contains.
*/
rb_iv_set(result, "@target_namespace", QNIL_OR_STRING(xschema->targetNamespace));
rb_iv_set(result, "@name", QNIL_OR_STRING(xschema->name));
rb_iv_set(result, "@id", QNIL_OR_STRING(xschema->id));
rb_iv_set(result, "@version", QNIL_OR_STRING(xschema->name));
return result;
}
static VALUE rxml_schema_init(VALUE class, xmlSchemaParserCtxtPtr xparser)
{
xmlSchemaPtr xschema;
xschema = xmlSchemaParse(xparser);
xmlSchemaFreeParserCtxt(xparser);
if (!xschema)
rxml_raise(&xmlLastError);
return rxml_wrap_schema(xschema);
}
/*
* call-seq:
* XML::Schema.initialize(schema_uri) -> schema
*
* Create a new schema from the specified URI.
*/
static VALUE rxml_schema_init_from_uri(VALUE class, VALUE uri)
{
xmlSchemaParserCtxtPtr xparser;
Check_Type(uri, T_STRING);
xmlResetLastError();
xparser = xmlSchemaNewParserCtxt(StringValuePtr(uri));
if (!xparser)
rxml_raise(&xmlLastError);
return rxml_schema_init(class, xparser);
}
/*
* call-seq:
* XML::Schema.document(document) -> schema
*
* Create a new schema from the specified document.
*/
static VALUE rxml_schema_init_from_document(VALUE class, VALUE document)
{
xmlDocPtr xdoc;
xmlSchemaParserCtxtPtr xparser;
Data_Get_Struct(document, xmlDoc, xdoc);
xmlResetLastError();
xparser = xmlSchemaNewDocParserCtxt(xdoc);
if (!xparser)
rxml_raise(&xmlLastError);
return rxml_schema_init(class, xparser);
}
/*
* call-seq:
* XML::Schema.from_string("schema_data") -> "value"
*
* Create a new schema using the specified string.
*/
static VALUE rxml_schema_init_from_string(VALUE class, VALUE schema_str)
{
xmlSchemaParserCtxtPtr xparser;
Check_Type(schema_str, T_STRING);
xmlResetLastError();
xparser = xmlSchemaNewMemParserCtxt(StringValuePtr(schema_str), (int)strlen(StringValuePtr(schema_str)));
if (!xparser)
rxml_raise(&xmlLastError);
return rxml_schema_init(class, xparser);
}
/*
* call-seq:
* XML::Schema.document -> document
*
* Return the Schema XML Document
*/
static VALUE rxml_schema_document(VALUE self)
{
xmlSchemaPtr xschema;
Data_Get_Struct(self, xmlSchema, xschema);
return rxml_node_wrap(xmlDocGetRootElement(xschema->doc));
}
static void scan_namespaces(xmlSchemaImportPtr ximport, VALUE array, const xmlChar *nsname)
{
xmlNodePtr xnode;
xmlNsPtr xns;
if (ximport->doc)
{
xnode = xmlDocGetRootElement(ximport->doc);
xns = xnode->nsDef;
while (xns)
{
VALUE namespace = rxml_namespace_wrap(xns);
rb_ary_push(array, namespace);
xns = xns->next;
}
}
}
/*
* call-seq:
* XML::Schema.namespaces -> array
*
* Returns an array of Namespaces defined by the schema
*/
static VALUE rxml_schema_namespaces(VALUE self)
{
VALUE result;
xmlSchemaPtr xschema;
Data_Get_Struct(self, xmlSchema, xschema);
result = rb_ary_new();
xmlHashScan(xschema->schemasImports, (xmlHashScanner)scan_namespaces, (void *)result);
return result;
}
static void scan_schema_element(xmlSchemaElementPtr xelement, VALUE hash, const xmlChar *name)
{
VALUE element = rxml_wrap_schema_element(xelement);
rb_hash_aset(hash, rb_str_new2((const char*)name), element);
}
static VALUE rxml_schema_elements(VALUE self)
{
VALUE result = rb_hash_new();
xmlSchemaPtr xschema;
Data_Get_Struct(self, xmlSchema, xschema);
xmlHashScan(xschema->elemDecl, (xmlHashScanner)scan_schema_element, (void *)result);
return result;
}
static void collect_imported_ns_elements(xmlSchemaImportPtr import, VALUE result, const xmlChar *name)
{
if (import->imported && import->schema)
{
VALUE elements = rb_hash_new();
xmlHashScan(import->schema->elemDecl, (xmlHashScanner)scan_schema_element, (void *)elements);
rb_hash_aset(result, QNIL_OR_STRING(import->schema->targetNamespace), elements);
}
}
/*
* call-seq:
* XML::Schema.imported_ns_elements -> hash
*
* Returns a hash by namespace of a hash of schema elements within the entire schema including imports
*/
static VALUE rxml_schema_imported_ns_elements(VALUE self)
{
xmlSchemaPtr xschema;
VALUE result = rb_hash_new();
Data_Get_Struct(self, xmlSchema, xschema);
if (xschema)
{
xmlHashScan(xschema->schemasImports, (xmlHashScanner)collect_imported_ns_elements, (void *)result);
}
return result;
}
static void scan_schema_type(xmlSchemaTypePtr xtype, VALUE hash, const xmlChar *name)
{
VALUE type = rxml_wrap_schema_type(xtype);
rb_hash_aset(hash, rb_str_new2((const char*)name), type);
}
static VALUE rxml_schema_types(VALUE self)
{
VALUE result = rb_hash_new();
xmlSchemaPtr xschema;
Data_Get_Struct(self, xmlSchema, xschema);
if (xschema != NULL && xschema->typeDecl != NULL)
{
xmlHashScan(xschema->typeDecl, (xmlHashScanner)scan_schema_type, (void *)result);
}
return result;
}
static void collect_imported_types(xmlSchemaImportPtr import, VALUE result, const xmlChar *name)
{
if (import->imported && import->schema)
{
xmlHashScan(import->schema->typeDecl, (xmlHashScanner)scan_schema_type, (void *)result);
}
}
/*
* call-seq:
* XML::Schema.imported_types -> hash
*
* Returns a hash of all types within the entire schema including imports
*/
static VALUE rxml_schema_imported_types(VALUE self)
{
xmlSchemaPtr xschema;
VALUE result = rb_hash_new();
Data_Get_Struct(self, xmlSchema, xschema);
if (xschema)
{
xmlHashScan(xschema->schemasImports, (xmlHashScanner)collect_imported_types, (void *)result);
}
return result;
}
static void collect_imported_ns_types(xmlSchemaImportPtr import, VALUE result, const xmlChar *name)
{
if (import->imported && import->schema)
{
VALUE types = rb_hash_new();
xmlHashScan(import->schema->typeDecl, (xmlHashScanner)scan_schema_type, (void *)types);
rb_hash_aset(result, QNIL_OR_STRING(import->schema->targetNamespace), types);
}
}
/*
* call-seq:
* XML::Schema.imported_ns_types -> hash
*
* Returns a hash by namespace of a hash of schema types within the entire schema including imports
*/
static VALUE rxml_schema_imported_ns_types(VALUE self)
{
xmlSchemaPtr xschema;
VALUE result = rb_hash_new();
Data_Get_Struct(self, xmlSchema, xschema);
if (xschema)
{
xmlHashScan(xschema->schemasImports, (xmlHashScanner)collect_imported_ns_types, (void *)result);
}
return result;
}
void rxml_init_schema(void)
{
cXMLSchema = rb_define_class_under(mXML, "Schema", rb_cObject);
rb_define_singleton_method(cXMLSchema, "new", rxml_schema_init_from_uri, 1);
rb_define_singleton_method(cXMLSchema, "from_string", rxml_schema_init_from_string, 1);
rb_define_singleton_method(cXMLSchema, "document", rxml_schema_init_from_document, 1);
/* Create attr_reader methods for the above instance variables */
rb_define_attr(cXMLSchema, "target_namespace", 1, 0);
rb_define_attr(cXMLSchema, "name", 1, 0);
rb_define_attr(cXMLSchema, "id", 1, 0);
rb_define_attr(cXMLSchema, "version", 1, 0);
// These are just methods so as to hide their values and not overly clutter the output of inspect/to_str
rb_define_method(cXMLSchema, "document", rxml_schema_document, 0);
rb_define_method(cXMLSchema, "namespaces", rxml_schema_namespaces, 0);
rb_define_method(cXMLSchema, "elements", rxml_schema_elements, 0);
rb_define_method(cXMLSchema, "imported_ns_elements", rxml_schema_imported_ns_elements, 0);
rb_define_method(cXMLSchema, "types", rxml_schema_types, 0);
rb_define_method(cXMLSchema, "imported_types", rxml_schema_imported_types, 0);
rb_define_method(cXMLSchema, "imported_ns_types", rxml_schema_imported_ns_types, 0);
rxml_init_schema_facet();
rxml_init_schema_element();
rxml_init_schema_attribute();
rxml_init_schema_type();
}
| 26.407407 | 107 | 0.743338 | [
"object"
] |
e57e5bdae11715f44102db3ae6a307f17f76bb6e | 1,793 | h | C | syncer/client/encoded_msg_map.h | wahidHarb/rdp-1 | 73a0813d9a08f0aad34b56ba678167e6387b5e74 | [
"Apache-2.0"
] | 112 | 2018-12-05T07:45:42.000Z | 2022-01-24T11:28:11.000Z | syncer/client/encoded_msg_map.h | wahidHarb/rdp-1 | 73a0813d9a08f0aad34b56ba678167e6387b5e74 | [
"Apache-2.0"
] | 2 | 2020-02-29T02:34:59.000Z | 2020-05-12T06:34:29.000Z | syncer/client/encoded_msg_map.h | wahidHarb/rdp-1 | 73a0813d9a08f0aad34b56ba678167e6387b5e74 | [
"Apache-2.0"
] | 88 | 2018-12-16T07:35:10.000Z | 2022-03-09T17:41:16.000Z | //
//Copyright 2018 vip.com.
//
//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.
//
#ifndef _ENCODED_MSG_MAP_H_
#define _ENCODED_MSG_MAP_H_
#include <rdp-comm/signal_handler.h>
#include <rdp-comm/logger.h>
#include "syncer_conf.h"
#include "syncer_incl.h"
#include "statistics_writer.h"
#include "split_package.h"
namespace syncer {
class EncodedMsgMap {
typedef std::map<uint64_t, void *> MsgMap;
enum {
DEF_MAX_MSG_SIZE = 50000
};
public:
explicit EncodedMsgMap(void);
~EncodedMsgMap(void);
public:
// \brief AddMsg Push an encoded msg to map
//
// \param seq_no
// \param msg
void AddMsg(uint64_t seq_no, void *msg);
// \brief PopMsg Pop an encoded msg from map
//
// \param seq_no
//
// \return
void PopMsg(uint64_t seq_no, vector<SeqTrans *> &seq_trans,
const int max_trans);
// \brief GetMsgSize Get msg size
//
// \return
size_t GetMsgSize(void);
// \brief SetCapacity set capacity_
//
// \param uint32_t
void SetCapacity(const uint32_t capacity);
private:
MsgMap msg_map_;
private:
pthread_cond_t add_cond_;
pthread_cond_t empty_cond_;
pthread_mutex_t mutex_;
uint64_t wait_seq_no_;
uint32_t capacity_;
};
extern EncodedMsgMap g_encode_msg_map;
} // namespace syncer
#endif // _ENCODED_MSG_MAP_H_
| 22.4125 | 117 | 0.721695 | [
"vector"
] |
e580ddff706d6053922173b4d48a44550972a651 | 1,343 | h | C | third_party/spirv-tools/test/val/val_code_generator.h | Alan-love/filament | 87ee5783b7f72bb5b045d9334d719ea2de9f5247 | [
"Apache-2.0"
] | 20 | 2019-04-18T07:37:34.000Z | 2022-02-02T21:43:47.000Z | test/val/val_code_generator.h | indrarahul2013/SPIRV-Tools | 636f449e1529a10d259eb7dc37d97192cf2820f8 | [
"Apache-2.0"
] | 11 | 2019-10-21T13:39:41.000Z | 2021-11-05T08:11:54.000Z | test/val/val_code_generator.h | indrarahul2013/SPIRV-Tools | 636f449e1529a10d259eb7dc37d97192cf2820f8 | [
"Apache-2.0"
] | 9 | 2021-07-21T10:53:59.000Z | 2022-03-03T10:27:33.000Z | // Copyright (c) 2019 Google LLC.
//
// 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.
// Utility class used to generate SPIR-V code strings for tests
#include <string>
#include <vector>
namespace spvtools {
namespace val {
struct EntryPoint {
std::string name;
std::string execution_model;
std::string execution_modes;
std::string body;
std::string interfaces;
};
class CodeGenerator {
public:
static CodeGenerator GetDefaultShaderCodeGenerator();
static CodeGenerator GetWebGPUShaderCodeGenerator();
std::string Build() const;
std::vector<EntryPoint> entry_points_;
std::string capabilities_;
std::string extensions_;
std::string memory_model_;
std::string before_types_;
std::string types_;
std::string after_types_;
std::string add_at_the_end_;
};
} // namespace val
} // namespace spvtools
| 26.86 | 75 | 0.743112 | [
"vector"
] |
e58ad5adb1da49da3db6c5481f4e5712a34c0b3c | 2,132 | h | C | include/AST/ASTNodeBase.h | fly-lang/fly | 4c219c5c5cdb16a8d341de28a1e15f1109c7cfdf | [
"Apache-2.0"
] | 3 | 2021-01-29T09:00:19.000Z | 2021-08-29T18:36:35.000Z | include/AST/ASTNodeBase.h | fly-lang/fly | 4c219c5c5cdb16a8d341de28a1e15f1109c7cfdf | [
"Apache-2.0"
] | 30 | 2021-02-07T23:19:05.000Z | 2022-03-23T10:28:55.000Z | include/AST/ASTNodeBase.h | fly-lang/fly | 4c219c5c5cdb16a8d341de28a1e15f1109c7cfdf | [
"Apache-2.0"
] | 2 | 2022-02-18T02:51:54.000Z | 2022-03-29T20:48:32.000Z | //===--------------------------------------------------------------------------------------------------------------===//
// include/AST/ASTNodeBase.h - Base AST Node
//
// Part of the Fly Project https://flylang.org
// Under the Apache License v2.0 see LICENSE for details.
// Thank you to LLVM Project https://llvm.org/
//
//===--------------------------------------------------------------------------------------------------------------===//
#ifndef FLY_ASTNODEBASE_H
#define FLY_ASTNODEBASE_H
#include "ASTFunc.h"
#include "Basic/SourceLocation.h"
#include "llvm/ADT/StringMap.h"
namespace fly {
class ASTContext;
class ASTGlobalVar;
class ASTClass;
class ASTFunc;
class ASTFuncCall;
class ASTUnrefGlobalVar;
class ASTUnrefCall;
class ASTNodeBase {
protected:
ASTContext* Context;
// Node FileName
const llvm::StringRef Name;
// Private Global Vars
llvm::StringMap<ASTGlobalVar *> GlobalVars;
// Public Functions
std::unordered_set<ASTFunc*> Functions;
// Calls created on Functions creations, each Function have a Call defined here
llvm::StringMap<std::vector<ASTFuncCall *>> FunctionCalls;
// Public Classes
llvm::StringMap<ASTClass *> Classes;
// Contains all unresolved VarRef to a GlobalVar
std::vector<ASTUnrefGlobalVar *> UnrefGlobalVars;
// Contains all unresolved Function Calls
std::vector<ASTUnrefCall *> UnrefFunctionCalls;
public:
ASTNodeBase() = delete;
ASTNodeBase(const llvm::StringRef &Name, ASTContext* Context);
const llvm::StringRef& getName();
ASTContext &getContext() const;
const llvm::StringMap<ASTGlobalVar *> &getGlobalVars() const;
const std::unordered_set<ASTFunc*> &getFunctions() const;
const llvm::StringMap<std::vector<ASTFuncCall *>> &getFunctionCalls() const;
const llvm::StringMap<ASTClass *> &getClasses() const;
bool AddFunctionCall(ASTFuncCall *Call);
virtual std::string str() const;
};
}
#endif //FLY_ASTNODEBASE_H
| 26.320988 | 120 | 0.588649 | [
"vector"
] |
e58af4a8896413a1eadc6e1e17c97830644fa1e9 | 17,056 | h | C | Source/Application.h | omercier01/basisfluid | a2db0690a8c13ce652e174d696bf92ed634924bc | [
"MIT"
] | 13 | 2020-03-23T15:27:04.000Z | 2021-12-25T13:17:55.000Z | Source/Application.h | omercier01/basisfluid | a2db0690a8c13ce652e174d696bf92ed634924bc | [
"MIT"
] | null | null | null | Source/Application.h | omercier01/basisfluid | a2db0690a8c13ce652e174d696bf92ed634924bc | [
"MIT"
] | 2 | 2020-03-24T00:36:30.000Z | 2020-04-11T05:43:03.000Z |
// Some comments refer to the paper "Local Bases for Model-reduced Smoke Simulations" for more details.
#ifndef APPLICATION_H
#define APPLICATION_H
#include "VectorField2D.h"
#include "GridData2D.h"
#include "BasisFlows.h"
#define GLM_FORCE_RADIANS
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <string>
#include <memory>
#include <vector>
class Obstacle;
class ObstacleShaderPipeline;
class ParticleShaderPipeline;
class VelocityArrowShaderPipeline;
enum class ObstacleType { None, Circle, Bar };
// Global class to manage program execution
class Application {
public:
//================================================
// Parameters
// Save simulation images to file or not
bool _saveWindowToFile = false;
// Window dimensions
unsigned int _windowWidth = 1000;
unsigned int _windowHeight = 1000;
// Frequency levels
// Note: Pick maximum basis flows sizes (minimum frequency levels) that are not too large
// compared to domain features, otherwise basis stretch can sometimes fail
const int _minFreqLvl = 1;
const int _maxFreqLvl = 2;
const int _minAnisoLvl = 0;
const int _maxAnisoLvl = 1; // MAXIMUM 2, OTHER BASES ARE NOT DEFINED
//
// Simulation parameters
//
// nb iterations to project forces
const uint _maxNbItMatBBInversion = 10;
// nb iterations when computing basis stretches
const uint _nbStretchLoops = 2;
// nb iterations to compute stretched coordinated (paper Section 6.1)
const unsigned int _nbNewtonInversionIterations = 3;
// time step
const float _dt = 0.0325f;
// buoyancy per particle
const float _buoyancyPerParticle = 0.1f;
// buoyancy reduction exponent with time (usually in [0,1])
const float _buoyancyDecayRatioWithAge = 1.f;
// simulation viualization viewpoint
const glm::mat4 _viewProjMat = { 1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1 };
// nb steps to advect particles
const uint _substepsParticles = 1;
// particle seeding region
const float _seedCenterX = 0.f;
const float _seedCenterY = -0.75f;
const float _seedRadius = 0.1f;
// nb substeps when evolving bases
const uint _substepsDeformation = 1;
// lambda and epsilon for energy cascade (paper Section 5.3)
/*const float _explicitTransferSpeed = 0.1f;
const float _explicitTransferExponent = -1.66f;
const float _factorDeformation = 0.5f;*/
const float _explicitTransferSpeed = 0.05f;
const float _explicitTransferExponent = -1.66f;
// the region of allowed basis corner movement has width _stretchBandRatio times the basis support half size,
// i.e. the basis can be stretched or sqquished by at most this ratio, otherwise it is discarded
const float _stretchBandRatio = 0.5f;
// particle life time, in nb of frames
const unsigned int _particleLifeTime = 300;
// nb of particles seeded each frame
const unsigned int _nbParticlesPerSeedGroupPerDimension = 200;
// transfer ratio to each neighboring frequency layers (paper Figure 6). "m" means "minus".
// coefficient 10 sends energy down the cascade, e.g. from frequency (2,2) to frequency (4,2).
// coefficient m10 sends energy back up , e.g. from frequency (4,2) to frequency (2,2).
// These ratios are later normalized to have unit sum.
const float _explicitTransfer_10 = 1.f;
const float _explicitTransfer_01 = 1.f;
const float _explicitTransfer_11 = 1.f;
const float _explicitTransfer_m10 = 0.f;
const float _explicitTransfer_0m1 = 0.f;
const float _explicitTransfer_m1m1 = 0.f;
//
// Obstacle parameters
//
//ObstacleType _obstacleType = ObstacleType::None;
ObstacleType _obstacleType = ObstacleType::Circle;
//ObstacleType _obstacleType = ObstacleType::Bar;
const float _obstacleCircleRadius = 0.2f;
const float _obstacleCircleMotionSpeed = 1.f;
const float _obstacleCircleMotionRadius = 0.25f;
const float _obstacleBarWidth = 0.1f;
const float _obstacleBarHeight = 0.2f;
const float _obstacleBarRotationSpeed = 0.789f;
const float _obstacleBarMotionSpeed = 0.75f;
const float _obstacleBarMotionAmplitude = 0.25f;
// Size of influence band around dynamic objects. See Equation 27
const float _boundarySDFBandDecrease = 0.25f;
// multiplicator for projected flow around moving obstacles
const float _obstacleBoundaryFactor = 3.f;
// simulation domain
const glm::vec2 _domainCenter = { 0,0 };
const glm::vec2 _domainHalfSize = { 1.f,1.f };
// simulation grid sizes
// velocity grid for visualization
const unsigned int _nbCellsVelocity = 64 - 1;
// grid to store basis templates
const unsigned int _nbCellsBasisTemplates = 64 - 1;
// obstacle marching squares
const unsigned int _obstacleDisplayRes = 256;
// grid to integrate basis when computing coefficients
const unsigned int _integralGridRes = 32 - 1;
// acceleration structure for basis centers
const unsigned int _accelBasisRes = 32;
// particle acceleration structure
const unsigned int _accelParticlesRes = 64;
// grid to compute forces
const unsigned int _forcesGridRes = 64 - 1;
// Width of support of first basis frequency level.
// Note: not tested with _lengthLvl0 != 1
const float _lengthLvl0 = 1.0f;
// the vector growth factor using mouse scroll
float _velocityArrowFactor = 0.1f;
// initial application controls
bool _seedParticles = true;
bool _showVelocity = false;
bool _useForcesFromParticles = true;
bool _drawParticles = true;
bool _moveObstacles = true;
bool _stepSimulation = true;
//================================================
// Size of grid to snap basis centers when saving coefficient dictionary to avoid float errors
const float _coeffSnapSize = _lengthLvl0 / float(1 << _maxFreqLvl) / 32.0f;
const float _domainLeft = _domainCenter.x - _domainHalfSize.x;
const float _domainRight = _domainCenter.x + _domainHalfSize.x;
const float _domainBottom = _domainCenter.y - _domainHalfSize.y;
const float _domainTop = _domainCenter.y + _domainHalfSize.y;
public:
Application();
~Application();
// Main loop
bool Run();
// Initialization calls, return false if failed
bool Init();
bool Init_DataBuffers();
bool Init_Obstacles();
bool Init_BasisFlows();
bool Init_Shaders();
// Main simulation loop
void SimulationStep();
// Render loop
void Draw();
// Render velocity grid
void ComputeVelocityGridForDisplay();
// Save window as png in the Output folder.
void SaveWindowToFile();
// Computes the B^T.B coefficient, using cached value if coefficient has been previously computed
// i,j: indices of coefficient to compute
// b1,b2: basis info of coefficient to compute
float MatBBCoeff(int i, int j);
float MatBBCoeff(const BasisFlow& b1, const BasisFlow& b2);
// Computes the T coefficient, using cached value if coefficient has been previously computed.
// iTransported, bTransported: index or basis info of basis being transported
// iTransporting, bTransporting: index or basis info of basis acting on the other
glm::vec2 MatTCoeff(int iTransported, int iTransporting);
glm::vec2 MatTCoeff(BasisFlow bTransported, BasisFlow bTransporting);
// Solves B^T.B.vecX = vecB for vecX, only using the basis flows that have all bits basisBitMask
// turned on. This is used to project forces onto the basis (where boundary basis flows are ignored)
// or to project a moving obstacle's motion onto the boundary bases (in which cases nly boundary
// basis flows are used).
// Uses Gauss-Seidel iterations. Since basis flows are ordered by wavenumber, doing only one step of
// Gauss-Seidel is equivalent to projection frequency layers independently.
void InverseBBMatrix(
DataBuffer1D<double>* vecX,
DataBuffer1D<double>* vecB,
unsigned int basisBitMask);
void InverseBBMatrixMain(
unsigned int iRow, double* vecX, double* vecB,
BasisFlow* basisDataPointer, unsigned int basisBitMask);
// Saves/loads the coefficient dictionaries to/from file
void SaveCoeffsBB(std::string filename);
void LoadCoeffsBB(std::string filename);
void SaveCoeffsT(std::string filename);
void LoadCoeffsT(std::string filename);
// Evaluates a basis at a given point from its basis template (i.e. scaling and translating the
// basis template to the right frequency level and center)
// p: point to evaluate
// freqLevel: Frequency of the basis
// center: center of the basis
glm::vec2 TranslatedBasisEval(const glm::vec2 p, const glm::ivec2 freqLvl, const glm::vec2 center);
// Computes \int(b1.b2), see Equation 1.
float IntegrateBasisBasis(BasisFlow b1, BasisFlow b2);
// Computes \int(b.vecField), where velField is a vector field defined on the simulation domain.
float IntegrateBasisGrid(BasisFlow& b, VectorField2D* velField);
// Computes basis flow's average on its support, i.e.
// \int_{S}(bVec)/\int_{S}, where S is bSupport's support. See Equation 18.
glm::vec2 AverageBasisOnSupport(BasisFlow bVec, BasisFlow bSupport);
// Computes the stretch of a given basis flow, see Section 6.1. If staticObstaclesOnly is true,
// only static obstacles will be used. During initialization, we need to excluse dynamic obstacles
// otherwise basis flows that are not used during the first frame could become used in later frames
// after a dynamic obstacle has moed. By only using stati obstacls, we make sure all basis flows
// are accounted for when precomputing interaction coefficients.
BasisFlow ComputeStretch(BasisFlow b, bool staticObstaclesOnly);
// Compute stretches for all basis flows
void ComputeStretches();
// Evaluates a stretched basis flow at point p, weighted by the basis's coefficient.
// p: evaluatiom point
// b: stretched basis
vec2 VecObstacle_stretch(vec2 p, BasisFlow const& b);
// Uses Newton iterations to inverse the bilinear coefficients for stretched coordinates,
// going from stretched world space (p) to unstretched UV space. Based on
// http://stackoverflow.com/questions/808441/inverse-bilinear-interpolation .
vec2 QuadCoord(vec2 p, BasisFlow const& b);
// Computes the Jacobian of the deformation form unstretched UV space to stretched world space.
mat2 QuadCoordInvDeriv(vec2 uv, BasisFlow const& b);
// Stores all particles in an acceleration grid for easy retrieval
void SetParticlesInAccelGrid();
// Advects all particles
void ComputeParticleAdvection();
// Adds new particles
void SeedParticles();
// Projects all buoyancy forces from particles onto the basis flows. Splats particle buoyancy
// on a grid, and projects forces from that grid to the basis flows.
void AddParticleForcesToBasisFlows();
// Projects dynamic obsacle motion onto boundary basis flows. See Secton 6.2 .
void ProjectDynamicObstacleBoundaryMotion();
// Computes blinear weights for basis advection. See Equation 20.
// newCenter: position where basis bi is being moved
// bi: basis being moved
// bj: one basis on a corner of the cell where newCenter lands, which will receive part of
// bi's contribution
void ComputeNewCenterProportions(vec2& newCenter, BasisFlow& bi, BasisFlow& bj, vec2& interBasisDist);
// Compute all basis flows advection
void ComputeBasisAdvection();
// Computed wavenumber from the basis flow's frequency. See Section 5.3 .
inline float WavenumberBasis(BasisFlow& b)
{
return powf(2.f, 0.5f*(b.freqLvl.x + b.freqLvl.y));
}
public:
// GLFW callbacks
static void CallbackWindowClosed(GLFWwindow* pGlfwWindow);
static void CallbackKey(GLFWwindow* pGlfwWindow, int key, int scancode, int action, int mods);
static void CallbackMouseScroll(GLFWwindow* pGlfwWindow, double xOffset, double yOffset);
static void DebugCallback(GLenum source, GLenum /*type*/, GLuint /*id*/, GLenum severity, std::string message);
public:
GLFWwindow * _glfwWindow;
// Relative neighboring basis frequecies used during energy transfers
static const unsigned int _nbExplicitTransferFreqs = 6;
const glm::ivec2 _explicitTransferFreqs[_nbExplicitTransferFreqs] = { {1,0}, {0,1}, {1,1}, {-1,0}, {0,-1}, {-1,-1} };
// simulation buffers
std::unique_ptr<VectorField2D> _velocityField = nullptr;
std::unique_ptr<VectorField2D> _forceField = nullptr;
std::unique_ptr<VectorField2D>* _basisFlowTemplates = nullptr;
std::unique_ptr<DataBuffer1D<BasisFlow>> _basisFlowParams = nullptr;
std::vector<ivec2> _freqLvls;
// particles buffers
std::unique_ptr<DataBuffer1D<vec2>> _partPos = nullptr;
std::unique_ptr<DataBuffer1D<vec2>> _partVecs = nullptr;
std::unique_ptr<DataBuffer1D<float>> _partAges = nullptr;
// particle acceleration grid
std::unique_ptr<GridData2D<std::vector<unsigned int>*>> _accelParticles = nullptr;
// draw buffers
std::unique_ptr<DataBuffer1D<vec2>> _bufferGridPoints = nullptr;
std::unique_ptr<DataBuffer1D<vec2>> _bufferArrows = nullptr;
std::unique_ptr<DataBuffer1D<vec2>> _obstacleLines = nullptr;
// force projection buffers
std::unique_ptr<DataBuffer1D<double>> _vecX = nullptr;
std::unique_ptr<DataBuffer1D<double>> _vecXForces = nullptr;
std::unique_ptr<DataBuffer1D<double>> _vecXBoundaryForces = nullptr;
std::unique_ptr<DataBuffer1D<double>> _vecB = nullptr;
// acceleration structure to fetch basis flows that intersect a region of the simulation domain
std::unique_ptr<DataBuffer2D<std::vector<unsigned int>*>> _accelBasisCentersIds = nullptr;
// Stores, for all basis flows, the ID of all beighboring basis flows.
std::unique_ptr<DataBuffer1D<std::vector<unsigned int>*>> _intersectingBasesIds = nullptr;
// Stores, for all basis flows, the ID of all neighboring basis flows of the same frequency.
// This is used during basis transport. Since a basis will usually transported near its
// current location, e only need to look at neighboring basis flows of the same frequencies
// to transfer its weight.
std::unique_ptr<DataBuffer1D<std::vector<unsigned int>*>> _intersectingBasesIdsTransport = nullptr;
// Stores, for all basis flows, the B^T.B coefficient of all neighboring basis flows. This is
// used during energy transfer in Equation 24.
std::unique_ptr<DataBuffer1D<std::vector<CoeffBBDecompressedIntersectionInfo>*>>
_intersectingBasesIdsDeformation[_nbExplicitTransferFreqs];
struct ExplicitTransferCoeffs {
float coeffs[_nbExplicitTransferFreqs];
};
// total contribution of beighboring basis, see denominator of Equation 24
std::vector<ExplicitTransferCoeffs> _coeffBBExplicitTransferSum_abs;
// list of all obstacles, inclusing simulation domain walls
std::vector<Obstacle*> _obstacles;
// list of all orthogonal groups of basis flows. Used when inverting the B^T.B matrix
// with the multicolor scheme, see Section 5.1 .
std::vector<std::vector<unsigned int>> _orthogonalBasisGroupIds;
// coefficient dictionaries
MapTypeBB _coeffsBB;
MapTypeT _coeffsT;
// Instead of evaluating the coefficient dictionaries, we store, for each basis, the list of it's
// neighboring coefficients and corresponding interaction coefficients. See last paragraph of
// section 5.4 . The decompressed BB coefficients do not include the basis itself in its list of
// neihbors, since we do not need it when inverting the B^T.B matrix. The B^T.B coefficient of a
// basis with itself is also already stored in the basis's normSquared field. For the
// decopressed T coefficient, the basis itself is inclused in the list, since we need to account
// for self advection when computing basis advection.
std::vector<std::vector<CoeffBBDecompressedIntersectionInfo>> _coeffsBBDecompressedIntersections;
std::vector<std::vector<CoeffTDecompressedIntersectionInfo>> _coeffsTDecompressedIntersections;
// shader pipelines
std::unique_ptr<ObstacleShaderPipeline> _pipelineObstacle;
std::unique_ptr<ParticleShaderPipeline> _pipelineParticle;
std::unique_ptr<VelocityArrowShaderPipeline> _pipelineVelocityArrow;
// Status
bool _readyToQuit = false;
bool _newBBCoeffComputed = false;
bool _newACoeffComputed = false;
bool _newTCoeffComputed = false;
bool _newRCoeffComputed = false;
bool _obstacleDisplayNeedsUpdating = true;
bool _basisStretchedUpdateRequired = true;
unsigned int _particleCircularSeedId = 0;
bool _particleSeedBufferLooped = false;
bool _velocityGridNeedsUpdating = true;
unsigned int _appFrameCount = 0;
};
extern Application* app;
#endif /*APPLICATION_H*/
| 39.665116 | 121 | 0.721623 | [
"render",
"vector",
"model"
] |
e58dcd001ff1739a4c56601c072ede139f4cfd04 | 45,395 | h | C | SAI-P4-BM/p4-switch/sai-p4-target/gen-cpp/bm/SimpleSwitch.h | bocon13/stratum-sonic | 9be75505869ee81d30ef9b65276f7d55f495658f | [
"Apache-2.0"
] | null | null | null | SAI-P4-BM/p4-switch/sai-p4-target/gen-cpp/bm/SimpleSwitch.h | bocon13/stratum-sonic | 9be75505869ee81d30ef9b65276f7d55f495658f | [
"Apache-2.0"
] | null | null | null | SAI-P4-BM/p4-switch/sai-p4-target/gen-cpp/bm/SimpleSwitch.h | bocon13/stratum-sonic | 9be75505869ee81d30ef9b65276f7d55f495658f | [
"Apache-2.0"
] | null | null | null | /**
* Autogenerated by Thrift Compiler (0.11.0)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
#ifndef SimpleSwitch_H
#define SimpleSwitch_H
#include <thrift/TDispatchProcessor.h>
#include <thrift/async/TConcurrentClientSyncInfo.h>
#include "simple_switch_types.h"
namespace sswitch_runtime {
#ifdef _MSC_VER
#pragma warning( push )
#pragma warning (disable : 4250 ) //inheriting methods via dominance
#endif
class SimpleSwitchIf {
public:
virtual ~SimpleSwitchIf() {}
virtual int32_t mirroring_mapping_add(const int32_t mirror_id, const int32_t egress_port) = 0;
virtual int32_t mirroring_mapping_delete(const int32_t mirror_id) = 0;
virtual int32_t mirroring_mapping_get_egress_port(const int32_t mirror_id) = 0;
virtual int32_t set_egress_queue_depth(const int32_t port_num, const int32_t depth_pkts) = 0;
virtual int32_t set_all_egress_queue_depths(const int32_t depth_pkts) = 0;
virtual int32_t set_egress_queue_rate(const int32_t port_num, const int64_t rate_pps) = 0;
virtual int32_t set_all_egress_queue_rates(const int64_t rate_pps) = 0;
virtual int64_t get_time_elapsed_us() = 0;
virtual int64_t get_time_since_epoch_us() = 0;
};
class SimpleSwitchIfFactory {
public:
typedef SimpleSwitchIf Handler;
virtual ~SimpleSwitchIfFactory() {}
virtual SimpleSwitchIf* getHandler(const ::apache::thrift::TConnectionInfo& connInfo) = 0;
virtual void releaseHandler(SimpleSwitchIf* /* handler */) = 0;
};
class SimpleSwitchIfSingletonFactory : virtual public SimpleSwitchIfFactory {
public:
SimpleSwitchIfSingletonFactory(const ::apache::thrift::stdcxx::shared_ptr<SimpleSwitchIf>& iface) : iface_(iface) {}
virtual ~SimpleSwitchIfSingletonFactory() {}
virtual SimpleSwitchIf* getHandler(const ::apache::thrift::TConnectionInfo&) {
return iface_.get();
}
virtual void releaseHandler(SimpleSwitchIf* /* handler */) {}
protected:
::apache::thrift::stdcxx::shared_ptr<SimpleSwitchIf> iface_;
};
class SimpleSwitchNull : virtual public SimpleSwitchIf {
public:
virtual ~SimpleSwitchNull() {}
int32_t mirroring_mapping_add(const int32_t /* mirror_id */, const int32_t /* egress_port */) {
int32_t _return = 0;
return _return;
}
int32_t mirroring_mapping_delete(const int32_t /* mirror_id */) {
int32_t _return = 0;
return _return;
}
int32_t mirroring_mapping_get_egress_port(const int32_t /* mirror_id */) {
int32_t _return = 0;
return _return;
}
int32_t set_egress_queue_depth(const int32_t /* port_num */, const int32_t /* depth_pkts */) {
int32_t _return = 0;
return _return;
}
int32_t set_all_egress_queue_depths(const int32_t /* depth_pkts */) {
int32_t _return = 0;
return _return;
}
int32_t set_egress_queue_rate(const int32_t /* port_num */, const int64_t /* rate_pps */) {
int32_t _return = 0;
return _return;
}
int32_t set_all_egress_queue_rates(const int64_t /* rate_pps */) {
int32_t _return = 0;
return _return;
}
int64_t get_time_elapsed_us() {
int64_t _return = 0;
return _return;
}
int64_t get_time_since_epoch_us() {
int64_t _return = 0;
return _return;
}
};
typedef struct _SimpleSwitch_mirroring_mapping_add_args__isset {
_SimpleSwitch_mirroring_mapping_add_args__isset() : mirror_id(false), egress_port(false) {}
bool mirror_id :1;
bool egress_port :1;
} _SimpleSwitch_mirroring_mapping_add_args__isset;
class SimpleSwitch_mirroring_mapping_add_args {
public:
SimpleSwitch_mirroring_mapping_add_args(const SimpleSwitch_mirroring_mapping_add_args&);
SimpleSwitch_mirroring_mapping_add_args& operator=(const SimpleSwitch_mirroring_mapping_add_args&);
SimpleSwitch_mirroring_mapping_add_args() : mirror_id(0), egress_port(0) {
}
virtual ~SimpleSwitch_mirroring_mapping_add_args() throw();
int32_t mirror_id;
int32_t egress_port;
_SimpleSwitch_mirroring_mapping_add_args__isset __isset;
void __set_mirror_id(const int32_t val);
void __set_egress_port(const int32_t val);
bool operator == (const SimpleSwitch_mirroring_mapping_add_args & rhs) const
{
if (!(mirror_id == rhs.mirror_id))
return false;
if (!(egress_port == rhs.egress_port))
return false;
return true;
}
bool operator != (const SimpleSwitch_mirroring_mapping_add_args &rhs) const {
return !(*this == rhs);
}
bool operator < (const SimpleSwitch_mirroring_mapping_add_args & ) const;
uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;
};
class SimpleSwitch_mirroring_mapping_add_pargs {
public:
virtual ~SimpleSwitch_mirroring_mapping_add_pargs() throw();
const int32_t* mirror_id;
const int32_t* egress_port;
uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;
};
typedef struct _SimpleSwitch_mirroring_mapping_add_result__isset {
_SimpleSwitch_mirroring_mapping_add_result__isset() : success(false) {}
bool success :1;
} _SimpleSwitch_mirroring_mapping_add_result__isset;
class SimpleSwitch_mirroring_mapping_add_result {
public:
SimpleSwitch_mirroring_mapping_add_result(const SimpleSwitch_mirroring_mapping_add_result&);
SimpleSwitch_mirroring_mapping_add_result& operator=(const SimpleSwitch_mirroring_mapping_add_result&);
SimpleSwitch_mirroring_mapping_add_result() : success(0) {
}
virtual ~SimpleSwitch_mirroring_mapping_add_result() throw();
int32_t success;
_SimpleSwitch_mirroring_mapping_add_result__isset __isset;
void __set_success(const int32_t val);
bool operator == (const SimpleSwitch_mirroring_mapping_add_result & rhs) const
{
if (!(success == rhs.success))
return false;
return true;
}
bool operator != (const SimpleSwitch_mirroring_mapping_add_result &rhs) const {
return !(*this == rhs);
}
bool operator < (const SimpleSwitch_mirroring_mapping_add_result & ) const;
uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;
};
typedef struct _SimpleSwitch_mirroring_mapping_add_presult__isset {
_SimpleSwitch_mirroring_mapping_add_presult__isset() : success(false) {}
bool success :1;
} _SimpleSwitch_mirroring_mapping_add_presult__isset;
class SimpleSwitch_mirroring_mapping_add_presult {
public:
virtual ~SimpleSwitch_mirroring_mapping_add_presult() throw();
int32_t* success;
_SimpleSwitch_mirroring_mapping_add_presult__isset __isset;
uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
};
typedef struct _SimpleSwitch_mirroring_mapping_delete_args__isset {
_SimpleSwitch_mirroring_mapping_delete_args__isset() : mirror_id(false) {}
bool mirror_id :1;
} _SimpleSwitch_mirroring_mapping_delete_args__isset;
class SimpleSwitch_mirroring_mapping_delete_args {
public:
SimpleSwitch_mirroring_mapping_delete_args(const SimpleSwitch_mirroring_mapping_delete_args&);
SimpleSwitch_mirroring_mapping_delete_args& operator=(const SimpleSwitch_mirroring_mapping_delete_args&);
SimpleSwitch_mirroring_mapping_delete_args() : mirror_id(0) {
}
virtual ~SimpleSwitch_mirroring_mapping_delete_args() throw();
int32_t mirror_id;
_SimpleSwitch_mirroring_mapping_delete_args__isset __isset;
void __set_mirror_id(const int32_t val);
bool operator == (const SimpleSwitch_mirroring_mapping_delete_args & rhs) const
{
if (!(mirror_id == rhs.mirror_id))
return false;
return true;
}
bool operator != (const SimpleSwitch_mirroring_mapping_delete_args &rhs) const {
return !(*this == rhs);
}
bool operator < (const SimpleSwitch_mirroring_mapping_delete_args & ) const;
uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;
};
class SimpleSwitch_mirroring_mapping_delete_pargs {
public:
virtual ~SimpleSwitch_mirroring_mapping_delete_pargs() throw();
const int32_t* mirror_id;
uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;
};
typedef struct _SimpleSwitch_mirroring_mapping_delete_result__isset {
_SimpleSwitch_mirroring_mapping_delete_result__isset() : success(false) {}
bool success :1;
} _SimpleSwitch_mirroring_mapping_delete_result__isset;
class SimpleSwitch_mirroring_mapping_delete_result {
public:
SimpleSwitch_mirroring_mapping_delete_result(const SimpleSwitch_mirroring_mapping_delete_result&);
SimpleSwitch_mirroring_mapping_delete_result& operator=(const SimpleSwitch_mirroring_mapping_delete_result&);
SimpleSwitch_mirroring_mapping_delete_result() : success(0) {
}
virtual ~SimpleSwitch_mirroring_mapping_delete_result() throw();
int32_t success;
_SimpleSwitch_mirroring_mapping_delete_result__isset __isset;
void __set_success(const int32_t val);
bool operator == (const SimpleSwitch_mirroring_mapping_delete_result & rhs) const
{
if (!(success == rhs.success))
return false;
return true;
}
bool operator != (const SimpleSwitch_mirroring_mapping_delete_result &rhs) const {
return !(*this == rhs);
}
bool operator < (const SimpleSwitch_mirroring_mapping_delete_result & ) const;
uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;
};
typedef struct _SimpleSwitch_mirroring_mapping_delete_presult__isset {
_SimpleSwitch_mirroring_mapping_delete_presult__isset() : success(false) {}
bool success :1;
} _SimpleSwitch_mirroring_mapping_delete_presult__isset;
class SimpleSwitch_mirroring_mapping_delete_presult {
public:
virtual ~SimpleSwitch_mirroring_mapping_delete_presult() throw();
int32_t* success;
_SimpleSwitch_mirroring_mapping_delete_presult__isset __isset;
uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
};
typedef struct _SimpleSwitch_mirroring_mapping_get_egress_port_args__isset {
_SimpleSwitch_mirroring_mapping_get_egress_port_args__isset() : mirror_id(false) {}
bool mirror_id :1;
} _SimpleSwitch_mirroring_mapping_get_egress_port_args__isset;
class SimpleSwitch_mirroring_mapping_get_egress_port_args {
public:
SimpleSwitch_mirroring_mapping_get_egress_port_args(const SimpleSwitch_mirroring_mapping_get_egress_port_args&);
SimpleSwitch_mirroring_mapping_get_egress_port_args& operator=(const SimpleSwitch_mirroring_mapping_get_egress_port_args&);
SimpleSwitch_mirroring_mapping_get_egress_port_args() : mirror_id(0) {
}
virtual ~SimpleSwitch_mirroring_mapping_get_egress_port_args() throw();
int32_t mirror_id;
_SimpleSwitch_mirroring_mapping_get_egress_port_args__isset __isset;
void __set_mirror_id(const int32_t val);
bool operator == (const SimpleSwitch_mirroring_mapping_get_egress_port_args & rhs) const
{
if (!(mirror_id == rhs.mirror_id))
return false;
return true;
}
bool operator != (const SimpleSwitch_mirroring_mapping_get_egress_port_args &rhs) const {
return !(*this == rhs);
}
bool operator < (const SimpleSwitch_mirroring_mapping_get_egress_port_args & ) const;
uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;
};
class SimpleSwitch_mirroring_mapping_get_egress_port_pargs {
public:
virtual ~SimpleSwitch_mirroring_mapping_get_egress_port_pargs() throw();
const int32_t* mirror_id;
uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;
};
typedef struct _SimpleSwitch_mirroring_mapping_get_egress_port_result__isset {
_SimpleSwitch_mirroring_mapping_get_egress_port_result__isset() : success(false) {}
bool success :1;
} _SimpleSwitch_mirroring_mapping_get_egress_port_result__isset;
class SimpleSwitch_mirroring_mapping_get_egress_port_result {
public:
SimpleSwitch_mirroring_mapping_get_egress_port_result(const SimpleSwitch_mirroring_mapping_get_egress_port_result&);
SimpleSwitch_mirroring_mapping_get_egress_port_result& operator=(const SimpleSwitch_mirroring_mapping_get_egress_port_result&);
SimpleSwitch_mirroring_mapping_get_egress_port_result() : success(0) {
}
virtual ~SimpleSwitch_mirroring_mapping_get_egress_port_result() throw();
int32_t success;
_SimpleSwitch_mirroring_mapping_get_egress_port_result__isset __isset;
void __set_success(const int32_t val);
bool operator == (const SimpleSwitch_mirroring_mapping_get_egress_port_result & rhs) const
{
if (!(success == rhs.success))
return false;
return true;
}
bool operator != (const SimpleSwitch_mirroring_mapping_get_egress_port_result &rhs) const {
return !(*this == rhs);
}
bool operator < (const SimpleSwitch_mirroring_mapping_get_egress_port_result & ) const;
uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;
};
typedef struct _SimpleSwitch_mirroring_mapping_get_egress_port_presult__isset {
_SimpleSwitch_mirroring_mapping_get_egress_port_presult__isset() : success(false) {}
bool success :1;
} _SimpleSwitch_mirroring_mapping_get_egress_port_presult__isset;
class SimpleSwitch_mirroring_mapping_get_egress_port_presult {
public:
virtual ~SimpleSwitch_mirroring_mapping_get_egress_port_presult() throw();
int32_t* success;
_SimpleSwitch_mirroring_mapping_get_egress_port_presult__isset __isset;
uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
};
typedef struct _SimpleSwitch_set_egress_queue_depth_args__isset {
_SimpleSwitch_set_egress_queue_depth_args__isset() : port_num(false), depth_pkts(false) {}
bool port_num :1;
bool depth_pkts :1;
} _SimpleSwitch_set_egress_queue_depth_args__isset;
class SimpleSwitch_set_egress_queue_depth_args {
public:
SimpleSwitch_set_egress_queue_depth_args(const SimpleSwitch_set_egress_queue_depth_args&);
SimpleSwitch_set_egress_queue_depth_args& operator=(const SimpleSwitch_set_egress_queue_depth_args&);
SimpleSwitch_set_egress_queue_depth_args() : port_num(0), depth_pkts(0) {
}
virtual ~SimpleSwitch_set_egress_queue_depth_args() throw();
int32_t port_num;
int32_t depth_pkts;
_SimpleSwitch_set_egress_queue_depth_args__isset __isset;
void __set_port_num(const int32_t val);
void __set_depth_pkts(const int32_t val);
bool operator == (const SimpleSwitch_set_egress_queue_depth_args & rhs) const
{
if (!(port_num == rhs.port_num))
return false;
if (!(depth_pkts == rhs.depth_pkts))
return false;
return true;
}
bool operator != (const SimpleSwitch_set_egress_queue_depth_args &rhs) const {
return !(*this == rhs);
}
bool operator < (const SimpleSwitch_set_egress_queue_depth_args & ) const;
uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;
};
class SimpleSwitch_set_egress_queue_depth_pargs {
public:
virtual ~SimpleSwitch_set_egress_queue_depth_pargs() throw();
const int32_t* port_num;
const int32_t* depth_pkts;
uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;
};
typedef struct _SimpleSwitch_set_egress_queue_depth_result__isset {
_SimpleSwitch_set_egress_queue_depth_result__isset() : success(false) {}
bool success :1;
} _SimpleSwitch_set_egress_queue_depth_result__isset;
class SimpleSwitch_set_egress_queue_depth_result {
public:
SimpleSwitch_set_egress_queue_depth_result(const SimpleSwitch_set_egress_queue_depth_result&);
SimpleSwitch_set_egress_queue_depth_result& operator=(const SimpleSwitch_set_egress_queue_depth_result&);
SimpleSwitch_set_egress_queue_depth_result() : success(0) {
}
virtual ~SimpleSwitch_set_egress_queue_depth_result() throw();
int32_t success;
_SimpleSwitch_set_egress_queue_depth_result__isset __isset;
void __set_success(const int32_t val);
bool operator == (const SimpleSwitch_set_egress_queue_depth_result & rhs) const
{
if (!(success == rhs.success))
return false;
return true;
}
bool operator != (const SimpleSwitch_set_egress_queue_depth_result &rhs) const {
return !(*this == rhs);
}
bool operator < (const SimpleSwitch_set_egress_queue_depth_result & ) const;
uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;
};
typedef struct _SimpleSwitch_set_egress_queue_depth_presult__isset {
_SimpleSwitch_set_egress_queue_depth_presult__isset() : success(false) {}
bool success :1;
} _SimpleSwitch_set_egress_queue_depth_presult__isset;
class SimpleSwitch_set_egress_queue_depth_presult {
public:
virtual ~SimpleSwitch_set_egress_queue_depth_presult() throw();
int32_t* success;
_SimpleSwitch_set_egress_queue_depth_presult__isset __isset;
uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
};
typedef struct _SimpleSwitch_set_all_egress_queue_depths_args__isset {
_SimpleSwitch_set_all_egress_queue_depths_args__isset() : depth_pkts(false) {}
bool depth_pkts :1;
} _SimpleSwitch_set_all_egress_queue_depths_args__isset;
class SimpleSwitch_set_all_egress_queue_depths_args {
public:
SimpleSwitch_set_all_egress_queue_depths_args(const SimpleSwitch_set_all_egress_queue_depths_args&);
SimpleSwitch_set_all_egress_queue_depths_args& operator=(const SimpleSwitch_set_all_egress_queue_depths_args&);
SimpleSwitch_set_all_egress_queue_depths_args() : depth_pkts(0) {
}
virtual ~SimpleSwitch_set_all_egress_queue_depths_args() throw();
int32_t depth_pkts;
_SimpleSwitch_set_all_egress_queue_depths_args__isset __isset;
void __set_depth_pkts(const int32_t val);
bool operator == (const SimpleSwitch_set_all_egress_queue_depths_args & rhs) const
{
if (!(depth_pkts == rhs.depth_pkts))
return false;
return true;
}
bool operator != (const SimpleSwitch_set_all_egress_queue_depths_args &rhs) const {
return !(*this == rhs);
}
bool operator < (const SimpleSwitch_set_all_egress_queue_depths_args & ) const;
uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;
};
class SimpleSwitch_set_all_egress_queue_depths_pargs {
public:
virtual ~SimpleSwitch_set_all_egress_queue_depths_pargs() throw();
const int32_t* depth_pkts;
uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;
};
typedef struct _SimpleSwitch_set_all_egress_queue_depths_result__isset {
_SimpleSwitch_set_all_egress_queue_depths_result__isset() : success(false) {}
bool success :1;
} _SimpleSwitch_set_all_egress_queue_depths_result__isset;
class SimpleSwitch_set_all_egress_queue_depths_result {
public:
SimpleSwitch_set_all_egress_queue_depths_result(const SimpleSwitch_set_all_egress_queue_depths_result&);
SimpleSwitch_set_all_egress_queue_depths_result& operator=(const SimpleSwitch_set_all_egress_queue_depths_result&);
SimpleSwitch_set_all_egress_queue_depths_result() : success(0) {
}
virtual ~SimpleSwitch_set_all_egress_queue_depths_result() throw();
int32_t success;
_SimpleSwitch_set_all_egress_queue_depths_result__isset __isset;
void __set_success(const int32_t val);
bool operator == (const SimpleSwitch_set_all_egress_queue_depths_result & rhs) const
{
if (!(success == rhs.success))
return false;
return true;
}
bool operator != (const SimpleSwitch_set_all_egress_queue_depths_result &rhs) const {
return !(*this == rhs);
}
bool operator < (const SimpleSwitch_set_all_egress_queue_depths_result & ) const;
uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;
};
typedef struct _SimpleSwitch_set_all_egress_queue_depths_presult__isset {
_SimpleSwitch_set_all_egress_queue_depths_presult__isset() : success(false) {}
bool success :1;
} _SimpleSwitch_set_all_egress_queue_depths_presult__isset;
class SimpleSwitch_set_all_egress_queue_depths_presult {
public:
virtual ~SimpleSwitch_set_all_egress_queue_depths_presult() throw();
int32_t* success;
_SimpleSwitch_set_all_egress_queue_depths_presult__isset __isset;
uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
};
typedef struct _SimpleSwitch_set_egress_queue_rate_args__isset {
_SimpleSwitch_set_egress_queue_rate_args__isset() : port_num(false), rate_pps(false) {}
bool port_num :1;
bool rate_pps :1;
} _SimpleSwitch_set_egress_queue_rate_args__isset;
class SimpleSwitch_set_egress_queue_rate_args {
public:
SimpleSwitch_set_egress_queue_rate_args(const SimpleSwitch_set_egress_queue_rate_args&);
SimpleSwitch_set_egress_queue_rate_args& operator=(const SimpleSwitch_set_egress_queue_rate_args&);
SimpleSwitch_set_egress_queue_rate_args() : port_num(0), rate_pps(0) {
}
virtual ~SimpleSwitch_set_egress_queue_rate_args() throw();
int32_t port_num;
int64_t rate_pps;
_SimpleSwitch_set_egress_queue_rate_args__isset __isset;
void __set_port_num(const int32_t val);
void __set_rate_pps(const int64_t val);
bool operator == (const SimpleSwitch_set_egress_queue_rate_args & rhs) const
{
if (!(port_num == rhs.port_num))
return false;
if (!(rate_pps == rhs.rate_pps))
return false;
return true;
}
bool operator != (const SimpleSwitch_set_egress_queue_rate_args &rhs) const {
return !(*this == rhs);
}
bool operator < (const SimpleSwitch_set_egress_queue_rate_args & ) const;
uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;
};
class SimpleSwitch_set_egress_queue_rate_pargs {
public:
virtual ~SimpleSwitch_set_egress_queue_rate_pargs() throw();
const int32_t* port_num;
const int64_t* rate_pps;
uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;
};
typedef struct _SimpleSwitch_set_egress_queue_rate_result__isset {
_SimpleSwitch_set_egress_queue_rate_result__isset() : success(false) {}
bool success :1;
} _SimpleSwitch_set_egress_queue_rate_result__isset;
class SimpleSwitch_set_egress_queue_rate_result {
public:
SimpleSwitch_set_egress_queue_rate_result(const SimpleSwitch_set_egress_queue_rate_result&);
SimpleSwitch_set_egress_queue_rate_result& operator=(const SimpleSwitch_set_egress_queue_rate_result&);
SimpleSwitch_set_egress_queue_rate_result() : success(0) {
}
virtual ~SimpleSwitch_set_egress_queue_rate_result() throw();
int32_t success;
_SimpleSwitch_set_egress_queue_rate_result__isset __isset;
void __set_success(const int32_t val);
bool operator == (const SimpleSwitch_set_egress_queue_rate_result & rhs) const
{
if (!(success == rhs.success))
return false;
return true;
}
bool operator != (const SimpleSwitch_set_egress_queue_rate_result &rhs) const {
return !(*this == rhs);
}
bool operator < (const SimpleSwitch_set_egress_queue_rate_result & ) const;
uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;
};
typedef struct _SimpleSwitch_set_egress_queue_rate_presult__isset {
_SimpleSwitch_set_egress_queue_rate_presult__isset() : success(false) {}
bool success :1;
} _SimpleSwitch_set_egress_queue_rate_presult__isset;
class SimpleSwitch_set_egress_queue_rate_presult {
public:
virtual ~SimpleSwitch_set_egress_queue_rate_presult() throw();
int32_t* success;
_SimpleSwitch_set_egress_queue_rate_presult__isset __isset;
uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
};
typedef struct _SimpleSwitch_set_all_egress_queue_rates_args__isset {
_SimpleSwitch_set_all_egress_queue_rates_args__isset() : rate_pps(false) {}
bool rate_pps :1;
} _SimpleSwitch_set_all_egress_queue_rates_args__isset;
class SimpleSwitch_set_all_egress_queue_rates_args {
public:
SimpleSwitch_set_all_egress_queue_rates_args(const SimpleSwitch_set_all_egress_queue_rates_args&);
SimpleSwitch_set_all_egress_queue_rates_args& operator=(const SimpleSwitch_set_all_egress_queue_rates_args&);
SimpleSwitch_set_all_egress_queue_rates_args() : rate_pps(0) {
}
virtual ~SimpleSwitch_set_all_egress_queue_rates_args() throw();
int64_t rate_pps;
_SimpleSwitch_set_all_egress_queue_rates_args__isset __isset;
void __set_rate_pps(const int64_t val);
bool operator == (const SimpleSwitch_set_all_egress_queue_rates_args & rhs) const
{
if (!(rate_pps == rhs.rate_pps))
return false;
return true;
}
bool operator != (const SimpleSwitch_set_all_egress_queue_rates_args &rhs) const {
return !(*this == rhs);
}
bool operator < (const SimpleSwitch_set_all_egress_queue_rates_args & ) const;
uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;
};
class SimpleSwitch_set_all_egress_queue_rates_pargs {
public:
virtual ~SimpleSwitch_set_all_egress_queue_rates_pargs() throw();
const int64_t* rate_pps;
uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;
};
typedef struct _SimpleSwitch_set_all_egress_queue_rates_result__isset {
_SimpleSwitch_set_all_egress_queue_rates_result__isset() : success(false) {}
bool success :1;
} _SimpleSwitch_set_all_egress_queue_rates_result__isset;
class SimpleSwitch_set_all_egress_queue_rates_result {
public:
SimpleSwitch_set_all_egress_queue_rates_result(const SimpleSwitch_set_all_egress_queue_rates_result&);
SimpleSwitch_set_all_egress_queue_rates_result& operator=(const SimpleSwitch_set_all_egress_queue_rates_result&);
SimpleSwitch_set_all_egress_queue_rates_result() : success(0) {
}
virtual ~SimpleSwitch_set_all_egress_queue_rates_result() throw();
int32_t success;
_SimpleSwitch_set_all_egress_queue_rates_result__isset __isset;
void __set_success(const int32_t val);
bool operator == (const SimpleSwitch_set_all_egress_queue_rates_result & rhs) const
{
if (!(success == rhs.success))
return false;
return true;
}
bool operator != (const SimpleSwitch_set_all_egress_queue_rates_result &rhs) const {
return !(*this == rhs);
}
bool operator < (const SimpleSwitch_set_all_egress_queue_rates_result & ) const;
uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;
};
typedef struct _SimpleSwitch_set_all_egress_queue_rates_presult__isset {
_SimpleSwitch_set_all_egress_queue_rates_presult__isset() : success(false) {}
bool success :1;
} _SimpleSwitch_set_all_egress_queue_rates_presult__isset;
class SimpleSwitch_set_all_egress_queue_rates_presult {
public:
virtual ~SimpleSwitch_set_all_egress_queue_rates_presult() throw();
int32_t* success;
_SimpleSwitch_set_all_egress_queue_rates_presult__isset __isset;
uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
};
class SimpleSwitch_get_time_elapsed_us_args {
public:
SimpleSwitch_get_time_elapsed_us_args(const SimpleSwitch_get_time_elapsed_us_args&);
SimpleSwitch_get_time_elapsed_us_args& operator=(const SimpleSwitch_get_time_elapsed_us_args&);
SimpleSwitch_get_time_elapsed_us_args() {
}
virtual ~SimpleSwitch_get_time_elapsed_us_args() throw();
bool operator == (const SimpleSwitch_get_time_elapsed_us_args & /* rhs */) const
{
return true;
}
bool operator != (const SimpleSwitch_get_time_elapsed_us_args &rhs) const {
return !(*this == rhs);
}
bool operator < (const SimpleSwitch_get_time_elapsed_us_args & ) const;
uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;
};
class SimpleSwitch_get_time_elapsed_us_pargs {
public:
virtual ~SimpleSwitch_get_time_elapsed_us_pargs() throw();
uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;
};
typedef struct _SimpleSwitch_get_time_elapsed_us_result__isset {
_SimpleSwitch_get_time_elapsed_us_result__isset() : success(false) {}
bool success :1;
} _SimpleSwitch_get_time_elapsed_us_result__isset;
class SimpleSwitch_get_time_elapsed_us_result {
public:
SimpleSwitch_get_time_elapsed_us_result(const SimpleSwitch_get_time_elapsed_us_result&);
SimpleSwitch_get_time_elapsed_us_result& operator=(const SimpleSwitch_get_time_elapsed_us_result&);
SimpleSwitch_get_time_elapsed_us_result() : success(0) {
}
virtual ~SimpleSwitch_get_time_elapsed_us_result() throw();
int64_t success;
_SimpleSwitch_get_time_elapsed_us_result__isset __isset;
void __set_success(const int64_t val);
bool operator == (const SimpleSwitch_get_time_elapsed_us_result & rhs) const
{
if (!(success == rhs.success))
return false;
return true;
}
bool operator != (const SimpleSwitch_get_time_elapsed_us_result &rhs) const {
return !(*this == rhs);
}
bool operator < (const SimpleSwitch_get_time_elapsed_us_result & ) const;
uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;
};
typedef struct _SimpleSwitch_get_time_elapsed_us_presult__isset {
_SimpleSwitch_get_time_elapsed_us_presult__isset() : success(false) {}
bool success :1;
} _SimpleSwitch_get_time_elapsed_us_presult__isset;
class SimpleSwitch_get_time_elapsed_us_presult {
public:
virtual ~SimpleSwitch_get_time_elapsed_us_presult() throw();
int64_t* success;
_SimpleSwitch_get_time_elapsed_us_presult__isset __isset;
uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
};
class SimpleSwitch_get_time_since_epoch_us_args {
public:
SimpleSwitch_get_time_since_epoch_us_args(const SimpleSwitch_get_time_since_epoch_us_args&);
SimpleSwitch_get_time_since_epoch_us_args& operator=(const SimpleSwitch_get_time_since_epoch_us_args&);
SimpleSwitch_get_time_since_epoch_us_args() {
}
virtual ~SimpleSwitch_get_time_since_epoch_us_args() throw();
bool operator == (const SimpleSwitch_get_time_since_epoch_us_args & /* rhs */) const
{
return true;
}
bool operator != (const SimpleSwitch_get_time_since_epoch_us_args &rhs) const {
return !(*this == rhs);
}
bool operator < (const SimpleSwitch_get_time_since_epoch_us_args & ) const;
uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;
};
class SimpleSwitch_get_time_since_epoch_us_pargs {
public:
virtual ~SimpleSwitch_get_time_since_epoch_us_pargs() throw();
uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;
};
typedef struct _SimpleSwitch_get_time_since_epoch_us_result__isset {
_SimpleSwitch_get_time_since_epoch_us_result__isset() : success(false) {}
bool success :1;
} _SimpleSwitch_get_time_since_epoch_us_result__isset;
class SimpleSwitch_get_time_since_epoch_us_result {
public:
SimpleSwitch_get_time_since_epoch_us_result(const SimpleSwitch_get_time_since_epoch_us_result&);
SimpleSwitch_get_time_since_epoch_us_result& operator=(const SimpleSwitch_get_time_since_epoch_us_result&);
SimpleSwitch_get_time_since_epoch_us_result() : success(0) {
}
virtual ~SimpleSwitch_get_time_since_epoch_us_result() throw();
int64_t success;
_SimpleSwitch_get_time_since_epoch_us_result__isset __isset;
void __set_success(const int64_t val);
bool operator == (const SimpleSwitch_get_time_since_epoch_us_result & rhs) const
{
if (!(success == rhs.success))
return false;
return true;
}
bool operator != (const SimpleSwitch_get_time_since_epoch_us_result &rhs) const {
return !(*this == rhs);
}
bool operator < (const SimpleSwitch_get_time_since_epoch_us_result & ) const;
uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;
};
typedef struct _SimpleSwitch_get_time_since_epoch_us_presult__isset {
_SimpleSwitch_get_time_since_epoch_us_presult__isset() : success(false) {}
bool success :1;
} _SimpleSwitch_get_time_since_epoch_us_presult__isset;
class SimpleSwitch_get_time_since_epoch_us_presult {
public:
virtual ~SimpleSwitch_get_time_since_epoch_us_presult() throw();
int64_t* success;
_SimpleSwitch_get_time_since_epoch_us_presult__isset __isset;
uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
};
class SimpleSwitchClient : virtual public SimpleSwitchIf {
public:
SimpleSwitchClient(apache::thrift::stdcxx::shared_ptr< ::apache::thrift::protocol::TProtocol> prot) {
setProtocol(prot);
}
SimpleSwitchClient(apache::thrift::stdcxx::shared_ptr< ::apache::thrift::protocol::TProtocol> iprot, apache::thrift::stdcxx::shared_ptr< ::apache::thrift::protocol::TProtocol> oprot) {
setProtocol(iprot,oprot);
}
private:
void setProtocol(apache::thrift::stdcxx::shared_ptr< ::apache::thrift::protocol::TProtocol> prot) {
setProtocol(prot,prot);
}
void setProtocol(apache::thrift::stdcxx::shared_ptr< ::apache::thrift::protocol::TProtocol> iprot, apache::thrift::stdcxx::shared_ptr< ::apache::thrift::protocol::TProtocol> oprot) {
piprot_=iprot;
poprot_=oprot;
iprot_ = iprot.get();
oprot_ = oprot.get();
}
public:
apache::thrift::stdcxx::shared_ptr< ::apache::thrift::protocol::TProtocol> getInputProtocol() {
return piprot_;
}
apache::thrift::stdcxx::shared_ptr< ::apache::thrift::protocol::TProtocol> getOutputProtocol() {
return poprot_;
}
int32_t mirroring_mapping_add(const int32_t mirror_id, const int32_t egress_port);
void send_mirroring_mapping_add(const int32_t mirror_id, const int32_t egress_port);
int32_t recv_mirroring_mapping_add();
int32_t mirroring_mapping_delete(const int32_t mirror_id);
void send_mirroring_mapping_delete(const int32_t mirror_id);
int32_t recv_mirroring_mapping_delete();
int32_t mirroring_mapping_get_egress_port(const int32_t mirror_id);
void send_mirroring_mapping_get_egress_port(const int32_t mirror_id);
int32_t recv_mirroring_mapping_get_egress_port();
int32_t set_egress_queue_depth(const int32_t port_num, const int32_t depth_pkts);
void send_set_egress_queue_depth(const int32_t port_num, const int32_t depth_pkts);
int32_t recv_set_egress_queue_depth();
int32_t set_all_egress_queue_depths(const int32_t depth_pkts);
void send_set_all_egress_queue_depths(const int32_t depth_pkts);
int32_t recv_set_all_egress_queue_depths();
int32_t set_egress_queue_rate(const int32_t port_num, const int64_t rate_pps);
void send_set_egress_queue_rate(const int32_t port_num, const int64_t rate_pps);
int32_t recv_set_egress_queue_rate();
int32_t set_all_egress_queue_rates(const int64_t rate_pps);
void send_set_all_egress_queue_rates(const int64_t rate_pps);
int32_t recv_set_all_egress_queue_rates();
int64_t get_time_elapsed_us();
void send_get_time_elapsed_us();
int64_t recv_get_time_elapsed_us();
int64_t get_time_since_epoch_us();
void send_get_time_since_epoch_us();
int64_t recv_get_time_since_epoch_us();
protected:
apache::thrift::stdcxx::shared_ptr< ::apache::thrift::protocol::TProtocol> piprot_;
apache::thrift::stdcxx::shared_ptr< ::apache::thrift::protocol::TProtocol> poprot_;
::apache::thrift::protocol::TProtocol* iprot_;
::apache::thrift::protocol::TProtocol* oprot_;
};
class SimpleSwitchProcessor : public ::apache::thrift::TDispatchProcessor {
protected:
::apache::thrift::stdcxx::shared_ptr<SimpleSwitchIf> iface_;
virtual bool dispatchCall(::apache::thrift::protocol::TProtocol* iprot, ::apache::thrift::protocol::TProtocol* oprot, const std::string& fname, int32_t seqid, void* callContext);
private:
typedef void (SimpleSwitchProcessor::*ProcessFunction)(int32_t, ::apache::thrift::protocol::TProtocol*, ::apache::thrift::protocol::TProtocol*, void*);
typedef std::map<std::string, ProcessFunction> ProcessMap;
ProcessMap processMap_;
void process_mirroring_mapping_add(int32_t seqid, ::apache::thrift::protocol::TProtocol* iprot, ::apache::thrift::protocol::TProtocol* oprot, void* callContext);
void process_mirroring_mapping_delete(int32_t seqid, ::apache::thrift::protocol::TProtocol* iprot, ::apache::thrift::protocol::TProtocol* oprot, void* callContext);
void process_mirroring_mapping_get_egress_port(int32_t seqid, ::apache::thrift::protocol::TProtocol* iprot, ::apache::thrift::protocol::TProtocol* oprot, void* callContext);
void process_set_egress_queue_depth(int32_t seqid, ::apache::thrift::protocol::TProtocol* iprot, ::apache::thrift::protocol::TProtocol* oprot, void* callContext);
void process_set_all_egress_queue_depths(int32_t seqid, ::apache::thrift::protocol::TProtocol* iprot, ::apache::thrift::protocol::TProtocol* oprot, void* callContext);
void process_set_egress_queue_rate(int32_t seqid, ::apache::thrift::protocol::TProtocol* iprot, ::apache::thrift::protocol::TProtocol* oprot, void* callContext);
void process_set_all_egress_queue_rates(int32_t seqid, ::apache::thrift::protocol::TProtocol* iprot, ::apache::thrift::protocol::TProtocol* oprot, void* callContext);
void process_get_time_elapsed_us(int32_t seqid, ::apache::thrift::protocol::TProtocol* iprot, ::apache::thrift::protocol::TProtocol* oprot, void* callContext);
void process_get_time_since_epoch_us(int32_t seqid, ::apache::thrift::protocol::TProtocol* iprot, ::apache::thrift::protocol::TProtocol* oprot, void* callContext);
public:
SimpleSwitchProcessor(::apache::thrift::stdcxx::shared_ptr<SimpleSwitchIf> iface) :
iface_(iface) {
processMap_["mirroring_mapping_add"] = &SimpleSwitchProcessor::process_mirroring_mapping_add;
processMap_["mirroring_mapping_delete"] = &SimpleSwitchProcessor::process_mirroring_mapping_delete;
processMap_["mirroring_mapping_get_egress_port"] = &SimpleSwitchProcessor::process_mirroring_mapping_get_egress_port;
processMap_["set_egress_queue_depth"] = &SimpleSwitchProcessor::process_set_egress_queue_depth;
processMap_["set_all_egress_queue_depths"] = &SimpleSwitchProcessor::process_set_all_egress_queue_depths;
processMap_["set_egress_queue_rate"] = &SimpleSwitchProcessor::process_set_egress_queue_rate;
processMap_["set_all_egress_queue_rates"] = &SimpleSwitchProcessor::process_set_all_egress_queue_rates;
processMap_["get_time_elapsed_us"] = &SimpleSwitchProcessor::process_get_time_elapsed_us;
processMap_["get_time_since_epoch_us"] = &SimpleSwitchProcessor::process_get_time_since_epoch_us;
}
virtual ~SimpleSwitchProcessor() {}
};
class SimpleSwitchProcessorFactory : public ::apache::thrift::TProcessorFactory {
public:
SimpleSwitchProcessorFactory(const ::apache::thrift::stdcxx::shared_ptr< SimpleSwitchIfFactory >& handlerFactory) :
handlerFactory_(handlerFactory) {}
::apache::thrift::stdcxx::shared_ptr< ::apache::thrift::TProcessor > getProcessor(const ::apache::thrift::TConnectionInfo& connInfo);
protected:
::apache::thrift::stdcxx::shared_ptr< SimpleSwitchIfFactory > handlerFactory_;
};
class SimpleSwitchMultiface : virtual public SimpleSwitchIf {
public:
SimpleSwitchMultiface(std::vector<apache::thrift::stdcxx::shared_ptr<SimpleSwitchIf> >& ifaces) : ifaces_(ifaces) {
}
virtual ~SimpleSwitchMultiface() {}
protected:
std::vector<apache::thrift::stdcxx::shared_ptr<SimpleSwitchIf> > ifaces_;
SimpleSwitchMultiface() {}
void add(::apache::thrift::stdcxx::shared_ptr<SimpleSwitchIf> iface) {
ifaces_.push_back(iface);
}
public:
int32_t mirroring_mapping_add(const int32_t mirror_id, const int32_t egress_port) {
size_t sz = ifaces_.size();
size_t i = 0;
for (; i < (sz - 1); ++i) {
ifaces_[i]->mirroring_mapping_add(mirror_id, egress_port);
}
return ifaces_[i]->mirroring_mapping_add(mirror_id, egress_port);
}
int32_t mirroring_mapping_delete(const int32_t mirror_id) {
size_t sz = ifaces_.size();
size_t i = 0;
for (; i < (sz - 1); ++i) {
ifaces_[i]->mirroring_mapping_delete(mirror_id);
}
return ifaces_[i]->mirroring_mapping_delete(mirror_id);
}
int32_t mirroring_mapping_get_egress_port(const int32_t mirror_id) {
size_t sz = ifaces_.size();
size_t i = 0;
for (; i < (sz - 1); ++i) {
ifaces_[i]->mirroring_mapping_get_egress_port(mirror_id);
}
return ifaces_[i]->mirroring_mapping_get_egress_port(mirror_id);
}
int32_t set_egress_queue_depth(const int32_t port_num, const int32_t depth_pkts) {
size_t sz = ifaces_.size();
size_t i = 0;
for (; i < (sz - 1); ++i) {
ifaces_[i]->set_egress_queue_depth(port_num, depth_pkts);
}
return ifaces_[i]->set_egress_queue_depth(port_num, depth_pkts);
}
int32_t set_all_egress_queue_depths(const int32_t depth_pkts) {
size_t sz = ifaces_.size();
size_t i = 0;
for (; i < (sz - 1); ++i) {
ifaces_[i]->set_all_egress_queue_depths(depth_pkts);
}
return ifaces_[i]->set_all_egress_queue_depths(depth_pkts);
}
int32_t set_egress_queue_rate(const int32_t port_num, const int64_t rate_pps) {
size_t sz = ifaces_.size();
size_t i = 0;
for (; i < (sz - 1); ++i) {
ifaces_[i]->set_egress_queue_rate(port_num, rate_pps);
}
return ifaces_[i]->set_egress_queue_rate(port_num, rate_pps);
}
int32_t set_all_egress_queue_rates(const int64_t rate_pps) {
size_t sz = ifaces_.size();
size_t i = 0;
for (; i < (sz - 1); ++i) {
ifaces_[i]->set_all_egress_queue_rates(rate_pps);
}
return ifaces_[i]->set_all_egress_queue_rates(rate_pps);
}
int64_t get_time_elapsed_us() {
size_t sz = ifaces_.size();
size_t i = 0;
for (; i < (sz - 1); ++i) {
ifaces_[i]->get_time_elapsed_us();
}
return ifaces_[i]->get_time_elapsed_us();
}
int64_t get_time_since_epoch_us() {
size_t sz = ifaces_.size();
size_t i = 0;
for (; i < (sz - 1); ++i) {
ifaces_[i]->get_time_since_epoch_us();
}
return ifaces_[i]->get_time_since_epoch_us();
}
};
// The 'concurrent' client is a thread safe client that correctly handles
// out of order responses. It is slower than the regular client, so should
// only be used when you need to share a connection among multiple threads
class SimpleSwitchConcurrentClient : virtual public SimpleSwitchIf {
public:
SimpleSwitchConcurrentClient(apache::thrift::stdcxx::shared_ptr< ::apache::thrift::protocol::TProtocol> prot) {
setProtocol(prot);
}
SimpleSwitchConcurrentClient(apache::thrift::stdcxx::shared_ptr< ::apache::thrift::protocol::TProtocol> iprot, apache::thrift::stdcxx::shared_ptr< ::apache::thrift::protocol::TProtocol> oprot) {
setProtocol(iprot,oprot);
}
private:
void setProtocol(apache::thrift::stdcxx::shared_ptr< ::apache::thrift::protocol::TProtocol> prot) {
setProtocol(prot,prot);
}
void setProtocol(apache::thrift::stdcxx::shared_ptr< ::apache::thrift::protocol::TProtocol> iprot, apache::thrift::stdcxx::shared_ptr< ::apache::thrift::protocol::TProtocol> oprot) {
piprot_=iprot;
poprot_=oprot;
iprot_ = iprot.get();
oprot_ = oprot.get();
}
public:
apache::thrift::stdcxx::shared_ptr< ::apache::thrift::protocol::TProtocol> getInputProtocol() {
return piprot_;
}
apache::thrift::stdcxx::shared_ptr< ::apache::thrift::protocol::TProtocol> getOutputProtocol() {
return poprot_;
}
int32_t mirroring_mapping_add(const int32_t mirror_id, const int32_t egress_port);
int32_t send_mirroring_mapping_add(const int32_t mirror_id, const int32_t egress_port);
int32_t recv_mirroring_mapping_add(const int32_t seqid);
int32_t mirroring_mapping_delete(const int32_t mirror_id);
int32_t send_mirroring_mapping_delete(const int32_t mirror_id);
int32_t recv_mirroring_mapping_delete(const int32_t seqid);
int32_t mirroring_mapping_get_egress_port(const int32_t mirror_id);
int32_t send_mirroring_mapping_get_egress_port(const int32_t mirror_id);
int32_t recv_mirroring_mapping_get_egress_port(const int32_t seqid);
int32_t set_egress_queue_depth(const int32_t port_num, const int32_t depth_pkts);
int32_t send_set_egress_queue_depth(const int32_t port_num, const int32_t depth_pkts);
int32_t recv_set_egress_queue_depth(const int32_t seqid);
int32_t set_all_egress_queue_depths(const int32_t depth_pkts);
int32_t send_set_all_egress_queue_depths(const int32_t depth_pkts);
int32_t recv_set_all_egress_queue_depths(const int32_t seqid);
int32_t set_egress_queue_rate(const int32_t port_num, const int64_t rate_pps);
int32_t send_set_egress_queue_rate(const int32_t port_num, const int64_t rate_pps);
int32_t recv_set_egress_queue_rate(const int32_t seqid);
int32_t set_all_egress_queue_rates(const int64_t rate_pps);
int32_t send_set_all_egress_queue_rates(const int64_t rate_pps);
int32_t recv_set_all_egress_queue_rates(const int32_t seqid);
int64_t get_time_elapsed_us();
int32_t send_get_time_elapsed_us();
int64_t recv_get_time_elapsed_us(const int32_t seqid);
int64_t get_time_since_epoch_us();
int32_t send_get_time_since_epoch_us();
int64_t recv_get_time_since_epoch_us(const int32_t seqid);
protected:
apache::thrift::stdcxx::shared_ptr< ::apache::thrift::protocol::TProtocol> piprot_;
apache::thrift::stdcxx::shared_ptr< ::apache::thrift::protocol::TProtocol> poprot_;
::apache::thrift::protocol::TProtocol* iprot_;
::apache::thrift::protocol::TProtocol* oprot_;
::apache::thrift::async::TConcurrentClientSyncInfo sync_;
};
#ifdef _MSC_VER
#pragma warning( pop )
#endif
} // namespace
#endif
| 34.865591 | 196 | 0.784558 | [
"vector"
] |
e5958676aae8cebb8fd44210611ee69757077d52 | 3,766 | h | C | src/lib/lgui/internal/dragdroptrackhelper.h | frank256/lgui | 4eae1ae100756256863a84f7698ced6584387e0f | [
"BSD-3-Clause"
] | 8 | 2018-09-25T21:09:07.000Z | 2022-01-25T10:37:17.000Z | src/lib/lgui/internal/dragdroptrackhelper.h | frank256/lgui | 4eae1ae100756256863a84f7698ced6584387e0f | [
"BSD-3-Clause"
] | 3 | 2018-09-28T21:44:06.000Z | 2021-12-23T17:34:39.000Z | src/lib/lgui/internal/dragdroptrackhelper.h | frank256/lgui | 4eae1ae100756256863a84f7698ced6584387e0f | [
"BSD-3-Clause"
] | 2 | 2021-03-01T14:10:05.000Z | 2022-01-27T02:09:43.000Z | /* _ _
* | | (_)
* | | __ _ _ _ _
* | | / _` || | | || |
* | || (_| || |_| || |
* |_| \__, | \__,_||_|
* __/ |
* |___/
*
* Copyright (c) 2015-22 frank256
*
* License (BSD):
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder 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.
*/
#ifndef LGUI_DRAGDROPTRACKHELPER_H
#define LGUI_DRAGDROPTRACKHELPER_H
#include "lgui/widget.h"
#include "lgui/dragrepresentation.h"
#include "eventdistributor.h"
#include "mousestate.h"
#include <vector>
namespace lgui {
namespace dtl {
class DragDropTrackHelper {
public:
explicit DragDropTrackHelper(EventDistributor& distr, const MouseState& last_mouse_state)
: mdistr(distr), mlast_mouse_state(last_mouse_state), mdrag_repr(nullptr) {}
DragRepresentation* drag_representation() { return mdrag_repr; }
const DragRepresentation* drag_representation() const { return mdrag_repr; }
void remove_not_under_drag(const WidgetTreeTraversalStack& traversal_stack, double timestamp);
void register_drag_entered(const WidgetTreeTraversalStack& stack, double timestamp, int button);
void prepare_drag_drop_operation(DragRepresentation* drag_repr, Position mouse_pos);
void finish_drag_drop_operation(Position mouse_pos, int button, double timestamp);
void clear_under_drag();
void abort_drag(bool send_events, bool send_dd_end_to_gone_src);
void remove_subtree_from_under_drag(Widget* widget, bool send_events,
bool send_dd_end_to_gone_src);
void remove_all_except_subtree_from_under_drag(Widget* widget, bool send_events,
bool send_dd_end_to_gone_src);
void reregister_drag(const WidgetTreeTraversalStack& traversal_stack, bool send_move);
private:
void remove_widget_and_children_from_under_drag(Widget* widget, bool send_events,
bool send_dd_end_to_gone_src,
bool invert_predicate);
EventDistributor& mdistr;
const MouseState& mlast_mouse_state;
std::vector<Widget*> mwidgets_under_drag;
DragRepresentation* mdrag_repr;
};
}
}
#endif //LGUI_DRAGDROPTRACKHELPER_H
| 40.934783 | 104 | 0.698885 | [
"vector"
] |
e5b81f1ca6417b934664654f4b0b25c68e21b101 | 4,428 | h | C | kernel/src/drivers/ahci/ahci_device.h | Andrispowq/HackOS | 73b24450281abbbe5f37b8f2c02904d82a255c25 | [
"Apache-2.0"
] | 10 | 2020-12-10T16:36:41.000Z | 2021-11-08T12:01:05.000Z | kernel/src/drivers/ahci/ahci_device.h | Andrispowq/HackOS | 73b24450281abbbe5f37b8f2c02904d82a255c25 | [
"Apache-2.0"
] | null | null | null | kernel/src/drivers/ahci/ahci_device.h | Andrispowq/HackOS | 73b24450281abbbe5f37b8f2c02904d82a255c25 | [
"Apache-2.0"
] | 1 | 2020-10-02T05:42:21.000Z | 2020-10-02T05:42:21.000Z | #ifndef AHCI_DEVICE_H
#define AHCI_DEVICE_H
#include "lib/stdio.h"
#include "acpi/pci/pci.h"
#include "lib/data_structures/vector.h"
#include "drivers/device/device.h"
#define ATA_DEV_BUSY 0x80
#define ATA_DEV_DRQ 0x08
#define ATA_CMD_READ_DMA_EX 0x25
#define HBA_PxIS_TFES (1 << 30)
namespace AHCI
{
enum PortType
{
None = 0,
SATA = 1,
SEMB = 2,
PM = 3,
SATAPI = 4,
};
enum FIS_TYPE
{
FIS_TYPE_REG_H2D = 0x27,
FIS_TYPE_REG_D2H = 0x34,
FIS_TYPE_DMA_ACT = 0x39,
FIS_TYPE_DMA_SETUP = 0x41,
FIS_TYPE_DATA = 0x46,
FIS_TYPE_BIST = 0x58,
FIS_TYPE_PIO_SETUP = 0x5F,
FIS_TYPE_DEV_BITS = 0xA1,
};
struct HBAPort
{
uint32_t CommandListBase;
uint32_t CommandListBaseUpper;
uint32_t FISBaseAddress;
uint32_t FISBaseAddressUpper;
uint32_t InterruptStatus;
uint32_t InterruptEnable;
uint32_t CommandStatus;
uint32_t Reserved0;
uint32_t TaskFileData;
uint32_t Signature;
uint32_t SataStatus;
uint32_t SataControl;
uint32_t SataError;
uint32_t SataActive;
uint32_t CommandIssue;
uint32_t SataNotification;
uint32_t FISSwitchControl;
uint32_t Reserved1[11];
uint32_t Vendor[4];
};
struct HBAMemory
{
uint32_t HostCapability;
uint32_t GlobalHostControl;
uint32_t InterruptStatus;
uint32_t PortsImplemented;
uint32_t Version;
uint32_t CCCControl;
uint32_t CCCPorts;
uint32_t EnclosureManagementLocation;
uint32_t EnclosureManagementControl;
uint32_t HostCapabilitiesExtended;
uint32_t BIOSHandoffControlStatus;
uint8_t Reserved0[0x74];
uint8_t Vendor[0x60];
HBAPort Ports[1];
};
struct HBACommandHeader
{
uint8_t CommandFISLength : 5;
uint8_t ATAPI : 1;
uint8_t Write : 1;
uint8_t Prefetchable : 1;
uint8_t Reset : 1;
uint8_t BIST : 1;
uint8_t ClearBusy : 1;
uint8_t Reserved0 : 1;
uint8_t PortMultiplier : 4;
uint16_t PRDTLength;
uint32_t PRDBCount;
uint32_t CommandTableBaseAddress;
uint32_t CommandTableBaseAddressUpper;
uint32_t Reserved1[4];
};
struct HBAPRDTEntry
{
uint32_t DataBaseAddress;
uint32_t DataBaseAddressUpper;
uint32_t Reserved0;
uint32_t ByteCount:22;
uint32_t Reserved1:9;
uint32_t InterruptOnCompletion:1;
};
struct HBACommandTable
{
uint8_t CommandFIS[64];
uint8_t ATAPICommand[16];
uint8_t Reserved[48];
HBAPRDTEntry PRDTEntry[];
};
struct FIS_REG_H2D
{
uint8_t FISType;
uint8_t PortMultiplier : 4;
uint8_t Reserved0 : 3;
uint8_t CommandControl : 1;
uint8_t Command;
uint8_t FeatureLow;
uint8_t LBA0;
uint8_t LBA1;
uint8_t LBA2;
uint8_t DeviceRegister;
uint8_t LBA3;
uint8_t LBA4;
uint8_t LBA5;
uint8_t FeatureHigh;
uint8_t CountLow;
uint8_t CountHigh;
uint8_t ISOCommandCompletion;
uint8_t Control;
uint8_t Reserved1[4];
};
class Port
{
public:
void Configure();
bool Read(uint64_t LBA, void* buffer, uint32_t sectorCount);
bool Write(uint64_t LBA, void* buffer, uint32_t sectorCount);
private:
void StartCMD();
void StopCMD();
public:
HBAPort* HBAPortPtr;
PortType AHCIPortType;
uint8_t PortNumber;
};
class AHCIDevice : public Device
{
public:
AHCIDevice(Port* port);
virtual DeviceType GetType() override { return DeviceType::AHCI; };
virtual void Read(uint64_t LBA, void* buffer, uint64_t size) override;
virtual void Write(uint64_t LBA, void* buffer, uint64_t size) override;
private:
Port* port;
};
class AHCIDriver
{
public:
AHCIDriver(PCI::PCIDeviceHeader* PCIBaseAddress);
~AHCIDriver() {}
vector<AHCIDevice*> PreparePorts();
private:
PCI::PCIDeviceHeader* PCIBaseAddress;
HBAMemory* ABAR;
Port* Ports[32];
uint8_t PortCount;
};
};
#endif | 22.591837 | 79 | 0.607046 | [
"vector"
] |
d5f9181361207871eb8d28aa0de99b63492f2bb8 | 6,277 | h | C | lib/overnet/router.h | PowerOlive/garnet | 16b5b38b765195699f41ccb6684cc58dd3512793 | [
"BSD-3-Clause"
] | null | null | null | lib/overnet/router.h | PowerOlive/garnet | 16b5b38b765195699f41ccb6684cc58dd3512793 | [
"BSD-3-Clause"
] | null | null | null | lib/overnet/router.h | PowerOlive/garnet | 16b5b38b765195699f41ccb6684cc58dd3512793 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2018 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.
#pragma once
#include <unordered_map>
#include "callback.h"
#include "closed_ptr.h"
#include "lazy_slice.h"
#include "once_fn.h"
#include "routable_message.h"
#include "routing_table.h"
#include "sink.h"
#include "slice.h"
#include "timer.h"
#include "trace.h"
namespace overnet {
namespace router_impl {
struct LocalStreamId {
NodeId peer;
StreamId stream_id;
uint64_t Hash() const { return peer.Hash() ^ stream_id.Hash(); }
};
inline bool operator==(const LocalStreamId& lhs, const LocalStreamId& rhs) {
return lhs.peer == rhs.peer && lhs.stream_id == rhs.stream_id;
}
} // namespace router_impl
} // namespace overnet
namespace std {
template <>
struct hash<overnet::router_impl::LocalStreamId> {
size_t operator()(const overnet::router_impl::LocalStreamId& id) const {
return id.Hash();
}
};
} // namespace std
namespace overnet {
inline auto ForwardingPayloadFactory(Slice payload) {
return [payload = std::move(payload)](auto args) mutable {
return std::move(payload);
};
}
struct Message final {
RoutableMessage header;
LazySlice make_payload;
TimeStamp received;
static Message SimpleForwarder(RoutableMessage msg, Slice payload,
TimeStamp received) {
return Message{std::move(msg), ForwardingPayloadFactory(payload), received};
}
};
class Link {
public:
virtual ~Link() {}
virtual void Close(Callback<void> quiesced) = 0;
virtual void Forward(Message message) = 0;
virtual LinkMetrics GetLinkMetrics() = 0;
};
template <class T = Link>
using LinkPtr = ClosedPtr<T, Link>;
template <class T, class... Args>
LinkPtr<T> MakeLink(Args&&... args) {
return MakeClosedPtr<T, Link>(std::forward<Args>(args)...);
}
class Router final {
public:
class StreamHandler {
public:
virtual ~StreamHandler() {}
virtual void Close(Callback<void> quiesced) = 0;
virtual void HandleMessage(SeqNum seq, TimeStamp received, Slice data) = 0;
};
Router(Timer* timer, TraceSink trace_sink, NodeId node_id,
bool allow_threading)
: timer_(timer),
trace_sink_(trace_sink.Decorate([this](const std::string& msg) {
std::ostringstream out;
out << "Router[" << this << "] " << msg;
return out.str();
})),
node_id_(node_id),
routing_table_(node_id, timer, trace_sink_, allow_threading) {
UpdateRoutingTable({NodeMetrics(node_id, 0)}, {}, false);
}
~Router();
void Close(Callback<void> quiesced);
// Forward a message to either ourselves or a link
void Forward(Message message);
// Register a (locally handled) stream into this Router
Status RegisterStream(NodeId peer, StreamId stream_id,
StreamHandler* stream_handler);
Status UnregisterStream(NodeId peer, StreamId stream_id,
StreamHandler* stream_handler);
// Register a link to another router (usually on a different machine)
void RegisterLink(LinkPtr<> link);
NodeId node_id() const { return node_id_; }
Timer* timer() const { return timer_; }
void UpdateRoutingTable(std::vector<NodeMetrics> node_metrics,
std::vector<LinkMetrics> link_metrics) {
UpdateRoutingTable(std::move(node_metrics), std::move(link_metrics), false);
}
void BlockUntilNoBackgroundUpdatesProcessing() {
routing_table_.BlockUntilNoBackgroundUpdatesProcessing();
}
// Return true if this router believes a route exists to a particular node.
bool HasRouteTo(NodeId node_id) {
return node_id == node_id_ || link_holder(node_id)->link() != nullptr;
}
TraceSink trace_sink() const { return trace_sink_; }
private:
Timer* const timer_;
const TraceSink trace_sink_;
const NodeId node_id_;
void UpdateRoutingTable(std::vector<NodeMetrics> node_metrics,
std::vector<LinkMetrics> link_metrics,
bool flush_old_nodes);
void MaybeStartPollingLinkChanges();
void MaybeStartFlushingOldEntries();
void CloseLinks(Callback<void> quiesced);
void CloseStreams(Callback<void> quiesced);
class StreamHolder {
public:
void HandleMessage(SeqNum seq, TimeStamp received, Slice payload);
Status SetHandler(StreamHandler* handler);
Status ClearHandler(StreamHandler* handler);
void Close(Callback<void> quiesced) {
if (handler_ != nullptr)
handler_->Close(std::move(quiesced));
}
bool has_handler() { return handler_ != nullptr; }
private:
struct Pending {
SeqNum seq;
TimeStamp received;
Slice payload;
};
StreamHandler* handler_ = nullptr;
std::vector<Pending> pending_;
};
class LinkHolder {
public:
LinkHolder(NodeId target, TraceSink trace_sink)
: trace_sink_(
trace_sink.Decorate([this, target](const std::string& msg) {
std::ostringstream out;
out << "Link[" << this << ";to=" << target << "] " << msg;
return out.str();
})) {}
void Forward(Message message);
void SetLink(Link* link, uint32_t path_mss);
Link* link() { return link_; }
uint32_t path_mss() { return path_mss_; }
private:
const TraceSink trace_sink_;
Link* link_ = nullptr;
uint32_t path_mss_ = std::numeric_limits<uint32_t>::max();
std::vector<Message> pending_;
};
LinkHolder* link_holder(NodeId node_id) {
auto it = links_.find(node_id);
if (it != links_.end())
return &it->second;
return &links_
.emplace(std::piecewise_construct,
std::forward_as_tuple(node_id),
std::forward_as_tuple(node_id, trace_sink_))
.first->second;
}
typedef router_impl::LocalStreamId LocalStreamId;
bool shutting_down_ = false;
std::unordered_map<uint64_t, LinkPtr<>> owned_links_;
std::unordered_map<LocalStreamId, StreamHolder> streams_;
std::unordered_map<NodeId, LinkHolder> links_;
RoutingTable routing_table_;
Optional<Timeout> poll_link_changes_timeout_;
Optional<Timeout> flush_old_nodes_timeout_;
};
} // namespace overnet
| 29.469484 | 80 | 0.671977 | [
"vector"
] |
9102460c05c601950abf0715257665c57057dcbe | 910 | h | C | src/aadcUser/src/HSOG_Runtime/adtf/decoder/DepthImageDecoder.h | AppliedAutonomyOffenburg/AADC_2015_A2O | 19a2ac67d743ad23e5a259ca70aed6b3d1f2e3ac | [
"BSD-4-Clause"
] | 1 | 2018-09-09T21:39:29.000Z | 2018-09-09T21:39:29.000Z | src/aadcUser/src/HSOG_Runtime/adtf/decoder/DepthImageDecoder.h | TeamAutonomousCarOffenburg/A2O_2015 | 19a2ac67d743ad23e5a259ca70aed6b3d1f2e3ac | [
"BSD-4-Clause"
] | null | null | null | src/aadcUser/src/HSOG_Runtime/adtf/decoder/DepthImageDecoder.h | TeamAutonomousCarOffenburg/A2O_2015 | 19a2ac67d743ad23e5a259ca70aed6b3d1f2e3ac | [
"BSD-4-Clause"
] | 1 | 2016-04-05T06:34:08.000Z | 2016-04-05T06:34:08.000Z | #pragma once
#include "Decoder.h"
#include "meta/ICameraConfig.h"
#include <vector>
namespace A2O {
/**
* The DepthImageDecoder manages the decoding of a depth image pin.
*
* \author Stefan Glaser
*/
class DepthImageDecoder : public Decoder {
public:
DepthImageDecoder(ICameraConfig::ConstPtr config, IEventLogger::ConstPtr logger);
virtual ~DepthImageDecoder();
virtual std::vector<IPerceptor::ConstPtr> decode(const InputPin& pin,
adtf::IMediaTypeDescription* mediaTypeDescription,
adtf::IMediaSample* mediaSample);
protected:
/** The name of the represented gyro perceptor. */
std::string _perceptiorName;
/** The time of the measurement. */
long _time;
/** The width of the camera image. */
unsigned int _frameWidth;
/** The height of the camera image. */
unsigned int _frameHeight;
double _focalLengthX;
double _focalLengthY;
};
}
| 20.681818 | 83 | 0.706593 | [
"vector"
] |
910f5c59527e062f3cc473aa39cba3002952c2c2 | 40,189 | h | C | win32/srkwin32app_defs.h | matiasinsaurralde/sonork | 25514411bca36368fc2719b6fb8ab1367e1bb218 | [
"BSD-Source-Code"
] | 2 | 2016-06-17T07:40:53.000Z | 2019-10-31T19:37:55.000Z | win32/srkwin32app_defs.h | matiasinsaurralde/sonork | 25514411bca36368fc2719b6fb8ab1367e1bb218 | [
"BSD-Source-Code"
] | null | null | null | win32/srkwin32app_defs.h | matiasinsaurralde/sonork | 25514411bca36368fc2719b6fb8ab1367e1bb218 | [
"BSD-Source-Code"
] | null | null | null | #if !defined(SRKWIN32APP_DEFS_H)
#define SRKWIN32APP_DEFS_H
/*
Sonork Messaging System
Portions Copyright (C) 2001 Sonork SRL:
This program is free software; you can redistribute it and/or modify
it under the terms of the Sonork Source Code License (SSCL).
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
SSCL for more details.
You should have received a copy of the SSCL along with this program;
if not, write to sscl@sonork.com.
You may NOT use this source code before reading and accepting the
Sonork Source Code License (SSCL).
*/
#include "srkwin_defs.h"
// ----------------------------------------------------------------------------
struct TSonorkExtUserData;
struct TSonorkMsg;
struct TSonorkWappData;
struct TSonorkError;
// ----------------------------------------------------------------------------
#define SONORK_APP_VERSION_MAJOR SONORK_CLIENT_VERSION_MAJOR
#define SONORK_APP_VERSION_MINOR SONORK_CLIENT_VERSION_MINOR
#define SONORK_APP_VERSION_PATCH SONORK_CLIENT_VERSION_PATCH
#define SONORK_APP_VERSION_BUILD SONORK_CLIENT_VERSION_BUILD
#define SONORK_APP_VERSION_NUMBER SONORK_CLIENT_VERSION_NUMBER
// -------------------------------------------------------------------------
// App flags & values
#define SONORK_APP_MAX_MSG_TEMPLATES 128
#define SONORK_APP_MAX_EXT_APPS 128
#define SONORK_APP_MAX_WEB_APPS 128
#define SONORK_APP_CONFIG_FILE_NAME_SIZE 16
#define SONORK_APP_MAX_UTS_CONNECTIONS 32
#define SONORK_APP_HTML_ENGINE_VERSION 1
#define SONORK_APP_MAX_MSG_TEXT_LENGTH (12288*2)
// ----------------------------------------------------------------------------
#define SONORK_SECS_FOR_USER_RESPONSE 60
#define SONORK_SECS_FOR_CIRCUIT_CONNECTION 20
#define SONORK_SECS_FOR_CIRCUIT_ACCEPTANCE 5
#define SONORK_SECS_FOR_PROTOCOL_INITIATION 20
#define SONORK_SECS_FOR_QUERY_REPLY (SONORK_SECS_FOR_CIRCUIT_CONNECTION)
#define SONORK_SECS_FOR_APP_TO_START 3
#define SONORK_MSECS_FOR_CIRCUIT_CONNECTION (SONORK_SECS_FOR_CIRCUIT_CONNECTION*1000)
#define SONORK_MSECS_FOR_PROTOCOL_INITIATION (SONORK_SECS_FOR_PROTOCOL_INITIATION*1000)
#define SONORK_MSECS_FOR_QUERY_REPLY (SONORK_SECS_FOR_QUERY_REPLY*1000)
#define SONORK_MSECS_FOR_CIRCUIT_ACCEPTANCE (SONORK_SECS_FOR_CIRCUIT_ACCEPTANCE*1000)
#define SONORK_APP_VISIBILITY_GROUPS 7
#define SONORK_UI_EVENT_TTL_FOREVER (0x3fffffff)
// ----------------------------------------------------------------------------
#define SONORK_USER_PIC_MAX_BYTES 32767
#define SONORK_USER_PIC_SW 104
#define SONORK_USER_PIC_SH 130
// ----------------------------------------------------------------------------
#define IS_SONORK_APP_SERVICE_ID(n) ((n)==SONORK_SERVICE_ID_NONE || (n)==SONORK_SERVICE_ID_SONORK)
// ----------------------------------------------------------------------------
enum SONORK_WIN32_APP_RUN_FLAG
{
SONORK_WAPP_RF_ALLOW_INTERNET_MODE = 0x00000001
//, SONORK_WAPP_RF_ALLOW_INTRANET_MODE = 0x00000002
, SONORK_WAPP_RF_IN_IPC_HANDLER = 0x00000100
, SONORK_WAPP_RF_BLINK_ON = 0x00001000
, SONORK_WAPP_RF_DISABLE_ALARMS = 0x00002000
, SONORK_WAPP_RF_TRACKER_SYNCH_PENDING = 0x00004000
, SONORK_WAPP_RF_TRACKER_CACHE_LOADED = 0x00008000
, SONORK_WAPP_RF_MSG_TEMPLATES_LOADED = 0x00010000
, SONORK_WAPP_RF_UNINSTALL = 0x00020000
, SONORK_WAPP_RF_REFRESHING_LIST = 0x00040000
, SONORK_WAPP_RF_CX_PENDING = 0x00100000
, SONORK_WAPP_RF_CONNECT_NOW = 0x00200000
, SONORK_WAPP_RF_SELF_DISCONNECT = 0x00400000
, SONORK_WAPP_RF_NO_AUTO_LOGIN = 0x00800000
, SONORK_WAPP_RF_NO_PROFILE_EVENTS = 0x01000000
, SONORK_WAPP_RF_SETUP_INIT = 0x02000000
, SONORK_WAPP_RF_SHOW_LOGIN = 0x04000000
, SONORK_WAPP_RF_APP_INITIALIZED = 0x10000000
, SONORK_WAPP_RF_APP_TERMINATING = 0x20000000
, SONORK_WAPP_RF_APP_TERMINATED = 0x40000000
};
// ----------------------------------------------------------------------------
enum SONORK_WIN32_APP_CFG_FLAG
{
SONORK_WAPP_CF_NO_CLOSE = 0x00000001
, SONORK_WAPP_CF_NO_UTS = 0x00000002
, SONORK_WAPP_CF_NO_INVISIBLE = 0x00000004
, SONORK_WAPP_CF_NO_VISIBILITY = 0x00000008
, SONORK_WAPP_CF_NO_USER_SELECT = 0x00000010
, SONORK_WAPP_CF_NO_NET_CONFIG = 0x00000020
, SONORK_WAPP_CF_NO_DISCONNECT = 0x00000100
, SONORK_WAPP_CF_POPUP_MSG_WIN = 0x00000200
, SONORK_WAPP_CF_NO_FILE_SEND = 0x00001000
, SONORK_WAPP_CF_NO_FILE_RECV = 0x00002000
, SONORK_WAPP_CF_INTRANET_MODE = 0x02000000
};
// ----------------------------------------------------------------------------
enum SONORK_APP_COMMAND
{
SONORK_APP_COMMAND_TERMINATE
, SONORK_APP_COMMAND_REFRESH
, SONORK_APP_COMMAND_FOREGROUND_HWND
, SONORK_APP_COMMAND_FOCUS_HWND
, SONORK_APP_COMMAND_HALTED =100 // Internal use only!!
, SONORK_APP_COMMAND_WIN_CREATED // Internal use only!!
, SONORK_APP_COMMAND_WIN_DESTROYED // Internal use only!!
, SONORK_APP_COMMAND_LOGIN_FATAL_ERROR // Internal use only!!
, SONORK_APP_COMMAND_SWITCH_MODE
, SONORK_APP_COMMAND_CLEAR_IPC_ENTRY
, SONORK_APP_COMMAND_RELOAD_EXT_APPS
, SONORK_APP_COMMAND_PSEUDO_TASK_RESULT
};
// ----------------------------------------------------------------------------
enum SONORK_APP_START_MODE
{
SONORK_APP_START_MODE_CANCEL = -1
, SONORK_APP_START_MODE_ASK = 0
, SONORK_APP_START_MODE_INTRANET
, SONORK_APP_START_MODE_INTERNET
, SONORK_APP_START_MODES
};
// ----------------------------------------------------------------------------
enum SONORK_APP_CFG_ITEM
{
SONORK_APP_CFG_NONE
, SONORK_APP_CFG_CLIENT_SERVER_PROFILE
};
// ----------------------------------------------------------------------------
enum SONORK_APP_DIR
{
SONORK_APP_DIR_ROOT
, SONORK_APP_DIR_DATA
, SONORK_APP_DIR_TEMP
, SONORK_APP_DIR_USERS
, SONORK_APP_DIR_APPS
, SONORK_APP_DIR_BIN
, SONORK_APP_DIR_MSGTPL
, SONORK_APP_DIR_SOUND
, SONORK_APP_DIR_SKIN
};
// ----------------------------------------------------------------------------
enum SONORK_APP_SOUND
{
SONORK_APP_SOUND_NONE
, SONORK_APP_SOUND_ERROR
, SONORK_APP_SOUND_NOTICE
, SONORK_APP_SOUND_CONNECT
, SONORK_APP_SOUND_REMIND
, SONORK_APP_SOUND_ONLINE
, SONORK_APP_SOUND_MSG_LO
, SONORK_APP_SOUND_MSG_HI
, SONORK_APP_SOUND_TRACKER
};
// ----------------------------------------------------------------------------
enum SONORK_APP_COUNTER
{
SONORK_APP_COUNTER_EVENTS
, SONORK_APP_COUNTER_UNREAD_MSGS
, SONORK_APP_COUNTER_PENDING_AUTHS
, SONORK_APP_COUNTER_SYS_CONSOLE
, SONORK_APP_COUNTERS
};
// ----------------------------------------------------------------------------
// Application tasks:
// When the application executes a request on Sonork, and the request
// handler is the application itself and not a window. The application
// stores the pending task's information in a <TSonorkAppTask> structure
// and places this structure in the <win32.task_queue>.
// ----------------------------------------------------------------------------
enum SONORK_APP_TASK_TYPE
{
SONORK_APP_TASK_NONE
, SONORK_APP_TASK_SEND_MSG
, SONORK_APP_TASK_SEND_SERVICE_MSG
, SONORK_APP_TASK_EXPORT_SERVICE
};
// ----------------------------------------------------------------------------
enum SONORK_APP_TASK_EXPORT_OP
{
SONORK_APP_TASK_EXPORT_OP_ADD
, SONORK_APP_TASK_EXPORT_OP_SET
, SONORK_APP_TASK_EXPORT_OP_DEL
, SONORK_APP_TASK_EXPORT_OP_KILL// Same as DEL, but entry is no longer valid
};
// ----------------------------------------------------------------------------
enum SONORK_UI_EVENT_TYPE
{
SONORK_UI_EVENT_NONE
, SONORK_UI_EVENT_SONORK_CONNECT
, SONORK_UI_EVENT_SONORK_DISCONNECT
, SONORK_UI_EVENT_WARNING
, SONORK_UI_EVENT_ERROR
, SONORK_UI_EVENT_USER_CONNECT
, SONORK_UI_EVENT_USER_DISCONNECT
, SONORK_UI_EVENT_TASK_START
, SONORK_UI_EVENT_TASK_END
, SONORK_UI_EVENT_ADD_USER
, SONORK_UI_EVENT_DEL_USER
, SONORK_UI_EVENT_UTS_LINKED
, SONORK_UI_EVENT_UTS_UNLINKED
, SONORK_UI_EVENT_EVENT_COUNT
, SONORK_UI_EVENT_SEL_COUNT
, SONORK_UI_EVENT_DEBUG
, SONORK_UI_EVENT_INCOMMING_EMAIL
, SONORK_UI_EVENT_SYS_MSG
, SONORK_UI_EVENT_USER_MSG
};
// ----------------------------------------------------------------------------
enum SONORK_UI_EVENT_FLAGS
{
SONORK_UI_EVENT_F_BICHO = 0x00000001
, SONORK_UI_EVENT_F_NO_BICHO = 0x00000000 // For clarity
, SONORK_UI_EVENT_F_SOUND = 0x00000002
, SONORK_UI_EVENT_F_NO_SOUND = 0x00000000 // For clarity
, SONORK_UI_EVENT_F_LOG = 0x00000004
, SONORK_UI_EVENT_F_NO_LOG = 0x00000000 // For clarity
, SONORK_UI_EVENT_F_LOG_AS_UNREAD = 0x00000010 // only if F_LOG is set
, SONORK_UI_EVENT_F_LOG_AUTO_OPEN = 0x00000020 // only if F_LOG is set
, SONORK_UI_EVENT_F_CLEAR_IF_NO_ERROR = 0x00000100 // for TASK_END event
, SONORK_UI_EVENT_F_WARNING = 0x00000200
, SONORK_UI_EVENT_INTERNAL_MASK = 0xfff00000 // Used internally by Set_UI_Event
, SONORK_UI_EVENT_F_SET_INFO = 0x00100000
, SONORK_UI_EVENT_F_AUTO_DISMISS = 0x00200000
, SONORK_UI_EVENT_F_SET_SLIDER = 0x00400000
};
// ----------------------------------------------------------------------------
enum SONORK_APP_DB
{
SONORK_APP_DB_REMIND
, SONORK_APP_DB_EMAIL_ACCOUNT
, SONORK_APP_DB_EMAIL_EXCEPT
, SONORK_APP_DB_TRACKER_SUBS
, SONORK_APP_DB_TRACKER_CACHE
};
// ----------------------------------------------------------------------------
// Special menu commands used globaly by all menus
enum SONORK_APP_MENU_COMMAND
{
SONORK_APP_CM_EAPP_BASE = 5000
, SONORK_APP_CM_EAPP_LIMIT = (SONORK_APP_CM_EAPP_BASE+SONORK_APP_MAX_EXT_APPS)
, SONORK_APP_CM_WAPP_BASE
, SONORK_APP_CM_WAPP_LIMIT = (SONORK_APP_CM_WAPP_BASE+SONORK_APP_MAX_WEB_APPS)
, SONORK_APP_CM_MTPL_BASE
, SONORK_APP_CM_MTPL_LIMIT = (SONORK_APP_CM_MTPL_BASE+SONORK_APP_MAX_WEB_APPS)
, SONORK_APP_CM_LIMIT
};
// ----------------------------------------------------------------------------
// Sonork application connection status
enum SONORK_APP_CX_STATUS
{
SONORK_APP_CX_STATUS_IDLE = 0
, SONORK_APP_CX_STATUS_NAME_RESOLVE
, SONORK_APP_CX_STATUS_LINKING
, SONORK_APP_CX_STATUS_LINKED
, SONORK_APP_CX_STATUS_REFRESHING_LIST
, SONORK_APP_CX_STATUS_DOWNLOADING_WAPPS
, SONORK_APP_CX_STATUS_REGISTERING_SID
, SONORK_APP_CX_STATUS_CONNECTING_FIRST =SONORK_APP_CX_STATUS_NAME_RESOLVE
, SONORK_APP_CX_STATUS_CONNECTING_LAST =SONORK_APP_CX_STATUS_REGISTERING_SID
, SONORK_APP_CX_STATUS_READY // All post-connect initilization finished
, SONORK_APP_CX_STATUS_READY_AND_GO // Post connect time elapsed (*)
};
// SONORK_APP_CX_STATUS_READY_AND_GO: We leave a small time window after connecting
// before starting to make sounds, etc..
// This is to avoid saturating the user with the notification sounds of the
// already connected users and server-stored messages.
// ----------------------------------------------------------------------------
// SERVICES
// ----------------------------------------------------------------------------
enum SONORK_APP_SERVICE_ENTRY_FLAGS
{
SONORK_APP_SERVICE_EF_REGISTERED = 0x00000001
, SONORK_APP_SERVICE_EF_EXPORTED = 0x00000010
, SONORK_APP_SERVICE_EF_LOCKED = 0x00000020
, SONORK_APP_SERVICE_EF_IPC = 0x00000040
, SONORK_APP_SERVICE_EF_HIDDEN = 0x10000000
};
// ----------------------------------------------------------------------------
enum SONORK_APP_SERVICE_QUERY_FLAGS
{
SONORK_APP_SERVICE_QF_ACTIVE = 0x00000001
, SONORK_APP_SERVICE_QF_CLEARED = 0x00000100
, SONORK_APP_SERVICE_QF_REMOVED = 0x00000200
};
// ----------------------------------------------------------------------------
enum SONORK_APP_SERVICE_CIRCUIT_FLAGS
{
SONORK_APP_SERVICE_CF_ACTIVE = 0x00000001
, SONORK_APP_SERVICE_CF_PENDING = 0x00000002
, SONORK_APP_SERVICE_CF_ACCEPTED = 0x00000004
, SONORK_APP_SERVICE_CF_REMOTE_DEAD = 0x00000008
, SONORK_APP_SERVICE_CF_OPEN_BY_LOCAL = 0x00000010
, SONORK_APP_SERVICE_CF_OPEN_BY_REMOTE = 0x00000020
, SONORK_APP_SERVICE_CF_CLEARED = 0x00000100
, SONORK_APP_SERVICE_CF_REMOVED = 0x00000200
};
// ----------------------------------------------------------------------------
enum SONORK_APP_SERVICE_TYPE
{
SONORK_APP_SERVICE_TYPE_NONE
, SONORK_APP_SERVICE_TYPE_CLIENT
, SONORK_APP_SERVICE_TYPE_LOCATOR
, SONORK_APP_SERVICE_TYPE_SERVER
};
// ----------------------------------------------------------------------------
enum SONORK_APP_SERVICE_EVENT
{
SONORK_APP_SERVICE_EVENT_NONE
, SONORK_APP_SERVICE_EVENT_INITIALIZE
, SONORK_APP_SERVICE_EVENT_EXPORT
, SONORK_APP_SERVICE_EVENT_BUSY
, SONORK_APP_SERVICE_EVENT_GET_NAME = 100
, SONORK_APP_SERVICE_EVENT_GET_SERVER_DATA
, SONORK_APP_SERVICE_EVENT_POKE_DATA = 200
, SONORK_APP_SERVICE_EVENT_QUERY_REQ = 300
, SONORK_APP_SERVICE_EVENT_QUERY_AKN
, SONORK_APP_SERVICE_EVENT_QUERY_END
, SONORK_APP_SERVICE_EVENT_CIRCUIT_REQ = 400
, SONORK_APP_SERVICE_EVENT_CIRCUIT_OPEN
, SONORK_APP_SERVICE_EVENT_CIRCUIT_DATA
, SONORK_APP_SERVICE_EVENT_CIRCUIT_UPDATE
, SONORK_APP_SERVICE_EVENT_CIRCUIT_CLOSED
};
// ----------------------------------------------------------------------------
enum SONORK_APP_SERVICE_CIRCUIT_REQ_RESULT
{
SONORK_APP_SERVICE_CIRCUIT_NOT_ACCEPTED
, SONORK_APP_SERVICE_CIRCUIT_ACCEPT_PENDING
, SONORK_APP_SERVICE_CIRCUIT_ACCEPTED
};
// ----------------------------------------------------------------------------
// Sonork APP-specific control messages
#define SONORK_APP_CTRLMSG_QUERY_PIC SONORK_CTRLMSG_CMD_01
#define SONORK_APP_CTRLMSG_QUERY_SERVICES SONORK_CTRLMSG_CMD_02
// ----------------------------------------------------------------------------
// External applications
#define SONORK_APP_EA_CONTEXT_MASK 0x00000007
#define SONORK_APP_EAF_NON_ZERO_IP 0x00000100
#define SONORK_APP_EAF_CONNECTED 0x00000200
#define SONORK_APP_EAF_SEND_REQ 0x01000000
#define SONORK_APP_EAF_WAIT_AKN 0x02000000
enum SONORK_APP_TYPE
{
SONORK_APP_TYPE_INTERNAL
, SONORK_APP_TYPE_EXTERNAL
, SONORK_APP_TYPE_WEB
};
enum SONORK_EXT_APP_CONTEXT
{
SONORK_EXT_APP_MAIN_CONTEXT
, SONORK_EXT_APP_USER_CONTEXT
, SONORK_EXT_APP_CTRL_CONTEXT
, SONORK_EXT_APP_CONTEXTS
};
enum SONORK_EXT_APP_TYPE
{
SONORK_EXT_APP_TYPE_REG
, SONORK_EXT_APP_TYPE_EXE
};
// SONORK_EXT_APP_PARAM_TYPE
// Defines the type of parameters for an application listed in the app.ini file.
enum SONORK_EXT_APP_PARAM_TYPE
{
SONORK_EXT_APP_PARAM_INVALID
, SONORK_EXT_APP_PARAM_RELATIVE
, SONORK_EXT_APP_PARAM_ABSOLUTE
, SONORK_EXT_APP_PARAM_TEMPORAL
};
// -------------------------------------------------------------------------
// Event mask Determine what type of events are dispatched to a window/IPC.
enum SONORK_APP_EVENT_MASK
{
SONORK_APP_EM_CX_STATUS_AWARE =0x00000001
, SONORK_APP_EM_PROFILE_AWARE =0x00000002
, SONORK_APP_EM_USER_LIST_AWARE =0x00000004
, SONORK_APP_EM_MSG_CONSUMER =0x00000010
, SONORK_APP_EM_MSG_PROCESSOR =0x00000020
, SONORK_APP_EM_CTRL_MSG_CONSUMER =0x00000040
, SONORK_APP_EM_SYS_WINDOWS_AWARE =0x00000100
, SONORK_APP_EM_MAIN_VIEW_AWARE =0x00000200
, SONORK_APP_EM_SKIN_AWARE =0x00000400
, SONORK_APP_EM_WAPP_PROCESSOR =0x00001000
#if defined(SONORK_APP_BUILD)
, SONORK_APP_EM_ENUMERABLE =0x10000000
#endif
};
// SONORK_APP_EM_ENUMERABLE:
// Window is placed in the application's main window queue,
// but no events are sent to it if not other flags are set.
#define SONORK_WIN_POKE_NET_RESOLVE_RESULT SONORK_WIN_POKE_APP_01
#define SONORK_WIN_POKE_DESTROY SONORK_WIN_POKE_APP_02
#define SONORK_WIN_POKE_SET_TAB SONORK_WIN_POKE_APP_03
#define SONORK_WIN_POKE_SONORK_TASK_RESULT SONORK_WIN_POKE_APP_04
#define SONORK_WIN_POKE_CHILD_NOTIFY SONORK_WIN_POKE_APP_05
#define SONORK_WIN_POKE_CHILD_DRAW_ITEM SONORK_WIN_POKE_APP_06
#define SONORK_WIN_POKE_ULTRA_MIN_DESTROY SONORK_WIN_POKE_APP_08
#define SONORK_WIN_POKE_ULTRA_MIN_PAINT SONORK_WIN_POKE_APP_09
// SONORK_EXT_DB_FLAGS
// Used for the SONORK_DB_TAG_FLAGS tag of the EXT database
// Note that some flags are data-dependant: And they mean
// different things for different types of data
// SONORK_EXT_DB_FILE_PATH_xxxxx
// These flags are used when storing the original location
// of a file sent/received.
// SONORK_EXT_DB_FILE_PATH_FULL
// If this flag is set, the data is the full path to the file. If it is
// not set, the data is the path to the folder, without the file name.
// Versions 1.04.05 and before did not use this flag
// Versions 1.04.06 and after always set this flag
#define SONORK_EXT_DB_FILE_PATH_FULL 0x00010000
// SONORK_APP_ATOM_DB_VALUES
// These values are mapped into SONORK_ATOM_DB_VALUE
// and are used for the application's MSG and EXT databases
#define SONORK_APP_ATOM_DB_VALUE_VERSION SONORK_ATOM_DB_VALUE_1
// This is the value for SONORK_APP_ATOM_DB_VALUE_VERSION
// that will be used when creating databases
#define SONORK_APP_CURRENT_ATOM_DB_VERSION 1
// -------------------------------------------------------------------------
// User message console line flags
#include "srk_ccache.h"
enum SONORK_APP_CCACHE_FLAGS
{
SONORK_APP_CCF_INCOMMING =SONORK_CCLF_INCOMMING //0x00000001
, SONORK_APP_CCF_UNREAD =SONORK_CCLF_01 //0x00000002
, SONORK_APP_CCF_DENIED =SONORK_CCLF_02 //0x00000004
, SONORK_APP_CCF_DELETED =SONORK_CCLF_02 //0x00000004
, SONORK_APP_CCF_PROCESSED =SONORK_CCLF_03 //0x00000008
, SONORK_APP_CCF_ACCEPTED =SONORK_CCLF_03 //0x00000008
, SONORK_APP_CCF_READ_ON_SELECT =SONORK_CCLF_08 //0x00001000
, SONORK_APP_CCF_NO_READ_ON_OPEN=SONORK_CCLF_09 //0x00002000
, SONORK_APP_CCF_PROTECTED =SONORK_CCLF_10 //0x00004000
, SONORK_APP_CCF_UNSENT =SONORK_CCLF_11 //0x00008000
, SONORK_APP_CCF_THREAD_START =SONORK_CCLF_THREAD_START //0x00010000
, SONORK_APP_CCF_IN_THREAD =SONORK_CCLF_IN_THREAD //0x00020000
, SONORK_APP_CCF_EXT_DATA =SONORK_CCLF_EXT_DATA //0x00040000
, SONORK_APP_CCF_QUERY =SONORK_CCLF_12 //0x00100000
, SONORK_APP_CCF_ERROR =SONORK_CCLF_13 //0x00200000
};
enum SONORK_APP_MSG_PROCESS_FLAGS
{
// SONORK_APP_MPF_PROCESSED
// The message has been processed/consumed
SONORK_APP_MPF_PROCESSED =0x00000001
// SONORK_APP_MPF_SUCCESS
// The message has been processed successfully (only if MPF_CONSUMED is also set)
, SONORK_APP_MPF_SUCCESS =0x00000002
// SONORK_APP_MPF_DONT_SEND
// Message was already sent, don't re-send, just store (if aplicable)
, SONORK_APP_MPF_DONT_SEND =0x00000004
// SONORK_APP_MPF_DONT_STORE
// Message should not be stored in local DB
, SONORK_APP_MPF_DONT_STORE =0x00000010
// SONORK_APP_MPF_STORED
// The message has been stored and the <mark> member of the event is valid
, SONORK_APP_MPF_STORED =0x00000020
// SONORK_APP_MPF_SILENT
// Message should be handled silently, don't make sounds or advise user
, SONORK_APP_MPF_SILENT =0x00000100
// SONORK_APP_MPF_SOFT_SOUND
// If incoming: Use soft sound instead of default user sound
, SONORK_APP_MPF_SOFT_SOUND =0x00000200
// SONORK_APP_MPF_AUTO_READ_SHORT
// If Incomming: Message may be marked as read if it's a short message
// "short message" means the whole text fits on screen and there is no
// need to open the message in the history window to see the whole of it.
, SONORK_APP_MPF_AUTO_READ_SHORT =0x00000400
// SONORK_APP_MPF_NO_STRIPPING
// Do no strip duplicates when storing the preview text on the message console
// (used for filenames, urls, etc.)
, SONORK_APP_MPF_NO_STRIPPING =0x00000800
// SONORK_APP_MPF_NO_TIME_SET
// If incomming: Don't adjust GMT time to local time
// If outgoign: Don't load current (local) time
, SONORK_APP_MPF_NO_TIME_SET =0x00001000
// SONORK_APP_MPF_UTS
// If incomming: Message arrived via UTS
// If outgoing: Message MUST go via UTS or fail
, SONORK_APP_MPF_UTS =0x00002000
// SONORK_APP_MPF_UTS
// If outgoing: Message MUST NOT go via UTS
, SONORK_APP_MPF_NO_UTS =0x00010000
// SONORK_APP_MPF_ADD_USER
// If user is not in the user list, add it to the contacts list
, SONORK_APP_MPF_ADD_USER =0x00020000
// SONORK_APP_MPF_NO_SERVICE_PARSE
// Will not attempt to derive the data service type from the text
// (Transform message into URL, Prepare Msg only))
, SONORK_APP_MPF_NO_SERVICE_PARSE =0x00040000
// SONORK_APP_MPF_CLEAR_SERVICE
// Will set the data service to NONE
, SONORK_APP_MPF_CLEAR_SERVICE =0x00080000
// SONORK_APP_MPF_NO_TRACKING_NUMBER
// Will not load the tracking number for the message
, SONORK_APP_MPF_NO_TRACKING_NUMBER =0x00100000
};
// -------------------------------------------------------------------------
// Profile & User flags/values
// Profile Configuration flags
#define SONORK_PCF_NO_HIDE_ON_MINIMIZE SONORK_PCF_1
#define SONORK_PCF_POPUP_MSG_WIN SONORK_PCF_2
#define SONORK_PCF_SEND_WITH_ENTER SONORK_PCF_3
#define SONORK_PCF_MUTE_SOUND SONORK_PCF_4
#define SONORK_PCF_NO_TOOL_TIPS SONORK_PCF_5
#define SONORK_PCF_NO_MSG_REMINDER SONORK_PCF_6
#define SONORK_PCF_IGNORE_NON_AUTHED_MSGS SONORK_PCF_7
#define SONORK_PCF_IGNORE_EMAILS SONORK_PCF_8
#define SONORK_PCF_CONFIRM_FILE_SEND SONORK_PCF_9
#define SONORK_PCF_NO_TRAY_BLINK SONORK_PCF_10
#define SONORK_PCF_GRPMSG_SAVUSR SONORK_PCF_11
#define SONORK_PCF_GRPMSG_SAVSYS SONORK_PCF_12
#define SONORK_PCF_NOT_PUBLIC_SID SONORK_PCF_13
#define SONORK_PCF_PUBLIC_SID_WHEN_FRIENDLY SONORK_PCF_14
#define SONORK_PCF_CHAT_SOUND SONORK_PCF_15
#define SONORK_PCF_NO_AUTO_SHOW_SID_MSG SONORK_PCF_16
#define SONORK_PCF_NO_COMPRESS_FILES SONORK_PCF_17
#define SONORK_PCF_NO_INVITATIONS SONORK_PCF_18
#define SONORK_PCF_NO_PUBLIC_INVITATIONS SONORK_PCF_19
// Profile Configuration values
#define SONORK_PCV_AUTO_AWAY_MINS SONORK_PCV_1
#define SONORK_PCV_DOWNLOAD_FILE_ACTION SONORK_PCV_2
#define SONORK_PCV_CHAT_COLOR SONORK_PCV_3
#define SONORK_PCV_INPUT_HEIGHT SONORK_PCV_4
#define SONORK_PCV_SLIDER_POS SONORK_PCV_5
// Profile Run flags
#define SONORK_PRF_CLIPBOARD_INITIALIZED SONORK_PRF_1
// App Run values
#define SONORK_ARV_FIRST_UNREAD_SYS_MSG SONORK_ARV_1
// App Ctrl Flags
#define SONORK_ACF_USE_PC_SPEAKER SONORK_ACF_1
// TSonorkExtUserData::SONORK_USER_CTRL_FLAGs
#define SONORK_APP_UCF_NO_SLIDER_CX_DISPLAY SONORK_UCF_2
#define SONORK_APP_UCF_NO_STATUS_CX_DISPLAY SONORK_UCF_3
// -----------------------------------------------------------------------
// APPLICATION EVENTS
// SONORK_APP_EVENT
// These events are broadcasted using TSonorkWin32App::BroadcastAppEvent
// and trigger the OnAppEvent() handler of every TSonorkWin that is in the
// app event queue. (Only windows with certain SONORK_APP_WIN_DESCRIPTOR flags
// are placed in the queue; see the SONORK_APP_WIN_DESCRIPTOR enum)
// The OnAppEvent receives three parameters:
// UINT event : The event id (SONORK_APP_EVENT)
// UINT param : Event specific parameter
// void*data : Event specific data
// Description of each event:
// SONORK_APP_EVENT_SHUTDOWN
// Last advise of the application shutting down, all windows should close NOW.
// No parameters.
// Event is non-maskable: It is received by all windows in the events list.
// SONORK_APP_EVENT_CX_STATUS
// The application has changed its CxStatus, SONORK_APP_CX_STATUS <param> holds
// the previous status. Windows that cannot work while disconnected should
// respond to this event and close when apropriate.
// This event is received by windows with the SONORK_APP_EM_CX_STATUS_AWARE flag
// SONORK_APP_EVENT_SET_LANGUAGE
// The language table has changed.
// This event is non-maskable: It is received by all windows in the events list.
// SONORK_APP_EVENT_OPEN_PROFILE
// An user profile has been open/closed.
// if BOOL:<param> is FALSE, the profile has been closed, otherwise
// it has been open.
// Most windows cannot work until the user profile is open
// because the profile determines which user is using the application.
// This event is received by windows with the SONORK_APP_EM_PROFILE_AWARE flag.
// Windows that need the profile open should close uppon receiving the
// event with <param>=FALSE.
// SONORK_APP_EVENT_SET_PROFILE
// The user profile has been modified
// <data> is a pointer to the TSonorkUserDataNotes structure with the
// new profile information that has been passed to BroadcastAppEvent()
// as <data> parameter. <param> is undefined.
// This event is received by windows with the SONORK_APP_EM_PROFILE_AWARE flag.
// SONORK_APP_EVENT_SID_CHANGED
// Online mode has changed.
// SONORK_SID_MODE:<param> is the new SID mode. <data> is not undefined.
// This event is received by windows with the SONORK_APP_EM_PROFILE_AWARE flag.
// SONORK_APP_EVENT_USER_SID
// Online mode of a user has changed.
// The SONORK_APP_EVENT_USER_SID_TYPE:<param> should be inspected to
// see how to handle this message.
// if <param> is SONORK_APP_EVENT_USER_SID_TYPE_LOCAL, <data>
// should be interpreted as (TSonorkAppEventLocalUserSid*)
// if <param> is SONORK_APP_EVENT_USER_SID_TYPE_REMOTE, <data>
// should be interpreted as (TSonorkAppEventRemoteUserSid*)
// if <param> is neither of above, the event must be ignored
// SONORK_APP_EVENT_SET_USER
// One of the users in the user list has changed its attributes
// UINT <param> holds the flags of the attributes changed.
// See TSonorkAppEventSetUser::SET_FLAGS for the list of flags.
// TSonorkAppEventSetUser* <data> is a pointer to the data of the user.
// Note that the TSonorkAppEventSetUser::<user_data> member may be
// null if TSonorkAppEventSetUser::<user_id> was not found in the user list.
// This event is received by windows with the SONORK_APP_EM_USER_LIST_AWARE flag
// SONORK_APP_EVENT_DEL_USER
// The application is about to delete an user.
// TSonorkId* <data> is a pointer to the TSonorkId of the user.
// <param> is undefined.
// Windows that are currently working with this user's data should
// immediately close, the user WILL be deleted as soon as the broadcast
// of the event ends.
// This event is received by windows with the SONORK_APP_EM_USER_LIST_AWARE flag
// SONORK_APP_EVENT_SONORK_MSG_RCVD
// A message has been received.
// TSonorkAppEventMsg* <data> holds the event data. <param> is undefined.
// The <ERR> field of <data> is NULL for this event
// This event is received by windows with the SONORK_APP_EM_MSG_CONSUMER flag.
// See TSonorkAppEventMsg for details on the event data.
// SONORK_APP_EVENT_SONORK_MSG_SENDING
// A message is being sent: It should be stored in the database.
// TSonorkAppEventMsg* <data> holds the event data. <param> is undefined.
// The <ERR> field of <data> is NULL for this event
// This event is received by windows with the SONORK_APP_EM_MSG_CONSUMER flag.
// See TSonorkAppEventMsg for details on the event data.
// SONORK_APP_EVENT_SONORK_MSG_SENT
// A message has been sent or failed to send: The status of the message
// must be updated in the database.
// TSonorkAppEventMsg* <data> holds the event data. <param> is undefined.
// The <ERR> field of <data> is valid for this event:
// if ERR->Result() is OK, the message was sent,
// otherwise message delivery failed
// This event is received by windows with either the SONORK_APP_EM_MSG_CONSUMER
// or the SONORK_APP_EM_MSG_PROCESSOR flags.
// See TSonorkAppEventMsg for details on the event data.
// SONORK_APP_EVENT_SONORK_MSG_QUERY_LOCK
// This event is triggered before starting a procedure that processes a
// message (and that will probably generate a MSG_PROCESSED event)
// to check if there exists another procedure/dialog already processing
// the message
// TSonorkAppEventMsgQueryLock* <data> holds the event data. <param> is undefined.
// This event is received by windows with the SONORK_APP_EM_MSG_PROCESSOR flag.
// See TSonorkAppEventMsgQueryLock for details on the event data.
// SONORK_APP_EVENT_SONORK_MSG_PROCESSED
// This event is triggered after a console message line has been processed/changed
// and the corresponding console file NEEDS to be updated.
// TSonorkAppEventMsgProcessed* <data> holds the event data. <param> is undefined.
// This event is received by windows with the SONORK_APP_EM_MSG_CONSUMER flag.
// See TSonorkAppEventMsgProcessed for details on the event data.
// SONORK_APP_EVENT_USER_UTS
// Event triggered when UTS link of an user changes.
// TSonorkId* <data> is a pointer to the TSonorkId of the user.
// <param> is the current UTS link which is zero if link has been closed.
// This event is received by windows with the SONORK_APP_EM_USER_LIST_AWARE flag.
// SONORK_APP_EVENT_START_WAPP
// Triggered when a Web Application (WAPP) needs to be started,
// TSonorkAppEventStartWapp* <data> holds the event data and <wParam>
// is nt used.
// The WAPP window serving that application should restore itself
// if hidden, minimized, and become the foreground window.
// Received by windows with the SONORK_APP_EM_WAPP_PROCESSOR flag
// See TSonorkAppEventStartWapp for details on the event data.
// SONORK_APP_EVENT_USER_MTPL_CHANGE
// Triggered when a the message templates menu has been modified.
// No parameters, the consumers can access GuApp::UserMtplMenu()
// This event is non-maskable: It is received by all windows in the events list.
// SONORK_APP_EVENT_DESKTOP_SIZE_CHANGE
// Triggered when app window receives WM_SETTINGCHANGE with SPI_GETWORKAREA
// flag set.
// This event is non-maskable: It is received by all windows in the events list.
// SONORK_APP_EVENT_MAIN_VIEW_SELECTION
// User selection (highlighting users) in the main view has changed.
// <param> is the new number of users selected. <data> is undefined.
// This event is received by windows with the SONORK_APP_EM_MAIN_VIEW_AWARE flag.
// SONORK_APP_EVENT_MAINTENANCE
// All windows should close: System is going into "Maintenance" mode
// <data> is the pointer to the TSonorkWin that requested Maintenance mode.
// This event is non-maskable: It is received by all windows in the events list.
// SONORK_APP_EVENT_FLUSH_BUFFERS
// The window should flush its buffers. This event is generated every X
// minutes so that, if something fails, nothing is left unwritten in memory.
// This event is non-maskable: It is received by all windows in the events list.
// ----------------------------------------------------------------------------
enum SONORK_APP_EVENT
{
SONORK_APP_EVENT_NONE = 0
, SONORK_APP_EVENT_SHUTDOWN = 1
, SONORK_APP_EVENT_FLUSH_BUFFERS = 5
, SONORK_APP_EVENT_MAINTENANCE = 6
, SONORK_APP_EVENT_OLD_CTRL_MSG = 7 // For V1.04 backwards support
, SONORK_APP_EVENT_OPEN_PROFILE = 10
, SONORK_APP_EVENT_CX_STATUS = 12
, SONORK_APP_EVENT_SET_PROFILE = 14 // User profile attributes have been modified
, SONORK_APP_EVENT_SID_CHANGED = 16 // User online mode has changed
, SONORK_APP_EVENT_SET_LANGUAGE = 18
, SONORK_APP_EVENT_SKIN_COLOR_CHANGED = 20
, SONORK_APP_EVENT_SYS_DIALOG = 22 // lower word of lParam contains dialog ID, high word contains true or false
, SONORK_APP_EVENT_USER_SID = 50 // User changed its sid attributes
, SONORK_APP_EVENT_SET_USER = 52 // User in local user list changed its attributes
, SONORK_APP_EVENT_DEL_USER = 54
, SONORK_APP_EVENT_USER_UTS = 53
, SONORK_APP_EVENT_SONORK_MSG_RCVD = 60 // message has been received
, SONORK_APP_EVENT_SONORK_MSG_SENDING = 62 // message has entered queue for sending
, SONORK_APP_EVENT_SONORK_MSG_SENT = 64 // message has been sent or failed to send
, SONORK_APP_EVENT_SONORK_MSG_QUERY_LOCK= 66
, SONORK_APP_EVENT_SONORK_PROCESS_MSG = 68
, SONORK_APP_EVENT_SONORK_MSG_PROCESSED = 70
, SONORK_APP_EVENT_START_WAPP = 80
, SONORK_APP_EVENT_USER_MTPL_CHANGE = 82
, SONORK_APP_EVENT_MAIN_VIEW_SELECTION = 100
, SONORK_APP_EVENT_DESKTOP_SIZE_CHANGE = 101
};
// ----------------------------------------------------------------------------
enum SONORK_APP_EVENT_USER_SID_TYPE
{
SONORK_APP_EVENT_USER_SID_LOCAL =1
, SONORK_APP_EVENT_USER_SID_REMOTE =2
};
// ----------------------------------------------------------------------------
enum SONORK_APP_EVENT_SET_USER_FLAGS
{
SONORK_APP_EVENT_SET_USER_F_AUTH_FLAGS =0x000001
, SONORK_APP_EVENT_SET_USER_F_DATA =0x000004
, SONORK_APP_EVENT_SET_USER_F_R_NOTES =0x000008
, SONORK_APP_EVENT_SET_USER_F_DISPLAY_ALIAS =0x000010
, SONORK_APP_EVENT_SET_USER_F_L_NOTES =0x000020
, SONORK_APP_EVENT_SET_USER_F_MSG_COUNT =0x000100
, SONORK_APP_EVENT_SET_USER_F_EXT_DATA =0x000400
, SONORK_APP_EVENT_SET_USER_F_REFRESH =0x000800
, SONORK_APP_EVENT_SET_USER_F_ALL =0x00ffff
, SONORK_APP_EVENT_SET_USER_F_ANY =0x00ffff
};
// ----------------------------------------------------------------------------
struct TSonorkMsgHandle
{
friend class TSonorkWin32App;
private:
DWORD pcFlags;
TSonorkServiceId sourceService;
public:
DWORD taskId;
DWORD handleId;
TSonorkCCacheMark mark;
const DWORD
ProcessFlags() const
{ return pcFlags; }
}__SONORK_PACKED;
// ----------------------------------------------------------------------------
#if defined(SONORK_APP_BUILD)
// These structures should not be used by the IPC.
// The IPC server maps them to IPC-defined structures
// in order to be able to freely change these types without
// affecting compatiblity with existing IPC applications.
// ----------------------------------------------------------------------------
struct TSonorkAppEventMsg
{
// SONORK_APP_EVENT_SONORK_MSG_RECV
// SONORK_APP_EVENT_SONORK_MSG_SENDING
// SONORK_APP_EVENT_SONORK_MSG_SENT
// A message has been received/sent or is being sent.
// TSonorkAppEventEventMsg* <data> holds the event data. <param> is undefined.
// A window should only process the event if it "knows" how to process it
// and ONLY if <consumed> is FALSE. After processing it, <consumed> should
// be set to TRUE.
// <pc_flags> are the proces flags
// <cc_flags> are stored in the message console.
DWORD pcFlags;
DWORD ccFlags;
// <HandleId> and <taskId> are valid only if event is
// SONORK_APP_EVENT_SONORK_MSG_SENT or SONORK_APP_EVENT_SONORK_MSG_SENDING
// 0 otherwise
DWORD handleId;
DWORD taskId;
// <mark> is valid only if event is SONORK_APP_EVENT_SONORK_MSG_SENT
// or after SONORK_APP_EVENT_SONORK_MSG_RCVD and/or
// SONORK_APP_EVENT_SONORK_MSG_SENDING is processed and stored
// (pcFlags has the SONORK_APP_MPF_STORED flag set)
// it is undefined otherwise.
TSonorkCCacheMark mark;
// <header> is valid for all events
const TSonorkMsgHeader* header;
// <msg> is valid only if event is SONORK_APP_EVENT_SONORK_MSG_RECV
// or SONORK_APP_EVENT_SONORK_MSG_SENDING, null otherwise
TSonorkMsg* msg;
// <ERR> is valid only if event is SONORK_APP_EVENT_SONORK_MSG_SENT,
// null otherwise
const TSonorkError* ERR;
};
// ----------------------------------------------------------------------------
struct TSonorkAppEventMsgQueryLock
{
// SONORK_APP_EVENT_SONORK_MSG_QUERY_LOCK
// This event is triggered before starting a procedure that processes a
// message (and that will probably generate a MSG_PROCESSED event)
// to check if there exists another procedure/dialog already processing
// All windows with the SONORK_APP_EM_MSG_PROCESSOR flag set will receive
// the event.
// The window should set <locked> to <true> if the message
// being processed matches <pConLineRef>, if not, it should
// ignore the message
TSonorkId userId;
const TSonorkCCacheMark* markPtr;
TSonorkWin* owner;
};
//
// ----------------------------------------------------------------------------
struct TSonorkAppEventMsgProcessed
{
// SONORK_APP_EVENT_SONORK_MSG_PROCESSED
// This event is triggered after a message has been processed/changed
// and the corresponding console file needs to be updated.
// A window should only process the event if it "knows" how to process it
// and ONLY if <consumed> is FALSE. After processing it,
// <consumed> should be set to TRUE.
// The <user_id> and <index> denote the user's console and line number
// whose flags need to be modified.
// <cc_flags> denote the new console flags and <cc_mask> the flags that
// need to be changed: only those flags set in <mask> should be udpated.
TSonorkId userId;
DWORD pcFlags;
DWORD ccFlags;
DWORD ccMask;
TSonorkCCacheMark* markPtr;
DWORD* extIndex;
};
// ----------------------------------------------------------------------------
// Used for old V1.04 support. Not used any more in V1.5, except in very few
// cases when "talking" to an old version.
// Newer versions will depreciate old ctrl messages completely.
// ----------------------------------------------------------------------------
enum SONORK_APP_OLD_CTRLMSG_RESULT_FLAGS
{
SONORK_APP_OLD_CTRLMSG_RF_MAY_BROADCAST = 0x000001
, SONORK_APP_OLD_CTRLMSG_RF_MAY_END_QUERY = 0x000002
, SONORK_APP_OLD_CTRLMSG_RF_DEFAULT = 0x000003
};
struct TSonorkAppEventOldCtrlMsg
{
const TSonorkUserHandle* handle;
const TSonorkCtrlMsg* msg;
const BYTE* data;
UINT data_size;
};
// ----------------------------------------------------------------------------
struct TSonorkAppEventSetUser
{
// Flags passed as wParam that can be tested
// for the SONORK_APP_EVENT_SET_USER event
// MSG_COUNT is a EXT_DATA member, so if MSG_COUNT is set,
TSonorkId user_id;
TSonorkExtUserData* user_data;
};
// ----------------------------------------------------------------------------
// SONORK_APP_EVENT_USER_SID structures & defs
struct TSonorkAppEventLocalUserSid
{
// online_dir:
// -1 if disconnected
// 0 if changed mode (without disconnecting or connecting)
// 1 if connected
int onlineDir;
SONORK_SID_MODE oldSidMode;
SONORK_SID_MODE newSidMode;
TSonorkExtUserData* userData;
};
// ----------------------------------------------------------------------------
struct TSonorkAppEventRemoteUserSid
{
// use <remote> struct if <lParam> of has SET_F_REMOTE flag
TSonorkId userId;
TSonorkSid sid;
TSonorkSidFlags sidFlags;
};
// ----------------------------------------------------------------------------
// TSonorkAppEventUserSid:
// Depending on the event's <lParam>, the the <local> or <remote> members should be used
// if lParam == SONORK_APP_EVENT_USER_SID_LOCAL, use <local>
// if lParam == SONORK_APP_EVENT_USER_SID_REMOTE, use <remote>
// if neither, IGNORE the event
union TSonorkAppEventUserSid
{
TSonorkAppEventLocalUserSid local;
TSonorkAppEventRemoteUserSid remote;
};
// ----------------------------------------------------------------------------
struct TSonorkAppEventStartWapp
{
// The Wapp window that processes this message should
// set <consumed> to true.
bool consumed;
const TSonorkWappData* wapp_data;
const TSonorkExtUserData* user_data; // Cannot be <NULL> if replying.
const TSonorkCCacheMark* reply_mark; // Set non-<NULL> if replying
};
struct TSonorkAppTask_SendMsg
{
TSonorkMsgHeader header;
DWORD pcFlags;
DWORD handleId;
TSonorkCCacheMark mark;
};
struct TSonorkAppTask_SendServiceMsg
{
DWORD instance;
DWORD systemId;
DWORD msgType;
};
struct TSonorkAppTask_ExportService
{
SONORK_APP_TASK_EXPORT_OP operation;
TSonorkServiceInstanceInfo service_info;
BOOL entry_dead;
};
struct TSonorkAppTask
{
SONORK_APP_TASK_TYPE type;
union
{
TSonorkAppTask_SendMsg send_msg;
TSonorkAppTask_ExportService export_service;
TSonorkAppTask_SendServiceMsg send_service_msg;
};
TSonorkAppTask(SONORK_APP_TASK_TYPE t){type=t;}
};
enum SONORK_MSG_WIN_OPEN_MODE
{
SONORK_MSG_WIN_OPEN_MINIMIZED
, SONORK_MSG_WIN_OPEN_AUTOMATIC
, SONORK_MSG_WIN_OPEN_FOREGROUND
};
#endif // #if defined(SONORK_APP_BUILD)
#endif
| 36.206306 | 112 | 0.710891 | [
"transform"
] |
911224da86aaeca8e50ff8ece1bb5554c8b167a9 | 347 | h | C | KaiLib/KaiThread.h | DaisukeT-GitHub/KaiLib | 4994443265eb84594da601af4f631803d9c74a1b | [
"MIT"
] | null | null | null | KaiLib/KaiThread.h | DaisukeT-GitHub/KaiLib | 4994443265eb84594da601af4f631803d9c74a1b | [
"MIT"
] | null | null | null | KaiLib/KaiThread.h | DaisukeT-GitHub/KaiLib | 4994443265eb84594da601af4f631803d9c74a1b | [
"MIT"
] | null | null | null | //
// KaiThread.h
//
#import "KaiLib.h"
/**
* @brief スレッド制御プロトコル
*
* スレッド処理などのメソッドを定義
*
*/
@protocol KaiThreadProtocol
- (void)runOnThread:(id)object;
- (NSString*)threadName;
@end
/**
* @brief スレッド制御クラス
*
* スレッド起動するクラスのベースクラス
*
*/
@interface KaiThread : NSObject <KaiThreadProtocol>
{
}
- (void)startThread:(id)object;
@end
| 9.378378 | 51 | 0.648415 | [
"object"
] |
91189cd6b86f607f909443604102d654085c09a8 | 655 | h | C | rss-reader/Presentation/ChannelFeed/View/Cell/UVFeedTableViewCell.h | trotnic/rss-reader | 846e7db45ed427a04b01536cd7a64de159592f57 | [
"MIT"
] | null | null | null | rss-reader/Presentation/ChannelFeed/View/Cell/UVFeedTableViewCell.h | trotnic/rss-reader | 846e7db45ed427a04b01536cd7a64de159592f57 | [
"MIT"
] | 1 | 2021-02-20T20:23:28.000Z | 2021-02-20T20:28:58.000Z | rss-reader/Presentation/ChannelFeed/View/Cell/UVFeedTableViewCell.h | trotnic/rss-reader | 846e7db45ed427a04b01536cd7a64de159592f57 | [
"MIT"
] | null | null | null | //
// UVFeedTableViewCell.h
// rss-reader
//
// Created by Uladzislau on 11/18/20.
//
#import <UIKit/UIKit.h>
#import "UVFeedItemDisplayModel.h"
NS_ASSUME_NONNULL_BEGIN
@interface UVFeedTableViewCell : UITableViewCell
@property (nonatomic, strong, readonly) UILabel *titleLabel;
@property (nonatomic, strong, readonly) UILabel *dateLabel;
@property (nonatomic, strong, readonly) UILabel *categoryLabel;
@property (nonatomic, strong, readonly) UILabel *descriptionLabel;
+ (NSString *)cellIdentifier;
- (void)setupWithModel:(id<UVFeedItemDisplayModel>)model reloadCompletion:(void(^)(void(^callback)(void)))completion;
@end
NS_ASSUME_NONNULL_END
| 25.192308 | 117 | 0.774046 | [
"model"
] |
9125a136c28c75037f51734d516c413a020fd0cd | 3,893 | h | C | Entity.h | Predator-SD/SDF-Tests | b7ed64a97528122a3c9a55afb21eb27fec98c622 | [
"MIT"
] | 2 | 2018-01-26T12:05:49.000Z | 2018-01-26T15:31:31.000Z | Entity.h | Predator-SD/SDF-Tests | b7ed64a97528122a3c9a55afb21eb27fec98c622 | [
"MIT"
] | null | null | null | Entity.h | Predator-SD/SDF-Tests | b7ed64a97528122a3c9a55afb21eb27fec98c622 | [
"MIT"
] | null | null | null | #ifndef ENTITY_H
#define ENTITY_H
#include<vector>
#include<cstdlib>
#include<cstdio>
#include "Profile.h"
#define SAFE_DELETE(p) do{delete (p);(p)=NULL;}while(false)
#define PI 3.141592653589
#define W 512
#define H 512
#define N 1024
#define BIAS 1e-6
#define MAX_DEPTH 7
using std::vector;
int cnt=0;
class Entity{
protected:
Profile *pr;
Color EM;
double RE;
double RA;
double RI[3];
public:
Entity(Profile *p,Color e,double re=0.0,double ra=0.0,double *ri=NULL):pr(p),EM(e),RE(re),RA(ra){
if(ri)
RI[0]=ri[0],
RI[1]=ri[1],
RI[2]=ri[2];
}
inline Profile *GetPr(void){
return pr;
}
inline Color GetEM(void){
return EM;
}
inline double GetRE(void){
return RE;
}
inline double GetRA(void){
return RA;
}
inline double GetRI(int index){
return RI[index];
}
virtual bool Inter(Point p,Vector d,Point &inter){
return pr->Inter(p,d,inter);
}
};
class Spotlight :
public Entity{
protected:
Vector dir;
double cosa;
public:
Spotlight(Profile *s,Color e,double re=0.0,double ra=0.0,double *ri=NULL,Vector dir={0.0,1.0},double a=0.03):
Entity(s,e,re,ra,ri),dir(dir){
cosa=cos(a);
}
bool Inter(Point p,Vector d,Point &inter){
if(d*(-dir)<cosa)
return false;
else return pr->Inter(p,d,inter);
}
};
class Space{
protected:
vector<Entity*> ie;
public:
Space(vector<Entity*> e):ie(e){}
inline vector<Entity*> GetEn(void){
return ie;
}
Color Reflect(Entity *e,Point inter,Vector d,Vector normal,int index,int depth){
if(depth>MAX_DEPTH||e->GetRE()==0.0) return (Color){0.0,0.0,0.0};
//Vector normal=e->GetPr()->GetN(inter);
//if(normal*d>0.0) return (Color){0.0,0.0,0.0};
Vector red=d.reflect(normal);
return GetColor(inter+red*BIAS,red,index,depth)*e->GetRE();
}
Color Refract(Entity *e,Point inter,Vector d,Vector normal,int index,int depth){
if(depth>MAX_DEPTH||e->GetRA()==0.0) return (Color){0.0,0.0,0.0};
//Vector normal=e->GetPr()->GetN(inter);
double idotn=d*normal;
double ri=e->GetRI(index);
double k,a;
if(idotn>0.0){
++cnt;
k=1.0-ri*ri*(1.0-idotn*idotn);
if(k<0.0) return (Color){0.0,0.0,0.0};
a=ri*idotn-sqrt(k);
}else{
ri=1.0/ri;
k=1.0-ri*ri*(1.0-idotn*idotn);
a=ri*idotn+sqrt(k);
}
Vector refract=d*ri-normal*a;
return GetColor(inter+refract*BIAS,refract,index,depth)*e->GetRA();
}
Color GetColor(Point p,Vector d,int ci,int depth=0){
double dis=10.0;
int ei=-1;
Point inter;
for(int j=0;j<ie.size();++j){
Point temp;
if(ie[j]->Inter(p,d,temp)){
double ndis=(temp-p).len();
if(dis>ndis)
ei=j,
dis=ndis,
inter=temp;
}
}
if(ei>=0){
Entity *ent=ie[ei];
Vector normal=ent->GetPr()->GetN(inter);
Color reflect=Reflect(ie[ei],inter,d,normal,ci,depth+1);
Color refract=(Color){0.0,0.0,0.0};
if(ci>=3){
refract.r=Refract(ent,inter,d,normal,0,depth+1).r;
refract.g=Refract(ent,inter,d,normal,1,depth+1).g;
refract.b=Refract(ent,inter,d,normal,2,depth+1).b;
}else
refract=Refract(ent,inter,d,normal,ci,depth+1);
return ent->GetEM()+reflect+refract;
}else
return (Color){0.0,0.0,0.0};
}
Color Integrate(Point p){
Color sum=(Color){0.0,0.0,0.0};
double theta;
for(int i=0;i<N;++i)
theta=2.0*PI*(i+(double)rand()/RAND_MAX)/N,
sum=sum+GetColor(p,(Vector){cos(theta),sin(theta)},3);
return sum/N;
}
};
Profile *Polygon(vector<Point> points){
Point sig=(Point){0.0,0.0};
for(vector<Point>::iterator it=points.begin();it!=points.end();++it)
sig.x+=(*it).x,sig.y+=(*it).y;
Point center=(Point){sig.x/points.size(),sig.y/points.size()};
Profile *s=NULL;
for(vector<Point>::iterator it=points.begin();(it+1)!=points.end();++it){
Point p1=*it,p2=*(it+1);
HalfPlane *l=new HalfPlane(p1,p2,center);
if(s) s=new PIntersect(s,l);
else s=l;
}
s=new PIntersect(s,new HalfPlane(*(points.end()-1),*(points.begin()),center));
return s;
}
#endif
| 21.748603 | 110 | 0.639353 | [
"vector"
] |
912a540dcdd122029e215d58b6511309fc0d13af | 4,370 | h | C | examples/pxScene2d/external/libnode-v10.15.3/deps/v8/third_party/antlr4/runtime/Cpp/runtime/src/tree/pattern/ParseTreePattern.h | madanagopaltcomcast/pxCore | c4a3a40a190521c8b6383d126c87612eca5b3c42 | [
"Apache-2.0"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | examples/pxScene2d/external/libnode-v10.15.3/deps/v8/third_party/antlr4/runtime/Cpp/runtime/src/tree/pattern/ParseTreePattern.h | madanagopaltcomcast/pxCore | c4a3a40a190521c8b6383d126c87612eca5b3c42 | [
"Apache-2.0"
] | 1,432 | 2017-06-21T04:08:48.000Z | 2020-08-25T16:21:15.000Z | examples/pxScene2d/external/libnode-v10.15.3/deps/v8/third_party/antlr4/runtime/Cpp/runtime/src/tree/pattern/ParseTreePattern.h | madanagopaltcomcast/pxCore | c4a3a40a190521c8b6383d126c87612eca5b3c42 | [
"Apache-2.0"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
#pragma once
#include "antlr4-common.h"
namespace antlr4 {
namespace tree {
namespace pattern {
/// <summary>
/// A pattern like {@code <ID> = <expr>;} converted to a <seealso
/// cref="ParseTree"/> by <seealso cref="ParseTreePatternMatcher#compile(String,
/// int)"/>.
/// </summary>
class ANTLR4CPP_PUBLIC ParseTreePattern {
public:
/// <summary>
/// Construct a new instance of the <seealso cref="ParseTreePattern"/> class.
/// </summary>
/// <param name="matcher"> The <seealso cref="ParseTreePatternMatcher"/> which
/// created this tree pattern. </param> <param name="pattern"> The tree
/// pattern in concrete syntax form. </param> <param name="patternRuleIndex">
/// The parser rule which serves as the root of the tree pattern. </param>
/// <param name="patternTree"> The tree pattern in <seealso cref="ParseTree"/>
/// form. </param>
ParseTreePattern(ParseTreePatternMatcher* matcher, const std::string& pattern,
int patternRuleIndex, ParseTree* patternTree);
ParseTreePattern(ParseTreePattern const&) = default;
virtual ~ParseTreePattern();
ParseTreePattern& operator=(ParseTreePattern const&) = default;
/// <summary>
/// Match a specific parse tree against this tree pattern.
/// </summary>
/// <param name="tree"> The parse tree to match against this tree pattern.
/// </param> <returns> A <seealso cref="ParseTreeMatch"/> object describing
/// the result of the match operation. The <seealso
/// cref="ParseTreeMatch#succeeded()"/> method can be used to determine
/// whether or not the match was successful. </returns>
virtual ParseTreeMatch match(ParseTree* tree);
/// <summary>
/// Determine whether or not a parse tree matches this tree pattern.
/// </summary>
/// <param name="tree"> The parse tree to match against this tree pattern.
/// </param> <returns> {@code true} if {@code tree} is a match for the current
/// tree pattern; otherwise, {@code false}. </returns>
virtual bool matches(ParseTree* tree);
/// Find all nodes using XPath and then try to match those subtrees against
/// this tree pattern.
/// @param tree The ParseTree to match against this pattern.
/// @param xpath An expression matching the nodes
///
/// @returns A collection of ParseTreeMatch objects describing the
/// successful matches. Unsuccessful matches are omitted from the result,
/// regardless of the reason for the failure.
virtual std::vector<ParseTreeMatch> findAll(ParseTree* tree,
const std::string& xpath);
/// <summary>
/// Get the <seealso cref="ParseTreePatternMatcher"/> which created this tree
/// pattern.
/// </summary>
/// <returns> The <seealso cref="ParseTreePatternMatcher"/> which created this
/// tree pattern. </returns>
virtual ParseTreePatternMatcher* getMatcher() const;
/// <summary>
/// Get the tree pattern in concrete syntax form.
/// </summary>
/// <returns> The tree pattern in concrete syntax form. </returns>
virtual std::string getPattern() const;
/// <summary>
/// Get the parser rule which serves as the outermost rule for the tree
/// pattern.
/// </summary>
/// <returns> The parser rule which serves as the outermost rule for the tree
/// pattern. </returns>
virtual int getPatternRuleIndex() const;
/// <summary>
/// Get the tree pattern as a <seealso cref="ParseTree"/>. The rule and token
/// tags from the pattern are present in the parse tree as terminal nodes with
/// a symbol of type <seealso cref="RuleTagToken"/> or <seealso
/// cref="TokenTagToken"/>.
/// </summary>
/// <returns> The tree pattern as a <seealso cref="ParseTree"/>. </returns>
virtual ParseTree* getPatternTree() const;
private:
const int patternRuleIndex;
/// This is the backing field for <seealso cref="#getPattern()"/>.
const std::string _pattern;
/// This is the backing field for <seealso cref="#getPatternTree()"/>.
ParseTree* _patternTree;
/// This is the backing field for <seealso cref="#getMatcher()"/>.
ParseTreePatternMatcher* const _matcher;
};
} // namespace pattern
} // namespace tree
} // namespace antlr4
| 39.017857 | 80 | 0.686499 | [
"object",
"vector"
] |
91334ee439f9ce801928e6c17820a8e940ffeae4 | 698 | h | C | aliyun-api-yundun/2015-04-16/include/ali_yundun_ddos_flow_graph_types.h | zcy421593/aliyun-openapi-cpp-sdk | 8af0a59dedf303fa6c6911a61c356237fa6105a1 | [
"Apache-2.0"
] | 1 | 2015-11-28T16:46:56.000Z | 2015-11-28T16:46:56.000Z | aliyun-api-yundun/2015-04-16/include/ali_yundun_ddos_flow_graph_types.h | zcy421593/aliyun-openapi-cpp-sdk | 8af0a59dedf303fa6c6911a61c356237fa6105a1 | [
"Apache-2.0"
] | null | null | null | aliyun-api-yundun/2015-04-16/include/ali_yundun_ddos_flow_graph_types.h | zcy421593/aliyun-openapi-cpp-sdk | 8af0a59dedf303fa6c6911a61c356237fa6105a1 | [
"Apache-2.0"
] | null | null | null | #ifndef ALI_YUNDUN_DDOS_FLOW_GRAPH_TYPESH
#define ALI_YUNDUN_DDOS_FLOW_GRAPH_TYPESH
#include <stdio.h>
#include <string>
#include <vector>
namespace aliyun {
struct YundunDdosFlowGraphRequestType {
std::string instance_id;
std::string instance_type;
};
struct YundunDdosFlowGraphNormalFlowType {
long time;
long bit_recv;
long bit_send;
long pkt_recv;
long pkt_send;
};
struct YundunDdosFlowGraphTotalFlowType {
long time;
long bit_recv;
long pkt_recv;
};
struct YundunDdosFlowGraphResponseType {
std::vector<YundunDdosFlowGraphNormalFlowType> normal_flows;
std::vector<YundunDdosFlowGraphTotalFlowType> total_flows;
};
} // end namespace
#endif
| 24.068966 | 63 | 0.766476 | [
"vector"
] |
9135b49a1dc8acb1059acbba1aecffaf550e03dd | 3,129 | h | C | algorithms/calibexecutive.h | gaugecam/GRIME2 | a9d197243bc073edbdc822053178ad750c82c7d6 | [
"Apache-2.0"
] | 3 | 2021-02-16T05:46:20.000Z | 2021-03-08T08:38:21.000Z | algorithms/calibexecutive.h | gaugecam-dev/GRIME2 | a9d197243bc073edbdc822053178ad750c82c7d6 | [
"Apache-2.0"
] | 6 | 2021-04-10T14:55:24.000Z | 2021-08-28T17:54:24.000Z | algorithms/calibexecutive.h | gaugecam/GRIME2 | a9d197243bc073edbdc822053178ad750c82c7d6 | [
"Apache-2.0"
] | 1 | 2021-04-15T02:20:19.000Z | 2021-04-15T02:20:19.000Z | #ifndef CALIBEXECUTIVE_H
#define CALIBEXECUTIVE_H
#include "calib.h"
#include "findcalibgrid.h"
#include "findsymbol.h"
namespace gc
{
class CalibExecParams
{
public:
CalibExecParams() :
stopSignFacetLength( -1.0 ),
drawCalib( false ),
drawMoveSearchROIs( false ),
drawWaterLineSearchROI( false ),
targetSearchROI( cv::Rect( -1, -1, -1, -1 ) )
{}
void clear()
{
calibType.clear();
worldPtCSVFilepath.clear();
stopSignFacetLength = -1.0;
calibResultJsonFilepath.clear();
drawCalib = false;
drawMoveSearchROIs = false;
drawWaterLineSearchROI = false;
targetSearchROI = cv::Rect( -1, -1, -1, -1 );
}
string calibType;
string worldPtCSVFilepath;
double stopSignFacetLength;
string calibResultJsonFilepath;
bool drawCalib;
bool drawMoveSearchROIs;
bool drawWaterLineSearchROI;
cv::Rect targetSearchROI;
friend std::ostream &operator<<( std::ostream &out, const CalibExecParams ¶ms ) ;
};
class CalibExecutive
{
public:
CalibExecutive();
void clear();
GC_STATUS Load( const std::string jsonFilepath );
GC_STATUS Calibrate( const std::string calibTargetImagePath, const std::string jsonParams, cv::Mat &imgResult );
GC_STATUS PixelToWorld( const cv::Point2d pixelPt, cv::Point2d &worldPt );
GC_STATUS WorldToPixel( const cv::Point2d worldPt, cv::Point2d &pixelPt );
GC_STATUS GetMoveSearchROIs( cv::Rect &rectLeft, cv::Rect &rectRight );
GC_STATUS SetMoveSearchROIs( const cv::Mat img, const cv::Rect rectLeft, const cv::Rect rectRight );
GC_STATUS DetectMove( std::vector< cv::Point2d > &origPos, std::vector< cv::Point2d > &newPos );
GC_STATUS DrawOverlay( const cv::Mat matIn, cv::Mat &imgMatOut,
const bool drawCalib, const bool drawMoveROIs, const bool drawSearchROI );
GC_STATUS FindMoveTargets( const cv::Mat &img, FindPointSet &ptsFound );
GC_STATUS MoveRefPoint( cv::Point2d &lftRefPt, cv::Point2d &rgtRefPt );
std::vector< LineEnds > &SearchLines();
cv::Rect &TargetRoi();
std::string &GetCalibType() { return paramsCurrent.calibType; }
private:
Calib bowTie;
FindSymbol stopSign;
FindCalibGrid findCalibGrid;
CalibExecParams paramsCurrent;
std::vector< LineEnds > nullSearchLines; ///< Empty vector of search lines to be searched for the water line
cv::Rect nullRect = cv::Rect( -1, -1, -1, -1 );
GC_STATUS CalibrateBowTie( const string imgFilepath, cv::Mat &imgOut );
GC_STATUS CalibrateStopSign( const string imgFilepath );
GC_STATUS FindMoveTargetsBowTie( const cv::Mat &img, FindPointSet &ptsFound );
GC_STATUS FindMoveTargetsStopSign( const cv::Mat &img, FindPointSet &ptsFound );
GC_STATUS MoveRefPointBowTie( cv::Point2d &lftRefPt, cv::Point2d &rgtRefPt );
GC_STATUS MoveRefPointStopSign( cv::Point2d &lftRefPt, cv::Point2d &rgtRefPt );
GC_STATUS ReadWorldCoordsFromCSVBowTie( const string csvFilepath, vector< vector< cv::Point2d > > &worldCoords );
};
} // namespace gc
#endif // CALIBEXECUTIVE_H
| 35.556818 | 117 | 0.691914 | [
"vector"
] |
913aada8a9b0b86b04d26251cf5be396622281e7 | 6,940 | h | C | network-manager-applet/src/libnma/nma-mobile-providers.h | apiraino/sway-ubuntu-build | bb774627867b2b72d5e149f870330933b10bba30 | [
"MIT"
] | null | null | null | network-manager-applet/src/libnma/nma-mobile-providers.h | apiraino/sway-ubuntu-build | bb774627867b2b72d5e149f870330933b10bba30 | [
"MIT"
] | null | null | null | network-manager-applet/src/libnma/nma-mobile-providers.h | apiraino/sway-ubuntu-build | bb774627867b2b72d5e149f870330933b10bba30 | [
"MIT"
] | null | null | null | // SPDX-License-Identifier: LGPL-2.1+
/*
* Copyright (C) 2009 Novell, Inc.
* Author: Tambet Ingo (tambet@gmail.com).
*
* Copyright (C) 2009 - 2012 Red Hat, Inc.
* Copyright (C) 2012 Lanedo GmbH.
*/
#ifndef NM_MOBILE_PROVIDERS_H
#define NM_MOBILE_PROVIDERS_H
#include <glib.h>
#include <glib-object.h>
#include <gio/gio.h>
/******************************************************************************/
/* Access method type */
/**
* NMAMobileFamily:
* @NMA_MOBILE_FAMILY_UNKNOWN: Unknown or invalid network access method
* @NMA_MOBILE_FAMILY_3GPP: 3rd Generation Partnership Project (3GPP) network
* @NMA_MOBILE_FAMILY_CDMA: A CDMA network
*/
typedef enum {
NMA_MOBILE_FAMILY_UNKNOWN = 0,
NMA_MOBILE_FAMILY_3GPP,
NMA_MOBILE_FAMILY_CDMA
} NMAMobileFamily;
#define NMA_TYPE_MOBILE_ACCESS_METHOD (nma_mobile_access_method_get_type ())
typedef struct _NMAMobileAccessMethod NMAMobileAccessMethod;
GType nma_mobile_access_method_get_type (void);
NMAMobileAccessMethod *nma_mobile_access_method_ref (NMAMobileAccessMethod *method);
void nma_mobile_access_method_unref (NMAMobileAccessMethod *method);
const gchar *nma_mobile_access_method_get_name (NMAMobileAccessMethod *method);
const gchar *nma_mobile_access_method_get_username (NMAMobileAccessMethod *method);
const gchar *nma_mobile_access_method_get_password (NMAMobileAccessMethod *method);
const gchar *nma_mobile_access_method_get_gateway (NMAMobileAccessMethod *method);
const gchar **nma_mobile_access_method_get_dns (NMAMobileAccessMethod *method);
const gchar *nma_mobile_access_method_get_3gpp_apn (NMAMobileAccessMethod *method);
NMAMobileFamily nma_mobile_access_method_get_family (NMAMobileAccessMethod *method);
/******************************************************************************/
/* Mobile provider type */
#define NMA_TYPE_MOBILE_PROVIDER (nma_mobile_provider_get_type ())
typedef struct _NMAMobileProvider NMAMobileProvider;
GType nma_mobile_provider_get_type (void);
NMAMobileProvider *nma_mobile_provider_ref (NMAMobileProvider *provider);
void nma_mobile_provider_unref (NMAMobileProvider *provider);
const gchar *nma_mobile_provider_get_name (NMAMobileProvider *provider);
GSList *nma_mobile_provider_get_methods (NMAMobileProvider *provider);
const gchar **nma_mobile_provider_get_3gpp_mcc_mnc (NMAMobileProvider *provider);
const guint32 *nma_mobile_provider_get_cdma_sid (NMAMobileProvider *provider);
/******************************************************************************/
/* Country Info type */
#define NMA_TYPE_COUNTRY_INFO (nma_country_info_get_type ())
typedef struct _NMACountryInfo NMACountryInfo;
GType nma_country_info_get_type (void);
NMACountryInfo *nma_country_info_ref (NMACountryInfo *country_info);
void nma_country_info_unref (NMACountryInfo *country_info);
const gchar *nma_country_info_get_country_code (NMACountryInfo *country_info);
const gchar *nma_country_info_get_country_name (NMACountryInfo *country_info);
GSList *nma_country_info_get_providers (NMACountryInfo *country_info);
/******************************************************************************/
/* Mobile providers database type */
#define NMA_TYPE_MOBILE_PROVIDERS_DATABASE (nma_mobile_providers_database_get_type ())
#define NMA_MOBILE_PROVIDERS_DATABASE(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), NMA_TYPE_MOBILE_PROVIDERS_DATABASE, NMAMobileProvidersDatabase))
#define NMA_MOBILE_PROVIDERS_DATABASE_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), NMA_TYPE_MOBILE_PROVIDERS_DATABASE, NMAMobileProvidersDatabaseClass))
#define NMA_IS_MOBILE_PROVIDERS_DATABASE(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), NMA_TYPE_MOBILE_PROVIDERS_DATABASE))
#define NMA_IS_MOBILE_PROVIDERS_DATABASE_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), NMA_TYPE_MOBILE_PROVIDERS_DATABASE))
#define NMA_MOBILE_PROVIDERS_DATABASE_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), NMA_TYPE_MOBILE_PROVIDERS_DATABASE, NMAMobileProvidersDatabaseClass))
typedef struct _NMAMobileProvidersDatabase NMAMobileProvidersDatabase;
typedef struct _NMAMobileProvidersDatabaseClass NMAMobileProvidersDatabaseClass;
typedef struct _NMAMobileProvidersDatabasePrivate NMAMobileProvidersDatabasePrivate;
struct _NMAMobileProvidersDatabase {
GObject parent;
NMAMobileProvidersDatabasePrivate *priv;
};
struct _NMAMobileProvidersDatabaseClass {
GObjectClass parent;
};
GType nma_mobile_providers_database_get_type (void);
void nma_mobile_providers_database_new (const gchar *country_codes,
const gchar *service_providers,
GCancellable *cancellable,
GAsyncReadyCallback callback,
gpointer user_data);
NMAMobileProvidersDatabase *nma_mobile_providers_database_new_finish (GAsyncResult *res,
GError **error);
NMAMobileProvidersDatabase *nma_mobile_providers_database_new_sync (const gchar *country_codes,
const gchar *service_providers,
GCancellable *cancellable,
GError **error);
GHashTable *nma_mobile_providers_database_get_countries (NMAMobileProvidersDatabase *self);
void nma_mobile_providers_database_dump (NMAMobileProvidersDatabase *self);
NMACountryInfo *nma_mobile_providers_database_lookup_country (NMAMobileProvidersDatabase *self,
const gchar *country_code);
NMAMobileProvider *nma_mobile_providers_database_lookup_3gpp_mcc_mnc (NMAMobileProvidersDatabase *self,
const gchar *mccmnc);
NMAMobileProvider *nma_mobile_providers_database_lookup_cdma_sid (NMAMobileProvidersDatabase *self,
guint32 sid);
/******************************************************************************/
/* Utils */
gboolean nma_mobile_providers_split_3gpp_mcc_mnc (const gchar *mccmnc,
gchar **mcc,
gchar **mnc);
#endif /* NM_MOBILE_PROVIDERS_H */
| 52.575758 | 158 | 0.640058 | [
"object"
] |
914b8cdf34ccde9e4e828b0a49d5298fd85dee12 | 1,380 | h | C | src/chunk_manager.h | donqustix/colvox-cpp | 26d881484f3bd106be881bca5a0b2c9ad485eac3 | [
"MIT"
] | null | null | null | src/chunk_manager.h | donqustix/colvox-cpp | 26d881484f3bd106be881bca5a0b2c9ad485eac3 | [
"MIT"
] | null | null | null | src/chunk_manager.h | donqustix/colvox-cpp | 26d881484f3bd106be881bca5a0b2c9ad485eac3 | [
"MIT"
] | null | null | null | #ifndef CHUNKMANAGER_H
#define CHUNKMANAGER_H
#include "chunk_location_hash.h"
#include <unordered_map>
#include <memory>
#include <queue>
namespace minecpp
{
class RenderData;
class ChunkLoadService;
class ChunkUpdateService;
class Chunk;
class ResourceContainer;
class MeshChunkBuilder;
class ChunkManager
{
std::unordered_map<ChunkLocation, std::unique_ptr<Chunk>> chunks;
std::unique_ptr<MeshChunkBuilder> meshBuilder;
std::unique_ptr<ChunkUpdateService> updateService;
std::unique_ptr<ChunkLoadService> loadService;
std::queue<Chunk*> chunksUpdate;
ResourceContainer* resourceContainer;
void updateChunk(Chunk* chunk) noexcept;
void updateChunkAndNeightbors(Chunk* chunk) noexcept;
void bindChunk(Chunk* chunk) noexcept;
void processBindingChunks() noexcept;
void processUpdatingChunks() noexcept;
void processBufferingChunks() noexcept;
public:
explicit ChunkManager(ResourceContainer& resourceContainer) noexcept;
ChunkManager(ChunkManager&&);
~ChunkManager();
ChunkManager& operator=(ChunkManager&&) noexcept;
void update() noexcept;
void render(const RenderData& renderData) const noexcept;
void setVoxel(int x, int y, int z, unsigned voxel) noexcept;
};
}
#endif
| 25.090909 | 77 | 0.697101 | [
"render"
] |
915f532e2b15e557349d5f36142bbe0b392c0f91 | 3,407 | h | C | sources/multikey_tree/multikey_tree.h | marozau/system_utilities | ec165b91477c405c3b50a63072df3e8dc1dc7e7a | [
"BSL-1.0"
] | null | null | null | sources/multikey_tree/multikey_tree.h | marozau/system_utilities | ec165b91477c405c3b50a63072df3e8dc1dc7e7a | [
"BSL-1.0"
] | null | null | null | sources/multikey_tree/multikey_tree.h | marozau/system_utilities | ec165b91477c405c3b50a63072df3e8dc1dc7e7a | [
"BSL-1.0"
] | null | null | null | #ifndef _SYSTEM_UTILITIES_COMMON_MULTIKEY_TREE_H_
#define _SYSTEM_UTILITIES_COMMON_MULTIKEY_TREE_H_
#include <string>
#include <boost/thread.hpp>
#include <boost/bind.hpp>
namespace system_utilities
{
namespace common
{
namespace details
{
class multikey_tree_hasher : public std::unary_function< const std::string::const_iterator& , char >
{
public:
result_type operator()( argument_type arg )
{
if (*arg < '/' || *arg > 'z')
{
throw std::invalid_argument( std::string("invalid symbol in stock name : ") + (*arg) );
}
else
{
return *arg - '/';
}
}
};
}
template< class value_type, const size_t key_range_size = 'z' - '/' + 1 >
class multikey_tree
{
static details::multikey_tree_hasher hasher_;
value_type node_data_;
typedef std::string key_type;
typedef key_type::const_iterator key_const_iterator;
typedef std::vector< multikey_tree< value_type, key_range_size >* > children_nodes;
children_nodes children_nodes_;
mutable boost::mutex children_nodes_mutex_;
public:
explicit multikey_tree< value_type, key_range_size >()
: node_data_()
, children_nodes_( key_range_size, NULL )
{
}
~multikey_tree()
{
for ( typename children_nodes::iterator i = children_nodes_.begin() ; i != children_nodes_.end(); ++i )
delete *i;
};
value_type* get_for_edit( const std::string& key )
{
return get_for_edit( key.begin(), key.end() );
}
value_type* get_for_edit( key_const_iterator stock_name_hash_suffix_iterator_begin, const key_const_iterator stock_name_hash_suffix_iterator_end )
{
if ( stock_name_hash_suffix_iterator_begin == stock_name_hash_suffix_iterator_end )
{
return &node_data_;
}
else
{
const size_t index = hasher_(stock_name_hash_suffix_iterator_begin);
{
boost::mutex::scoped_lock lock(children_nodes_mutex_);
if (children_nodes_[index] == NULL)
children_nodes_[index] = new multikey_tree();
}
return children_nodes_[index]->get_for_edit(stock_name_hash_suffix_iterator_begin + 1, stock_name_hash_suffix_iterator_end);
}
}
const value_type* get_for_read( const std::string& key ) const
{
return get_for_read( key.begin(), key.end() );
}
const value_type* get_for_read( key_const_iterator stock_name_hash_suffix_iterator_begin, key_const_iterator stock_name_hash_suffix_iterator_end ) const
{
if ( stock_name_hash_suffix_iterator_begin == stock_name_hash_suffix_iterator_end )
{
return &node_data_;
}
else
{
const size_t index = hasher_(stock_name_hash_suffix_iterator_begin);
{
boost::mutex::scoped_lock lock(children_nodes_mutex_);
if ( children_nodes_[index] == NULL )
throw std::invalid_argument(" Incorrect request parameter ");
}
return children_nodes_[index]->get_for_read(stock_name_hash_suffix_iterator_begin + 1, stock_name_hash_suffix_iterator_end);
}
}
void clear()
{
for( size_t i = 0; i < key_range_size; ++i )
if ( children_nodes_[i] != NULL )
{
delete children_nodes_[i];
children_nodes_[i] = NULL;
}
}
};
template< class value_type, const size_t key_range_size >
details::multikey_tree_hasher multikey_tree< value_type, key_range_size >::hasher_;
}
}
#endif // _SYSTEM_UTILITIES_COMMON_MULTIKEY_TREE_H_
| 27.699187 | 155 | 0.697975 | [
"vector"
] |
916ce3560c28c829409f149511e6b6badb036b61 | 1,380 | h | C | Aplicacion Movil/generated/bundles/login-transition/build/Android/Preview/app/src/main/include/Uno.IntPtr.h | marferfer/SpinOff-LoL | a9dba8ac9dd476ec1ef94712d9a8e76d3b45aca8 | [
"Apache-2.0"
] | null | null | null | Aplicacion Movil/generated/bundles/login-transition/build/Android/Preview/app/src/main/include/Uno.IntPtr.h | marferfer/SpinOff-LoL | a9dba8ac9dd476ec1ef94712d9a8e76d3b45aca8 | [
"Apache-2.0"
] | null | null | null | Aplicacion Movil/generated/bundles/login-transition/build/Android/Preview/app/src/main/include/Uno.IntPtr.h | marferfer/SpinOff-LoL | a9dba8ac9dd476ec1ef94712d9a8e76d3b45aca8 | [
"Apache-2.0"
] | null | null | null | // This file was generated based on C:/Users/JuanJose/AppData/Local/Fusetools/Packages/UnoCore/1.9.0/Source/Uno/IntPtr.uno.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Uno.Object.h>
namespace g{
namespace Uno{
// public intrinsic struct IntPtr :11
// {
uStructType* IntPtr_typeof();
void IntPtr__Equals_fn(void** __this, uType* __type, uObject* o, bool* __retval);
void IntPtr__GetHashCode_fn(void** __this, uType* __type, int32_t* __retval);
void IntPtr__op_Equality_fn(void** left, void** right, bool* __retval);
void IntPtr__op_Inequality_fn(void** left, void** right, bool* __retval);
void IntPtr__ToString_fn(void** __this, uType* __type, uString** __retval);
struct IntPtr
{
static void* Zero_;
static void*& Zero() { return Zero_; }
static bool Equals(void* __this, uType* __type, uObject* o) { bool __retval; return IntPtr__Equals_fn(&__this, __type, o, &__retval), __retval; }
static int32_t GetHashCode(void* __this, uType* __type) { int32_t __retval; return IntPtr__GetHashCode_fn(&__this, __type, &__retval), __retval; }
static uString* ToString(void* __this, uType* __type) { uString* __retval; return IntPtr__ToString_fn(&__this, __type, &__retval), __retval; }
static bool op_Equality(void* left, void* right);
static bool op_Inequality(void* left, void* right);
};
// }
}} // ::g::Uno
| 41.818182 | 150 | 0.734783 | [
"object"
] |
9190522a57919240ebca58b4d3b12f63bb8dfc04 | 1,943 | h | C | SW4STM32/Tetris/Application/User/Player.h | PUT-PTM/2018_LEDTetris | 4089528e39653fd279bda14c078339f7d22fb810 | [
"MIT"
] | null | null | null | SW4STM32/Tetris/Application/User/Player.h | PUT-PTM/2018_LEDTetris | 4089528e39653fd279bda14c078339f7d22fb810 | [
"MIT"
] | null | null | null | SW4STM32/Tetris/Application/User/Player.h | PUT-PTM/2018_LEDTetris | 4089528e39653fd279bda14c078339f7d22fb810 | [
"MIT"
] | null | null | null | #ifndef PLAYER_H
#define PLAYER_H
#include "MAX7219_MatrixDisplay.h"
class Player {
// Class fields
bool block[3][3];
bool landed;
bool gameOver;
// Top Left position of 3x3 block
int topLeft[2]; //row col
//possible rotations 0 90 180 270;
int rotation;
// letter of block used to rotate
char letter;
public:
Player() {
landed = false;
gameOver = false;
rotation = 0;
letter = 'D';
}
void setTopLeft(int row, int col);
//Methods
//Display block on display
//TopLeft indicates position of block
void displayPlayer(MAX7219_MatrixDisplay &display);
//Playerblock is cleard used when moving/ rotation player
void clearPlayer(MAX7219_MatrixDisplay &display);
//Coping shape to block
void shapeToBlock(bool block[3][3]);
//Spawn new block on arg position
//position depends of shape
void spawnBlock(MAX7219_MatrixDisplay &display, int pos);
//Movement Methods
//Move one space down
void moveDown(MAX7219_MatrixDisplay &display);
//Move one space right
void moveRight(MAX7219_MatrixDisplay &display);
//Move one space left
void moveLeft(MAX7219_MatrixDisplay &display);
//Return true when rotation is allowed false when disallowed
bool allowRotation(MAX7219_MatrixDisplay &display, bool newShape[3][3]);
//Rotatie block 90 degree
void rotate(MAX7219_MatrixDisplay &display);
//Clear lines when row is filled
void clearLines(MAX7219_MatrixDisplay &display);
//Move rows down when one row is cleared
void shiftDown(MAX7219_MatrixDisplay &display, int row);
//Check collision of next move
//TRUE - collison
//FALSE - no collison
bool checkColision(MAX7219_MatrixDisplay &display, int newTopLeft[2]);
//Choosing Random block and calling spawnBlock
void spawnRandomBlock(MAX7219_MatrixDisplay &display);
//Czyszczenie wyswietlacza
void Clear(MAX7219_MatrixDisplay &display);
//Zapalanie po przekatnej
void Diagonal(MAX7219_MatrixDisplay &display);
};
#endif /* PLAYER_H */
| 22.858824 | 73 | 0.755018 | [
"shape"
] |
8c8020e67c85cad9c261bc7296a7253c736466c8 | 6,117 | c | C | Space Invaders/drawUtility.c | NicolaLancellotti/Space-Invaders | 6528ea0e4ef9f32f22083d984d9845863f52e563 | [
"Apache-2.0"
] | null | null | null | Space Invaders/drawUtility.c | NicolaLancellotti/Space-Invaders | 6528ea0e4ef9f32f22083d984d9845863f52e563 | [
"Apache-2.0"
] | null | null | null | Space Invaders/drawUtility.c | NicolaLancellotti/Space-Invaders | 6528ea0e4ef9f32f22083d984d9845863f52e563 | [
"Apache-2.0"
] | null | null | null | #include "drawUtility.h"
#include "preferences.h"
//______________________________________________________________________________
#pragma mark - Variables
#define ALPHA 0.1
const GLfloat MY_COLOR_ORANGE_1[] = {1.00, 0.57, 0.00, 1.0};
const GLfloat MY_COLOR_ORANGE_2[] = {0.93, 0.53, 0.00, 1.0};
const GLfloat MY_COLOR_ORANGE_3[] = {0.81, 0.46, 0.00, 1.0};
const GLfloat MY_COLOR_RED_1[] = {1.00, 0.00, 0.00, 1.0};
const GLfloat MY_COLOR_RED_2[] = {0.89, 0.00, 0.00, 1.0};
const GLfloat MY_COLOR_RED_3[] = {0.72, 0.00, 0.00, 1.0};
const GLfloat MY_COLOR_GREEN_1[] = {0.00, 1.00, 0.10, 1.0};
const GLfloat MY_COLOR_GREEN_2[] = {0.00, 0.75, 0.07, 1.0};
const GLfloat MY_COLOR_GREEN_3[] = {0.00, 0.34, 0.02, 1.0};
const GLfloat MY_COLOR_BLU_1[] = {0.00, 0.00, 1.00, 1.0};
const GLfloat MY_COLOR_SKY_1[] = {0.42, 0.71, 1.00, 1.0};
const GLfloat MY_COLOR_SKY_2[] = {0.27, 0.47, 0.68, 1.0};
const GLfloat MY_COLOR_SKY_3[] = {0.19, 0.35, 0.50, 1.0};
const GLfloat MY_COLOR_YELLOW_1[] = {1.00, 1.00, 0.00, 1.0};
const GLfloat MY_COLOR_YELLOW_2[] = {0.91, 0.91, 0.01, 1.0};
const GLfloat MY_COLOR_YELLOW_3[] = {0.77, 0.77, 0.01, 1.0};
const GLfloat MY_COLOR_VIOLET_0[] = {0.75, 0.61, 0.97, 1.0};
const GLfloat MY_COLOR_VIOLET_1[] = {0.60, 0.49, 0.80, 1.0};
const GLfloat MY_COLOR_VIOLET_3[] = {0.33, 0.26, 0.44, 1.0};
const GLfloat MY_COLOR_GRAY_1[] = {0.95, 0.95, 0.95, 1.0};
const GLfloat MY_COLOR_GRAY_2[] = {0.73, 0.73, 0.73, 1.0};
const GLfloat MY_COLOR_GRAY_3[] = {0.31, 0.31, 0.31, 1.0};
const GLfloat MY_COLOR_WHITE[] = {1.00, 1.00, 1.00, 1.0};
const GLfloat MY_COLOR_ORANGE_ALPHA_1[] = {1.00, 0.57, 0.00, ALPHA};
const GLfloat MY_COLOR_ORANGE_ALPHA_2[] = {0.93, 0.53, 0.00, ALPHA};
const GLfloat MY_COLOR_ORANGE_ALPHA_3[] = {0.81, 0.46, 0.00, ALPHA};
const GLfloat MY_COLOR_RED_ALPHA_1[] = {1.00, 0.00, 0.00, ALPHA};
const GLfloat MY_COLOR_RED_ALPHA_2[] = {0.89, 0.00, 0.00, ALPHA};
const GLfloat MY_COLOR_RED_ALPHA_3[] = {0.72, 0.00, 0.00, ALPHA};
const GLfloat MY_COLOR_GREEN_ALPHA_1[] = {0.00, 1.00, 0.10, ALPHA};
const GLfloat MY_COLOR_GREEN_ALPHA_2[] = {0.00, 0.75, 0.07, ALPHA};
const GLfloat MY_COLOR_GREEN_ALPHA_3[] = {0.00, 0.34, 0.02, ALPHA};
const GLfloat MY_COLOR_BLU_ALPHA_1[] = {0.00, 0.00, 1.00, ALPHA};
const GLfloat MY_COLOR_SKY_ALPHA_1[] = {0.42, 0.71, 1.00, ALPHA};
const GLfloat MY_COLOR_SKY_ALPHA_2[] = {0.27, 0.47, 0.68, ALPHA};
const GLfloat MY_COLOR_SKY_ALPHA_3[] = {0.19, 0.35, 0.50, ALPHA};
const GLfloat MY_COLOR_YELLOW_ALPHA_1[] = {1.00, 1.00, 0.00, ALPHA};
const GLfloat MY_COLOR_YELLOW_ALPHA_2[] = {0.91, 0.91, 0.01, ALPHA};
const GLfloat MY_COLOR_YELLOW_ALPHA_3[] = {0.77, 0.77, 0.01, ALPHA};
const GLfloat MY_COLOR_VIOLET_ALPHA_0[] = {0.75, 0.61, 0.97, ALPHA};
const GLfloat MY_COLOR_VIOLET_ALPHA_1[] = {0.60, 0.49, 0.80, ALPHA};
const GLfloat MY_COLOR_VIOLET_ALPHA_3[] = {0.33, 0.26, 0.44, ALPHA};
const GLfloat MY_COLOR_GRAY_ALPHA_1[] = {0.95, 0.95, 0.95, ALPHA};
const GLfloat MY_COLOR_GRAY_ALPHA_2[] = {0.73, 0.73, 0.73, ALPHA};
const GLfloat MY_COLOR_GRAY_ALPHA_3[] = {0.31, 0.31, 0.31, ALPHA};
// Vertex Array
GLfloat vertices[] = {
-0.5, -0.5, -0.5,
0.5, -0.5, -0.5,
0.5, 0.5, -0.5,
-0.5, 0.5, -0.5,
-0.5, -0.5, 0.5,
0.5, -0.5, 0.5,
0.5, 0.5, 0.5,
-0.5, 0.5, 0.5
};
GLubyte frontFace[] = {4, 5, 6, 7};
GLubyte backFace[] = {0, 3, 2, 1};
GLubyte leftFace[] = {0, 4, 7, 3};
GLubyte rightFace[] = {1, 2, 6, 5};
GLubyte topFace[] = {2, 3, 7, 6};
GLubyte bottomFace[] = {0, 1, 5, 4};
//______________________________________________________________________________
#pragma mark - Draw Shape
void drawRectangle(GLfloat xMin, GLfloat xMax, GLfloat yMin, GLfloat yMax)
{
glVertex2f(xMin, yMin);
glVertex2f(xMax, yMin);
glVertex2f(xMax, yMax);
glVertex2f(xMin, yMax);
}
void drawParallelepiped(GLfloat xMin, GLfloat xMax,GLfloat yMin, GLfloat yMax,
GLfloat depth,
const GLfloat *colorFrontBack,
const GLfloat colorLeftRight[],
const GLfloat colorTopBottom[])
{
glVertexPointer(3, GL_FLOAT, 0, vertices);
GLfloat x = xMax - xMin;
GLfloat y = yMax - yMin;
glPushMatrix();
glTranslatef(x / 2.0 + xMin, y / 2.0 + yMin, -depth / 2);
glScalef(x, y, depth);
glColor4fv(colorTopBottom);
glDrawElements(GL_QUADS, 4, GL_UNSIGNED_BYTE, topFace);
glDrawElements(GL_QUADS, 4, GL_UNSIGNED_BYTE, bottomFace);
glColor4fv(colorLeftRight);
glDrawElements(GL_QUADS, 4, GL_UNSIGNED_BYTE, leftFace);
glDrawElements(GL_QUADS, 4, GL_UNSIGNED_BYTE, rightFace);
glColor4fv(colorFrontBack);
glDrawElements(GL_QUADS, 4, GL_UNSIGNED_BYTE, frontFace);
glDrawElements(GL_QUADS, 4, GL_UNSIGNED_BYTE, backFace);
glPopMatrix();
}
//______________________________________________________________________________
#pragma mark - Other
void drawBottomLine()
{
glColor3fv(MY_COLOR_GREEN_1);
glBegin(GL_LINE_LOOP);
glVertex2f(0, BOTTOM_LINE);
glVertex2f(SPACE_WIDTH, BOTTOM_LINE);
glEnd();
}
void drawTopLine()
{
glColor3fv(MY_COLOR_GREEN_1);
glBegin(GL_LINE_LOOP);
glVertex2f(0, TOP_LINE);
glVertex2f(SPACE_WIDTH, TOP_LINE);
glEnd();
}
void drawBackGround()
{
glShadeModel(GL_SMOOTH);
glPushMatrix();
glTranslatef(0, 0, -1850);
glRotatef(-10, 0, 0, 1);
glScaled(2000, 2000, 1);
glBegin(GL_QUADS);
glColor3f(0.29, 0.02, 0.02);
glVertex3f(-1.5, -1.5, 0);
glVertex3f( 1.5, -1.5, 0);
glColor3f(0.01, 0.13, 0.40);
glVertex3f( 1.5, 1.5, 0);
glVertex3d(-1.5, 1.5, 0);
glEnd();
glPopMatrix();
glShadeModel(GL_FLAT);
}
void drawBoundingBoxs(const cannon_t *cannon, const barrier_t barriers[],
const aliens_t *aliens)
{
drawBoundingBox(&cannon->bb);
for (int i = 0; i < BARRIERS_NUM; ++i) {
drawBoundingBox(&barriers[i].bb);
}
for (int row = aliens->topRow; row <= aliens->bottomRow; ++row ) {
for (int col = aliens->leftCol; col <= aliens->rightCol; ++col ) {
drawBoundingBox(&aliens->matrix[row][col].bb);
}
}
drawBoundingBox(&aliens->bb);
}
| 34.954286 | 81 | 0.657021 | [
"shape"
] |
8c8b1225b8bb41889234decfed995959201f4f14 | 424,022 | c | C | src/pdb_drv/silo_pdb.c | markcmiller86/silo | 2597088f1b0c48873fee8635ce788df0defaf5b2 | [
"Apache-2.0"
] | 8 | 2021-10-08T00:22:19.000Z | 2022-03-21T02:17:31.000Z | src/pdb_drv/silo_pdb.c | markcmiller86/silo | 2597088f1b0c48873fee8635ce788df0defaf5b2 | [
"Apache-2.0"
] | 184 | 2019-03-20T03:02:33.000Z | 2019-03-24T18:08:08.000Z | src/pdb_drv/silo_pdb.c | markcmiller86/silo | 2597088f1b0c48873fee8635ce788df0defaf5b2 | [
"Apache-2.0"
] | 4 | 2021-12-28T11:40:36.000Z | 2022-03-30T08:51:51.000Z | /*
Copyright (C) 1994-2016 Lawrence Livermore National Security, LLC.
LLNL-CODE-425250.
All rights reserved.
This file is part of Silo. For details, see silo.llnl.gov.
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 disclaimer below.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the disclaimer (as noted
below) in the documentation and/or other materials provided with
the distribution.
* Neither the name of the LLNS/LLNL 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 LAWRENCE
LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY 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.
This work was produced at Lawrence Livermore National Laboratory under
Contract No. DE-AC52-07NA27344 with the DOE.
Neither the United States Government nor Lawrence Livermore National
Security, LLC nor any of their employees, makes any warranty, express
or implied, or assumes any liability or responsibility for the
accuracy, completeness, or usefulness of any information, apparatus,
product, or process disclosed, or represents that its use would not
infringe privately-owned rights.
Any reference herein to any specific commercial products, process, or
services by trade name, trademark, manufacturer or otherwise does not
necessarily constitute or imply its endorsement, recommendation, or
favoring by the United States Government or Lawrence Livermore
National Security, LLC. The views and opinions of authors expressed
herein do not necessarily state or reflect those of the United States
Government or Lawrence Livermore National Security, LLC, and shall not
be used for advertising or product endorsement purposes.
*/
/*
* silo-pdb.c -- The PDB functions.
*/
#define NEED_SCORE_MM
#include "silo_pdb_private.h"
#include <float.h>
/* The code between BEGIN/END monikers used to reside in a separate
* file, 'pjjacket.c' but was moved here to reduce polution of the
* global namespace with PJ symbols that are relevant only to the
* PDB driver as well as to make it easier to re-map the code here
* for th PDB proper driver */
/* BEGIN pjjacket.c */
/*
Module Name pjjacket.c
Purpose
This module contains the 'jacket' functions which map the
special directory PDB functions (prefixed with 'PJ') using
variable names into valid PDB functions.
Programmer
Jeffery Long, NSSD/B
Contents
Jacket Routines
---------------
(int) PJ_read()
(int) PJ_read_as()
(int) PJ_read_alt()
(int) PJ_read_as_alt()
*/
static char *pj_fixname(PDBfile *, char const *);
/*-------------------------------------------------------------------------
* Function: PJ_read
*
* Purpose:
*
* Return: Success:
*
* Failure:
*
* Programmer:
*
* Modifications:
*
*-------------------------------------------------------------------------
*/
INTERNAL int
PJ_read (PDBfile *file, char const *name, void *var) {
char *newname = pj_fixname(file, name);
return (lite_PD_read(file, newname, var));
}
/*-------------------------------------------------------------------------
* Function: PJ_read_alt
*
* Purpose:
*
* Return: Success:
*
* Failure:
*
* Programmer:
*
* Modifications:
*
*-------------------------------------------------------------------------
*/
INTERNAL int
PJ_read_alt (PDBfile *file, char *name, void *var, long *ind) {
char *newname = pj_fixname(file, name);
return (lite_PD_read_alt(file, newname, var, ind));
}
/*-------------------------------------------------------------------------
* Function: PJ_read_as
*
* Purpose:
*
* Return: Success:
*
* Failure:
*
* Programmer:
*
* Modifications:
*
*-------------------------------------------------------------------------
*/
INTERNAL int
PJ_read_as (PDBfile *file, char *name, char *type, void *var) {
char *newname = pj_fixname(file, name);
return (lite_PD_read_as(file, newname, type, var));
}
/*-------------------------------------------------------------------------
* Function: PJ_read_as_alt
*
* Purpose:
*
* Return: Success:
*
* Failure:
*
* Programmer:
*
* Modifications:
*
*-------------------------------------------------------------------------
*/
INTERNAL int
PJ_read_as_alt (PDBfile *file, char *name, char *type, void *var, long *ind) {
char *newname = pj_fixname(file, name);
return (lite_PD_read_as_alt(file, newname, type, var, ind));
}
/*-----------------------------------------------------------*
* Modifications:
*
* Al Leibee, Mon Aug 9 10:30:54 PDT 1993
* Converted to new PDBlib interface for PD_inquire_entry.
* Note that the new args 'flag' and 'full path' are not
* used since pj_fixname is always invoked to get the full
* path name.
*-----------------------------------------------------------*/
/*-------------------------------------------------------------------------
* Function: PJ_inquire_entry
*
* Purpose:
*
* Return: Success:
*
* Failure:
*
* Programmer:
*
* Modifications:
*
*-------------------------------------------------------------------------
*/
INTERNAL syment *
PJ_inquire_entry (PDBfile *file, char const *name) {
char *newname = pj_fixname(file, name);
return (lite_PD_inquire_entry(file, newname, FALSE, NULL));
}
/*======================================================================
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
======================================================================*/
/*
* Modifications
*
* Al Leibee, Wed Jul 7 08:00:00 PDT 1993
* SCALLOC_N to ALLOC_N to be not SCORE-dependent.
*/
/*-------------------------------------------------------------------------
* Function: pj_fixname
*
* Purpose:
*
* Return: Success:
*
* Failure:
*
* Programmer:
*
* Modifications:
*
* Robb Matzke, Sun Dec 18 17:33:35 EST 1994
* _outname is static allocated instead of on the heap. Otherwise
* it shows up as a memory leak since we always forget to free it
* at the end of the program.
*
* Mark C. Miller, Mon Jan 30 19:43:02 PST 2006
* Increased size of _outname to something more appropriate. Added
* code to avoid over-writes
*
*-------------------------------------------------------------------------
*/
INTERNAL char *
pj_fixname (PDBfile *file, char const *inname) {
static char _outname[MAXLINE];
/*
* If requested name begins with a '/', just use it.
* Otherwise, form a name with an absolute path.
*/
if (inname[0] == '/') {
strncpy(_outname, inname, sizeof(_outname));
_outname[sizeof(_outname)-1] = '\0';
}
else {
PJ_get_fullpath(lite_PD_pwd(file), inname, _outname);
}
return (_outname);
}
/*-------------------------------------------------------------------------
* Function: PJ_write
*
* Purpose:
*
* Return: Success:
*
* Failure:
*
* Programmer:
*
* Modifications:
*
*-------------------------------------------------------------------------
*/
#ifdef PDB_WRITE
INTERNAL int
PJ_write (PDBfile *file, char *name, char *type, void *var) {
char *newname = pj_fixname(file, name);
return (lite_PD_write(file, newname, type, var));
}
#endif /* PDB_WRITE */
/*-------------------------------------------------------------------------
* Function: PJ_write_alt
*
* Purpose:
*
* Return: Success:
*
* Failure:
*
* Programmer:
*
* Modifications:
*
*-------------------------------------------------------------------------
*/
#ifdef PDB_WRITE
INTERNAL int
PJ_write_alt (PDBfile *file, char const *name, char const *type,
void const *var, int nd, long const *ind) {
char *newname = pj_fixname(file, name);
return (lite_PD_write_alt(file, newname, (char *) type,
(void *) var, nd, (long *) ind));
}
#endif /* PDB_WRITE */
/*-------------------------------------------------------------------------
* Function: PJ_write_len
*
* Purpose: Alternate form of PD_write_alt, which accepts length rather
* than pairs of min/max indices.
*
* Return: Success:
*
* Failure:
*
* Programmer:
*
* Modifications:
*
*-------------------------------------------------------------------------
*/
#ifdef PDB_WRITE
INTERNAL int
PJ_write_len (PDBfile *file, char const *name, char const *type, void const *var, int nd,
long const *len) {
long ind[15], i;
char *newname = pj_fixname(file, name);
for (i = 0; i < nd; i++) {
ind[i * 3] = 0;
ind[i * 3 + 1] = len[i] - 1;
ind[i * 3 + 2] = 1;
}
return (lite_PD_write_alt(file, newname, (char*) type, (void*) var, nd, ind));
}
#endif /* PDB_WRITE */
/* END pjjacket.c */
/* The code between BEGIN/END monikers used to reside in a separate
* file, 'pjobj.c' but was moved here to reduce polution of the
* global namespace with PJ symbols that are relevant only to the
* PDB driver as well as to make it easier to re-map the code here
* for th PDB proper driver */
/* BEGIN pjobj.c */
/*-------------------------------------------------------------------------
* Global private variables.
*-------------------------------------------------------------------------
*/
static int _pj_force_single = FALSE;
/*======================================================================
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
======================================================================
Module Name pjobject.c
Purpose
This module contains functions for easily reading PDB objects.
Programmer
Jeffery Long, NSSD/B
Description
The principal function here is PJ_GetObject. It operates on a
PJcomplist data structure, which is simply a set of names, pointers,
and data types which describe the components of a PDB object.
PJ_GetObject interprets the object description and reads the object
components into the pointers provided.
There are three macros defined in pjgroup.h for simplifying the use
of PJ_GetObject. They are PJ_INIT_OBJ, PJ_DEFINE_OBJ and
PJ_DEFALL_OBJ. PJ_INIT_OBJ takes a single argument, the address of
a PJ_Object to manipulate. PJ_DEFINE_OBJ & PJ_DEFALL_OBJ take four
arguments: the component name, the address of where to store the
component, the component data type, and a sentinel indicating
whether or not the component is a scalar.
Contents
int PJ_GetObject (file, objname, object, ret_type)
void *PJ_GetComponent (file, objname, compname)
*/
/* Definition of global variables (bleah!) */
/* The variable use_PJgroup_cache is used in the PJ_GetObject function call.
* That function will cache any PJgroup that it retrieves, if possible.
* Sometimes, however, we've changed the state of the file (like changing
* directories) and must ignore any cache that we already have. The
* "use_PJgroup_cache" variable is a boolean value that allows us to ignore
* the cached value when we need to. Note that, even if this variable is set
* to 0 here, it will be reset to 1 after the first group is read.
*/
static int use_PJgroup_cache = 1;
/* To cache the PJgroup, we need to keep the group, and we need to keep
* the "definition" of which object it is. This information can be
* captured by storing the name of the object, the name of the file it
* came from, and the directory from which it came.
*/
static PJgroup *cached_group = NULL;
static char *cached_obj_name = NULL;
static char *cached_file_name = NULL;
PRIVATE int db_pdb_ParseVDBSpec (char const *mvdbspec, char **varname,
char **filename);
PRIVATE int pj_GetVarDatatypeID (PDBfile *file, char *varname);
PRIVATE void reduce_path(char *path, char *npath);
/*----------------------------------------------------------------------
* Routine PJ_ForceSingle
*
* Purpose
*
* Set the force single flag.
*
* Programmer
*
* Eric Brugger, February 15, 1995
*
* Notes
*
* Modified
*
*--------------------------------------------------------------------
*/
INTERNAL int
PJ_ForceSingle (int flag) {
_pj_force_single = flag ? 1 : 0;
return (0);
}
/*----------------------------------------------------------------------
* Routine PJ_InqForceSingle
*
* Purpose
*
* Inquire the status of the force single flag.
*
* Programmer
*
* Eric Brugger, February 15, 1995
*
* Notes
*
* Modified
*
*--------------------------------------------------------------------
*/
INTERNAL int
PJ_InqForceSingle(void)
{
return (_pj_force_single);
}
/*----------------------------------------------------------------------
* Routine: PJ_NoCache
*
* Purpose:
* Turn off caching of PJgroups until the next PJ_GetObject call.
*
* Programmer:
* Sean Ahern, Mon Jul 1 08:23:41 PDT 1996
*
* Notes:
* See comment at the top of this file about the use_PJgroup_cache
* global variable.
*
* Modifications:
*
* Jim Reus, 23 Apr 97
* Provide void in parameter list (to agree with header file).
*
*--------------------------------------------------------------------
*/
INTERNAL void
PJ_NoCache ( void )
{
use_PJgroup_cache = 0;
}
/*----------------------------------------------------------------------
* Routine PJ_GetObject
*
* Purpose
*
* Read the contents of an object and store each entity into the
* address provided in the given component list structure.
*
* Programmer
*
* Jeffery W. Long, NSSD-B
*
* Notes
*
* Modified
*
* Robb Matzke, Tue Nov 8 08:30:58 PST 1994
* Added error mechanism
*
* Sean Ahern, Wed Jun 26 16:26:08 PDT 1996
* Added caching of the PJgroup.
*
* Eric Brugger, Wed Dec 11 12:41:47 PST 1996
* I swapped the order of the loops over group component names
* and list component names. This can be made slightly more
* efficient since the inner loop can be made to terminate
* earlier if a match is found. This also closes a memory leak
* in the case where a component name is in the group twice and
* the memory for it should be allocated. This has the other
* side affect of changing the behaviour such that if an entry
* shows up more than once it will take the first one, not the
* last one.
*
* Sean Ahern, Mon Nov 23 17:03:59 PST 1998
* Removed the memory associated with the group when we're replacing the
* cached one. Moved the memory management of the cache to a better
* place in the file.
*
* Eric Brugger, Tue Dec 15 14:41:20 PST 1998
* I modified the routine to handle file names in the object name.
*
* Sean Ahern, Thu Mar 30 11:01:56 PST 2000
* Fixed a memory leak.
*
* Sean Ahern, Tue Jun 13 17:25:25 PDT 2000
* Made the function return the type of the object, if requested.
* Beefed up the error message if the object isn't found.
*
* Mark C. Miller, Wed Sep 12 09:08:32 PDT 2012
* Replaced returned 'ret_type' argument with input expected_dbtype
* argument and cause it to fail if type that is read doesn't
* match the expected_dbtype.
*--------------------------------------------------------------------*/
INTERNAL int
PJ_GetObject(PDBfile *file_in, char const *objname_in, PJcomplist *tobj, int expected_dbtype)
{
int i, j, error;
char *varname=NULL, *filename=NULL;
char const *objname=NULL;
PDBfile *file=NULL;
char *me = "PJ_GetObject";
if (!file_in)
return db_perror(NULL, E_NOFILE, me);
if (!objname_in || !*objname_in)
return db_perror("objname", E_BADARGS, me);
/*
* If the object name has a filename in it then open the file
*/
if (db_pdb_ParseVDBSpec(objname_in, &varname, &filename) < 0)
{
FREE(varname);
return db_perror("objname", E_BADARGS, me);
}
if (filename != NULL)
{
objname = varname;
if ((file = lite_PD_open((char*)filename, "r")) == NULL)
{
FREE (varname);
FREE (filename);
return db_perror("objname", E_BADARGS, me);
}
#ifdef USING_PDB_PROPER
PD_set_track_pointers(file, FALSE);
#endif
}
else
{
objname = objname_in;
file = file_in;
}
/* Read object description if we don't have it cached.
*
* There are three things that we have to check:
* use_PJgroup_cache is true
* cache_obj_name is the same as the passed-in name
* cache_file_name is the same as the passed-in file's name
*
* If any of these are false, we can't use the cached PJgroup and must
* instead read a new one from the PDBfile.
*/
if ((use_PJgroup_cache == 0) ||
(cached_obj_name == NULL) || (strcmp(cached_obj_name, objname) != 0) ||
(cached_file_name == NULL) || (strcmp(cached_file_name, file->name)))
{
PJ_ClearCache();
error = !PJ_get_group(file, objname, &cached_group);
if (error || cached_group == NULL)
{
char err_str[256];
sprintf(err_str,"PJ_get_group: Probably no such object \"%s\".",objname);
FREE(varname);
FREE(filename);
db_perror(err_str, E_CALLFAIL, me);
return -1;
}
/* Check object type before we do any allocations */
if (expected_dbtype > 0)
{
int matched = 1;
if (expected_dbtype == DB_QUADMESH)
{
if ((strcmp(cached_group->type, DBGetObjtypeName(DB_QUAD_RECT)) != 0) &&
(strcmp(cached_group->type, DBGetObjtypeName(DB_QUAD_CURV)) != 0))
matched = 0;
}
else if (strcmp(cached_group->type, DBGetObjtypeName(expected_dbtype)) != 0)
{
matched = 0;
}
if (!matched)
{
char error[256];
sprintf(error,"Requested %s object \"%s\" is not a %s.",
cached_group->type, objname_in, DBGetObjtypeName(expected_dbtype));
FREE(varname);
FREE(filename);
db_perror(error, E_NOTFOUND, me);
return -1;
}
}
/* We've gotten a new group, remember which one it is. */
cached_obj_name = STRDUP(objname);
cached_file_name = STRDUP(file->name);
/* Now that we've cached a group, turn caching back on. */
use_PJgroup_cache = 1;
}
/* Check object type */
if (expected_dbtype > 0)
{
int matched = 1;
if (expected_dbtype == DB_QUADMESH)
{
if ((strcmp(cached_group->type, DBGetObjtypeName(DB_QUAD_RECT)) != 0) &&
(strcmp(cached_group->type, DBGetObjtypeName(DB_QUAD_CURV)) != 0))
matched = 0;
}
else if (strcmp(cached_group->type, DBGetObjtypeName(expected_dbtype)) != 0)
{
matched = 0;
}
if (!matched)
{
char error[256];
FREE(varname);
FREE(filename);
sprintf(error,"Requested %s object \"%s\" is not a %s.",
cached_group->type, objname_in, DBGetObjtypeName(expected_dbtype));
db_perror(error, E_NOTFOUND, me);
return -1;
}
}
/* Walk through the object, putting the data into the appropriate memory
* locations. */
for (i = 0; i < tobj->num; i++)
{
for (j = 0; j < cached_group->ncomponents; j++)
{
if (tobj->ptr[i] != NULL &&
STR_EQUAL(cached_group->comp_names[j], tobj->name[i]))
{
/*
* For alloced arrays, pass the address of the
* pointer (i.e., ptr[i]). If not alloced, address
* is already in the ptr[i] element.
*/
PJ_ReadVariable(file, cached_group->pdb_names[j],
tobj->type[i], (int)tobj->alloced[i],
(tobj->alloced[i]) ?
(char **)&tobj->ptr[i] :
(char **)tobj->ptr[i]);
}
}
}
/*
* If the variable was from another file the file.
*/
if (filename != NULL)
{
FREE (filename);
lite_PD_close (file);
}
FREE (varname);
return 0;
}
/*----------------------------------------------------------------------
* Function: PJ_ClearCache
*
* Purpose: Frees up the storage associated with the cache.
*
* Programmer: Sean Ahern, Mon Nov 23 17:19:17 PST 1998
*
* Modifications:
*
* Lisa J. Roberts, Tue Jul 27 12:46:30 PDT 1999
* Added a return statement at the end of the function.
*
* Brad Whitlock, Thu Jan 20 15:32:27 PST 2000
* Added the void to the argument list to preserve the prototype.
*
*--------------------------------------------------------------------*/
INTERNAL int
PJ_ClearCache(void)
{
int error;
static char *me = "PJ_ClearCache";
/* Free up the old group. */
if (cached_group)
{
error = !PJ_rel_group(cached_group);
if (error)
{
db_perror("PJ_rel_group", E_CALLFAIL, me);
return -1;
}
cached_group = NULL;
}
FREE(cached_obj_name);
FREE(cached_file_name);
return 0;
}
/*----------------------------------------------------------------------
* Routine PJ_GetComponent
*
* Purpose
*
* Read the contents of an object and store each entity into the
* address provided in the given component list structure.
*
* Programmer
*
* Jeffery W. Long, NSSD-B
*
* Notes
*
* Modified
*
* Robb Matzke, Tue Nov 8 08:39:56 PST 1994
* Added error mechanism
*--------------------------------------------------------------------
*/
INTERNAL void *
PJ_GetComponent (PDBfile *file, char const *objname, char const *compname) {
char *result = NULL;
PJcomplist tmp_obj;
char *me = "PJ_GetComponent";
PJcomplist *_tcl;
/* Read just the requested component of the given object */
INIT_OBJ(&tmp_obj);
DEFALL_OBJ(compname, &result, DB_NOTYPE);
if (PJ_GetObject(file, objname, &tmp_obj, 0) < 0) {
db_perror("PJ_GetObject", E_CALLFAIL, me);
return NULL;
}
return ((void *)result);
}
/*----------------------------------------------------------------------
* Routine PJ_GetComponentType
*
* Purpose
*
* Reads the contents of an object if it is not already cached and
* looks in the component list to determine the component type.
*
* Programmer
*
* Brad Whitlock, Thu Jan 20 15:26:51 PST 2000
*
* Notes
*
* Modified
*
*--------------------------------------------------------------------
*/
INTERNAL int
PJ_GetComponentType (PDBfile *file, char const *objname, char const *compname)
{
int retval = DB_NOTYPE;
char *me = "PJ_GetComponentType";
PJcomplist *_tcl;
/* If there is no cached group, or we are interested in a
* different object, get the one we want. */
if(cached_group == NULL || cached_obj_name == NULL ||
(!STR_EQUAL(cached_obj_name, objname)))
{
char *result = NULL;
PJcomplist tmp_obj;
/* Read just the requested component of the given object */
INIT_OBJ(&tmp_obj);
DEFALL_OBJ(compname, &result, DB_NOTYPE);
if (PJ_GetObject(file, objname, &tmp_obj, 0) < 0) {
db_perror("PJ_GetObject", E_CALLFAIL, me);
return DB_NOTYPE;
}
FREE(result);
}
/* If there is now cached group information (and there should be)
* then look for the component in the group and determine its type. */
if(use_PJgroup_cache && cached_group)
{
int i, index, found = 0;
/* Look through the cached group's component list to find
* the appropriate index. */
for(i = 0; i < cached_group->ncomponents; i++)
{
if(strcmp(compname, cached_group->comp_names[i]) == 0)
{
found = 1;
index = i;
break;
}
}
/* If the component name was in the list then determine
* the type. If it does not have a prefix, then it must be
* a variable since components can only be int,float,double,
* string, or variable. */
if(found)
{
if(strncmp(cached_group->pdb_names[index], "'<i>", 4) == 0)
retval = DB_INT;
else if(strncmp(cached_group->pdb_names[index], "'<f>", 4) == 0)
retval = DB_FLOAT;
else if(strncmp(cached_group->pdb_names[index], "'<d>", 4) == 0)
retval = DB_DOUBLE;
else if(strncmp(cached_group->pdb_names[index], "'<s>", 4) == 0)
retval = DB_CHAR;
else
retval = DB_VARIABLE;
}
}
return retval;
}
/*----------------------------------------------------------------------
* Routine PJ_ReadVariable
*
* Purpose
*
* Read an entity of arbitrary type from a PDB file.
*
* Programmer
*
* Jeffery W. Long, NSSD-B
*
* Notes
*
* If the requested entity is either a scalar or a literal, the
* result will be stored directly into the space pointed to by
* var. Otherwise, space will be allocated and var will be
* assigned the new address.
*
* Modifications
* Al Leibee, Thu Feb 17 13:04:47 PST 1994
* Removed Kludge re use of db_pdb_getvarinfo by using
* pdb_getvarinfo.
*
* Robb Matzke, Fri Dec 2 13:51:28 PST 1994
* If this function allocates space for `var' we use the C
* libraray--not SCORE.
*
* Eric Brugger, Mon Oct 23 12:17:03 PDT 1995
* I corrected a bug with the forcing of values. If the value
* was forced, new storage was allocated for the space to put the
* results. But this was a bug since if storage was passed to the
* routine, then the data had to be put in that space.
*
* Eric Brugger, Thu Aug 20 11:46:54 PDT 1998
* I modified the routine to not perform forcing of values to
* single if the required type was DB_NOTYPE. I think that the
* correct behavior is to only do forcing if the required data
* type is DB_FLOAT, but this routine gets used a lot and to
* check that it was always being called correctly is a lot of
* work.
*
* Brad Whitlock, Thu Jan 20 17:33:20 PST 2000
* Added code for double conversion.
*
* Eric Brugger, Fri Sep 1 14:53:59 PDT 2000
* Added code to compress out "../" from the variable name.
*
* Mark C. Miller, Fri Nov 13 15:26:38 PST 2009
* Add support for long long data type.
*
* Mark C. Miller, Mon Dec 7 09:50:19 PST 2009
* Conditionally compile long long support only when its
* different from long.
*
* Mark C. Miller, Mon Jan 11 16:02:16 PST 2010
* Made long long support UNconditionally compiled.
*
* Mark C. MIller Mon Dec 10 09:54:05 PST 2012
* Fix possible ABR when tname is size zero.
*--------------------------------------------------------------------*/
INTERNAL int
PJ_ReadVariable(PDBfile *file,
char *name_in, /*Name of variable to read */
int req_datatype, /*Requested datatype for variable */
int alloced, /*has space already been allocated? */
char **var) /*Address of ptr to store data into */
{
int num, size, i, okay;
int act_datatype, forcing;
int *iptr;
char tname[256], *lit;
float *local_f;
char *local_c;
float *fptr;
double *dptr;
char *name=0;
okay = TRUE;
name = ALLOC_N(char, strlen(name_in)+1);
reduce_path(name_in, name);
/* Determine actual datatype of variable or literal */
act_datatype = pj_GetVarDatatypeID(file, name);
/* Set sentinel if will be forcing doubles to floats */
if (req_datatype != DB_NOTYPE && req_datatype != act_datatype &&
_pj_force_single)
forcing = 1;
else
forcing = 0;
/*--------------------------------------------------
* If name is enclosed in single quotes, take it as
* a literal value.
*-------------------------------------------------*/
if (name[0] == '\'') {
int tnmlen;
/*
* No forcing of literals. Since literals return an
* an actual data type of -1, they will never get forced
* since this is not a valid type. This is a case of two
* wrongs making a right since if the actual data type had
* been a valid value, this routine would have tried to
* convert it which would have been an error.
*/
forcing = 0;
/*--------------------------------------------------
* Component is a literal. Convert from ascii
* to type specified in string (default is int).
*-------------------------------------------------*/
strcpy(tname, &name[1]);
tnmlen = strlen(tname);
tnmlen = tnmlen>0?tnmlen:1;
tname[tnmlen - 1] = '\0';
if (name[1] == '<')
lit = &tname[3];
else
lit = tname;
if (STR_BEGINSWITH(tname, "<i>")) {
if (alloced)
iptr = (int *)*var;
else
iptr = ALLOC(int);
*iptr = atoi(lit);
*var = (char *)iptr;
}
else if (STR_BEGINSWITH(tname, "<f>")) {
if (alloced)
fptr = (float *)*var;
else
fptr = ALLOC(float);
*fptr = (float)atof(lit);
*var = (char *)fptr;
}
else if (STR_BEGINSWITH(tname, "<d>")) {
if (alloced)
dptr = (double *)*var;
else
dptr = ALLOC(double);
*dptr = (double)atof(lit);
*var = (char *)dptr;
}
else if (STR_BEGINSWITH(tname, "<s>")) {
if (alloced)
strcpy(*var, lit);
else {
*var = ALLOC_N(char, strlen(lit) + 1);
strcpy(*var, lit);
}
}
else {
if (alloced)
iptr = (int *)*var;
else
iptr = ALLOC(int);
*iptr = atoi(lit);
*var = (char *)iptr;
}
}
else {
/*--------------------------------------------------
* Component is not a literal. See if it was
* alloced. If so, read directly into 'var' space.
* Otherwise, let PDB assign address to our ptr.
* NOTE -- if num is returned '-1', name is a
* pointered array.
*-------------------------------------------------*/
(void)pdb_getvarinfo(file, name, tname, &num, &size, 0);
/* If not already allocated, and is not a pointered var, allocate */
if (!alloced && num > 0) {
if (forcing)
*var = ALLOC_N (char, num * sizeof(float));
else
{
if (act_datatype == DB_CHAR)
{
*var = ALLOC_N (char, (num+1) * size);
(*var)[num] = '\0';
}
else
{
*var = ALLOC_N (char, num * size);
}
}
alloced = 1;
}
/*
* If we are forcing the values to float, then read the
* values into a buffer the size of the data as it exists
* in the file.
*/
if (forcing) {
local_f = (float *) *var;
*var = ALLOC_N (char, num * size);
}
if (alloced)
/*------------------------------
* Space already allocated by
* caller, so use that.
*-----------------------------*/
okay = PJ_read(file, name, *var);
else
/*------------------------------
* Let PDBlib allocate new
* space. Just set pointer.
*-----------------------------*/
okay = PJ_read(file, name, var);
/*
* PDB cannot query length of pointered vars in file, so
* num is set to -1. Now that it has been read, can query
* length.
*/
if (num < 0) {
num = lite_SC_arrlen(*var) / size;
local_c = ALLOC_N(char, num * size);
memcpy(local_c, *var, num * size);
SCFREE(*var);
*var = local_c;
}
}
/*--------------------------------------------------
* Map values to float if
* force-single flag is TRUE.
*--------------------------------------------------*/
if (okay && forcing) {
char *c_conv = NULL;
double *d_conv = NULL;
long *l_conv = NULL;
long long *ll_conv = NULL;
short *s_conv = NULL;
int *i_conv = NULL;
switch (act_datatype) {
case DB_INT:
i_conv = (int *)(*var);
for (i = 0; i < num; i++)
local_f[i] = (float)i_conv[i];
break;
case DB_SHORT:
s_conv = (short *)(*var);
for (i = 0; i < num; i++)
local_f[i] = (float)s_conv[i];
break;
case DB_LONG:
l_conv = (long *)(*var);
for (i = 0; i < num; i++)
local_f[i] = (float)l_conv[i];
break;
case DB_LONG_LONG:
ll_conv = (long long *)(*var);
for (i = 0; i < num; i++)
local_f[i] = (float)ll_conv[i];
break;
case DB_DOUBLE:
d_conv = (double *)(*var);
for (i = 0; i < num; i++)
local_f[i] = (float)d_conv[i];
break;
case DB_CHAR:
c_conv = (char *)(*var);
for (i = 0; i < num; i++)
local_f[i] = (float)c_conv[i];
break;
default:
break;
}
}
if (forcing) {
FREE(*var);
*var = (char *)local_f;
}
FREE(name);
return (okay);
}
/*----------------------------------------------------------------------
* Routine pj_GetVarDatatypeID
*
* Purpose
*
* Return the datatype of the given variable.
*
* Notes
*
* Modifications
*
* Al Leibee, Wed Aug 18 15:59:26 PDT 1993
* Convert to new PJ_inquire_entry interface.
*
* Sean Ahern, Wed Apr 12 11:14:38 PDT 2000
* Removed the last two parameters to PJ_inquire_entry because they
* weren't being used.
*--------------------------------------------------------------------*/
PRIVATE int
pj_GetVarDatatypeID (PDBfile *file, char *varname) {
syment *ep;
if (varname[0] == '<')
return DB_CHAR;
ep = PJ_inquire_entry(file, varname);
if (ep == NULL)
return (OOPS);
return (SW_GetDatatypeID(ep->type));
}
/*----------------------------------------------------------------------
* Routine db_pdb_ParseVDBSpec
*
* Purpose
*
* Parse a variable database specification.
*
* Notes
*
* Modifications
*
*--------------------------------------------------------------------*/
PRIVATE int
db_pdb_ParseVDBSpec (char const *mvdbspec, char **varname, char **filename)
{
int len_filename, len_varname;
/*
* Split spec into SILO name and SILO directory/variable name.
*/
if (strchr (mvdbspec, ':') != NULL)
{
len_filename = strcspn (mvdbspec, ":");
*filename = ALLOC_N (char, len_filename+1);
strncpy (*filename, mvdbspec, len_filename);
len_varname = strlen(mvdbspec) - (len_filename+1);
if (len_varname <= 0)
{
FREE (*filename);
return (OOPS);
}
/*
* If a / does not exist at the beginning of the
* path, insert it.
*/
if (mvdbspec[len_filename+1] == '/')
{
*varname = ALLOC_N (char, len_varname+1);
strncpy (*varname, &mvdbspec[len_filename+1], len_varname);
}
else
{
*varname = ALLOC_N (char, len_varname+2);
(*varname) [0] = '/';
strncpy (&((*varname)[1]), &mvdbspec[len_filename+1], len_varname);
len_varname++;
}
}
else
{
*filename = NULL;
*varname = ALLOC_N (char, strlen(mvdbspec)+1);
strcpy (*varname, mvdbspec);
}
return (OKAY);
}
/*----------------------------------------------------------------------
* Routine reduce_path
*
* Purpose
*
* Compress out the "../" from a path.
*
* Notes
*
* Programmer Eric Brugger
* Date September 1, 2000
*
* Modifications
*
*--------------------------------------------------------------------*/
PRIVATE void
reduce_path(char *path, char *npath)
{
int i, j;
int lpath;
npath [0] = '/' ;
npath [1] = '\0' ;
j = 0 ;
lpath = strlen (path) ;
for (i = 0; i < lpath; i++) {
while (path [i] == '/' && path [i+1] == '/')
i++ ;
if (path [i] == '/' && path [i+1] == '.' && path [i+2] == '.' &&
(path [i+3] == '/' || path [i+3] == '\0')) {
if (j > 0)
j-- ;
while (npath [j] != '/' && j > 0)
j-- ;
i += 2 ;
}
else {
npath [j++] = path [i] ;
}
}
npath [j] = '\0' ;
/*
* Check that the path is valid.
*/
if (j == 0) {
path [0] = '/';
path [1] = '\0';
}
}
/* END pjobj.c */
/* The code between BEGIN/END monikers used to reside in a separate
* file, 'pjgroup.c' but was moved here to reduce polution of the
* global namespace with PJ symbols that are relevant only to the
* PDB driver as well as to make it easier to re-map the code here
* for th PDB proper driver */
/* BEGIN pjgroup.c */
/*======================================================================
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
======================================================================
Module Name pjgroup.c
Purpose
This module provides a capability for reading and writing
group descriptions in a PDB file.
Programmer
Jeffery Long, NSSD/B
Description
Contents
User-Callable Functions (C)
int PJ_put_group (file, group, overwrite)
int PJ_get_group (file, name, PJgroup **group)
PJgroup *PJ_make_group (name, type, comp_names, pdb_names, num)
int PJ_rel_group (group)
User-Callable Functions (Fortran)
Internal-Use-Only Functions
======================================================================
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
======================================================================*/
/*
**********************
* Modification History
**********************
* $Id: pjgroup.c,v 1.4 1995/08/30 00:21:38 ahern Exp $
* $Header: /SRC/pact/repository/src/silo/pdb/pjgroup.c,v 1.4 1995/08/30 00:21:38 ahern Exp $
* $Log: pjgroup.c,v $
* Revision 1.4 1995/08/30 00:21:38 ahern
* < ahern | D95_08_29_17_20_15 > Reformatted whitespace and tabs. You'll find that most changes are in comments.
*
* Revision 1.3 1995/08/28 21:53:40 ahern
* < ahern | D95_08_28_14_49_09 > Ran indent on silo.
*
* Revision 1.2 1995/04/21 16:16:34 brugger
* < brugger | D95_04_21_09_10_55 > I merged in Robbs silo filters enhancements into silo.
*
* Revision 1.1 1995/02/01 00:54:03 brugger
* < brugger | D95_01_31_16_47_08 > I incorporated robbs new device independent silo.
*
* Revision 1.2 1994/10/17 16:17:29 brugger
* < brugger | D94_10_17_09_09_09 > I restructured silo
*
* Revision 1.1.1.1 1994/04/13 22:55:17 sabrown
* Reconfigure SILO
*
* Revision 1.2 1993/09/27 16:30:37 leibee
* < leibee | Mon Sep 27 09:25:46 PDT 1993 > Commit of v2_3 of SILO
*
*
* Al Leibee, Wed Jul 21 09:01:32 PDT 1993
* Ensure that PJ_make_group input strings are
* SCORE-allocated.
*
* Revision 1.2 1993/07/13 16:57:51 leibee
* Updated slide, pdbext, silo, swat modules: made allocate/free usage consistant re SCORE and system memory managers; reduced dependence on SCORE memory manager; removed check for SCORE-allocated array within FREE; added configman files.
*
*
* Al Leibee, Wed Jul 7 08:00:00 PDT 1993
* Made allocation/free usage consistant.
*/
/*=============================
* Global Data for this Module
*=============================*/
/*--------------------------------------------------------------------
* Routine PJ_get_group
*
* Purpose
*
* Read a group description from the given PDB file.
*
* Notes
*
* Modified
*
* Robb Matzke, 5 Feb 1997
* This function returns 0 instead of dumping core if NAME is
* not a group.
*
* Eric Brugger, Mon Dec 7 11:03:09 PST 1998
* Removed call to lite_PD_reset_ptr_list since it was removed.
*
*--------------------------------------------------------------------
*/
INTERNAL int
PJ_get_group(
PDBfile *file, /* PDB file pointer */
char const *name, /* Name of group desc to read */
PJgroup **group) /* Variable to write into */
{
syment *ep;
/*
* Make sure the thing we're looking up is really a group.
*/
ep = lite_PD_inquire_entry (file, (char *) name, TRUE, NULL);
if (!ep || strcmp(PD_entry_type(ep), "Group *")) return 0;
return ((int)PJ_read(file, name, group));
}
/*--------------------------------------------------------------------
* Routine PJ_make_group
*
* Purpose
*
* Return a group description variable constructed from given
* elements.
*
* Notes
*
* Modifications
*
* Al Leibee, Wed Jul 21 09:01:32 PDT 1993
* Ensure that inputted strings are SCORE-allocated.
*
* Al Leibee, Wed Jul 7 08:00:00 PDT 1993
* Character strings known to have been allocated by SCORE.
*
* Jeremy Meredith, Fri Nov 19 10:04:54 PST 1999
* Changed SC_strdup to safe_strdup.
*
* Jeremy Meredith, Tue Nov 30 09:12:15 PST 1999
* I changed safe_strdup back to SC_strdup. Not allocating the
* memory with SCORE's memory management routines caused severe
* problems because the memory block was not tagged correctly.
*
*--------------------------------------------------------------------
*/
INTERNAL PJgroup *
PJ_make_group (
char *name, /* Name of this group */
char *type, /* Type of this group */
char **comp_names, /* Array of component names (num) */
char **pdb_names, /* Array of internal (PDB) names (num) */
int num) /* Number of components provided */
{
PJgroup *group;
char *sc_type, *sc_name;
char **sc_comp_nms;
char **sc_int_nms;
int i;
if (num <= 0 || name == NULL || type == NULL ||
comp_names == NULL || pdb_names == NULL)
return (NULL);
group = SCALLOC(PJgroup);
/*----------------------------------------
* Ensure strings allocated by SCORE
* by making duplicates.
*----------------------------------------*/
sc_comp_nms = SCALLOC_N(char *, num);
sc_int_nms = SCALLOC_N(char *, num);
for (i = 0; i < num; i++) {
sc_comp_nms[i] = SC_strdup(comp_names[i]);
sc_int_nms[i] = SC_strdup(pdb_names[i]);
}
sc_type = SC_strdup(type);
sc_name = SC_strdup(name);
/*----------------------------------------
* Store new pointers in group variable.
*----------------------------------------*/
group->name = sc_name;
group->type = sc_type;
group->ncomponents = num;
group->comp_names = sc_comp_nms;
group->pdb_names = sc_int_nms;
return (group);
}
/*--------------------------------------------------------------------
* Routine PJ_rel_group
*
* Purpose
*
* Release the space associated with the given group.
*
* Notes
*
* Modifications
*
* Al Leibee, Wed Jul 7 08:00:00 PDT 1993
* FREE to SCFREE to be consistant with allocation.
*
* Sean Ahern, Mon Nov 23 17:02:49 PST 1998
* Made the return value meaningful.
*--------------------------------------------------------------------*/
INTERNAL int
PJ_rel_group (PJgroup *group) {
int i;
if (group == NULL || group->ncomponents <= 0)
return (FALSE);
for (i = 0; i < group->ncomponents; i++) {
SCFREE(group->comp_names[i]);
SCFREE(group->pdb_names[i]);
}
SCFREE(group->name);
SCFREE(group->type);
SCFREE(group->comp_names);
SCFREE(group->pdb_names);
SCFREE(group);
return (TRUE);
}
/*--------------------------------------------------------------------
* Routine PJ_print_group
*
* Purpose
*
* Print the given group.
*
* Notes
*
*--------------------------------------------------------------------
*/
INTERNAL int
PJ_print_group (PJgroup *group, FILE *fp) {
int i;
if (group == NULL || group->ncomponents <= 0)
return (FALSE);
if (fp == NULL)
fp = stdout;
fprintf(fp, "Group: %s is of type %s and has %d components.\n",
group->name, group->type, group->ncomponents);
for (i = 0; i < group->ncomponents; i++) {
fprintf(fp, "Component [%d] = %s ==> %s\n", i,
group->comp_names[i], group->pdb_names[i]);
}
return 0;
}
/*--------------------------------------------------------------------
* Routine PJ_put_group
*
* Purpose
*
* Write a group description into the given PDB file.
*
* Return: Success: non-zero
*
* Failute: zero
*
* Notes
*
*
* Modifications
*
* Al Leibee, Wed Jul 7 08:00:00 PDT 1993
* FREE to SCFREE to be consistant with allocation.
*
* Robb Matzke, 7 Mar 1997
* Added the OVERWRITE argument. If non-zero, then we can overwrite
* any existing group with the same name.
*
* Eric Brugger, Mon Dec 7 11:03:09 PST 1998
* Removed call to lite_PD_reset_ptr_list since it was removed.
*
*--------------------------------------------------------------------
*/
#ifdef PDB_WRITE
INTERNAL int
PJ_put_group (
PDBfile *file, /* PDB file pointer */
PJgroup *group, /* Group variable to write */
int overwrite)
{
char **varlist;
char name[MAXNAME];
if (file == NULL || group == NULL)
return (FALSE);
/*----------------------------------------
* Define the group struct, if it hasn't
* been already.
*----------------------------------------*/
if (PD_inquire_type(file, "Group") == NULL) {
if ((lite_PD_defstr(file, "Group",
"char *name",
"char *type",
"char **comp_names",
"char **pdb_names",
"integer ncomponents",
lite_LAST)) == NULL)
printf("PJ_put_group -- Error defining Group structure.\n");
}
/*----------------------------------------
* Build an absolute pathname.
*---------------------------------------*/
PJ_get_fullpath(lite_PD_pwd(file), group->name, name);
/*----------------------------------------
* Make sure this group description hasn't
* already been written.
*----------------------------------------*/
if (!overwrite) {
#ifdef USING_PDB_PROPER
varlist = SC_hasharr_dump(file->symtab, name, 0, 0);
#else
varlist = lite_SC_hash_dump(file->symtab, name);
#endif
if (varlist != NULL && varlist[0] != NULL)
return (FALSE);
/*FREE(varlist); */
SCFREE(varlist);
}
/*----------------------------------------
* Write the group description variable.
*----------------------------------------*/
return ((int)PJ_write(file, name, "Group *", &group));
}
#endif /* PDB_WRITE */
/* END pjgroup.c */
/* File-wide modifications:
* Sean Ahern, Fri Aug 1 13:23:38 PDT 1997
* Reformatted tabs to spaces.
*/
static char *_valstr[10] =
{"value0", "value1", "value2",
"value3", "value4", "value5",
"value6", "value7", "value8",
"value9"};
static char *_mixvalstr[10] =
{"mixed_value0", "mixed_value1",
"mixed_value2", "mixed_value3",
"mixed_value4", "mixed_value5",
"mixed_value6", "mixed_value7",
"mixed_value8", "mixed_value9"};
static char *_ptvalstr[10] =
{"0_data", "1_data", "2_data",
"3_data", "4_data", "5_data",
"6_data", "7_data", "8_data",
"9_data"};
/* Symbolic constants used in calls to db_StringListToStringArray
to indicate behavior. A '!' in front means to not perform the
associated action. For PDB driver, we handle the slash swap
on the 'names' member of multi-block objects only and we
skip first semicolon ONLY for those string arrays that were
added to PDB driver prior to db_StringListToStringArray
coming into existence. This is to ensure diffs on files
before and after this change don't vary due to leading
semicolon. */
static int const skipFirstSemicolon = 1;
/*----------------------------------------------------------------------
* Routine db_pdb_GetVarDatatype
*
* Purpose
*
* Return the datatype of the given variable.
*
* Notes
*
* Modifications
*
* Al Leibee, Wed Aug 18 15:59:26 PDT 1993
* Convert to new PJ_inquire_interface.
*
* Sean Ahern, Wed Apr 12 11:14:38 PDT 2000
* Removed the last two parameters to PJ_inquire_entry because they
* weren't being used.
*
* Mark C. Miller, Thu May 13 19:02:58 PDT 2010
* Moved here from pjobj.c so it could be made static (private).
*--------------------------------------------------------------------*/
PRIVATE int
db_pdb_GetVarDatatype (PDBfile *pdb, char const *varname) {
syment *ep;
int datatype;
ep = PJ_inquire_entry(pdb, varname);
if (!ep)
return -1;
datatype = SW_GetDatatypeID(ep->type);
return datatype;
}
/*-------------------------------------------------------------------------
* Function: db_pdb_InitCallbacks
*
* Purpose: Initialize the callbacks in a DBfile structure.
*
* Programmer: matzke@viper
* Tue Nov 29 13:26:58 PST 1994
*
* Modifications:
*
* Eric Brugger, Thu Feb 16 08:45:00 PST 1995
* I added the DBReadVarSlice callback.
*
* Jim Reus, 23 Apr 97
* I changed this to prototype form.
*
* Jeremy Meredith, Sept 18 1998
* I added multi-material-species
*
* Eric Brugger, Tue Mar 30 10:49:56 PST 1999
* I added the DBPutZonelist2 callback.
*
* Robb Matzke, 2000-01-14
* I organized callbacks by category for easier comparison with other
* drivers.
*
* Brad Whitlock, Thu Jan 20 11:59:11 PDT 2000
* I added the DBGetComponentType callback.
*-------------------------------------------------------------------------*/
PRIVATE void
db_pdb_InitCallbacks ( DBfile *dbfile )
{
/* Properties of the driver */
dbfile->pub.pathok = FALSE; /*driver doesn't handle paths well*/
/* File operations */
dbfile->pub.close = db_pdb_close;
dbfile->pub.module = db_pdb_Filters;
dbfile->pub.flush = db_pdb_flush;
/* Directory operations */
dbfile->pub.cd = db_pdb_SetDir;
dbfile->pub.g_dir = db_pdb_GetDir;
dbfile->pub.newtoc = db_pdb_NewToc;
#ifdef PDB_WRITE
dbfile->pub.mkdir = db_pdb_MkDir;
#endif
/* Variable inquiries */
dbfile->pub.exist = db_pdb_InqVarExists;
dbfile->pub.g_varlen = db_pdb_GetVarLength;
dbfile->pub.g_varbl = db_pdb_GetVarByteLength;
dbfile->pub.g_vartype = db_pdb_GetVarType;
dbfile->pub.g_vardims = db_pdb_GetVarDims;
/* Variable I/O operations */
dbfile->pub.g_var = db_pdb_GetVar;
dbfile->pub.r_var = db_pdb_ReadVar;
dbfile->pub.r_varslice = db_pdb_ReadVarSlice;
dbfile->pub.r_varvals = db_pdb_ReadVarVals;
#ifdef PDB_WRITE
dbfile->pub.write = db_pdb_Write;
dbfile->pub.writeslice = db_pdb_WriteSlice;
#endif
/* Low-level object functions */
dbfile->pub.g_obj = db_pdb_GetObject;
dbfile->pub.inqvartype = db_pdb_InqVarType;
dbfile->pub.i_meshtype = db_pdb_InqMeshtype;
dbfile->pub.i_meshname = db_pdb_InqMeshname;
dbfile->pub.g_comp = db_pdb_GetComponent;
dbfile->pub.g_comptyp = db_pdb_GetComponentType;
dbfile->pub.g_compnames = db_pdb_GetComponentNames;
#ifdef PDB_WRITE
dbfile->pub.c_obj = db_pdb_WriteObject; /*overloaded with w_obj*/
dbfile->pub.w_obj = db_pdb_WriteObject; /*overloaded with c_obj*/
dbfile->pub.w_comp = db_pdb_WriteComponent;
#endif
/* Curve functions */
dbfile->pub.g_cu = db_pdb_GetCurve;
#ifdef PDB_WRITE
dbfile->pub.p_cu = db_pdb_PutCurve;
#endif
/* Defvar functions */
dbfile->pub.g_defv = db_pdb_GetDefvars;
#ifdef PDB_WRITE
dbfile->pub.p_defv = db_pdb_PutDefvars;
#endif
/* Csgmesh functions */
dbfile->pub.g_csgm = db_pdb_GetCsgmesh;
dbfile->pub.g_csgv = db_pdb_GetCsgvar;
dbfile->pub.g_csgzl = db_pdb_GetCSGZonelist;
#ifdef PDB_WRITE
dbfile->pub.p_csgm = db_pdb_PutCsgmesh;
dbfile->pub.p_csgv = db_pdb_PutCsgvar;
dbfile->pub.p_csgzl = db_pdb_PutCSGZonelist;
#endif
/* Quadmesh functions */
dbfile->pub.g_qm = db_pdb_GetQuadmesh;
dbfile->pub.g_qv = db_pdb_GetQuadvar;
#ifdef PDB_WRITE
dbfile->pub.p_qm = db_pdb_PutQuadmesh;
dbfile->pub.p_qv = db_pdb_PutQuadvar;
#endif
/* Unstructured mesh functions */
dbfile->pub.g_um = db_pdb_GetUcdmesh;
dbfile->pub.g_uv = db_pdb_GetUcdvar;
dbfile->pub.g_fl = db_pdb_GetFacelist;
dbfile->pub.g_zl = db_pdb_GetZonelist;
dbfile->pub.g_phzl = db_pdb_GetPHZonelist;
#ifdef PDB_WRITE
dbfile->pub.p_um = db_pdb_PutUcdmesh;
dbfile->pub.p_sm = db_pdb_PutUcdsubmesh;
dbfile->pub.p_uv = db_pdb_PutUcdvar;
dbfile->pub.p_fl = db_pdb_PutFacelist;
dbfile->pub.p_zl = db_pdb_PutZonelist;
dbfile->pub.p_zl2= db_pdb_PutZonelist2;
dbfile->pub.p_phzl= db_pdb_PutPHZonelist;
#endif
/* Material functions */
dbfile->pub.g_ma = db_pdb_GetMaterial;
dbfile->pub.g_ms = db_pdb_GetMatspecies;
#ifdef PDB_WRITE
dbfile->pub.p_ma = db_pdb_PutMaterial;
dbfile->pub.p_ms = db_pdb_PutMatspecies;
#endif
/* Pointmesh functions */
dbfile->pub.g_pm = db_pdb_GetPointmesh;
dbfile->pub.g_pv = db_pdb_GetPointvar;
#ifdef PDB_WRITE
dbfile->pub.p_pm = db_pdb_PutPointmesh;
dbfile->pub.p_pv = db_pdb_PutPointvar;
#endif
/* Multiblock functions */
dbfile->pub.g_mm = db_pdb_GetMultimesh;
dbfile->pub.g_mmadj = db_pdb_GetMultimeshadj;
dbfile->pub.g_mv = db_pdb_GetMultivar;
dbfile->pub.g_mt = db_pdb_GetMultimat;
dbfile->pub.g_mms= db_pdb_GetMultimatspecies;
#ifdef PDB_WRITE
dbfile->pub.p_mm = db_pdb_PutMultimesh;
dbfile->pub.p_mmadj = db_pdb_PutMultimeshadj;
dbfile->pub.p_mv = db_pdb_PutMultivar;
dbfile->pub.p_mt = db_pdb_PutMultimat;
dbfile->pub.p_mms= db_pdb_PutMultimatspecies;
#endif
/* Compound arrays */
dbfile->pub.g_ca = db_pdb_GetCompoundarray;
#ifdef PDB_WRITE
dbfile->pub.p_ca = db_pdb_PutCompoundarray;
#endif
/* MRG trees and Groupel maps */
dbfile->pub.g_mrgt = db_pdb_GetMrgtree;
dbfile->pub.g_grplm = db_pdb_GetGroupelmap;
dbfile->pub.g_mrgv = db_pdb_GetMrgvar;
#ifdef PDB_WRITE
dbfile->pub.p_mrgt = db_pdb_PutMrgtree;
dbfile->pub.p_grplm = db_pdb_PutGroupelmap;
dbfile->pub.p_mrgv = db_pdb_PutMrgvar;
#endif
dbfile->pub.free_z = db_pdb_FreeCompressionResources;
dbfile->pub.sort_obo = db_pdb_SortObjectsByOffset;
}
/*-------------------------------------------------------------------------
* Function: db_pdb_close
*
* Purpose: Closes a PDB file and free the memory associated with
* the file.
*
* Return: Success: NULL, usually assigned to the file
* pointer being closed as in:
* dbfile = db_pdb_close (dbfile) ;
*
* Failure: Never fails.
*
* Programmer: matzke@viper
* Wed Nov 2 13:42:25 PST 1994
*
* Modifications:
* Eric Brugger, Mon Feb 27 15:55:01 PST 1995
* I changed the return value to be an integer instead of a pointer
* to a DBfile.
*
* Sean Ahern, Mon Jul 1 14:05:38 PDT 1996
* Turned off the PJgroup cache when we close files.
*
* Sean Ahern, Tue Oct 20 17:21:18 PDT 1998
* Reformatted whitespace.
*
* Sean Ahern, Mon Nov 23 17:29:17 PST 1998
* Added clearing of the object cache when the file is closed.
*-------------------------------------------------------------------------*/
SILO_CALLBACK int
db_pdb_close(DBfile *_dbfile)
{
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
if (dbfile)
{
/*
* Free the private parts of the file.
*/
lite_PD_close(dbfile->pdb);
dbfile->pdb = NULL;
/* We've closed a file, so we can't cache PJgroups any more */
PJ_NoCache();
/*
* Free the public parts of the file.
*/
silo_db_close(_dbfile);
/* Clear the current object cache. */
PJ_ClearCache();
}
return 0;
}
/*-------------------------------------------------------------------------
* Function: db_pdb_flush
*
* Purpose: Flushes a PDB file to disk.
*
* Return: Success: 0
* Fail: -1
*
* Programmer: Mark C. Miller, Fri Aug 14 11:47:56 PDT 2015
*-------------------------------------------------------------------------*/
SILO_CALLBACK int
db_pdb_flush(DBfile *_dbfile)
{
int retval = -1;
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
if (!dbfile)
return retval;
if (lite_PD_flush(dbfile->pdb) == TRUE)
retval = 0;
return retval;
}
/*-------------------------------------------------------------------------
* Function: db_pdb_Open
*
* Purpose: Opens a PDB file that already exists.
*
* Return: Success: ptr to the file structure
*
* Failure: NULL, db_errno set.
*
* Programmer: matzke@viper
* Wed Nov 2 13:15:16 PST 1994
*
* Modifications:
* Eric Brugger, Fri Jan 27 08:27:46 PST 1995
* I changed the call DBGetToc to db_pdb_GetToc.
*
* Robb Matzke, Tue Mar 7 10:36:13 EST 1995
* I changed the call db_pdb_GetToc to DBNewToc.
*
* Sean Ahern, Sun Oct 1 03:05:08 PDT 1995
* Made "me" static.
*
* Sean Ahern, Sun Oct 1 06:09:25 PDT 1995
* Fixed a parameter type problem.
*
* Sean Ahern, Mon Jan 8 17:37:47 PST 1996
* Added the mode parameter and accompanying logic.
*
* Eric Brugger, Fri Jan 19 10:00:41 PST 1996
* I checked to see if it is a netcdf flavor of pdb file.
* If it is, then it returns NULL.
*
* Sean Ahern, Fri Oct 16 17:46:57 PDT 1998
* Reformatted whitespace.
*
* Mark C. Miller, Wed Feb 25 09:37:48 PST 2009
* Changed error code for failure to open to E_DRVRCANTOPEN
*-------------------------------------------------------------------------*/
INTERNAL DBfile *
db_pdb_Open(char const *name, int mode, int opts_set_id)
{
PDBfile *pdb;
DBfile_pdb *dbfile;
static char *me = "db_pdb_Open";
if (!SW_file_exists(name))
{
db_perror(name, E_NOFILE, me);
return NULL;
} else if (!SW_file_readable(name))
{
db_perror("not readable", E_NOFILE, me);
return NULL;
}
if (mode == DB_READ)
{
if (NULL == (pdb = lite_PD_open((char*)name, "r")))
{
db_perror(NULL, E_DRVRCANTOPEN, me);
return NULL;
}
} else if (mode == DB_APPEND)
{
if (NULL == (pdb = lite_PD_open((char*)name, "a")))
{
db_perror(NULL, E_DRVRCANTOPEN, me);
return NULL;
}
} else
{
db_perror("mode", E_INTERNAL, me);
return (NULL);
}
/*
* If it is the netcdf flavor of pdb, then return NULL.
*/
#ifdef USING_PDB_PROPER
PD_set_track_pointers(pdb, FALSE);
if (NULL != SC_hasharr_lookup(pdb->symtab, "_whatami"))
#else
if (NULL != lite_SC_lookup("_whatami", pdb->symtab))
#endif
{
lite_PD_close(pdb);
return (NULL);
}
dbfile = ALLOC(DBfile_pdb);
memset(dbfile, 0, sizeof(DBfile_pdb));
dbfile->pub.name = STRDUP(name);
dbfile->pub.type = DB_PDB;
#ifdef USING_PDB_PROPER
dbfile->pub.type = DB_PDBP;
#endif
dbfile->pdb = pdb;
db_pdb_InitCallbacks((DBfile *) dbfile);
return (DBfile *) dbfile;
}
/*-------------------------------------------------------------------------
* Function: db_pdb_Create
*
* Purpose: Creates a PDB file and begins the process of writing
* mesh and mesh-related data into that file.
*
* NOTE: The `mode' parameter is unused.
* But it's caught at the DBCreate call.
*
* Return: Success: pointer to a new file
*
* Failure: NULL, db_errno set
*
* Programmer: matzke@viper
* Thu Nov 3 14:46:38 PST 1994
*
* Modifications:
* Eric Brugger, Fri Jan 27 08:27:46 PST 1995
* I changed the call DBGetToc to db_pdb_GetToc.
*
* Robb Matzke, Tue Mar 7 10:37:07 EST 1995
* I changed the call db_pdb_GetToc to DBNewToc.
*
* Sean Ahern, Sun Oct 1 03:05:32 PDT 1995
* Made "me" static.
*
* Sean Ahern, Wed Oct 4 17:13:16 PDT 1995
* Fixed a parameter type problem.
*
* Sean Ahern, Fri Oct 16 17:47:22 PDT 1998
* Reformatted whitespace.
*
* Hank Childs, Thu Jan 6 13:41:38 PST 2000
* Put in cast to long of strlen to remove compiler warning.
*
* Jeremy Meredith, Wed Oct 25 16:16:59 PDT 2000
* Added DB_INTEL so we had a little-endian target.
*
* Thomas R. Treadway, Wed Feb 28 11:36:34 PST 2007
* Checked for compression option.
*-------------------------------------------------------------------------*/
/* ARGSUSED */
INTERNAL DBfile *
db_pdb_Create (char const *name, int mode, int target, int opts_set_id, char const *finfo)
{
DBfile_pdb *dbfile;
static char *me = "db_pdb_create";
if (SILO_Globals.enableChecksums)
{
db_perror(name, E_NOTIMP, "no checksums in PDB driver");
return NULL;
}
if (SILO_Globals.compressionParams)
{
db_perror(name, E_NOTIMP, "no compression in PDB driver");
return NULL;
}
/*
* The target type.
*/
switch (target)
{
case DB_LOCAL:
break;
case DB_SUN3:
lite_PD_target(&lite_IEEEA_STD, &lite_M68000_ALIGNMENT);
break;
case DB_SUN4:
lite_PD_target(&lite_IEEEA_STD, &lite_SPARC_ALIGNMENT);
break;
case DB_SGI:
lite_PD_target(&lite_IEEEA_STD, &lite_MIPS_ALIGNMENT);
break;
case DB_RS6000:
lite_PD_target(&lite_IEEEA_STD, &lite_RS6000_ALIGNMENT);
break;
case DB_CRAY:
lite_PD_target(&lite_CRAY_STD, &lite_UNICOS_ALIGNMENT);
break;
case DB_INTEL:
lite_PD_target(&lite_IEEEA_STD, &lite_INTELA_ALIGNMENT);
break;
default:
db_perror("target", E_BADARGS, me);
return NULL;
}
if (NULL == (dbfile = ALLOC(DBfile_pdb)))
{
db_perror(name, E_NOMEM, me);
return NULL;
}
dbfile->pub.name = STRDUP(name);
dbfile->pub.type = DB_PDB;
#ifdef USING_PDB_PROPER
dbfile->pub.type = DB_PDBP;
#endif
db_pdb_InitCallbacks((DBfile *) dbfile);
if (NULL == (dbfile->pdb = lite_PD_open((char*)name, "w")))
{
FREE(dbfile->pub.name);
FREE(dbfile);
db_perror(name, E_NOFILE, me);
return NULL;
}
#ifdef USING_PDB_PROPER
PD_set_track_pointers(dbfile->pdb, FALSE);
#endif
DBNewToc((DBfile *) dbfile);
if (finfo)
{
long count = (long) strlen(finfo) + 1;
PJ_write_len(dbfile->pdb, "_fileinfo", "char", finfo, 1, &count);
}
#ifdef USING_PDB_PROPER
{
long count = 1;
int version_val = PDB_SYSTEM_VERSION;
PJ_write_len(dbfile->pdb, "_pdblibinfo", "integer", &version_val, 1, &count);
}
#endif
return (DBfile *) dbfile;
}
/*-------------------------------------------------------------------------
* Function: db_pdb_ForceSingle
*
* Purpose: If status is non-zero, then force all double-precision
* floating-point values to single precision.
*
* Return: Success: 0
*
* Failure: never fails
*
* Programmer: matzke@viper
* Tue Jan 10 10:50:49 PST 1995
*
* Modifications:
*-------------------------------------------------------------------------*/
INTERNAL int
db_pdb_ForceSingle (int status)
{
PJ_ForceSingle(status);
return 0;
}
/*--------------------------------------------------------------------
* Routine PJ_ls
*
* Purpose
*
* Return a list of all variables of the specified type in the
* specified directory.
*
* Notes
*
* Providing a NULL string for 'type' will cause the type check
* to be avoided. Providing a NULL string for the directory path
* will cause only the root directory to be searched.
*
* Modifications
*
* Robb Matzke, Fri Feb 24 10:37:43 EST 1995
* This function just calls PD_ls(). But we must make sure that
* the return value is allocated with the C memory management.
*
* Robb Matzke, Fri Dec 2 13:20:38 PST 1994
* Removed references to SCORE memory management. The varlist
* vector and the strings in that vector are allocated with
* SCORE by lite_SC_hash_dump()--actually, the strings pointed to
* by this vector should not be freed because they are in the
* hash table.
*
* Al Leibee, Mon Aug 9 10:30:54 PDT 1993
* Convert to new PD_inquire_entry interface.
*
* Al Leibee, Thu Jul 8 08:05:09 PDT 1993
* FREE to SCFREE to be consistant with allocation.
*--------------------------------------------------------------------*/
INTERNAL char **
PJ_ls (PDBfile *file, /* PDB file pointer */
char *path, /* Path of dir to search (if NULL use '/') */
char *type, /* Variable type to search for (else NULL) */
int *num) /* Returned number of matches */
{
char **score_out, **malloc_out;
score_out = lite_PD_ls(file, path, type, num);
if (*num == 0)
{
lite_SC_free(score_out);
return 0;
}
malloc_out = ALLOC_N(char *, *num + 1);
memcpy(malloc_out, score_out, *num * sizeof(char *));
malloc_out[*num] = NULL;
lite_SC_free(score_out);
return malloc_out;
}
/*--------------------------------------------------------------------
* Routine PJ_get_fullpath
*
* Purpose
*
* Generate a full pathname from the current working directory
* and the given pathname (abs/rel)
*
* Notes
*
* This routine is for internal use only. Not for user-level.
*
* Robb Matzke, Fri Feb 24 10:40:39 EST 1995
* Removed the call to PJ_file_has_dirs() and we assume that all
* files support directories.
*
* Sean Ahern, Fri Oct 16 17:47:44 PDT 1998
* Reformatted whitespace.
*--------------------------------------------------------------------*/
INTERNAL int
PJ_get_fullpath(
char *cwd, /* Current working directory */
char const *path, /* Pathname (abs or rel) to traverse */
char *name) /* Returned adjusted name */
{
char *abspath;
if (cwd == NULL || path == NULL || name == NULL)
return (FALSE);
abspath = db_absoluteOf_path(cwd, path);
strcpy(name, abspath);
free(abspath);
return (TRUE);
}
/*-------------------------------------------------------------------------
* Function: db_pdb_getobjinfo
*
* Purpose:
*
* Return: Success:
*
* Failure:
*
* Programmer:
*
* Modifications:
* Al Leibee, Fri Sep 3 10:54:47 PDT 1993
* Error check on PJ_read.
*
* Eric Brugger, Thu Feb 9 12:54:37 PST 1995
* I modified the routine to read elements of the group structure
* as "abc->type" instead of "abc.type".
*
* Sean Ahern, Sun Oct 1 03:05:56 PDT 1995
* Made "me" static.
*
* Eric Brugger, Fri Dec 4 12:45:22 PST 1998
* Added code to free ctype to eliminate a memory leak.
*-------------------------------------------------------------------------*/
PRIVATE int
db_pdb_getobjinfo (PDBfile *pdb,
char const *name, /* Name of object to inquire about */
char *type, /* Returned object type of 'name' */
int *num) /* Returned number of elements */
{
char newname[MAXNAME];
char *ctype;
static char *me = "db_pdb_getobjinfo";
if (!pdb)
return db_perror(NULL, E_NOFILE, me);
if (!name || !*name)
return db_perror("name", E_BADARGS, me);
*num = *type = 0;
sprintf(newname, "%s->type", name);
if (PJ_read(pdb, newname, &ctype) == FALSE) {
return db_perror("PJ_read", E_CALLFAIL, me);
}
strcpy(type, ctype);
SCFREE(ctype);
sprintf(newname, "%s->ncomponents", name);
PJ_read(pdb, newname, num);
return 0;
}
/*-------------------------------------------------------------------------
* Function: db_pdb_getvarinfo
*
* Purpose:
*
* Return: Success:
*
* Failure:
*
* Programmer:
*
* Modifications:
*
* Al Leibee, Wed Aug 18 15:59:26 PDT 1993
* Convert to new PJ_inquire_entry interface.
*
* Al Leibee, Mon Aug 30 15:13:50 PDT 1993
* Use PD_inquire_host_type to get true data type size.
*
* Sean Ahern, Sun Oct 1 03:06:20 PDT 1995
* Made "me" static.
*
* Sean Ahern, Wed Apr 12 11:14:38 PDT 2000
* Removed the last two parameters to PJ_inquire_entry because they
* weren't being used.
*-------------------------------------------------------------------------*/
PRIVATE int
db_pdb_getvarinfo (PDBfile *pdb,
char const *name, /*Name of var to inquire about */
char *type, /*Returned datatype of 'name' */
int *num, /*Returned number of elements */
int *size, /*Returned element size */
int verbose) /*Sentinel: 1=print error msgs*/
{
int is_ptr;
char lastchar;
char *s;
defstr *dp;
syment *ep;
static char *me = "db_pdb_getvarinfo";
*num = *size = 0;
if (type)
type[0] = '\0';
/*
* Get symbol table entry for requested variable.
*/
ep = PJ_inquire_entry(pdb, name);
if (ep == NULL)
return db_perror("PJ_inquire_entry", E_CALLFAIL, me);
/* Assign values */
if (type)
strcpy(type, ep->type);
lastchar = STR_LASTCHAR(ep->type);
is_ptr = (lastchar == '*');
if (is_ptr) {
s = ALLOC_N(char, strlen(ep->type) + 1);
strcpy(s, ep->type);
s[strcspn(s, " *")] = '\0';
/* Get data size of primitive (non-pointer) unit */
dp = PD_inquire_host_type(pdb, s);
*size = dp->size;
*num = -1; /* lite_SC_arrlen(values) / dp->size; */
if (verbose)
printf("Cannot query length of pointered variable.\n");
FREE(s);
}
else {
dp = PD_inquire_host_type(pdb, ep->type);
if (dp == NULL) {
if (verbose)
printf("Don't know about data of type: %s\n", ep->type);
return db_perror("PD_inquire_host_type", E_CALLFAIL, me);
}
/* Assign values */
*size = dp->size;
*num = ep->number;
}
return 0;
}
/*-------------------------------------------------------------------------
* Function: db_pdb_GetDir
*
* Purpose: Return the name of the current directory by copying the
* name to the output buffer supplied.
*
* Return: Success: 0
*
* Failure: -1
*
* Programmer: matzke@viper
* Tue Nov 8 08:52:38 PST 1994
*
* Modifications:
* Sean Ahern, Sun Oct 1 03:06:52 PDT 1995
* Made "me" static.
*-------------------------------------------------------------------------*/
SILO_CALLBACK int
db_pdb_GetDir (DBfile *_dbfile, char *result)
{
char *p;
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
static char *me = "db_pdb_GetDir";
if (!result)
return db_perror("result", E_BADARGS, me);
p = lite_PD_pwd(dbfile->pdb);
if (!p || !*p) {
db_perror("PD_pwd", E_CALLFAIL, me);
result[0] = '\0';
return -1;
}
strcpy(result, p);
return 0;
}
/*-------------------------------------------------------------------------
* Function: db_pdb_NewToc
*
* Purpose: Read the table of contents from the current directory
* and make it the current table of contents for the file
* pointer, freeing any previously existing table of contents.
*
* Notes
*
* It is assumed that scalar values within the TOC have been
* initialized to zero.
*
* Return: Success: 0
*
* Failure: -1, db_errno set
*
* Programmer: matzke@viper
* Thu Nov 3 14:34:31 PST 1994
*
* Modifications
* Al Leibee, Wed Jul 7 08:00:00 PDT 1993
* Changed FREE to SCFREE for consistant allocate/free usage.
*
* Al Leibee, Wed Aug 18 15:59:26 PDT 1993
* Convert to new PJ_inquire_entry interface.
*
* Al Leibee, Mon Aug 1 16:16:00 PDT 1994
* Added material species.
*
* Robb Matzke, Tue Oct 25 09:46:48 PDT 1994
* added compound arrays.
*
* Robb Matzke, Fri Dec 2 14:05:57 PST 1994
* Removed all references to SCORE memory management. Local variable
* `name' is now allocated on the stack instead of by memory management.
*
* Eric Brugger, Fri Jan 27 08:27:46 PST 1995
* I made it into an internal routine.
*
* Eric Brugger, Thu Feb 9 12:54:37 PST 1995
* I modified the routine to read elements of the group structure
* as "abc->type" instead of "abc.type".
*
* Eric Brugger, Thu Feb 9 15:07:29 PST 1995
* I modified the routine to handle the obj in the table of contents.
*
* Robb Matzke, Tue Feb 21 16:20:58 EST 1995
* Removed references to the `id' fields of the DBtoc.
*
* Robb Matzke, Tue Mar 7 10:38:59 EST 1995
* Changed the name from db_pdb_GetToc to db_pdb_NewToc.
*
* Robb Matzke, Tue Mar 7 11:21:21 EST 1995
* Changed this to a CALLBACK.
*
* Katherine Price, Thu May 25 14:44:42 PDT 1995
* Added multi-block materials.
*
* Eric Brugger, Thu Jun 29 09:44:47 PDT 1995
* I modified the routine so that directories would show up in the
* table of contents.
*
* Sean Ahern, Sun Oct 1 03:07:17 PDT 1995
* Made "me" static.
*
* Eric Brugger, Mon Oct 23 08:00:16 PDT 1995
* I corrected a bug where the last character of a directory name
* was always eliminated. This was done to get rid to the terminating
* '/' character in a directory name. Well it turns out that not
* all silo files have a '/' at the end of a directory name.
*
* Jeremy Meredith, Sept 18 1998
* Added multi-block species.
*
* Jeremy Meredith, Nov 17 1998
* Added initialization of imultimatspecies.
*
* Eric Brugger, Fri Dec 4 12:45:22 PST 1998
* Added code to free ctype to eliminate a memory leak.
*
* Hank Childs, Thu Jan 6 13:33:21 PST 2000
* Removed print statement that appears to be a debugging relic.
*
* Robb Matzke, Fri May 19 13:18:36 EDT 2000
* Avoid malloc(0)/calloc(0) since the behavior is undefined by Posix.
*-------------------------------------------------------------------------*/
SILO_CALLBACK int
db_pdb_NewToc (DBfile *_dbfile)
{
#define PJDIR -10
#define PJVAR -11
int i, lstr, num;
int *types=NULL;
int ivar, iqmesh, iqvar, iumesh, iuvar, icurve, idir, iarray,
imat, imatspecies, imultimesh, imultivar, imultimat, imultimatspecies,
ipmesh, iptvar, iobj, icsgmesh, icsgvar, idefvars, imultimeshadj,
imrgtree, igroupelmap, imrgvar;
DBtoc *toc;
char *ctype;
char **list; /* Names of everything in current directory */
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
PDBfile *file; /* PDB file pointer */
char name[128];
static char *me = "db_pdb_NewToc";
db_FreeToc(_dbfile);
dbfile->pub.toc = toc = db_AllocToc();
file = dbfile->pdb;
/*------------------------------------------------------------
* Get count of each entity (var, dir, curve, etc.)
* Start by getting list of everything in current dir,
* then count occurences of each type. Build an array of types
* which correspond to each item in list.
* (list is allocated by malloc(). The strings it points
* to should never be free since they are the strings stored in
* the SCORE hash table used by PDB.
*------------------------------------------------------------*/
list = PJ_ls(file, ".", NULL, &num);
if (num) types = ALLOC_N(int, num);
for (i = 0; i < num; i++) {
syment *ep;
ep = lite_PD_inquire_entry(file, list[i], TRUE, NULL);
if (ep == NULL) {
types[i] = 999999;
continue;
}
/*----------------------------------------
* Directory
*----------------------------------------*/
if (STR_BEGINSWITH(ep->type, "Directory")) {
toc->ndir++;
types[i] = PJDIR;
/*----------------------------------------
* Group (object)
*----------------------------------------*/
}
else if (STR_BEGINSWITH(ep->type, "GroupDataShadow")) {
toc->nobj++;
continue;
}
else if (STR_BEGINSWITH(ep->type, "Group")) {
/*
* Read the type field of each object and increment
* the appropriate count.
*/
sprintf(name, "%s.type", list[i]);
if (!PJ_read(file, name, &ctype)) {
sprintf(name, "%s->type", list[i]);
if (!PJ_read(file, name, &ctype)) {
FREE(types);
FREE(list);
return db_perror("PJ_read", E_CALLFAIL, me);
}
}
types[i] = DBGetObjtypeTag(ctype);
SCFREE(ctype);
switch (types[i]) {
case DB_MULTIMESH:
toc->nmultimesh++;
break;
case DB_MULTIMESHADJ:
toc->nmultimeshadj++;
break;
case DB_MULTIVAR:
toc->nmultivar++;
break;
case DB_MULTIMAT:
toc->nmultimat++;
break;
case DB_MULTIMATSPECIES:
toc->nmultimatspecies++;
break;
case DB_CSGMESH:
toc->ncsgmesh++;
break;
case DB_CSGVAR:
toc->ncsgvar++;
break;
case DB_DEFVARS:
toc->ndefvars++;
break;
case DB_QUADMESH:
case DB_QUAD_RECT:
case DB_QUAD_CURV:
toc->nqmesh++;
break;
case DB_QUADVAR:
toc->nqvar++;
break;
case DB_UCDMESH:
toc->nucdmesh++;
break;
case DB_UCDVAR:
toc->nucdvar++;
break;
case DB_POINTMESH:
toc->nptmesh++;
break;
case DB_POINTVAR:
toc->nptvar++;
break;
case DB_CURVE:
toc->ncurve++;
break;
case DB_MATERIAL:
toc->nmat++;
break;
case DB_MATSPECIES:
toc->nmatspecies++;
break;
case DB_ARRAY:
toc->narray++;
break;
case DB_MRGTREE:
toc->nmrgtree++;
break;
case DB_GROUPELMAP:
toc->ngroupelmap++;
break;
case DB_MRGVAR:
toc->nmrgvar++;
break;
default:
toc->nobj++;
break;
}
/*----------------------------------------
* Other (variable?)
*----------------------------------------*/
}
else {
types[i] = PJVAR;
toc->nvar++;
}
}
/*----------------------------------------------------------------------
* Now all the counts have been made; allocate space.
*---------------------------------------------------------------------*/
if (toc->nvar > 0) {
toc->var_names = ALLOC_N(char *, toc->nvar);
}
if (toc->nobj > 0) {
toc->obj_names = ALLOC_N(char *, toc->nobj);
}
if (toc->ndir > 0) {
toc->dir_names = ALLOC_N(char *, toc->ndir);
}
if (toc->ncurve > 0) {
toc->curve_names = ALLOC_N(char *, toc->ncurve);
}
if (toc->ndefvars > 0) {
toc->defvars_names = ALLOC_N(char *, toc->ndefvars);
}
if (toc->nmultimesh > 0) {
toc->multimesh_names = ALLOC_N(char *, toc->nmultimesh);
}
if (toc->nmultimeshadj > 0) {
toc->multimeshadj_names = ALLOC_N(char *, toc->nmultimeshadj);
}
if (toc->nmultivar > 0) {
toc->multivar_names = ALLOC_N(char *, toc->nmultivar);
}
if (toc->nmultimat > 0) {
toc->multimat_names = ALLOC_N(char *, toc->nmultimat);
}
if (toc->nmultimatspecies > 0) {
toc->multimatspecies_names = ALLOC_N(char *, toc->nmultimatspecies);
}
if (toc->ncsgmesh > 0) {
toc->csgmesh_names = ALLOC_N(char *, toc->ncsgmesh);
}
if (toc->ncsgvar > 0) {
toc->csgvar_names = ALLOC_N(char *, toc->ncsgvar);
}
if (toc->nqmesh > 0) {
toc->qmesh_names = ALLOC_N(char *, toc->nqmesh);
}
if (toc->nqvar > 0) {
toc->qvar_names = ALLOC_N(char *, toc->nqvar);
}
if (toc->nucdmesh > 0) {
toc->ucdmesh_names = ALLOC_N(char *, toc->nucdmesh);
}
if (toc->nucdvar > 0) {
toc->ucdvar_names = ALLOC_N(char *, toc->nucdvar);
}
if (toc->nptmesh > 0) {
toc->ptmesh_names = ALLOC_N(char *, toc->nptmesh);
}
if (toc->nptvar > 0) {
toc->ptvar_names = ALLOC_N(char *, toc->nptvar);
}
if (toc->nmat > 0) {
toc->mat_names = ALLOC_N(char *, toc->nmat);
}
if (toc->nmatspecies > 0) {
toc->matspecies_names = ALLOC_N(char *, toc->nmatspecies);
}
if (toc->narray > 0) {
toc->array_names = ALLOC_N(char *, toc->narray);
}
if (toc->nmrgtree > 0) {
toc->mrgtree_names = ALLOC_N(char *, toc->nmrgtree);
}
if (toc->ngroupelmap > 0) {
toc->groupelmap_names = ALLOC_N(char *, toc->ngroupelmap);
}
if (toc->nmrgvar > 0) {
toc->mrgvar_names = ALLOC_N(char *, toc->nmrgvar);
}
/*----------------------------------------------------------------------
* Now loop over all the items in the directory and store the
* names and ID's
*---------------------------------------------------------------------*/
icurve = ivar = iqmesh = iqvar = iumesh = iuvar = idir = iarray = 0;
imultimesh = imultivar = imultimat = imat = imatspecies = ipmesh = 0;
iptvar = iobj = imultimatspecies = icsgmesh = icsgvar = idefvars = 0;
imultimeshadj = imrgtree = igroupelmap = imrgvar = 0 ;
for (i = 0; i < num; i++) {
switch (types[i]) {
case 999999:
/*The call to PD_inquire_entry() failed above. */
break;
case PJDIR:
/*
* After copying the directory name, eliminate
* the terminating '/' if one is present.
*/
toc->dir_names[idir] = STRDUP(list[i]);
lstr = strlen(list[i]);
if (toc->dir_names[idir][lstr-1] == '/')
toc->dir_names[idir][lstr-1] = '\0';
idir++;
break;
case PJVAR:
toc->var_names[ivar] = STRDUP(list[i]);
ivar++;
break;
case DB_MULTIMESH:
toc->multimesh_names[imultimesh] = STRDUP(list[i]);
imultimesh++;
break;
case DB_MULTIMESHADJ:
toc->multimeshadj_names[imultimeshadj] = STRDUP(list[i]);
imultimeshadj++;
break;
case DB_MULTIVAR:
toc->multivar_names[imultivar] = STRDUP(list[i]);
imultivar++;
break;
case DB_MULTIMAT:
toc->multimat_names[imultimat] = STRDUP(list[i]);
imultimat++;
break;
case DB_MULTIMATSPECIES:
toc->multimatspecies_names[imultimatspecies] = STRDUP(list[i]);
imultimatspecies++;
break;
case DB_CSGMESH:
toc->csgmesh_names[icsgmesh] = STRDUP(list[i]);
icsgmesh++;
break;
case DB_CSGVAR:
toc->csgvar_names[icsgvar] = STRDUP(list[i]);
icsgvar++;
break;
case DB_DEFVARS:
toc->defvars_names[idefvars] = STRDUP(list[i]);
idefvars++;
break;
case DB_QUAD_RECT:
case DB_QUAD_CURV:
case DB_QUADMESH:
toc->qmesh_names[iqmesh] = STRDUP(list[i]);
iqmesh++;
break;
case DB_QUADVAR:
toc->qvar_names[iqvar] = STRDUP(list[i]);
iqvar++;
break;
case DB_UCDMESH:
toc->ucdmesh_names[iumesh] = STRDUP(list[i]);
iumesh++;
break;
case DB_UCDVAR:
toc->ucdvar_names[iuvar] = STRDUP(list[i]);
iuvar++;
break;
case DB_POINTMESH:
toc->ptmesh_names[ipmesh] = STRDUP(list[i]);
ipmesh++;
break;
case DB_POINTVAR:
toc->ptvar_names[iptvar] = STRDUP(list[i]);
iptvar++;
break;
case DB_CURVE:
toc->curve_names[icurve] = STRDUP(list[i]);
icurve++;
break;
case DB_MATERIAL:
toc->mat_names[imat] = STRDUP(list[i]);
imat++;
break;
case DB_MATSPECIES:
toc->matspecies_names[imatspecies] = STRDUP(list[i]);
imatspecies++;
break;
case DB_ARRAY:
toc->array_names[iarray] = STRDUP(list[i]);
iarray++;
break;
case DB_MRGTREE:
toc->mrgtree_names[imrgtree] = STRDUP(list[i]);
imrgtree++;
break;
case DB_GROUPELMAP:
toc->groupelmap_names[igroupelmap] = STRDUP(list[i]);
igroupelmap++;
break;
case DB_MRGVAR:
toc->mrgvar_names[imrgvar] = STRDUP(list[i]);
imrgvar++;
break;
default:
toc->obj_names[iobj] = STRDUP(list[i]);
iobj++;
break;
}
}
FREE(list);
FREE(types);
return 0;
}
/*-------------------------------------------------------------------------
* Function: db_pdb_InqVarType
*
* Purpose: Return the DBObjectType for a given object name
*
* Return: Success: the ObjectType for the given object
*
* Failure: DB_INVALID_OBJECT
*
* Programmer: Sean Ahern,
* Wed Oct 28 14:46:53 PST 1998
*
* Modifications:
* Eric Brugger, Fri Dec 4 12:45:22 PST 1998
* Added code to free char_type to eliminate a memory leak.
*
* Sean Ahern, Wed Dec 9 16:21:52 PST 1998
* Added some checks of the return value of DBGetObjtypeTag to make sure
* that we're returning a DBObjectType.
*
* Sean Ahern, Thu Apr 29 16:24:16 PDT 1999
* Added two checks, one is if the variable exists at all. The other is to
* add some logic to help PDB understand directories.
*
* Lisa J. Roberts, Tue Nov 23 09:49:42 PST 1999
* Removed type, which was unused.
*
* Hank Childs, Thu Jan 6 13:46:02 PST 2000
* Put in cast to remove compiler warning.
*-------------------------------------------------------------------------*/
SILO_CALLBACK DBObjectType
db_pdb_InqVarType(DBfile *_dbfile, char const *varname)
{
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
PDBfile *file = dbfile->pdb;
char *char_type = NULL;
char name[256];
syment *entry;
int typetag;
/* First, check to see if it exists */
entry = lite_PD_inquire_entry(file, (char *)varname, TRUE, NULL);
if (entry == NULL)
{
/* This could be a directory. Add a "/" to the end and try again. */
char *newname = (char*)malloc(strlen(varname)+2);
sprintf(newname,"%s/",varname);
entry = lite_PD_inquire_entry(file, newname, TRUE, NULL);
free(newname);
/* If it's NULL now, we really have an invalid object. Otherwise,
* just drop out of the if, and continue. */
if (entry == NULL)
return(DB_INVALID_OBJECT);
}
/* Then, check to see if it's a directory. */
if (STR_BEGINSWITH(entry->type, "Directory"))
return(DB_DIR);
else if (STR_BEGINSWITH(entry->type, "Group"))
{
/* It's not a directory. Ask PDB what the type is. */
sprintf(name, "%s.type", varname);
if (!PJ_read(file, name, &char_type))
{
sprintf(name, "%s->type", varname);
if (!PJ_read(file, name, &char_type))
return(DB_INVALID_OBJECT);
}
typetag = DBGetObjtypeTag(char_type);
SCFREE(char_type);
if ((typetag == DB_QUAD_RECT) || (typetag == DB_QUAD_CURV))
typetag = DB_QUADMESH;
return( (DBObjectType) typetag);
} else
{
return(DB_VARIABLE);
}
/* For stupid compilers */
/* NOTREACHED */
return(DB_INVALID_OBJECT);
}
/*-------------------------------------------------------------------------
* Function: db_pdb_GetObject
*
* Purpose: Reads a group from a PDB file.
*
* Return: Success: Ptr to the new group, all memory allocated
* by malloc().
*
* Failure: NULL
*
* Programmer: Robb Matzke
* robb@callisto.nuance.mdn.com
* Jan 24, 1997
*
* Modifications:
*
* Lisa J. Roberts, Tue Nov 23 09:39:49 PST 1999
* Changed strdup to safe_strdup.
*
* Mark C. Miller, Wed Jan 21 13:52:10 PST 2009
* Removed #if 0 conditional compilation of PJ_rel_group call to fix
* a leak.
*-------------------------------------------------------------------------*/
SILO_CALLBACK DBobject *
db_pdb_GetObject (DBfile *_file, char const *name)
{
PJgroup *group=NULL;
PDBfile *file = ((DBfile_pdb *)_file)->pdb;
DBobject *obj=NULL;
int i;
if (!PJ_get_group (file, name, &group)) return NULL;
/*
* We build our own DBobject here instead of calling DBMakeObject
* because we have a character string type name instead of an
* integer type constant.
*/
obj = (DBobject *)calloc (1, sizeof (DBobject));
obj->name = _db_safe_strdup (group->name);
obj->type = _db_safe_strdup (group->type);
obj->ncomponents = obj->maxcomponents = group->ncomponents;
obj->comp_names = (char **)malloc (obj->maxcomponents * sizeof(char*));
obj->pdb_names = (char **)malloc (obj->maxcomponents * sizeof(char*));
for (i=0; i<group->ncomponents; i++) {
obj->comp_names[i] = _db_safe_strdup (group->comp_names[i]);
obj->pdb_names[i] = _db_safe_strdup (group->pdb_names[i]);
}
PJ_rel_group (group);
return obj;
}
/*----------------------------------------------------------------------
* Routine db_pdb_GetMaterial
*
* Purpose
*
* Read a material-data object from a SILO file and return the
* SILO structure for this type.
*
* Modified
*
* Robb Matzke, Mon Nov 14 14:30:12 EST 1994
* Device independence rewrite.
*
* Sean Ahern, Sun Oct 1 03:07:59 PDT 1995
* Made "me" static.
*
* Robb Matzke, 26 Aug 1997
* The datatype is set from DB_DOUBLE to DB_FLOAT only if the
* force-single flag is set.
*
* Sean Ahern, Wed Jun 14 10:53:56 PDT 2000
* Added a check to make sure the object we're reading is the right type.
*
* Sean Ahern, Thu Mar 1 12:28:07 PST 2001
* Added support for the dataReadMask stuff.
*
* Sean Ahern, Tue Feb 5 13:35:49 PST 2002
* Added support for material names.
*
* Mark C. Miller, Wed Feb 2 07:59:53 PST 2005
* Moved DBAlloc call to after PJ_GetObject. Added automatic
* var for PJ_GetObject to read into. Added check for return
* value of PJ_GetObject.
*
* Mark C. Miller, Tue Nov 10 09:14:01 PST 2009
* Added logic to control behavior of slash character swapping for
* windows/linux and skipping of first semicolon in calls to
* db_StringListToStringArray.
*--------------------------------------------------------------------*/
SILO_CALLBACK DBmaterial *
db_pdb_GetMaterial(DBfile *_dbfile, /*DB file pointer */
char const *name) /*Name of material object to return*/
{
DBmaterial *mm = NULL;
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
static char *me = "db_pdb_GetMaterial";
PJcomplist tmp_obj;
char *tmpnames = NULL;
char *tmpcolors = NULL;
DBmaterial tmpmm;
PJcomplist *_tcl;
/* Comp. Name Comp. Address Data Type */
memset(&tmpmm, 0, sizeof(DBmaterial));
INIT_OBJ(&tmp_obj);
DEFINE_OBJ("ndims", &tmpmm.ndims, DB_INT);
DEFINE_OBJ("dims", tmpmm.dims, DB_INT);
DEFINE_OBJ("major_order", &tmpmm.major_order, DB_INT);
DEFINE_OBJ("origin", &tmpmm.origin, DB_INT);
DEFALL_OBJ("meshid", &tmpmm.meshname, DB_CHAR);
DEFINE_OBJ("allowmat0", &tmpmm.allowmat0, DB_INT);
DEFINE_OBJ("guihide", &tmpmm.guihide, DB_INT);
DEFINE_OBJ("nmat", &tmpmm.nmat, DB_INT);
DEFINE_OBJ("mixlen", &tmpmm.mixlen, DB_INT);
DEFINE_OBJ("datatype", &tmpmm.datatype, DB_INT);
if (DBGetDataReadMask2File(_dbfile) & DBMatMatnos)
DEFALL_OBJ("matnos", &tmpmm.matnos, DB_INT);
if (DBGetDataReadMask2File(_dbfile) & DBMatMatnames)
DEFALL_OBJ("matnames", &tmpnames, DB_CHAR);
if (DBGetDataReadMask2File(_dbfile) & DBMatMatcolors)
DEFALL_OBJ("matcolors", &tmpcolors, DB_CHAR);
if (DBGetDataReadMask2File(_dbfile) & DBMatMatlist)
DEFALL_OBJ("matlist", &tmpmm.matlist, DB_INT);
if (DBGetDataReadMask2File(_dbfile) & DBMatMixList)
{
DEFALL_OBJ("mix_mat", &tmpmm.mix_mat, DB_INT);
DEFALL_OBJ("mix_next", &tmpmm.mix_next, DB_INT);
DEFALL_OBJ("mix_zone", &tmpmm.mix_zone, DB_INT);
DEFALL_OBJ("mix_vf", &tmpmm.mix_vf, DB_FLOAT);
}
if (PJ_GetObject(dbfile->pdb, name, &tmp_obj, DB_MATERIAL) < 0)
return NULL;
if (NULL == (mm = DBAllocMaterial()))
{
db_perror("DBAllocMaterial", E_CALLFAIL, me);
return NULL;
}
*mm = tmpmm;
_DBQQCalcStride(mm->stride, mm->dims, mm->ndims, mm->major_order);
/* If we have material names, restore it to an array of names. In the
* file, it's stored as one string, with individual names separated by
* semicolons. */
if ((tmpnames != NULL) && (mm->nmat > 0))
{
char *s, *name;
int i;
char error[256];
mm->matnames = ALLOC_N(char *, mm->nmat);
s = &tmpnames[0];
name = (char *)strtok(s, ";");
for (i = 0; i < mm->nmat; i++)
{
mm->matnames[i] = STRDUP(name);
if (i + 1 < mm->nmat)
{
name = (char *)strtok(NULL, ";");
if (name == NULL)
{
sprintf(error, "(%s) Not enough material names found\n", me);
db_perror(error, E_INTERNAL, me);
}
}
}
FREE(tmpnames);
}
if ((tmpcolors != NULL) && (mm->nmat > 0))
{
mm->matcolors = DBStringListToStringArray(tmpcolors, &(mm->nmat), !skipFirstSemicolon);
FREE(tmpcolors);
}
mm->id = 0;
mm->name = STRDUP(name);
if (0 >= mm->mixlen)
{
mm->datatype = DB_NOTYPE;
}
if (DB_DOUBLE == mm->datatype && PJ_InqForceSingle())
{
mm->datatype = DB_FLOAT;
}
return (mm);
}
/*----------------------------------------------------------------------
* Routine db_pdb_GetMatspecies
*
* Purpose
*
* Read a matspecies-data object from a SILO file and return the
* SILO structure for this type.
*
* Modifications
*
* Robb Matzke, Tue Nov 29 13:29:57 PST 1994
* Changed for device independence.
*
* Al Leibee, Tue Jul 26 08:44:01 PDT 1994
* Replaced composition by species.
*
* Sean Ahern, Sun Oct 1 03:08:19 PDT 1995
* Made "me" static.
*
* Jeremy Meredith, Wed Jul 7 12:15:31 PDT 1999
* I removed the origin value from the species object.
*
* Sean Ahern, Wed Jun 14 17:19:12 PDT 2000
* Added a check to make sure the object is the right type.
*
* Mark C. Miller, Wed Feb 2 07:59:53 PST 2005
* Moved DBAlloc call to after PJ_GetObject. Added automatic
* var for PJ_GetObject to read into. Added check for return
* value of PJ_GetObject.
*
* Mark C. Miller, Tue Sep 8 15:40:51 PDT 2009
* Added names and colors for species.
*
* Mark C. Miller, Tue Nov 10 09:14:01 PST 2009
* Added logic to control behavior of slash character swapping for
* windows/linux and skipping of first semicolon in calls to
* db_StringListToStringArray.
*--------------------------------------------------------------------*/
SILO_CALLBACK DBmatspecies *
db_pdb_GetMatspecies (DBfile *_dbfile, /*DB file pointer */
char const *objname) /*Name of matspecies obj to return */
{
DBmatspecies *mm;
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
static char *me = "db_pdb_GetMatspecies";
char *tmpnames = NULL;
char *tmpcolors = NULL;
char tmpstr[256];
PJcomplist tmp_obj;
DBmatspecies tmpmm;
int i, nstrs = 0;
PJcomplist *_tcl;
/*------------------------------------------------------------*/
/* Comp. Name Comp. Address Data Type */
/*------------------------------------------------------------*/
memset(&tmpmm, 0, sizeof(DBmatspecies));
INIT_OBJ(&tmp_obj);
DEFALL_OBJ("matname", &tmpmm.matname, DB_CHAR);
DEFINE_OBJ("ndims", &tmpmm.ndims, DB_INT);
DEFINE_OBJ("dims", tmpmm.dims, DB_INT);
DEFINE_OBJ("major_order", &tmpmm.major_order, DB_INT);
DEFINE_OBJ("datatype", &tmpmm.datatype, DB_INT);
DEFINE_OBJ("nmat", &tmpmm.nmat, DB_INT);
DEFALL_OBJ("nmatspec", &tmpmm.nmatspec, DB_INT);
DEFINE_OBJ("nspecies_mf", &tmpmm.nspecies_mf, DB_INT);
DEFALL_OBJ("speclist", &tmpmm.speclist, DB_INT);
DEFINE_OBJ("mixlen", &tmpmm.mixlen, DB_INT);
DEFALL_OBJ("mix_speclist", &tmpmm.mix_speclist, DB_INT);
DEFINE_OBJ("guihide", &tmpmm.guihide, DB_INT);
if (DBGetDataReadMask2File(_dbfile) & DBMatMatnames)
DEFALL_OBJ("species_names", &tmpnames, DB_CHAR);
if (DBGetDataReadMask2File(_dbfile) & DBMatMatcolors)
DEFALL_OBJ("speccolors", &tmpcolors, DB_CHAR);
if (PJ_GetObject(dbfile->pdb, objname, &tmp_obj, DB_MATSPECIES) < 0)
return NULL;
if (NULL == (mm = DBAllocMatspecies())) {
db_perror("DBAllocMatspecies", E_CALLFAIL, me);
return NULL;
}
*mm = tmpmm;
/* Now read in species_mf per its datatype. */
INIT_OBJ(&tmp_obj);
if (mm->datatype == 0) {
strcpy(tmpstr, objname);
strcat(tmpstr, "_data");
mm->datatype = db_pdb_GetVarDatatype(dbfile->pdb, tmpstr);
if (mm->datatype < 0)
mm->datatype = DB_FLOAT;
}
if (mm->datatype == DB_DOUBLE && PJ_InqForceSingle())
mm->datatype = DB_FLOAT;
DEFALL_OBJ("species_mf", &mm->species_mf, mm->datatype);
PJ_GetObject(dbfile->pdb, objname, &tmp_obj, 0);
_DBQQCalcStride(mm->stride, mm->dims, mm->ndims, mm->major_order);
mm->id = 0;
mm->name = STRDUP(objname);
for (i=0; i < mm->nmat; i++)
nstrs += mm->nmatspec[i];
if (tmpnames != NULL)
{
if (nstrs > 0)
mm->specnames = DBStringListToStringArray(tmpnames, &nstrs, !skipFirstSemicolon);
FREE(tmpnames);
}
if (tmpcolors != NULL)
{
if (nstrs > 0)
mm->speccolors = DBStringListToStringArray(tmpcolors, &nstrs, !skipFirstSemicolon);
FREE(tmpcolors);
}
return (mm);
}
/*-------------------------------------------------------------------------
* Function: db_pdb_GetCompoundarray
*
* Purpose: Read a compound array object from a PDB data file.
*
* Return: Success: pointer to the new object
*
* Failure: NULL, db_errno set
*
* Programmer: matzke@viper
* Wed Nov 2 14:43:05 PST 1994
*
* Modifications:
* Sean Ahern, Sun Oct 1 03:09:15 PDT 1995
* Made "me" static.
*
* Sean Ahern, Wed Jun 14 17:19:34 PDT 2000
* Added a check to make sure the object is the right type.
*
* Mark C. Miller, Wed Feb 2 07:59:53 PST 2005
* Moved DBAlloc call to after PJ_GetObject. Added automatic
* var for PJ_GetObject to read into. Added check for return
* value of PJ_GetObject.
*-------------------------------------------------------------------------*/
SILO_CALLBACK DBcompoundarray *
db_pdb_GetCompoundarray (DBfile *_dbfile, char const *array_name)
{
int i;
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
DBcompoundarray *ca = NULL;
char *s, delim[2], *name_vector = NULL;
static char *me = "db_pdb_GetCompoundarray";
PJcomplist tmp_obj;
DBcompoundarray tmpca;
PJcomplist *_tcl;
/*------------------------------------------------------------*/
/* Comp. Name Comp. Address Data Type */
/*------------------------------------------------------------*/
memset(&tmpca, 0, sizeof(DBcompoundarray));
INIT_OBJ(&tmp_obj);
DEFINE_OBJ("nelems", &tmpca.nelems, DB_INT);
DEFINE_OBJ("nvalues", &tmpca.nvalues, DB_INT);
DEFINE_OBJ("datatype", &tmpca.datatype, DB_INT);
DEFALL_OBJ("elemnames", &name_vector, DB_CHAR);
DEFALL_OBJ("elemlengths", &tmpca.elemlengths, DB_INT);
if (PJ_GetObject(dbfile->pdb, array_name, &tmp_obj, DB_ARRAY) < 0)
return NULL;
if (NULL == (ca = DBAllocCompoundarray()))
return NULL;
*ca = tmpca;
if (ca->nelems <= 0 || ca->nvalues <= 0 || ca->datatype < 0 ||
!name_vector) {
DBFreeCompoundarray(ca);
db_perror(array_name, E_NOTFOUND, me);
return NULL;
}
/*
* Internally, the meshnames are stored in a single character
* string as a delimited set of names. Here we break them into
* separate names. The delimiter is the first character of the
* name vector.
*/
if (name_vector && ca->nelems > 0) {
ca->elemnames = ALLOC_N(char *, ca->nelems);
delim[0] = name_vector[0];
delim[1] = '\0';
for (i = 0; i < ca->nelems; i++) {
s = strtok(i ? NULL : (name_vector + 1), delim);
ca->elemnames[i] = STRDUP(s);
}
FREE(name_vector);
}
/*
* Read the rest of the object--the vector of values, per datatype.
*/
INIT_OBJ(&tmp_obj);
if (DB_DOUBLE == ca->datatype && PJ_InqForceSingle()) {
ca->datatype = DB_FLOAT;
}
DEFALL_OBJ("values", &ca->values, ca->datatype);
PJ_GetObject(dbfile->pdb, array_name, &tmp_obj, 0);
ca->id = 0;
ca->name = STRDUP(array_name);
return ca;
}
/*-------------------------------------------------------------------------
* Function: db_pdb_GetCurve
*
* Purpose: Read a curve object from a PDB data file.
*
* Return: Success: pointer to the new object
*
* Failure: NULL, db_errno set
*
* Programmer: Robb Matzke
* robb@callisto.nuance.com
* May 16, 1996
*
* Modifications:
*
* Sean Ahern, Wed Jun 14 17:19:43 PDT 2000
* Added a check to make sure the object is the right type.
*
* Sean Ahern, Thu Mar 1 12:28:07 PST 2001
* Added support for the dataReadMask stuff.
*
* Mark C. Miller, Wed Feb 2 07:59:53 PST 2005
* Moved DBAlloc call to after PJ_GetObject. Added automatic
* var for PJ_GetObject to read into. Added check for return
* value of PJ_GetObject.
*
* Thomas R. Treadway, Fri Jul 7 11:43:41 PDT 2006
* Added DBOPT_REFERENCE support.
*-------------------------------------------------------------------------*/
SILO_CALLBACK DBcurve *
db_pdb_GetCurve (DBfile *_dbfile, char const *name)
{
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile ;
DBcurve *cu ;
static char *me = "db_pdb_GetCurve" ;
PJcomplist tmp_obj ;
DBcurve tmpcu;
PJcomplist *_tcl;
memset(&tmpcu, 0, sizeof(DBcurve));
INIT_OBJ (&tmp_obj) ;
DEFINE_OBJ ("npts", &tmpcu.npts, DB_INT) ;
DEFINE_OBJ ("datatype", &tmpcu.datatype, DB_INT) ;
DEFALL_OBJ ("label", &tmpcu.title, DB_CHAR) ;
DEFALL_OBJ ("xvarname", &tmpcu.xvarname, DB_CHAR) ;
DEFALL_OBJ ("yvarname", &tmpcu.yvarname, DB_CHAR) ;
DEFALL_OBJ ("xlabel", &tmpcu.xlabel, DB_CHAR) ;
DEFALL_OBJ ("ylabel", &tmpcu.ylabel, DB_CHAR) ;
DEFALL_OBJ ("xunits", &tmpcu.xunits, DB_CHAR) ;
DEFALL_OBJ ("yunits", &tmpcu.yunits, DB_CHAR) ;
DEFALL_OBJ ("reference",&tmpcu.reference,DB_CHAR) ;
DEFINE_OBJ ("guihide", &tmpcu.guihide, DB_INT) ;
DEFINE_OBJ ("coord_sys", &tmpcu.coord_sys, DB_INT) ;
DEFINE_OBJ ("missing_value", &tmpcu.missing_value, DB_DOUBLE);
if (PJ_GetObject (dbfile->pdb, name, &tmp_obj, DB_CURVE)<0)
return NULL ;
if (NULL == (cu = DBAllocCurve ())) return NULL ;
*cu = tmpcu;
if (DB_DOUBLE == cu->datatype && PJ_InqForceSingle())
cu->datatype = DB_FLOAT ;
/*
* Read the x and y arrays.
*/
if (DBGetDataReadMask2File(_dbfile) & DBCurveArrays)
{
if (cu->reference && (cu->x || cu->y)) {
db_perror ("x and y not NULL", E_BADARGS, me) ;
return NULL ;
} else if (cu->reference) {
cu->x = NULL;
cu->y = NULL;
} else {
INIT_OBJ (&tmp_obj) ;
DEFALL_OBJ ("xvals", &cu->x, cu->datatype) ;
DEFALL_OBJ ("yvals", &cu->y, cu->datatype) ;
PJ_GetObject (dbfile->pdb, name, &tmp_obj, 0) ;
}
}
if (cu->missing_value == DB_MISSING_VALUE_NOT_SET)
cu->missing_value = 0.0;
else if (cu->missing_value == 0.0)
cu->missing_value = DB_MISSING_VALUE_NOT_SET;
cu->id = 0 ;
return cu ;
}
/*-------------------------------------------------------------------------
* Function: db_pdb_GetComponent
*
* Purpose: Read a component value from the data file.
*
* Return: Success: pointer to component.
*
* Failure: NULL
*
* Programmer: matzke@viper
* Tue Nov 8 08:26:55 PST 1994
*
* Modifications:
* Sean Ahern, Sun Oct 1 03:10:32 PDT 1995
* Made "me" static.
*-------------------------------------------------------------------------*/
SILO_CALLBACK void *
db_pdb_GetComponent (DBfile *_dbfile, char const *objname, char const *compname)
{
void *result;
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
static char *me = "db_pdb_GetComponent";
result = PJ_GetComponent(dbfile->pdb, objname, compname);
if (!result) {
db_perror("PJ_GetComponent", E_CALLFAIL, me);
return NULL;
}
return result;
}
/*-------------------------------------------------------------------------
* Function: db_pdb_GetComponentType
*
* Purpose: Read a component type from the data file.
*
* Return: Success: integer representing component type.
*
* Failure: DB_NOTYPE
*
* Programmer: Brad Whitlock
* Thu Jan 20 12:02:29 PDT 2000
*
* Modifications:
*-------------------------------------------------------------------------*/
SILO_CALLBACK int
db_pdb_GetComponentType (DBfile *_dbfile, char const *objname, char const *compname)
{
int retval = DB_NOTYPE;
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
retval = PJ_GetComponentType(dbfile->pdb, objname, compname);
return retval;
}
/*----------------------------------------------------------------------
* Routine db_pdb_GetDefvars
*
* Purpose
*
* Read a defvars structure from the given database.
*
* Programmger
*
* Mark C. Miller,
* August 8, 2005
*
* Modifications:
*
* Mark C. Miller, Tue Nov 10 09:14:01 PST 2009
* Added logic to control behavior of slash character swapping for
* windows/linux and skipping of first semicolon in calls to
* db_StringListToStringArray.
*
* Mark C. Miller, Thu Jan 6 17:01:28 PST 2011
* Fix name of guihide array (removed the extra 's').
*--------------------------------------------------------------------*/
SILO_CALLBACK DBdefvars *
db_pdb_GetDefvars(DBfile *_dbfile, char const *objname)
{
DBdefvars *defv = NULL;
int ncomps, type;
char *tmpnames, *tmpdefns, tmp[256];
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
PJcomplist tmp_obj;
static char *me = "db_pdb_GetDefvars";
db_pdb_getobjinfo(dbfile->pdb, (char *) objname, tmp, &ncomps);
type = DBGetObjtypeTag(tmp);
/* Read multi-block object */
if (type == DB_DEFVARS)
{
DBdefvars tmpdefv;
PJcomplist *_tcl;
memset(&tmpdefv, 0, sizeof(DBdefvars));
INIT_OBJ(&tmp_obj);
DEFINE_OBJ("ndefs", &tmpdefv.ndefs, DB_INT);
DEFALL_OBJ("types", &tmpdefv.types, DB_INT);
DEFALL_OBJ("guihide", &tmpdefv.guihides, DB_INT);
DEFALL_OBJ("names", &tmpnames, DB_CHAR);
DEFALL_OBJ("defns", &tmpdefns, DB_CHAR);
if (PJ_GetObject(dbfile->pdb, (char *) objname, &tmp_obj, DB_DEFVARS) < 0)
return NULL;
if ((defv = DBAllocDefvars(0)) == NULL)
return NULL;
*defv = tmpdefv;
if ((tmpnames != NULL) && (defv->ndefs > 0))
{
defv->names = DBStringListToStringArray(tmpnames, &(defv->ndefs), !skipFirstSemicolon);
FREE(tmpnames);
}
if ((tmpdefns != NULL) && (defv->ndefs > 0))
{
defv->defns = DBStringListToStringArray(tmpdefns, &(defv->ndefs), !skipFirstSemicolon);
FREE(tmpdefns);
}
}
return (defv);
}
/*-------------------------------------------------------------------------
* Function: pdb_getvarinfo
*
* Purpose:
*
* Return: Success:
*
* Failure:
*
* Programmer:
*
* Modifications:
* Sean Ahern, Wed Apr 12 11:14:38 PDT 2000
* Removed the last two parameters to PJ_inquire_entry because they
* weren't being used.
*-------------------------------------------------------------------------*/
INTERNAL int
pdb_getvarinfo (PDBfile *pdbfile,
char *name, /*Name of variable to inquire about */
char *type, /*Returned datatype of 'name' */
int *num, /*Returned number of elements */
int *size, /*Returned element size */
int verbose) /*Sentinel: 1==print error msgs; 0==quiet*/
{
int is_ptr;
char lastchar;
char *s;
defstr *dp;
syment *ep;
*num = *size = 0;
if (type)
type[0] = '\0';
/*
* Get symbol table entry for requested variable.
*/
ep = PJ_inquire_entry(pdbfile, name);
if (ep == NULL)
return (OOPS);
/* Assign values */
if (type)
strcpy(type, ep->type);
lastchar = STR_LASTCHAR(ep->type);
if (lastchar == '*')
is_ptr = 1;
else
is_ptr = 0;
if (is_ptr) {
s = STRDUP(ep->type);
s[strcspn(s, " *")] = '\0';
/* Get data size of primitive (non-pointer) unit */
dp = PD_inquire_host_type(pdbfile, s);
*size = dp->size;
*num = -1; /* lite_SC_arrlen(values) / dp->size; */
if (verbose)
printf("Cannot query length of pointered variable.\n");
FREE(s);
}
else {
dp = PD_inquire_host_type(pdbfile, ep->type);
if (dp == NULL) {
if (verbose)
printf("Don't know about data of type: %s\n", ep->type);
return (OOPS);
}
/* Assign values */
*size = dp->size;
*num = ep->number;
}
return (OKAY);
}
/*----------------------------------------------------------------------
* Routine db_pdb_GetMultimesh
*
* Purpose
*
* Read a multi-block-mesh structure from the given database. If the
* requested object is not multi-block, return the information for
* that one mesh only.
*
* Modifications
* Al Leibee, Wed Jul 7 08:00:00 PDT 1993
* Change SCALLOC_N to ALLOC_N and SC_strsave to STR_SAVE to be less
* SCORE dependent. Change FREE to SCFREE to be consistant with
* allocation.
*
* Robb Matzke, Mon Nov 14 14:37:33 EST 1994
* Device independence rewrite.
*
* Robb Matzke, Fri Dec 2 14:11:57 PST 1994
* Removed references to SCORE memory management: `tmpnames'
*
* Eric Brugger, Fri Jan 27 09:33:44 PST 1995
* I modified the routine to return NULL unless the variable is
* a multimesh.
*
* Sean Ahern, Sun Oct 1 03:11:55 PDT 1995
* Made "me" static.
*
* Eric Brugger, Wed Jul 2 13:30:05 PDT 1997
* Modify the call to DBAllocMultimesh to not allocate any arrays
* in the multimesh structure.
*
* Jeremy Meredith, Fri May 21 10:04:25 PDT 1999
* Added ngroups, blockorigin, and grouporigin.
*
* Jeremy Meredith, Fri Jul 23 09:08:09 PDT 1999
* Added a check to stop strtok from occurring past the end of the
* array. This was crashing the code intermittently.
*
* Sean Ahern, Wed Jun 14 17:19:47 PDT 2000
* Added a check to make sure the object is the right type.
*
* Mark C. Miller, Wed Feb 2 07:59:53 PST 2005
* Moved DBAlloc call to after PJ_GetObject. Added automatic
* var for PJ_GetObject to read into. Added check for return
* value of PJ_GetObject.
*
* Thomas R. Treadway, Thu Jul 20 13:34:57 PDT 2006
* Added lgroupings, groupings, and groupnames options.
*
* Mark C. Miller, Tue Nov 10 09:14:01 PST 2009
* Replaced strtok-loop over ...names member with call to
* db_StringListToStringArray. Added logic to control behavior of
* slash character swapping for windows/linux and skipping of first
* semicolon in calls to db_StringListToStringArray.
*
* Mark C. Miller, Wed Jul 14 20:40:55 PDT 2010
* Added support for namescheme/empty list options.
*--------------------------------------------------------------------*/
SILO_CALLBACK DBmultimesh *
db_pdb_GetMultimesh (DBfile *_dbfile, char const *objname)
{
DBmultimesh *mm = NULL;
int ncomps, type;
char *tmpnames=0, tmp[256];
char *tmpgnames = 0;
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
PJcomplist tmp_obj;
static char *me = "db_pdb_GetMultimesh";
PJcomplist *_tcl;
db_pdb_getobjinfo(dbfile->pdb, objname, tmp, &ncomps);
type = DBGetObjtypeTag(tmp);
if (type == DB_MULTIMESH) {
DBmultimesh tmpmm;
memset(&tmpmm, 0, sizeof(DBmultimesh));
/* Read multi-block object */
INIT_OBJ(&tmp_obj);
DEFINE_OBJ("nblocks", &tmpmm.nblocks, DB_INT);
DEFINE_OBJ("ngroups", &tmpmm.ngroups, DB_INT);
DEFINE_OBJ("blockorigin", &tmpmm.blockorigin, DB_INT);
DEFINE_OBJ("grouporigin", &tmpmm.grouporigin, DB_INT);
DEFINE_OBJ("guihide", &tmpmm.guihide, DB_INT);
DEFALL_OBJ("meshids", &tmpmm.meshids, DB_INT);
DEFALL_OBJ("meshtypes", &tmpmm.meshtypes, DB_INT);
DEFALL_OBJ("meshnames", &tmpnames, DB_CHAR);
DEFALL_OBJ("meshdirs", &tmpmm.dirids, DB_INT);
DEFINE_OBJ("extentssize", &tmpmm.extentssize, DB_INT);
DEFALL_OBJ("extents", &tmpmm.extents, DB_DOUBLE);
DEFALL_OBJ("zonecounts", &tmpmm.zonecounts, DB_INT);
DEFALL_OBJ("has_external_zones", &tmpmm.has_external_zones, DB_INT);
DEFINE_OBJ("lgroupings", &tmpmm.lgroupings, DB_INT);
DEFALL_OBJ("groupings", &tmpmm.groupings, DB_INT);
DEFALL_OBJ("groupnames", &tmpgnames, DB_CHAR);
DEFALL_OBJ("mrgtree_name", &tmpmm.mrgtree_name, DB_CHAR);
DEFINE_OBJ("tv_connectivity", &tmpmm.tv_connectivity, DB_INT);
DEFINE_OBJ("disjoint_mode", &tmpmm.disjoint_mode, DB_INT);
DEFINE_OBJ("topo_dim", &tmpmm.topo_dim, DB_INT);
DEFALL_OBJ("file_ns", &tmpmm.file_ns, DB_CHAR);
DEFALL_OBJ("block_ns", &tmpmm.block_ns, DB_CHAR);
DEFINE_OBJ("block_type", &tmpmm.block_type, DB_INT);
DEFALL_OBJ("empty_list", &tmpmm.empty_list, DB_INT);
DEFINE_OBJ("empty_cnt", &tmpmm.empty_cnt, DB_INT);
DEFINE_OBJ("repr_block_idx", &tmpmm.repr_block_idx, DB_INT);
if (PJ_GetObject(dbfile->pdb, objname, &tmp_obj, DB_MULTIMESH) < 0)
return NULL;
if ((mm = DBAllocMultimesh(0)) == NULL)
return NULL;
*mm = tmpmm;
/* The value we store to the file for 'topo_dim' member is
designed such that zero indicates a value that was NOT
specified in the file. Since zero is a valid topological
dimension, when we store topo_dim to a file, we always
add 1. So, we have to subtract it here. This was implemented
for multimeshes in 4.7 and so is handled correctly for
them in all cases. Likewise for repr_block_idx. */
mm->topo_dim = mm->topo_dim - 1;
mm->repr_block_idx = mm->repr_block_idx-1;
/*----------------------------------------
* Internally, the meshnames and groupings
* iare stored in a single character string
* as a delimited set of names. Here we break
* them into separate names.
*----------------------------------------*/
if ((tmpnames != NULL) && (mm->nblocks > 0)) {
db_StringListToStringArrayMBOpt(tmpnames, &(mm->meshnames), &(mm->meshnames_alloc), mm->nblocks);
}
if ((tmpgnames != NULL) && (mm->lgroupings > 0)) {
mm->groupnames = DBStringListToStringArray(tmpgnames, &(mm->lgroupings), !skipFirstSemicolon);
FREE(tmpgnames);
}
}
return (mm);
}
/*----------------------------------------------------------------------
* Routine db_pdb_GetMultimeshadj
*
* Purpose
*
* Read some or all of a multi-block-mesh adjacency object from
* the given database.
*--------------------------------------------------------------------*/
SILO_CALLBACK DBmultimeshadj *
db_pdb_GetMultimeshadj (DBfile *_dbfile, char const *objname, int nmesh,
int const *block_map)
{
DBmultimeshadj *mmadj = NULL;
int ncomps, type;
int i, j, tmpnmesh;
char tmp[256], *nlsname = 0, zlsname = 0;
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
PJcomplist tmp_obj;
static char *me = "db_pdb_GetMultimeshadj";
char tmpn[256];
int *offsetmap, *offsetmapn=0, *offsetmapz=0, lneighbors, tmpoff;
PJcomplist *_tcl;
db_pdb_getobjinfo(dbfile->pdb, (char*)objname, tmp, &ncomps);
type = DBGetObjtypeTag(tmp);
if (type == DB_MULTIMESHADJ) {
DBmultimeshadj tmpmmadj;
memset(&tmpmmadj, 0, sizeof(DBmultimeshadj));
/* Read multi-block object */
INIT_OBJ(&tmp_obj);
DEFINE_OBJ("nblocks", &tmpmmadj.nblocks, DB_INT);
DEFINE_OBJ("lneighbors", &tmpmmadj.lneighbors, DB_INT);
DEFINE_OBJ("totlnodelists", &tmpmmadj.totlnodelists, DB_INT);
DEFINE_OBJ("totlzonelists", &tmpmmadj.totlzonelists, DB_INT);
DEFINE_OBJ("blockorigin", &tmpmmadj.blockorigin, DB_INT);
DEFALL_OBJ("meshtypes", &tmpmmadj.meshtypes, DB_INT);
DEFALL_OBJ("nneighbors", &tmpmmadj.nneighbors, DB_INT);
DEFALL_OBJ("neighbors", &tmpmmadj.neighbors, DB_INT);
DEFALL_OBJ("back", &tmpmmadj.back, DB_INT);
DEFALL_OBJ("lnodelists", &tmpmmadj.lnodelists, DB_INT);
DEFALL_OBJ("lzonelists", &tmpmmadj.lzonelists, DB_INT);
if (PJ_GetObject(dbfile->pdb, (char*)objname, &tmp_obj, DB_MULTIMESHADJ) < 0)
return NULL;
if ((mmadj = DBAllocMultimeshadj(0)) == NULL)
return NULL;
*mmadj = tmpmmadj;
offsetmap = ALLOC_N(int, mmadj->nblocks);
lneighbors = 0;
for (i = 0; i < mmadj->nblocks; i++)
{
offsetmap[i] = lneighbors;
lneighbors += mmadj->nneighbors[i];
}
if (mmadj->lnodelists && (DBGetDataReadMask2File(_dbfile) & DBMMADJNodelists))
{
mmadj->nodelists = ALLOC_N(int *, lneighbors);
offsetmapn = ALLOC_N(int, mmadj->nblocks);
tmpoff = 0;
for (i = 0; i < mmadj->nblocks; i++)
{
offsetmapn[i] = tmpoff;
for (j = 0; j < mmadj->nneighbors[i]; j++)
tmpoff += mmadj->lnodelists[offsetmap[i]+j];
}
}
if (mmadj->lzonelists && (DBGetDataReadMask2File(_dbfile) & DBMMADJZonelists))
{
mmadj->zonelists = ALLOC_N(int *, lneighbors);
offsetmapz = ALLOC_N(int, mmadj->nblocks);
tmpoff = 0;
for (i = 0; i < mmadj->nblocks; i++)
{
offsetmapz[i] = tmpoff;
for (j = 0; j < mmadj->nneighbors[i]; j++)
tmpoff += mmadj->lzonelists[offsetmap[i]+j];
}
}
tmpnmesh = nmesh;
if (nmesh <= 0 || !block_map)
tmpnmesh = mmadj->nblocks;
/* This loop could be optimized w.r.t. number of I/O requests
it makes. The nodelists and/or zonelists could be read in
a single call. But then we'd have to split it into separate
arrays duplicating memory */
for (i = 0; (i < tmpnmesh) &&
(DBGetDataReadMask2File(_dbfile) & (DBMMADJNodelists|DBMMADJZonelists)); i++)
{
int blockno = block_map ? block_map[i] : i;
if (mmadj->lnodelists && (DBGetDataReadMask2File(_dbfile) & DBMMADJNodelists))
{
tmpoff = offsetmapn[blockno];
for (j = 0; j < mmadj->nneighbors[blockno]; j++)
{
long ind[3];
int len = mmadj->lnodelists[offsetmap[blockno]+j];
int *nlist = ALLOC_N(int, len);
ind[0] = tmpoff;
ind[1] = tmpoff + len - 1;
ind[2] = 1;
db_mkname(dbfile->pdb, (char*)objname, "nodelists", tmpn);
if (!PJ_read_alt(dbfile->pdb, tmpn, nlist, ind)) {
FREE(offsetmap);
FREE(offsetmapn);
FREE(offsetmapz);
db_perror("PJ_read_alt", E_CALLFAIL, me);
}
mmadj->nodelists[offsetmap[blockno]+j] = nlist;
tmpoff += len;
}
}
if (mmadj->lzonelists && (DBGetDataReadMask2File(_dbfile) & DBMMADJZonelists))
{
tmpoff = offsetmapz[blockno];
for (j = 0; j < mmadj->nneighbors[blockno]; j++)
{
long ind[3];
int len = mmadj->lzonelists[offsetmap[blockno]+j];
int *zlist = ALLOC_N(int, len);
ind[0] = tmpoff;
ind[1] = tmpoff + len - 1;
ind[2] = 1;
db_mkname(dbfile->pdb, (char*)objname, "zonelists", tmpn);
if (!PJ_read_alt(dbfile->pdb, tmpn, zlist, ind)) {
FREE(offsetmap);
FREE(offsetmapn);
FREE(offsetmapz);
db_perror("PJ_read_alt", E_CALLFAIL, me);
}
mmadj->zonelists[offsetmap[blockno]+j] = zlist;
tmpoff += len;
}
}
}
FREE(offsetmap);
FREE(offsetmapn);
FREE(offsetmapz);
}
return (mmadj);
}
/*-------------------------------------------------------------------------
* Function: db_pdb_GetMultivar
*
* Purpose: Read a multi-block-var structure from the given database.
*
* Return: Success: ptr to a new structure
*
* Failure: NULL
*
* Programmer: robb@cloud
* Tue Feb 21 11:04:39 EST 1995
*
* Modifications:
* Sean Ahern, Sun Oct 1 03:12:16 PDT 1995
* Made "me" static.
*
* Eric Brugger, Wed Jul 2 13:30:05 PDT 1997
* Modify the call to DBAllocMultivar to not allocate any arrays
* in the multivar structure.
*
* Jeremy Meredith, Fri May 21 10:04:25 PDT 1999
* Added ngroups, blockorigin, and grouporigin.
*
* Jeremy Meredith, Fri Jul 23 09:08:09 PDT 1999
* Added a check to stop strtok from occurring past the end of the
* array. This was crashing the code intermittently.
*
* Sean Ahern, Wed Jun 14 17:20:24 PDT 2000
* Added a check to make sure the object is the right type.
*
* Mark C. Miller, Wed Feb 2 07:59:53 PST 2005
* Moved DBAlloc call to after PJ_GetObject. Added automatic
* var for PJ_GetObject to read into. Added check for return
* value of PJ_GetObject.
*
* Mark C. Miller, Thu Nov 5 16:15:49 PST 2009
* Added support for conserved/extensive options.
*
* Mark C. Miller, Tue Nov 10 09:14:01 PST 2009
* Replaced strtok-loop over ...names member with call to
* db_StringListToStringArray. Added logic to control behavior of
* slash character swapping for windows/linux and skipping of first
* semicolon in calls to db_StringListToStringArray.
*
* Mark C. Miller, Wed Jul 14 20:40:55 PDT 2010
* Added support for namescheme/empty list options.
*-------------------------------------------------------------------------*/
SILO_CALLBACK DBmultivar *
db_pdb_GetMultivar (DBfile *_dbfile, char const *objname)
{
DBmultivar *mv = NULL;
int ncomps, type;
char *tmpnames=0, tmp[256];
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
PJcomplist tmp_obj;
static char *me = "db_pdb_GetMultivar";
char *rpnames = NULL;
PJcomplist *_tcl;
db_pdb_getobjinfo(dbfile->pdb, objname, tmp, &ncomps);
type = DBGetObjtypeTag(tmp);
if (type == DB_MULTIVAR) {
DBmultivar tmpmv;
memset(&tmpmv, 0, sizeof(DBmultivar));
/* Read multi-block object */
INIT_OBJ(&tmp_obj);
DEFINE_OBJ("nvars", &tmpmv.nvars, DB_INT);
DEFALL_OBJ("vartypes", &tmpmv.vartypes, DB_INT);
DEFALL_OBJ("varnames", &tmpnames, DB_CHAR);
DEFINE_OBJ("ngroups", &tmpmv.ngroups, DB_INT);
DEFINE_OBJ("blockorigin", &tmpmv.blockorigin, DB_INT);
DEFINE_OBJ("grouporigin", &tmpmv.grouporigin, DB_INT);
DEFINE_OBJ("extentssize", &tmpmv.extentssize, DB_INT);
DEFALL_OBJ("extents", &tmpmv.extents, DB_DOUBLE);
DEFINE_OBJ("guihide", &tmpmv.guihide, DB_INT);
DEFALL_OBJ("region_pnames", &rpnames, DB_CHAR);
DEFINE_OBJ("tensor_rank", &tmpmv.tensor_rank, DB_INT);
DEFALL_OBJ("mmesh_name", &tmpmv.mmesh_name, DB_CHAR);
DEFINE_OBJ("conserved", &tmpmv.conserved, DB_INT);
DEFINE_OBJ("extensive", &tmpmv.extensive, DB_INT);
DEFALL_OBJ("file_ns", &tmpmv.file_ns, DB_CHAR);
DEFALL_OBJ("block_ns", &tmpmv.block_ns, DB_CHAR);
DEFINE_OBJ("block_type", &tmpmv.block_type, DB_INT);
DEFALL_OBJ("empty_list", &tmpmv.empty_list, DB_INT);
DEFINE_OBJ("empty_cnt", &tmpmv.empty_cnt, DB_INT);
DEFINE_OBJ("repr_block_idx", &tmpmv.repr_block_idx, DB_INT);
DEFINE_OBJ("missing_value", &tmpmv.missing_value, DB_DOUBLE);
if (PJ_GetObject(dbfile->pdb, objname, &tmp_obj, DB_MULTIVAR) < 0)
return NULL;
if ((mv = DBAllocMultivar(0)) == NULL)
return NULL;
*mv = tmpmv;
/* -1 to support zero value indicating NOT SET */
mv->repr_block_idx = mv->repr_block_idx - 1;
/*----------------------------------------
* Internally, the varnames are stored
* in a single character string as a
* delimited set of names. Here we break
* them into separate names.
*----------------------------------------*/
if (tmpnames != NULL && mv->nvars > 0) {
db_StringListToStringArrayMBOpt(tmpnames, &(mv->varnames), &(mv->varnames_alloc), mv->nvars);
}
if (rpnames != NULL)
{
mv->region_pnames = DBStringListToStringArray(rpnames, 0, !skipFirstSemicolon);
FREE(rpnames);
}
if (mv->missing_value == DB_MISSING_VALUE_NOT_SET)
mv->missing_value = 0.0;
else if (mv->missing_value == 0.0)
mv->missing_value = DB_MISSING_VALUE_NOT_SET;
}
return (mv);
}
/*-------------------------------------------------------------------------
* Function: db_pdb_GetMultimat
*
* Purpose: Read a multi-material structure from the given database.
*
* Return: Success: ptr to a new structure
*
* Failure: NULL
*
* Programmer: robb@cloud
* Tue Feb 21 12:39:51 EST 1995
*
* Modifications:
* Sean Ahern, Sun Oct 1 03:12:39 PDT 1995
* Made "me" static.
*
* Sean Ahern, Mon Jun 24 14:44:44 PDT 1996
* Added better error checking to keep strtok from running off the
* end of the tmpnames array,
*
* Sean Ahern, Mon Jun 24 15:03:43 PDT 1996
* Fixed a memory leak where mt->matnames was being allocated twice,
* once in DBAllocMultimat, and once here.
*
* Sean Ahern, Tue Jun 25 13:41:23 PDT 1996
* Since we know that material names are delimited by ';', we don't
* need the delim array. Just use ";" instead.
*
* Eric Brugger, Wed Jul 2 13:30:05 PDT 1997
* Modify the call to DBAllocMultimat to not allocate any arrays
* in the multimat structure.
*
* Jeremy Meredith, Fri May 21 10:04:25 PDT 1999
* Added ngroups, blockorigin, and grouporigin.
*
* Sean Ahern, Wed Jun 14 17:20:55 PDT 2000
* Added a check to make sure the object is the right type.
*
* Mark C. Miller, Wed Feb 2 07:59:53 PST 2005
* Moved DBAlloc call to after PJ_GetObject. Added automatic
* var for PJ_GetObject to read into. Added check for return
* value of PJ_GetObject.
*
* Mark C. Miller, Mon Aug 7 17:03:51 PDT 2006
* Added material_names and matcolors as well as nmatnos and matnos
*
* Mark C. Miller, Tue Nov 10 09:14:01 PST 2009
* Replaced strtok-loop over ...names member with call to
* db_StringListToStringArray. Added logic to control behavior of
* slash character swapping for windows/linux and skipping of first
* semicolon in calls to db_StringListToStringArray.
*
* Mark C. Miller, Thu Feb 4 11:14:20 PST 2010
* Added missing logic for setting allowmat0.
*
* Mark C. Miller, Wed Jul 14 20:40:55 PDT 2010
* Added support for namescheme/empty list options.
*-------------------------------------------------------------------------*/
SILO_CALLBACK DBmultimat *
db_pdb_GetMultimat (DBfile *_dbfile, char const *objname)
{
DBmultimat *mt = NULL;
int ncomps, type;
char *tmpnames=NULL, *s=NULL, *name=NULL, tmp[256];
char *tmpmatcolors=NULL, *tmpmaterial_names=NULL;
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
PJcomplist tmp_obj;
static char *me = "db_pdb_GetMultimat";
PJcomplist *_tcl;
db_pdb_getobjinfo(dbfile->pdb, objname, tmp, &ncomps);
type = DBGetObjtypeTag(tmp);
if (type == DB_MULTIMAT) {
DBmultimat tmpmt;
memset(&tmpmt, 0, sizeof(DBmultimat));
/* Read multi-block object */
INIT_OBJ(&tmp_obj);
DEFINE_OBJ("nmats", &tmpmt.nmats, DB_INT);
DEFALL_OBJ("matnames", &tmpnames, DB_CHAR);
DEFINE_OBJ("ngroups", &tmpmt.ngroups, DB_INT);
DEFINE_OBJ("blockorigin", &tmpmt.blockorigin, DB_INT);
DEFINE_OBJ("grouporigin", &tmpmt.grouporigin, DB_INT);
DEFINE_OBJ("nmatnos", &tmpmt.nmatnos, DB_INT);
DEFALL_OBJ("matnos", &tmpmt.matnos, DB_INT);
DEFALL_OBJ("mixlens", &tmpmt.mixlens, DB_INT);
DEFALL_OBJ("matcounts", &tmpmt.matcounts, DB_INT);
DEFALL_OBJ("matlists", &tmpmt.matlists, DB_INT);
DEFINE_OBJ("guihide", &tmpmt.guihide, DB_INT);
DEFINE_OBJ("allowmat0", &tmpmt.allowmat0, DB_INT);
DEFALL_OBJ("material_names", &tmpmaterial_names, DB_CHAR);
DEFALL_OBJ("matcolors", &tmpmatcolors, DB_CHAR);
DEFALL_OBJ("mmesh_name", &tmpmt.mmesh_name, DB_CHAR);
DEFALL_OBJ("file_ns", &tmpmt.file_ns, DB_CHAR);
DEFALL_OBJ("block_ns", &tmpmt.block_ns, DB_CHAR);
DEFALL_OBJ("empty_list", &tmpmt.empty_list, DB_INT);
DEFINE_OBJ("empty_cnt", &tmpmt.empty_cnt, DB_INT);
DEFINE_OBJ("repr_block_idx", &tmpmt.repr_block_idx, DB_INT);
if (PJ_GetObject(dbfile->pdb, objname, &tmp_obj, DB_MULTIMAT) < 0)
return NULL;
if ((mt = DBAllocMultimat(0)) == NULL)
return NULL;
*mt = tmpmt;
/* -1 to support zero value indicating NOT SET */
mt->repr_block_idx = mt->repr_block_idx - 1;
/*----------------------------------------
* Internally, the material names are stored
* in a single character string as a
* delimited set of names. Here we break
* them into separate names.
*----------------------------------------*/
if (tmpnames != NULL && mt->nmats > 0)
{
db_StringListToStringArrayMBOpt(tmpnames, &(mt->matnames), &(mt->matnames_alloc), mt->nmats);
}
if (tmpmaterial_names && mt->nmatnos > 0)
{
mt->material_names = DBStringListToStringArray(tmpmaterial_names,
&(mt->nmatnos), !skipFirstSemicolon);
FREE(tmpmaterial_names);
}
if (tmpmatcolors && mt->nmatnos > 0)
{
mt->matcolors = DBStringListToStringArray(tmpmatcolors,
&(mt->nmatnos), !skipFirstSemicolon);
FREE(tmpmatcolors);
}
}
return (mt);
}
/*-------------------------------------------------------------------------
* Function: db_pdb_GetMultimatspecies
*
* Purpose: Read a multi-species structure from the given database.
*
* Return: Success: ptr to a new structure
*
* Failure: NULL
*
* Programmer: Jeremy S. Meredith
* Sept 17 1998
*
* Modifications:
*
* Jeremy Meredith, Fri May 21 10:04:25 PDT 1999
* Added ngroups, blockorigin, and grouporigin.
*
* Sean Ahern, Wed Jun 14 17:21:18 PDT 2000
* Added a check to make sure the object is the right type.
*
* Mark C. Miller, Wed Feb 2 07:59:53 PST 2005
* Moved DBAlloc call to after PJ_GetObject. Added automatic
* var for PJ_GetObject to read into. Added check for return
* value of PJ_GetObject.
*
* Mark C. Miller, Mon Aug 7 17:03:51 PDT 2006
* Added nmat and nmatspec
*
* Mark C. Miller, Tue Sep 8 15:40:51 PDT 2009
* Added names and colors for species.
*
* Mark C. Miller, Tue Nov 10 09:14:01 PST 2009
* Replaced strtok-loop over ...names member with call to
* db_StringListToStringArray. Added logic to control behavior of
* slash character swapping for windows/linux and skipping of first
* semicolon in calls to db_StringListToStringArray.
*
* Mark C. Miller, Wed Jul 14 20:40:55 PDT 2010
* Added support for namescheme/empty list options.
*-------------------------------------------------------------------------*/
SILO_CALLBACK DBmultimatspecies *
db_pdb_GetMultimatspecies (DBfile *_dbfile, char const *objname)
{
DBmultimatspecies *mms = NULL;
int ncomps, type;
int i, nstrs = 0;
char *tmpnames=NULL, *s=NULL, *name=NULL, tmp[256];
char *tmpspecnames=NULL, *tmpcolors=NULL;
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
PJcomplist tmp_obj;
static char *me = "db_pdb_GetMultimatspecies";
PJcomplist *_tcl;
db_pdb_getobjinfo(dbfile->pdb, objname, tmp, &ncomps);
type = DBGetObjtypeTag(tmp);
if (type == DB_MULTIMATSPECIES) {
DBmultimatspecies tmpmms;
memset(&tmpmms, 0, sizeof(DBmultimatspecies));
/* Read multi-block object */
INIT_OBJ(&tmp_obj);
DEFINE_OBJ("nspec", &tmpmms.nspec, DB_INT);
DEFALL_OBJ("specnames", &tmpnames, DB_CHAR);
DEFINE_OBJ("ngroups", &tmpmms.ngroups, DB_INT);
DEFINE_OBJ("blockorigin", &tmpmms.blockorigin, DB_INT);
DEFINE_OBJ("grouporigin", &tmpmms.grouporigin, DB_INT);
DEFINE_OBJ("guihide", &tmpmms.guihide, DB_INT);
DEFINE_OBJ("nmat", &tmpmms.nmat, DB_INT);
DEFALL_OBJ("nmatspec", &tmpmms.nmatspec, DB_INT);
if (DBGetDataReadMask2File(_dbfile) & DBMatMatnames)
DEFALL_OBJ("species_names", &tmpspecnames, DB_CHAR);
if (DBGetDataReadMask2File(_dbfile) & DBMatMatcolors)
DEFALL_OBJ("speccolors", &tmpcolors, DB_CHAR);
DEFALL_OBJ("file_ns", &tmpmms.file_ns, DB_CHAR);
DEFALL_OBJ("block_ns", &tmpmms.block_ns, DB_CHAR);
DEFALL_OBJ("empty_list", &tmpmms.empty_list, DB_INT);
DEFINE_OBJ("empty_cnt", &tmpmms.empty_cnt, DB_INT);
DEFINE_OBJ("repr_block_idx", &tmpmms.repr_block_idx, DB_INT);
if (PJ_GetObject(dbfile->pdb, objname, &tmp_obj, DB_MULTIMATSPECIES) < 0)
return NULL;
if ((mms = DBAllocMultimatspecies(0)) == NULL)
return NULL;
*mms = tmpmms;
/* -1 to support zero value indicating NOT SET */
mms->repr_block_idx = mms->repr_block_idx - 1;
/*----------------------------------------
* Internally, the material species names
* are stored in a single character string
* as a delimited set of names. Here we
* break them into separate names.
*----------------------------------------*/
if (tmpnames != NULL && mms->nspec > 0)
{
db_StringListToStringArrayMBOpt(tmpnames, &(mms->specnames), &(mms->specnames_alloc), mms->nspec);
}
if (tmpspecnames != NULL)
{
for (i = 0; i < mms->nmat; i++)
nstrs += mms->nmatspec[i];
if (nstrs > 0)
mms->species_names = DBStringListToStringArray(tmpspecnames, &nstrs, !skipFirstSemicolon);
FREE(tmpspecnames);
}
if (tmpcolors != NULL)
{
if (nstrs == 0)
{
for (i = 0; i < mms->nmat; i++)
nstrs += mms->nmatspec[i];
}
if (nstrs > 0)
mms->speccolors = DBStringListToStringArray(tmpcolors, &nstrs, !skipFirstSemicolon);
FREE(tmpcolors);
}
}
return (mms);
}
/*----------------------------------------------------------------------
* Routine db_pdb_GetPointmesh
*
* Purpose
*
* Read a point-mesh object from a SILO file and return the
* SILO structure for this type.
*
* Modifications
*
* Al Leibee, Tue Apr 19 08:56:11 PDT 1994
* Added dtime.
*
* Robb Matzke, Mon Nov 14 15:49:15 EST 1994
* Device independence rewrite
*
* Robb Matzke, 27 Aug 1997
* The datatype is changed to DB_FLOAT only if it was DB_DOUBLE
* and force_single is turned on.
*
* Jeremy Meredith, Fri May 21 10:04:25 PDT 1999
* Added group_no.
*
* Sean Ahern, Wed Jun 14 17:21:36 PDT 2000
* Added a check to make sure the object is the right type.
*
* Mark C. Miller, Wed Feb 2 07:59:53 PST 2005
* Moved DBAlloc call to after PJ_GetObject. Added automatic
* var for PJ_GetObject to read into. Added check for return
* value of PJ_GetObject.
*
* Mark C. Miller, Fri Nov 13 15:26:38 PST 2009
* Add support for long long global node/zone numbers.
*
* Mark C. Miller, Sat Nov 14 20:28:34 PST 2009
* Changed how long long global node/zone numbers are supported
* from a int (bool), "llong_gnode|zoneno" to an int holding
* the actual datatype. The type is assumed int if it its
* value is zero or it does not exist. Otherwise, the type is
* is whatever is stored in gnznodtype member.
*--------------------------------------------------------------------*/
SILO_CALLBACK DBpointmesh *
db_pdb_GetPointmesh (DBfile *_dbfile, char const *objname)
{
DBpointmesh *pm = NULL;
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
PJcomplist tmp_obj;
static char *me = "db_pdb_GetPointmesh";
DBpointmesh tmppm;
PJcomplist *_tcl;
char *tmpannums = 0;
/*------------------------------------------------------------*/
/* Comp. Name Comp. Address Data Type */
/*------------------------------------------------------------*/
memset(&tmppm, 0, sizeof(DBpointmesh));
INIT_OBJ(&tmp_obj);
DEFINE_OBJ("block_no", &tmppm.block_no, DB_INT);
DEFINE_OBJ("group_no", &tmppm.group_no, DB_INT);
DEFINE_OBJ("cycle", &tmppm.cycle, DB_INT);
DEFINE_OBJ("time", &tmppm.time, DB_FLOAT);
DEFINE_OBJ("dtime", &tmppm.dtime, DB_DOUBLE);
DEFINE_OBJ("datatype", &tmppm.datatype, DB_INT);
DEFINE_OBJ("ndims", &tmppm.ndims, DB_INT);
DEFINE_OBJ("nels", &tmppm.nels, DB_INT);
DEFINE_OBJ("origin", &tmppm.origin, DB_INT);
DEFINE_OBJ("gnznodtype", &tmppm.gnznodtype, DB_INT);
DEFINE_OBJ("min_extents", tmppm.min_extents, DB_FLOAT);
DEFINE_OBJ("max_extents", tmppm.max_extents, DB_FLOAT);
DEFINE_OBJ("guihide", &tmppm.guihide, DB_INT);
DEFALL_OBJ("mrgtree_name", &tmppm.mrgtree_name, DB_CHAR);
if (DBGetDataReadMask2File(_dbfile) & DBPMCoords)
{
DEFALL_OBJ("coord0", &tmppm.coords[0], DB_FLOAT);
DEFALL_OBJ("coord1", &tmppm.coords[1], DB_FLOAT);
DEFALL_OBJ("coord2", &tmppm.coords[2], DB_FLOAT);
}
DEFALL_OBJ("label0", &tmppm.labels[0], DB_CHAR);
DEFALL_OBJ("label1", &tmppm.labels[1], DB_CHAR);
DEFALL_OBJ("label2", &tmppm.labels[2], DB_CHAR);
DEFALL_OBJ("units0", &tmppm.units[0], DB_CHAR);
DEFALL_OBJ("units1", &tmppm.units[1], DB_CHAR);
DEFALL_OBJ("units2", &tmppm.units[2], DB_CHAR);
if (DBGetDataReadMask2File(_dbfile) & DBPMGhostNodeLabels)
DEFALL_OBJ("ghost_node_labels", &tmppm.ghost_node_labels, DB_CHAR);
DEFALL_OBJ("alt_nodenum_vars", &tmpannums, DB_CHAR);
if (PJ_GetObject(dbfile->pdb, objname, &tmp_obj, DB_POINTMESH) < 0)
return NULL;
if ((pm = DBAllocPointmesh()) == NULL)
return NULL;
*pm = tmppm;
if (tmpannums != NULL)
{
pm->alt_nodenum_vars = DBStringListToStringArray(tmpannums, 0, !skipFirstSemicolon);
FREE(tmpannums);
}
/*
* Read the remainder of the object: loop over all values
* associated with this variable.
*/
pm->gnznodtype = tmppm.gnznodtype?tmppm.gnznodtype:DB_INT;
if (DBGetDataReadMask2File(_dbfile) & DBPMGlobNodeNo) {
INIT_OBJ(&tmp_obj);
DEFALL_OBJ("gnodeno", &tmppm.gnodeno, pm->gnznodtype);
pm->gnodeno = 0;
if (PJ_GetObject(dbfile->pdb, objname, &tmp_obj, 0)>=0)
pm->gnodeno = tmppm.gnodeno;
}
pm->id = 0;
pm->name = STRDUP(objname);
if (DB_DOUBLE==pm->datatype && PJ_InqForceSingle()) {
pm->datatype = DB_FLOAT;
}
return (pm);
}
/*----------------------------------------------------------------------
* Routine db_pdb_GetPointvar
*
* Purpose
*
* Read a point-var object from a SILO file and return the
* SILO structure for this type.
*
* Modifications
*
* Al Leibee, Tue Apr 19 08:56:11 PDT 1994
* Added dtime.
*
* Robb Matzke, Mon Nov 14 15:58:36 EST 1994
* Device independence rewrite.
*
* Sean Ahern, Fri May 24 17:35:58 PDT 1996
* Added smarts for figuring out the datatype, similar to
* db_pdb_GetUcdvar and db_pdb_GetQuadvar.
*
* Sean Ahern, Fri May 24 17:36:31 PDT 1996
* I corrected a possible bug where, if force single were on,
* the datatype would only be set to DB_FLOAT if the datatype
* had previously been DB_DOUBLE. This ignored things like
* DB_INT.
*
* Eric Brugger, Fri Sep 6 08:12:40 PDT 1996
* I removed the reading of "meshid" since it is not used and
* is actually stored as a string in the silo files not an
* integer. This caused a memory overwrite which only hurt
* things if the string was more than 104 characters.
*
* Sam Wookey, Wed Jul 1 16:21:09 PDT 1998
* Corrected the way we retrieve variables with nvals > 1.
*
* Sean Ahern, Wed Jun 14 17:22:54 PDT 2000
* Added a check to make sure the object is the right type.
*
* Sean Ahern, Thu Mar 1 12:28:07 PST 2001
* Added support for the dataReadMask stuff.
*
* Eric Brugger, Tue Mar 2 16:21:15 PST 2004
* Modified the routine to use _ptvalstr for the names of the
* components when the variable has more than one component.
* Each component name needs to be a seperate string for things
* to work properly, since a pointer to the string is stored and
* not a copy of the string.
*
* Mark C. Miller, Wed Feb 2 07:59:53 PST 2005
* Moved DBAlloc call to after PJ_GetObject. Added automatic
* var for PJ_GetObject to read into. Added check for return
* value of PJ_GetObject.
*
* Mark C. Miller, Thu Nov 5 16:15:49 PST 2009
* Added support for conserved/extensive options.
*
* Mark C. Miller, Tue Nov 10 09:14:01 PST 2009
* Added logic to control behavior of slash character swapping for
* windows/linux and skipping of first semicolon in calls to
* db_StringListToStringArray.
*--------------------------------------------------------------------*/
SILO_CALLBACK DBmeshvar *
db_pdb_GetPointvar (DBfile *_dbfile, char const *objname)
{
DBmeshvar *mv = NULL;
int i;
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
PJcomplist tmp_obj;
char tmp[256];
static char *me = "db_pdb_GetPointvar";
char *rpnames = NULL;
DBmeshvar tmpmv;
PJcomplist *_tcl;
/*------------------------------------------------------------*/
/* Comp. Name Comp. Address Data Type */
/*------------------------------------------------------------*/
memset(&tmpmv, 0, sizeof(DBmeshvar));
INIT_OBJ(&tmp_obj);
DEFINE_OBJ("cycle", &tmpmv.cycle, DB_INT);
DEFINE_OBJ("time", &tmpmv.time, DB_FLOAT);
DEFINE_OBJ("dtime", &tmpmv.dtime, DB_DOUBLE);
DEFINE_OBJ("datatype", &tmpmv.datatype, DB_INT);
DEFINE_OBJ("ndims", &tmpmv.ndims, DB_INT);
DEFINE_OBJ("nels", &tmpmv.nels, DB_INT);
DEFINE_OBJ("nvals", &tmpmv.nvals, DB_INT);
DEFINE_OBJ("origin", &tmpmv.origin, DB_INT);
DEFALL_OBJ("label", &tmpmv.label, DB_CHAR);
DEFALL_OBJ("units", &tmpmv.units, DB_CHAR);
DEFALL_OBJ("meshid",&tmpmv.meshname, DB_CHAR);
DEFINE_OBJ("guihide", &tmpmv.guihide, DB_INT);
DEFALL_OBJ("region_pnames", &rpnames, DB_CHAR);
DEFINE_OBJ("conserved", &tmpmv.conserved, DB_INT);
DEFINE_OBJ("extensive", &tmpmv.extensive, DB_INT);
DEFINE_OBJ("missing_value", &tmpmv.missing_value, DB_DOUBLE);
if (PJ_GetObject(dbfile->pdb, objname, &tmp_obj, DB_POINTVAR) < 0)
return NULL;
if ((mv = DBAllocMeshvar()) == NULL)
return NULL;
*mv = tmpmv;
/*
* Read the remainder of the object: loop over all values
* associated with this variable.
*/
if (mv->ndims>0 && mv->nels>0 && mv->nvals>0 && (DBGetDataReadMask2File(_dbfile) & DBPVData)) {
INIT_OBJ(&tmp_obj);
mv->vals = ALLOC_N(void*, mv->nvals);
if (mv->datatype == 0) {
if(mv->nvals == 1)
{
sprintf(tmp, "%s_data", objname);
}
else
{
sprintf(tmp, "%s_0_data", objname);
}
if ((mv->datatype = db_pdb_GetVarDatatype(dbfile->pdb, tmp)) < 0) {
/* Not found. Assume float. */
mv->datatype = DB_FLOAT;
}
}
if (PJ_InqForceSingle())
mv->datatype = DB_FLOAT;
if(mv->nvals == 1)
{
DEFALL_OBJ("_data", &mv->vals[0], DB_FLOAT);
}
else
{
for (i = 0; i < mv->nvals; i++)
{
DEFALL_OBJ(_ptvalstr[i], &mv->vals[i], DB_FLOAT);
}
}
PJ_GetObject(dbfile->pdb, objname, &tmp_obj, 0);
}
if (rpnames != NULL)
{
mv->region_pnames = DBStringListToStringArray(rpnames, 0, !skipFirstSemicolon);
FREE(rpnames);
}
if (mv->missing_value == DB_MISSING_VALUE_NOT_SET)
mv->missing_value = 0.0;
else if (mv->missing_value == 0.0)
mv->missing_value = DB_MISSING_VALUE_NOT_SET;
mv->id = 0;
mv->name = STRDUP(objname);
return (mv);
}
/*----------------------------------------------------------------------
* Routine db_pdb_GetQuadmesh
*
* Purpose
*
* Read a quad-mesh object from a SILO file and return the
* SILO structure for this type.
*
* Modifications
*
* Al Leibee, Tue Apr 19 08:56:11 PDT 1994
* Added dtime.
*
* Robb Matzke, Mon Nov 14 16:03:55 EST 1994
* Device independence rewrite.
*
* Sean Ahern, Fri Aug 1 13:24:28 PDT 1997
* Reformatted code through "indent".
*
* Sean Ahern, Fri Aug 1 13:24:45 PDT 1997
* Changed how the datatype is computed. It used to be unconditionally
* set to DB_FLOAT. Now we only do that if we're doing a force single.
*
* Jeremy Meredith, Fri May 21 10:04:25 PDT 1999
* Added group_no and baseindex[].
*
* Eric Brugger, Thu Aug 26 09:05:20 PDT 1999
* I modified the routine to set the base_index field base on
* the origin field when the base_index field is not defined in
* the file.
*
* Sean Ahern, Wed Jun 14 17:36:42 PDT 2000
* Added checks to make sure the object has the right type.
*
* Sean Ahern, Thu Mar 1 12:28:07 PST 2001
* Added support for the dataReadMask stuff.
*
* Mark C. Miller, Wed Feb 2 07:59:53 PST 2005
* Moved DBAlloc call to after PJ_GetObject. Added automatic
* var for PJ_GetObject to read into. Added check for return
* value of PJ_GetObject.
*--------------------------------------------------------------------*/
SILO_CALLBACK DBquadmesh *
db_pdb_GetQuadmesh (DBfile *_dbfile, char const *objname)
{
DBquadmesh *qm = NULL;
PJcomplist tmp_obj;
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
static char *me = "db_pdb_GetQuadmesh";
DBquadmesh tmpqm;
PJcomplist *_tcl;
char *tmpannum = 0, *tmpaznum = 0;
memset(&tmpqm, 0, sizeof(DBquadmesh));
tmpqm.base_index[0] = -99999;
/*------------------------------------------------------------*
* Comp. Name Comp. Address Data Type *
*------------------------------------------------------------*/
INIT_OBJ(&tmp_obj);
DEFINE_OBJ("block_no", &tmpqm.block_no, DB_INT);
DEFINE_OBJ("group_no", &tmpqm.group_no, DB_INT);
DEFINE_OBJ("cycle", &tmpqm.cycle, DB_INT);
DEFINE_OBJ("time", &tmpqm.time, DB_FLOAT);
DEFINE_OBJ("dtime", &tmpqm.dtime, DB_DOUBLE);
DEFINE_OBJ("datatype", &tmpqm.datatype, DB_INT);
DEFINE_OBJ("coord_sys", &tmpqm.coord_sys, DB_INT);
DEFINE_OBJ("coordtype", &tmpqm.coordtype, DB_INT);
DEFINE_OBJ("facetype", &tmpqm.facetype, DB_INT);
DEFINE_OBJ("planar", &tmpqm.planar, DB_INT);
DEFINE_OBJ("ndims", &tmpqm.ndims, DB_INT);
DEFINE_OBJ("nspace", &tmpqm.nspace, DB_INT);
DEFINE_OBJ("nnodes", &tmpqm.nnodes, DB_INT);
DEFINE_OBJ("major_order", &tmpqm.major_order, DB_INT);
DEFINE_OBJ("origin", &tmpqm.origin, DB_INT);
if (DBGetDataReadMask2File(_dbfile) & DBQMCoords)
{
DEFALL_OBJ("coord0", &tmpqm.coords[0], DB_FLOAT);
DEFALL_OBJ("coord1", &tmpqm.coords[1], DB_FLOAT);
DEFALL_OBJ("coord2", &tmpqm.coords[2], DB_FLOAT);
}
DEFALL_OBJ("label0", &tmpqm.labels[0], DB_CHAR);
DEFALL_OBJ("label1", &tmpqm.labels[1], DB_CHAR);
DEFALL_OBJ("label2", &tmpqm.labels[2], DB_CHAR);
DEFALL_OBJ("units0", &tmpqm.units[0], DB_CHAR);
DEFALL_OBJ("units1", &tmpqm.units[1], DB_CHAR);
DEFALL_OBJ("units2", &tmpqm.units[2], DB_CHAR);
DEFINE_OBJ("dims", tmpqm.dims, DB_INT);
DEFINE_OBJ("min_index", tmpqm.min_index, DB_INT);
DEFINE_OBJ("max_index", tmpqm.max_index, DB_INT);
DEFINE_OBJ("min_extents", tmpqm.min_extents, DB_FLOAT);
DEFINE_OBJ("max_extents", tmpqm.max_extents, DB_FLOAT);
DEFINE_OBJ("baseindex", tmpqm.base_index, DB_INT);
DEFINE_OBJ("guihide", &tmpqm.guihide, DB_INT);
DEFALL_OBJ("mrgtree_name", &tmpqm.mrgtree_name, DB_CHAR);
if (DBGetDataReadMask2File(_dbfile) & DBQMGhostNodeLabels)
DEFALL_OBJ("ghost_node_labels", &tmpqm.ghost_node_labels, DB_CHAR);
if (DBGetDataReadMask2File(_dbfile) & DBQMGhostZoneLabels)
DEFALL_OBJ("ghost_zone_labels", &tmpqm.ghost_zone_labels, DB_CHAR);
DEFALL_OBJ("alt_nodenum_vars", &tmpannum, DB_CHAR);
DEFALL_OBJ("alt_zonenum_vars", &tmpaznum, DB_CHAR);
/* The type passed here to PJ_GetObject is NULL because quadmeshes can have
* one of two types: DB_COLLINEAR or DB_NONCOLLINEAR. */
if (PJ_GetObject(dbfile->pdb, objname, &tmp_obj, DB_QUADMESH) < 0)
return NULL;
if ((qm = DBAllocQuadmesh()) == NULL)
return NULL;
*qm = tmpqm;
if (tmpannum)
{
qm->alt_nodenum_vars = DBStringListToStringArray(tmpannum, 0, !skipFirstSemicolon);
FREE(tmpannum);
}
if (tmpaznum)
{
qm->alt_zonenum_vars = DBStringListToStringArray(tmpaznum, 0, !skipFirstSemicolon);
FREE(tmpaznum);
}
/*
* If base_index was not set with the PJ_GetObject call, then
* set it based on origin.
*/
if (qm->base_index[0] == -99999)
{
int i;
qm->base_index[0] = 0;
for (i = 0; i < qm->ndims; i++)
{
qm->base_index[i] = qm->origin;
}
}
qm->id = 0;
qm->name = STRDUP(objname);
if (PJ_InqForceSingle())
qm->datatype = DB_FLOAT;
_DBQMSetStride(qm);
return (qm);
}
/*----------------------------------------------------------------------
* Routine db_pdb_GetQuadvar
*
* Purpose
*
* Read a quad-var object from a SILO file and return the
* SILO structure for this type.
*
* Modifications
*
* Al Leibee, Wed Jul 20 07:56:37 PDT 1994
* Added get of mixed zone data arrays.
*
* Al Leibee, Tue Apr 19 08:56:11 PDT 1994
* Added dtime.
*
* Robb Matzke, Mon Nov 14 17:02:44 EST 1994
* Device independence rewrite.
*
* Sean Ahern, Fri Sep 29 18:39:08 PDT 1995
* Requested DB_FLOATS instead of qv->datatype.
*
* Sean Ahern, Fri May 24 17:20:00 PDT 1996
* I corrected a possible bug where, if force single were on,
* the datatype would only be set to DB_FLOAT if the datatype
* had previously been DB_DOUBLE. This ignored things like
* DB_INT.
*
* Robb Matzke, 19 Jun 1997
* Reads the optional `ascii_labels' field.
*
* Sean Ahern, Wed Jun 14 17:23:49 PDT 2000
* Added a check to make sure the object is the right type.
*
* Sean Ahern, Thu Mar 1 12:28:07 PST 2001
* Added support for the dataReadMask stuff.
*
* Brad Whitlock, Wed Jul 21 12:05:56 PDT 2004
* I fixed a coding error that prevented PJ_GetObject from
* reading in labels and units for the quadvar.
* value of PJ_GetObject.
*
* Mark C. Miller, Wed Feb 2 07:59:53 PST 2005
* Moved DBAlloc call to after PJ_GetObject. Added automatic
* var for PJ_GetObject to read into. Added check for return
* value of PJ_GetObject.
*
* Mark C. Miller, Thu Nov 5 16:15:49 PST 2009
* Added support for conserved/extensive options.
*
* Mark C. Miller, Tue Nov 10 09:14:01 PST 2009
* Added logic to control behavior of slash character swapping for
* windows/linux and skipping of first semicolon in calls to
* db_StringListToStringArray.
*--------------------------------------------------------------------*/
SILO_CALLBACK DBquadvar *
db_pdb_GetQuadvar (DBfile *_dbfile, char const *objname)
{
DBquadvar *qv = NULL;
int i;
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
PJcomplist tmp_obj;
char tmp[256];
static char *me = "db_pdb_GetQuadvar";
char *rpnames = NULL;
DBquadvar tmpqv;
PJcomplist *_tcl;
/*------------------------------------------------------------*/
/* Comp. Name Comp. Address Data Type */
/*------------------------------------------------------------*/
memset(&tmpqv, 0, sizeof(DBquadvar));
INIT_OBJ(&tmp_obj);
/* Scalars */
DEFINE_OBJ("cycle", &tmpqv.cycle, DB_INT);
DEFINE_OBJ("time", &tmpqv.time, DB_FLOAT);
DEFINE_OBJ("dtime", &tmpqv.dtime, DB_DOUBLE);
DEFINE_OBJ("datatype", &tmpqv.datatype, DB_INT);
DEFINE_OBJ("centering", &tmpqv.centering, DB_INT);
DEFINE_OBJ("ndims", &tmpqv.ndims, DB_INT);
DEFINE_OBJ("major_order", &tmpqv.major_order, DB_INT);
DEFINE_OBJ("nels", &tmpqv.nels, DB_INT);
DEFINE_OBJ("nvals", &tmpqv.nvals, DB_INT);
DEFINE_OBJ("origin", &tmpqv.origin, DB_INT);
DEFINE_OBJ("mixlen", &tmpqv.mixlen, DB_INT);
DEFINE_OBJ("use_specmf", &tmpqv.use_specmf, DB_INT);
DEFINE_OBJ("ascii_labels", &tmpqv.ascii_labels, DB_INT);
DEFALL_OBJ("meshid", &tmpqv.meshname, DB_CHAR);
DEFINE_OBJ("guihide", &tmpqv.guihide, DB_INT);
DEFINE_OBJ("conserved", &tmpqv.conserved, DB_INT);
DEFINE_OBJ("conserved", &tmpqv.extensive, DB_INT);
DEFINE_OBJ("missing_value", &tmpqv.missing_value, DB_DOUBLE);
/* Arrays */
DEFINE_OBJ("min_index", tmpqv.min_index, DB_INT);
DEFINE_OBJ("max_index", tmpqv.max_index, DB_INT);
DEFINE_OBJ("dims", tmpqv.dims, DB_INT);
DEFINE_OBJ("align", tmpqv.align, DB_FLOAT);
DEFALL_OBJ("region_pnames", &rpnames, DB_CHAR);
/* Arrays that PJ_GetObject must allocate. */
DEFALL_OBJ("label", &tmpqv.label, DB_CHAR);
DEFALL_OBJ("units", &tmpqv.units, DB_CHAR);
if (PJ_GetObject(dbfile->pdb, objname, &tmp_obj, DB_QUADVAR) < 0)
return NULL;
/* Patch up "centering" if it wasn't present in file but align is.
Align only worked for node/zone centering. */
tmpqv.centering = db_fix_obsolete_centering(tmpqv.ndims, tmpqv.align, tmpqv.centering);
if ((qv = DBAllocQuadvar()) == NULL)
return NULL;
*qv = tmpqv;
/*
* Read the remainder of the object: loop over all values
* associated with this variable.
*/
if ((qv->ndims>0) && (qv->nvals > 0) && (DBGetDataReadMask2File(_dbfile) & DBQVData)) {
INIT_OBJ(&tmp_obj);
qv->vals = ALLOC_N(void*, qv->nvals);
if (qv->mixlen > 0) {
qv->mixvals = ALLOC_N(void*, qv->nvals);
}
if (qv->datatype == 0) {
strcpy(tmp, objname);
strcat(tmp, "_data");
if ((qv->datatype = db_pdb_GetVarDatatype(dbfile->pdb, tmp)) < 0) {
/* Not found. Assume float. */
qv->datatype = DB_FLOAT;
}
}
if (PJ_InqForceSingle())
qv->datatype = DB_FLOAT;
for (i = 0; i < qv->nvals; i++) {
DEFALL_OBJ(_valstr[i], &qv->vals[i], DB_FLOAT);
if (qv->mixlen > 0) {
DEFALL_OBJ(_mixvalstr[i], &qv->mixvals[i], DB_FLOAT);
}
}
PJ_GetObject(dbfile->pdb, objname, &tmp_obj, 0);
}
if (rpnames != NULL)
{
qv->region_pnames = DBStringListToStringArray(rpnames, 0, !skipFirstSemicolon);
FREE(rpnames);
}
if (qv->missing_value == DB_MISSING_VALUE_NOT_SET)
qv->missing_value = 0.0;
else if (qv->missing_value == 0.0)
qv->missing_value = DB_MISSING_VALUE_NOT_SET;
qv->id = 0;
qv->name = STRDUP(objname);
_DBQQCalcStride(qv->stride, qv->dims, qv->ndims, qv->major_order);
return (qv);
}
/*----------------------------------------------------------------------
* Routine DBGetUcdmesh
*
* Purpose
*
* Read a ucd-mesh structure from the given database.
*
* Programmer
*
* Jeffery W. Long, NSSD-B
*
* Parameters
*
* DBGetUcdmesh {Out} {Pointer to DBucdmesh structure}
* dbfile {In} {Pointer to current file}
* meshname {In} {Name of ucdmesh to read}
*
* Notes
*
* Modified
*
* Robb Matzke, Tue Nov 15 10:54:15 EST 1994
* Device independence rewrite.
*
* Eric Brugger, Wed Dec 11 13:01:52 PST 1996
* I plugged some memory leaks by freeing flname, zlname and
* elname at the end.
*
* Eric Brugger, Tue Oct 20 12:46:53 PDT 1998
* Modify the routine to read in the min_index and max_index
* fields of the zonelist.
*
* Eric Brugger, Tue Mar 30 11:17:58 PST 1999
* Modify the routine to read in the shapetype field of the
* zonelist. This field is optional.
*
* Jeremy Meredith, Fri May 21 10:04:25 PDT 1999
* Added group_no, gnodeno, and gzoneno.
*
* Sean Ahern, Wed Jun 14 17:24:07 PDT 2000
* Added a check to make sure the object is the right type.
*
* Sean Ahern, Thu Mar 1 12:28:07 PST 2001
* Added support for the dataReadMask stuff.
*
* Mark C. Miller, Wed Feb 2 07:59:53 PST 2005
* Moved DBAlloc calls to after PJ_GetObject. Added automatic
* vars for PJ_GetObject to read into. Added checks for return
* value of PJ_GetObject calls.
*
* Mark C. Miller, Fri Nov 13 15:26:38 PST 2009
* Add support for long long global node/zone numbers. Protect
* call to db_SplitShapelist if data read mask did not include
* zonelist info.
*
* Mark C. Miller, Sat Nov 14 20:28:34 PST 2009
* Changed how long long global node/zone numbers are supported
* from a int (bool), "llong_gnode|zoneno" to an int holding
* the actual datatype. The type is assumed int if it its
* value is zero or it does not exist. Otherwise, the type is
* is whatever is stored in gnznodtype member.
*--------------------------------------------------------------------*/
SILO_CALLBACK DBucdmesh *
db_pdb_GetUcdmesh (DBfile *_dbfile, char const *meshname)
{
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
DBucdmesh *um = NULL;
char *flname = NULL, *zlname = NULL, *elname = NULL,
*phzlname = NULL;
PJcomplist tmp_obj;
int lo_offset, hi_offset;
static char *me = "db_pdb_GetUcdmesh";
DBucdmesh tmpum;
PJcomplist *_tcl;
char *tmpannum = 0;
/*------------------------------------------------------------*/
/* Comp. Name Comp. Address Data Type */
/*------------------------------------------------------------*/
memset(&tmpum, 0, sizeof(DBucdmesh));
INIT_OBJ(&tmp_obj);
DEFINE_OBJ("block_no", &tmpum.block_no, DB_INT);
DEFINE_OBJ("group_no", &tmpum.group_no, DB_INT);
DEFINE_OBJ("cycle", &tmpum.cycle, DB_INT);
DEFINE_OBJ("time", &tmpum.time, DB_FLOAT);
DEFINE_OBJ("dtime", &tmpum.dtime, DB_DOUBLE);
DEFINE_OBJ("datatype", &tmpum.datatype, DB_INT);
DEFINE_OBJ("coord_sys", &tmpum.coord_sys, DB_INT);
DEFINE_OBJ("topo_dim", &tmpum.topo_dim, DB_INT);
DEFINE_OBJ("ndims", &tmpum.ndims, DB_INT);
DEFINE_OBJ("nnodes", &tmpum.nnodes, DB_INT);
DEFINE_OBJ("origin", &tmpum.origin, DB_INT);
DEFINE_OBJ("min_extents", tmpum.min_extents, DB_FLOAT);
DEFINE_OBJ("max_extents", tmpum.max_extents, DB_FLOAT);
if (DBGetDataReadMask2File(_dbfile) & DBUMCoords)
{
DEFALL_OBJ("coord0", &tmpum.coords[0], DB_FLOAT);
DEFALL_OBJ("coord1", &tmpum.coords[1], DB_FLOAT);
DEFALL_OBJ("coord2", &tmpum.coords[2], DB_FLOAT);
}
DEFALL_OBJ("label0", &tmpum.labels[0], DB_CHAR);
DEFALL_OBJ("label1", &tmpum.labels[1], DB_CHAR);
DEFALL_OBJ("label2", &tmpum.labels[2], DB_CHAR);
DEFALL_OBJ("units0", &tmpum.units[0], DB_CHAR);
DEFALL_OBJ("units1", &tmpum.units[1], DB_CHAR);
DEFALL_OBJ("units2", &tmpum.units[2], DB_CHAR);
DEFINE_OBJ("guihide", &tmpum.guihide, DB_INT);
DEFINE_OBJ("gnznodtype", &tmpum.gnznodtype, DB_INT);
/* Get SILO ID's for other UCD mesh components */
DEFALL_OBJ("facelist", &flname, DB_CHAR);
DEFALL_OBJ("zonelist", &zlname, DB_CHAR);
DEFALL_OBJ("edgelist", &elname, DB_CHAR);
/* Optional polyhedral zonelist */
DEFALL_OBJ("phzonelist", &phzlname, DB_CHAR);
DEFALL_OBJ("mrgtree_name", &tmpum.mrgtree_name, DB_CHAR);
DEFINE_OBJ("tv_connectivity", &tmpum.tv_connectivity, DB_INT);
DEFINE_OBJ("disjoint_mode", &tmpum.disjoint_mode, DB_INT);
if (DBGetDataReadMask2File(_dbfile) & DBUMGhostNodeLabels)
DEFALL_OBJ("ghost_node_labels", &tmpum.ghost_node_labels, DB_CHAR);
DEFALL_OBJ("alt_nodenum_vars", &tmpannum, DB_CHAR);
if (PJ_GetObject(dbfile->pdb, meshname, &tmp_obj, DB_UCDMESH) < 0)
return NULL;
if ((um = DBAllocUcdmesh()) == NULL)
return NULL;
*um = tmpum;
if (tmpannum)
{
um->alt_nodenum_vars = DBStringListToStringArray(tmpannum, 0, !skipFirstSemicolon);
FREE(tmpannum);
}
if (PJ_InqForceSingle() == TRUE)
um->datatype = DB_FLOAT;
um->id = 0;
um->name = STRDUP(meshname);
/* The value we store to the file for 'topo_dim' member is
designed such that zero indicates a value that was NOT
specified in the file. Since zero is a valid topological
dimension, when we store topo_dim to a file, we always
add 1. So, we have to subtract it here. However, this
data member was not being handled correctly in files
versions before 4.7. So, for older files, if topo_dim
is non-zero we just pass it without alteration. */
if (!DBFileVersionGE(_dbfile,4,5,1) || DBFileVersionGE(_dbfile, 4,7,0))
um->topo_dim = um->topo_dim - 1;
/* Optional global node number */
um->gnznodtype = um->gnznodtype?um->gnznodtype:DB_INT;
if (um->nnodes>0 && (DBGetDataReadMask2File(_dbfile) & DBUMGlobNodeNo)) {
INIT_OBJ(&tmp_obj);
DEFALL_OBJ("gnodeno", &tmpum.gnodeno, um->gnznodtype);
um->gnodeno = 0;
if (PJ_GetObject(dbfile->pdb, meshname, &tmp_obj, 0)>=0)
um->gnodeno = tmpum.gnodeno;
}
/* Read facelist, zonelist, and edgelist */
if (um->nnodes>0 && (flname != NULL && strlen(flname) > 0)
&& (DBGetDataReadMask2File(_dbfile) & DBUMFacelist))
{
DBfacelist tmpfaces;
memset(&tmpfaces, 0, sizeof(DBfacelist));
/*------------------------------------------------------------*/
/* Comp. Name Comp. Address Data Type */
/*------------------------------------------------------------*/
INIT_OBJ(&tmp_obj);
DEFINE_OBJ("ndims", &tmpfaces.ndims, DB_INT);
DEFINE_OBJ("nfaces", &tmpfaces.nfaces, DB_INT);
DEFINE_OBJ("lnodelist", &tmpfaces.lnodelist, DB_INT);
DEFINE_OBJ("nshapes", &tmpfaces.nshapes, DB_INT);
DEFINE_OBJ("ntypes", &tmpfaces.ntypes, DB_INT);
DEFINE_OBJ("origin", &tmpfaces.origin, DB_INT);
DEFALL_OBJ("nodelist", &tmpfaces.nodelist, DB_INT);
DEFALL_OBJ("shapesize", &tmpfaces.shapesize, DB_INT);
DEFALL_OBJ("shapecnt", &tmpfaces.shapecnt, DB_INT);
DEFALL_OBJ("typelist", &tmpfaces.typelist, DB_INT);
DEFALL_OBJ("types", &tmpfaces.types, DB_INT);
DEFALL_OBJ("zoneno", &tmpfaces.zoneno, DB_INT);
if (PJ_GetObject(dbfile->pdb, flname, &tmp_obj, 0) < 0)
{
DBFreeUcdmesh(um);
return NULL;
}
if ((um->faces = DBAllocFacelist()) == NULL)
{
DBFreeUcdmesh(um);
return NULL;
}
*(um->faces) = tmpfaces;
}
if (um->nnodes>0 && (zlname != NULL && strlen(zlname) > 0)
&& (DBGetDataReadMask2File(_dbfile) & DBUMZonelist))
{
DBzonelist tmpzones;
memset(&tmpzones, 0, sizeof(DBzonelist));
/*------------------------------------------------------------*/
/* Comp. Name Comp. Address Data Type */
/*------------------------------------------------------------*/
INIT_OBJ(&tmp_obj);
DEFINE_OBJ("ndims", &tmpzones.ndims, DB_INT);
DEFINE_OBJ("nzones", &tmpzones.nzones, DB_INT);
DEFINE_OBJ("nshapes", &tmpzones.nshapes, DB_INT);
DEFINE_OBJ("lnodelist", &tmpzones.lnodelist, DB_INT);
DEFINE_OBJ("origin", &tmpzones.origin, DB_INT);
DEFALL_OBJ("nodelist", &tmpzones.nodelist, DB_INT);
DEFALL_OBJ("shapetype", &tmpzones.shapetype, DB_INT);
DEFALL_OBJ("shapesize", &tmpzones.shapesize, DB_INT);
DEFALL_OBJ("shapecnt", &tmpzones.shapecnt, DB_INT);
DEFINE_OBJ("gnznodtype", &tmpzones.gnznodtype, DB_INT);
/*----------------------------------------------------------*/
/* These are optional so set them to their default values */
/*----------------------------------------------------------*/
lo_offset = 0;
hi_offset = 0;
DEFINE_OBJ("lo_offset", &lo_offset, DB_INT);
DEFINE_OBJ("hi_offset", &hi_offset, DB_INT);
if (DBGetDataReadMask2File(_dbfile) & DBZonelistGhostZoneLabels)
DEFALL_OBJ("ghost_zone_labels", &tmpzones.ghost_zone_labels, DB_CHAR);
if (PJ_GetObject(dbfile->pdb, zlname, &tmp_obj, DB_ZONELIST) < 0)
{
DBFreeUcdmesh(um);
return NULL;
}
if ((um->zones = DBAllocZonelist()) == NULL)
{
DBFreeUcdmesh(um);
return NULL;
}
*(um->zones) = tmpzones;
um->zones->min_index = lo_offset;
um->zones->max_index = um->zones->nzones - hi_offset - 1;
/*----------------------------------------------------------*/
/* If we have ghost zones, split any group of shapecnt so */
/* all the shapecnt refer to all real zones or all ghost */
/* zones. This will make dealing with ghost zones easier */
/* for applications. */
/*----------------------------------------------------------*/
if ((lo_offset != 0 || hi_offset != 0) &&
DBGetDataReadMask2File(_dbfile) & DBZonelistInfo)
{
db_SplitShapelist (um);
}
/* Read optional global zone numbers */
um->zones->gnznodtype = um->zones->gnznodtype?um->zones->gnznodtype:DB_INT;
if (DBGetDataReadMask2File(_dbfile) & DBZonelistGlobZoneNo) {
INIT_OBJ(&tmp_obj);
DEFALL_OBJ("gzoneno", &tmpzones.gzoneno, um->zones->gnznodtype);
um->zones->gzoneno = 0;
if (PJ_GetObject(dbfile->pdb, zlname, &tmp_obj, 0)>=0)
um->zones->gzoneno = tmpzones.gzoneno;
}
}
if (um->nnodes>0 && elname && *elname) {
DBedgelist tmpedges;
memset(&tmpedges, 0, sizeof(DBedgelist));
/*------------------------------------------------------------*/
/* Comp. Name Comp. Address Data Type */
/*------------------------------------------------------------*/
INIT_OBJ(&tmp_obj);
DEFINE_OBJ("ndims", &tmpedges.ndims, DB_INT);
DEFINE_OBJ("nedges", &tmpedges.nedges, DB_INT);
DEFINE_OBJ("origin", &tmpedges.origin, DB_INT);
DEFALL_OBJ("edge_beg", &tmpedges.edge_beg, DB_INT);
DEFALL_OBJ("edge_end", &tmpedges.edge_end, DB_INT);
if (PJ_GetObject(dbfile->pdb, elname, &tmp_obj, 0) < 0)
{
DBFreeUcdmesh(um);
return NULL;
}
if ((um->edges = DBAllocEdgelist()) == NULL)
{
DBFreeUcdmesh(um);
return NULL;
}
*(um->edges) = tmpedges;
}
if (um->nnodes>0 && phzlname && *phzlname && (DBGetDataReadMask2File(_dbfile) & DBUMZonelist)) {
um->phzones = db_pdb_GetPHZonelist(_dbfile, phzlname);
}
FREE (zlname);
FREE (flname);
FREE (elname);
FREE (phzlname);
return (um);
}
/*----------------------------------------------------------------------
* Routine db_pdb_GetUcdvar
*
* Purpose
*
* Read a ucd-var object from a SILO file and return the
* SILO structure for this type.
*
* Modifications
*
* Al Leibee, Tue Apr 19 08:56:11 PDT 1994
* Added dtime.
*
* Robb Matzke, Tue Nov 15 11:05:44 EST 1994
* Device independence rewrite.
*
* Sean Ahern, Tue Dec 5 16:38:55 PST 1995
* Added PDB logic to determine datatype
* if it's not in the SILO file.
*
* Eric Brugger, Thu May 23 10:02:33 PDT 1996
* I corrected a bug where the datatype was being incorrectly set
* to DOUBLE, if force single were on and the datatype was
* specified in the silo file.
*
* Sean Ahern, Fri May 24 17:20:00 PDT 1996
* I corrected a possible bug where, if force single were on,
* the datatype would only be set to DB_FLOAT if the datatype
* had previously been DB_DOUBLE. This ignored things like
* DB_INT.
*
* Eric Brugger, Fri Sep 6 08:12:40 PDT 1996
* I removed the reading of "meshid" since it is not used and
* is actually stored as a string in the silo files not an
* integer. This caused a memory overwrite which only hurt
* things if the string was more than 48 characters.
*
* Sean Ahern, Wed Jun 14 17:24:41 PDT 2000
* Added a check to make sure the object is the right type.
*
* Sean Ahern, Thu Mar 1 12:28:07 PST 2001
* Added support for the dataReadMask stuff.
*
* Mark C. Miller, Wed Feb 2 07:59:53 PST 2005
* Moved DBAlloc call to after PJ_GetObject. Added automatic
* var for PJ_GetObject to read into. Added check for return
* value of PJ_GetObject.
*
* Brad Whitlock, Wed Jan 18 15:07:57 PST 2006
* Added optional ascii_labels.
*
* Mark C. Miller, Thu Nov 5 16:15:49 PST 2009
* Added support for conserved/extensive options.
*
* Mark C. Miller, Tue Nov 10 09:14:01 PST 2009
* Added logic to control behavior of slash character swapping for
* windows/linux and skipping of first semicolon in calls to
* db_StringListToStringArray.
*--------------------------------------------------------------------*/
SILO_CALLBACK DBucdvar *
db_pdb_GetUcdvar (DBfile *_dbfile, char const *objname)
{
DBucdvar *uv = NULL;
int i;
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
PJcomplist tmp_obj;
char tmp[256];
static char *me = "db_pdb_GetUcdvar";
char *rpnames = NULL;
DBucdvar tmpuv;
PJcomplist *_tcl;
/*------------------------------------------------------------*/
/* Comp. Name Comp. Address Data Type */
/*------------------------------------------------------------*/
memset(&tmpuv, 0, sizeof(DBucdvar));
INIT_OBJ(&tmp_obj);
DEFINE_OBJ("cycle", &tmpuv.cycle, DB_INT);
DEFINE_OBJ("time", &tmpuv.time, DB_FLOAT);
DEFINE_OBJ("dtime", &tmpuv.dtime, DB_DOUBLE);
DEFINE_OBJ("datatype", &tmpuv.datatype, DB_INT);
DEFINE_OBJ("centering", &tmpuv.centering, DB_INT);
DEFINE_OBJ("ndims", &tmpuv.ndims, DB_INT);
DEFINE_OBJ("nels", &tmpuv.nels, DB_INT);
DEFINE_OBJ("nvals", &tmpuv.nvals, DB_INT);
DEFINE_OBJ("origin", &tmpuv.origin, DB_INT);
DEFINE_OBJ("mixlen", &tmpuv.mixlen, DB_INT);
DEFINE_OBJ("use_specmf", &tmpuv.use_specmf, DB_INT);
DEFINE_OBJ("ascii_labels", &tmpuv.ascii_labels, DB_INT);
DEFALL_OBJ("label", &tmpuv.label, DB_CHAR);
DEFALL_OBJ("units", &tmpuv.units, DB_CHAR);
DEFALL_OBJ("meshid",&tmpuv.meshname, DB_CHAR);
DEFINE_OBJ("guihide", &tmpuv.guihide, DB_INT);
DEFALL_OBJ("region_pnames", &rpnames, DB_CHAR);
DEFINE_OBJ("conserved", &tmpuv.conserved, DB_INT);
DEFINE_OBJ("extensive", &tmpuv.extensive, DB_INT);
DEFINE_OBJ("missing_value", &tmpuv.missing_value, DB_DOUBLE);
if (PJ_GetObject(dbfile->pdb, objname, &tmp_obj, DB_UCDVAR) < 0)
return NULL;
if ((uv = DBAllocUcdvar()) == NULL)
return NULL;
*uv = tmpuv;
/*
* Read the remainder of the object: loop over all values
* associated with this variable.
*/
if ((uv->nvals > 0) && (DBGetDataReadMask2File(_dbfile) & DBUVData)) {
INIT_OBJ(&tmp_obj);
uv->vals = ALLOC_N(void*, uv->nvals);
if (uv->mixlen > 0) {
uv->mixvals = ALLOC_N(void*, uv->nvals);
}
if (uv->datatype == 0) {
strcpy(tmp, objname);
strcat(tmp, "_data");
if ((uv->datatype = db_pdb_GetVarDatatype(dbfile->pdb, tmp)) < 0) {
/* Not found. Assume float. */
uv->datatype = DB_FLOAT;
}
}
if (PJ_InqForceSingle())
uv->datatype = DB_FLOAT;
for (i = 0; i < uv->nvals; i++) {
DEFALL_OBJ(_valstr[i], &uv->vals[i], DB_FLOAT);
if (uv->mixlen > 0) {
DEFALL_OBJ(_mixvalstr[i], &uv->mixvals[i], DB_FLOAT);
}
}
PJ_GetObject(dbfile->pdb, objname, &tmp_obj, 0);
}
if (rpnames != NULL)
{
uv->region_pnames = DBStringListToStringArray(rpnames, 0, !skipFirstSemicolon);
FREE(rpnames);
}
if (uv->missing_value == DB_MISSING_VALUE_NOT_SET)
uv->missing_value = 0.0;
else if (uv->missing_value == 0.0)
uv->missing_value = DB_MISSING_VALUE_NOT_SET;
uv->id = 0;
uv->name = STRDUP(objname);
return (uv);
}
/*----------------------------------------------------------------------
* Routine DBGetCsgmesh
*
* Purpose
*
* Read a CSG mesh structure from the given database.
*
* Programmer
*
* Mark C. Miller
* August 9, 2005
*
* Modifications:
*
* Mark C. Miller, Tue Nov 10 09:14:01 PST 2009
* Added logic to control behavior of slash character swapping for
* windows/linux and skipping of first semicolon in calls to
* db_StringListToStringArray.
*--------------------------------------------------------------------*/
SILO_CALLBACK DBcsgmesh *
db_pdb_GetCsgmesh (DBfile *_dbfile, char const *meshname)
{
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
DBcsgmesh *csgm = NULL;
char *zlname = NULL, *tmpbndnames = NULL;
PJcomplist tmp_obj;
static char *me = "db_pdb_GetCsgmesh";
DBcsgmesh tmpcsgm;
PJcomplist *_tcl;
/*------------------------------------------------------------*/
/* Comp. Name Comp. Address Data Type */
/*------------------------------------------------------------*/
memset(&tmpcsgm, 0, sizeof(DBcsgmesh));
INIT_OBJ(&tmp_obj);
DEFINE_OBJ("block_no", &tmpcsgm.block_no, DB_INT);
DEFINE_OBJ("group_no", &tmpcsgm.group_no, DB_INT);
DEFINE_OBJ("cycle", &tmpcsgm.cycle, DB_INT);
DEFINE_OBJ("time", &tmpcsgm.time, DB_FLOAT);
DEFINE_OBJ("dtime", &tmpcsgm.dtime, DB_DOUBLE);
DEFINE_OBJ("lcoeffs", &tmpcsgm.lcoeffs, DB_INT);
DEFINE_OBJ("datatype", &tmpcsgm.datatype, DB_INT);
DEFINE_OBJ("ndims", &tmpcsgm.ndims, DB_INT);
DEFINE_OBJ("nbounds", &tmpcsgm.nbounds, DB_INT);
DEFINE_OBJ("origin", &tmpcsgm.origin, DB_INT);
DEFINE_OBJ("min_extents", tmpcsgm.min_extents, DB_DOUBLE);
DEFINE_OBJ("max_extents", tmpcsgm.max_extents, DB_DOUBLE);
DEFALL_OBJ("label0", &tmpcsgm.labels[0], DB_CHAR);
DEFALL_OBJ("label1", &tmpcsgm.labels[1], DB_CHAR);
DEFALL_OBJ("label2", &tmpcsgm.labels[2], DB_CHAR);
DEFALL_OBJ("units0", &tmpcsgm.units[0], DB_CHAR);
DEFALL_OBJ("units1", &tmpcsgm.units[1], DB_CHAR);
DEFALL_OBJ("units2", &tmpcsgm.units[2], DB_CHAR);
DEFALL_OBJ("csgzonelist", &zlname, DB_CHAR);
DEFINE_OBJ("guihide", &tmpcsgm.guihide, DB_INT);
DEFALL_OBJ("mrgtree_name", &tmpcsgm.mrgtree_name, DB_CHAR);
DEFINE_OBJ("tv_connectivity", &tmpcsgm.tv_connectivity, DB_INT);
DEFINE_OBJ("disjoint_mode", &tmpcsgm.disjoint_mode, DB_INT);
if (DBGetDataReadMask2File(_dbfile) & DBCSGMBoundaryInfo)
{
DEFALL_OBJ("typeflags", &tmpcsgm.typeflags, DB_INT);
DEFALL_OBJ("bndids", &tmpcsgm.bndids, DB_INT);
}
/* Optional boundary names */
if (DBGetDataReadMask2File(_dbfile) & DBCSGMBoundaryNames)
DEFALL_OBJ("bndnames", &tmpbndnames, DB_CHAR);
if (PJ_GetObject(dbfile->pdb, (char*) meshname, &tmp_obj, DB_CSGMESH) < 0)
return NULL;
/* now that we know the object's data type, we can correctly
read the coeffs */
if ((DBGetDataReadMask2File(_dbfile) & DBCSGMBoundaryInfo) && (tmpcsgm.lcoeffs > 0))
{
INIT_OBJ(&tmp_obj);
if (DB_DOUBLE == tmpcsgm.datatype && PJ_InqForceSingle()) {
tmpcsgm.datatype = DB_FLOAT;
}
DEFALL_OBJ("coeffs", &tmpcsgm.coeffs, tmpcsgm.datatype);
PJ_GetObject(dbfile->pdb, (char*) meshname, &tmp_obj, 0);
}
if ((tmpbndnames != NULL) && (tmpcsgm.nbounds > 0))
{
tmpcsgm.bndnames = DBStringListToStringArray(tmpbndnames, &tmpcsgm.nbounds, !skipFirstSemicolon);
FREE(tmpbndnames);
}
tmpcsgm.name = STRDUP(meshname);
if ((tmpcsgm.nbounds > 0 && zlname && *zlname &&
(DBGetDataReadMask2File(_dbfile) & DBCSGMZonelist)))
tmpcsgm.zones = db_pdb_GetCSGZonelist(_dbfile, zlname);
if ((csgm = DBAllocCsgmesh()) == NULL)
return NULL;
*csgm = tmpcsgm;
FREE (zlname);
return (csgm);
}
/*----------------------------------------------------------------------
* Routine db_pdb_GetCsgvar
*
* Purpose
*
* Read a csg-var object from a SILO file and return the
* SILO structure for this type.
*
* Programmer
*
* Mark C. Miller, August 10, 2005
*
* Modifications:
*
* Mark C. Miller, Tue Nov 10 09:14:01 PST 2009
* Added logic to control behavior of slash character swapping for
* windows/linux and skipping of first semicolon in calls to
* db_StringListToStringArray.
*--------------------------------------------------------------------*/
SILO_CALLBACK DBcsgvar *
db_pdb_GetCsgvar (DBfile *_dbfile, char const *objname)
{
DBcsgvar *csgv = NULL;
int i;
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
PJcomplist tmp_obj;
char tmp[256];
static char *me = "db_pdb_GetCsgvar";
char *rpnames = NULL;
DBcsgvar tmpcsgv;
PJcomplist *_tcl;
memset(&tmpcsgv, 0, sizeof(DBcsgvar));
INIT_OBJ(&tmp_obj);
DEFINE_OBJ("cycle", &tmpcsgv.cycle, DB_INT);
DEFINE_OBJ("time", &tmpcsgv.time, DB_FLOAT);
DEFINE_OBJ("dtime", &tmpcsgv.dtime, DB_DOUBLE);
DEFINE_OBJ("datatype", &tmpcsgv.datatype, DB_INT);
DEFINE_OBJ("centering", &tmpcsgv.centering, DB_INT);
DEFINE_OBJ("nels", &tmpcsgv.nels, DB_INT);
DEFINE_OBJ("nvals", &tmpcsgv.nvals, DB_INT);
DEFINE_OBJ("ascii_labels", &tmpcsgv.ascii_labels, DB_INT);
DEFALL_OBJ("label", &tmpcsgv.label, DB_CHAR);
DEFALL_OBJ("units", &tmpcsgv.units, DB_CHAR);
DEFALL_OBJ("meshid",&tmpcsgv.meshname, DB_CHAR);
DEFINE_OBJ("guihide", &tmpcsgv.guihide, DB_INT);
DEFALL_OBJ("region_pnames", &rpnames, DB_CHAR);
DEFINE_OBJ("missing_value", &tmpcsgv.missing_value, DB_DOUBLE);
if (PJ_GetObject(dbfile->pdb, (char*) objname, &tmp_obj, DB_CSGVAR) < 0)
return NULL;
/*
* Read the remainder of the object: loop over all values
* associated with this variable.
*/
if ((tmpcsgv.nvals > 0) && (DBGetDataReadMask2File(_dbfile) & DBCSGVData)) {
INIT_OBJ(&tmp_obj);
tmpcsgv.vals = ALLOC_N(void *, tmpcsgv.nvals);
if (tmpcsgv.datatype == 0) {
strcpy(tmp, objname);
strcat(tmp, "_data");
if ((tmpcsgv.datatype = db_pdb_GetVarDatatype(dbfile->pdb, tmp)) < 0) {
/* Not found. Assume float. */
tmpcsgv.datatype = DB_FLOAT;
}
}
if ((tmpcsgv.datatype == DB_DOUBLE) && PJ_InqForceSingle())
tmpcsgv.datatype = DB_FLOAT;
for (i = 0; i < tmpcsgv.nvals; i++) {
DEFALL_OBJ(_valstr[i], &tmpcsgv.vals[i], tmpcsgv.datatype);
}
PJ_GetObject(dbfile->pdb, (char*) objname, &tmp_obj, 0);
}
if (rpnames != NULL)
{
tmpcsgv.region_pnames = DBStringListToStringArray(rpnames, 0, !skipFirstSemicolon);
FREE(rpnames);
}
if (tmpcsgv.missing_value == DB_MISSING_VALUE_NOT_SET)
tmpcsgv.missing_value = 0.0;
else if (tmpcsgv.missing_value == 0.0)
tmpcsgv.missing_value = DB_MISSING_VALUE_NOT_SET;
if ((csgv = DBAllocCsgvar()) == NULL)
return NULL;
tmpcsgv.name = STRDUP(objname);
*csgv = tmpcsgv;
return (csgv);
}
/*-------------------------------------------------------------------------
* Function: db_pdb_GetFacelist
*
* Purpose: Reads a facelist object from a SILO file.
*
* Return: Success: A pointer to a new facelist structure.
*
* Failure: NULL
*
* Programmer: Robb Matzke
* Friday, January 14, 2000
*
* Modifications:
*
* Sean Ahern, Wed Jun 14 17:24:58 PDT 2000
* Added a check to make sure the object is the right type.
*
* Sean Ahern, Thu Mar 1 12:28:07 PST 2001
* Added support for the dataReadMask stuff.
*
* Mark C. Miller, Wed Feb 2 07:59:53 PST 2005
* Moved DBAlloc call to after PJ_GetObject. Added automatic
* var for PJ_GetObject to read into. Added check for return
* value of PJ_GetObject.
*-------------------------------------------------------------------------*/
SILO_CALLBACK DBfacelist *
db_pdb_GetFacelist(DBfile *_dbfile, char const *objname)
{
DBfacelist *fl=NULL;
PJcomplist tmp_obj;
DBfile_pdb *dbfile = (DBfile_pdb*)_dbfile;
static char *me = "db_pdb_GetFacelist";
DBfacelist tmpfl;
PJcomplist *_tcl;
/*------------------------------------------------------------*/
/* Comp. Name Comp. Address Data Type */
/*------------------------------------------------------------*/
memset(&tmpfl, 0, sizeof(DBfacelist));
INIT_OBJ(&tmp_obj);
DEFINE_OBJ("ndims", &tmpfl.ndims, DB_INT);
DEFINE_OBJ("nfaces", &tmpfl.nfaces, DB_INT);
DEFINE_OBJ("origin", &tmpfl.origin, DB_INT);
DEFINE_OBJ("lnodelist", &tmpfl.lnodelist, DB_INT);
DEFINE_OBJ("nshapes", &tmpfl.nshapes, DB_INT);
DEFINE_OBJ("ntypes", &tmpfl.ntypes, DB_INT);
if (DBGetDataReadMask2File(_dbfile) & DBFacelistInfo)
{
DEFALL_OBJ("nodelist", &tmpfl.nodelist, DB_INT);
DEFALL_OBJ("shapecnt", &tmpfl.shapecnt, DB_INT);
DEFALL_OBJ("shapesize", &tmpfl.shapesize, DB_INT);
DEFALL_OBJ("typelist", &tmpfl.typelist, DB_INT);
DEFALL_OBJ("types", &tmpfl.types, DB_INT);
DEFALL_OBJ("nodeno", &tmpfl.nodeno, DB_INT);
DEFALL_OBJ("zoneno", &tmpfl.zoneno, DB_INT);
}
if (PJ_GetObject(dbfile->pdb, objname, &tmp_obj, DB_FACELIST) < 0)
return NULL;
if ((fl = DBAllocFacelist()) == NULL)
return NULL;
*fl = tmpfl;
return fl;
}
/*-------------------------------------------------------------------------
* Function: db_pdb_GetZonelist
*
* Purpose: Reads a zonelist object from a SILO file.
*
* Return: Success: A pointer to a new facelist structure.
*
* Failure: NULL
*
* Programmer: Robb Matzke
* Friday, January 14, 2000
*
* Modifications:
*
* Sean Ahern, Wed Jun 14 17:25:16 PDT 2000
* Added a check to make sure the object is the right type.
*
* Sean Ahern, Thu Mar 1 12:28:07 PST 2001
* Added support for the dataReadMask stuff.
*
* Mark C. Miller, Wed Feb 2 07:59:53 PST 2005
* Moved DBAlloc call to after PJ_GetObject. Added automatic
* var for PJ_GetObject to read into. Added check for return
* value of PJ_GetObject.
*
* Mark C. Miller, Fri Nov 13 15:26:38 PST 2009
* Add support for long long global node/zone numbers.
*
* Mark C. Miller, Sat Nov 14 20:28:34 PST 2009
* Changed how long long global node/zone numbers are supported
* from a int (bool), "llong_gnode|zoneno" to an int holding
* the actual datatype. The type is assumed int if it its
* value is zero or it does not exist. Otherwise, the type is
* is whatever is stored in gnznodtype member.
*-------------------------------------------------------------------------*/
SILO_CALLBACK DBzonelist *
db_pdb_GetZonelist(DBfile *_dbfile, char const *objname)
{
DBzonelist *zl = NULL;
PJcomplist tmp_obj;
DBfile_pdb *dbfile = (DBfile_pdb*)_dbfile;
static char *me = "db_pdb_GetZonelist";
DBzonelist tmpzl;
PJcomplist *_tcl;
char *tmpaznum = 0;
/*------------------------------------------------------------*/
/* Comp. Name Comp. Address Data Type */
/*------------------------------------------------------------*/
memset(&tmpzl, 0, sizeof(DBzonelist));
INIT_OBJ(&tmp_obj);
DEFINE_OBJ("ndims", &tmpzl.ndims, DB_INT);
DEFINE_OBJ("nzones", &tmpzl.nzones, DB_INT);
DEFINE_OBJ("origin", &tmpzl.origin, DB_INT);
DEFINE_OBJ("lnodelist", &tmpzl.lnodelist, DB_INT);
DEFINE_OBJ("nshapes", &tmpzl.nshapes, DB_INT);
DEFINE_OBJ("min_index", &tmpzl.min_index, DB_INT);
DEFINE_OBJ("max_index", &tmpzl.max_index, DB_INT);
DEFINE_OBJ("gnznodtype", &tmpzl.gnznodtype, DB_INT);
if (DBGetDataReadMask2File(_dbfile) & DBZonelistInfo)
{
DEFALL_OBJ("shapecnt", &tmpzl.shapecnt, DB_INT);
DEFALL_OBJ("shapesize", &tmpzl.shapesize, DB_INT);
DEFALL_OBJ("shapetype", &tmpzl.shapetype, DB_INT);
DEFALL_OBJ("nodelist", &tmpzl.nodelist, DB_INT);
DEFALL_OBJ("zoneno", &tmpzl.zoneno, DB_INT);
}
if (DBGetDataReadMask2File(_dbfile) & DBZonelistGhostZoneLabels)
DEFALL_OBJ("ghost_zone_labels", &tmpzl.ghost_zone_labels, DB_CHAR);
DEFALL_OBJ("alt_zonenum_vars", &tmpaznum, DB_CHAR);
if (PJ_GetObject(dbfile->pdb, objname, &tmp_obj, DB_ZONELIST) < 0)
return NULL;
if ((zl = DBAllocZonelist()) == NULL)
return NULL;
*zl = tmpzl;
if (tmpaznum)
{
zl->alt_zonenum_vars = DBStringListToStringArray(tmpaznum, 0, !skipFirstSemicolon);
FREE(tmpaznum);
}
/* optional global zone numbers */
zl->gnznodtype = zl->gnznodtype?zl->gnznodtype:DB_INT;
if (DBGetDataReadMask2File(_dbfile) & DBZonelistGlobZoneNo) {
INIT_OBJ(&tmp_obj);
DEFALL_OBJ("gzoneno", &tmpzl.gzoneno, zl->gnznodtype);
zl->gzoneno = 0;
if (PJ_GetObject(dbfile->pdb, objname, &tmp_obj, 0)>=0)
zl->gzoneno = tmpzl.gzoneno;
}
return zl;
}
/*-------------------------------------------------------------------------
* Function: db_pdb_GetPHZonelist
*
* Purpose: Reads a DBphzonelist object from a SILO file.
*
* Return: Success: A pointer to a new facelist structure.
*
* Failure: NULL
*
* Programmer: Robb Matzke
* Friday, January 14, 2000
*
* Modifications:
*
* Sean Ahern, Wed Jun 14 17:25:16 PDT 2000
* Added a check to make sure the object is the right type.
*
* Sean Ahern, Thu Mar 1 12:28:07 PST 2001
* Added support for the dataReadMask stuff.
*
* Mark C. Miller, Wed Feb 2 07:59:53 PST 2005
* Moved DBAlloc call to after PJ_GetObject. Added automatic
* var for PJ_GetObject to read into. Added check for return
* value of PJ_GetObject.
*
* Mark C. Miller, Fri Nov 13 15:26:38 PST 2009
* Add support for long long global node/zone numbers.
*
* Mark C. Miller, Sat Nov 14 20:28:34 PST 2009
* Changed how long long global node/zone numbers are supported
* from a int (bool), "llong_gnode|zoneno" to an int holding
* the actual datatype. The type is assumed int if it its
* value is zero or it does not exist. Otherwise, the type is
* is whatever is stored in gnznodtype member.
*-------------------------------------------------------------------------*/
SILO_CALLBACK DBphzonelist *
db_pdb_GetPHZonelist(DBfile *_dbfile, char const *objname)
{
DBphzonelist *phzl = NULL;
PJcomplist tmp_obj;
DBfile_pdb *dbfile = (DBfile_pdb*)_dbfile;
static char *me = "db_pdb_GetPHZonelist";
DBphzonelist tmpphzl;
PJcomplist *_tcl;
char *tmpaznum = 0;
/*------------------------------------------------------------*/
/* Comp. Name Comp. Address Data Type */
/*------------------------------------------------------------*/
memset(&tmpphzl, 0, sizeof(DBphzonelist));
INIT_OBJ(&tmp_obj);
DEFINE_OBJ("nfaces", &tmpphzl.nfaces, DB_INT);
DEFINE_OBJ("lnodelist", &tmpphzl.lnodelist, DB_INT);
DEFINE_OBJ("nzones", &tmpphzl.nzones, DB_INT);
DEFINE_OBJ("lfacelist", &tmpphzl.lfacelist, DB_INT);
DEFINE_OBJ("origin", &tmpphzl.origin, DB_INT);
DEFINE_OBJ("lo_offset", &tmpphzl.lo_offset, DB_INT);
DEFINE_OBJ("hi_offset", &tmpphzl.hi_offset, DB_INT);
DEFINE_OBJ("gnznodtype", &tmpphzl.gnznodtype, DB_INT);
if (DBGetDataReadMask2File(_dbfile) & DBZonelistInfo)
{
DEFALL_OBJ("nodecnt", &tmpphzl.nodecnt, DB_INT);
DEFALL_OBJ("nodelist", &tmpphzl.nodelist, DB_INT);
DEFALL_OBJ("extface", &tmpphzl.extface, DB_CHAR);
DEFALL_OBJ("facecnt", &tmpphzl.facecnt, DB_INT);
DEFALL_OBJ("facelist", &tmpphzl.facelist, DB_INT);
DEFALL_OBJ("zoneno", &tmpphzl.zoneno, DB_INT);
}
if (DBGetDataReadMask2File(_dbfile) & DBZonelistGhostZoneLabels)
DEFALL_OBJ("ghost_zone_labels", &tmpphzl.ghost_zone_labels, DB_CHAR);
DEFALL_OBJ("alt_zonenum_vars", &tmpaznum, DB_CHAR);
if (PJ_GetObject(dbfile->pdb, objname, &tmp_obj, DB_PHZONELIST) < 0)
return NULL;
if ((phzl = DBAllocPHZonelist()) == NULL)
return NULL;
*phzl = tmpphzl;
if (tmpaznum)
{
phzl->alt_zonenum_vars = DBStringListToStringArray(tmpaznum, 0, !skipFirstSemicolon);
FREE(tmpaznum);
}
/* optional global zone numbers */
phzl->gnznodtype = phzl->gnznodtype?phzl->gnznodtype:DB_INT;
if (DBGetDataReadMask2File(_dbfile) & DBZonelistGlobZoneNo) {
INIT_OBJ(&tmp_obj);
DEFALL_OBJ("gzoneno", &tmpphzl.gzoneno, phzl->gnznodtype);
phzl->gzoneno = 0;
if (PJ_GetObject(dbfile->pdb, objname, &tmp_obj, 0)>=0)
phzl->gzoneno = tmpphzl.gzoneno;
}
return phzl;
}
/*-------------------------------------------------------------------------
* Function: db_pdb_GetCSGZonelist
*
* Purpose: Reads a CSG zonelist object from a SILO file.
*
* Return: Success: A pointer to a new facelist structure.
*
* Failure: NULL
*
* Programmer: Mark C. Miller
* August 9, 2005
*
* Modifications:
*
* Mark C. Miller, Tue Nov 10 09:14:01 PST 2009
* Added logic to control behavior of slash character swapping for
* windows/linux and skipping of first semicolon in calls to
* db_StringListToStringArray.
*-------------------------------------------------------------------------*/
SILO_CALLBACK DBcsgzonelist *
db_pdb_GetCSGZonelist(DBfile *_dbfile, char const *objname)
{
char *tmprnames = 0, *tmpznames = 0, *tmpaznums = 0;
DBcsgzonelist *zl = NULL;
PJcomplist tmp_obj;
DBfile_pdb *dbfile = (DBfile_pdb*)_dbfile;
static char *me = "db_pdb_GetCSGZonelist";
DBcsgzonelist tmpzl;
PJcomplist *_tcl;
/*------------------------------------------------------------*/
/* Comp. Name Comp. Address Data Type */
/*------------------------------------------------------------*/
memset(&tmpzl, 0, sizeof(DBcsgzonelist));
INIT_OBJ(&tmp_obj);
DEFINE_OBJ("nregs", &tmpzl.nregs, DB_INT);
DEFINE_OBJ("origin", &tmpzl.origin, DB_INT);
DEFINE_OBJ("lxform", &tmpzl.lxform, DB_INT);
DEFINE_OBJ("datatype", &tmpzl.datatype, DB_INT);
DEFINE_OBJ("nzones", &tmpzl.nzones, DB_INT);
DEFINE_OBJ("min_index", &tmpzl.min_index, DB_INT);
DEFINE_OBJ("max_index", &tmpzl.max_index, DB_INT);
if (DBGetDataReadMask2File(_dbfile) & DBZonelistInfo)
{
DEFALL_OBJ("typeflags", &tmpzl.typeflags, DB_INT);
DEFALL_OBJ("leftids", &tmpzl.leftids, DB_INT);
DEFALL_OBJ("rightids", &tmpzl.rightids, DB_INT);
DEFALL_OBJ("zonelist", &tmpzl.zonelist, DB_INT);
}
if (DBGetDataReadMask2File(_dbfile) & DBCSGZonelistRegNames)
DEFALL_OBJ("regnames", &tmprnames, DB_CHAR);
if (DBGetDataReadMask2File(_dbfile) & DBCSGZonelistZoneNames)
DEFALL_OBJ("zonenames", &tmpznames, DB_CHAR);
DEFALL_OBJ("alt_zonenum_vars", &tmpaznums, DB_CHAR);
if (PJ_GetObject(dbfile->pdb, (char*) objname, &tmp_obj, DB_CSGZONELIST) < 0)
return NULL;
/* now that we know the object's data type, we can correctly
read the xforms */
if ((DBGetDataReadMask2File(_dbfile) & DBZonelistInfo) && (tmpzl.lxform > 0))
{
INIT_OBJ(&tmp_obj);
if (DB_DOUBLE == tmpzl.datatype && PJ_InqForceSingle()) {
tmpzl.datatype = DB_FLOAT;
}
DEFALL_OBJ("xform", &tmpzl.xform, tmpzl.datatype);
PJ_GetObject(dbfile->pdb, (char*) objname, &tmp_obj, 0);
}
if ((tmprnames != NULL) && (tmpzl.nregs > 0))
{
tmpzl.regnames = DBStringListToStringArray(tmprnames, &tmpzl.nregs, !skipFirstSemicolon);
FREE(tmprnames);
}
if ((tmpznames != NULL) && (tmpzl.nzones > 0))
{
tmpzl.zonenames = DBStringListToStringArray(tmpznames, &tmpzl.nzones, !skipFirstSemicolon);
FREE(tmpznames);
}
if (tmpaznums != NULL)
{
tmpzl.alt_zonenum_vars = DBStringListToStringArray(tmpaznums, 0, !skipFirstSemicolon);
FREE(tmpaznums);
}
if ((zl = DBAllocCSGZonelist()) == NULL)
return NULL;
*zl = tmpzl;
return zl;
}
/*-------------------------------------------------------------------------
* Function: db_pdb_GetVar
*
* Purpose: Allocates space for a variable and reads the variable
* from the database.
*
* Return: Success: Pointer to variable data
*
* Failure: NULL
*
* Programmer: robb@cloud
* Tue Nov 15 11:12:23 EST 1994
*
* Modifications:
* Sean Ahern, Sun Oct 1 03:13:19 PDT 1995
* Made "me" static.
*-------------------------------------------------------------------------*/
SILO_CALLBACK void *
db_pdb_GetVar (DBfile *_dbfile, char const *name)
{
static char *me = "db_pdb_GetVar";
char *data;
int n;
/* Find out how long (in bytes) requested variable is. */
if (0 == (n = DBGetVarByteLength(_dbfile, name))) {
db_perror(name, E_NOTFOUND, me);
return NULL;
}
/* Read it and return. */
data = ALLOC_N(char, n);
if (DBReadVar(_dbfile, name, data) < 0) {
db_perror("DBReadVar", E_CALLFAIL, me);
FREE(data);
return (NULL);
}
return data;
}
/*-------------------------------------------------------------------------
* Function: db_pdb_GetVarByteLength
*
* Purpose: Returns the in-memory length of the given variable in bytes.
*
* Return: Success: length of variable in bytes
*
* Failure: -1
*
* Programmer: robb@cloud
* Tue Nov 15 11:45:42 EST 1994
*
* Modifications:
*-------------------------------------------------------------------------*/
SILO_CALLBACK int
db_pdb_GetVarByteLength (DBfile *_dbfile, char const *varname)
{
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
int number, size;
db_pdb_getvarinfo(dbfile->pdb, varname, NULL, &number, &size, 0);
return number * size;
}
/*-------------------------------------------------------------------------
* Function: db_pdb_GetVarDims
*
* Purpose: Returns the size of each dimension.
*
* Return: Success: Number of dimensions not to exceed MAXDIMS.
* The dimension sizes are written to DIMS.
*
* Failure: -1
*
* Programmer: Robb Matzke
* robb@maya.nuance.mdn.com
* Mar 6 1997
*
* Modifications:
* Sean Ahern, Wed Apr 12 11:14:38 PDT 2000
* Removed the last two parameters to PJ_inquire_entry because they
* weren't being used.
*-------------------------------------------------------------------------*/
SILO_CALLBACK int
db_pdb_GetVarDims (DBfile *_dbfile, char const *varname, int maxdims, int *dims)
{
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
static char *me = "db_pdb_GetVarDims";
syment *ep;
dimdes *dd;
int i;
ep = PJ_inquire_entry (dbfile->pdb, varname);
if (!ep) return db_perror ("PJ_inquire_entry", E_CALLFAIL, me);
for (i=0, dd=ep->dimensions; i<maxdims && dd; i++, dd=dd->next) {
dims[i] = dd->number;
}
return i;
}
/*-------------------------------------------------------------------------
* Function: db_pdb_GetVarType
*
* Purpose: Returns the data type ID (DB_INT, DB_FLOAT, etc) of the
* variable.
*
* Return: Success: type ID
*
* Failure: -1
*
* Programmer: matzke@viper
* Thu Dec 22 09:00:39 PST 1994
*
* Modifications:
*-------------------------------------------------------------------------*/
SILO_CALLBACK int
db_pdb_GetVarType (DBfile *_dbfile, char const *varname)
{
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
int number, size;
char type_name[256];
db_pdb_getvarinfo(dbfile->pdb, varname, type_name, &number, &size, 0);
return db_GetDatatypeID(type_name);
}
/*-------------------------------------------------------------------------
* Function: db_pdb_GetVarLength
*
* Purpose: Returns the number of elements in the requested variable.
*
* Return: Success: number of elements
*
* Failure: -1
*
* Programmer: robb@cloud
* Tue Nov 15 12:06:36 EST 1994
*
* Modifications:
*-------------------------------------------------------------------------*/
SILO_CALLBACK int
db_pdb_GetVarLength (DBfile *_dbfile, char const *varname)
{
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
int number, size;
db_pdb_getvarinfo(dbfile->pdb, varname, NULL, &number, &size, 0);
return number;
}
/*-------------------------------------------------------------------------
* Function: db_pdb_InqMeshname
*
* Purpose: Returns the name of a mesh associated with a mesh-variable.
* Caller must allocate space for mesh name.
*
* Return: Success: 0
*
* Failure: -1
*
* Programmer: robb@cloud
* Tue Nov 15 12:10:59 EST 1994
*
* Modifications:
* Katherine Price, Fri Jun 2 08:58:54 PDT 1995
* Added error return code.
*
* Sean Ahern, Mon Jun 24 13:30:53 PDT 1996
* Fixed a memory leak.
*-------------------------------------------------------------------------*/
SILO_CALLBACK int
db_pdb_InqMeshname (DBfile *_dbfile, char const *vname, char *mname)
{
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
void *v;
if ((v = PJ_GetComponent(dbfile->pdb, vname, "meshid"))) {
if (mname)
strcpy(mname, (char *)v);
FREE(v);
return 0;
}
FREE(v);
return -1;
}
/*-------------------------------------------------------------------------
* Function: db_pdb_InqMeshtype
*
* Purpose: returns the mesh type.
*
* Return: Success: mesh type
*
* Failure: -1
*
* Programmer: robb@cloud
* Tue Nov 15 12:16:12 EST 1994
*
* Modifications:
* Eric Brugger, Thu Feb 9 12:54:37 PST 1995
* I modified the routine to read elements of the group structure
* as "abc->type" instead of "abc.type".
*
* Sean Ahern, Sun Oct 1 03:13:44 PDT 1995
* Made "me" static.
*
* Eric Brugger, Fri Dec 4 12:45:22 PST 1998
* Added code to free ctype to eliminate a memory leak.
*-------------------------------------------------------------------------*/
SILO_CALLBACK int
db_pdb_InqMeshtype (DBfile *_dbfile, char const *mname)
{
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
char tmp[256], *ctype;
int type;
static char *me = "db_pdb_InqMeshtype";
sprintf(tmp, "%s->type", mname);
if (!PJ_read(dbfile->pdb, tmp, &ctype)) {
return db_perror("PJ_read", E_CALLFAIL, me);
}
type = DBGetObjtypeTag(ctype);
SCFREE(ctype);
return type;
}
/*----------------------------------------------------------------------
* Routine db_pdb_InqVarExists
*
* Purpose
* Check whether the variable exists and return non-zero if so,
* and 0 if not
*
* Programmer
* Sean Ahern, Thu Jul 20 12:04:39 PDT 1995
*
* Modifications
* Sean Ahern, Sun Oct 1 03:14:03 PDT 1995
* Made "me" static.
*
* Sean Ahern, Wed Apr 12 11:14:38 PDT 2000
* Removed the last two parameters to PJ_inquire_entry because they
* weren't being used.
*--------------------------------------------------------------------*/
SILO_CALLBACK int
db_pdb_InqVarExists (DBfile *_dbfile, char const *varname)
{
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
syment *ep;
ep = PJ_inquire_entry(dbfile->pdb, varname);
if (!ep)
return (0);
else
return (1);
}
/*-------------------------------------------------------------------------
* Function: db_pdb_ReadVar
*
* Purpose: Reads a variable into the given space.
*
* Return: Success: 0
*
* Failure: -1
*
* Programmer: robb@cloud
* Mon Nov 21 21:05:07 EST 1994
*
* Modifications:
* Sean Ahern, Sun Oct 1 03:18:45 PDT 1995
* Made "me" static.
*-------------------------------------------------------------------------*/
SILO_CALLBACK int
db_pdb_ReadVar (DBfile *_dbfile, char const *vname, void *result)
{
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
static char *me = "db_pdb_ReadVar";
if (!PJ_read(dbfile->pdb, vname, result)) {
return db_perror("PJ_read", E_CALLFAIL, me);
}
return 0;
}
/*-------------------------------------------------------------------------
* Function: db_pdb_ReadVarSlice
*
* Purpose: Reads a slice of a variable into the given space.
*
* Return: Success: 0
*
* Failure: -1
*
* Programmer: brugger@sgibird
* Thu Feb 16 08:45:00 PST 1995
*
* Modifications:
* Sean Ahern, Sun Oct 1 03:19:03 PDT 1995
* Made "me" static.
*-------------------------------------------------------------------------*/
SILO_CALLBACK int
db_pdb_ReadVarSlice (DBfile *_dbfile, char const *vname, int const *offset, int const *length,
int const *stride, int ndims, void *result)
{
int i;
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
long ind[3 * MAXDIMS_VARWRITE];
static char *me = "db_pdb_ReadVarSlice";
for (i = 0; i < ndims && i < MAXDIMS_VARWRITE; i++) {
ind[3 * i] = offset[i];
ind[3 * i + 1] = offset[i] + length[i] - 1;
ind[3 * i + 2] = stride[i];
}
if (!PJ_read_alt(dbfile->pdb, (char*)vname, result, ind)) {
return db_perror("PJ_read_alt", E_CALLFAIL, me);
}
return 0;
}
#define FSTRS1(A) ={#A}
#define FSTRS2(A,B) ={#A,#B}
#define FSTRS3(A,B,C) ={#A,#B,#C}
#define FSTRS4(A,B,C,D) ={#A,#B,#C,#D}
#define FSTRS5(A,B,C,D,E) ={#A,#B,#C,#D,#E}
#define DSNAMES_CASE(OTYPE, FMTSTRS) \
case OTYPE: \
{ \
int i, j, pass; \
char const *fmtstrs[] FMTSTRS; \
PJgroup *group=NULL; \
if (!PJ_get_group(pdbfile, name, &group)) \
{ \
PJ_rel_group(group); \
return 0; \
} \
for (pass = 0; pass < 2; pass++) \
{ \
if (pass == 1) \
{ \
_dsnames = (char **) malloc(n * sizeof(char*)); \
n = 0; \
} \
for (i=0; i<group->ncomponents; i++) \
{ \
for (j=0; j < sizeof(fmtstrs)/sizeof(fmtstrs[0]); j++) \
{ \
char tmp[32]; \
snprintf(tmp, sizeof(tmp), fmtstrs[j], n); \
if (!strcmp(group->comp_names[i], tmp)) \
{ \
if (pass == 1) \
_dsnames[n] = _db_safe_strdup(group->pdb_names[i]); \
n++; \
} \
} \
} \
if (n == 0) \
{ \
PJ_rel_group(group); \
return 0; \
} \
} \
PJ_rel_group(group); \
break; \
}
PRIVATE int
db_pdb_get_obj_dsnames(DBfile *_dbfile, char const *name, DBObjectType *otype,
int *dscount, char ***dsnames)
{
int n = 0;
char **_dsnames = 0;
static char const *me = "db_pdb_get_obj_dsnames";
DBObjectType _otype = db_pdb_InqVarType(_dbfile, name);
PDBfile *pdbfile = ((DBfile_pdb *)_dbfile)->pdb;
*otype = _otype;
switch (_otype)
{
DSNAMES_CASE(DB_CURVE, FSTRS2(xvals,yvals));
DSNAMES_CASE(DB_QUADVAR, FSTRS2(value%d,mixed_value%d));
DSNAMES_CASE(DB_QUADMESH, FSTRS1(coord%d));
DSNAMES_CASE(DB_QUADCURV, FSTRS1(coord%d));
DSNAMES_CASE(DB_QUADRECT, FSTRS1(coord%d));
DSNAMES_CASE(DB_UCDVAR, FSTRS1(value%d));
DSNAMES_CASE(DB_UCDMESH, FSTRS1(coord%d));
DSNAMES_CASE(DB_POINTMESH, FSTRS1(coord%d));
DSNAMES_CASE(DB_POINTVAR, FSTRS2(_data,%d_data));
DSNAMES_CASE(DB_MULTIMESH, FSTRS4(meshtypes,meshnames,extents,zonecounts));
DSNAMES_CASE(DB_MULTIVAR, FSTRS3(vartypes,varnames,extents));
DSNAMES_CASE(DB_MULTIMAT, FSTRS3(matnames,mixlens,matcounts));
DSNAMES_CASE(DB_MULTIMATSPECIES, FSTRS1(specnames));
DSNAMES_CASE(DB_MATERIAL, FSTRS5(matlist,mix_next,mix_vf,mix_mat,mix_zone));
DSNAMES_CASE(DB_MATSPECIES, FSTRS4(speclist,species_mf,nmatspec,mix_speclist));
DSNAMES_CASE(DB_ZONELIST, FSTRS4(nodelist,shapecnt,shapesize,shapetype));
DSNAMES_CASE(DB_FACELIST, FSTRS4(nodelist,shapecnt,shapesize,zoneno));
DSNAMES_CASE(DB_ARRAY, FSTRS3(elemnames,elemlengths,values));
case DB_VARIABLE:
{
n = 1;
_dsnames = (char**) malloc(n*sizeof(char*));
_dsnames[0] = _db_safe_strdup(name);
break;
}
}
*dscount = n;
*dsnames = _dsnames;
return 1;
}
PRIVATE int
db_pdb_ReadDenseArrayVals(DBfile *_dbfile, char const *vname, int objtype,
int dscount, char const * const *dsnames, int nvals, int ndims, int const *indices,
void **result, int *ncomps, int *nitems)
{
static char const *me = "db_pdb_ReadDenseArrayVals";
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
int db_type, db_type_size;
int i, j, k;
char *p;
db_type = db_pdb_GetVarType(_dbfile, dsnames[0]);
if (db_type < 0)
return db_perror(vname, E_CALLFAIL, me);
db_type_size = db_GetMachDataSize(db_type);
/* If result space isn't already allocated, allocate it */
if (!*result)
{
*result = malloc(nvals*dscount*db_type_size);
if (!*result)
return db_perror(vname, E_NOMEM, me);
}
/* Loop to read the equivalent value(s) from each dataset */
p = (char *) *result;
for (j = 0; j < nvals; j++)
{
for (i = 0; i < dscount; i++)
{
if (objtype == DB_QUADRECT) /* really dscount sep. 1D arrays */
{
long ind[3];
ind[0] = indices[j*ndims+i];
ind[1] = indices[j*ndims+i];
ind[2] = 1;
if (!PJ_read_alt(dbfile->pdb, (char*)dsnames[i], p, ind))
return db_perror("PJ_read_alt", E_CALLFAIL, me);
}
else
{
long ind[3 * MAXDIMS_VARWRITE];
for (k = 0; k < ndims && k < MAXDIMS_VARWRITE; k++)
{
ind[3 * k ] = indices[j*ndims+k];
ind[3 * k + 1] = indices[j*ndims+k];
ind[3 * k + 2] = 1;
}
if (!PJ_read_alt(dbfile->pdb, (char*)dsnames[i], p, ind))
return db_perror("PJ_read_alt", E_CALLFAIL, me);
}
p += db_type_size;
}
}
if (ncomps) *ncomps = dscount;
if (nitems) *nitems = nvals;
return 0;
}
PRIVATE int
db_pdb_ReadMatVals(DBfile *_dbfile, char const *vname, int objtype,
int dscount, char const * const *dsnames, int nvals, int ndims, int const *indices,
void **result, int *ncomps, int *nitems)
{
static char const *me = "db_pdb_ReadMatVals";
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
int i, have_mixed = 0;
int *matlist_result = 0;
DBmaterial *origmat = 0, *mat = 0;
unsigned long long oldmask;
/* 0 1 2 3 4 */
/* FSTRS5(matlist,mix_next,mix_vf,mix_mat,mix_zone)); */
oldmask = DBSetDataReadMask2File(_dbfile, DBNone);
origmat = db_pdb_GetMaterial(_dbfile, vname);
DBSetDataReadMask2File(_dbfile, oldmask);
/* Do partial I/O on matlist */
if (db_pdb_ReadDenseArrayVals(_dbfile, vname, objtype, 1,
(char const * const *) &dsnames[0],
nvals, ndims, indices, (void**) &matlist_result, 0, nitems) < 0)
return db_perror(dsnames[0], E_CALLFAIL, me);
if (!*result)
{
*result = DBAllocMaterial();
if (!*result)
return db_perror(vname, E_NOMEM, me);
}
mat = *result;
mat->matlist = matlist_result;
mat->ndims = 1;
mat->dims[0] = nvals;
/* If none are negative values, we're done */
for (i = 0; i < *nitems && !have_mixed; i++)
have_mixed = matlist_result[i] < 0;
if (!have_mixed)
{
if (ncomps) *ncomps = 1;
if (nitems) *nitems = 1;
return 0;
}
/* For negative matlist entries, need to follow the links for mix_next, mix_mat, mix_vf */
for (i = 0; i < *nitems; i++)
{
long ind[3];
int mixidx;
int mix_next, mix_mat, mix_zone;
double const dbl_max = DBL_MAX;
int const halfn = (int const) sizeof(double)/2;
double mix_vf = dbl_max;
float *fp = (float*) &mix_vf;
void const *halfa = (void*) &mix_vf;
void const *halfb = (void*) ((char*) &mix_vf + halfn);
void const *halfc = (void*) &dbl_max;
void const *halfd = (void*) ((char*) &dbl_max + halfn);
if (mat->matlist[i] >= 0) continue;
mixidx = -(mat->matlist[i]);
printf("mixidx = %d\n", mixidx);
printf("dsname[1] = \"%s\"\n", dsnames[1]);
printf("dsname[2] = \"%s\"\n", dsnames[2]);
printf("dsname[3] = \"%s\"\n", dsnames[3]);
while (mixidx != 0)
{
ind[0] = mixidx-1; ind[1] = mixidx-1; ind[2] = 1;
PJ_read_alt(dbfile->pdb, (char*)dsnames[2], &mix_next, ind);
printf("ind[0]=%ld,ind[1]=%ld,ind[2]=%ld\n",ind[0],ind[1],ind[2]);
printf("mix_next = %d\n",mix_next);
PJ_read_alt(dbfile->pdb, (char*)dsnames[1], &mix_vf, ind);
if (memcmp(halfa,halfc,halfn) == 0 || memcmp(halfb,halfd,halfn) == 0)
{
printf("looks like float, *fp=%f\n",*fp);
mix_vf = (double) *fp;
}
PJ_read_alt(dbfile->pdb, (char*)dsnames[3], &mix_mat, ind);
mixidx = mix_next;
printf("got mat=%d, vf = %f, mixidx=%d\n", mix_mat, mix_vf, mixidx);
mix_vf = dbl_max;
#if 0
if (dscount > 4)
PJ_read_alt(dbfile->pdb, (char*)dsnames[4], &mix_zone, ind);
#endif
}
}
return db_perror(vname, E_CALLFAIL, me);
}
SILO_CALLBACK int
db_pdb_ReadVarVals(DBfile *_dbfile, char const *vname, int mode,
int nvals, int ndims, void const *_indices, void **result,
int *ncomps, int *nitems)
{
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
static char const *me = "db_pdb_ReadVarVals";
DBObjectType objtype;
int dscount = 0;
char **dsnames = 0;
int db_type, db_type_size;
int i, j, k;
char *p;
int const *indices = (int const *) _indices;
if (db_pdb_get_obj_dsnames(_dbfile, vname, &objtype, &dscount, &dsnames) < 0)
return db_perror(vname, E_CALLFAIL, me);
if (dscount <= 0)
return db_perror(vname, E_CALLFAIL, me);
/* There are two basic cases here. One is a simple (dense) array.
The other is some non-dense "object" (e.g. the coordinates of
a rectilinear mesh, a zonelist, a material, etc.) These latter
objects cannot be handled by PDB's simple partial I/O interface
and require special handling. All the special cases we handle
in the switch. */
switch (objtype)
{
case DB_MATERIAL: return db_pdb_ReadMatVals(_dbfile, vname, objtype, dscount,
(char const * const *) dsnames,
nvals, ndims, indices, result, ncomps, nitems);
#if 0
case DB_ZONELIST: return db_pdb_ReadZonelistVals(_dbfile, vname, dscount, dsnames,
nvals, ndims, indices, result, ncomps, nitems);
#endif
default: return db_pdb_ReadDenseArrayVals(_dbfile, vname, objtype, dscount,
(char const * const *) dsnames, nvals, ndims, indices,
result, ncomps, nitems);
}
return db_perror(vname, E_CALLFAIL, me);
}
/*-------------------------------------------------------------------------
* Function: db_pdb_SetDir
*
* Purpose: Sets the current directory within the database.
*
* Return: Success: 0
*
* Failure: -1
*
* Programmer: robb@cloud
* Mon Nov 21 21:10:37 EST 1994
*
* Modifications:
* Eric Brugger, Fri Jan 27 08:27:46 PST 1995
* I changed the call DBGetToc to db_pdb_GetToc.
*
* Robb Matzke, Fri Feb 24 10:15:54 EST 1995
* The directory ID (pub.dirid) is no longer set since PJ_pwd_id()
* has gone away.
*
* Robb Matzke, Tue Mar 7 10:40:02 EST 1995
* I changed the call db_pdb_GetToc to DBNewToc.
*
* Sean Ahern, Sun Oct 1 03:19:19 PDT 1995
* Made "me" static.
*
* Sean Ahern, Mon Jul 1 14:06:08 PDT 1996
* Turned off the PJgroup cache when we change directories.
*-------------------------------------------------------------------------*/
SILO_CALLBACK int
db_pdb_SetDir (DBfile *_dbfile, char const *path)
{
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
static char *me = "db_pdb_SetDir";
char error_message[256];
if (1 == lite_PD_cd(dbfile->pdb, (char*) path)) {
dbfile->pub.dirid = 0;
/* We've changed directories, so we can't cache PJgroups any more */
PJ_NoCache();
/* Must make new table-of-contents since dir has changed */
db_FreeToc(_dbfile);
}
else {
sprintf(error_message,"\"%s\" ***%s***",path,lite_PD_err);
return db_perror(error_message, E_NOTDIR, me);
}
return 0;
}
/*-------------------------------------------------------------------------
* Function: db_pdb_Filters
*
* Purpose: Output the name of this device driver to the specified
* stream.
*
* Return: Success: 0
*
* Failure: never fails
*
* Programmer: robb@cloud
* Tue Mar 7 11:11:59 EST 1995
*
* Modifications:
*
* Hank Childs, Thu Jan 6 13:48:40 PST 2000
* Put in lint directive for unused arguments.
*-------------------------------------------------------------------------*/
/* ARGSUSED */
SILO_CALLBACK int
db_pdb_Filters (DBfile *dbfile, FILE *stream)
{
fprintf(stream, "PDB Device Driver\n");
return 0;
}
/*-------------------------------------------------------------------------
* Function: db_pdb_GetComponentNames
*
* Purpose: Returns the component names for the specified object.
* Each component name also has a variable name under which
* the component value is stored in the data file. The
* COMP_NAMES and FILE_NAMES output arguments will point to
* an array of pointers to names. Each name as well as the
* two arrays will be allocated with `malloc'.
*
* Return: Success: Number of components found for the
* specified object.
*
* Failure: zero.
*
* Programmer: Robb Matzke
* robb@callisto.nuance.mdn.com
* May 20, 1996
*
* Modifications:
*
* Lisa J. Roberts, Tue Nov 23 09:39:49 PST 1999
* Changed strdup to safe_strdup.
*-------------------------------------------------------------------------*/
SILO_CALLBACK int
db_pdb_GetComponentNames (DBfile *_dbfile, char const *objname,
char ***comp_names, char ***file_names)
{
PJgroup *group = NULL ;
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile ;
int i ;
syment *ep ;
if (comp_names) *comp_names = NULL ;
if (file_names) *file_names = NULL ;
/*
* First make sure that the specified object is type "Group *", otherwise
* we'll get a segmentation fault deep within the PDB library!
*/
ep = lite_PD_inquire_entry (dbfile->pdb, (char*)objname, TRUE, NULL) ;
if (!ep || strcmp(ep->type, "Group *")) return 0 ;
/*
* OK, now we can go ahead and get the group, but watch out
* for the empty group.
*/
if (!PJ_get_group (dbfile->pdb, objname, &group)) return 0 ;
if (!group) return 0 ;
if (group->ncomponents<=0) return 0 ;
/*
* Copy the group component names and pdb names into the
* output arrays after allocating them.
*/
if (comp_names)
*comp_names = (char**)malloc(group->ncomponents * sizeof(char *)) ;
if (file_names)
*file_names = (char**)malloc(group->ncomponents * sizeof(char *)) ;
for (i=0; i<group->ncomponents; i++) {
if (comp_names) (*comp_names)[i] = _db_safe_strdup (group->comp_names[i]) ;
if (file_names) (*file_names)[i] = _db_safe_strdup (group->pdb_names[i]) ;
}
return group->ncomponents ;
}
/*----------------------------------------------------------------------
* Routine DBGetMrgtree
*
* Purpose
*
* Read mrg tree structure from the given database.
*
* Programmer
*
* Mark C. Miller, Wed Oct 10 13:08:36 PDT 2007
*
* Modifications:
*
* Mark C. Miller, Tue Nov 10 09:14:01 PST 2009
* Added logic to control behavior of slash character swapping for
* windows/linux and skipping of first semicolon in calls to
* db_StringListToStringArray.
*--------------------------------------------------------------------*/
SILO_CALLBACK DBmrgtree *
db_pdb_GetMrgtree(DBfile *_dbfile, char const *mrgtree_name)
{
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
DBmrgtree *tree = NULL;
PJcomplist tmp_obj;
static char *me = "db_pdb_GetMrgtree";
DBmrgtree tmptree;
DBmrgtnode **ltree;
int root, num_nodes, i, j, n;
int *intArray = 0;
char *s, **strArray = 0;
char *mrgv_onames = 0, *mrgv_rnames = 0;
PJcomplist *_tcl;
/*------------------------------------------------------------*/
/* Comp. Name Comp. Address Data Type */
/*------------------------------------------------------------*/
memset(&tmptree, 0, sizeof(DBmrgtree));
INIT_OBJ(&tmp_obj);
/* read header and scalars data only first */
DEFINE_OBJ("src_mesh_type", &tmptree.src_mesh_type, DB_INT);
DEFINE_OBJ("type_info_bits", &tmptree.type_info_bits, DB_INT);
DEFINE_OBJ("num_nodes", &tmptree.num_nodes, DB_INT);
DEFINE_OBJ("root", &root, DB_FLOAT);
DEFALL_OBJ("src_mesh_name", &tmptree.src_mesh_name, DB_CHAR);
DEFALL_OBJ("scalars", &intArray, DB_INT);
DEFALL_OBJ("mrgvar_onames", &mrgv_onames, DB_CHAR);
DEFALL_OBJ("mrgvar_rnames", &mrgv_rnames, DB_CHAR);
if (PJ_GetObject(dbfile->pdb, (char*)mrgtree_name, &tmp_obj, DB_MRGTREE) < 0)
return NULL;
tree = (DBmrgtree *) calloc(1,sizeof(DBmrgtree));
memset(tree, 0, sizeof(DBmrgtree));
*tree = tmptree;
tree->root = 0;
tree->cwr = 0;
num_nodes = tree->num_nodes;
if (num_nodes <= 0) return (tree);
/* allocate all the nodes of the tree and a linear list of pointers
to them */
ltree = (DBmrgtnode **) malloc(num_nodes * sizeof(DBmrgtnode*));
for (i = 0; i < num_nodes; i++)
ltree[i] = (DBmrgtnode *) calloc(1,sizeof(DBmrgtnode));
/* Read the nodal scalar data */
for (i = 0; i < num_nodes; i++)
{
ltree[i]->narray = intArray[i*6+0];
ltree[i]->type_info_bits = intArray[i*6+1];
ltree[i]->max_children = intArray[i*6+2];
ltree[i]->nsegs = intArray[i*6+3];
ltree[i]->num_children = intArray[i*6+4];
ltree[i]->parent = intArray[i*6+5] >= 0 ? ltree[intArray[i*6+5]] : 0;
}
FREE(intArray);
/* read the node 'name' member */
INIT_OBJ(&tmp_obj);
DEFALL_OBJ("name", &s, DB_CHAR);
PJ_GetObject(dbfile->pdb, (char*)mrgtree_name, &tmp_obj, 0);
if (s)
{
strArray = DBStringListToStringArray(s, &num_nodes, !skipFirstSemicolon);
for (i = 0; i < num_nodes; i++)
ltree[i]->name = strArray[i];
FREE(s);
FREE(strArray); /* free only top-level array of pointers */
}
/* read the node 'names' member */
INIT_OBJ(&tmp_obj);
DEFALL_OBJ("names", &s, DB_CHAR);
PJ_GetObject(dbfile->pdb, (char*)mrgtree_name, &tmp_obj, 0);
if (s)
{
strArray = DBStringListToStringArray(s, 0, !skipFirstSemicolon);
n = 0;
for (i = 0; i < num_nodes; i++)
{
if (ltree[i]->narray == 0)
continue;
if (strchr(strArray[n], '%') == 0)
{
ltree[i]->names = (char**) malloc(ltree[i]->narray * sizeof(char*));
for (j = 0; j < ltree[i]->narray; j++, n++)
ltree[i]->names[j] = strArray[n];
}
else
{
ltree[i]->names = (char**) malloc(1 * sizeof(char*));
ltree[i]->names[0] = strArray[n];
n++;
}
}
FREE(s);
FREE(strArray); /* free only top-level array of pointers */
}
/* read the maps_name data */
INIT_OBJ(&tmp_obj);
DEFALL_OBJ("maps_name", &s, DB_CHAR);
PJ_GetObject(dbfile->pdb, (char*)mrgtree_name, &tmp_obj, 0);
if (s)
{
strArray = DBStringListToStringArray(s, &num_nodes, !skipFirstSemicolon);
for (i = 0; i < num_nodes; i++)
ltree[i]->maps_name = strArray[i];
FREE(s);
FREE(strArray); /* free only top-level array of pointers */
}
/* read the map segment id data */
INIT_OBJ(&tmp_obj);
DEFALL_OBJ("seg_ids", &intArray, DB_INT);
PJ_GetObject(dbfile->pdb, (char*)mrgtree_name, &tmp_obj, 0);
n = 0;
for (i = 0; i < num_nodes; i++)
{
int ns = ltree[i]->nsegs*(ltree[i]->narray?ltree[i]->narray:1);
if (ns > 0)
{
ltree[i]->seg_ids = (int*) malloc(ns * sizeof(int));
for (j = 0; j < ns; j++)
ltree[i]->seg_ids[j] = intArray[n++];
}
}
FREE(intArray);
/* read the map segment len data */
INIT_OBJ(&tmp_obj);
DEFALL_OBJ("seg_lens", &intArray, DB_INT);
PJ_GetObject(dbfile->pdb, (char*)mrgtree_name, &tmp_obj, 0);
n = 0;
for (i = 0; i < num_nodes; i++)
{
int ns = ltree[i]->nsegs*(ltree[i]->narray?ltree[i]->narray:1);
if (ns > 0)
{
ltree[i]->seg_lens = (int*) malloc(ns * sizeof(int));
for (j = 0; j < ns; j++)
ltree[i]->seg_lens[j] = intArray[n++];
}
}
FREE(intArray);
/* read the map segment type data */
INIT_OBJ(&tmp_obj);
DEFALL_OBJ("seg_types", &intArray, DB_INT);
PJ_GetObject(dbfile->pdb, (char*)mrgtree_name, &tmp_obj, 0);
n = 0;
for (i = 0; i < num_nodes; i++)
{
int ns = ltree[i]->nsegs*(ltree[i]->narray?ltree[i]->narray:1);
if (ns > 0)
{
ltree[i]->seg_types = (int*) malloc(ns * sizeof(int));
for (j = 0; j < ns; j++)
ltree[i]->seg_types[j] = intArray[n++];
}
}
FREE(intArray);
/* read the child ids */
INIT_OBJ(&tmp_obj);
DEFALL_OBJ("children", &intArray, DB_INT);
PJ_GetObject(dbfile->pdb, (char*)mrgtree_name, &tmp_obj, 0);
n = 0;
for (i = 0; i < num_nodes; i++)
{
int nc = ltree[i]->num_children;
if (nc > 0)
{
ltree[i]->children = (DBmrgtnode**) malloc(nc * sizeof(DBmrgtnode*));
for (j = 0; j < nc; j++)
ltree[i]->children[j] = ltree[intArray[n++]];
}
}
FREE(intArray);
if (mrgv_onames)
{
tree->mrgvar_onames = DBStringListToStringArray(mrgv_onames, 0, !skipFirstSemicolon);
FREE(mrgv_onames);
}
if (mrgv_rnames)
{
tree->mrgvar_rnames = DBStringListToStringArray(mrgv_rnames, 0, !skipFirstSemicolon);
FREE(mrgv_rnames);
}
tree->root = ltree[root];
tree->cwr = tree->root;
FREE(ltree);
return (tree);
}
/*----------------------------------------------------------------------
* Routine DBGetGroupelmap
*
* Purpose
*
* Read groupel map object from the given database.
*
* Programmer
*
* Mark C. Miller, Wed Oct 10 13:08:36 PDT 2007
*
*--------------------------------------------------------------------*/
SILO_CALLBACK DBgroupelmap*
db_pdb_GetGroupelmap(DBfile *_dbfile, char const *name)
{
int i, j, n;
DBgroupelmap *gm = NULL;
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
static char *me = "db_pdb_GetGroupelmap";
PJcomplist tmp_obj;
int *segData = NULL;
int *fracLengths = NULL;
void *fracsArray = NULL;
DBgroupelmap tmpgm;
PJcomplist *_tcl;
memset(&tmpgm, 0, sizeof(DBgroupelmap));
INIT_OBJ(&tmp_obj);
DEFINE_OBJ("num_segments", &tmpgm.num_segments, DB_INT);
DEFINE_OBJ("fracs_data_type", &tmpgm.fracs_data_type, DB_INT);
DEFALL_OBJ("groupel_types", &tmpgm.groupel_types, DB_INT);
DEFALL_OBJ("segment_lengths", &tmpgm.segment_lengths, DB_INT);
DEFALL_OBJ("segment_ids", &tmpgm.segment_ids, DB_INT);
DEFALL_OBJ("segment_data", &segData, DB_INT);
DEFALL_OBJ("frac_lengths", &fracLengths, DB_INT);
DEFALL_OBJ("segment_fracs", &fracsArray, DB_FLOAT);
if (PJ_GetObject(dbfile->pdb, (char*)name, &tmp_obj, DB_GROUPELMAP) < 0)
return NULL;
gm = (DBgroupelmap*) calloc(1,sizeof(DBgroupelmap));
*gm = tmpgm;
/* unflatten the segment data */
gm->segment_data = (int **) malloc(gm->num_segments * sizeof(int*));
n = 0;
for (i = 0; i < gm->num_segments; i++)
{
int sl = gm->segment_lengths[i];
gm->segment_data[i] = 0;
if (sl > 0)
{
gm->segment_data[i] = (int*) malloc(sl * sizeof(int));
for (j = 0; j < sl; j++)
gm->segment_data[i][j] = segData[n++];
}
}
FREE(segData);
/* unflatten frac data if we have it */
if (fracLengths != NULL)
{
gm->segment_fracs = (void **)malloc(gm->num_segments * sizeof(void*));
n = 0;
for (i = 0; i < gm->num_segments; i++)
{
int len = fracLengths[i];
if (len <= 0)
{
gm->segment_fracs[i] = 0;
continue;
}
gm->segment_fracs[i] = malloc(len * ((gm->fracs_data_type==DB_FLOAT)?sizeof(float):sizeof(double)));
for (j = 0; j < len; j++)
{
if (gm->fracs_data_type == DB_FLOAT)
{
float *pfa = (float *) fracsArray;
float *psf = (float *) (gm->segment_fracs[i]);
psf[j] = pfa[n++];
}
else
{
double *pfa = (double *) fracsArray;
double *psf = (double *) (gm->segment_fracs[i]);
psf[j] = pfa[n++];
}
}
}
}
else
{
gm->segment_fracs = 0;
}
FREE(fracLengths);
FREE(fracsArray);
gm->name = STRDUP(name);
if (DB_DOUBLE == gm->fracs_data_type && PJ_InqForceSingle())
gm->fracs_data_type = DB_FLOAT;
return gm;
}
/*----------------------------------------------------------------------
* Routine db_pdb_GetMrgvar
*
* Purpose
*
* Read a mrgvar object from a SILO file and return the
* SILO structure for this type.
*
*
* Mark C. Miller, Tue Nov 10 09:14:01 PST 2009
* Replaced strtok-loop over ...names member with call to
* db_StringListToStringArray. Added logic to control behavior of
* slash character swapping for windows/linux and skipping of first
* semicolon in calls to db_StringListToStringArray.
*--------------------------------------------------------------------*/
SILO_CALLBACK DBmrgvar *
db_pdb_GetMrgvar(DBfile *_dbfile, char const *objname)
{
DBmrgvar *mrgv = NULL;
int i;
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
PJcomplist tmp_obj;
char tmp[256];
static char *me = "db_pdb_GetMrgvar";
char *rpnames = NULL;
char *cnames = NULL;
DBmrgvar tmpmrgv;
PJcomplist *_tcl;
/*------------------------------------------------------------*/
/* Comp. Name Comp. Address Data Type */
/*------------------------------------------------------------*/
memset(&tmpmrgv, 0, sizeof(DBmrgvar));
INIT_OBJ(&tmp_obj);
DEFINE_OBJ("ncomps", &tmpmrgv.ncomps, DB_INT);
DEFINE_OBJ("nregns", &tmpmrgv.nregns, DB_INT);
DEFINE_OBJ("datatype", &tmpmrgv.datatype, DB_INT);
DEFALL_OBJ("mrgt_name",&tmpmrgv.mrgt_name, DB_CHAR);
DEFALL_OBJ("compnames", &cnames, DB_CHAR);
DEFALL_OBJ("reg_pnames", &rpnames, DB_CHAR);
if (PJ_GetObject(dbfile->pdb, (char*)objname, &tmp_obj, DB_MRGVAR) < 0)
return NULL;
mrgv = (DBmrgvar *) calloc(1, sizeof(DBmrgvar));
*mrgv = tmpmrgv;
INIT_OBJ(&tmp_obj);
mrgv->data = ALLOC_N(void *, mrgv->ncomps);
if (mrgv->datatype == 0) {
strcpy(tmp, objname);
strcat(tmp, "_data");
if ((mrgv->datatype = db_pdb_GetVarDatatype(dbfile->pdb, tmp)) < 0) {
/* Not found. Assume float. */
mrgv->datatype = DB_FLOAT;
}
}
if (PJ_InqForceSingle())
mrgv->datatype = DB_FLOAT;
for (i = 0; i < mrgv->ncomps; i++) {
DEFALL_OBJ(_valstr[i], &mrgv->data[i], DB_FLOAT);
}
PJ_GetObject(dbfile->pdb, (char*)objname, &tmp_obj, 0);
if (cnames != NULL)
{
mrgv->compnames = DBStringListToStringArray(cnames, &(mrgv->ncomps), !skipFirstSemicolon);
FREE(cnames);
}
if (rpnames != NULL)
{
mrgv->reg_pnames = DBStringListToStringArray(rpnames, 0, !skipFirstSemicolon);
FREE(rpnames);
}
mrgv->name = STRDUP(objname);
return (mrgv);
}
/*----------------------------------------------------------------------
* Routine db_pdb_FreeCompressionResources
*
* Purpose: Implement this method to quite error messages from top
* top-level api. This is better than just NOT generating
* those messages at the top-level because that would make
* the choice for all drivers.
*
* Programmer: Mark C. Miller, Tue Dec 2 09:59:20 PST 2008
*--------------------------------------------------------------------*/
SILO_CALLBACK int
db_pdb_FreeCompressionResources(DBfile *_dbfile, char const *meshname)
{
return 0;
}
/*----------------------------------------------------------------------
* Routine db_pdb_WriteObject
*
* Purpose
*
* Write an object into the given file.
*
* Programmer
*
* Jeffery W. Long, NSSD-B
*
* Returns
*
* Returns OKAY on success, OOPS on failure.
*
* Modifications:
*
* Robb Matzke, 7 Mar 1997
* Returns a failure status if PJ_put_group fails.
*
* Robb Matzke, 7 Mar 1997
* The FREEMEM argument was replaced with a FLAGS argument that
* has the value 0, FREE_MEM, or OVER_WRITE depending on how
* this function got called (FREE_MEM still doesn't do anything).
*
* Mark C. Miller, 10May06
* Passed value for SILO_Globals.allowOverwrites to PJ_put_group
*--------------------------------------------------------------------*/
#ifdef PDB_WRITE
SILO_CALLBACK int
db_pdb_WriteObject(DBfile *_file, /*File to write into */
DBobject const *obj,/*Object description to write out */
int flags) /*Sentinel: 1=free associated memory */
{
PJgroup *group;
PDBfile *file;
static char *me = "db_pdb_WriteObject";
if (!obj || !_file)
return (OOPS);
file = ((DBfile_pdb *) _file)->pdb;
group = PJ_make_group(obj->name, obj->type, obj->comp_names,
obj->pdb_names, obj->ncomponents);
if (!PJ_put_group(file, group, (OVER_WRITE==flags?1:0) ||
SILO_Globals.allowOverwrites)) {
PJ_rel_group (group);
return db_perror ("PJ_put_group", E_CALLFAIL, me);
}
PJ_rel_group(group);
return (OKAY);
}
#endif /* PDB_WRITE */
/*----------------------------------------------------------------------
* Routine db_pdb_WriteComponent
*
* Purpose
*
* Add a variable component to the given object structure, AND
* write out the associated data.
*
* Programmer
*
* Jeffery W. Long, NSSD-B
*
* Returns
*
* Returns OKAY on success, OOPS on failure.
*--------------------------------------------------------------------*/
#ifdef PDB_WRITE
SILO_CALLBACK int
db_pdb_WriteComponent (DBfile *_file, DBobject *obj, char const *compname,
char const *prefix, char const *datatype, void const *var,
int nd, long const *count)
{
PDBfile *file;
char tmp[256];
file = ((DBfile_pdb *) _file)->pdb;
db_mkname(file, prefix, compname, tmp);
PJ_write_len(file, tmp, datatype, var, nd, count);
DBAddVarComponent(obj, compname, tmp);
return 0;
}
#endif /* PDB_WRITE */
/*-------------------------------------------------------------------------
* Function: db_pdb_Write
*
* Purpose: Writes a single variable into a file.
*
* Return: Success: 0
*
* Failure: -1
*
* Programmer: robb@cloud
* Mon Nov 21 21:17:50 EST 1994
*
* Modifications:
*
* Robb Matzke, Sun Dec 18 17:14:18 EST 1994
* Changed SW_GetDatatypeString to db_GetDatatypeString.
*
* Sean Ahern, Sun Oct 1 03:19:43 PDT 1995
* Made "me" static.
*-------------------------------------------------------------------------*/
#ifdef PDB_WRITE
SILO_CALLBACK int
db_pdb_Write (DBfile *_dbfile, char const *vname, void const *var,
int const *dims, int ndims, int datatype)
{
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
char *idata;
int i;
long ind[3 * MAXDIMS_VARWRITE];
static char *me = "db_pdb_Write";
for (i = 0; i < 3 * MAXDIMS_VARWRITE; i++)
ind[i] = 0;
for (i = 0; i < ndims; i++) {
ind[3 * i] = 0;
ind[3 * i + 1] = dims[i] - 1;
ind[3 * i + 2] = 1;
}
idata = db_GetDatatypeString(datatype);
if (!PJ_write_alt(dbfile->pdb, vname, idata,
var, ndims, ind)) {
return db_perror("PJ_write_alt", E_CALLFAIL, me);
}
FREE(idata);
return 0;
}
#endif /* PDB_WRITE */
/*-------------------------------------------------------------------------
* Function: db_pdb_WriteSlice
*
* Purpose: Similar to db_pdb_Write except only part of the data is
* written. If VNAME doesn't exist, space is reserved for
* the entire variable based on DIMS; otherwise we check
* that DIMS has the same value as originally. Then we
* write the specified slice to the file.
*
* Return: Success: 0
*
* Failure: -1
*
* Programmer: Robb Matzke
* robb@callisto.nuance.com
* May 9, 1996
*
* Modifications:
* Sean Ahern, Tue Mar 31 11:15:03 PST 1998
* Freed dtype_s.
*-------------------------------------------------------------------------*/
#ifdef PDB_WRITE
SILO_CALLBACK int
db_pdb_WriteSlice(
DBfile *_dbfile,
char const *vname,
void const *values,
int dtype,
int const *offset,
int const *length,
int const *stride,
int const *dims,
int ndims
)
{
char *dtype_s ;
long dim_extents[9] ;
int i ;
DBfile_pdb *dbfile = (DBfile_pdb*)_dbfile ;
syment *ep ;
dimdes *dimensions ;
static char *me = "db_pdb_WriteSlice" ;
if (NULL==(dtype_s=db_GetDatatypeString (dtype))) {
return db_perror ("db_GetDatatypeString", E_CALLFAIL, me) ;
}
if ((ep=lite_PD_inquire_entry (dbfile->pdb, (char*) vname, TRUE, NULL))) {
/*
* Variable already exists. Make sure the supplied dimensions
* are the same as what was originally used when space was reserved.
*/
for (i=0, dimensions=ep->dimensions;
i<ndims && dimensions;
i++, dimensions=dimensions->next) {
if (0!=dimensions->index_min) {
FREE(dtype_s);
return db_perror ("index_min!=0", E_BADARGS, me) ;
}
if (dimensions->number!=dims[i]) {
FREE(dtype_s);
return db_perror ("dims", E_BADARGS, me) ;
}
}
if (i!=ndims) {
FREE(dtype_s);
return db_perror ("ndims", E_BADARGS, me) ;
}
} else {
/*
* Variable doesn't exist yet. Reserve space for the variable
* in the database and enter it's name in the symbol table.
*/
for (i=0; i<3 && i<ndims; i++) {
dim_extents[i*2+0] = 0 ; /*minimum index*/
dim_extents[i*2+1] = dims[i]-1 ; /*maximum index*/
}
if (!lite_PD_defent_alt (dbfile->pdb, (char*) vname, dtype_s, ndims,
dim_extents)) {
FREE(dtype_s);
return db_perror ("PD_defent_alt", E_CALLFAIL, me) ;
}
}
/*
* Verify that offset and length are compatible with
* the supplied dimensions.
*/
for (i=0; i<ndims; i++) {
if (offset[i]<0 || offset[i]>=dims[i]) {
FREE(dtype_s);
return db_perror ("offset", E_BADARGS, me) ;
}
if (length[i]<=0 || length[i]>dims[i]) {
FREE(dtype_s);
return db_perror ("length", E_BADARGS, me) ;
}
if (offset[i]+length[i]>dims[i]) {
FREE(dtype_s);
return db_perror ("offset+length", E_BADARGS, me) ;
}
}
/*
* Write the specified chunk of the values to the file.
*/
for (i=0; i<3 && i<ndims; i++) {
dim_extents[i*3+0] = offset[i] ;
dim_extents[i*3+1] = offset[i] + length[i] - 1 ;
dim_extents[i*3+2] = stride[i] ;
}
PJ_write_alt (dbfile->pdb, vname, dtype_s, values, ndims, dim_extents);
FREE(dtype_s);
return 0 ;
}
#endif /* PDB_WRITE */
/*-------------------------------------------------------------------------
* Function: db_pdb_MkDir
*
* Purpose: Creates a new directory in the open database file.
*
* Return: Success: directory ID
*
* Failure: -1
*
* Programmer: robb@cloud
* Tue Nov 15 15:13:44 EST 1994
*
* Modifications:
* Sean Ahern, Sun Oct 1 03:14:25 PDT 1995
* Made "me" static.
*-------------------------------------------------------------------------*/
#ifdef PDB_WRITE
SILO_CALLBACK int
db_pdb_MkDir (DBfile *_dbfile, char const *name)
{
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
static char *me = "db_pdb_MkDir";
if (!lite_PD_mkdir(dbfile->pdb, (char*) name)) {
return db_perror("PD_mkdir", E_CALLFAIL, me);
}
return 0;
}
#endif /* PDB_WRITE */
/*-------------------------------------------------------------------------
* Function: db_pdb_PutCompoundarray
*
* Purpose: Put a compound array object into the PDB data file.
*
* Return: Success: 0
*
* Failure: -1, db_errno set
*
* Programmer: matzke@viper
* Thu Nov 3 11:04:22 PST 1994
*
* Modifications:
*
* Robb Matzke, Thu Nov 3 14:21:25 PST 1994
* Sets db_errno on failure.
*
* Robb Matzke, Fri Dec 2 14:08:24 PST 1994
* Remove all references to SCORE memory management.
*
* Robb Matzke, Sun Dec 18 17:04:29 EST 1994
* Changed SW_GetDatatypeString to db_GetDatatypeString and
* removed associated memory leak.
*
* Sean Ahern, Sun Oct 1 03:09:48 PDT 1995
* Added "me" and made it static.
*
* Hank Childs, Thu Jan 6 13:48:40 PST 2000
* Casted strlen to long to remove compiler warning.
* Put in lint directive for unused arguments.
*
* Hank Childs, Wed Apr 11 08:05:24 PDT 2001
* Concatenate strings more intelligently [HYPer02535].
*
* Hank Childs, Mon May 14 14:27:29 PDT 2001
* Fixed bug where there was an assumption that the string is
* NULL terminated.
*
* Eric Brugger, Tue Apr 23 10:14:46 PDT 2002
* I modified the routine to add a ';' delimiter to the end of the
* name string so that GetCompoundarray would work properly since it
* makes that assumption.
*
* Eric Brugger, Mon Sep 16 15:40:20 PDT 2002
* I corrected a bug where the routine would write out the string
* containing the component names one too large. It still writes out
* the same number of characters, but now the array is one larger
* and the last character is set to a NULL character. This seemed
* the safest thing to do.
*
*-------------------------------------------------------------------------*/
#ifdef PDB_WRITE
/* ARGSUSED */
SILO_CALLBACK int
db_pdb_PutCompoundarray (
DBfile *_dbfile, /*pointer to open file */
char const *array_name, /*name of array object */
char const * const *elemnames, /*simple array names */
int const *elemlengths, /*lengths of simple arrays */
int nelems, /*number of simple arrays */
void const *values, /*vector of simple values */
int nvalues, /*num of values (redundant) */
int datatype, /*type of simple all values */
DBoptlist const *optlist /*option list */
)
{
DBobject *obj;
char *tmp, *cur;
int i, acc, len;
long count[3];
/*
* Build the list of simple array names in the format:
* `;name1;name2;...;nameN;' The string must have a ';' at
* the end for GetCompoundarray to work properly.
*/
for (i = 0, acc = 1; i < nelems; i++)
acc += strlen(elemnames[i]) + 1;
acc++;
tmp = ALLOC_N(char, acc);
tmp[0] = '\0';
cur = tmp;
for (i = 0; i < nelems; i++) {
strncpy(cur, ";", 1);
cur += 1;
len = strlen(elemnames[i]);
strncpy(cur, elemnames[i], len);
cur += len;
}
cur[0] = ';';
cur++;
cur[0] = '\0';
#if 0 /*No global options available at this time */
db_ProcessOptlist(DB_ARRAY, optlist);
#endif
obj = DBMakeObject(array_name, DB_ARRAY, 25);
/*
* Write the compound array components to the database.
*/
count[0] = (long) (cur - tmp) + 1;
DBWriteComponent(_dbfile, obj, "elemnames", array_name,
"char", tmp, 1, count);
FREE(tmp);
count[0] = nelems;
DBWriteComponent(_dbfile, obj, "elemlengths", array_name,
"integer", elemlengths, 1, count);
DBAddIntComponent(obj, "nelems", nelems);
count[0] = nvalues;
tmp = db_GetDatatypeString(datatype);
DBWriteComponent(_dbfile, obj, "values", array_name,
tmp, values, 1, count);
FREE(tmp);
DBAddIntComponent(obj, "nvalues", nvalues);
DBAddIntComponent(obj, "datatype", datatype);
DBWriteObject(_dbfile, obj, TRUE);
DBFreeObject(obj);
return OKAY;
}
#endif /* PDB_WRITE */
/*-------------------------------------------------------------------------
* Function: db_pdb_PutCurve
*
* Purpose: Put a curve object into the PDB data file.
*
* Return: Success: 0
*
* Failure: -1, db_errno set
*
* Programmer: Robb Matzke
* robb@callisto.nuance.com
* May 15, 1996
*
* Modifications:
*
* Thomas R. Treadway, Fri Jul 7 11:43:41 PDT 2006
* Added DBOPT_REFERENCE support.
*-------------------------------------------------------------------------*/
#ifdef PDB_WRITE
SILO_CALLBACK int
db_pdb_PutCurve (DBfile *_dbfile, char const *name, void const *xvals, void const *yvals,
int dtype, int npts, DBoptlist const *opts)
{
DBobject *obj ;
char *dtype_s ;
long lnpts = npts ;
static char *me = "db_pdb_PutCurve" ;
/*
* Set global curve options to default values, then initialize
* them with any values specified in the options list.
*/
db_InitCurve (opts) ;
obj = DBMakeObject (name, DB_CURVE, 19) ;
/*
* Write the X and Y arrays. If the user specified a variable
* name with the OPTS for the X or Y arrays then we assume that
* the arrays have already been stored in the file. This allows
* us to share X values (or Y values) among several curves.
* If a variable name is specified, then the corresponding X or
* Y values array must be the null pointer!
*/
dtype_s = db_GetDatatypeString (dtype) ;
if (_cu._varname[0]) {
DBAddVarComponent (obj, "xvals", _cu._varname[0]) ;
} else {
if (npts && xvals && !_cu._reference) {
DBWriteComponent (_dbfile, obj, "xvals", name, dtype_s,
xvals, 1, &lnpts);
}
}
if (_cu._varname[1]) {
DBAddVarComponent (obj, "yvals", _cu._varname[1]) ;
} else {
if (npts && yvals && !_cu._reference) {
DBWriteComponent (_dbfile, obj, "yvals", name, dtype_s,
yvals, 1, &lnpts);
}
}
FREE (dtype_s) ;
/*
* Now output the other values of the curve.
*/
DBAddIntComponent (obj, "npts", npts) ;
DBAddIntComponent (obj, "datatype", dtype) ;
if (_cu._label) DBAddStrComponent (obj, "label", _cu._label) ;
if (_cu._varname[0]) DBAddStrComponent (obj, "xvarname", _cu._varname[0]) ;
if (_cu._labels[0]) DBAddStrComponent (obj, "xlabel", _cu._labels[0]) ;
if (_cu._units[0]) DBAddStrComponent (obj, "xunits", _cu._units[0]) ;
if (_cu._varname[1]) DBAddStrComponent (obj, "yvarname", _cu._varname[1]) ;
if (_cu._labels[1]) DBAddStrComponent (obj, "ylabel", _cu._labels[1]) ;
if (_cu._units[1]) DBAddStrComponent (obj, "yunits", _cu._units[1]) ;
if (_cu._reference) DBAddStrComponent (obj, "reference",_cu._reference) ;
if (_cu._guihide) DBAddIntComponent (obj, "guihide", _cu._guihide) ;
if (_cu._coord_sys) DBAddIntComponent (obj, "coord_sys", _cu._coord_sys) ;
if (_cu._missing_value != DB_MISSING_VALUE_NOT_SET)
{
if (_cu._missing_value == 0.0)
DBAddDblComponent(obj, "missing_value", DB_MISSING_VALUE_NOT_SET);
else
DBAddDblComponent(obj, "missing_value", _cu._missing_value);
}
DBWriteObject (_dbfile, obj, TRUE) ;
DBFreeObject(obj);
return 0 ;
}
#endif /* PDB_WRITE */
/*----------------------------------------------------------------------
* Routine db_pdb_PutDefvars
*
* Purpose
*
* Write a defvars object into the open SILO file.
*
* Programmer
*
* Mark C. Miller
* August 8, 2005
*
*--------------------------------------------------------------------*/
#ifdef PDB_WRITE
SILO_CALLBACK int
db_pdb_PutDefvars(
DBfile *dbfile,
char const *name,
int ndefs,
char const * const *names,
int const *types,
char const * const *defns,
DBoptlist const * const *optlists
)
{
int i, len;
long count[1];
DBobject *obj;
char *tmp = NULL, *cur = NULL;
int *guihide = NULL;
/*
* Optlists are a little funky for this object because we were
* concerned about possibly handling things like units, etc. So,
* we really have an array of optlists that needs to get serialized.
*/
if (optlists)
{
for (i = 0; i < ndefs; i++)
{
db_InitDefvars(optlists[i]);
if (_dv._guihide)
{
if (guihide == NULL)
guihide = (int* ) calloc(ndefs, sizeof(int));
guihide[i] = _dv._guihide;
}
}
}
/*-------------------------------------------------------------
* Build object description from literals and var-id's
*-------------------------------------------------------------*/
obj = DBMakeObject(name, DB_DEFVARS, 10);
DBAddIntComponent(obj, "ndefs", ndefs);
/*-------------------------------------------------------------
* Define and write variables types
*-------------------------------------------------------------*/
count[0] = ndefs;
DBWriteComponent(dbfile, obj, "types", name, "integer",
(int*) types, 1, count);
/*-------------------------------------------------------------
* Define and write variable names
*-------------------------------------------------------------*/
DBStringArrayToStringList((char const * const *)names, ndefs, &tmp, &len);
count[0] = len;
DBWriteComponent(dbfile, obj, "names", name, "char",
tmp, 1, count);
FREE(tmp);
tmp = NULL;
/*-------------------------------------------------------------
* Define and write variable definitions
*-------------------------------------------------------------*/
DBStringArrayToStringList((char const * const *)defns, ndefs, &tmp, &len);
count[0] = len;
DBWriteComponent(dbfile, obj, "defns", name, "char",
tmp, 1, count);
FREE(tmp);
tmp = NULL;
if (guihide != NULL) {
count[0] = ndefs;
DBWriteComponent(dbfile, obj, "guihide", name, "integer", guihide,
1, count);
free(guihide);
}
/*-------------------------------------------------------------
* Write defvars object to SILO file.
*-------------------------------------------------------------*/
DBWriteObject(dbfile, obj, TRUE);
DBFreeObject(obj);
return 0;
}
#endif /* PDB_WRITE */
/*----------------------------------------------------------------------
* Routine db_pdb_PutFacelist
*
* Purpose
*
* Write a ucd facelist object into the open output file.
*
* Programmer
*
* Jeffery W. Long, NSSD-B
*
* Notes
*
* Modified
*
* Robb Matzke, Wed Nov 16 11:39:19 EST 1994
* Added device independence.
*
* Robb Matzke, Fri Dec 2 14:12:48 PST 1994
* Changed SCFREE(obj) to DBFreeObject(obj)
*--------------------------------------------------------------------*/
#ifdef PDB_WRITE
SILO_CALLBACK int
db_pdb_PutFacelist(
DBfile *dbfile,
char const *name,
int nfaces,
int ndims,
int const *nodelist,
int lnodelist,
int origin,
int const *zoneno,
int const *shapesize,
int const *shapecnt,
int nshapes,
int const *types,
int const *typelist,
int ntypes
)
{
long count[5];
DBobject *obj;
/*--------------------------------------------------
* Build up object description by defining literals
* and defining/writing arrays.
*-------------------------------------------------*/
obj = DBMakeObject(name, DB_FACELIST, 15);
DBAddIntComponent(obj, "ndims", ndims);
DBAddIntComponent(obj, "nfaces", nfaces);
DBAddIntComponent(obj, "nshapes", nshapes);
DBAddIntComponent(obj, "ntypes", ntypes);
DBAddIntComponent(obj, "lnodelist", lnodelist);
DBAddIntComponent(obj, "origin", origin);
count[0] = lnodelist;
DBWriteComponent(dbfile, obj, "nodelist", name, "integer",
nodelist, 1, count);
if (ndims == 2 || ndims == 3) {
count[0] = nshapes;
DBWriteComponent(dbfile, obj, "shapecnt", name, "integer",
shapecnt, 1, count);
DBWriteComponent(dbfile, obj, "shapesize", name, "integer",
shapesize, 1, count);
}
if (ntypes > 0 && typelist != NULL) {
count[0] = ntypes;
DBWriteComponent(dbfile, obj, "typelist", name, "integer",
typelist, 1, count);
}
if (ntypes > 0 && types != NULL) {
count[0] = nfaces;
DBWriteComponent(dbfile, obj, "types", name, "integer",
types, 1, count);
}
if (zoneno != NULL) {
count[0] = nfaces;
DBWriteComponent(dbfile, obj, "zoneno", name, "integer",
zoneno, 1, count);
}
/*-------------------------------------------------------------
* Write object to output file.
*-------------------------------------------------------------*/
DBWriteObject(dbfile, obj, TRUE);
DBFreeObject(obj);
return 0;
}
#endif /* PDB_WRITE */
/*----------------------------------------------------------------------
* Routine db_pdb_PutMaterial
*
* Purpose
*
* Write a material object into the open SILO file.
*
* Programmer
*
* Jeffery W. Long, NSSD-B
*
* Notes
*
* See the prologue for DBPutMaterial for a description of this
* data.
*
* Modifications
*
* Robb Matzke, Sun Dec 18 17:05:39 EST 1994
* Changed SW_GetDatatypeString to db_GetDatatypeString and removed
* associated memory leak.
*
* Robb Matzke, Fri Dec 2 14:13:55 PST 1994
* Changed SCFREE(obj) to DBFreeObject(obj)
*
* Robb Matzke, Wed Nov 16 11:45:08 EST 1994
* Added device independence.
*
* Al Leibee, Tue Jul 13 17:14:31 PDT 1993
* FREE of obj to SCFREE for consistant MemMan usage.
*
* Sean Ahern, Wed Jan 17 17:02:31 PST 1996
* Added writing of the datatype parameter.
*
* Sean Ahern, Tue Feb 5 10:19:53 PST 2002
* Added naming of Silo materials.
*
* Mark C. Miller, Thu Feb 11 09:40:10 PST 2010
* Set global values in _ma to zero after use.
*--------------------------------------------------------------------*/
#ifdef PDB_WRITE
SILO_CALLBACK int
db_pdb_PutMaterial(
DBfile *dbfile,
char const *name,
char const *mname,
int nmat,
int const *matnos,
int const *matlist,
int const *dims,
int ndims,
int const *mix_next,
int const *mix_mat,
int const *mix_zone,
void const *mix_vf,
int mixlen,
int datatype,
DBoptlist const *optlist
)
{
int i, nels;
long count[3];
DBobject *obj;
char *datatype_str;
int is_empty = 1;
for (i = 0; i < ndims; i++)
{
if (dims[i] > 0)
{
is_empty = 0;
break;
}
}
/*-------------------------------------------------------------
* Process option list; build object description.
*-------------------------------------------------------------*/
db_ProcessOptlist(DB_MATERIAL, optlist);
obj = DBMakeObject(name, DB_MATERIAL, 26);
/*-------------------------------------------------------------
* Define literals used by material data.
*-------------------------------------------------------------*/
DBAddStrComponent(obj, "meshid", mname);
DBAddIntComponent(obj, "ndims", ndims);
DBAddIntComponent(obj, "nmat", nmat);
DBAddIntComponent(obj, "mixlen", mixlen);
DBAddIntComponent(obj, "origin", _ma._origin);
DBAddIntComponent(obj, "major_order", _ma._majororder);
DBAddIntComponent(obj, "datatype", datatype);
if (_ma._allowmat0)
DBAddIntComponent(obj, "allowmat0", _ma._allowmat0);
if (_ma._guihide)
DBAddIntComponent(obj, "guihide", _ma._guihide);
/*-------------------------------------------------------------
* Define variables, write them into object description.
*-------------------------------------------------------------*/
count[0] = ndims;
DBWriteComponent(dbfile, obj, "dims", name, "integer", dims, 1, count);
/* Do zonal material ID array */
nels = ndims==0?0:1;
for (i = 0; i < ndims; i++)
nels *= dims[i];
count[0] = nels;
if (!is_empty)
DBWriteComponent(dbfile, obj, "matlist", name, "integer", matlist, 1, count);
/* Do material numbers list */
count[0] = nmat;
DBWriteComponent(dbfile, obj, "matnos", name, "integer", matnos, 1, count);
/* Now do mixed data arrays (mix_zone is optional) */
if (!is_empty && mixlen > 0) {
datatype_str = db_GetDatatypeString(datatype);
count[0] = mixlen;
DBWriteComponent(dbfile, obj, "mix_vf", name, datatype_str,
mix_vf, 1, count);
FREE(datatype_str);
DBWriteComponent(dbfile, obj, "mix_next", name, "integer",
mix_next, 1, count);
DBWriteComponent(dbfile, obj, "mix_mat", name, "integer",
mix_mat, 1, count);
if (mix_zone != NULL) {
DBWriteComponent(dbfile, obj, "mix_zone", name, "integer",
mix_zone, 1, count);
}
}
/* If we have material names, write them out */
if (_ma._matnames != NULL)
{
int len; long llen; char *tmpstr = 0;
DBStringArrayToStringList((char const * const *)_ma._matnames, nmat, &tmpstr, &len);
llen = (long) len;
DBWriteComponent(dbfile, obj, "matnames", name, "char", tmpstr, 1, &llen);
FREE(tmpstr);
_ma._matnames = NULL;
}
if (_ma._matcolors != NULL)
{
int len; long llen; char *tmpstr = 0;
DBStringArrayToStringList((char const * const *)_ma._matcolors, nmat, &tmpstr, &len);
llen = (long) len;
DBWriteComponent(dbfile, obj, "matcolors", name, "char", tmpstr, 1, &llen);
FREE(tmpstr);
_ma._matcolors = NULL;
}
/*-------------------------------------------------------------
* Write material object to output file. Request that underlying
* memory be freed (the 'TRUE' argument.)
*-------------------------------------------------------------*/
DBWriteObject(dbfile, obj, TRUE);
DBFreeObject(obj);
return 0;
}
#endif /* PDB_WRITE */
/*----------------------------------------------------------------------
* Routine db_pdb_PutMatspecies
*
* Purpose
*
* Write a material species object into the open SILO file.
*
* Programmer
*
* Al Leibee, DSAD-B
*
* Notes
*
* See the prologue for DBPutMatspecies for a description of this
* data.
*
* Modifications
*
* Robb Matzke, Fri Dec 2 14:14:27 PST 1994
* Changed SCFREE(obj) to DBFreeObject(obj)
*
* Robb Matzke, Sun Dec 18 17:06:28 EST 1994
* Changed SW_GetDatatypeString to db_GetDatatypeString and removed
* associated memory leak.
*
* Jeremy Meredith, Wed Jul 7 12:15:31 PDT 1999
* I removed the origin value from the species object.
*
* Mark C. Miller, Tue Sep 8 15:40:51 PDT 2009
* Added names and colors for species.
*
* Mark C. Miller, Thu Feb 11 09:40:10 PST 2010
* Set global values in _ma to zero after use.
*--------------------------------------------------------------------*/
#ifdef PDB_WRITE
SILO_CALLBACK int
db_pdb_PutMatspecies (DBfile *dbfile, char const *name, char const *matname,
int nmat, int const *nmatspec, int const *speclist,
int const *dims, int ndims, int nspecies_mf,
void const *species_mf, int const *mix_speclist,
int mixlen, int datatype, DBoptlist const *optlist) {
long count[3];
int i, nels, nstrs;
DBobject *obj;
char *datatype_str;
int is_empty = 1;
for (i = 0; i < ndims; i++)
{
if (dims[i] > 0)
{
is_empty = 0;
break;
}
}
/*-------------------------------------------------------------
* Process option list; build object description.
*-------------------------------------------------------------*/
db_ProcessOptlist(DB_MATSPECIES, optlist);
obj = DBMakeObject(name, DB_MATSPECIES, 15);
/*-------------------------------------------------------------
* Define literals used by material species data.
*-------------------------------------------------------------*/
DBAddStrComponent(obj, "matname", matname);
DBAddIntComponent(obj, "ndims", ndims);
DBAddIntComponent(obj, "nmat", nmat);
DBAddIntComponent(obj, "nspecies_mf", nspecies_mf);
DBAddIntComponent(obj, "mixlen", mixlen);
DBAddIntComponent(obj, "datatype", datatype);
DBAddIntComponent(obj, "major_order", _ms._majororder);
if (_ms._guihide)
DBAddIntComponent(obj, "guihide", _ms._guihide);
/*-------------------------------------------------------------
* Define variables, write them into object description.
*-------------------------------------------------------------*/
count[0] = ndims;
DBWriteComponent(dbfile, obj, "dims", name, "integer", dims, 1, count);
/* Do zonal material species ID array */
nels = ndims==0?0:1;
for (i = 0; i < ndims; i++)
nels *= dims[i];
count[0] = nels;
if (!is_empty)
DBWriteComponent(dbfile, obj, "speclist", name, "integer", speclist, 1, count);
/* Do material species count per material list */
count[0] = nmat;
DBWriteComponent(dbfile, obj, "nmatspec", name, "integer", nmatspec, 1, count);
/* Do material species mass fractions */
datatype_str = db_GetDatatypeString(datatype);
count[0] = nspecies_mf;
if (!is_empty)
DBWriteComponent(dbfile, obj, "species_mf", name, datatype_str, species_mf, 1, count);
FREE(datatype_str);
/* Now do mixed data arrays */
if (!is_empty && mixlen > 0) {
count[0] = mixlen;
DBWriteComponent(dbfile, obj, "mix_speclist", name, "integer",
mix_speclist, 1, count);
}
/* If we have species names or colors, write them out */
nstrs = 0;
if (_ms._specnames != NULL)
{
int len; long llen; char *tmpstr = 0;
/* count how many names we have */
for (i=0; i < nmat; i++)
nstrs += nmatspec[i];
DBStringArrayToStringList((char const * const *)_ms._specnames, nstrs, &tmpstr, &len);
llen = (long) len;
DBWriteComponent(dbfile, obj, "species_names", name, "char", tmpstr, 1, &llen);
FREE(tmpstr);
_ms._specnames = NULL;
}
if (_ms._speccolors != NULL)
{
int len; long llen; char *tmpstr = 0;
/* count how many names we have */
if (nstrs == 0)
{
for (i=0; i < nmat; i++)
nstrs += nmatspec[i];
}
DBStringArrayToStringList((char const * const *)_ms._speccolors, nstrs, &tmpstr, &len);
llen = (long) len;
DBWriteComponent(dbfile, obj, "speccolors", name, "char", tmpstr, 1, &llen);
FREE(tmpstr);
_ms._speccolors = NULL;
}
/*-------------------------------------------------------------
* Write material object to output file. Request that underlying
* memory be freed (the 'TRUE' argument.)
*-------------------------------------------------------------*/
DBWriteObject(dbfile, obj, TRUE);
DBFreeObject(obj);
return 0;
}
#endif /* PDB_WRITE */
/*----------------------------------------------------------------------
* Routine db_pdb_PutMultimesh
*
* Purpose
*
* Write a multi-block mesh object into the open SILO file.
*
* Programmer
*
* Jeffery W. Long, NSSD-B
*
* Notes
*
* Modified
* Robb Matzke, Fri Dec 2 14:15:31 PST 1994
* Changed SCFREE(obj) to DBFreeObject(obj)
*
* Eric Brugger, Fri Jan 12 17:42:55 PST 1996
* I added cycle, time and dtime as options.
*
* Sean Ahern, Thu Aug 15 11:16:18 PDT 1996
* Allowed the mesh names to be any length, rather than hardcoded.
*
* Eric Brugger, Fri Oct 17 09:11:58 PDT 1997
* I corrected the outputing of the cyle, time and dtime options to
* use the values from the global _mm instead of _pm. A cut
* and paste error.
*
* Jeremy Meredith, Fri May 21 10:04:25 PDT 1999
* Added ngroups, blockorigin, and grouporigin.
*
* Hank Childs, Thu Jan 6 13:51:22 PST 2000
* Casted a strlen to long to remove compiler warning.
*
* Hank Childs, Wed Apr 11 08:05:24 PDT 2001
* Concatenate strings more intelligently [HYPer02535].
*
* Hank Childs, Mon May 14 14:27:29 PDT 2001
* Fixed bug where there was an assumption that the string is
* NULL terminated.
*
* Thomas R. Treadway, Thu Jul 20 13:34:57 PDT 2006
* Added lgroupings, groupings, and groupnames options.
*
* Mark C. Miller, Wed Jul 14 20:40:55 PDT 2010
* Added support for namescheme/empty list options.
*--------------------------------------------------------------------*/
#ifdef PDB_WRITE
SILO_CALLBACK int
db_pdb_PutMultimesh (DBfile *dbfile, char const *name, int nmesh,
char const * const *meshnames, int const *meshtypes,
DBoptlist const *optlist) {
int i, len;
long count[3];
DBobject *obj;
char *tmp = NULL, *cur = NULL;
char *gtmp = NULL;
/*-------------------------------------------------------------
* Initialize global data, and process options.
*-------------------------------------------------------------*/
db_InitMulti(dbfile, optlist);
/*-------------------------------------------------------------
* Build object description from literals and var-id's
*-------------------------------------------------------------*/
obj = DBMakeObject(name, DB_MULTIMESH, 31);
DBAddIntComponent(obj, "nblocks", nmesh);
DBAddIntComponent(obj, "ngroups", _mm._ngroups);
DBAddIntComponent(obj, "blockorigin", _mm._blockorigin);
DBAddIntComponent(obj, "grouporigin", _mm._grouporigin);
if (_mm._guihide)
DBAddIntComponent(obj, "guihide", _mm._guihide);
if (_mm._mrgtree_name)
DBAddStrComponent(obj, "mrgtree_name", _mm._mrgtree_name);
if (_mm._tv_connectivity)
DBAddIntComponent(obj, "tv_connectivity", _mm._tv_connectivity);
if (_mm._disjoint_mode)
DBAddIntComponent(obj, "disjoint_mode", _mm._disjoint_mode);
if (_mm._topo_dim > 0)
DBAddIntComponent(obj, "topo_dim", _mm._topo_dim);
/*-------------------------------------------------------------
* Define and write variables before adding them to object.
*-------------------------------------------------------------*/
count[0] = nmesh;
if (meshtypes)
DBWriteComponent(dbfile, obj, "meshtypes", name, "integer",
meshtypes, 1, count);
if (meshnames)
{
/* Compute size needed for string of concatenated block names.
*
* Note that we start with 2 so that we have one `;' and the NULL
* terminator. Also, the +1 in the "len +=" line is for the `;'
* character.
*/
len = 2;
for(i=0; i<nmesh; i++)
{
len += strlen(meshnames[i]) + 1;
}
tmp = ALLOC_N(char,len);
/* Build 1-D character string from 2-D mesh-name array */
tmp[0] = ';';
tmp[1] = '\0';
cur = tmp+1;
for (i = 0; i < nmesh; i++) {
int len2;
len2 = strlen(meshnames[i]);
strncpy(cur, meshnames[i], len2);
cur += len2;
strncpy(cur, ";", 1);
cur += 1;
}
count[0] = (long) (cur - tmp);
DBWriteComponent(dbfile, obj, "meshnames", name, "char",
tmp, 1, count);
}
/*-------------------------------------------------------------
* Define and write the time and cycle.
*-------------------------------------------------------------*/
DBAddIntComponent(obj, "cycle", _mm._cycle);
if (_mm._time_set == TRUE)
DBAddVarComponent(obj, "time", _mm._nm_time);
if (_mm._dtime_set == TRUE)
DBAddVarComponent(obj, "dtime", _mm._nm_dtime);
/*-------------------------------------------------------------
* Add the DBOPT_EXTENTS_SIZE and DBOPT_EXTENTS options if present.
*-------------------------------------------------------------*/
if (_mm._extents != NULL && _mm._extentssize > 0) {
DBAddIntComponent(obj, "extentssize", _mm._extentssize);
count[0] = _mm._extentssize * nmesh;
DBWriteComponent(dbfile, obj, "extents", name, "double", _mm._extents,
1, count);
}
/*-------------------------------------------------------------
* Add the DBOPT_ZONECOUNTS option if present.
*-------------------------------------------------------------*/
if (_mm._zonecounts != NULL) {
count[0] = nmesh;
DBWriteComponent(dbfile, obj, "zonecounts", name, "integer",
_mm._zonecounts, 1, count);
}
/*-------------------------------------------------------------
* Add the DBOPT_HAS_EXTERNAL_ZONES option if present.
*-------------------------------------------------------------*/
if (_mm._has_external_zones != NULL) {
count[0] = nmesh;
DBWriteComponent(dbfile, obj, "has_external_zones", name, "integer",
_mm._has_external_zones, 1, count);
}
/*-------------------------------------------------------------
* Add the DBOPT_GROUP* options if present.
*-------------------------------------------------------------*/
if (_mm._lgroupings > 0)
DBAddIntComponent(obj, "lgroupings", _mm._lgroupings);
if ((_mm._lgroupings > 0) && (_mm._groupnames != NULL)) {
DBStringArrayToStringList((char const * const *)_mm._groupnames,
_mm._lgroupings, >mp, &len);
count[0] = len;
DBWriteComponent(dbfile, obj, "groupnames", name, "char",
gtmp, 1, count);
FREE(gtmp);
}
if ((_mm._lgroupings > 0) && (_mm._groupings != NULL)) {
count[0] = _mm._lgroupings;
DBWriteComponent(dbfile, obj, "groupings", name, "integer",
_mm._groupings, 1, count);
}
/*-------------------------------------------------------------
* Add the DBOPT_MB_... options if present.
*-------------------------------------------------------------*/
if (_mm._file_ns)
{
count[0] = strlen(_mm._file_ns)+1;
DBWriteComponent(dbfile, obj, "file_ns", name, "char",
_mm._file_ns, 1, count);
}
if (_mm._block_ns)
{
count[0] = strlen(_mm._block_ns)+1;
DBWriteComponent(dbfile, obj, "block_ns", name, "char",
_mm._block_ns, 1, count);
}
if (_mm._block_type)
DBAddIntComponent(obj, "block_type", _mm._block_type);
if (_mm._empty_list && _mm._empty_cnt>0)
{
DBAddIntComponent(obj, "empty_cnt", _mm._empty_cnt);
count[0] = _mm._empty_cnt;
DBWriteComponent(dbfile, obj, "empty_list", name, "integer",
_mm._empty_list, 1, count);
}
if (_mm._repr_block_idx > 0)
DBAddIntComponent(obj, "repr_block_idx", _mm._repr_block_idx);
/*-------------------------------------------------------------
* Write multi-mesh object to SILO file.
*-------------------------------------------------------------*/
DBWriteObject(dbfile, obj, TRUE);
DBFreeObject(obj);
FREE(tmp);
return 0;
}
#endif /* PDB_WRITE */
/*----------------------------------------------------------------------
* Routine db_pdb_PutMultimeshadj
*
* Purpose
*
* Write some or all of a multi-block mesh adjacency object into the
* open SILO file. This routine is designed to permit multiple
* writes to the same object with different pieces being written
* each time.
*
* Programmer
*
* Mark C. Miller, August 23, 2005
*
*--------------------------------------------------------------------*/
#ifdef PDB_WRITE
SILO_CALLBACK int
db_pdb_PutMultimeshadj (DBfile *_dbfile, char const *name, int nmesh,
int const *meshtypes, int const *nneighbors,
int const *neighbors, int const *back,
int const *lnodelists, int const * const *nodelists,
int const *lzonelists, int const * const *zonelists,
DBoptlist const *optlist) {
long count[2];
int i, len, noff, zoff, lneighbors;
DBfile_pdb *dbfile = (DBfile_pdb*)_dbfile;
syment *ep;
dimdes *dimensions;
static char *me = "db_pdb_PutMultimeshadj";
char tmpn[256];
if ((ep=lite_PD_inquire_entry (dbfile->pdb, (char*)name, TRUE, NULL))) {
/*
* Object already exists. Do whatever sanity checking we can do without
* reading back problem-sized data. Basically, this means checking
* existence and size of various components.
*/
/* meshtypes should *always* exist and be of size nmesh */
db_mkname(dbfile->pdb, (char*)name, "meshtypes", tmpn);
if ((ep=lite_PD_inquire_entry(dbfile->pdb, tmpn, TRUE, NULL)))
{
len = 0;
for (dimensions=ep->dimensions; dimensions; dimensions=dimensions->next)
len += dimensions->number;
if (len != nmesh)
return db_perror("inconsistent meshtypes", E_BADARGS, me);
}
else
{
return db_perror("not a DBmultimeshadj object", E_BADARGS, me);
}
/* nneirhbors should *always* exist and be of size nmesh */
db_mkname(dbfile->pdb, (char*)name, "nneighbors", tmpn);
if ((ep=lite_PD_inquire_entry(dbfile->pdb, tmpn, TRUE, NULL)))
{
len = 0;
for (dimensions=ep->dimensions; dimensions; dimensions=dimensions->next)
len += dimensions->number;
if (len != nmesh)
return db_perror("inconsistent nneighbors", E_BADARGS, me);
}
else
{
return db_perror("not a DBmultimeshadj object", E_BADARGS, me);
}
/* compute expected size of neighbors array */
lneighbors = 0;
for (i = 0; i < nmesh; i++)
lneighbors += nneighbors[i];
/* neighbors should always exist and be of size lneighbors */
db_mkname(dbfile->pdb, (char*)name, "neighbors", tmpn);
if ((ep=lite_PD_inquire_entry(dbfile->pdb, tmpn, TRUE, NULL)))
{
len = 0;
for (dimensions=ep->dimensions; dimensions; dimensions=dimensions->next)
len += dimensions->number;
if (len != lneighbors)
return db_perror("inconsistent neighbors", E_BADARGS, me);
}
else
{
return db_perror("not a DBmultimeshadj object", E_BADARGS, me);
}
/* if lnodelists exists, it should be of size lneighbors AND it
should be non-NULL in the argument list. Otherwise, it should be NULL */
db_mkname(dbfile->pdb, (char*)name, "lnodelists", tmpn);
if ((ep=lite_PD_inquire_entry(dbfile->pdb, tmpn, TRUE, NULL)))
{
if (lnodelists == 0)
return db_perror("inconsistent lnodelists", E_BADARGS, me);
len = 0;
for (dimensions=ep->dimensions; dimensions; dimensions=dimensions->next)
len += dimensions->number;
if (len != lneighbors)
return db_perror("inconsistent lnodelists", E_BADARGS, me);
}
else
{
if (lnodelists != 0)
return db_perror("inconsistent lnodelists", E_BADARGS, me);
}
/* if lzonelists exists, it should be of size lneighbors AND it
should be non-NULL in the argument list. Otherwise, it should be NULL */
db_mkname(dbfile->pdb, (char*)name, "lzonelists", tmpn);
if ((ep=lite_PD_inquire_entry(dbfile->pdb, tmpn, TRUE, NULL)))
{
if (lzonelists == 0)
return db_perror("inconsistent lzonelists", E_BADARGS, me);
len = 0;
for (dimensions=ep->dimensions; dimensions; dimensions=dimensions->next)
len += dimensions->number;
if (len != lneighbors)
return db_perror("inconsistent lzonelists", E_BADARGS, me);
}
else
{
if (lzonelists != 0)
return db_perror("inconsistent lzonelists", E_BADARGS, me);
}
} else {
/*
* Object doesn't exist yet. Write all the object's invariant
* components and reserve space for the nodelists and/or
* zonelists and enter names in the symbol table.
*/
DBobject *obj;
/* compute length of neighbors, back, lnodelists, nodelists,
lzonelists, zonelists arrays */
lneighbors = 0;
for (i = 0; i < nmesh; i++)
lneighbors += nneighbors[i];
db_InitMulti(_dbfile, optlist);
obj = DBMakeObject(name, DB_MULTIMESHADJ, 13);
DBAddIntComponent(obj, "nblocks", nmesh);
DBAddIntComponent(obj, "blockorigin", _mm._blockorigin);
DBAddIntComponent(obj, "lneighbors", lneighbors);
count[0] = nmesh;
DBWriteComponent(_dbfile, obj, "meshtypes", name, "integer",
meshtypes, 1, count);
DBWriteComponent(_dbfile, obj, "nneighbors", name, "integer",
nneighbors, 1, count);
count[0] = lneighbors;
if (count[0] > 0) {
DBWriteComponent(_dbfile, obj, "neighbors", name, "integer",
neighbors, 1, count);
if (back) {
DBWriteComponent(_dbfile, obj, "back", name, "integer",
back, 1, count);
}
if (lnodelists) {
DBWriteComponent(_dbfile, obj, "lnodelists", name, "integer",
lnodelists, 1, count);
}
if (lzonelists) {
DBWriteComponent(_dbfile, obj, "lzonelists", name, "integer",
lzonelists, 1, count);
}
}
/* All object components up to here are invariant and *should*
be identical in repeated calls. Now, handle the parts of the
object that can vary from call to call. Reserve space for
the entire nodelists and/or zonelists arrays */
if (nodelists) {
/* compute total length of nodelists array */
len = 0;
for (i = 0; i < lneighbors; i++)
len += lnodelists[i];
if (len > 0) {
DBAddIntComponent(obj, "totlnodelists", len);
/* reserve space for the nodelists array in the file */
count[0] = 0;
count[1] = len - 1;
db_mkname(dbfile->pdb, (char*)name, "nodelists", tmpn);
if (!lite_PD_defent_alt (dbfile->pdb, tmpn, "integer", 1, count)) {
return db_perror ("PD_defent_alt", E_CALLFAIL, me) ;
}
/* add the nodelists array to this object */
DBAddVarComponent(obj, "nodelists", tmpn);
}
}
if (zonelists) {
/* compute total length of nodelists array */
len = 0;
for (i = 0; i < lneighbors; i++)
len += lzonelists[i];
if (len > 0) {
DBAddIntComponent(obj, "totlzonelists", len);
/* reserve space for the nodelists array in the file */
count[0] = 0;
count[1] = len - 1;
db_mkname(dbfile->pdb, (char*)name, "zonelists", tmpn);
if (!lite_PD_defent_alt (dbfile->pdb, tmpn, "integer", 1, count)) {
return db_perror ("PD_defent_alt", E_CALLFAIL, me) ;
}
/* add the nodelists array to this object */
DBAddVarComponent(obj, "zonelists", tmpn);
}
}
/* Ok, finally, create the object in the file */
DBWriteObject(_dbfile, obj, TRUE);
DBFreeObject(obj);
}
/* Ok, now write contents of nodelists and/or zonelists */
noff = 0;
zoff = 0;
for (i = 0; i < lneighbors; i++)
{
long dim_extents[3];
if (nodelists)
{
if (nodelists[i])
{
dim_extents[0] = noff;
dim_extents[1] = noff + lnodelists[i] - 1;
dim_extents[2] = 1;
db_mkname(dbfile->pdb, (char*)name, "nodelists", tmpn);
PJ_write_alt (dbfile->pdb, tmpn, "integer", (int*) nodelists[i], 1, dim_extents);
}
noff += lnodelists[i];
}
if (zonelists)
{
if (zonelists[i])
{
dim_extents[0] = zoff;
dim_extents[1] = zoff + lzonelists[i] - 1;
dim_extents[2] = 1;
db_mkname(dbfile->pdb, (char*)name, "zonelists", tmpn);
PJ_write_alt (dbfile->pdb, tmpn, "integer", (int*) zonelists[i], 1, dim_extents);
}
zoff += lzonelists[i];
}
}
return 0;
}
#endif
/*----------------------------------------------------------------------
* Routine db_pdb_PutMultivar
*
* Purpose
*
* Write a multi-block variable object into the open SILO file.
*
* Programmer
*
* Jeffery W. Long, NSSD-B
*
* Notes
*
* Modified
* Robb Matzke, Fri Dec 2 14:16:09 PST 1994
* Changed SCFREE(obj) to DBFreeObject(obj)
*
* Eric Brugger, Fri Jan 12 17:42:55 PST 1996
* I added cycle, time and dtime as options.
*
* Sean Ahern, Thu Aug 15 11:16:18 PDT 1996
* Allowed the mesh names to be any length, rather than hardcoded.
*
* Eric Brugger, Fri Oct 17 09:11:58 PDT 1997
* I corrected the outputing of the cyle, time and dtime options to
* use the values from the global _mm instead of _pm. A cut
* and paste error.
*
* Jeremy Meredith, Fri May 21 10:04:25 PDT 1999
* Added ngroups, blockorigin, and grouporigin.
*
* Hank Childs, Thu Jan 6 13:51:22 PST 2000
* Casted a strlen to long to remove a compiler warning.
*
* Hank Childs, Wed Apr 11 08:05:24 PDT 2001
* Concatenate strings more intelligently [HYPer02535].
*
* Hank Childs, Mon May 14 14:27:29 PDT 2001
* Fixed bug where there was an assumption that the string is
* NULL terminated.
*
* Mark C. Miller, Thu Nov 5 16:15:49 PST 2009
* Added support for conserved/extensive options.
*
* Mark C. Miller, Wed Jul 14 20:40:55 PDT 2010
* Added support for namescheme/empty list options.
*--------------------------------------------------------------------*/
#ifdef PDB_WRITE
SILO_CALLBACK int
db_pdb_PutMultivar (DBfile *dbfile, char const *name, int nvars,
char const * const *varnames, int const *vartypes, DBoptlist const *optlist) {
int i, len;
long count[3];
char *tmp = NULL, *cur = NULL;
DBobject *obj;
/*-------------------------------------------------------------
* Initialize global data, and process options.
*-------------------------------------------------------------*/
db_InitMulti(dbfile, optlist);
/*-------------------------------------------------------------
* Build object description from literals and var-id's
*-------------------------------------------------------------*/
obj = DBMakeObject(name, DB_MULTIVAR, 32);
DBAddIntComponent(obj, "nvars", nvars);
DBAddIntComponent(obj, "ngroups", _mm._ngroups);
DBAddIntComponent(obj, "blockorigin", _mm._blockorigin);
DBAddIntComponent(obj, "grouporigin", _mm._grouporigin);
if (_mm._guihide)
DBAddIntComponent(obj, "guihide", _mm._guihide);
if (_mm._region_pnames != NULL)
{
char *s=0; int len=0; long llen;
DBStringArrayToStringList((char const * const *)_mm._region_pnames, -1, &s, &len);
llen = len;
DBWriteComponent(dbfile, obj, "region_pnames", name, "char", s, 1, &llen);
FREE(s);
}
if (_mm._tensor_rank)
DBAddIntComponent(obj, "tensor_rank", _mm._tensor_rank);
if (_mm._mmesh_name != NULL)
DBAddStrComponent(obj, "mmesh_name", _mm._mmesh_name);
if (_mm._conserved)
DBAddIntComponent(obj, "conserved", _mm._conserved);
if (_mm._extensive)
DBAddIntComponent(obj, "extensive", _mm._extensive);
/*-------------------------------------------------------------
* Define and write variables before adding them to object.
*-------------------------------------------------------------*/
count[0] = nvars;
if (vartypes)
DBWriteComponent(dbfile, obj, "vartypes", name, "integer",
vartypes, 1, count);
/* Compute size needed for string of concatenated block names.
*
* Note that we start with 2 so that we have one `;' and the NULL
* terminator. Also, the +1 in the "len +=" line is for the `;'
* character.
*/
if (varnames)
{
len = 2;
for(i=0; i<nvars; i++)
{
len += strlen(varnames[i]) + 1;
}
tmp = ALLOC_N(char,len);
/* Build 1-D character string from 2-D mesh-name array */
tmp[0] = ';';
tmp[1] = '\0';
cur = tmp+1;
for (i = 0; i < nvars; i++) {
int len2;
len2 = strlen(varnames[i]);
strncpy(cur, varnames[i], len2);
cur += len2;
strncpy(cur, ";", 1);
cur += 1;
}
count[0] = (long) (cur - tmp);
DBWriteComponent(dbfile, obj, "varnames", name, "char",
tmp, 1, count);
}
/*-------------------------------------------------------------
* Define and write the time and cycle.
*-------------------------------------------------------------*/
DBAddIntComponent(obj, "cycle", _mm._cycle);
if (_mm._time_set == TRUE)
DBAddVarComponent(obj, "time", _mm._nm_time);
if (_mm._dtime_set == TRUE)
DBAddVarComponent(obj, "dtime", _mm._nm_dtime);
/*-------------------------------------------------------------
* Add the DBOPT_EXTENTS_SIZE and DBOPT_EXTENTS options if present.
*-------------------------------------------------------------*/
if (_mm._extents != NULL && _mm._extentssize > 0) {
DBAddIntComponent(obj, "extentssize", _mm._extentssize);
count[0] = _mm._extentssize * nvars;
DBWriteComponent(dbfile, obj, "extents", name, "double", _mm._extents,
1, count);
}
/*-------------------------------------------------------------
* Add the DBOPT_MB_... options if present.
*-------------------------------------------------------------*/
if (_mm._file_ns)
{
count[0] = strlen(_mm._file_ns)+1;
DBWriteComponent(dbfile, obj, "file_ns", name, "char",
_mm._file_ns, 1, count);
}
if (_mm._block_ns)
{
count[0] = strlen(_mm._block_ns)+1;
DBWriteComponent(dbfile, obj, "block_ns", name, "char",
_mm._block_ns, 1, count);
}
if (_mm._block_type)
DBAddIntComponent(obj, "block_type", _mm._block_type);
if (_mm._empty_list && _mm._empty_cnt>0) {
DBAddIntComponent(obj, "empty_cnt", _mm._empty_cnt);
count[0] = _mm._empty_cnt;
DBWriteComponent(dbfile, obj, "empty_list", name, "integer",
_mm._empty_list, 1, count);
}
if (_mm._repr_block_idx)
DBAddIntComponent(obj, "repr_block_idx", _mm._repr_block_idx);
if (_mm._missing_value != DB_MISSING_VALUE_NOT_SET)
{
if (_mm._missing_value == 0.0)
DBAddDblComponent(obj, "missing_value", DB_MISSING_VALUE_NOT_SET);
else
DBAddDblComponent(obj, "missing_value", _mm._missing_value);
}
/*-------------------------------------------------------------
* Write multi-var object to SILO file.
*-------------------------------------------------------------*/
DBWriteObject(dbfile, obj, TRUE);
DBFreeObject(obj);
FREE(tmp);
return 0;
}
#endif /* PDB_WRITE */
/*----------------------------------------------------------------------
* Routine db_pdb_PutMultimat
*
* Purpose
*
* Write a multi-material object into the open SILO file.
*
* Programmer
*
* robb@cloud
* Tue Feb 21 12:42:07 EST 1995
*
* Notes
*
* Modified
* Eric Brugger, Fri Jan 12 17:42:55 PST 1996
* I added cycle, time and dtime as options.
*
* Sean Ahern, Thu Aug 15 11:16:18 PDT 1996
* Allowed the mesh names to be any length, rather than hardcoded.
*
* Eric Brugger, Fri Oct 17 09:11:58 PDT 1997
* I corrected the outputing of the cyle, time and dtime options to
* use the values from the global _mm instead of _pm. A cut
* and paste error. I added code to write out the DPOPT_NMATNOS
* and DPOPT_MATNOS options if provided.
*
* Jeremy Meredith, Sept 23 1998
* Corrected a bug where 'browser' wouldn't read "matnos": changed
* type used when writing "matnos" from "int" to "integer".
*
* Jeremy Meredith, Fri May 21 10:04:25 PDT 1999
* Added ngroups, blockorigin, and grouporigin.
*
* Hank Childs, Thu Jan 6 13:51:22 PST 2000
* Cast a strlen to long to avoid a compiler warning.
*
* Hank Childs, Wed Apr 11 08:05:24 PDT 2001
* Concatenate strings more intelligently [HYPer02535].
*
* Hank Childs, Mon May 14 14:27:29 PDT 2001
* Fixed bug where there was an assumption that the string is
* NULL terminated.
*
* Mark C. Miller, Mon Aug 7 17:03:51 PDT 2006
* Added matnames and matcolors options
*
* Mark C. Miller, Wed Jul 14 20:40:55 PDT 2010
* Added support for namescheme/empty list options.
*--------------------------------------------------------------------*/
#ifdef PDB_WRITE
SILO_CALLBACK int
db_pdb_PutMultimat (DBfile *dbfile, char const *name, int nmats,
char const * const *matnames, DBoptlist const *optlist) {
int i, len;
long count[3];
char *tmp = NULL, *cur = NULL;
DBobject *obj;
/*-------------------------------------------------------------
* Initialize global data, and process options.
*-------------------------------------------------------------*/
db_InitMulti(dbfile, optlist);
/*-------------------------------------------------------------
* Build object description from literals and var-id's
*-------------------------------------------------------------*/
obj = DBMakeObject(name, DB_MULTIMAT, 31);
DBAddIntComponent(obj, "nmats", nmats);
DBAddIntComponent(obj, "ngroups", _mm._ngroups);
DBAddIntComponent(obj, "blockorigin", _mm._blockorigin);
DBAddIntComponent(obj, "grouporigin", _mm._grouporigin);
if (_mm._allowmat0)
DBAddIntComponent(obj, "allowmat0", _mm._allowmat0);
if (_mm._guihide)
DBAddIntComponent(obj, "guihide", _mm._guihide);
if (_mm._mmesh_name != NULL)
DBAddStrComponent(obj, "mmesh_name", _mm._mmesh_name);
/*-------------------------------------------------------------
* Define and write materials before adding them to object.
*-------------------------------------------------------------*/
/* Compute size needed for string of concatenated block names.
*
* Note that we start with 2 so that we have one `;' and the NULL
* terminator. Also, the +1 in the "len +=" line is for the `;'
* character.
*/
if (matnames)
{
len = 2;
for(i=0; i<nmats; i++)
{
len += strlen(matnames[i]) + 1;
}
tmp = ALLOC_N(char,len);
/* Build 1-D character string from 2-D mesh-name array */
tmp[0] = ';';
tmp[1] = '\0';
cur = tmp+1;
for (i = 0; i < nmats; i++) {
int len2;
len2 = strlen(matnames[i]);
strncpy(cur, matnames[i], len2);
cur += len2;
strncpy(cur, ";", 1);
cur += 1;
}
count[0] = (long) (cur - tmp);
DBWriteComponent(dbfile, obj, "matnames", name, "char",
tmp, 1, count);
}
/*-------------------------------------------------------------
* Define and write the time and cycle.
*-------------------------------------------------------------*/
DBAddIntComponent(obj, "cycle", _mm._cycle);
if (_mm._time_set == TRUE)
DBAddVarComponent(obj, "time", _mm._nm_time);
if (_mm._dtime_set == TRUE)
DBAddVarComponent(obj, "dtime", _mm._nm_dtime);
/*-------------------------------------------------------------
* Add the DBOPT_MATNOS and DBOPT_NMATNOS options if present.
*-------------------------------------------------------------*/
if (_mm._matnos != NULL && _mm._nmatnos > 0) {
DBAddIntComponent(obj, "nmatnos", _mm._nmatnos);
count[0] = _mm._nmatnos;
DBWriteComponent(dbfile, obj, "matnos", name, "integer", _mm._matnos,
1, count);
}
/*-------------------------------------------------------------
* Add the DBOPT_MIXLENS option if present.
*-------------------------------------------------------------*/
if (_mm._mixlens != NULL) {
count[0] = nmats;
DBWriteComponent(dbfile, obj, "mixlens", name, "integer", _mm._mixlens,
1, count);
}
/*-------------------------------------------------------------
* Add the DBOPT_MATCOUNTS and DBOPT_MATLISTS options if present.
*-------------------------------------------------------------*/
if (_mm._matcounts != NULL && _mm._matlists != NULL) {
long tot = 0;
for (i = 0; i < nmats; i++)
tot += _mm._matcounts[i];
if (tot) {
count[0] = nmats;
DBWriteComponent(dbfile, obj, "matcounts", name, "integer", _mm._matcounts, 1, count);
DBWriteComponent(dbfile, obj, "matlists", name, "integer", _mm._matlists, 1, &tot);
}
}
/*-------------------------------------------------------------
* Add the DBOPT_MATNAMES option if present
*-------------------------------------------------------------*/
if (_mm._matnames && _mm._nmatnos > 0) {
int len; long llen; char *tmpstr = 0;
DBStringArrayToStringList((char const * const *)_mm._matnames, _mm._nmatnos,
&tmpstr, &len);
llen = (long) len;
DBWriteComponent(dbfile, obj, "material_names", name, "char", tmpstr, 1, &llen);
FREE(tmpstr);
_mm._matnames = 0;
}
/*-------------------------------------------------------------
* Add the DBOPT_MATCOLORS option if present
*-------------------------------------------------------------*/
if (_mm._matcolors && _mm._nmatnos > 0) {
int len; long llen; char *tmpstr = 0;
DBStringArrayToStringList((char const * const *)_mm._matcolors, _mm._nmatnos,
&tmpstr, &len);
llen = (long) len;
DBWriteComponent(dbfile, obj, "matcolors", name, "char", tmpstr, 1, &llen);
FREE(tmpstr);
_mm._matcolors = 0;
}
/*-------------------------------------------------------------
* Add the DBOPT_MB_... options if present.
*-------------------------------------------------------------*/
if (_mm._file_ns)
{
count[0] = strlen(_mm._file_ns)+1;
DBWriteComponent(dbfile, obj, "file_ns", name, "char",
_mm._file_ns, 1, count);
}
if (_mm._block_ns)
{
count[0] = strlen(_mm._block_ns)+1;
DBWriteComponent(dbfile, obj, "block_ns", name, "char",
_mm._block_ns, 1, count);
}
if (_mm._empty_list && _mm._empty_cnt>0) {
DBAddIntComponent(obj, "empty_cnt", _mm._empty_cnt);
count[0] = _mm._empty_cnt;
DBWriteComponent(dbfile, obj, "empty_list", name, "integer",
_mm._empty_list, 1, count);
}
if (_mm._repr_block_idx)
DBAddIntComponent(obj, "repr_block_idx", _mm._repr_block_idx);
/*-------------------------------------------------------------
* Write multi-material object to SILO file.
*-------------------------------------------------------------*/
DBWriteObject(dbfile, obj, TRUE);
DBFreeObject(obj);
FREE(tmp);
return 0;
}
#endif /* PDB_WRITE */
/*----------------------------------------------------------------------
* Routine db_pdb_PutMultimatspecies
*
* Purpose
*
* Write a multi-species object into the open SILO file.
*
* Programmer
* Jeremy S. Meredith
* Sept 17 1998
*
* Notes
*
* Modified
*
* Jeremy Meredith, Fri May 21 10:04:25 PDT 1999
* Added ngroups, blockorigin, and grouporigin.
*
* Hank Childs, Thu Jan 6 13:51:22 PST 2000
* Cast a strlen to long to avoid a compiler warning.
*
* Jeremy Meredith, Thu Feb 10 16:00:53 PST 2000
* Fixed an off-by-one error on the max number of components.
*
* Hank Childs, Wed Apr 11 08:05:24 PDT 2001
* Concatenate strings more intelligently [HYPer02535].
*
* Hank Childs, Mon May 14 14:27:29 PDT 2001
* Fixed bug where there was an assumption that the string is
* NULL terminated.
*
* Mark C. Miller, Tue Sep 8 15:40:51 PDT 2009
* Added names and colors for species.
*
* Mark C. Miller, Wed Jul 14 20:40:55 PDT 2010
* Added support for namescheme/empty list options.
*--------------------------------------------------------------------*/
#ifdef PDB_WRITE
SILO_CALLBACK int
db_pdb_PutMultimatspecies (DBfile *dbfile, char const *name, int nspec,
char const * const *specnames, DBoptlist const *optlist) {
int i, len, nstrs;
long count[3];
char *tmp = NULL, *cur = NULL;
DBobject *obj;
/*-------------------------------------------------------------
* Initialize global data, and process options.
*-------------------------------------------------------------*/
db_InitMulti(dbfile, optlist);
/*-------------------------------------------------------------
* Build object description from literals and var-id's
*-------------------------------------------------------------*/
obj = DBMakeObject(name, DB_MULTIMATSPECIES, 31);
DBAddIntComponent(obj, "nspec", nspec);
DBAddIntComponent(obj, "ngroups", _mm._ngroups);
DBAddIntComponent(obj, "blockorigin", _mm._blockorigin);
DBAddIntComponent(obj, "grouporigin", _mm._grouporigin);
if (_mm._guihide)
DBAddIntComponent(obj, "guihide", _mm._guihide);
/*-------------------------------------------------------------
* Define and write species before adding them to object.
*-------------------------------------------------------------*/
/* Compute size needed for string of concatenated block names.
*
* Note that we start with 2 so that we have one `;' and the NULL
* terminator. Also, the +1 in the "len +=" line is for the `;'
* character.
*/
if (specnames)
{
len = 2;
for(i=0; i<nspec; i++)
{
len += strlen(specnames[i]) + 1;
}
tmp = ALLOC_N(char,len);
/* Build 1-D character string from 2-D mesh-name array */
tmp[0] = ';';
tmp[1] = '\0';
cur = tmp+1;
for (i = 0; i < nspec; i++) {
int len2;
len2 = strlen(specnames[i]);
strncpy(cur, specnames[i], len2);
cur += len2;
strncpy(cur, ";", 1);
cur += 1;
}
count[0] = (long) (cur - tmp);
DBWriteComponent(dbfile, obj, "specnames", name, "char",
tmp, 1, count);
}
/*-------------------------------------------------------------
* Define and write the time and cycle.
*-------------------------------------------------------------*/
DBAddIntComponent(obj, "cycle", _mm._cycle);
if (_mm._time_set == TRUE)
DBAddVarComponent(obj, "time", _mm._nm_time);
if (_mm._dtime_set == TRUE)
DBAddVarComponent(obj, "dtime", _mm._nm_dtime);
/*-------------------------------------------------------------
* Write the DBOPT_MATNAME, _NMAT, and _NMATSPEC to the file.
*-------------------------------------------------------------*/
if (_mm._matname != NULL)
DBAddStrComponent(obj, "matname", _mm._matname);
if (_mm._nmat > 0 && _mm._nmatspec != NULL) {
DBAddIntComponent(obj, "nmat", _mm._nmat);
count[0]=_mm._nmat;
DBWriteComponent(dbfile, obj, "nmatspec", name, "integer", _mm._nmatspec,
1, count);
/* If we have species names or colors, write them out */
nstrs = 0;
if (_mm._specnames != NULL)
{
int len; long llen; char *tmpstr = 0;
/* count how many names we have */
for (i=0; i < _mm._nmat; i++)
nstrs += _mm._nmatspec[i];
DBStringArrayToStringList((char const * const *)_mm._specnames, nstrs, &tmpstr, &len);
llen = (long) len;
DBWriteComponent(dbfile, obj, "species_names", name, "char", tmpstr, 1, &llen);
FREE(tmpstr);
}
if (_mm._speccolors != NULL)
{
int len; long llen; char *tmpstr = 0;
/* count how many names we have */
if (nstrs == 0)
{
for (i=0; i < _mm._nmat; i++)
nstrs += _mm._nmatspec[i];
}
DBStringArrayToStringList((char const * const *)_mm._speccolors, nstrs, &tmpstr, &len);
llen = (long) len;
DBWriteComponent(dbfile, obj, "speccolors", name, "char", tmpstr, 1, &llen);
FREE(tmpstr);
}
}
/*-------------------------------------------------------------
* Add the DBOPT_MB_... options if present.
*-------------------------------------------------------------*/
if (_mm._file_ns)
{
count[0] = strlen(_mm._file_ns)+1;
DBWriteComponent(dbfile, obj, "file_ns", name, "char",
_mm._file_ns, 1, count);
}
if (_mm._block_ns)
{
count[0] = strlen(_mm._block_ns)+1;
DBWriteComponent(dbfile, obj, "block_ns", name, "char",
_mm._block_ns, 1, count);
}
if (_mm._empty_list && _mm._empty_cnt>0) {
DBAddIntComponent(obj, "empty_cnt", _mm._empty_cnt);
count[0] = _mm._empty_cnt;
DBWriteComponent(dbfile, obj, "empty_list", name, "integer",
_mm._empty_list, 1, count);
}
if (_mm._repr_block_idx)
DBAddIntComponent(obj, "repr_block_idx", _mm._repr_block_idx);
/*-------------------------------------------------------------
* Write multi-species object to SILO file.
*-------------------------------------------------------------*/
DBWriteObject(dbfile, obj, TRUE);
DBFreeObject(obj);
FREE(tmp);
return 0;
}
#endif /* PDB_WRITE */
/*----------------------------------------------------------------------
* Routine db_pdb_PutPointmesh
*
* Purpose
*
* Write a point mesh object into the open output file.
*
* Programmer
*
* Jeffery W. Long, NSSD-B
*
* Notes
*
* Modifications
*
* Al Leibee, Mon Apr 18 07:45:58 PDT 1994
* Added _dtime.
*
* Robb Matzke, Fri Dec 2 14:16:41 PST 1994
* Changed SCFREE(obj) to DBFreeObject(obj)
*
* Robb Matzke, Sun Dec 18 17:07:34 EST 1994
* Changed SW_GetDatatypeString to db_GetDatatypeString and
* removed associated memory leak.
*
* Sean Ahern, Sun Oct 1 03:15:18 PDT 1995
* Made "me" static.
*
* Robb Matzke, 11 Nov 1997
* Added `datatype' to the file.
*
* Jeremy Meredith, Fri May 21 10:04:25 PDT 1999
* Added group_no.
*
* Eric Brugger, Fri Mar 8 12:23:35 PST 2002
* I modified the routine to output min and max extents as either
* float or doubles, depending on the datatype of the coordinates.
*
* Mark C. Miller, Fri Nov 13 15:26:38 PST 2009
* Add support for long long global node/zone numbers.
*
* Mark C. Miller, Sat Nov 14 20:28:34 PST 2009
* Changed how long long global node/zone numbers are supported
* from a int (bool), "llong_gnode|zoneno" to an int holding
* the actual datatype. The type is assumed int if it its
* value is zero or it does not exist. Otherwise, the type is
* is whatever is stored in gnznodtype member.
*
* Mark C. Miller, Tue Nov 17 22:22:09 PST 2009
* Changed name of long long datatype to match what PDB proper
* would call it.
*--------------------------------------------------------------------*/
#ifdef PDB_WRITE
SILO_CALLBACK int
db_pdb_PutPointmesh (DBfile *dbfile, char const *name, int ndims, DBVCP2_t _coords,
int nels, int datatype, DBoptlist const *optlist) {
int i;
long count[3];
DBobject *obj;
char *datatype_str, tmp[1024];
float fmin_extents[3], fmax_extents[3];
double dmin_extents[3], dmax_extents[3];
static char *me = "db_pdb_PutPointmesh";
void const * const *coords = (void const * const *) _coords;
/*-------------------------------------------------------------
* Initialize global data, and process options.
*-------------------------------------------------------------*/
db_InitPoint(dbfile, optlist, ndims, nels);
obj = DBMakeObject(name, DB_POINTMESH, 31);
/*-------------------------------------------------------------
* Write coordinate arrays.
*-------------------------------------------------------------*/
datatype_str = db_GetDatatypeString(datatype);
count[0] = nels;
for (i = 0; i < ndims && nels; i++) {
sprintf(tmp, "coord%d", i);
DBWriteComponent(dbfile, obj, tmp, name, datatype_str,
coords[i], 1, count);
}
FREE(datatype_str);
/*-------------------------------------------------------------
* Find the mesh extents from the coordinate arrays. Write
* them out to output file.
*-------------------------------------------------------------*/
count[0] = ndims;
if (ndims && nels) {
switch (datatype) {
case DB_FLOAT:
switch (ndims) {
case 3:
_DBarrminmax((float*)coords[2], nels, &fmin_extents[2], &fmax_extents[2]);
case 2:
_DBarrminmax((float*)coords[1], nels, &fmin_extents[1], &fmax_extents[1]);
case 1:
_DBarrminmax((float*)coords[0], nels, &fmin_extents[0], &fmax_extents[0]);
break;
default:
return db_perror("ndims", E_BADARGS, me);
}
DBWriteComponent(dbfile, obj, "min_extents", name, "float",
fmin_extents, 1, count);
DBWriteComponent(dbfile, obj, "max_extents", name, "float",
fmax_extents, 1, count);
break;
case DB_DOUBLE:
switch (ndims) {
case 3:
_DBdarrminmax((double *)coords[2], nels,
&dmin_extents[2], &dmax_extents[2]);
case 2:
_DBdarrminmax((double *)coords[1], nels,
&dmin_extents[1], &dmax_extents[1]);
case 1:
_DBdarrminmax((double *)coords[0], nels,
&dmin_extents[0], &dmax_extents[0]);
break;
default:
return db_perror("ndims", E_BADARGS, me);
}
DBWriteComponent(dbfile, obj, "min_extents", name, "double",
dmin_extents, 1, count);
DBWriteComponent(dbfile, obj, "max_extents", name, "double",
dmax_extents, 1, count);
break;
default:
return db_perror("type not supported", E_NOTIMP, me);
}
}
if (nels>0 && _pm._gnodeno)
{
count[0] = nels;
if (_pm._llong_gnodeno)
DBWriteComponent(dbfile, obj, "gnodeno", name, "long_long",
_pm._gnodeno, 1, count);
else
DBWriteComponent(dbfile, obj, "gnodeno", name, "integer",
_pm._gnodeno, 1, count);
}
/*-------------------------------------------------------------
* Build a SILO object definition for a point mesh. The minimum
* required information for a point mesh is the coordinate arrays,
* the number of dimensions, and the type (RECT/CURV). Process
* the provided options to complete the definition.
*
* The SILO object definition is composed of a string of delimited
* component names plus an array of SILO *identifiers* of
* previously defined variables.
*-------------------------------------------------------------*/
DBAddIntComponent(obj, "ndims", ndims);
DBAddIntComponent(obj, "nspace", _pm._nspace);
DBAddIntComponent(obj, "nels", _pm._nels);
DBAddIntComponent(obj, "cycle", _pm._cycle);
DBAddIntComponent(obj, "origin", _pm._origin);
DBAddIntComponent(obj, "min_index", _pm._minindex);
DBAddIntComponent(obj, "max_index", _pm._maxindex);
DBAddIntComponent(obj, "datatype", datatype);
if (_pm._llong_gnodeno)
DBAddIntComponent(obj, "gnznodtype", DB_LONG_LONG);
if (_pm._guihide)
DBAddIntComponent(obj, "guihide", _pm._guihide);
if (_pm._group_no >= 0)
DBAddIntComponent(obj, "group_no", _pm._group_no);
if (_pm._time_set == TRUE)
DBAddVarComponent(obj, "time", _pm._nm_time);
if (_pm._dtime_set == TRUE)
DBAddVarComponent(obj, "dtime", _pm._nm_dtime);
/*-------------------------------------------------------------
* Process character strings: labels & units for x, y, &/or z,
*-------------------------------------------------------------*/
if (_pm._labels[0] != NULL)
DBAddStrComponent(obj, "label0", _pm._labels[0]);
if (_pm._labels[1] != NULL)
DBAddStrComponent(obj, "label1", _pm._labels[1]);
if (_pm._labels[2] != NULL)
DBAddStrComponent(obj, "label2", _pm._labels[2]);
if (_pm._units[0] != NULL)
DBAddStrComponent(obj, "units0", _pm._units[0]);
if (_pm._units[1] != NULL)
DBAddStrComponent(obj, "units1", _pm._units[1]);
if (_pm._units[2] != NULL)
DBAddStrComponent(obj, "units2", _pm._units[2]);
if (_pm._mrgtree_name != NULL)
DBAddStrComponent(obj, "mrgtree_name", _pm._mrgtree_name);
if (nels>0 && _pm._ghost_node_labels != NULL)
{
count[0] = nels;
DBWriteComponent(dbfile, obj, "ghost_node_labels", name, "char",
_pm._ghost_node_labels, 1, count);
}
if (nels>0 && _pm._alt_nodenum_vars)
{
int nvars=-1, len; long llen; char *tmpstr = 0;
DBStringArrayToStringList((char const * const *)_pm._alt_nodenum_vars, nvars, &tmpstr, &len);
llen = (long) len;
DBWriteComponent(dbfile, obj, "alt_nodenum_vars", name, "char", tmpstr, 1, &llen);
FREE(tmpstr);
}
/*-------------------------------------------------------------
* Write point-mesh object to output file.
*-------------------------------------------------------------*/
DBWriteObject(dbfile, obj, TRUE);
DBFreeObject(obj);
return (OKAY);
}
#endif /* PDB_WRITE */
/*----------------------------------------------------------------------
* Routine db_pdb_PutPointvar
*
* Purpose
*
* Write a point variable object into the open output file.
*
* Programmer
*
* Jeffery W. Long, NSSD-B
*
* Notes
*
* Modifications
*
* Robb Matzke, Sun Dec 18 17:08:42 EST 1994
* Changed SW_GetDatatypeString to db_GetDatatypeString and removed
* associated memory leak.
*
* Robb Matzke, Fri Dec 2 14:17:15 PST 1994
* Changed SCFREE(obj) to DBFreeObject(obj)
*
* Al Leibee, Mon Apr 18 07:45:58 PDT 1994
* Added _dtime.
*
* Sean Ahern, Tue Mar 24 17:23:04 PST 1998
* Bumped up the min number of attributes so that we can write out 3D
* point meshes.
*
* Mark C. Miller, Tue Sep 6 11:05:58 PDT 2005
* Removed duplicate DBAddStr call for "meshid"
*
* Mark C. Miller, Thu Nov 5 16:15:49 PST 2009
* Added support for conserved/extensive options.
*--------------------------------------------------------------------*/
#ifdef PDB_WRITE
SILO_CALLBACK int
db_pdb_PutPointvar (DBfile *dbfile, char const *name, char const *meshname, int nvars,
DBVCP2_t _vars, int nels, int datatype,
DBoptlist const *optlist) {
int i;
long count[3];
DBobject *obj;
char *datatype_str;
char tmp[1024];
void const * const *vars = (void const * const *) _vars;
/*-------------------------------------------------------------
* Initialize global data, and process options.
*-------------------------------------------------------------*/
db_InitPoint(dbfile, optlist, _pm._ndims, nels);
obj = DBMakeObject(name, DB_POINTVAR, nvars+20);
/*-------------------------------------------------------------
* Write variable arrays.
* Set index variables and counters.
*-----------------------------------------------------------*/
if (nels>0 && nvars>0)
{
datatype_str = db_GetDatatypeString(datatype);
count[0] = nels;
if (nvars == 1) {
DBWriteComponent(dbfile, obj, "_data", name, datatype_str,
vars[0], 1, count);
}
else {
for (i = 0; i < nvars; i++) {
sprintf(tmp, "%d_data", i);
DBWriteComponent(dbfile, obj, tmp, name, datatype_str,
vars[i], 1, count);
}
}
FREE(datatype_str);
}
/*-------------------------------------------------------------
* Build a SILO object definition for a point var. The
* minimum required information for a point var is the variable
* itself, plus the ID for the associated point mesh object.
* Process any additional options to complete the definition.
*-------------------------------------------------------------*/
DBAddStrComponent(obj, "meshid", meshname);
if (_pm._time_set == TRUE)
DBAddVarComponent(obj, "time", _pm._nm_time);
if (_pm._dtime_set == TRUE)
DBAddVarComponent(obj, "dtime", _pm._nm_dtime);
DBAddIntComponent(obj, "nvals", nvars);
DBAddIntComponent(obj, "nels", nels);
DBAddIntComponent(obj, "ndims", _pm._ndims);
DBAddIntComponent(obj, "datatype", datatype);
DBAddIntComponent(obj, "nspace", _pm._nspace);
DBAddIntComponent(obj, "origin", _pm._origin);
DBAddIntComponent(obj, "cycle", _pm._cycle);
DBAddIntComponent(obj, "min_index", _pm._minindex);
DBAddIntComponent(obj, "max_index", _pm._maxindex);
if (_pm._guihide)
DBAddIntComponent(obj, "guihide", _pm._guihide);
if (_pm._ascii_labels)
DBAddIntComponent(obj, "ascii_labels", _pm._ascii_labels);
/*-------------------------------------------------------------
* Process character strings: labels & units for variable.
*-------------------------------------------------------------*/
if (_pm._label != NULL)
DBAddStrComponent(obj, "label", _pm._label);
if (_pm._unit != NULL)
DBAddStrComponent(obj, "units", _pm._unit);
if (_pm._region_pnames != NULL)
{
char *s=0; int len=0; long llen;
DBStringArrayToStringList((char const * const *)_pm._region_pnames, -1, &s, &len);
llen = len;
DBWriteComponent(dbfile, obj, "region_pnames", name, "char", s, 1, &llen);
FREE(s);
}
if (_pm._conserved)
DBAddIntComponent(obj, "conserved", _pm._conserved);
if (_pm._extensive)
DBAddIntComponent(obj, "extensive", _pm._extensive);
if (_pm._missing_value != DB_MISSING_VALUE_NOT_SET)
{
if (_pm._missing_value == 0.0)
DBAddDblComponent(obj, "missing_value", DB_MISSING_VALUE_NOT_SET);
else
DBAddDblComponent(obj, "missing_value", _pm._missing_value);
}
/*-------------------------------------------------------------
* Write point-mesh object to output file.
*-------------------------------------------------------------*/
DBWriteObject(dbfile, obj, 0);
DBFreeObject(obj);
return 0;
}
#endif /* PDB_WRITE */
/*----------------------------------------------------------------------
* Routine db_pdb_PutQuadmesh
*
* Purpose
*
* Write a quad mesh object into the open SILO file.
*
* Programmer
*
* Jeffery W. Long, NSSD-B
*
* Notes
*
* Modifications
*
* Robb Matzke, Sun Dec 18 17:10:00 EST 1994
* Changed SW_GetDatatypeString to db_GetDatatypeString and removed
* associated memory leak.
*
* Robb Matzke, Fri Dec 2 14:17:56 PST 1994
* Changed SCFREE(obj) to DBFreeObject(obj)
*
* Robb Matzke, Wed Nov 23 12:00:20 EST 1994
* Increased third argument of DBMakeObject from 25 to 40 because
* we were running out of room. Thanks to the new error mechanism,
* we actually got a message for this!
*
* Al Leibee, Sun Apr 17 07:54:25 PDT 1994
* Added dtime.
*
* Sean Ahern, Fri Oct 16 17:48:23 PDT 1998
* Reformatted whitespace.
*
* Sean Ahern, Tue Oct 20 17:22:58 PDT 1998
* Changed the extents so that they are written out in the datatype that
* is passed to the call.
*
* Jeremy Meredith, Fri May 21 10:04:25 PDT 1999
* Added group_no and base_index[].
*
* Hank Childs, Thu Jan 6 13:48:40 PST 2000
* Put in lint directive for unused argument.
*
*--------------------------------------------------------------------*/
#ifdef PDB_WRITE
/* ARGSUSED */
SILO_CALLBACK int
db_pdb_PutQuadmesh (DBfile *dbfile, char const *name, char const * const *coordnames,
DBVCP2_t _coords, int const *dims, int ndims, int datatype,
int coordtype, DBoptlist const *optlist)
{
int i;
long count[3];
int nd;
char *datatype_str;
DBobject *obj;
char tmp[1024];
void const * const *coords = (void const * const *) _coords;
int is_empty = 1;
/* The following is declared as double for worst case. */
double min_extents[3]={0,0,0}, max_extents[3]={0,0,0};
/*-------------------------------------------------------------
* Initialize global data, and process options.
*-------------------------------------------------------------*/
db_InitQuad(dbfile, name, optlist, dims, ndims);
obj = DBMakeObject(name, coordtype, 44);
/*-------------------------------------------------------------
* Write coordinate arrays.
*-------------------------------------------------------------*/
for (i = 0; i < ndims; i++)
{
if (dims[i] > 0)
{
is_empty = 0;
break;
}
}
for (i = 0; i < ndims; i++)
count[i] = dims[i];
if (coordtype == DB_COLLINEAR)
nd = 1;
else
nd = ndims;
datatype_str = db_GetDatatypeString(datatype);
for (i = 0; (i < ndims) && !is_empty; i++)
{
if (coordtype == DB_COLLINEAR)
count[0] = dims[i];
/* Do coordinate array, in form: coordN, where n = 0, 1, ... */
sprintf(tmp, "coord%d", i);
DBWriteComponent(dbfile, obj, tmp, name, datatype_str,
coords[i], nd, count);
}
/*-------------------------------------------------------------
* Find the mesh extents from the coordinate arrays. Write
* them out to SILO file.
*-------------------------------------------------------------*/
_DBQMCalcExtents(coords, datatype, _qm._minindex, _qm._maxindex_n, dims,
ndims, coordtype, min_extents, max_extents);
count[0] = ndims;
DBWriteComponent(dbfile, obj, "min_extents", name, datatype_str,
min_extents, 1, count);
DBWriteComponent(dbfile, obj, "max_extents", name, datatype_str,
max_extents, 1, count);
FREE(datatype_str);
/*-------------------------------------------------------------
* Build a SILO object definition for a quad mesh. The minimum
* required information for a quad mesh is the coordinate arrays,
* the number of dimensions, and the type (RECT/CURV). Process
* the provided options to complete the definition.
*
* The SILO object definition is composed of a string of delimited
* component names plus an array of internal PDB variable names.
*-------------------------------------------------------------*/
DBAddIntComponent(obj, "ndims", ndims);
DBAddIntComponent(obj, "coordtype", coordtype);
DBAddIntComponent(obj, "datatype", datatype);
DBAddIntComponent(obj, "nspace", _qm._nspace);
DBAddIntComponent(obj, "nnodes", _qm._nnodes);
DBAddIntComponent(obj, "facetype", _qm._facetype);
DBAddIntComponent(obj, "major_order", _qm._majororder);
DBAddIntComponent(obj, "cycle", _qm._cycle);
DBAddIntComponent(obj, "coord_sys", _qm._coord_sys);
DBAddIntComponent(obj, "planar", _qm._planar);
DBAddIntComponent(obj, "origin", _qm._origin);
if (_qm._group_no >= 0)
DBAddIntComponent(obj, "group_no", _qm._group_no);
DBAddVarComponent(obj, "dims", _qm._nm_dims);
DBAddVarComponent(obj, "min_index", _qm._nm_minindex);
DBAddVarComponent(obj, "max_index", _qm._nm_maxindex_n);
DBAddVarComponent(obj, "baseindex", _qm._nm_baseindex);
if (_qm._time_set == TRUE)
DBAddVarComponent(obj, "time", _qm._nm_time);
if (_qm._dtime_set == TRUE)
DBAddVarComponent(obj, "dtime", _qm._nm_dtime);
/*-------------------------------------------------------------
* Process character strings: labels & units for x, y, &/or z,
*-------------------------------------------------------------*/
if (_qm._labels[0] != NULL)
DBAddStrComponent(obj, "label0", _qm._labels[0]);
if (_qm._labels[1] != NULL)
DBAddStrComponent(obj, "label1", _qm._labels[1]);
if (_qm._labels[2] != NULL)
DBAddStrComponent(obj, "label2", _qm._labels[2]);
if (_qm._units[0] != NULL)
DBAddStrComponent(obj, "units0", _qm._units[0]);
if (_qm._units[1] != NULL)
DBAddStrComponent(obj, "units1", _qm._units[1]);
if (_qm._units[2] != NULL)
DBAddStrComponent(obj, "units2", _qm._units[2]);
if (_qm._guihide)
DBAddIntComponent(obj, "guihide", _qm._guihide);
if (_qm._mrgtree_name != NULL)
DBAddStrComponent(obj, "mrgtree_name", _qm._mrgtree_name);
if (!is_empty && _qm._ghost_node_labels != NULL)
{
for (i = 0; i < ndims; i++)
count[i] = dims[i];
DBWriteComponent(dbfile, obj, "ghost_node_labels", name, "char",
_qm._ghost_node_labels, ndims, count);
}
if (!is_empty && _qm._ghost_zone_labels != NULL)
{
for (i = 0; i < ndims; i++)
count[i] = dims[i]-1;
DBWriteComponent(dbfile, obj, "ghost_zone_labels", name, "char",
_qm._ghost_zone_labels, ndims, count);
}
if (!is_empty && _qm._alt_nodenum_vars)
{
int nvars=-1, len; long llen; char *tmpstr = 0;
DBStringArrayToStringList((char const * const *)_qm._alt_nodenum_vars, nvars, &tmpstr, &len);
llen = (long) len;
DBWriteComponent(dbfile, obj, "alt_nodenum_vars", name, "char", tmpstr, 1, &llen);
FREE(tmpstr);
}
if (!is_empty && _qm._alt_zonenum_vars)
{
int nvars=-1, len; long llen; char *tmpstr = 0;
DBStringArrayToStringList((char const * const *)_qm._alt_zonenum_vars, nvars, &tmpstr, &len);
llen = (long) len;
DBWriteComponent(dbfile, obj, "alt_zonenum_vars", name, "char", tmpstr, 1, &llen);
FREE(tmpstr);
}
/*-------------------------------------------------------------
* Write quad-mesh object to SILO file.
*-------------------------------------------------------------*/
DBWriteObject(dbfile, obj, TRUE);
DBFreeObject(obj);
return 0;
}
#endif /* PDB_WRITE */
/*----------------------------------------------------------------------
* Routine db_pdb_PutQuadvar
*
* Purpose
*
* Write a quad variable object into the open SILO file.
*
* Programmer
*
* Jeffery W. Long, NSSD-B
*
* Notes
*
* Modifications
*
* Al Leibee, Sun Apr 17 07:54:25 PDT 1994
* Added dtime.
*
* Al Leibee, Wed Jul 20 07:56:37 PDT 1994
* Added write of mixlen component.
*
* Al Leibee, Wed Aug 3 16:57:38 PDT 1994
* Added _use_specmf.
*
* Robb Matzke, Fri Dec 2 14:18:34 PST 1994
* Changed SCFREE(obj) to DBFreeObject(obj)
*
* Robb Matzke, Sun Dec 18 17:11:12 EST 1994
* Changed SW_GetDatatypeString to db_GetDatatypeString and
* removed associated memory leak.
*
* Sean Ahern, Sun Oct 1 03:16:19 PDT 1995
* Made "me" static.
*
* Robb Matzke, 1 May 1996
* The `dims' is actually used. Before we just used the
* dimension variable whose name was based on the centering. Now
* we store the dimensions for every quadvar.
*
* Robb Matzke, 19 Jun 1997
* Added the `ascii_labels' optional field. The default is
* false, so we write `ascii_labels' to the file only if it isn't
* false.
*
* Eric Brugger, Mon Oct 6 15:11:26 PDT 1997
* I modified the routine to output the maximum index properly.
*
* Mark C. Miller, Thu Nov 5 16:15:49 PST 2009
* Added support for conserved/extensive options. Also, split
* out the logic for centering and alignment to make clearer.
* Added logic to support edge/face centering -- need to
* multiply by ndims for each of i-,j- and k- associated edges
* or faces. In addition, needed to add a 'centering' member
* to quadvars.
*--------------------------------------------------------------------*/
#ifdef PDB_WRITE
SILO_CALLBACK int
db_pdb_PutQuadvar (DBfile *_dbfile, char const *name, char const *meshname, int nvars,
char const * const *varnames, DBVCP2_t _vars, int const *dims, int ndims,
DBVCP2_t _mixvars, int mixlen, int datatype, int centering,
DBoptlist const *optlist) {
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
int i, nels;
long count[4], mcount[1];
char *suffix, *datatype_str, tmp1[1024], tmp2[1024];
static char *me = "db_pdb_PutQuadvar";
DBobject *obj;
int maxindex[3] ;
void const * const *vars = (void const * const *) _vars;
void const * const *mixvars = (void const * const *) _mixvars;
int is_empty = 1;
for (i = 0; i < ndims; i++)
{
if (dims[i] > 0)
{
is_empty = 0;
break;
}
}
/*-------------------------------------------------------------
* Initialize global data, and process options.
*-------------------------------------------------------------*/
db_InitQuad(_dbfile, meshname, optlist, dims, ndims);
obj = DBMakeObject(name, DB_QUADVAR, (1+(mixlen!=0))*nvars + 30);
DBAddStrComponent(obj, "meshid", meshname);
/*-------------------------------------------------------------
* Write variable arrays.
* Set index variables and counters.
*-----------------------------------------------------------*/
nels = !is_empty?1:0;
for (i = 0; i < ndims; i++) {
count[i] = dims[i];
nels *= dims[i];
}
if ((ndims > 1 && centering == DB_EDGECENT) ||
(ndims > 2 && centering == DB_FACECENT))
nels *= ndims;
switch (centering) {
case DB_NODECENT:
DBAddVarComponent(obj, "align", _qm._nm_alignn);
break;
case DB_EDGECENT:
if (ndims == 1) /* edge centering on 1D mesh is like zone centering */
DBAddVarComponent(obj, "align", _qm._nm_alignz);
break;
case DB_FACECENT:
if (ndims == 2) /* face centering on 2D mesh is like zone centering */
DBAddVarComponent(obj, "align", _qm._nm_alignz);
break;
case DB_ZONECENT:
DBAddVarComponent(obj, "align", _qm._nm_alignz);
break;
default:
return db_perror("centering", E_BADARGS, me);
}
/*
* Dimensions
*/
db_mkname (dbfile->pdb, name, "dims", tmp2) ;
mcount[0] = ndims ;
if (mcount[0])
{
PJ_write_len (dbfile->pdb, tmp2, "integer", dims, 1, mcount) ;
DBAddVarComponent (obj, "dims", tmp2) ;
}
/*
* Max indices
*/
for (i=0; i<ndims; i++) maxindex[i] = dims[i] - _qm._hi_offset[i] - 1 ;
db_mkname (dbfile->pdb, name, "maxindex", tmp2) ;
mcount[0] = ndims ;
if (mcount[0])
{
PJ_write_len (dbfile->pdb, tmp2, "integer", maxindex, 1, mcount) ;
DBAddVarComponent (obj, "max_index", tmp2) ;
}
/*-------------------------------------------------------------
* We first will write the given variables to SILO, then
* we'll define a Quadvar object in SILO composed of the
* variables plus the given options.
*-------------------------------------------------------------*/
suffix = "data";
datatype_str = db_GetDatatypeString(datatype);
for (i = 0; i < nvars && !is_empty; i++) {
db_mkname(dbfile->pdb, varnames[i], suffix, tmp2);
if ((ndims > 1 && centering == DB_EDGECENT) ||
(ndims > 2 && centering == DB_FACECENT))
{
int j, tmpndims = ndims+1;
long tmpcnt[4] = {0,0,0,0};
for (j = ndims; j > 0; j--)
tmpcnt[j] = count[j-1];
tmpcnt[0] = ndims;
PJ_write_len(dbfile->pdb, tmp2, datatype_str, vars[i],
tmpndims, tmpcnt);
}
else
{
int k; long n=ndims==0?0:1;
for (k = 0; k < ndims; n *= count[k++]);
if (n)
PJ_write_len(dbfile->pdb, tmp2, datatype_str, vars[i], ndims, count);
}
sprintf(tmp1, "value%d", i);
DBAddVarComponent(obj, tmp1, tmp2);
/* Write the mixed data component if present */
if (mixvars != NULL && mixvars[i] != NULL && mixlen > 0) {
mcount[0] = mixlen;
db_mkname(dbfile->pdb, varnames[i], "mix", tmp2);
PJ_write_len(dbfile->pdb, tmp2, datatype_str, mixvars[i],
1, mcount);
sprintf(tmp1, "mixed_value%d", i);
DBAddVarComponent(obj, tmp1, tmp2);
}
}
FREE(datatype_str);
/*-------------------------------------------------------------
* Build a SILO object definition for a quad mesh var. The
* minimum required information for a quad var is the variable
* itself, plus the ID for the associated quad mesh object.
* Process any additional options to complete the definition.
*-------------------------------------------------------------*/
DBAddIntComponent(obj, "ndims", ndims);
DBAddIntComponent(obj, "nvals", nvars);
DBAddIntComponent(obj, "nels", nels);
DBAddIntComponent(obj, "origin", _qm._origin);
DBAddIntComponent(obj, "datatype", datatype);
DBAddIntComponent(obj, "centering", centering);
DBAddIntComponent(obj, "mixlen", mixlen);
/*-------------------------------------------------------------
* Add 'recommended' optional components.
*-------------------------------------------------------------*/
DBAddIntComponent(obj, "major_order", _qm._majororder);
DBAddIntComponent(obj, "cycle", _qm._cycle);
if (_qm._time_set == TRUE)
DBAddVarComponent(obj, "time", _qm._nm_time);
if (_qm._dtime_set == TRUE)
DBAddVarComponent(obj, "dtime", _qm._nm_dtime);
DBAddVarComponent(obj, "min_index", _qm._nm_minindex);
DBAddIntComponent(obj, "use_specmf", _qm._use_specmf);
if (_qm._ascii_labels) {
DBAddIntComponent(obj, "ascii_labels", _qm._ascii_labels);
}
if (_qm._guihide)
DBAddIntComponent(obj, "guihide", _qm._guihide);
/*-------------------------------------------------------------
* Process character strings: labels & units for variable.
*-------------------------------------------------------------*/
if (_qm._label != NULL)
DBAddStrComponent(obj, "label", _qm._label);
if (_qm._unit != NULL)
DBAddStrComponent(obj, "units", _qm._unit);
if (_qm._region_pnames != NULL)
{
char *s=0; int len=0; long llen;
DBStringArrayToStringList((char const * const *)_qm._region_pnames, -1, &s, &len);
llen = len;
DBWriteComponent(_dbfile, obj, "region_pnames", name, "char", s, 1, &llen);
FREE(s);
}
if (_qm._conserved)
DBAddIntComponent(obj, "conserved", _qm._conserved);
if (_qm._extensive)
DBAddIntComponent(obj, "extensive", _qm._extensive);
if (_qm._missing_value != DB_MISSING_VALUE_NOT_SET)
{
if (_qm._missing_value == 0.0)
DBAddDblComponent(obj, "missing_value", DB_MISSING_VALUE_NOT_SET);
else
DBAddDblComponent(obj, "missing_value", _qm._missing_value);
}
/*-------------------------------------------------------------
* Write quad-var object to output file.
*-------------------------------------------------------------*/
DBWriteObject(_dbfile, obj, 0);
DBFreeObject(obj);
return 0;
}
#endif /* PDB_WRITE */
/*----------------------------------------------------------------------
* Routine db_pdb_PutCsgmesh
*
* Purpose
*
* Write a csg mesh object into the open output file.
*
* Programmer
*
* Mark C. Miller , Tue Aug 2 19:15:39 PDT 2005
*
*--------------------------------------------------------------------*/
#ifdef PDB_WRITE
/* ARGSUSED */
SILO_CALLBACK int
db_pdb_PutCsgmesh (DBfile *dbfile, char const *name, int ndims,
int nbounds,
int const *typeflags, int const *bndids,
void const *coeffs, int lcoeffs, int datatype,
double const *extents, char const *zlname,
DBoptlist const *optlist) {
long count[3];
DBobject *obj;
char *datatype_str;
double min_extents[3], max_extents[3];
/*-------------------------------------------------------------
* Initialize global data, and process options.
*-------------------------------------------------------------*/
strcpy(_csgm._meshname, name);
db_InitCsg(dbfile, name, optlist);
obj = DBMakeObject(name, DB_CSGMESH, 34);
count[0] = nbounds;
if (nbounds)
DBWriteComponent(dbfile, obj, "typeflags", name, "integer", typeflags, 1, count);
if (nbounds && bndids)
DBWriteComponent(dbfile, obj, "bndids", name, "integer", bndids, 1, count);
datatype_str = db_GetDatatypeString(datatype);
count[0] = lcoeffs;
if (nbounds)
DBWriteComponent(dbfile, obj, "coeffs", name, datatype_str, coeffs, 1, count);
FREE(datatype_str);
if (extents)
{
min_extents[0] = extents[0];
min_extents[1] = extents[1];
min_extents[2] = extents[2];
max_extents[0] = extents[3];
max_extents[1] = extents[4];
max_extents[2] = extents[5];
count[0] = ndims;
DBWriteComponent(dbfile, obj, "min_extents", name, "double",
min_extents, 1, count);
DBWriteComponent(dbfile, obj, "max_extents", name, "double",
max_extents, 1, count);
}
/*-------------------------------------------------------------
* Build a output object definition for a ucd mesh. The minimum
* required information for a ucd mesh is the coordinate arrays,
* the number of dimensions, and the type (RECT/CURV). Process
* the provided options to complete the definition.
*
* The output object definition is composed of a string of delimited
* component names plus an array of output *identifiers* of
* previously defined variables.
*-------------------------------------------------------------*/
if (zlname)
DBAddStrComponent(obj, "csgzonelist", zlname);
DBAddIntComponent(obj, "ndims", ndims);
DBAddIntComponent(obj, "nbounds", nbounds);
DBAddIntComponent(obj, "cycle", _csgm._cycle);
DBAddIntComponent(obj, "datatype", datatype);
DBAddIntComponent(obj, "lcoeffs", lcoeffs);
if (_csgm._guihide)
DBAddIntComponent(obj, "guihide", _csgm._guihide);
if (_csgm._group_no >= 0)
DBAddIntComponent(obj, "group_no", _csgm._group_no);
if (_csgm._time_set == TRUE)
DBAddVarComponent(obj, "time", _csgm._nm_time);
if (_csgm._dtime_set == TRUE)
DBAddVarComponent(obj, "dtime", _csgm._nm_dtime);
/*-------------------------------------------------------------
* Process character strings: labels & units for x, y, &/or z,
*-------------------------------------------------------------*/
if (_csgm._labels[0] != NULL)
DBAddStrComponent(obj, "label0", _csgm._labels[0]);
if (_csgm._labels[1] != NULL)
DBAddStrComponent(obj, "label1", _csgm._labels[1]);
if (_csgm._labels[2] != NULL)
DBAddStrComponent(obj, "label2", _csgm._labels[2]);
if (_csgm._units[0] != NULL)
DBAddStrComponent(obj, "units0", _csgm._units[0]);
if (_csgm._units[1] != NULL)
DBAddStrComponent(obj, "units1", _csgm._units[1]);
if (_csgm._units[2] != NULL)
DBAddStrComponent(obj, "units2", _csgm._units[2]);
if (_csgm._mrgtree_name != NULL)
DBAddStrComponent(obj, "mrgtree_name", _csgm._mrgtree_name);
if (_csgm._tv_connectivity)
DBAddIntComponent(obj, "tv_connectivity", _csgm._tv_connectivity);
if (_csgm._disjoint_mode)
DBAddIntComponent(obj, "disjoint_mode", _csgm._disjoint_mode);
/*-------------------------------------------------------------
* Write csg-mesh object to output file.
*-------------------------------------------------------------*/
DBWriteObject(dbfile, obj, TRUE);
DBFreeObject(obj);
return 0;
}
#endif /* PDB_WRITE */
/*----------------------------------------------------------------------
* Routine db_pdb_PutCsgvar
*
* Purpose
*
* Write a csg variable object into the open output file.
*
* Programmer
*
* Mark C. Miller, August 10. 2005
*
* Modifications:
* Mark C. Miller, Thu Nov 5 16:15:49 PST 2009
* Added support for conserved/extensive options.
*--------------------------------------------------------------------*/
#ifdef PDB_WRITE
SILO_CALLBACK int
db_pdb_PutCsgvar (DBfile *_dbfile, char const *name, char const *meshname,
int nvars, char const * const *varnames, void const * const *vars,
int nels, int datatype, int centering,
DBoptlist const *optlist) {
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
int i;
long count[3];
DBobject *obj;
char *suffix, *datatype_str, tmp1[256], tmp2[256];
static char *me = "db_pdb_PutCsgvar";
db_InitCsg(_dbfile, name, optlist);
obj = DBMakeObject(name, DB_CSGVAR, nvars+19);
DBAddStrComponent(obj, "meshid", meshname);
/*-------------------------------------------------------------
* Write variable arrays.
* Set index variables and counters.
*-----------------------------------------------------------*/
count[0] = nels;
switch (centering) {
case DB_NODECENT:
case DB_ZONECENT:
case DB_FACECENT:
break;
default:
return db_perror("centering", E_BADARGS, me);
}
/*-------------------------------------------------------------
* We first will write the given variables to output, then
* we'll define a Ucdvar object in output composed of the
* variables plus the given options.
*-------------------------------------------------------------*/
suffix = "data";
datatype_str = db_GetDatatypeString(datatype);
for (i = 0; i < nvars && nels; i++) {
db_mkname(dbfile->pdb, (char*) varnames[i], suffix, tmp2);
PJ_write_len(dbfile->pdb, tmp2, datatype_str, vars[i],
1, count);
sprintf(tmp1, "value%d", i);
DBAddVarComponent(obj, tmp1, tmp2);
}
FREE(datatype_str);
/*-------------------------------------------------------------
* Build a output object definition for a ucd mesh var. The
* minimum required information for a ucd var is the variable
* itself, plus the ID for the associated ucd mesh object.
* Process any additional options to complete the definition.
*-------------------------------------------------------------*/
DBAddIntComponent(obj, "nvals", nvars);
DBAddIntComponent(obj, "nels", nels);
DBAddIntComponent(obj, "centering", centering);
DBAddIntComponent(obj, "datatype", datatype);
if (_csgm._guihide)
DBAddIntComponent(obj, "guihide", _csgm._guihide);
/*-------------------------------------------------------------
* Add 'recommended' optional components.
*-------------------------------------------------------------*/
if (_csgm._time_set == TRUE)
DBAddVarComponent(obj, "time", _csgm._nm_time);
if (_csgm._dtime_set == TRUE)
DBAddVarComponent(obj, "dtime", _csgm._nm_dtime);
if (centering == DB_ZONECENT)
{
if (_csgm._hi_offset_set == TRUE)
DBAddIntComponent(obj, "hi_offset", _csgm._hi_offset);
if (_csgm._lo_offset_set == TRUE)
DBAddIntComponent(obj, "lo_offset", _csgm._lo_offset);
}
DBAddIntComponent(obj, "cycle", _csgm._cycle);
DBAddIntComponent(obj, "use_specmf", _csgm._use_specmf);
if (_csgm._ascii_labels) {
DBAddIntComponent(obj, "ascii_labels", _csgm._ascii_labels);
}
/*-------------------------------------------------------------
* Process character strings: labels & units for variable.
*-------------------------------------------------------------*/
if (_csgm._label != NULL)
DBAddStrComponent(obj, "label", _csgm._label);
if (_csgm._unit != NULL)
DBAddStrComponent(obj, "units", _csgm._unit);
if (_csgm._region_pnames != NULL)
{
char *s=0; int len=0; long llen;
DBStringArrayToStringList((char const * const *)_csgm._region_pnames, -1, &s, &len);
llen = len;
DBWriteComponent(_dbfile, obj, "region_pnames", name, "char", s, 1, &llen);
FREE(s);
}
if (_csgm._conserved)
DBAddIntComponent(obj, "conserved", _csgm._conserved);
if (_csgm._extensive)
DBAddIntComponent(obj, "extensive", _csgm._extensive);
if (_csgm._missing_value != DB_MISSING_VALUE_NOT_SET)
{
if (_csgm._missing_value == 0.0)
DBAddDblComponent(obj, "missing_value", DB_MISSING_VALUE_NOT_SET);
else
DBAddDblComponent(obj, "missing_value", _csgm._missing_value);
}
/*-------------------------------------------------------------
* Write ucd-mesh object to output file.
*-------------------------------------------------------------*/
DBWriteObject(_dbfile, obj, 0);
DBFreeObject(obj);
return 0;
}
#endif /* PDB_WRITE */
/*----------------------------------------------------------------------
* Routine db_pdb_PutCSGZonelist
*
* Purpose
*
* Write a csg zonelist object into the open output file.
*
* Programmer
*
* Mark C. Miller
* August 9, 2005
*
*--------------------------------------------------------------------*/
#ifdef PDB_WRITE
SILO_CALLBACK int
db_pdb_PutCSGZonelist (DBfile *dbfile, char const *name, int nregs,
int const *typeflags,
int const *leftids, int const *rightids,
void const *xforms, int lxforms, int datatype,
int nzones, int const *zonelist, DBoptlist const *optlist) {
long count[1];
DBobject *obj;
memset(&_csgzl, 0, sizeof(_csgzl));
db_ProcessOptlist(DB_CSGZONELIST, optlist);
/*--------------------------------------------------
* Build up object description by defining literals
* and defining/writing arrays.
*-------------------------------------------------*/
obj = DBMakeObject(name, DB_CSGZONELIST, 15);
DBAddIntComponent(obj, "nregs", nregs);
DBAddIntComponent(obj, "datatype", datatype);
DBAddIntComponent(obj, "nzones", nzones);
count[0] = nregs;
DBWriteComponent(dbfile, obj, "typeflags", name, "integer",
typeflags, 1, count);
DBWriteComponent(dbfile, obj, "leftids", name, "integer",
leftids, 1, count);
DBWriteComponent(dbfile, obj, "rightids", name, "integer",
rightids, 1, count);
count[0] = nzones;
DBWriteComponent(dbfile, obj, "zonelist", name, "integer",
zonelist, 1, count);
if (xforms && lxforms > 0)
{
char *datatype_str = db_GetDatatypeString(datatype);
count[0] = lxforms;
DBWriteComponent(dbfile, obj, "xforms", name, datatype_str, xforms, 1, count);
}
if (_csgzl._regnames)
{
int len; char *tmp;
DBStringArrayToStringList((char const * const *)_csgzl._regnames, nregs, &tmp, &len);
count[0] = len;
DBWriteComponent(dbfile, obj, "regnames", name, "char", tmp, 1, count);
FREE(tmp);
}
if (_csgzl._zonenames)
{
int len; char *tmp;
DBStringArrayToStringList((char const * const *)_csgzl._zonenames, nzones, &tmp, &len);
count[0] = len;
DBWriteComponent(dbfile, obj, "zonenames", name, "char", tmp, 1, count);
FREE(tmp);
}
if (_csgzl._alt_zonenum_vars)
{
int nvars=-1, len; char *tmp;
DBStringArrayToStringList((char const * const *)_csgzl._alt_zonenum_vars, nvars, &tmp, &len);
count[0] = len;
DBWriteComponent(dbfile, obj, "alt_zonenum_vars", name, "char", tmp, 1, count);
FREE(tmp);
}
/*-------------------------------------------------------------
* Write object to output file.
*-------------------------------------------------------------*/
DBWriteObject(dbfile, obj, TRUE);
DBFreeObject(obj);
return 0;
}
#endif /* PDB_WRITE */
/*----------------------------------------------------------------------
* Routine db_pdb_PutUcdmesh
*
* Purpose
*
* Write a ucd mesh object into the open output file.
*
* Programmer
*
* Jeffery W. Long, NSSD-B
*
* Notes
*
* Modifications
* Robb Matzke, Sun Dec 18 17:12:16 EST 1994
* Changed SW_GetDatatypeString to db_GetDatatypeString and
* removed associated memory leak.
*
* Robb Matzke, Fri Dec 2 14:19:04 PST 1994
* Changed SCFREE(obj) to DBFreeObject(obj)
*
* Al Leibee, Mon Apr 18 07:45:58 PDT 1994
* Added _dtime.
*
* Sean Ahern, Wed Oct 21 09:22:30 PDT 1998
* Changed how we pass extents data to the UM_CalcExtents function.
*
* Jeremy Meredith, Fri May 21 10:04:25 PDT 1999
* Added group_no and gnodeno.
*
* Hank Childs, Thu Jan 6 13:51:22 PST 2000
* Put in lint directive for unused arguments.
*
* Mark C. Miller, Fri Nov 13 15:26:38 PST 2009
* Add support for long long global node/zone numbers.
*
* Mark C. Miller, Sat Nov 14 20:28:34 PST 2009
* Changed how long long global node/zone numbers are supported
* from a int (bool), "llong_gnode|zoneno" to an int holding
* the actual datatype. The type is assumed int if it its
* value is zero or it does not exist. Otherwise, the type is
* is whatever is stored in gnznodtype member.
*
* Mark C. Miller, Tue Nov 17 22:22:09 PST 2009
* Changed name of long long datatype to match what PDB proper
* would call it.
*--------------------------------------------------------------------*/
#ifdef PDB_WRITE
/* ARGSUSED */
SILO_CALLBACK int
db_pdb_PutUcdmesh (DBfile *dbfile, char const *name, int ndims, char const * const *coordnames,
DBVCP2_t _coords, int nnodes, int nzones, char const *zlname,
char const *flname, int datatype, DBoptlist const *optlist) {
int i;
long count[3];
DBobject *obj;
char *datatype_str;
char tmp[256];
void const * const *coords = (void const * const *) _coords;
/* Following is declared as double for worst case */
double min_extents[3]={0,0,0}, max_extents[3]={0,0,0};
/*-------------------------------------------------------------
* Initialize global data, and process options.
*-------------------------------------------------------------*/
strcpy(_um._meshname, name);
db_InitUcd(dbfile, name, optlist, ndims, nnodes, nzones);
obj = DBMakeObject(name, DB_UCDMESH, 33);
/*-------------------------------------------------------------
* We first will write the given coordinate arrays to output,
* then we'll define a UCD-mesh object in output composed of the
* coordinates plus the given options.
*-------------------------------------------------------------*/
datatype_str = db_GetDatatypeString(datatype);
count[0] = nnodes;
for (i = 0; (i < ndims) && (nnodes > 0); i++) {
sprintf(tmp, "coord%d", i);
DBWriteComponent(dbfile, obj, tmp, name, datatype_str,
coords[i], 1, count);
}
/*-------------------------------------------------------------
* Find the mesh extents from the coordinate arrays. Write
* them out to output file.
*-------------------------------------------------------------*/
UM_CalcExtents(coords, datatype, ndims, nnodes, min_extents, max_extents);
count[0] = ndims;
DBWriteComponent(dbfile, obj, "min_extents", name, datatype_str,
min_extents, 1, count);
DBWriteComponent(dbfile, obj, "max_extents", name, datatype_str,
max_extents, 1, count);
FREE(datatype_str);
/*-------------------------------------------------------------
* Build a output object definition for a ucd mesh. The minimum
* required information for a ucd mesh is the coordinate arrays,
* the number of dimensions, and the type (RECT/CURV). Process
* the provided options to complete the definition.
*
* The output object definition is composed of a string of delimited
* component names plus an array of output *identifiers* of
* previously defined variables.
*-------------------------------------------------------------*/
if (flname)
DBAddStrComponent(obj, "facelist", flname);
if (zlname)
DBAddStrComponent(obj, "zonelist", zlname);
DBAddIntComponent(obj, "ndims", ndims);
DBAddIntComponent(obj, "nnodes", nnodes);
DBAddIntComponent(obj, "nzones", nzones);
DBAddIntComponent(obj, "facetype", _um._facetype);
DBAddIntComponent(obj, "cycle", _um._cycle);
DBAddIntComponent(obj, "coord_sys", _um._coord_sys);
if (_um._topo_dim > 0)
DBAddIntComponent(obj, "topo_dim", _um._topo_dim);
DBAddIntComponent(obj, "planar", _um._planar);
DBAddIntComponent(obj, "origin", _um._origin);
DBAddIntComponent(obj, "datatype", datatype);
if (_um._llong_gnodeno)
DBAddIntComponent(obj, "gnznodtype", DB_LONG_LONG);
if (_um._gnodeno)
{
count[0] = nnodes;
if (_um._llong_gnodeno)
DBWriteComponent(dbfile, obj, "gnodeno", name, "long_long",
_um._gnodeno, 1, count);
else
DBWriteComponent(dbfile, obj, "gnodeno", name, "integer",
_um._gnodeno, 1, count);
}
if (_um._group_no >= 0)
DBAddIntComponent(obj, "group_no", _um._group_no);
if (_um._time_set == TRUE)
DBAddVarComponent(obj, "time", _um._nm_time);
if (_um._dtime_set == TRUE)
DBAddVarComponent(obj, "dtime", _um._nm_dtime);
/*-------------------------------------------------------------
* Process character strings: labels & units for x, y, &/or z,
*-------------------------------------------------------------*/
if (_um._labels[0] != NULL)
DBAddStrComponent(obj, "label0", _um._labels[0]);
if (_um._labels[1] != NULL)
DBAddStrComponent(obj, "label1", _um._labels[1]);
if (_um._labels[2] != NULL)
DBAddStrComponent(obj, "label2", _um._labels[2]);
if (_um._units[0] != NULL)
DBAddStrComponent(obj, "units0", _um._units[0]);
if (_um._units[1] != NULL)
DBAddStrComponent(obj, "units1", _um._units[1]);
if (_um._units[2] != NULL)
DBAddStrComponent(obj, "units2", _um._units[2]);
if (_um._guihide)
DBAddIntComponent(obj, "guihide", _um._guihide);
/*-------------------------------------------------------------
* Optional polyhedral zonelist
*-------------------------------------------------------------*/
if (_um._phzl_name != NULL)
DBAddStrComponent(obj, "phzonelist", _um._phzl_name);
if (_um._mrgtree_name != NULL)
DBAddStrComponent(obj, "mrgtree_name", _um._mrgtree_name);
if (_um._tv_connectivity)
DBAddIntComponent(obj, "tv_connectivity", _um._tv_connectivity);
if (_um._disjoint_mode)
DBAddIntComponent(obj, "disjoint_mode", _um._disjoint_mode);
if (nnodes>0 && _um._ghost_node_labels != NULL)
{
count[0] = nnodes;
DBWriteComponent(dbfile, obj, "ghost_node_labels", name, "char",
_um._ghost_node_labels, 1, count);
}
if (nnodes>0 && _um._alt_nodenum_vars)
{
int nvars=-1, len; long llen; char *tmpstr = 0;
DBStringArrayToStringList((char const * const *)_um._alt_nodenum_vars, nvars, &tmpstr, &len);
llen = (long) len;
DBWriteComponent(dbfile, obj, "alt_nodenum_vars", name, "char", tmpstr, 1, &llen);
FREE(tmpstr);
}
/*-------------------------------------------------------------
* Write ucd-mesh object to output file.
*-------------------------------------------------------------*/
DBWriteObject(dbfile, obj, TRUE);
DBFreeObject(obj);
return 0;
}
#endif /* PDB_WRITE */
/*----------------------------------------------------------------------
* Routine db_pdb_PutUcdsubmesh
*
* Purpose
*
* Write a subset of a ucd mesh object into the open output file.
*
* Programmer
*
* Jim Reus
*
* Notes
*
* Modifications
* none yet.
*
*--------------------------------------------------------------------*/
#ifdef PDB_WRITE
SILO_CALLBACK int
db_pdb_PutUcdsubmesh (DBfile *dbfile, char const *name, char const *parentmesh,
int nzones, char const *zlname, char const *flname,
DBoptlist const *optlist) {
int i;
DBobject *obj;
int *Pdatatype,datatype;
int *Pndims,ndims;
int *Pnnodes,nnodes;
/*-------------------------------------------------------------
* We first retreive certain attributes from the parent mesh.
* Of course this had better succeed...
*-------------------------------------------------------------*/
Pndims = (int *)DBGetComponent(dbfile,parentmesh,"ndims");
ndims = *Pndims;
Pnnodes = (int *)DBGetComponent(dbfile,parentmesh,"nnodes");
nnodes = *Pnnodes;
Pdatatype = (int *)DBGetComponent(dbfile,parentmesh,"datatype");
datatype = *Pdatatype;
/*-------------------------------------------------------------
* Now we can initialize global data, and process options.
*-------------------------------------------------------------*/
strcpy(_um._meshname, name);
db_InitUcd(dbfile, name, optlist, ndims, nnodes, nzones);
obj = DBMakeObject(name, DB_UCDMESH, 28);
/*-------------------------------------------------------------
* Then we will add references to the coordinate arrays of the
* parent mesh...
*-------------------------------------------------------------*/
for (i = 0; i < ndims; i++) {
char myComponName[256];
char parentComponName[256];
sprintf(myComponName, "coord%d", i);
sprintf(parentComponName, "%s_coord%d", parentmesh, i);
DBAddVarComponent(obj,myComponName,parentComponName);
}
/*-------------------------------------------------------------
* For now we'll simply refer to the extents provided for the
* parent mesh. It would be be better to compute extents for
* the cordinates actually used, but then we'd have to retrieve
* the coords...
*-------------------------------------------------------------*/
{ char myComponName[256];
char parentComponName[256];
sprintf(myComponName, "min_extents");
sprintf(parentComponName, "%s_min_extents", parentmesh);
DBAddVarComponent(obj,myComponName,parentComponName);
sprintf(myComponName, "max_extents");
sprintf(parentComponName, "%s_max_extents", parentmesh);
DBAddVarComponent(obj,myComponName,parentComponName);
}
/*-------------------------------------------------------------
* Build a output object definition for a ucd mesh. The minimum
* required information for a ucd mesh is the coordinate arrays,
* the number of dimensions, and the type (RECT/CURV). Process
* the provided options to complete the definition.
*
* The output object definition is composed of a string of delimited
* component names plus an array of output *identifiers* of
* previously defined variables.
*-------------------------------------------------------------*/
if (flname)
DBAddStrComponent(obj, "facelist", flname);
if (zlname)
DBAddStrComponent(obj, "zonelist", zlname);
DBAddIntComponent(obj, "ndims", ndims);
DBAddIntComponent(obj, "nnodes", nnodes);
DBAddIntComponent(obj, "nzones", nzones);
DBAddIntComponent(obj, "facetype", _um._facetype);
DBAddIntComponent(obj, "cycle", _um._cycle);
DBAddIntComponent(obj, "coord_sys", _um._coord_sys);
if (_um._topo_dim > 0)
DBAddIntComponent(obj, "topo_dim", _um._topo_dim);
DBAddIntComponent(obj, "planar", _um._planar);
DBAddIntComponent(obj, "origin", _um._origin);
DBAddIntComponent(obj, "datatype", datatype);
if (_um._time_set == TRUE)
DBAddVarComponent(obj, "time", _um._nm_time);
if (_um._dtime_set == TRUE)
DBAddVarComponent(obj, "dtime", _um._nm_dtime);
/*-------------------------------------------------------------
* Process character strings: labels & units for x, y, &/or z,
*-------------------------------------------------------------*/
if (_um._labels[0] != NULL)
DBAddStrComponent(obj, "label0", _um._labels[0]);
if (_um._labels[1] != NULL)
DBAddStrComponent(obj, "label1", _um._labels[1]);
if (_um._labels[2] != NULL)
DBAddStrComponent(obj, "label2", _um._labels[2]);
if (_um._units[0] != NULL)
DBAddStrComponent(obj, "units0", _um._units[0]);
if (_um._units[1] != NULL)
DBAddStrComponent(obj, "units1", _um._units[1]);
if (_um._units[2] != NULL)
DBAddStrComponent(obj, "units2", _um._units[2]);
if (_um._guihide)
DBAddIntComponent(obj, "guihide", _um._guihide);
if (_um._tv_connectivity)
DBAddIntComponent(obj, "tv_connectivity", _um._tv_connectivity);
if (_um._disjoint_mode)
DBAddIntComponent(obj, "disjoint_mode", _um._disjoint_mode);
/*-------------------------------------------------------------
* Write ucd-mesh object to output file.
*-------------------------------------------------------------*/
DBWriteObject(dbfile, obj, TRUE);
FREE(Pdatatype);
FREE(Pnnodes);
FREE(Pndims);
DBFreeObject(obj);
return 0;
}
#endif /* PDB_WRITE */
/*----------------------------------------------------------------------
* Routine db_pdb_PutUcdvar
*
* Purpose
*
* Write a ucd variable object into the open output file.
*
* Programmer
*
* Jeffery W. Long, NSSD-B
*
* Notes
*
* Modifications
* Al Leibee, Mon Apr 18 07:45:58 PDT 1994
* Added _dtime.
*
* Al Leibee, Mon Jul 11 12:00:00 PDT 1994
* Use mixlen, not _mixlen.
*
* Al Leibee, Wed Jul 20 07:56:37 PDT 1994
* Write mixlen component.
*
* Al Leibee, Wed Aug 3 16:57:38 PDT 1994
* Added _use_specmf.
*
* Robb Matzke, Fri Dec 2 14:19:42 PST 1994
* Changed SCFREE(obj) to DBFreeObject(obj)
*
* Robb Matzke, Sun Dec 18 17:13:17 EST 1994
* Changed SW_GetDatatypeString to db_GetDatatypeString and
* removed associated memory leak.
*
* Sean Ahern, Sun Oct 1 03:17:35 PDT 1995
* Made "me" static.
*
* Eric Brugger, Wed Oct 15 14:45:47 PDT 1997
* Added _hi_offset and _lo_offset.
*
* Hank Childs, Thu Jan 6 13:51:22 PST 2000
* Removed unused variable nm_cent.
*
* Robb Matzke, 2000-05-23
* Removed the duplicate `meshid' field.
*
* Brad Whitlock, Wed Jan 18 15:09:57 PST 2006
* Added ascii_labels.
*
* Mark C. Miller, Thu Nov 5 16:15:49 PST 2009
* Added support for conserved/extensive options.
*
* Mark C. Miller, Wed Nov 11 22:17:40 PST 2009
* Removed unnecessary code checking centering.
*--------------------------------------------------------------------*/
#ifdef PDB_WRITE
SILO_CALLBACK int
db_pdb_PutUcdvar (DBfile *_dbfile, char const *name, char const *meshname, int nvars,
char const * const *varnames, DBVCP2_t _vars, int nels, DBVCP2_t _mixvars,
int mixlen, int datatype, int centering,
DBoptlist const *optlist) {
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
int i;
long count[3], mcount[1];
DBobject *obj;
char *suffix, *datatype_str, tmp1[256], tmp2[256];
static char *me = "db_pdb_PutUcdvar";
void const * const *vars = (void const * const *) _vars;
void const * const *mixvars = (void const * const *) _mixvars;
/*-------------------------------------------------------------
* Initialize global data, and process options.
*-------------------------------------------------------------*/
#if 1 /*which way is right? (1st one is the original) */
db_InitUcd(_dbfile, meshname, optlist, _um._ndims,
_um._nnodes, _um._nzones);
#else
db_InitUcd(_dbfile, meshname, optlist, ndims, nnodes, nzones);
#endif
obj = DBMakeObject(name, DB_UCDVAR, (1+(mixlen!=0)) * nvars + 22);
DBAddStrComponent(obj, "meshid", meshname);
/*-------------------------------------------------------------
* Write variable arrays.
* Set index variables and counters.
*-----------------------------------------------------------*/
count[0] = nels;
/*-------------------------------------------------------------
* We first will write the given variables to output, then
* we'll define a Ucdvar object in output composed of the
* variables plus the given options.
*-------------------------------------------------------------*/
suffix = "data";
datatype_str = db_GetDatatypeString(datatype);
for (i = 0; i < nvars && nels; i++) {
db_mkname(dbfile->pdb, varnames[i], suffix, tmp2);
PJ_write_len(dbfile->pdb, tmp2, datatype_str, vars[i],
1, count);
sprintf(tmp1, "value%d", i);
DBAddVarComponent(obj, tmp1, tmp2);
/* Write the mixed data component if present */
if (mixvars != NULL && mixvars[i] != NULL && mixlen > 0) {
mcount[0] = mixlen;
db_mkname(dbfile->pdb, varnames[i], "mix", tmp2);
PJ_write_len(dbfile->pdb, tmp2, datatype_str, mixvars[i],
1, mcount);
sprintf(tmp1, "mixed_value%d", i);
DBAddVarComponent(obj, tmp1, tmp2);
}
}
FREE(datatype_str);
/*-------------------------------------------------------------
* Build a output object definition for a ucd mesh var. The
* minimum required information for a ucd var is the variable
* itself, plus the ID for the associated ucd mesh object.
* Process any additional options to complete the definition.
*-------------------------------------------------------------*/
DBAddIntComponent(obj, "ndims", _um._ndims);
DBAddIntComponent(obj, "nvals", nvars);
DBAddIntComponent(obj, "nels", nels);
DBAddIntComponent(obj, "centering", centering);
DBAddIntComponent(obj, "origin", _um._origin);
DBAddIntComponent(obj, "mixlen", mixlen);
DBAddIntComponent(obj, "datatype", datatype);
/*-------------------------------------------------------------
* Add 'recommended' optional components.
*-------------------------------------------------------------*/
if (_um._time_set == TRUE)
DBAddVarComponent(obj, "time", _um._nm_time);
if (_um._dtime_set == TRUE)
DBAddVarComponent(obj, "dtime", _um._nm_dtime);
if (centering == DB_ZONECENT)
{
if (_um._hi_offset_set == TRUE)
DBAddIntComponent(obj, "hi_offset", _um._hi_offset);
if (_um._lo_offset_set == TRUE)
DBAddIntComponent(obj, "lo_offset", _um._lo_offset);
}
DBAddIntComponent(obj, "cycle", _um._cycle);
DBAddIntComponent(obj, "use_specmf", _um._use_specmf);
if (_um._ascii_labels) {
DBAddIntComponent(obj, "ascii_labels", _um._ascii_labels);
}
/*-------------------------------------------------------------
* Process character strings: labels & units for variable.
*-------------------------------------------------------------*/
if (_um._label != NULL)
DBAddStrComponent(obj, "label", _um._label);
if (_um._unit != NULL)
DBAddStrComponent(obj, "units", _um._unit);
if (_um._guihide)
DBAddIntComponent(obj, "guihide", _um._guihide);
if (_um._region_pnames != NULL)
{
char *s=0; int len=0; long llen;
DBStringArrayToStringList((char const * const *)_um._region_pnames, -1, &s, &len);
llen = len;
DBWriteComponent(_dbfile, obj, "region_pnames", name, "char", s, 1, &llen);
FREE(s);
}
if (_um._conserved)
DBAddIntComponent(obj, "conserved", _um._conserved);
if (_um._extensive)
DBAddIntComponent(obj, "extensive", _um._extensive);
if (_um._missing_value != DB_MISSING_VALUE_NOT_SET)
{
if (_um._missing_value == 0.0)
DBAddDblComponent(obj, "missing_value", DB_MISSING_VALUE_NOT_SET);
else
DBAddDblComponent(obj, "missing_value", _um._missing_value);
}
/*-------------------------------------------------------------
* Write ucd-mesh object to output file.
*-------------------------------------------------------------*/
DBWriteObject(_dbfile, obj, 0);
DBFreeObject(obj);
return 0;
}
#endif /* PDB_WRITE */
/*----------------------------------------------------------------------
* Routine db_pdb_PutZonelist
*
* Purpose
*
* Write a ucd zonelist object into the open output file.
*
* Programmer
*
* Jeffery W. Long, NSSD-B
*
* Notes
*
* Modified
* Robb Matzke, Fri Dec 2 14:20:10 PST 1994
* Changed SCFREE(obj) to DBFreeObject(obj)
*
*--------------------------------------------------------------------*/
#ifdef PDB_WRITE
SILO_CALLBACK int
db_pdb_PutZonelist (DBfile *dbfile, char const *name, int nzones, int ndims,
int const *nodelist, int lnodelist, int origin, int const *shapesize,
int const *shapecnt, int nshapes) {
long count[5];
DBobject *obj;
/*--------------------------------------------------
* Build up object description by defining literals
* and defining/writing arrays.
*-------------------------------------------------*/
obj = DBMakeObject(name, DB_ZONELIST, 15);
DBAddIntComponent(obj, "ndims", ndims);
DBAddIntComponent(obj, "nzones", nzones);
DBAddIntComponent(obj, "nshapes", nshapes);
DBAddIntComponent(obj, "lnodelist", lnodelist);
DBAddIntComponent(obj, "origin", origin);
count[0] = lnodelist;
DBWriteComponent(dbfile, obj, "nodelist", name, "integer",
nodelist, 1, count);
count[0] = nshapes;
DBWriteComponent(dbfile, obj, "shapecnt", name, "integer",
shapecnt, 1, count);
DBWriteComponent(dbfile, obj, "shapesize", name, "integer",
shapesize, 1, count);
/*-------------------------------------------------------------
* Write object to output file.
*-------------------------------------------------------------*/
DBWriteObject(dbfile, obj, TRUE);
DBFreeObject(obj);
return 0;
}
#endif /* PDB_WRITE */
/*----------------------------------------------------------------------
* Routine db_pdb_PutZonelist2
*
* Purpose
*
* Write a ucd zonelist object into the open output file.
*
* Programmer
*
* Eric Brugger
* March 30, 1999
*
* Notes
*
* Modified
*
* Jeremy Meredith, Fri May 21 10:04:25 PDT 1999
* Added an option list, a call to initialize it, and gzoneno.
*
* Mark C. Miller, Fri Nov 13 15:26:38 PST 2009
* Add support for long long global node/zone numbers.
*
* Mark C. Miller, Tue Nov 17 22:22:09 PST 2009
* Changed name of long long datatype to match what PDB proper
* would call it.
*--------------------------------------------------------------------*/
#ifdef PDB_WRITE
SILO_CALLBACK int
db_pdb_PutZonelist2 (DBfile *dbfile, char const *name, int nzones, int ndims,
int const *nodelist, int lnodelist, int origin,
int lo_offset, int hi_offset, int const *shapetype,
int const *shapesize, int const *shapecnt, int nshapes,
DBoptlist const *optlist) {
long count[5];
DBobject *obj;
db_InitZonelist(dbfile, optlist);
/*--------------------------------------------------
* Build up object description by defining literals
* and defining/writing arrays.
*-------------------------------------------------*/
obj = DBMakeObject(name, DB_ZONELIST, 16);
DBAddIntComponent(obj, "ndims", ndims);
DBAddIntComponent(obj, "nzones", nzones);
DBAddIntComponent(obj, "nshapes", nshapes);
DBAddIntComponent(obj, "lnodelist", lnodelist);
DBAddIntComponent(obj, "origin", origin);
DBAddIntComponent(obj, "lo_offset", lo_offset);
DBAddIntComponent(obj, "hi_offset", hi_offset);
if (_uzl._llong_gzoneno)
DBAddIntComponent(obj, "gnznodtype", DB_LONG_LONG);
count[0] = lnodelist;
DBWriteComponent(dbfile, obj, "nodelist", name, "integer",
nodelist, 1, count);
count[0] = nshapes;
DBWriteComponent(dbfile, obj, "shapecnt", name, "integer",
shapecnt, 1, count);
DBWriteComponent(dbfile, obj, "shapesize", name, "integer",
shapesize, 1, count);
DBWriteComponent(dbfile, obj, "shapetype", name, "integer",
shapetype, 1, count);
if (nzones>0 && _uzl._gzoneno)
{
count[0] = nzones;
if (_uzl._llong_gzoneno)
DBWriteComponent(dbfile, obj, "gzoneno", name, "long_long",
_uzl._gzoneno, 1, count);
else
DBWriteComponent(dbfile, obj, "gzoneno", name, "integer",
_uzl._gzoneno, 1, count);
}
if (nzones>0 && _uzl._ghost_zone_labels)
{
count[0] = nzones;
DBWriteComponent(dbfile, obj, "ghost_zone_labels", name, "char",
_uzl._ghost_zone_labels, 1, count);
}
if (nzones>0 && _uzl._alt_zonenum_vars)
{
int nvars=-1, len; long llen; char *tmpstr = 0;
DBStringArrayToStringList((char const * const *)_uzl._alt_zonenum_vars, nvars, &tmpstr, &len);
llen = (long) len;
DBWriteComponent(dbfile, obj, "alt_zonenum_vars", name, "char", tmpstr, 1, &llen);
FREE(tmpstr);
}
/*-------------------------------------------------------------
* Write object to output file.
*-------------------------------------------------------------*/
DBWriteObject(dbfile, obj, TRUE);
DBFreeObject(obj);
return 0;
}
#endif /* PDB_WRITE */
/*----------------------------------------------------------------------
* Routine db_pdb_PutPHZonelist
*
* Purpose
*
* Write a polyhedral zonelist object into the open output file.
*
* Programmer
*
* Mark C. Miller
* July 27, 2004
*
* Modifications:
* Mark C. Miller, Fri Nov 13 15:26:38 PST 2009
* Add support for long long global node/zone numbers.
*
* Mark C. Miller, Sat Nov 14 20:28:34 PST 2009
* Changed how long long global node/zone numbers are supported
* from a int (bool), "llong_gnode|zoneno" to an int holding
* the actual datatype. The type is assumed int if it its
* value is zero or it does not exist. Otherwise, the type is
* is whatever is stored in gnznodtype member.
*
* Mark C. Miller, Tue Nov 17 22:22:09 PST 2009
* Changed name of long long datatype to match what PDB proper
* would call it.
*--------------------------------------------------------------------*/
#ifdef PDB_WRITE
SILO_CALLBACK int
db_pdb_PutPHZonelist (DBfile *dbfile, char const *name,
int nfaces, int const *nodecnt, int lnodelist, int const *nodelist, char const *extface,
int nzones, int const *facecnt, int lfacelist, int const *facelist,
int origin, int lo_offset, int hi_offset,
DBoptlist const *optlist) {
long count[1];
DBobject *obj;
db_InitPHZonelist(dbfile, optlist);
/*--------------------------------------------------
* Build up object description by defining literals
* and defining/writing arrays.
*-------------------------------------------------*/
obj = DBMakeObject(name, DB_PHZONELIST, 16);
DBAddIntComponent(obj, "nfaces", nfaces);
DBAddIntComponent(obj, "lnodelist", lnodelist);
DBAddIntComponent(obj, "nzones", nzones);
DBAddIntComponent(obj, "lfacelist", lfacelist);
DBAddIntComponent(obj, "origin", origin);
DBAddIntComponent(obj, "lo_offset", lo_offset);
DBAddIntComponent(obj, "hi_offset", hi_offset);
if (_phzl._llong_gzoneno)
DBAddIntComponent(obj, "gnznodtype", DB_LONG_LONG);
count[0] = nfaces;
DBWriteComponent(dbfile, obj, "nodecnt", name, "integer",
nodecnt, 1, count);
count[0] = lnodelist;
DBWriteComponent(dbfile, obj, "nodelist", name, "integer",
nodelist, 1, count);
if (facecnt)
{
count[0] = nzones;
DBWriteComponent(dbfile, obj, "facecnt", name, "integer",
facecnt, 1, count);
}
if (facelist)
{
count[0] = lfacelist;
DBWriteComponent(dbfile, obj, "facelist", name, "integer",
facelist, 1, count);
}
if (extface)
{
count[0] = nfaces;
DBWriteComponent(dbfile, obj, "extface", name, "char",
extface, 1, count);
}
if (nzones>0 && _phzl._gzoneno)
{
count[0] = nzones;
if (_phzl._llong_gzoneno)
DBWriteComponent(dbfile, obj, "gzoneno", name, "long_long",
_phzl._gzoneno, 1, count);
else
DBWriteComponent(dbfile, obj, "gzoneno", name, "integer",
_phzl._gzoneno, 1, count);
}
if (nzones>0 && _phzl._ghost_zone_labels)
{
count[0] = nzones;
DBWriteComponent(dbfile, obj, "ghost_zone_labels", name, "char",
_phzl._ghost_zone_labels, 1, count);
}
if (nzones>0 && _phzl._alt_zonenum_vars)
{
int nvars=-1, len; long llen; char *tmpstr = 0;
DBStringArrayToStringList((char const * const *)_phzl._alt_zonenum_vars, nvars, &tmpstr, &len);
llen = (long) len;
DBWriteComponent(dbfile, obj, "alt_zonenum_vars", name, "char", tmpstr, 1, &llen);
FREE(tmpstr);
}
/*-------------------------------------------------------------
* Write object to output file.
*-------------------------------------------------------------*/
DBWriteObject(dbfile, obj, TRUE);
DBFreeObject(obj);
return 0;
}
#endif /* PDB_WRITE */
/*----------------------------------------------------------------------
* Routine db_pdb_PutMrgtree
*
* Purpose
*
* Write mrg tree object into the open output file.
*
* Programmer
*
* Mark C. Miller, Wed Oct 10 10:25:53 PDT 2007
*
* Modifications:
*
* Mark C. Miller, Mon Nov 17 19:02:58 PST 2008
* Fixed output of src_mesh_name
*
*--------------------------------------------------------------------*/
#ifdef PDB_WRITE
/* ARGSUSED */
SILO_CALLBACK int
db_pdb_PutMrgtree(DBfile *dbfile, char const *name,
char const *mesh_name, DBmrgtree const *tree, DBoptlist const *optlist)
{
int i, j, n, len, pass, num_nodes = tree->num_nodes;
int tot_segs, tot_children;
long count;
char *s = 0;
DBmrgtnode **ltree = 0;
char **strArray = 0;
int *intArray = 0;
DBobject *obj;
obj = DBMakeObject(name, DB_MRGTREE, 17);
/* Set global options */
db_ResetGlobalData_Mrgtree();
db_ProcessOptlist(DB_MRGTREE, optlist);
/* allocate an emtpy, linearized list of tree node pointers */
ltree = (DBmrgtnode **) malloc(num_nodes * sizeof(DBmrgtnode*));
/* walk tree to populate the linearized list of nodes ptrs */
DBWalkMrgtree(tree, (DBmrgwalkcb) DBLinearizeMrgtree, ltree, DB_POSTORDER);
/* form an array of the integer, scalar data at each node */
intArray = (int *) malloc(num_nodes * sizeof(int) * 6);
for (i = 0; i < num_nodes; i++)
{
intArray[i*6+0] = ltree[i]->narray;
intArray[i*6+1] = ltree[i]->type_info_bits;
intArray[i*6+2] = ltree[i]->max_children;
intArray[i*6+3] = ltree[i]->nsegs;
intArray[i*6+4] = ltree[i]->num_children;
intArray[i*6+5] = ltree[i] != tree->root ? ltree[i]->parent->walk_order : -1;
}
count = num_nodes * 6;
DBWriteComponent(dbfile, obj, "scalars", name, "integer", intArray, 1, &count);
FREE(intArray);
/* form an array of strings of the name data member */
strArray = (char **) malloc(num_nodes * sizeof(char *));
for (i = 0; i < num_nodes; i++)
strArray[i] = ltree[i]->name;
/* output all the node names as one long dataset */
s = 0;
DBStringArrayToStringList((char const * const *)strArray, num_nodes, &s, &len);
count = len;
DBWriteComponent(dbfile, obj, "name", name, "char", s, 1, &count);
FREE(s);
FREE(strArray);
/* form an array of strings of names data member */
/* requires 2 passes; first pass only counts, 2nd pass builds the array */
for (pass = 0; pass < 2; pass ++)
{
if (pass == 1)
{
if (n == 0)
break;
strArray = (char **) malloc(n * sizeof(char *));
}
n = 0;
for (i = 0; i < num_nodes; i++)
{
if (ltree[i]->narray > 0)
{
if (strchr(ltree[i]->names[0], '%') == 0)
{
for (j = 0; j < ltree[i]->narray; j++)
{
if (pass == 1)
strArray[n] = ltree[i]->names[j];
n++;
}
}
else
{
if (pass == 1)
strArray[n] = ltree[i]->names[0];
n++;
}
}
}
}
if (n > 0)
{
s = 0;
DBStringArrayToStringList((char const * const *)strArray, n, &s, &len);
count = len;
DBWriteComponent(dbfile, obj, "names", name, "char", s, 1, &count);
FREE(s);
}
FREE(strArray);
/* linearize and output map name data */
strArray = (char **) malloc(num_nodes * sizeof(char*));
for (i = 0; i < num_nodes; i++)
strArray[i] = ltree[i]->maps_name;
s = 0;
len = 0;
DBStringArrayToStringList((char const * const *)strArray, num_nodes, &s, &len);
count = len;
DBWriteComponent(dbfile, obj, "maps_name", name, "char", s, 1, &count);
FREE(s);
FREE(strArray);
tot_segs = 0;
for (i = 0; i < num_nodes; i++)
tot_segs += ltree[i]->nsegs * (ltree[i]->narray?ltree[i]->narray:1);
count = tot_segs;
if (tot_segs > 0)
{
/* linearize and output map segment id data */
intArray = (int *) malloc(tot_segs * sizeof(int));
n = 0;
for (i = 0; i < num_nodes; i++)
for (j = 0; j < ltree[i]->nsegs * (ltree[i]->narray?ltree[i]->narray:1); j++)
intArray[n++] = ltree[i]->seg_ids[j];
DBWriteComponent(dbfile, obj, "seg_ids", name, "integer", intArray, 1, &count);
FREE(intArray);
/* linearize and output seg len type data */
intArray = (int *) malloc(tot_segs * sizeof(int));
n = 0;
for (i = 0; i < num_nodes; i++)
for (j = 0; j < ltree[i]->nsegs * (ltree[i]->narray?ltree[i]->narray:1); j++)
intArray[n++] = ltree[i]->seg_lens[j];
DBWriteComponent(dbfile, obj, "seg_lens", name, "integer", intArray, 1, &count);
FREE(intArray);
/* linearize and output seg type data */
intArray = (int *) malloc(tot_segs * sizeof(int));
n = 0;
for (i = 0; i < num_nodes; i++)
for (j = 0; j < ltree[i]->nsegs * (ltree[i]->narray?ltree[i]->narray:1); j++)
intArray[n++] = ltree[i]->seg_types[j];
DBWriteComponent(dbfile, obj, "seg_types", name, "integer", intArray, 1, &count);
FREE(intArray);
}
/* form integer array for children data */
tot_children = 0;
for (i = 0; i < num_nodes; i++)
tot_children += ltree[i]->num_children;
if (tot_children)
{
count = tot_children;
intArray = (int *) malloc(tot_children * sizeof(int));
n = 0;
for (i = 0; i < num_nodes; i++)
for (j = 0; j < ltree[i]->num_children; j++)
intArray[n++] = ltree[i]->children[j]->walk_order;
DBWriteComponent(dbfile, obj, "children", name, "integer", intArray, 1, &count);
FREE(intArray);
}
FREE(ltree);
if (_mrgt._mrgvar_onames)
{
s = 0;
len = 0;
DBStringArrayToStringList((char const * const *)_mrgt._mrgvar_onames, -1, &s, &len);
count = len;
DBWriteComponent(dbfile, obj, "mrgvar_onames", name, "char", s, 1, &count);
FREE(s);
}
if (_mrgt._mrgvar_rnames)
{
s = 0;
len = 0;
DBStringArrayToStringList((char const * const *)_mrgt._mrgvar_rnames, -1, &s, &len);
count = len;
DBWriteComponent(dbfile, obj, "mrgvar_rnames", name, "char", s, 1, &count);
FREE(s);
}
DBAddIntComponent(obj, "src_mesh_type", tree->src_mesh_type);
DBAddStrComponent(obj, "src_mesh_name", mesh_name);
DBAddIntComponent(obj, "type_info_bits", tree->type_info_bits);
DBAddIntComponent(obj, "num_nodes", tree->num_nodes);
DBAddIntComponent(obj, "root", tree->root->walk_order);
/*-------------------------------------------------------------
* Write object to output file.
*-------------------------------------------------------------*/
DBWriteObject(dbfile, obj, TRUE);
DBFreeObject(obj);
return 0;
}
#endif /* PDB_WRITE */
/*----------------------------------------------------------------------
* Routine db_pdb_PutGroupelmap
*
* Purpose
*
* Write groupel map object into the open output file.
*
* Programmer
*
* Mark C. Miller, Wed Oct 10 10:25:53 PDT 2007
*
* Modifications:
* Mark C. Miller, Wed Aug 18 20:55:42 PDT 2010
* Fix bug setting correct size for frac_lengths array.
*--------------------------------------------------------------------*/
#ifdef PDB_WRITE
/* ARGSUSED */
SILO_CALLBACK int
db_pdb_PutGroupelmap(DBfile *dbfile, char const *name,
int num_segments, int const *groupel_types, int const *segment_lengths,
int const *segment_ids, int const * const *segment_data, void const * const *segment_fracs,
int fracs_data_type, DBoptlist const *opts)
{
int i, j, tot_len;
int *intArray;
long count;
DBobject *obj;
/*-------------------------------------------------------------
* Process option list; build object description.
*-------------------------------------------------------------*/
db_ProcessOptlist(DB_GROUPELMAP, opts);
obj = DBMakeObject(name, DB_GROUPELMAP, 10);
DBAddIntComponent(obj, "num_segments", num_segments);
DBAddIntComponent(obj, "fracs_data_type", fracs_data_type);
/* Write raw data arrays */
count = num_segments;
DBWriteComponent(dbfile, obj, "groupel_types", name, "integer",
groupel_types, 1, &count);
DBWriteComponent(dbfile, obj, "segment_lengths", name, "integer",
segment_lengths, 1, &count);
if (segment_ids)
DBWriteComponent(dbfile, obj, "segment_ids", name, "integer",
segment_ids, 1, &count);
tot_len = 0;
for (i = 0; i < num_segments; i++)
tot_len += segment_lengths[i];
if (tot_len)
{
intArray = (int *) malloc(tot_len * sizeof(int));
tot_len = 0;
for (i = 0; i < num_segments; i++)
for (j = 0; j < segment_lengths[i]; j++)
intArray[tot_len++] = segment_data[i][j];
count = tot_len;
DBWriteComponent(dbfile, obj, "segment_data", name, "integer",
intArray, 1, &count);
FREE(intArray);
}
/* write out fractional data if we have it */
if (segment_fracs)
{
void *fracsArray;
char *datatype_str;
/* write array of frac lengths */
tot_len = 0;
intArray = (int *) malloc(num_segments * sizeof(int));
for (i = 0; i < num_segments; i++)
{
int len = segment_fracs[i] == 0 ? 0 : segment_lengths[i];
intArray[i] = len;
tot_len += len;
}
count = num_segments;
DBWriteComponent(dbfile, obj, "frac_lengths", name, "integer",
intArray, 1, &count);
FREE(intArray);
/* build and write out fractional data array */
if (tot_len)
{
fracsArray = (void *) malloc(tot_len * ((fracs_data_type==DB_FLOAT)?sizeof(float):sizeof(double)));
tot_len = 0;
for (i = 0; i < num_segments; i++)
{
if (segment_fracs[i] == 0)
continue;
for (j = 0; j < segment_lengths[i]; j++)
{
if (fracs_data_type == DB_FLOAT)
{
float *pfa = (float *) fracsArray;
float *psf = (float *) segment_fracs[i];
pfa[tot_len++] = psf[j];
}
else
{
double *pfa = (double *) fracsArray;
double *psf = (double *) segment_fracs[i];
pfa[tot_len++] = psf[j];
}
}
}
count = tot_len;
datatype_str = db_GetDatatypeString(fracs_data_type);
DBWriteComponent(dbfile, obj, "segment_fracs", name, datatype_str,
fracsArray, 1, &count);
FREE(fracsArray);
FREE(datatype_str);
}
}
/*-------------------------------------------------------------
* Write material object to output file. Request that underlying
* memory be freed (the 'TRUE' argument.)
*-------------------------------------------------------------*/
DBWriteObject(dbfile, obj, TRUE);
DBFreeObject(obj);
return 0;
}
#endif /* PDB_WRITE */
/*----------------------------------------------------------------------
* Routine db_pdb_PutMrgvar
*
* Purpose
*
* Write a mrg variable object into the open output file.
*
* Programmer
*
* Mark C. Miller, Thu Oct 18 09:35:47 PDT 2007
*
*--------------------------------------------------------------------*/
#ifdef PDB_WRITE
SILO_CALLBACK int
db_pdb_PutMrgvar(DBfile *_dbfile, char const *name, char const *mrgt_name,
int ncomps, char const * const *compnames,
int nregns, char const * const *reg_pnames,
int datatype, void const * const *data, DBoptlist const *optlist)
{
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
int i, nstrs;
char *s=0; int len=0; long llen;
DBobject *obj;
char *suffix, *datatype_str, tmp1[256], tmp2[256];
static char *me = "db_pdb_PutMrgvar";
/*-------------------------------------------------------------
* Initialize global data, and process options.
*-------------------------------------------------------------*/
obj = DBMakeObject(name, DB_MRGVAR, 20);
DBAddStrComponent(obj, "mrgt_name", mrgt_name);
suffix = "data";
datatype_str = db_GetDatatypeString(datatype);
llen = nregns;
for (i = 0; i < ncomps; i++) {
char tmp3[256];
if (compnames && compnames[i])
{
sprintf(tmp3, "%s_%s", name, compnames[i]);
db_mkname(dbfile->pdb, tmp3, suffix, tmp2);
}
else
{
sprintf(tmp3, "%s_comp%d", name, i);
db_mkname(dbfile->pdb, tmp3, suffix, tmp2);
}
PJ_write_len(dbfile->pdb, tmp2, datatype_str, data[i],
1, &llen);
sprintf(tmp1, "value%d", i);
DBAddVarComponent(obj, tmp1, tmp2);
}
FREE(datatype_str);
DBAddIntComponent(obj, "ncomps", ncomps);
DBAddIntComponent(obj, "nregns", nregns);
DBAddIntComponent(obj, "datatype", datatype);
if (compnames)
{
DBStringArrayToStringList((char const * const *)compnames, ncomps, &s, &len);
llen = len;
DBWriteComponent(_dbfile, obj, "compnames", name, "char", s, 1, &llen);
FREE(s);
}
nstrs = nregns;
if (strchr(reg_pnames[0], '%') != 0)
nstrs = 1;
DBStringArrayToStringList((char const * const *)reg_pnames, nstrs, &s, &len);
llen = len;
DBWriteComponent(_dbfile, obj, "reg_pnames", name, "char", s, 1, &llen);
FREE(s);
DBWriteObject(_dbfile, obj, 0);
DBFreeObject(obj);
return 0;
}
#endif /* PDB_WRITE */
/*----------------------------------------------------------------------
* Routine db_pdb_SortObjectsByOffset
*
* Purpose: Returned array of sorted indices for a list of object names
* sorted by offset within the file.
*
* Programmer: Mark C. Miller, Thu Jul 15 08:06:27 PDT 2010
*
*--------------------------------------------------------------------*/
/* Support type for db_hdf5_SortObjectsByOffset */
typedef struct _index_offset_pair_t {
int index;
long offset;
} index_offset_pair_t;
/* Support function for db_hdf5_SortObjectsByOffset */
static int compare_index_offset_pair(void const *a1, void const *a2)
{
index_offset_pair_t *p1 = (index_offset_pair_t*) a1;
index_offset_pair_t *p2 = (index_offset_pair_t*) a2;
if (p1->offset < p2->offset) return -1;
else if (p1->offset > p2->offset) return 1;
else return 0;
}
SILO_CALLBACK int
db_pdb_SortObjectsByOffset(DBfile *_dbfile, int nobjs,
char const *const *const names, int *ordering)
{
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
static char *me = "db_pdb_SortObjectsByOffset";
index_offset_pair_t *iop = (index_offset_pair_t*)
malloc(nobjs * sizeof(index_offset_pair_t));
int i;
for (i = 0; i < nobjs; i++)
{
iop[i].index = i;
if (strchr(names[i], ':')) iop[i].offset = LONG_MAX;
else
{
syment *ep = lite_PD_inquire_entry (dbfile->pdb, (char*)names[i], TRUE, NULL);
if (!ep) iop[i].offset = LONG_MAX;
else iop[i].offset = PD_entry_address(ep);
}
}
/* Ok, sort the index/offset pairs */
qsort(iop, nobjs, sizeof(index_offset_pair_t), compare_index_offset_pair);
/* Populate ordering array */
for (i = 0; i < nobjs; i++)
ordering[i] = iop[i].index;
free(iop);
return 0;
}
/*----------------------------------------------------------------------
* Routine db_InitCsg
*
* Purpose
*
* Initialize the csg output package. This involves
* setting global data (vars, dim-ids, var-ids), writing standard
* dimensions and variables to the output file, and processing the
* option list provided by the caller.
*
* Programmer
*
* Mark C. Miller, Wed Aug 3 14:39:03 PDT 2005
*
*--------------------------------------------------------------------*/
#ifdef PDB_WRITE
PRIVATE int
db_InitCsg(DBfile *_dbfile, char const *meshname, DBoptlist const *optlist) {
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
long count[3];
char tmp[256];
db_mkname(dbfile->pdb, meshname, "typeflags", tmp);
if (lite_PD_inquire_entry(dbfile->pdb, tmp, FALSE, NULL) != NULL) {
db_ResetGlobalData_Csgmesh();
db_ProcessOptlist(DB_CSGMESH, optlist);
db_build_shared_names_csgmesh(_dbfile, meshname);
return 0;
}
/*--------------------------------------------------
* Process the given option list (this function
* modifies the global variable data based on
* the option values.)
*--------------------------------------------------*/
db_ResetGlobalData_Csgmesh();
db_ProcessOptlist(DB_CSGMESH, optlist);
db_build_shared_names_csgmesh(_dbfile, meshname);
/* Write some scalars */
count[0] = 1L;
if (_csgm._time_set == TRUE)
PJ_write_len(dbfile->pdb, _csgm._nm_time, "float", &(_csgm._time), 1, count);
if (_csgm._dtime_set == TRUE)
PJ_write_len(dbfile->pdb, _csgm._nm_dtime, "double",
&(_csgm._dtime), 1, count);
PJ_write_len(dbfile->pdb, _csgm._nm_cycle, "integer", &(_csgm._cycle),
1, count);
return 0;
}
#endif /* PDB_WRITE */
/*----------------------------------------------------------------------
* Routine db_InitPoint
*
* Purpose
*
* Initialize the point output package. This involves
* setting global data (vars, dim-ids, var-ids), writing standard
* dimensions and variables to the output file, and processing the
* option list provided by the caller.
*
* Programmer
*
* Jeffery W. Long, NSSD-B
*
* Notes
*
* Modifications
*
* Al Leibee, Mon Apr 18 07:45:58 PDT 1994
* Added _dtime.
*
*--------------------------------------------------------------------*/
#ifdef PDB_WRITE
PRIVATE int
db_InitPoint (DBfile *_dbfile, DBoptlist const *optlist, int ndims, int nels) {
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
long count[3];
/*--------------------------------------------------
* Process the given option list (this function
* modifies the global variable data based on
* the option values.)
*--------------------------------------------------*/
db_ResetGlobalData_PointMesh(ndims);
db_ProcessOptlist(DB_POINTMESH, optlist);
/*--------------------------------------------------
* Assign values to global data.
*--------------------------------------------------*/
_pm._nels = nels;
_pm._minindex = _pm._lo_offset;
_pm._maxindex = nels - _pm._hi_offset - 1;
_pm._coordnames[0] = "xpt_data";
_pm._coordnames[1] = "ypt_data";
_pm._coordnames[2] = "zpt_data";
/*------------------------------------------------------
* Define all attribute arrays and scalars which are
* likely to be needed. Some require a zonal AND nodal
* version.
*-----------------------------------------------------*/
/* Write some scalars */
count[0] = 1L;
if (_pm._time_set == TRUE) {
db_mkname(dbfile->pdb, NULL, "time", _pm._nm_time);
PJ_write_len(dbfile->pdb, _pm._nm_time, "float", &(_pm._time),
1, count);
}
if (_pm._dtime_set == TRUE) {
db_mkname(dbfile->pdb, NULL, "dtime", _pm._nm_dtime);
PJ_write_len(dbfile->pdb, _pm._nm_dtime, "double", &(_pm._dtime),
1, count);
}
db_mkname(dbfile->pdb, NULL, "cycle", _pm._nm_cycle);
PJ_write_len(dbfile->pdb, _pm._nm_cycle, "integer", &(_pm._cycle),
1, count);
return 0;
}
#endif /* PDB_WRITE */
/*----------------------------------------------------------------------
* Routine db_InitQuad
*
* Purpose
*
* Initialize the quadrilateral output package. This involves
* setting global data (vars, dim-ids, var-ids), writing standard
* dimensions and variables to the SILO file, and processing the
* option list provided by the caller.
*
* Programmer
*
* Jeffery W. Long, NSSD-B
*
* Notes
*
* Modifications
*
* Modifications
*
* Al Leibee, Sun Apr 17 07:54:25 PDT 1994
* Added dtime.
* Al Leibee, Mon Aug 9 10:30:54 PDT 1993
* Converted to new PD_inquire_entry interface.
*
* Jeremy Meredith, Fri May 21 10:04:25 PDT 1999
* Added baseindex[].
*
* Hank Childs, Thu Jan 6 13:51:22 PST 2000
* Removed unused variable error.
*
*--------------------------------------------------------------------*/
#ifdef PDB_WRITE
PRIVATE int
db_InitQuad (DBfile *_dbfile, char const *meshname, DBoptlist const *optlist,
int const *dims, int ndims) {
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
int i, is_empty = 1;
int nzones, nnodes;
long count[3];
float a[3];
char tmp[1024];
char *p=NULL;
/*--------------------------------------------------
* Define number of zones and nodes.
*--------------------------------------------------*/
nzones = nnodes = ndims?1:0;
for (i = 0; i < ndims; i++) {
nzones *= (dims[i] - 1);
nnodes *= dims[i];
if (dims[i] > 0)
is_empty = 0;
}
/*--------------------------------------------------
* Process the given option list (this function
* modifies the global variable data based on
* the option values.)
*--------------------------------------------------*/
db_ResetGlobalData_QuadMesh(ndims);
db_ProcessOptlist(DB_QUADMESH, optlist);
db_build_shared_names_quadmesh(_dbfile, meshname);
/*--------------------------------------------------
* Determine if this directory has already been
* initialized for the given mesh. If so, set
* the names of the shared variables (e.g., 'dims')
* and return. If not, write out the dimensions
* and set the names.
*--------------------------------------------------*/
db_mkname(dbfile->pdb, meshname, "dims", tmp);
if (lite_PD_inquire_entry(dbfile->pdb, tmp, FALSE, NULL) != NULL) {
return 0;
}
/*--------------------------------------------------
* Assign values to global data.
*--------------------------------------------------*/
_qm._nzones = nzones;
_qm._nnodes = nnodes;
FREE(_qm._meshname);
_qm._meshname = STRDUP(meshname);
for (i = 0; i < ndims; i++) {
_qm._dims[i] = dims[i];
_qm._zones[i] = dims[i] - 1;
_qm._minindex[i] = _qm._lo_offset[i];
_qm._maxindex_n[i] = dims[i] - _qm._hi_offset[i] - 1;
_qm._maxindex_z[i] = _qm._maxindex_n[i] - 1;
}
/*--------------------------------------------------
* This directory is uninitialized.
*
* Define all attribute arrays and scalars which are
* likely to be needed. Some require a zonal AND nodal
* version.
*-----------------------------------------------------*/
count[0] = ndims;
/* File name contained within meshname */
p = (char *)strchr(meshname, ':');
if (p == NULL) {
PJ_write_len(dbfile->pdb, _qm._nm_dims, "integer", dims, 1, count);
PJ_write_len(dbfile->pdb, _qm._nm_zones, "integer", _qm._zones, 1, count);
PJ_write_len(dbfile->pdb, _qm._nm_maxindex_n, "integer", _qm._maxindex_n, 1, count);
PJ_write_len(dbfile->pdb, _qm._nm_maxindex_z, "integer", _qm._maxindex_z, 1, count);
PJ_write_len(dbfile->pdb, _qm._nm_minindex, "integer", _qm._minindex, 1, count);
PJ_write_len(dbfile->pdb, _qm._nm_baseindex, "integer", _qm._baseindex, 1, count);
a[0] = a[1] = a[2] = 0.5;
PJ_write_len(dbfile->pdb, _qm._nm_alignz, "float", a, 1, count);
a[0] = a[1] = a[2] = 0.0;
PJ_write_len(dbfile->pdb, _qm._nm_alignn, "float", a, 1, count);
}
/* Write some scalars */
count[0] = 1L;
if (_qm._time_set == TRUE) {
PJ_write_len(dbfile->pdb, _qm._nm_time, "float", &(_qm._time), 1, count);
}
if (_qm._dtime_set == TRUE) {
PJ_write_len(dbfile->pdb, _qm._nm_dtime, "double",
&(_qm._dtime), 1, count);
}
PJ_write_len(dbfile->pdb, _qm._nm_cycle, "integer",
&(_qm._cycle), 1, count);
return 0;
}
#endif /* PDB_WRITE */
/*----------------------------------------------------------------------
* Routine db_InitUcd
*
* Purpose
*
* Initialize the uc output package. This involves
* setting global data (vars, dim-ids, var-ids), writing standard
* dimensions and variables to the output file, and processing the
* option list provided by the caller.
*
* Programmer
*
* Jeffery W. Long, NSSD-B
*
* Notes
*
* Modifications
*
* Al Leibee, Mon Aug 9 10:30:54 PDT 1993
* Converted to new PD_inquire_entry interface.
*
* Hank Childs, Thu Jan 6 13:51:22 PST 2000
* Removed unused variable error.
*
*--------------------------------------------------------------------*/
#ifdef PDB_WRITE
PRIVATE int
db_InitUcd (DBfile *_dbfile, char const *meshname, DBoptlist const *optlist,
int ndims, int nnodes, int nzones) {
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
long count[3];
float a[3];
char tmp[256];
char *p=NULL;
/*--------------------------------------------------
* Process the given option list (this function
* modifies the global variable data based on
* the option values.)
*--------------------------------------------------*/
db_ResetGlobalData_Ucdmesh(ndims, nnodes, nzones);
db_ProcessOptlist(DB_UCDMESH, optlist);
db_build_shared_names_ucdmesh(_dbfile, meshname);
/*--------------------------------------------------
* Determine if this directory has already been
* initialized. Return if it has.
*--------------------------------------------------*/
db_mkname(dbfile->pdb, meshname, "align_zonal", tmp);
if (lite_PD_inquire_entry(dbfile->pdb, tmp, FALSE, NULL) != NULL) {
return 0;
}
/*--------------------------------------------------
* Assign values to global data.
*--------------------------------------------------*/
_um._nzones = nzones;
_um._nnodes = nnodes;
/*------------------------------------------------------
* Define all attribute arrays and scalars which are
* likely to be needed. Some require a zonal AND nodal
* version.
*-----------------------------------------------------*/
count[0] = ndims;
if (count[0] <= 0)
return 0;
/*------------------------------------------------------
* Assume that if there is a file in the meshname, that
* there is possibily another mesh that may be pointing to,
* so we'll use that meshes discriptions.
*-----------------------------------------------------*/
p = (char *)strchr(meshname, ':');
if (p == NULL && count[0]) {
a[0] = a[1] = a[2] = 0.5;
PJ_write_len(dbfile->pdb, _um._nm_alignz, "float", a, 1, count);
a[0] = a[1] = a[2] = 0.0;
PJ_write_len(dbfile->pdb, _um._nm_alignn, "float", a, 1, count);
}
/* Write some scalars */
count[0] = 1L;
if (_um._time_set == TRUE)
PJ_write_len(dbfile->pdb, _um._nm_time, "float", &(_um._time), 1, count);
if (_um._dtime_set == TRUE)
PJ_write_len(dbfile->pdb, _um._nm_dtime, "double",
&(_um._dtime), 1, count);
PJ_write_len(dbfile->pdb, _um._nm_cycle, "integer", &(_um._cycle),
1, count);
return 0;
}
#endif /* PDB_WRITE */
/*----------------------------------------------------------------------
* Routine db_InitZonelist
*
* Purpose
*
* Initialize the ucd zonelist output package. This involves
* setting global data and processing the option list provided
* by the caller.
*
* Programmer
*
* Jeremy Meredith, May 21 1999
*
* Notes
*
* Modifications
*
* Hank Childs, Thu Jan 6 13:51:22 PST 2000
* Put in lint directive for unused arguments. Removed unused
* argument dbfile.
*--------------------------------------------------------------------*/
#ifdef PDB_WRITE
/* ARGSUSED */
PRIVATE int
db_InitZonelist (DBfile *_dbfile, DBoptlist const *optlist)
{
/*--------------------------------------------------
* Process the given option list (this function
* modifies the global variable data based on
* the option values.)
*--------------------------------------------------*/
db_ResetGlobalData_Ucdzonelist();
db_ProcessOptlist(DB_ZONELIST, optlist);
return 0;
}
#endif /* PDB_WRITE */
/*----------------------------------------------------------------------
* Routine db_InitPHZonelist
*
* Purpose
*
* Initialize the polyhedral zonelist output package. This involves
* setting global data and processing the option list provided
* by the caller.
*
* Programmer
*
* Mark C. Miller, July 27, 2004
*--------------------------------------------------------------------*/
#ifdef PDB_WRITE
/* ARGSUSED */
PRIVATE int
db_InitPHZonelist (DBfile *_dbfile, DBoptlist const *optlist)
{
/*--------------------------------------------------
* Process the given option list (this function
* modifies the global variable data based on
* the option values.)
*--------------------------------------------------*/
db_ResetGlobalData_phzonelist();
db_ProcessOptlist(DB_PHZONELIST, optlist);
return 0;
}
#endif /* PDB_WRITE */
/*----------------------------------------------------------------------
* Routine db_build_shared_names_csgmesh
*
* Purpose
*
* Build the names of the shared variables, based on the name
* of the current mesh. Store the names in the global variables
* (which all begin with the prefix "_nm_".
*
* Programmer
*
* Mark C. Miller, Wed Aug 3 14:39:03 PDT 2005
*--------------------------------------------------------------------*/
#ifdef PDB_WRITE
PRIVATE void
db_build_shared_names_csgmesh(DBfile *_dbfile, char const *meshname) {
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
if (_csgm._time_set == TRUE)
db_mkname(dbfile->pdb, NULL, "time", _csgm._nm_time);
if (_csgm._dtime_set == TRUE)
db_mkname(dbfile->pdb, NULL, "dtime", _csgm._nm_dtime);
db_mkname(dbfile->pdb, NULL, "cycle", _csgm._nm_cycle);
}
#endif /* PDB_WRITE */
/*----------------------------------------------------------------------
* Routine db_build_shared_names_quadmesh
*
* Purpose
*
* Build the names of the shared variables, based on the name
* of the current mesh. Store the names in the global variables
* (which all begin with the prefix "_nm_").
*
* Programmer
*
* Jeffery W. Long, NSSD-B
*
* Modifications
*
* Al Leibee, Sun Apr 17 07:54:25 PDT 1994
* Added dtime.
*
* Jeremy Meredith, Fri May 21 10:04:25 PDT 1999
* Added _nm_baseindex.
*
*--------------------------------------------------------------------*/
#ifdef PDB_WRITE
PRIVATE void
db_build_shared_names_quadmesh (DBfile *_dbfile, char const *meshname) {
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
db_mkname(dbfile->pdb, meshname, "dims", _qm._nm_dims);
db_mkname(dbfile->pdb, meshname, "zonedims", _qm._nm_zones);
db_mkname(dbfile->pdb, meshname, "max_index_n", _qm._nm_maxindex_n);
db_mkname(dbfile->pdb, meshname, "max_index_z", _qm._nm_maxindex_z);
db_mkname(dbfile->pdb, meshname, "min_index", _qm._nm_minindex);
db_mkname(dbfile->pdb, meshname, "align_zonal", _qm._nm_alignz);
db_mkname(dbfile->pdb, meshname, "align_nodal", _qm._nm_alignn);
db_mkname(dbfile->pdb, meshname, "baseindex", _qm._nm_baseindex);
if (_qm._time_set == TRUE)
db_mkname(dbfile->pdb, NULL, "time", _qm._nm_time);
if (_qm._dtime_set == TRUE)
db_mkname(dbfile->pdb, NULL, "dtime", _qm._nm_dtime);
db_mkname(dbfile->pdb, NULL, "cycle", _qm._nm_cycle);
}
#endif /* PDB_WRITE */
/*----------------------------------------------------------------------
* Routine db_ResetGlobalData_phzonelist
*
* Purpose
*
* Reset global data to default values. For internal use only.
*
* Programmer
*
* Mark C. Miller, July 27, 2004
*
*--------------------------------------------------------------------*/
#ifdef PDB_WRITE
PRIVATE int
db_ResetGlobalData_phzonelist (void) {
memset(&_phzl, 0, sizeof(_phzl));
return 0;
}
#endif /* PDB_WRITE */
/*----------------------------------------------------------------------
* Routine db_build_shared_names_ucdmesh
*
* Purpose
*
* Build the names of the shared variables, based on the name
* of the current mesh. Store the names in the global variables
* (which all begin with the prefix "_nm_".
*
* Programmer
*
* Jeffery W. Long, NSSD-B
*
* Modifications
*
* Al Leibee, Mon Apr 18 07:45:58 PDT 1994
* Added _dtime.
*--------------------------------------------------------------------*/
#ifdef PDB_WRITE
PRIVATE void
db_build_shared_names_ucdmesh (DBfile *_dbfile, char const *meshname) {
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
db_mkname(dbfile->pdb, meshname, "align_zonal", _um._nm_alignz);
db_mkname(dbfile->pdb, meshname, "align_nodal", _um._nm_alignn);
if (_um._time_set == TRUE)
db_mkname(dbfile->pdb, NULL, "time", _um._nm_time);
if (_um._dtime_set == TRUE)
db_mkname(dbfile->pdb, NULL, "dtime", _um._nm_dtime);
db_mkname(dbfile->pdb, NULL, "cycle", _um._nm_cycle);
}
#endif /* PDB_WRITE */
/*----------------------------------------------------------------------
* Routine db_mkname
*
* Purpose
*
* Generate a name based on current directory, given name, and
* the given suffix.
*
* Modifications:
* Sean Ahern, Mon Dec 18 17:48:30 PST 2000
* If the "name" starts with "/", then we don't need to determine our
* current working directory. I added this logic path.
*
* Eric Brugger, Fri Apr 6 11:15:37 PDT 2001
* I changed a comparison between an integer and NULL to an integer
* and 0.
*
*--------------------------------------------------------------------*/
#ifdef PDB_WRITE
PRIVATE void
db_mkname (PDBfile *pdb, char const *name, char const *suffix, char *out)
{
char *cwd;
out[0] = '\0';
/* Check if the "name" starts with "/", indicating an absolute
* pathname. */
if (!name || (strncmp(name, "/", 1) != 0))
{
/* Get the directory name. */
if ((cwd = lite_PD_pwd(pdb)))
{
strcat(out, cwd);
if (!STR_EQUAL("/", cwd))
strcat(out, "/");
} else
{
strcat(out, "/");
}
}
/* And tack on the file name and extension is supplied. */
if (name)
strcat(out, name);
if (suffix)
{
if (name)
strcat(out, "_");
strcat(out, suffix);
}
}
#endif /* PDB_WRITE */
/*----------------------------------------------------------------------
* Routine db_InitMulti
*
* Purpose
*
* Initialize the quadrilateral output package. This involves
* setting global data (vars, dim-ids, var-ids), writing standard
* dimensions and variables to the SILO file, and processing the
* option list provided by the caller.
*
* Programmer
*
* Eric Brugger, January 12, 1996
*
* Notes
*
* Modifications
*
*--------------------------------------------------------------------*/
#ifdef PDB_WRITE
PRIVATE int
db_InitMulti (DBfile *_dbfile, DBoptlist const *const optlist) {
DBfile_pdb *dbfile = (DBfile_pdb *) _dbfile;
long count[3];
/*--------------------------------------------------
* Process the given option list (this function
* modifies the global variable data based on
* the option values.)
*--------------------------------------------------*/
db_ResetGlobalData_MultiMesh();
db_ProcessOptlist(DB_MULTIMESH, optlist);
/*------------------------------------------------------
* Define all attribute arrays and scalars which are
* likely to be needed. Some require a zonal AND nodal
* version.
*-----------------------------------------------------*/
/* Write some scalars */
count[0] = 1L;
if (_mm._time_set == TRUE) {
db_mkname(dbfile->pdb, NULL, "time", _mm._nm_time);
PJ_write_len(dbfile->pdb, _mm._nm_time, "float", &(_mm._time),
1, count);
}
if (_mm._dtime_set == TRUE) {
db_mkname(dbfile->pdb, NULL, "dtime", _mm._nm_dtime);
PJ_write_len(dbfile->pdb, _mm._nm_dtime, "double", &(_mm._dtime),
1, count);
}
db_mkname(dbfile->pdb, NULL, "cycle", _mm._nm_cycle);
PJ_write_len(dbfile->pdb, _mm._nm_cycle, "integer", &(_mm._cycle),
1, count);
return 0;
}
#endif /* PDB_WRITE */
/*-------------------------------------------------------------------------
* Function: db_InitCurve
*
* Purpose: Inititalize global curve data.
*
* Return: void
*
* Programmer: Robb Matzke
* robb@callisto.nuance.com
* May 16, 1996
*
* Modifications:
*
*-------------------------------------------------------------------------*/
#ifdef PDB_WRITE
PRIVATE void
db_InitCurve (DBoptlist const * const opts) {
db_ResetGlobalData_Curve () ;
db_ProcessOptlist (DB_CURVE, opts) ;
}
#endif /* PDB_WRITE */
/*-------------------------------------------------------------------------
* Function: db_InitDefvars
*
* Purpose: Inititalize global defvars data.
*
* Return: void
*
* Programmer: Mark C. Miller
* March 22, 2006
*
* Modifications:
*
*-------------------------------------------------------------------------*/
#ifdef PDB_WRITE
PRIVATE void
db_InitDefvars (DBoptlist const *opts) {
db_ResetGlobalData_Defvars () ;
db_ProcessOptlist (DB_DEFVARS, opts) ;
}
#endif /* PDB_WRITE */
| 32.732901 | 238 | 0.536892 | [
"mesh",
"object",
"vector",
"3d"
] |
8c913d79803a3dc0408c5d12402d59805be804f4 | 296 | h | C | guodegangjingxuanji/guodegangjingxuanji/Views/ProgrammeHeadView.h | lynnx4869/guodegangjingxuanji | 0d6fe47a13d63c1b13bdb45fdf9bd7c92cee0d9d | [
"MIT"
] | null | null | null | guodegangjingxuanji/guodegangjingxuanji/Views/ProgrammeHeadView.h | lynnx4869/guodegangjingxuanji | 0d6fe47a13d63c1b13bdb45fdf9bd7c92cee0d9d | [
"MIT"
] | null | null | null | guodegangjingxuanji/guodegangjingxuanji/Views/ProgrammeHeadView.h | lynnx4869/guodegangjingxuanji | 0d6fe47a13d63c1b13bdb45fdf9bd7c92cee0d9d | [
"MIT"
] | null | null | null | //
// ProgrammeHeadView.h
// guodegangjingxuanji
//
// Created by qianfeng on 15/9/7.
// Copyright (c) 2015年 lyning. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "ProgrammeModel.h"
@interface ProgrammeHeadView : UIView
@property (nonatomic, strong) ProgrammeModel *model;
@end
| 17.411765 | 52 | 0.719595 | [
"model"
] |
8c9209bb9b555783deca87f96742317740ff320a | 7,109 | h | C | npp/include/tencentcloud/npp/v20190823/model/RreCallerHandle.h | li5ch/tencentcloud-sdk-cpp | 12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4 | [
"Apache-2.0"
] | 43 | 2019-08-14T08:14:12.000Z | 2022-03-30T12:35:09.000Z | npp/include/tencentcloud/npp/v20190823/model/RreCallerHandle.h | li5ch/tencentcloud-sdk-cpp | 12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4 | [
"Apache-2.0"
] | 12 | 2019-07-15T10:44:59.000Z | 2021-11-02T12:35:00.000Z | npp/include/tencentcloud/npp/v20190823/model/RreCallerHandle.h | li5ch/tencentcloud-sdk-cpp | 12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4 | [
"Apache-2.0"
] | 28 | 2019-07-12T09:06:22.000Z | 2022-03-30T08:04:18.000Z | /*
* 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.
*/
#ifndef TENCENTCLOUD_NPP_V20190823_MODEL_RRECALLERHANDLE_H_
#define TENCENTCLOUD_NPP_V20190823_MODEL_RRECALLERHANDLE_H_
#include <string>
#include <vector>
#include <map>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
#include <tencentcloud/core/AbstractModel.h>
#include <tencentcloud/npp/v20190823/model/KeyList.h>
namespace TencentCloud
{
namespace Npp
{
namespace V20190823
{
namespace Model
{
/**
* 结构体,主叫呼叫预处理操作,根据不同操作确认是否呼通被叫。如需使用,本结构体需要与 keyList 结构体配合使用,此时这两个参数都为必填项
*/
class RreCallerHandle : public AbstractModel
{
public:
RreCallerHandle();
~RreCallerHandle() = default;
void ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const;
CoreInternalOutcome Deserialize(const rapidjson::Value &value);
/**
* 获取呼叫主叫以后,给主叫用户的语音提示,播放该提示时用户所有按键无效
* @return ReadPrompt 呼叫主叫以后,给主叫用户的语音提示,播放该提示时用户所有按键无效
*/
std::string GetReadPrompt() const;
/**
* 设置呼叫主叫以后,给主叫用户的语音提示,播放该提示时用户所有按键无效
* @param ReadPrompt 呼叫主叫以后,给主叫用户的语音提示,播放该提示时用户所有按键无效
*/
void SetReadPrompt(const std::string& _readPrompt);
/**
* 判断参数 ReadPrompt 是否已赋值
* @return ReadPrompt 是否已赋值
*/
bool ReadPromptHasBeenSet() const;
/**
* 获取可中断提示,播放该提示时,用户可以按键
* @return InterruptPrompt 可中断提示,播放该提示时,用户可以按键
*/
std::string GetInterruptPrompt() const;
/**
* 设置可中断提示,播放该提示时,用户可以按键
* @param InterruptPrompt 可中断提示,播放该提示时,用户可以按键
*/
void SetInterruptPrompt(const std::string& _interruptPrompt);
/**
* 判断参数 InterruptPrompt 是否已赋值
* @return InterruptPrompt 是否已赋值
*/
bool InterruptPromptHasBeenSet() const;
/**
* 获取对应按键操作,如果没有结构体里定义按键操作用户按键以后都从 interruptPrompt 重新播放
* @return KeyList 对应按键操作,如果没有结构体里定义按键操作用户按键以后都从 interruptPrompt 重新播放
*/
std::vector<KeyList> GetKeyList() const;
/**
* 设置对应按键操作,如果没有结构体里定义按键操作用户按键以后都从 interruptPrompt 重新播放
* @param KeyList 对应按键操作,如果没有结构体里定义按键操作用户按键以后都从 interruptPrompt 重新播放
*/
void SetKeyList(const std::vector<KeyList>& _keyList);
/**
* 判断参数 KeyList 是否已赋值
* @return KeyList 是否已赋值
*/
bool KeyListHasBeenSet() const;
/**
* 获取最多重复播放次数,超过该次数拆线
* @return RepeatTimes 最多重复播放次数,超过该次数拆线
*/
std::string GetRepeatTimes() const;
/**
* 设置最多重复播放次数,超过该次数拆线
* @param RepeatTimes 最多重复播放次数,超过该次数拆线
*/
void SetRepeatTimes(const std::string& _repeatTimes);
/**
* 判断参数 RepeatTimes 是否已赋值
* @return RepeatTimes 是否已赋值
*/
bool RepeatTimesHasBeenSet() const;
/**
* 获取用户按键回调通知地址,如果为空不回调
* @return KeyPressUrl 用户按键回调通知地址,如果为空不回调
*/
std::string GetKeyPressUrl() const;
/**
* 设置用户按键回调通知地址,如果为空不回调
* @param KeyPressUrl 用户按键回调通知地址,如果为空不回调
*/
void SetKeyPressUrl(const std::string& _keyPressUrl);
/**
* 判断参数 KeyPressUrl 是否已赋值
* @return KeyPressUrl 是否已赋值
*/
bool KeyPressUrlHasBeenSet() const;
/**
* 获取提示音男声女声:1女声,2男声。默认女声
* @return PromptGender 提示音男声女声:1女声,2男声。默认女声
*/
std::string GetPromptGender() const;
/**
* 设置提示音男声女声:1女声,2男声。默认女声
* @param PromptGender 提示音男声女声:1女声,2男声。默认女声
*/
void SetPromptGender(const std::string& _promptGender);
/**
* 判断参数 PromptGender 是否已赋值
* @return PromptGender 是否已赋值
*/
bool PromptGenderHasBeenSet() const;
private:
/**
* 呼叫主叫以后,给主叫用户的语音提示,播放该提示时用户所有按键无效
*/
std::string m_readPrompt;
bool m_readPromptHasBeenSet;
/**
* 可中断提示,播放该提示时,用户可以按键
*/
std::string m_interruptPrompt;
bool m_interruptPromptHasBeenSet;
/**
* 对应按键操作,如果没有结构体里定义按键操作用户按键以后都从 interruptPrompt 重新播放
*/
std::vector<KeyList> m_keyList;
bool m_keyListHasBeenSet;
/**
* 最多重复播放次数,超过该次数拆线
*/
std::string m_repeatTimes;
bool m_repeatTimesHasBeenSet;
/**
* 用户按键回调通知地址,如果为空不回调
*/
std::string m_keyPressUrl;
bool m_keyPressUrlHasBeenSet;
/**
* 提示音男声女声:1女声,2男声。默认女声
*/
std::string m_promptGender;
bool m_promptGenderHasBeenSet;
};
}
}
}
}
#endif // !TENCENTCLOUD_NPP_V20190823_MODEL_RRECALLERHANDLE_H_
| 35.019704 | 116 | 0.474328 | [
"vector",
"model"
] |
8ca4f36792d5e490d14772c454189fb9be69dd35 | 4,320 | h | C | Ray/Scene/REntity.h | CAt0mIcS/Ray | 898ebbfe1207513045718a4fb1df339621568de4 | [
"MIT"
] | null | null | null | Ray/Scene/REntity.h | CAt0mIcS/Ray | 898ebbfe1207513045718a4fb1df339621568de4 | [
"MIT"
] | null | null | null | Ray/Scene/REntity.h | CAt0mIcS/Ray | 898ebbfe1207513045718a4fb1df339621568de4 | [
"MIT"
] | null | null | null | #pragma once
#include "../RBase.h"
#include "../Utils/RAssert.h"
#include <../../Extern/entt/src/entt/entt.hpp>
namespace At0::Ray
{
class RAY_EXPORT Entity
{
public:
static constexpr entt::entity Null = (entt::entity)-1;
public:
Entity() = default;
/**
* Construct an entity from an existing entitty handle
* @param handle Entity handle
* @param registry Registry from which the entity was created
*/
Entity(entt::entity handle, entt::registry* registry);
/**
* Construct an entity from an existing entity handle. Entity must've been created from the
* Scene's registry (default)
*/
Entity(entt::entity handle);
Entity(const Entity& other) = default;
/**
* Adds a new component to the entity
* @tparam Component The component to add to the entity
* @tparam Args Arguments to initialize the component
* @returns A reference to the created component
*/
template<typename Comp, typename... Args>
decltype(auto) Emplace(Args&&... args)
{
RAY_MEXPECTS(!Has<Comp>(), "[Entity] Entity (ID={0}) already has component",
(uint32_t)m_EntityHandle);
RAY_MEXPECTS(Valid(), "[Entity] Cannot assign component to null entity.");
if constexpr (std::is_constructible_v<Comp, Entity&, Args...>)
{
return m_Registry->emplace<Comp>(
m_EntityHandle, *this, std::forward<Args>(args)...);
}
else
{
return m_Registry->emplace<Comp>(m_EntityHandle, std::forward<Args>(args)...);
}
}
/**
* @tparam Components The components to check
* @returns If this entity has all of the specified components
*/
template<typename... Comp>
bool Has() const
{
RAY_MEXPECTS(Valid(), "[Entity] Cannot check component(s) of null entity.");
return m_Registry->has<Comp...>(m_EntityHandle);
}
/**
* @tparam Components The components to check
* @returns If this entity has any of the specified components
*/
template<typename... Comp>
bool HasAny() const
{
RAY_MEXPECTS(Valid(), "[Entity] Cannot check component(s) of null entity.");
return m_Registry->any<Comp...>(m_EntityHandle);
}
/**
* @tparam Component The components to get
* @returns The component specified or a tuple of components
*/
template<typename... Comp>
decltype(auto) Get()
{
RAY_MEXPECTS(Valid(), "[Entity] Cannot get component(s) of null entity.");
RAY_MEXPECTS(Has<Comp...>(), "[Entity] Does not have specified component(s)");
return m_Registry->get<Comp...>(m_EntityHandle);
}
/**
* @tparam Component The components to get
* @returns The component specified or a tuple of components
*/
template<typename... Comp>
decltype(auto) Get() const
{
RAY_MEXPECTS(Valid(), "[Entity] Cannot get component(s) of null entity.");
RAY_MEXPECTS(Has<Comp...>(), "[Entity] Does not have specified component(s)");
return m_Registry->get<Comp...>(m_EntityHandle);
}
/**
* @returns True if the entity is not the null entity
*/
constexpr bool Valid() const { return m_EntityHandle != Entity::Null; }
/**
* Adds/Removes/Changes the ParentEntity component's entity
*/
void SetParent(Entity parent);
/**
* Adds a child to the entity
*/
void AddChild(Entity child);
/**
* Adds list of children to the entity
*/
void AddChildren(const std::vector<Entity>& children);
/**
* Checks if the entity has the ParentEntity component
*/
bool HasParent() const;
/**
* @returns Parent entity, fails if the parent does not exist
*/
Entity GetParent() const;
/**
* @returns Children of the entity, fails if it doesn't have a HierachyComponent
*/
const std::vector<Entity>& GetChildren() const;
/**
* @returns if this has child
*/
bool HasChild(Entity child) const;
/**
* Casting operator to the entity identifier
*/
explicit operator entt::entity() const { return m_EntityHandle; }
explicit operator uint32_t() const { return (uint32_t)m_EntityHandle; }
constexpr bool operator==(const Entity& other) const;
constexpr bool operator!=(const Entity& other) const;
constexpr operator bool() { return Valid(); }
RAY_EXPORT friend std::ostream& operator<<(std::ostream& os, Entity e);
private:
entt::registry* m_Registry = nullptr;
entt::entity m_EntityHandle = Null;
};
} // namespace At0::Ray
| 26.832298 | 93 | 0.67037 | [
"vector"
] |
8ca7d03e89609dc27674a694ed3729b812995693 | 788 | h | C | plugins/core/scene/renderer_tools/Madgine_Tools/sceneeditor/gridpass.h | MadManRises/Madgine | c9949bc9cf8b30d63db0da2382c9fbc5b60bcd0f | [
"MIT"
] | 5 | 2018-05-16T14:09:34.000Z | 2019-10-24T19:01:15.000Z | plugins/core/scene/renderer_tools/Madgine_Tools/sceneeditor/gridpass.h | MadManRises/Madgine | c9949bc9cf8b30d63db0da2382c9fbc5b60bcd0f | [
"MIT"
] | 71 | 2017-06-20T06:41:42.000Z | 2021-01-11T11:18:53.000Z | plugins/core/scene/renderer_tools/Madgine_Tools/sceneeditor/gridpass.h | MadManRises/Madgine | c9949bc9cf8b30d63db0da2382c9fbc5b60bcd0f | [
"MIT"
] | 2 | 2018-05-16T13:57:25.000Z | 2018-05-16T13:57:51.000Z | #pragma once
#include "Madgine/render/renderpass.h"
/*#include "OpenGL/util/openglprogram.h"
#include "OpenGL/util/openglbuffer.h"
#include "OpenGL/util/openglvertexarray.h"*/
#include "gpumeshloader.h"
#include "programloader.h"
#include "Madgine/render/shadinglanguage/sl.h"
#define SL_SHADER grid
#include INCLUDE_SL_SHADER
namespace Engine {
namespace Tools {
struct GridPass : Render::RenderPass {
GridPass(Render::Camera *camera, int priority);
virtual void render(Render::RenderTarget *target, size_t iteration) override;
virtual int priority() const override;
private:
Render::GPUMeshLoader::HandleType mMesh;
Render::ProgramLoader::HandleType mProgram;
Render::Camera *mCamera;
int mPriority;
};
}
} | 21.888889 | 85 | 0.71066 | [
"render"
] |
8cabf5eb7e6009b45f7df1cce016a1209b4bd6b1 | 3,532 | h | C | include/stp/Simplifier/constantBitP/ConstantBitPropagation.h | eurecom-s3/stp | f8510975ecc2c9774d9dbd5759f95e90f0a32cd6 | [
"BSL-1.0",
"MIT"
] | null | null | null | include/stp/Simplifier/constantBitP/ConstantBitPropagation.h | eurecom-s3/stp | f8510975ecc2c9774d9dbd5759f95e90f0a32cd6 | [
"BSL-1.0",
"MIT"
] | null | null | null | include/stp/Simplifier/constantBitP/ConstantBitPropagation.h | eurecom-s3/stp | f8510975ecc2c9774d9dbd5759f95e90f0a32cd6 | [
"BSL-1.0",
"MIT"
] | null | null | null | // -*- c++ -*-
/********************************************************************
* AUTHORS: Trevor Hansen
*
* BEGIN DATE: Jul 5, 2010
*
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 CONSTANTBITPROPAGATION_H_
#define CONSTANTBITPROPAGATION_H_
#include "FixedBits.h"
#include "Dependencies.h"
#include "NodeToFixedBitsMap.h"
#include "WorkList.h"
#include "MultiplicationStats.h"
namespace BEEV
{
class ASTNode;
typedef unsigned int * CBV;
class Simplifier;
}
namespace simplifier
{
namespace constantBitP
{
enum Result
{
NO_CHANGE = 1, CHANGED, CONFLICT, NOT_IMPLEMENTED
};
class MultiplicationStatsMap;
class WorkList;
using BEEV::ASTNode;
using BEEV::Simplifier;
class ConstantBitPropagation
{
NodeFactory *nf;
Simplifier *simplifier;
Result status;
WorkList *workList;
Dependencies * dependents;
bool topFixed;
// A vector that's reused.
std::vector< unsigned > previousChildrenFixedCount;
void
printNodeWithFixings();
FixedBits*
getUpdatedFixedBits(const ASTNode& n);
FixedBits*
getCurrentFixedBits(const ASTNode& n);
void
scheduleDown(const ASTNode& n);
public:
NodeToFixedBitsMap* fixedMap;
MultiplicationStatsMap* msm;
bool isUnsatisfiable()
{
return status == CONFLICT;
}
// propagates.
ConstantBitPropagation(BEEV::Simplifier* _sm, NodeFactory* _nf, const ASTNode & top);
~ConstantBitPropagation()
{
clearTables();
}
;
// Returns the node after writing in simplifications from constant Bit propagation.
BEEV::ASTNode
topLevelBothWays(const ASTNode& top, bool setTopToTrue = true, bool conjoinToTop=true);
void clearTables()
{
delete fixedMap;
fixedMap = NULL;
delete dependents;
dependents = NULL;
delete workList;
workList = NULL;
delete msm;
msm = NULL;
}
bool
checkAtFixedPoint(const ASTNode& n, BEEV::ASTNodeSet & visited);
void
propagate();
void
scheduleUp(const ASTNode& n);
void
scheduleNode(const ASTNode& n);
void
setNodeToTrue(const ASTNode& top);
ASTNodeMap
getAllFixed();
void initWorkList(const ASTNode n)
{
workList->initWorkList(n);
}
};
}
}
#endif /* CONSTANTBITPROPAGATION_H_ */
| 24.027211 | 93 | 0.652039 | [
"vector"
] |
8cade7ad88f09431343582736df4afbe99970c27 | 5,364 | h | C | include/ibc/gl/model/model_base.h | dairoku/libibc | d99d8802c70263455df438588f97b38d401dd34a | [
"MIT"
] | null | null | null | include/ibc/gl/model/model_base.h | dairoku/libibc | d99d8802c70263455df438588f97b38d401dd34a | [
"MIT"
] | 1 | 2019-01-06T06:37:13.000Z | 2019-06-01T07:12:33.000Z | include/ibc/gl/model/model_base.h | dairoku/libibc | d99d8802c70263455df438588f97b38d401dd34a | [
"MIT"
] | null | null | null | // =============================================================================
// model_base.h
//
// MIT License
//
// Copyright (c) 2019 Dairoku Sekiguchi
//
// 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 ibc/gl/models/model_base.h
\author Dairoku Sekiguchi
\version 1.0.0
\date 2019/04/30
\brief Header file for the ModelBase class
*/
#ifndef IBC_GL_MODEL_BASE_H_
#define IBC_GL_MODEL_BASE_H_
// Includes --------------------------------------------------------------------
#include "ibc/base/types.h"
#include "ibc/gl/shader_interface.h"
#include "ibc/gl/model_interface.h"
// Namespace -------------------------------------------------------------------
//namespace ibc::gl::model // <- nested namespace (C++17)
namespace ibc { namespace gl { namespace model
{
// ---------------------------------------------------------------------------
// ModelBase class
// ---------------------------------------------------------------------------
#ifndef QT_VERSION
class ModelBase : public virtual ibc::gl::ModelInterface
#else
class ModelBase : public virtual ibc::gl::ModelInterface, protected IBC_QOPENGL_CLASS_NAME
#endif
{
public:
// Constructors and Destructor ---------------------------------------------
// -------------------------------------------------------------------------
// ModelBase
// -------------------------------------------------------------------------
ModelBase()
{
mShaderInterface = NULL;
mIsEnabled = true;
#ifdef QT_VERSION
mOpenGLFunctionsInitialized = false;
#endif
}
// -------------------------------------------------------------------------
// ~ModelBase
// -------------------------------------------------------------------------
virtual ~ModelBase()
{
}
// Member functions --------------------------------------------------------
// -------------------------------------------------------------------------
// setShader
// -------------------------------------------------------------------------
virtual void setShader(ibc::gl::ShaderInterface *inShaderInterface)
{
mShaderInterface = inShaderInterface;
}
// -------------------------------------------------------------------------
// getShader
// -------------------------------------------------------------------------
virtual ibc::gl::ShaderInterface *getShader()
{
return mShaderInterface;
}
// -------------------------------------------------------------------------
// initModel
// -------------------------------------------------------------------------
virtual bool initModel()
{
#ifdef QT_VERSION
if (mOpenGLFunctionsInitialized == false)
{
initializeOpenGLFunctions();
mOpenGLFunctionsInitialized = true;
}
#endif
return true;
}
// -------------------------------------------------------------------------
// disposeModel
// -------------------------------------------------------------------------
virtual void disposeModel()
{
}
// -------------------------------------------------------------------------
// setEnabled
// -------------------------------------------------------------------------
virtual void setEnabled(bool inEnabled)
{
mIsEnabled = inEnabled;
}
// -------------------------------------------------------------------------
// isEnabled
// -------------------------------------------------------------------------
virtual bool isEnabled()
{
return mIsEnabled;
}
// -------------------------------------------------------------------------
// drawModel
// -------------------------------------------------------------------------
virtual void drawModel(const GLfloat inModelView[16], const GLfloat inProjection[16])
{
UNUSED(inModelView);
UNUSED(inProjection);
}
protected:
// Member variables --------------------------------------------------------
ibc::gl::ShaderInterface *mShaderInterface;
bool mIsEnabled;
#ifdef QT_VERSION
bool mOpenGLFunctionsInitialized;
#endif
};
};};};
#endif // #ifdef IBC_GL_MODEL_BASE_H_
| 37.25 | 92 | 0.422632 | [
"model"
] |
8cb3c027aa13e24fc7dc43ef659c76eccef74c89 | 6,638 | h | C | apps/RAMDanceToolkit/src/scenes/SoundCube/SoundCube.h | YCAMInterlab/RAMDanceToolkit | 5db15135f4ad6f6a9116610b909df99036f74797 | [
"Apache-2.0"
] | 52 | 2015-01-13T05:17:23.000Z | 2021-05-09T14:09:39.000Z | apps/RAMDanceToolkit/src/scenes/SoundCube/SoundCube.h | YCAMInterlab/RAMDanceToolkit | 5db15135f4ad6f6a9116610b909df99036f74797 | [
"Apache-2.0"
] | 7 | 2015-01-12T10:25:14.000Z | 2018-09-18T12:34:15.000Z | apps/RAMDanceToolkit/src/scenes/SoundCube/SoundCube.h | YCAMInterlab/RAMDanceToolkit | 5db15135f4ad6f6a9116610b909df99036f74797 | [
"Apache-2.0"
] | 31 | 2015-01-12T06:39:15.000Z | 2020-04-06T07:05:08.000Z | //
// SoundCube.h - RAMDanceToolkit
//
// Copyright 2012-2013 YCAM InterLab, Yoshito Onishi, Satoru Higa, Motoi Shimizu, and Kyle McDonald
//
// 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.
#pragma once
#include "ramMain.h"
class SoundCube : public ramBaseScene
{
public:
class Shape
{
public:
ofColor color;
ofSoundPlayer *player;
bool trigger_mode;
bool visible;
ramCollisionEvent event;
Shape() : id(-1), obj(NULL), alpha(0), player(NULL), trigger_mode(false), visible(true) {}
~Shape()
{
if (obj)
{
delete obj;
}
if (player)
{
player->stop();
delete player;
}
}
void set(int id, ramPrimitive *obj)
{
this->id = id;
this->obj = obj;
event.setPrimitive(obj);
}
void loadSound(const string &path, bool trigger = false, bool loop = true)
{
if (player) delete player;
player = new ofSoundPlayer;
player->loadSound(path);
player->setLoop(loop ? OF_LOOP_NORMAL : OF_LOOP_NONE);
trigger_mode = trigger;
volume = volume_t = 0;
player->play();
event.setTrigger(RAM_TRIGGER_BOTH);
}
void draw(float fade = 0.1)
{
if (event.update())
{
if (event.getState())
{
if (trigger_mode) volume_t = 1;
else volume_t = 0;
}
else
{
if (!trigger_mode) volume_t = 1;
else volume_t = 0;
}
}
ofPushStyle();
if (event.getState())
{
alpha += (0 - alpha) * 0.1;
}
else
{
alpha += (1 - alpha) * 0.1;
}
volume += (volume_t - volume) * fade;
player->setVolume(volume);
if(visible)
{
ofSetColor(color, 127 + 127 * (1 - alpha));
obj->transformGL();
ofDrawBitmapString(ofToString(id), 0, 0);
obj->restoreTransformGL();
obj->draw();
}
ofPopStyle();
}
private:
int id;
ramPrimitive *obj;
float alpha;
float volume, volume_t;
};
string getName() const { return "SoundCube"; }
bool fill;
float line_width;
float fade;
bool show_box;
void setupControlPanel()
{
fade = 0.5;
ramGetGUI().addSlider("line width", 0, 10, &line_width);
ramGetGUI().addSlider("fade", 0, 1, &fade);
ramGetGUI().addToggle("show box", &show_box);
}
void setup()
{
show_box = true;
ofAddListener(ofEvents().keyPressed, this, &SoundCube::onKeyPressed);
}
void update()
{
for(int i=0; i<shapes.size(); i++)
shapes.at(i)->visible = show_box;
}
void onEnabled()
{
cout << "[Unit enabled] " << getName() << endl;
loadXML();
}
void onDisabled()
{
cout << "[Unit disabled] " << getName() << endl;
for (int i = 0; i < shapes.size(); i++)
{
shapes[i]->player->stop();
}
}
void draw()
{
ramBeginCamera();
ofNoFill();
ofPushStyle();
ofSetLineWidth(line_width);
if (show_box) ofDrawAxis(100);
for (int i = 0; i < shapes.size(); i++)
{
shapes[i]->draw(fade);
}
ofPopStyle();
ramEndCamera();
}
void loadXML()
{
clear();
#define _S(src) #src
string default_xml = _S(
<scene>
<shape type="cube" x="-100" y="50" z="0" rx="0" ry="90" rz="0" sx="200" sy="100" sz="100" color="FFFFFF" sound="../../../../resources/Sounds/1.aif" trigger="off" loop="on"/>
<shape type="cube" x="200" y="50" z="0" rx="0" ry="0" rz="0" sx="100" sy="100" sz="100" color="FFFFFF" sound="../../../../resources/Sounds/2.aif" trigger="on" loop="on"/>
<shape type="cube" x="200" y="50" z="200" rx="0" ry="0" rz="0" sx="100" sy="100" sz="100" color="FFFFFF" sound="../../../../resources/Sounds/3.aif" trigger="off" loop="on"/>
<shape type="cube" x="200" y="50" z="-200" rx="0" ry="0" rz="0" sx="100" sy="100" sz="100" color="FFFFFF" sound="../../../../resources/Sounds/4.aif" trigger="on" loop="on"/>
</scene>
);
#undef _S
const string filePath = "SoundCube.xml";
if (!ofFile::doesFileExist(filePath))
{
ofBuffer buf(default_xml);
ofBufferToFile(filePath, buf);
}
ofxXmlSettings xml;
xml.loadFile(filePath);
xml.pushTag("scene");
int n = xml.getNumTags("shape");
for (int i = 0; i < n; i++)
{
ofVec3f pos;
ofVec3f rot;
ofVec3f size;
pos.x = xml.getAttribute("shape", "x", 0, i);
pos.y = xml.getAttribute("shape", "y", 0, i);
pos.z = xml.getAttribute("shape", "z", 0, i);
rot.x = xml.getAttribute("shape", "rx", 0, i);
rot.y = xml.getAttribute("shape", "ry", 0, i);
rot.z = xml.getAttribute("shape", "rz", 0, i);
size.x = xml.getAttribute("shape", "sx", 1, i);
size.y = xml.getAttribute("shape", "sy", 1, i);
size.z = xml.getAttribute("shape", "sz", 1, i);
string hex = xml.getAttribute("shape", "color", "777777", i);
ofColor color = ofColor::fromHex(ofHexToInt(hex));
string type = xml.getAttribute("shape", "type", "", i);
if (type != "")
{
ramPrimitive *s;
if (type == "cube")
{
s = new ramBoxPrimitive(size);
}
else if (type == "pyramid")
{
s = new ramPyramidPrimitive(size.x);
}
else if (type == "sphere")
{
s = new ramSpherePrimitive(size.x);
}
else
{
ofLogError("Shape") << "invalid shape type";
continue;
}
s->setPosition(pos);
s->setOrientation(rot);
s->updatePhysicsTransform();
s->getRigidBody().setStatic(true);
Shape *o = new Shape;
o->color = color;
o->set(i, s);
string sound = xml.getAttribute("shape", "sound", "", i);
bool toggle_mode = xml.getAttribute("shape", "trigger", "off", i) == "on";
bool loop = xml.getAttribute("shape", "loop", "off", i) == "on";
if (sound != "")
{
o->loadSound(ramToResourcePath(sound), toggle_mode, loop);
}
cout << type << " loaded." << endl;
shapes.push_back(o);
}
else
{
ofLogError("Shape") << "invalid shape type";
continue;
}
}
xml.popTag();
}
void clear()
{
for (int i = 0; i < shapes.size(); i++)
delete shapes[i];
shapes.clear();
}
void onKeyPressed(ofKeyEventArgs &e)
{
if (isEnabled()) return;
if (e.key == 'r')
loadXML();
}
protected:
vector<Shape*> shapes;
};
| 20.424615 | 173 | 0.578186 | [
"shape",
"vector"
] |
8cb5a6693cc6122b27acda160d8233155eadf895 | 2,554 | h | C | garnet/bin/trace/tests/run_test.h | opensource-assist/fuschia | 66646c55b3d0b36aae90a4b6706b87f1a6261935 | [
"BSD-3-Clause"
] | 3 | 2020-08-02T04:46:18.000Z | 2020-08-07T10:10:53.000Z | garnet/bin/trace/tests/run_test.h | opensource-assist/fuschia | 66646c55b3d0b36aae90a4b6706b87f1a6261935 | [
"BSD-3-Clause"
] | null | null | null | garnet/bin/trace/tests/run_test.h | opensource-assist/fuschia | 66646c55b3d0b36aae90a4b6706b87f1a6261935 | [
"BSD-3-Clause"
] | 1 | 2020-08-07T10:11:49.000Z | 2020-08-07T10:11:49.000Z | // Copyright 2018 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.
#ifndef GARNET_BIN_TRACE_TESTS_RUN_TEST_H_
#define GARNET_BIN_TRACE_TESTS_RUN_TEST_H_
#include <fuchsia/sys/cpp/fidl.h>
#include <lib/zx/job.h>
#include <lib/zx/process.h>
#include <lib/zx/time.h>
#include <string>
#include <vector>
namespace tracing {
namespace test {
// Our component's tmp directory.
constexpr char kTestTmpPath[] = "/tmp";
// Path to use for package-relative paths.
constexpr char kTestPackagePath[] = "/pkg";
// Path to our package for use in spawned processes.
// Our component's /pkg directory is bound to this path in the spawned process.
// This is useful when wanting the trace program to be able to read our tspec files.
constexpr char kSpawnedTestPackagePath[] = "/test-pkg";
// Path to our tmp directory for use in spawned processes.
// Our component's /tmp directory is bound to this path in the spawned process.
// This is useful when wanting the trace program to write output to our /tmp directory.
constexpr char kSpawnedTestTmpPath[] = "/test-tmp";
// Run the trace program, but do not wait for it to exit.
// |args| is the list of arguments to pass. It is not called |argv| as it does not include argv[0].
// Wait for trace to exit with |WaitAndGetReturnCode()|.
// The only current reason to use this instead of |RunTraceAndWait()| is when one is expecting a
// non-zero return code from trace.
bool RunTrace(const zx::job& job, const std::vector<std::string>& args, zx::process* out_child);
// Run the trace program and wait for it to exit.
// Returns true if trace ran successfully and exited with a zero return code.
// |args| is the list of arguments to pass. It is not called |argv| as it does not include argv[0].
bool RunTraceAndWait(const zx::job& job, const std::vector<std::string>& args);
// We don't need to pass a context to RunTspec because the trace program
// is currently a system app. If that changes then we will need a context
// to run the trace too.
bool RunTspec(const std::string& relative_tspec_path,
const std::string& relative_output_file_path);
// N.B. This is a synchronous call that uses an internal async loop.
// ("synchronous" meaning that it waits for the verifier to complete).
bool VerifyTspec(const std::string& relative_tspec_path,
const std::string& relative_output_file_path);
} // namespace test
} // namespace tracing
#endif // GARNET_BIN_TRACE_TESTS_RUN_TEST_H_
| 41.193548 | 99 | 0.742365 | [
"vector"
] |
8cbc0779200ba5da16941163eb3f63d0dffc7c87 | 6,944 | h | C | include/core/particle.h | cubic1271/leaps | 492cdcddfc0b3f63b657da94fc4a4303980dd07f | [
"Zlib",
"CC0-1.0",
"MIT"
] | null | null | null | include/core/particle.h | cubic1271/leaps | 492cdcddfc0b3f63b657da94fc4a4303980dd07f | [
"Zlib",
"CC0-1.0",
"MIT"
] | null | null | null | include/core/particle.h | cubic1271/leaps | 492cdcddfc0b3f63b657da94fc4a4303980dd07f | [
"Zlib",
"CC0-1.0",
"MIT"
] | null | null | null | #ifndef TWILIGHT_PARTICLE_H
#define TWILIGHT_PARTICLE_H
#include <cmath>
#include <vector>
#include <map>
#include <string>
#include <simple2d/simple2d.h>
#include "util.h"
namespace twilight {
class vec2 {
public:
double x;
double y;
vec2() : x(0), y(0) { }
vec2(double x, double y) : x(x), y(y) { }
vec2(vec2& target) = default;
vec2(const vec2& target) = default;
vec2& operator= (vec2 target) {
if(&target != this) {
x = target.x;
y = target.y;
}
return *this;
}
vec2 operator+ (double scalar) {return {x + scalar, y + scalar};}
vec2 operator+ (vec2 target) {return {x + target.x, y + target.y};}
vec2 operator- (double scalar) {return {x - scalar, y - scalar};}
vec2 operator- (vec2 target) {return {x - target.x, y - target.y};}
vec2 operator* (double scalar) {return {x * scalar, y * scalar};}
vec2 operator/ (double scalar) {return {x / scalar, y / scalar};}
double dot(vec2 target) {return x * target.x + y * target.y;}
vec2 ccw() {return {-y, x}; }
vec2 cw() {return {y, -x}; }
double magnitude() {
return sqrt(x * x + y * y);
}
vec2 rotate(double beta) {
return {
cos(beta) * x - sin(beta) * y,
sin(beta) * x + cos(beta) * y
};
}
vec2 normalize() {
double val = sqrt((x * x) + (y * y));
return {x / val, y / val};
}
};
/**
* A 2-D equivalent of a camera.
*
* Takes a series of x, y coordinates in the simulation and projects them into appropriate positions on the screen -
* this keeps us from having to use pixel values to drive our physical simulation, which is usually suboptimal. It
* also allows us to, for example, handle zoom and scroll without too much additional difficulty.
*/
class Projector {
public:
Projector()
:screen_width(0), screen_height(0), screen_x_offset(0), screen_y_offset(0),
simulation_width(0), simulation_height(0), simulation_x_offset(0), simulation_y_offset(0) { }
void simulationToScreen(const vec2& simulation, vec2& screen);
void screenToSimulation(const vec2& screen, vec2& simulation);
void setScreen(int width, int height) { screen_width = width; screen_height = height; }
void setScreenOffset(int x, int y) { screen_x_offset = x; screen_y_offset = y; }
void setSimulation(double width, double height) { simulation_width = int(width); simulation_height = int(height); }
void setSimulationOffset(double x, double y) {simulation_x_offset = int(x); simulation_y_offset = int(y); }
private:
int screen_width;
int screen_height;
int screen_x_offset;
int screen_y_offset;
int simulation_width;
int simulation_height;
int simulation_x_offset;
int simulation_y_offset;
};
class Particle {
public:
vec2 position;
vec2 velocity;
vec2 acceleration;
S2D_Sprite* graphic;
double elapsed;
double lifetime;
explicit Particle()
: position{0, 0}, velocity{0, 0}, acceleration{0, 0}, graphic(nullptr), elapsed(0),
lifetime(0) { }
explicit Particle(S2D_Sprite* graphic)
: position{0, 0}, velocity{0, 0}, acceleration{0, 0}, graphic(graphic), elapsed(0),
lifetime(0) { }
void setPosition(vec2 location) {this->position = location; }
void setVelocity(vec2 velocity) {this->velocity = velocity; }
void setAcceleration(vec2 acceleration) {this->acceleration = acceleration; }
void setLifetime(double life) { this->lifetime = life; }
};
class ParticleSystem {
public:
static constexpr int PARTICLE_SYSTEM_RUNNING = 0;
static constexpr int PARTICLE_SYSTEM_STOPPED = 1;
void setEmission(double emission) { this->emission = emission; }
void setLocation(vec2 location) { this->location = location; }
void setLifetime(double lifetime) { this->lifetime = lifetime; }
void setPersistent(bool persistent) { this->persistent = persistent; }
void setDirection(vec2 direction) { this->direction = direction; }
void setSpeed(double speed) { this->speed = speed; }
void setRadius(double radius) { this->radius = radius; }
void setState(int state) { this->state = state; }
void setName(std::string name) { this->name = name; }
void setAcceleration(vec2 acceleration) { this->acceleration = acceleration; }
void update(double dt);
void render();
bool complete() { return clock.total() > systemLifetime && particles.empty(); }
ParticleSystem()
: state(PARTICLE_SYSTEM_STOPPED), emission(0), clock{ }, location{0, 0}, lifetime(0), systemLifetime(0),
persistent(false), direction{0.0, -1.0}, angle(0), speed(0), radius(5), rangeMin(1), rangeMax(1),
acceleration{ }, graphics{ }, particles{ } { }
private:
// Properties of the particle system itself
int state;
double emission;
twilight::Timer clock{};
vec2 location;
double lifetime;
double systemLifetime;
bool persistent;
// Properties of the particles being emitted
vec2 direction;
double angle;
double speed;
double radius;
vec2 acceleration;
uint32_t rangeMin;
uint32_t rangeMax;
std::string name;
std::vector<S2D_Sprite*> graphics{};
std::vector<Particle> particles{};
friend class ParticleManager;
};
class ParticleManager {
public:
typedef std::vector<ParticleSystem*> ParticleSystemContainer;
typedef std::map<std::string, ParticleSystem*> ParticleSystemCache;
static ParticleManager* instance();
ParticleSystem* loadParticleSystem(std::string name);
void update(double dt);
void render();
void clear();
private:
ParticleSystemContainer system;
ParticleSystemCache cache;
};
}
#endif //TWILIGHT_PARTICLE_H
| 37.535135 | 123 | 0.546803 | [
"render",
"vector"
] |
8cc3da2833fcf0e6a4c9b4fb24f4c7ee85bc98fe | 658 | h | C | tutorials/es/bibliotecas-gui/sdl/src/SdlTexture.h | mlafroce/mlafroce.github.io | b9d652801d9ce4f1126532139b419090be27f032 | [
"CC-BY-4.0"
] | 1 | 2017-03-23T18:51:28.000Z | 2017-03-23T18:51:28.000Z | tutorials/es/bibliotecas-gui/sdl/src/SdlTexture.h | mlafroce/mlafroce.github.io | b9d652801d9ce4f1126532139b419090be27f032 | [
"CC-BY-4.0"
] | null | null | null | tutorials/es/bibliotecas-gui/sdl/src/SdlTexture.h | mlafroce/mlafroce.github.io | b9d652801d9ce4f1126532139b419090be27f032 | [
"CC-BY-4.0"
] | 1 | 2017-08-14T14:50:33.000Z | 2017-08-14T14:50:33.000Z | #ifndef __SDL_TEXTURE_H__
#define __SDL_TEXTURE_H__
#include <string>
class SDL_Texture;
class SDL_Renderer;
class SdlWindow;
class Area;
class SdlTexture {
public:
/**
* Crea un SDL_Texture, lanza una excepción si el filename es inválido
**/
SdlTexture(const std::string &filename, const SdlWindow& window);
/**
* Libera la memoria reservada por la textura
**/
~SdlTexture();
/**
* Renderiza la textura cargada
**/
int render(const Area& src, const Area& dest) const;
private:
SDL_Texture* loadTexture(const std::string &filename);
SDL_Renderer* renderer;
SDL_Texture* texture;
};
#endif
| 21.225806 | 74 | 0.680851 | [
"render"
] |
8ccf7ba587102128b4ee52d88a290c044da7da05 | 632 | h | C | src/game/game_tank0_state.h | sea-kg/sdl2-example | 71389fef00ee7c9573832f3ebdfb96696606e3a1 | [
"MIT"
] | 1 | 2021-04-10T04:55:57.000Z | 2021-04-10T04:55:57.000Z | src/game/game_tank0_state.h | sea-kg/sdl2-example | 71389fef00ee7c9573832f3ebdfb96696606e3a1 | [
"MIT"
] | 44 | 2021-03-11T04:07:24.000Z | 2021-05-10T06:22:34.000Z | src/game/game_tank0_state.h | sea-kg/yourCityIsInvadedByAliens | 71389fef00ee7c9573832f3ebdfb96696606e3a1 | [
"MIT"
] | null | null | null | #pragma once
#include <vector>
#include "coordxy.h"
#include "move_object_direction.h"
#include "game_rocket_state.h"
class GameTank0State {
public:
GameTank0State(const CoordXY &p0);
MoveObjectDirection getDirection();
const CoordXY &getPosition();
void turnLeft();
void turnRight();
void move();
bool hasRocket();
void rechargeRocket();
void shotRocket();
GameRocketState *popRocket();
private:
CoordXY m_p0;
bool m_bHasRocket;
MoveObjectDirection m_nDirection;
std::vector<GameRocketState *> m_vRockets;
};
| 24.307692 | 50 | 0.632911 | [
"vector"
] |
8ccf855ffe81546b200701bd2eec3c6064f71174 | 1,381 | h | C | tests/juliet/testcases/CWE36_Absolute_Path_Traversal/s01/CWE36_Absolute_Path_Traversal__char_environment_fopen_83.h | RanerL/analyzer | a401da4680f163201326881802ee535d6cf97f5a | [
"MIT"
] | 28 | 2017-01-20T15:25:54.000Z | 2020-03-17T00:28:31.000Z | testcases/CWE36_Absolute_Path_Traversal/s01/CWE36_Absolute_Path_Traversal__char_environment_fopen_83.h | mellowCS/cwe_checker_juliet_suite | ae604f6fd94964251fbe88ef04d5287f6c1ffbe2 | [
"MIT"
] | 1 | 2017-01-20T15:26:27.000Z | 2018-08-20T00:55:37.000Z | testcases/CWE36_Absolute_Path_Traversal/s01/CWE36_Absolute_Path_Traversal__char_environment_fopen_83.h | mellowCS/cwe_checker_juliet_suite | ae604f6fd94964251fbe88ef04d5287f6c1ffbe2 | [
"MIT"
] | 2 | 2019-07-15T19:07:04.000Z | 2019-09-07T14:21:04.000Z | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE36_Absolute_Path_Traversal__char_environment_fopen_83.h
Label Definition File: CWE36_Absolute_Path_Traversal.label.xml
Template File: sources-sink-83.tmpl.h
*/
/*
* @description
* CWE: 36 Absolute Path Traversal
* BadSource: environment Read input from an environment variable
* GoodSource: Full path and file name
* Sinks: fopen
* BadSink : Open the file named in data using fopen()
* Flow Variant: 83 Data flow: data passed to class constructor and destructor by declaring the class object on the stack
*
* */
#include "std_testcase.h"
#ifndef _WIN32
#include <wchar.h>
#endif
namespace CWE36_Absolute_Path_Traversal__char_environment_fopen_83
{
#ifndef OMITBAD
class CWE36_Absolute_Path_Traversal__char_environment_fopen_83_bad
{
public:
CWE36_Absolute_Path_Traversal__char_environment_fopen_83_bad(char * dataCopy);
~CWE36_Absolute_Path_Traversal__char_environment_fopen_83_bad();
private:
char * data;
};
#endif /* OMITBAD */
#ifndef OMITGOOD
class CWE36_Absolute_Path_Traversal__char_environment_fopen_83_goodG2B
{
public:
CWE36_Absolute_Path_Traversal__char_environment_fopen_83_goodG2B(char * dataCopy);
~CWE36_Absolute_Path_Traversal__char_environment_fopen_83_goodG2B();
private:
char * data;
};
#endif /* OMITGOOD */
}
| 25.109091 | 122 | 0.768284 | [
"object"
] |
8ceaa6c082db45982550c2954809d0ec7e3d7b4b | 10,577 | c | C | graph.c | shoumodip/graph | 670bea777af1d0dbec1f74d8b8f80ae3e6370d1b | [
"MIT"
] | null | null | null | graph.c | shoumodip/graph | 670bea777af1d0dbec1f74d8b8f80ae3e6370d1b | [
"MIT"
] | null | null | null | graph.c | shoumodip/graph | 670bea777af1d0dbec1f74d8b8f80ae3e6370d1b | [
"MIT"
] | null | null | null | #include <ctype.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <stdbool.h>
/*
* The usage information of the program
*/
#define USAGE \
"usage: graph [EQUATION] [FLAG]\n" \
"flags:\n" \
" -h - Display this help message and exit\n" \
" -r ROWS - Set the number of rows in the graph\n" \
" -c COLS - Set the number of columns in the graph\n" \
" -o PATH - Set the path of the output file\n" \
" -f FORE - Set the color of the foreground in the graph\n" \
" -b BACK - Set the color of the background in the graph\n" \
/*
* Get the maximum between two values
*/
#define MAX(a, b) ((a > b) ? a : b)
/*
* Get the maximum between two values
*/
#define MIN(a, b) ((a < b) ? a : b)
/*
* Assert a condition
*/
#define ASSERT(condition, ...) \
if (!(condition)) { \
fprintf(stderr, "error: "); \
fprintf(stderr, __VA_ARGS__); \
fprintf(stderr, "\n"); \
graph_free(graph); \
exit(1); \
}
/*
* Grow an array to a particular length
*/
#define GROW_ARRAY(type, array, length, capacity, min) \
if (length >= capacity) { \
capacity = (capacity >= min) ? capacity * 2 : min; \
array = (array) \
? realloc(array, sizeof(type) * capacity) \
: malloc(sizeof(type) * capacity); \
}
/*
* A term of algebraic polynomial
*/
typedef struct {
float scale;
size_t power;
} Term;
/*
* An algebraic polynomial which represents a line in 2D space
*/
typedef struct {
Term *terms;
size_t count;
size_t capacity;
} Line;
/*
* The minimum number of terms in a line
* Set to a sufficiently high value to avoid repeated realloc() calls,
* which has a high time complexity.
*/
#define MINIMUM_LINE_CAPACITY 8
/*
* A graph in 2D space
*/
typedef struct {
Line *lines;
size_t count;
size_t capacity;
size_t rows;
size_t cols;
uint32_t fore;
uint32_t back;
char *path;
bool *grid;
} Graph;
/*
* The minimum number of lines in a graph
* Set to a sufficiently high value to avoid repeated realloc() calls,
* which has a high time complexity.
*/
#define MINIMUM_GRAPH_CAPACITY 128
/*
* Skip the whitespace in a string
* @param expr **char The string to skip the whitespace in
*/
void skip_whitespace(char **expr)
{
while (isspace(**expr)) *expr += 1;
}
/*
* Parse a scalar from the beginning of a string
* @param expr **char The string to parse the scalar from
* @return float The parsed scalar or 1.0 incase of parsing failure
*/
float parse_scale(char **expr)
{
skip_whitespace(expr);
return (isdigit(**expr) || **expr == '-') ? strtof(*expr, expr) : 1.0;
}
/*
* Parse 'x'power from the beginning of a string
* @param expr **char The string to parse the power from
* @return size_t The parsed power or 0 incase of parsing failure
*/
size_t parse_power(char **expr)
{
skip_whitespace(expr);
if (**expr != 'x') return 0;
*expr += 1;
skip_whitespace(expr);
return (isdigit(**expr)) ? strtod(*expr, expr) : 1;
}
/*
* Parse a term from a string
* @param term *Term The term to parse into
* @param expr **char The string to parse from
* @return bool If the end of the polynomial has been reached
*/
bool term_parse(Term *term, char **expr)
{
skip_whitespace(expr);
switch (**expr) {
case '-':
*expr += 1;
term->scale = -1.0 * parse_scale(expr);
break;
case '+':
*expr += 1;
term->scale = parse_scale(expr);
break;
case '\0':
return false;
default:
term->scale = parse_scale(expr);
break;
}
term->power = parse_power(expr);
return true;
}
/*
* Solve a term for a value of 'x'
* @param term Term The term to solve
* @param x float The value of 'x' to solve for
* @return float The solved value
*/
float term_solve(Term term, float x)
{
for (size_t i = 0; i < term.power; ++i) term.scale *= x;
return term.scale;
}
/*
* Append a term to a line
* @param line *Line The line to append to term to
* @param term Term The term to append to the line
*/
void line_append(Line *line, Term term)
{
GROW_ARRAY(Term,
line->terms,
line->count,
line->capacity,
MINIMUM_LINE_CAPACITY);
line->terms[line->count++] = term;
}
/*
* Deallocate all memory in a line
* @param line *Line The line to free
*/
void line_free(Line *line)
{
if (line->terms) free(line->terms);
line->count = line->capacity = 0;
}
/*
* Parse a string into a line
* @param line *Line The line to parse the string into
* @param expr **char The string to parse
*/
void line_parse(Line *line, char **expr)
{
Term term = {0};
while (term_parse(&term, expr)) line_append(line, term);
}
/*
* Solve a line for a value of 'x'
* @param line *Line The line to solve
* @param x float The value to solve for
* @return float The solved result
*/
float line_solve(Line line, float x)
{
float result = 0.0;
for (size_t i = 0; i < line.count; ++i)
result += term_solve(line.terms[i], x);
return result;
}
/*
* Append a line to a graph
* @param graph *Graph The graph to append to line to
* @param line Line The line to append to the graph
*/
void graph_append(Graph *graph, Line line)
{
GROW_ARRAY(Line,
graph->lines,
graph->count,
graph->capacity,
MINIMUM_GRAPH_CAPACITY);
graph->lines[graph->count++] = line;
}
/*
* Deallocate all memory in a graph
* @param graph *Graph The graph to free
*/
void graph_free(Graph *graph)
{
if (graph->lines) {
for (size_t i = 0; i < graph->count; ++i)
line_free(&graph->lines[i]);
free(graph->lines);
}
if (graph->grid) free(graph->grid);
}
/*
* Parse the command line arguments into a graph
* @param graph *Graph The graph to parse the arguments into
* @param argc size_t The number of command line arguments
* @param argv **char The command line arguments
*/
void graph_args(Graph *graph, size_t argc, char **argv)
{
graph->rows = 100;
graph->cols = 100;
graph->fore = 0x93E0E3;
graph->back = 0x3F3F3F;
graph->path = "output.ppm";
for (size_t i = 1; i < argc; ++i) {
if (strcmp(argv[i], "-r") == 0) {
ASSERT(argc > ++i, "ROWS not specified [-r]\n" USAGE);
graph->rows = atoi(argv[i]);
ASSERT(graph->rows != 0, "invalid number of rows: '%s'", argv[i]);
} else if (strcmp(argv[i], "-c") == 0) {
ASSERT(argc > ++i, "COLS not specified [-c]\n" USAGE);
graph->cols = atoi(argv[i]);
ASSERT(graph->cols != 0, "invalid number of columns: '%s'", argv[i]);
} else if (strcmp(argv[i], "-f") == 0) {
ASSERT(argc > ++i, "FORE not specified [-f]\n" USAGE);
int parsed = sscanf((*argv[i] == '#') ? argv[i] + 1 : argv[i],
"%x", &graph->back);
ASSERT(parsed == 1, "invalid foreground color: '%s'", argv[i]);
} else if (strcmp(argv[i], "-b") == 0) {
ASSERT(argc > ++i, "BACK not specified [-b]\n" USAGE);
int parsed = sscanf((*argv[i] == '#') ? argv[i] + 1 : argv[i],
"%x", &graph->back);
ASSERT(parsed == 1, "invalid background color: '%s'", argv[i]);
} else if (strcmp(argv[i], "-o") == 0) {
ASSERT(argc > ++i, "PATH not specified [-o]\n" USAGE);
graph->path = argv[i];
} else if (strcmp(argv[i], "-h") == 0) {
fprintf(stdout, USAGE);
exit(0);
} else {
ASSERT(*argv[i] != '-', "invalid flag '%s'", argv[i]);
Line line = {0};
line_parse(&line, &argv[i]);
graph_append(graph, line);
}
}
graph->grid = calloc(graph->rows * graph->cols, sizeof(bool));
}
/*
* Render the grid of a graph
* @param graph *Graph The graph to render
*/
void graph_draw(Graph *graph)
{
float dx = graph->cols / 2.0;
float dy = graph->rows / 2.0;
for (size_t i = 0; i < graph->count; ++i) {
bool drawn = false;
size_t ly = 0;
for (size_t x = 0; x < graph->cols; ++x) {
size_t y = dy - line_solve(graph->lines[i], x - dx);
if (y < graph->rows) {
if (drawn) {
for (size_t ay = MIN(y, ly); ay < MAX(y, ly); ++ay) {
if (ay < graph->rows) {
graph->grid[ay * graph->cols + x] = true;
}
}
} else {
graph->grid[y * graph->cols + x] = true;
drawn = true;
}
ly = y;
}
}
}
}
/*
* Store the RGB components in an array
* @param components uint8_t[3] The array to store the components into
* @param color uint32_t The color to extract the components from
*/
void rgb_components(uint8_t components[3], uint32_t color)
{
for (size_t i = 0; i < 3; ++i) components[2 - i] = (color >> 8 * i) & 0xff;
}
/*
* Save the graph to a PPM image
* @param graph *Graph The graph to draw
*/
void graph_save(Graph *graph)
{
FILE *file = fopen(graph->path, "w");
ASSERT(file, "could not write '%s'", graph->path);
uint8_t foreground[3], background[3];
rgb_components(foreground, graph->fore);
rgb_components(background, graph->back);
fprintf(file, "P3 %zu %zu 255\n", graph->cols, graph->rows);
for (size_t y = 0; y < graph->rows; ++y) {
for (size_t x = 0; x < graph->cols; ++x) {
uint8_t *face = (graph->grid[y * graph->cols + x])
? foreground
: background;
fprintf(file, "%u %u %u ", face[0], face[1], face[2]);
}
fprintf(file, "\n");
}
fclose(file);
}
int main(int argc, char **argv)
{
Graph graph = {0};
graph_args(&graph, argc, argv);
graph_draw(&graph);
graph_save(&graph);
graph_free(&graph);
return 0;
}
| 26.575377 | 81 | 0.535974 | [
"render"
] |
8ceaf79f519a779145baf7bb9d82e52fa8ff648d | 3,001 | h | C | include/FunctionalPlus/Generate.h | okam/FunctionalPlus | 6cdf23dd9e7a8149a9e651488cd503cb2e8ed421 | [
"BSL-1.0"
] | 1 | 2021-06-25T21:00:47.000Z | 2021-06-25T21:00:47.000Z | include/FunctionalPlus/Generate.h | okam/FunctionalPlus | 6cdf23dd9e7a8149a9e651488cd503cb2e8ed421 | [
"BSL-1.0"
] | null | null | null | include/FunctionalPlus/Generate.h | okam/FunctionalPlus | 6cdf23dd9e7a8149a9e651488cd503cb2e8ed421 | [
"BSL-1.0"
] | null | null | null | // Copyright Tobias Hermann 2015.
// 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)
#pragma once
#include "ContainerCommon.h"
namespace FunctionalPlus
{
// Generate(f, 3) == [f(), f(), f()]
template <typename ContainerOut, typename F>
ContainerOut Generate(F f, std::size_t amount)
{
static_assert(utils::function_traits<F>::arity == 0, "Wrong arity.");
ContainerOut ys;
PrepareContainer(ys, amount);
auto it = BackInserter<ContainerOut>(ys);
for (std::size_t i = 0; i < amount; ++i)
{
*it = f();
}
return ys;
}
// GenerateByIdx(f, 3) == [f(0), f(1), f(2)]
template <typename ContainerOut, typename F>
ContainerOut GenerateByIdx(F f, std::size_t amount)
{
static_assert(utils::function_traits<F>::arity == 1, "Wrong arity.");
typedef typename utils::function_traits<F>::template arg<0>::type FIn;
static_assert(std::is_convertible<std::size_t, FIn>::value, "Function does not take std::size_t or compatible type.");
ContainerOut ys;
PrepareContainer(ys, amount);
auto it = BackInserter<ContainerOut>(ys);
for (std::size_t i = 0; i < amount; ++i)
{
*it = f(i);
}
return ys;
}
// GenerateIntegralRangeStep(2, 9, 2) == [2, 4, 6, 8]
template <typename ContainerOut, typename T>
ContainerOut GenerateIntegralRangeStep
(const T start, const T end, const T step)
{
ContainerOut result;
std::size_t size = (end - start) / step;
PrepareContainer(result, size);
auto it = BackInserter<ContainerOut>(result);
for (T x = start; x < end; x+=step)
*it = x;
return result;
}
// GenerateIntegralRange(2, 8, 2) == [2, 3, 4, 5, 6, 7, 8]
template <typename ContainerOut, typename T>
ContainerOut GenerateIntegralRange(const T start, const T end)
{
return GenerateIntegralRangeStep<ContainerOut>(start, end, 1);
}
// Repeat(3, [1, 2]) == [1, 2, 1, 2, 1, 2]
template <typename Container>
Container Repeat(size_t n, const Container& xs)
{
std::vector<Container> xss(n, xs);
return Concat(xss);
}
// Replicate(3, [1]) == [1, 1, 1]
template <typename ContainerOut>
ContainerOut Replicate(size_t n, const typename ContainerOut::value_type& x)
{
return ContainerOut(n, x);
}
// Infixes(3, [1,2,3,4,5,6]) == [[1,2,3], [2,3,4], [3,4,5], [4,5,6]]
template <typename ContainerOut, typename ContainerIn>
ContainerOut Infixes(std::size_t length, ContainerIn& xs)
{
static_assert(std::is_convertible<ContainerIn, typename ContainerOut::value_type>::value, "ContainerOut can not take values of type ContainerIn as elements.");
ContainerOut result;
if (Size(xs) < length)
return result;
PrepareContainer(result, Size(xs) - length);
auto itOut = BackInserter(result);
std::size_t idx = 0;
for (;idx < Size(xs) - length; ++idx)
{
*itOut = GetRange(idx, idx + length, xs);
}
return result;
}
} // namespace FunctionalPlus | 30.313131 | 163 | 0.66078 | [
"vector"
] |
8cf07ab44b1c5a4b575f193eac84c7e8a93d0389 | 2,746 | h | C | chrome/browser/history/download_database.h | leiferikb/bitpop-private | 4c967307d228e86f07f2576068a169e846c833ca | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2021-11-15T15:17:43.000Z | 2021-11-15T15:17:43.000Z | chrome/browser/history/download_database.h | houseoflifeproperty/bitpop-private | 4c967307d228e86f07f2576068a169e846c833ca | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/history/download_database.h | houseoflifeproperty/bitpop-private | 4c967307d228e86f07f2576068a169e846c833ca | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2020-11-04T07:24:02.000Z | 2020-11-04T07:24:02.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.
#ifndef CHROME_BROWSER_HISTORY_DOWNLOAD_DATABASE_H_
#define CHROME_BROWSER_HISTORY_DOWNLOAD_DATABASE_H_
#include <string>
#include <vector>
#include "base/threading/platform_thread.h"
#include "sql/meta_table.h"
class FilePath;
namespace sql {
class Connection;
}
namespace history {
struct DownloadRow;
// Maintains a table of downloads.
class DownloadDatabase {
public:
// The value of |db_handle| indicating that the associated DownloadItem is not
// yet persisted.
static const int64 kUninitializedHandle;
// Must call InitDownloadTable before using any other functions.
DownloadDatabase();
virtual ~DownloadDatabase();
int next_download_id() const { return next_id_; }
// Get all the downloads from the database.
void QueryDownloads(
std::vector<DownloadRow>* results);
// Update the state of one download. Returns true if successful.
// Does not update |url|, |start_time|; uses |db_handle| only
// to select the row in the database table to update.
bool UpdateDownload(const DownloadRow& data);
// Fixes state of the download entries. Sometimes entries with IN_PROGRESS
// state are not updated during browser shutdown (particularly when crashing).
// On the next start such entries are considered canceled. This functions
// fixes such entries.
bool CleanUpInProgressEntries();
// Create a new database entry for one download and return its primary db id.
int64 CreateDownload(const DownloadRow& info);
// Remove |handle| from the database.
void RemoveDownload(int64 handle);
int CountDownloads();
protected:
// Returns the database for the functions in this interface.
virtual sql::Connection& GetDB() = 0;
// Returns the meta-table object for the functions in this interface.
virtual sql::MetaTable& GetMetaTable() = 0;
// Returns true if able to successfully rewrite the invalid values for the
// |state| field from 3 to 4. Returns false if there was an error fixing the
// database. See http://crbug.com/140687
bool MigrateDownloadsState();
// Creates the downloads table if needed.
bool InitDownloadTable();
// Used to quickly clear the downloads. First you would drop it, then you
// would re-initialize it.
bool DropDownloadTable();
private:
bool EnsureColumnExists(const std::string& name, const std::string& type);
bool owning_thread_set_;
base::PlatformThreadId owning_thread_;
int next_id_;
int next_db_handle_;
DISALLOW_COPY_AND_ASSIGN(DownloadDatabase);
};
} // namespace history
#endif // CHROME_BROWSER_HISTORY_DOWNLOAD_DATABASE_H_
| 29.212766 | 80 | 0.752003 | [
"object",
"vector"
] |
8cf3d7a99a979219303b8ccc2535c8a3b260ff73 | 3,692 | h | C | SampleApp/include/SampleApp/DefaultEndpoint/DefaultEndpointRangeControllerHandler.h | AndersSpringborg/avs-device-sdk | 8e77a64c5be5a0b7b19c53549d91b0c45c37df3a | [
"Apache-2.0"
] | 1,272 | 2017-08-17T04:58:05.000Z | 2022-03-27T03:28:29.000Z | SampleApp/include/SampleApp/DefaultEndpoint/DefaultEndpointRangeControllerHandler.h | AndersSpringborg/avs-device-sdk | 8e77a64c5be5a0b7b19c53549d91b0c45c37df3a | [
"Apache-2.0"
] | 1,948 | 2017-08-17T03:39:24.000Z | 2022-03-30T15:52:41.000Z | SampleApp/include/SampleApp/DefaultEndpoint/DefaultEndpointRangeControllerHandler.h | AndersSpringborg/avs-device-sdk | 8e77a64c5be5a0b7b19c53549d91b0c45c37df3a | [
"Apache-2.0"
] | 630 | 2017-08-17T06:35:59.000Z | 2022-03-29T04:04:44.000Z | /*
* Copyright Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.
*/
#ifndef ALEXA_CLIENT_SDK_SAMPLEAPP_INCLUDE_SAMPLEAPP_DEFAULTENDPOINT_DEFAULTENDPOINTRANGECONTROLLERHANDLER_H_
#define ALEXA_CLIENT_SDK_SAMPLEAPP_INCLUDE_SAMPLEAPP_DEFAULTENDPOINT_DEFAULTENDPOINTRANGECONTROLLERHANDLER_H_
#include <list>
#include <AVSCommon/SDKInterfaces/RangeController/RangeControllerInterface.h>
#include <AVSCommon/Utils/Threading/Executor.h>
namespace alexaClientSDK {
namespace sampleApp {
/**
* An implementation of an @c RangeControllerInterface.
*/
class DefaultEndpointRangeControllerHandler
: public avsCommon::sdkInterfaces::rangeController::RangeControllerInterface {
public:
/**
* Create a DefaultEndpointRangeControllerHandler object.
*
* @param instance The instance name of the capability.
* @return A pointer to a new DefaultEndpointRangeControllerHandler object if it succeeds; otherwise, @c nullptr.
*/
static std::shared_ptr<DefaultEndpointRangeControllerHandler> create(const std::string& instance);
/// @name RangeControllerInterface methods
/// @{
avsCommon::sdkInterfaces::rangeController::RangeControllerInterface::RangeControllerConfiguration getConfiguration()
override;
std::pair<avsCommon::avs::AlexaResponseType, std::string> setRangeValue(
double value,
avsCommon::sdkInterfaces::AlexaStateChangeCauseType cause) override;
std::pair<avsCommon::avs::AlexaResponseType, std::string> adjustRangeValue(
double value,
avsCommon::sdkInterfaces::AlexaStateChangeCauseType cause) override;
std::pair<
avsCommon::avs::AlexaResponseType,
avsCommon::utils::Optional<avsCommon::sdkInterfaces::rangeController::RangeControllerInterface::RangeState>>
getRangeState() override;
bool addObserver(
std::shared_ptr<avsCommon::sdkInterfaces::rangeController::RangeControllerObserverInterface> observer) override;
void removeObserver(
const std::shared_ptr<avsCommon::sdkInterfaces::rangeController::RangeControllerObserverInterface>& observer)
override;
/// @}
private:
/**
* Constructor.
*
* @param instance The instance name of the capability.
*/
DefaultEndpointRangeControllerHandler(const std::string& instance);
/// The instance name of the capability.
std::string m_instance;
/// Current range value of the capability.
double m_currentRangeValue;
/// Represents the maximum range supported.
double m_maximumRangeValue;
/// Represents the minimum range supported.
double m_minmumRangeValue;
/// Represents the value to change when moving through the range.
double m_precision;
/// Mutex to serialize access to variables.
std::mutex m_mutex;
/// The list of @c RangeControllerObserverInterface observers that will get notified.
std::list<std::shared_ptr<avsCommon::sdkInterfaces::rangeController::RangeControllerObserverInterface>> m_observers;
};
} // namespace sampleApp
} // namespace alexaClientSDK
#endif // ALEXA_CLIENT_SDK_SAMPLEAPP_INCLUDE_SAMPLEAPP_DEFAULTENDPOINT_DEFAULTENDPOINTRANGECONTROLLERHANDLER_H_
| 38.458333 | 120 | 0.756501 | [
"object"
] |
8cfb972b00076943d444a5b389897f0157466a99 | 8,644 | h | C | QCA4020_SDK/target/thirdparty/qurt/2.0/qurt_internal.h | r8d8/lastlock | 78c02e5fbb129b1bc4147bd55eec2882267d7e87 | [
"Apache-2.0"
] | null | null | null | QCA4020_SDK/target/thirdparty/qurt/2.0/qurt_internal.h | r8d8/lastlock | 78c02e5fbb129b1bc4147bd55eec2882267d7e87 | [
"Apache-2.0"
] | null | null | null | QCA4020_SDK/target/thirdparty/qurt/2.0/qurt_internal.h | r8d8/lastlock | 78c02e5fbb129b1bc4147bd55eec2882267d7e87 | [
"Apache-2.0"
] | null | null | null | #ifndef QURT_INTERNAL_H
#define QURT_INTERNAL_H
/*=============================================================================
Copyright (c) 2015-2016, The Linux Foundation. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted (subject to the limitations in the
disclaimer below) 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 Linux Foundation nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE
GRANTED BY THIS LICENSE. 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.
qurt_internal.h
GENERAL DESCRIPTION
QuRT internal functions and typedefs
=============================================================================*/
#include "FreeRTOS.h"
#include "task.h"
#ifdef __cplusplus
extern "C" {
#endif
/*=============================================================================
CONSTANTS AND MACROS
=============================================================================*/
#undef ASSERT
#define ASSERT( x ) if( ( x ) == 0 ) { taskDISABLE_INTERRUPTS(); for( ;; ); }
/*======================================================================
Constants
======================================================================*/
#ifdef TRUE
#undef TRUE
#endif
#ifdef FALSE
#undef FALSE
#endif
#define TRUE 1 /* Boolean true value. */
#define FALSE 0 /* Boolean false value. */
#ifndef NULL
#define NULL ( (void *) 0)
#endif
/* Time */
#define QURT_TIME_NO_WAIT 0x00000000
#define QURT_TIME_WAIT_FOREVER 0xFFFFFFFF
/* OS object size */
#define QURT_INFO_OBJ_SIZE_BYTES 64
#define QURT_MUTEX_OBJ_SIZE_BYTES 64
#define QURT_SIGNAL_OBJ_SIZE_BYTES 64
#define QURT_THREAD_ATTR_OBJ_SIZE_BYTES 128
#define QURT_TIMER_OBJ_SIZE_BYTES 128
#define QURT_PIPE_ATTR_OBJ_SIZE_BYTES 16
/* Signal attributes */
#define QURT_SIGNAL_ATTR_WAIT_ANY 0x00000001
#define QURT_SIGNAL_ATTR_WAIT_ALL 0x00000002
#define QURT_SIGNAL_ATTR_CLEAR_MASK 0x00000004
/* Thread attributes */
#define QURT_THREAD_ATTR_PRIORITY_MAX 0
#define QURT_THREAD_ATTR_PRIORITY_DEFAULT 16
#define QURT_THREAD_ATTR_PRIORITY_MIN 31
#define QURT_THREAD_ATTR_NAME_MAXLEN 10
#define QURT_THREAD_DEFAULT_STACK_SIZE 128
/* Timer attributes */
#define QURT_TIMER_ONESHOT 0x01 /**< one short timer .*/
#define QURT_TIMER_PERIODIC 0x02 /**< periodic timer .*/
#define QURT_TIMER_NO_AUTO_START 0x04 /**< No Auto Activate.*/
#define QURT_TIMER_AUTO_START 0x08 /**< Default, Auto Activate */
/* Error codes */
#define QURT_EOK 0 /**< Operation successfully performed. */
#define QURT_EFATAL -1 /**< FATAL error which should never happen. */
#define QURT_EVAL -2 /**< Wrong values for parameters. The specified page does not exist. */
#define QURT_EMEM -3 /**< Not enough memory to perform operation.*/
#define QURT_EINVALID -4 /**< Invalid argument value, invalid key. */
#define QURT_EFAILED_TIMEOUT -5 /**< time out. */
#define QURT_EUNKNOWN -6 /**< Defined but never used in BLAST. */
#define QURT_EFAILED -7 /**< Operation failed. */
#define QURT_ENOMSGS -8 /**< Message queue empty. */
#define QURT_ENOTALLOWED -9 /**< Operation not allowed. */
/*======================================================================
Standard Types
======================================================================*/
/* The following definitions are the same across platforms*/
#ifndef _ARM_ASM_
#ifndef _BOOLEAN_DEFINED
typedef unsigned char boolean; /* Boolean value type. */
#define _BOOLEAN_DEFINED
#endif
#ifndef _UINT32_DEFINED
typedef unsigned long int uint32; /* Unsigned 32 bit value */
#define _UINT32_DEFINED
#endif
#ifndef _UINT16_DEFINED
typedef unsigned short uint16; /* Unsigned 16 bit value */
#define _UINT16_DEFINED
#endif
#ifndef _UINT8_DEFINED
typedef unsigned char uint8; /* Unsigned 8 bit value */
#define _UINT8_DEFINED
#endif
#ifndef _INT32_DEFINED
typedef signed long int int32; /* Signed 32 bit value */
#define _INT32_DEFINED
#endif
#ifndef _INT16_DEFINED
typedef signed short int16; /* Signed 16 bit value */
#define _INT16_DEFINED
#endif
#ifndef _INT8_DEFINED
typedef signed char int8; /* Signed 8 bit value */
#define _INT8_DEFINED
#endif
#ifndef _INT64_DEFINED
typedef long long int64;
#define _INT64_DEFINED
#endif
#ifndef _UINT64_DEFINED
typedef unsigned long long uint64;
#define _UINT64_DEFINED
#endif
#endif /* _ARM_ASM_ */
/*=============================================================================
TYPEDEFS
=============================================================================*/
/* qurt info */
typedef struct _qurt_info_t
{
void (*idlehook) (uint32);
void (*bsphook)(void);
uint8 *rtos_heap_start;
unsigned long rtos_heap_size;
uint32 idle_time;
}_qurt_info_t;
/* qurt_interrupt_handler_func_ptr_t type */
typedef void (*qurt_interrupt_handler_func_ptr_t) ( uint32 n_irq );
/** qurt_time_t types. */
typedef uint32 qurt_time_t;
/** qurt_time_unit_t types.*/
typedef enum {
QURT_TIME_TICK , /**< -- Return time in Ticks */
QURT_TIME_MSEC , /**< -- Return time in Milliseconds */
QURT_TIME_NONE=0xFFFFFFFF /**< -- Identifier to use if no particular return type is needed */
}qurt_time_unit_t;
/** QuRT init data_types **/
typedef struct qurt_data_s
{
/* Pointer to the heap used by RTOS */
void *hPtr;
/* Reserved pointer for future use */
void *rPtr;
} qurt_data_t;
/** QuRT info type */
typedef struct qurt_info /* 8 byte aligned */
{
unsigned long long _bSpace[QURT_INFO_OBJ_SIZE_BYTES/sizeof(unsigned long long)];
}qurt_info_t;
/** QuRT mutex type */
typedef unsigned int qurt_mutex_t;
/** QuRT signal type */
typedef unsigned int qurt_signal_t;
/** Thread ID type */
typedef unsigned long qurt_thread_t;
/** Thread attributes structure */
typedef struct qurt_thread_attr /* 8 byte aligned */
{
unsigned long long _bSpace[QURT_THREAD_ATTR_OBJ_SIZE_BYTES/sizeof(unsigned long long)];
}qurt_thread_attr_t;
/** qurt_timer_t types.*/
typedef unsigned long qurt_timer_t;
/** qurt_timer_cb_func_t types. */
typedef void (*qurt_timer_callback_func_t)( void *);
typedef struct qurt_timer_attr /* 8 byte aligned */
{
unsigned long long _bSpace[QURT_TIMER_OBJ_SIZE_BYTES/sizeof(unsigned long long)];
}qurt_timer_attr_t;
/** Represents pipes.*/
typedef void * qurt_pipe_t;
/** Represents pipe attributes. */
typedef struct qurt_pipe_attr /* 8 byte aligned */
{
unsigned long long _bSpace[QURT_PIPE_ATTR_OBJ_SIZE_BYTES/sizeof(unsigned long long)];
}qurt_pipe_attr_t;
/*=============================================================================
FUNCTIONS
=============================================================================*/
#ifdef __cplusplus
}
#endif
#endif /* QURT_INTERNAL_H */
| 33.634241 | 107 | 0.618117 | [
"object"
] |
8cfd4967b8129b3b75877db9a16588588d810b0c | 3,872 | c | C | game/g_abel_monster.c | AimHere/thirty-flights-of-linux | cd154b82e1e61535f01445ca46f38b36499a4ca4 | [
"Libpng",
"Zlib"
] | 3 | 2019-02-23T22:38:55.000Z | 2020-03-16T14:08:19.000Z | game/g_abel_monster.c | AimHere/thirty-flights-of-linux | cd154b82e1e61535f01445ca46f38b36499a4ca4 | [
"Libpng",
"Zlib"
] | null | null | null | game/g_abel_monster.c | AimHere/thirty-flights-of-linux | cd154b82e1e61535f01445ca46f38b36499a4ca4 | [
"Libpng",
"Zlib"
] | null | null | null |
#include "g_local.h"
void npc_think (edict_t *self)
{
if (self->style == 0) // gun
{
if (self->s.frame < 13)
self->s.frame++;
else
self->s.frame = 0;
}
else if (self->style == 1) // sit on chair
{
if (self->s.frame < 23)
self->s.frame++;
else
self->s.frame = 14;
}
else if (self->style == 2)
{
if (self->s.frame < 27)
self->s.frame++;
else
self->s.frame = 24;
}
else if (self->style == 3)
{
if (self->s.frame < 31)
self->s.frame++;
else
self->s.frame = 28;
}
self->nextthink=level.time+FRAMETIME;
}
void npc_use (edict_t *self, edict_t *other, edict_t *activator)
{
if (!activator->client || !self->target)
return;
//gi.dprintf("using npc\n");
G_UseTargets (self, activator);
//self->client->ps.stats[STAT_GRENADEABLE] = "abba\n";
//gi.dprintf("%s\n",self->client->ps.stats[STAT_GRENADEABLE]);
}
void npc_pain (edict_t *self, edict_t *other, float kick, int damage)
{
//self->monsterinfo.currentmove = &flipper_move_pain1;
gi.dprintf("ouch\n");
}
void SP_monster_npc (edict_t *self)
{
gi.setmodel (self, "models/monsters/charlie/tris.md2");
self->model = "models/monsters/charlie/tris.md2";
self->solid = SOLID_BBOX;
if ((self->style != 2) && (self->style != 3))
{
VectorSet(self->mins, -8, -8, 0);
VectorSet(self->maxs, 8, 8, 52);
}
else
{
VectorSet(self->mins, -16, -16, 0);
VectorSet(self->maxs, 16, 16, 37);
}
self->think=npc_think;
self->nextthink=level.time+FRAMETIME;
if (self->style == 2)
self->s.modelindex2 = gi.modelindex ("models/weapons/g_machn/tris.md2");
//self->modelindex2 = "models/weapons/g_machn/tris.md2";
self->takedamage = DAMAGE_YES;
self->pain = npc_pain;
gi.linkentity (self);
}
// ========== MONSTER_STARER
void starer_think(edict_t *self)
{
edict_t *player;
player = &g_edicts[1];
if (player)
{
//found player.
//face the player.
vec3_t playervec;
float ymin,ymax;
vec3_t forward, right;
VectorCopy (player->s.origin, playervec);
playervec[2] += self->attenuation; //they focus on your head.
VectorSubtract (playervec, self->pos1, playervec);
//only stare if within radius.
if (VectorLength(playervec) > self->radius)
{
VectorCopy(self->pos2,playervec);
}
else
{
vectoangles(playervec,playervec);
ymin = self->pos2[1] - 89;
ymax = self->pos2[1] + 89;
if (playervec[YAW] > ymax || playervec[YAW] < ymin)
{
//player out of fov. snap back to default position.
VectorCopy(self->pos2,playervec);
}
}
VectorCopy (playervec, self->s.angles);
AngleVectors (playervec, forward, right, NULL);
G_ProjectSource (self->pos1, self->offset, forward, right, self->s.origin);
if (self->spawnflags & 1)
{
self->s.origin[0] += crandom() * 0.1;
self->s.origin[1] += crandom() * 0.1;
self->s.origin[2] += crandom() * 0.4;
}
}
self->think = starer_think;
self->nextthink = level.time + FRAMETIME;
}
void SP_monster_starer(edict_t *self)
{
if (!self->usermodel)
self->s.modelindex = gi.modelindex ("models/monsters/npc/head.md2");
else
self->s.modelindex = gi.modelindex (self->usermodel);
if (!self->attenuation)
self->attenuation = 14;
if (self->spawnflags & 2)
self->svflags = SVF_NOCLIENT;
if (!self->radius)
self->radius = 160;
self->s.renderfx |= RF_NOSHADOW;
VectorCopy(self->s.origin, self->pos1);
self->solid = SOLID_NOT;
self->takedamage = DAMAGE_NO;
VectorCopy(self->s.angles, self->pos2);
self->think = starer_think;
self->nextthink = level.time + FRAMETIME;
//BC baboo
if (skill->value >= 2 && !self->usermodel)
{
//the head model.
self->s.skinnum = 7;
}
gi.linkentity (self);
} | 20.595745 | 78 | 0.60124 | [
"model",
"solid"
] |
ea0a1a4c328fdc0b55bc78529365a15166b163f0 | 1,380 | h | C | Src/GLRenderer/GLFrameBuffer.h | lai001/LearningComputerGraphics | 83760374cacdf3d178fa0818dbe5e30f445a75ab | [
"MIT"
] | null | null | null | Src/GLRenderer/GLFrameBuffer.h | lai001/LearningComputerGraphics | 83760374cacdf3d178fa0818dbe5e30f445a75ab | [
"MIT"
] | null | null | null | Src/GLRenderer/GLFrameBuffer.h | lai001/LearningComputerGraphics | 83760374cacdf3d178fa0818dbe5e30f445a75ab | [
"MIT"
] | null | null | null | #pragma once
#include <string>
#include <functional>
#include <array>
#include "ThirdParty/opengl.h"
#include "ThirdParty/glm.h"
#include "ThirdParty/noncopyable.hpp"
#include "GLShader.h"
#include "GLTexture.h"
#include "GLVertexObject.h"
enum EClearBufferFlags
{
None = 1 << 0,
Depth = 1 << 1,
Color = 1 << 2,
Stencil = 1 << 3
};
class FGLFrameBuffer: public boost::noncopyable
{
private:
unsigned int FramebufferID;
unsigned int RenderbuffersID;
int Width;
int Height;
FGLVertexObject* VertexObject;
FGLShader* Shader;
FGLTexture* ColorTexture;
std::array<float, 24> Vertices;
public:
FGLFrameBuffer(const int Width, const int Height, const glm::vec2 TopLeft, const glm::vec2 Size);
~FGLFrameBuffer();
int PostProcessing = 0;
glm::vec4 ClearColor;
unsigned char ClearBufferFlags;
void Unbind();
void Bind();
void AddColorAttachment();
const FGLTexture* GetColorTexture() const;
const FGLShader* GetShader() const;
void Render(std::function<void()> Closure);
void Draw();
static std::array<float, 24> GetVerticesFromRect(const glm::vec2 TopLeft, const glm::vec2 Size);
static void GLClearColor(const glm::vec4 Color);
static void ClearBuffer(const unsigned char ClearBufferFlags);
static void SetViewport(const int X, const int Y, const int Width, const int Height);
static void SetViewport(const glm::ivec4& Viewport);
};
| 18.648649 | 98 | 0.734058 | [
"render"
] |
86bda246d8b81d369930a762053d410c0fe2acfe | 3,593 | c | C | lib/wizards/nalle/wwb_daemon_cp.c | vlehtola/questmud | 8bc3099b5ad00a9e0261faeb6637c76b521b6dbe | [
"MIT"
] | null | null | null | lib/wizards/nalle/wwb_daemon_cp.c | vlehtola/questmud | 8bc3099b5ad00a9e0261faeb6637c76b521b6dbe | [
"MIT"
] | null | null | null | lib/wizards/nalle/wwb_daemon_cp.c | vlehtola/questmud | 8bc3099b5ad00a9e0261faeb6637c76b521b6dbe | [
"MIT"
] | null | null | null | // a secret channel - don't touch/see/hear this.
#include <ansi.h>
#define CHAN "wwb"
//#define DATA_FILE "/wizards/nalle/daemons/wwb_last"
#define DATA_FILE "/data/wwb_last"
#define TP this_player()
#define COLOURS "/cmds/std/_lite"
#define LAST_MAX 31
string *last_messages;
static string *chan_members;
string identify_member(string str);
int send_channel(string str);
string construct_chanstr(object ob, string str);
int show_last(int n);
int show_who();
/*************************************************/
reset(arg)
{
if(arg) return;
if(!last_messages) last_messages = ({ "" });
if(!restore_object(DATA_FILE)) save_object(DATA_FILE);
}
/*************************************************/
status input(string str) // entinen wwb_cmd
{
int i;
object *ob;
// Member list
chan_members=({"nalle","walla","houtmi","phileas"});
// ID check
if(!identify_member(TP->query_name())) return 0;
if(!this_player()->query_name()) { return 1; }
if(str=="last") { show_last(30); return 1; }
if(str=="who") { show_who(); return 1; }
if(!str) {
write("Syntax : wwb <message, 'last' or 'who'>\n");
return 1;
}
if(sizeof(last_messages)>=LAST_MAX)
{
last_messages=last_messages[1..(LAST_MAX-1)];
}
send_channel(str);
seteuid(getuid()); // Caution! SETEUID called
save_object(DATA_FILE);
return 1;
}
/*******/
int send_channel(string str)
{
object ob;
int i;
string *buffy;
// ID check (Redundant, for security)
if(!identify_member(TP->query_name())) return 0;
for(i=0;i<sizeof(chan_members);i++)
{
ob=find_player(chan_members[i]);
if(ob)
if(interactive(ob)) tell_object(ob,construct_chanstr(ob, str));
}
if(!last_messages)
last_messages=({ sprintf("["+ctime()[11..15]+"] "+construct_chanstr(ob, str)) });
else
last_messages+=({ sprintf("["+ctime()[11..15]+"] "+construct_chanstr(ob, str)) });
return 1;
}
/*******/
string construct_chanstr(object ob, string str) {
string temp, color_temp;
color_temp=COLOURS->give_color(ob, CHAN);
if(!strlen(color_temp)) color_temp=BOLD;
if(TP->query_wiz()) { temp="<"+CHAN+">"; }
else
{ temp="["+CHAN+"]"; }
if(TP->query_terminal()) temp=color_temp+temp+OFF;
temp+=": ";
return TP->query_name()+" "+temp+str+"\n";
}
/*******/
int identify_member(string str)
{
int i;
str=lower_case(str);
// Check
for(i=0;i<sizeof(chan_members);i++) if(chan_members[i]==str) return 1;
return 0;
}
/*******/
int show_last(int n)
{
int i;
if(!last_messages) { write("No messages here yet.\n"); return 1; }
for(i=0;i<sizeof(last_messages);i++)
{
write(last_messages[i]);
}
write("Displayed "+i+" message(s).\n");
return 1;
}
/*******/
int show_who() {
int i,idletime;
string result,idlestring;
// ID check (Redundant, for security)
if(!identify_member(TP->query_name())) return 0;
result="Statistics of ["+CHAN+"]: ";
for(i=0;i<sizeof(chan_members);i++)
if(find_player(chan_members[i]))
if(interactive(find_player(chan_members[i]))) {
idletime=query_idle(find_player(chan_members[i]));
idlestring="";
if(idletime>=3600) {
idlestring+=((idletime-(idletime%3600))/3600)+"h ";
idletime=idletime%3600;
}
if(idletime>=60) {
idlestring+=((idletime-(idletime%60))/60)+"m ";
idletime=idletime%60;
}
idlestring+=idletime+"s";
result+=capitalize(chan_members[i])+" ("+idlestring+"), ";
}
tell_object(TP,result[0..(strlen(result)-3)]+"\n");
return 1;
}
/*******/
| 19.741758 | 84 | 0.601169 | [
"object"
] |
86c462a40187ac21db982754b98a5d393dce9ef7 | 1,957 | h | C | 2006/inc/rxsrvice.h | kevinzhwl/ObjectARXCore | ce09e150aa7d87675ca15c9416497c0487e3d4d4 | [
"MIT"
] | 12 | 2015-10-05T07:11:57.000Z | 2021-11-20T10:22:38.000Z | 2012/inc/rxsrvice.h | HelloWangQi/ObjectARXCore | ce09e150aa7d87675ca15c9416497c0487e3d4d4 | [
"MIT"
] | null | null | null | 2012/inc/rxsrvice.h | HelloWangQi/ObjectARXCore | ce09e150aa7d87675ca15c9416497c0487e3d4d4 | [
"MIT"
] | 14 | 2015-12-04T08:42:08.000Z | 2022-01-08T02:09:23.000Z | //
// Copyright (C) 1992-1999 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
#ifndef _rxsrvice_h
#define _rxsrvice_h 1
#include "rxobject.h"
#pragma pack (push, 8)
extern "C" {
typedef AcRx::AppRetCode (*DepFuncPtr)(AcRx::AppMsgCode, void*);
}
class AcRxServicePrototype;
class AcRxService;
class AcRxService: public AcRxObject
{
public:
ACRX_DECLARE_MEMBERS(AcRxService);
AcRxService();
virtual ~AcRxService();
AcRxObject* getSysInfo() const;
void setSysInfo(AcRxObject* sysInfoObj);
void addDependency();
void removeDependency();
Adesk::Boolean unloadable() const;
// The following functions are not currently implemented
// They are present as place holders so that they can be
// implemented in the future without breaking binary
// compatibility
//
DepFuncPtr dependencyFunctionPtr();
void setDependencyFunctionPtr(DepFuncPtr);
private:
AcRxServicePrototype* mpImpService;
};
#pragma pack (pop)
#endif
| 30.107692 | 72 | 0.706694 | [
"object"
] |
86c5879666483618581dd19adffcd96cf148b790 | 7,533 | h | C | sstmac/hardware/vtk/vtk_stats.h | jpkenny/sst-macro | bcc1f43034281885104962586d8b104df84b58bd | [
"BSD-Source-Code"
] | 20 | 2017-01-26T09:28:23.000Z | 2022-01-17T11:31:55.000Z | sstmac/hardware/vtk/vtk_stats.h | jpkenny/sst-macro | bcc1f43034281885104962586d8b104df84b58bd | [
"BSD-Source-Code"
] | 542 | 2016-03-29T22:50:58.000Z | 2022-03-22T20:14:08.000Z | sstmac/hardware/vtk/vtk_stats.h | jpkenny/sst-macro | bcc1f43034281885104962586d8b104df84b58bd | [
"BSD-Source-Code"
] | 36 | 2016-03-10T21:33:54.000Z | 2021-12-01T07:44:12.000Z | /**
Copyright 2009-2021 National Technology and Engineering Solutions of Sandia,
LLC (NTESS). Under the terms of Contract DE-NA-0003525, the U.S. Government
retains certain rights in this software.
Sandia National Laboratories is a multimission laboratory managed and operated
by National Technology and Engineering Solutions of Sandia, LLC., a wholly
owned subsidiary of Honeywell International, Inc., for the U.S. Department of
Energy's National Nuclear Security Administration under contract DE-NA0003525.
Copyright (c) 2009-2021, NTESS
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 copyright holder 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.
Questions? Contact sst-macro-help@sandia.gov
*/
#ifndef sstmac_hw_vtk_stats_included_h
#define sstmac_hw_vtk_stats_included_h
#include <sstmac/common/stats/stat_collector.h>
#include <vector>
#include <queue>
#include <memory>
#include <tuple>
#include <sstmac/hardware/topology/topology.h>
#if SSTMAC_INTEGRATED_SST_CORE
#include <sst/core/statapi/statfieldinfo.h>
//#include <sst/core/sst_types.h>
using namespace SST;
#endif
namespace sstmac {
namespace hw {
class Topology;
struct traffic_event {
uint64_t time_; // progress time
int port_;
//this is mutable due to the nonsense that is
//C++ sets that does not allow modifying items in the set
//even after collision
mutable double color_;
int id_;
traffic_event(uint64_t t, int port, double c, int id) :
time_(t), port_(port), color_(c), id_(id)
{
}
};
#define VTK_NUM_CELLS_PER_SWITCH 7
struct vtk_link {
uint16_t id1;
uint16_t id2;
uint16_t port1;
uint16_t port2;
vtk_link(uint16_t i1, uint16_t p1, uint16_t i2, uint16_t p2) :
id1(i1), port1(p1), id2(i2), port2(p2)
{
//if (i1 > i2){ //link is identified with i1 < i2
// std::swap(id1,id2);
// std::swap(port1,port2);
//}
}
uint64_t id64() const {
uint32_t i1 = id1;
uint32_t p1 = port1;
uint32_t side1 = (i1 << 16) | p1;
uint32_t i2 = id2;
uint32_t p2 = port2;
uint32_t side2 = (i2 << 16) | p2;
uint64_t s1 = side1;
uint64_t s2 = side2;
uint64_t id = (s1 << 32) | s2;
return id;
}
static vtk_link construct(uint64_t id){
uint64_t upper32_mask = (~uint64_t(0)) << 32;
uint32_t upper16_mask = (~uint32_t(0)) << 16;
uint64_t lower32_mask = (~uint64_t(0)) >> 32;
uint32_t lower16_mask = (~(uint32_t(0))) >> 16;
uint32_t upper32 = (upper32_mask & id) >> 32;
uint32_t lower32 = lower32_mask & id;
uint16_t i1 = (upper16_mask & upper32) >> 16;
uint16_t p1 = lower16_mask & upper32;
uint16_t i2 = (upper16_mask & lower32) >> 16;
uint16_t p2 = lower16_mask & lower32;
return vtk_link(i1,p1,i2,p2);
}
};
struct vtk_port {
uint16_t id;
uint16_t port;
vtk_port(uint16_t i, uint16_t p) :
id(i), port(p) {}
static vtk_port construct(uint32_t id){
uint32_t upper16_mask = (~uint32_t(0)) << 16;
uint32_t lower16_mask = (~(uint32_t(0))) >> 16;
uint16_t i = (upper16_mask & id) >> 16;
uint16_t p = (lower16_mask & id);
return vtk_port(i,p);
}
uint32_t id32() const {
uint32_t i = id;
uint32_t p = port;
uint32_t myid = (i << 16) | p;
return myid;
}
};
class StatVTK : public StatCollector
{
FactoryRegister("vtk", stat_collector, stat_vtk)
public:
struct display_config {
double idle_switch_color;
double idle_link_color;
double highlight_switch_color;
double highlight_link_color;
double bidirectional_shift;
double min_face_color;
double max_face_color_sum;
double scale_face_color_sum;
double active_face_width;
std::string name;
std::set<int> special_fills;
};
StatVTK(SST::Params& params);
std::string toString() const override {
return "VTK stats";
}
static void outputExodus(const std::string& fileroot,
std::multimap<uint64_t, traffic_event>&& traffMap,
const display_config& cfg,
Topology *topo =nullptr);
void dumpLocalData() override;
void dumpGlobalData() override;
void globalReduce(ParallelRuntime *rt) override;
void clear() override;
void collect_new_intensity(TimeDelta time, int port, double intens);
void collect_new_color(TimeDelta time, int port, double color);
void reduce(StatCollector *coll) override;
void finalize(TimeDelta t) override;
StatCollector* doClone(SST::Params& params) const override {
return new StatVTK(params);
}
int id() const {
return id_;
}
void configure(SwitchId sid, hw::Topology* top);
private:
/**
* @brief The port_state struct
* The VTK collection has 3 different types of quantities
* Intensity = this is the raw input value (a double) saying what some
* quantity of interest is (contention delay, queue depth)
* Level = this is a discrete quantity that maps the intensity to an integer
* level based upon a given set of thresholds
* Color = this is the value (a double) that is written as a VTK state
* at a given timepoint. Depending on configuration,
* either intensity or level could be written as the color
*/
struct port_state {
int active_ports;
int congested_ports;
TimeDelta last_collection;
TimeDelta pending_collection_start;
int current_level;
double accumulated_color;
double current_color;
double active_vtk_color;
TimeDelta last_wait_finished;
port_state() :
accumulated_color(0.),
current_level(0)
{
}
};
struct compare_events {
bool operator()(const traffic_event& l, const traffic_event& r){
if (l.time_ != r.time_) return l.time_ < r.time_;
if (l.id_ != r.id_) return l.id_ < r.id_;
return l.port_ < r.port_;
}
};
std::vector<int> intensity_levels_;
std::vector<port_state> port_states_;
TimeDelta min_interval_;
int id_;
std::vector<std::pair<int,int>> filters_;
display_config display_cfg_;
std::set<traffic_event, compare_events> sorted_event_list_;
std::multimap<uint64_t, traffic_event> traffic_event_map_;
hw::Topology* top_;
bool active_;
bool flicker_;
};
}
}
#endif
| 28.319549 | 81 | 0.707819 | [
"vector"
] |
86c590ca99a363f3401b1f4652ca4adb01c6a90a | 808 | h | C | include/backend/base/base_prewhiten.h | ViewFaceCore/TenniS | c1d21a71c1cd025ddbbe29924c8b3296b3520fc0 | [
"BSD-2-Clause"
] | null | null | null | include/backend/base/base_prewhiten.h | ViewFaceCore/TenniS | c1d21a71c1cd025ddbbe29924c8b3296b3520fc0 | [
"BSD-2-Clause"
] | null | null | null | include/backend/base/base_prewhiten.h | ViewFaceCore/TenniS | c1d21a71c1cd025ddbbe29924c8b3296b3520fc0 | [
"BSD-2-Clause"
] | null | null | null | //
// Created by kier on 2019/2/20.
//
#ifndef TENSORSTACK_BACKEND_BASE_BASE_PREWHITEN_H
#define TENSORSTACK_BACKEND_BASE_BASE_PREWHITEN_H
#include "base_activation.h"
namespace ts {
namespace base {
class PreWhiten : public Activation {
public:
using self = PreWhiten;
using supper = Activation;
void active(const Tensor &x, Tensor &out) final;
/**
* calculation
* @param x satisfied shape.dims() > 1
* @param out have same shape with x
* @note all Tensor parameters' memory are already sync to given running memory device.
*/
virtual void prewhiten(const Tensor &x, Tensor &out) = 0;
};
}
}
#endif //TENSORSTACK_BACKEND_BASE_BASE_PREWHITEN_H
| 25.25 | 99 | 0.610149 | [
"shape"
] |
86c9dc34d176a06b6a1b05ccc80713e00d51caff | 3,815 | h | C | Geometry/MeshTopologyQueries.h | elix22/IogramSource | 3a4ce55d94920e060776b4aa4db710f57a4280bc | [
"MIT"
] | 28 | 2017-03-01T04:09:18.000Z | 2022-02-01T13:33:50.000Z | Geometry/MeshTopologyQueries.h | elix22/IogramSource | 3a4ce55d94920e060776b4aa4db710f57a4280bc | [
"MIT"
] | 3 | 2017-03-09T05:22:49.000Z | 2017-08-02T18:38:05.000Z | Geometry/MeshTopologyQueries.h | elix22/IogramSource | 3a4ce55d94920e060776b4aa4db710f57a4280bc | [
"MIT"
] | 17 | 2017-03-01T14:00:01.000Z | 2022-02-08T06:36:54.000Z | //
// Copyright (c) 2016 - 2017 Mesh Consultants Inc.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#pragma once
#include <Urho3D/Core/Variant.h>
#include <Urho3D/Container/Vector.h>
#include <Urho3D/AngelScript/APITemplates.h>
// TriMeshWithData is a variant map:
/*
["type"] = TriMeshWithData
["mesh"] = VariantMap
["vertex-vertex"] = VariantVector (with Vector<Vector<int>> structure)
["vertex-face"] = VariantVector (with Vector<Vector<int>> structure)
["face-face"] = VariantVector
*/
// Leaving out edges and labels for now
// ASSUMES MANIFOLD
// this computes all the various adjacency data and stores it as an enhanced triMesh
Urho3D::Variant TriMesh_ComputeAdjacencyData(const Urho3D::Variant& triMesh); // REGISTERED
// this checks for existance, but makes no guarantee that the data is uptodate.
bool TriMesh_HasAdjacencyData(const Urho3D::Variant& triMeshWithData); // REGISTERED
/// VERTEX QUERIES
Urho3D::VariantVector TriMesh_VertexToVertices(Urho3D::Variant& triMeshWithData, int vertID); // REGISTERED as TriMesh_VertexToVerticesArrayFromId
Urho3D::Vector<Urho3D::Variant> TriMesh_VertexToVertices(Urho3D::Variant& triMeshWithData); // REGISTERED as TriMesh_VertexToVerticesArray
Urho3D::VariantVector TriMesh_VertexToFaces(Urho3D::Variant& triMeshWithData, int vertID); // REGISTERED as TriMesh_VertexToFacesArray
//Urho3D::VariantVector TriMesh_VertexToLabels(const Urho3D::Variant& triMesh, int vertID);
/// FACE QUERIES
Urho3D::VariantVector TriMesh_FaceToVertices(const Urho3D::Variant& triMeshWithData, int faceID); // REGISTERED as TriMesh_FaceToVerticesArray
Urho3D::VariantVector TriMesh_FaceToFaces(const Urho3D::Variant& triMeshWithData, int faceID); // REGISTERED as TriMesh_FaceToFacesArray
//Urho3D::VariantVector TriMesh_FaceToLabels(const Urho3D::Variant& triMesh, int faceID);
// TODO
/// LABEL QUERIES
//Urho3D::VariantVector TriMesh_LabelToVertices(const Urho3D::Variant& triMesh, int faceID);
//Urho3D::VariantVector TriMesh_LabelToFaces(const Urho3D::Variant& triMesh, int faceID);
//Urho3D::VariantVector TriMesh_LabelToLabels(const Urho3D::Variant& triMesh, int faceID);
// for scripts
Urho3D::CScriptArray* TriMesh_VertexToVerticesArrayFromId(Urho3D::Variant& triMeshWithData, int vertID);
Urho3D::CScriptArray* TriMesh_VertexToVerticesArray(Urho3D::Variant& triMeshWithData);
Urho3D::CScriptArray* TriMesh_VertexToFacesArray(Urho3D::Variant& triMeshWithData, int vertID);
Urho3D::CScriptArray* TriMesh_FaceToVerticesArray(const Urho3D::Variant& triMeshWithData, int faceID);
Urho3D::CScriptArray* TriMesh_FaceToFacesArray(const Urho3D::Variant& triMeshWithData, int faceID);
bool RegisterMeshTopologyQueryFunctions(Urho3D::Context* context);
| 48.910256 | 147 | 0.777195 | [
"mesh",
"vector"
] |
86ca6fed0de28003472ad93ea2dfdb972c6ff85e | 291 | h | C | include/utility/fofn.h | isovic/raptor | 171e0f1b94366f20250a00389400a2fcd267bcc6 | [
"BSD-3-Clause-Clear"
] | 60 | 2019-07-09T14:57:48.000Z | 2022-03-29T06:53:39.000Z | include/utility/fofn.h | isovic/raptor | 171e0f1b94366f20250a00389400a2fcd267bcc6 | [
"BSD-3-Clause-Clear"
] | 2 | 2019-05-28T01:59:50.000Z | 2021-05-18T13:15:10.000Z | include/utility/fofn.h | isovic/raptor | 171e0f1b94366f20250a00389400a2fcd267bcc6 | [
"BSD-3-Clause-Clear"
] | 4 | 2019-05-25T15:41:56.000Z | 2019-07-10T11:44:22.000Z | /*
* fofn.h
*
* Created on: Mar 12, 2019
* Author: Ivan Sovic
*/
#ifndef SRC_UTILITY_FOFN_HPP_
#define SRC_UTILITY_FOFN_HPP_
#include <string>
#include <vector>
namespace raptor {
std::vector<std::string> ParseFOFN(const std::string& in_path);
} // namespace raptor
#endif
| 13.857143 | 63 | 0.690722 | [
"vector"
] |
86d30dd89aa047a80fa4bae03a8a4c40e24ab7c5 | 2,533 | h | C | API/API.h | ZSYTY/MiniSQL | 69115d8a5d7f2e0b70a4da331066dfd1a5c4a8f6 | [
"MIT"
] | 1 | 2020-06-30T23:53:51.000Z | 2020-06-30T23:53:51.000Z | API/API.h | MagicAtom/MiniSQL | 69115d8a5d7f2e0b70a4da331066dfd1a5c4a8f6 | [
"MIT"
] | null | null | null | API/API.h | MagicAtom/MiniSQL | 69115d8a5d7f2e0b70a4da331066dfd1a5c4a8f6 | [
"MIT"
] | 1 | 2020-06-30T23:53:28.000Z | 2020-06-30T23:53:28.000Z | /*
* @Author: Tianyu You
* @Date: 2020-05-24 16:27:42
* @Last Modified by: Tianyu You
* @Last Modified time: 2020-06-21 21:57:28
*/
#ifndef MINISQL_API_H
#define MINISQL_API_H
#include "../Common/Common.h"
#include "../RecordManager/RecordManager.h"
#include "../CatalogManager/CatalogManager.h"
#include "../IndexManager/IndexManager.h"
using namespace MiniSQL;
namespace API
{
class APISingleton
{
public:
~APISingleton();
APISingleton(const APISingleton &) = delete;
APISingleton &operator=(const APISingleton &) = delete;
CatalogManager *getCatalogManager()
{
return catalogManager;
}
IndexManager *getIndexManager()
{
return indexManager;
}
RecordManager *getRecordManager()
{
return recordManager;
}
// Usage: APISingleton &apiSingleton = API::APISingleton::getInstance();
static APISingleton &getInstance()
{
static APISingleton instance;
return instance;
}
private:
APISingleton()
{
bufferManager = new BufferManager();
catalogManager = new CatalogManager(bufferManager);
indexManager = new IndexManager(bufferManager, catalogManager);
recordManager = new RecordManager(bufferManager, indexManager, catalogManager);
}
BufferManager *bufferManager = nullptr;
RecordManager *recordManager = nullptr;
CatalogManager *catalogManager = nullptr;
IndexManager *indexManager = nullptr;
};
// Returning true means success, vice versa.
// std::pair<ValueName, ValueType>
bool createTable(const std::string &tableName,
const std::vector<std::pair<std::string, SqlValueType>> &schema,
const std::string &primaryKeyName = "");
bool dropTable(const std::string &tableName);
bool
createIndex(const std::string &tableName, const std::string &columnName,
const std::string &indexName);
bool dropIndex(const std::string &indexName);
// select * only
bool select(const std::string &tableName,
const std::vector<SqlCondition> &conditions);
bool insertTuple(const std::string &tableName,
const std::vector<SqlValue> &values);
bool deleteTuple(const std::string &tableName,
const std::vector<SqlCondition> &conditions);
} // namespace API
#endif | 26.946809 | 91 | 0.620608 | [
"vector"
] |
86e1311014cfff62706a1b1f59ca782380f6d3b2 | 4,076 | h | C | murphi2murphi/src/Printer.h | civic-fv/rumur-romp | 194ad7307d9452bd265e6da5f4f6a5439fe01c10 | [
"Unlicense"
] | 4 | 2020-10-21T21:12:27.000Z | 2021-10-05T23:22:10.000Z | murphi2murphi/src/Printer.h | civic-fv/rumur-romp | 194ad7307d9452bd265e6da5f4f6a5439fe01c10 | [
"Unlicense"
] | 216 | 2018-02-11T00:05:20.000Z | 2022-03-10T02:31:58.000Z | murphi2murphi/src/Printer.h | civic-fv/rumur-romp | 194ad7307d9452bd265e6da5f4f6a5439fe01c10 | [
"Unlicense"
] | 6 | 2020-05-05T08:29:48.000Z | 2022-03-08T20:15:52.000Z | #pragma once
#include "Stage.h"
#include <cstddef>
#include <iostream>
#include <rumur/rumur.h>
class Printer : public Stage {
private:
std::istream ∈
std::ostream &out;
// current position within the input file
unsigned long line = 1;
unsigned long column = 1;
public:
Printer(std::istream &in_, std::ostream &out_);
void visit_add(const rumur::Add &n) final;
void visit_aliasdecl(const rumur::AliasDecl &n) final;
void visit_aliasrule(const rumur::AliasRule &n) final;
void visit_aliasstmt(const rumur::AliasStmt &n) final;
void visit_and(const rumur::And &n) final;
void visit_array(const rumur::Array &n) final;
void visit_assignment(const rumur::Assignment &n) final;
void visit_band(const rumur::Band &n) final;
void visit_bnot(const rumur::Bnot &n) final;
void visit_bor(const rumur::Bor &n) final;
void visit_clear(const rumur::Clear &n) final;
void visit_constdecl(const rumur::ConstDecl &n) final;
void visit_div(const rumur::Div &n) final;
void visit_element(const rumur::Element &n) final;
void visit_enum(const rumur::Enum &n) final;
void visit_eq(const rumur::Eq &n) final;
void visit_errorstmt(const rumur::ErrorStmt &n) final;
void visit_exists(const rumur::Exists &n) final;
void visit_exprid(const rumur::ExprID &n) final;
void visit_field(const rumur::Field &n) final;
void visit_for(const rumur::For &n) final;
void visit_forall(const rumur::Forall &n) final;
void visit_function(const rumur::Function &n) final;
void visit_functioncall(const rumur::FunctionCall &n) final;
void visit_geq(const rumur::Geq &n) final;
void visit_gt(const rumur::Gt &n) final;
void visit_if(const rumur::If &n) final;
void visit_ifclause(const rumur::IfClause &n) final;
void visit_implication(const rumur::Implication &n) final;
void visit_isundefined(const rumur::IsUndefined &n) final;
void visit_leq(const rumur::Leq &n) final;
void visit_lsh(const rumur::Lsh &n) final;
void visit_lt(const rumur::Lt &n) final;
void visit_mod(const rumur::Mod &n) final;
void visit_model(const rumur::Model &n) final;
void visit_mul(const rumur::Mul &n) final;
void visit_negative(const rumur::Negative &n) final;
void visit_neq(const rumur::Neq &n) final;
void visit_not(const rumur::Not &n) final;
void visit_number(const rumur::Number &n) final;
void visit_or(const rumur::Or &n) final;
void visit_procedurecall(const rumur::ProcedureCall &n) final;
void visit_property(const rumur::Property &n) final;
void visit_propertyrule(const rumur::PropertyRule &n) final;
void visit_propertystmt(const rumur::PropertyStmt &n) final;
void visit_put(const rumur::Put &n) final;
void visit_quantifier(const rumur::Quantifier &n) final;
void visit_range(const rumur::Range &n) final;
void visit_record(const rumur::Record &n) final;
void visit_return(const rumur::Return &n) final;
void visit_rsh(const rumur::Rsh &n) final;
void visit_ruleset(const rumur::Ruleset &n) final;
void visit_scalarset(const rumur::Scalarset &n) final;
void visit_simplerule(const rumur::SimpleRule &n) final;
void visit_startstate(const rumur::StartState &n) final;
void visit_sub(const rumur::Sub &n) final;
void visit_switch(const rumur::Switch &n) final;
void visit_switchcase(const rumur::SwitchCase &n) final;
void visit_ternary(const rumur::Ternary &n) final;
void visit_typedecl(const rumur::TypeDecl &n) final;
void visit_typeexprid(const rumur::TypeExprID &n) final;
void visit_undefine(const rumur::Undefine &n) final;
void visit_vardecl(const rumur::VarDecl &n) final;
void visit_while(const rumur::While &n) final;
void visit_xor(const rumur::Xor &n) final;
void process(const Token &t) final;
void sync_to(const rumur::Node &n) final;
void sync_to(const rumur::position &pos) final;
void skip_to(const rumur::Node &n) final;
void skip_to(const rumur::position &pos) final;
void finalise() final;
virtual ~Printer() = default;
private:
void visit_bexpr(const rumur::BinaryExpr &n);
void visit_uexpr(const rumur::UnaryExpr &n);
};
| 39.572816 | 64 | 0.738224 | [
"model"
] |
86e7675e8c2f47e5a68456b8f22e612607434e98 | 15,755 | h | C | package/wav6/iwlwav-dev/drivers/net/wireless/intel/iwlwav/wireless/shared_mbss_mac/HwRegs/Wave500B/MacGenriscTxRegs.h | opensag/atom-openwrt | ff4f04f2f2c36a507d27406a040105cc763d2f89 | [
"Apache-2.0"
] | 3 | 2019-06-04T14:29:04.000Z | 2020-05-07T04:47:09.000Z | package/wav6/iwlwav-dev/drivers/net/wireless/intel/iwlwav/wireless/shared_mbss_mac/HwRegs/Wave500B/MacGenriscTxRegs.h | opensag/atom-openwrt | ff4f04f2f2c36a507d27406a040105cc763d2f89 | [
"Apache-2.0"
] | null | null | null | package/wav6/iwlwav-dev/drivers/net/wireless/intel/iwlwav/wireless/shared_mbss_mac/HwRegs/Wave500B/MacGenriscTxRegs.h | opensag/atom-openwrt | ff4f04f2f2c36a507d27406a040105cc763d2f89 | [
"Apache-2.0"
] | 2 | 2019-06-04T11:02:20.000Z | 2021-12-07T03:08:02.000Z |
/***********************************************************************************
File: MacGenriscTxRegs.h
Module: macGenriscTx
SOC Revision: 843
Purpose:
Description: This File was auto generated using SOC Online
************************************************************************************/
#ifndef _MAC_GENRISC_TX_REGS_H_
#define _MAC_GENRISC_TX_REGS_H_
/*---------------------------------------------------------------------------------
/ Registers Addresses
/----------------------------------------------------------------------------------*/
#include "HwMemoryMap.h"
#define MAC_GENRISC_TX_BASE_ADDRESS MEMORY_MAP_UNIT_26_BASE_ADDRESS
#define REG_MAC_GENRISC_TX_INTERNAL_REGISTER0 (MAC_GENRISC_TX_BASE_ADDRESS + 0x0)
#define REG_MAC_GENRISC_TX_INTERNAL_REGISTER1 (MAC_GENRISC_TX_BASE_ADDRESS + 0x4)
#define REG_MAC_GENRISC_TX_INTERNAL_REGISTER2 (MAC_GENRISC_TX_BASE_ADDRESS + 0x8)
#define REG_MAC_GENRISC_TX_INTERNAL_REGISTER3 (MAC_GENRISC_TX_BASE_ADDRESS + 0xC)
#define REG_MAC_GENRISC_TX_INTERNAL_REGISTER4 (MAC_GENRISC_TX_BASE_ADDRESS + 0x10)
#define REG_MAC_GENRISC_TX_INTERNAL_REGISTER5 (MAC_GENRISC_TX_BASE_ADDRESS + 0x14)
#define REG_MAC_GENRISC_TX_INTERNAL_REGISTER6 (MAC_GENRISC_TX_BASE_ADDRESS + 0x18)
#define REG_MAC_GENRISC_TX_INTERNAL_REGISTER7 (MAC_GENRISC_TX_BASE_ADDRESS + 0x1C)
#define REG_MAC_GENRISC_TX_INTERNAL_REGISTER8 (MAC_GENRISC_TX_BASE_ADDRESS + 0x20)
#define REG_MAC_GENRISC_TX_INTERNAL_REGISTER9 (MAC_GENRISC_TX_BASE_ADDRESS + 0x24)
#define REG_MAC_GENRISC_TX_INTERNAL_REGISTER10 (MAC_GENRISC_TX_BASE_ADDRESS + 0x28)
#define REG_MAC_GENRISC_TX_INTERNAL_REGISTER11 (MAC_GENRISC_TX_BASE_ADDRESS + 0x2C)
#define REG_MAC_GENRISC_TX_INTERNAL_REGISTER12 (MAC_GENRISC_TX_BASE_ADDRESS + 0x30)
#define REG_MAC_GENRISC_TX_INTERNAL_REGISTER13 (MAC_GENRISC_TX_BASE_ADDRESS + 0x34)
#define REG_MAC_GENRISC_TX_INTERNAL_REGISTER14 (MAC_GENRISC_TX_BASE_ADDRESS + 0x38)
#define REG_MAC_GENRISC_TX_INTERNAL_REGISTER15 (MAC_GENRISC_TX_BASE_ADDRESS + 0x3C)
#define REG_MAC_GENRISC_TX_STATUS_REGISTER (MAC_GENRISC_TX_BASE_ADDRESS + 0x40)
#define REG_MAC_GENRISC_TX_ERR_REG_0 (MAC_GENRISC_TX_BASE_ADDRESS + 0x44)
#define REG_MAC_GENRISC_TX_ERR_REG_1 (MAC_GENRISC_TX_BASE_ADDRESS + 0x48)
#define REG_MAC_GENRISC_TX_LAST_PC_EXECUTED (MAC_GENRISC_TX_BASE_ADDRESS + 0x4C)
#define REG_MAC_GENRISC_TX_ADD_OUT_ABORT (MAC_GENRISC_TX_BASE_ADDRESS + 0x54)
#define REG_MAC_GENRISC_TX_STOP_OP (MAC_GENRISC_TX_BASE_ADDRESS + 0x60)
#define REG_MAC_GENRISC_TX_CONTINUE_OP (MAC_GENRISC_TX_BASE_ADDRESS + 0x64)
#define REG_MAC_GENRISC_TX_SINGLE_STEP (MAC_GENRISC_TX_BASE_ADDRESS + 0x68)
#define REG_MAC_GENRISC_TX_EXT_COMMAND (MAC_GENRISC_TX_BASE_ADDRESS + 0x6C)
#define REG_MAC_GENRISC_TX_STEP_COMMAND (MAC_GENRISC_TX_BASE_ADDRESS + 0x70)
#define REG_MAC_GENRISC_TX_BRKP_ADDRESS (MAC_GENRISC_TX_BASE_ADDRESS + 0x74)
#define REG_MAC_GENRISC_TX_BRKP_ADDRESS_EN (MAC_GENRISC_TX_BASE_ADDRESS + 0x7C)
#define REG_MAC_GENRISC_TX_TEST_BUS_DATA (MAC_GENRISC_TX_BASE_ADDRESS + 0x80)
#define REG_MAC_GENRISC_TX_TEST_BUS_ENABLE (MAC_GENRISC_TX_BASE_ADDRESS + 0x84)
#define REG_MAC_GENRISC_TX_INTTEUPTS_SAMPLE (MAC_GENRISC_TX_BASE_ADDRESS + 0x88)
#define REG_MAC_GENRISC_TX_STM_GCLK_BYPASS (MAC_GENRISC_TX_BASE_ADDRESS + 0x8C)
#define REG_MAC_GENRISC_TX_START_OP (MAC_GENRISC_TX_BASE_ADDRESS + 0x90)
#define REG_MAC_GENRISC_TX_ABORT_CNT_LIMIT (MAC_GENRISC_TX_BASE_ADDRESS + 0x94)
#define REG_MAC_GENRISC_TX_CPU2GENRISC_DEBUG_MODE_EN (MAC_GENRISC_TX_BASE_ADDRESS + 0x98)
#define REG_MAC_GENRISC_TX_GENRISC_UPPER_IRQ_ENABLE (MAC_GENRISC_TX_BASE_ADDRESS + 0x9C)
#define REG_MAC_GENRISC_TX_GENRISC_LOWER_IRQ_ENABLE (MAC_GENRISC_TX_BASE_ADDRESS + 0xA0)
#define REG_MAC_GENRISC_TX_GENRISC_UPPER_IRQ_SET (MAC_GENRISC_TX_BASE_ADDRESS + 0xA4)
#define REG_MAC_GENRISC_TX_GENRISC_UPPER_IRQ_CLR (MAC_GENRISC_TX_BASE_ADDRESS + 0xA8)
#define REG_MAC_GENRISC_TX_GENRISC_UPPER_IRQ_STATUS (MAC_GENRISC_TX_BASE_ADDRESS + 0xAC)
#define REG_MAC_GENRISC_TX_GENRISC_LOWER_IRQ_SET (MAC_GENRISC_TX_BASE_ADDRESS + 0xB0)
#define REG_MAC_GENRISC_TX_GENRISC_LOWER_IRQ_CLR (MAC_GENRISC_TX_BASE_ADDRESS + 0xB4)
#define REG_MAC_GENRISC_TX_GENRISC_LOWER_IRQ_STATUS (MAC_GENRISC_TX_BASE_ADDRESS + 0xB8)
#define REG_MAC_GENRISC_TX_MIPS2GENRISC_IRQ_SET (MAC_GENRISC_TX_BASE_ADDRESS + 0xBC)
#define REG_MAC_GENRISC_TX_MIPS2GENRISC_IRQ_CLR (MAC_GENRISC_TX_BASE_ADDRESS + 0xC0)
#define REG_MAC_GENRISC_TX_MIPS2GENRISC_IRQ_STATUS (MAC_GENRISC_TX_BASE_ADDRESS + 0xC4)
#define REG_MAC_GENRISC_TX_INT_VECTOR (MAC_GENRISC_TX_BASE_ADDRESS + 0xC8)
/*---------------------------------------------------------------------------------
/ Data Type Definition
/----------------------------------------------------------------------------------*/
/*REG_MAC_GENRISC_TX_INTERNAL_REGISTER0 0x0 */
typedef union
{
uint32 val;
struct
{
uint32 internalRegister0:32; // Internal Register 0
} bitFields;
} RegMacGenriscTxInternalRegister0_u;
/*REG_MAC_GENRISC_TX_INTERNAL_REGISTER1 0x4 */
typedef union
{
uint32 val;
struct
{
uint32 internalRegister1:32; // Internal Register 1
} bitFields;
} RegMacGenriscTxInternalRegister1_u;
/*REG_MAC_GENRISC_TX_INTERNAL_REGISTER2 0x8 */
typedef union
{
uint32 val;
struct
{
uint32 internalRegister2:32; // Internal Register 2
} bitFields;
} RegMacGenriscTxInternalRegister2_u;
/*REG_MAC_GENRISC_TX_INTERNAL_REGISTER3 0xC */
typedef union
{
uint32 val;
struct
{
uint32 internalRegister3:32; // Internal Register 3
} bitFields;
} RegMacGenriscTxInternalRegister3_u;
/*REG_MAC_GENRISC_TX_INTERNAL_REGISTER4 0x10 */
typedef union
{
uint32 val;
struct
{
uint32 internalRegister4:32; // Internal Register 4
} bitFields;
} RegMacGenriscTxInternalRegister4_u;
/*REG_MAC_GENRISC_TX_INTERNAL_REGISTER5 0x14 */
typedef union
{
uint32 val;
struct
{
uint32 internalRegister5:32; // Internal Register 5
} bitFields;
} RegMacGenriscTxInternalRegister5_u;
/*REG_MAC_GENRISC_TX_INTERNAL_REGISTER6 0x18 */
typedef union
{
uint32 val;
struct
{
uint32 internalRegister6:32; // Internal Register 6
} bitFields;
} RegMacGenriscTxInternalRegister6_u;
/*REG_MAC_GENRISC_TX_INTERNAL_REGISTER7 0x1C */
typedef union
{
uint32 val;
struct
{
uint32 internalRegister7:32; // Internal Register 7
} bitFields;
} RegMacGenriscTxInternalRegister7_u;
/*REG_MAC_GENRISC_TX_INTERNAL_REGISTER8 0x20 */
typedef union
{
uint32 val;
struct
{
uint32 internalRegister8:32; // Internal Register 8
} bitFields;
} RegMacGenriscTxInternalRegister8_u;
/*REG_MAC_GENRISC_TX_INTERNAL_REGISTER9 0x24 */
typedef union
{
uint32 val;
struct
{
uint32 internalRegister9:32; // Internal Register 9
} bitFields;
} RegMacGenriscTxInternalRegister9_u;
/*REG_MAC_GENRISC_TX_INTERNAL_REGISTER10 0x28 */
typedef union
{
uint32 val;
struct
{
uint32 internalRegister10:32; // Internal Register 10
} bitFields;
} RegMacGenriscTxInternalRegister10_u;
/*REG_MAC_GENRISC_TX_INTERNAL_REGISTER11 0x2C */
typedef union
{
uint32 val;
struct
{
uint32 internalRegister11:32; // Internal Register 11
} bitFields;
} RegMacGenriscTxInternalRegister11_u;
/*REG_MAC_GENRISC_TX_INTERNAL_REGISTER12 0x30 */
typedef union
{
uint32 val;
struct
{
uint32 internalRegister12:32; // Internal Register 12
} bitFields;
} RegMacGenriscTxInternalRegister12_u;
/*REG_MAC_GENRISC_TX_INTERNAL_REGISTER13 0x34 */
typedef union
{
uint32 val;
struct
{
uint32 internalRegister13:32; // Internal Register 13
} bitFields;
} RegMacGenriscTxInternalRegister13_u;
/*REG_MAC_GENRISC_TX_INTERNAL_REGISTER14 0x38 */
typedef union
{
uint32 val;
struct
{
uint32 internalRegister14:32; // Internal Register 14
} bitFields;
} RegMacGenriscTxInternalRegister14_u;
/*REG_MAC_GENRISC_TX_INTERNAL_REGISTER15 0x3C */
typedef union
{
uint32 val;
struct
{
uint32 internalRegister15:32; // Internal Register 15
} bitFields;
} RegMacGenriscTxInternalRegister15_u;
/*REG_MAC_GENRISC_TX_STATUS_REGISTER 0x40 */
typedef union
{
uint32 val;
struct
{
uint32 statusEqual:1; // status equal bit
uint32 statusBig:1; // status big bit
uint32 statusLittle:1; // status little bit
uint32 statusNeg:1; // status neg bit
uint32 statusCarry:1; // status carry bit
uint32 divValid:1; // Divider result valid
uint32 currInterrupt:4; // Current interrupt
uint32 intEn:1; // interrupt enable
uint32 intActive:1; // interrupt active
uint32 enabled:1; // enabled
uint32 timerExpired:1; // timer expired
uint32 haltWaitInt:1; // halt wait intterrupt
uint32 reserved0:1;
uint32 breakStall:1; // break stall
uint32 stackError:1; // stack error
uint32 notLegalOpcErr:1; // not legal opcode error
uint32 abortError:1; // abort error
uint32 reserved1:12;
} bitFields;
} RegMacGenriscTxStatusRegister_u;
/*REG_MAC_GENRISC_TX_ERR_REG_0 0x44 */
typedef union
{
uint32 val;
struct
{
uint32 errReg0:16; // Error reg 0
uint32 reserved0:16;
} bitFields;
} RegMacGenriscTxErrReg0_u;
/*REG_MAC_GENRISC_TX_ERR_REG_1 0x48 */
typedef union
{
uint32 val;
struct
{
uint32 errReg1:16; // Error reg 1
uint32 reserved0:16;
} bitFields;
} RegMacGenriscTxErrReg1_u;
/*REG_MAC_GENRISC_TX_LAST_PC_EXECUTED 0x4C */
typedef union
{
uint32 val;
struct
{
uint32 lastExecuted:16; // Last pc executed
uint32 reserved0:16;
} bitFields;
} RegMacGenriscTxLastPcExecuted_u;
/*REG_MAC_GENRISC_TX_ADD_OUT_ABORT 0x54 */
typedef union
{
uint32 val;
struct
{
uint32 addOutAbort:28; // Address out abort
uint32 reserved0:4;
} bitFields;
} RegMacGenriscTxAddOutAbort_u;
/*REG_MAC_GENRISC_TX_STOP_OP 0x60 */
typedef union
{
uint32 val;
struct
{
uint32 stopOp:1; // stop opcode
uint32 reserved0:31;
} bitFields;
} RegMacGenriscTxStopOp_u;
/*REG_MAC_GENRISC_TX_CONTINUE_OP 0x64 */
typedef union
{
uint32 val;
struct
{
uint32 continueOp:1; // continue opcode
uint32 reserved0:31;
} bitFields;
} RegMacGenriscTxContinueOp_u;
/*REG_MAC_GENRISC_TX_SINGLE_STEP 0x68 */
typedef union
{
uint32 val;
struct
{
uint32 singleStep:1; // single step
uint32 reserved0:31;
} bitFields;
} RegMacGenriscTxSingleStep_u;
/*REG_MAC_GENRISC_TX_EXT_COMMAND 0x6C */
typedef union
{
uint32 val;
struct
{
uint32 extCommand:1; // ext command
uint32 reserved0:31;
} bitFields;
} RegMacGenriscTxExtCommand_u;
/*REG_MAC_GENRISC_TX_STEP_COMMAND 0x70 */
typedef union
{
uint32 val;
struct
{
uint32 stepCommand:32; // step command
} bitFields;
} RegMacGenriscTxStepCommand_u;
/*REG_MAC_GENRISC_TX_BRKP_ADDRESS 0x74 */
typedef union
{
uint32 val;
struct
{
uint32 brkpAddress1:16; // brkp address1
uint32 brkpAddress2:16; // brkp address2
} bitFields;
} RegMacGenriscTxBrkpAddress_u;
/*REG_MAC_GENRISC_TX_BRKP_ADDRESS_EN 0x7C */
typedef union
{
uint32 val;
struct
{
uint32 brkpAddress1En:1; // brkp address1 enable
uint32 brkpAddress2En:1; // brkp address2 enable
uint32 reserved0:30;
} bitFields;
} RegMacGenriscTxBrkpAddressEn_u;
/*REG_MAC_GENRISC_TX_TEST_BUS_DATA 0x80 */
typedef union
{
uint32 val;
struct
{
uint32 testBusData:24; // test bus data
uint32 reserved0:8;
} bitFields;
} RegMacGenriscTxTestBusData_u;
/*REG_MAC_GENRISC_TX_TEST_BUS_ENABLE 0x84 */
typedef union
{
uint32 val;
struct
{
uint32 testBusEnable:1; // test bus enable
uint32 reserved0:31;
} bitFields;
} RegMacGenriscTxTestBusEnable_u;
/*REG_MAC_GENRISC_TX_INTTEUPTS_SAMPLE 0x88 */
typedef union
{
uint32 val;
struct
{
uint32 intteuptsSample:15; // intteupts sample
uint32 reserved0:17;
} bitFields;
} RegMacGenriscTxIntteuptsSample_u;
/*REG_MAC_GENRISC_TX_STM_GCLK_BYPASS 0x8C */
typedef union
{
uint32 val;
struct
{
uint32 stmGclkBypass:1; // stm gclk bypass
uint32 reserved0:31;
} bitFields;
} RegMacGenriscTxStmGclkBypass_u;
/*REG_MAC_GENRISC_TX_START_OP 0x90 */
typedef union
{
uint32 val;
struct
{
uint32 startOp:1; // start opcode
uint32 reserved0:31;
} bitFields;
} RegMacGenriscTxStartOp_u;
/*REG_MAC_GENRISC_TX_ABORT_CNT_LIMIT 0x94 */
typedef union
{
uint32 val;
struct
{
uint32 abortCntLimit:16; // abort counter limit
uint32 reserved0:16;
} bitFields;
} RegMacGenriscTxAbortCntLimit_u;
/*REG_MAC_GENRISC_TX_CPU2GENRISC_DEBUG_MODE_EN 0x98 */
typedef union
{
uint32 val;
struct
{
uint32 lowerCpu2GenriscDebugModeEn:1; // lower cpu2genrisc debug mode enable
uint32 upperCpu2GenriscDebugModeEn:1; // Upper cpu2genrisc debug mode enable
uint32 reserved0:30;
} bitFields;
} RegMacGenriscTxCpu2GenriscDebugModeEn_u;
/*REG_MAC_GENRISC_TX_GENRISC_UPPER_IRQ_ENABLE 0x9C */
typedef union
{
uint32 val;
struct
{
uint32 genriscUpperIrqEnable:16; // GenRisc to Upper IRQ enable
uint32 reserved0:16;
} bitFields;
} RegMacGenriscTxGenriscUpperIrqEnable_u;
/*REG_MAC_GENRISC_TX_GENRISC_LOWER_IRQ_ENABLE 0xA0 */
typedef union
{
uint32 val;
struct
{
uint32 genriscLowerIrqEnable:16; // GenRisc to lower IRQ enable
uint32 reserved0:16;
} bitFields;
} RegMacGenriscTxGenriscLowerIrqEnable_u;
/*REG_MAC_GENRISC_TX_GENRISC_UPPER_IRQ_SET 0xA4 */
typedef union
{
uint32 val;
struct
{
uint32 genriscUpperIrqSet:16; // GenRisc to Upper IRQ set
uint32 reserved0:16;
} bitFields;
} RegMacGenriscTxGenriscUpperIrqSet_u;
/*REG_MAC_GENRISC_TX_GENRISC_UPPER_IRQ_CLR 0xA8 */
typedef union
{
uint32 val;
struct
{
uint32 genriscUpperIrqClr:16; // GenRisc to Upper IRQ clear
uint32 reserved0:16;
} bitFields;
} RegMacGenriscTxGenriscUpperIrqClr_u;
/*REG_MAC_GENRISC_TX_GENRISC_UPPER_IRQ_STATUS 0xAC */
typedef union
{
uint32 val;
struct
{
uint32 genriscUpperIrqStatus:16; // GenRisc to Upper IRQ status
uint32 reserved0:16;
} bitFields;
} RegMacGenriscTxGenriscUpperIrqStatus_u;
/*REG_MAC_GENRISC_TX_GENRISC_LOWER_IRQ_SET 0xB0 */
typedef union
{
uint32 val;
struct
{
uint32 genriscLowerIrqSet:16; // GenRisc to Lower IRQ set
uint32 reserved0:16;
} bitFields;
} RegMacGenriscTxGenriscLowerIrqSet_u;
/*REG_MAC_GENRISC_TX_GENRISC_LOWER_IRQ_CLR 0xB4 */
typedef union
{
uint32 val;
struct
{
uint32 genriscLowerIrqClr:16; // GenRisc to Lower IRQ clear
uint32 reserved0:16;
} bitFields;
} RegMacGenriscTxGenriscLowerIrqClr_u;
/*REG_MAC_GENRISC_TX_GENRISC_LOWER_IRQ_STATUS 0xB8 */
typedef union
{
uint32 val;
struct
{
uint32 genriscLowerIrqStatus:16; // GenRisc to Lower IRQ status
uint32 reserved0:16;
} bitFields;
} RegMacGenriscTxGenriscLowerIrqStatus_u;
/*REG_MAC_GENRISC_TX_MIPS2GENRISC_IRQ_SET 0xBC */
typedef union
{
uint32 val;
struct
{
uint32 mips2GenriscIrqSet:2; // MIPS to GenRisc IRQ set
uint32 reserved0:30;
} bitFields;
} RegMacGenriscTxMips2GenriscIrqSet_u;
/*REG_MAC_GENRISC_TX_MIPS2GENRISC_IRQ_CLR 0xC0 */
typedef union
{
uint32 val;
struct
{
uint32 mips2GenriscIrqClr:2; // MIPS to GenRisc IRQ clear
uint32 reserved0:30;
} bitFields;
} RegMacGenriscTxMips2GenriscIrqClr_u;
/*REG_MAC_GENRISC_TX_MIPS2GENRISC_IRQ_STATUS 0xC4 */
typedef union
{
uint32 val;
struct
{
uint32 mips2GenriscIrqStatus:2; // MIPS to GenRisc IRQ status
uint32 reserved0:30;
} bitFields;
} RegMacGenriscTxMips2GenriscIrqStatus_u;
/*REG_MAC_GENRISC_TX_INT_VECTOR 0xC8 */
typedef union
{
uint32 val;
struct
{
uint32 intVector:11; // GenRisc IRQ vector
uint32 reserved0:21;
} bitFields;
} RegMacGenriscTxIntVector_u;
#endif // _MAC_GENRISC_TX_REGS_H_
| 26.70339 | 95 | 0.748397 | [
"vector"
] |
86ef64f94440ba657ffbe0034e4cfe178060270f | 2,279 | h | C | vtkm/worklet/DispatcherMapField.h | rushah05/VTKm_FP16 | 487819a1dbdd8dc3f95cca2942e3f2706a2514b5 | [
"BSD-3-Clause"
] | 2 | 2021-07-07T22:53:19.000Z | 2021-07-31T19:29:35.000Z | vtkm/worklet/DispatcherMapField.h | rushah05/VTKm_FP16 | 487819a1dbdd8dc3f95cca2942e3f2706a2514b5 | [
"BSD-3-Clause"
] | 2 | 2020-11-18T16:50:34.000Z | 2022-01-21T13:31:47.000Z | vtkm/worklet/DispatcherMapField.h | rushah05/VTKm_FP16 | 487819a1dbdd8dc3f95cca2942e3f2706a2514b5 | [
"BSD-3-Clause"
] | 5 | 2020-10-02T10:14:35.000Z | 2022-03-10T07:50:22.000Z | //============================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
//
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//============================================================================
#ifndef vtk_m_worklet_Dispatcher_MapField_h
#define vtk_m_worklet_Dispatcher_MapField_h
#include <vtkm/worklet/internal/DispatcherBase.h>
namespace vtkm
{
namespace worklet
{
class WorkletMapField;
/// \brief Dispatcher for worklets that inherit from \c WorkletMapField.
///
template <typename WorkletType>
class DispatcherMapField
: public vtkm::worklet::internal::
DispatcherBase<DispatcherMapField<WorkletType>, WorkletType, vtkm::worklet::WorkletMapField>
{
using Superclass = vtkm::worklet::internal::
DispatcherBase<DispatcherMapField<WorkletType>, WorkletType, vtkm::worklet::WorkletMapField>;
using ScatterType = typename Superclass::ScatterType;
public:
template <typename... T>
VTKM_CONT DispatcherMapField(T&&... args)
: Superclass(std::forward<T>(args)...)
{
}
template <typename Invocation>
VTKM_CONT void DoInvoke(Invocation& invocation) const
{
using namespace vtkm::worklet::internal;
// This is the type for the input domain
using InputDomainType = typename Invocation::InputDomainType;
// We can pull the input domain parameter (the data specifying the input
// domain) from the invocation object.
const InputDomainType& inputDomain = invocation.GetInputDomain();
// For a DispatcherMapField, the inputDomain must be an ArrayHandle (or
// an VariantArrayHandle that gets cast to one). The size of the domain
// (number of threads/worklet instances) is equal to the size of the
// array.
auto numInstances = SchedulingRange(inputDomain);
// A MapField is a pretty straightforward dispatch. Once we know the number
// of invocations, the superclass can take care of the rest.
this->BasicInvoke(invocation, numInstances);
}
};
}
} // namespace vtkm::worklet
#endif //vtk_m_worklet_Dispatcher_MapField_h
| 34.014925 | 98 | 0.697236 | [
"object"
] |
86f3485cb6d83e3ba5536a6574fbec42078ae518 | 3,958 | h | C | include/mujinvision/imagesubscribermanager.h | ompugao/mujinvision | ab6b2cb23573158227082a3d02620647d0d6b06f | [
"Apache-2.0"
] | 2 | 2021-01-29T07:47:36.000Z | 2022-02-17T02:29:19.000Z | include/mujinvision/imagesubscribermanager.h | ompugao/mujinvision | ab6b2cb23573158227082a3d02620647d0d6b06f | [
"Apache-2.0"
] | null | null | null | include/mujinvision/imagesubscribermanager.h | ompugao/mujinvision | ab6b2cb23573158227082a3d02620647d0d6b06f | [
"Apache-2.0"
] | null | null | null | // -*- coding: utf-8 -*-
// Copyright (C) 2012-2014 MUJIN Inc. <rosen.diankov@mujin.co.jp>
//
// 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 imagesubscribermanager.h
\brief Public headers of ImageSubscriberManager.
*/
#ifndef MUJIN_VISION_IMAGE_SUBSCRIBER_MANAGER_H
#define MUJIN_VISION_IMAGE_SUBSCRIBER_MANAGER_H
#include "imagesubscriber.h"
namespace mujinvision {
class MUJINVISION_API ImageSubscriberManager
{
public:
ImageSubscriberManager() {
}
virtual ~ImageSubscriberManager() {
}
/** \brief Initializes the image subscriber manager.
\param mNameCamera map to cameras the subscribers subscribe to
\param subscribers vector of subscribers to be managed
*/
virtual void Initialize(const std::map<std::string, CameraPtr >&mNameCamera, const std::vector<ImageSubscriberPtr>&subscribers) = 0;
virtual void DeInitialize() = 0;
/** \brief Gets the latest color image from camera and its timestamp.
\param cameraname name of the camera
\param timestamp timestamp of the color image
\return pointer to the color image
*/
virtual ColorImagePtr GetColorImage(const std::string& cameraname, unsigned long long& timestamp) = 0;
/** \brief Gets the latest n color images from camera and the min/max timestamps.
\param cameraname name of the camera
\param n number of desired images
\param colorimages vector to which the desired images will be pushed
\param starttime timestamp of the earliest image
\param endtime timestamp of the latest image
*/
//virtual void GetConsecutiveColorImages(const std::string& cameraname, const unsigned int n, std::vector<ColorImagePtr>& colorimages, unsigned long long& starttime, unsigned long long& endtime) = 0;
/** \brief Gets the depth image from the latest n images with depth data, and the min/max timestamps of the images used.
\param cameraname name of the camera
\param n number of desired images to use for creating the depth image
\param starttime timestamp of the earliest image
\param endtime timestamp of the latest image
\return pointer to the depth image
*/
virtual DepthImagePtr GetDepthImage(const std::string& cameraname, const unsigned int n, unsigned long long& starttime, unsigned long long& endtime) = 0;
/** \brief Writes color image to disk.
*/
virtual void WriteColorImage(ColorImageConstPtr colorimage, const std::string& filename) = 0;
/** \brief Writes depth image to disk.
*/
virtual void WriteDepthImage(DepthImageConstPtr depthimage, const std::string& filename) = 0;
/** \brief Creates image susbcriber.
\param ip ip address of the image subscriber
\param port port of the image subscriber
\params_pt boost property tree defining the image subscriber parameters
*/
virtual ImageSubscriberPtr CreateImageSubscriber(const std::string& ip, const unsigned int port, const ptree& params_pt) = 0;
protected:
std::vector<ImageSubscriberPtr> _vSubscribers;
std::map<std::string, CameraPtr> _mNameCamera; ///< name -> camera
};
typedef boost::shared_ptr<ImageSubscriberManager> ImageSubscriberManagerPtr;
typedef boost::shared_ptr<ImageSubscriberManager const> ImageSubscriberManagerConstPtr;
typedef boost::weak_ptr<ImageSubscriberManager> ImageSubscriberManagerWeakPtr;
} // namespace mujinvision
#endif
| 42.106383 | 203 | 0.733199 | [
"vector"
] |
8102bfc3f90612f0abc9e2f4de06fa5da9daddfc | 2,643 | h | C | inc/basedatamanager.h | sunjinbo/roadmap | f6e8feccc2b41b88e70c59cb5599d2dd121ae0c0 | [
"MIT"
] | null | null | null | inc/basedatamanager.h | sunjinbo/roadmap | f6e8feccc2b41b88e70c59cb5599d2dd121ae0c0 | [
"MIT"
] | null | null | null | inc/basedatamanager.h | sunjinbo/roadmap | f6e8feccc2b41b88e70c59cb5599d2dd121ae0c0 | [
"MIT"
] | null | null | null | /*
* ============================================================================
* Name : basedatamanager.h
* Part of : RoadMap
* Interface :
* Description :
* Version :
*
* Copyright 2007 Nokia. All rights reserved.
* This material, including documentation and any related computer
* programs, is protected by copyright controlled by Nokia. All
* rights are reserved. Copying, including reproducing, storing,
* adapting or translating, any or all of this material requires the
* prior written consent of Nokia. This material also contains
* confidential information which may not be disclosed to others
* without the prior written consent of Nokia.
* ============================================================================
*
*/
#ifndef M_MBASEDATAMGR_H
#define M_MBASEDATAMGR_H
// INCLUDES
#include <e32cmn.h>
#include <e32base.h>
#include <badesca.h>
#include <s32std.h>
#include "basedata.h"
/**
*
* A interface only, all the data manager class which can be dirived from it
*
* @since S60 v3.1
*/
class MBaseDataManager
{
public: // New functions
/**
*
* Add a MBaseData objct to the manager
*
* @since S60 v3.1
* @param aData the MBaseData objct which will be added
* @return the processing result
*/
virtual TInt AddL( const MBaseData& aData ) = 0;
/**
*
* DeleteL a MBaseData objct from the manager
*
* @since S60 v3.1
* @param aIndex the INDEX in which will be deleted
* @return the processing result
*/
virtual TInt DeleteL( TInt aIndex ) = 0;
/**
*
* Edit a MBaseData objct from the manager
*
* @since S60 v3.1
* @param aData the MBaseData objct which will be edited
* @return the processing result
*/
virtual TInt EditL
( TInt aIndex, const MBaseData& aData ) = 0;
/**
*
* Find a MBaseData object from the manager
*
* @since S60 v3.1
* @param aData the MBaseData objct which will be found
* @return the processing result
*/
virtual TInt Find( const MBaseData& aMBaseData ) const = 0;
/**
*
* Is this data already exist?
*
* @since S60 v3.1
* @param aMBaseData the pointer of a TCountryData oject
* @return the position
*/
virtual TInt IsExist
( const MBaseData& aData, TInt aIndex ) const = 0;
/**
*
* How many MBaseData object in this manager?
*
* @since S60 v3.1
* @return the result
*/
virtual TInt Count() const = 0;
};
#endif // M_MBASEDATAMGR_H
// End of File
| 24.027273 | 78 | 0.58305 | [
"object"
] |
81133f6018c75846c6b53309882c8efeed7bfdf9 | 2,629 | h | C | ImgReconstruction/Core/utils.h | SanCHEESE/ImgBlurRemoval | 0d92eee97ed26a503ead9f4802025a2d73498fdd | [
"MIT"
] | 1 | 2016-01-06T16:03:52.000Z | 2016-01-06T16:03:52.000Z | ImgReconstruction/Core/utils.h | SanCHEESE/ImgReconstruction | 0d92eee97ed26a503ead9f4802025a2d73498fdd | [
"MIT"
] | null | null | null | ImgReconstruction/Core/utils.h | SanCHEESE/ImgReconstruction | 0d92eee97ed26a503ead9f4802025a2d73498fdd | [
"MIT"
] | null | null | null | //
// utils.h
// ImgReconstruction
//
// Created by Alexander Bochkarev on 26.10.15.
// Copyright © 2015 Alexander Bochkarev. All rights reserved.
//
#pragma once
#include "CImagePatch.h"
namespace utils
{
template<typename T>
int hamming(T p1, T p2)
{
int hammingDistance = 0;
for (int i = sizeof(T) * 8 - 1; i >= 0; i--) {
if (((p1 >> i) % 2) != ((p2 >> i) % 2)) {
hammingDistance++;
}
}
return hammingDistance;
}
double StandartDeviation(const CImage& img);
// classification
uint64 PHash(const CImage &image, const cv::Size& size = {4, 4});
uint64 AvgHash(const CImage &image, const cv::Size& size = {4, 4});
template<typename Key>
CImage CreateHistImg(const std::map<Key, std::vector<CImagePatch>>& data)
{
cv::Size patchSize = data.begin()->second[0].GetSize();
int maxHeight = 0;
// count height
for (auto& it: data) {
int rowHeight = it.second.size() * (patchSize.height + 1);
if (maxHeight < rowHeight) {
maxHeight = rowHeight;
}
}
CImage histogramImg(maxHeight + 3 + 50, data.size() * (patchSize.width + 3) + 3, CV_8UC1, cv::Scalar(255));
int x = 0;
for (auto& it: data) {
auto patches = it.second;
CImage columnImage(1, patchSize.width, CV_8UC1, cv::Scalar(255));
for (int i = 0; i < patches.size(); i++) {
CImage greyPatchImg = patches[i].GrayImage();
cv::Mat horisontalSeparator(1, greyPatchImg.GetFrame().width, CV_8UC1, cv::Scalar(255));
cv::vconcat(columnImage, greyPatchImg, columnImage);
cv::vconcat(columnImage, horisontalSeparator, columnImage);
}
CImage textImg = CImage::GetImageWithText(std::to_string(patches.size()), cv::Point(1, 10), RGB(0, 0, 0), RGB(255, 255, 255), cv::Size(50, 11));
textImg = textImg.GetRotatedImage(-90); // clockwise
cv::Mat roi = histogramImg.rowRange(histogramImg.rows - 50 - columnImage.rows, histogramImg.rows - 50).colRange(x, x + columnImage.cols);
columnImage.copyTo(roi);
cv::Mat roi2 = histogramImg.rowRange(histogramImg.rows - 50, histogramImg.rows).colRange(x, x + textImg.cols);
textImg.copyTo(roi2);
x += columnImage.cols + 3;
}
return histogramImg;
}
std::ostream& operator<<(std::ostream& os, const cv::Mat& mat);
void WriteParamsToFile(const std::string& filename);
} | 33.278481 | 156 | 0.568277 | [
"vector"
] |
8114688131bd6f31646a802f2c4db388ea0ef6ad | 1,130 | h | C | src/Injections/SpyGlass.Injection.x86/Hook.h | Washi1337/SpyGlass | 4b4a3c1c3d523f124c0bf6638c1f314963278ebf | [
"MIT"
] | 52 | 2019-07-08T01:24:30.000Z | 2022-03-23T03:39:12.000Z | src/Injections/SpyGlass.Injection.x86/Hook.h | Washi1337/SpyGlass | 4b4a3c1c3d523f124c0bf6638c1f314963278ebf | [
"MIT"
] | null | null | null | src/Injections/SpyGlass.Injection.x86/Hook.h | Washi1337/SpyGlass | 4b4a3c1c3d523f124c0bf6638c1f314963278ebf | [
"MIT"
] | 15 | 2019-07-12T01:03:11.000Z | 2021-10-17T21:42:38.000Z | #pragma once
#include <vector>
/**
* Specifies parameters for setting hooks.
*/
struct HookParameters
{
void* Address;
int BytesToOverwrite;
std::vector<int> OffsetsNeedingFixup;
};
#define REGISTER_COUNT 9
#define REGISTER_EAX 0
#define REGISTER_ECX 1
#define REGISTER_EDX 2
#define REGISTER_EBX 3
#define REGISTER_ESP 4
#define REGISTER_EBP 5
#define REGISTER_ESI 6
#define REGISTER_EDI 7
#define REGISTER_EIP 8
/**
* Defines the function signature of a hook callback.
* @param registers: A pointer to a collection of register values.
* @param stack: A pointer to the top of the stack.
*/
typedef void (_stdcall *HookCallBack)(SIZE_T* registers, SIZE_T* stack);
/*
* Represents a single hook instance that is set at a specific memory location with one callback.
*/
class Hook
{
public:
Hook(HookParameters parameters, HookCallBack callback);
~Hook();
void Set();
void Unset();
private:
void ReadBytesToOverwrite();
void CreateTrampoline();
void CreateHookBytes();
HookParameters _parameters;
HookCallBack _callback;
bool _isSet;
char* _originalBytes;
char* _hookBytes;
void* _trampoline;
}; | 19.152542 | 97 | 0.752212 | [
"vector"
] |
81211796cf49026c94000345e9cae04049b45955 | 980 | h | C | Src/Math/CRandom.h | RudiBik/Breakanoid | 70c1eeb7f311ed3903dcf20ed8098fe7e1b44131 | [
"MIT"
] | null | null | null | Src/Math/CRandom.h | RudiBik/Breakanoid | 70c1eeb7f311ed3903dcf20ed8098fe7e1b44131 | [
"MIT"
] | null | null | null | Src/Math/CRandom.h | RudiBik/Breakanoid | 70c1eeb7f311ed3903dcf20ed8098fe7e1b44131 | [
"MIT"
] | null | null | null | #pragma once
/* Period parameters */
#define CMATH_N 624
#define CMATH_M 397
#define CMATH_MATRIX_A 0x9908b0df /* constant vector a */
#define CMATH_UPPER_MASK 0x80000000 /* most significant w-r bits */
#define CMATH_LOWER_MASK 0x7fffffff /* least significant r bits */
/* Tempering parameters */
#define CMATH_TEMPERING_MASK_B 0x9d2c5680
#define CMATH_TEMPERING_MASK_C 0xefc60000
#define CMATH_TEMPERING_SHIFT_U(y) (y >> 11)
#define CMATH_TEMPERING_SHIFT_S(y) (y << 7)
#define CMATH_TEMPERING_SHIFT_T(y) (y << 15)
#define CMATH_TEMPERING_SHIFT_L(y) (y >> 18)
class CRandom
{
private:
// DATA
unsigned int rseed;
unsigned int rseed_sp;
unsigned long mt[CMATH_N]; /* the array for the state vector */
int mti; /* mti==N+1 means mt[N] is not initialized */
// FUNCTIONS
public:
CRandom(void);
unsigned int Random( unsigned int n );
float Random( );
void SetRandomSeed(unsigned int n);
unsigned int GetRandomSeed(void);
void Randomize(void);
}; | 26.486486 | 67 | 0.728571 | [
"vector"
] |
bcbf26921ccad107f88e4a3db5dd2abfc576da96 | 800 | h | C | iPhoneOS11.2.sdk/System/Library/Frameworks/ARKit.framework/Headers/ARPointCloud.h | onezens/sdks | a194d40f2ef4c4a00d8d3d1b3a2d7a9a110449b7 | [
"MIT"
] | 304 | 2018-03-07T06:24:31.000Z | 2022-03-02T02:37:45.000Z | iPhoneOS11.2.sdk/System/Library/Frameworks/ARKit.framework/Headers/ARPointCloud.h | tobygrand/sdks | d43e7efaa664af3f92e6a4b306ee56a8e7a3eef6 | [
"MIT"
] | 6 | 2018-05-10T12:15:00.000Z | 2022-01-11T03:32:36.000Z | iPhoneOS11.2.sdk/System/Library/Frameworks/ARKit.framework/Headers/ARPointCloud.h | tobygrand/sdks | d43e7efaa664af3f92e6a4b306ee56a8e7a3eef6 | [
"MIT"
] | 62 | 2018-03-07T07:03:01.000Z | 2022-03-23T14:03:42.000Z | //
// ARPointCloud.h
// ARKit
//
// Copyright © 2016-2017 Apple Inc. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <simd/simd.h>
NS_ASSUME_NONNULL_BEGIN
API_AVAILABLE(ios(11.0)) API_UNAVAILABLE(macos, watchos, tvos)
@interface ARPointCloud : NSObject
/**
The number of points in the point cloud.
*/
@property (nonatomic, readonly) NSUInteger count NS_REFINED_FOR_SWIFT;
/**
The 3D points comprising the point cloud.
*/
@property (nonatomic, readonly) const vector_float3 *points NS_REFINED_FOR_SWIFT;
/**
The 3D point identifiers comprising the point cloud.
*/
@property (nonatomic, readonly) const uint64_t *identifiers NS_REFINED_FOR_SWIFT;
/** Unavailable */
- (instancetype)init NS_UNAVAILABLE;
+ (instancetype)new NS_UNAVAILABLE;
@end
NS_ASSUME_NONNULL_END
| 21.052632 | 81 | 0.7575 | [
"3d"
] |
bcd2827ce3974ca245d2c59014eb8368724c69c5 | 25,881 | c | C | main.c | rainli323/tqcorr | a150773ec8ad3e55bd81bf6893b6cc48d7d31709 | [
"Xnet",
"X11"
] | null | null | null | main.c | rainli323/tqcorr | a150773ec8ad3e55bd81bf6893b6cc48d7d31709 | [
"Xnet",
"X11"
] | null | null | null | main.c | rainli323/tqcorr | a150773ec8ad3e55bd81bf6893b6cc48d7d31709 | [
"Xnet",
"X11"
] | null | null | null | // this version uses mpi version of scratch files. it also expects imcr's to
// be seperated to different processors dynaimcally
/***********************************************************************
* *
* main program for MRCISD(TQ) based on CFGCI *
* March 9, 2008 by WJ *
* *
**********************************************************************/
#include "cfgci_tq.h"
int comm_sz, my_rank; //MPI related variables
FILE *outfile, *infofile, *scrfile;
int prntflag, mxdim, nmcrt, nstates, iter, mxiter=1, invflag=0;
long ncsft, ncsfq1, ncsfm;
double **upp, **hwpp, **wwpp, *energs, *civec;
double **upp2, **hwpp2, **wwpp2, *energs2;
int main(void)
{
extern int comm_sz, my_rank;
extern int prntflag, nstates, iter, mxiter;
extern long ncsft, ncsfq1, ncsfm;
extern double **upp, **hwpp, **wwpp, **hwpp2, **wwpp2, *energs, *energs2;
extern FILE *outfile, *infofile, *scrfile;
int ichk, i, j, k, ij, nroots, nnstates, nstates2;
int conv=0;
long ncsfs[3], totalmem;
double repnuc, cpu_time, runtime;
double diff, etol=1.e-12, temp, sum, sum2, mem;
double **upptemp, **upptemp2, **uvecs, **vpp;
double **wpp, **wpp2, **wppinv, **wppinv2, **wqp;
double **hwpp_sum, **wwpp_sum, **wwpp_sum2, **hwpp_sum2;
double *heff, *eigval, *old_energs, *old_energs2, *energs0;
char inname[LENNAME], outname[LENNAME], *cptr;
char *keyword_ptr, line[LENLINE], str[LENLINE];
char *asctime(const struct tm *tmptr);
struct tm *tmptr;
time_t lt;
size_t memtmp;
FILE *infile, *cifile;
void initci(long totalmem);
void mkhw(void);
void multiply(double **a, double **b, double **c, int n);
void multiplyplus(double **a, double **b, double **c, int n);
MPI_Init(NULL, NULL);
MPI_Comm_size(MPI_COMM_WORLD, &comm_sz);
MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
if (comm_sz == 1) {
(void)printf("\nError: This is the parallel version of tqcorr.exe, please use more than one processor or use the serial code\n" );
MPI_Abort(MPI_COMM_WORLD, 1);
}
cpu_time = (double)clock()/CLOCKS_PER_SEC;
if ((infofile = fopen(INFONAME, "r+b")) == NULL) {
(void)printf("\nError opening %s\n", INFONAME);
MPI_Abort(MPI_COMM_WORLD, 1);
}
getname(infofile, inname, LENNAME);
(void)strcpy(outname, inname);
cptr = strstr(outname, ".inp");
(void)strcpy(cptr, ".log");
if ((outfile = fopen(outname, "a")) == NULL) {
(void)printf("\nError opening %s\n", outname);
MPI_Abort(MPI_COMM_WORLD, 1);
}
if (my_rank == 0) {
/* data from infofile */
prntflag = getint(infofile, 36); /* set default printing level */
nstates = getint(infofile, 31);
repnuc = getreal(infofile, 1);
mem = getreal(infofile, 5);
getarray(infofile, 60, ncsfs, 3 * sizeof(long int)); /* for all space */
ncsft = ncsfs[0];
ncsfq1 = ncsfs[1];
ncsfm = ncsfs[2];
totalmem = (long) (1.e9 * mem);
if ((infile = fopen(inname, "r")) == NULL) {
(void)printf("\nError opening input file\n");
MPI_Abort(MPI_COMM_WORLD, 1);
}
(void)strcpy(line, KEY);
str[0] = '\0';
ichk = locate(line, infile);
if (ichk) {
do {
(void) fgets(line, sizeof(line), infile);
keyword_ptr = strstr(line, "NSTATES=");
if (keyword_ptr != NULL) {
keyword_ptr += 8;
i = sscanf(keyword_ptr,"%d", &nroots);
}
keyword_ptr = strstr(line, "MXITER=");
if (keyword_ptr != NULL) {
keyword_ptr += 7;
i = sscanf(keyword_ptr,"%d", &mxiter);
}
keyword_ptr = strstr(line, "INVERSE=");
if (keyword_ptr != NULL) {
keyword_ptr += 8;
i = sscanf(keyword_ptr,"%d", &invflag);
}
keyword_ptr = strstr(line, "ETOL=");
if (keyword_ptr != NULL) {
keyword_ptr += 5;
i = sscanf(keyword_ptr,"%lf", &etol);
}
keyword_ptr = strstr(line, "PRINT=");
if (keyword_ptr != NULL) {
keyword_ptr += 6;
i = sscanf(keyword_ptr,"%d", &prntflag);
}
} while ((keyword_ptr=strstr(line,"#END")) == NULL);
}
(void)fclose(infile);
if (prntflag) {
(void)fprintf(outfile,
"\n********** Configuration Interaction program (TQ)");
(void)fprintf(outfile,"**********\n");
lt = time(NULL);
tmptr = localtime(<);
(void)fprintf(outfile, "%s", asctime(tmptr));
if (!ichk) {
(void)fprintf(outfile, "\ninput not found => using defaults\n");
(void)fflush(outfile);
}
(void)fprintf(outfile, "\ntotal number of processors (including master proc): %d\n", comm_sz);
(void)fprintf(outfile, "\ndimension of model space: %ld", ncsfm);
(void)fprintf(outfile, "\ndimension of M+Q1 space: %ld", ncsfq1+ncsfm);
(void)fprintf(outfile, "\ndimension of M+Q1+Q2 space: %ld", ncsft);
(void)fprintf(outfile, "\nprint flag = %d", prntflag);
(void)fprintf(outfile, "\nnroots = %d\n\n", nstates);
(void)fflush(outfile);
}
if (nstates<1) {
(void)fprintf(outfile, "\nNo converged root from MRCISD!\n");
MPI_Abort(MPI_COMM_WORLD, 1);
}
mxdim = nstates;
nnstates = (nstates*(nstates+1))/2;
}
MPI_Bcast(&prntflag, 1, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Bcast(&nstates, 1, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Bcast(&nnstates, 1, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Bcast(&mxiter, 1, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Bcast(&invflag, 1, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Bcast(&ncsfq1, 1, MPI_LONG, 0, MPI_COMM_WORLD);
MPI_Bcast(&totalmem, 1, MPI_LONG, 0, MPI_COMM_WORLD);
if (mxiter>1) {
if ((scrfile = mpisopen(SCRNAME, "w+b", infofile, my_rank)) == NULL) {
(void)printf("\nProcessor %d: Error opening %s\n", my_rank, SCRNAME);
MPI_Abort(MPI_COMM_WORLD, 1);
}
}
energs = (double *)malloc(nstates * sizeof(double));
getarray(infofile, 27, energs, nstates * sizeof(double)); /* for all space */
if (my_rank == 0) {
energs0 = (double *)malloc(nstates * sizeof(double));
old_energs = (double *)malloc(nstates * sizeof(double));
eigval = (double *)malloc(nstates * sizeof(double));
for (i=0; i<nstates; i++) {
old_energs[i] = energs[i];
energs0[i] = energs[i];
}
if (prntflag) {
(void)fprintf(outfile, "\n MRCISD energies:\n");
(void) fprintf(outfile, "\n\nState Energy ");
(void) fprintf(outfile, "\n (I) /a.u./ ");
(void) fprintf(outfile, "\n..... ..................");
for (i=0; i<nstates; i++)
(void) fprintf(outfile,"\n %d %+.12lf",
i+1, old_energs[i]+repnuc);
(void)fprintf(outfile, "\n\n");
(void) fflush(outfile);
}
}
civec = (double *)malloc(ncsfq1 * nstates * sizeof(double));
if (!civec) {
(void)fprintf(outfile, "\n\nmemory allocation error for civec in processor %d\n\n", my_rank);
MPI_Abort(MPI_COMM_WORLD, 1);
}
if (my_rank == 0) {
cifile = sopen(CINAME, "rb", infofile);
if (cifile == NULL) {
(void)fprintf(outfile, "\nError opening file: %s\n", CINAME);
MPI_Abort(MPI_COMM_WORLD, 1);
}
(void)fseek(cifile, ncsfm*nstates*sizeof(double), SEEK_SET);
if (fread(civec, ncsfq1*nstates*sizeof(double), 1, cifile)!=1) {
(void)fprintf(outfile, "\n\nfread error (%s)\n\n", CINAME);
MPI_Abort(MPI_COMM_WORLD, 1);
}
}
MPI_Bcast(civec, ncsfq1*nstates, MPI_DOUBLE, 0, MPI_COMM_WORLD);
initci(totalmem);
hwpp = dmatrix0(nstates, nstates);
upp = dmatrix0(nstates, nstates);
wwpp = (double **)malloc(nstates * sizeof(double *));
memtmp = nnstates * sizeof(double);
memtmp += 4 * nstates * sizeof(double);
if (sizeof(double) > sizeof(int)) memtmp += nstates * sizeof(double);
else memtmp += nstates * sizeof(int);
wwpp[0] = (double *)malloc(memtmp);
for (i=1; i<nstates; i++) {
wwpp[i] = wwpp[i-1] + i;
}
for (i=0; i<nstates; i++) {
upp[i][i] = 1.0;
}
/* prepare the arrays for inverse matrix (He2e2-Ep)(-1) */
if (invflag) {
hwpp2 = dmatrix0(nstates, nstates);
upp2 = dmatrix0(nstates, nstates);
wwpp2 = (double **)malloc(nstates * sizeof(double *));
wwpp2[0] = (double *)malloc(memtmp);
for (i=1; i<nstates; i++) {
wwpp2[i] = wwpp2[i-1] + i;
}
energs2 = (double *)malloc(nstates * sizeof(double));
for (i=0; i<nstates; i++) {
energs2[i] = energs[i];
upp2[i][i] = 1.0;
}
}
hwpp_sum= dmatrix0(nstates, nstates);
wwpp_sum= (double **)malloc(nstates * sizeof(double *));
wwpp_sum[0] = (double *)malloc(memtmp);
for (i=1; i<nstates; i++) {
wwpp_sum[i] = wwpp_sum[i-1] + i;
}
if (invflag) {
hwpp_sum2= dmatrix0(nstates, nstates);
wwpp_sum2= (double **)malloc(nstates * sizeof(double *));
wwpp_sum2[0] = (double *)malloc(memtmp);
for (i=1; i<nstates; i++) {
wwpp_sum2[i] = wwpp_sum2[i-1] + i;
}
}
if (my_rank == 0) {
wpp = dmatrix0(nstates, nstates);
wppinv = dmatrix0(nstates, nstates);
wqp = dmatrix0(nstates, nstates);
upptemp = dmatrix0(nstates, nstates);
uvecs = dmatrix0(nstates, nstates);
vpp = dmatrix0(nstates, nstates);
heff = (double *)malloc(memtmp);
for (i=0; i<nstates; i++) {
wppinv[i][i] = 1.0;
upptemp[i][i] = 1.0;
}
/* prepare the arrays for inverse matrix (He2e2-Ep)(-1) */
if (invflag) {
upptemp2 = dmatrix0(nstates, nstates);
wpp2 = dmatrix0(nstates, nstates);
wppinv2 = dmatrix0(nstates, nstates);
old_energs2 = (double *)malloc(nstates * sizeof(double));
for (i=0; i<nstates; i++) {
old_energs2[i] = energs[i];
wppinv2[i][i] = 1.0;
upptemp2[i][i] = 1.0;
}
}
}
nstates2 = nstates*nstates;
/* start TQ iteration */
for (iter=0; iter<mxiter && (!conv); iter++) {
for (i=0; i<nstates2; i++) {
hwpp[0][i] = 0.0;
hwpp_sum[0][i] = 0.0;
}
for (i=0; i<nnstates; i++) {
wwpp[0][i] = 0.0;
wwpp_sum[0][i] = 0.0;
}
if (invflag) {
for (i=0; i<nstates2; i++) {
hwpp2[0][i] = 0.0;
hwpp_sum2[0][i] = 0.0;
}
for (i=0; i<nnstates; i++) {
wwpp2[0][i] = 0.0;
wwpp_sum2[0][i] = 0.0;
}
}
MPI_Bcast(&iter, 1, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Bcast(energs, nstates, MPI_DOUBLE, 0, MPI_COMM_WORLD);
for (i = 0; i < nstates; i++) {
MPI_Bcast(upp[i], nstates, MPI_DOUBLE, 0, MPI_COMM_WORLD);
}
if (invflag) {
MPI_Bcast(energs2, nstates, MPI_DOUBLE, 0, MPI_COMM_WORLD);
for (i = 0; i < nstates; i++) {
MPI_Bcast(upp2[i], nstates, MPI_DOUBLE, 0, MPI_COMM_WORLD);
}
}
MPI_Barrier(MPI_COMM_WORLD);
mkhw();
for (i = 0; i < nstates; i++) {
MPI_Reduce(hwpp[i], hwpp_sum[i], nstates, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
MPI_Reduce(wwpp[i], wwpp_sum[i], i+1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
}
if (invflag) {
for (i = 0; i < nstates; i++) {
MPI_Reduce(hwpp2[i], hwpp_sum2[i], nstates, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
MPI_Reduce(wwpp2[i], wwpp_sum2[i], i+1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
}
}
MPI_Barrier(MPI_COMM_WORLD);
if (my_rank == 0) { //copy data from sum to regular so the following code stay the saem
for (i = 0; i < nstates; i++) {
for (j = 0; j <= i; j++) {
wwpp[i][j] = wwpp_sum[i][j];
}
for (j = 0; j < nstates; j++) {
hwpp[i][j] = hwpp_sum[i][j];
}
}
if (invflag) {
for (i = 0; i < nstates; i++) {
for (j = 0; j <= i; j++) {
wwpp2[i][j] = wwpp_sum2[i][j];
}
for (j = 0; j < nstates; j++) {
hwpp2[i][j] = hwpp_sum2[i][j];
}
}
}
}
if (my_rank == 0) { //all operations in the current iteration can be done by the master.
if (prntflag) {
(void)fprintf(outfile, "\n******* iteration #%d ********* \n", iter+1);
(void)fprintf(outfile, "\n (HW)pp matrix for MRCISD(TQ):\n");
for (i=0; i<nstates; i++) {
for (j=0; j<nstates; j++) {
(void)fprintf(outfile, " (HW)pp[%d][%d]=%.12f", i, j, hwpp[i][j]);
}
(void)fprintf(outfile, "\n");
}
for (i=0; i<nstates; i++) {
(void)fprintf(outfile, " Lower[%d][%d]=%.12f\n",
i, i, old_energs[i]+hwpp[i][i]+repnuc);
}
(void)fprintf(outfile, "\n (WW)pp matrix for MRCISD(TQ):\n");
for (i=0; i<nstates; i++) {
for (j=0; j<=i; j++) {
(void)fprintf(outfile, " WW[%d][%d]=%.12f", i, j, wwpp[i][j]);
}
(void)fprintf(outfile, "\n");
}
for (i=0; i<nstates; i++) {
(void)fprintf(outfile, " Upper[%d][%d]=%.12f\n", i, i,
old_energs[i]+hwpp[i][i]/(1.+wwpp[i][i])+repnuc);
}
}
(void)fflush(outfile);
/* =============================================================== *
* Update (HW)pp *
* (HW)pp = Wpp(-1)*(HW)pp *
* scratch use of vpp[][] *
* =============================================================== */
multiply(wppinv, hwpp, vpp, nstates);
/* =============================================================== *
* update matrices Wpp and Wpp(-1) *
* =============================================================== */
for (i=0; i<nstates; i++) eigval[i] = 0.0;
if (nstates==1) {
uvecs[0][0] = 1.0;
eigval[0] = sqrt(1.-wwpp[0][0]);
} else {
for (i=0; i<nstates; i++) {
for (j=0; j<i; j++) wwpp[i][j] *= -1.;
wwpp[i][i] = 1.-wwpp[i][i];
}
jacobi2dm(wwpp[0], eigval, uvecs, nstates, 0);
for (i=0; i<nstates; i++) eigval[i] = sqrt(eigval[i]);
}
for (i=0; i<nstates; i++) {
for (j=0; j<=i; j++) {
sum = 0.0;
sum2 = 0.0;
for (k=0; k<nstates; k++) {
temp = uvecs[i][k]*uvecs[j][k];
sum += temp*eigval[k];
sum2 += temp/eigval[k];
}
wpp[i][j] = sum;
wppinv[i][j] = sum2;
if(i>j) {
wpp[j][i] = sum;
wppinv[j][i] = sum2;
}
}
}
/* =============================================================== *
* Construct Heff *
* =============================================================== */
/* scratch use of upp[][] to get (hpw)pp */
for (i=0; i<nstates; i++) {
for (j=0; j<=i; j++) {
sum = 0.0;
for (k=0; k<nstates; k++) {
temp = upptemp[k][i]*upptemp[k][j];
sum += temp*energs0[k];
}
upp[i][j] = sum;
if(i>j) {
upp[j][i] = sum;
}
}
}
/* add (hpw)pp to (hqw)pp, scratch use of vpp[][] */
multiplyplus(upp, wpp, vpp, nstates);
multiply(wppinv, vpp, hwpp, nstates);
for (i=0, ij=0; i<nstates; i++) {
for (j=0; j<i; j++, ij++) {
heff[ij] = 0.5 * (hwpp[i][j] + hwpp[j][i]);
}
heff[ij++] = hwpp[i][i];
}
if (prntflag) {
(void)fprintf(outfile, "\n (Heff)pp matrix for MRCISD(TQ):\n");
for (i=0,ij=0; i<nstates; i++) {
for (j=0; j<=i; j++,ij++) {
(void)fprintf(outfile, " (Heff)pp[%d]=%.12f", ij, heff[ij]);
}
(void)fprintf(outfile, "\n");
}
}
(void)fflush(outfile);
/* =============================================================== *
* Diagonalization of Heff and update Upp and Vpp *
* =============================================================== */
for (i=0; i<nstates; i++) eigval[i] = 0.0;
if (nstates == 1) {
vpp[0][0] = 1.0;
energs[0] = heff[0];
} else {
jacobi2dm(heff, energs, vpp, nstates, 0);
}
if (prntflag) {
(void) fprintf(outfile, "\n\nState Energy ");
(void) fprintf(outfile, "\n (I) /a.u./ ");
(void) fprintf(outfile, "\n..... ..................");
for (i=0; i<nstates; i++)
(void) fprintf(outfile,"\n %d %+.12lf",
i+1, energs[i]+repnuc);
(void) fflush(outfile);
/* Test only */
/*(void) fprintf(outfile, "\n\nState Energy ");
(void) fprintf(outfile, "\n (I) /a.u./ ");
(void) fprintf(outfile, "\n..... ..................");*/
/* Test only */
}
for (i=0, diff=0.0; i<nstates; i++) {
temp = old_energs[i] - energs[i];
/* Test only */
/*if (prntflag) {
(void) fprintf(outfile,"\n %d %+16.14e", i+1, temp);
(void)fflush(outfile);
}*/
/* Test only */
diff += temp * temp;
old_energs[i] = energs[i];
}
diff = sqrt(diff);
if (prntflag) {
(void)fprintf(outfile, "\n Convergence test: %16.12lf\n", diff);
(void)fflush(outfile);
}
if ((!invflag)&&(diff<etol)) conv = 1;
}
MPI_Bcast(&conv, 1, MPI_INT, 0, MPI_COMM_WORLD);
if (prntflag>1) prntflag = 1;
if (my_rank == 0) {
/* update Upp and save it to Upptemp */
multiply(upptemp, vpp, upp, nstates);
for (i=0; i<nstates2; i++) upptemp[0][i] = upp[0][i];
/* update (UW)pp to Upp */
multiply(upptemp, wpp, upp, nstates);
}
if (my_rank == 0) {
if (invflag) {
(void)fprintf(outfile, "\n******* inverse matrix ********* \n");
(void)fprintf(outfile, "\n (HW)pp matrix for MRCISD(TQ):\n");
for (i=0; i<nstates; i++) {
for (j=0; j<nstates; j++) {
(void)fprintf(outfile, " (HW)pp[%d][%d]=%.12f", i, j, hwpp2[i][j]);
}
(void)fprintf(outfile, "\n");
}
for (i=0; i<nstates; i++) {
(void)fprintf(outfile, " Lower[%d][%d]=%.12f\n",
i, i, old_energs2[i]+hwpp2[i][i]+repnuc);
}
(void)fprintf(outfile, "\n (WW)pp matrix for MRCISD(TQ):\n");
for (i=0; i<nstates; i++) {
for (j=0; j<=i; j++) {
(void)fprintf(outfile, " WW[%d][%d]=%.12f", i, j, wwpp2[i][j]);
}
(void)fprintf(outfile, "\n");
}
for (i=0; i<nstates; i++) {
(void)fprintf(outfile, " Upper[%d][%d]=%.12f\n", i, i,
old_energs2[i]+hwpp2[i][i]/(1.+wwpp2[i][i])+repnuc);
}
/* =============================================================== *
* Update (HW)pp *
* (HW)pp = Wpp(-1)*(HW)pp *
* scratch use of vpp[][] *
* =============================================================== */
multiply(wppinv2, hwpp2, vpp, nstates);
/* =============================================================== *
* Calculation of Wpp and Wpp(-1) *
* =============================================================== */
for (i=0; i<nstates; i++) eigval[i] = 0.0;
if (nstates==1) {
uvecs[0][0] = 1.0;
eigval[0] = sqrt(1.-wwpp2[0][0]);
} else {
for (i=0; i<nstates; i++) {
for (j=0; j<i; j++) wwpp2[i][j] *= -1.;
wwpp2[i][i] = 1.-wwpp2[i][i];
}
jacobi2dm(wwpp2[0], eigval, uvecs, nstates, 0);
for (i=0; i<nstates; i++) eigval[i] = sqrt(eigval[i]);
}
for (i=0; i<nstates; i++) {
for (j=0; j<=i; j++) {
sum = 0.0;
sum2 = 0.0;
for (k=0; k<nstates; k++) {
temp = uvecs[i][k]*uvecs[j][k];
sum += temp*eigval[k];
sum2 += temp/eigval[k];
}
wpp2[i][j] = sum;
wppinv2[i][j] = sum2;
if(i>j) {
wpp2[j][i] = sum;
wppinv2[j][i] = sum2;
}
}
}
/* =============================================================== *
* Construct Heff *
* =============================================================== */
/* scratch use of upp2[][] to get (hpw)pp */
for (i=0; i<nstates; i++) {
for (j=0; j<=i; j++) {
sum = 0.0;
for (k=0; k<nstates; k++) {
temp = upptemp2[k][i]*upptemp2[k][j];
sum += temp*energs0[k];
}
upp2[i][j] = sum;
if (i>j) {
upp2[j][i] = sum;
}
}
}
/* add (hpw)pp to (hqw)pp */
multiplyplus(upp2, wpp2, vpp, nstates);
multiply(wppinv2, vpp, hwpp2, nstates);
for (i=0, ij=0; i<nstates; i++) {
for (j=0; j<i; j++, ij++) {
heff[ij] = 0.5 * (hwpp2[i][j] + hwpp2[j][i]);
}
heff[ij++] = hwpp2[i][i];
}
if (prntflag) {
(void)fprintf(outfile, "\n ****** with inverse matrix ******* \n");
(void)fprintf(outfile, "\n (Heff)pp matrix for MRCISD(TQ):\n");
for (i=0,ij=0; i<nstates; i++) {
for (j=0; j<=i; j++,ij++) {
(void)fprintf(outfile, " (Heff)pp[%d]=%.12f", ij, heff[ij]);
}
(void)fprintf(outfile, "\n");
}
(void)fflush(outfile);
}
/* =============================================================== *
* Diagonalization of Heff and update Upp and Vpp *
* =============================================================== */
for (i=0; i<nstates; i++) eigval[i] = 0.0;
if (nstates == 1) {
vpp[0][0] = 1.0;
energs2[0] = heff[0];
} else {
jacobi2dm(heff, energs2, vpp, nstates, 0);
}
if (prntflag) {
(void) fprintf(outfile, "\n\nState Energy ");
(void) fprintf(outfile, "\n (I) /a.u./ ");
(void) fprintf(outfile, "\n..... ..................");
for (i=0; i<nstates; i++)
(void) fprintf(outfile,"\n %d %+.12lf",
i+1, energs2[i]+repnuc);
(void) fflush(outfile);
}
for (i=0, diff=0.0; i<nstates; i++) {
diff += (energs2[i] - old_energs2[i]) * (energs2[i] - old_energs2[i]);
old_energs2[i] = energs2[i];
}
diff = sqrt(diff);
if (prntflag) {
(void)fprintf(outfile, "\n Convergence test: %16.12lf\n", diff);
(void)fflush(outfile);
}
if (diff<etol) conv = 1;
}
}
MPI_Bcast(&conv, 1, MPI_INT, 0, MPI_COMM_WORLD);
if (prntflag>1) prntflag = 1;
if (my_rank == 0) {
if (invflag) {
/* update Upp and save it to Upptemp */
multiply(upptemp2, vpp, upp2, nstates);
for (i=0; i<nstates2; i++) upptemp2[0][i] = upp2[0][i];
/* update (UW)pp to Upp */
multiply(upptemp2, wpp2, upp2, nstates);
} /* end of if (invflag) */
if ((!iter)&&prntflag) {
runtime = (double)clock()/CLOCKS_PER_SEC - cpu_time;
(void)fprintf(outfile,
" \n\n first iteration cpu time MRCISD(TQ) = %.2lf s\n\n", runtime);
lt = time(NULL);
tmptr = localtime(<);
(void)fprintf(outfile, "%s", asctime(tmptr));
(void)fflush(outfile);
}
}
} /* end of iterations */
if (my_rank == 0) {
if (iter==mxiter)
(void) fprintf(outfile,"\n MRCISD(TQ) does not converge in %d iterations!", iter);
/* ................................... *
Print energies of the MRCISD(TQ) states
* ................................... */
/*if (prntflag) {
(void) fprintf(outfile, "\n\nState Energy ");
(void) fprintf(outfile, "\n (I) /a.u./ ");
(void) fprintf(outfile, "\n..... ..................");
for (i=0; i<nstates; i++)
(void) fprintf(outfile,"\n %d %+.12lf",
i+1, energs[i]+repnuc);
(void) fflush(outfile);
}*/
if (prntflag) {
runtime = (double)clock()/CLOCKS_PER_SEC - cpu_time;
(void)fprintf(outfile, " \n\ntotal cpu time MRCISD(TQ) = %.2lf s\n\n",
runtime);
lt = time(NULL);
tmptr = localtime(<);
(void)fprintf(outfile, "%s", asctime(tmptr));
(void)fprintf(outfile, "\n********** "
"End of MRCISD(TQ) (CFGCI variant) **********\n\n");
}
}
(void)fclose(outfile);
(void)fclose(infofile);
MPI_Finalize();
return 0;
}
/* C = A * B */
void multiply(double **a, double **b, double **c, int n) {
int i, j, k;
double temp;
for (i=0; i<n; i++) {
for (j=0; j<n; j++) {
temp = 0.0;
for (k=0; k<n; k++) {
temp += a[i][k] * b[k][j];
}
c[i][j] = temp;
}
}
}
/* C += A * B */
void multiplyplus(double **a, double **b, double **c, int n) {
int i, j, k;
double temp;
for (i=0; i<n; i++) {
for (j=0; j<n; j++) {
temp = 0.0;
for (k=0; k<n; k++) {
temp += a[i][k] * b[k][j];
}
c[i][j] += temp;
}
}
}
| 31.833948 | 132 | 0.455083 | [
"model"
] |
bce10994569495abbc77325c35e3d333b95b9f2a | 1,188 | c | C | lib/wizards/jenny/linnake/mosut/hallguard.c | vlehtola/questmud | 8bc3099b5ad00a9e0261faeb6637c76b521b6dbe | [
"MIT"
] | null | null | null | lib/wizards/jenny/linnake/mosut/hallguard.c | vlehtola/questmud | 8bc3099b5ad00a9e0261faeb6637c76b521b6dbe | [
"MIT"
] | null | null | null | lib/wizards/jenny/linnake/mosut/hallguard.c | vlehtola/questmud | 8bc3099b5ad00a9e0261faeb6637c76b521b6dbe | [
"MIT"
] | null | null | null | inherit "obj/monster";
reset(arg) {
object armour,weapon;
::reset(arg);
if(arg) { return; }
set_race("human");
set_gender(1);
call_other(this_object(), "set_level", 24);
call_other(this_object(), "set_name", "guard");
call_other(this_object(), "set_alias", "human");
call_other(this_object(), "set_short", "Hallguard watching every step you take");
call_other(this_object(), "set_long", "Kind looking hallguard is here watching people to behave properly.\n"+
"He looks quite strong and is wielding a black sword that looks\n"+
"quite scary. He is wearing normal clothes but he does have an\n"+
"armour on his torso.\n");
call_other(this_object(), "set_al", 0);
call_other(this_object(), "set_aggressive", 0);
armour = clone_object("/wizards/jenny/linnake/rojut/black_armour.c");
move_object(armour, this_object());
init_command("wear armour");
weapon = clone_object("/wizards/jenny/linnake/rojut/guard_sword.c");
move_object(weapon, this_object());
init_command("wield sword");
}
| 42.428571 | 113 | 0.612795 | [
"object"
] |
bce30e8265e9962e8a25816445575f5211950ee4 | 776 | h | C | src/VM/types/object.h | joakimthun/Elsa | 3be901149c1102d190dda1c7f3340417f03666c7 | [
"MIT"
] | 16 | 2015-10-12T14:24:45.000Z | 2021-07-20T01:56:04.000Z | src/VM/types/object.h | haifenghuang/Elsa | 3be901149c1102d190dda1c7f3340417f03666c7 | [
"MIT"
] | null | null | null | src/VM/types/object.h | haifenghuang/Elsa | 3be901149c1102d190dda1c7f3340417f03666c7 | [
"MIT"
] | 2 | 2017-11-12T01:39:09.000Z | 2021-07-20T01:56:09.000Z | #pragma once
#include <stdlib.h>
#include "object_types\vm_type.h"
#include "gcobject.h"
#include "exceptions/runtime_exception.h"
#include "constants/struct_info.h"
namespace elsa {
namespace vm {
typedef union {
int i;
float f;
wchar_t c;
GCObject* gco;
uint8_t b;
} Value;
class Object
{
public:
Object();
Object(int v);
Object(float v);
Object(wchar_t v);
Object(GCObject* o);
Object(bool v);
Object(uint8_t b);
int i() const;
float f() const;
wchar_t c() const;
uint8_t b() const;
GCObject* gco() const;
GCObject* function() const;
const Value& get_value() const;
elsa::VMType get_type() const;
void set_type(elsa::VMType type);
private:
elsa::VMType type_;
Value value_;
};
}
} | 16.166667 | 41 | 0.639175 | [
"object"
] |
bce65370fbdca0bb63b1afe9c5ace5077594c553 | 4,760 | h | C | renderer/parameter.h | khoehlein/fV-SRN | 601f3e952b090df92e875c233c2c9ca646523948 | [
"MIT"
] | null | null | null | renderer/parameter.h | khoehlein/fV-SRN | 601f3e952b090df92e875c233c2c9ca646523948 | [
"MIT"
] | null | null | null | renderer/parameter.h | khoehlein/fV-SRN | 601f3e952b090df92e875c233c2c9ca646523948 | [
"MIT"
] | null | null | null | #pragma once
#include <variant>
#include <vector_types.h>
#include <torch/types.h>
BEGIN_RENDERER_NAMESPACE
enum class ParameterType
{
Bool, Int, Int2, Int3, Int4,
Double, Double2, Double3, Double4,
Tensor
};
struct ParameterBase {};
/**
* \brief A (differentiable) parameter of the renderer.
* These parameters can be controlled by Python,
* and contain those three fields:
* - value: the actual value (or multiple options if batched)
* - static constexpr bool supportsGradients
* - grad: the gradient tensor
* - forwardIndex: an integer tensor with the index into forward derivatives
*
* The values can usually be defined as a single scalar, e.g. 'double' or 'double4',
* or as a torch::Tensor. This allows the parameter to be batched over the pixels/images.
* The exact semantics depends on the use case.
* The scalar parameters are stored as double-precision on the host.
* Only during rendering they are cast to the actual scalar type (single or double precision).
*
* There does not exist a default implementation intentionally
* to support only specific primitive parameter types.
*
*/
template<typename T>
struct Parameter;
#define PARAMETER_NON_DIFFERENTIABLE(T, PT) \
template<> \
struct Parameter<T> : ParameterBase \
{ \
using value_t = T; \
/* The value of this parameter: scalar or tensor for batching*/ \
std::variant<T, torch::Tensor> value; \
enum { supportsGradients = false }; \
static constexpr ParameterType type = ParameterType::PT; \
};
PARAMETER_NON_DIFFERENTIABLE(bool, Bool);
PARAMETER_NON_DIFFERENTIABLE(int, Int);
PARAMETER_NON_DIFFERENTIABLE(int2, Int2);
PARAMETER_NON_DIFFERENTIABLE(int3, Int3);
PARAMETER_NON_DIFFERENTIABLE(int4, Int4);
#undef PARAMETER_NON_DIFFERENTIABLE
#define PARAMETER_DIFFERENTIABLE(T, PT) \
template<> \
struct Parameter<T> : ParameterBase \
{ \
/* The scalar type of this parameter */ \
using value_t = T; \
/* The value of this parameter: scalar or tensor for batching*/ \
std::variant<T, torch::Tensor> value; \
/* Gradients are supported */ \
enum { supportsGradients = true }; \
static constexpr ParameterType type = ParameterType::PT; \
/* If defined and of the same shape as 'value', will contain the gradients*/ \
torch::Tensor grad; \
/* The indices for the forward method*/ \
torch::Tensor forwardIndex; \
Parameter() = default; \
Parameter(const T& v) : value(v) {} \
Parameter(const torch::Tensor& v) : value(v) {} \
};
PARAMETER_DIFFERENTIABLE(double , Double);
PARAMETER_DIFFERENTIABLE(double2, Double2);
PARAMETER_DIFFERENTIABLE(double3, Double3);
PARAMETER_DIFFERENTIABLE(double4, Double4);
#undef PARAMETER_DIFFERENTIABLE
template<>
struct Parameter<torch::Tensor> : ParameterBase
{
using value_t = torch::Tensor;
torch::Tensor value;
enum { supportsGradients = true };
static constexpr ParameterType type = ParameterType::Tensor;
torch::Tensor grad;
torch::Tensor forwardIndex;
};
/**
* For use in the UI: enforces that the parameter
* stores a scalar value (instead of the batched tensor)
* and returns a pointer to the parameter for ImGUI.
* If the parameter is stored as batched tensor,
* replace it by 'alternative'.
*/
template<typename T>
T* enforceAndGetScalar(Parameter<T>& p, const T& alternative = T())
{
static_assert(std::is_same_v<
decltype(p.value),
std::variant<T, torch::Tensor>>,
"The parameter does not store its value as variant<T, Tensor>.");
//already stored as scalar
if (std::holds_alternative<T>(p.value))
return &std::get<T>(p.value);
//enforce scalar
p.value = alternative;
return &std::get<T>(p.value);
}
template<typename T>
const T* getScalarOrThrow(const Parameter<T>& p)
{
static_assert(std::is_same_v<
decltype(p.value),
std::variant<T, torch::Tensor>>,
"The parameter does not store its value as variant<T, Tensor>.");
//already stored as scalar
if (std::holds_alternative<T>(p.value))
return &std::get<T>(p.value);
//stored as tensor -> throw
throw std::runtime_error("parameter stored as batched tensor, can't save it");
}
template<typename T>
T* getScalarOrThrow(Parameter<T>& p)
{
static_assert(std::is_same_v<
decltype(p.value),
std::variant<T, torch::Tensor>>,
"The parameter does not store its value as variant<T, Tensor>.");
//already stored as scalar
if (std::holds_alternative<T>(p.value))
return &std::get<T>(p.value);
//stored as tensor -> throw
throw std::runtime_error("parameter stored as batched tensor, can't save it");
}
END_RENDERER_NAMESPACE
| 33.286713 | 94 | 0.688025 | [
"shape"
] |
bcf3a4d694f78380a9323ce20b9e3847a9499428 | 1,625 | h | C | zircon/system/ulib/inspect-vmo/include/lib/inspect-vmo/inspect.h | zhangpf/fuchsia-rs | 903568f28ddf45f09157ead36d61b50322c9cf49 | [
"BSD-3-Clause"
] | 1 | 2019-10-09T10:50:57.000Z | 2019-10-09T10:50:57.000Z | zircon/system/ulib/inspect-vmo/include/lib/inspect-vmo/inspect.h | zhangpf/fuchsia-rs | 903568f28ddf45f09157ead36d61b50322c9cf49 | [
"BSD-3-Clause"
] | 5 | 2020-09-06T09:02:06.000Z | 2022-03-02T04:44:22.000Z | zircon/system/ulib/inspect-vmo/include/lib/inspect-vmo/inspect.h | ZVNexus/fuchsia | c5610ad15208208c98693618a79c705af935270c | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2018 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.
#ifndef LIB_INSPECT_VMO_INSPECT_H_
#define LIB_INSPECT_VMO_INSPECT_H_
#include <lib/inspect-vmo/state.h>
namespace inspect {
namespace vmo {
// Entry point into the Inspection VMO.
//
// This inspector owns a VMO into which inspection data is written for
// later reading through a read-only copy of the VMO.
class Inspector final {
public:
// Create a new inspection VMO with default capacity and maximum size.
Inspector();
// Create a new inspection VMO with explicit capacity and maximum size.
Inspector(size_t capacity, size_t max_size);
// Disallow copy and move.
Inspector(const Inspector&) = delete;
Inspector(Inspector&&) = default;
Inspector& operator=(const Inspector&) = delete;
Inspector& operator=(Inspector&&) = default;
// Return a reference to the contained VMO. This VMO may be duplicated
// and passed to reader processes for inspection.
const zx::vmo& GetVmo() const { return state_->GetVmo(); }
// Creates a new object stored at the root of the given VMO.
// By convention, the object returned by the first call of this method is the root of the tree.
// Objects created by additional calls may be ignored depending on the reader.
Object CreateObject(const char* name) const;
private:
// Shared reference to the state, which owns the VMO.
fbl::RefPtr<internal::State> state_;
};
} // namespace vmo
} // namespace inspect
#endif // LIB_INSPECT_VMO_INSPECT_H_
| 33.163265 | 99 | 0.725538 | [
"object"
] |
bcfdfde0018bf3daf413450afb74a8803727e2e5 | 8,199 | c | C | src/PJ/muparts.c | AnimatorPro/Animator-Pro | 6d0b68cd94bb5cfde2cdd05e9a7c8ee1e1cb3cbb | [
"BSD-3-Clause"
] | 119 | 2015-01-10T15:13:50.000Z | 2022-01-24T04:54:34.000Z | src/PJ/muparts.c | AnimatorPro/Animator-Pro | 6d0b68cd94bb5cfde2cdd05e9a7c8ee1e1cb3cbb | [
"BSD-3-Clause"
] | 6 | 2015-10-22T20:14:59.000Z | 2021-07-10T03:25:21.000Z | src/PJ/muparts.c | AnimatorPro/Animator-Pro | 6d0b68cd94bb5cfde2cdd05e9a7c8ee1e1cb3cbb | [
"BSD-3-Clause"
] | 27 | 2015-04-24T22:55:30.000Z | 2022-01-21T13:54:00.000Z | #define MUPARTS_INTERNALS
#include "jimk.h"
#include "broadcas.h"
#include "brush.h"
#include "celmenu.h"
#include "flicel.h"
#include "menus.h"
#include "palmenu.h"
#include "pentools.h"
#include "rastcurs.h"
#include "softmenu.h"
#include "timemenu.h"
#include "zoom.h"
static void pget_color(Button *b);
static void fill_inkwell(Button *b);
/**** standard header group 1 the right side of the home menu ****/
#define SHG ((Sgroup1_data *)(b->group))
static void sh1_hang_minitime(Button *b)
{
Sgroup1_data *shg;
shg = b->group;
b->group = shg->minidat;
hang_children(b);
b->group = shg;
}
#undef SHG
Button sh1_brush_sel = MB_INIT1(
NONEXT,
NOCHILD, /* children */
12, 12, 163, -2, /* w,h,x,y */
NOTEXT, /* datme */
see_pen,
toggle_pen,
set_pbrush,
NOGROUP,0,
NOKEY,
0 /* flags */
);
static Button sh1_tco_sel = MB_INIT1(
&sh1_brush_sel, /* next */
NOCHILD, /* children */
11, 9, 96, 0, /* w,h,x,y */
NODATA, /* "K", */
ncorner_text,
mb_toggle_zclear,
go_cel_menu,
&vs.zero_clear, 1,
NOKEY,
MB_B_GHILITE /* flags */
);
static Button sh1_filp_sel = MB_INIT1(
&sh1_tco_sel, /* next */
NOCHILD, /* children */
11, 9, 86, 0, /* w,h,x,y */
NODATA, /* "F", */
ncorner_text,
toggle_bgroup,
NOOPT,
&vs.fillp, 1,
NOKEY,
MB_B_GHILITE /* flags */
);
static Button sh1_tim_sel = MB_INIT1(
&sh1_filp_sel, /* next */
NOCHILD, /* children */
11, 9, 76, 0, /* w,h,x,y */
NODATA, /* "T", */
ncorner_text,
toggle_bgroup,
go_multi,
&vs.multi, 1,
NOKEY,
MB_B_GHILITE /* flags */
);
static Button sh1_ccolor_sel = MB_INIT1(
&sh1_tim_sel, /* next */
NOCHILD, /* children */
11, 11, 177, -1, /* w,h,x,y */
NOTEXT, /* datme */
ccolor_box,
go_color_grid,
ppalette,
NOGROUP,-0xAA,
NOKEY,
0 /* flags */
);
Button std_head1_sel = MB_INIT1(
&sh1_ccolor_sel, /* next */
&minitime_sel, /* children */
76, 9, 0, 0, /* w,h,x,y */
NOTEXT, /* datme */
sh1_hang_minitime,
NOFEEL,
NOOPT,
NOGROUP,0,
NOKEY,
MB_GHANG /* flags */
);
void redraw_head1_ccolor(Button *hanger)
/* redraws parts of a std_head1_sel dependent on ccolor from hanger sel */
{
Button *b;
if(!hanger || (b = hanger->children) == NULL)
return;
draw_buttontop(b->next);
}
/****** mini palette sel ******/
static void see_inkwell(Button *b)
{
SHORT color;
color = vs.inks[b->identity];
mb_dinside(b,color);
if (vs.inks[b->identity] == vs.ccolor)
color = mc_red(b);
else
color = mc_grey(b);
mb_dcorner(b,color);
}
void pget_color(), fill_inkwell();
static Button mp_ink7_sel = MB_INIT1(
NONEXT,
NOCHILD,
12, 9, 80, 0, /* w,h,x,y */
NULL,
see_inkwell,
pget_color,
fill_inkwell,
NOGROUP,7,
NOKEY,
MB_SCALE_ABSW
);
static Button mp_ink6_sel = MB_INIT1(
&mp_ink7_sel,
NOCHILD,
12, 9, 69, 0, /* w,h,x,y */
NULL,
see_inkwell,
pget_color,
fill_inkwell,
NOGROUP,6,
NOKEY,
MB_SCALE_ABSW
);
static Button mp_ink5_sel = MB_INIT1(
&mp_ink6_sel,
NOCHILD,
12, 9, 58, 0, /* w,h,x,y */
NULL,
see_inkwell,
pget_color,
fill_inkwell,
NOGROUP,5,
NOKEY,
MB_SCALE_ABSW
);
static Button mp_ink4_sel = MB_INIT1(
&mp_ink5_sel,
NOCHILD,
12, 9, 47, 0, /* w,h,x,y */
NULL,
see_inkwell,
pget_color,
fill_inkwell,
NOGROUP,4,
NOKEY,
MB_SCALE_ABSW
);
static Button mp_ink3_sel = MB_INIT1(
&mp_ink4_sel,
NOCHILD,
12, 9, 36, 0, /* w,h,x,y */
NULL,
see_inkwell,
pget_color,
fill_inkwell,
NOGROUP,3,
NOKEY,
MB_SCALE_ABSW
);
static Button mp_ink2_sel = MB_INIT1(
&mp_ink3_sel,
NOCHILD,
12, 9, 25, 0, /* w,h,x,y */
NULL,
see_inkwell,
pget_color,
fill_inkwell,
NOGROUP,2,
NOKEY,
MB_SCALE_ABSW
);
static Button mp_ink1_sel = MB_INIT1(
&mp_ink2_sel,
NOCHILD,
12, 9, 14, 0, /* w,h,x,y */
NULL,
see_inkwell,
pget_color,
fill_inkwell,
NOGROUP,1,
NOKEY,
MB_SCALE_ABSW
);
static Button mp_ink0_sel = MB_INIT1(
&mp_ink1_sel,
NOCHILD,
12, 9, 0, 0, /* w,h,x,y */
NULL,
see_inkwell,
pget_color,
fill_inkwell,
NOGROUP,0,
NOKEY,
0
);
Button minipal_sel = MB_INIT1(
NONEXT,
&mp_ink0_sel,
81, 9, 0, 0, /* w,h,x,y */
NULL,
NOSEE,
NOFEEL,
NOOPT,
NOGROUP,0,
NOKEY,
0
);
void mb_toggle_zclear(Button *b)
{
toggle_bgroup(b);
do_rmode_redraw(RSTAT_ZCLEAR);
}
static void pget_color(Button *b)
/* this called from within a feelme so mx my are good */
{
if ( icb.mx > b->x
&& icb.mx < (b->x + b->width - 1)
&& icb.my > b->y
&& icb.my < (b->y + b->height - 1))
{
vs.cycle_draw = 0;
update_ccolor(pj_get_dot(b->root,icb.mx, icb.my));
}
}
static void show_ink(Pixel c)
{
static Pixel lastc;
Rgb3 m;
if (c != lastc)
{
get_color_rgb(c,vb.pencel->cmap,&m);
soft_top_textf("!%-3d%-3d%-3d%-3d", "top_color", c, m.r, m.g, m.b);
draw_buttontop(&sh1_ccolor_sel);
}
lastc = c;
}
static void fill_inkwell(Button *b)
{
int c;
Cursorhdr *ocurs;
USHORT changes = 0;
ocurs = set_pen_cursor(&pick_cursor.hdr);
mb_dcorner(b,mc_red(b));
show_ink(-1);
if((c = get_a_end(show_ink))>=0)
{
changes |= NEW_MINIPAL_INK;
if(b->identity == 0)
{
if(thecel && (thecel->cd.tcolor != c))
{
set_flicel_tcolor(thecel,c);
changes |= NEW_CEL_TCOLOR;
}
if(vs.inks[0] != c)
changes |= NEW_INK0;
}
if(b->identity == 1 && vs.inks[1] != c)
changes |= NEW_INK1;
#ifdef SET_CCOLOR
if(c != occolor)
{
set_ccolor(c);
changes |= NEW_CCOLOR;
}
#endif /* SET_CCOLOR */
vs.inks[b->identity] = c;
}
set_pen_cursor(ocurs);
#ifndef SET_CCOLOR
draw_buttontop(&sh1_ccolor_sel);
#endif /* SET_CCOLOR */
do_color_redraw(changes);
see_inkwell(b);
}
/****** zoom cycle_color pan group *********/
static void see_ccycle(Button *b)
{
mb_set_hilite(b,vs.cycle_draw);
ncorner_text(b);
}
static Button zpg_pan_sel = MB_INIT1(
NONEXT,
NOCHILD, /* children */
38, 9, 168, 14, /* w,h,x,y */
NODATA, /* "Pan", */
ncorner_text,
movefli_tool,
movefli_tool,
NOGROUP,0,
NOKEY,
0 /* flags */
);
static Button zpg_cycle_sel = MB_INIT1(
&zpg_pan_sel, /* next */
NOCHILD, /* children */
11, 9, 155, 14, /* w,h,x,y */
NODATA, /* "C", */
see_ccycle,
mb_toggle_ccycle,
shortcut_ccycle,
NOGROUP,0,
NOKEY,
MB_GHANG /* flags */
);
static void see_zoom(Button *b)
{
set_button_disable(b,zoom_disabled());
ncorner_text(b);
}
Button zpan_cycle_group = MB_INIT1(
&zpg_cycle_sel, /* next */
NOCHILD,
39, 9, 114, 14, /* w,h,x,y */
NODATA, /* "Zoom", */
see_zoom,
toggle_zoom,
go_zoom_settings,
&vs.zoom_open,1,
'z',
MB_B_GHILITE
);
void zpan_ccycle_redraw(Button *hanger)
{
if(hanger && hanger->children)
draw_button(hanger->children->next);
}
/* texts used in vmarqi.c */
char *rub_line_str;
/* "(![1] ![2]) wid ![3] hgt ![4] (![5] ![6]) deg ![7] rad ![8]" */
char *box_coor_str; /* "(![1] ![2] ) (![3] ![4] )" */
char *rub_rect_str; /* "![1] ![2] (![3] ![4]) ![5] ![6]" */
char *rub_circle_str; /* "R = ![1] D = ![2]" */
static Smu_button_list mup_smblist[] = {
{ "kcol", { /* butn */ &sh1_tco_sel } },
{ "fillp", { /* butn */ &sh1_filp_sel } },
{ "otime", { /* butn */ &sh1_tim_sel } },
{ "pan", { /* butn */ &zpg_pan_sel } },
{ "ccycle", { /* butn */ &zpg_cycle_sel } },
{ "zoom", { /* butn */ &zpan_cycle_group } },
{ "tseg_all", { /* butn */ &tseg_a_sel } }, /* button in tseg.c */
{ "tseg_seg", { /* butn */ &tseg_s_sel } }, /* button in tseg.c */
{ "tseg_frame", { /* butn */ &tseg_f_sel } }, /* button in tseg.c */
{ "pbrush", { /* butn */ &sh1_brush_sel } },
/* texts start with 'T' */
{ "Trub_line", { /* ps */ &rub_line_str } },
{ "Tbox_coor", { /* ps */ &box_coor_str } },
{ "Trub_rect", { /* ps */ &rub_rect_str } },
{ "Trub_circle",{ /* ps */ &rub_circle_str } },
};
static void *mupss;
Errcode init_menu_parts(void)
{
return(soft_buttons("pj_muparts",mup_smblist,
Array_els(mup_smblist),&mupss));
}
void cleanup_menu_parts(void)
{
smu_free_scatters(&mupss);
}
| 19.756627 | 75 | 0.591414 | [
"3d"
] |
bcffceefd6ce9ae98f9186055c6de1b695f73b12 | 378 | h | C | XiaoYa/MemberCollectionViewCell.h | huixinHu/XiaoYa | 21df920f18cc46034282d37f6560c1877c33b1ec | [
"MIT"
] | null | null | null | XiaoYa/MemberCollectionViewCell.h | huixinHu/XiaoYa | 21df920f18cc46034282d37f6560c1877c33b1ec | [
"MIT"
] | null | null | null | XiaoYa/MemberCollectionViewCell.h | huixinHu/XiaoYa | 21df920f18cc46034282d37f6560c1877c33b1ec | [
"MIT"
] | null | null | null | //
// MemberCollectionViewCell.h
// XiaoYa
//
// Created by commet on 2017/7/11.
// Copyright © 2017年 commet. All rights reserved.
//
#import <UIKit/UIKit.h>
@class GroupMemberModel;
@interface MemberCollectionViewCell : UICollectionViewCell
@property (nonatomic ,strong ,nonnull)GroupMemberModel *model;
@property (nonatomic ,weak ,nullable)UIButton *deleteSelect;
@end
| 22.235294 | 62 | 0.756614 | [
"model"
] |
4c13b4a87033e7cf6e93198579c381947800fc97 | 2,787 | c | C | src/fs/xfs/xfsprogs-dev/spaceman/file.c | fengjixuchui/hydra | d49e652018a007bae9d22cb59dfa086deff7ad2f | [
"MIT"
] | 110 | 2019-08-21T04:23:22.000Z | 2022-01-20T16:08:36.000Z | src/fs/xfs/xfsprogs-dev/spaceman/file.c | fengjixuchui/hydra | d49e652018a007bae9d22cb59dfa086deff7ad2f | [
"MIT"
] | 16 | 2019-11-19T03:46:35.000Z | 2021-12-19T19:26:07.000Z | src/fs/xfs/xfsprogs-dev/spaceman/file.c | fengjixuchui/hydra | d49e652018a007bae9d22cb59dfa086deff7ad2f | [
"MIT"
] | 24 | 2019-09-30T21:38:08.000Z | 2021-11-22T00:22:18.000Z | /*
* Copyright (c) 2004-2005 Silicon Graphics, Inc.
* Copyright (c) 2012 Red Hat, Inc.
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it would be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "libxfs.h"
#include <sys/mman.h>
#include "command.h"
#include "input.h"
#include "init.h"
#include "path.h"
#include "space.h"
static cmdinfo_t print_cmd;
fileio_t *filetable;
int filecount;
fileio_t *file;
static void
print_fileio(
fileio_t *file,
int index,
int braces)
{
printf(_("%c%03d%c %-14s\n"), braces? '[' : ' ', index,
braces? ']' : ' ', file->name);
}
static int
print_f(
int argc,
char **argv)
{
int i;
for (i = 0; i < filecount; i++)
print_fileio(&filetable[i], i, &filetable[i] == file);
return 0;
}
int
openfile(
char *path,
xfs_fsop_geom_t *geom,
struct fs_path *fs_path)
{
struct fs_path *fsp;
int fd;
fd = open(path, 0);
if (fd < 0) {
perror(path);
return -1;
}
if (ioctl(fd, XFS_IOC_FSGEOMETRY, geom) < 0) {
perror("XFS_IOC_FSGEOMETRY");
close(fd);
return -1;
}
if (fs_path) {
fsp = fs_table_lookup(path, FS_MOUNT_POINT);
if (!fsp) {
fprintf(stderr, _("%s: cannot find mount point."),
path);
close(fd);
return -1;
}
memcpy(fs_path, fsp, sizeof(struct fs_path));
}
return fd;
}
int
addfile(
char *name,
int fd,
xfs_fsop_geom_t *geometry,
struct fs_path *fs_path)
{
char *filename;
filename = strdup(name);
if (!filename) {
perror("strdup");
close(fd);
return -1;
}
/* Extend the table of currently open files */
filetable = (fileio_t *)realloc(filetable, /* growing */
++filecount * sizeof(fileio_t));
if (!filetable) {
perror("realloc");
filecount = 0;
free(filename);
close(fd);
return -1;
}
/* Finally, make this the new active open file */
file = &filetable[filecount - 1];
file->fd = fd;
file->name = filename;
file->geom = *geometry;
memcpy(&file->fs_path, fs_path, sizeof(file->fs_path));
return 0;
}
void
print_init(void)
{
print_cmd.name = "print";
print_cmd.altname = "p";
print_cmd.cfunc = print_f;
print_cmd.argmin = 0;
print_cmd.argmax = 0;
print_cmd.flags = CMD_FLAG_ONESHOT;
print_cmd.oneline = _("list current open files");
add_command(&print_cmd);
}
| 20.05036 | 71 | 0.667743 | [
"geometry"
] |
4c14fc81fe9dfbffee8a98aa1dcc2697a64232c3 | 380 | h | C | PauseMenu.h | bsurmanski/qt-settlers | 114741a0d9ea8712d323ee9ce8a46c814bc333b1 | [
"MIT"
] | 1 | 2019-03-01T10:43:30.000Z | 2019-03-01T10:43:30.000Z | PauseMenu.h | bsurmanski/qt-settlers | 114741a0d9ea8712d323ee9ce8a46c814bc333b1 | [
"MIT"
] | null | null | null | PauseMenu.h | bsurmanski/qt-settlers | 114741a0d9ea8712d323ee9ce8a46c814bc333b1 | [
"MIT"
] | null | null | null | /*
* File: PauseMenu.h
* Author: brandon
*
* Created on May 31, 2011, 1:21 PM
*/
#ifndef PAUSEMENU_H
#define PAUSEMENU_H
#include "Model.h"
class PauseMenu {
public:
PauseMenu();
PauseMenu(const PauseMenu& orig);
virtual ~PauseMenu();
bool Update();
void Draw();
private:
Model* pauseModel;
Vector3f rotation;
};
#endif /* PAUSEMENU_H */
| 13.571429 | 37 | 0.634211 | [
"model"
] |
4c1c0bcea9a20a278948484b63a007eb9a56e80f | 1,945 | h | C | examples/pxScene2d/external/libnode-v0.12.7/deps/v8/src/compiler/pipeline.h | madanagopaltcomcast/pxCore | c4a3a40a190521c8b6383d126c87612eca5b3c42 | [
"Apache-2.0"
] | 2,494 | 2015-02-11T04:34:13.000Z | 2022-03-31T14:21:47.000Z | examples/pxScene2d/external/libnode-v0.12.7/deps/v8/src/compiler/pipeline.h | madanagopaltcomcast/pxCore | c4a3a40a190521c8b6383d126c87612eca5b3c42 | [
"Apache-2.0"
] | 1,432 | 2017-06-21T04:08:48.000Z | 2020-08-25T16:21:15.000Z | examples/pxScene2d/external/libnode-v0.12.7/deps/v8/src/compiler/pipeline.h | madanagopaltcomcast/pxCore | c4a3a40a190521c8b6383d126c87612eca5b3c42 | [
"Apache-2.0"
] | 442 | 2015-02-12T13:45:46.000Z | 2022-03-21T05:28:05.000Z | // Copyright 2014 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef V8_COMPILER_PIPELINE_H_
#define V8_COMPILER_PIPELINE_H_
#include "src/v8.h"
#include "src/compiler.h"
// Note: TODO(turbofan) implies a performance improvement opportunity,
// and TODO(name) implies an incomplete implementation
namespace v8 {
namespace internal {
namespace compiler {
// Clients of this interface shouldn't depend on lots of compiler internals.
class CallDescriptor;
class Graph;
class Schedule;
class SourcePositionTable;
class Linkage;
class Pipeline {
public:
explicit Pipeline(CompilationInfo* info) : info_(info) {}
// Run the entire pipeline and generate a handle to a code object.
Handle<Code> GenerateCode();
// Run the pipeline on a machine graph and generate code. If {schedule}
// is {NULL}, then compute a new schedule for code generation.
Handle<Code> GenerateCodeForMachineGraph(Linkage* linkage, Graph* graph,
Schedule* schedule = NULL);
CompilationInfo* info() const { return info_; }
Zone* zone() { return info_->zone(); }
Isolate* isolate() { return info_->isolate(); }
static inline bool SupportedBackend() { return V8_TURBOFAN_BACKEND != 0; }
static inline bool SupportedTarget() { return V8_TURBOFAN_TARGET != 0; }
static inline bool VerifyGraphs() {
#ifdef DEBUG
return true;
#else
return FLAG_turbo_verify;
#endif
}
static void SetUp();
static void TearDown();
private:
CompilationInfo* info_;
Schedule* ComputeSchedule(Graph* graph);
void VerifyAndPrintGraph(Graph* graph, const char* phase);
Handle<Code> GenerateCode(Linkage* linkage, Graph* graph, Schedule* schedule,
SourcePositionTable* source_positions);
};
}
}
} // namespace v8::internal::compiler
#endif // V8_COMPILER_PIPELINE_H_
| 28.188406 | 79 | 0.71671 | [
"object"
] |
4c1e6ec1426db4a4575501395ac3d35c19abee22 | 1,307 | h | C | source/cpp/core/IComparable.h | Glympse/CrossCompiling | 8bf179d6e07a17591a09f05b808b888d2a9785b5 | [
"MIT"
] | 15 | 2015-06-23T07:14:53.000Z | 2021-12-27T12:10:58.000Z | source/cpp/core/IComparable.h | Glympse/CrossCompiling | 8bf179d6e07a17591a09f05b808b888d2a9785b5 | [
"MIT"
] | 6 | 2016-03-02T08:15:26.000Z | 2016-04-05T21:56:45.000Z | source/cpp/core/IComparable.h | Glympse/CrossCompiling | 8bf179d6e07a17591a09f05b808b888d2a9785b5 | [
"MIT"
] | 5 | 2015-06-23T04:40:36.000Z | 2018-07-15T02:52:04.000Z | //------------------------------------------------------------------------------
//
// Copyright (c) 2014 Glympse Inc. All rights reserved.
//
//------------------------------------------------------------------------------
#ifndef ICOMPARABLE_H__GLYMPSE__
#define ICOMPARABLE_H__GLYMPSE__
namespace Glympse
{
/**
* The IComparable interface is introduced to provide additional mechanizm
* of content-oriented objects comparison, which does not conflict with
* language-specific one (Object.equals in Java and Object.Equals in C#).
*/
/*O*public**/ struct IComparable : public virtual ICommon
{
/**
* Compares this instance with the specified object and indicates if they are equal.
* In order to be equal, o must represent the same object as this instance using a class-specific comparison.
* The general contract is that this comparison should be reflexive, symmetric, and transitive.
* Also, no object reference other than NULL is equal to NULL.
*
* @param o The object to compare this instance with.
* @return Returns true if the specified object is equal to this object; false otherwise.
*/
public: virtual bool isEqual(const GCommon& o) = 0;
};
/*C*/typedef O< IComparable > GComparable;/**/
}
#endif // !ICOMPARABLE_H__GLYMPSE__
| 35.324324 | 113 | 0.629686 | [
"object"
] |
878efbd3fb5e1430623906f1641137ee8cc27349 | 1,089 | h | C | realsense2_camera/include/sensor_params.h | yushijinhun/realsense-ros | d227d612f91c83c526cc74e059f024b0d812499f | [
"Apache-2.0"
] | null | null | null | realsense2_camera/include/sensor_params.h | yushijinhun/realsense-ros | d227d612f91c83c526cc74e059f024b0d812499f | [
"Apache-2.0"
] | null | null | null | realsense2_camera/include/sensor_params.h | yushijinhun/realsense-ros | d227d612f91c83c526cc74e059f024b0d812499f | [
"Apache-2.0"
] | null | null | null | // License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2022 Intel Corporation. All Rights Reserved.
#pragma once
#include <librealsense2/rs.hpp>
#include <rclcpp/rclcpp.hpp>
#include <dynamic_params.h>
namespace realsense2_camera
{
class SensorParams
{
public:
SensorParams(std::shared_ptr<Parameters> parameters, rclcpp::Logger logger):
_logger(logger),
_parameters(parameters) {};
~SensorParams();
void registerDynamicOptions(rs2::options sensor, const std::string& module_name);
void clearParameters();
std::shared_ptr<Parameters> getParameters() {return _parameters;};
public:
rclcpp::Logger _logger;
private:
template<class T>
void set_parameter(rs2::options sensor, rs2_option option, const std::string& module_name, const std::string& description_addition="");
private:
std::shared_ptr<Parameters> _parameters;
std::vector<std::string> _parameters_names;
};
}
| 32.029412 | 147 | 0.640037 | [
"vector"
] |
8791eaa07db3af6e1efc8101741933d048dcbac3 | 7,508 | h | C | cpp/src/arrow/array/array_dict.h | timkpaine/arrow | a96297e65e17e728e4321cdecc7ace146e1363fb | [
"CC-BY-3.0",
"Apache-2.0",
"CC0-1.0",
"MIT"
] | 9,734 | 2016-02-17T13:22:12.000Z | 2022-03-31T09:35:00.000Z | cpp/src/arrow/array/array_dict.h | timkpaine/arrow | a96297e65e17e728e4321cdecc7ace146e1363fb | [
"CC-BY-3.0",
"Apache-2.0",
"CC0-1.0",
"MIT"
] | 11,470 | 2016-02-19T15:30:28.000Z | 2022-03-31T23:27:21.000Z | cpp/src/arrow/array/array_dict.h | XpressAI/arrow | eafd885e06f6bbc1eb169ed64016f804c1810bec | [
"CC-BY-3.0",
"Apache-2.0",
"CC0-1.0",
"MIT"
] | 2,637 | 2016-02-17T10:56:29.000Z | 2022-03-31T08:20:13.000Z | // 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.
#pragma once
#include <cstdint>
#include <memory>
#include "arrow/array/array_base.h"
#include "arrow/array/data.h"
#include "arrow/result.h"
#include "arrow/status.h"
#include "arrow/type.h"
#include "arrow/util/macros.h"
#include "arrow/util/visibility.h"
namespace arrow {
// ----------------------------------------------------------------------
// DictionaryArray
/// \brief Array type for dictionary-encoded data with a
/// data-dependent dictionary
///
/// A dictionary array contains an array of non-negative integers (the
/// "dictionary indices") along with a data type containing a "dictionary"
/// corresponding to the distinct values represented in the data.
///
/// For example, the array
///
/// ["foo", "bar", "foo", "bar", "foo", "bar"]
///
/// with dictionary ["bar", "foo"], would have dictionary array representation
///
/// indices: [1, 0, 1, 0, 1, 0]
/// dictionary: ["bar", "foo"]
///
/// The indices in principle may be any integer type.
class ARROW_EXPORT DictionaryArray : public Array {
public:
using TypeClass = DictionaryType;
explicit DictionaryArray(const std::shared_ptr<ArrayData>& data);
DictionaryArray(const std::shared_ptr<DataType>& type,
const std::shared_ptr<Array>& indices,
const std::shared_ptr<Array>& dictionary);
/// \brief Construct DictionaryArray from dictionary and indices
/// array and validate
///
/// This function does the validation of the indices and input type. It checks if
/// all indices are non-negative and smaller than the size of the dictionary.
///
/// \param[in] type a dictionary type
/// \param[in] dictionary the dictionary with same value type as the
/// type object
/// \param[in] indices an array of non-negative integers smaller than the
/// size of the dictionary
static Result<std::shared_ptr<Array>> FromArrays(
const std::shared_ptr<DataType>& type, const std::shared_ptr<Array>& indices,
const std::shared_ptr<Array>& dictionary);
static Result<std::shared_ptr<Array>> FromArrays(
const std::shared_ptr<Array>& indices, const std::shared_ptr<Array>& dictionary) {
return FromArrays(::arrow::dictionary(indices->type(), dictionary->type()), indices,
dictionary);
}
/// \brief Transpose this DictionaryArray
///
/// This method constructs a new dictionary array with the given dictionary
/// type, transposing indices using the transpose map. The type and the
/// transpose map are typically computed using DictionaryUnifier.
///
/// \param[in] type the new type object
/// \param[in] dictionary the new dictionary
/// \param[in] transpose_map transposition array of this array's indices
/// into the target array's indices
/// \param[in] pool a pool to allocate the array data from
Result<std::shared_ptr<Array>> Transpose(
const std::shared_ptr<DataType>& type, const std::shared_ptr<Array>& dictionary,
const int32_t* transpose_map, MemoryPool* pool = default_memory_pool()) const;
/// \brief Determine whether dictionary arrays may be compared without unification
bool CanCompareIndices(const DictionaryArray& other) const;
/// \brief Return the dictionary for this array, which is stored as
/// a member of the ArrayData internal structure
std::shared_ptr<Array> dictionary() const;
std::shared_ptr<Array> indices() const;
/// \brief Return the ith value of indices, cast to int64_t. Not recommended
/// for use in performance-sensitive code. Does not validate whether the
/// value is null or out-of-bounds.
int64_t GetValueIndex(int64_t i) const;
const DictionaryType* dict_type() const { return dict_type_; }
private:
void SetData(const std::shared_ptr<ArrayData>& data);
const DictionaryType* dict_type_;
std::shared_ptr<Array> indices_;
// Lazily initialized when invoking dictionary()
mutable std::shared_ptr<Array> dictionary_;
};
/// \brief Helper class for incremental dictionary unification
class ARROW_EXPORT DictionaryUnifier {
public:
virtual ~DictionaryUnifier() = default;
/// \brief Construct a DictionaryUnifier
/// \param[in] value_type the data type of the dictionaries
/// \param[in] pool MemoryPool to use for memory allocations
static Result<std::unique_ptr<DictionaryUnifier>> Make(
std::shared_ptr<DataType> value_type, MemoryPool* pool = default_memory_pool());
/// \brief Unify dictionaries accross array chunks
///
/// The dictionaries in the array chunks will be unified, their indices
/// accordingly transposed.
///
/// Only dictionaries with a primitive value type are currently supported.
/// However, dictionaries nested inside a more complex type are correctly unified.
static Result<std::shared_ptr<ChunkedArray>> UnifyChunkedArray(
const std::shared_ptr<ChunkedArray>& array,
MemoryPool* pool = default_memory_pool());
/// \brief Unify dictionaries accross the chunks of each table column
///
/// The dictionaries in each table column will be unified, their indices
/// accordingly transposed.
///
/// Only dictionaries with a primitive value type are currently supported.
/// However, dictionaries nested inside a more complex type are correctly unified.
static Result<std::shared_ptr<Table>> UnifyTable(
const Table& table, MemoryPool* pool = default_memory_pool());
/// \brief Append dictionary to the internal memo
virtual Status Unify(const Array& dictionary) = 0;
/// \brief Append dictionary and compute transpose indices
/// \param[in] dictionary the dictionary values to unify
/// \param[out] out_transpose a Buffer containing computed transpose indices
/// as int32_t values equal in length to the passed dictionary. The value in
/// each slot corresponds to the new index value for each original index
/// for a DictionaryArray with the old dictionary
virtual Status Unify(const Array& dictionary,
std::shared_ptr<Buffer>* out_transpose) = 0;
/// \brief Return a result DictionaryType with the smallest possible index
/// type to accommodate the unified dictionary. The unifier cannot be used
/// after this is called
virtual Status GetResult(std::shared_ptr<DataType>* out_type,
std::shared_ptr<Array>* out_dict) = 0;
/// \brief Return a unified dictionary with the given index type. If
/// the index type is not large enough then an invalid status will be returned.
/// The unifier cannot be used after this is called
virtual Status GetResultWithIndexType(const std::shared_ptr<DataType>& index_type,
std::shared_ptr<Array>* out_dict) = 0;
};
} // namespace arrow
| 41.480663 | 88 | 0.711375 | [
"object"
] |
8796a22b3ea9add141585936a7efc7816ae6a1e4 | 76,941 | c | C | jdwp/mainHandler.c | ztimekeeper/SedonaVM_Debug | c5a30d6841462574c815e2877c2e6741a4f05c00 | [
"MIT",
"AFL-3.0"
] | null | null | null | jdwp/mainHandler.c | ztimekeeper/SedonaVM_Debug | c5a30d6841462574c815e2877c2e6741a4f05c00 | [
"MIT",
"AFL-3.0"
] | null | null | null | jdwp/mainHandler.c | ztimekeeper/SedonaVM_Debug | c5a30d6841462574c815e2877c2e6741a4f05c00 | [
"MIT",
"AFL-3.0"
] | null | null | null | //#define LOG_PACKETS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <pthread.h>
#include "misc/MConstants.h"
#include "misc/MTypes.h"
#include "misc/MEventkind.h"
#include "commandsets/MCommandsets.h"
#include "commandsets/VirtualMachine.h"
#include "commandsets/ReferenceType.h"
#include "commandsets/ClassType.h"
#include "commandsets/ArrayType.h"
#include "commandsets/Method.h"
#include "commandsets/ObjectReference.h"
#include "commandsets/StringReference.h"
#include "commandsets/ThreadReference.h"
#include "commandsets/ThreadGroupReference.h"
#include "commandsets/ArrayReference.h"
#include "commandsets/ClassLoaderReference.h"
#include "commandsets/EventRequest.h"
#include "commandsets/Event.h"
#include "initializer.h"
#ifdef _WIN32
#include <winsock.h>
#include <io.h>
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <unistd.h>
#endif
#define JDWP_INIT_WAIT 1 // halt check delay
#define LOCAL_IP "127.0.0.1" // output purpose "local" or "remote"
#define PORT 8000 // default JDWP
#define HANDSHAKE_SIZE 14 // default JDWP
#define HANDSHAKE_STR "JDWP-Handshake" // default JDWP ASCII - 1 byte per char, hence 14 size byte total string
// internal forwards
#ifdef LOG_PACKETS
static void logPacket(Packet* p);
#endif // LOG_PACKETS
static void release_jdwpInitHalt();
static void jdwpSend_error(u2 errorcode);
static void sleep(long s);
static void close_socket();
// special event handler, forwarded from vm code
static void onStackOverFlow(int opcode, Cell* frame_p, Cell* stack_p);
// special event handler, forwarded from vm code
static void onNullPointerException(int opcode, Cell* frame_p, Cell* stack_p);
// terminate on fatal error
static void error_exit(char* error_message);
// jdwp packet sender
static void jdwpSend(Packet* packet);
// constants used in scope
const static u1 THREAD_COUNT = 4; // 3 here, 1 magic jni
const static u1 THREAD_GROUP_COUNT = 2;
const static u1 THREAD_GROUP_MAIN_COUNT = 2; // tgid for pid, jdwp tid and 2 magic jni
const static u1 THREAD_GROUP_SUB_COUNT = 1;
const static u1 THREAD_GROUP_MAIN_TGID = 1;
const static u1 THREAD_GROUP_SUB_TGID = 2;
// Thread constants
const static u1* MAIN_THREADGROUP_NAME = (u1*) "Main_ThreadGroup";
const static u1* SUB_THREADGROUP_NAME = (u1*) "Sub_ThreadGroup";
const static u1* MAIN_THREAD_NAME = (u1*) "SVM_Process";
const static u1* JDWP_THREAD_NAME = (u1*) "JDWP_Thread";
const static u1* MAIN_APPLICATION_NAME = (u1*) "APP_Thread";
const static u1* JNI_THREAD_NAME = (u1*) "JNI_Thread";
// CS VM VERSION constants to send
const u1* __CS_VM_VERSION_description = (u1*) "Sedona VM_DEBUG_MODE v1.28d";
const u1 __CS_VM_VERSION_jdwpMajor = 1;
const u1 __CS_VM_VERSION_jdwpMinor = 1;
const u1* __CS_VM_VERSION_vmVersion = (u1*) "1.28";
const u1* __CS_VM_VERSION_vmName = (u1*) "SedonaVM";
// Internal vars
static Packet* _MPacket; // pointer to oncommand recv packet
static Packet* _PACKET_ERROR; // constant packet error var
static pthread_t THREAD_RECV; // ref for thread start
static volatile u1 init_jdwp; // waiter till vm can be launched
static threadid_t JDWP_TID = 0; // thread id of jdwp
static threadid_t JNI_TID = 0;
#ifdef _WIN32
static SOCKET _SERVERSOCKET;
static SOCKET _CLIENTSOCKET;
static void close_socket() {
closesocket(_CLIENTSOCKET);
}
static void sleep(long s) {
Sleep(s);
}
#else
static int _SERVERSOCKET;
static int _CLIENTSOCKET;
static void close_socket() {
close(_CLIENTSOCKET);
}
#endif
// packet handler functions forwards for server usage
inline static u1 readu1() {
return PacketHandler->read_u1(_MPacket);
}
inline static u2 readu2() {
return PacketHandler->read_u2(_MPacket);
}
inline static u4 readu4() {
return PacketHandler->read_u4(_MPacket);
}
inline static uint64_t readu8() {
return PacketHandler->read_u8(_MPacket);
}
inline static u4 readlength() {
return PacketHandler->read_length(_MPacket);
}
inline static u4 readid() {
return PacketHandler->read_id(_MPacket);
}
inline static u1 readflags() {
return PacketHandler->read_flags(_MPacket);
}
inline static u2 readerrorcode() {
return PacketHandler->read_errorcode(_MPacket);
}
inline static u1 readcommand() {
return PacketHandler->read_command(_MPacket);
}
inline static u1 readcommandset() {
return PacketHandler->read_commandset(_MPacket);
}
inline static tagid_t readtag() {
return PacketHandler->read_tag(_MPacket);
}
inline static methodid_t readmethodid() {
return PacketHandler->read_methodid(_MPacket);
}
inline static fieldid_t readfieldid() {
return PacketHandler->read_fieldid(_MPacket);
}
inline static objectid_t readobjectid() {
return PacketHandler->read_objectid(_MPacket);
}
inline static threadid_t readthreadid() {
return PacketHandler->read_threadid(_MPacket);
}
inline static threadgroupid_t readthreadgroupid() {
return PacketHandler->read_threadgroupid(_MPacket);
}
inline static Location* readlocation() {
return PacketHandler->read_location(_MPacket);
}
inline static u1* readstr() {
return PacketHandler->read_str(_MPacket);
}
inline static u2* readutf() {
return PacketHandler->read_utf(_MPacket);
}
inline static Packet* newReply(size_t bytes) {
return PacketHandler->newReplyPacket(readid(), bytes);
}
inline static void jdwpSend_Not_Implemented() {
jdwpSend_error(NOT_IMPLEMENTED);
}
// START - CS-Handles: ######################## Virtual Machine ########################
// Sends the JDWP version implemented by the target VM
inline static void onSend_CS_VM_Version() {
printf("onSend_CS_VM_Version()\n");
size_t psize = string__SIZE(__CS_VM_VERSION_description) +
(int__SIZE << 1) +
string__SIZE(__CS_VM_VERSION_vmVersion) +
string__SIZE(__CS_VM_VERSION_vmName);
Packet* p = newReply(psize);
PacketHandler->write_str(p, __CS_VM_VERSION_description);
PacketHandler->write_u4 (p, __CS_VM_VERSION_jdwpMajor);
PacketHandler->write_u4 (p, __CS_VM_VERSION_jdwpMinor);
PacketHandler->write_str(p, __CS_VM_VERSION_vmVersion);
PacketHandler->write_str(p, __CS_VM_VERSION_vmName);
jdwpSend(p);
}
// Sends reference types for all the classes loaded by the target VM which match the given signature.
// Multiple reference types will be returned if two or more class loaders have loaded a class of the same name.
// The search is confined to loaded classes only; no attempt is made to load a class of the given signature.
inline static void onSend_CS_VM_ClassesBySignature() { // I need to figure out if this is needed first!
printf("onSend_CS_VM_ClassesBySignature()\n");
Packet* p;
u1* signstr = readstr();
RefTypeID* typeID = RefHandler->find_BySignature(signstr);
if(typeID == NULL) {
printf("NOT found class = %s\n", signstr);
p = newReply(int__SIZE);
PacketHandler->write_u4(p, 0);
}
else {
printf("found class = %s, clazzid = %i\n", typeID->clazzname, typeID->ref_clazzid);
p = newReply(int__SIZE + byte__SIZE + referenceTypeID__SIZE + int__SIZE);
PacketHandler->write_u4(p, 1); // classes of signature
PacketHandler->write_tag(p, TYPETAG_CLASS); // no interfaces, just classes
PacketHandler->write_objectid(p, typeID->ref_clazzid);
PacketHandler->write_u4(p, typeID->status);
}
jdwpSend(p);
}
// Sends reference types for all classes currently loaded by the target VM.
inline static void onSend_CS_VM_AllClasses() { // I need to figure out if this is needed first!
printf("onSend_CS_VM_AllClasses()\n");
PacketList* clazzes = RefHandler->allClazzRefs_to_PacketList();
Packet* p = newReply(PacketHandler->get_ByteSize(clazzes) + int__SIZE);
PacketHandler->write_u4(p, clazzes->size);
PacketHandler->write_list(p, clazzes);
jdwpSend(p);
}
// Sends all threads currently running in the target VM, No JNI natives or Multi threading
inline static void onSend_CS_VM_AllThreads() {
printf("onSend_CS_VM_AllThreads()\n");
Packet* p = newReply(int__SIZE + threadid__SIZE * THREAD_COUNT);
PacketHandler->write_u4(p, THREAD_COUNT);
PacketHandler->write_threadid(p, VMController->pid());
PacketHandler->write_threadid(p, JDWP_TID);
PacketHandler->write_threadid(p, VMController->app_tid());
if(JNI_TID != 0) { // a weirdo. i force a creation by tracking it from tgr
PacketHandler->write_threadid(p, JNI_TID);
}
jdwpSend(p);
}
inline static void onSend_CS_VM_TopLevelThreadGroups() {
printf("onSend_CS_VM_TopLevelThreadGroups()\n");
Packet* p = newReply(int__SIZE + threadGroupID__SIZE * THREAD_GROUP_COUNT);
PacketHandler->write_u4(p, THREAD_GROUP_COUNT);
PacketHandler->write_threadgroupid(p, THREAD_GROUP_MAIN_TGID);
PacketHandler->write_threadgroupid(p, THREAD_GROUP_SUB_TGID);
jdwpSend(p);
}
inline static void onSend_CS_VM_Dispose() { // Invalidates this virtual machine mirror
printf("onSend_CS_VM_Dispose()\n");
VMController->dispose();
error_exit(EXIT_SUCCESS);
}
inline static void onSend_CS_VM_IDSizes() { // Sends id sizes for fields, methods, etc
printf("onSend_CS_VM_IDSizes()\n");
// Order: fieldID, methodID, objectID, referenceTypeID, frameID
Packet* p = newReply(int__SIZE * 5);
PacketHandler->write_u4(p, fieldID__SIZE);
PacketHandler->write_u4(p, methodID__SIZE);
PacketHandler->write_u4(p, objectid__SIZE);
PacketHandler->write_u4(p, referenceTypeID__SIZE);
PacketHandler->write_u4(p, frameID__SIZE);
jdwpSend(p);
}
// Suspends the execution of the application running in the target VM
// All threads currently running will be suspended
inline static void onSend_CS_VM_Suspend() {
printf("onSend_CS_VM_Suspend()\n");
VMController->suspend();
jdwpSend(newReply(0));
}
// Resumes execution of the application after the suspend command or an event has stopped it
// Suspensions of the Virtual Machine and individual threads are counted
// If a particular thread is suspended n times, it must resumed n times before it will continue
inline static void onSend_CS_VM_Resume() {
printf("onSend_CS_VM_Resume()\n");
jdwpSend(newReply(0));
VMController->resume();
}
// Terminates the target VM with the given exit code
inline static void onSend_CS_VM_Exit() {
printf("onSend_CS_VM_Exit()\n");
Packet* p = newReply(int__SIZE);
PacketHandler->write_u4(p, 0);
jdwpSend(p);
VMController->exit();
}
// Injection, doesn't look needed at all
inline static void onSend_CS_VM_CreateString() {
printf("onSend_CS_VM_CreateString()\n");
jdwpSend_Not_Implemented();
}
// apparently this is very nice for monitoring vars
// sadly, i think this requires the jnit or whatever this tooling interface is called :/
inline static void onSend_CS_VM_Capabilities() {
printf("onSend_CS_VM_Capabilities()\n");
Packet* p = newReply(7);
PacketHandler->write_u1(p, FALSE); // canWatchFieldModification
PacketHandler->write_u1(p, FALSE); // canWatchFieldAccess
PacketHandler->write_u1(p, FALSE); // canGetBytecodes
PacketHandler->write_u1(p, TRUE); // canGetSyntheticAttribute
PacketHandler->write_u1(p, FALSE); // canGetOwnedMonitorInfo
PacketHandler->write_u1(p, FALSE); // canGetCurrentContendedMonitor
PacketHandler->write_u1(p, FALSE); // canGetMonitorInfo
jdwpSend(p);
}
// list of classpath, bootclasspath
inline static void onSend_CS_VM_ClassPaths() {
printf("onSend_CS_VM_ClassPaths()\n");
// TODO: impl.
jdwpSend_Not_Implemented();
}
inline static void onSend_CS_VM_DisposeObjects() {
printf("onSend_CS_VM_DisposeObjects()\n");
ObjectHandler->dispose();
}
inline static void onSend_CS_VM_HoldEvents() {
printf("onSend_CS_VM_HoldEvents()\n");
EventHandler->holdEvents(TRUE);
}
inline static void onSend_CS_VM_ReleaseEvents() {
printf("onSend_CS_VM_ReleaseEvents()\n");
EventHandler->holdEvents(FALSE);
}
// Since JDWP version 1.4
inline static void onSend_CS_VM_CapabilitiesNew() {
printf("onSend_CS_VM_CapabilitiesNew()\n");
Packet* p = newReply(32);
PacketHandler->write_u1(p, FALSE); // canWatchFieldModification
PacketHandler->write_u1(p, FALSE); // canWatchFieldAccess
PacketHandler->write_u1(p, FALSE); // canGetBytecodes
PacketHandler->write_u1(p, TRUE); // canGetSyntheticAttribute
PacketHandler->write_u1(p, FALSE); // canGetOwnedMonitorInfo
PacketHandler->write_u1(p, FALSE); // canGetCurrentContendedMonitor
PacketHandler->write_u1(p, FALSE); // canGetMonitorInfo
// start new ones
PacketHandler->write_u1(p, FALSE); // Can the VM redefine classes?
PacketHandler->write_u1(p, FALSE); // Can the VM add methods when redefining classes?
PacketHandler->write_u1(p, FALSE); // Can the VM redefine classesin arbitrary ways?
PacketHandler->write_u1(p, FALSE); // Can the VM pop stack frames?
PacketHandler->write_u1(p, FALSE); // Can the VM filter events by specific object?
PacketHandler->write_u1(p, FALSE); // Can the VM get the source debug extension?
PacketHandler->write_u1(p, FALSE); // Can the VM request VM death events?
PacketHandler->write_u1(p, FALSE); // Can the VM set a default stratum?
PacketHandler->write_u1(p, FALSE); // Can the VM return instances, counts of instances of classes and referring objects?
PacketHandler->write_u1(p, FALSE); // Can the VM request monitor events?
PacketHandler->write_u1(p, FALSE); // Can the VM get monitors with frame depth info?
PacketHandler->write_u1(p, FALSE); // Can the VM filter class prepare events by source name?
PacketHandler->write_u1(p, FALSE); // Can the VM return the constant pool information?
PacketHandler->write_u1(p, FALSE); // Can the VM force early return from a method?
// 11 ones reserved for future capability
PacketHandler->write_u1(p, FALSE); // Reserved22 for future capability
PacketHandler->write_u1(p, FALSE); // Reserved23 for future capability
PacketHandler->write_u1(p, FALSE); // Reserved24 for future capability
PacketHandler->write_u1(p, FALSE); // Reserved25 for future capability
PacketHandler->write_u1(p, FALSE); // Reserved26 for future capability
PacketHandler->write_u1(p, FALSE); // Reserved27 for future capability
PacketHandler->write_u1(p, FALSE); // Reserved28 for future capability
PacketHandler->write_u1(p, FALSE); // Reserved29 for future capability
PacketHandler->write_u1(p, FALSE); // Reserved30 for future capability
PacketHandler->write_u1(p, FALSE); // Reserved31 for future capability
PacketHandler->write_u1(p, FALSE); // Reserved32 for future capability
jdwpSend(p);
}
// Injection, this is so risky to allow new classes, we wont support this
// Disabled by CapabilitiesNew
// This should not be sent!
inline static void onSend_CS_VM_RedefineClasses() {
printf("onSend_CS_VM_RedefineClasses()\n");
jdwpSend_Not_Implemented(); // error code NOT defined
}
// Disabled by CapabilitiesNew
// This should not be sent!
inline static void onSend_CS_VM_SetDefaultStratum() {
printf("onSend_CS_VM_SetDefaultStratum()\n");
jdwpSend_Not_Implemented(); // error code NOT defined
}
// This is java vm specific, and i believe its not required at all (generics)
// This should not be sent!
inline static void onSend_CS_VM_AllClassesWithGeneric() {
printf("onSend_CS_VM_AllClassesWithGeneric()\n");
PacketList* clazzes = RefHandler->allClazzRefsWithGenetrics_to_PacketList();
Packet* p = newReply(PacketHandler->get_ByteSize(clazzes) + int__SIZE);
PacketHandler->write_u4(p, clazzes->size);
PacketHandler->write_list(p, clazzes);
jdwpSend(p);
}
// Disabled by CapabilitiesNew
// This should not be sent!
inline static void onSend_CS_VM_InstanceCounts() {
printf("onSend_CS_VM_InstanceCounts()\n");
jdwpSend_Not_Implemented(); // No error code defined
}
// On unknown commands in "Virtual Machine" Command Set
inline static void onSend_CS_VM_UnknownCommand() {
printf("onSend_CS_VM_UnknownCommand()\n");
jdwpSend_Not_Implemented(); // Set default error code on not implemented
}
// END - CS-Handles: ######################## Virtual Machine ########################
// Command Set "Virtual Machine" Main Handler
inline static void onCSVirtualMachine() {
printf("onCSVirtualMachine\n");
switch(readcommand()) {
case VMVERSION:
onSend_CS_VM_Version();
break;
case VMClassesBySignature:
onSend_CS_VM_ClassesBySignature();
break;
case VMAllClasses:
onSend_CS_VM_AllClasses();
break;
case VMAllThreads:
onSend_CS_VM_AllThreads();
break;
case VMTopLevelThreadGroups:
onSend_CS_VM_TopLevelThreadGroups();
break;
case VMIDSizes:
onSend_CS_VM_IDSizes();
break;
case VMDispose:
onSend_CS_VM_Dispose();
break;
case VMSuspend:
onSend_CS_VM_Suspend();
break;
case VMResume:
onSend_CS_VM_Resume();
break;
case VMExit:
onSend_CS_VM_Exit();
break;
case VMCreateString:
onSend_CS_VM_CreateString();
break;
case VMCapabilities:
onSend_CS_VM_Capabilities();
break;
case VMClassPaths:
onSend_CS_VM_ClassPaths();
break;
case VMDisposeObjects:
onSend_CS_VM_DisposeObjects();
break;
case VMHoldEvents:
onSend_CS_VM_HoldEvents();
break;
case VMReleaseEvents:
onSend_CS_VM_ReleaseEvents();
break;
case VMCapabilitiesNew:
onSend_CS_VM_CapabilitiesNew();
break;
case VMRedefineClasses:
onSend_CS_VM_RedefineClasses();
break;
case VMSetDefaultStratum:
onSend_CS_VM_SetDefaultStratum();
break;
case VMAllClassesWithGeneric:
onSend_CS_VM_AllClassesWithGeneric();
break;
case VMInstanceCounts:
onSend_CS_VM_InstanceCounts();
break;
default:
onSend_CS_VM_UnknownCommand();
break;
}
}
// START - CS-Handles: ######################## ReferenceType ########################
inline static void onSend_CS_RT_UnknownCommand() {
printf("onSend_CS_RT_UnknownCommand\n");
jdwpSend_Not_Implemented();
}
// Sends the JNI signature of a reference type
inline static void onSend_CS_RT_Signature() {
printf("onSend_CS_RT_Signature\n");
referencetypeid_t rtid = readobjectid();
RefTypeID* typeID = RefHandler->find_ByID(rtid);
printf("found typeID = %s\n", typeID->clazzname);
Packet* p = newReply(PacketHandler->utf_size(typeID->signature));
PacketHandler->write_utf(p, typeID->signature);
jdwpSend(p);
}
inline static void onSend_CS_RT_ClassLoader() {
printf("onSend_CS_RT_ClassLoader\n");
// TODO: impl. (need to meet prof. bockisch for these stuff)
jdwpSend_Not_Implemented();
}
inline static void onSend_CS_RT_Modifiers() {
printf("onSend_CS_RT_Modifiers\n");
referencetypeid_t rtid = readobjectid();
RefTypeID* typeID = RefHandler->find_ByID(rtid);
if(typeID == NULL) {
jdwpSend_error(INVALID_OBJECT);
return;
}
Packet* p = newReply(int__SIZE);
PacketHandler->write_u4(p, typeID->modBits);
jdwpSend(p);
}
inline static void onSend_CS_RT_Fields() {
printf("onSend_CS_RT_Fields\n");
referencetypeid_t rtid = readobjectid();
RefTypeID* typeID = RefHandler->find_ByID(rtid);
if(typeID == NULL) {
jdwpSend_error(INVALID_OBJECT);
return;
}
Packet* p;
if(typeID->num_fields == 0) {
p = newReply(int__SIZE);
PacketHandler->write_u4(p, 0);
}
else {
// raw bytes
PacketList* fieldBytes = RefHandler->fields_to_PacketList(typeID);
// int num of declared fields
p = newReply(int__SIZE + PacketHandler->get_ByteSize(fieldBytes));
PacketHandler->write_u4(p, typeID->num_fields);
PacketHandler->write_list(p, fieldBytes);
}
jdwpSend(p);
}
inline static void onSend_CS_RT_Methods() {
printf("onSend_CS_RT_Methods\n");
referencetypeid_t rtid = readobjectid();
RefTypeID* typeID = RefHandler->find_ByID(rtid);
if(typeID == NULL) {
jdwpSend_error(INVALID_CLASS);
return;
}
Packet* p = NULL;
if(typeID->num_methods == 0) {
p = newReply(int__SIZE);
PacketHandler->write_u4(p, 0);
}
else {
PacketList* methodRawBytes = RefHandler->methods_to_PacketList(typeID);
p = newReply(int__SIZE + PacketHandler->get_ByteSize(methodRawBytes));
PacketHandler->write_u4(p, typeID->num_methods);
PacketHandler->write_list(p, methodRawBytes);
}
jdwpSend(p);
}
inline static void onSend_CS_RT_Values() {
printf("onSend_CS_RT_Values\n");
referencetypeid_t rtid = readobjectid();
u4 fields = readu4();
fieldid_t* field_ids = (fieldid_t*) malloc(fieldID__SIZE * fields);
u4 start = 0;
while(start++ < fields) {
*field_ids = readfieldid();
field_ids++;
}
RefTypeID* typeID = RefHandler->find_ByID(rtid);
// variablehandler retrieves the values of fields! TODO :)
}
inline static void onSend_CS_RT_NestedTypes() {
printf("onSend_CS_RT_NestedTypes\n");
// no nested classes
jdwpSend_error(INVALID_CLASS);
}
inline static void onSend_CS_RT_Interfaces() {
printf("onSend_CS_RT_Interfaces\n");
referencetypeid_t rtid = readobjectid();
RefTypeID* typeID = RefHandler->find_ByID(rtid);
if(typeID == NULL) {
jdwpSend_error(INVALID_OBJECT);
return;
}
Packet* p;
u2 interfaces = typeID->num_interfaces;
if(interfaces == 0) {
p = newReply(int__SIZE);
PacketHandler->write_u4(p, 0);
}
else {
p = newReply(referenceTypeID__SIZE * interfaces + int__SIZE);
PacketHandler->write_u4(p, interfaces);
u2 start = 0;
while(start < interfaces) {
PacketHandler->write_objectid(p, typeID->interfaces[start]->ref_clazzid);
start++;
}
}
jdwpSend(p);
}
inline static void onSend_CS_RT_ClassObject() {
printf("onSend_CS_RT_ClassObject\n");
referencetypeid_t rtid = readobjectid();
RefTypeID* typeID = RefHandler->find_ByID(rtid);
if(typeID == NULL) {
jdwpSend_error(INVALID_OBJECT);
return;
}
Packet* p = newReply(referenceTypeID__SIZE);
PacketHandler->write_objectid(p, typeID->ref_clazzid);
jdwpSend(p);
}
inline static void onSend_CS_RT_SourceDebugExtension() {
printf("onSend_CS_RT_SourceDebugExtension\n");
// no extension | capability disables this anyway
jdwpSend_Not_Implemented();
}
inline static void onSend_CS_RT_SignatureWithGeneric() {
printf("onSend_CS_RT_SignatureWithGeneric\n");
referencetypeid_t rtid = readobjectid();
RefTypeID* typeID = RefHandler->find_ByID(rtid);
Packet* p = newReply(PacketHandler->utf_size(typeID->signature) + int__SIZE);
PacketHandler->write_utf(p, typeID->signature);
// always assume there is no generic!
PacketHandler->write_u4(p, 0); // empty string | generic signature
jdwpSend(p);
}
inline static void onSend_CS_RT_FieldsWithGeneric() {
printf("onSend_CS_RT_FieldsWithGeneric\n");
referencetypeid_t rtid = readobjectid();
RefTypeID* typeID = RefHandler->find_ByID(rtid);
PacketList* pList = RefHandler->fields_WithGeneric_to_PacketList(typeID);
Packet* p = newReply(PacketHandler->get_ByteSize(pList));
PacketHandler->write_list(p, pList);
jdwpSend(p);
}
inline static void onSend_CS_RT_MethodsWithGeneric() {
printf("onSend_CS_RT_MethodsWithGeneric\n");
referencetypeid_t rtid = readobjectid();
RefTypeID* typeID = RefHandler->find_ByID(rtid);
PacketList* pList = RefHandler->methods_WithGeneric_to_PacketList(typeID);
Packet* p = newReply(PacketHandler->get_ByteSize(pList));
PacketHandler->write_list(p, pList);
jdwpSend(p);
}
inline static void onSend_CS_RT_Instances() {
printf("onSend_CS_RT_Instances\n");
// disabled by capabilities
jdwpSend_Not_Implemented();
}
inline static void onSend_CS_RT_ClassFileVersion() {
printf("onSend_CS_RT_ClassFileVersion\n");
Packet* p = newReply(int__SIZE << 1);
PacketHandler->write_u4(p, __CS_VM_VERSION_jdwpMajor);
PacketHandler->write_u4(p, __CS_VM_VERSION_jdwpMinor);
jdwpSend(p);
}
inline static void onSend_CS_RT_ConstantPool() {
printf("onSend_CS_RT_ConstantPool\n");
// disabled by capabilities
jdwpSend_Not_Implemented();
}
// END - CS-Handles: ######################## ReferenceType ########################
// Command Set "ReferenceType" Main Handler
inline static void onCSReferenceType() {
printf("onCSReferenceType\n");
switch(readcommand()) {
case RTSignature:
onSend_CS_RT_Signature();
break;
case RTClassLoader:
onSend_CS_RT_ClassLoader();
break;
case RTModifiers:
onSend_CS_RT_Modifiers();
break;
case RTFields:
onSend_CS_RT_Fields();
break;
case RTMethods:
onSend_CS_RT_Methods();
break;
case RTGetValues:
onSend_CS_RT_Values();
break;
case RTNestedTypes:
onSend_CS_RT_NestedTypes();
break;
case RTInterfaces:
onSend_CS_RT_Interfaces();
break;
case RTClassObject:
onSend_CS_RT_ClassObject();
break;
case RTSourceDebugExtension:
onSend_CS_RT_SourceDebugExtension();
break;
case RTSignatureWithGeneric:
onSend_CS_RT_SignatureWithGeneric();
break;
case RTFieldsWithGeneric:
onSend_CS_RT_FieldsWithGeneric();
break;
case RTMethodsWithGeneric:
onSend_CS_RT_MethodsWithGeneric();
break;
case RTInstances:
onSend_CS_RT_Instances();
break;
case RTClassFileVersion:
onSend_CS_RT_ClassFileVersion();
break;
case RTConstantPool:
onSend_CS_RT_ConstantPool();
break;
default:
onSend_CS_RT_UnknownCommand();
break;
}
}
// START - CS-Handles: ######################## ClassType ########################
inline static void onSend_CS_CT_SuperClass() {
printf("onSend_CS_CT_SuperClass\n");
referencetypeid_t clazzid = readobjectid(); // check if has superclass
RefTypeID* typeID = RefHandler->find_ByID(clazzid);
if(typeID == NULL) {
jdwpSend_error(INVALID_OBJECT);
return;
}
Packet* p = newReply(referenceTypeID__SIZE); // No SuperClasses yet!
if(typeID->superClazz == NULL) {
PacketHandler->write_objectid(p, 0);
}
else {
PacketHandler->write_objectid(p, typeID->superClazz->ref_clazzid);
}
jdwpSend(p);
}
// Injection
// Sets the value of one or more static fields
// Each field must be member of the class type or one of its superclasses, superinterfaces, or implemented interfaces
inline static void onSend_CS_CT_SetValues() {
printf("onSend_CS_CT_SetValues\n");
// TODO: Meeting with prof. Bockisch
jdwpSend_Not_Implemented();
}
// Injection
// Allows to invoke static methods synchronously
inline static void onSend_CS_CT_InvokeMethod() {
printf("onSend_CS_CT_InvokeMethod\n");
// TODO: Meeting with prof. Bockisch
jdwpSend_Not_Implemented();
}
// Injection
inline static void onSend_CS_CT_NewInstance() {
printf("onSend_CS_CT_NewInstance\n");
// TODO: Meeting with prof. Bockisch
jdwpSend_Not_Implemented();
}
inline static void onSend_CS_CT_UnknownCommand() {
printf("onSend_CS_CT_UnknownCommand\n");
jdwpSend_Not_Implemented();
}
// END - CS-Handles: ######################## ClassType ########################
// Command Set "ClassType" Main Handler
inline static void onCSClassType() {
printf("onCSClassType\n");
switch(readcommand()) {
case CTSuperclass:
onSend_CS_CT_SuperClass();
break;
case CTSetValues:
onSend_CS_CT_SetValues();
break;
case CTInvokeMethod:
onSend_CS_CT_InvokeMethod();
break;
case CTNewInstance:
onSend_CS_CT_NewInstance();
break;
default:
onSend_CS_CT_UnknownCommand();
break;
}
}
// START - CS-Handles: ######################## ArrayType ########################
inline static void onSend_CS_AT_NewInstance() {
printf("onSend_CS_AT_NewInstance\n");
// TODO: Meeting with prof. Bockisch
jdwpSend_Not_Implemented();
}
inline static void onSend_CS_AT_UnknownCommand() {
printf("onSend_CS_AT_UnknownCommand\n");
// TODO: Meeting with prof. Bockisch
jdwpSend_Not_Implemented();
}
// END - CS-Handles: ######################## ArrayType ########################
// Command Set "ArrayType" Main Handler
inline static void onCSArrayType() {
printf("onCSArrayType\n");
switch(readcommand()) {
case ATNewInstance:
onSend_CS_AT_NewInstance();
break;
default:
onSend_CS_AT_UnknownCommand();
break;
}
}
// START - CS-Handles: ######################## InterfaceType ########################
// -------------------------------------------- This CommandSet is Empty ------------
// END - CS-Handles: ######################## InterfaceType ########################
// Command Set "InterfaceType" Main Handler
inline static void onCSInterfaceType() {
printf("onCSInterfaceType\n");
jdwpSend_Not_Implemented(); // CS is Empty!
}
// START - CS-Handles: ######################## Method ########################
// -Meta Data here-
// Sends line number information for the method, if present. The line table maps source line numbers to the initial code index of the line
// The line table is ordered by code index (from lowest to highest)
// The line number information is constant unless a new class de([Ljava/lang/String;)Vfinition is installed using RedefineClasses
inline static void onSend_CS_M_LineTable() {
printf("onSend_CS_M_LineTable\n");
referencetypeid_t rtid = readobjectid();
methodid_t mid = readmethodid();
printf("rtid = %i, mid = %i\n", rtid, mid);
method* m = RefHandler->get_method(rtid, mid);
u4 lines = m->lines;
printf("found m with lines = %i\n", lines);
Packet* p = newReply((long__SIZE << 1) + int__SIZE + (long__SIZE + int__SIZE) * lines);
PacketHandler->write_u8(p, m->startline);
PacketHandler->write_u8(p, m->endline);
PacketHandler->write_u4(p, lines);
u4 start = 0;
while(start < lines) {
PacketHandler->write_u8(p, m->lineTable[start]->lineCodeIndex);
PacketHandler->write_u4(p, m->lineTable[start]->lineNumber);
start++;
}
jdwpSend(p);
}
// -Meta Data here-
// Sends variable information for the method. The variable table includes arguments and locals declared within the method.
// For instance methods, the "this" reference is included in the table. Also, synthetic variables may be present.
inline static void onSend_CS_M_VariableTable() {
printf("onSend_CS_M_VariableTable\n");
// TO_WAIT: I need to impl. meta-data setups first
jdwpSend_Not_Implemented();
}
// Retrieve the method's bytecodes as defined in the JVM Specification.Requires canGetBytecodes capability - see CapabilitiesNew.
// Disabled by CapabilitiesNew
inline static void onSend_CS_M_Bytecodes() { // we can enable this infact, it requires Java bytecode but we can map sedona to java!!
printf("onSend_CS_M_Bytecodes\n");
// Should not be sent!
jdwpSend_Not_Implemented();
}
// Determine if this method is obsolete
// A method is obsolete if it has been replaced by a non-equivalent method using the RedefineClasses command
// We won't support this!
inline static void onSend_CS_M_IsObsolete() {
printf("onSend_CS_M_IsObsolete\n");
Packet* p = newReply(byte__SIZE);
PacketHandler->write_u1(p, FALSE); // all methods are org and no enhancements by compiler too
jdwpSend(p);
}
// Since JDWP version 1.5
// Is it supported?
inline static void onSend_CS_M_VariableTableWithGeneric() {
printf("onSend_CS_M_VariableTableWithGeneric\n");
// TODO: make sure its not supported
jdwpSend_Not_Implemented();
}
static void onSend_CS_M_UnknownCommand() {
printf("onSend_CS_M_UnknownCommand\n");
jdwpSend_Not_Implemented();
}
// END - CS-Handles: ######################## Method ########################
// Command Set "Method" Main Handler
inline static void onCSMethod() {
printf("onCSMethod\n");
switch(readcommand()) {
case MLineTable:
onSend_CS_M_LineTable();
break;
case MVariableTable:
onSend_CS_M_VariableTable();
break;
case MBytecodes:
onSend_CS_M_Bytecodes();
break;
case MIsObsolete:
onSend_CS_M_IsObsolete();
break;
case MVariableTableWithGeneric:
onSend_CS_M_VariableTableWithGeneric();
break;
default:
onSend_CS_M_UnknownCommand();
break;
}
}
// START - CS-Handles: ######################## Field ########################
// -------------------------------------------- This CommandSet is Empty ------------
// END - CS-Handles: ######################## Field ########################
// Command Set "Field" Main Handler
inline static void onCSField() {
printf("onCSField\n");
jdwpSend_Not_Implemented();
}
// START - CS-Handles: ######################## ObjectReference ########################
// Sends the runtime type of the object. The runtime type will be a class or an array.
inline static void onSend_CS_OR_ReferenceType() { // ObjectHandler will handle this!
printf("onSend_CS_OR_ReferenceType\n");
referencetypeid_t rtid = readobjectid();
RefTypeID* typeID = RefHandler->find_ByID(rtid); // assume all reftypes are objids!!!
printf("ReferenceTypeID = %i, found = %s\n", rtid, typeID != NULL ? "TRUE" : "FALSE");
if(typeID == NULL) {
jdwpSend_error(INVALID_OBJECT);
return;
}
Packet* p = newReply(tag__SIZE + referenceTypeID__SIZE);
PacketHandler->write_tag(p, TYPETAG_CLASS); // later i need to add a field for array types
PacketHandler->write_objectid(p, rtid);
jdwpSend(p);
}
// Sends Returns the value of one or more instance fields
// Each field must be member of the object's type or one of its superclasses, superinterfaces,
// or implemented interfaces. Access control is not enforced; for example, the values of private fields can be obtained.
inline static void onSend_CS_OR_GetValues() {
printf("onSend_CS_OR_GetValues\n");
// TODO: impl.
jdwpSend_Not_Implemented();
}
// Injection!
inline static void onSend_CS_OR_SetValues() {
printf("onSend_CS_OR_SetValues\n");
// TODO: impl.
jdwpSend_Not_Implemented();
}
// Returns monitor information for an object. All threads in the VM must be suspended
// Disabled by GetMonitorInfo capability
inline static void onSend_CS_OR_MonitorInfo() {
printf("onSend_CS_OR_MonitorInfo\n");
// Should not be sent!
jdwpSend_Not_Implemented();
}
// Injected! We wont support this!
inline static void onSend_CS_OR_InvokeMethod() {
printf("onSend_CS_OR_InvokeMethod\n");
// Should not be sent!
jdwpSend_Not_Implemented();
}
// Blocks GC to clean given objectid
// We just have "Static" context is valid until vm termination
inline static void onSend_CS_OR_DisableCollection() {
printf("onSend_CS_OR_DisableCollection\n");
}
// Unblocks GC to clean given objectid
// We just have "Static" context is valid until vm termination
inline static void onSend_CS_OR_EnableCollection() {
printf("onSend_CS_OR_EnableCollection\n");
}
// Determines whether an object has been garbage collected in the target VM
// We just have "Static" context is valid until vm termination
// => Anyway: We must send "false" always, to notify IDE that the objectid is not collected by GC!
inline static void onSend_CS_OR_IsCollected() {
printf("onSend_CS_OR_IsCollected\n");
objectid_t objid = readobjectid();
printf("Reporting objectID as a-live: %i\n", objid);
Packet* p = newReply(byte__SIZE);
PacketHandler->write_u1(p, FALSE);
jdwpSend(p);
}
// Disabled by canGetInstanceInfo capability
inline static void onSend_CS_OR_ReferringObjects() {
printf("onSend_CS_OR_ReferringObjects\n");
// Should not be sent!
jdwpSend_Not_Implemented();
}
inline static void onSend_CS_OR_UnknownCommand() {
printf("onSend_CS_OR_UnknownCommand\n");
jdwpSend_Not_Implemented();
}
// END - CS-Handles: ######################## ObjectReference ########################
// Command Set "ObjectReference" Main Handler
inline static void onCSObjectReference() {
printf("onCSObjectReference\n");
switch(readcommand()) {
case ORReferenceType:
onSend_CS_OR_ReferenceType();
break;
case ORGetValues:
onSend_CS_OR_GetValues();
break;
case ORSetValues:
onSend_CS_OR_SetValues();
break;
case ORMonitorInfo:
onSend_CS_OR_MonitorInfo();
break;
case ORInvokeMethod:
onSend_CS_OR_InvokeMethod();
break;
case ORDisableCollection:
onSend_CS_OR_DisableCollection();
break;
case OREnableCollection:
onSend_CS_OR_EnableCollection();
break;
case ORIsCollected:
onSend_CS_OR_IsCollected();
break;
case ORReferringObjects:
onSend_CS_OR_ReferringObjects();
break;
default:
onSend_CS_OR_UnknownCommand();
break;
}
}
// START - CS-Handles: ######################## StringReference ########################
// Sends the characters contained in the string.
inline static void onSend_CS_SR_Value() {
printf("onSend_CS_SR_Value\n");
// TODO: impl.
jdwpSend_Not_Implemented();
}
inline static void onSend_CS_SR_UnknownCommand() {
printf("onSend_CS_SR_UnknownCommand\n");
jdwpSend_Not_Implemented();
}
// END - CS-Handles: ######################## StringReference ########################
// Command Set "StringReference" Main Handler
inline static void onCSStringReference() {
printf("onCSStringReference\n");
switch(readcommand()) {
case SRValue:
onSend_CS_SR_Value();
break;
default:
onSend_CS_SR_UnknownCommand();
break;
}
}
// START - CS-Handles: ######################## ThreadReference ########################
// Sends the thread name.
inline static void onSend_CS_TR_Name() {
printf("onSend_CS_TR_Name\n");
Packet* p = NULL;
threadid_t tid = readthreadid();
printf("ThreadID = %i\n", tid);
if(VMController->pid() == tid) {
p = newReply(string__SIZE(MAIN_THREAD_NAME));
PacketHandler->write_str(p, MAIN_THREAD_NAME);
}
else if(JDWP_TID == tid) {
p = newReply(string__SIZE(JDWP_THREAD_NAME));
PacketHandler->write_str(p, JDWP_THREAD_NAME);
}
else if(VMController->app_tid() == tid) { // APP_TID
p = newReply(string__SIZE(MAIN_APPLICATION_NAME));
PacketHandler->write_str(p, MAIN_APPLICATION_NAME);
}
else if(JNI_TID == tid) {
p = newReply(string__SIZE(JNI_THREAD_NAME));
PacketHandler->write_str(p, JNI_THREAD_NAME);
}
else {
jdwpSend_error(INVALID_THREAD);
return;
}
jdwpSend(p);
}
// Danger! Just 2 Main threads are running, none can be suspended!
inline static void onSend_CS_TR_Suspend() {
printf("onSend_CS_TR_Suspend\n");
threadid_t tid = readthreadid();
if(VMController->app_tid() == tid) {
jdwpSend(newReply(0));
VMController->suspend();
}
else {
jdwpSend_error(INVALID_THREAD);
}
}
// Suspension is not valid, so resuming should not be sent!
inline static void onSend_CS_TR_Resume() {
printf("onSend_CS_TR_Resume\n");
threadid_t tid = readthreadid();
if(VMController->app_tid() == tid) {
if(VMController->suspendCount() <= 1) {
EventHandler->dispatch_THREAD_START();
}
VMController->resume();
jdwpSend(newReply(0));
}
else {
jdwpSend_error(INVALID_THREAD);
}
}
// Whether it is the Main thread of JDWP thread, we send status running!
inline static void onSend_CS_TR_Status() {
printf("onSend_CS_TR_Status\n");
threadid_t tid = readthreadid();
printf("threadid = %i\n", tid);
if(tid != VMController->app_tid() && tid != VMController->pid() && tid != JNI_TID && tid != JDWP_TID) {
jdwpSend_error(INVALID_OBJECT);
return;
}
Packet* p = newReply(int__SIZE << 1);
if(tid == VMController->app_tid()) {
VMController->suspend(); // test case
if(VMController->isSuspended()) {
PacketHandler->write_u4(p, SLEEPING);
PacketHandler->write_u4(p, SUSPEND_STATUS_SUSPENDED);
}
else {
PacketHandler->write_u4(p, RUNNING);
PacketHandler->write_u4(p, 0);
}
}
else {
PacketHandler->write_u4(p, RUNNING);
PacketHandler->write_u4(p, 0);
}
jdwpSend(p);
}
// Sends the thread group that contains a given thread
inline static void onSend_CS_TR_ThreadGroup() {
printf("onSend_CS_TR_ThreadGroup\n");
threadid_t tid = readthreadid();
Packet* p = newReply(threadGroupID__SIZE);
if(tid == VMController->app_tid()) {
PacketHandler->write_threadgroupid(p, THREAD_GROUP_SUB_TGID);
}
else {
PacketHandler->write_threadgroupid(p, THREAD_GROUP_MAIN_TGID);
if(tid != JDWP_TID && tid != VMController->pid()) {
JNI_TID = tid;
}
}
jdwpSend(p);
}
// Not sure if this is needed.. i need to check later!
inline static void onSend_CS_TR_Frames() {
printf("onSend_CS_TR_Frames\n");
Packet* p = NULL;
threadid_t tid = readthreadid();
u4 startFrame = readu4();
int32_t length = readu4();
if(length < 0){
length = VMController->get_frameCount() - startFrame;
}
printf("tid = %i, startFrame = %i, Length = %i\n", tid, startFrame, length);
p = newReply(int__SIZE + length * (frameID__SIZE + location__SIZE));
PacketHandler->write_u4(p, length);
FrameContainer** allFrames = VMController->getAllFrames();
while(startFrame < length) {
printf("frameID = %i, frameLocation_clazz = %i, frameLocation_mid = %i, frameLocation_index = %i\n",
allFrames[startFrame]->frameID,
allFrames[startFrame]->frameLocation->classID,
allFrames[startFrame]->frameLocation->methodID,
allFrames[startFrame]->frameLocation->index);
PacketHandler->write_frameid(p, allFrames[startFrame]->frameID);
PacketHandler->write_location(p, allFrames[startFrame]->frameLocation);
startFrame++;
}
jdwpSend(p);
}
inline static void onSend_CS_TR_FrameCount() {
printf("onSend_CS_TR_FrameCount\n");
threadid_t tid = readthreadid();
if(VMController->app_tid() == tid) {
Packet* p = newReply(int__SIZE);
PacketHandler->write_u4(p, VMController->get_frameCount());
jdwpSend(p);
}
else {
jdwpSend_error(INVALID_THREAD);
}
}
// Sends the objects whose monitors have been entered by this thread
// The thread must be suspended, and the returned information is relevant only while the thread is suspended
// Disabled by canGetOwnedMonitorInfo capability
inline static void onSend_CS_TR_OwnedMonitors() {
printf("onSend_CS_TR_OwnedMonitors\n");
// Should not be sent!
jdwpSend_Not_Implemented();
}
// Disabled by canGetCurrentContendedMonitor capability
inline static void onSend_CS_TR_CurrentContendedMonitor() {
printf("onSend_CS_TR_CurrentContendedMonitor\n");
// Should not be sent!
jdwpSend_Not_Implemented();
}
// Stops the thread with an asynchronous exception, as if done by java.lang.Thread.stop
// This means stop the main and only application thread? just close the whole vm then
inline static void onSend_CS_TR_Stop() {
printf("onSend_CS_TR_Stop\n");
VMController->exit();
}
// Interrupt the thread, as if done by java.lang.Thread.interrupt
// again here we usually go and terminate the thread in java, and do other stuff. in sedona theres no other stuff
inline static void onSend_CS_TR_Interrupt() {
printf("onSend_CS_TR_Interrupt\n");
VMController->exit();
}
// Get the suspend count for this thread
// The suspend count is the number of times the thread has been suspended through the thread-level
// or VM-level suspend commands without a corresponding resume
inline static void onSend_CS_TR_SuspendCount() {
printf("onSend_CS_TR_SuspendCount\n");
threadid_t tid = readthreadid();
Packet* p = newReply(int__SIZE);
if(tid == VMController->app_tid() && VMController->isSuspended()) {
PacketHandler->write_u4(p, VMController->suspendCount()); // just one, no count stuff needed.
}
else {
PacketHandler->write_u4(p, 0);
}
jdwpSend(p);
}
// Disabled by canGetMonitorFrameInfo capability
inline static void onSend_CS_TR_OwnedMonitorsStackDepthInfo() {
printf("onSend_CS_TR_OwnedMonitorsStackDepthInfo\n");
// Should not be sent!
jdwpSend_Not_Implemented();
}
// Disabled by canForceEarlyReturn capability
inline static void onSend_CS_TR_ForceEarlyReturn() {
printf("onSend_CS_TR_ForceEarlyReturn\n");
if(VMController->isSuspended() == FALSE) {
jdwpSend_error(THREAD_NOT_SUSPENDED);
return;
}
threadid_t tid = readthreadid();
if(VMController->app_tid() != tid) {
jdwpSend_error(INVALID_THREAD);
return;
}
switch(readtag()) {
case TAG_ARRAY: {
// yo
break;
}
case TAG_BYTE: {
VMController->force_ExitMethod((Cell*)readu1()); // dummy
break;
}
case TAG_CHAR: {
VMController->force_ExitMethod((Cell*)readu2()); // dummy
break;
}
case TAG_OBJECT: {
// yo
break;
}
case TAG_FLOAT: {
VMController->force_ExitMethod((Cell*)readu4());
break;
}
case TAG_DOUBLE: {
VMController->force_ExitMethod((Cell*)readu8());
break;
}
case TAG_INT: {
VMController->force_ExitMethod((Cell*)readu4());
break;
}
case TAG_LONG: {
VMController->force_ExitMethod((Cell*)readu8());
break;
}
case TAG_SHORT: {
VMController->force_ExitMethod((Cell*)readu2());
break;
}
case TAG_VOID: {
VMController->force_ExitMethod((Cell*) NULL);
break;
}
case TAG_BOOLEAN: {
VMController->force_ExitMethod((Cell*)readu1());
break;
}
case TAG_STRING: {
VMController->force_ExitMethod((Cell*)readstr());
break;
}
case TAG_THREAD: {
jdwpSend_error(TYPE_MISMATCH);
break;
}
case TAG_THREAD_GROUP: {
jdwpSend_error(TYPE_MISMATCH);
break;
}
case TAG_CLASS_LOADER: {
jdwpSend_error(TYPE_MISMATCH);
break;
}
case TAG_CLASS_OBJECT: {
// well well well...
break;
}
default: {
jdwpSend_error(INVALID_OBJECT);
break;
}
}
VMController->resume();
}
inline static void onSend_CS_TR_UnknownCommand() {
printf("onSend_CS_TR_UnknownCommand\n");
jdwpSend_Not_Implemented();
}
// END - CS-Handles: ######################## ThreadReference ########################
// Command Set "ThreadReference" Main Handler
static void onCSThreadReference() {
printf("onCSThreadReference\n");
switch(readcommand()) {
case TRName:
onSend_CS_TR_Name();
break;
case TRSuspend:
onSend_CS_TR_Suspend();
break;
case TRResume:
onSend_CS_TR_Resume();
break;
case TRStatus:
onSend_CS_TR_Status();
break;
case TRThreadGroup:
onSend_CS_TR_ThreadGroup();
break;
case TRFrames:
onSend_CS_TR_Frames();
break;
case TRFrameCount:
onSend_CS_TR_FrameCount();
break;
case TROwnedMonitors:
onSend_CS_TR_OwnedMonitors();
break;
case TRCurrentContendedMonitor:
onSend_CS_TR_CurrentContendedMonitor();
break;
case TRStop:
onSend_CS_TR_Stop();
break;
case TRInterrupt:
onSend_CS_TR_Interrupt();
break;
case TRSuspendCount:
onSend_CS_TR_SuspendCount();
break;
case TROwnedMonitorsStackDepthInfo:
onSend_CS_TR_OwnedMonitorsStackDepthInfo();
break;
case TRForceEarlyReturn:
onSend_CS_TR_ForceEarlyReturn();
break;
default:
onSend_CS_TR_UnknownCommand();
break;
}
}
// START - CS-Handles: ######################## ThreadGroupReference ########################
// Sends the thread group name
// We just have the one -> send it
inline static void onSend_CS_TGR_Name() {
printf("onSend_CS_TGR_Name\n");
threadgroupid_t tgid = readthreadgroupid();
printf("tgid = %i\n", tgid);
Packet* p;
if(tgid == THREAD_GROUP_MAIN_TGID) {
p = newReply(string__SIZE(MAIN_THREADGROUP_NAME));
PacketHandler->write_str(p, MAIN_THREADGROUP_NAME);
}
else if(tgid == THREAD_GROUP_SUB_TGID) {
p = newReply(string__SIZE(SUB_THREADGROUP_NAME));
PacketHandler->write_str(p, SUB_THREADGROUP_NAME);
}
else {
jdwpSend_error(INVALID_THREAD_GROUP);
return;
}
jdwpSend(p);
}
// Sends the thread group, if any, which contains a given thread group
// -> We just got 1 group -> send empty list
inline static void onSend_CS_TGR_Parent() {
printf("onSend_CS_TGR_Parent\n");
threadgroupid_t tgid = readthreadgroupid();
printf("TGR = %i\n", tgid);
if(tgid != THREAD_GROUP_MAIN_TGID && tgid != THREAD_GROUP_SUB_TGID) {
jdwpSend_error(INVALID_THREAD_GROUP);
return;
}
Packet* p = newReply(threadGroupID__SIZE);
PacketHandler->write_threadgroupid(p, 0);
//or null if the given thread group is a top-level thread group
jdwpSend(p);
}
// Here we just get the main threadgroupid
// We just send the 2 main threads
inline static void onSend_CS_TGR_Children() { // not sure if this is right since i count 5 but send 3
printf("onSend_CS_TGR_Children\n");
threadgroupid_t tgid = readthreadgroupid();
Packet* p;
if(tgid == THREAD_GROUP_MAIN_TGID) {
p = newReply(int__SIZE + (threadid__SIZE + int__SIZE) * THREAD_GROUP_MAIN_COUNT);
PacketHandler->write_u4(p, THREAD_GROUP_MAIN_COUNT); // childThreads number
// childThread
PacketHandler->write_threadid(p, VMController->pid());
PacketHandler->write_u4(p, 0); // childGroups
// childThread
PacketHandler->write_threadid(p, JDWP_TID);
PacketHandler->write_u4(p, 0); // childGroups
}
else if(tgid == THREAD_GROUP_SUB_TGID) {
p = newReply(int__SIZE + (threadid__SIZE + int__SIZE) * THREAD_GROUP_SUB_COUNT);
PacketHandler->write_u4(p, THREAD_GROUP_SUB_COUNT);
PacketHandler->write_threadid(p, VMController->app_tid());
PacketHandler->write_u4(p, 0);
}
else {
jdwpSend_error(INVALID_THREAD_GROUP);
return;
}
jdwpSend(p);
}
inline static void onSend_CS_TGR_UnknownCommand() {
printf("onSend_CS_TGR_UnknownCommand\n");
jdwpSend_Not_Implemented();
}
// END - CS-Handles: ######################## ThreadGroupReference ########################
// Command Set "ThreadGroupReference" Main Handler
inline static void onCSThreadGroupReference() {
printf("onCSThreadGroupReference\n");
switch(readcommand()) {
case TGRName:
onSend_CS_TGR_Name();
break;
case TGRParent:
onSend_CS_TGR_Parent();
break;
case TGRChildren:
onSend_CS_TGR_Children();
break;
default:
onSend_CS_TGR_UnknownCommand();
break;
}
}
// START - CS-Handles: ######################## ArrayReference ########################
// Sends the number of components in a given array
// @Out Data: ArrayID (objectid)
inline static void onSend_CS_AR_Length() {
objectid_t o_id = readobjectid();
Variable* var = ObjectHandler->get(o_id);
Packet* p;
if(var == NULL || !ObjectHandler->isArray(var)) {
jdwpSend_error(INVALID_OBJECT);
return;
}
p = newReply(int__SIZE);
PacketHandler->write_u4(p, var->v_size);
jdwpSend(p);
}
// Sends a range of array components. The specified range must be within the bounds of the array.
// @Out Data: ArrayID (objectid), int: first_index, int:length
// @Reply Data: The get values. If the values are objects, they are tagged-values; otherwise, they are untagged-values
inline static void onSend_CS_AR_GetValues() {
objectid_t o_id = readobjectid();
u4 firstIndex = readu4();
u4 length = readu4();
Variable* var = ObjectHandler->get(o_id);
// switch type and call type getter from variable handler
if(var == NULL || !ObjectHandler->isArray(var)) {
jdwpSend_error(INVALID_ARRAY);
return;
}
jdwpSend_Not_Implemented();
}
// END - CS-Handles: ######################## ArrayReference ########################
// Command Set "ArrayReference" Main Handler
inline static void onCSArrayReference() {
printf("onCSArrayReference\n");
switch(readcommand()) {
case ARLength:
onSend_CS_AR_Length();
break;
case ARGetValues:
onSend_CS_AR_GetValues();
break;
case ARSetValues:
break;
default:
break;
}
}
// START - CS-Handles: ######################## ClassLoaderReference ########################
inline static void onSend_CS_CLR_VisibleClasses() {
printf("onSend_CS_CLR_VisibleClasses\n");
jdwpSend_error(INVALID_CLASS_LOADER);
}
inline static void onSend_CS_CLR_UnknownCommand() {
printf("onSend_CS_CLR_UnknownCommand\n");
jdwpSend_Not_Implemented();
}
// END - CS-Handles: ######################## ClassLoaderReference ########################
// Command Set "ClassLoaderReference" Main Handler
inline static void onCSClassLoaderReference() {
printf("onCSClassLoaderReference\n");
switch(readcommand()) {
case CLRVisibleClasses:
onSend_CS_CLR_VisibleClasses();
break;
default:
onSend_CS_CLR_UnknownCommand();
break;
}
}
// START - CS-Handles: ######################## EventRequest ########################
// Basic functionality, this needs to be expanded later on!
inline static void onSend_CS_ER_Set() {
printf("onSend_CS_ER_Set\n");
EventRequest* e = EventHandler->newEvent();
e->eventKind = readu1();
e->suspendPolicy = readu1();
e->modCount = readu4();
switch(e->eventKind) { // always mute these events, they never occur in a Sedona application
case VM_DEATH:
case THREAD_DEATH_END:
case EXCEPTION:
case CLASS_UNLOAD:
//e->isremoved = TRUE;
e->triggered = FALSE;
break;
}
printf("EventRequest received: %s\n", EventHandler->eventKind_to_cstr(e->eventKind));
if(e->modCount > 0) {
u4 modifiers_start = 0;
while(modifiers_start < e->modCount) {
switch(readu1()) { // modKind u1 byte
case MODKIND_COUNT: { // 1
e->mods[modifiers_start].count.count = readu4();
printf("MODKIND_COUNT: count = %i\n", e->mods[modifiers_start].count.count);
break;
}
case MODKIND_Conditional: { // 2
e->mods[modifiers_start].conditional.exprId = readu4();
printf("MODKIND_Conditional: exprid = %i\n", e->mods[modifiers_start].conditional.exprId);
break;
}
case MODKIND_ThreadOnly: { // 3
e->mods[modifiers_start].threadOnly.threadId = readthreadid();
printf("MODKIND_ThreadOnly: threadid = %i\n", e->mods[modifiers_start].threadOnly.threadId);
break;
}
case MODKIND_ClassOnly: { // 4
e->mods[modifiers_start].classOnly.refTypeId = readobjectid();
printf("MODKIND_ClassOnly: clazzid = %i\n", e->mods[modifiers_start].classOnly.refTypeId);
break;
}
case MODKIND_ClassMatch: { // 5
e->mods[modifiers_start].classMatch.classPattern = readstr();
printf("MODKIND_ClassMatch: classPattern = %s\n", e->mods[modifiers_start].classMatch.classPattern);
// skip inner classes ?
if(strchr(e->mods[modifiers_start].classMatch.classPattern, '*') != NULL) {
printf("MODKIND_ClassMatch: *stared* classPattern = %s\n", e->mods[modifiers_start].classMatch.classPattern);
size_t lenstr = strlen(e->mods[modifiers_start].classMatch.classPattern);
if(e->mods[modifiers_start].classMatch.classPattern[lenstr - 2] == '$') { // star only -> all classes?
e->mods[modifiers_start].classMatch.classPattern[lenstr - 2] = '\0';
}
else {
e->mods[modifiers_start].classMatch.classPattern[lenstr - 1] = '\0';
}
printf("MODKIND_ClassMatch: unstared classPattern = %s\n", e->mods[modifiers_start].classMatch.classPattern);
}
else {
printf("MODKIND_ClassMatch: regular classPattern = %s\n", e->mods[modifiers_start].classMatch.classPattern);
}
RefTypeID* typeID = RefHandler->find_ByClazzname(e->mods[modifiers_start].classMatch.classPattern);
if(typeID == NULL) {
//e->isremoved = TRUE;
//e->triggered = FALSE;
// why am i getting weirdos?
jdwpSend_error(INVALID_CLASS);
break;
}
break;
}
case MODKIND_ClassExclude: { // 6
e->mods[modifiers_start].classExclude.classPattern = readstr();
printf("MODKIND_ClassExclude: classPattern = %s\n", e->mods[modifiers_start].classExclude.classPattern);
break;
}
case MODKIND_LocationOnly: { // 7
e->mods[modifiers_start].locationOnly.loc = *readlocation();
if(e->eventKind == BREAKPOINT) {
printf("MODKIND_LocationOnly: clazzid = %i, mid = %i, index = %i, tagID = %i\n",
e->mods[modifiers_start].locationOnly.loc.classID,
e->mods[modifiers_start].locationOnly.loc.methodID,
e->mods[modifiers_start].locationOnly.loc.index,
e->mods[modifiers_start].locationOnly.loc.tag);
}
break;
}
case MODKIND_ExceptionOnly: { // 8
e->mods[modifiers_start].exceptionOnly.refTypeId = readobjectid();
e->mods[modifiers_start].exceptionOnly.caught = readu1();
e->mods[modifiers_start].exceptionOnly.uncaught = readu1();
e->isremoved = TRUE;
e->triggered = FALSE;
printf("MODKIND_ExceptionOnly: clazzid = %i, caught = %i, uncaught = %i\n",
e->mods[modifiers_start].exceptionOnly.refTypeId,
e->mods[modifiers_start].exceptionOnly.caught,
e->mods[modifiers_start].exceptionOnly.uncaught);
break;
}
case MODKIND_FieldOnly: { // 9
e->mods[modifiers_start].fieldOnly.refTypeId = readobjectid();
e->mods[modifiers_start].fieldOnly.fieldId = readfieldid();
printf("MODKIND_FieldOnly: clazzid = %i, fieldid = %i\n",
e->mods[modifiers_start].fieldOnly.refTypeId,
e->mods[modifiers_start].fieldOnly.fieldId);
break;
}
case MODKIND_Step: { // 10
e->mods[modifiers_start].step.threadId = readthreadid();
e->mods[modifiers_start].step.size = readu4();
e->mods[modifiers_start].step.depth = readu4();
printf("MODKIND_Step: threadid = %i, size = %i, depth = %i\n",
e->mods[modifiers_start].step.threadId,
e->mods[modifiers_start].step.size,
e->mods[modifiers_start].step.depth);
break;
}
case MODKIND_InstanceOnly: { // 11
e->mods[modifiers_start].instanceOnly.objectId = readobjectid();
printf("MODKIND_InstanceOnly: clazzid = %i\n", e->mods[modifiers_start].instanceOnly.objectId);
break;
}
case MODKIND_SourceNameMatch: { // 12
e->mods[modifiers_start].sourceNameMatch.sourceNamePattern = readstr();
printf("MODKIND_InstanceOnly: sourceNamePattern = %s\n", e->mods[modifiers_start].sourceNameMatch.sourceNamePattern);
break;
}
default: {
printf("Error at parsing modKinds in EventRequest CommandSet!\n");
break;
}
}
modifiers_start++;
}
}
if(e->isremoved == FALSE) {
EventHandler->add(e);
}
Packet* p = newReply(int__SIZE);
PacketHandler->write_u4(p, e->requestId);
jdwpSend(p);
//if(e->eventKind == THREAD_START && init_jdwp == FALSE) {
//EventHandler->dispatch_VM_INIT();
//release_jdwpInitHalt();
//}
}
inline static void onSend_CS_ER_Clear() {
printf("onSend_CS_ER_Clear\n");
u1 eventKind = readu1(); // skip EventKind
u4 requestID = readu4();
EventHandler->remove(eventKind, requestID);
jdwpSend(newReply(0));
}
inline static void onSend_CS_ER_ClearAllBreakpoints() {
printf("onSend_CS_ER_ClearAllBreakpoints\n");
EventHandler->removeAllEventKind(BREAKPOINT);
}
inline static void onSend_CS_ER_UnknownCommand() {
printf("onSend_CS_CLR_UnknownCommand\n");
jdwpSend_Not_Implemented();
}
// END - CS-Handles: ######################## EventRequest ########################
// Command Set "EventRequest" Main Handler
inline static void onCSEventRequest() {
printf("onCSEventRequest\n");
switch(readcommand()) {
case ERSet:
onSend_CS_ER_Set();
break;
case ERClear:
onSend_CS_ER_Clear();
break;
case ERClearAllBreakpoints:
onSend_CS_ER_ClearAllBreakpoints();
break;
default:
onSend_CS_ER_UnknownCommand();
break;
}
}
// Command Set "StackFrame" Main Handler
inline static void onCSStackFrame() {
printf("onCSStackFrame\n");
}
// Command Set "ClassObjectReference" Main Handler
inline static void onCSClassObjectReference() {
printf("onCSClassObjectReference\n");
}
inline static void onSend_CS_E_UnknownCommand() {
printf("onSend_CS_E_UnknownCommand\n");
jdwpSend_Not_Implemented();
}
// UNKNOWN Command Set Main Handler
inline static void onCSUnknown() {
printf("onCSUnknown\n");
jdwpSend_Not_Implemented();
}
// CommandSet classifier
inline static void onCommand() {
switch(readcommandset()) { // CommandSet classification
case CSVirtualMachine:
onCSVirtualMachine();
break;
case CSReferenceType:
onCSReferenceType();
break;
case CSClassType:
onCSClassType();
break;
case CSArrayType:
onCSArrayType();
break;
case CSInterfaceType:
onCSInterfaceType();
break;
case CSMethod:
onCSMethod();
break;
case CSField:
onCSField();
break;
case CSObjectReference:
onCSObjectReference();
break;
case CSStringReference:
onCSStringReference();
break;
case CSThreadReference:
onCSThreadReference();
break;
case CSThreadGroupReference:
onCSThreadGroupReference();
break;
case CSArrayReference:
onCSArrayReference();
break;
case CSClassLoaderReference:
onCSClassLoaderReference();
break;
case CSEventRequest:
onCSEventRequest();
break;
case CSStackFrame:
onCSStackFrame();
break;
case CSClassObjectReference:
onCSClassObjectReference();
break;
default:
onCSUnknown();
break;
}
}
inline static void onPacket() {
if(PacketHandler->isPacketReply(_MPacket)) {
printf("Received a replyPacket! VM-Client mode not supported!\n");
jdwpSend_error(SCHEMA_CHANGE_NOT_IMPLEMENTED);
}
else {
onCommand();
}
}
inline static void readStream(u4 count, u1* mbuff) {
if(recv(_CLIENTSOCKET, mbuff, count, 0) <= 0) // -1 Error/Disconnected, 0 Remote Client closed connection
error_exit("[readStream()] - IDE disconnected, SVM terminating...");
}
// implements extern functions
inline static u1 is_initedJDWP() { // returns jdwp init status, to break halter on application launcher
return init_jdwp;
}
// check mpayload cap
inline static void ensurePayloadCap(u1* buff, u4* mbuff_size, u4 pLen) {
if(*mbuff_size < pLen) {
buff = (u1*) malloc(pLen - MIN_PACKET_SIZE);
*mbuff_size = pLen - MIN_PACKET_SIZE;
}
}
// OnReceive__CommandPacket Main Handler
inline static void onReceive() {
u4 mbuff_size = 0; // let this by dynamic, rather than init value
u4 pLen = 0;
u1* mheader = (u1*) malloc(MIN_PACKET_SIZE);
u1* mpayload = (u1*) malloc(mbuff_size);
release_jdwpInitHalt();
while(TRUE) {
readStream(MIN_PACKET_SIZE, mheader);
pLen = PacketHandler->read_u4_buff(mheader + LENGTH_POS);
ensurePayloadCap(mpayload, &mbuff_size, pLen);
if(pLen < MIN_PACKET_SIZE) { // crap received <.<
printf("[onReceive()] - Packet size Failure!\n");
jdwpSend_error(SCHEMA_CHANGE_NOT_IMPLEMENTED);
continue;
}
else if(pLen > MIN_PACKET_SIZE) { // read payload
readStream(pLen - MIN_PACKET_SIZE, mpayload);
_MPacket = PacketHandler->newPacketFromHeaderPayload(mheader, mpayload);
}
else {
_MPacket = PacketHandler->newPacketFromHeader(mheader);
}
onPacket();
}
}
// Handles the first must packet, which is a custom handshake-packet, to identify the IDE(debugger) is running JDWP
// Then he jumps to onCommand() which handles any upcoming CommandPacket
// NOTE: On this routine, TCP is established but we require a second custom handshake in JDWP given format
inline static void onHandShake() {
#ifdef _WIN32
JDWP_TID = (threadid_t) GetCurrentThreadId();
#else
JDWP_TID = (threadid_t) pthread_getthreadid_np();
#endif
printf("####################################################\n");
printf("[onHandShake()] - Waiting for ASCII Handshake = '%s'\n", HANDSHAKE_STR);
u1* hbuffer = (u1*) malloc(HANDSHAKE_SIZE);
readStream(HANDSHAKE_SIZE, hbuffer); // ASCII here
printf("[onHandShake()] - Handshake received, validating...\n");
if(strcmp(hbuffer, HANDSHAKE_STR) == 0) { // ensure the packet was HANDSHAKE_SIZE
printf("[onHandShake()] - Handshake is valid, VM_DEBUG_MODE Active\n");
send(_CLIENTSOCKET, hbuffer, HANDSHAKE_SIZE, 0);
free(hbuffer);
EventHandler->dispatch_VM_INIT();
onReceive();
}
else
error_exit("[onHandShake()] - Handshake failed, SVM terminating...\n");
}
#ifdef LOG_PACKETS
inline static void log_header(FILE* fp, Packet* p) {
u1* header;
u1* formatedheader;
if(PacketHandler->isPacketCommand(p)) {
header = "Header:\n\tLength = %u\n\tID = %u\n\tFlags = %d\n\tCommandSet = %i\n\tCommand = %i\n";
formatedheader = (u1*) malloc(strlen(header) + 4 + 4 + 4 + 4 + 4);
sprintf(formatedheader, header, read_length(p), read_id(p), read_flags(p), read_commandset(p), read_command(p));
}
else {
header = "Header:\n\tLength = %u\n\tID = %u\n\tFlags = %i\n\tErrorcode = %i\n";
formatedheader = (u1*) malloc(strlen(header) + 4 + 4 + 4 + 4 + 4);
sprintf(formatedheader, header, read_length(p), read_id(p), read_flags(p), read_errorcode(p));
}
fwrite(formatedheader, byte__SIZE, strlen(formatedheader), fp);
}
inline static void log_data(FILE* fp, Packet* p) {
if(p->offset == MIN_PACKET_SIZE) {
fwrite("DATA: [-]\n---------------------------------\n\n", byte__SIZE, 45, fp);
return;
}
fwrite("DATA: [", byte__SIZE, 7, fp);
u4 start = DATA_VARIABLE_POS;
u4 count = p->offset;
while(start < count) {
if(start + 1 < count) {
fprintf(fp, "%i, ", p->data[start]);
}
else {
fprintf(fp, "%i]", p->data[start]);
}
start++;
}
fwrite("\n---------------------------------\n\n", byte__SIZE, 36, fp);
}
inline static void logPacket(Packet* p) {
FILE* fp_vm = fopen("log_packets\\vm_packets.plog", "ab+");
FILE* fp_ide = fopen("log_packets\\ide_packets.plog", "ab+");
log_header(fp_vm, p);
log_header(fp_ide, _MPacket);
log_data(fp_vm, p);
log_data(fp_ide, _MPacket);
fflush(fp_vm);
fflush(fp_ide);
fclose(fp_vm);
fclose(fp_ide);
}
#endif // LOG_PACKETS
inline static void release_jdwpInitHalt() {
printf("----## Application execution halt released, application running ##----\n");
init_jdwp = TRUE; // declare VM as setup and release halt on main program executer
}
inline static void jdwpSend_error(u2 errorcode) {
PacketHandler->write_errorcode(_PACKET_ERROR, errorcode);
PacketHandler->write_id(_PACKET_ERROR, readid());
send(_CLIENTSOCKET, _PACKET_ERROR->data, MIN_PACKET_SIZE, 0);
#ifdef LOG_PACKETS
logPacket(_PACKET_ERROR);
#endif
}
inline static void error_exit(char* error_message) {
close_socket();
#ifdef _WIN32
fprintf(stderr, "%s: %d\n", error_message, WSAGetLastError());
#else
fprintf(stderr, "%s: %s\n", error_message, strerror(errno));
#endif
exit(EXIT_FAILURE);
}
// Main init. routine. Called by VM is running in VM_DEBUG_MODE
void init_mainHandler() {
MHandler->onStackOverFlow = onStackOverFlow;
MHandler->onNullPointerException = onNullPointerException;
MHandler->error_exit = error_exit;
MHandler->jdwpSend = jdwpSend;
_PACKET_ERROR = PacketHandler->newReplyPacket(0, 0); // must be handler!
init_jdwp = FALSE;
struct sockaddr_in server_addr;
struct sockaddr_in client_addr;
unsigned int clientaddrsize;
#ifdef _WIN32
WORD wVersionRequested;
WSADATA wsaData;
wVersionRequested = MAKEWORD(1, 1);
if(WSAStartup(wVersionRequested, &wsaData) != 0)
error_exit("[init. JDWP()] - WINDOWS: Fatal error of Winsock, SVM terminating...");
else
printf("[init. JDWP()] - WINDOWS: Winsock is up\n");
#endif
_SERVERSOCKET = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if(_SERVERSOCKET < 0)
error_exit("[init. JDWP()] - Fatal error, socket creation failed, SVM terminating...");
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET; // TCP
server_addr.sin_addr.s_addr = htonl(INADDR_ANY); // all
server_addr.sin_port = htons(PORT); // big endian port short
if(bind(_SERVERSOCKET, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0)
error_exit("[init. JDWP()] - Error at binding socket to address, SVM terminating...");
if(listen(_SERVERSOCKET, 0) == -1) // backlog, no queuing here
error_exit("[init. JDWP()] - Listening for connections failed, SVM terminating...");
printf("[init. JDWP()] - Listening on %s:%i - Waiting for IDE...\n", LOCAL_IP, PORT);
clientaddrsize = sizeof(client_addr);
_CLIENTSOCKET = accept(_SERVERSOCKET, (struct sockaddr*)&client_addr, &clientaddrsize);
if(_CLIENTSOCKET < 0)
error_exit("[init. JDWP()] - Couldn't accept IDE incoming connection, SVM terminating...");
char* client_ip = inet_ntoa(client_addr.sin_addr); // get client/ide ip address
if(strncmp(client_ip, LOCAL_IP, sizeof(LOCAL_IP)) == 0) // check if is local or remote
printf("[init. JDWP()] - IDE connected locally from IP: %s\n", client_ip);
else
printf("[init. JDWP()] - IDE connected from a #Remote# IP: %s\n", client_ip);
if(pthread_create(&THREAD_RECV, NULL, &onHandShake, NULL) != 0) // if thread creation failed
error_exit("[init. JDWP()] - Couldn't create recieve loop into thread, SVM terminating...");
while(is_initedJDWP() == FALSE) { // halter, flows once IDE HandShaked
sleep(JDWP_INIT_WAIT);
}
}
// extern error handlers
inline static void onStackOverFlow(int opcode, Cell* fp, Cell* sp) {
EventRequest* e = EventHandler->newEvent();
e->requestId = 0;
e->eventKind = EXCEPTION;
e->suspendPolicy = SP_ALL;
e->mods[0].exceptionOnly.refTypeId = RefHandler->find_ByClazzname("java.lang.Error")->ref_clazzid;
EventHandler->dispatch(e);
}
inline static void onNullPointerException(int opcode, Cell* fp, Cell* sp) {
EventRequest* e = EventHandler->newEvent();
e->requestId = 0;
e->eventKind = EXCEPTION;
e->suspendPolicy = SP_ALL;
e->mods[0].exceptionOnly.refTypeId = RefHandler->find_ByClazzname("java.lang.Error")->ref_clazzid;
EventHandler->dispatch(e);
}
// packet sender
inline static void jdwpSend(Packet* packet) {
PacketHandler->write_length(packet, packet->offset);
send(_CLIENTSOCKET, packet->data, packet->offset, 0);
#ifdef LOG_PACKETS
logPacket(packet);
#endif
// lets free it
free(packet->data);
free(packet);
}
| 32.05875 | 138 | 0.632277 | [
"object"
] |
8797636bd5de9d1df9017dcea7361f47e193262d | 4,449 | h | C | Lite Foundation/Source/LFAutoreleasePool.h | JustSid/Lite-C | 3ae5cc2fda2ebcd4f5b0f532ffec8a37e37512b6 | [
"MIT"
] | 1 | 2021-12-31T16:30:38.000Z | 2021-12-31T16:30:38.000Z | Lite Foundation/Source/LFAutoreleasePool.h | JustSid/Lite-C | 3ae5cc2fda2ebcd4f5b0f532ffec8a37e37512b6 | [
"MIT"
] | null | null | null | Lite Foundation/Source/LFAutoreleasePool.h | JustSid/Lite-C | 3ae5cc2fda2ebcd4f5b0f532ffec8a37e37512b6 | [
"MIT"
] | null | null | null | //
// LFAutoreleasePool.h
// Lite Foundation
//
// Copyright (c) 2011 by Sidney Just
// 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 _LFAUTORELEASEPOOL_H_
#define _LFAUTORELEASEPOOL_H_
/**
* @defgroup LFAutoreleasePoolRef LFAutoreleasePoolRef
* @{
* @brief The LFAutoreleasePoolRef is a special class that collects objects and releases them at a later point
*
* The LFAutoreleasePoolRef stores objects and sends them at a later time a release message. It is useful to relinquish the ownership of an object without risking
* to shorten its lifetime. Usually the opposite is the case, in which a autorelease pool extends an objects lifetime.
* <br />
* <br />
* You can add objects to an LFAutoreleasePool multiple times, for every time the object is added to the pool, it will receive an release call when the pool gets drained.
* You usually use the LFAutorelease() function to add an object to the topmost pool, this relinqusihes your ownership of the object like a release call but keeps the object alive.
* When the pool receives a LFAutoreleasePoolDrain() call or gets deallocated, it will send a release method to every stored object.
* @sa LFAutoreleasePoolDrain()
* @sa LFAutorelease()
*/
#include "LFBase.h"
#include "LFRuntime.h"
/**
* @brief The autorelease pools layout
*
* While the internal layout of the LFAutoreleasePool class is open, you should neither depend on it nor alter it!
* The layout might change at any time.
**/
struct __LFAutoreleasePool
{
LFRuntimeBase base;
/**
* The previous top most pool
**/
struct __LFAutoreleasePool *prev;
void *thread;
/**
* The buffer holding the objects
**/
LFTypeRef *objects;
/**
* The number of objects in the buffer
**/
LFIndex count;
/**
* The capacity of the buffer
**/
LFIndex capacity;
};
/**
* The autorelease pool type
**/
typedef struct __LFAutoreleasePool* LFAutoreleasePoolRef;
/**
* Returns the type ID of the autorelease pool class. Can be used to create new instances.
**/
LF_EXPORT LFTypeID LFAutoreleasePoolGetTypeID();
/**
* Creates a new autorelease pool and makes it the topmost one
**/
LF_EXPORT LFAutoreleasePoolRef LFAutoreleasePoolCreate();
/**
* Returns the topmost autorelease pool.
**/
LF_EXPORT LFAutoreleasePoolRef LFAutoreleasePoolGetCurrentPool();
/**
* Sends a release message to every stored object and then clears the buffer.
* @remark When you are doing heavy memory allocations repeatly in a loop, its often a good idea to wrap the loop in an pool and draining it at the end of every iteration to avoid memory spikes
* @remark The pool is automatically drained on its deallocation.
**/
LF_EXPORT void LFAutoreleasePoolDrain(LFAutoreleasePoolRef pool);
/**
* Adds an object to the autorelease pool. For every time you add the object into the pool, it will receive a release message when the pool is drained.
* @remark Usually you don't need to call this method but use LFAutorelease() which is slightly faster
* @remark Adding an autorelease pool will raise in an assertion.
* @sa LFAutoreleasePoolDrain()
* @sa LFAutorelease()
**/
LF_EXPORT void LFAutoreleasePoolAddObject(LFAutoreleasePoolRef pool, LFTypeRef object);
/**
* Adds the object to the topmost autorelease pool
* @return Returns the same object you passed, this is useful in nested function calls.
**/
LF_EXPORT LFTypeRef LFAutorelease(LFTypeRef object);
/**
* @}
**/
#endif
| 38.686957 | 193 | 0.756125 | [
"object"
] |
87a14f0607a35a41b562b647f94b92cdc9b74d3c | 807 | h | C | Big2lib/Big2lib/Player.h | ISDProjectGp/Big2 | d776d6fcdaa6faa9a63ab6e8a8b80ecb10a1e436 | [
"Apache-2.0"
] | null | null | null | Big2lib/Big2lib/Player.h | ISDProjectGp/Big2 | d776d6fcdaa6faa9a63ab6e8a8b80ecb10a1e436 | [
"Apache-2.0"
] | null | null | null | Big2lib/Big2lib/Player.h | ISDProjectGp/Big2 | d776d6fcdaa6faa9a63ab6e8a8b80ecb10a1e436 | [
"Apache-2.0"
] | null | null | null | #ifndef _ABSTRACT_PLAYER_H_
#define _ABSTRACT_PLAYER_H_
#include "AbstractPlayer.h"
#include "Hand.h"
using namespace AbstractPlayerCode;
using namespace HandCode;
namespace PlayerCode {
// The class of player , store his hand //
class Player : public AbstractPlayer
{
private:
Hand* _hand; // Pointer point to player's hand //
public:
/*
* Init the player
* @note create the hand object
*/
Player();
/*
* Destruct the Player
* @note Delete the hand object in player
*/
~Player();
/*
* Caculate the total score of the player
* @note Each call will (Total score - Penalty score)
*/
virtual void win();
/*
* Get the address of the hand object in player
* @return the address of the hand object
*/
Hand& gethand();
};
}
#endif
| 17.543478 | 71 | 0.651797 | [
"object"
] |
87a7aff6e114beba388ee1039994410cef41fec5 | 7,507 | h | C | logdevice/common/RecoveryNode.h | mickvav/LogDevice | 24a8b6abe4576418eceb72974083aa22d7844705 | [
"BSD-3-Clause"
] | 1 | 2021-05-19T23:01:58.000Z | 2021-05-19T23:01:58.000Z | logdevice/common/RecoveryNode.h | mickvav/LogDevice | 24a8b6abe4576418eceb72974083aa22d7844705 | [
"BSD-3-Clause"
] | null | null | null | logdevice/common/RecoveryNode.h | mickvav/LogDevice | 24a8b6abe4576418eceb72974083aa22d7844705 | [
"BSD-3-Clause"
] | null | null | null | /**
* Copyright (c) 2017-present, Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include "logdevice/common/Address.h"
#include "logdevice/common/ExponentialBackoffTimer.h"
#include "logdevice/common/SocketCallback.h"
#include "logdevice/common/protocol/MessageType.h"
namespace facebook { namespace logdevice {
class EpochRecovery;
/**
* @file a RecoveryNode represents a storage node as a participant in the
* recovery of a particular epoch of a log. Each RecoveryNode object is
* a member of exactly one RecoverySet.
*/
class RecoveryNode {
public:
/**
* @param shard ID of the shard
* @param recovery EpochRecovery to which this RecoveryNode belongs
*/
RecoveryNode(ShardID shard, EpochRecovery* recovery);
~RecoveryNode();
// the state of this node with respect to a particular epoch recovery
enum class State : uint8_t {
// SEAL sent but SEALED has not yet been received for the node
SEALING = 0,
// SEALED has been received along with its local tail attribute (e.g., lng)
SEALED,
// START has been sent, updating digest with records from node
DIGESTING,
// All records in the range ]LNG, (next-epoch,0)[ stored on this shard
// have been received and applied to the digest.
DIGESTED,
// The node has finished digest and is eligible for participating in
// mutations (e.g., can accept writes). The node will always be in the
// mutation set in the mutation phase, and epoch recovery may perform
// mutation on it.
MUTATABLE,
// CLEAN has been sent to node
CLEANING,
// CLEANED(success) has been received
CLEAN,
// the number of states, must be last
Count
};
ShardID getShardID() const {
return shard_;
}
NodeID getNodeID() const {
return nid_;
}
State getState() const {
return state_;
}
/**
* Perform a state transition into @param state. If state is DIGESTING or
* CLEAN, this involves sending a START or CLEAN message respectively
* The parameters of those messages are determined by the state of recovery_.
*/
void transition(State state);
/**
* This function must be called only if this RecoveryNode is in
* state DIGESTING or CLEANING. Moreover, it must have sent a START
* (or CLEAN respectively) to nid_ and must be waiting for a
* reply. The Socket to nid_ must still be connected.
*
* The function activates the resend_ timer. Upon expiration the
* timer will try to resend the START or CLEAN, depending on the
* current state.
*/
void resendMessage();
/**
* Called by the onSent() of a START or CLEAN message previously sent by this
* RecoveryNode.
*
* @param type type of message: START or CLEAN
* @param status OK if message was passed to TCP, otherwise one of the
* error codes documented for Message::onSent().
* @param rsid if @param type is START, the stream id in the START header
*/
void onMessageSent(MessageType type,
Status status,
read_stream_id_t rsid = READ_STREAM_ID_INVALID);
/**
* EpochRecovery uses this in order to check that a STARTED, RECORD or
* GAP that it got from nid_ is not stale.
*
* @param rsid the read stream to which the STARTED, RECORD, or GAP
* belongs
*/
bool digestingReadStream(read_stream_id_t rsid) const;
/**
* If this node is in the DIGESTING state, returns the read stream id included
* in the START message that is being sent. Otherwise, 0 is returned. This
* method is used by RecoverySet::onMessageSent() to ensure stale messages
* are ignored (e.g. a START message that was buffered before EpochRecovery
* was restarted).
*/
read_stream_id_t getExpectedReadStreamID() const {
return expected_read_stream_id_;
}
/**
* @return a human-readable name for RecoveryNode::State @param st
*/
static const char* stateName(State st);
private:
ShardID shard_;
// cluster offset of the node that holds this shard.
NodeID nid_;
// current state of the node, should only be changed by changState() but not
// directly
State state_ = State::SEALING;
// When this object is in DIGESTING state, this field contains the read
// stream id in the most recent START sent by this object in order to initiate
// a read stream for reading digest records and gaps from nid_. At all other
// times this field is READ_STREAM_ID_INVALID.
read_stream_id_t read_stream_id_;
// Set by transition() to the read stream id of the START message that's being
// sent. Since read_stream_id_ is only set when START message is passed to TCP
// (see comment in onMessageSent), this is used to ensure that onMessageSent
// processes the correct START message.
read_stream_id_t expected_read_stream_id_;
// backpointer to the EpochRecovery machine that has this
// RecoveryNode in its RecoverySet
EpochRecovery* recovery_;
/**
* Change the state of the recovery node to @param to.
* Note: Changing the state_ member variable must be done through this
* function ONLY.
*/
void changeState(State to);
/**
* Called by socket_callback_ when the Socket to the node represented by
* this RecoveryNode object closes and.
*
* @param reason reason for disconnection, this is the value passed to
* Socket::close(). See Socket.h.
*/
void onDisconnect(Status reason);
/**
* Called by START_Message::onSent() when a START message sent by
* this RecoveryNode while transitioning into DIGESTING has been
* sent or dropped.
*
* @param id read stream id in the SENT. Checked against read_stream_id_.
* @param st see Message::onSent(). If this is not Status::OK,
* start a retry timer.
*/
void onStartSent(read_stream_id_t id, Status st);
/**
* Called when (1) the resend_ timer expires after an unsuccessful attempt
* to send a START or CLEAN to this node, or (2) when the connection to the
* node is closed after a START or CLEAN have been sent, but the RecoveryNode
* has not yet moved on to the next state. The action is to resend the
* message to nid_.
*/
void resend();
/**
* Attempts to send a START message with RECOVERY flag set to nid_.
* Registers socket_callback_ on success.
*
*/
int requestDigestRecords();
/**
* Attempts to send a STOP message to the storage node to terminate the
* digest read stream. Called when EpochRecovery restarts or aborts. Must
* called in the DIGESTING state.
*/
void stopDigesting();
class RecoverySocketCallback : public SocketCallback {
public:
explicit RecoverySocketCallback(RecoveryNode* owner) : owner_(owner) {
ld_check(owner);
}
void operator()(Status st, const Address& name) override {
ld_check(!name.isClientAddress() &&
name.id_.node_.index() == owner_->nid_.index());
owner_->onDisconnect(st);
}
private:
RecoveryNode* owner_;
};
// calls onDisconnect() when a Socket to nid_ into which we have
// successfully sent a START or CLEAN closes.
RecoverySocketCallback socket_callback_;
// resends START and SEAL indefinitely on a failure
std::unique_ptr<BackoffTimer> resend_;
};
}} // namespace facebook::logdevice
| 31.809322 | 80 | 0.693353 | [
"object"
] |
87a87973a5b61ea9b06b2516515e47fe6bc77a4f | 50,871 | h | C | 3rdparty/QxOrm/include/QxDao/QxDaoThrowable.h | kevinlq/QxOrm_Example | 25c8c535a7602c0102e76df48969bb64f7711175 | [
"Apache-2.0"
] | 2 | 2021-06-07T10:07:57.000Z | 2021-07-20T23:02:55.000Z | 3rdparty/QxOrm/include/QxDao/QxDaoThrowable.h | kevinlq/QxOrm_Example | 25c8c535a7602c0102e76df48969bb64f7711175 | [
"Apache-2.0"
] | null | null | null | 3rdparty/QxOrm/include/QxDao/QxDaoThrowable.h | kevinlq/QxOrm_Example | 25c8c535a7602c0102e76df48969bb64f7711175 | [
"Apache-2.0"
] | null | null | null | /****************************************************************************
**
** https://www.qxorm.com/
** Copyright (C) 2013 Lionel Marty (contact@qxorm.com)
**
** This file is part of the QxOrm library
**
** This software is provided 'as-is', without any express or implied
** warranty. In no event will the authors be held liable for any
** damages arising from the use of this software
**
** Commercial Usage
** Licensees holding valid commercial QxOrm licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Lionel Marty
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file 'license.gpl3.txt' included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met : http://www.gnu.org/copyleft/gpl.html
**
** If you are unsure which license is appropriate for your use, or
** if you have questions regarding the use of this file, please contact :
** contact@qxorm.com
**
****************************************************************************/
#ifndef _QX_DAO_THROWABLE_H_
#define _QX_DAO_THROWABLE_H_
#ifdef _MSC_VER
#pragma once
#endif
/*!
* \file QxDaoThrowable.h
* \author Lionel Marty
* \ingroup QxDao
* \brief Same functions as qx::dao namespace, but throw a <i>qx::dao::sql_error</i> exception when a SQL error occurred (instead of returning a QSqlError instance)
*/
#include <QxDao/QxDao.h>
#include <QxDao/QxSqlError.h>
namespace qx {
namespace dao {
/*!
* \ingroup QxDao
* \brief Same functions as qx::dao namespace, but throw a <i>qx::dao::sql_error</i> exception when a SQL error occurred (instead of returning a QSqlError instance)
*/
namespace throwable {
/// @cond TO_AVOID_DOXYGEN_WARNINGS
/*!
* \ingroup QxDao
* \brief Return the number of lines in the table (database) mapped to the C++ class T (registered into QxOrm context) and filtered by a user SQL query
* \param lCount Output parameter with the number of lines in the table associated to the SQL query
* \param query Define a user SQL query added to default SQL query builded by QxOrm library (optional parameter)
* \param pDatabase Connection to database (you can manage your own connection pool for example, you can also define a transaction, etc.); if NULL, a valid connection for the current thread is provided by qx::QxSqlDatabase singleton class (optional parameter)
*
* qx::dao::throwable::count<T>() execute following SQL query :<br>
* <i>SELECT COUNT(*) FROM my_table</i> + <i>WHERE my_query...</i>
*/
template <class T>
inline void count(long & lCount, const qx::QxSqlQuery & query = qx::QxSqlQuery(), QSqlDatabase * pDatabase = NULL)
{ QSqlError err = qx::dao::detail::QxDao_Count<T>::count(lCount, query, pDatabase); if (err.isValid()) { throw qx::dao::sql_error(err); } }
/*!
* \ingroup QxDao
* \brief Return the number of lines in the table (database) mapped to the C++ class T (registered into QxOrm context) and filtered by a user SQL query (with possibility to add relations to SQL query)
* \param lCount Output parameter with the number of lines in the table associated to the SQL query
* \param relation List of relationships keys to be fetched (eager fetch instead of default lazy fetch for a relation)
* \param query Define a user SQL query added to default SQL query builded by QxOrm library (optional parameter)
* \param pDatabase Connection to database (you can manage your own connection pool for example, you can also define a transaction, etc.); if NULL, a valid connection for the current thread is provided by qx::QxSqlDatabase singleton class (optional parameter)
*
* qx::dao::throwable::count_with_relation<T>() execute following SQL query :<br>
* <i>SELECT COUNT(*) FROM my_table</i> + <i>XXX_JOINS_XXX</i> + <i>WHERE my_query...</i>
*/
template <class T>
inline void count_with_relation(long & lCount, const QStringList & relation, const qx::QxSqlQuery & query = qx::QxSqlQuery(), QSqlDatabase * pDatabase = NULL)
{ QSqlError err = qx::dao::detail::QxDao_Count_WithRelation<T>::count(lCount, relation, query, pDatabase); if (err.isValid()) { throw qx::dao::sql_error(err); } }
/*!
* \ingroup QxDao
* \brief Insert an element or a list of elements into database
* \param t Element (or list of elements) to be inserted into database
* \param pDatabase Connection to database (you can manage your own connection pool for example, you can also define a transaction, etc.); if NULL, a valid connection for the current thread is provided by qx::QxSqlDatabase singleton class (optional parameter)
* \return Throw a <i>qx::dao::sql_error</i> exception when a SQL error occurred
*
* qx::dao::throwable::insert<T>() execute following SQL query :<br>
* <i>INSERT INTO my_table (my_column_1, my_column_2, etc.) VALUES (?, ?, etc.)</i>
*/
template <class T>
inline void insert(T & t, QSqlDatabase * pDatabase = NULL)
{ QSqlError err = qx::dao::detail::QxDao_Insert<T>::insert(t, pDatabase); if (err.isValid()) { throw qx::dao::sql_error(err); } }
/*!
* \ingroup QxDao
* \brief Insert (if no exist) or update (if already exist) an element or a list of elements into database
* \param t Element (or list of elements) to be inserted (if no exist) or updated (if already exist) into database
* \param pDatabase Connection to database (you can manage your own connection pool for example, you can also define a transaction, etc.); if NULL, a valid connection for the current thread is provided by qx::QxSqlDatabase singleton class (optional parameter)
* \return Throw a <i>qx::dao::sql_error</i> exception when a SQL error occurred
*
* qx::dao::throwable::save<T>() execute following SQL query :<br>
* <i>INSERT INTO my_table (my_column_1, my_column_2, etc.) VALUES (?, ?, etc.)</i>
* <br>or (if already exist into database) :<br>
* <i>UPDATE my_table SET my_column_1 = ?, my_column_2 = ?, etc.</i>
*/
template <class T>
inline void save(T & t, QSqlDatabase * pDatabase = NULL)
{ QSqlError err = qx::dao::detail::QxDao_Save<T>::save(t, pDatabase); if (err.isValid()) { throw qx::dao::sql_error(err); } }
/*!
* \ingroup QxDao
* \brief Delete a line (or list of lines) of a table (database) mapped to a C++ object of type T (registered into QxOrm context)
* \param t Element (or list of elements) to be deleted into database
* \param pDatabase Connection to database (you can manage your own connection pool for example, you can also define a transaction, etc.); if NULL, a valid connection for the current thread is provided by qx::QxSqlDatabase singleton class (optional parameter)
* \return Throw a <i>qx::dao::sql_error</i> exception when a SQL error occurred
*
* qx::dao::throwable::delete_by_id<T>() execute following SQL query :<br>
* <i>DELETE FROM my_table WHERE my_id = ?</i><br>
* <br>
* If a soft delete behavior is defined for class T, qx::dao::throwable::delete_by_id<T>() execute following SQL query :<br>
* <i>UPDATE my_table SET is_deleted='1' WHERE my_id = ?</i>
*/
template <class T>
inline void delete_by_id(T & t, QSqlDatabase * pDatabase = NULL)
{ QSqlError err = qx::dao::detail::QxDao_DeleteById<T>::deleteById(t, pDatabase, true); if (err.isValid()) { throw qx::dao::sql_error(err); } }
/*!
* \ingroup QxDao
* \brief Destroy a line (or list of lines) of a table (database) mapped to a C++ object of type T (registered into QxOrm context), even if a soft delete behavior is defined for class T
* \param t Element (or list of elements) to be destroyed into database
* \param pDatabase Connection to database (you can manage your own connection pool for example, you can also define a transaction, etc.); if NULL, a valid connection for the current thread is provided by qx::QxSqlDatabase singleton class (optional parameter)
* \return Throw a <i>qx::dao::sql_error</i> exception when a SQL error occurred
*
* qx::dao::throwable::destroy_by_id<T>() execute following SQL query :<br>
* <i>DELETE FROM my_table WHERE my_id = ?</i>
*/
template <class T>
inline void destroy_by_id(T & t, QSqlDatabase * pDatabase = NULL)
{ QSqlError err = qx::dao::detail::QxDao_DeleteById<T>::deleteById(t, pDatabase, false); if (err.isValid()) { throw qx::dao::sql_error(err); } }
/*!
* \ingroup QxDao
* \brief Delete all lines of a table (database) mapped to a C++ class T (registered into QxOrm context)
* \param pDatabase Connection to database (you can manage your own connection pool for example, you can also define a transaction, etc.); if NULL, a valid connection for the current thread is provided by qx::QxSqlDatabase singleton class (optional parameter)
* \return Throw a <i>qx::dao::sql_error</i> exception when a SQL error occurred
*
* qx::dao::throwable::delete_all<T>() execute following SQL query :<br>
* <i>DELETE FROM my_table</i><br>
* <br>
* If a soft delete behavior is defined for class T, qx::dao::throwable::delete_all<T>() execute following SQL query :<br>
* <i>UPDATE my_table SET is_deleted='1'</i>
*/
template <class T>
inline void delete_all(QSqlDatabase * pDatabase = NULL)
{ QSqlError err = qx::dao::detail::QxDao_DeleteAll<T>::deleteAll("", pDatabase, true); if (err.isValid()) { throw qx::dao::sql_error(err); } }
/*!
* \ingroup QxDao
* \brief Destroy all lines of a table (database) mapped to a C++ class T (registered into QxOrm context), even if a soft delete behavior is defined for class T
* \param pDatabase Connection to database (you can manage your own connection pool for example, you can also define a transaction, etc.); if NULL, a valid connection for the current thread is provided by qx::QxSqlDatabase singleton class (optional parameter)
* \return Throw a <i>qx::dao::sql_error</i> exception when a SQL error occurred
*
* qx::dao::throwable::destroy_all<T>() execute following SQL query :<br>
* <i>DELETE FROM my_table</i>
*/
template <class T>
inline void destroy_all(QSqlDatabase * pDatabase = NULL)
{ QSqlError err = qx::dao::detail::QxDao_DeleteAll<T>::deleteAll("", pDatabase, false); if (err.isValid()) { throw qx::dao::sql_error(err); } }
/*!
* \ingroup QxDao
* \brief Delete all lines of a table (database) mapped to a C++ class T (registered into QxOrm context) and filtered by a user SQL query
* \param query Define a user SQL query added to default SQL query builded by QxOrm library
* \param pDatabase Connection to database (you can manage your own connection pool for example, you can also define a transaction, etc.); if NULL, a valid connection for the current thread is provided by qx::QxSqlDatabase singleton class (optional parameter)
* \return Throw a <i>qx::dao::sql_error</i> exception when a SQL error occurred
*
* qx::dao::throwable::delete_by_query<T>() execute following SQL query :<br>
* <i>DELETE FROM my_table</i> + <i>WHERE my_query...</i><br>
* <br>
* If a soft delete behavior is defined for class T, qx::dao::throwable::delete_by_query<T>() execute following SQL query :<br>
* <i>UPDATE my_table SET is_deleted='1'</i> + <i>WHERE my_query...</i>
*/
template <class T>
inline void delete_by_query(const qx::QxSqlQuery & query, QSqlDatabase * pDatabase = NULL)
{ QSqlError err = qx::dao::detail::QxDao_DeleteAll<T>::deleteAll(query, pDatabase, true); if (err.isValid()) { throw qx::dao::sql_error(err); } }
/*!
* \ingroup QxDao
* \brief Destroy all lines of a table (database) mapped to a C++ class T (registered into QxOrm context) and filtered by a user SQL query, even if a soft delete behavior is defined for class T
* \param query Define a user SQL query added to default SQL query builded by QxOrm library
* \param pDatabase Connection to database (you can manage your own connection pool for example, you can also define a transaction, etc.); if NULL, a valid connection for the current thread is provided by qx::QxSqlDatabase singleton class (optional parameter)
* \return Throw a <i>qx::dao::sql_error</i> exception when a SQL error occurred
*
* qx::dao::throwable::destroy_by_query<T>() execute following SQL query :<br>
* <i>DELETE FROM my_table</i> + <i>WHERE my_query...</i>
*/
template <class T>
inline void destroy_by_query(const qx::QxSqlQuery & query, QSqlDatabase * pDatabase = NULL)
{ QSqlError err = qx::dao::detail::QxDao_DeleteAll<T>::deleteAll(query, pDatabase, false); if (err.isValid()) { throw qx::dao::sql_error(err); } }
/*!
* \ingroup QxDao
* \brief Create a table into database (with all columns) mapped to a C++ class T (registered into QxOrm context) : be careful, this function can be used only with a SQLite database to create examples or prototypes; For other databases, it is recommended to use QxEntityEditor application or to manage the database schema with an external tool provided by the SGBD (SQLite Manager for SQLite, pgAdmin for PostgreSQL, MySQL Workbench for MySQL, etc...)
* \param pDatabase Connection to database (you can manage your own connection pool for example, you can also define a transaction, etc.); if NULL, a valid connection for the current thread is provided by qx::QxSqlDatabase singleton class (optional parameter)
* \return Throw a <i>qx::dao::sql_error</i> exception when a SQL error occurred
*
* qx::dao::throwable::create_table<T>() execute following SQL query :<br>
* <i>CREATE TABLE my_table (my_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, my_column_1 TEXT, my_column_2 TEXT, etc.)</i>
*/
template <class T>
inline void create_table(QSqlDatabase * pDatabase = NULL)
{ QSqlError err = qx::dao::detail::QxDao_CreateTable<T>::createTable(pDatabase); if (err.isValid()) { throw qx::dao::sql_error(err); } }
/*!
* \ingroup QxDao
* \brief Fetch an object t (retrieve all its properties) of type T (registered into QxOrm context) mapped to a table in the database (t must have a valid id before to be fetched without error)
* \param relation List of relationships keys to be fetched (eager fetch instead of default lazy fetch for a relation) : use "|" separator to put many relationships keys into this parameter
* \param t Instance (with a valid id) to be fetched (retrieve all properties from database)
* \param pDatabase Connection to database (you can manage your own connection pool for example, you can also define a transaction, etc.); if NULL, a valid connection for the current thread is provided by qx::QxSqlDatabase singleton class (optional parameter)
* \return Throw a <i>qx::dao::sql_error</i> exception when a SQL error occurred
*
* qx::dao::throwable::fetch_by_id_with_relation<T>() execute following SQL query :<br>
* <i>SELECT * FROM my_table WHERE my_id = ?</i>
*/
template <class T>
inline void fetch_by_id_with_relation(const QString & relation, T & t, QSqlDatabase * pDatabase = NULL)
{ QSqlError err = qx::dao::detail::QxDao_FetchById_WithRelation<T>::fetchById(relation, t, pDatabase); if (err.isValid()) { throw qx::dao::sql_error(err); } }
/*!
* \ingroup QxDao
* \brief Fetch an object t (retrieve all its properties) of type T (registered into QxOrm context) mapped to a table in the database (t must have a valid id before to be fetched without error)
* \param relation List of relationships keys to be fetched (eager fetch instead of default lazy fetch for a relation)
* \param t Instance (with a valid id) to be fetched (retrieve all properties from database)
* \param pDatabase Connection to database (you can manage your own connection pool for example, you can also define a transaction, etc.); if NULL, a valid connection for the current thread is provided by qx::QxSqlDatabase singleton class (optional parameter)
* \return Throw a <i>qx::dao::sql_error</i> exception when a SQL error occurred
*
* qx::dao::throwable::fetch_by_id_with_relation<T>() execute following SQL query :<br>
* <i>SELECT * FROM my_table WHERE my_id = ?</i>
*/
template <class T>
inline void fetch_by_id_with_relation(const QStringList & relation, T & t, QSqlDatabase * pDatabase = NULL)
{ QSqlError err = qx::dao::detail::QxDao_FetchById_WithRelation<T>::fetchById(relation, t, pDatabase); if (err.isValid()) { throw qx::dao::sql_error(err); } }
/*!
* \ingroup QxDao
* \brief Fetch an object t (retrieve all its properties and relationships) of type T (registered into QxOrm context) mapped to a table in the database (t must have a valid id before to be fetched without error)
* \param t Instance (with a valid id) to be fetched (retrieve all properties and relationships from database)
* \param pDatabase Connection to database (you can manage your own connection pool for example, you can also define a transaction, etc.); if NULL, a valid connection for the current thread is provided by qx::QxSqlDatabase singleton class (optional parameter)
* \return Throw a <i>qx::dao::sql_error</i> exception when a SQL error occurred
*
* qx::dao::throwable::fetch_by_id_with_all_relation<T>() execute following SQL query :<br>
* <i>SELECT * FROM my_table WHERE my_id = ?</i>
*/
template <class T>
inline void fetch_by_id_with_all_relation(T & t, QSqlDatabase * pDatabase = NULL)
{ QSqlError err = qx::dao::detail::QxDao_FetchById_WithRelation<T>::fetchById("*", t, pDatabase); if (err.isValid()) { throw qx::dao::sql_error(err); } }
/*!
* \ingroup QxDao
* \brief Fetch a list of objects (retrieve all elements and properties associated) of type T (container registered into QxOrm context) mapped to a table in the database
* \param relation List of relationships keys to be fetched (eager fetch instead of default lazy fetch for a relation) : use "|" separator to put many relationships keys into this parameter
* \param t Container to be fetched (retrieve all elements and properties associated); t is cleared before executing SQL query
* \param pDatabase Connection to database (you can manage your own connection pool for example, you can also define a transaction, etc.); if NULL, a valid connection for the current thread is provided by qx::QxSqlDatabase singleton class (optional parameter)
* \return Throw a <i>qx::dao::sql_error</i> exception when a SQL error occurred
*
* qx::dao::throwable::fetch_all_with_relation<T>() execute following SQL query :<br>
* <i>SELECT * FROM my_table</i>
*/
template <class T>
inline void fetch_all_with_relation(const QString & relation, T & t, QSqlDatabase * pDatabase = NULL)
{ QSqlError err = qx::dao::detail::QxDao_FetchAll_WithRelation<T>::fetchAll(relation, "", t, pDatabase); if (err.isValid()) { throw qx::dao::sql_error(err); } }
/*!
* \ingroup QxDao
* \brief Fetch a list of objects (retrieve all elements and properties associated) of type T (container registered into QxOrm context) mapped to a table in the database
* \param relation List of relationships keys to be fetched (eager fetch instead of default lazy fetch for a relation)
* \param t Container to be fetched (retrieve all elements and properties associated); t is cleared before executing SQL query
* \param pDatabase Connection to database (you can manage your own connection pool for example, you can also define a transaction, etc.); if NULL, a valid connection for the current thread is provided by qx::QxSqlDatabase singleton class (optional parameter)
* \return Throw a <i>qx::dao::sql_error</i> exception when a SQL error occurred
*
* qx::dao::throwable::fetch_all_with_relation<T>() execute following SQL query :<br>
* <i>SELECT * FROM my_table</i>
*/
template <class T>
inline void fetch_all_with_relation(const QStringList & relation, T & t, QSqlDatabase * pDatabase = NULL)
{ QSqlError err = qx::dao::detail::QxDao_FetchAll_WithRelation<T>::fetchAll(relation, "", t, pDatabase); if (err.isValid()) { throw qx::dao::sql_error(err); } }
/*!
* \ingroup QxDao
* \brief Fetch a list of objects (retrieve all elements and properties + all relationships associated) of type T (container registered into QxOrm context) mapped to a table in the database
* \param t Container to be fetched (retrieve all elements and properties + all relationships associated); t is cleared before executing SQL query
* \param pDatabase Connection to database (you can manage your own connection pool for example, you can also define a transaction, etc.); if NULL, a valid connection for the current thread is provided by qx::QxSqlDatabase singleton class (optional parameter)
* \return Throw a <i>qx::dao::sql_error</i> exception when a SQL error occurred
*
* qx::dao::throwable::fetch_all_with_all_relation<T>() execute following SQL query :<br>
* <i>SELECT * FROM my_table</i>
*/
template <class T>
inline void fetch_all_with_all_relation(T & t, QSqlDatabase * pDatabase = NULL)
{ QSqlError err = qx::dao::detail::QxDao_FetchAll_WithRelation<T>::fetchAll("*", "", t, pDatabase); if (err.isValid()) { throw qx::dao::sql_error(err); } }
/*!
* \ingroup QxDao
* \brief Fetch a list of objects (retrieve all elements and properties associated) of type T (container registered into QxOrm context) mapped to a table in the database and filtered by a user SQL query
* \param relation List of relationships keys to be fetched (eager fetch instead of default lazy fetch for a relation) : use "|" separator to put many relationships keys into this parameter
* \param query Define a user SQL query added to default SQL query builded by QxOrm library
* \param t Container to be fetched (retrieve all elements and properties associated); t is cleared before executing SQL query
* \param pDatabase Connection to database (you can manage your own connection pool for example, you can also define a transaction, etc.); if NULL, a valid connection for the current thread is provided by qx::QxSqlDatabase singleton class (optional parameter)
* \return Throw a <i>qx::dao::sql_error</i> exception when a SQL error occurred
*
* qx::dao::throwable::fetch_by_query_with_relation<T>() execute following SQL query :<br>
* <i>SELECT * FROM my_table</i> + <i>WHERE my_query...</i>
*/
template <class T>
inline void fetch_by_query_with_relation(const QString & relation, const qx::QxSqlQuery & query, T & t, QSqlDatabase * pDatabase = NULL)
{ QSqlError err = qx::dao::detail::QxDao_FetchAll_WithRelation<T>::fetchAll(relation, query, t, pDatabase); if (err.isValid()) { throw qx::dao::sql_error(err); } }
/*!
* \ingroup QxDao
* \brief Fetch a list of objects (retrieve all elements and properties associated) of type T (container registered into QxOrm context) mapped to a table in the database and filtered by a user SQL query
* \param relation List of relationships keys to be fetched (eager fetch instead of default lazy fetch for a relation)
* \param query Define a user SQL query added to default SQL query builded by QxOrm library
* \param t Container to be fetched (retrieve all elements and properties associated); t is cleared before executing SQL query
* \param pDatabase Connection to database (you can manage your own connection pool for example, you can also define a transaction, etc.); if NULL, a valid connection for the current thread is provided by qx::QxSqlDatabase singleton class (optional parameter)
* \return Throw a <i>qx::dao::sql_error</i> exception when a SQL error occurred
*
* qx::dao::throwable::fetch_by_query_with_relation<T>() execute following SQL query :<br>
* <i>SELECT * FROM my_table</i> + <i>WHERE my_query...</i>
*/
template <class T>
inline void fetch_by_query_with_relation(const QStringList & relation, const qx::QxSqlQuery & query, T & t, QSqlDatabase * pDatabase = NULL)
{ QSqlError err = qx::dao::detail::QxDao_FetchAll_WithRelation<T>::fetchAll(relation, query, t, pDatabase); if (err.isValid()) { throw qx::dao::sql_error(err); } }
/*!
* \ingroup QxDao
* \brief Fetch a list of objects (retrieve all elements and properties + all relationships associated) of type T (container registered into QxOrm context) mapped to a table in the database and filtered by a user SQL query
* \param query Define a user SQL query added to default SQL query builded by QxOrm library
* \param t Container to be fetched (retrieve all elements and properties + all relationships associated); t is cleared before executing SQL query
* \param pDatabase Connection to database (you can manage your own connection pool for example, you can also define a transaction, etc.); if NULL, a valid connection for the current thread is provided by qx::QxSqlDatabase singleton class (optional parameter)
* \return Throw a <i>qx::dao::sql_error</i> exception when a SQL error occurred
*
* qx::dao::throwable::fetch_by_query_with_all_relation<T>() execute following SQL query :<br>
* <i>SELECT * FROM my_table</i> + <i>WHERE my_query...</i>
*/
template <class T>
inline void fetch_by_query_with_all_relation(const qx::QxSqlQuery & query, T & t, QSqlDatabase * pDatabase = NULL)
{ QSqlError err = qx::dao::detail::QxDao_FetchAll_WithRelation<T>::fetchAll("*", query, t, pDatabase); if (err.isValid()) { throw qx::dao::sql_error(err); } }
/*!
* \ingroup QxDao
* \brief Insert an element and its relationships (or a list of elements + relationships) into database
* \param relation List of relationships keys to be inserted in others tables of database : use "|" separator to put many relationships keys into this parameter
* \param t Element (or list of elements) to be inserted into database
* \param pDatabase Connection to database (you can manage your own connection pool for example, you can also define a transaction, etc.); if NULL, a valid connection for the current thread is provided by qx::QxSqlDatabase singleton class (optional parameter)
* \return Throw a <i>qx::dao::sql_error</i> exception when a SQL error occurred
*
* qx::dao::throwable::insert_with_relation<T>() execute following SQL query :<br>
* <i>INSERT INTO my_table (my_column_1, my_column_2, etc.) VALUES (?, ?, etc.)</i>
*/
template <class T>
inline void insert_with_relation(const QString & relation, T & t, QSqlDatabase * pDatabase = NULL)
{ QSqlError err = qx::dao::detail::QxDao_Insert_WithRelation<T>::insert(relation, t, pDatabase); if (err.isValid()) { throw qx::dao::sql_error(err); } }
/*!
* \ingroup QxDao
* \brief Insert an element and its relationships (or a list of elements + relationships) into database
* \param relation List of relationships keys to be inserted in others tables of database
* \param t Element (or list of elements) to be inserted into database
* \param pDatabase Connection to database (you can manage your own connection pool for example, you can also define a transaction, etc.); if NULL, a valid connection for the current thread is provided by qx::QxSqlDatabase singleton class (optional parameter)
* \return Throw a <i>qx::dao::sql_error</i> exception when a SQL error occurred
*
* qx::dao::throwable::insert_with_relation<T>() execute following SQL query :<br>
* <i>INSERT INTO my_table (my_column_1, my_column_2, etc.) VALUES (?, ?, etc.)</i>
*/
template <class T>
inline void insert_with_relation(const QStringList & relation, T & t, QSqlDatabase * pDatabase = NULL)
{ QSqlError err = qx::dao::detail::QxDao_Insert_WithRelation<T>::insert(relation, t, pDatabase); if (err.isValid()) { throw qx::dao::sql_error(err); } }
/*!
* \ingroup QxDao
* \brief Insert an element and all its relationships (or a list of elements + all relationships) into database
* \param t Element (or list of elements) to be inserted into database
* \param pDatabase Connection to database (you can manage your own connection pool for example, you can also define a transaction, etc.); if NULL, a valid connection for the current thread is provided by qx::QxSqlDatabase singleton class (optional parameter)
* \return Throw a <i>qx::dao::sql_error</i> exception when a SQL error occurred
*
* qx::dao::throwable::insert_with_all_relation<T>() execute following SQL query :<br>
* <i>INSERT INTO my_table (my_column_1, my_column_2, etc.) VALUES (?, ?, etc.)</i>
*/
template <class T>
inline void insert_with_all_relation(T & t, QSqlDatabase * pDatabase = NULL)
{ QSqlError err = qx::dao::detail::QxDao_Insert_WithRelation<T>::insert("*", t, pDatabase); if (err.isValid()) { throw qx::dao::sql_error(err); } }
/*!
* \ingroup QxDao
* \brief Update an element and its relationships (or a list of elements + relationships) into database
* \param relation List of relationships keys to be updated in others tables of database : use "|" separator to put many relationships keys into this parameter
* \param t Element (or list of elements) to be updated into database
* \param pDatabase Connection to database (you can manage your own connection pool for example, you can also define a transaction, etc.); if NULL, a valid connection for the current thread is provided by qx::QxSqlDatabase singleton class (optional parameter)
* \return Throw a <i>qx::dao::sql_error</i> exception when a SQL error occurred
*
* qx::dao::throwable::update_with_relation<T>() execute following SQL query :<br>
* <i>UPDATE my_table SET my_column_1 = ?, my_column_2 = ?, etc.</i>
*/
template <class T>
inline void update_with_relation(const QString & relation, T & t, QSqlDatabase * pDatabase = NULL)
{ QSqlError err = qx::dao::detail::QxDao_Update_WithRelation<T>::update(relation, "", t, pDatabase); if (err.isValid()) { throw qx::dao::sql_error(err); } }
/*!
* \ingroup QxDao
* \brief Update an element and its relationships (or a list of elements + relationships) into database (adding a user SQL query to the default SQL query builded by QxOrm library)
* \param relation List of relationships keys to be updated in others tables of database : use "|" separator to put many relationships keys into this parameter
* \param query Define a user SQL query added to default SQL query builded by QxOrm library
* \param t Element (or list of elements) to be updated into database
* \param pDatabase Connection to database (you can manage your own connection pool for example, you can also define a transaction, etc.); if NULL, a valid connection for the current thread is provided by qx::QxSqlDatabase singleton class (optional parameter)
* \return Throw a <i>qx::dao::sql_error</i> exception when a SQL error occurred
*
* qx::dao::throwable::update_by_query_with_relation<T>() execute following SQL query :<br>
* <i>UPDATE my_table SET my_column_1 = ?, my_column_2 = ?, etc.</i> + <i>WHERE my_query...</i>
*/
template <class T>
inline void update_by_query_with_relation(const QString & relation, const qx::QxSqlQuery & query, T & t, QSqlDatabase * pDatabase = NULL)
{ QSqlError err = qx::dao::detail::QxDao_Update_WithRelation<T>::update(relation, query, t, pDatabase); if (err.isValid()) { throw qx::dao::sql_error(err); } }
/*!
* \ingroup QxDao
* \brief Update an element and its relationships (or a list of elements + relationships) into database
* \param relation List of relationships keys to be updated in others tables of database
* \param t Element (or list of elements) to be updated into database
* \param pDatabase Connection to database (you can manage your own connection pool for example, you can also define a transaction, etc.); if NULL, a valid connection for the current thread is provided by qx::QxSqlDatabase singleton class (optional parameter)
* \return Throw a <i>qx::dao::sql_error</i> exception when a SQL error occurred
*
* qx::dao::throwable::update_with_relation<T>() execute following SQL query :<br>
* <i>UPDATE my_table SET my_column_1 = ?, my_column_2 = ?, etc.</i>
*/
template <class T>
inline void update_with_relation(const QStringList & relation, T & t, QSqlDatabase * pDatabase = NULL)
{ QSqlError err = qx::dao::detail::QxDao_Update_WithRelation<T>::update(relation, "", t, pDatabase); if (err.isValid()) { throw qx::dao::sql_error(err); } }
/*!
* \ingroup QxDao
* \brief Update an element and its relationships (or a list of elements + relationships) into database (adding a user SQL query to the default SQL query builded by QxOrm library)
* \param relation List of relationships keys to be updated in others tables of database
* \param query Define a user SQL query added to default SQL query builded by QxOrm library
* \param t Element (or list of elements) to be updated into database
* \param pDatabase Connection to database (you can manage your own connection pool for example, you can also define a transaction, etc.); if NULL, a valid connection for the current thread is provided by qx::QxSqlDatabase singleton class (optional parameter)
* \return Throw a <i>qx::dao::sql_error</i> exception when a SQL error occurred
*
* qx::dao::throwable::update_by_query_with_relation<T>() execute following SQL query :<br>
* <i>UPDATE my_table SET my_column_1 = ?, my_column_2 = ?, etc.</i> + <i>WHERE my_query...</i>
*/
template <class T>
inline void update_by_query_with_relation(const QStringList & relation, const qx::QxSqlQuery & query, T & t, QSqlDatabase * pDatabase = NULL)
{ QSqlError err = qx::dao::detail::QxDao_Update_WithRelation<T>::update(relation, query, t, pDatabase); if (err.isValid()) { throw qx::dao::sql_error(err); } }
/*!
* \ingroup QxDao
* \brief Update an element and all its relationships (or a list of elements + all relationships) into database
* \param t Element (or list of elements) to be updated into database
* \param pDatabase Connection to database (you can manage your own connection pool for example, you can also define a transaction, etc.); if NULL, a valid connection for the current thread is provided by qx::QxSqlDatabase singleton class (optional parameter)
* \return Throw a <i>qx::dao::sql_error</i> exception when a SQL error occurred
*
* qx::dao::throwable::update_with_all_relation<T>() execute following SQL query :<br>
* <i>UPDATE my_table SET my_column_1 = ?, my_column_2 = ?, etc.</i>
*/
template <class T>
inline void update_with_all_relation(T & t, QSqlDatabase * pDatabase = NULL)
{ QSqlError err = qx::dao::detail::QxDao_Update_WithRelation<T>::update("*", "", t, pDatabase); if (err.isValid()) { throw qx::dao::sql_error(err); } }
/*!
* \ingroup QxDao
* \brief Update an element and all its relationships (or a list of elements + all relationships) into database (adding a user SQL query to the default SQL query builded by QxOrm library)
* \param query Define a user SQL query added to default SQL query builded by QxOrm library
* \param t Element (or list of elements) to be updated into database
* \param pDatabase Connection to database (you can manage your own connection pool for example, you can also define a transaction, etc.); if NULL, a valid connection for the current thread is provided by qx::QxSqlDatabase singleton class (optional parameter)
* \return Throw a <i>qx::dao::sql_error</i> exception when a SQL error occurred
*
* qx::dao::throwable::update_by_query_with_all_relation<T>() execute following SQL query :<br>
* <i>UPDATE my_table SET my_column_1 = ?, my_column_2 = ?, etc.</i> + <i>WHERE my_query...</i>
*/
template <class T>
inline void update_by_query_with_all_relation(const qx::QxSqlQuery & query, T & t, QSqlDatabase * pDatabase = NULL)
{ QSqlError err = qx::dao::detail::QxDao_Update_WithRelation<T>::update("*", query, t, pDatabase); if (err.isValid()) { throw qx::dao::sql_error(err); } }
/*!
* \ingroup QxDao
* \brief Insert (if no exist) or update (if already exist) an element and its relationships (or a list of elements + relationships) into database
* \param relation List of relationships keys to be inserted or updated in others tables of database : use "|" separator to put many relationships keys into this parameter
* \param t Element (or list of elements) to be inserted (if no exist) or updated (if already exist) into database
* \param pDatabase Connection to database (you can manage your own connection pool for example, you can also define a transaction, etc.); if NULL, a valid connection for the current thread is provided by qx::QxSqlDatabase singleton class (optional parameter)
* \return Throw a <i>qx::dao::sql_error</i> exception when a SQL error occurred
*
* qx::dao::throwable::save_with_relation<T>() execute following SQL query :<br>
* <i>INSERT INTO my_table (my_column_1, my_column_2, etc.) VALUES (?, ?, etc.)</i>
* <br>or (if already exist into database) :<br>
* <i>UPDATE my_table SET my_column_1 = ?, my_column_2 = ?, etc.</i>
*/
template <class T>
inline void save_with_relation(const QString & relation, T & t, QSqlDatabase * pDatabase = NULL)
{ QSqlError err = qx::dao::detail::QxDao_Save_WithRelation<T>::save(relation, t, pDatabase); if (err.isValid()) { throw qx::dao::sql_error(err); } }
/*!
* \ingroup QxDao
* \brief Insert (if no exist) or update (if already exist) an element and its relationships (or a list of elements + relationships) into database
* \param relation List of relationships keys to be inserted or updated in others tables of database
* \param t Element (or list of elements) to be inserted (if no exist) or updated (if already exist) into database
* \param pDatabase Connection to database (you can manage your own connection pool for example, you can also define a transaction, etc.); if NULL, a valid connection for the current thread is provided by qx::QxSqlDatabase singleton class (optional parameter)
* \return Throw a <i>qx::dao::sql_error</i> exception when a SQL error occurred
*
* qx::dao::throwable::save_with_relation<T>() execute following SQL query :<br>
* <i>INSERT INTO my_table (my_column_1, my_column_2, etc.) VALUES (?, ?, etc.)</i>
* <br>or (if already exist into database) :<br>
* <i>UPDATE my_table SET my_column_1 = ?, my_column_2 = ?, etc.</i>
*/
template <class T>
inline void save_with_relation(const QStringList & relation, T & t, QSqlDatabase * pDatabase = NULL)
{ QSqlError err = qx::dao::detail::QxDao_Save_WithRelation<T>::save(relation, t, pDatabase); if (err.isValid()) { throw qx::dao::sql_error(err); } }
/*!
* \ingroup QxDao
* \brief Insert (if no exist) or update (if already exist) an element and all its relationships (or a list of elements + all relationships) into database
* \param t Element (or list of elements) to be inserted (if no exist) or updated (if already exist) into database
* \param pDatabase Connection to database (you can manage your own connection pool for example, you can also define a transaction, etc.); if NULL, a valid connection for the current thread is provided by qx::QxSqlDatabase singleton class (optional parameter)
* \return Throw a <i>qx::dao::sql_error</i> exception when a SQL error occurred
*
* qx::dao::throwable::save_with_all_relation<T>() execute following SQL query :<br>
* <i>INSERT INTO my_table (my_column_1, my_column_2, etc.) VALUES (?, ?, etc.)</i>
* <br>or (if already exist into database) :<br>
* <i>UPDATE my_table SET my_column_1 = ?, my_column_2 = ?, etc.</i>
*/
template <class T>
inline void save_with_all_relation(T & t, QSqlDatabase * pDatabase = NULL)
{ QSqlError err = qx::dao::detail::QxDao_Save_WithRelation<T>::save("*", t, pDatabase); if (err.isValid()) { throw qx::dao::sql_error(err); } }
/*!
* \ingroup QxDao
* \brief Insert (if no exist) or update (if already exist) recursively an element and all levels of relationships (or a list of elements + all levels of relationships) into database, useful to save a tree structure for example
* \param t Element (or list of elements) to be inserted (if no exist) or updated (if already exist) into database
* \param eSaveMode To improve performance, use this parameter to indicate if you just want to insert or update all elements in database
* \param pDatabase Connection to database (you can manage your own connection pool for example, you can also define a transaction, etc.); if NULL, a valid connection for the current thread is provided by qx::QxSqlDatabase singleton class (optional parameter)
* \param pRelationParams Keep this parameter as NULL, it is used internally by QxOrm library to iterate over each level of relationship
* \return Throw a <i>qx::dao::sql_error</i> exception when a SQL error occurred
*
* qx::dao::throwable::save_with_relation_recursive<T>() execute following SQL query :<br>
* <i>INSERT INTO my_table (my_column_1, my_column_2, etc.) VALUES (?, ?, etc.)</i>
* <br>or (if already exist into database) :<br>
* <i>UPDATE my_table SET my_column_1 = ?, my_column_2 = ?, etc.</i><br>
* <br>
* <b>Note :</b> to improve performance, and if you know that you are just inserting or updating items in database, you can use the parameter <i>eSaveMode</i> :<br>
* - <i>qx::dao::save_mode::e_check_insert_or_update</i> : check before saving if item already exists in database ;<br>
* - <i>qx::dao::save_mode::e_insert_only</i> : only insert items in database (use only 1 SQL query to insert collection of items) ;<br>
* - <i>qx::dao::save_mode::e_update_only</i> : only update items in database (use only 1 SQL query to update collection of items).
*/
template <class T>
inline void save_with_relation_recursive(T & t, qx::dao::save_mode::e_save_mode eSaveMode = qx::dao::save_mode::e_check_insert_or_update, QSqlDatabase * pDatabase = NULL, qx::QxSqlRelationParams * pRelationParams = NULL)
{ QSqlError err = qx::dao::detail::QxDao_Save_WithRelation_Recursive<T>::save(t, eSaveMode, pDatabase, pRelationParams); if (err.isValid()) { throw qx::dao::sql_error(err); } }
/*!
* \ingroup QxDao
* \brief Fetch an object t (retrieve all its properties) of type T (registered into QxOrm context) mapped to a table in the database (t must have a valid id before to be fetched without error)
* \param t Instance (with a valid id) to be fetched (retrieve all properties from database)
* \param pDatabase Connection to database (you can manage your own connection pool for example, you can also define a transaction, etc.); if NULL, a valid connection for the current thread is provided by qx::QxSqlDatabase singleton class (optional parameter)
* \param columns List of database table columns (mapped to properties of C++ class T) to be fetched (optional parameter)
* \return Throw a <i>qx::dao::sql_error</i> exception when a SQL error occurred
*
* qx::dao::throwable::fetch_by_id<T>() execute following SQL query :<br>
* <i>SELECT * FROM my_table WHERE my_id = ?</i>
*/
template <class T>
inline void fetch_by_id(T & t, QSqlDatabase * pDatabase = NULL, const QStringList & columns = QStringList())
{ QSqlError err = qx::dao::detail::QxDao_FetchById<T>::fetchById(t, pDatabase, columns); if (err.isValid()) { throw qx::dao::sql_error(err); } }
/*!
* \ingroup QxDao
* \brief Fetch a list of objects (retrieve all elements and properties associated) of type T (container registered into QxOrm context) mapped to a table in the database
* \param t Container to be fetched (retrieve all elements and properties associated); t is cleared before executing SQL query
* \param pDatabase Connection to database (you can manage your own connection pool for example, you can also define a transaction, etc.); if NULL, a valid connection for the current thread is provided by qx::QxSqlDatabase singleton class (optional parameter)
* \param columns List of database table columns (mapped to properties of C++ class T) to be fetched (optional parameter)
* \return Throw a <i>qx::dao::sql_error</i> exception when a SQL error occurred
*
* qx::dao::throwable::fetch_all<T>() execute following SQL query :<br>
* <i>SELECT * FROM my_table</i>
*/
template <class T>
inline void fetch_all(T & t, QSqlDatabase * pDatabase = NULL, const QStringList & columns = QStringList())
{ QSqlError err = qx::dao::detail::QxDao_FetchAll<T>::fetchAll("", t, pDatabase, columns); if (err.isValid()) { throw qx::dao::sql_error(err); } }
/*!
* \ingroup QxDao
* \brief Fetch a list of objects (retrieve all elements and properties associated) of type T (container registered into QxOrm context) mapped to a table in the database and filtered by a user SQL query
* \param query Define a user SQL query added to default SQL query builded by QxOrm library
* \param t Container to be fetched (retrieve all elements and properties associated); t is cleared before executing SQL query
* \param pDatabase Connection to database (you can manage your own connection pool for example, you can also define a transaction, etc.); if NULL, a valid connection for the current thread is provided by qx::QxSqlDatabase singleton class (optional parameter)
* \param columns List of database table columns (mapped to properties of C++ class T) to be fetched (optional parameter)
* \return Throw a <i>qx::dao::sql_error</i> exception when a SQL error occurred
*
* qx::dao::throwable::fetch_by_query<T>() execute following SQL query :<br>
* <i>SELECT * FROM my_table</i> + <i>WHERE my_query...</i>
*/
template <class T>
inline void fetch_by_query(const qx::QxSqlQuery & query, T & t, QSqlDatabase * pDatabase = NULL, const QStringList & columns = QStringList())
{ QSqlError err = qx::dao::detail::QxDao_FetchAll<T>::fetchAll(query, t, pDatabase, columns); if (err.isValid()) { throw qx::dao::sql_error(err); } }
/*!
* \ingroup QxDao
* \brief Update an element or a list of elements into database
* \param t Element (or list of elements) to be updated into database
* \param pDatabase Connection to database (you can manage your own connection pool for example, you can also define a transaction, etc.); if NULL, a valid connection for the current thread is provided by qx::QxSqlDatabase singleton class (optional parameter)
* \param columns List of database table columns (mapped to properties of C++ class T) to be updated (optional parameter)
* \return Throw a <i>qx::dao::sql_error</i> exception when a SQL error occurred
*
* qx::dao::throwable::update<T>() execute following SQL query :<br>
* <i>UPDATE my_table SET my_column_1 = ?, my_column_2 = ?, etc.</i>
*/
template <class T>
inline void update(T & t, QSqlDatabase * pDatabase = NULL, const QStringList & columns = QStringList())
{ QSqlError err = qx::dao::detail::QxDao_Update<T>::update("", t, pDatabase, columns); if (err.isValid()) { throw qx::dao::sql_error(err); } }
/*!
* \ingroup QxDao
* \brief Update an element or a list of elements into database (adding a user SQL query to the default SQL query builded by QxOrm library)
* \param query Define a user SQL query added to default SQL query builded by QxOrm library
* \param t Element (or list of elements) to be updated into database
* \param pDatabase Connection to database (you can manage your own connection pool for example, you can also define a transaction, etc.); if NULL, a valid connection for the current thread is provided by qx::QxSqlDatabase singleton class (optional parameter)
* \param columns List of database table columns (mapped to properties of C++ class T) to be updated (optional parameter)
* \return Throw a <i>qx::dao::sql_error</i> exception when a SQL error occurred
*
* qx::dao::throwable::update_by_query<T>() execute following SQL query :<br>
* <i>UPDATE my_table SET my_column_1 = ?, my_column_2 = ?, etc.</i> + <i>WHERE my_query...</i>
*/
template <class T>
inline void update_by_query(const qx::QxSqlQuery & query, T & t, QSqlDatabase * pDatabase = NULL, const QStringList & columns = QStringList())
{ QSqlError err = qx::dao::detail::QxDao_Update<T>::update(query, t, pDatabase, columns); if (err.isValid()) { throw qx::dao::sql_error(err); } }
/*!
* \ingroup QxDao
* \brief Update only modified fields/properties of an element or a list of elements into database (using is dirty pattern and qx::dao::ptr<T> smart-pointer)
* \param ptr Element (or list of elements) to be updated into database
* \param pDatabase Connection to database (you can manage your own connection pool for example, you can also define a transaction, etc.); if NULL, a valid connection for the current thread is provided by qx::QxSqlDatabase singleton class (optional parameter)
* \return Throw a <i>qx::dao::sql_error</i> exception when a SQL error occurred
*
* qx::dao::throwable::update_optimized<T>() execute following SQL query :<br>
* <i>UPDATE my_table SET my_column_1 = ?, my_column_2 = ?, etc.</i>
*/
template <class T>
inline void update_optimized(qx::dao::ptr<T> & ptr, QSqlDatabase * pDatabase = NULL)
{ QSqlError err = qx::dao::detail::QxDao_Update_Optimized<T>::update_optimized("", ptr, pDatabase); if (err.isValid()) { throw qx::dao::sql_error(err); } }
/*!
* \ingroup QxDao
* \brief Update only modified fields/properties of an element or a list of elements into database (using is dirty pattern and qx::dao::ptr<T> smart-pointer), adding a user SQL query to the default SQL query builded by QxOrm library
* \param query Define a user SQL query added to default SQL query builded by QxOrm library
* \param ptr Element (or list of elements) to be updated into database
* \param pDatabase Connection to database (you can manage your own connection pool for example, you can also define a transaction, etc.); if NULL, a valid connection for the current thread is provided by qx::QxSqlDatabase singleton class (optional parameter)
* \return Throw a <i>qx::dao::sql_error</i> exception when a SQL error occurred
*
* qx::dao::throwable::update_optimized_by_query<T>() execute following SQL query :<br>
* <i>UPDATE my_table SET my_column_1 = ?, my_column_2 = ?, etc.</i> + <i>WHERE my_query...</i>
*/
template <class T>
inline void update_optimized_by_query(const qx::QxSqlQuery & query, qx::dao::ptr<T> & ptr, QSqlDatabase * pDatabase = NULL)
{ QSqlError err = qx::dao::detail::QxDao_Update_Optimized<T>::update_optimized(query, ptr, pDatabase); if (err.isValid()) { throw qx::dao::sql_error(err); } }
/*!
* \ingroup QxDao
* \brief Execute a custom SQL query or a stored procedure, all columns that can be mapped to the instance of type T will be fetched automatically
* \param query Define a custom SQL query or a stored procedure to call
* \param t Instance of type T, all columns that can be mapped to this instance will be fetched automatically
* \param pDatabase Connection to database (you can manage your own connection pool for example, you can also define a transaction, etc.); if NULL, a valid connection for the current thread is provided by qx::QxSqlDatabase singleton class (optional parameter)
* \return Throw a <i>qx::dao::sql_error</i> exception when a SQL error occurred
*/
template <class T>
inline void execute_query(qx::QxSqlQuery & query, T & t, QSqlDatabase * pDatabase = NULL)
{ QSqlError err = qx::dao::detail::QxDao_ExecuteQuery<T>::executeQuery(query, t, pDatabase); if (err.isValid()) { throw qx::dao::sql_error(err); } }
inline void call_query(qx::QxSqlQuery & query, QSqlDatabase * pDatabase = NULL)
{ QSqlError err = qx::dao::call_query(query, pDatabase); if (err.isValid()) { throw qx::dao::sql_error(err); } }
/// @endcond
} // namespace throwable
} // namespace dao
} // namespace qx
#endif // _QX_DAO_THROWABLE_H_
| 73.301153 | 451 | 0.737827 | [
"object"
] |
87b03e98328bf83b2269793fab45ad85cc1be5d8 | 1,620 | h | C | include/icsneo/device/tree/neovifire2/neovifire2.h | bretzlaff/libicsneo | 1796cf9487ebf04013118cb2b577c0eea2ad8e18 | [
"BSD-3-Clause"
] | null | null | null | include/icsneo/device/tree/neovifire2/neovifire2.h | bretzlaff/libicsneo | 1796cf9487ebf04013118cb2b577c0eea2ad8e18 | [
"BSD-3-Clause"
] | null | null | null | include/icsneo/device/tree/neovifire2/neovifire2.h | bretzlaff/libicsneo | 1796cf9487ebf04013118cb2b577c0eea2ad8e18 | [
"BSD-3-Clause"
] | null | null | null | #ifndef __NEOVIFIRE2_H_
#define __NEOVIFIRE2_H_
#ifdef __cplusplus
#include "icsneo/device/device.h"
#include "icsneo/device/devicetype.h"
#include "icsneo/platform/ftdi.h"
namespace icsneo {
class NeoVIFIRE2 : public Device {
public:
static constexpr DeviceType::Enum DEVICE_TYPE = DeviceType::FIRE2;
static constexpr const char* SERIAL_START = "CY";
static const std::vector<Network>& GetSupportedNetworks() {
static std::vector<Network> supportedNetworks = {
Network::NetID::HSCAN,
Network::NetID::MSCAN,
Network::NetID::HSCAN2,
Network::NetID::HSCAN3,
Network::NetID::HSCAN4,
Network::NetID::HSCAN5,
Network::NetID::HSCAN6,
Network::NetID::HSCAN7,
Network::NetID::LSFTCAN,
Network::NetID::LSFTCAN2,
Network::NetID::SWCAN,
Network::NetID::SWCAN2,
Network::NetID::Ethernet,
Network::NetID::LIN,
Network::NetID::LIN2,
Network::NetID::LIN3,
Network::NetID::LIN4
};
return supportedNetworks;
}
protected:
NeoVIFIRE2(neodevice_t neodevice) : Device(neodevice) {
getWritableNeoDevice().type = DEVICE_TYPE;
}
virtual void setupEncoder(Encoder& encoder) override {
Device::setupEncoder(encoder);
encoder.supportCANFD = true;
}
virtual void setupSupportedRXNetworks(std::vector<Network>& rxNetworks) override {
for(auto& netid : GetSupportedNetworks())
rxNetworks.emplace_back(netid);
}
// The supported TX networks are the same as the supported RX networks for this device
virtual void setupSupportedTXNetworks(std::vector<Network>& txNetworks) override { setupSupportedRXNetworks(txNetworks); }
};
}
#endif // __cplusplus
#endif | 24.179104 | 123 | 0.735802 | [
"vector"
] |
87c43483b38a4ab048d0c478fbae760d22a969a8 | 3,354 | h | C | Code/Components/Synthesis/synthesis/current/measurementequation/IMeasurementEquation.h | rtobar/askapsoft | 6bae06071d7d24f41abe3f2b7f9ee06cb0a9445e | [
"BSL-1.0",
"Apache-2.0",
"OpenSSL"
] | 1 | 2020-06-18T08:37:43.000Z | 2020-06-18T08:37:43.000Z | Code/Components/Synthesis/synthesis/current/measurementequation/IMeasurementEquation.h | ATNF/askapsoft | d839c052d5c62ad8a511e58cd4b6548491a6006f | [
"BSL-1.0",
"Apache-2.0",
"OpenSSL"
] | null | null | null | Code/Components/Synthesis/synthesis/current/measurementequation/IMeasurementEquation.h | ATNF/askapsoft | d839c052d5c62ad8a511e58cd4b6548491a6006f | [
"BSL-1.0",
"Apache-2.0",
"OpenSSL"
] | null | null | null | /// @file
///
/// @brief An abstract measurement equation.
/// @details To be able to use common code regardless on the type of the
/// measurement equaiton used (i.e. ComponentEquation, ImageFFTEquation, etc)
/// we need a common ancestor of the measurement equation classes.
/// askap::scimath::Equation is not specialised enough for this purpose.
///
/// @copyright (c) 2007 CSIRO
/// Australia Telescope National Facility (ATNF)
/// Commonwealth Scientific and Industrial Research Organisation (CSIRO)
/// PO Box 76, Epping NSW 1710, Australia
/// atnf-enquiries@csiro.au
///
/// This file is part of the ASKAP software distribution.
///
/// The ASKAP software distribution is free software: you can redistribute it
/// and/or modify it under the terms of the GNU General Public License as
/// published by the Free Software Foundation; either version 2 of the License,
/// or (at your option) any later version.
///
/// This program is distributed in the hope that it will be useful,
/// but WITHOUT ANY WARRANTY; without even the implied warranty of
/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
/// GNU General Public License for more details.
///
/// You should have received a copy of the GNU General Public License
/// along with this program; if not, write to the Free Software
/// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
///
/// @author Max Voronkov <maxim.voronkov@csiro.au>
#ifndef I_MEASUREMENT_EQUATION_H
#define I_MEASUREMENT_EQUATION_H
// own includes
#include <fitting/INormalEquations.h>
#include <dataaccess/IDataAccessor.h>
#include <dataaccess/IConstDataAccessor.h>
namespace askap {
namespace synthesis {
/// @brief An abstract measurement equation.
/// @details To be able to use common code regardless on the type of the
/// measurement equaiton used (i.e. ComponentEquation, ImageFFTEquation, etc)
/// we need a common ancestor of the measurement equation classes.
/// askap::scimath::Equation is not specialised enough for this purpose.
/// @ingroup measurementequation
struct IMeasurementEquation
{
/// @brief empty virtual descrtuctor to make the compiler happy
virtual ~IMeasurementEquation();
/// @brief Predict model visibilities for one accessor (chunk).
/// @details This prediction is done for single chunk of data only.
/// It seems that all measurement equations should work with accessors
/// rather than iterators (i.e. the iteration over chunks should be
/// moved to the higher level, outside this class).
/// @param[in] chunk a read-write accessor to work with
virtual void predict(accessors::IDataAccessor &chunk) const = 0;
/// @brief Calculate the normal equation for one accessor (chunk).
/// @details This calculation is done for a single chunk of
/// data only (one iteration).It seems that all measurement
/// equations should work with accessors rather than iterators
/// (i.e. the iteration over chunks should be moved to the higher
/// level, outside this class).
/// @param[in] chunk a read-write accessor to work with
/// @param[in] ne Normal equations
virtual void calcEquations(const accessors::IConstDataAccessor &chunk,
askap::scimath::INormalEquations& ne) const = 0;
};
} // namespace synthesis
} // namespace askap
#endif // #ifndef I_MEASUREMENT_EQUATION_H
| 40.409639 | 79 | 0.737329 | [
"model"
] |
87c5342ff09c355112bcea4d991d3169ae5fac49 | 1,256 | h | C | TileMap.h | Conr86/DarkWaterMapEditor | 0a544e8c55f2c7a2e6a1fb21f5674202207ad55d | [
"MIT"
] | null | null | null | TileMap.h | Conr86/DarkWaterMapEditor | 0a544e8c55f2c7a2e6a1fb21f5674202207ad55d | [
"MIT"
] | null | null | null | TileMap.h | Conr86/DarkWaterMapEditor | 0a544e8c55f2c7a2e6a1fb21f5674202207ad55d | [
"MIT"
] | null | null | null | #ifndef TILEMAP_H
#define TILEMAP_H
#include <SFML/Graphics.hpp>
#include <vector>
#include <map>
class TileMap : public sf::Drawable, public sf::Transformable
{
public:
// the map size is stored as a Vector2i, basically a pair, but accessable using .x and .y
std::pair<int,int> map_size;
// something used to create the map, calculated in the load function
int tileSetConstant;
// function to get size of map from parsed tile_data
void calcMapSize(std::map<std::pair<int,int>,int> tiles);
// tiles are stored as a map. with the position (a pair of ints) as the key and the type (int) as the value
std::map<std::pair<int,int>,int> load(const std::string map_file, const std::string& tileset, int tileSize);
// save to file
bool save(std::map<std::pair<int,int>,int> tiles, std::string fileName);
// creates the map drawable thing
void create (std::map<std::pair<int,int>,int> tiles, const std::string& tileset, int tileSize);
sf::Texture m_tileset;
private:
virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const;
sf::VertexArray m_vertices;
//sf::Texture m_tileset;
};
#endif // TILEMAP_H
| 33.052632 | 116 | 0.657643 | [
"vector"
] |
87ca34f384fc64dd45ac150641fa31ff38b78cc4 | 3,024 | h | C | kmer_counter/kb_collector.h | RabbitBio/RabbitUniq | 63b2ac93690e28c024adb83264e644b187472697 | [
"MIT"
] | null | null | null | kmer_counter/kb_collector.h | RabbitBio/RabbitUniq | 63b2ac93690e28c024adb83264e644b187472697 | [
"MIT"
] | null | null | null | kmer_counter/kb_collector.h | RabbitBio/RabbitUniq | 63b2ac93690e28c024adb83264e644b187472697 | [
"MIT"
] | null | null | null | /*
This file is a part of KMC software distributed under GNU GPL 3 licence.
The homepage of the KMC project is http://sun.aei.polsl.pl/kmc
Authors: Sebastian Deorowicz, Agnieszka Debudaj-Grabysz, Marek Kokot
Version: 3.1.1
Date : 2019-05-19
*/
#ifndef _KB_COLLECTOR_H
#define _KB_COLLECTOR_H
#include "defs.h"
#include "params.h"
#include "kmer.h"
#include "queues.h"
#include "radix.h"
#include "rev_byte.h"
#include <string>
#include <algorithm>
#include <numeric>
#include <array>
#include <vector>
#include <stdio.h>
using namespace std;
//----------------------------------------------------------------------------------
// Class collecting kmers belonging to a single bin
class CKmerBinCollector
{
list<pair<uint64, uint64>> expander_parts; //range, n_plus_x_recs_in_range
uint64 prev_n_plus_x_recs = 0;
uint64 prev_pos = 0;
enum comparision_state { kmer_smaller, rev_smaller, equals };
uint32 bin_no;
CBinPartQueue *bin_part_queue;
CBinDesc *bd;
uint32 kmer_len;
uchar* buffer;
uint32 buffer_size;
uint32 buffer_pos;
uint32 super_kmer_no = 0;
const uint32 max_super_kmers_expander_pack = 1ul << 12;
CMemoryPool *pmm_bins;
uint32 n_recs;
uint32 n_plus_x_recs;
uint32 n_super_kmers;
uint32 max_x;
uint32 kmer_bytes;
bool both_strands;
template<unsigned DIVIDE_FACTOR> void update_n_plus_x_recs(char* seq, uint32 n);
public:
CKmerBinCollector(CKMCQueues& Queues, CKMCParams& Params, uint32 _buffer_size, uint32 _bin_no);
void PutExtendedKmer(uint64 id, char* seq, uint32 n);
void Flush();
};
//---------------------------------------------------------------------------------
template<unsigned DIVIDE_FACTOR> void CKmerBinCollector::update_n_plus_x_recs(char* seq, uint32 n)
{
uchar kmer, rev;
uint32 kmer_pos = 4;
uint32 rev_pos = kmer_len;
uint32 x;
kmer = (seq[0] << 6) + (seq[1] << 4) + (seq[2] << 2) + seq[3];
// [haoz:] before change encode strategy
//rev = ((3 - seq[kmer_len - 1]) << 6) + ((3 - seq[kmer_len - 2]) << 4) + ((3 - seq[kmer_len - 3]) << 2) + (3 - seq[kmer_len - 4]);
rev = ((0b10 ^ seq[kmer_len - 1]) << 6) + ((0b10 ^ seq[kmer_len - 2]) << 4) + ((0b10 ^ seq[kmer_len - 3]) << 2) + (0b10 ^ seq[kmer_len - 4]);
x = 0;
comparision_state current_state, new_state;
if (kmer < rev)
current_state = kmer_smaller;
else if (rev < kmer)
current_state = rev_smaller;
else
current_state = equals;
for (uint32 i = 0; i < n - kmer_len; ++i)
{
rev >>= 2;
// [haoz:] before change encode strategy
// rev += (3 - seq[rev_pos++]) << 6;
rev += (0b10 ^ seq[rev_pos++]) << 6;
kmer <<= 2;
kmer += seq[kmer_pos++];
if (kmer < rev)
new_state = kmer_smaller;
else if (rev < kmer)
new_state = rev_smaller;
else
new_state = equals;
if (new_state == current_state)
{
if (current_state == equals)
++n_plus_x_recs;
else
++x;
}
else
{
current_state = new_state;
n_plus_x_recs += 1 + x / DIVIDE_FACTOR;
x = 0;
}
}
n_plus_x_recs += 1 + x / DIVIDE_FACTOR;
}
#endif
// ***** EOF
| 24 | 142 | 0.631283 | [
"vector"
] |
87cc120e99ef9ef2cec096e9628924ce7422df3a | 1,857 | h | C | lite/backends/cuda/nvtx_wrapper.h | wanglei91/Paddle-Lite | 8b2479f4cdd6970be507203d791bede5a453c09d | [
"Apache-2.0"
] | 1,799 | 2019-08-19T03:29:38.000Z | 2022-03-31T14:30:50.000Z | lite/backends/cuda/nvtx_wrapper.h | wanglei91/Paddle-Lite | 8b2479f4cdd6970be507203d791bede5a453c09d | [
"Apache-2.0"
] | 3,767 | 2019-08-19T03:36:04.000Z | 2022-03-31T14:37:26.000Z | lite/backends/cuda/nvtx_wrapper.h | wanglei91/Paddle-Lite | 8b2479f4cdd6970be507203d791bede5a453c09d | [
"Apache-2.0"
] | 798 | 2019-08-19T02:28:23.000Z | 2022-03-31T08:31:54.000Z | // Copyright (c) 2020 PaddlePaddle Authors. 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.
#pragma once
#include <cuda.h>
#include <cuda_runtime.h>
#include "nvtx3/nvToolsExt.h"
namespace paddle {
namespace lite {
enum class Color : uint32_t {
Engine = 0xFFD2691E,
Runner = 0xFFFFD700,
};
// Generate an NVTX range that is started when `generate` is called
// and closed when the object is destroyed.
class NVTXRangeAnnotation {
public:
explicit NVTXRangeAnnotation(nvtxDomainHandle_t domain);
NVTXRangeAnnotation(NVTXRangeAnnotation&& other);
NVTXRangeAnnotation(const NVTXRangeAnnotation&) = delete;
NVTXRangeAnnotation& operator=(const NVTXRangeAnnotation&) = delete;
~NVTXRangeAnnotation();
void generate(nvtxStringHandle_t stringHandle, Color color);
private:
nvtxDomainHandle_t domain_;
bool isGenerating_;
};
class NVTXAnnotator {
public:
static const NVTXAnnotator& Global();
public:
bool IsEnabled() const;
NVTXRangeAnnotation AnnotateBlock() const;
nvtxStringHandle_t RegisterString(const char*) const;
private:
// Only a global instance of that object is allowed.
// It can be accessed by call `NVTXAnnotator::Global()` function.
explicit NVTXAnnotator(const char* domainName);
private:
nvtxDomainHandle_t domain_;
};
} // namespace lite
} // namespace paddle
| 29.015625 | 75 | 0.756058 | [
"object"
] |
0ce1539aee5bfe1577926c9bee83d27ccb049c0f | 6,206 | h | C | ThirdParty/JSBSim/include/models/FGInput.h | Lynnvon/FlightSimulator | 2dca6f8364b7f4972a248de3dbc3a711740f5ed4 | [
"MIT"
] | 1 | 2022-02-03T08:29:35.000Z | 2022-02-03T08:29:35.000Z | ThirdParty/JSBSim/include/models/FGInput.h | Lynnvon/FlightSimulator | 2dca6f8364b7f4972a248de3dbc3a711740f5ed4 | [
"MIT"
] | null | null | null | ThirdParty/JSBSim/include/models/FGInput.h | Lynnvon/FlightSimulator | 2dca6f8364b7f4972a248de3dbc3a711740f5ed4 | [
"MIT"
] | null | null | null | /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Header: FGInput.h
Author: Jon Berndt
Date started: 12/2/98
------------- Copyright (C) 1999 Jon S. Berndt (jon@jsbsim.org) -------------
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
details.
You should have received a copy of the GNU Lesser General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA.
Further information about the GNU Lesser General Public License can also be found on
the world wide web at http://www.gnu.org.
HISTORY
--------------------------------------------------------------------------------
12/02/98 JSB Created
19/01/15 PCH Split the code in several classes (see input_output dir)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SENTRY
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
#ifndef FGINPUT_H
#define FGINPUT_H
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
INCLUDES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
#include "FGModel.h"
#include "input_output/FGInputType.h"
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
FORWARD DECLARATIONS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
namespace JSBSim {
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CLASS DOCUMENTATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/** Handles simulation input.
INPUT section definition
The following specifies the way that JSBSim writes out data.
<pre>
NAME is the filename you want the input to come from
TYPE can be:
SOCKET Will eventually send data to a socket input, where NAME
would then be the IP address of the machine the data should
be sent to. DON'T USE THIS YET!
NONE Specifies to do nothing. This setting makes it easy to turn on and
off the data input without having to mess with anything else.
Examples:
</pre>
@code
<input type="SOCKET" port="4321"/>
@endcode
<br>
The class FGInput is the manager of the inputs requested by the user. It
manages a list of instances derived from the abstract class FGInputType.
*/
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CLASS DECLARATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
class FGInput : public FGModel
{
public:
FGInput(FGFDMExec*);
~FGInput() override;
/** Load the input directives and adds a new input instance to the Input
Manager list.
@param el XMLElement that is pointing to the input directives
@result true if the execution succeeded. */
bool Load(Element* el) override;
/** Initializes the instance. This method is called by FGFDMExec::RunIC().
This is were the initialization of all classes derived from FGInputType
takes place. It is important that this method is not called prior
to FGFDMExec::RunIC() so that the initialization process can be executed
properly.
@result true if the execution succeeded. */
bool InitModel(void) override;
/** Runs the Input model; called by the Executive
Can pass in a value indicating if the executive is directing the simulation to Hold.
@param Holding if true, the executive has been directed to hold the sim from
advancing time. Some models may ignore this flag, such as the Input
model, which may need to be active to listen on a socket for the
"Resume" command to be given.
@return false if no error */
bool Run(bool Holding) override;
/** Adds a new input instance to the Input Manager. The definition of the
new input instance is read from a file.
@param fname the name of the file from which the ouput directives should
be read.
@return true if the execution succeeded. */
bool SetDirectivesFile(const SGPath& fname);
/// Enables the input generation for all input instances.
void Enable(void) { enabled = true; }
/// Disables the input generation for all input instances.
void Disable(void) { enabled = false; }
/** Toggles the input generation of each input instance.
@param idx ID of the input instance which input generation will be
toggled.
@result false if the instance does not exist otherwise returns the status
of the input generation (i.e. true if the input has been
enabled, false if the input has been disabled) */
bool Toggle(int idx);
/** Overwrites the name identifier under which the input will be logged.
This method is taken into account if it is called between Load() and
FGFDMExec::RunIC() otherwise it is ignored until the next call to
SetStartNewInput().
@param idx ID of the instance which name identifier will be changed
@param name new name
@result false if the instance does not exists. */
bool SetInputName(unsigned int idx, const std::string& name);
/** Get the name identifier to which the input will be directed.
@param idx ID of the input instance from which the name identifier must
be obtained
@result the name identifier.*/
std::string GetInputName(unsigned int idx) const;
private:
std::vector<FGInputType*> InputTypes;
bool enabled;
void Debug(int from) override;
};
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#endif
| 40.03871 | 90 | 0.581212 | [
"vector",
"model"
] |
0ce8be9ce2ad8950ce5c230e616bcb086ccecf37 | 6,621 | h | C | modules/platforms/cpp/benchmarks/include/ignite/benchmarks/odbc_utils.h | tsdb-io/gridgain | 6726ed9cc34a7d2671a3625600c375939d40bc35 | [
"CC0-1.0"
] | 218 | 2015-01-04T13:20:55.000Z | 2022-03-28T05:28:55.000Z | modules/platforms/cpp/benchmarks/include/ignite/benchmarks/odbc_utils.h | tsdb-io/gridgain | 6726ed9cc34a7d2671a3625600c375939d40bc35 | [
"CC0-1.0"
] | 175 | 2015-02-04T23:16:56.000Z | 2022-03-28T18:34:24.000Z | modules/platforms/cpp/benchmarks/include/ignite/benchmarks/odbc_utils.h | tsdb-io/gridgain | 6726ed9cc34a7d2671a3625600c375939d40bc35 | [
"CC0-1.0"
] | 93 | 2015-01-06T20:54:23.000Z | 2022-03-31T08:09:00.000Z | /*
* Copyright 2020 GridGain Systems, Inc. and Contributors.
*
* Licensed under the GridGain Community Edition License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gridgain.com/products/software/community-edition/gridgain-community-edition-license
*
* 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.
*/
#ifndef IGNITE_BENCHMARKS_ODBC_UTILS_H
#define IGNITE_BENCHMARKS_ODBC_UTILS_H
#include <ignite/benchmarks/utils.h>
#include <sql.h>
#include <sqlext.h>
#include <vector>
#include <string>
#include <sstream>
#include <boost/chrono.hpp>
#include <boost/thread.hpp>
namespace odbc_utils
{
/** Read buffer size. */
enum { ODBC_BUFFER_SIZE = 1024 };
/**
* Represents simple string buffer.
*/
struct OdbcStringBuffer
{
SQLCHAR buffer[ODBC_BUFFER_SIZE];
SQLLEN reallen;
};
/**
* Fetch result set returned by query.
*
* @param stmt Statement.
*/
void FetchOdbcResultSet(SQLHSTMT stmt)
{
SQLSMALLINT columnsCnt = 0;
// Getting number of columns in result set.
SQLNumResultCols(stmt, &columnsCnt);
std::vector<OdbcStringBuffer> columns(columnsCnt);
// Binding colums.
for (SQLSMALLINT i = 0; i < columnsCnt; ++i)
SQLBindCol(stmt, i + 1, SQL_C_DEFAULT, columns[i].buffer, ODBC_BUFFER_SIZE, &columns[i].reallen);
while (true)
{
SQLRETURN ret = SQLFetch(stmt);
if (!SQL_SUCCEEDED(ret))
break;
}
}
/**
* Extract error message.
*
* @param handleType Type of the handle.
* @param handle Handle.
* @return Error message.
*/
std::string GetOdbcErrorMessage(SQLSMALLINT handleType, SQLHANDLE handle)
{
SQLCHAR sqlstate[7] = {};
SQLINTEGER nativeCode;
SQLCHAR message[ODBC_BUFFER_SIZE];
SQLSMALLINT reallen = 0;
SQLGetDiagRec(handleType, handle, 1, sqlstate, &nativeCode, message, ODBC_BUFFER_SIZE, &reallen);
return std::string(reinterpret_cast<char*>(sqlstate)) + ": " +
std::string(reinterpret_cast<char*>(message), reallen);
}
/**
* Extract error from ODBC handle and throw it as runtime_error.
*
* @param handleType Type of the handle.
* @param handle Handle.
* @param msg Error message.
*/
void ThrowOdbcError(SQLSMALLINT handleType, SQLHANDLE handle, std::string msg)
{
std::stringstream builder;
builder << msg << ": " << GetOdbcErrorMessage(handleType, handle);
throw std::runtime_error(builder.str());
}
/**
* Check that ODBC operation complete successfully.
*
* @param ret Value returned by the operation.
* @param handleType Type of the handle.
* @param handle Handle.
* @param msg Error message.
*/
void CheckOdbcOperation(SQLRETURN ret, SQLSMALLINT handleType, SQLHANDLE handle, std::string msg)
{
if (!SQL_SUCCEEDED(ret))
ThrowOdbcError(handleType, handle, msg);
}
/**
* Execute SQL query using ODBC interface.
*/
SQLHSTMT Execute(SQLHDBC dbc, const std::string& query)
{
SQLHSTMT stmt;
// Allocate a statement handle
SQLAllocHandle(SQL_HANDLE_STMT, dbc, &stmt);
std::vector<SQLCHAR> buf(query.begin(), query.end());
SQLRETURN ret = SQLExecDirect(stmt, &buf[0], static_cast<SQLSMALLINT>(buf.size()));
CheckOdbcOperation(ret, SQL_HANDLE_STMT, stmt, "Failed to execute query");
return stmt;
}
/**
* Fetch cache data using ODBC interface.
*/
void ExecuteAndFetch(SQLHDBC dbc, const std::string& query)
{
SQLHSTMT stmt = Execute(dbc, query);
FetchOdbcResultSet(stmt);
// Releasing statement handle.
SQLFreeHandle(SQL_HANDLE_STMT, stmt);
}
/**
* Insert data using ODBC interface.
*/
void ExecuteNoFetch(SQLHDBC dbc, const std::string& query)
{
SQLHSTMT stmt = Execute(dbc, query);
// Releasing statement handle.
SQLFreeHandle(SQL_HANDLE_STMT, stmt);
}
/**
* Get next row.
*
* @param stmt Statement.
*/
void NextRow(SQLHSTMT stmt)
{
SQLRETURN ret = SQLFetch(stmt);
CheckOdbcOperation(ret, SQL_HANDLE_STMT, stmt, "Failed to get next row");
}
/**
* Get single field of the current row.
*
* @param stmt Statement.
* @param idx Column index.
* @param resType Result type.
*/
template<typename T>
T GetSigleColumn(SQLHSTMT stmt, int32_t idx, int resType = SQL_C_SBIGINT)
{
T val;
SQLRETURN ret = SQLGetData(stmt, idx, resType, &val, 0, 0);
CheckOdbcOperation(ret, SQL_HANDLE_STMT, stmt, "Failed to get field");
return val;
}
/**
* Utility OdbcLock class.
*
* Based on atomicity of table creation.
*/
class OdbcLock
{
public:
OdbcLock(SQLHDBC dbc, const std::string& lockName) :
locked(false),
dbc(dbc),
lockName(lockName)
{
// No-op.
}
/**
* Try get a lock for
*
* @return true if locked.
*/
bool TryLock()
{
if (locked)
return true;
try
{
odbc_utils::ExecuteNoFetch(dbc, "CREATE TABLE PUBLIC." + lockName + " (id int primary key, field1 int)");
locked = true;
}
catch (std::exception&)
{
locked = false;
}
return locked;
}
/**
* Timed lock.
* @param secs Timeout in seconds.
* @return @c true if successfully locked within timeout.
*/
bool TimedLock(int64_t secs)
{
using namespace boost;
chrono::steady_clock::time_point begin = chrono::steady_clock::now();
chrono::steady_clock::time_point now = begin;
while (chrono::duration_cast<chrono::seconds>(now - begin).count() < secs)
{
TryLock();
if (locked)
return true;
this_thread::sleep_for(chrono::milliseconds(500));
now = chrono::steady_clock::now();
}
return locked;
}
/**
* Unlock.
*/
void Unlock()
{
if (!locked)
return;
try
{
odbc_utils::ExecuteNoFetch(dbc, "DROP TABLE PUBLIC." + lockName);
}
catch (std::exception&)
{
// No-op.
}
locked = false;
}
~OdbcLock()
{
Unlock();
}
private:
/** Lock flag. */
bool locked;
/** Connection. */
SQLHDBC dbc;
/** Lock name. */
std::string lockName;
};
} // namespace odbc_utils
#endif // IGNITE_BENCHMARKS_ODBC_UTILS_H
| 21.923841 | 117 | 0.640085 | [
"vector"
] |
0cf12b53286cbc37eaab478574bc47688b1af538 | 3,857 | h | C | core/sql/common/NAHeap.h | anoopsharma00/incubator-trafodion | b109e2cf5883f8e763af853ab6fad7ce7110d9e8 | [
"Apache-2.0"
] | null | null | null | core/sql/common/NAHeap.h | anoopsharma00/incubator-trafodion | b109e2cf5883f8e763af853ab6fad7ce7110d9e8 | [
"Apache-2.0"
] | null | null | null | core/sql/common/NAHeap.h | anoopsharma00/incubator-trafodion | b109e2cf5883f8e763af853ab6fad7ce7110d9e8 | [
"Apache-2.0"
] | null | null | null | /* -*-C++-*-
*****************************************************************************
*
* File: NAHeap.h
* Description: The memory management classes for Noah Ark sql.
*
* Created: 9/28/96
* Language: C++
*
// @@@ START COPYRIGHT @@@
//
// 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.
//
// @@@ END COPYRIGHT @@@
*
*****************************************************************************
*/
// -----------------------------------------------------------------------
#ifndef NAHEAP__H
#define NAHEAP__H
#include "ComSpace.h"
#ifdef NA_STD_NAMESPACE
#include <iosfwd>
using namespace std;
#else
class ostream;
#endif
// -----------------------------------------------------------------------
// This file contains the memory management classes :
//
// -class CollHeap - abstract base class. defined in CollHeap.h
// allocateMemory, deallocateMemory methods defined.
//
// -class NASpace: public CollHeap
// NASpace acts as a Space in exp_space.h
//
// -class NAMFHeap: public CollHeap
// NAMFHeap use malloc/free.
//
// -examples:
// class YourHeap : public CollHeap
// implement your allocateMemory and deallocateMemory methods.
//
// class YourClass : NABasicObject
//
// then, you can do
// YourHeap* aHeap = new YourHeap;
// YourClass* object = new (aHeap) YourClass(aHeap);
// the memory will be allocated through YourHeap
// YourClass* sysObject = new YourClass;
// the memory will be allocated through global new
// delete object;
// delete sysObject;
// the memory allocated will be freed accordingly.
//
// - Some new operators and macro defines (for delete) for CollHeap*
// memory management.
// These are for classes/types that can NOT be derived from NABasicObject.
// e.g. RW classes, basic types, .etc. Also for the new of array which
// goes through the global new/delete always.
// void * operator new(size_t size, CollHeap* h);
// NADELETEBASIC
// NADELETE
// NADELETEARRAY
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
// NASpace is a space that will use the Space for memory allocation.
// And it acts just like a space, i.e. the memory deallocated will not
// be reused.
// -----------------------------------------------------------------------
class NASpace : public CollHeap
{
public:
NA_EIDPROC
NASpace(Space::SpaceType t=Space::SYSTEM_SPACE);
NA_EIDPROC
virtual ~NASpace();
NA_EIDPROC
virtual void * allocateMemory(size_t size, NABoolean failureIsFatal = TRUE);
NA_EIDPROC
virtual void deallocateMemory(void*)
{
#ifdef NAHEAP__DEBUG
cout << "NASpace::deallocateMemory()\n";
#endif
}
#if (defined(_DEBUG) || defined(NSK_MEMDEBUG)) && !defined(__EID)
NA_EIDPROC
virtual void dump(ostream* outstream, Lng32 indent) {};
#else
NA_EIDPROC
inline void dump(void* outstream, Lng32 indent) {}
#endif
private:
NA_EIDPROC
NASpace(const NASpace&);
NA_EIDPROC
NASpace& operator =(const NASpace&);
Space s_;
}; // end of NASpace
#endif
| 28.783582 | 78 | 0.609023 | [
"object"
] |
4904b1bbf43db562936de2db745ea9321965f5e5 | 952 | h | C | Engine/Renderable.h | metalheadjohny/Stale_Memes | 69717ff036471fa642141ac2ff9a23525b475cea | [
"MIT"
] | 1 | 2019-09-02T08:23:40.000Z | 2019-09-02T08:23:40.000Z | Engine/Renderable.h | metalheadjohny/Stale_Memes | 69717ff036471fa642141ac2ff9a23525b475cea | [
"MIT"
] | 3 | 2021-05-09T20:19:23.000Z | 2021-08-10T19:00:19.000Z | Engine/Renderable.h | metalheadjohny/Stale_Memes | 69717ff036471fa642141ac2ff9a23525b475cea | [
"MIT"
] | null | null | null | #pragma once
#include "Model.h"
#include "Material.h"
#include "Shader.h"
class Renderable
{
public:
// Memory heavy but... useful for now I guess?
SMatrix _localTransform;
SMatrix _transform;
Mesh* mesh{};
Material* mat{};
float zDepth{0.f};
Renderable() = default;
Renderable(Mesh& mesh, const SMatrix& transform) : mesh(&mesh), mat(mesh._material.get()), _transform(transform) {}
// Wrong, make material do this. It needs to encapsulate everything. This will become more complex over time.
//void Renderable::updateBuffersAuto(ID3D11DeviceContext* cont) const
//{
// mat->getVS()->updateBuffersAuto(cont, *this);
// mat->getPS()->updateBuffersAuto(cont, *this);
//}
// Same as above. Can't allow this to become a god class.
inline void setBuffers(ID3D11DeviceContext* dc) const
{
mat->getVS()->setBuffers(dc);
mat->getPS()->setBuffers(dc);
}
inline const SMatrix& renderTransform() const
{
return _transform;
}
}; | 23.219512 | 116 | 0.704832 | [
"mesh",
"model",
"transform"
] |
4904b3eca0363ba11ab9d6f06e2671980e66d2bf | 143 | h | C | models/particles2.h | resetius/graphtoys | 28cc9bcfc4dbb60e49ff49dff7cee1c5952518c3 | [
"BSD-3-Clause"
] | null | null | null | models/particles2.h | resetius/graphtoys | 28cc9bcfc4dbb60e49ff49dff7cee1c5952518c3 | [
"BSD-3-Clause"
] | 13 | 2022-01-30T20:37:30.000Z | 2022-02-23T21:15:31.000Z | models/particles2.h | resetius/graphtoys | 28cc9bcfc4dbb60e49ff49dff7cee1c5952518c3 | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#include <lib/object.h>
struct Render;
struct Config;
struct Object* CreateParticles2(struct Render* r, struct Config* config);
| 17.875 | 73 | 0.769231 | [
"render",
"object"
] |
490e372bd356b44ab752af2fa1426c0ee84ba89e | 8,224 | h | C | aws-cpp-sdk-lexv2-models/include/aws/lexv2-models/model/WaitAndContinueSpecification.h | fboranek/aws-sdk-cpp | 2aa01e7d5c5431d9702caf9bf21f4e07b6ef15ae | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-lexv2-models/include/aws/lexv2-models/model/WaitAndContinueSpecification.h | fboranek/aws-sdk-cpp | 2aa01e7d5c5431d9702caf9bf21f4e07b6ef15ae | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-lexv2-models/include/aws/lexv2-models/model/WaitAndContinueSpecification.h | fboranek/aws-sdk-cpp | 2aa01e7d5c5431d9702caf9bf21f4e07b6ef15ae | [
"Apache-2.0"
] | null | null | null | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/lexv2-models/LexModelsV2_EXPORTS.h>
#include <aws/lexv2-models/model/ResponseSpecification.h>
#include <aws/lexv2-models/model/StillWaitingResponseSpecification.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace LexModelsV2
{
namespace Model
{
/**
* <p>Specifies the prompts that Amazon Lex uses while a bot is waiting for
* customer input. </p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/models.lex.v2-2020-08-07/WaitAndContinueSpecification">AWS
* API Reference</a></p>
*/
class AWS_LEXMODELSV2_API WaitAndContinueSpecification
{
public:
WaitAndContinueSpecification();
WaitAndContinueSpecification(Aws::Utils::Json::JsonView jsonValue);
WaitAndContinueSpecification& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>The response that Amazon Lex sends to indicate that the bot is waiting for
* the conversation to continue.</p>
*/
inline const ResponseSpecification& GetWaitingResponse() const{ return m_waitingResponse; }
/**
* <p>The response that Amazon Lex sends to indicate that the bot is waiting for
* the conversation to continue.</p>
*/
inline bool WaitingResponseHasBeenSet() const { return m_waitingResponseHasBeenSet; }
/**
* <p>The response that Amazon Lex sends to indicate that the bot is waiting for
* the conversation to continue.</p>
*/
inline void SetWaitingResponse(const ResponseSpecification& value) { m_waitingResponseHasBeenSet = true; m_waitingResponse = value; }
/**
* <p>The response that Amazon Lex sends to indicate that the bot is waiting for
* the conversation to continue.</p>
*/
inline void SetWaitingResponse(ResponseSpecification&& value) { m_waitingResponseHasBeenSet = true; m_waitingResponse = std::move(value); }
/**
* <p>The response that Amazon Lex sends to indicate that the bot is waiting for
* the conversation to continue.</p>
*/
inline WaitAndContinueSpecification& WithWaitingResponse(const ResponseSpecification& value) { SetWaitingResponse(value); return *this;}
/**
* <p>The response that Amazon Lex sends to indicate that the bot is waiting for
* the conversation to continue.</p>
*/
inline WaitAndContinueSpecification& WithWaitingResponse(ResponseSpecification&& value) { SetWaitingResponse(std::move(value)); return *this;}
/**
* <p>The response that Amazon Lex sends to indicate that the bot is ready to
* continue the conversation.</p>
*/
inline const ResponseSpecification& GetContinueResponse() const{ return m_continueResponse; }
/**
* <p>The response that Amazon Lex sends to indicate that the bot is ready to
* continue the conversation.</p>
*/
inline bool ContinueResponseHasBeenSet() const { return m_continueResponseHasBeenSet; }
/**
* <p>The response that Amazon Lex sends to indicate that the bot is ready to
* continue the conversation.</p>
*/
inline void SetContinueResponse(const ResponseSpecification& value) { m_continueResponseHasBeenSet = true; m_continueResponse = value; }
/**
* <p>The response that Amazon Lex sends to indicate that the bot is ready to
* continue the conversation.</p>
*/
inline void SetContinueResponse(ResponseSpecification&& value) { m_continueResponseHasBeenSet = true; m_continueResponse = std::move(value); }
/**
* <p>The response that Amazon Lex sends to indicate that the bot is ready to
* continue the conversation.</p>
*/
inline WaitAndContinueSpecification& WithContinueResponse(const ResponseSpecification& value) { SetContinueResponse(value); return *this;}
/**
* <p>The response that Amazon Lex sends to indicate that the bot is ready to
* continue the conversation.</p>
*/
inline WaitAndContinueSpecification& WithContinueResponse(ResponseSpecification&& value) { SetContinueResponse(std::move(value)); return *this;}
/**
* <p>A response that Amazon Lex sends periodically to the user to indicate that
* the bot is still waiting for input from the user.</p>
*/
inline const StillWaitingResponseSpecification& GetStillWaitingResponse() const{ return m_stillWaitingResponse; }
/**
* <p>A response that Amazon Lex sends periodically to the user to indicate that
* the bot is still waiting for input from the user.</p>
*/
inline bool StillWaitingResponseHasBeenSet() const { return m_stillWaitingResponseHasBeenSet; }
/**
* <p>A response that Amazon Lex sends periodically to the user to indicate that
* the bot is still waiting for input from the user.</p>
*/
inline void SetStillWaitingResponse(const StillWaitingResponseSpecification& value) { m_stillWaitingResponseHasBeenSet = true; m_stillWaitingResponse = value; }
/**
* <p>A response that Amazon Lex sends periodically to the user to indicate that
* the bot is still waiting for input from the user.</p>
*/
inline void SetStillWaitingResponse(StillWaitingResponseSpecification&& value) { m_stillWaitingResponseHasBeenSet = true; m_stillWaitingResponse = std::move(value); }
/**
* <p>A response that Amazon Lex sends periodically to the user to indicate that
* the bot is still waiting for input from the user.</p>
*/
inline WaitAndContinueSpecification& WithStillWaitingResponse(const StillWaitingResponseSpecification& value) { SetStillWaitingResponse(value); return *this;}
/**
* <p>A response that Amazon Lex sends periodically to the user to indicate that
* the bot is still waiting for input from the user.</p>
*/
inline WaitAndContinueSpecification& WithStillWaitingResponse(StillWaitingResponseSpecification&& value) { SetStillWaitingResponse(std::move(value)); return *this;}
/**
* <p>Specifies whether the bot will wait for a user to respond. When this field is
* false, wait and continue responses for a slot aren't used and the bot expects an
* appropriate response within the configured timeout. If the <code>active</code>
* field isn't specified, the default is true.</p>
*/
inline bool GetActive() const{ return m_active; }
/**
* <p>Specifies whether the bot will wait for a user to respond. When this field is
* false, wait and continue responses for a slot aren't used and the bot expects an
* appropriate response within the configured timeout. If the <code>active</code>
* field isn't specified, the default is true.</p>
*/
inline bool ActiveHasBeenSet() const { return m_activeHasBeenSet; }
/**
* <p>Specifies whether the bot will wait for a user to respond. When this field is
* false, wait and continue responses for a slot aren't used and the bot expects an
* appropriate response within the configured timeout. If the <code>active</code>
* field isn't specified, the default is true.</p>
*/
inline void SetActive(bool value) { m_activeHasBeenSet = true; m_active = value; }
/**
* <p>Specifies whether the bot will wait for a user to respond. When this field is
* false, wait and continue responses for a slot aren't used and the bot expects an
* appropriate response within the configured timeout. If the <code>active</code>
* field isn't specified, the default is true.</p>
*/
inline WaitAndContinueSpecification& WithActive(bool value) { SetActive(value); return *this;}
private:
ResponseSpecification m_waitingResponse;
bool m_waitingResponseHasBeenSet;
ResponseSpecification m_continueResponse;
bool m_continueResponseHasBeenSet;
StillWaitingResponseSpecification m_stillWaitingResponse;
bool m_stillWaitingResponseHasBeenSet;
bool m_active;
bool m_activeHasBeenSet;
};
} // namespace Model
} // namespace LexModelsV2
} // namespace Aws
| 40.512315 | 170 | 0.715953 | [
"model"
] |
491041b417667fa6ca30750727d91b4164566bb9 | 4,278 | h | C | DisplayLib/OpenGL/Display.h | cdoty/SuperPlay | e2d33cb52635251cd3f180b73f5fb08944940d18 | [
"MIT"
] | 26 | 2015-01-23T03:07:12.000Z | 2021-11-14T20:35:03.000Z | DisplayLib/OpenGL/Display.h | cdoty/SuperPlay | e2d33cb52635251cd3f180b73f5fb08944940d18 | [
"MIT"
] | 1 | 2016-05-09T22:04:21.000Z | 2016-05-10T03:27:07.000Z | DisplayLib/OpenGL/Display.h | cdoty/SuperPlay | e2d33cb52635251cd3f180b73f5fb08944940d18 | [
"MIT"
] | 8 | 2015-04-13T19:15:36.000Z | 2021-01-13T13:24:45.000Z | #pragma once
#ifdef WIN32
#include <windows.h>
#endif
#if defined __APPLE__
#include <TargetConditionals.h>
#if (TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR)
#define __IOS__
#endif
#endif
#if !defined __ANDROID__ && !defined __IOS__ && !defined MARMALADE && !defined EMSCRIPTEN && !defined ANGLE
#include "GL/glew.h"
#endif
#ifdef __APPLE__
#ifdef __IOS__
#define GL_GLEXT_PROTOTYPES
#include <OpenGLES/ES1/gl.h>
#include <OpenGLES/ES1/glext.h>
#else
#include <OpenGL/gl.h>
#endif
#elif defined __ANDROID__ || defined EMSCRIPTEN || defined ANGLE
#define GL_GLEXT_PROTOTYPES
#include <GLES/gl.h>
#include <GLES/glext.h>
#elif defined MARMALADE
#else
#include <GL/gl.h>
#include <GL/glext.h>
#endif
#include <TinySTL/vector.h>
#include <TinySTL/unordered_map.h>
#include "IDisplay.h"
#include "IndexBuffer.h"
#include "Macros.h"
#include "Texture.h"
#include "Types.h"
#include "VertexBuffer.h"
#if defined WIN32
#include "GLWin32.h"
#elif defined __ANDROID__
#include "GLAndroid.h"
#elif defined MARMALADE
#include "GLMarmalade.h"
#elif defined EMSCRIPTEN
#include "GLEmscripten.h"
#elif defined __linux__
#include "GLLinux.h"
#elif defined __APPLE__
#ifdef __IOS__
#include "GLiOS.h"
#else
#include "GLMacOSX.h"
#endif
#endif
NAMESPACE(SPlay)
class Display : public IDisplay
{
public:
// Constructor
Display();
// Destructor
virtual ~Display();
// Create
static Display* create();
// Initialize
virtual bool initialize();
// Close
virtual void close();
// Render
virtual bool render();
// Clear
virtual void clear(uint32_t _uColor);
// Resize
virtual void resize();
// Create vertex buffer
virtual int createVertexBuffer(int _iVertices, bool _bDynamic);
// Get vertex buffer
virtual VertexBuffer* getVertexBuffer(int _iIndex) const;
// Remove vertex buffer
virtual void removeVertexBuffer(int _iIndex);
// Create index buffer
virtual int createIndexBuffer(int _iVertices, bool _bDynamic);
// Get index buffer
virtual IndexBuffer* getIndexBuffer(int _iIndex) const;
// Remove index buffer
virtual void removeIndexBuffer(int _iIndex);
// Create texture
virtual int createTexture(const char* _szTextureName, int _iWidth, int _iHeight, eFormat _eFormat, bool _bDynamic);
// Get texture
virtual Texture* getTexture(int _iHash);
// Remove texture
virtual void removeTexture(int _iHash);
// Bind texture
virtual void bindTexture(int _iHash);
// Draw triangles
virtual bool drawTriangles(int _iVertexBufferIndex, int _iVertices = 0, int _iIndexBufferIndex = -1,
int _iTriangles = 0);
// Set clip rect
virtual void setClipRect(const Rect& _rctClip);
// Reset clip rect
virtual void resetClipRect();
#ifdef __IOS__
// Set default frame buffer
void setDefaultFrameBuffer(GLuint _uDefaultFrameBuffer) {m_uDefaultFrameBuffer = _uDefaultFrameBuffer;}
#endif
private:
struct TextureData
{
Texture* pTexture;
int iReferenceCount;
};
// GL platform
GLPlatform* m_pGLPlatform;
// Window size
float m_fRenderWidth;
float m_fRenderHeight;
// Render texture UVs
float m_fU2;
float m_fV2;
// Frame buffer
GLuint m_uFrameBuffer;
GLuint m_uRenderTexture;
#ifdef __IOS__
GLuint m_uDefaultFrameBuffer;
#endif
// Vertex buffer
int m_iVertexBuffer;
// Dynamic textures supported?
bool m_bDynamicTextures;
typedef tinystl::unordered_map<size_t, TextureData> TextureMap;
// Textures
TextureMap m_mapTextures;
// Vertex buffers
tinystl::vector<VertexBuffer*> m_vecVertexBuffers;
// Index buffers
tinystl::vector<IndexBuffer*> m_vecIndexBuffers;
// Offset
Point m_ptOffset;
// Initialize OpenGL
bool initializeOpenGL();
// Close OpenGL
void closeOpenGL();
// Setup device
bool setupDevice();
// Create render target
bool createRenderTarget(int _iWidth, int _iHeight, GLint _iFormat = GL_RGBA);
// Create vertex buffer
bool createVertexBuffer();
// Setup vertices
bool setupVertices();
// Setup transform
void setupTransform();
};
ENDNAMESPACE
| 20.76699 | 118 | 0.694717 | [
"render",
"vector",
"transform"
] |
49190320e399befb933e8c9b16019f784c1c177b | 569 | h | C | oneEngine/oneGame/source/after/entities/menu/CTerrainLoadscreen.h | jonting/1Engine | f22ba31f08fa96fe6405ebecec4f374138283803 | [
"BSD-3-Clause"
] | 8 | 2017-12-08T02:59:31.000Z | 2022-02-02T04:30:03.000Z | oneEngine/oneGame/source/after/entities/menu/CTerrainLoadscreen.h | jonting/1Engine | f22ba31f08fa96fe6405ebecec4f374138283803 | [
"BSD-3-Clause"
] | 2 | 2021-04-16T03:44:42.000Z | 2021-08-30T06:48:44.000Z | oneEngine/oneGame/source/after/entities/menu/CTerrainLoadscreen.h | jonting/1Engine | f22ba31f08fa96fe6405ebecec4f374138283803 | [
"BSD-3-Clause"
] | 1 | 2021-04-16T02:09:54.000Z | 2021-04-16T02:09:54.000Z |
#ifndef _C_TERRAIN_LOADSCREEN_H_
#define _C_TERRAIN_LOADSCREEN_H_
#include "renderer/object/CRenderableObject.h"
#include "engine/behavior/CGameBehavior.h"
class CBitmapFont;
class CTerrainLoadscreen : public CRenderableObject, public CGameBehavior
{
public:
CTerrainLoadscreen ( void );
~CTerrainLoadscreen ( void );
void Update ( void );
bool Render ( const char pass );
private:
glMaterial* bgMaterial;
glMaterial* barMaterial;
glMaterial* matFntLoader;
CBitmapFont* fntLoaderText;
ftype currentPercentage;
//ftype targetPercentage;
};
#endif | 17.78125 | 73 | 0.780316 | [
"render",
"object"
] |
492b79946d08db68a8411939501d95326f86c9b8 | 3,170 | h | C | rt_common.h | fixstars/ion-bb-demo | 1cb6183baf453be61e5bb3f8ecbf0cac9d77f841 | [
"MIT"
] | null | null | null | rt_common.h | fixstars/ion-bb-demo | 1cb6183baf453be61e5bb3f8ecbf0cac9d77f841 | [
"MIT"
] | null | null | null | rt_common.h | fixstars/ion-bb-demo | 1cb6183baf453be61e5bb3f8ecbf0cac9d77f841 | [
"MIT"
] | null | null | null | #ifndef ION_BB_DEMO_RT_COMMON_H
#define ION_BB_DEMO_RT_COMMON_H
#include <algorithm>
#include <cstdio>
#include <string>
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#else
#include <dlfcn.h>
#endif
#ifdef _WIN32
#define ION_EXPORT __declspec(dllexport)
#else
#define ION_EXPORT
#endif
namespace ion {
namespace bb {
namespace demo {
template<typename... Rest>
std::string format(const char *fmt, const Rest &... rest) {
int length = snprintf(NULL, 0, fmt, rest...) + 1; // Explicit place for null termination
std::vector<char> buf(length, 0);
snprintf(&buf[0], length, fmt, rest...);
std::string s(buf.begin(), std::find(buf.begin(), buf.end(), '\0'));
return s;
}
class DynamicModule {
public:
#ifdef _WIN32
using Handle = HMODULE;
#else
using Handle = void *;
#endif
DynamicModule(const std::string &module_name, bool essential) {
if (module_name == "") {
handle_ = nullptr;
return;
}
#ifdef _WIN32
auto file_name = module_name + ".dll";
handle_ = LoadLibraryA(file_name.c_str());
#else
auto file_name = "lib" + module_name + ".so";
handle_ = dlopen(file_name.c_str(), RTLD_NOW);
#endif
if (handle_ == nullptr) {
if (essential) {
throw std::runtime_error(get_error_string());
} else {
std::cerr << format("WARNING: Not found the not essential dynamic library: %s, it may work as a simulation mode", module_name.c_str());
}
}
}
~DynamicModule() {
if (handle_ != nullptr) {
#ifdef _WIN32
FreeLibrary(handle_);
#else
dlclose(handle_);
#endif
}
}
DynamicModule(const std::string &module_name)
: DynamicModule(module_name, true) {
}
bool is_available(void) const {
return handle_ != NULL;
}
template<typename T>
T get_symbol(const std::string &symbol_name) const {
#if defined(_WIN32)
return reinterpret_cast<T>(GetProcAddress(handle_, symbol_name.c_str()));
#else
return reinterpret_cast<T>(dlsym(handle_, symbol_name.c_str()));
#endif
}
private:
std::string get_error_string(void) const {
std::string error_msg;
#ifdef _WIN32
LPVOID lpMsgBuf;
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr, GetLastError(),
MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),
(LPTSTR)&lpMsgBuf, 0, nullptr);
std::size_t len = 0;
wcstombs_s(&len, nullptr, 0, reinterpret_cast<const wchar_t *>(lpMsgBuf), _TRUNCATE);
std::vector<char> buf(len + 1, 0);
wcstombs_s(nullptr, &buf[0], len, reinterpret_cast<const wchar_t *>(lpMsgBuf), _TRUNCATE);
error_msg.assign(buf.begin(), buf.end());
LocalFree(lpMsgBuf);
#else
const char *buf(dlerror());
error_msg.assign(buf ? buf : "none");
#endif
return error_msg;
}
Handle handle_;
};
} // namespace demo
} // namespace bb
} // namespace ion
#endif
| 25.564516 | 151 | 0.615457 | [
"vector"
] |
4930282b0d4dc87fe7f7c733ed5fe66304c34ef1 | 1,125 | h | C | app/tenncor/tests/include/util_test.h | mingkaic/rocnnet | b0e6b9ef1b80ee3d33d68f48dd051a99c2df39ab | [
"MIT"
] | 3 | 2017-01-18T20:42:56.000Z | 2018-11-07T12:56:15.000Z | app/tenncor/tests/include/util_test.h | mingkaic/rocnnet | b0e6b9ef1b80ee3d33d68f48dd051a99c2df39ab | [
"MIT"
] | 10 | 2016-12-01T08:15:28.000Z | 2018-09-28T17:16:32.000Z | app/tenncor/tests/include/util_test.h | mingkaic/rocnnet | b0e6b9ef1b80ee3d33d68f48dd051a99c2df39ab | [
"MIT"
] | null | null | null | //
// Created by Mingkai Chen on 2017-03-09.
//
#include <vector>
#include <iostream>
#include "tensor/tensorshape.hpp"
#include "tensor/tensor_handler.hpp"
#ifndef UTIL_TEST_H
#define UTIL_TEST_H
using namespace nnet;
bool tensorshape_equal (
const tensorshape& ts1,
const tensorshape& ts2);
bool tensorshape_equal (
const tensorshape& ts1,
std::vector<size_t>& ts2);
void print (std::vector<double> raw);
tensorshape make_partial (std::vector<size_t> shapelist);
tensorshape make_incompatible (std::vector<size_t> shapelist);
// make partial full, but incompatible to comp
tensorshape make_full_incomp (std::vector<size_t> partial, std::vector<size_t> complete);
tensorshape padd(std::vector<size_t> shapelist, size_t nfront, size_t nback);
std::vector<std::vector<double> > doubleDArr(std::vector<double> v, std::vector<size_t> dimensions);
tensorshape random_shape (void);
tensorshape random_def_shape (int lowerrank = 2, int upperrank = 11, size_t minn = 17, size_t maxn = 7341);
void adder (double* dest, std::vector<const double*> src, nnet::shape_io shape);
#endif /* UTIL_TEST_H */
| 19.396552 | 107 | 0.744 | [
"shape",
"vector"
] |
493770d7f3064331fb449877a45cc5fb4e466ca8 | 3,935 | h | C | modules/none_core/framework/Envelope.h | 0x07dc/none | 9fd20137427a92bab232e2af781f0fc5836a2656 | [
"MIT"
] | null | null | null | modules/none_core/framework/Envelope.h | 0x07dc/none | 9fd20137427a92bab232e2af781f0fc5836a2656 | [
"MIT"
] | null | null | null | modules/none_core/framework/Envelope.h | 0x07dc/none | 9fd20137427a92bab232e2af781f0fc5836a2656 | [
"MIT"
] | null | null | null | #ifndef FRAMEWORK_ENVELOPE_H
#define FRAMEWORK_ENVELOPE_H
#include <limits>
#include <juce_audio_basics/juce_audio_basics.h>
#include "TypeDef.h"
#include "EnvelopeConstructorInput.h"
namespace none {
template<class ThisType, class ConstructorMementoType>
class Envelope {
std::vector<LargeNum> longBufferIdx{0};
// Max of LargeNum (aka unsigned long long int) is less than that of double
// Should be const, although that requires a custom copy/move constructor
int maxLongBufferIdx = (int)std::numeric_limits<LargeNum>::max();
protected:
LargeNum newBuffersSinceStart = 0;
int sampleRate;
int startSampleNum;
int releaseSampleNum, releaseBufferNum = 0;
bool isFinished = false;
bool isInRelease = false;
public:
virtual float getAmplitude(int sampleNum) = 0;
virtual bool getIsFinished(){
return isFinished;
};
Envelope() = delete;
Envelope(int startSampleNum, int sampleRate) :
startSampleNum(startSampleNum), sampleRate(sampleRate){};
Envelope(int startSampleNum, int sampleRate, const ConstructorMementoType& /*input*/) : startSampleNum(startSampleNum) {}
void nextBuffer(){
// Modulo max numeric size, will glitch, but should never happen (will prevent possible overflow)
newBuffersSinceStart = (newBuffersSinceStart + 1) % std::numeric_limits<LargeNum>::max();
};
void setReleaseSampleNum(int newReleaseSampleNum) {
releaseSampleNum = newReleaseSampleNum;
isInRelease = true;
};
static void readMidiMessages(
const int& sampleRate,
juce::MidiBuffer &midiMessages,
std::map<float, ThisType>& output,
ConstructorMementoType& constructorMemento){
// Go through midiMessages
// midiMessages is sorted by timestamp
for(auto msg : midiMessages){
juce::MidiMessage midi = msg.getMessage();
// find noteOns, and create new ADSRs
if(midi.isNoteOn()){
// Replace any duplicate notes
auto it = output.find((float)midi.getNoteNumber());
if(it != output.end()){
it->second = ThisType((int)midi.getTimeStamp(), sampleRate, constructorMemento);
} else {
output.emplace(
(float)midi.getNoteNumber(),
ThisType((int)midi.getTimeStamp(), sampleRate, constructorMemento)
);
}
}
// find noteOffs, and update relevant ADSRs
if(midi.isNoteOff()){
auto it = output.find((float)midi.getNoteNumber());
if(it != output.end()){
it->second.setReleaseSampleNum((int)midi.getTimeStamp());
}
}
}
// Check through output and remove any instances where the release has finished
std::map<float, ThisType> newOutput;
for(std::pair<const float, ThisType>& adsr : output){
if(!adsr.second.getIsFinished())
newOutput.insert(adsr);
}
output = newOutput;
}
LargeNum getAndIncrementLongBufferIdx(int channel){
LargeNum result = longBufferIdx[channel];
longBufferIdx[channel] = (longBufferIdx[channel] + 1) % maxLongBufferIdx;
return result;
}
void resizeLongBufferIdx(int newSize){
// TODO handle downsizing
if(longBufferIdx.size() < newSize)
longBufferIdx.resize(newSize, longBufferIdx[0]);
}
};
}
#endif //FRAMEWORK_ENVELOPE_H
| 37.122642 | 129 | 0.571283 | [
"vector"
] |
402c00659aae33e2facbea0991bc28e6b961c32a | 23,433 | h | C | Include/xsapi-cpp/social_manager.h | natiskan/xbox-live-api | 9e7e51e0863b5983c2aa334a7b0db579b3bdf1de | [
"MIT"
] | 118 | 2019-05-13T22:56:02.000Z | 2022-03-16T06:12:39.000Z | Include/xsapi-cpp/social_manager.h | aspavlov/xbox-live-api | 4bec6f92347d0ad6c85463b601821333de631e3a | [
"MIT"
] | 31 | 2019-05-07T13:09:28.000Z | 2022-01-26T10:02:59.000Z | Include/xsapi-cpp/social_manager.h | aspavlov/xbox-live-api | 4bec6f92347d0ad6c85463b601821333de631e3a | [
"MIT"
] | 48 | 2019-05-28T23:55:31.000Z | 2021-12-22T03:47:56.000Z | // Copyright (c) Microsoft Corporation
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#pragma once
#include "xsapi-cpp/presence.h"
#include "xsapi-c/social_manager_c.h"
#include "xsapi-cpp/mem.h"
#include "xsapi-cpp/types.h"
namespace xbox {
namespace services {
namespace social {
/// <summary>
/// Contains classes and enumerations for more easily managing social
/// scenarios.
/// </summary>
namespace manager {
/// <summary>
/// Detail level controls how much information is exposed in each xbox_live_social_graph_user
/// Detail level can only be set on construction of social_manager
/// </summary>
enum class social_manager_extra_detail_level
{
/// <summary>Only get default PeopleHub information (presence, profile)</summary>
no_extra_detail = static_cast<uint32_t>(XblSocialManagerExtraDetailLevel::NoExtraDetail),
/// <summary>Add extra detail for the title history for the users</summary>
title_history_level = static_cast<uint32_t>(XblSocialManagerExtraDetailLevel::TitleHistoryLevel),
/// <summary>Add extra detail for the preferred color for the users</summary>
preferred_color_level = static_cast<uint32_t>(XblSocialManagerExtraDetailLevel::PreferredColorLevel)
};
DEFINE_ENUM_FLAG_OPERATORS(social_manager_extra_detail_level);
/// <summary>
/// The filter level of information
/// Title will only show users associated with a particular title
/// </summary>
enum class presence_filter
{
/// <summary>Unknown</summary>
unknown = static_cast<uint32_t>(XblPresenceFilter::Unknown),
/// <summary>Is currently playing current title and is online</summary>
title_online = static_cast<uint32_t>(XblPresenceFilter::TitleOnline),
/// <summary>Has played this title and is offline</summary>
title_offline = static_cast<uint32_t>(XblPresenceFilter::TitleOffline),
/// <summary>Has played this title, is online but not currently playing this title</summary>
title_online_outside_title = static_cast<uint32_t>(XblPresenceFilter::TitleOnlineOutsideTitle),
/// <summary>Everyone currently online</summary>
all_online = static_cast<uint32_t>(XblPresenceFilter::AllOnline),
/// <summary>Everyone currently offline</summary>
all_offline = static_cast<uint32_t>(XblPresenceFilter::AllOffline),
/// <summary>Everyone who has played or is playing the title</summary>
all_title = static_cast<uint32_t>(XblPresenceFilter::AllTitle),
/// <summary>Everyone</summary>
all = static_cast<uint32_t>(XblPresenceFilter::All)
};
/// <summary>
/// The types of possible events
/// </summary>
enum class social_event_type
{
/// <summary>Users added to social graph</summary>
users_added_to_social_graph = static_cast<uint32_t>(XblSocialManagerEventType::UsersAddedToSocialGraph),
/// <summary>Users removed from social graph</summary>
users_removed_from_social_graph = static_cast<uint32_t>(XblSocialManagerEventType::UsersRemovedFromSocialGraph),
/// <summary>Users presence record has changed</summary>
presence_changed = static_cast<uint32_t>(XblSocialManagerEventType::PresenceChanged),
/// <summary>Users profile information has changed</summary>
profiles_changed = static_cast<uint32_t>(XblSocialManagerEventType::ProfilesChanged),
/// <summary>Relationship to users has changed</summary>
social_relationships_changed = static_cast<uint32_t>(XblSocialManagerEventType::SocialRelationshipsChanged),
/// <summary>Social graph load complete from adding a local user</summary>
local_user_added = static_cast<uint32_t>(XblSocialManagerEventType::LocalUserAdded),
/// <summary>
/// Legacy. Formerly raised when a user's graph was destroyed, but is no longer raised.
/// C++ interface will continue to raise this event (always on the next do_work call after removed_local_user)
/// to maintain backward compatability.
/// </summary>
local_user_removed = static_cast<uint32_t>(XblSocialManagerEventType::UnknownEvent) + 1,
/// <summary>Xbox Social User Group load complete (will only trigger for views that take a list of users)</summary>
social_user_group_loaded = static_cast<uint32_t>(XblSocialManagerEventType::SocialUserGroupLoaded),
/// <summary>Social user group updated</summary>
social_user_group_updated = static_cast<uint32_t>(XblSocialManagerEventType::SocialUserGroupUpdated),
/// <summary>unknown.</summary>
unknown = static_cast<uint32_t>(XblSocialManagerEventType::UnknownEvent)
};
/// <summary>
/// Possible relationship types to filter by
/// </summary>
enum class relationship_filter
{
/// <summary>Friends of the user (user is following)</summary>
friends = static_cast<uint32_t>(XblRelationshipFilter::Friends),
/// <summary>Favorites of the user</summary>
favorite = static_cast<uint32_t>(XblRelationshipFilter::Favorite)
};
/// <summary>
/// Identifies type of social user group created
/// </summary>
enum class social_user_group_type
{
/// <summary>Social user group based off of filters</summary>
filter_type = static_cast<uint32_t>(XblSocialUserGroupType::FilterType),
/// <summary>Social user group based off of list of users</summary>
user_list_type = static_cast<uint32_t>(XblSocialUserGroupType::UserListType)
};
/// <summary>
/// Data about whether the user has played the title
/// </summary>
class title_history
{
public:
/// <summary>
/// Whether the user has played this title
/// </summary>
inline bool has_user_played() const;
/// <summary>
/// The last time the user had played
/// </summary>
inline utility::datetime last_time_user_played() const;
/// <summary>
/// Internal functions
/// </summary>
inline title_history(const XblTitleHistory& titleHistory);
inline title_history(const title_history& other);
inline title_history& operator=(title_history other);
inline ~title_history() = default;
private:
std::shared_ptr<const XblTitleHistory> m_owningPtr{ nullptr };
const XblTitleHistory* m_titleHistory;
};
/// <summary>
/// Preferred color for the user. Set via the shell.
/// </summary>
class preferred_color
{
public:
/// <summary>
/// Users primary color
/// </summary>
inline const char_t* primary_color() const;
/// <summary>
/// Users secondary color
/// </summary>
inline const char_t* secondary_color() const;
/// <summary>
/// Users tertiary color
/// </summary>
inline const char_t* tertiary_color() const;
/// <summary>
/// Does a comparison on if preferred colors are equal
/// </summary>
inline bool operator!=(const preferred_color& rhs) const;
/// <summary>
/// Internal function
/// </summary>
inline preferred_color(const XblPreferredColor& preferredColor);
private:
string_t m_primaryColor;
string_t m_secondaryColor;
string_t m_tertiaryColor;
};
/// <summary>
/// Social manager version of the presence title record
/// Gives information about different titles presence information
/// </summary>
class social_manager_presence_title_record
{
public:
/// <summary>
/// The title ID.
/// </summary>
inline uint32_t title_id() const;
/// <summary>
/// The active state for the title.
/// </summary>
inline bool is_title_active() const;
/// <summary>
/// The formatted and localized presence string.
/// </summary>
inline const char_t* presence_text() const;
/// <summary>
/// The active state for the title.
/// </summary>
inline bool is_broadcasting() const;
/// <summary>
/// Device type
/// </summary>
inline xbox::services::presence::presence_device_type device_type() const;
/// <summary>
/// Whether or not this is the primary primary presence record
/// </summary>
inline bool is_primary() const;
/// <summary>
/// Internal functions
/// </summary>
inline social_manager_presence_title_record(const XblSocialManagerPresenceTitleRecord& titleRecord);
inline social_manager_presence_title_record(const social_manager_presence_title_record& other);
inline social_manager_presence_title_record& operator=(social_manager_presence_title_record other);
inline ~social_manager_presence_title_record() = default;
private:
std::shared_ptr<const XblSocialManagerPresenceTitleRecord> m_owningPtr{ nullptr };
const XblSocialManagerPresenceTitleRecord* m_titleRecord;
string_t m_presenceText;
};
/// <summary>
/// Social manager presence record. Shows information on users current presence status and stores title records
/// </summary>
class social_manager_presence_record
{
public:
/// <summary>
/// The user's presence state.
/// </summary>
inline xbox::services::presence::user_presence_state user_state() const;
/// <summary>
/// Collection of presence title record objects returned by a request.
/// </summary>
inline const std::vector<social_manager_presence_title_record>& presence_title_records() const;
/// <summary>
/// Returns whether the user is playing this title id
/// </summary>
inline bool is_user_playing_title(_In_ uint32_t titleId) const;
/// <summary>
/// Internal functions
/// </summary>
inline social_manager_presence_record(const XblSocialManagerPresenceRecord& presenceRecord);
inline social_manager_presence_record(const social_manager_presence_record& other);
inline social_manager_presence_record& operator=(social_manager_presence_record other);
inline ~social_manager_presence_record() = default;
private:
std::shared_ptr<const XblSocialManagerPresenceRecord> m_owningPtr{ nullptr };
const XblSocialManagerPresenceRecord* m_presenceRecord;
std::vector<social_manager_presence_title_record> m_titleRecords;
};
/// <summary>
/// Xbox Social User that contains profile, presence, preferred color, and title history data
/// </summary>
class xbox_social_user
{
public:
/// <summary>
/// The xbox user id
/// </summary>
inline const char_t* xbox_user_id() const;
/// <summary>
/// Whether they are a favorite
/// </summary>
inline bool is_favorite() const;
/// <summary>
/// Whether the calling user is following them
/// </summary>
inline bool is_following_user() const;
/// <summary>
/// Whether they calling user is followed by this person
/// </summary>
inline bool is_followed_by_caller() const;
/// <summary>
/// The display name
/// </summary>
inline const char_t* display_name() const;
/// <summary>
/// The real name
/// </summary>
inline const char_t* real_name() const;
/// <summary>
/// The display pic uri
/// </summary>
inline const char_t* display_pic_url_raw() const;
/// <summary>
/// Whether to use the players avatar
/// </summary>
inline bool use_avatar() const;
/// <summary>
/// Players gamerscore
/// </summary>
inline const char_t* gamerscore() const;
/// <summary>
/// Players gamertag
/// </summary>
inline const char_t* gamertag() const;
/// <summary>
/// Modern gamertag for the player. Not guaranteed to be unique.
/// </summary>
inline const char_t* modern_gamertag() const;
/// <summary>
/// Suffix appended to modern gamertag to ensure uniqueness. May be empty in some cases.
/// </summary>
inline const char_t* modern_gamertag_suffix() const;
/// <summary>
/// Combined modern gamertag and suffix. Format will be "MGT#suffix".
/// Guaranteed to be no more than 16 rendered characters.
/// </summary>
inline const char_t* unique_modern_gamertag() const;
/// <summary>
/// Users presence record
/// </summary>
inline const xbox::services::social::manager::social_manager_presence_record& presence_record() const;
/// <summary>
/// Title history for the user
/// </summary>
inline const xbox::services::social::manager::title_history& title_history() const;
/// <summary>
/// Preferred color for the user
/// </summary>
inline const preferred_color& preferred_color() const;
/// <summary>
/// Internal functions
/// </summary>
inline xbox_social_user(const XblSocialManagerUser& user);
inline xbox_social_user(const xbox_social_user& other);
inline xbox_social_user& operator=(xbox_social_user other);
inline ~xbox_social_user() = default;
private:
std::shared_ptr<const XblSocialManagerUser> m_owningPtr{ nullptr };
const XblSocialManagerUser* m_user;
string_t m_gamerscore;
string_t m_gamertag;
string_t m_modernGamertag;
string_t m_modernGamertagSuffix;
string_t m_uniqueModernGamertag;
string_t m_xboxUserId;
string_t m_displayName;
string_t m_realName;
string_t m_displayPicUrlRaw;
xbox::services::social::manager::title_history m_titleHistory;
xbox::services::social::manager::preferred_color m_preferredColor;
xbox::services::social::manager::social_manager_presence_record m_presenceRecord;
};
/// <summary>
/// Base class for social event args
/// </summary>
class social_event_args
{
public:
social_event_args() {}
virtual ~social_event_args() {}
};
/// <summary>
/// Contains an xbox user id for purposes of storing in stl data types
/// </summary>
class xbox_user_id_container
{
public:
/// <summary>
/// A users xbox user id
/// </summary>
inline const char_t* xbox_user_id() const;
/// <summary>
/// Internal function
/// </summary>
inline xbox_user_id_container(_In_ uint64_t xuid);
private:
string_t m_xboxUserId;
};
/// <summary>
/// An event that something in the social graph has changed
/// </summary>
class social_event
{
public:
/// <summary>
/// The user whose graph got changed
/// </summary>
inline xbox_live_user_t user() const;
/// <summary>
/// The type of event this is
/// Tells the caller what to cast the event_args to
/// </summary>
inline social_event_type event_type() const;
/// <summary>
/// List of users this event affects
/// </summary>
inline std::vector<xbox_user_id_container> users_affected() const;
/// <summary>
/// The social event args
/// </summary>
inline std::shared_ptr<social_event_args> event_args() const;
/// <summary>
/// Error that occurred
/// </summary>
inline std::error_code err() const;
/// <summary>
/// Error message
/// </summary>
inline std::string err_message() const;
/// <summary>
/// Internal functions
/// </summary>
inline social_event(const XblSocialManagerEvent& event);
inline social_event(const xbox_live_user_t& removedUser);
private:
XblSocialManagerEvent m_event{};
social_event_type m_eventType{ social_event_type::unknown };
std::shared_ptr<social_event_args> m_args;
};
/// <summary>
/// A subset snapshot of the users social graph
/// </summary>
class xbox_social_user_group
{
public:
/// <summary>
/// Gets an up to date list of users from the social graph
/// The returned value remains valid until the next call to do_work
/// </summary>
inline std::vector<xbox_social_user*> users() const;
/// <summary>
/// Returns copied group of users from social user group
/// </summary>
/// <param name="socialUserVector">Vector of social users to populate</param>
/// <returns>An xbox_live_result representing the success of copying the users</returns>
inline xbox_live_result<void> get_copy_of_users(
_Inout_ std::vector<xbox_social_user>& socialUserVector
);
/// <summary>
/// Type of social user group
/// </summary>
inline social_user_group_type social_user_group_type() const;
/// <summary>
/// Users who are contained in this user group currently
/// For list this is static, for filter this is dynamic and will change on do_work
/// </summary>
inline std::vector<xbox_user_id_container> users_tracked_by_social_user_group() const;
/// <summary>
/// The local user who the user group is related to
/// </summary>
inline xbox_live_user_t local_user() const;
/// <summary>
/// Returns the presence filter used if group type is filter type
/// </summary>
inline presence_filter presence_filter_of_group() const;
/// <summary>
/// Returns the relationship filter used if group type is filter type
/// </summary>
inline relationship_filter relationship_filter_of_group() const;
/// <summary>
/// Returns users from xuids. Pointers become invalidated by next do_work
/// </summary>
inline std::vector<xbox_social_user*> get_users_from_xbox_user_ids(_In_ const std::vector<xbox_user_id_container>& xboxUserIds);
/// <summary>
/// Internal function
/// </summary>
inline xbox_social_user_group(XblSocialManagerUserGroupHandle group);
private:
inline void PopulateUsers() const;
XblSocialManagerUserGroupHandle m_group;
mutable std::vector<xbox_social_user> m_users;
friend class social_manager;
};
/// <summary>
/// Social user group args for when a social user group loads
/// </summary>
class social_user_group_loaded_event_args : public social_event_args
{
public:
/// <summary>
/// The loaded social user group
/// </summary>
inline std::shared_ptr<xbox_social_user_group> social_user_group() const;
/// <summary>
/// internal function
/// </summary>
inline social_user_group_loaded_event_args(std::shared_ptr<xbox_social_user_group> group);
private:
std::shared_ptr<xbox_social_user_group> m_group;
};
/// <summary>
/// Social Manager that handles core logic
/// </summary>
class social_manager
{
public:
/// <summary>
/// Gets the social_manager singleton instance
/// </summary>
inline static std::shared_ptr<social_manager> get_singleton_instance();
/// <summary>
/// Create a social graph for the specified local user
/// The result of a local user being added will be triggered through the local_user_added event in do_work
/// </summary>
/// <param name="user">Xbox Live User</param>
/// <param name="extraDetailLevel">The level of verbosity that should be in the xbox_social_user</param>
/// <returns>An xbox_live_result to report any potential error</returns>
inline xbox_live_result<void> add_local_user(
_In_ xbox_live_user_t user,
_In_ social_manager_extra_detail_level extraDetailLevel
);
/// <summary>
/// Removes a social graph for the specified local user
/// The result of a local user being added will be triggered through the local_user_removed event in do_work
/// </summary>
/// <param name="user">Xbox Live User</param>
/// <returns>An xbox_live_result to report any potential error</returns>
inline xbox_live_result<void> remove_local_user(
_In_ xbox_live_user_t user
);
/// <summary>
/// Called whenever the title wants to update the social graph and get list of change events
/// Must be called every frame for data to be up to date
/// </summary>
/// <returns> The list of what has changed in between social graph updates</returns>
inline std::vector<social_event> do_work();
/// <summary>
/// Constructs a social Xbox Social User Group, which is a collection of users with social information
/// The result of a user group being loaded will be triggered through the social_user_group_loaded event in do_work
/// </summary>
/// <param name="user">Xbox Live User</param>
/// <param name="presenceDetailLevel">The restriction of users based on their presence and title activity</param>
/// <param name="relationshipFilter">The restriction of users based on their relationship to the calling user</param>
/// <returns>An xbox_live_result of the created Xbox Social User Group</returns>
inline xbox_live_result<std::shared_ptr<xbox_social_user_group>> create_social_user_group_from_filters(
_In_ xbox_live_user_t user,
_In_ presence_filter presenceDetailLevel,
_In_ relationship_filter filter
);
/// <summary>
/// Constructs a social Xbox Social User Group, which is a collection of users with social information
/// The result of a user group being loaded will be triggered through the social_user_group_loaded event in do_work
/// </summary>
/// <param name="user">Xbox Live User</param>
/// <param name="xboxUserIdList">List of users to populate the Xbox Social User Group with. This is currently capped at 100 users total.</param>
/// <returns>An xbox_live_result of the created Xbox Social User Group</returns>
inline xbox_live_result<std::shared_ptr<xbox_social_user_group>> create_social_user_group_from_list(
_In_ xbox_live_user_t user,
_In_ std::vector<string_t> xboxUserIdList
);
/// <summary>
/// Destroys a created social Xbox Social User Group
/// This will stop updating the Xbox Social User Group and remove tracking for any users the Xbox Social User Group holds
/// </summary>
/// <param name="socialUserGroup">The social Xbox Social User Group to destroy and stop tracking</param>
/// <returns>An xbox_live_result to report any potential error</returns>
inline xbox_live_result<void> destroy_social_user_group(
_In_ std::shared_ptr<xbox_social_user_group> socialUserGroup
);
/// <summary>
/// Returns all local users who have been added to the social manager
/// </summary>
inline std::vector<xbox_live_user_t> local_users() const;
/// <summary>
/// Updates specified social user group to new group of users
/// Does a diff to see which users have been added or removed from
/// The result of a user group being updated will be triggered through the social_user_group_updated event in do_work
/// </summary>
/// <param name="group">The xbox social user group to add users to</param>
/// <param name="users">List of users to add to the xbox social user group. Total number of users not in social graph is limited at 100.</param>
/// <returns>An xbox_live_result representing the success of adding the users to the group</returns>
inline xbox_live_result<void> update_social_user_group(
_In_ const std::shared_ptr<xbox_social_user_group>& group,
_In_ const std::vector<string_t>& users
);
/// <summary>
/// Whether to enable social manager to poll every 30 seconds from the presence service
/// </summary>
/// <param name="user">Xbox Live User</param>
/// <param name="shouldEnablePolling">Whether or not polling should enabled</param>
/// <returns>An xbox_live_result representing the success enabling polling</returns>
inline xbox_live_result<void> set_rich_presence_polling_status(
_In_ xbox_live_user_t user,
_In_ bool shouldEnablePolling
);
private:
social_manager() = default;
std::vector<xbox_live_user_t> m_removedUsers;
std::unordered_map<XblSocialManagerUserGroupHandle, std::shared_ptr<xbox_social_user_group>> m_groups;
friend class social_event;
};
}}}}
#include "impl/social_manager.hpp"
| 34.460294 | 148 | 0.704989 | [
"vector"
] |
403998e4c5de56bcbda2441371dd1f844f57ee06 | 2,790 | h | C | sourceCode/application/logic/vecttype.h | lp-rep/stackprof-1 | 62d9cb96ad7dcdaa26b6383559f542cadc1c7af2 | [
"CECILL-B"
] | 2 | 2022-02-27T20:08:04.000Z | 2022-03-03T13:45:40.000Z | sourceCode/application/logic/vecttype.h | lp-rep/stackprof-1 | 62d9cb96ad7dcdaa26b6383559f542cadc1c7af2 | [
"CECILL-B"
] | 1 | 2021-06-07T17:09:04.000Z | 2021-06-11T11:48:23.000Z | sourceCode/application/logic/vecttype.h | lp-rep/stackprof-1 | 62d9cb96ad7dcdaa26b6383559f542cadc1c7af2 | [
"CECILL-B"
] | 1 | 2021-06-03T21:06:55.000Z | 2021-06-03T21:06:55.000Z | #ifndef VECTTYPE_H
#define VECTTYPE_H
#include <vector>
#include <stddef.h>
#include <memory>
using namespace std;
//inheritance way with virtual
class VectorType {
public:
virtual void resize(uint32_t count) = 0; //@LP:because size_type is vector<T> dependant, we can not use size_type as method parameter here, and then in the children :|
virtual void* data() = 0;
virtual void clear() = 0;
virtual bool empty() = 0;
//virtual void showContent() = 0;
virtual size_t size() = 0;
virtual void fillZero() = 0;
virtual ~VectorType();
};
class VectorUint8 : public VectorType {
public:
//void resize(vector<char>::size_type count) { _vectChar.resize(count); }
void resize(uint32_t count);
void* data();
void clear();
bool empty();
//void showContent() { for (auto iter: _vectChar) cout << (int)iter << endl; }
//char at(uint32_t idx);
size_t size();
void fillZero();
~VectorUint8();
private:
vector<unsigned char> _vectUint8;
};
class VectorFloat : public VectorType {
public:
//void resize(vector<float>::size_type count) { _vectFloat.resize(count); }
void resize(uint32_t count);
void* data();
void clear();
bool empty();
//void showContent() { for (auto iter: _vectFloat) cout << (float)iter << endl; }
//float at(uint32_t idx);
size_t size();
void fillZero();
~VectorFloat();
private:
vector<float> _vectFloat;
};
//@#LP check that 16 bits is constant on the different platforms and compilers
class VectorSignedInt16 : public VectorType {
public:
//void resize(vector<float>::size_type count) { _vectFloat.resize(count); }
void resize(uint32_t count);
void* data();
void clear();
bool empty();
//void showContent() { for (auto iter: _vectFloat) cout << (float)iter << endl; }
// /*un*/signed short int at(uint32_t idx);
size_t size();
void fillZero();
~VectorSignedInt16();
private:
vector<signed short int> _vectSignedInt16; //@#LP check that 16 bits is constant on the different platforms and compilers
};
//@#LP check that 16 bits is constant on the different platforms and compilers
class VectorUnsignedInt16 : public VectorType {
public:
//void resize(vector<float>::size_type count) { _vectFloat.resize(count); }
void resize(uint32_t count);
void* data();
void clear();
bool empty();
//void showContent() { for (auto iter: _vectFloat) cout << (float)iter << endl; }
// /*un*/signed short int at(uint32_t idx);
size_t size();
void fillZero();
~VectorUnsignedInt16();
private:
vector<unsigned short int> _vectUnsignedInt16; //@#LP check that 16 bits is constant on the different platforms and compilers
};
#endif // VECTTYPE_H
| 24.473684 | 171 | 0.65914 | [
"vector"
] |
404548f028a8b8fa4e8836ef69867475810a0e15 | 6,484 | h | C | git/attr.h | jjcoderzero/git-source-code-reading | a630f12e853cfad0a44c78820cca21c4b75dd502 | [
"MIT"
] | null | null | null | git/attr.h | jjcoderzero/git-source-code-reading | a630f12e853cfad0a44c78820cca21c4b75dd502 | [
"MIT"
] | 1 | 2020-02-11T10:13:18.000Z | 2020-02-18T18:54:42.000Z | _site/git/attr.h | astabschneider/astabschneider.github.io | 65dbdc6007ffff572b30ac97b6a154699bd88863 | [
"MIT"
] | null | null | null | #ifndef ATTR_H
#define ATTR_H
/**
* gitattributes mechanism gives a uniform way to associate various attributes
* to set of paths.
*
*
* Querying Specific Attributes
* ----------------------------
*
* - Prepare `struct attr_check` using attr_check_initl() function, enumerating
* the names of attributes whose values you are interested in, terminated with
* a NULL pointer. Alternatively, an empty `struct attr_check` can be
* prepared by calling `attr_check_alloc()` function and then attributes you
* want to ask about can be added to it with `attr_check_append()` function.
*
* - Call `git_check_attr()` to check the attributes for the path.
*
* - Inspect `attr_check` structure to see how each of the attribute in the
* array is defined for the path.
*
*
* Example
* -------
*
* To see how attributes "crlf" and "ident" are set for different paths.
*
* - Prepare a `struct attr_check` with two elements (because we are checking
* two attributes):
*
* ------------
* static struct attr_check *check;
* static void setup_check(void)
* {
* if (check)
* return; // already done
* check = attr_check_initl("crlf", "ident", NULL);
* }
* ------------
*
* - Call `git_check_attr()` with the prepared `struct attr_check`:
*
* ------------
* const char *path;
*
* setup_check();
* git_check_attr(path, check);
* ------------
*
* - Act on `.value` member of the result, left in `check->items[]`:
*
* ------------
* const char *value = check->items[0].value;
*
* if (ATTR_TRUE(value)) {
* The attribute is Set, by listing only the name of the
* attribute in the gitattributes file for the path.
* } else if (ATTR_FALSE(value)) {
* The attribute is Unset, by listing the name of the
* attribute prefixed with a dash - for the path.
* } else if (ATTR_UNSET(value)) {
* The attribute is neither set nor unset for the path.
* } else if (!strcmp(value, "input")) {
* If none of ATTR_TRUE(), ATTR_FALSE(), or ATTR_UNSET() is
* true, the value is a string set in the gitattributes
* file for the path by saying "attr=value".
* } else if (... other check using value as string ...) {
* ...
* }
* ------------
*
* To see how attributes in argv[] are set for different paths, only
* the first step in the above would be different.
*
* ------------
* static struct attr_check *check;
* static void setup_check(const char **argv)
* {
* check = attr_check_alloc();
* while (*argv) {
* struct git_attr *attr = git_attr(*argv);
* attr_check_append(check, attr);
* argv++;
* }
* }
* ------------
*
*
* Querying All Attributes
* -----------------------
*
* To get the values of all attributes associated with a file:
*
* - Prepare an empty `attr_check` structure by calling `attr_check_alloc()`.
*
* - Call `git_all_attrs()`, which populates the `attr_check` with the
* attributes attached to the path.
*
* - Iterate over the `attr_check.items[]` array to examine the attribute
* names and values. The name of the attribute described by an
* `attr_check.items[]` object can be retrieved via
* `git_attr_name(check->items[i].attr)`. (Please note that no items will be
* returned for unset attributes, so `ATTR_UNSET()` will return false for all
* returned `attr_check.items[]` objects.)
*
* - Free the `attr_check` struct by calling `attr_check_free()`.
*/
struct index_state;
/**
* An attribute is an opaque object that is identified by its name. Pass the
* name to `git_attr()` function to obtain the object of this type.
* The internal representation of this structure is of no interest to the
* calling programs. The name of the attribute can be retrieved by calling
* `git_attr_name()`.
*/
struct git_attr;
/* opaque structures used internally for attribute collection */
struct all_attrs_item;
struct attr_stack;
struct index_state;
/*
* Given a string, return the gitattribute object that
* corresponds to it.
*/
const struct git_attr *git_attr(const char *);
/* Internal use */
extern const char git_attr__true[];
extern const char git_attr__false[];
/**
* Attribute Values
* ----------------
*
* An attribute for a path can be in one of four states: Set, Unset, Unspecified
* or set to a string, and `.value` member of `struct attr_check_item` records
* it. The three macros check these, if none of them returns true, `.value`
* member points at a string value of the attribute for the path.
*/
/* Returns true if the attribute is Set for the path. */
#define ATTR_TRUE(v) ((v) == git_attr__true)
/* Returns true if the attribute is Unset for the path. */
#define ATTR_FALSE(v) ((v) == git_attr__false)
/* Returns true if the attribute is Unspecified for the path. */
#define ATTR_UNSET(v) ((v) == NULL)
/* This structure represents one attribute and its value. */
struct attr_check_item {
const struct git_attr *attr;
const char *value;
};
/**
* This structure represents a collection of `attr_check_item`. It is passed to
* `git_check_attr()` function, specifying the attributes to check, and
* receives their values.
*/
struct attr_check {
int nr;
int alloc;
struct attr_check_item *items;
int all_attrs_nr;
struct all_attrs_item *all_attrs;
struct attr_stack *stack;
};
struct attr_check *attr_check_alloc(void);
struct attr_check *attr_check_initl(const char *, ...);
struct attr_check *attr_check_dup(const struct attr_check *check);
struct attr_check_item *attr_check_append(struct attr_check *check,
const struct git_attr *attr);
void attr_check_reset(struct attr_check *check);
void attr_check_clear(struct attr_check *check);
void attr_check_free(struct attr_check *check);
/*
* Return the name of the attribute represented by the argument. The
* return value is a pointer to a null-delimited string that is part
* of the internal data structure; it should not be modified or freed.
*/
const char *git_attr_name(const struct git_attr *);
void git_check_attr(const struct index_state *istate,
const char *path, struct attr_check *check);
/*
* Retrieve all attributes that apply to the specified path.
* check holds the attributes and their values.
*/
void git_all_attrs(const struct index_state *istate,
const char *path, struct attr_check *check);
enum git_attr_direction {
GIT_ATTR_CHECKIN,
GIT_ATTR_CHECKOUT,
GIT_ATTR_INDEX
};
void git_attr_set_direction(enum git_attr_direction new_direction);
void attr_start(void);
#endif /* ATTR_H */
| 30.441315 | 80 | 0.688772 | [
"object"
] |
4048542f3cd1a8f031789334ff2ce32232aab748 | 14,259 | c | C | mex/include/sisl-4.5.0/src/sh1779.c | sangyoonHan/extern | a3c874538a7262b895b60d3c4d493e5b34cf81f8 | [
"BSD-2-Clause"
] | null | null | null | mex/include/sisl-4.5.0/src/sh1779.c | sangyoonHan/extern | a3c874538a7262b895b60d3c4d493e5b34cf81f8 | [
"BSD-2-Clause"
] | null | null | null | mex/include/sisl-4.5.0/src/sh1779.c | sangyoonHan/extern | a3c874538a7262b895b60d3c4d493e5b34cf81f8 | [
"BSD-2-Clause"
] | null | null | null | //===========================================================================
// SISL - SINTEF Spline Library, version 4.5.0.
// Definition and interrogation of NURBS curves and surfaces.
//
// Copyright (C) 2000-2005, 2010 SINTEF ICT, Applied Mathematics, Norway.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation version 2 of the License.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc.,
// 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
//
// Contact information: E-mail: tor.dokken@sintef.no
// SINTEF ICT, Department of Applied Mathematics,
// P.O. Box 124 Blindern,
// 0314 Oslo, Norway.
//
// Other licenses are also available for this software, notably licenses
// for:
// - Building commercial software.
// - Building software whose source code you wish to keep private.
//===========================================================================
#include "sisl-copyright.h"
/*
*
* $Id: sh1779.c,v 1.2 2001-03-19 15:59:05 afr Exp $
*
*/
#define SH1779
#include "sislP.h"
#if defined(SISLNEEDPROTOTYPES)
void
sh1779 (SISLObject * po1, SISLObject * po2, double aepsge,
SISLIntdat ** rintdat, SISLIntpt * pintpt,
int *jnewpt, int *jstat)
#else
void
sh1779 (po1, po2, aepsge, rintdat, pintpt, jnewpt, jstat)
SISLObject *po1;
SISLObject *po2;
double aepsge;
SISLIntdat **rintdat;
SISLIntpt *pintpt;
int *jnewpt;
int *jstat;
#endif
/* UPDATE: (ujk) : Must tune the test on when to use local
info (=subtask no ?),
As in sh1780 it is necessary to determine when a helppoint
is close enough to a mainpoint to be neglected.
sh1784 does not tell if it march outside the surface,
this might be a problem. */
/*
*********************************************************************
*
*********************************************************************
*
* PURPOSE : Set pre-topology data in 3-dimensional curve-surface
* intersection. Also find help points if necessary.
*
*
* INPUT : po1 - Pointer to the first object in the intersection.
* po2 - Pointer to the second object in the intersection.
* aepsge - Geometry resolution.
* rintdat - Intersection data structure.
* pintpt - Current intersection point.
*
*
* OUTPUT : pintpt - Intersection point after updating pre-topology.
* jnewpt - Number of new int.pt. created.
* jstat - status messages
* > 0 : Warning.
* = 0 : Ok.
* < 0 : Error.
*
*
* METHOD :
*
* CALLS : shevalc - ? (s1221 used )Evaluate curve using filtered coefficients.
* s1421 - Evaluate surface using filtered coefficients.
* sh1784 - March along curve as long as it coincide
* with a surface.
* s6ang - Angle between two vectors.
* s6length - Length of vector.
* s6dist - Distance between two points.
* sh6idcon - Connect intersection points.
* sh6genhbrs - Get neighbours.
* sh6getgeo - Get geometric info from intersection point.
* sh6settop - Set topology of intersection point.
* hp_newIntpt - Create new intersection point.
*
* REFERENCES :
*
* WRITTEN BY : Vibeke Skytt, SI, Oslo, Norway. 04.91.
* Ulf J. Krystad, SI, 06.91.
*********************************************************************
*/
{
int kstat = 0; /* Status variable. */
int ki; /* Counters. */
int kleft1 = 0, kleft2 = 0; /* Parameters to the evaluator. */
int kdim; /* Dimension of geometry space. */
int kpos = 0; /* Current position in int.pt. array. */
int kpar1, kpar2; /* Index of parameter value of object. */
int kn; /* Number of vertices of curve. */
int kk; /* Order of curve. */
int kmarch = 0; /* Indicates if marching is necessary. */
int lleft[2]; /* Array storing pre-topology information. */
int lright[2]; /* Array storing pre-topology information. */
int *ll1, *ll2, *lr1, *lr2; /* Pointers into pre-topology arrays. */
double tref; /* Referance value in equality test. */
double *st; /* Knot vector of curve. */
double sder[9]; /* Result of curve evaluation. */
double stang[3]; /* Tangent vector of curve. */
double snorm[3]; /* Normal vector of surface. */
double slast[3]; /* Last parameter value of coincidence. */
double snext[3]; /* First parameter value outside interval
of coincidence. */
double *ret_val; /* Pointer to geo data from sh6getgeom */
double *ret_norm; /* Pointer to geo data from sh6getgeom */
double *sptpar = pintpt->epar;/* Pointer to parameter values of int.pt. */
SISLCurve *qc; /* Pointer to the curve. */
SISLSurf *qs; /* Pointer to the surface. */
SISLIntpt *uintpt[2]; /* Array containing new intersection points. */
SISLIntpt *qpt1, *qpt2; /* Intersection points in list. */
double *nullp = SISL_NULL;
double sf_low_lim[2];
double sf_high_lim[2];
/* Don't make pretop for help points ! */
if (sh6ishelp (pintpt))
{
*jstat = 0;
goto out;
}
/* Set pointers into the arrays storing pre-topology information. */
if (po1->iobj == SISLCURVE)
{
qc = po1->c1;
qs = po2->s1;
kpar1 = 0;
kpar2 = 1;
ll1 = lleft;
lr1 = lright;
ll2 = lleft + 1;
lr2 = lright + 1;
}
else
{
qc = po2->c1;
qs = po1->s1;
kpar1 = 2;
kpar2 = 0;
ll1 = lleft + 1;
lr1 = lright + 1;
ll2 = lleft;
lr2 = lright;
}
/* Get pre-topology of intersection point. */
sh6gettop (pintpt, -1, lleft, lright, lleft + 1, lright + 1, &kstat);
/* Describe curve partly by local parameters. */
kdim = qc->idim;
kk = qc->ik;
kn = qc->in;
st = qc->et;
tref = st[kn] - st[kk - 1];
sf_low_lim[0] = qs->et1[qs->ik1 - 1] + REL_COMP_RES;
sf_low_lim[1] = qs->et2[qs->ik2 - 1] + REL_COMP_RES;
sf_high_lim[0] = qs->et1[qs->in1] - REL_COMP_RES;
sf_high_lim[1] = qs->et2[qs->in2] - REL_COMP_RES;
/* Fetch geometry information, curve. */
sh6getgeom ((po1->iobj == SISLCURVE) ? po1 : po2,
(po1->iobj == SISLCURVE) ? 1 : 2,
pintpt, &ret_val, &ret_norm, aepsge, &kstat);
if (kstat < 0)
goto error;
/* Local copy of curve tangent */
memcopy (stang, ret_val + kdim, kdim, DOUBLE);
/* Fetch geometry information, surface. */
sh6getgeom ((po1->iobj == SISLSURFACE) ? po1 : po2,
(po1->iobj == SISLSURFACE) ? 1 : 2,
pintpt, &ret_val, &ret_norm, aepsge, &kstat);
if (kstat < 0)
goto error;
/* Local copy of surface normal */
memcopy (snorm, ret_norm, kdim, DOUBLE);
/* (ALA) Test if local information may be used to compute pre-topology. */
s6length (snorm, kdim, &kstat);
s6length (snorm, kdim, &ki);
if (!kstat || !ki || fabs (PIHALF - s6ang (snorm, stang, kdim)) < 0.05)
{
/* Check if the intersection point lies at the start point of
the curve. */
if (DEQUAL (sptpar[kpar1] + tref, st[kn] + tref))
;
else
{
/* Check if the intersection point is member of a list
in this parameter direction of the curve. */
qpt1 = qpt2 = SISL_NULL;
kmarch = 1;
/* UPDATE (ujk) : only one list ? */
sh6getnhbrs (pintpt, &qpt1, &qpt2, &kstat);
if (kstat < 0)
goto error;
kmarch = 0;
if (qpt1 != SISL_NULL && qpt1->epar[kpar1] > sptpar[kpar1])
*lr1 = SI_ON;
else if (qpt2 != SISL_NULL && qpt2->epar[kpar1] > sptpar[kpar1])
*lr1 = SI_ON;
else
kmarch = 1;
}
if (kmarch)
{
/* Perform marching to compute pre-topology. March first in the
positive direction of the curve. */
sh1784 (qc, qs, aepsge, sptpar, (kpar1 == 0), 1, slast, snext, &kstat);
if (kstat < 0)
goto error;
if (kstat == 1)
{
/* The endpoint of the curve is reached. */
;
}
else if (kstat == 2)
;
else
{
if (slast[kpar2] > sf_high_lim[0] ||
slast[kpar2 + 1] > sf_high_lim[1] ||
slast[kpar2] < sf_low_lim[0] ||
slast[kpar2 + 1] < sf_low_lim[1])
;
else
{
/* Create help point. First fetch geometry information. */
s1221 (qc, 0, slast[kpar1], &kleft1, sder, &kstat);
if (kstat < 0)
goto error;
s1221 (qc, 0, snext[kpar1], &kleft1, sder + kdim, &kstat);
if (kstat < 0)
goto error;
s6diff (sder + kdim, sder, kdim, stang);
s1421 (qs, 1, slast + kpar2, &kleft1, &kleft2, sder, snorm, &kstat);
if (kstat < 0)
goto error;
/* Discuss tangent- and normal vector, and set up pre-topology
in one direction of the curve. */
if (s6scpr (snorm, stang, kdim) > DZERO)
*lr1 = SI_OUT;
else
*lr1 = SI_IN;
/* UPDATE (ujk) : Tuning on distance */
if (s6dist (sptpar, slast, 3) > (double) 0.05 * tref)
{
/* Create help point. Set pre-topology data as undefined. */
/* UPDATE (ujk) : If calculated values is stored, kder must
be 1 for curve and 2 for surface (sh6getgeom). Should
shevalc be used in stead of s1221 ? */
uintpt[kpos] = SISL_NULL;
if ((uintpt[kpos] = hp_newIntpt (3, slast, DZERO, -SI_ORD,
lleft[0], lright[0], lleft[1],
lright[1], 0, 0, nullp, nullp)) == SISL_NULL)
goto err101;
kpos++;
}
}
}
}
/* Check if the intersection point lies at the end point of
the curve. */
kmarch = 0;
if (DEQUAL (sptpar[kpar1] + tref, st[kk - 1] + tref))
;
else
{
/* Check if the intersection point is member of a list
in this parameter direction of the curve. */
qpt1 = qpt2 = SISL_NULL;
kmarch = 1;
/* UPDATE (ujk) : only one list ? */
/* UPDATE (ujk) : only one list ? */
sh6getnhbrs (pintpt, &qpt1, &qpt2, &kstat);
if (kstat < 0)
goto error;
kmarch = 0;
if (qpt1 != SISL_NULL && qpt1->epar[kpar1] < sptpar[kpar1])
*ll1 = SI_ON;
else if (qpt2 != SISL_NULL && qpt2->epar[kpar1] < sptpar[kpar1])
*ll1 = SI_ON;
else
kmarch = 1;
}
if (kmarch)
{
/* March in the negative direction of the curve. */
sh1784 (qc, qs, aepsge, sptpar, (kpar1 == 0), -1, slast, snext, &kstat);
if (kstat < 0)
goto error;
if (kstat == 1)
{
/* The endpoint of the curve is reached. */
;
}
else if (kstat == 2)
;
else
{
if (slast[kpar2] > sf_high_lim[0] ||
slast[kpar2 + 1] > sf_high_lim[1] ||
slast[kpar2] < sf_low_lim[0] ||
slast[kpar2 + 1] < sf_low_lim[1])
;
else
{
/* Create help point. First fetch geometry information. */
s1221 (qc, 0, slast[kpar1], &kleft1, sder, &kstat);
if (kstat < 0)
goto error;
s1221 (qc, 0, snext[kpar1], &kleft1, sder + kdim, &kstat);
if (kstat < 0)
goto error;
s6diff (sder + kdim, sder, kdim, stang);
s1421 (qs, 1, slast + kpar2, &kleft1, &kleft2, sder, snorm, &kstat);
if (kstat < 0)
goto error;
/* Discuss tangent- and normal vector, and set up pre-topology
in one direction of the curve. */
if (s6scpr (snorm, stang, kdim) > DZERO)
*ll1 = SI_OUT;
else
*ll1 = SI_IN;
/* UPDATE (ujk) : Tuning on distance */
if (s6dist (sptpar, slast, 3) > (double) 0.05 * tref)
{
/* Create help point. Set pre-topology data as undefined. */
/* UPDATE (ujk) : If calculated values is stored, kder must
be 1 for curve and 2 for surface (sh6getgeom). Should
shevalc be used in stead of s1221 ? */
uintpt[kpos] = SISL_NULL;
if ((uintpt[kpos] = hp_newIntpt (3, slast, DZERO, -SI_ORD,
lleft[0], lright[0], lleft[1],
lright[1], 0, 0, nullp, nullp)) == SISL_NULL)
goto err101;
kpos++;
}
}
}
}
}
else
{
/* Pre-topology data of the curve may be computed from
local information. */
if (s6scpr (snorm, stang, kdim) > DZERO)
{
*ll1 = SI_IN;
*lr1 = SI_OUT;
}
else
{
*ll1 = SI_OUT;
*lr1 = SI_IN;
}
}
/* Update pre-topology of intersection point. */
/* UPDATE (ujk), index = -1 ?? */
sh6settop (pintpt, -1, lleft[0], lright[0], lleft[1], lright[1], &kstat);
/* Join intersection points, and set pretopology of help points. */
for (ki = 0; ki < kpos; ki++)
{
/* Help point ? */
if (sh6ishelp (uintpt[ki]))
sh6settop (uintpt[ki], -1, *(pintpt->left_obj_1), *(pintpt->right_obj_1),
*(pintpt->left_obj_2), *(pintpt->right_obj_2), &kstat);
sh6idcon (rintdat, &uintpt[ki], &pintpt, &kstat);
if (kstat < 0)
goto error;
}
/* Pre-topology information computed. */
*jnewpt = kpos;
*jstat = 0;
goto out;
/* Error in scratch allocation. */
err101:*jstat = -101;
goto out;
/* Error lower level routine. */
error:*jstat = kstat;
goto out;
out:
return;
}
| 29.893082 | 87 | 0.538397 | [
"geometry",
"object",
"vector"
] |
404de5f6f1d419a04fef14c81cca11d70de8af85 | 543 | h | C | include/xmol/geom/SpatialIndex.h | sizmailov/pyxmolpp2 | 9395ba1b1ddc957e0b33dc6decccdb711e720764 | [
"MIT"
] | 4 | 2020-06-24T11:07:57.000Z | 2022-01-15T23:00:30.000Z | include/xmol/geom/SpatialIndex.h | sizmailov/pyxmolpp2 | 9395ba1b1ddc957e0b33dc6decccdb711e720764 | [
"MIT"
] | 84 | 2018-04-22T12:29:31.000Z | 2020-06-17T15:03:37.000Z | include/xmol/geom/SpatialIndex.h | sizmailov/pyxmolpp2 | 9395ba1b1ddc957e0b33dc6decccdb711e720764 | [
"MIT"
] | 6 | 2018-06-04T09:16:26.000Z | 2022-03-12T11:05:54.000Z | #pragma once
#include "fwd.h"
#include "xmol/future/span.h"
#include <map>
#include <vector>
namespace xmol::geom {
class SpatialIndex {
public:
using bin_id_t = std::tuple<int, int, int>;
using index_t = int;
using indices_t = std::vector<index_t>;
SpatialIndex(const future::Span<XYZ>& coords, double bin_side_length);
indices_t within(double distance, const XYZ& point);
private:
std::map<bin_id_t, indices_t> m_bins;
const future::Span<XYZ>& m_coords;
const double m_bin_side_length = 1.0;
};
} // namespace xmol::geom | 22.625 | 72 | 0.71639 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.