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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0e4f20e78e34676d4ecb13313f2564f4600c0bc9 | 1,559 | h | C | SummonEngine/Engine/ForwardRenderer.h | Raboni/SummonEngine | 2a1078d60b604a918b920d098f3f0e60e5ce35bc | [
"MIT"
] | 1 | 2020-03-27T15:22:17.000Z | 2020-03-27T15:22:17.000Z | SummonEngine/Engine/ForwardRenderer.h | Raboni/SummonEngine | 2a1078d60b604a918b920d098f3f0e60e5ce35bc | [
"MIT"
] | null | null | null | SummonEngine/Engine/ForwardRenderer.h | Raboni/SummonEngine | 2a1078d60b604a918b920d098f3f0e60e5ce35bc | [
"MIT"
] | 1 | 2021-01-22T03:49:01.000Z | 2021-01-22T03:49:01.000Z | #pragma once
#include "RenderSettings.h"
#include "PBRBufferStructs.h"
#include <GrowingArray.hpp>
namespace CU
{
class Camera;
}
class DXFramework;
class ModelInstance;
struct ModelRenderCommand;
struct PointLightRenderCommand;
class EnviromentLight;
class VertexShader;
class GeometryShader;
class PixelShader;
struct ID3D11Device;
struct ID3D11DeviceContext;
struct ID3D11CommandList;
struct ID3D11Buffer;
struct ID3D11InputLayout;
struct ID3D11VertexShader;
struct ID3D11PixelShader;
class ForwardRenderer
{
public:
ForwardRenderer(RenderSettings& aSettings);
~ForwardRenderer();
bool Init(DXFramework* aFramework);
void Render(const CU::Camera* aCamera, const EnviromentLight* aLight,
const CU::GrowingArray<ModelRenderCommand>& aModelList, const CU::GrowingArray<CU::GrowingArray<PointLightRenderCommand>>& aLightList);
void RenderSkybox(const CU::Camera* aCamera, const EnviromentLight* aLight, const ModelRenderCommand& aSkybox);
private:
FrameBufferData myFrameBufferData;
ObjectBufferData myObjectBufferData;
PointLightListBufferData myPointLightBufferData;
RenderSettings& mySettings;
ID3D11Device* myDevice;
ID3D11DeviceContext* myContext;
ID3D11Buffer* myFrameBuffer;
ID3D11Buffer* myObjectBuffer;
ID3D11Buffer* myEnviromentLightBuffer;
ID3D11Buffer* myPointLightBuffer;
VertexShader* myDefaultVertexShader;
VertexShader* myDefaultVertexShaderAnim;
VertexShader* myDefaultVertexShaderCustom;
GeometryShader* myDefaultGeometryShaderCustom;
PixelShader* myDefaultPixelShaderCustom;
PixelShader* myDefaultPixelShader;
}; | 28.345455 | 137 | 0.839641 | [
"render"
] |
0e5386043008490ad1393d435e08ad9ecde1dadd | 426 | h | C | design-patterns/design-patterns/Behavioral/Mediator/Mediators/Mediator.h | danabeknar/design-patterns | 7e6b4a23c7725b01b38939e35554992830cc53ac | [
"MIT"
] | 12 | 2018-11-21T07:11:09.000Z | 2019-05-13T15:01:06.000Z | design-patterns/design-patterns/Behavioral/Mediator/Mediators/Mediator.h | danabeknar/design-patterns | 7e6b4a23c7725b01b38939e35554992830cc53ac | [
"MIT"
] | null | null | null | design-patterns/design-patterns/Behavioral/Mediator/Mediators/Mediator.h | danabeknar/design-patterns | 7e6b4a23c7725b01b38939e35554992830cc53ac | [
"MIT"
] | 1 | 2020-06-16T16:30:52.000Z | 2020-06-16T16:30:52.000Z | //
// Mediator.h
// design-patterns
//
// Created by Beknar Danabek on 04/01/2019.
// Copyright © 2019 beknar. All rights reserved.
//
#import <Foundation/Foundation.h>
@class Module;
/// Common mediator interface
@protocol Mediator
/**
Method that notifies with sender and event
@param sender Module object
@param event NSString object
*/
- (void)notifyWithSender:(Module *)sender event:(NSString *)event;
@end
| 17.04 | 66 | 0.713615 | [
"object"
] |
0e586a186590d8f4169ec0d4d77e832b931cc885 | 885 | h | C | include/wlr/types/wlr_box.h | topisani/wlroots | 4984ea49eeaa292d66be9e535d93a4d8185f3e18 | [
"MIT"
] | null | null | null | include/wlr/types/wlr_box.h | topisani/wlroots | 4984ea49eeaa292d66be9e535d93a4d8185f3e18 | [
"MIT"
] | null | null | null | include/wlr/types/wlr_box.h | topisani/wlroots | 4984ea49eeaa292d66be9e535d93a4d8185f3e18 | [
"MIT"
] | null | null | null | #ifndef WLR_TYPES_WLR_BOX_H
#define WLR_TYPES_WLR_BOX_H
#include <stdbool.h>
#include <wayland-server.h>
struct wlr_box {
int x, y;
int width, height;
};
void wlr_box_closest_point(const struct wlr_box *box, double x, double y,
double *dest_x, double *dest_y);
bool wlr_box_intersection(const struct wlr_box *box_a,
const struct wlr_box *box_b, struct wlr_box *dest);
bool wlr_box_contains_point(const struct wlr_box *box, double x, double y);
bool wlr_box_empty(const struct wlr_box *box);
/**
* Transforms a box inside a `width` x `height` box.
*/
void wlr_box_transform(const struct wlr_box *box,
enum wl_output_transform transform, int width, int height,
struct wlr_box *dest);
/**
* Creates the smallest box that contains the box rotated about its center.
*/
void wlr_box_rotated_bounds(const struct wlr_box *box, float rotation,
struct wlr_box *dest);
#endif
| 24.583333 | 75 | 0.761582 | [
"transform"
] |
cd71a2296d7d72f3b443eef53c800fd3954b5f60 | 3,881 | h | C | muan/logging/logger.h | hansonl02/frc-robot-code | 4b120c917a7709df9f010c9089a87c320bab3a16 | [
"MIT"
] | 61 | 2017-01-22T04:38:32.000Z | 2022-03-07T00:04:37.000Z | muan/logging/logger.h | hansonl02/frc-robot-code | 4b120c917a7709df9f010c9089a87c320bab3a16 | [
"MIT"
] | 3 | 2018-06-28T05:34:57.000Z | 2019-01-16T15:46:22.000Z | muan/logging/logger.h | hansonl02/frc-robot-code | 4b120c917a7709df9f010c9089a87c320bab3a16 | [
"MIT"
] | 17 | 2017-05-12T15:32:03.000Z | 2021-12-09T12:49:38.000Z | #ifndef MUAN_LOGGING_LOGGER_H_
#define MUAN_LOGGING_LOGGER_H_
#include <atomic>
#include <map>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "gtest/gtest_prod.h"
#include "muan/logging/filewriter.h"
#include "muan/logging/textlogger.h"
#include "muan/queues/message_queue.h"
#include "muan/units/units.h"
#include "muan/utils/proto_utils.h"
#include "muan/utils/threading_utils.h"
#include "third_party/aos/common/time.h"
#include "third_party/aos/common/util/phased_loop.h"
#include "third_party/aos/linux_code/init.h"
#include "third_party/optional/optional.hpp"
namespace muan {
namespace logging {
/*
* A logging class that takes QueueReader objects and logs them to disk as CSV
* files. It also supports logging text.
*
* Simple use:
*
* Logger logger;
*
* MessageQueue<protobuf_class> mq(100);
* logger.AddQueue("some_queue", mq.MakeReader());
*
* auto textlog = logger.GetTextLogger("log_name");
* textlog("Everything is on fire! Send help.");
*
* You only want to have one logger object running at a time. You should add
* QueueReaders to it as needed.
*
* A note about realtime behavior - The Logger class is running in a thread
* that is not expected to be realtime. Logging messages is realtime, but the
* following operations are not realtime:
* - Adding a Queue to be logged
* - Creating a textlog
* However, these operations should only happen in the beginning of the robot
* code, when the subsystems are being initialized, this should not be a
* problem.
*
* Right now, textlog uses std::string, which is non-realtime if it needs to be
* expanded, so it is up to callers to ensure that the construction of the
* logging string is realtime.
*/
class Logger {
FRIEND_TEST(Logger, TextLogger);
public:
Logger();
explicit Logger(std::unique_ptr<FileWriter>&& writer);
virtual ~Logger() = default;
// Adds a QueueReader<protobuf_class> to the list of queues to be logged,
// under the name "name". The name will determine the file that it logs to,
// as well as serving as a human-readable name in other places.
template <class T>
void AddQueue(const std::string& name, T* queue);
// This is designed to be used with std::thread to run the logger. It will
// run forever, calling the Update function.
void operator()();
// This starts the logger if you have previously stopped it by calling Stop().
void Start();
// This stops the logger from running. It can be resumed calling Start().
void Stop();
// Log with format strings, such as
// LOG(level, "x=%d y=%f", x, y);
template <typename... Ts>
static void LogText(int level, const char* filename, int line, Ts... args);
#define LOG(level, fmt, ...) \
muan::logging::Logger::LogText(level, __FILE__, __LINE__, fmt, ##__VA_ARGS__)
// Very much not realtime. Public only because a bunch of tests use it.
void Update();
private:
std::unique_ptr<FileWriter> writer_;
std::atomic<bool> running_{false};
class GenericReader {
public:
virtual ~GenericReader() = default;
virtual std::experimental::optional<std::string> GetMessageAsCSV(
bool header) = 0;
};
template <class R>
class Reader : public GenericReader {
public:
explicit Reader(R reader);
std::experimental::optional<std::string> GetMessageAsCSV(
bool header) override;
private:
R reader_;
};
struct QueueLog {
std::unique_ptr<GenericReader> reader;
std::string name; // Human friendly name for this log
std::string filename;
bool write_header; // Do we still need to write the header?
};
std::vector<std::unique_ptr<QueueLog>> queue_logs_;
TextLogger::LogQueue::QueueReader textlog_reader_;
static TextLogger text_logger;
}; // class Logger
} // namespace logging
} // namespace muan
#include "logger.hpp"
#endif // MUAN_LOGGING_LOGGER_H_
| 30.085271 | 80 | 0.713991 | [
"object",
"vector"
] |
cd7bdbb9f5c6797fe4a5c039541d5c08a4550de3 | 3,037 | h | C | src/ocean/blif2sls/Network.h | yrrapt/cacd | 696f5a22cb71b83eabbb9de199f1972d458fa9e9 | [
"ISC"
] | 11 | 2019-10-16T11:03:49.000Z | 2021-09-28T19:46:12.000Z | src/ocean/blif2sls/Network.h | yrrapt/cacd | 696f5a22cb71b83eabbb9de199f1972d458fa9e9 | [
"ISC"
] | null | null | null | src/ocean/blif2sls/Network.h | yrrapt/cacd | 696f5a22cb71b83eabbb9de199f1972d458fa9e9 | [
"ISC"
] | 1 | 2021-09-29T18:15:17.000Z | 2021-09-29T18:15:17.000Z | /*
* ISC License
*
* Copyright (C) 1992-2018 by
* Ireneusz Karkowski
* Patrick Groeneveld
* Delft University of Technology
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/*
* Network - represents one sls network
*/
#ifndef __NETWORK_H
#define __NETWORK_H
#include "src/ocean/libocean/Array.h"
#include "src/ocean/libocean/String.h"
#define NetworkDesc __FirstUserClassDesc__
#define EquivalenceDesc NetworkDesc+1
// this class represents two names of
// nodes in a network that are equivalent
class Equivalence : public Object
{
public:
Equivalence(const String&,const String&);
~Equivalence(){}
virtual classType desc() const {return EquivalenceDesc;}
virtual const char* className()const {return "Equivalence";}
virtual Boolean isEqual(const Object& ob)const
{ return Boolean(s1 == ((Equivalence&)ob).s1); }
virtual Object* copy()const {return new Equivalence(s1,s2);}
virtual void printOn(ostream& strm =cout)const;
virtual unsigned hash()const { return 0; }
String s1;
String s2;
};
// This class keeps a sls network: name,
// * name of the network (name)
// * terminals of the network (args)
// * calls to other networks (itself) (might be empty for a network prototype)
class Network: public Array
{
public:
Network(const String& name,Network* proto=NULL);
~Network();
virtual classType desc() const {return NetworkDesc;}
virtual const char* className()const {return "Network";}
int scanPrototype(istream& is);
String& scanToken(istream& is,String& s);
void addTerm(String&,int i=-1);
int getTermNum(const String& s);
String& getName();
void printOn(ostream& os)const;
int numberOfArg(void)const;
String& getArg(int i)const;
Network& getProto()const {return *proto;}
void addEquiv(Equivalence &eq);
void readSpecials(const char* fn);
int isSpecial(const String& s)const;
private:
Network* proto;
String name;
Array args;
static Array eqList;
static Array specials;
};
#endif
| 30.676768 | 78 | 0.643069 | [
"object"
] |
cd7cb9decdd42bca277184fbdf2b364153c09701 | 7,133 | h | C | libbittrex/include/libbittrex/models/order.h | gurpinars/bittrex-cpp | b327fd64efcde88a6f87cc92558c54dc7e4ae280 | [
"MIT"
] | 10 | 2017-10-06T11:16:09.000Z | 2019-06-02T10:14:57.000Z | libbittrex/include/libbittrex/models/order.h | msamigurpinar/bittrex-cpp | b327fd64efcde88a6f87cc92558c54dc7e4ae280 | [
"MIT"
] | 1 | 2018-02-03T09:11:08.000Z | 2018-02-06T06:49:12.000Z | libbittrex/include/libbittrex/models/order.h | gurpinars/bittrex-cpp | b327fd64efcde88a6f87cc92558c54dc7e4ae280 | [
"MIT"
] | 4 | 2018-02-03T06:53:38.000Z | 2019-05-21T08:46:17.000Z | #pragma once
#include <string>
#include <boost/property_tree/ptree.hpp>
namespace bittrex::model {
struct Order {
explicit Order(boost::property_tree::ptree &j) {
account_id = j.get<std::string>("AccountId");
order_uuid = j.get<std::string>("OrderUuid");
exchange = j.get<std::string>("Exchange");
type = j.get<std::string>("Type");
quantity = j.get<std::string>("Quantity");
quantity_remaining = j.get<std::string>("QuantityRemaining");
limit = j.get<std::string>("Limit");
reserved = j.get<std::string>("Reserved");
reserve_remaining = j.get<std::string>("ReserveRemaining");
commission_reserved = j.get<std::string>("CommissionReserved");
commission_reserve_remaining = j.get<std::string>("CommissionReserveRemaining");
commission_paid = j.get<std::string>("CommissionPaid");
price = j.get<std::string>("Price");
price_per_unit = j.get<std::string>("PricePerUnit");
opened = j.get<std::string>("Opened");
closed = j.get<std::string>("Closed");
is_open = j.get<std::string>("IsOpen");
sentinel = j.get<std::string>("Sentinel");
cancel_initiated = j.get<std::string>("CancelInitiated");
immediate_or_cancel = j.get<std::string>("ImmediateOrCancel");
is_conditional = j.get<std::string>("IsConditional");
condition = j.get<std::string>("Condition");
condition_target = j.get<std::string>("ConditionTarget");
}
Order(const Order &other) {
account_id = other.account_id;
order_uuid = other.order_uuid;
exchange = other.exchange;
type = other.type;
quantity = other.quantity;
quantity_remaining = other.quantity_remaining;
limit = other.limit;
reserved = other.reserved;
reserve_remaining = other.reserve_remaining;
commission_reserved = other.commission_reserved;
commission_reserve_remaining = other.commission_reserve_remaining;
commission_paid = other.commission_paid;
price = other.price;
price_per_unit = other.price_per_unit;
opened = other.opened;
closed = other.closed;
is_open = other.is_open;
sentinel = other.sentinel;
cancel_initiated = other.cancel_initiated;
immediate_or_cancel = other.immediate_or_cancel;
is_conditional = other.is_conditional;
condition = other.condition;
condition_target = other.condition_target;
}
Order &operator=(const Order &other) noexcept {
if (this != &other) {
account_id = other.account_id;
order_uuid = other.order_uuid;
exchange = other.exchange;
type = other.type;
quantity = other.quantity;
quantity_remaining = other.quantity_remaining;
limit = other.limit;
reserved = other.reserved;
reserve_remaining = other.reserve_remaining;
commission_reserved = other.commission_reserved;
commission_reserve_remaining = other.commission_reserve_remaining;
commission_paid = other.commission_paid;
price = other.price;
price_per_unit = other.price_per_unit;
opened = other.opened;
closed = other.closed;
is_open = other.is_open;
sentinel = other.sentinel;
cancel_initiated = other.cancel_initiated;
immediate_or_cancel = other.immediate_or_cancel;
is_conditional = other.is_conditional;
condition = other.condition;
condition_target = other.condition_target;
}
return *this;
}
Order(Order &&other) noexcept {
account_id = std::move(other.account_id);
order_uuid = std::move(other.order_uuid);
exchange = std::move(other.exchange);
type = std::move(other.type);
quantity = std::move(other.quantity);
quantity_remaining = std::move(other.quantity_remaining);
limit = std::move(other.limit);
reserved = std::move(other.reserved);
reserve_remaining = std::move(other.reserve_remaining);
commission_reserved = std::move(other.commission_reserved);
commission_reserve_remaining = std::move(other.commission_reserve_remaining);
commission_paid = std::move(other.commission_paid);
price = std::move(other.price);
price_per_unit = std::move(other.price_per_unit);
opened = std::move(other.opened);
closed = std::move(other.closed);
is_open = std::move(other.is_open);
sentinel = std::move(other.sentinel);
cancel_initiated = std::move(other.cancel_initiated);
immediate_or_cancel = std::move(other.immediate_or_cancel);
is_conditional = std::move(other.is_conditional);
condition = std::move(other.condition);
condition_target = std::move(other.condition_target);
}
Order &operator=(Order &&other) noexcept {
if (this != &other) {
account_id = std::move(other.account_id);
order_uuid = std::move(other.order_uuid);
exchange = std::move(other.exchange);
type = std::move(other.type);
quantity = std::move(other.quantity);
quantity_remaining = std::move(other.quantity_remaining);
limit = std::move(other.limit);
reserved = std::move(other.reserved);
reserve_remaining = std::move(other.reserve_remaining);
commission_reserved = std::move(other.commission_reserved);
commission_reserve_remaining = std::move(other.commission_reserve_remaining);
commission_paid = std::move(other.commission_paid);
price = std::move(other.price);
price_per_unit = std::move(other.price_per_unit);
opened = std::move(other.opened);
closed = std::move(other.closed);
is_open = std::move(other.is_open);
sentinel = std::move(other.sentinel);
cancel_initiated = std::move(other.cancel_initiated);
immediate_or_cancel = std::move(other.immediate_or_cancel);
is_conditional = std::move(other.is_conditional);
condition = std::move(other.condition);
condition_target = std::move(other.condition_target);
}
return *this;
}
std::string account_id;
std::string order_uuid;
std::string exchange;
std::string type;
std::string quantity;
std::string quantity_remaining;
std::string limit;
std::string reserved;
std::string reserve_remaining;
std::string commission_reserved;
std::string commission_reserve_remaining;
std::string commission_paid;
std::string price;
std::string price_per_unit;
std::string opened;
std::string closed;
std::string is_open;
std::string sentinel;
std::string cancel_initiated;
std::string immediate_or_cancel;
std::string is_conditional;
std::string condition;
std::string condition_target;
};
} //Namespace bittrex
| 41.71345 | 89 | 0.635777 | [
"model"
] |
cd8b8acee76017f5928ad52f53ee34fab2dea04a | 1,560 | h | C | MPlayer-1.3.0/ffmpeg/libavcodec/diractab.h | xu5343/ffmpegtoolkit_CentOS7 | 974496c709a1c8c69034e46ae5ce7101cf03716f | [
"Apache-2.0"
] | 41 | 2015-04-06T09:15:47.000Z | 2022-02-06T19:02:09.000Z | Thirdparty/ffmpeg/ffmpeg-3.0.2/x64/release/include/libavcodec/diractab.h | shorttermmem/AMF | 43b5211be2d84056ea940b50a98758ec369afef6 | [
"MIT"
] | 15 | 2016-08-26T15:13:03.000Z | 2022-01-05T22:55:11.000Z | Thirdparty/ffmpeg/ffmpeg-3.0.2/x64/release/include/libavcodec/diractab.h | shorttermmem/AMF | 43b5211be2d84056ea940b50a98758ec369afef6 | [
"MIT"
] | 24 | 2015-08-08T10:15:19.000Z | 2021-07-15T22:04:51.000Z | /*
* Copyright (C) 2016 Open Broadcast Systems Ltd.
* Author (C) 2016 Rostislav Pehlivanov <atomnuker@gmail.com>
*
* This file is part of FFmpeg.
*
* FFmpeg 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.1 of the License, or (at your option) any later version.
*
* FFmpeg 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 FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef AVCODEC_DIRACTAB_H
#define AVCODEC_DIRACTAB_H
#include <stdint.h>
/* Tables here are shared between the Dirac/VC-2 decoder and the VC-2 encoder */
/* Default quantization tables for each wavelet transform */
extern const uint8_t ff_dirac_default_qmat[7][4][4];
/* Scaling factors needed for quantization/dequantization */
extern const int32_t ff_dirac_qscale_tab[116];
/* Scaling offsets needed for quantization/dequantization, for intra frames */
extern const int32_t ff_dirac_qoffset_intra_tab[120];
/* Scaling offsets needed for quantization/dequantization, for inter frames */
extern const int ff_dirac_qoffset_inter_tab[122];
#endif /* AVCODEC_DIRACTAB_H */
| 37.142857 | 80 | 0.764744 | [
"transform"
] |
cd91f4dbc13a716d82881e46075493b8924ec6f6 | 6,657 | c | C | pybricks/pupdevices/pb_type_pupdevices_colorsensor.c | ZPhilo/pybricks-micropython | bf3072b6f7dd87b60e50d7c2130ca3c393a5709f | [
"MIT"
] | 1 | 2021-02-26T16:46:32.000Z | 2021-02-26T16:46:32.000Z | pybricks/pupdevices/pb_type_pupdevices_colorsensor.c | ZPhilo/pybricks-micropython | bf3072b6f7dd87b60e50d7c2130ca3c393a5709f | [
"MIT"
] | 1 | 2021-04-15T15:23:59.000Z | 2021-04-15T15:23:59.000Z | pybricks/pupdevices/pb_type_pupdevices_colorsensor.c | BertLindeman/pybricks-micropython | 8f22a99551100e66ddf08d014d9f442f22b33b4d | [
"MIT"
] | 1 | 2021-04-27T17:59:10.000Z | 2021-04-27T17:59:10.000Z | // SPDX-License-Identifier: MIT
// Copyright (c) 2018-2020 The Pybricks Authors
#include "py/mpconfig.h"
#if PYBRICKS_PY_PUPDEVICES
#include "py/mphal.h"
#include <pybricks/common.h>
#include <pybricks/parameters.h>
#include <pybricks/pupdevices.h>
#include <pybricks/util_mp/pb_kwarg_helper.h>
#include <pybricks/util_mp/pb_obj_helper.h>
#include <pybricks/util_pb/pb_color_map.h>
#include <pybricks/util_pb/pb_device.h>
#include <pybricks/util_pb/pb_error.h>
// Class structure for ColorSensor. Note: first two members must match pb_ColorSensor_obj_t
typedef struct _pupdevices_ColorSensor_obj_t {
mp_obj_base_t base;
mp_obj_t color_map;
pb_device_t *pbdev;
mp_obj_t lights;
} pupdevices_ColorSensor_obj_t;
// pybricks._common.ColorSensor._get_hsv_reflected
STATIC void pupdevices_ColorSensor__get_hsv_reflected(pb_device_t *pbdev, pbio_color_hsv_t *hsv) {
// Read RGB
int32_t data[4];
pb_device_get_values(pbdev, PBIO_IODEV_MODE_PUP_COLOR_SENSOR__RGB_I, data);
const pbio_color_rgb_t rgb = {
.r = data[0] == 1024 ? 255 : data[0] >> 2,
.g = data[1] == 1024 ? 255 : data[1] >> 2,
.b = data[2] == 1024 ? 255 : data[2] >> 2,
};
// Convert to HSV
color_map_rgb_to_hsv(&rgb, hsv);
}
// pybricks._common.ColorSensor._get_hsv_ambient
STATIC void pupdevices_ColorSensor__get_hsv_ambient(pb_device_t *pbdev, pbio_color_hsv_t *hsv) {
// Read SHSV mode (light off). This data is not available in RGB format
int32_t data[4];
pb_device_get_values(pbdev, PBIO_IODEV_MODE_PUP_COLOR_SENSOR__SHSV, data);
// Scale saturation and value to match 0-100% range in typical applications
hsv->h = data[0];
hsv->s = data[1] / 10;
if (hsv->s > 100) {
hsv->s = 100;
}
hsv->v = data[2] / 10;
if (hsv->v > 100) {
hsv->v = 100;
}
}
// pybricks.pupdevices.ColorSensor.__init__
STATIC mp_obj_t pupdevices_ColorSensor_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
PB_PARSE_ARGS_CLASS(n_args, n_kw, args,
PB_ARG_REQUIRED(port));
pupdevices_ColorSensor_obj_t *self = m_new_obj(pupdevices_ColorSensor_obj_t);
self->base.type = (mp_obj_type_t *)type;
mp_int_t port = pb_type_enum_get_value(port_in, &pb_enum_type_Port);
// Get iodevices
self->pbdev = pb_device_get_device(port, PBIO_IODEV_TYPE_ID_SPIKE_COLOR_SENSOR);
// Create an instance of the LightArray class
self->lights = common_LightArray_obj_make_new(self->pbdev, PBIO_IODEV_MODE_PUP_COLOR_SENSOR__LIGHT, 3);
// Do one reading to make sure everything is working and to set default mode
pbio_color_hsv_t hsv;
pupdevices_ColorSensor__get_hsv_reflected(self->pbdev, &hsv);
// Save default settings
pb_color_map_save_default(&self->color_map);
return MP_OBJ_FROM_PTR(self);
}
// pybricks._common.ColorSensor.hsv
STATIC mp_obj_t pupdevices_ColorSensor_hsv(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
PB_PARSE_ARGS_METHOD(n_args, pos_args, kw_args,
pupdevices_ColorSensor_obj_t, self,
PB_ARG_DEFAULT_TRUE(surface));
// Create color object
pb_type_Color_obj_t *color = pb_type_Color_new_empty();
// Get either reflected or ambient HSV
if (mp_obj_is_true(surface_in)) {
pupdevices_ColorSensor__get_hsv_reflected(self->pbdev, &color->hsv);
} else {
pupdevices_ColorSensor__get_hsv_ambient(self->pbdev, &color->hsv);
}
// Return color
return MP_OBJ_FROM_PTR(color);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pupdevices_ColorSensor_hsv_obj, 1, pupdevices_ColorSensor_hsv);
// pybricks._common.ColorSensor.color
STATIC mp_obj_t pupdevices_ColorSensor_color(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
PB_PARSE_ARGS_METHOD(n_args, pos_args, kw_args,
pupdevices_ColorSensor_obj_t, self,
PB_ARG_DEFAULT_TRUE(surface));
// Get either reflected or ambient HSV
pbio_color_hsv_t hsv;
if (mp_obj_is_true(surface_in)) {
pupdevices_ColorSensor__get_hsv_reflected(self->pbdev, &hsv);
} else {
pupdevices_ColorSensor__get_hsv_ambient(self->pbdev, &hsv);
}
// Get and return discretized color
return pb_color_map_get_color(&self->color_map, &hsv);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pupdevices_ColorSensor_color_obj, 1, pupdevices_ColorSensor_color);
// pybricks.pupdevices.ColorSensor.reflection
STATIC mp_obj_t pupdevices_ColorSensor_reflection(mp_obj_t self_in) {
pupdevices_ColorSensor_obj_t *self = MP_OBJ_TO_PTR(self_in);
// Get reflection from average RGB reflection, which ranges from 0 to 3*1024
int32_t data[4];
pb_device_get_values(self->pbdev, PBIO_IODEV_MODE_PUP_COLOR_SENSOR__RGB_I, data);
// Return value as reflection
return mp_obj_new_int((data[0] + data[1] + data[2]) * 100 / 3072);
}
MP_DEFINE_CONST_FUN_OBJ_1(pupdevices_ColorSensor_reflection_obj, pupdevices_ColorSensor_reflection);
// pybricks.pupdevices.ColorSensor.ambient
STATIC mp_obj_t pupdevices_ColorSensor_ambient(mp_obj_t self_in) {
pupdevices_ColorSensor_obj_t *self = MP_OBJ_TO_PTR(self_in);
// Get ambient from "V" in SHSV, which ranges from 0 to 10000
int32_t data[4];
pb_device_get_values(self->pbdev, PBIO_IODEV_MODE_PUP_COLOR_SENSOR__SHSV, data);
// Return scaled to 100.
return pb_obj_new_fraction(data[2], 100);
}
MP_DEFINE_CONST_FUN_OBJ_1(pupdevices_ColorSensor_ambient_obj, pupdevices_ColorSensor_ambient);
// dir(pybricks.pupdevices.ColorSensor)
STATIC const mp_rom_map_elem_t pupdevices_ColorSensor_locals_dict_table[] = {
{ MP_ROM_QSTR(MP_QSTR_lights), MP_ROM_ATTRIBUTE_OFFSET(pupdevices_ColorSensor_obj_t, lights)},
{ MP_ROM_QSTR(MP_QSTR_hsv), MP_ROM_PTR(&pupdevices_ColorSensor_hsv_obj) },
{ MP_ROM_QSTR(MP_QSTR_color), MP_ROM_PTR(&pupdevices_ColorSensor_color_obj) },
{ MP_ROM_QSTR(MP_QSTR_reflection), MP_ROM_PTR(&pupdevices_ColorSensor_reflection_obj) },
{ MP_ROM_QSTR(MP_QSTR_ambient), MP_ROM_PTR(&pupdevices_ColorSensor_ambient_obj) },
{ MP_ROM_QSTR(MP_QSTR_detectable_colors), MP_ROM_PTR(&pb_ColorSensor_detectable_colors_obj) },
};
STATIC MP_DEFINE_CONST_DICT(pupdevices_ColorSensor_locals_dict, pupdevices_ColorSensor_locals_dict_table);
// type(pybricks.pupdevices.ColorSensor)
const mp_obj_type_t pb_type_pupdevices_ColorSensor = {
{ &mp_type_type },
.name = MP_QSTR_ColorSensor,
.make_new = pupdevices_ColorSensor_make_new,
.locals_dict = (mp_obj_dict_t *)&pupdevices_ColorSensor_locals_dict,
};
#endif // PYBRICKS_PY_PUPDEVICES
| 38.04 | 126 | 0.74478 | [
"object"
] |
cd976e771b0e6a26a2e0a631daa7642ffbca53e4 | 1,600 | h | C | ogsr_engine/xrGame/sound_memory_manager_inline.h | stepa2/OGSR-Engine | 32a23aa30506684be1267d9c4fc272350cd167c5 | [
"Apache-2.0"
] | 247 | 2018-11-02T18:50:55.000Z | 2022-03-15T09:11:43.000Z | ogsr_engine/xrGame/sound_memory_manager_inline.h | stepa2/OGSR-Engine | 32a23aa30506684be1267d9c4fc272350cd167c5 | [
"Apache-2.0"
] | 193 | 2018-11-02T20:12:44.000Z | 2022-03-07T13:35:17.000Z | ogsr_engine/xrGame/sound_memory_manager_inline.h | stepa2/OGSR-Engine | 32a23aa30506684be1267d9c4fc272350cd167c5 | [
"Apache-2.0"
] | 106 | 2018-10-26T11:33:01.000Z | 2022-03-19T12:34:20.000Z | ////////////////////////////////////////////////////////////////////////////
// Module : sound_memory_manager_inline.h
// Created : 02.10.2001
// Modified : 19.11.2003
// Author : Dmitriy Iassenev
// Description : Sound memory manager inline functions
////////////////////////////////////////////////////////////////////////////
#pragma once
IC CSoundMemoryManager::CSoundMemoryManager (CCustomMonster *object, CAI_Stalker *stalker, CSound_UserDataVisitor *visitor)
{
VERIFY (object);
m_object = object;
VERIFY (visitor);
m_visitor = visitor;
m_stalker = stalker;
m_max_sound_count = 0;
#ifdef USE_SELECTED_SOUND
m_selected_sound = 0;
#endif
}
IC const CSoundMemoryManager::SOUNDS &CSoundMemoryManager::objects () const
{
VERIFY (m_sounds);
return (*m_sounds);
}
IC void CSoundMemoryManager::priority (const ESoundTypes &sound_type, u32 priority)
{
VERIFY (m_priorities.end() == m_priorities.find(sound_type));
m_priorities.insert (std::make_pair(sound_type,priority));
}
#ifdef USE_SELECTED_SOUND
IC const MemorySpace::CSoundObject *CSoundMemoryManager::sound () const
{
return (m_selected_sound);
}
#endif
IC void CSoundMemoryManager::set_squad_objects (SOUNDS *squad_objects)
{
m_sounds = squad_objects;
}
IC void CSoundMemoryManager::set_threshold (float threshold)
{
m_sound_threshold = threshold;
VERIFY (_valid(m_sound_threshold));
}
IC void CSoundMemoryManager::restore_threshold ()
{
m_sound_threshold = m_min_sound_threshold;
VERIFY (_valid(m_sound_threshold));
}
| 27.118644 | 128 | 0.6525 | [
"object"
] |
cd97d9845666f8d17056591c41cd3a40cec088a4 | 19,885 | h | C | tke/include/tencentcloud/tke/v20180525/model/AddExistedInstancesRequest.h | TencentCloud/tencentcloud-sdk-cpp-intl-en | 752c031f5ad2c96868183c5931eae3a42dd5ae6c | [
"Apache-2.0"
] | 1 | 2022-01-27T09:27:34.000Z | 2022-01-27T09:27:34.000Z | tke/include/tencentcloud/tke/v20180525/model/AddExistedInstancesRequest.h | TencentCloud/tencentcloud-sdk-cpp-intl-en | 752c031f5ad2c96868183c5931eae3a42dd5ae6c | [
"Apache-2.0"
] | null | null | null | tke/include/tencentcloud/tke/v20180525/model/AddExistedInstancesRequest.h | TencentCloud/tencentcloud-sdk-cpp-intl-en | 752c031f5ad2c96868183c5931eae3a42dd5ae6c | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef TENCENTCLOUD_TKE_V20180525_MODEL_ADDEXISTEDINSTANCESREQUEST_H_
#define TENCENTCLOUD_TKE_V20180525_MODEL_ADDEXISTEDINSTANCESREQUEST_H_
#include <string>
#include <vector>
#include <map>
#include <tencentcloud/core/AbstractModel.h>
#include <tencentcloud/tke/v20180525/model/InstanceAdvancedSettings.h>
#include <tencentcloud/tke/v20180525/model/EnhancedService.h>
#include <tencentcloud/tke/v20180525/model/LoginSettings.h>
#include <tencentcloud/tke/v20180525/model/NodePoolOption.h>
namespace TencentCloud
{
namespace Tke
{
namespace V20180525
{
namespace Model
{
/**
* AddExistedInstances request structure.
*/
class AddExistedInstancesRequest : public AbstractModel
{
public:
AddExistedInstancesRequest();
~AddExistedInstancesRequest() = default;
std::string ToJsonString() const;
/**
* 获取Cluster ID
* @return ClusterId Cluster ID
*/
std::string GetClusterId() const;
/**
* 设置Cluster ID
* @param ClusterId Cluster ID
*/
void SetClusterId(const std::string& _clusterId);
/**
* 判断参数 ClusterId 是否已赋值
* @return ClusterId 是否已赋值
*/
bool ClusterIdHasBeenSet() const;
/**
* 获取Instance list. Spot instance is not supported.
* @return InstanceIds Instance list. Spot instance is not supported.
*/
std::vector<std::string> GetInstanceIds() const;
/**
* 设置Instance list. Spot instance is not supported.
* @param InstanceIds Instance list. Spot instance is not supported.
*/
void SetInstanceIds(const std::vector<std::string>& _instanceIds);
/**
* 判断参数 InstanceIds 是否已赋值
* @return InstanceIds 是否已赋值
*/
bool InstanceIdsHasBeenSet() const;
/**
* 获取Detailed information of the instance
* @return InstanceAdvancedSettings Detailed information of the instance
*/
InstanceAdvancedSettings GetInstanceAdvancedSettings() const;
/**
* 设置Detailed information of the instance
* @param InstanceAdvancedSettings Detailed information of the instance
*/
void SetInstanceAdvancedSettings(const InstanceAdvancedSettings& _instanceAdvancedSettings);
/**
* 判断参数 InstanceAdvancedSettings 是否已赋值
* @return InstanceAdvancedSettings 是否已赋值
*/
bool InstanceAdvancedSettingsHasBeenSet() const;
/**
* 获取Enhanced services. This parameter is used to specify whether to enable Cloud Security, Cloud Monitoring and other services. If this parameter is not specified, Cloud Monitor and Cloud Security are enabled by default.
* @return EnhancedService Enhanced services. This parameter is used to specify whether to enable Cloud Security, Cloud Monitoring and other services. If this parameter is not specified, Cloud Monitor and Cloud Security are enabled by default.
*/
EnhancedService GetEnhancedService() const;
/**
* 设置Enhanced services. This parameter is used to specify whether to enable Cloud Security, Cloud Monitoring and other services. If this parameter is not specified, Cloud Monitor and Cloud Security are enabled by default.
* @param EnhancedService Enhanced services. This parameter is used to specify whether to enable Cloud Security, Cloud Monitoring and other services. If this parameter is not specified, Cloud Monitor and Cloud Security are enabled by default.
*/
void SetEnhancedService(const EnhancedService& _enhancedService);
/**
* 判断参数 EnhancedService 是否已赋值
* @return EnhancedService 是否已赋值
*/
bool EnhancedServiceHasBeenSet() const;
/**
* 获取Node login information (currently only supports using Password or single KeyIds)
* @return LoginSettings Node login information (currently only supports using Password or single KeyIds)
*/
LoginSettings GetLoginSettings() const;
/**
* 设置Node login information (currently only supports using Password or single KeyIds)
* @param LoginSettings Node login information (currently only supports using Password or single KeyIds)
*/
void SetLoginSettings(const LoginSettings& _loginSettings);
/**
* 判断参数 LoginSettings 是否已赋值
* @return LoginSettings 是否已赋值
*/
bool LoginSettingsHasBeenSet() const;
/**
* 获取When reinstalling the system, you can specify the HostName of the modified instance (when the cluster is in HostName mode, this parameter is required, and the rule name is the same as the [Create CVM Instance](https://intl.cloud.tencent.com/document/product/213/15730?from_cn_redirect=1) API HostName except for uppercase letters not being supported.
* @return HostName When reinstalling the system, you can specify the HostName of the modified instance (when the cluster is in HostName mode, this parameter is required, and the rule name is the same as the [Create CVM Instance](https://intl.cloud.tencent.com/document/product/213/15730?from_cn_redirect=1) API HostName except for uppercase letters not being supported.
*/
std::string GetHostName() const;
/**
* 设置When reinstalling the system, you can specify the HostName of the modified instance (when the cluster is in HostName mode, this parameter is required, and the rule name is the same as the [Create CVM Instance](https://intl.cloud.tencent.com/document/product/213/15730?from_cn_redirect=1) API HostName except for uppercase letters not being supported.
* @param HostName When reinstalling the system, you can specify the HostName of the modified instance (when the cluster is in HostName mode, this parameter is required, and the rule name is the same as the [Create CVM Instance](https://intl.cloud.tencent.com/document/product/213/15730?from_cn_redirect=1) API HostName except for uppercase letters not being supported.
*/
void SetHostName(const std::string& _hostName);
/**
* 判断参数 HostName 是否已赋值
* @return HostName 是否已赋值
*/
bool HostNameHasBeenSet() const;
/**
* 获取Security group to which the instance belongs. This parameter can be obtained from the `sgId` field returned by DescribeSecurityGroups. If this parameter is not specified, the default security group is bound. (Currently, you can only set a single sgId)
* @return SecurityGroupIds Security group to which the instance belongs. This parameter can be obtained from the `sgId` field returned by DescribeSecurityGroups. If this parameter is not specified, the default security group is bound. (Currently, you can only set a single sgId)
*/
std::vector<std::string> GetSecurityGroupIds() const;
/**
* 设置Security group to which the instance belongs. This parameter can be obtained from the `sgId` field returned by DescribeSecurityGroups. If this parameter is not specified, the default security group is bound. (Currently, you can only set a single sgId)
* @param SecurityGroupIds Security group to which the instance belongs. This parameter can be obtained from the `sgId` field returned by DescribeSecurityGroups. If this parameter is not specified, the default security group is bound. (Currently, you can only set a single sgId)
*/
void SetSecurityGroupIds(const std::vector<std::string>& _securityGroupIds);
/**
* 判断参数 SecurityGroupIds 是否已赋值
* @return SecurityGroupIds 是否已赋值
*/
bool SecurityGroupIdsHasBeenSet() const;
/**
* 获取Node pool options
* @return NodePool Node pool options
*/
NodePoolOption GetNodePool() const;
/**
* 设置Node pool options
* @param NodePool Node pool options
*/
void SetNodePool(const NodePoolOption& _nodePool);
/**
* 判断参数 NodePool 是否已赋值
* @return NodePool 是否已赋值
*/
bool NodePoolHasBeenSet() const;
/**
* 获取Skips the specified verification. Valid values: GlobalRouteCIDRCheck, VpcCniCIDRCheck
* @return SkipValidateOptions Skips the specified verification. Valid values: GlobalRouteCIDRCheck, VpcCniCIDRCheck
*/
std::vector<std::string> GetSkipValidateOptions() const;
/**
* 设置Skips the specified verification. Valid values: GlobalRouteCIDRCheck, VpcCniCIDRCheck
* @param SkipValidateOptions Skips the specified verification. Valid values: GlobalRouteCIDRCheck, VpcCniCIDRCheck
*/
void SetSkipValidateOptions(const std::vector<std::string>& _skipValidateOptions);
/**
* 判断参数 SkipValidateOptions 是否已赋值
* @return SkipValidateOptions 是否已赋值
*/
bool SkipValidateOptionsHasBeenSet() const;
/**
* 获取This parameter is used to customize the configuration of an instance, which corresponds to the `InstanceIds` one-to-one in sequence. If this parameter is passed in, the default parameter `InstanceAdvancedSettings` will be overwritten and will not take effect. If this parameter is not passed in, the `InstanceAdvancedSettings` will take effect for each instance.
The array length of `InstanceAdvancedSettingsOverride` should be the same as the array length of `InstanceIds`. If its array length is greater than the `InstanceIds` array length, an error will be reported. If its array length is less than the `InstanceIds` array length, the instance without corresponding configuration will use the default configuration.
* @return InstanceAdvancedSettingsOverrides This parameter is used to customize the configuration of an instance, which corresponds to the `InstanceIds` one-to-one in sequence. If this parameter is passed in, the default parameter `InstanceAdvancedSettings` will be overwritten and will not take effect. If this parameter is not passed in, the `InstanceAdvancedSettings` will take effect for each instance.
The array length of `InstanceAdvancedSettingsOverride` should be the same as the array length of `InstanceIds`. If its array length is greater than the `InstanceIds` array length, an error will be reported. If its array length is less than the `InstanceIds` array length, the instance without corresponding configuration will use the default configuration.
*/
std::vector<InstanceAdvancedSettings> GetInstanceAdvancedSettingsOverrides() const;
/**
* 设置This parameter is used to customize the configuration of an instance, which corresponds to the `InstanceIds` one-to-one in sequence. If this parameter is passed in, the default parameter `InstanceAdvancedSettings` will be overwritten and will not take effect. If this parameter is not passed in, the `InstanceAdvancedSettings` will take effect for each instance.
The array length of `InstanceAdvancedSettingsOverride` should be the same as the array length of `InstanceIds`. If its array length is greater than the `InstanceIds` array length, an error will be reported. If its array length is less than the `InstanceIds` array length, the instance without corresponding configuration will use the default configuration.
* @param InstanceAdvancedSettingsOverrides This parameter is used to customize the configuration of an instance, which corresponds to the `InstanceIds` one-to-one in sequence. If this parameter is passed in, the default parameter `InstanceAdvancedSettings` will be overwritten and will not take effect. If this parameter is not passed in, the `InstanceAdvancedSettings` will take effect for each instance.
The array length of `InstanceAdvancedSettingsOverride` should be the same as the array length of `InstanceIds`. If its array length is greater than the `InstanceIds` array length, an error will be reported. If its array length is less than the `InstanceIds` array length, the instance without corresponding configuration will use the default configuration.
*/
void SetInstanceAdvancedSettingsOverrides(const std::vector<InstanceAdvancedSettings>& _instanceAdvancedSettingsOverrides);
/**
* 判断参数 InstanceAdvancedSettingsOverrides 是否已赋值
* @return InstanceAdvancedSettingsOverrides 是否已赋值
*/
bool InstanceAdvancedSettingsOverridesHasBeenSet() const;
/**
* 获取Node image (it is required when creating a node)
* @return ImageId Node image (it is required when creating a node)
*/
std::string GetImageId() const;
/**
* 设置Node image (it is required when creating a node)
* @param ImageId Node image (it is required when creating a node)
*/
void SetImageId(const std::string& _imageId);
/**
* 判断参数 ImageId 是否已赋值
* @return ImageId 是否已赋值
*/
bool ImageIdHasBeenSet() const;
private:
/**
* Cluster ID
*/
std::string m_clusterId;
bool m_clusterIdHasBeenSet;
/**
* Instance list. Spot instance is not supported.
*/
std::vector<std::string> m_instanceIds;
bool m_instanceIdsHasBeenSet;
/**
* Detailed information of the instance
*/
InstanceAdvancedSettings m_instanceAdvancedSettings;
bool m_instanceAdvancedSettingsHasBeenSet;
/**
* Enhanced services. This parameter is used to specify whether to enable Cloud Security, Cloud Monitoring and other services. If this parameter is not specified, Cloud Monitor and Cloud Security are enabled by default.
*/
EnhancedService m_enhancedService;
bool m_enhancedServiceHasBeenSet;
/**
* Node login information (currently only supports using Password or single KeyIds)
*/
LoginSettings m_loginSettings;
bool m_loginSettingsHasBeenSet;
/**
* When reinstalling the system, you can specify the HostName of the modified instance (when the cluster is in HostName mode, this parameter is required, and the rule name is the same as the [Create CVM Instance](https://intl.cloud.tencent.com/document/product/213/15730?from_cn_redirect=1) API HostName except for uppercase letters not being supported.
*/
std::string m_hostName;
bool m_hostNameHasBeenSet;
/**
* Security group to which the instance belongs. This parameter can be obtained from the `sgId` field returned by DescribeSecurityGroups. If this parameter is not specified, the default security group is bound. (Currently, you can only set a single sgId)
*/
std::vector<std::string> m_securityGroupIds;
bool m_securityGroupIdsHasBeenSet;
/**
* Node pool options
*/
NodePoolOption m_nodePool;
bool m_nodePoolHasBeenSet;
/**
* Skips the specified verification. Valid values: GlobalRouteCIDRCheck, VpcCniCIDRCheck
*/
std::vector<std::string> m_skipValidateOptions;
bool m_skipValidateOptionsHasBeenSet;
/**
* This parameter is used to customize the configuration of an instance, which corresponds to the `InstanceIds` one-to-one in sequence. If this parameter is passed in, the default parameter `InstanceAdvancedSettings` will be overwritten and will not take effect. If this parameter is not passed in, the `InstanceAdvancedSettings` will take effect for each instance.
The array length of `InstanceAdvancedSettingsOverride` should be the same as the array length of `InstanceIds`. If its array length is greater than the `InstanceIds` array length, an error will be reported. If its array length is less than the `InstanceIds` array length, the instance without corresponding configuration will use the default configuration.
*/
std::vector<InstanceAdvancedSettings> m_instanceAdvancedSettingsOverrides;
bool m_instanceAdvancedSettingsOverridesHasBeenSet;
/**
* Node image (it is required when creating a node)
*/
std::string m_imageId;
bool m_imageIdHasBeenSet;
};
}
}
}
}
#endif // !TENCENTCLOUD_TKE_V20180525_MODEL_ADDEXISTEDINSTANCESREQUEST_H_
| 59.894578 | 427 | 0.60699 | [
"vector",
"model"
] |
cdb83db01a2c75dec4b51e00682232b21fd1d0b3 | 17,075 | h | C | src/Engine/rpg/event/Event.h | mpavlinsky/bobsgame | dd4c0713828594ef601c61785164b3fa41e27e2a | [
"Unlicense"
] | 13 | 2021-06-30T15:47:33.000Z | 2021-09-18T15:44:34.000Z | src/Engine/rpg/event/Event.h | mpavlinsky/bobsgame | dd4c0713828594ef601c61785164b3fa41e27e2a | [
"Unlicense"
] | null | null | null | src/Engine/rpg/event/Event.h | mpavlinsky/bobsgame | dd4c0713828594ef601c61785164b3fa41e27e2a | [
"Unlicense"
] | 7 | 2021-06-30T17:14:41.000Z | 2021-10-14T01:41:18.000Z | //------------------------------------------------------------------------------
//Copyright Robert Pelloni.
//All Rights Reserved.
//------------------------------------------------------------------------------
#pragma once
#include "bobtypes.h"
class Logger;
#include "src/Engine/network/ServerObject.h"
class ServerObject;
class Door;
class EventCommand;
class EventData;
class Event : public ServerObject
{
public:
static Logger log;
private:
bool addedToQueue = false;
long long timeAddedToQueue = 0;
bool blockWhileNotHere = false;
long long ticksCounter = 0;
public:
Sprite* sprite = nullptr;
Map* map;
Door* door = nullptr;
Area* area = nullptr;
Entity* entity = nullptr;
EventCommand* commandTree = nullptr;
EventCommand* currentCommand = nullptr;
private:
EventData* data;
public:
Event(Engine* g, int id);
Event(Engine* g, EventData* eventData);
virtual EventData* getData();
virtual int getID();
virtual string getName();
virtual int type();
virtual string getComment();
virtual string text();
virtual string getTYPEIDString();
virtual void setID(int id);
virtual void setName(const string& name);
virtual void setType(int type);
virtual void setComment(const string& comment);
virtual void setText(const string& text);
//The following method was originally marked 'synchronized':
virtual void setData_S(EventData* eventData);
virtual Map* getMap();
virtual Map* getCurrentMap() override;
virtual bool getWasAddedToQueue();
virtual void setAddedToQueue();
virtual void reset();
private:
void parseEventString(string s);
public:
virtual void run();
virtual void getNextCommandInParent();
virtual void getNextCommand();
private:
void getNextCommandIfTrueOrSkipToNextParentCommandIfFalse(bool b);
public:
virtual void doCommand();
private:
void isPlayerTouchingThisArea();
void isPlayerWalkingIntoThisDoor();
void isPlayerTouchingThisEntity();
void isPlayerTouchingAnyEntityUsingThisSprite();
void isPlayerWalkingIntoDoor_DOOR();
void isPlayerWalkingIntoWarp_WARP();
void isPlayerAutoPilotOn();
void isActionButtonHeld();
void isFlagSet_FLAG();
void hasSkillAtLeast_SKILL_FLOAT1();
void isCurrentState_STATE();
void isPlayerStandingInArea_AREA();
void isEntityStandingInArea_ENTITY_AREA();
void hourPastOrEqualTo_INT23();
void hourLessThan_INT23();
void minutePastOrEqualTo_INT59();
void minuteLessThan_INT59();
void hasMoneyAtLeastAmount_FLOAT();
void hasMoneyLessThanAmount_FLOAT();
void hasItem_ITEM();
void hasGame_GAME();
void isPlayerMale();
void isPlayerFemale();
void isAnyEntityUsingSprite_SPRITE();
void isAnyEntityUsingSpriteAtArea_SPRITE_AREA();
void isEntitySpawned_ENTITY();
void isEntityAtArea_ENTITY_AREA();
void isAreaEmpty_AREA();
void hasFinishedDialogue_DIALOGUE();
void isTextBoxOpen();
void isTextAnswerBoxOpen();
void isTextAnswerSelected_INT4();
void isTextAnswerSelected_STRING();
void randomEqualsOneOutOfLessThan_INT();
void randomEqualsOneOutOfIncluding_INT();
void isAnyMusicPlaying();
void isMusicPlaying();
void isRaining();
void isWindy();
void isSnowing();
void isFoggy();
//
// private void isPlayerHolding()/
// {
// // TODO Auto-generated method stub
//
// }
//
//
// private void isPlayerWearing()
// {
// // TODO Auto-generated method stub
//
// }
void isMapOutside();
void hasTalkedToThisToday();
void hasBeenMinutesSinceFlagSet_FLAG_INT();
void hasBeenHoursSinceFlagSet_FLAG_INT23();
void hasBeenDaysSinceFlagSet_FLAG_INT();
void isThisActivated();
void haveSecondsPassedSinceActivated_INT();
void haveMinutesPassedSinceActivated_INT();
void haveHoursPassedSinceActivated_INT();
void haveDaysPassedSinceActivated_INT();
void hasActivatedThisEver();
void hasActivatedThisSinceEnterRoom();
void hasBeenHereEver();
void hasBeenHereSinceEnterRoom();
void haveSecondsPassedSinceBeenHere_INT();
void haveMinutesPassedSinceBeenHere_INT();
void haveDaysPassedSinceBeenHere_INT();
void haveHoursPassedSinceBeenHere_INT();
void isLightOn_LIGHT(); //(INT)
void alwaysBlockWhileNotStandingHere();
void blockUntilActionButtonPressed();
void blockUntilActionCaptionButtonPressed_STRING();
void blockUntilCancelButtonPressed();
void blockForTicks_INT();
void blockUntilClockHour_INT23();
void blockUntilClockMinute_INT59();
void loadMapState_STATE();
void runEvent_EVENT();
void blockUntilEventDone_EVENT();
void clearEvent_EVENT();
void clearThisEvent();
void setThisActivated_BOOL();
void toggleThisActivated();
void setLastBeenHereTime();
void resetLastBeenHereTime();
void setFlag_FLAG_BOOL();
void setFlagTrue_FLAG();
void setFlagFalse_FLAG();
void giveSkillPoints_SKILL_INT();
void removeSkillPoints_SKILL_INT();
void setSkillPoints_SKILL_INT();
void enterThisDoor();
void enterThisWarp();
void enterDoor_DOOR();
void enterWarp_WARP();
void changeMap_MAP_AREA();
void changeMap_MAP_DOOR();
void changeMap_MAP_WARP();
void changeMap_MAP_INT_INT();
void doDialogue_DIALOGUE();
void doDialogueWithCaption_DIALOGUE();
void doDialogueIfNew_DIALOGUE();
void setSpriteBox0_ENTITY();
void setSpriteBox1_ENTITY();
void setSpriteBox0_SPRITE();
void setSpriteBox1_SPRITE();
void blockUntilTextBoxClosed();
void blockUntilTextAnswerBoxClosed();
void doCinematicTextNoBorder_DIALOGUE_INTy();
void setDoorOpenAnimation_DOOR_BOOLopenClose(); //(DOOR,BOOL)
void setDoorActionIcon_DOOR_BOOLonOff(); //(DOOR,BOOL)
void setDoorDestination_DOOR_DOORdestination(); //(DOOR,DOORdestination)
void setAreaActionIcon_AREA_BOOLonOff(); //(DOOR,BOOL)
void setWarpDestination_WARP_WARPdestination(); //(WARP,WARPdestination)
//
// private void playVideo_VIDEO()//(VIDEO)
// {
// // TODO
//
// getNextCommand();
// }
void setPlayerToTempPlayerWithSprite_SPRITE();
void setPlayerToNormalPlayer();
void setPlayerExists_BOOL();
void setPlayerControlsEnabled_BOOL();
void enablePlayerControls();
void disablePlayerControls();
void setPlayerAutoPilot_BOOL();
void setPlayerShowNameCaption_BOOL();
void setPlayerShowAccountTypeCaption_BOOL();
void playerSetBehaviorQueueOnOff_BOOL(); //(ENTITY)
void playerSetToArea_AREA();
void playerSetToDoor_DOOR();
void playerSetToTileXY_INTxTile1X_INTyTile1X();
void playerWalkToArea_AREA();
void playerWalkToDoor_DOOR();
void playerWalkToEntity_ENTITY();
void playerWalkToTileXY_INTxTile1X_INTyTile1X();
void playerBlockUntilReachesArea_AREA(); //TODO rename these
void playerBlockUntilReachesEntity_ENTITY();
void playerBlockUntilReachesDoor_DOOR();
void playerBlockUntilReachesTileXY_INTxTile1X_INTyTile1X();
void playerWalkToAreaAndBlockUntilThere_AREA();
void playerWalkToEntityAndBlockUntilThere_ENTITY();
void playerWalkToDoorAndBlockUntilThere_DOOR();
void playerWalkToTileXYAndBlockUntilThere_INTxTile1X_INTyTile1X();
void playerStandAndShuffle(); //(ENTITY)
void playerStandAndShuffleAndFaceEntity_ENTITY(); //(ENTITY)
void playerSetFaceMovementDirection_STRINGdirection(); //(ENTITY,INT)
void playerSetMovementSpeed_INTticksPerPixel(); //(ENTITY,INT)
void playerDoAnimationByNameOnce_STRINGanimationName_INTticksPerFrame_BOOLrandomUpToTicks(); //(INTticksPerFrame)
void playerDoAnimationByNameLoop_STRINGanimationName_INTticksPerFrame_BOOLrandomUpToTicks_INTticksBetweenLoops_BOOLrandomUpToTicks(); //(INTticksPerFrame)
void playerDoAnimationByNameOnce_STRINGanimationName_INTticksPerFrame(); //(INTticksPerFrame)
void playerDoAnimationByNameLoop_STRINGanimationName_INTticksPerFrame(); //(INTticksPerFrame)
void playerStopAnimating();
void playerSetGlobalAnimationDisabled_BOOL();
void playerSetToAlpha_FLOAT();
void entitySetBehaviorQueueOnOff_ENTITY_BOOL(); //(ENTITY)
void entitySetToArea_ENTITY_AREA();
void entitySetToDoor_ENTITY_DOOR();
void entitySetToTileXY_ENTITY_INTxTile1X_INTyTile1X();
void entityWalkToArea_ENTITY_AREA();
void entityWalkToDoor_ENTITY_DOOR();
void entityWalkToEntity_ENTITY_ENTITY();
void entityWalkToTileXY_ENTITY_INTxTile1X_INTyTile1X();
void entityMoveToArea_ENTITY_AREA_BOOLwalkOrSlide_BOOLcheckHit_BOOLavoidOthers_BOOLpushOthers_BOOLpathfind_BOOLanimate_BOOLmoveDiagonal(); //(ENTITY,AREA,BOOLwalk,BOOLhit,BOOLpath,BOOLanim,BOOLdiag)
void entityMoveToDoor_ENTITY_DOOR_BOOLwalkOrSlide_BOOLcheckHit_BOOLavoidOthers_BOOLpushOthers_BOOLpathfind_BOOLanimate_BOOLmoveDiagonal(); //(ENTITY,ENTITY,BOOLwalk,BOOLhit,BOOLpath,BOOLanim,BOOLdiag)
void entityMoveToEntity_ENTITY_ENTITY_BOOLwalkOrSlide_BOOLcheckHit_BOOLavoidOthers_BOOLpushOthers_BOOLpathfind_BOOLanimate_BOOLmoveDiagonal(); //(ENTITY,ENTITY,BOOLwalk,BOOLhit,BOOLpath,BOOLanim,BOOLdiag)
void entityMoveToTileXY_ENTITY_INTxTile1X_INTyTile1X_BOOLwalkOrSlide_BOOLcheckHit_BOOLavoidOthers_BOOLpushOthers_BOOLpathfind_BOOLanimate_BOOLmoveDiagonal(); //(ENTITY,ENTITY,BOOLwalk,BOOLhit,BOOLpath,BOOLanim,BOOLdiag)
void entityBlockUntilReachesArea_ENTITY_AREA();
void entityBlockUntilReachesEntity_ENTITY_ENTITY();
void entityBlockUntilReachesDoor_ENTITY_DOOR();
void entityBlockUntilReachesTileXY_ENTITY_INTxTile1X_INTyTile1X();
void entityWalkToAreaAndBlockUntilThere_ENTITY_AREA();
void entityWalkToEntityAndBlockUntilThere_ENTITY_ENTITY();
void entityWalkToDoorAndBlockUntilThere_ENTITY_DOOR();
void entityWalkToTileXYAndBlockUntilThere_ENTITY_INTxTile1X_INTyTile1X();
void entityStandAndShuffle_ENTITY(); //(ENTITY)
void entityStandAndShuffleAndFacePlayer_ENTITY(); //(ENTITY)
void entityStandAndShuffleAndFaceEntity_ENTITY_ENTITY(); //(ENTITY)
void entitySetFaceMovementDirection_ENTITY_STRINGdirection(); //(ENTITY,INT)
void entitySetMovementSpeed_ENTITY_INTticksPerPixel(); //(ENTITY,INT)
void entitySetAnimateRandomFrames_ENTITY_INTticksPerFrame_BOOLrandomUpToTicks(); //(INTticksPerFrame)
void entityAnimateOnceThroughCurrentAnimationFrames_ENTITY_INTticksPerFrame_BOOLrandomUpToTicks();
void entityAnimateLoopThroughCurrentAnimationFrames_ENTITY_INTticksPerFrame_BOOLrandomUpToTicks_INTticksBetweenLoops_BOOLrandomUpToTicks(); //(INTticksPerFrame)
void entityAnimateOnceThroughAllFrames_ENTITY_INTticksPerFrame_BOOLrandomUpToTicks(); //(INTticksPerFrame)
void entityAnimateLoopThroughAllFrames_ENTITY_INTticksPerFrame_BOOLrandomUpToTicks_INTticksBetweenLoops_BOOLrandomUpToTicks(); //(INTticksPerFrame)
void entitySetAnimationByNameFirstFrame_ENTITY_STRINGanimationName(); //(INTticksPerFrame)
void entityDoAnimationByNameOnce_ENTITY_STRINGanimationName_INTticksPerFrame(); //(INTticksPerFrame)
void entityDoAnimationByNameLoop_ENTITY_STRINGanimationName_INTticksPerFrame(); //(INTticksPerFrame)
void entityDoAnimationByNameOnce_ENTITY_STRINGanimationName_INTticksPerFrame_BOOLrandomUpToTicks(); //(INTticksPerFrame)
void entityDoAnimationByNameLoop_ENTITY_STRINGanimationName_INTticksPerFrame_BOOLrandomUpToTicks_INTticksBetweenLoops_BOOLrandomUpToTicks(); //(INTticksPerFrame)
void entityStopAnimating_ENTITY();
void entitySetGlobalAnimationDisabled_ENTITY_BOOL();
void entitySetNonWalkable_ENTITY_BOOL();
void entitySetPushable_ENTITY_BOOL();
void entityFadeOutDelete_ENTITY();
void entityDeleteInstantly_ENTITY();
void entitySetToAlpha_ENTITY_FLOAT();
void spawnSpriteAsEntity_SPRITE_STRINGentityIdent_AREA(); //(SPRITE,STRINGentityIdent,AREA)
void spawnSpriteAsEntityFadeIn_SPRITE_STRINGentityIdent_AREA(); //(SPRITE,STRINGentityIdent,AREA)
void spawnSpriteAsNPC_SPRITE_STRINGentityIdent_AREA(); //(SPRITE,STRINGentityIdent,AREA)
void spawnSpriteAsNPCFadeIn_SPRITE_STRINGentityIdent_AREA(); //(SPRITE,STRINGentityIdent,AREA)
void createScreenSpriteUnderTextAtPercentOfScreen_SPRITE_FLOATx_FLOATy(); //(SPRITE,FLOATx,FLOATy)
void createScreenSpriteOverTextAtPercentOfScreen_SPRITE_FLOATx_FLOATy(); //(SPRITE,FLOATx,FLOATy)
void createScreenSpriteUnderText_SPRITE_INTx_INTy(); //(SPRITE,INTx,INTy)
void createScreenSpriteOverText_SPRITE_INTx_INTy(); //(SPRITE,INTx,INTy)
void setCameraTarget_AREA(); //(AREA)
void setCameraTarget_ENTITY(); //(ENTITY)
void setCameraNoTarget();
void setCameraIgnoreBounds_BOOL();
void setCameraTargetToPlayer();
void blockUntilCameraReaches_AREA();
void blockUntilCameraReaches_ENTITY();
void blockUntilCameraReachesPlayer();
void pushCameraState();
void popCameraState();
void setKeyboardCameraZoom_BOOL();
void enableKeyboardCameraZoom();
void disableKeyboardCameraZoom();
void setCameraAutoZoomByPlayerMovement_BOOL(); //(BOOL)
void enableCameraAutoZoomByPlayerMovement(); //(BOOL)
void disableCameraAutoZoomByPlayerMovement(); //(BOOL)
void setCameraZoom_FLOAT(); //(FLOAT)
void setCameraSpeed_FLOAT(); //(FLOAT)
//
// private void setEntityProperty_ENTITY_STRINGpropertyName_BOOL()//(ENTITY,STRINGpropertyName,BOOL)
// {
// Entity e = (Entity) currentCommand.parameterList.get(p++).object;
//
// boolean b = currentCommand.parameterList.get(p++).b;
//
// // TODO
//
// getNextCommand();
//
// }
void giveItem_ITEM(); //(ITEM)
void takeItem_ITEM(); //(ITEM)
void giveGame_GAME(); //(GAME)
void takeMoney_FLOAT(); //(FLOAT)
void giveMoney_FLOAT(); //(FLOAT)
void playSound_SOUND(); //(SOUND)
void playSound_SOUND_FLOATvol();
void playSound_SOUND_FLOATvol_FLOATpitch_INTtimes();
void playMusicOnce_MUSIC();
void playMusicLoop_MUSIC();
void playMusic_MUSIC_FLOATvol_FLOATpitch_BOOLloop();
void stopMusic_MUSIC();
void stopAllMusic();
void blockUntilLoopingMusicDoneWithLoopAndReplaceWith_MUSIC_MUSIC();
void blockUntilMusicDone_MUSIC();
void blockUntilAllMusicDone();
void fadeOutMusic_MUSIC_INT();
void fadeOutAllMusic_INT();
void shakeScreen_INTticks_INTxpixels_INTypixels_INTticksPerShake();
void fadeToBlack_INTticks();
void fadeFromBlack_INTticks();
void fadeToWhite_INTticks();
void fadeFromWhite_INTticks();
void fadeColorFromCurrentAlphaToAlpha_INTticks_INTr_INTg_INTb_FLOATtoAlpha();
void fadeColorFromAlphaToAlpha_INTticks_INTr_INTg_INTb_FLOATfromAlpha_FLOATtoAlpha();
void fadeColorFromTransparentToAlphaBackToTransparent_INTticks_INTr_INTg_INTb_FLOATtoAlpha();
void setInstantOverlay_INTr_INTg_INTb_FLOATa();
void clearOverlay();
void fadeColorFromCurrentAlphaToAlphaUnderLights_INTticks_INTr_INTg_INTb_FLOATtoAlpha();
void setInstantOverlayUnderLights_INTr_INTg_INTb_FLOATa();
void clearOverlayUnderLights();
void fadeColorFromCurrentAlphaToAlphaGroundLayer_INTticks_INTr_INTg_INTb_FLOATtoAlpha();
void setInstantOverlayGroundLayer_INTr_INTg_INTb_FLOATa();
void clearOverlayGroundLayer();
void setLetterbox_BOOL();
void setLetterbox_BOOL_INTticks(); //(BOOL_INTticks)
void setLetterbox_BOOL_INTticks_INTsize(); //(BOOL)
void setLetterbox_BOOL_INTticks_FLOATsize(); //(BOOL)
void setBlur_BOOL(); //(BOOL)
void setMosaic_BOOL(); //(BOOL)
void setHBlankWave_BOOL(); //(BOOL)
void setRotate_BOOL(); //(BOOL)
void setBlackAndWhite_BOOL(); //(BOOL)
void setInvertedColors_BOOL(); //(BOOL)
void set8BitMode_BOOL(); //(BOOL)
void setEngineSpeed_FLOAT(); //(INT)
void toggleLightOnOff_LIGHT(); //(LIGHT)
void setLightOnOff_LIGHT_BOOL(); //(LIGHT,BOOL)
void setLightFlicker_LIGHT_BOOL(); //(LIGHT,BOOL)
void toggleAllLightsOnOff();
void setAllLightsOnOff_BOOL(); //(BOOL)
void setRandomSpawn_BOOL();
void deleteRandoms();
void makeCaption_STRING_INTsec_INTx_INTy_INTr_INTg_INTb();
void makeCaptionOverPlayer_STRING_INTsec_INTr_INTg_INTb();
void makeCaptionOverEntity_ENTITY_STRING_INTsec_INTr_INTg_INTb();
void makeNotification_STRING_INTsec_INTx_INTy_INTr_INTg_INTb(); //(STRING,INTsec,INTx,INTy,INTr,INTg,INTb)
void setShowConsoleMessage_GAMESTRING_INTr_INTg_INT_b_INTticks();
void setShowClockCaption_BOOL();
void setShowDayCaption_BOOL();
void setShowMoneyCaption_BOOL();
void setShowAllStatusBarCaptions_BOOL();
void setShowStatusBar_BOOL();
void setShowNDButton_BOOL();
void setShowGameStoreButton_BOOL();
void setShowStuffButton_BOOL();
void setShowAllButtons_BOOL();
void setNDEnabled_BOOL();
void setGameStoreMenuEnabled_BOOL();
void setStuffMenuEnabled_BOOL();
void setAllMenusAndNDEnabled_BOOL();
void setClockUnknown();
void setClockNormal();
void setTimePaused_BOOL();
void setTimeFastForward();
void setTimeNormalSpeed();
void setNDOpen_BOOL();
void startGame();
void startBobsGameOnStadiumScreen_AREA();
void blockUntilBobsGameDead();
void showLoginScreen();
void closeAllMenusAndND();
void openStuffMenu();
void openItemsMenu();
void openLogMenu();
void openStatusMenu();
void openFriendsMenu();
void openSettingsMenu();
void openGameStoreMenu();
void pushGameState();
void popGameState();
void showTitleScreen();
void showCinemaEvent();
void runGlobalEvent();
};
| 16.691105 | 220 | 0.785944 | [
"object"
] |
cdc8378f8ac10bce82f0ebb9e56524cea4069616 | 3,683 | h | C | OnboardFilterTds/ObfFilterTrack.h | fermi-lat/OnboardFilterTds | 08e52c32a988a82025a429c1c89f7747992a9bbd | [
"BSD-3-Clause"
] | null | null | null | OnboardFilterTds/ObfFilterTrack.h | fermi-lat/OnboardFilterTds | 08e52c32a988a82025a429c1c89f7747992a9bbd | [
"BSD-3-Clause"
] | null | null | null | OnboardFilterTds/ObfFilterTrack.h | fermi-lat/OnboardFilterTds | 08e52c32a988a82025a429c1c89f7747992a9bbd | [
"BSD-3-Clause"
] | null | null | null | /** @file ObfFilterTrack.h
* @author Tracy Usher
*
* $Header: /nfs/slac/g/glast/ground/cvs/OnboardFilterTds/OnboardFilterTds/ObfFilterStatus.h,v 1.7 2008/01/11 21:28:11 usher Exp $
*/
#ifndef ObfFilterTrack_H
#define ObfFilterTrack_H 1
#include "GaudiKernel/SmartRefVector.h"
#include "GaudiKernel/ObjectVector.h"
#include "GaudiKernel/ContainedObject.h"
#include "GaudiKernel/MsgStream.h"
static const CLID& CLID_ObfFilterTrack = InterfaceID("ObfFilterTrack", 1, 0);
namespace OnboardFilterTds {
/**
* @class ObfFilterTrack
*
* @brief This TDS object contains the "best" track information from
* the onboard filter tracking.
*
*/
class ObfFilterTrack : virtual public DataObject
{
public:
// Standard constructor
ObfFilterTrack() : m_nXhits(0), m_nYhits(0), m_xInt(0), m_yInt(0), m_z(0), m_slpXZ(0), m_slpYZ(0) {}
// Constructor with known parameters
ObfFilterTrack(int xHits, int yHits, float xInt, float yInt, float z, float slpXZ, float slpYZ) :
m_nXhits(xHits), m_nYhits(yHits), m_xInt(xInt), m_yInt(yInt), m_z(z), m_slpXZ(slpXZ), m_slpYZ(slpYZ) {}
// TDS DataObject mumbo jumbo
virtual const CLID& clID() const { return ObfFilterTrack::classID(); }
static const CLID& classID() { return CLID_ObfFilterTrack; }
// Standard destructor
virtual ~ObfFilterTrack() {}
// A special "fill" method for use in Root IO
void initialize(int xHits, int yHits, float xInt, float yInt, float z, float slpXZ, float slpYZ);
// Get the track paramters
const int get_nXhits() const {return m_nXhits;}
const int get_nYhits() const {return m_nYhits;}
const float get_xInt() const {return m_xInt;}
const float get_yInt() const {return m_yInt;}
const float get_z() const {return m_z;}
const float get_slpXZ() const {return m_slpXZ;}
const float get_slpYZ() const {return m_slpYZ;}
/// writes out the information of the cluster if msglevel is set to debug
std::ostream& fillStream( std::ostream& s ) const;
private:
int m_nXhits; // Number of hits on the X projection
int m_nYhits; // Number of hits on the Y projection
float m_xInt; // Intercept of the X projection
float m_yInt; // Intercept of the Y projection
float m_z; // Z coordinate of intercept
float m_slpXZ; // slope X-Z plane
float m_slpYZ; // slope Y-Z plane
};
/// Fill the ASCII output stream
inline std::ostream& ObfFilterTrack::fillStream( std::ostream& s ) const
{
return s << "class ObfFilterTrack"
<< " :"
<< "\n Number hits X projection = " << m_nXhits
<< "\n Number hits Y projection = " << m_nYhits
<< "\n Intercept of X projection = "
<< EventFloatFormat (EventFormat::width, EventFormat::precision )
<< m_xInt
<< "\n Intercept of Y projection = "
<< EventFloatFormat (EventFormat::width, EventFormat::precision )
<< m_yInt
<< "\n Z Coordinate at intercept = "
<< EventFloatFormat (EventFormat::width, EventFormat::precision )
<< m_z
<< "\n Slope of X projection = "
<< EventFloatFormat (EventFormat::width, EventFormat::precision )
<< m_slpXZ
<< "\n Slope of Y projection = "
<< EventFloatFormat (EventFormat::width, EventFormat::precision )
<< m_slpYZ
<< std::endl;
}
inline void ObfFilterTrack::initialize(int xHits, int yHits, float xInt, float yInt, float z, float slpXZ, float slpYZ)
{
m_nXhits = xHits;
m_nYhits = yHits;
m_xInt = xInt;
m_yInt = yInt;
m_z = z;
m_slpXZ = slpXZ;
m_slpYZ = slpYZ;
}
} // end namespace
#endif // ObfFilterTrack_H
| 33.788991 | 129 | 0.660331 | [
"object"
] |
cdcb38af1d1a61f21f94ea47fb471d08b2bf08f8 | 8,444 | h | C | ll/include/liblilfes/utility.h | mynlp/enju | d984a630b30b95de16f3b715277e95dc6fbe15b4 | [
"Apache-2.0"
] | 48 | 2016-10-11T06:07:02.000Z | 2022-03-02T16:26:25.000Z | ll/include/liblilfes/utility.h | mynlp/enju | d984a630b30b95de16f3b715277e95dc6fbe15b4 | [
"Apache-2.0"
] | 7 | 2017-02-13T09:14:34.000Z | 2019-01-18T06:06:29.000Z | ll/include/liblilfes/utility.h | mynlp/enju | d984a630b30b95de16f3b715277e95dc6fbe15b4 | [
"Apache-2.0"
] | 18 | 2016-11-13T23:14:28.000Z | 2022-01-12T15:21:44.000Z | #ifndef __utility_h
#define __utility_h
#include "lconfig.h"
#include "builtin.h"
#include <cassert>
#include <list>
#include <string>
#include <utility>
#include <vector>
namespace lilfes {
//////////////////////////////////////////////////////////////////////
////
//// calling predicates from a C program
////
//////////////////////////////////////////////////////////////////////
procedure* prepare_proc(const type* type);
procedure* prepare_proc(const type* type, size_t nargs);
procedure* prepare_proc(const module* mod, const std::string& name, size_t nargs);
bool call_proc(machine& mach, procedure* proc, std::vector<FSP>& args);
void findall_proc(machine& mach, procedure* proc, const std::vector<FSP> & args, const std::vector<bool> & output_flags, std::list<std::vector<FSP> > & results);
//////////////////////////////////////////////////////////////////////
////
//// Loading LiLFeS program
////
//////////////////////////////////////////////////////////////////////
module* load_module( machine& mach, const std::string& title, const std::string& module_name, module* parent_module = module::UserModule() );
int pushfile(machine *m, const std::string &fname, int pi, const std::string &prefix = "");
//////////////////////////////////////////////////////////////////////
////
//// conversion between list and vector
////
//////////////////////////////////////////////////////////////////////
template < class T >
class c_to_lilfes {
public:
bool convert( machine&, T c, FSP fsp ) {
return fsp.Unify( c );
}
};
template <>
class c_to_lilfes< int > {
public:
bool convert( machine&, int c, FSP fsp ) {
return fsp.Unify( static_cast<mint>( c ) );
}
};
template <>
class c_to_lilfes< float > {
public:
bool convert( machine&, float c, FSP fsp ) {
return fsp.Unify( static_cast<mfloat>( c ) );
}
};
template <>
class c_to_lilfes< double > {
public:
bool convert( machine&, double c, FSP fsp ) {
return fsp.Unify( static_cast<mfloat>( c ) );
}
};
template <>
class c_to_lilfes< std::vector< cell > > {
public:
bool convert( machine& mach, const std::vector< cell >& vec, FSP fsp ) {
FSP f( mach, vec );
return fsp.Unify( f );
}
};
template < class T >
class c_to_lilfes< std::vector< T > > {
public:
bool convert( machine& mach, const std::vector< T >& vec, FSP fsp ) {
for ( typename std::vector< T >::const_iterator it = vec.begin();
it != vec.end();
++it ) {
FSP v( mach );
if ( fsp.Coerce( cons )
&& c_to_lilfes< T >().convert( mach, *it, v )
&& fsp.Follow( hd ).Unify( v ) ) {
fsp = fsp.Follow( tl );
continue;
} else {
return false;
}
}
return fsp.Coerce( nil );
}
};
template < class T1, class T2 >
class c_to_lilfes< std::pair< T1, T2 > > {
public:
bool convert( machine& mach, const std::pair< T1, T2 >& pr, FSP fsp ) {
FSP p1( mach );
FSP p2( mach );
return fsp.Coerce( t_comma )
&& c_to_lilfes< T1 >().convert( mach, pr.first, p1 )
&& fsp.Follow( f_arg[ 1 ] ).Unify( p1 )
&& c_to_lilfes< T2 >().convert( mach, pr.second, p2 )
&& fsp.Follow( f_arg[ 2 ] ).Unify( p2 );
}
};
template < class T >
bool vector_to_list( machine& mach,
const std::vector< T >& vec,
FSP fsp ) {
return c_to_lilfes< std::vector< T > >().convert( mach, vec, fsp );
}
// template < class T >
// bool vector_to_list( machine& mach,
// const std::vector< T >& vec,
// FSP fsp ) {
// FSP list( mach );
// FSP root( list );
// for ( typename std::vector< T >::const_iterator it = vec.begin();
// it != vec.end();
// ++it ) {
// list.Coerce( cons );
// list.Follow( hd ).Unify( *it );
// list = list.Follow( tl );
// }
// list.Coerce( nil );
// return fsp.Unify( root );
// }
//////////////////////////////////////////////////////////////////////
template < class T >
class lilfes_to_c {
public:
bool convert( machine&, FSP fsp, T& c );
};
template <>
inline bool lilfes_to_c< FSP >::convert( machine&, FSP arg1, FSP& arg2 ) {
arg2 = arg1;
return true;
}
template <>
inline bool lilfes_to_c< std::string >::convert( machine&, FSP fsp, std::string& s ) {
if ( ! fsp.IsString() ) return false;
s = fsp.ReadString();
return true;
}
template <>
inline bool lilfes_to_c< const char* >::convert( machine&, FSP fsp, const char*& s ) {
if ( ! fsp.IsString() ) return false;
s = fsp.ReadString();
return true;
}
template <>
inline bool lilfes_to_c< int >::convert( machine&, FSP fsp, int& i ) {
if ( ! fsp.IsInteger() ) return false;
i = fsp.ReadInteger();
return true;
}
template <>
inline bool lilfes_to_c< float >::convert( machine&, FSP fsp, float& f ) {
mfloat x = 0.0;
if ( fsp.IsInteger() ) {
x = fsp.ReadInteger();
f = static_cast< float >( x );
return true;
}
if ( fsp.IsFloat() ) {
x = fsp.ReadFloat();
f = static_cast< float >( x );
return true;
}
return false;
}
template <>
inline bool lilfes_to_c< double >::convert( machine&, FSP fsp, double& f ) {
mfloat x = 0.0;
if ( fsp.IsInteger() ) {
x = fsp.ReadInteger();
f = static_cast< double >( x );
return true;
}
if ( fsp.IsFloat() ) {
x = fsp.ReadFloat();
f = static_cast< double >( x );
return true;
}
return false;
}
template < class T >
class lilfes_to_c< std::vector< T > > {
public:
bool convert( machine& mach, FSP fsp, std::vector< T >& vec ) {
if ( ! fsp.GetType()->IsSubType( lilfes::t_list ) ) return false;
while ( fsp.GetType() == cons ) {
FSP head = fsp.Follow( hd );
vec.push_back( T() );
if ( ! lilfes_to_c< T >().convert( mach, head, vec.back() ) ) return false;
fsp = fsp.Follow( tl );
}
return true;
}
};
template <>
inline bool lilfes_to_c< std::vector< cell > >::convert( machine&, FSP fsp, std::vector< cell >& f ) {
fsp.Serialize( f );
return true;
}
// template <>
// bool lilfes_to_c< FSP >::convert( machine&, FSP, FSP& );
// template <>
// bool lilfes_to_c< std::string >::convert( machine&, FSP, std::string& );
// template <>
// bool lilfes_to_c< const char* >::convert( machine&, FSP, const char*& );
// template <>
// bool lilfes_to_c< int >::convert( machine&, FSP, int& );
// template <>
// bool lilfes_to_c< float >::convert( machine&, FSP, float& );
// template <>
// bool lilfes_to_c< std::vector< cell > >::convert( machine&, FSP, std::vector< cell >& );
template < class T1, class T2 >
class lilfes_to_c< std::pair< T1, T2 > > {
public:
bool convert( machine& mach, FSP fsp, std::pair< T1, T2 >& pr ) {
if ( ! fsp.GetType()->IsSubType( lilfes::t_comma ) ) return false;
return lilfes_to_c< T1 >().convert( mach, fsp.Follow( f_arg[ 1 ] ), pr.first )
&& lilfes_to_c< T2 >().convert( mach, fsp.Follow( f_arg[ 2 ] ), pr.second );
}
};
template < class T >
bool list_to_vector( machine& mach,
FSP fsp,
std::vector< T >& vec ) {
return lilfes_to_c< std::vector< T > >().convert( mach, fsp, vec );
}
// template < class T >
// bool list_to_vector( machine& mach,
// FSP fsp,
// std::vector< T >& vec );
// template <>
// bool list_to_vector< FSP >( machine&,
// FSP fsp,
// std::vector< FSP >& vec );
// template <>
// bool list_to_vector< std::string >( machine&,
// FSP fsp,
// std::vector< std::string >& vec );
// template <>
// bool list_to_vector< int >( machine&,
// FSP fsp,
// std::vector< int >& vec );
// template <>
// bool list_to_vector< float >( machine&,
// FSP fsp,
// std::vector< float >& vec );
//////////////////////////////////////////////////////////////////////
////
//// push/pop IP and TrailPoint
////
//////////////////////////////////////////////////////////////////////
class IPTrailStack {
private:
machine* mach;
code* IP;
core_p trailp;
public:
IPTrailStack( machine* m ) : mach( m ), IP( m->GetIP() ), trailp( m->SetTrailPoint( NULL ) ) {}
~IPTrailStack() {
mach->TrailBack( trailp );
mach->SetIP( IP );
}
};
} // namespace lilfes
#endif // __utility_h
| 26.977636 | 161 | 0.526291 | [
"vector"
] |
cde36b000a33d9a6443c3c450ed456c2bbdcc7a2 | 1,759 | h | C | pohessian/include/pohessian/HessianClient.h | pierredavidbelanger/pohessian | f31c49455b295a0b7386d18c78789f586620e6b9 | [
"Apache-2.0"
] | null | null | null | pohessian/include/pohessian/HessianClient.h | pierredavidbelanger/pohessian | f31c49455b295a0b7386d18c78789f586620e6b9 | [
"Apache-2.0"
] | null | null | null | pohessian/include/pohessian/HessianClient.h | pierredavidbelanger/pohessian | f31c49455b295a0b7386d18c78789f586620e6b9 | [
"Apache-2.0"
] | null | null | null | //
// PoHessian
// Portable C++ Hessian Implementation
//
// Copyright (C) 2012 Pierre-David Belanger
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 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, see <http://www.gnu.org/licenses/>.
//
#ifndef pohessian_HessianClient_INCLUDED
#define pohessian_HessianClient_INCLUDED
#include <string>
#include <vector>
#include <ostream>
#include "pohessian/PoHessian.h"
#include "pohessian/HessianTypes.h"
#include "Poco/URI.h"
namespace PoHessian {
class PoHessian_API HessianClientImpl;
class PoHessian_API HessianClient {
public:
enum HessianVersion {
HESSIAN_VERSION_1
};
HessianClient(const HessianVersion version, const Poco::URI& uri);
ValuePtr call(const std::string& method);
ValuePtr call(const std::string& method, const HeaderList& headers);
ValuePtr call(const std::string& method, const ParameterList& parameters);
ValuePtr call(const std::string& method, const HeaderList& headers, const ParameterList& parameters);
ReplyPtr call(const CallPtr& call);
protected:
const HessianVersion _version;
const Poco::URI _uri;
};
}
#endif
| 29.316667 | 109 | 0.702672 | [
"vector"
] |
cde6442f4b112b053cafc34c17d49d9feaa9b480 | 3,673 | h | C | include/simdjson/generic/ondemand/object.h | moneytech/simdjson | 0134d45320c66c576cdee8064c059e5e091e475f | [
"Apache-2.0"
] | null | null | null | include/simdjson/generic/ondemand/object.h | moneytech/simdjson | 0134d45320c66c576cdee8064c059e5e091e475f | [
"Apache-2.0"
] | null | null | null | include/simdjson/generic/ondemand/object.h | moneytech/simdjson | 0134d45320c66c576cdee8064c059e5e091e475f | [
"Apache-2.0"
] | null | null | null | #include "simdjson/error.h"
namespace simdjson {
namespace SIMDJSON_IMPLEMENTATION {
namespace ondemand {
/**
* A forward-only JSON object field iterator.
*/
class object {
public:
/**
* Create a new invalid object.
*
* Exists so you can declare a variable and later assign to it before use.
*/
simdjson_really_inline object() noexcept = default;
simdjson_really_inline object(object &&other) noexcept = default;
simdjson_really_inline object &operator=(object &&other) noexcept = default;
object(const object &) = delete;
object &operator=(const object &) = delete;
simdjson_really_inline ~object() noexcept;
simdjson_really_inline object_iterator begin() noexcept;
simdjson_really_inline object_iterator end() noexcept;
simdjson_really_inline simdjson_result<value> operator[](const std::string_view key) & noexcept;
simdjson_really_inline simdjson_result<value> operator[](const std::string_view key) && noexcept;
protected:
/**
* Begin object iteration.
*
* @param doc The document containing the object. The iterator must be just after the opening `{`.
* @param error If this is not SUCCESS, creates an error chained object.
*/
static simdjson_really_inline simdjson_result<object> start(json_iterator_ref &&iter) noexcept;
static simdjson_really_inline object started(json_iterator_ref &&iter) noexcept;
/**
* Internal object creation. Call object::begin(doc) instead of this.
*
* @param doc The document containing the object. doc->depth must already be incremented to
* reflect the object's depth. The iterator must be just after the opening `{`.
*/
simdjson_really_inline object(json_iterator_ref &&_iter) noexcept;
simdjson_really_inline error_code find_field(const std::string_view key) noexcept;
/**
* Document containing the primary iterator.
*
* PERF NOTE: expected to be elided in favor of the parent document: this is set when the object
* is first used, and never changes afterwards.
*/
json_iterator_ref iter{};
/**
* Whether we are at the start.
*
* PERF NOTE: this should be elided into inline control flow: it is only used for the first []
* or * call, and SSA optimizers commonly do first-iteration loop optimization.
*/
bool at_start{};
friend class value;
friend class document;
friend struct simdjson_result<object>;
};
} // namespace ondemand
} // namespace SIMDJSON_IMPLEMENTATION
} // namespace simdjson
namespace simdjson {
template<>
struct simdjson_result<SIMDJSON_IMPLEMENTATION::ondemand::object> : public SIMDJSON_IMPLEMENTATION::implementation_simdjson_result_base<SIMDJSON_IMPLEMENTATION::ondemand::object> {
public:
simdjson_really_inline simdjson_result(SIMDJSON_IMPLEMENTATION::ondemand::object &&value) noexcept; ///< @private
simdjson_really_inline simdjson_result(error_code error) noexcept; ///< @private
simdjson_really_inline simdjson_result() noexcept = default;
simdjson_really_inline simdjson_result(simdjson_result<SIMDJSON_IMPLEMENTATION::ondemand::object> &&a) noexcept = default;
simdjson_really_inline ~simdjson_result() noexcept = default; ///< @private
simdjson_really_inline simdjson_result<SIMDJSON_IMPLEMENTATION::ondemand::object_iterator> begin() noexcept;
simdjson_really_inline simdjson_result<SIMDJSON_IMPLEMENTATION::ondemand::object_iterator> end() noexcept;
simdjson_really_inline simdjson_result<SIMDJSON_IMPLEMENTATION::ondemand::value> operator[](std::string_view key) & noexcept;
simdjson_really_inline simdjson_result<SIMDJSON_IMPLEMENTATION::ondemand::value> operator[](std::string_view key) && noexcept;
};
} // namespace simdjson
| 39.074468 | 180 | 0.763136 | [
"object"
] |
cde75617077a7d383d8e3374d5ea384574119525 | 2,923 | h | C | NAMD_2.12_Source/charm-6.7.1/src/libs/ck-libs/ParFUM/ParFUM_locking.h | scottkwarren/config-db | fb5c3da2465e5cff0ad30950493b11d452bd686b | [
"MIT"
] | 1 | 2019-01-17T20:07:23.000Z | 2019-01-17T20:07:23.000Z | NAMD_2.12_Source/charm-6.7.1/src/libs/ck-libs/ParFUM/ParFUM_locking.h | scottkwarren/config-db | fb5c3da2465e5cff0ad30950493b11d452bd686b | [
"MIT"
] | null | null | null | NAMD_2.12_Source/charm-6.7.1/src/libs/ck-libs/ParFUM/ParFUM_locking.h | scottkwarren/config-db | fb5c3da2465e5cff0ad30950493b11d452bd686b | [
"MIT"
] | null | null | null | /* File: ParFUM_locking.h
* Authors: Nilesh Choudhury
*
*/
#ifndef __PARFUM_LOCKING_H
#define __PARFUM_LOCKING_H
#define _LOCKCHUNKS
///there is one fem_lock associated with every FEM_Mesh: Chunk Lock (no longer in use)
class FEM_lock {
///Index of the lock (chunk)
int idx;
///Current owner of the lock
int owner;
///Is there an owner for the lock
bool isOwner;
///Is the chunk locked
bool isLocked;
///Does this chunk have locks
bool hasLocks;
///Is this chunk locking some chunks
bool isLocking;
///Is this chunk unlocking some chunks
bool isUnlocking;
///The list of chunks locked by this chunk
CkVec<int> lockedChunks;
///cross-pointer to the femMeshModify object
femMeshModify *mmod;
private:
///Is chunk 'index' locked by this chunk currently
bool existsChunk(int index);
public:
///default constructor
FEM_lock() {};
///constructor
FEM_lock(int i, femMeshModify *m);
///constructor
FEM_lock(femMeshModify *m);
///destructor
~FEM_lock();
///Pup this object
void pup(PUP::er &p);
///Return the index of this chunk
int getIdx() { return idx; }
///locks all chunks which contain all the following nodes and elements
int lock(int numNodes, int *nodes, int numElems, int* elems, int elemType=0);
///unlock all the chunks this chunk has locked currently
int unlock();
///chunk 'own' locks the chunk 'chunkNo'
int lock(int chunkNo, int own);
///chunk 'own' unlocks the chunk 'chunkNo'
int unlock(int chunkNo, int own);
};
///there is one fem_lock associated with every node (locks on elements are not required)
class FEM_lockN {
///owner of the lock on this node
int owner;
///Is there some operation waiting for this lock
int pending;
///cross-pointer to the femMeshModify object on this chunk
femMeshModify *theMod;
///index of the node which this lock protects
int idx;
///the number of read locks on this node
int noreadLocks;
///the number of write locks on this node
int nowriteLocks;
public:
///default constructor
FEM_lockN() {};
///constructor
FEM_lockN(int i,femMeshModify *mod);
///constructor
FEM_lockN(femMeshModify *mod);
///destructor
~FEM_lockN();
///Pup routine for this object
void pup(PUP::er &p);
///Set the femMeshModify object for this chunk
void setMeshModify(femMeshModify *mod);
///return the index of this node
int getIdx() { return idx; }
///reset the data on this node
void reset(int i,femMeshModify *mod);
///get a read lock
int rlock();
///unlock a read lock
int runlock();
///'own' chunk gets a write lock on this node
int wlock(int own);
///unlock the write lock on this node by chunk 'own'
int wunlock(int own);
///Are there any locks on this node
bool haslocks();
///verify if locks exist on this node
bool verifyLock(void);
///who owns this lock now
int lockOwner();
};
// end ParFUM_locking.h
#endif
| 25.198276 | 88 | 0.69415 | [
"object"
] |
cdf4e13cf7375cb721e5109cb131f691e4d1ff23 | 4,246 | c | C | nitan/clone/book/yjj_book2.c | cantona/NT6 | 073f4d491b3cfe6bfbe02fbad12db8983c1b9201 | [
"MIT"
] | 1 | 2019-03-27T07:25:16.000Z | 2019-03-27T07:25:16.000Z | nitan/clone/book/yjj_book2.c | cantona/NT6 | 073f4d491b3cfe6bfbe02fbad12db8983c1b9201 | [
"MIT"
] | null | null | null | nitan/clone/book/yjj_book2.c | cantona/NT6 | 073f4d491b3cfe6bfbe02fbad12db8983c1b9201 | [
"MIT"
] | null | null | null | //rama@sz
//易筋經殘篇
inherit BOOK;
int do_xiulian();
int finish(object me);
void setup()
{}
void init()
{
add_action("do_xiulian", "xiulian");
add_action("do_xiulian", "xiu");
}
void create()
{
set_name("易筋經殘篇", ({ "yijinjing" }));
set_weight(600);
set("no_drop",1);
set("no_get",1);
set("no_steal",1);
if( clonep() )
set_default_object(__FILE__);
else
{
set("unit", "本");
set("long", "這是一本梵文經書,每一頁上都寫彎彎曲曲的文字,沒一個識得。\n");
set("value", 5000);
set("material", "paper");
}
}
int do_xiulian()
{
object me,ob;
object where_1;
int poison_lvl;
me=this_player();
if(!me->query_skill("poison",1))
return notify_fail("你連基本的毒功都不會,還想領略這麼高深的技巧?\n");
poison_lvl = me->query_skill("poison",1);
where_1 = environment(me);
if (!present("yijinjing", me))
return 0;
if( me->is_busy() )
return notify_fail("你正忙着呢!\n");
if( query("pigging", where_1) )
return notify_fail("你還是專心拱豬吧!\n");
if( query("sleep_room", where_1) )
return notify_fail("不能在睡房裏修煉,這會影響他人。\n");
if( query("no_fight", where_1) )
return notify_fail("這裏空氣不好,還是找別處吧!\n");
if( query("name", where_1) == "大車裏" )
return notify_fail("車裏太顛簸, 修練會走火入魔. \n");
if( me->is_busy() || query_temp("pending/exercising", me) )
if( me->is_fighting() )
return notify_fail("戰鬥中不能修煉,會走火入魔。\n");
if( query_temp("is_riding", me) )
return notify_fail("在坐騎上修練,會走火入魔。\n");
if( query("canewhua", me) == 1 )
return notify_fail("你無法再從這本書上學到任何新東西了。\n");
if( !stringp(me->query_skill_mapped("force")) || me->query_skill_mapped("force") != "huagong-dafa")
return notify_fail("你必須先用 enable 化功大法。\n");
if (poison_lvl < 250)
return notify_fail("第一頁上面的一些用毒技巧,你怎麼也領略不了,看來你的毒功還有待加強。");
if(present("yijinjing",me) && !present("shenmuwang ding",me))
{
write("你開始按照定春秋教你的獨特練功方法調息打坐。\n");
if(random(4)==1){
write("沒有神木王鼎的幫助,你根本無法控制住自己的氣,你只覺得體內橫衝直撞,你有些神智不清了!\n");
write("你哇的吐出一口鮮血,你只覺得意識在慢慢的消失!\n");
set_temp("die_reason", "修煉易筋經殘扁,走火入魔死了", me);
me->receive_damage("qi",query("eff_qi", me)+200);
return 1;
}
else
me->start_busy(30);
call_out("finish",60);
return 1;
}
ob=present("shenmuwang ding",me);
if( query("fake", ob) || query("item_make", ob) )
{
return notify_fail("你試了半天,神木王鼎沒有半點動靜,看來是個假貨!\n");
}
write("你開始按照易筋經上面獨特的練功方法開始調息打坐。\n");
write("神木王鼎也冒出了裊裊的清煙,一切都讓你你覺得和諧極了,慢慢的甚至忘記了自我的存在。\n");
if( random((200/query("int", me)))>3 )
{
write("忽然你覺得腦子裏面有些混亂,好像哪個地方不對了!\n");
write("你哇的吐出一口鮮血,你只覺得意識在慢慢的消失!\n");
me->receive_damage("jing",30);
me->receive_damage("qi",100);
me->start_busy(30);
return 1;
}
else
{
me->start_busy(30);
call_out("finish",60);
}
return 1;
}
int finish(object me)
{
me=this_player();
write("你只覺得渾身上下舒暢無比,不由暗自歎道:“真不愧是易筋經!”\n");
me->clear_condition("bingcan_poison",5);
if( query("yijinjing", me)<1 )
{
set("yijinjing", 1, me);
}
addn("yijinjing", 1, me);
if( query("yijinjing", me) >= 10 )
{
write("你心台忽然一片明朗,多日來的疑慮一掃而空!你領悟出了化功大法真正精髓的所在!\n");
delete("yijinjing", me);
set("canewhua", 1, me);
set("huagong_hua", 1, me);
me->clear_condition("bingcan_poison");
return 1;
//學會yun hua
}
return 1;
}
| 29.282759 | 107 | 0.475977 | [
"object"
] |
cdf8290fa9f2a84cc9472d9c59fce77a1a756aec | 22,039 | c | C | ccs-workspace/firmware-main/JTOK/src/jtok_object.c | DalhousieSpaceSystemsLab/CubeSat-ADCS-Firmware | ea641cef6a200e6adc49740b41985468ab7e3667 | [
"MIT"
] | null | null | null | ccs-workspace/firmware-main/JTOK/src/jtok_object.c | DalhousieSpaceSystemsLab/CubeSat-ADCS-Firmware | ea641cef6a200e6adc49740b41985468ab7e3667 | [
"MIT"
] | 2 | 2021-12-14T13:30:44.000Z | 2022-01-13T04:57:12.000Z | ccs-workspace/firmware-main/JTOK/src/jtok_object.c | DalhousieSpaceSystemsLab/CubeSat-ADCS-Firmware | ea641cef6a200e6adc49740b41985468ab7e3667 | [
"MIT"
] | null | null | null | /**
* @file jtok_object.c
* @author Carl Mattatall (cmattatall2@gmail.com)
* @brief Source module to handle jtok object operations
* @version 0.1
* @date 2020-12-25
*
* @copyright Copyright (c) 2020 Carl Mattatall
*
*/
#include <assert.h>
#include <limits.h>
#include "jtok_object.h"
#include "jtok_array.h"
#include "jtok_primitive.h"
#include "jtok_string.h"
#include "jtok_shared.h"
JTOK_PARSE_STATUS_t jtok_parse_object(jtok_parser_t *parser, int depth)
{
JTOK_PARSE_STATUS_t status = JTOK_PARSE_STATUS_OK;
int start = parser->pos;
const char *json = parser->json;
int len = parser->json_len;
jtok_tkn_t *tokens = parser->tkn_pool;
if (depth > JTOK_MAX_RECURSE_DEPTH)
{
status = JTOK_PARSE_STATUS_NEST_DEPTH_EXCEEDED;
return status;
}
enum
{
OBJECT_KEY,
OBJECT_COLON,
OBJECT_VALUE,
OBJECT_COMMA,
} expecting = OBJECT_KEY;
if (tokens == NULL) /* Check for caller API error */
{
return status;
}
else if (json[parser->pos] != '{')
{
return JTOK_PARSE_STATUS_NON_OBJECT;
}
jtok_tkn_t *token = jtok_alloc_token(parser);
if (token == NULL)
{
/*
* Do not reset parser->pos because we want
* caller to see which token maxed out the
* pool
*/
status = JTOK_PARSE_STATUS_NOMEM;
return status;
}
/* If the object has a parent key, increase that key's size */
token->parent = parser->toksuper;
/* new superior token becomes the one we JUST processed */
parser->toksuper = parser->toknext - 1;
/* Index of current top level token is the current superior token */
/* We need to preserve the index of top level token in the currenet
* stack frame because parsing a sub-object changes the value of
* parser->toksuper
*/
int object_token_index = parser->toksuper;
/* end of token will be populated when we find the closing brace */
jtok_fill_token(token, JTOK_OBJECT, parser->pos, JTOK_INVALID_ARRAY_INDEX);
/* go inside the object */
parser->pos++;
/* all objects start with no children (since they can be empty) */
parser->last_child = JTOK_NO_CHILD_IDX;
for (; parser->pos < len && json[parser->pos] != '\0' &&
status == JTOK_PARSE_STATUS_OK;
parser->pos++)
{
switch (json[parser->pos])
{
case '{':
{
switch (expecting)
{
case OBJECT_KEY:
{
status = JTOK_PARSE_STATUS_OBJ_NOKEY;
}
break;
case OBJECT_COLON:
{
status = JTOK_PARSE_STATUS_VAL_NO_COLON;
}
break;
case OBJECT_VALUE: /* Enter and parse the sub-object */
{
/* Index of the key that owns this object */
int key_idx = parser->toksuper;
status = jtok_parse_object(parser, depth + 1);
if (status == JTOK_PARSE_STATUS_OK)
{
if (key_idx != JTOK_NO_PARENT_IDX)
{
tokens[key_idx].size++;
}
parser->toksuper = key_idx;
expecting = OBJECT_COMMA;
parser->last_child = key_idx;
}
}
break;
case OBJECT_COMMA:
default:
{
status = JTOK_PARSE_STATUS_INVAL;
}
break;
}
}
break;
case '[':
{
switch (expecting)
{
case OBJECT_KEY:
{
status = JTOK_PARSE_STATUS_OBJ_NOKEY;
}
break;
case OBJECT_COLON:
{
status = JTOK_PARSE_STATUS_VAL_NO_COLON;
}
break;
case OBJECT_VALUE:
{
/* Index of key that "owns" the array */
int key_idx = parser->toksuper;
status = jtok_parse_array(parser, depth + 1);
if (status == JTOK_PARSE_STATUS_OK)
{
if (key_idx != JTOK_NO_PARENT_IDX)
{
tokens[key_idx].size++;
}
else
{
/* Keys must have a parent token */
status = JTOK_PARSE_STATUS_INVALID_PARENT;
}
parser->last_child = key_idx;
expecting = OBJECT_COMMA;
}
}
break;
case OBJECT_COMMA:
{
status = JTOK_PARSE_STATUS_INVAL;
}
break;
default:
{
status = JTOK_PARSE_STATUS_INVAL;
}
break;
}
}
break;
case '}':
{
switch (expecting)
{
/* Technically we should be checking if this is the very
* first token in the object, because
* {"key1" : "value1", "key2" : "value2",} is invalid
* from the trailing comma
* (transition to expecting==key only occurs when finding
* comma or when we START parsing the object)
*
* So in cases where we have transitioned from a comma,
* if we find '}' then it means we have a trailing
* comma inside the object
*/
/********************************
* Case where we find end of *
* object instead of key *
* (aka: empty object) *
* *
* eg: { } *
* ^ Right here *
*******************************/
case OBJECT_KEY:
{
jtok_tkn_t *parent_obj = &tokens[object_token_index];
if (parent_obj->type != JTOK_OBJECT ||
parser->toknext == 0)
{
parser->pos = start;
status = JTOK_PARSE_STATUS_INVAL;
}
else
{
parent_obj->end = parser->pos + 1;
parser->toksuper = parent_obj->parent;
/* Don't have to update children->sibling link
* because there are no children in the object */
}
return status;
}
break;
/****************************************************
* Case wherein, instead of comma, *
* we find end of object '}' *
* eg : {\"key\":true, \"blah\":false } *
* ^ *
* Right here *
***************************************************/
case OBJECT_COMMA:
{
jtok_tkn_t *parent_obj = &tokens[object_token_index];
if (parent_obj->type != JTOK_OBJECT ||
parser->toknext == 0)
{
parser->pos = start;
status = JTOK_PARSE_STATUS_INVAL;
}
else
{
parent_obj->end = parser->pos + 1;
/* Update superior token to the key that owns
* the current object */
parser->toksuper = parent_obj->parent;
/* Final item in object has no sibling key */
if (parser->last_child != JTOK_NO_CHILD_IDX)
{
tokens[parser->last_child].sibling =
JTOK_NO_SIBLING_IDX;
}
/* Update last child */
parser->last_child = JTOK_NO_CHILD_IDX;
}
return status;
}
break;
case OBJECT_COLON:
{
status = JTOK_PARSE_STATUS_KEY_NO_VAL;
}
break;
case OBJECT_VALUE:
{
status = JTOK_PARSE_STATUS_KEY_NO_VAL;
}
break;
default:
{
status = JTOK_PARSE_STATUS_INVAL;
}
break;
}
}
break;
case '\"':
case '\'':
{
switch (expecting)
{
case OBJECT_KEY:
{
jtok_tkn_t *parent_obj = &tokens[parser->toksuper];
if (parent_obj->type == JTOK_OBJECT)
{
status = jtok_parse_string(parser);
if (status == JTOK_PARSE_STATUS_OK)
{
if (parser->last_child != JTOK_NO_CHILD_IDX)
{
/* Link previous child to current child */
tokens[parser->last_child].sibling =
parser->toknext - 1;
}
/* Update last child and increase parent size */
parser->last_child = parser->toknext - 1;
parent_obj->size++;
}
expecting = OBJECT_COLON;
}
else
{
status = JTOK_PARSE_STATUS_INVALID_PARENT;
}
}
break;
case OBJECT_VALUE:
{
jtok_tkn_t *key_tkn = &tokens[parser->toksuper];
if (key_tkn->type == JTOK_STRING)
{
if (key_tkn->size != 0)
{
/* an object key can only have 1 value */
status = JTOK_PARSE_STATUS_KEY_MULTIPLE_VAL;
}
else
{
status = jtok_parse_string(parser);
if (status == JTOK_PARSE_STATUS_OK)
{
key_tkn->size++;
}
expecting = OBJECT_COMMA;
}
}
else
{
status = JTOK_PARSE_STATUS_INVALID_PARENT;
}
}
break;
case OBJECT_COLON: /* found " when expecting ':' */
{
status = JTOK_PARSE_STATUS_VAL_NO_COLON;
}
break;
case OBJECT_COMMA: /* found " when expecting ',' */
{
status = JTOK_PARSE_STATUS_VAL_NO_COMMA;
}
break;
default:
{
status = JTOK_PARSE_STATUS_INVAL;
}
break;
}
}
break;
case '\t':
case '\r':
case '\n':
case ' ':
continue; /* skip whitespce */
case ':':
{
if (expecting == OBJECT_COLON)
{
expecting = OBJECT_VALUE;
/* Superior token becomes the key we just processed */
parser->toksuper = parser->toknext - 1;
}
else
{
parser->pos = start;
status = JTOK_PARSE_STATUS_INVAL;
}
}
break;
case ',':
{
if (expecting == OBJECT_COMMA)
{
expecting = OBJECT_KEY;
jtok_tkn_t *parent_key = &tokens[parser->toksuper];
parser->toksuper = parent_key->parent;
}
else
{
status = JTOK_PARSE_STATUS_OBJ_NOKEY;
}
}
break;
case '+':
case '-':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 't':
case 'f':
case 'n':
{
/* We must be expecting a value */
if (expecting == OBJECT_VALUE)
{
/* We're at the start of a primitive so validate parent type
*/
jtok_tkn_t *parent = &tokens[parser->toksuper];
switch (parent->type)
{
case JTOK_OBJECT:
{
/* primitives cannot be keys (they are not
* quoted)
*/
parser->pos = start;
status = JTOK_PARSE_STATUS_INVAL;
}
break;
case JTOK_STRING:
{
if (parent->size != 0)
{
/* an object key can only have 1 value */
parser->pos = start;
status = JTOK_PARSE_STATUS_INVAL;
}
}
break;
default:
{
/*
* If we're inside parse_object,
* other types cannot be parent tokens
*/
status = JTOK_PARSE_STATUS_INVAL;
}
break;
}
if (status == JTOK_PARSE_STATUS_OK)
{
status = jtok_parse_primitive(parser);
if (status == JTOK_PARSE_STATUS_OK)
{
if (parser->toksuper != JTOK_NO_PARENT_IDX)
{
tokens[parser->toksuper].size++;
}
expecting = OBJECT_COMMA;
}
}
}
else
{
/* move pos to start of the key that's missing the value */
parser->pos = tokens[parser->toksuper].start;
status = JTOK_PARSE_STATUS_KEY_NO_VAL;
}
}
break;
default: /* unexpected character */
{
parser->pos = start;
status = JTOK_PARSE_STATUS_INVAL;
}
break;
} /* end of character switch statement */
}
if (status == JTOK_PARSE_STATUS_OK)
{
/* If we didnt find the } to close current object, we have partial JSON
*/
parser->pos = start;
status = JTOK_PARSE_STATUS_PARTIAL_TOKEN;
}
return status;
}
bool jtok_toktokcmp_object(const jtok_tkn_t *obj1, const jtok_tkn_t *obj2)
{
const jtok_tkn_t *const pool1 = obj1->pool;
assert(pool1 != NULL);
assert(pool1->type == JTOK_OBJECT);
assert(pool1->json == obj1->json);
if (pool1 != obj1)
{
/* Greater than 1 because if it's non-empty, it must AT LEAST
* have a key inside it as well as the value for that key */
assert(pool1->size > 1);
}
const jtok_tkn_t *const pool2 = obj2->pool;
assert(pool2 != NULL);
assert(pool2->type == JTOK_OBJECT);
assert(pool2->json == obj2->json);
if (pool2 != obj2)
{
/* Greater than 1 because if it's non-empty, it must AT LEAST
* have a key inside it as well as the value for that key */
assert(pool2->size > 1);
}
bool is_equal = true;
if (obj1->type != JTOK_OBJECT || obj2->type != JTOK_OBJECT)
{
is_equal = false;
}
else
{
/* Easy preliminary check */
if (obj1->size != obj2->size)
{
is_equal = false;
}
else if (obj1->size > 0)
{
/*
* 2 empty objects are trivally equal
* so only perform child comparison if the objects actaully
* have children
*/
int i;
int j;
/* When object not empty, its first child is token after object */
jtok_tkn_t *child1 = (jtok_tkn_t *)&obj1[1];
assert(child1->type == JTOK_STRING);
for (i = 0; i < obj1->size && is_equal; i++)
{
jtok_tkn_t *child2 = (jtok_tkn_t *)&obj2[1];
assert(child2->type == JTOK_STRING);
/* Try to find matching key in second object */
for (j = 0; j < obj2->size && is_equal; j++)
{
if (jtok_toktokcmp(child1, child2))
{
/* If key matches, compare values */
jtok_tkn_t *val1 = &child1[1];
jtok_tkn_t *val2 = &child2[1];
if (jtok_toktokcmp(val1, val2))
{
/* value of key in obj1 matches value of key in obj2
* exit search loop for key in obj2 */
break;
}
else
{
/*
* Since there cannot be duplicate keys
* in a json object, if we find the key in obj2
* but it's value isn't equal to the value of the
* SAME key in obj1, then the objects cannot be
* equal.
*/
is_equal = false;
}
}
else
{
/* Curerent key in obj2 doesnt match current key in
* obj1, but the objects may have keys ordered
* differently. So we check if we can explore other
* child keys and if yes, we repeat the process until
* all of obj2's child keys are exhausted */
if (child2->sibling == JTOK_NO_SIBLING_IDX)
{
/* We've ran out of children in obj2 to check
* against current key in obj1 */
is_equal = false;
break;
}
else
{
/* Go to next key */
child2 = (jtok_tkn_t *)&pool2[child2->sibling];
}
}
} /* END J LOOP */
if (j == obj2->size)
{
/* Did not find key in obj2 matching current key in obj1
*/
is_equal = false;
}
else
{
/* We matched current key in obj1, */
/* so go to next key to match. */
child1 = (jtok_tkn_t *)&pool1[child1->sibling];
}
} /* END I LOOP */
}
}
return is_equal;
} | 35.894137 | 80 | 0.362993 | [
"object"
] |
0772d48c4ed385ae57e40d14a3183b131f40e071 | 1,629 | h | C | network/Messages/FilterAddMessage.h | jambolo/Equity | e9f142aec8c5292406b32633fd714c26cf7fd6cd | [
"MIT"
] | null | null | null | network/Messages/FilterAddMessage.h | jambolo/Equity | e9f142aec8c5292406b32633fd714c26cf7fd6cd | [
"MIT"
] | null | null | null | network/Messages/FilterAddMessage.h | jambolo/Equity | e9f142aec8c5292406b32633fd714c26cf7fd6cd | [
"MIT"
] | null | null | null | #pragma once
#include "network/Message.h"
#include <nlohmann/json_fwd.hpp>
namespace Network
{
//! An add-filter message.
//!
//! This message adds the given data element to the connections current filter without requiring a completely new one to be set.
//!
//! The given data element will be added to the bloom filter. A filter must have been previously provided using a load-filter
//! message. This message is useful if a new key or script is added to a clients wallet whilst it has connections to the network
//! open, it avoids the need to re-calculate and send an entirely new filter to every peer (though doing so is usually advisable
//! to maintain anonymity).
//!
//! @note This message is related to bloom filtering of connections and is defined in BIP 0037.
//! @sa FilterClearMessage, FilterLoadMessage, MerkleBlockMessage
class FilterAddMessage : public Message
{
public:
// Constructor
//!
//! @param data data element
FilterAddMessage(std::vector<uint8_t> const & data);
// Deserialization constructor
//!
//! @param[in,out] in pointer to the next byte to deserialize
//! @param[in,out] size number of bytes remaining in the serialized stream
FilterAddMessage(uint8_t const * & in, size_t & size);
//! @name Overrides Serializable
//!@{
virtual void serialize(std::vector<uint8_t> & out) const override;
virtual nlohmann::json toJson() const override;
//!@}
//! Data element to add to the current filter.
std::vector<uint8_t> data_;
//! Message type
static char const TYPE[];
};
} // namespace Network
| 33.9375 | 128 | 0.698588 | [
"vector"
] |
07836a87f14f9774ed4ddc88b33e9b5454f2255a | 1,848 | h | C | visualization/heavenlybody/heavenlybody3d.h | fdeitelhoff/SolarSystemSimulation | 9a5232498c2a6b6fe9dd02dfb11e91b9aad5ab48 | [
"MIT"
] | null | null | null | visualization/heavenlybody/heavenlybody3d.h | fdeitelhoff/SolarSystemSimulation | 9a5232498c2a6b6fe9dd02dfb11e91b9aad5ab48 | [
"MIT"
] | null | null | null | visualization/heavenlybody/heavenlybody3d.h | fdeitelhoff/SolarSystemSimulation | 9a5232498c2a6b6fe9dd02dfb11e91b9aad5ab48 | [
"MIT"
] | null | null | null | /*
Copyright (C) 2012 by
Fabian Deitelhoff (FH@FabianDeitelhoff.de) and
Christof Geisler (christof.geisler@stud.fh-swf.de)
This file is part of the project SolarSystemSimulation.
SolarSystemSimulation is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SolarSystemSimulation 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 SolarSystemSimulation. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef HEAVENLYBODY3D_H
#define HEAVENLYBODY3D_H
#include <QDebug>
#include "model/heavenlybody/heavenlybody.h"
#include "OpenGL/glcolorrgba.h"
#include "OpenGL/GL/glut.h"
#include "OpenGL/glvector.h"
/**
Class to calculate and paint the heavenly bodies.
@author Fabian Deitelhoff <FH@FabianDeitelhoff.de>
@author Christof Geisler <christof.geisler@stud.fh-swf.de>
*/
class HeavenlyBody3d
{
public:
HeavenlyBody3d(HeavenlyBody *heavenlyBody);
virtual void paintHeavenlyBody3d();
virtual void calculateHeavenlyBody3d();
void setOrbitVisisble(bool orbitVisisble);
double getRadius();
GLVector getCenter();
QString getName();
double calculateDistance(HeavenlyBody3d *heavenlyBody3d);
protected:
GLColorRGBA color;
float x;
float y;
GLVector heavenlyBodyCenter;
bool isOrbitVisisble();
private:
GLdouble radius;
bool orbitVisisble;
QString name;
};
#endif // HEAVENLYBODY3D_H
| 25.666667 | 82 | 0.737554 | [
"model"
] |
07885aab4109053a0db3953549e9ed3888419778 | 39,673 | h | C | qtensor/data.h | jwinkle/eQ | dbc94575fad9c8e4f1feaddc6a1c1c9067967ed2 | [
"MIT"
] | null | null | null | qtensor/data.h | jwinkle/eQ | dbc94575fad9c8e4f1feaddc6a1c1c9067967ed2 | [
"MIT"
] | null | null | null | qtensor/data.h | jwinkle/eQ | dbc94575fad9c8e4f1feaddc6a1c1c9067967ed2 | [
"MIT"
] | 1 | 2021-08-25T15:04:47.000Z | 2021-08-25T15:04:47.000Z | // This code conforms with the UFC specification version 2018.1.0
// and was automatically generated by FFC version 2018.1.0.
//
// This code was generated with the option '-l dolfin' and
// contains DOLFIN-specific wrappers that depend on DOLFIN.
//
// This code was generated with the following parameters:
//
// add_tabulate_tensor_timing: False
// convert_exceptions_to_warnings: False
// cpp_optimize: True
// cpp_optimize_flags: '-O2'
// epsilon: 1e-14
// error_control: False
// external_include_dirs: ''
// external_includes: ''
// external_libraries: ''
// external_library_dirs: ''
// form_postfix: True
// format: 'dolfin'
// generate_dummy_tabulate_tensor: False
// max_signature_length: 0
// optimize: True
// precision: None
// quadrature_degree: None
// quadrature_rule: None
// representation: 'auto'
// split: False
#ifndef __DATA_H
#define __DATA_H
#include <algorithm>
#include <iostream>
#include <stdexcept>
#include <ufc.h>
class data_finite_element_0: public ufc::finite_element
{
public:
data_finite_element_0() : ufc::finite_element()
{
// Do nothing
}
~data_finite_element_0() override
{
// Do nothing
}
const char * signature() const final override
{
return "FiniteElement('Lagrange', triangle, 1)";
}
ufc::shape cell_shape() const final override
{
return ufc::shape::triangle;
}
std::size_t topological_dimension() const final override
{
return 2;
}
std::size_t geometric_dimension() const final override
{
return 2;
}
std::size_t space_dimension() const final override
{
return 3;
}
std::size_t value_rank() const final override
{
return 0;
}
std::size_t value_dimension(std::size_t i) const final override
{
return 1;
}
std::size_t value_size() const final override
{
return 1;
}
std::size_t reference_value_rank() const final override
{
return 0;
}
std::size_t reference_value_dimension(std::size_t i) const final override
{
return 1;
}
std::size_t reference_value_size() const final override
{
return 1;
}
std::size_t degree() const final override
{
return 1;
}
const char * family() const final override
{
return "Lagrange";
}
void evaluate_reference_basis(double * reference_values,
std::size_t num_points,
const double * X) const final override
{
static const double coefficients0[1][3] = { { 0.4714045207910317, -0.2886751345948129, -0.16666666666666666 } };
static const double coefficients1[1][3] = { { 0.4714045207910317, 0.2886751345948129, -0.16666666666666666 } };
static const double coefficients2[1][3] = { { 0.4714045207910316, 0.0, 0.3333333333333333 } };
for (std::size_t k = 0; k < num_points * 3; ++k)
reference_values[k] = 0.0;
for (std::size_t ip = 0; ip < num_points; ++ip)
{
// Map from UFC reference coordinate X to FIAT reference coordinate Y
const double Y[2] = { 2.0 * X[ip * 2] - 1.0, 2.0 * X[ip * 2 + 1] - 1.0 };
// Compute basisvalues for each relevant embedded degree
double basisvalues1[3] = {};
basisvalues1[0] = 1.0;
const double tmp1_1 = (1.0 + 2.0 * Y[0] + Y[1]) / 2.0;
basisvalues1[1] = tmp1_1;
basisvalues1[2] = (0.5 + 1.5 * Y[1]) * basisvalues1[0];
basisvalues1[0] *= std::sqrt(0.5);
basisvalues1[2] *= std::sqrt(1.0);
basisvalues1[1] *= std::sqrt(3.0);
// Accumulate products of coefficients and basisvalues
for (std::size_t r = 0; r < 3; ++r)
reference_values[3 * ip] += coefficients0[0][r] * basisvalues1[r];
for (std::size_t r = 0; r < 3; ++r)
reference_values[3 * ip + 1] += coefficients1[0][r] * basisvalues1[r];
for (std::size_t r = 0; r < 3; ++r)
reference_values[3 * ip + 2] += coefficients2[0][r] * basisvalues1[r];
}
}
void evaluate_reference_basis_derivatives(double * reference_values,
std::size_t order,
std::size_t num_points,
const double * X) const final override
{
if (order == 0)
{
evaluate_reference_basis(reference_values, num_points, X);
return;
}
const std::size_t num_derivatives = std::pow(2, order);
std::fill_n(reference_values, num_points * 3 * num_derivatives, 0.0);
if (order > 1)
return;
// Tables of derivatives of the polynomial base (transpose).
alignas(32) static const double dmats0[2][3][3] =
{ { { 0.0, 0.0, 0.0 },
{ 4.8989794855663495, 0.0, 0.0 },
{ 0.0, 0.0, 0.0 } },
{ { 0.0, 0.0, 0.0 },
{ 2.449489742783182, 0.0, 0.0 },
{ 4.242640687119285, 0.0, 0.0 } } };
static const double coefficients0[1][3] = { { 0.4714045207910317, -0.2886751345948129, -0.16666666666666666 } };
static const double coefficients1[1][3] = { { 0.4714045207910317, 0.2886751345948129, -0.16666666666666666 } };
static const double coefficients2[1][3] = { { 0.4714045207910316, 0.0, 0.3333333333333333 } };
const std::size_t reference_offset[3] = {};
const std::size_t num_components[3] = { 1, 1, 1 };
// Precomputed combinations
const std::size_t combinations[1][2][1] =
{ { { 0 },
{ 1 } } };
for (std::size_t ip = 0; ip < num_points; ++ip)
{
// Map from UFC reference coordinate X to FIAT reference coordinate Y
const double Y[2] = { 2.0 * X[ip * 2] - 1.0, 2.0 * X[ip * 2 + 1] - 1.0 };
// Compute basisvalues for each relevant embedded degree
double basisvalues1[3] = {};
basisvalues1[0] = 1.0;
const double tmp1_1 = (1.0 + 2.0 * Y[0] + Y[1]) / 2.0;
basisvalues1[1] = tmp1_1;
basisvalues1[2] = (0.5 + 1.5 * Y[1]) * basisvalues1[0];
basisvalues1[0] *= std::sqrt(0.5);
basisvalues1[2] *= std::sqrt(1.0);
basisvalues1[1] *= std::sqrt(3.0);
// Loop over all dofs
for (std::size_t i = 0; i < 3; ++i)
{
double derivatives[2] = {};
switch (i)
{
case 0:
// Compute reference derivatives for dof 0.
for (std::size_t r = 0; r < num_derivatives; ++r)
{
double aux[3] = {};
// Declare derivative matrix (of polynomial basis).
double dmats[3][3] = {};
// Initialize dmats.
std::size_t comb = combinations[order - 1][r][0];
std::copy_n(&dmats0[comb][0][0], 9, &dmats[0][0]);
// Looping derivative order to generate dmats.
for (std::size_t s = 1; s < order; ++s)
{
// Store previous dmats matrix.
double dmats_old[3][3];
std::copy_n(&dmats[0][0], 9, &dmats_old[0][0]);
// Resetting dmats.
std::fill_n(&dmats[0][0], 9, 0.0);
// Update dmats using an inner product.
comb = combinations[order - 1][r][s];
for (std::size_t t = 0; t < 3; ++t)
for (std::size_t u = 0; u < 3; ++u)
for (std::size_t tu = 0; tu < 3; ++tu)
dmats[t][u] += dmats0[comb][t][tu] * dmats_old[tu][u];
}
for (std::size_t s = 0; s < 3; ++s)
for (std::size_t t = 0; t < 3; ++t)
aux[s] += dmats[s][t] * basisvalues1[t];
derivatives[r] = 0.0;
for (std::size_t s = 0; s < 3; ++s)
derivatives[r] += coefficients0[0][s] * aux[s];
}
break;
case 1:
// Compute reference derivatives for dof 1.
for (std::size_t r = 0; r < num_derivatives; ++r)
{
double aux[3] = {};
// Declare derivative matrix (of polynomial basis).
double dmats[3][3] = {};
// Initialize dmats.
std::size_t comb = combinations[order - 1][r][0];
std::copy_n(&dmats0[comb][0][0], 9, &dmats[0][0]);
// Looping derivative order to generate dmats.
for (std::size_t s = 1; s < order; ++s)
{
// Store previous dmats matrix.
double dmats_old[3][3];
std::copy_n(&dmats[0][0], 9, &dmats_old[0][0]);
// Resetting dmats.
std::fill_n(&dmats[0][0], 9, 0.0);
// Update dmats using an inner product.
comb = combinations[order - 1][r][s];
for (std::size_t t = 0; t < 3; ++t)
for (std::size_t u = 0; u < 3; ++u)
for (std::size_t tu = 0; tu < 3; ++tu)
dmats[t][u] += dmats0[comb][t][tu] * dmats_old[tu][u];
}
for (std::size_t s = 0; s < 3; ++s)
for (std::size_t t = 0; t < 3; ++t)
aux[s] += dmats[s][t] * basisvalues1[t];
derivatives[r] = 0.0;
for (std::size_t s = 0; s < 3; ++s)
derivatives[r] += coefficients1[0][s] * aux[s];
}
break;
case 2:
// Compute reference derivatives for dof 2.
for (std::size_t r = 0; r < num_derivatives; ++r)
{
double aux[3] = {};
// Declare derivative matrix (of polynomial basis).
double dmats[3][3] = {};
// Initialize dmats.
std::size_t comb = combinations[order - 1][r][0];
std::copy_n(&dmats0[comb][0][0], 9, &dmats[0][0]);
// Looping derivative order to generate dmats.
for (std::size_t s = 1; s < order; ++s)
{
// Store previous dmats matrix.
double dmats_old[3][3];
std::copy_n(&dmats[0][0], 9, &dmats_old[0][0]);
// Resetting dmats.
std::fill_n(&dmats[0][0], 9, 0.0);
// Update dmats using an inner product.
comb = combinations[order - 1][r][s];
for (std::size_t t = 0; t < 3; ++t)
for (std::size_t u = 0; u < 3; ++u)
for (std::size_t tu = 0; tu < 3; ++tu)
dmats[t][u] += dmats0[comb][t][tu] * dmats_old[tu][u];
}
for (std::size_t s = 0; s < 3; ++s)
for (std::size_t t = 0; t < 3; ++t)
aux[s] += dmats[s][t] * basisvalues1[t];
derivatives[r] = 0.0;
for (std::size_t s = 0; s < 3; ++s)
derivatives[r] += coefficients2[0][s] * aux[s];
}
break;
}
for (std::size_t r = 0; r < num_derivatives; ++r)
for (std::size_t c = 0; c < num_components[i]; ++c)
reference_values[3 * num_derivatives * ip + num_derivatives * i + r + (reference_offset[i] + c)] = derivatives[num_derivatives * c + r];
}
}
}
void transform_reference_basis_derivatives(double * values,
std::size_t order,
std::size_t num_points,
const double * reference_values,
const double * X,
const double * J,
const double * detJ,
const double * K,
int cell_orientation) const final override
{
const std::size_t num_derivatives = std::pow(2, order);
// Precomputed combinations
const std::size_t combinations[1][2][1] =
{ { { 0 },
{ 1 } } };
std::fill_n(values, num_points * 3 * num_derivatives, 0.0);
const std::size_t reference_offsets[3] = {};
const std::size_t physical_offsets[3] = {};
for (std::size_t ip = 0; ip < num_points; ++ip)
{
double transform[2][2];
for (std::size_t r = 0; r < num_derivatives; ++r)
for (std::size_t s = 0; s < num_derivatives; ++s)
transform[r][s] = 1.0;
for (std::size_t r = 0; r < num_derivatives; ++r)
for (std::size_t s = 0; s < num_derivatives; ++s)
for (std::size_t k = 0; k < order; ++k)
transform[r][s] *= K[2 * 2 * ip + 2 * combinations[order - 1][s][k] + combinations[order - 1][r][k]];
for (std::size_t d = 0; d < 3; ++d)
{
for (std::size_t s = 0; s < num_derivatives; ++s)
{
for (std::size_t i = 0; i < 1; ++i)
{
// Using affine transform to map values back to the physical element.
const double mapped_value = reference_values[3 * num_derivatives * ip + num_derivatives * d + s + reference_offsets[d]];
// Mapping derivatives back to the physical element
for (std::size_t r = 0; r < num_derivatives; ++r)
values[3 * num_derivatives * ip + num_derivatives * d + r + (physical_offsets[d] + i)] += transform[r][s] * mapped_value;
}
}
}
}
}
void evaluate_basis(std::size_t i,
double * values,
const double * x,
const double * coordinate_dofs,
int cell_orientation,
const ufc::coordinate_mapping * cm=nullptr
) const final override
{
double X[2] = {};
double J[4];
double detJ;
double K[4];
if (cm)
{
cm->compute_reference_geometry(X, J, &detJ, K, 1, x, coordinate_dofs, cell_orientation);
}
else
{
compute_jacobian_triangle_2d(J, coordinate_dofs);
compute_jacobian_inverse_triangle_2d(K, detJ, J);
// Compute constants
const double C0 = coordinate_dofs[2] + coordinate_dofs[4];
const double C1 = coordinate_dofs[3] + coordinate_dofs[5];
// Get coordinates and map to the reference (FIAT) element
double Y[2] = { (J[1] * (C1 - 2.0 * x[1]) + J[3] * (2.0 * x[0] - C0)) / detJ, (J[0] * (2.0 * x[1] - C1) + J[2] * (C0 - 2.0 * x[0])) / detJ };
// Map to FFC reference coordinate
for (std::size_t k = 0; k < 2; ++k)
X[k] = (Y[k] + 1.0) / 2.0;
}
// Evaluate basis on reference element
double ref_values[3];
evaluate_reference_basis(ref_values, 1, X);
// Push forward
double physical_values[3];
transform_reference_basis_derivatives(physical_values, 0, 1, ref_values, X, J, &detJ, K, cell_orientation);
for (std::size_t k = 0; k < 1; ++k)
values[k] = physical_values[i + k];
}
void evaluate_basis_all(double * values,
const double * x,
const double * coordinate_dofs,
int cell_orientation,
const ufc::coordinate_mapping * cm=nullptr
) const final override
{
// Helper variable to hold value of a single dof.
double dof_values = 0.0;
// Loop dofs and call evaluate_basis
for (std::size_t r = 0; r < 3; ++r)
{
evaluate_basis(r, &dof_values, x, coordinate_dofs, cell_orientation);
values[r] = dof_values;
}
}
void evaluate_basis_derivatives(std::size_t i,
std::size_t n,
double * values,
const double * x,
const double * coordinate_dofs,
int cell_orientation,
const ufc::coordinate_mapping * cm=nullptr
) const final override
{
std::size_t num_derivatives = std::pow(2, n);
std::fill_n(values, num_derivatives, 0.0);
// Call evaluate_basis_all if order of derivatives is equal to zero.
if (n == 0)
{
evaluate_basis(i, values, x, coordinate_dofs, cell_orientation);
return;
}
// If order of derivatives is greater than the maximum polynomial degree, return zeros.
if (n > 1)
return;
// Compute Jacobian
double J[4];
compute_jacobian_triangle_2d(J, coordinate_dofs);
// Compute Inverse Jacobian and determinant
double K[4];
double detJ;
compute_jacobian_inverse_triangle_2d(K, detJ, J);
// Compute constants
const double C0 = coordinate_dofs[2] + coordinate_dofs[4];
const double C1 = coordinate_dofs[3] + coordinate_dofs[5];
// Get coordinates and map to the reference (FIAT) element
double Y[2] = { (J[1] * (C1 - 2.0 * x[1]) + J[3] * (2.0 * x[0] - C0)) / detJ, (J[0] * (2.0 * x[1] - C1) + J[2] * (C0 - 2.0 * x[0])) / detJ };
// Precomputed combinations
const std::size_t combinations[1][2][1] =
{ { { 0 },
{ 1 } } };
// Declare transformation matrix
double transform[2][2] =
{ { 1.0, 1.0 },
{ 1.0, 1.0 } };
// Construct transformation matrix
for (std::size_t row = 0; row < num_derivatives; ++row)
for (std::size_t col = 0; col < num_derivatives; ++col)
for (std::size_t k = 0; k < n; ++k)
transform[row][col] *= K[2 * combinations[n - 1][col][k] + combinations[n - 1][row][k]];
switch (i)
{
case 0:
{
double basisvalues[3] = {};
basisvalues[0] = 1.0;
const double tmp1_1 = (1.0 + 2.0 * Y[0] + Y[1]) / 2.0;
basisvalues[1] = tmp1_1;
basisvalues[2] = (0.5 + 1.5 * Y[1]) * basisvalues[0];
basisvalues[0] *= std::sqrt(0.5);
basisvalues[2] *= std::sqrt(1.0);
basisvalues[1] *= std::sqrt(3.0);
// Table(s) of coefficients
static const double coefficients0[3] = { 0.4714045207910317, -0.2886751345948129, -0.16666666666666666 };
// Tables of derivatives of the polynomial base (transpose).
static const double dmats0[3][3] =
{ { 0.0, 0.0, 0.0 },
{ 4.8989794855663495, 0.0, 0.0 },
{ 0.0, 0.0, 0.0 } };
static const double dmats1[3][3] =
{ { 0.0, 0.0, 0.0 },
{ 2.449489742783182, 0.0, 0.0 },
{ 4.242640687119285, 0.0, 0.0 } };
// Compute reference derivatives.
// Declare array of derivatives on FIAT element.
double derivatives[2] = {};
// Declare derivative matrix (of polynomial basis).
double dmats[3][3] =
{ { 1.0, 0.0, 0.0 },
{ 0.0, 1.0, 0.0 },
{ 0.0, 0.0, 1.0 } };
// Declare (auxiliary) derivative matrix (of polynomial basis).
double dmats_old[3][3] =
{ { 1.0, 0.0, 0.0 },
{ 0.0, 1.0, 0.0 },
{ 0.0, 0.0, 1.0 } };
// Loop possible derivatives.
for (std::size_t r = 0; r < num_derivatives; ++r)
{
// Reset dmats to identity
std::fill_n(&dmats[0][0], 9, 0.0);
for (std::size_t t = 0; t < 3; ++t)
dmats[t][t] = 1.0;
// Looping derivative order to generate dmats.
for (std::size_t s = 0; s < n; ++s)
{
std::copy_n(&dmats[0][0], 9, &dmats_old[0][0]);
std::fill_n(&dmats[0][0], 9, 0.0);
// Update dmats using an inner product.
// _dmats_product(shape_dmats, comb[r][s], 0)
if (combinations[n - 1][r][s] == 0)
{
for (std::size_t t = 0; t < 3; ++t)
for (std::size_t u = 0; u < 3; ++u)
for (std::size_t tu = 0; tu < 3; ++tu)
dmats[t][u] += dmats_old[tu][u] * dmats0[t][tu];
}
// _dmats_product(shape_dmats, comb[r][s], 1)
if (combinations[n - 1][r][s] == 1)
{
for (std::size_t t = 0; t < 3; ++t)
for (std::size_t u = 0; u < 3; ++u)
for (std::size_t tu = 0; tu < 3; ++tu)
dmats[t][u] += dmats_old[tu][u] * dmats1[t][tu];
}
}
for (std::size_t s = 0; s < 3; ++s)
for (std::size_t t = 0; t < 3; ++t)
derivatives[r] += coefficients0[s] * dmats[s][t] * basisvalues[t];
}
// Transform derivatives back to physical element
for (std::size_t r = 0; r < num_derivatives; ++r)
for (std::size_t s = 0; s < num_derivatives; ++s)
values[r] += transform[r][s] * derivatives[s];
}
break;
case 1:
{
double basisvalues[3] = {};
basisvalues[0] = 1.0;
const double tmp1_1 = (1.0 + 2.0 * Y[0] + Y[1]) / 2.0;
basisvalues[1] = tmp1_1;
basisvalues[2] = (0.5 + 1.5 * Y[1]) * basisvalues[0];
basisvalues[0] *= std::sqrt(0.5);
basisvalues[2] *= std::sqrt(1.0);
basisvalues[1] *= std::sqrt(3.0);
// Table(s) of coefficients
static const double coefficients0[3] = { 0.4714045207910317, 0.2886751345948129, -0.16666666666666666 };
// Tables of derivatives of the polynomial base (transpose).
static const double dmats0[3][3] =
{ { 0.0, 0.0, 0.0 },
{ 4.8989794855663495, 0.0, 0.0 },
{ 0.0, 0.0, 0.0 } };
static const double dmats1[3][3] =
{ { 0.0, 0.0, 0.0 },
{ 2.449489742783182, 0.0, 0.0 },
{ 4.242640687119285, 0.0, 0.0 } };
// Compute reference derivatives.
// Declare array of derivatives on FIAT element.
double derivatives[2] = {};
// Declare derivative matrix (of polynomial basis).
double dmats[3][3] =
{ { 1.0, 0.0, 0.0 },
{ 0.0, 1.0, 0.0 },
{ 0.0, 0.0, 1.0 } };
// Declare (auxiliary) derivative matrix (of polynomial basis).
double dmats_old[3][3] =
{ { 1.0, 0.0, 0.0 },
{ 0.0, 1.0, 0.0 },
{ 0.0, 0.0, 1.0 } };
// Loop possible derivatives.
for (std::size_t r = 0; r < num_derivatives; ++r)
{
// Reset dmats to identity
std::fill_n(&dmats[0][0], 9, 0.0);
for (std::size_t t = 0; t < 3; ++t)
dmats[t][t] = 1.0;
// Looping derivative order to generate dmats.
for (std::size_t s = 0; s < n; ++s)
{
std::copy_n(&dmats[0][0], 9, &dmats_old[0][0]);
std::fill_n(&dmats[0][0], 9, 0.0);
// Update dmats using an inner product.
// _dmats_product(shape_dmats, comb[r][s], 0)
if (combinations[n - 1][r][s] == 0)
{
for (std::size_t t = 0; t < 3; ++t)
for (std::size_t u = 0; u < 3; ++u)
for (std::size_t tu = 0; tu < 3; ++tu)
dmats[t][u] += dmats_old[tu][u] * dmats0[t][tu];
}
// _dmats_product(shape_dmats, comb[r][s], 1)
if (combinations[n - 1][r][s] == 1)
{
for (std::size_t t = 0; t < 3; ++t)
for (std::size_t u = 0; u < 3; ++u)
for (std::size_t tu = 0; tu < 3; ++tu)
dmats[t][u] += dmats_old[tu][u] * dmats1[t][tu];
}
}
for (std::size_t s = 0; s < 3; ++s)
for (std::size_t t = 0; t < 3; ++t)
derivatives[r] += coefficients0[s] * dmats[s][t] * basisvalues[t];
}
// Transform derivatives back to physical element
for (std::size_t r = 0; r < num_derivatives; ++r)
for (std::size_t s = 0; s < num_derivatives; ++s)
values[r] += transform[r][s] * derivatives[s];
}
break;
case 2:
{
double basisvalues[3] = {};
basisvalues[0] = 1.0;
const double tmp1_1 = (1.0 + 2.0 * Y[0] + Y[1]) / 2.0;
basisvalues[1] = tmp1_1;
basisvalues[2] = (0.5 + 1.5 * Y[1]) * basisvalues[0];
basisvalues[0] *= std::sqrt(0.5);
basisvalues[2] *= std::sqrt(1.0);
basisvalues[1] *= std::sqrt(3.0);
// Table(s) of coefficients
static const double coefficients0[3] = { 0.4714045207910316, 0.0, 0.3333333333333333 };
// Tables of derivatives of the polynomial base (transpose).
static const double dmats0[3][3] =
{ { 0.0, 0.0, 0.0 },
{ 4.8989794855663495, 0.0, 0.0 },
{ 0.0, 0.0, 0.0 } };
static const double dmats1[3][3] =
{ { 0.0, 0.0, 0.0 },
{ 2.449489742783182, 0.0, 0.0 },
{ 4.242640687119285, 0.0, 0.0 } };
// Compute reference derivatives.
// Declare array of derivatives on FIAT element.
double derivatives[2] = {};
// Declare derivative matrix (of polynomial basis).
double dmats[3][3] =
{ { 1.0, 0.0, 0.0 },
{ 0.0, 1.0, 0.0 },
{ 0.0, 0.0, 1.0 } };
// Declare (auxiliary) derivative matrix (of polynomial basis).
double dmats_old[3][3] =
{ { 1.0, 0.0, 0.0 },
{ 0.0, 1.0, 0.0 },
{ 0.0, 0.0, 1.0 } };
// Loop possible derivatives.
for (std::size_t r = 0; r < num_derivatives; ++r)
{
// Reset dmats to identity
std::fill_n(&dmats[0][0], 9, 0.0);
for (std::size_t t = 0; t < 3; ++t)
dmats[t][t] = 1.0;
// Looping derivative order to generate dmats.
for (std::size_t s = 0; s < n; ++s)
{
std::copy_n(&dmats[0][0], 9, &dmats_old[0][0]);
std::fill_n(&dmats[0][0], 9, 0.0);
// Update dmats using an inner product.
// _dmats_product(shape_dmats, comb[r][s], 0)
if (combinations[n - 1][r][s] == 0)
{
for (std::size_t t = 0; t < 3; ++t)
for (std::size_t u = 0; u < 3; ++u)
for (std::size_t tu = 0; tu < 3; ++tu)
dmats[t][u] += dmats_old[tu][u] * dmats0[t][tu];
}
// _dmats_product(shape_dmats, comb[r][s], 1)
if (combinations[n - 1][r][s] == 1)
{
for (std::size_t t = 0; t < 3; ++t)
for (std::size_t u = 0; u < 3; ++u)
for (std::size_t tu = 0; tu < 3; ++tu)
dmats[t][u] += dmats_old[tu][u] * dmats1[t][tu];
}
}
for (std::size_t s = 0; s < 3; ++s)
for (std::size_t t = 0; t < 3; ++t)
derivatives[r] += coefficients0[s] * dmats[s][t] * basisvalues[t];
}
// Transform derivatives back to physical element
for (std::size_t r = 0; r < num_derivatives; ++r)
for (std::size_t s = 0; s < num_derivatives; ++s)
values[r] += transform[r][s] * derivatives[s];
}
break;
}
}
void evaluate_basis_derivatives_all(std::size_t n,
double * values,
const double * x,
const double * coordinate_dofs,
int cell_orientation,
const ufc::coordinate_mapping * cm=nullptr
) const final override
{
// Call evaluate_basis_all if order of derivatives is equal to zero.
if (n == 0)
{
evaluate_basis_all(values, x, coordinate_dofs, cell_orientation);
return;
}
unsigned int num_derivatives = std::pow(2, n);
// Set values equal to zero.
std::fill_n(values, num_derivatives * 3, 0.0);
// If order of derivatives is greater than the maximum polynomial degree, return zeros.
if (n > 1)
return;
// Helper variable to hold values of a single dof.
double dof_values[2] = {};
// Loop dofs and call evaluate_basis_derivatives.
for (std::size_t r = 0; r < 3; ++r)
{
evaluate_basis_derivatives(r, n, dof_values, x, coordinate_dofs, cell_orientation);
for (std::size_t s = 0; s < num_derivatives; ++s)
values[num_derivatives * r + s] = dof_values[s];
}
}
double evaluate_dof(std::size_t i,
const ufc::function& f,
const double * coordinate_dofs,
int cell_orientation,
const ufc::cell& c,
const ufc::coordinate_mapping * cm=nullptr
) const final override
{
// Declare variables for result of evaluation
double vals[1];
// Declare variable for physical coordinates
double y[2];
switch (i)
{
case 0:
{
y[0] = coordinate_dofs[0];
y[1] = coordinate_dofs[1];
f.evaluate(vals, y, c);
return vals[0];
}
break;
case 1:
{
y[0] = coordinate_dofs[2];
y[1] = coordinate_dofs[3];
f.evaluate(vals, y, c);
return vals[0];
}
break;
case 2:
{
y[0] = coordinate_dofs[4];
y[1] = coordinate_dofs[5];
f.evaluate(vals, y, c);
return vals[0];
}
break;
}
return 0.0;
}
void evaluate_dofs(double * values,
const ufc::function& f,
const double * coordinate_dofs,
int cell_orientation,
const ufc::cell& c,
const ufc::coordinate_mapping * cm=nullptr
) const final override
{
// Declare variables for result of evaluation
double vals[1];
// Declare variable for physical coordinates
double y[2];
y[0] = coordinate_dofs[0];
y[1] = coordinate_dofs[1];
f.evaluate(vals, y, c);
values[0] = vals[0];
y[0] = coordinate_dofs[2];
y[1] = coordinate_dofs[3];
f.evaluate(vals, y, c);
values[1] = vals[0];
y[0] = coordinate_dofs[4];
y[1] = coordinate_dofs[5];
f.evaluate(vals, y, c);
values[2] = vals[0];
}
void interpolate_vertex_values(double * vertex_values,
const double * dof_values,
const double * coordinate_dofs,
int cell_orientation,
const ufc::coordinate_mapping * cm=nullptr
) const final override
{
// Evaluate function and change variables
vertex_values[0] = dof_values[0];
vertex_values[1] = dof_values[1];
vertex_values[2] = dof_values[2];
}
void tabulate_dof_coordinates(double * dof_coordinates,
const double * coordinate_dofs,
const ufc::coordinate_mapping * cm=nullptr
) const final override
{
dof_coordinates[0] = coordinate_dofs[0];
dof_coordinates[1] = coordinate_dofs[1];
dof_coordinates[2] = coordinate_dofs[2];
dof_coordinates[2 + 1] = coordinate_dofs[3];
dof_coordinates[2 * 2] = coordinate_dofs[4];
dof_coordinates[2 * 2 + 1] = coordinate_dofs[5];
}
void tabulate_reference_dof_coordinates(double * reference_dof_coordinates) const final override
{
static const double dof_X[6] = { 0.0, 0.0, 1.0, 0.0, 0.0, 1.0 };
std::copy_n(dof_X, 6, reference_dof_coordinates);
}
std::size_t num_sub_elements() const final override
{
return 0;
}
ufc::finite_element * create_sub_element(std::size_t i) const final override
{
return nullptr;
}
ufc::finite_element * create() const final override
{
return new data_finite_element_0();
}
};
class data_dofmap_0: public ufc::dofmap
{
public:
data_dofmap_0() : ufc::dofmap()
{
// Do nothing
}
~data_dofmap_0() override
{
// Do nothing
}
const char * signature() const final override
{
return "FFC dofmap for FiniteElement('Lagrange', triangle, 1)";
}
bool needs_mesh_entities(std::size_t d) const final override
{
static const bool return_values[3] = { true, false, false };
if (d >= 3)
return false;
return return_values[d];
}
std::size_t topological_dimension() const final override
{
return 2;
}
std::size_t global_dimension(const std::vector<std::size_t>&
num_global_entities) const final override
{
return num_global_entities[0];
}
std::size_t num_global_support_dofs() const final override
{
return 0;
}
std::size_t num_element_support_dofs() const final override
{
return 3;
}
std::size_t num_element_dofs() const final override
{
return 3;
}
std::size_t num_facet_dofs() const final override
{
return 2;
}
std::size_t num_entity_dofs(std::size_t d) const final override
{
static const std::size_t return_values[3] = { 1, 0, 0 };
if (d >= 3)
return 0;
return return_values[d];
}
std::size_t num_entity_closure_dofs(std::size_t d) const final override
{
static const std::size_t return_values[3] = { 1, 2, 3 };
if (d >= 3)
return 0;
return return_values[d];
}
void tabulate_dofs(std::size_t * dofs,
const std::vector<std::size_t>& num_global_entities,
const std::vector<std::vector<std::size_t>>& entity_indices) const final override
{
dofs[0] = entity_indices[0][0];
dofs[1] = entity_indices[0][1];
dofs[2] = entity_indices[0][2];
}
void tabulate_facet_dofs(std::size_t * dofs,
std::size_t facet) const final override
{
switch (facet)
{
case 0:
dofs[0] = 1;
dofs[1] = 2;
break;
case 1:
dofs[0] = 0;
dofs[1] = 2;
break;
case 2:
dofs[0] = 0;
dofs[1] = 1;
break;
}
}
void tabulate_entity_dofs(std::size_t * dofs,
std::size_t d, std::size_t i) const final override
{
switch (d)
{
case 0:
switch (i)
{
case 0:
dofs[0] = 0;
break;
case 1:
dofs[0] = 1;
break;
case 2:
dofs[0] = 2;
break;
}
break;
}
}
void tabulate_entity_closure_dofs(std::size_t * dofs,
std::size_t d, std::size_t i) const final override
{
switch (d)
{
case 0:
switch (i)
{
case 0:
dofs[0] = 0;
break;
case 1:
dofs[0] = 1;
break;
case 2:
dofs[0] = 2;
break;
}
break;
case 1:
switch (i)
{
case 0:
dofs[0] = 1;
dofs[1] = 2;
break;
case 1:
dofs[0] = 0;
dofs[1] = 2;
break;
case 2:
dofs[0] = 0;
dofs[1] = 1;
break;
}
break;
case 2:
switch (i)
{
case 0:
dofs[0] = 0;
dofs[1] = 1;
dofs[2] = 2;
break;
}
break;
}
}
std::size_t num_sub_dofmaps() const final override
{
return 0;
}
ufc::dofmap * create_sub_dofmap(std::size_t i) const final override
{
return nullptr;
}
ufc::dofmap * create() const final override
{
return new data_dofmap_0();
}
};
// DOLFIN wrappers
// Standard library includes
#include <string>
// DOLFIN includes
#include <dolfin/common/NoDeleter.h>
#include <dolfin/mesh/Mesh.h>
#include <dolfin/mesh/MultiMesh.h>
#include <dolfin/fem/FiniteElement.h>
#include <dolfin/fem/DofMap.h>
#include <dolfin/fem/Form.h>
#include <dolfin/fem/MultiMeshForm.h>
#include <dolfin/function/FunctionSpace.h>
#include <dolfin/function/MultiMeshFunctionSpace.h>
#include <dolfin/function/GenericFunction.h>
#include <dolfin/function/CoefficientAssigner.h>
#include <dolfin/function/MultiMeshCoefficientAssigner.h>
#include <dolfin/adaptivity/ErrorControl.h>
#include <dolfin/adaptivity/GoalFunctional.h>
#include <dolfin/la/GenericVector.h>
namespace data
{
class FunctionSpace: public dolfin::FunctionSpace
{
public:
// Constructor for standard function space
FunctionSpace(std::shared_ptr<const dolfin::Mesh> mesh):
dolfin::FunctionSpace(mesh,
std::make_shared<const dolfin::FiniteElement>(std::make_shared<data_finite_element_0>()),
std::make_shared<const dolfin::DofMap>(std::make_shared<data_dofmap_0>(), *mesh))
{
// Do nothing
}
// Constructor for constrained function space
FunctionSpace(std::shared_ptr<const dolfin::Mesh> mesh, std::shared_ptr<const dolfin::SubDomain> constrained_domain):
dolfin::FunctionSpace(mesh,
std::make_shared<const dolfin::FiniteElement>(std::make_shared<data_finite_element_0>()),
std::make_shared<const dolfin::DofMap>(std::make_shared<data_dofmap_0>(), *mesh, constrained_domain))
{
// Do nothing
}
};
}
#endif
| 37.008396 | 156 | 0.478008 | [
"mesh",
"shape",
"vector",
"transform"
] |
078a98988a66ce76b40d9b5e172ac1b1224cc6d6 | 4,570 | h | C | src/base/polynomial.h | chetanskumar1991/colmap | d8d3cfbdef8de706f1501f07ac78068741ad1d89 | [
"BSD-3-Clause"
] | 255 | 2018-12-14T05:59:29.000Z | 2020-11-04T12:15:32.000Z | src/base/polynomial.h | Pascal-So/colmap | 7c82a22a2ac97e54272d54a1c7276cb293bcdd2f | [
"BSD-3-Clause"
] | 35 | 2018-12-25T03:02:48.000Z | 2020-11-19T03:33:25.000Z | src/base/polynomial.h | Pascal-So/colmap | 7c82a22a2ac97e54272d54a1c7276cb293bcdd2f | [
"BSD-3-Clause"
] | 54 | 2018-12-14T06:09:21.000Z | 2020-11-21T08:29:31.000Z | // Copyright (c) 2018, ETH Zurich and UNC Chapel Hill.
// 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 ETH Zurich and UNC Chapel Hill 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 HOLDERS OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Author: Johannes L. Schoenberger (jsch-at-demuc-dot-de)
#ifndef COLMAP_SRC_BASE_POLYNOMIAL_H_
#define COLMAP_SRC_BASE_POLYNOMIAL_H_
#include <Eigen/Core>
namespace colmap {
// All polynomials are assumed to be the form:
//
// sum_{i=0}^N polynomial(i) x^{N-i}.
//
// and are given by a vector of coefficients of size N + 1.
//
// The implementation is based on COLMAP's old polynomial functionality and is
// inspired by Ceres-Solver's/Theia's implementation to support complex
// polynomials. The companion matrix implementation is based on NumPy.
// Evaluate the polynomial for the given coefficients at x using the Horner
// scheme. This function is templated such that the polynomial may be evaluated
// at real and/or imaginary points.
template <typename T>
T EvaluatePolynomial(const Eigen::VectorXd& coeffs, const T& x);
// Find the root of polynomials of the form: a * x + b = 0.
// The real and/or imaginary variable may be NULL if the output is not needed.
bool FindLinearPolynomialRoots(const Eigen::VectorXd& coeffs,
Eigen::VectorXd* real, Eigen::VectorXd* imag);
// Find the roots of polynomials of the form: a * x^2 + b * x + c = 0.
// The real and/or imaginary variable may be NULL if the output is not needed.
bool FindQuadraticPolynomialRoots(const Eigen::VectorXd& coeffs,
Eigen::VectorXd* real, Eigen::VectorXd* imag);
// Find the roots of a polynomial using the Durand-Kerner method, based on:
//
// https://en.wikipedia.org/wiki/Durand%E2%80%93Kerner_method
//
// The Durand-Kerner is comparatively fast but often unstable/inaccurate.
// The real and/or imaginary variable may be NULL if the output is not needed.
bool FindPolynomialRootsDurandKerner(const Eigen::VectorXd& coeffs,
Eigen::VectorXd* real,
Eigen::VectorXd* imag);
// Find the roots of a polynomial using the companion matrix method, based on:
//
// R. A. Horn & C. R. Johnson, Matrix Analysis. Cambridge,
// UK: Cambridge University Press, 1999, pp. 146-7.
//
// Compared to Durand-Kerner, this method is slower but more stable/accurate.
// The real and/or imaginary variable may be NULL if the output is not needed.
bool FindPolynomialRootsCompanionMatrix(const Eigen::VectorXd& coeffs,
Eigen::VectorXd* real,
Eigen::VectorXd* imag);
////////////////////////////////////////////////////////////////////////////////
// Implementation
////////////////////////////////////////////////////////////////////////////////
template <typename T>
T EvaluatePolynomial(const Eigen::VectorXd& coeffs, const T& x) {
T value = 0.0;
for (Eigen::VectorXd::Index i = 0; i < coeffs.size(); ++i) {
value = value * x + coeffs(i);
}
return value;
}
} // namespace colmap
#endif // COLMAP_SRC_BASE_POLYNOMIAL_H_
| 44.803922 | 80 | 0.682276 | [
"vector"
] |
078e70ae67804c22cb7ac097a94b70e761379fc2 | 1,879 | h | C | lib/typelib/TypeDatabase.h | alexanderlinne/TypeART | a83c63b3c82d1e4801c1c4651c9351b311ef1fa6 | [
"BSD-3-Clause"
] | null | null | null | lib/typelib/TypeDatabase.h | alexanderlinne/TypeART | a83c63b3c82d1e4801c1c4651c9351b311ef1fa6 | [
"BSD-3-Clause"
] | null | null | null | lib/typelib/TypeDatabase.h | alexanderlinne/TypeART | a83c63b3c82d1e4801c1c4651c9351b311ef1fa6 | [
"BSD-3-Clause"
] | null | null | null | // TypeART library
//
// Copyright (c) 2017-2022 TypeART Authors
// Distributed under the BSD 3-Clause license.
// (See accompanying file LICENSE.txt or copy at
// https://opensource.org/licenses/BSD-3-Clause)
//
// Project home: https://github.com/tudasc/TypeART
//
// SPDX-License-Identifier: BSD-3-Clause
//
#ifndef TYPEART_TYPEDATABASE_H
#define TYPEART_TYPEDATABASE_H
#include <memory>
#include <string>
#include <system_error>
#include <utility>
#include <vector>
namespace typeart {
enum class StructTypeFlag : int { USER_DEFINED = 1, LLVM_VECTOR = 2 };
struct StructTypeInfo {
int type_id;
std::string name;
size_t extent;
size_t num_members;
std::vector<size_t> offsets;
std::vector<int> member_types;
std::vector<size_t> array_sizes;
StructTypeFlag flag;
};
class TypeDatabase {
public:
virtual void registerStruct(const StructTypeInfo& struct_info) = 0;
[[nodiscard]] virtual bool isUnknown(int type_id) const = 0;
[[nodiscard]] virtual bool isValid(int type_id) const = 0;
[[nodiscard]] virtual bool isReservedType(int type_id) const = 0;
[[nodiscard]] virtual bool isBuiltinType(int type_id) const = 0;
[[nodiscard]] virtual bool isStructType(int type_id) const = 0;
[[nodiscard]] virtual bool isUserDefinedType(int type_id) const = 0;
[[nodiscard]] virtual bool isVectorType(int type_id) const = 0;
[[nodiscard]] virtual const std::string& getTypeName(int type_id) const = 0;
[[nodiscard]] virtual const StructTypeInfo* getStructInfo(int type_id) const = 0;
[[nodiscard]] virtual size_t getTypeSize(int type_id) const = 0;
[[nodiscard]] virtual const std::vector<StructTypeInfo>& getStructList() const = 0;
virtual ~TypeDatabase() = default;
};
std::pair<std::unique_ptr<TypeDatabase>, std::error_code> make_database(const std::string& file);
} // namespace typeart
#endif // TYPEART_TYPEDATABASE_H
| 26.464789 | 97 | 0.73124 | [
"vector"
] |
078f1227fa36d8c16b9cb1a19f7a19a9a35d83e0 | 6,497 | h | C | ios/web/navigation/crw_wk_navigation_handler.h | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 575 | 2015-06-18T23:58:20.000Z | 2022-03-23T09:32:39.000Z | ios/web/navigation/crw_wk_navigation_handler.h | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | ios/web/navigation/crw_wk_navigation_handler.h | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 52 | 2015-07-14T10:40:50.000Z | 2022-03-15T01:11:49.000Z | // Copyright 2019 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 IOS_WEB_NAVIGATION_CRW_WK_NAVIGATION_HANDLER_H_
#define IOS_WEB_NAVIGATION_CRW_WK_NAVIGATION_HANDLER_H_
#import <UIKit/UIKit.h>
#import <WebKit/WebKit.h>
#import <memory>
#import "ios/web/security/cert_verification_error.h"
#import "ios/web/web_state/ui/crw_web_view_handler.h"
#import "ios/web/web_state/ui/crw_web_view_handler_delegate.h"
#include "ui/base/page_transition_types.h"
@class CRWWKNavigationHandler;
@class CRWPendingNavigationInfo;
@class CRWWKNavigationStates;
@class CRWJSInjector;
@class CRWCertVerificationController;
class GURL;
namespace web {
enum class WKNavigationState;
enum class ErrorRetryCommand;
struct Referrer;
class NavigationContextImpl;
class WKBackForwardListItemHolder;
}
// CRWWKNavigationHandler uses this protocol to interact with its owner.
@protocol CRWWKNavigationHandlerDelegate <CRWWebViewHandlerDelegate>
// Returns associated certificate verificatio controller.
- (CRWCertVerificationController*)
certVerificationControllerForNavigationHandler:
(CRWWKNavigationHandler*)navigationHandler;
// Returns the associated js injector.
- (CRWJSInjector*)JSInjectorForNavigationHandler:
(CRWWKNavigationHandler*)navigationHandler;
// Sets document URL to newURL, and updates any relevant state information.
- (void)navigationHandler:(CRWWKNavigationHandler*)navigationHandler
setDocumentURL:(const GURL&)newURL
context:(web::NavigationContextImpl*)context;
// Sets up WebUI for URL.
- (void)navigationHandler:(CRWWKNavigationHandler*)navigationHandler
createWebUIForURL:(const GURL&)URL;
- (std::unique_ptr<web::NavigationContextImpl>)
navigationHandler:(CRWWKNavigationHandler*)navigationHandler
registerLoadRequestForURL:(const GURL&)URL
sameDocumentNavigation:(BOOL)sameDocumentNavigation
hasUserGesture:(BOOL)hasUserGesture
rendererInitiated:(BOOL)renderedInitiated
placeholderNavigation:(BOOL)placeholderNavigation;
// Instructs the delegate to display the webView.
- (void)navigationHandlerDisplayWebView:
(CRWWKNavigationHandler*)navigationHandler;
// Notifies the delegate that the page has actually started loading.
- (void)navigationHandlerDidStartLoading:
(CRWWKNavigationHandler*)navigationHandler;
// Notifies the delegate that web process has crashed.
- (void)navigationHandlerWebProcessDidCrash:
(CRWWKNavigationHandler*)navigationHandler;
// Instructs the delegate to load current URL.
- (void)navigationHandler:(CRWWKNavigationHandler*)navigationHandler
loadCurrentURLWithRendererInitiatedNavigation:(BOOL)rendererInitiated;
// Notifies the delegate that load has completed.
- (void)navigationHandler:(CRWWKNavigationHandler*)navigationHandler
didCompleteLoadWithSuccess:(BOOL)loadSuccess
forContext:(web::NavigationContextImpl*)context;
@end
// Handler class for WKNavigationDelegate, deals with navigation callbacks from
// WKWebView and maintains page loading state.
@interface CRWWKNavigationHandler : CRWWebViewHandler <WKNavigationDelegate>
- (instancetype)init NS_UNAVAILABLE;
- (instancetype)initWithDelegate:(id<CRWWKNavigationHandlerDelegate>)delegate
NS_DESIGNATED_INITIALIZER;
// Indicates if the webview reported a crash.
@property(nonatomic, assign, readonly) BOOL webProcessCrashed;
// Pending information for an in-progress page navigation. The lifetime of
// this object starts at |decidePolicyForNavigationAction| where the info is
// extracted from the request, and ends at either |didCommitNavigation| or
// |didFailProvisionalNavigation|.
@property(nonatomic, strong) CRWPendingNavigationInfo* pendingNavigationInfo;
// Holds all WKNavigation objects and their states which are currently in
// flight.
@property(nonatomic, readonly, strong) CRWWKNavigationStates* navigationStates;
// The current page loading phase.
// TODO(crbug.com/956511): Remove this once refactor is done.
@property(nonatomic, readwrite, assign) web::WKNavigationState navigationState;
// Returns the WKBackForwardlistItemHolder of current navigation item.
@property(nonatomic, readonly, assign)
web::WKBackForwardListItemHolder* currentBackForwardListItemHolder;
// Returns the referrer for the current page.
@property(nonatomic, readonly, assign) web::Referrer currentReferrer;
// Instructs this handler to stop loading.
- (void)stopLoading;
// Informs this handler that any outstanding load operations are cancelled.
- (void)loadCancelled;
// Returns context for pending navigation that has |URL|. null if there is no
// matching pending navigation.
- (web::NavigationContextImpl*)contextForPendingMainFrameNavigationWithURL:
(const GURL&)URL;
// Returns YES if current navigation item is WKNavigationTypeBackForward.
- (BOOL)isCurrentNavigationBackForward;
// Returns YES if the current navigation item corresponds to a web page
// loaded by a POST request.
- (BOOL)isCurrentNavigationItemPOST;
// Sets last committed NavigationItem's title to the given |title|, which can
// not be nil.
- (void)setLastCommittedNavigationItemTitle:(NSString*)title;
// Maps WKNavigationType to ui::PageTransition.
- (ui::PageTransition)pageTransitionFromNavigationType:
(WKNavigationType)navigationType;
// Loads a blank page directly into WKWebView as a placeholder to create a new
// back forward item (f.e. for error page). This page has the URL
// about:blank?for=<encoded original URL>. If |originalContext| is provided,
// reuse it for the placeholder navigation instead of creating a new one.
- (web::NavigationContextImpl*)
loadPlaceholderInWebViewForURL:(const GURL&)originalURL
rendererInitiated:(BOOL)rendererInitiated
forContext:(std::unique_ptr<web::NavigationContextImpl>)
originalContext;
// Called when the web page has changed document and/or URL, and so the page
// navigation should be reported to the delegate, and internal state updated to
// reflect the fact that the navigation has occurred. |context| contains
// information about the navigation that triggered the document/URL change.
- (void)webPageChangedWithContext:(web::NavigationContextImpl*)context
webView:(WKWebView*)webView;
@end
#endif // IOS_WEB_NAVIGATION_CRW_WK_NAVIGATION_HANDLER_H_
| 40.104938 | 80 | 0.787133 | [
"object"
] |
079e56d06623ddc544127799e6bb63ce97f8baad | 12,032 | h | C | lullaby/systems/transform/transform_system.h | jjzhang166/lullaby | d9b11ea811cb5869b46165b9b9537b6063c6cbae | [
"Apache-2.0"
] | null | null | null | lullaby/systems/transform/transform_system.h | jjzhang166/lullaby | d9b11ea811cb5869b46165b9b9537b6063c6cbae | [
"Apache-2.0"
] | null | null | null | lullaby/systems/transform/transform_system.h | jjzhang166/lullaby | d9b11ea811cb5869b46165b9b9537b6063c6cbae | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2017 Google Inc. 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 LULLABY_SYSTEMS_TRANSFORM_TRANSFORM_SYSTEM_H_
#define LULLABY_SYSTEMS_TRANSFORM_TRANSFORM_SYSTEM_H_
#include "lullaby/modules/ecs/component.h"
#include "lullaby/modules/ecs/system.h"
#include "lullaby/util/bits.h"
#include "lullaby/util/math.h"
#include "mathfu/constants.h"
#include "mathfu/glsl_mappings.h"
namespace lull {
/// The TransformSystem provide Entities with position, rotation, scale and
/// volume (via an AABB). It also allows entities to be attached to each other
/// to create a scene graph hierarchy.
class TransformSystem : public System {
public:
/// TransformFlags are custom flags defined by applications that help group
/// transform components together to do operation on. For example a collision
/// system maybe defined a unique flag for collidables, while a render system
/// may flag renderables. This can be used to pull and operate on all the
/// relevant entities with the flag.
using TransformFlags = uint32_t;
static const TransformFlags kInvalidFlag;
static const TransformFlags kAllFlags;
enum AddChildMode {
kPreserveParentToEntityTransform,
kPreserveWorldToEntityTransform,
};
typedef std::function<mathfu::mat4(const Sqt&, const mathfu::mat4*)>
CalculateWorldFromEntityMatrixFunc;
explicit TransformSystem(Registry* registry);
~TransformSystem() override;
/// Adds a transform to the Entity using the specified ComponentDef.
void Create(Entity e, HashValue type, const Def* def) override;
/// Adds a transform to |e| using |sqt|. If |e| already has a transform, just
/// sets sqt.
void Create(Entity e, const Sqt& sqt);
/// Performs post creation initialization.
void PostCreateInit(Entity e, HashValue type, const Def* def) override;
/// Removes the transform from the Entity.
void Destroy(Entity e) override;
/// Sets the specified transform to be included when calling foreach with the
/// provided flag.
void SetFlag(Entity e, TransformFlags flag);
/// Removes the specified transform from being included when calling foreach
/// with the provided flag.
void ClearFlag(Entity e, TransformFlags flag);
/// Checks whether an entity has a flag.
bool HasFlag(Entity e, TransformFlags flag) const;
/// Sets the Aabb for the specified transform.
void SetAabb(Entity e, Aabb box);
/// Gets the (padded) Aabb for the specified transform.
const Aabb* GetAabb(Entity e) const;
/// Sets the padding for the specified entity. This adds the padding aabb to
/// any Aabbs set to this entity.
void SetAabbPadding(Entity e, const Aabb& padding);
/// Gets the padding for the specified entity.
const Aabb* GetAabbPadding(Entity e) const;
/// Enables an Entity and all its children. OnEnabledEvent will be dispatched
/// when this is called if the entity was previously disabled.
void Enable(Entity e);
/// Disables an Entity and all its children. Disabled entities will not be
/// rendered or collided against, and will not be included in
/// transform_system.ForEach() calls. OnDisabledEvent will be dispatched if
/// the entity was previously enabled.
void Disable(Entity e);
/// Gets the inherited enabled status for an entity. Returns true if no entity
/// is found.
bool IsEnabled(Entity e) const;
/// Gets the local enabled status for an entity. This will only return false
/// if Disable has been called on this specific entity. Returns true if no
/// entity is found.
bool IsLocallyEnabled(Entity e) const;
/// Set the specified entity to the given position, rotation, and scale.
void SetSqt(Entity e, const Sqt& sqt);
/// Gets the SQT for the specified entity (or NULL if it does not have a
/// transform).
const Sqt* GetSqt(Entity e) const;
/// Adds the translation and multiplies the rotation and scale into the
/// existing local_sqt.
void ApplySqt(Entity e, const Sqt& sqt);
/// Sets the local translation of the entity.
void SetLocalTranslation(Entity e, const mathfu::vec3& translation);
/// Gets the local translation of the entity (or (0, 0, 0) if it does not have
/// a transform).
mathfu::vec3 GetLocalTranslation(Entity e) const;
/// Sets the local rotation of the entity.
void SetLocalRotation(Entity e, const mathfu::quat& rotation);
/// Gets the local rotation of the entity (or (0, 0, 0, 0) if it does not have
/// a transform).
mathfu::quat GetLocalRotation(Entity e) const;
/// Sets the local scale of the entity.
void SetLocalScale(Entity e, const mathfu::vec3& scale);
/// Gets the local scale of the entity (or (0, 0, 0) if it does not have a
/// transform).
mathfu::vec3 GetLocalScale(Entity e) const;
/// Sets the world matrix of an entity. Local sqt values will be derived from
/// based on the parent's current world_transform.
void SetWorldFromEntityMatrix(Entity e,
const mathfu::mat4& world_from_entity_mat);
/// Gets the world matrix for the specified entity (or NULL if it does not
/// have a transform).
const mathfu::mat4* GetWorldFromEntityMatrix(Entity e) const;
/// Overrides the default function that calculates the Entity's world matrix.
void SetWorldFromEntityMatrixFunction(
Entity e, CalculateWorldFromEntityMatrixFunc func);
/// Returns the parent Entity, if it exists.
Entity GetParent(Entity child) const;
/// Establish a parent/child relationship between two Entities
void AddChild(
Entity parent, Entity child,
AddChildMode mode = AddChildMode::kPreserveParentToEntityTransform);
/// Create an entity and add it as a child. Shortcut to EntityFactory::Create
/// followed by TransformSystem::AddChild that avoids an extra call to
/// UpdateTransform().
Entity CreateChild(Entity parent, const std::string& name);
/// Populates the specified |child| entity with the component data specified
/// in the blueprint |name| and adds it as a child to the |parent| entity.
/// Shortcut to EntityFactory::Create followed by TransformSystem::AddChild
/// that avoids an extra call to UpdateTransform().
Entity CreateChildWithEntity(Entity parent, Entity child,
const std::string& name);
/// Inserts a child at the specific index in the parent's list of children.
/// Negative indecies will insert from the back of the list. For example, a
/// |child| inserted at an |index| of '-1' would become the last element in
/// the list, at '-2' it would be the second to last, etc. Out-of-range
/// |index| values are clamped so as not to exceed the number of children in
/// the list.
void InsertChild(Entity parent, Entity child, int index = -1);
/// Moves a child entity to the given index in its parent's list of children.
/// If the |child| has no parent, this has no effect. The |index| behaves the
/// same as described in InsertChild().
void MoveChild(Entity child, int index);
/// Break a child's connection to its parent.
void RemoveParent(Entity child);
/// Retrieve the list of children of an Entity
const std::vector<Entity>* GetChildren(Entity parent) const;
/// Destroys all child entities of the given parent entity. If |parent| has
/// no children, this has no effect.
void DestroyChildren(Entity parent);
/// Returns the number of children belonging to the |parent| entity.
size_t GetChildCount(Entity parent) const;
/// Returns the index of the |child| entity within its parent's list of
/// children. Returns 0 if the |child| has no parent.
size_t GetChildIndex(Entity child) const;
/// Returns true if |ancestor| is in the parent chain of |target|.
bool IsAncestorOf(Entity ancestor, Entity target) const;
/// Returns a unique flag that can be used to iterate via ForEach.
TransformFlags RequestFlag();
/// Releases a flag. After calling this, you should set all references to
/// kInvalidFlag.
void ReleaseFlag(TransformFlags flag);
/// Calls the provided function with every Transform and provides the
/// TransformFlags.
template <typename Fn>
void ForAll(Fn fn) const {
world_transforms_.ForEach([&](const WorldTransform& transform) {
fn(transform.GetEntity(), transform.world_from_entity_mat, transform.box,
transform.flags);
});
}
/// Calls the provided function with a Transform for every Entity which has
/// the provided flag.
///
/// For example:
/// @code
/// transform_system->ForEach(
/// kSomeFlag,
/// [this](Entity e, const mathfu::mat4& world_from_entity_mat,
/// const Aabb& box) {
/// DoSomethingToEntityAt(e, world_from_entity_mat);
/// });
/// @endcode
template <typename Fn>
void ForEach(TransformFlags flag, Fn fn) const {
if (flag == kAllFlags) {
ForAll([&](Entity e, const mathfu::mat4& world_from_entity_mat,
const Aabb& box, Bits) { fn(e, world_from_entity_mat, box); });
} else {
ForAll([&](Entity e, const mathfu::mat4& world_from_entity_mat,
const Aabb& box, Bits flags) {
if (CheckBit(flags, flag)) fn(e, world_from_entity_mat, box);
});
}
}
/// Calls the provided function on the provided entity and all of it's
/// descendants.
template <typename Fn>
void ForAllDescendants(Entity parent, Fn fn) const {
fn(parent);
const auto* const children = GetChildren(parent);
if (children) {
for (const lull::Entity& child : *children) {
ForAllDescendants(child, fn);
}
}
}
private:
struct GraphNode : Component {
explicit GraphNode(Entity e)
: Component(e),
local_sqt(mathfu::kZeros3f, mathfu::quat::identity, mathfu::kOnes3f),
parent(kNullEntity),
enable_self(true) {}
Sqt local_sqt;
Aabb aabb_padding;
CalculateWorldFromEntityMatrixFunc world_from_entity_matrix_function;
std::vector<Entity> children;
Entity parent;
bool enable_self;
};
struct WorldTransform : Component {
// This struct should be kept as small as possible to reduce cache misses
// when iterating.
explicit WorldTransform(Entity e) : Component(e), flags(0) {}
Bits flags;
mathfu::mat4 world_from_entity_mat;
Aabb box;
};
static mathfu::mat4 CalculateWorldFromEntityMatrix(
const Sqt& local_sqt, const mathfu::mat4* world_from_parent_mat);
void UpdateTransforms(Entity child);
void SetEnabled(Entity e, bool enabled);
void UpdateEnabled(Entity e, bool parent_enabled);
const WorldTransform* GetWorldTransform(Entity e) const;
WorldTransform* GetWorldTransform(Entity e);
// Break a child's connection to its parent without sending any events.
void RemoveParentNoEvent(Entity child);
// Establish a parent/child relationship between two Entities without
// sending any events.
bool AddChildNoEvent(Entity parent, Entity child, AddChildMode mode);
ComponentPool<GraphNode> nodes_;
ComponentPool<WorldTransform> world_transforms_;
ComponentPool<WorldTransform> disabled_transforms_;
uint32_t reserved_flags_;
// A map of parent/child relationships requested by CreateChild, which need to
// be handled during Create().
std::unordered_map<Entity, Entity> pending_children_;
TransformSystem(const TransformSystem&);
TransformSystem& operator=(const TransformSystem&);
};
} // namespace lull
LULLABY_SETUP_TYPEID(lull::TransformSystem);
#endif // LULLABY_SYSTEMS_TRANSFORM_TRANSFORM_SYSTEM_H_
| 37.36646 | 80 | 0.718833 | [
"render",
"vector",
"transform"
] |
07aae34a0e628a7ae72566d8ca73ac2c0c0f17db | 2,012 | h | C | compiler/src/core/Block.h | d08ble/acpu | fb7b809ada746ecc3d1dbbe1096b120ac8f63256 | [
"Unlicense"
] | 2 | 2021-08-28T14:45:13.000Z | 2021-11-15T12:24:03.000Z | compiler/src/core/Block.h | d08ble/acpu | fb7b809ada746ecc3d1dbbe1096b120ac8f63256 | [
"Unlicense"
] | null | null | null | compiler/src/core/Block.h | d08ble/acpu | fb7b809ada746ecc3d1dbbe1096b120ac8f63256 | [
"Unlicense"
] | null | null | null | //
// Another CPU Language - ACPUL - a{};
//
// THIS SOFTWARE IS PROVIDED BY THE FREEBSD PROJECT ``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 FREEBSD PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
// OF SUCH DAMAGE.
//
// Made by d08ble, thanks for watching.
//
#ifndef ACPULanguage_Block_h
#define ACPULanguage_Block_h
#include <iostream>
#include "Expression.h"
namespace acpul {
class Block
{
Object *_object;
std::vector<Expression *> _expressions;
bool _codeType; // 0 object "o;" "o();"
// 1 code "o+1; "o:=1;" "o;o;"
public:
Block() : _codeType(false) {}
void setObject(Object *object_) { _object = object_; }
Object *object() { return _object; }
size_t expressionsCount() { return _expressions.size(); }
Expression *expressionAtIndex(int i) { return _expressions[i]; }
bool codeType() { return _codeType; }
void addExpression(stree &tree, stree::iterator node);
void updateCodeType();
bool isLink();
Object *getLinkObject();
bool getNumber(float &v);
bool isFollowing();
// DUMP HELPER
void dumpFull(int prefix, int flags);
};
}
#endif
| 32.451613 | 89 | 0.60338 | [
"object",
"vector"
] |
07c43602469f156cb4536cbd785d3a072883ac0c | 13,047 | h | C | src/atlas/array/native/NativeArrayView.h | twsearle/atlas | a1916fd521f9935f846004e6194f80275de4de83 | [
"Apache-2.0"
] | 67 | 2018-03-01T06:56:49.000Z | 2022-03-08T18:44:47.000Z | src/atlas/array/native/NativeArrayView.h | twsearle/atlas | a1916fd521f9935f846004e6194f80275de4de83 | [
"Apache-2.0"
] | 93 | 2018-12-07T17:38:04.000Z | 2022-03-31T10:04:51.000Z | src/atlas/array/native/NativeArrayView.h | twsearle/atlas | a1916fd521f9935f846004e6194f80275de4de83 | [
"Apache-2.0"
] | 33 | 2018-02-28T17:06:19.000Z | 2022-01-20T12:12:27.000Z | /*
* (C) Copyright 2013 ECMWF.
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
* In applying this licence, ECMWF does not waive the privileges and immunities
* granted to it by virtue of its status as an intergovernmental organisation
* nor does it submit to any jurisdiction.
*/
/// @file ArrayView.h
/// This file contains the ArrayView class, a class that allows to wrap any
/// contiguous raw data into
/// a view which is accessible with multiple indices.
/// All it needs is the strides for each index, and the shape of each index.
/// ATTENTION: The last index is stride 1
///
/// Bounds-checking can be turned ON by defining
/// "ATLAS_ARRAYVIEW_BOUNDS_CHECKING"
/// before including this header.
///
/// Example 1:
/// int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9};
/// int[2] strides = { 3, 1 };
/// int[2] shape = { 3, 3 };
/// ArrayView<int,2> matrix( array, shape, strides );
/// for( idx_t i=0; i<matrix.shape(0); ++i ) {
/// for( idx_t j=0; j<matrix.shape(1); ++j ) {
/// matrix(i,j) *= 10;
/// }
/// }
///
/// Strides can also be omitted as for most common cases it can be inferred
/// from the shape.
///
/// Example 2:
/// int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9};
/// int[2] shape = { 3, 3 };
/// ArrayView<int,2> matrix( array, shape );
/// which is identical for this matrix to previous Example 1
///
/// There is also an easier way to wrap Field and Array classes:
///
/// Example 3:
/// ArrayView<int,3> fieldview( Field );
/// ArrayView<int,2> arrayview( Array );
///
/// @author Willem Deconinck
#pragma once
#include <array>
#include <cstddef>
#include <initializer_list>
#include <iostream>
#include <type_traits>
#include "atlas/array/ArrayUtil.h"
#include "atlas/array/ArrayViewDefs.h"
#include "atlas/array/LocalView.h"
#include "atlas/array/Range.h"
#include "atlas/array/helpers/ArraySlicer.h"
#include "atlas/library/config.h"
//------------------------------------------------------------------------------------------------------
namespace atlas {
namespace array {
//------------------------------------------------------------------------------------------------------
/// @brief Multi-dimensional access to a Array object or Field object
///
/// An ArrayView enables access to the inner data-memory-storage of the Array.
/// It is required to create the view using the make_view helper functions.
///
/// ### Example 1:
///
/// @code{.cpp}
/// auto view = make_view<double,2>( Array );
/// double sum = 0;
/// for( idx_t i=0; i<view.shape(0); ++i ) {
/// for( idx_t j=0; j<view.shape(1); ++j ) {
/// sum += view(i,j);
/// }
/// }
/// @endcode
///
/// ### Data storage
///
/// Depending on whether atlas was compiled with the Feature `GRIDTOOLS_STORAGE`, the
/// internal data allocation of the Array object is managed by [GridTools](https://gridtools.github.io/)
/// (ATLAS_HAVE_GRIDTOOLS==1) or by Atlas itself (ATLAS_HAVE_GRIDTOOLS==0).
///
/// The ArrayView class is therefore also compiled differently dependening on this feature.
template <typename Value, int Rank>
class ArrayView {
template <typename T>
using is_non_const_value_type = typename std::is_same<T, typename std::remove_const<Value>::type>;
#define ENABLE_IF_NON_CONST \
template <bool EnableBool = true, \
typename std::enable_if<(!std::is_const<Value>::value && EnableBool), int>::type* = nullptr>
#define ENABLE_IF_CONST_WITH_NON_CONST(T) \
template <typename T, typename std::enable_if<(std::is_const<Value>::value && is_non_const_value_type<T>::value), \
int>::type* = nullptr>
public:
// -- Type definitions
using value_type = Value;
using non_const_value_type = typename std::remove_const<Value>::type;
static constexpr bool is_const = std::is_const<Value>::value;
static constexpr bool is_non_const = !std::is_const<Value>::value;
static constexpr int RANK{Rank};
private:
using slicer_t = typename helpers::ArraySlicer<ArrayView<Value, Rank>>;
using const_slicer_t = typename helpers::ArraySlicer<const ArrayView<const Value, Rank>>;
template <typename... Args>
struct slice_t {
using type = typename slicer_t::template Slice<Args...>::type;
};
template <typename... Args>
struct const_slice_t {
using type = typename const_slicer_t::template Slice<Args...>::type;
};
public:
// -- Constructors
ArrayView(const ArrayView& other):
data_(other.data_), size_(other.size_), shape_(other.shape_), strides_(other.strides_) {}
ENABLE_IF_CONST_WITH_NON_CONST(value_type)
ArrayView(const ArrayView<value_type, Rank>& other): data_(other.data()), size_(other.size()) {
for (idx_t j = 0; j < Rank; ++j) {
shape_[j] = other.shape(j);
strides_[j] = other.stride(j);
}
}
#ifndef DOXYGEN_SHOULD_SKIP_THIS
// This constructor should not be used directly, but only through a array::make_view() function.
ArrayView(value_type* data, const ArrayShape& shape, const ArrayStrides& strides): data_(data) {
size_ = 1;
for (int j = 0; j < Rank; ++j) {
shape_[j] = shape[j];
strides_[j] = strides[j];
size_ *= size_t(shape_[j]);
}
}
#endif
ENABLE_IF_CONST_WITH_NON_CONST(value_type)
operator const ArrayView<value_type, Rank>&() const { return *(const ArrayView<value_type, Rank>*)(this); }
// -- Access methods
/// @brief Multidimensional index operator: view(i,j,k,...)
template <typename... Idx>
value_type& operator()(Idx... idx) {
check_bounds(idx...);
return data_[index(idx...)];
}
/// @brief Multidimensional index operator: view(i,j,k,...)
template <typename... Ints>
const value_type& operator()(Ints... idx) const {
return data_[index(idx...)];
}
/// @brief Access to data using square bracket [idx] operator @m_class{m-label m-warning} **Rank==1**.
///
/// Note that this function is only present when Rank == 1
#ifndef DOXYGEN_SHOULD_SKIP_THIS
template <typename Int, bool EnableBool = true>
typename std::enable_if<(Rank == 1 && EnableBool), const value_type&>::type operator[](Int idx) const {
#else
// Doxygen API is cleaner!
template <typename Int>
value_type operator[](Int idx) const {
#endif
check_bounds(idx);
return data_[idx * strides_[0]];
}
/// @brief Access to data using square bracket [idx] operator @m_class{m-label m-warning} **Rank==1**
///
/// Note that this function is only present when Rank == 1
#ifndef DOXYGEN_SHOULD_SKIP_THIS
template <typename Int, bool EnableBool = true>
typename std::enable_if<(Rank == 1 && EnableBool), value_type&>::type operator[](Int idx) {
#else
// Doxygen API is cleaner!
template <typename Int>
value_type operator[](Int idx) {
#endif
check_bounds(idx);
return data_[idx * strides_[0]];
}
/// @brief Return number of values in dimension **Dim** (template argument)
///
/// Example use:
/// @code{.cpp}
/// for( idx_t i=0; i<view.shape<0>(); ++i ) {
/// for( idx_t j=0; j<view.shape<1>(); +j ) {
/// ...
/// }
/// }
/// @endcode
template <unsigned int Dim>
idx_t shape() const {
return shape_[Dim];
}
/// @brief Return stride for values in dimension **Dim** (template argument)
template <unsigned int Dim>
idx_t stride() const {
return strides_[Dim];
}
/// @brief Return total number of values (accumulated over all dimensions)
size_t size() const { return size_; }
/// @brief Return the number of dimensions
static constexpr idx_t rank() { return Rank; }
const idx_t* strides() const { return strides_.data(); }
const idx_t* shape() const { return shape_.data(); }
/// @brief Return number of values in dimension idx
template <typename Int>
idx_t shape(Int idx) const {
return shape_[idx];
}
/// @brief Return stride for values in dimension idx
template <typename Int>
idx_t stride(Int idx) const {
return strides_[idx];
}
/// @brief Access to internal data. @m_class{m-label m-danger} **dangerous**
value_type const* data() const { return data_; }
/// @brief Access to internal data. @m_class{m-label m-danger} **dangerous**
value_type* data() { return data_; }
bool valid() const { return true; }
/// @brief Return true when all values are contiguous in memory.
///
/// This means that if there is e.g. padding in the fastest dimension, or if
/// the ArrayView represents a slice, the returned value will be false.
bool contiguous() const { return (size_ == size_t(shape_[0]) * size_t(strides_[0]) ? true : false); }
ENABLE_IF_NON_CONST
void assign(const value_type& value);
ENABLE_IF_NON_CONST
void assign(const std::initializer_list<value_type>& list);
ENABLE_IF_NON_CONST
void assign(const ArrayView& other);
void dump(std::ostream& os) const;
/// @brief Obtain a slice from this view: view.slice( Range, Range, ... )
///
/// The return type of this function is intentionally `auto` and is guaranteed to have
/// the same API as ArrayView, but is not necessarily this type.
///
/// If the current view has Rank == 2, a Rank == 1 slice can be created in several ways:
///
/// @code{.cpp}
/// auto slice1 = view.slice( Range(0,2), Range::all() );
/// auto slice2 = view.slice( Range::To(2), Range::all() );
/// @endcode
///
/// Sometimes it may be required to extend the rank of the current view to cater for
/// certain algorithms requiring an extra rank.
///
/// @code{.cpp}
/// auto slice3 = view.slice( Range::all(), Range::all(), Range::dummy() );
/// @endcode
template <typename... Args>
#ifndef DOXYGEN_SHOULD_SKIP_THIS
typename slice_t<Args...>::type slice(Args... args) {
#else
// C++14 will allow auto return type
auto slice(Args... args) {
#endif
return slicer_t(*this).apply(args...);
}
/// @brief Obtain a slice from this view: view.slice( Range, Range, ... )
template <typename... Args>
#ifndef DOXYGEN_SHOULD_SKIP_THIS
typename const_slice_t<Args...>::type slice(Args... args) const {
#else
// C++14 will allow auto return type
auto slice(Args... args) const {
#endif
return const_slicer_t(*this).apply(args...);
}
private:
// -- Private methods
template <int Dim, typename Int, typename... Ints>
constexpr idx_t index_part(Int idx, Ints... next_idx) const {
return idx * strides_[Dim] + index_part<Dim + 1>(next_idx...);
}
template <int Dim, typename Int>
constexpr idx_t index_part(Int last_idx) const {
return last_idx * strides_[Dim];
}
template <typename... Ints>
constexpr idx_t index(Ints... idx) const {
return index_part<0>(idx...);
}
#if ATLAS_ARRAYVIEW_BOUNDS_CHECKING
template <typename... Ints>
void check_bounds(Ints... idx) const {
static_assert(sizeof...(idx) == Rank, "Expected number of indices is different from rank of array");
return check_bounds_part<0>(idx...);
}
#else
template <typename... Ints>
void check_bounds(Ints... idx) const {
static_assert(sizeof...(idx) == Rank, "Expected number of indices is different from rank of array");
}
#endif
template <typename... Ints>
void check_bounds_force(Ints... idx) const {
static_assert(sizeof...(idx) == Rank, "Expected number of indices is different from rank of array");
return check_bounds_part<0>(idx...);
}
template <int Dim, typename Int, typename... Ints>
void check_bounds_part(Int idx, Ints... next_idx) const {
if (idx_t(idx) >= shape_[Dim]) {
throw_OutOfRange("ArrayView", array_dim<Dim>(), idx, shape_[Dim]);
}
check_bounds_part<Dim + 1>(next_idx...);
}
template <int Dim, typename Int>
void check_bounds_part(Int last_idx) const {
if (idx_t(last_idx) >= shape_[Dim]) {
throw_OutOfRange("ArrayView", array_dim<Dim>(), last_idx, shape_[Dim]);
}
}
// -- Private data
value_type* data_;
size_t size_;
std::array<idx_t, Rank> shape_;
std::array<idx_t, Rank> strides_;
};
//------------------------------------------------------------------------------------------------------
#undef ENABLE_IF_NON_CONST
#undef ENABLE_IF_CONST_WITH_NON_CONST
} // namespace array
} // namespace atlas
| 34.15445 | 119 | 0.607113 | [
"object",
"shape"
] |
07c695f0313c5fec0c4e1fb036553fff9219cfe3 | 756 | c | C | src/tests/textures/3d_textures.c | tevoran/T3Vtech-3 | caf2dbec3d96fa8045c9b57621495549f5e26e2f | [
"MIT"
] | 5 | 2022-02-01T13:39:12.000Z | 2022-03-30T16:57:58.000Z | src/tests/textures/3d_textures.c | tevoran/T3Vtech-3 | caf2dbec3d96fa8045c9b57621495549f5e26e2f | [
"MIT"
] | 1 | 2022-03-26T17:51:23.000Z | 2022-03-26T17:51:23.000Z | src/tests/textures/3d_textures.c | tevoran/T3Vtech-3 | caf2dbec3d96fa8045c9b57621495549f5e26e2f | [
"MIT"
] | 4 | 2022-03-19T13:36:34.000Z | 2022-03-30T16:58:02.000Z | #include <tt.h>
int main(int argc, char *argv[])
{
tt_init("T3Vtech3 test window", 1920, 1080, false, 16, NULL);
tt_3d_object *quad=tt_3d_object_new();
tt_3d_object_make_quad(quad);
tt_vec3 pos={0,0,-7};
tt_vec3 scale={2.8,1.0,1.0};
tt_3d_object_set_position(quad, &pos);
tt_3d_object_scale(quad, &scale);
tt_3d_object_light_affected(quad, false);
tt_font *font=tt_font_open("assets/fonts/OpenSans-Light.ttf", 50);
tt_color_rgba_u8 color={255,255,255,255};
tt_3d_texture *text=tt_3d_texture_make_text(font, "3D T3Vtech-3 test text", color);
tt_3d_object_use_texture(quad, text);
tt_vec3 rot_axis={0,1,0};
while(!tt_input_keyboard_key_press(TT_KEY_ESC))
{
tt_3d_object_rotate(quad, &rot_axis, 0.01);
tt_new_frame();
}
return 0;
} | 25.2 | 84 | 0.736772 | [
"3d"
] |
07d8794f22c114cd94ff1d9eb89a355f99268e75 | 20,904 | c | C | xen-4.6.0/xen/arch/x86/cpu/mwait-idle.c | StanPlatinum/VMI-as-a-Service | 5828a9c73815ad7e043428e7e56dc0715aaa60a1 | [
"MIT"
] | 3 | 2019-08-31T19:58:24.000Z | 2020-10-02T06:50:22.000Z | xen-4.6.0/xen/arch/x86/cpu/mwait-idle.c | StanPlatinum/VMI-as-a-Service | 5828a9c73815ad7e043428e7e56dc0715aaa60a1 | [
"MIT"
] | 1 | 2020-10-16T19:13:49.000Z | 2020-10-16T19:13:49.000Z | xen-4.6.0/xen/arch/x86/cpu/mwait-idle.c | StanPlatinum/ROP-detection-inside-VMs | 7b39298dd0791711cbd78fd0730b819b755cc995 | [
"MIT"
] | 1 | 2021-06-06T21:10:21.000Z | 2021-06-06T21:10:21.000Z | /*
* mwait_idle.c - native hardware idle loop for modern processors
*
* Copyright (c) 2013, Intel Corporation.
* Len Brown <len.brown@intel.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope 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, see <http://www.gnu.org/licenses/>.
*/
/*
* mwait_idle is a cpuidle driver that loads on specific processors
* in lieu of the legacy ACPI processor_idle driver. The intent is to
* make Linux more efficient on these processors, as mwait_idle knows
* more than ACPI, as well as make Linux more immune to ACPI BIOS bugs.
*/
/*
* Design Assumptions
*
* All CPUs have same idle states as boot CPU
*
* Chipset BM_STS (bus master status) bit is a NOP
* for preventing entry into deep C-states
*/
/*
* Known limitations
*
* The driver currently initializes for_each_online_cpu() upon load.
* It it unaware of subsequent processors hot-added to the system.
* This means that if you boot with maxcpus=n and later online
* processors above n, those processors will use C1 only.
*
* ACPI has a .suspend hack to turn off deep C-states during suspend
* to avoid complications with the lapic timer workaround.
* Have not seen issues with suspend, but may need same workaround here.
*/
/* un-comment DEBUG to enable pr_debug() statements */
#define DEBUG
#include <xen/lib.h>
#include <xen/cpu.h>
#include <xen/init.h>
#include <xen/softirq.h>
#include <xen/trace.h>
#include <asm/cpuidle.h>
#include <asm/hpet.h>
#include <asm/mwait.h>
#include <asm/msr.h>
#include <acpi/cpufreq/cpufreq.h>
#define MWAIT_IDLE_VERSION "0.4"
#undef PREFIX
#define PREFIX "mwait-idle: "
#ifdef DEBUG
# define pr_debug(fmt...) printk(KERN_DEBUG fmt)
#else
# define pr_debug(fmt...)
#endif
static __initdata bool_t no_mwait_idle;
invbool_param("mwait-idle", no_mwait_idle);
static unsigned int mwait_substates;
#define LAPIC_TIMER_ALWAYS_RELIABLE 0xFFFFFFFF
/* Reliable LAPIC Timer States, bit 1 for C1 etc. Default to only C1. */
static unsigned int lapic_timer_reliable_states = (1 << 1);
struct idle_cpu {
const struct cpuidle_state *state_table;
/*
* Hardware C-state auto-demotion may not always be optimal.
* Indicate which enable bits to clear here.
*/
unsigned long auto_demotion_disable_flags;
bool_t byt_auto_demotion_disable_flag;
bool_t disable_promotion_to_c1e;
};
static const struct idle_cpu *icpu;
static const struct cpuidle_state {
char name[16];
unsigned int flags;
unsigned int exit_latency; /* in US */
unsigned int target_residency; /* in US */
} *cpuidle_state_table;
/*
* Set this flag for states where the HW flushes the TLB for us
* and so we don't need cross-calls to keep it consistent.
* If this flag is set, SW flushes the TLB, so even if the
* HW doesn't do the flushing, this flag is safe to use.
*/
#define CPUIDLE_FLAG_TLB_FLUSHED 0x10000
/*
* MWAIT takes an 8-bit "hint" in EAX "suggesting"
* the C-state (top nibble) and sub-state (bottom nibble)
* 0x00 means "MWAIT(C1)", 0x10 means "MWAIT(C2)" etc.
*
* We store the hint at the top of our "flags" for each state.
*/
#define flg2MWAIT(flags) (((flags) >> 24) & 0xFF)
#define MWAIT2flg(eax) ((eax & 0xFF) << 24)
#define MWAIT_HINT2CSTATE(hint) (((hint) >> MWAIT_SUBSTATE_SIZE) & MWAIT_CSTATE_MASK)
#define MWAIT_HINT2SUBSTATE(hint) ((hint) & MWAIT_CSTATE_MASK)
/*
* States are indexed by the cstate number,
* which is also the index into the MWAIT hint array.
* Thus C0 is a dummy.
*/
static const struct cpuidle_state nehalem_cstates[] = {
{
.name = "C1-NHM",
.flags = MWAIT2flg(0x00),
.exit_latency = 3,
.target_residency = 6,
},
{
.name = "C1E-NHM",
.flags = MWAIT2flg(0x01),
.exit_latency = 10,
.target_residency = 20,
},
{
.name = "C3-NHM",
.flags = MWAIT2flg(0x10) | CPUIDLE_FLAG_TLB_FLUSHED,
.exit_latency = 20,
.target_residency = 80,
},
{
.name = "C6-NHM",
.flags = MWAIT2flg(0x20) | CPUIDLE_FLAG_TLB_FLUSHED,
.exit_latency = 200,
.target_residency = 800,
},
{}
};
static const struct cpuidle_state snb_cstates[] = {
{
.name = "C1-SNB",
.flags = MWAIT2flg(0x00),
.exit_latency = 2,
.target_residency = 2,
},
{
.name = "C1E-SNB",
.flags = MWAIT2flg(0x01),
.exit_latency = 10,
.target_residency = 20,
},
{
.name = "C3-SNB",
.flags = MWAIT2flg(0x10) | CPUIDLE_FLAG_TLB_FLUSHED,
.exit_latency = 80,
.target_residency = 211,
},
{
.name = "C6-SNB",
.flags = MWAIT2flg(0x20) | CPUIDLE_FLAG_TLB_FLUSHED,
.exit_latency = 104,
.target_residency = 345,
},
{
.name = "C7-SNB",
.flags = MWAIT2flg(0x30) | CPUIDLE_FLAG_TLB_FLUSHED,
.exit_latency = 109,
.target_residency = 345,
},
{}
};
static const struct cpuidle_state byt_cstates[] = {
{
.name = "C1-BYT",
.flags = MWAIT2flg(0x00),
.exit_latency = 1,
.target_residency = 1,
},
{
.name = "C6N-BYT",
.flags = MWAIT2flg(0x58) | CPUIDLE_FLAG_TLB_FLUSHED,
.exit_latency = 300,
.target_residency = 275,
},
{
.name = "C6S-BYT",
.flags = MWAIT2flg(0x52) | CPUIDLE_FLAG_TLB_FLUSHED,
.exit_latency = 500,
.target_residency = 560,
},
{
.name = "C7-BYT",
.flags = MWAIT2flg(0x60) | CPUIDLE_FLAG_TLB_FLUSHED,
.exit_latency = 1200,
.target_residency = 4000,
},
{
.name = "C7S-BYT",
.flags = MWAIT2flg(0x64) | CPUIDLE_FLAG_TLB_FLUSHED,
.exit_latency = 10000,
.target_residency = 20000,
},
{}
};
static const struct cpuidle_state cht_cstates[] = {
{
.name = "C1-CHT",
.flags = MWAIT2flg(0x00),
.exit_latency = 1,
.target_residency = 1,
},
{
.name = "C6N-CHT",
.flags = MWAIT2flg(0x58) | CPUIDLE_FLAG_TLB_FLUSHED,
.exit_latency = 80,
.target_residency = 275,
},
{
.name = "C6S-CHT",
.flags = MWAIT2flg(0x52) | CPUIDLE_FLAG_TLB_FLUSHED,
.exit_latency = 200,
.target_residency = 560,
},
{
.name = "C7-CHT",
.flags = MWAIT2flg(0x60) | CPUIDLE_FLAG_TLB_FLUSHED,
.exit_latency = 1200,
.target_residency = 4000,
},
{
.name = "C7S-CHT",
.flags = MWAIT2flg(0x64) | CPUIDLE_FLAG_TLB_FLUSHED,
.exit_latency = 10000,
.target_residency = 20000,
},
{}
};
static const struct cpuidle_state ivb_cstates[] = {
{
.name = "C1-IVB",
.flags = MWAIT2flg(0x00),
.exit_latency = 1,
.target_residency = 1,
},
{
.name = "C1E-IVB",
.flags = MWAIT2flg(0x01),
.exit_latency = 10,
.target_residency = 20,
},
{
.name = "C3-IVB",
.flags = MWAIT2flg(0x10) | CPUIDLE_FLAG_TLB_FLUSHED,
.exit_latency = 59,
.target_residency = 156,
},
{
.name = "C6-IVB",
.flags = MWAIT2flg(0x20) | CPUIDLE_FLAG_TLB_FLUSHED,
.exit_latency = 80,
.target_residency = 300,
},
{
.name = "C7-IVB",
.flags = MWAIT2flg(0x30) | CPUIDLE_FLAG_TLB_FLUSHED,
.exit_latency = 87,
.target_residency = 300,
},
{}
};
static const struct cpuidle_state ivt_cstates[] = {
{
.name = "C1-IVT",
.flags = MWAIT2flg(0x00),
.exit_latency = 1,
.target_residency = 1,
},
{
.name = "C1E-IVT",
.flags = MWAIT2flg(0x01),
.exit_latency = 10,
.target_residency = 80,
},
{
.name = "C3-IVT",
.flags = MWAIT2flg(0x10) | CPUIDLE_FLAG_TLB_FLUSHED,
.exit_latency = 59,
.target_residency = 156,
},
{
.name = "C6-IVT",
.flags = MWAIT2flg(0x20) | CPUIDLE_FLAG_TLB_FLUSHED,
.exit_latency = 82,
.target_residency = 300,
},
{}
};
static const struct cpuidle_state ivt_cstates_4s[] = {
{
.name = "C1-IVT-4S",
.flags = MWAIT2flg(0x00),
.exit_latency = 1,
.target_residency = 1,
},
{
.name = "C1E-IVT-4S",
.flags = MWAIT2flg(0x01),
.exit_latency = 10,
.target_residency = 250,
},
{
.name = "C3-IVT-4S",
.flags = MWAIT2flg(0x10) | CPUIDLE_FLAG_TLB_FLUSHED,
.exit_latency = 59,
.target_residency = 300,
},
{
.name = "C6-IVT-4S",
.flags = MWAIT2flg(0x20) | CPUIDLE_FLAG_TLB_FLUSHED,
.exit_latency = 84,
.target_residency = 400,
},
{}
};
static const struct cpuidle_state ivt_cstates_8s[] = {
{
.name = "C1-IVT-8S",
.flags = MWAIT2flg(0x00),
.exit_latency = 1,
.target_residency = 1,
},
{
.name = "C1E-IVT-8S",
.flags = MWAIT2flg(0x01),
.exit_latency = 10,
.target_residency = 500,
},
{
.name = "C3-IVT-8S",
.flags = MWAIT2flg(0x10) | CPUIDLE_FLAG_TLB_FLUSHED,
.exit_latency = 59,
.target_residency = 600,
},
{
.name = "C6-IVT-8S",
.flags = MWAIT2flg(0x20) | CPUIDLE_FLAG_TLB_FLUSHED,
.exit_latency = 88,
.target_residency = 700,
},
{}
};
static const struct cpuidle_state hsw_cstates[] = {
{
.name = "C1-HSW",
.flags = MWAIT2flg(0x00),
.exit_latency = 2,
.target_residency = 2,
},
{
.name = "C1E-HSW",
.flags = MWAIT2flg(0x01),
.exit_latency = 10,
.target_residency = 20,
},
{
.name = "C3-HSW",
.flags = MWAIT2flg(0x10) | CPUIDLE_FLAG_TLB_FLUSHED,
.exit_latency = 33,
.target_residency = 100,
},
{
.name = "C6-HSW",
.flags = MWAIT2flg(0x20) | CPUIDLE_FLAG_TLB_FLUSHED,
.exit_latency = 133,
.target_residency = 400,
},
{
.name = "C7s-HSW",
.flags = MWAIT2flg(0x32) | CPUIDLE_FLAG_TLB_FLUSHED,
.exit_latency = 166,
.target_residency = 500,
},
{
.name = "C8-HSW",
.flags = MWAIT2flg(0x40) | CPUIDLE_FLAG_TLB_FLUSHED,
.exit_latency = 300,
.target_residency = 900,
},
{
.name = "C9-HSW",
.flags = MWAIT2flg(0x50) | CPUIDLE_FLAG_TLB_FLUSHED,
.exit_latency = 600,
.target_residency = 1800,
},
{
.name = "C10-HSW",
.flags = MWAIT2flg(0x60) | CPUIDLE_FLAG_TLB_FLUSHED,
.exit_latency = 2600,
.target_residency = 7700,
},
{}
};
static const struct cpuidle_state bdw_cstates[] = {
{
.name = "C1-BDW",
.flags = MWAIT2flg(0x00),
.exit_latency = 2,
.target_residency = 2,
},
{
.name = "C1E-BDW",
.flags = MWAIT2flg(0x01),
.exit_latency = 10,
.target_residency = 20,
},
{
.name = "C3-BDW",
.flags = MWAIT2flg(0x10) | CPUIDLE_FLAG_TLB_FLUSHED,
.exit_latency = 40,
.target_residency = 100,
},
{
.name = "C6-BDW",
.flags = MWAIT2flg(0x20) | CPUIDLE_FLAG_TLB_FLUSHED,
.exit_latency = 133,
.target_residency = 400,
},
{
.name = "C7s-BDW",
.flags = MWAIT2flg(0x32) | CPUIDLE_FLAG_TLB_FLUSHED,
.exit_latency = 166,
.target_residency = 500,
},
{
.name = "C8-BDW",
.flags = MWAIT2flg(0x40) | CPUIDLE_FLAG_TLB_FLUSHED,
.exit_latency = 300,
.target_residency = 900,
},
{
.name = "C9-BDW",
.flags = MWAIT2flg(0x50) | CPUIDLE_FLAG_TLB_FLUSHED,
.exit_latency = 600,
.target_residency = 1800,
},
{
.name = "C10-BDW",
.flags = MWAIT2flg(0x60) | CPUIDLE_FLAG_TLB_FLUSHED,
.exit_latency = 2600,
.target_residency = 7700,
},
{}
};
static const struct cpuidle_state atom_cstates[] = {
{
.name = "C1E-ATM",
.flags = MWAIT2flg(0x00),
.exit_latency = 10,
.target_residency = 20,
},
{
.name = "C2-ATM",
.flags = MWAIT2flg(0x10),
.exit_latency = 20,
.target_residency = 80,
},
{
.name = "C4-ATM",
.flags = MWAIT2flg(0x30) | CPUIDLE_FLAG_TLB_FLUSHED,
.exit_latency = 100,
.target_residency = 400,
},
{
.name = "C6-ATM",
.flags = MWAIT2flg(0x52) | CPUIDLE_FLAG_TLB_FLUSHED,
.exit_latency = 140,
.target_residency = 560,
},
{}
};
static const struct cpuidle_state avn_cstates[] = {
{
.name = "C1-AVN",
.flags = MWAIT2flg(0x00),
.exit_latency = 2,
.target_residency = 2,
},
{
.name = "C6-AVN",
.flags = MWAIT2flg(0x51) | CPUIDLE_FLAG_TLB_FLUSHED,
.exit_latency = 15,
.target_residency = 45,
},
{}
};
static void mwait_idle(void)
{
unsigned int cpu = smp_processor_id();
struct acpi_processor_power *power = processor_powers[cpu];
struct acpi_processor_cx *cx = NULL;
unsigned int eax, next_state, cstate;
u64 before, after;
u32 exp = 0, pred = 0, irq_traced[4] = { 0 };
if (max_cstate > 0 && power && !sched_has_urgent_vcpu() &&
(next_state = cpuidle_current_governor->select(power)) > 0) {
do {
cx = &power->states[next_state];
} while (cx->type > max_cstate && --next_state);
if (!next_state)
cx = NULL;
menu_get_trace_data(&exp, &pred);
}
if (!cx) {
if (pm_idle_save)
pm_idle_save();
else
safe_halt();
return;
}
cpufreq_dbs_timer_suspend();
sched_tick_suspend();
/* sched_tick_suspend() can raise TIMER_SOFTIRQ. Process it now. */
process_pending_softirqs();
/* Interrupts must be disabled for C2 and higher transitions. */
local_irq_disable();
if (!cpu_is_haltable(cpu)) {
local_irq_enable();
sched_tick_resume();
cpufreq_dbs_timer_resume();
return;
}
eax = cx->address;
cstate = ((eax >> MWAIT_SUBSTATE_SIZE) & MWAIT_CSTATE_MASK) + 1;
#if 0 /* XXX Can we/do we need to do something similar on Xen? */
/*
* leave_mm() to avoid costly and often unnecessary wakeups
* for flushing the user TLB's associated with the active mm.
*/
if (cpuidle_state_table[].flags & CPUIDLE_FLAG_TLB_FLUSHED)
leave_mm(cpu);
#endif
if (!(lapic_timer_reliable_states & (1 << cstate)))
lapic_timer_off();
before = cpuidle_get_tick();
TRACE_4D(TRC_PM_IDLE_ENTRY, cx->type, before, exp, pred);
update_last_cx_stat(power, cx, before);
if (cpu_is_haltable(cpu))
mwait_idle_with_hints(eax, MWAIT_ECX_INTERRUPT_BREAK);
after = cpuidle_get_tick();
cstate_restore_tsc();
trace_exit_reason(irq_traced);
TRACE_6D(TRC_PM_IDLE_EXIT, cx->type, after,
irq_traced[0], irq_traced[1], irq_traced[2], irq_traced[3]);
/* Now back in C0. */
update_idle_stats(power, cx, before, after);
local_irq_enable();
if (!(lapic_timer_reliable_states & (1 << cstate)))
lapic_timer_on();
sched_tick_resume();
cpufreq_dbs_timer_resume();
if ( cpuidle_current_governor->reflect )
cpuidle_current_governor->reflect(power);
}
static void auto_demotion_disable(void *dummy)
{
u64 msr_bits;
rdmsrl(MSR_NHM_SNB_PKG_CST_CFG_CTL, msr_bits);
msr_bits &= ~(icpu->auto_demotion_disable_flags);
wrmsrl(MSR_NHM_SNB_PKG_CST_CFG_CTL, msr_bits);
}
static void byt_auto_demotion_disable(void *dummy)
{
wrmsrl(MSR_CC6_DEMOTION_POLICY_CONFIG, 0);
wrmsrl(MSR_MC6_DEMOTION_POLICY_CONFIG, 0);
}
static void c1e_promotion_disable(void *dummy)
{
u64 msr_bits;
rdmsrl(MSR_IA32_POWER_CTL, msr_bits);
msr_bits &= ~0x2;
wrmsrl(MSR_IA32_POWER_CTL, msr_bits);
}
static const struct idle_cpu idle_cpu_nehalem = {
.state_table = nehalem_cstates,
.auto_demotion_disable_flags = NHM_C1_AUTO_DEMOTE | NHM_C3_AUTO_DEMOTE,
.disable_promotion_to_c1e = 1,
};
static const struct idle_cpu idle_cpu_atom = {
.state_table = atom_cstates,
};
static const struct idle_cpu idle_cpu_lincroft = {
.state_table = atom_cstates,
.auto_demotion_disable_flags = ATM_LNC_C6_AUTO_DEMOTE,
};
static const struct idle_cpu idle_cpu_snb = {
.state_table = snb_cstates,
.disable_promotion_to_c1e = 1,
};
static const struct idle_cpu idle_cpu_byt = {
.state_table = byt_cstates,
.disable_promotion_to_c1e = 1,
.byt_auto_demotion_disable_flag = 1,
};
static const struct idle_cpu idle_cpu_cht = {
.state_table = cht_cstates,
.disable_promotion_to_c1e = 1,
.byt_auto_demotion_disable_flag = 1,
};
static const struct idle_cpu idle_cpu_ivb = {
.state_table = ivb_cstates,
.disable_promotion_to_c1e = 1,
};
static const struct idle_cpu idle_cpu_ivt = {
.state_table = ivt_cstates,
.disable_promotion_to_c1e = 1,
};
static const struct idle_cpu idle_cpu_hsw = {
.state_table = hsw_cstates,
.disable_promotion_to_c1e = 1,
};
static const struct idle_cpu idle_cpu_bdw = {
.state_table = bdw_cstates,
.disable_promotion_to_c1e = 1,
};
static const struct idle_cpu idle_cpu_avn = {
.state_table = avn_cstates,
.disable_promotion_to_c1e = 1,
};
#define ICPU(model, cpu) \
{ X86_VENDOR_INTEL, 6, model, X86_FEATURE_MWAIT, \
&idle_cpu_##cpu}
static const struct x86_cpu_id intel_idle_ids[] __initconst = {
ICPU(0x1a, nehalem),
ICPU(0x1e, nehalem),
ICPU(0x1f, nehalem),
ICPU(0x25, nehalem),
ICPU(0x2c, nehalem),
ICPU(0x2e, nehalem),
ICPU(0x2f, nehalem),
ICPU(0x1c, atom),
ICPU(0x26, lincroft),
ICPU(0x2a, snb),
ICPU(0x2d, snb),
ICPU(0x36, atom),
ICPU(0x37, byt),
ICPU(0x4c, cht),
ICPU(0x3a, ivb),
ICPU(0x3e, ivt),
ICPU(0x3c, hsw),
ICPU(0x3f, hsw),
ICPU(0x45, hsw),
ICPU(0x46, hsw),
ICPU(0x4d, avn),
ICPU(0x3d, bdw),
ICPU(0x47, bdw),
ICPU(0x4f, bdw),
ICPU(0x56, bdw),
{}
};
/*
* mwait_idle_state_table_update()
*
* Update the default state_table for this CPU-id
*
* Currently used to access tuned IVT multi-socket targets
* Assumption: num_sockets == (max_package_num + 1)
*/
static void __init mwait_idle_state_table_update(void)
{
/* IVT uses a different table for 1-2, 3-4, and > 4 sockets */
if (boot_cpu_data.x86_model == 0x3e) { /* IVT */
unsigned int cpu, max_apicid = boot_cpu_physical_apicid;
for_each_present_cpu(cpu)
if (max_apicid < x86_cpu_to_apicid[cpu])
max_apicid = x86_cpu_to_apicid[cpu];
switch (apicid_to_socket(max_apicid)) {
case 0: case 1:
/* 1 and 2 socket systems use default ivt_cstates */
break;
case 2: case 3:
cpuidle_state_table = ivt_cstates_4s;
break;
default:
cpuidle_state_table = ivt_cstates_8s;
break;
}
}
}
static int __init mwait_idle_probe(void)
{
unsigned int eax, ebx, ecx;
const struct x86_cpu_id *id = x86_match_cpu(intel_idle_ids);
if (!id) {
pr_debug(PREFIX "does not run on family %d model %d\n",
boot_cpu_data.x86, boot_cpu_data.x86_model);
return -ENODEV;
}
if (boot_cpu_data.cpuid_level < CPUID_MWAIT_LEAF)
return -ENODEV;
cpuid(CPUID_MWAIT_LEAF, &eax, &ebx, &ecx, &mwait_substates);
if (!(ecx & CPUID5_ECX_EXTENSIONS_SUPPORTED) ||
!(ecx & CPUID5_ECX_INTERRUPT_BREAK) ||
!mwait_substates)
return -ENODEV;
if (!max_cstate || no_mwait_idle) {
pr_debug(PREFIX "disabled\n");
return -EPERM;
}
pr_debug(PREFIX "MWAIT substates: %#x\n", mwait_substates);
icpu = id->driver_data;
cpuidle_state_table = icpu->state_table;
if (boot_cpu_has(X86_FEATURE_ARAT))
lapic_timer_reliable_states = LAPIC_TIMER_ALWAYS_RELIABLE;
pr_debug(PREFIX "v" MWAIT_IDLE_VERSION " model %#x\n",
boot_cpu_data.x86_model);
pr_debug(PREFIX "lapic_timer_reliable_states %#x\n",
lapic_timer_reliable_states);
mwait_idle_state_table_update();
return 0;
}
static int mwait_idle_cpu_init(struct notifier_block *nfb,
unsigned long action, void *hcpu)
{
unsigned int cpu = (unsigned long)hcpu, cstate;
struct acpi_processor_power *dev = processor_powers[cpu];
switch (action) {
default:
return NOTIFY_DONE;
case CPU_UP_PREPARE:
cpuidle_init_cpu(cpu);
return NOTIFY_DONE;
case CPU_ONLINE:
if (!dev)
return NOTIFY_DONE;
break;
}
dev->count = 1;
for (cstate = 0; cpuidle_state_table[cstate].target_residency; ++cstate) {
unsigned int num_substates, hint, state;
struct acpi_processor_cx *cx;
hint = flg2MWAIT(cpuidle_state_table[cstate].flags);
state = MWAIT_HINT2CSTATE(hint) + 1;
if (state > max_cstate) {
printk(PREFIX "max C-state %u reached\n", max_cstate);
break;
}
/* Number of sub-states for this state in CPUID.MWAIT. */
num_substates = (mwait_substates >> (state * 4))
& MWAIT_SUBSTATE_MASK;
/* If NO sub-states for this state in CPUID, skip it. */
if (num_substates == 0)
continue;
if (dev->count >= ACPI_PROCESSOR_MAX_POWER) {
printk(PREFIX "max C-state count of %u reached\n",
ACPI_PROCESSOR_MAX_POWER);
break;
}
if (state > 2 && !boot_cpu_has(X86_FEATURE_NONSTOP_TSC) &&
!pm_idle_save)
setup_clear_cpu_cap(X86_FEATURE_TSC_RELIABLE);
cx = dev->states + dev->count;
cx->type = state;
cx->address = hint;
cx->entry_method = ACPI_CSTATE_EM_FFH;
cx->latency = cpuidle_state_table[cstate].exit_latency;
cx->target_residency =
cpuidle_state_table[cstate].target_residency;
dev->count++;
}
if (icpu->auto_demotion_disable_flags)
on_selected_cpus(cpumask_of(cpu), auto_demotion_disable, NULL, 1);
if (icpu->byt_auto_demotion_disable_flag)
on_selected_cpus(cpumask_of(cpu), byt_auto_demotion_disable, NULL, 1);
if (icpu->disable_promotion_to_c1e)
on_selected_cpus(cpumask_of(cpu), c1e_promotion_disable, NULL, 1);
return NOTIFY_DONE;
}
int __init mwait_idle_init(struct notifier_block *nfb)
{
int err;
if (pm_idle_save)
return -ENODEV;
err = mwait_idle_probe();
if (!err && !boot_cpu_has(X86_FEATURE_ARAT)) {
hpet_broadcast_init();
if (xen_cpuidle < 0 && !hpet_broadcast_is_available())
err = -ENODEV;
else if(!lapic_timer_init())
err = -EINVAL;
if (err)
pr_debug(PREFIX "not used (%d)\n", err);
}
if (!err) {
nfb->notifier_call = mwait_idle_cpu_init;
mwait_idle_cpu_init(nfb, CPU_UP_PREPARE, NULL);
pm_idle_save = pm_idle;
pm_idle = mwait_idle;
dead_idle = acpi_dead_idle;
}
return err;
}
| 23.175166 | 85 | 0.689103 | [
"model"
] |
07df0645153ac1946a45d36fc15d53bf46f456d3 | 768 | h | C | dev/g++/ifsttar/wifiMapping/aggreg/include/txtStorage.h | YannGarcia/repo | 0f3de24c71d942c752ada03c10861e83853fdf71 | [
"MIT"
] | null | null | null | dev/g++/ifsttar/wifiMapping/aggreg/include/txtStorage.h | YannGarcia/repo | 0f3de24c71d942c752ada03c10861e83853fdf71 | [
"MIT"
] | null | null | null | dev/g++/ifsttar/wifiMapping/aggreg/include/txtStorage.h | YannGarcia/repo | 0f3de24c71d942c752ada03c10861e83853fdf71 | [
"MIT"
] | 1 | 2017-01-27T12:53:50.000Z | 2017-01-27T12:53:50.000Z | #if !defined(__TXTSTORAGE_H__)
#define __TXTSTORAGE_H__
#include <iostream>
#include <fstream>
#include <memory> // Used for unique_ptr
#include <vector>
#include "abstractStorage.h"
namespace beagleboneStorage {
class txtStorage : public abstractStorage {
std::ofstream _file;
std::string _storageDevice;
public:
txtStorage();
~txtStorage();
virtual int initialize(const std::string & p_storageDevice);
virtual int uninitialize();
virtual int open();
virtual void close();
virtual void store(const std::vector<unsigned char> & p_data);
virtual void store(const datum & p_datum);
}; // End of class txtStorage
} // End of namespace beagleboneStorage
using namespace beagleboneStorage;
#endif // __TXTSTORAGE_H__
| 21.942857 | 66 | 0.721354 | [
"vector"
] |
07e0b14477d41e6ef9aee82215787be27fc76da6 | 10,460 | c | C | old files/Simulink kopier/simulink/Old/NLPID_nidll_vxworks_rtw/NLPID_data.c | eliasga/CS_EnterpriseI_archive | fff170b4c31fc25648eea80af99a1c8f79c3a036 | [
"MIT"
] | null | null | null | old files/Simulink kopier/simulink/Old/NLPID_nidll_vxworks_rtw/NLPID_data.c | eliasga/CS_EnterpriseI_archive | fff170b4c31fc25648eea80af99a1c8f79c3a036 | [
"MIT"
] | null | null | null | old files/Simulink kopier/simulink/Old/NLPID_nidll_vxworks_rtw/NLPID_data.c | eliasga/CS_EnterpriseI_archive | fff170b4c31fc25648eea80af99a1c8f79c3a036 | [
"MIT"
] | 3 | 2020-01-23T10:01:04.000Z | 2021-02-02T09:44:41.000Z | /*
* NLPID_data.c
*
* Real-Time Workshop code generation for Simulink model "NLPID.mdl".
*
* Model Version : 1.31
* Real-Time Workshop version : 7.3 (R2009a) 15-Jan-2009
* C source code generated on : Mon Mar 17 14:06:18 2014
*
* Target selection: nidll_vxworks.tlc
* Note: GRT includes extra infrastructure and instrumentation for prototyping
* Embedded hardware selection: 32-bit Generic
* Code generation objectives: Unspecified
* Validation result: Not run
*/
#include "NLPID.h"
#include "NLPID_private.h"
/* Block parameters (auto storage) */
Parameters_NLPID NLPID_P = {
0.0,
9.0,
1.0,
1.0,
-1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
0.001,
1.0,
0.001,
1.0,
1.7453292519943295E-002,
0.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.7453292519943295E-002,
1.0,
1.7453292519943295E-002,
{ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 },
1.0,
0.001,
1.0,
1.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.7453292519943295E-002,
1.0,
0.0,
0.0,
0.0,
5.5,
0.0,
2.0,
0.0,
0.0,
5.5,
0.0,
0.0,
3.4906585039886591E-002,
-1.0,
2.0,
1.0,
5.7295779513082323E+001,
1.0E+010,
-1.0E+010,
180.0,
360.0,
1.7453292519943295E-002,
5.7295779513082323E+001,
1.0E+010,
-1.0E+010,
180.0,
360.0,
1.7453292519943295E-002,
10000.0,
4.5,
0.0,
1.0,
-10000.0,
10000.0,
-10000.0,
2.0,
5.7295779513082323E+001,
1.0E+010,
-1.0E+010,
180.0,
360.0,
1.7453292519943295E-002,
5.7295779513082323E+001,
1.0E+010,
-1.0E+010,
180.0,
360.0,
1.7453292519943295E-002,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
0.15,
1.0,
0.0,
0.0,
3.0518509475997192E-005,
1.0,
0.0,
3.0518509475997192E-005,
1.0,
0.0,
3.0518509475997192E-005,
1.0,
0.0,
3.0518509475997192E-005,
1.0,
0.0,
0.0,
1.0,
0.0,
0.0,
1.0,
0.0,
0.055,
0.0,
1.0,
0.45,
-1.0,
1.0,
0.0,
0.055,
-1.0,
0.0,
1.0,
0.45,
-1.0,
0.0,
1.0,
0.385,
1.0E+010,
-1.0E+010,
3.1415926535897931E+000,
6.2831853071795862E+000,
1.0E+010,
-1.0E+010,
3.1415926535897931E+000,
6.2831853071795862E+000,
{ 2.5800000000000006E-001, 0.0, 0.0, 0.0, 0.338, 1.0115000000000002E-002, 0.0,
1.0115000000000002E-002, 2.7600000000000003E-002 },
1.0,
1.0,
1.0,
0.0,
0.0,
{ 2.5800000000000007E-003, 0.0, 0.0, 0.0, 0.00338, 1.0115000000000002E-004,
0.0, 1.0115000000000002E-004, 2.7600000000000004E-004 },
1.0,
1.0,
1.0,
{ 4.1280000000000010E+000, 0.0, 0.0, 0.0, 5.408, 1.6184000000000004E-001, 0.0,
1.6184000000000004E-001, 4.4160000000000005E-001 },
1.0,
1.0,
1.0,
-0.001,
0.001,
0.0,
0.0,
{ -1.324, -1.169, -0.919, -0.703, -0.535, -0.292, -0.165, -0.06, 0.0 },
{ -1.0, -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2089 },
0.0,
{ 0.0, 0.051, 0.153, 0.308, 0.48, 0.663, 0.911, 1.057, 1.221, 1.374 },
{ 0.05, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9 },
-0.001,
0.001,
0.0,
0.0,
0.0,
{ -0.766, -0.649, -0.522, -0.411, -0.323, -0.246, -0.156, -0.075, -0.018,
-0.006, 0.0 },
{ -1.0, -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1, -0.0466 },
0.0,
{ 0.0, 0.052, 0.207, 0.331, 0.509, 0.689, 0.829, 0.961, 1.079, 1.12 },
{ 0.1665, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0 },
-0.001,
0.001,
0.0,
0.0,
{ -1.291, -1.088, -0.885, -0.618, -0.403, -0.211, -0.034, 0.0 },
{ -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2809 },
0.0,
{ 0.0, 0.014, 0.04, 0.147, 0.302, 0.494, 0.68, 0.968, 1.111, 1.289, 1.339 },
{ 0.0452, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0 },
-0.001,
0.001,
0.0,
0.0,
{ -1.249, -1.225, -1.094, -0.896, -0.696, -0.502, -0.314, -0.169, -0.042, 0.0
},
{ -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1, -0.0674 },
0.0,
{ 0.0, 0.063, 0.107, 0.274, 0.441, 0.599, 0.731 },
{ 0.3588, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0 },
-0.001,
0.001,
0.0,
0.0,
{ -1.263, -1.0309, -0.3808 },
{ -0.3, -0.2, -0.1 },
0.0,
{ 0.348, 0.829, 1.093 },
{ 0.1, 0.2, 0.3 },
1.0,
-1.0,
0.5,
0.4,
1.0,
0.0,
0.055,
0.0,
1.0,
0.45,
-1.0,
1.0,
0.0,
0.055,
-1.0,
0.0,
1.0,
0.45,
-1.0,
0.0,
1.0,
0.385,
0.0,
0.0,
0.0,
0.0,
1.0,
1.5,
0.0,
0.0,
0.0,
0.8,
0.0,
0.0,
0.0,
4.5,
5.7295779513082323E+001,
1.0E+010,
-1.0E+010,
180.0,
360.0,
1.7453292519943295E-002,
5.7295779513082323E+001,
1.0E+010,
-1.0E+010,
180.0,
360.0,
1.7453292519943295E-002,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
4.0,
0.0,
0.0,
0.0,
50.0,
0.0,
0.0,
0.0,
8.0,
-1.0,
{ 0.0, 0.0 },
0.0,
3.0,
-1.0,
1.0,
10.0,
-1.0,
-0.59739,
-1.0,
0.0,
0.0,
0.0,
-3.50625,
-1.0,
0.1814,
-1.0,
0.0,
-7.25,
-1.0,
-1.9,
-1.0,
17.6,
-2.0,
0.0,
0.0,
0.0,
-10.0,
0.03,
0.0,
0.0,
0.0,
1.76,
-1.0,
-1.0,
2.0,
{ 0.0, 0.0, 0.0, 0.0 },
{ 0.0, 0.0, 0.0, 0.0 },
2.0,
1.5,
-1.0,
0.0,
-1.0,
{ 0.0, 0.0 },
-1.0,
-1.0,
1.0,
2.0,
2.0,
2.0,
1.0,
3.0,
-1.0,
1.5,
3.0,
{ 0.0, 0.0 },
0.0,
0.0,
1.0,
0.0,
0.0,
0.0,
0.0,
1.0,
1.0,
-0.001,
0.001,
0.0,
0.0,
{ -1.324, -1.169, -0.919, -0.703, -0.535, -0.292, -0.165, -0.06, 0.0 },
{ -1.0, -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2089 },
0.0,
{ 0.0, 0.051, 0.153, 0.308, 0.48, 0.663, 0.911, 1.057, 1.221, 1.374 },
{ 0.05, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9 },
-0.001,
0.001,
0.0,
0.0,
0.0,
{ -0.766, -0.649, -0.522, -0.411, -0.323, -0.246, -0.156, -0.075, -0.018,
-0.006, 0.0 },
{ -1.0, -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1, -0.0466 },
0.0,
{ 0.0, 0.052, 0.207, 0.331, 0.509, 0.689, 0.829, 0.961, 1.079, 1.12 },
{ 0.1665, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0 },
-0.001,
0.001,
0.0,
0.0,
{ -1.291, -1.088, -0.885, -0.618, -0.403, -0.211, -0.034, 0.0 },
{ -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2809 },
0.0,
{ 0.0, 0.014, 0.04, 0.147, 0.302, 0.494, 0.68, 0.968, 1.111, 1.289, 1.339 },
{ 0.0452, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0 },
-0.001,
0.001,
0.0,
0.0,
{ -1.249, -1.225, -1.094, -0.896, -0.696, -0.502, -0.314, -0.169, -0.042, 0.0
},
{ -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1, -0.0674 },
0.0,
{ 0.0, 0.063, 0.107, 0.274, 0.441, 0.599, 0.731 },
{ 0.3588, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0 },
-0.001,
0.001,
0.0,
0.0,
{ -1.263, -1.0309, -0.3808 },
{ -0.3, -0.2, -0.1 },
0.0,
{ 0.348, 0.829, 1.093 },
{ 0.1, 0.2, 0.3 },
0.5,
0.4,
1.0,
-1.0,
1.0,
0.0,
0.055,
0.0,
1.0,
0.45,
-1.0,
1.0,
0.0,
0.055,
-1.0,
0.0,
1.0,
0.45,
-1.0,
0.0,
1.0,
0.385,
{ -1.0, -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2089, 0.05, 0.1, 0.2, 0.3,
0.4, 0.5, 0.6, 0.7, 0.8, 0.9 },
{ -1.324, -1.169, -0.919, -0.703, -0.535, -0.292, -0.165, -0.06, 0.0, 0.0,
0.051, 0.153, 0.308, 0.48, 0.663, 0.911, 1.057, 1.221, 1.374 },
{ -1.0, -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1, -0.0466, 0.1665,
0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0 },
{ -0.766, -0.649, -0.522, -0.411, -0.323, -0.246, -0.156, -0.075, -0.018,
-0.006, 0.0, 0.0, 0.052, 0.207, 0.331, 0.509, 0.689, 0.829, 0.961, 1.079,
1.12 },
{ -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2809, 0.0452, 0.1, 0.2, 0.3,
0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0 },
{ -1.291, -1.088, -0.885, -0.618, -0.403, -0.211, -0.034, 0.0, 0.0, 0.014,
0.04, 0.147, 0.302, 0.494, 0.68, 0.968, 1.111, 1.289, 1.339 },
{ -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1, -0.0674, 0.3588, 0.5,
0.6, 0.7, 0.8, 0.9, 1.0 },
{ -1.249, -1.225, -1.094, -0.896, -0.696, -0.502, -0.314, -0.169, -0.042, 0.0,
0.0, 0.063, 0.107, 0.274, 0.441, 0.599, 0.731 },
{ -0.3, -1.9999999999999998E-001, -9.9999999999999978E-002, 0.0,
9.9999999999999978E-002, 1.9999999999999998E-001, 0.3 },
{ -1.263, -1.0309, -0.3808, 0.0, 0.348, 0.829, 1.093 },
0.0,
0.0,
0.05,
0.8,
2.0,
{ 1.0, 0.0, 0.0, 1.0 },
-1.0,
{ 0.0, 0.0 },
-1.0,
1.0,
1.0,
-1.0,
1.0,
1.0,
1.0,
-1.0,
1.0,
2.0,
-1.0,
1.0,
1.0,
1.0,
-1.0,
1.0,
3.0,
-1.0,
1.0,
1.0,
2.0,
1.0,
3.0,
-2.6,
3.0,
-3.5,
1.6,
-1.5,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
0.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
-1.0,
1.0,
0.0,
-1.0,
0.0,
-1.0,
-1.0,
1.0,
1.0,
-1.0,
1.0,
0.0,
0.02,
0.05,
0.02,
0.02,
-0.02,
0.05,
0.05,
0.0,
0.0,
-1.0,
-1.0,
1.0,
1.0,
-1.0,
1.0,
0.0,
-1.0,
1.0,
2.0,
-1.0,
1.0,
0.0,
-1.0,
1.0,
3.0,
-1.0,
1.0,
0.0,
-1.0,
1.0,
4.0,
-1.0,
1.0,
0.0,
-1.0,
1.0,
5.0,
-1.0,
1.0,
0.0,
-1.0,
1.0,
6.0,
-1.0,
1.0,
0.0,
-1.0,
-1.0,
{ -1.0, 0.0, 1.0 },
{ -1.0, 0.0, 1.0 },
{ 0.06, 0.0495363, 0.043301, 0.06, 0.052446, 0.043301, 0.06, 0.0541518,
0.043301 },
{ -1.0, 0.0, 1.0 },
{ -1.0, 0.0, 1.0 },
{ 0.0386088, 0.0386088, 0.0386088, 0.0459941, 0.0477243, 0.0500953, 0.057,
0.057, 0.057 },
{ -1.0, 0.0, 1.0 },
{ -1.0, 0.0, 1.0 },
{ 0.0640809, 0.0640809, 0.0640809, 0.0539629, 0.0541315, 0.0556492, 0.0442664,
0.0442664, 0.0442664 },
{ -1.0, 0.0, 1.0 },
{ -1.0, 0.0, 1.0 },
{ 0.0602867, 0.0470489, 0.0403879, 0.0602867, 0.049747, 0.0403879, 0.0602867,
0.0526138, 0.0403879 },
-0.02,
0.05,
1.0,
1.0,
-1.9,
-1.0,
0.1814,
-1.0,
-0.59739,
-1.0,
-3.50625,
-1.0,
-7.25,
-1.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
1.76,
17.6,
-2.0,
0.0,
0.0,
0.0,
-10.0,
0.03,
0.0,
0.0,
0.0,
-1.0,
0.0,
0.0,
0.0,
0.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
128U,
192U,
128U,
192U,
128U,
192U,
128U,
192U,
128U,
192U,
128U,
192U,
128U,
192U,
128U,
192U,
128U,
192U,
128U,
192U
};
/* Constant parameters (auto storage) */
const ConstParam_NLPID NLPID_ConstP = {
/* Computed Parameter: INDEX_ARRAY_FLAT
* Referenced by blocks:
* '<S127>/Multiport Selector'
* '<S127>/Multiport Selector1'
* '<S127>/Multiport Selector2'
* '<S127>/Multiport Selector3'
* '<S127>/Multiport Selector4'
*/
1
};
| 14.116059 | 81 | 0.447801 | [
"model"
] |
35b366040bc78bfff71fdd5629e7d62808ca516c | 12,155 | h | C | kernel/src/sched/Thread.h | tristanseifert/kush-os | 1ffd595aae8f3dc880e798eff72365b8b6c631f0 | [
"0BSD"
] | 4 | 2021-06-22T20:52:30.000Z | 2022-02-04T00:19:44.000Z | kernel/src/sched/Thread.h | tristanseifert/kush-os | 1ffd595aae8f3dc880e798eff72365b8b6c631f0 | [
"0BSD"
] | null | null | null | kernel/src/sched/Thread.h | tristanseifert/kush-os | 1ffd595aae8f3dc880e798eff72365b8b6c631f0 | [
"0BSD"
] | null | null | null | #ifndef KERN_SCHED_THREAD_H
#define KERN_SCHED_THREAD_H
#include <stddef.h>
#include <stdint.h>
#include <runtime/List.h>
#include <runtime/Queue.h>
#include <runtime/Vector.h>
#include <runtime/SmartPointers.h>
#include <handle/Manager.h>
#include <arch/ThreadState.h>
#include <arch/rwlock.h>
#include "SchedulerData.h"
namespace ipc {
class IrqHandler;
}
namespace sched {
class Blockable;
class SignalFlag;
struct Task;
struct BlockWait;
/**
* Threads are the smallest units of execution in the kernel. They are the unit of work that the
* scheduler concerns itself with.
*
* Each thread can either be ready to run, blocked, or paused. When the scheduler decides to run
* the thread, its saved CPU state is loaded and the task executed. When the task returns to the
* kernel (either through a syscall that blocks/context switches, or via its time quantum expiring)
* its state is saved again.
*
* Depending on the nature of the thread's return to the kernel, it will be added back to the run
* queue if it's ready to run again and not blocked. (This implies threads cannot change from
* runnable to blocked if they're not currently executing.)
*/
struct Thread: public rt::SharedFromThis<Thread> {
friend class Scheduler;
friend class Blockable;
friend class IdleWorker;
friend struct BlockWait;
/// Length of thread names
constexpr static const size_t kNameLength = 32;
private:
/// why a block returned
enum class BlockState {
None = 0,
/// Currently blocking
Blocking = 1,
/// The blocking condition(s) were signalled
Unblocked = 2,
/// The block was timed, and the timeout has expired
Timeout = 3,
/// One of the blockables aborted the attempt to go to sleep
Aborted = 4,
};
public:
enum class State {
/// Thread can become runnable at any time, but only via an explicit API call
Paused = 0,
/// Thread requests to be scheduled as soon as possible
Runnable = 1,
/// Thread is waiting on some event to occur
Blocked = 2,
/// Blocked on sleep (may end early)
Sleeping = 3,
/// Waiting for notification
NotifyWait = 4,
/// About to be destroyed; do not schedule or access.
Zombie = 5,
};
/// return codes for blockOn
enum class BlockOnReturn {
/// Unknown error
Error = -1,
/// thread unblocked
Unblocked = 0,
/// block timed out
Timeout = 1,
/// block aborted
Aborted = 2,
};
/**
* Defines the types of faults that a thread may receive. These are synchronous-ish events
* generated by the processor, indicating events such as an illegal opcode, or invalid math
* operation.
*/
enum class FaultType {
/// General fault; this always terminates the task this thread is in
General = 0,
/// The instruction executed is invalid; context is pointer to the pc in exc frame
InvalidInstruction = 1,
/// A page fault was unhandled (pc = faulting address; context = pc exception frame)
UnhandledPagefault = 2,
/// Protection violation
ProtectionViolation = 3,
};
public:
/// Global thread id
uintptr_t tid = 0;
/// task that owns us
rt::SharedPtr<Task> task = nullptr;
/// when set, we're attached to the given task
bool attachedToTask = false;
/// handle to the thread
Handle handle;
/// descriptive thread name, if desired
char name[kNameLength] = {0};
/// current thread state
State state = State::Paused;
/**
* Threads marked as kernel mode are treated a bit specially by the scheduler, in that
* only kernel threads may be placed in the highest priority run queues.
*/
bool kernelMode = false;
/**
* Flag set when the scheduler has assigned the thread to a processor and it is executing;
* it will be cleared immediately after the thread is switched out.
*
* This flag is the responsibility of the arch context switching code.
*/
bool isActive = false;
/// when set, this thread should kill itself when switched out
bool needsToDie = false;
/// Timestamp at which the thread was switched to
uint64_t lastSwitchedTo = 0;
/// number of the last syscall this thread performed
uintptr_t lastSyscall = UINTPTR_MAX;
/// scheduler data
SchedulerThreadData sched;
/**
* Priority of the thread; this should be a value between -100 and 100, with negative
* values having the lowest priority. The scheduler internally converts this to whatever
* priority system it uses.
*/
int16_t priority = 0;
/**
* Notification value and mask for the thread.
*
* Notifications are an asynchronous signalling mechanism that can be used to signal a
* thread that a paritcular event occurred, without any additional auxiliary information;
* this makes it ideal for things like interrupt handlers.
*
* Each thread defines a notification mask, which indicates on which bits (set) of the
* notification set the thread is interested in; when the notification mask is updated, it
* is compared against the mask, and if any bits are set, the thread can be unblocked.
*/
uintptr_t notifications = 0;
uintptr_t notificationMask = 0;
/// Set once a thread has moved from NotifyWait to possibly runnable
bool notified = false;
/**
* This counter is incremented any time the thread leaves the runnable state; it is used to
* detect when a deadline (or other unblock event) takes place yet the subject thread has
* changed state since then.
*
* In other words, when a deadline (or other object) fires, it should ensure the epoch
* value is the same as what it was when it began blocking.
*/
uintptr_t epoch = 0;
/**
* Objects this thread is currently blocking on
*/
rt::List<rt::SharedPtr<Blockable>> blockingOn;
/// Interrupt handlers owned by the thread; they're removed when we deallocate
rt::List<rt::SharedPtr<ipc::IrqHandler>> irqHandlers;
/**
* The thread can be accessed read-only by multiple processes, but the scheduler will
* always require write access, in order to be able to save processor state later.
*/
DECLARE_RWLOCK(lock);
/// notification flags to signal when terminating
rt::List<rt::SharedPtr<SignalFlag>> terminateSignals;
/// size of the thread's kernel stack (in bytes)
size_t stackSize = 0;
/// bottom of the kernel stack of this thread
void *stack = nullptr;
/// architecture-specific thread state
arch::ThreadState regs __attribute__((aligned(16)));
private:
/// whether we're blocking and why the block finished
BlockState blockState = BlockState::None;
public:
/// Allocates a new kernel thread
static rt::SharedPtr<Thread> kernelThread(const rt::SharedPtr<Task> &task,
void (*entry)(uintptr_t), const uintptr_t param = 0);
/// Allocates a new userspace thread
static rt::SharedPtr<Thread> userThread(const rt::SharedPtr<Task> &task,
void (*entry)(uintptr_t), const uintptr_t param = 0);
Thread(const rt::SharedPtr<Task> &task, const uintptr_t pc, const uintptr_t param,
const bool kernelThread = false);
~Thread();
/// Context switches to this thread.
void switchTo();
/// Returns to user mode, with the specified program counter and stack.
void returnToUser(const uintptr_t pc, const uintptr_t stack, const uintptr_t arg = 0) __attribute__((noreturn));
/// Updates the notification mask; set bits are unmasked (i.e. will occur)
inline void setNotificationMask(uintptr_t newMask) {
__atomic_store(&this->notificationMask, &newMask, __ATOMIC_RELEASE);
}
/// Return thread handle
constexpr auto getHandle() const {
return this->handle;
}
/// Sets the thread's name.
void setName(const char *name, const size_t length = 0);
/// Sets the thread's scheduling priority
inline void setPriority(int16_t priority) {
__atomic_store(&this->priority, &priority, __ATOMIC_RELEASE);
}
/// Sets the thread's state.
void setState(State newState) {
if(this->state == State::Blocked && newState == State::Runnable) {
REQUIRE(this->blockingOn.empty(), "cannot be runnable while blocking");
}
__atomic_store(&this->state, &newState, __ATOMIC_RELEASE);
}
/// Atomically reads the current state.
const State getState() const {
State s;
__atomic_load(&this->state, &s, __ATOMIC_RELAXED);
return s;
}
/// Blocks the thread on the given object.
BlockOnReturn blockOn(const rt::SharedPtr<Blockable> &b, const uint64_t until = 0);
/// Unblocks the thread due to the given blockable
void unblock(const rt::SharedPtr<Blockable> &b);
/// Sets the given notification bits.
void notify(const uintptr_t bits);
/// Blocks the thread waiting to receive notifications, optionally with a mask.
uintptr_t blockNotify(const uintptr_t mask = 0, const uintptr_t timeout = UINTPTR_MAX);
/// Waits for the thread to be terminated.
int waitOn(const uint64_t waitUntil = 0);
/// Terminates this thread.
void terminate(const bool release = true, const bool inIsr = false);
/// Handles a fault of the given type. Called from fault handlers.
void handleFault(const FaultType type, const uintptr_t pc, void *context, const void *arch);
/// Returns a handle to the currently executing thread.
static rt::SharedPtr<Thread> current();
/// Blocks the current thread for the given number of nanoseconds.
static void sleep(const uint64_t nanos);
/// Give up the rest of this thread's CPU time
static void yield();
/// Terminates the calling thread
static void die() __attribute__((noreturn));
private:
/// next thread id
static uintptr_t nextTid;
/// whether creation/deallocation of threads is logged
static bool gLogLifecycle;
private:
/// Called when this thread is switching out
void switchFrom();
/// Called on context switch out to complete termination.
void deferredTerminate();
/// Invoke all termination handlers
void callTerminators();
/// scheduler is attempting to determine if thread should be runnable again
void schedTestUnblock();
/// any pending blocks should be cancelled
void blockExpired();
/// set thread state with optionally idsabling validation
void setState(State newState, const bool validate) {
if(validate) {
return this->setState(newState);
}
__atomic_store(&this->state, &newState, __ATOMIC_RELEASE);
}
};
}
#endif
| 38.22327 | 120 | 0.603209 | [
"object",
"vector"
] |
35b6cfb23e918d332aba5330fd4e33b51a67a7b0 | 2,801 | h | C | SRDownloadManager/SRDownloadManager.h | ihomelp07/SRDownloadManager | 3397ea6c45c6505f189f508674c30dbf72761ab6 | [
"MIT"
] | 249 | 2017-01-19T15:18:17.000Z | 2022-02-02T14:33:07.000Z | SRDownloadManager/SRDownloadManager.h | ihomelp07/SRDownloadManager | 3397ea6c45c6505f189f508674c30dbf72761ab6 | [
"MIT"
] | 21 | 2017-02-20T11:13:50.000Z | 2021-01-15T04:35:45.000Z | SRDownloadManager/SRDownloadManager.h | ihomelp07/SRDownloadManager | 3397ea6c45c6505f189f508674c30dbf72761ab6 | [
"MIT"
] | 49 | 2017-01-22T02:28:50.000Z | 2020-04-30T05:48:36.000Z | //
// SRDownloadManager.h
// SRDownloadManager
//
// Created by https://github.com/guowilling on 17/1/10.
// Copyright © 2017年 SR. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "SRDownloadModel.h"
typedef NS_ENUM(NSInteger, SRWaitingQueueMode) {
SRWaitingQueueModeFIFO,
SRWaitingQueueModeLIFO
};
@interface SRDownloadManager : NSObject
/**
The directory where downloaded files are cached, default is .../Library/Caches/SRDownloadManager if not setted.
*/
@property (nonatomic, copy) NSString *cacheFilesDirectory;
/**
The count of max concurrent downloads, default is -1 which means no limit.
*/
@property (nonatomic, assign) NSInteger maxConcurrentCount;
/**
The mode of waiting download queue, default is FIFO.
*/
@property (nonatomic, assign) SRWaitingQueueMode waitingQueueMode;
+ (instancetype)sharedManager;
/**
Starts a file download action with URL, download state, download progress and download completion block.
@param URL The URL of the file which to be downloaded.
@param destPath The path to save the file after the download is completed, if pass nil file will be saved in default path.
@param state A block object to be executed when the download state changed.
@param progress A block object to be executed when the download progress changed.
@param completion A block object to be executed when the download completion.
*/
- (void)download:(NSURL *)URL
destPath:(NSString *)destPath
state:(void (^)(SRDownloadState state))state
progress:(void (^)(NSInteger receivedSize, NSInteger expectedSize, CGFloat progress))progress
completion:(void (^)(BOOL success, NSString *filePath, NSError *error))completion;
- (BOOL)isDownloadCompletedOfURL:(NSURL *)URL;
#pragma mark - Downloads
/**
Suspend the download of the URL.
*/
- (void)suspendDownloadOfURL:(NSURL *)URL;
/**
Suspend all downloads include which are downloading and waiting.
*/
- (void)suspendDownloads;
/**
Resume the download of the URL.
*/
- (void)resumeDownloadOfURL:(NSURL *)URL;
/**
Resume all downloads.
*/
- (void)resumeDownloads;
/**
Cancle the download of the URL.
*/
- (void)cancelDownloadOfURL:(NSURL *)URL;
/**
Cancle all downloads include which are downloading and waiting.
*/
- (void)cancelDownloads;
#pragma mark - Files
/**
The full path of the file corresponding to the URL cached in the sandbox.
*/
- (NSString *)fileFullPathOfURL:(NSURL *)URL;
/**
The progress of the file corresponding to the URL has been downloaded.
*/
- (CGFloat)hasDownloadedProgressOfURL:(NSURL *)URL;
/**
Delete the file of the URL in the current cache files directory.
*/
- (void)deleteFileOfURL:(NSURL *)URL;
/**
Delete all files in the current cache files directory.
*/
- (void)deleteFiles;
@end
| 25.935185 | 125 | 0.729025 | [
"object"
] |
35bf08e15f05dc038dbe542968d64c1c95103938 | 3,876 | h | C | src/modules/core/include/CodecEvalFramework.h | krejov100/DepthCodec | fced6980bbdb85e28fba19ee722b6955b4bed4dc | [
"Apache-2.0"
] | 2 | 2019-12-09T22:07:33.000Z | 2022-03-06T10:41:16.000Z | src/modules/core/include/CodecEvalFramework.h | krejov100/DepthCodec | fced6980bbdb85e28fba19ee722b6955b4bed4dc | [
"Apache-2.0"
] | 25 | 2018-08-13T22:28:43.000Z | 2018-09-18T16:30:20.000Z | src/modules/core/include/CodecEvalFramework.h | krejov100/DepthCodec | fced6980bbdb85e28fba19ee722b6955b4bed4dc | [
"Apache-2.0"
] | null | null | null | //
// Created by philip on 8/2/18.
//
#pragma once
#include <vector>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/serialization/shared_ptr.hpp>
#include <PinholeCameraIntrinsic.h>
#include "NamedTimer.h"
#include "opencv2/opencv.hpp"
#include "DataStream.hpp"
#include "iostream"
#include "DepthCodec.h"
#include "Frame.h"
#include "ImageError.h"
/// This is an interface for a compressable object
/// differnt datatypes will need to be compressed in differnt ways
/// template to IMAGE_TYPE with concept of image
void showCompressionArtifacts(const cv::Mat& original, const cv::Mat& compressed);
void showPointCloudCompression(const Frame& originalFrame, const Frame& compressedFrame);
class CompressionMetric{
public:
CompressionMetric(){}
NamedTimer compressionTimer;
NamedTimer decompressionTimer;
size_t originalSizeInBytes = 1;
size_t compressedSizeInBytes = 1;
float meanSquaredError = FLT_MAX;
float peakSignalToNoise = 0;
float pointCloudInlierRMS = FLT_MAX;
void printPerformance(std::ostream& ostream) const;
};
template<typename CODEC_TYPE, typename DATA_TYPE>
std::stringstream compress(std::shared_ptr<CODEC_TYPE> codec, const DATA_TYPE& example)
{
std::stringstream ss;
boost::archive::binary_oarchive bo(ss);
codec->compress(example);
bo << codec;
return ss;
}
template<>
std::stringstream compress(std::shared_ptr<IDepthCodec> codec, const Frame& example)
{
std::stringstream ss;
boost::archive::binary_oarchive bo(ss);
auto depthImage = example.getDepthImage();
codec->compress(depthImage);
bo << codec;
return ss;
}
template<typename CODEC_TYPE, typename DATA_TYPE>
void decompress(std::shared_ptr<CODEC_TYPE> codec, std::stringstream& ss, DATA_TYPE& rslt)
{
boost::archive::binary_iarchive bi(ss);
bi >> codec;
codec->decompress(rslt);
}
template<typename CODEC_TYPE, typename DATA_TYPE>
void compressAndDecompress(std::shared_ptr<CODEC_TYPE> codec, const DATA_TYPE& example, DATA_TYPE& rslt)
{
std::stringstream ss = compress(codec, example);
decompress(codec, ss, rslt);
}
// The CODEC_POLICY is templated as it may be depth based, requiring DATA_TYPE to be cv::Mat
// if its pointcloud based then it needs to be pcl::Pointcloud or open3d::Pointcloud
template<typename DATA_TYPE, typename CODEC_TYPE>
class CodecEvalFramework{
std::vector<CompressionMetric> results;
std::shared_ptr<CODEC_TYPE> mCodec;
public:
CodecEvalFramework(std::shared_ptr<CODEC_TYPE> codec):mCodec(codec){};
/// Todo Extract the visualisation to a seperate class
CompressionMetric evaluateCodecOnExample(const DATA_TYPE& example, bool showArtifacts=true)
{
CompressionMetric rslt;
rslt.originalSizeInBytes = example.total() * example.elemSize();
/// Evaluate Compression
rslt.compressionTimer = NamedTimer("Compression");
std::stringstream ss = compress(mCodec, example);
rslt.compressionTimer.endTimer();
/// Evaluate CompressedData https://stackoverflow.com/questions/4432793/size-of-stringstream
rslt.compressedSizeInBytes = ss.str().size();
/// Evaluate decompression
rslt.decompressionTimer = NamedTimer("Decompression");
DATA_TYPE decompressed;
decompress(mCodec, ss,decompressed);
rslt.decompressionTimer.endTimer();
/// Evaluate lossyness
rslt.meanSquaredError = MSE(example, decompressed);
rslt.peakSignalToNoise = PSNR(example, decompressed);
if(showArtifacts) {
showCompressionArtifacts(example, decompressed);
}
cv::imshow("sdf", decompressed);
return rslt;
};
CompressionMetric evaluateCodecOnPointCloud(std::shared_ptr<open3d::PointCloud> pc, bool showArtifacts=true){
}
};
| 31.008 | 113 | 0.72549 | [
"object",
"vector"
] |
35d6d3d5c740f843301522d24409fa12a8ab7480 | 58,394 | c | C | src/kehayden/linearSat/linearSat.c | diekhans/kent | f714d84de41a802085b997abac94bb1abab4bd7a | [
"IJG"
] | null | null | null | src/kehayden/linearSat/linearSat.c | diekhans/kent | f714d84de41a802085b997abac94bb1abab4bd7a | [
"IJG"
] | null | null | null | src/kehayden/linearSat/linearSat.c | diekhans/kent | f714d84de41a802085b997abac94bb1abab4bd7a | [
"IJG"
] | null | null | null | /* linearSat - assemble repeat regions such as centromeres from reads that have
* been parsed into various repeat monomer variants. Cycles of these variants tend to
* form higher order repeats. */
/* Copyright (C) 2013 The Regents of the University of California
* See README in this or parent directory for licensing information. */
#include "common.h"
#include "linefile.h"
#include "hash.h"
#include "options.h"
#include "dystring.h"
#include "dlist.h"
#include "obscure.h"
#include "errAbort.h"
/* Global vars - all of which can be set by command line options. */
int pseudoCount = 1;
int maxChainSize = 3;
int initialOutSize = 10000;
int maxOutSize;
int maxToMiss = 0;
boolean fullOnly = FALSE;
boolean betweens = FALSE;
void usage()
/* Explain usage and exit. */
{
errAbort(
"linearSat - create a linear projection of satellite arrays using the probablistic model\n"
"of HuRef satellite graphs based on Sanger style reads.\n"
"usage:\n"
" linearSat monomerFile.txt monomerOrder.txt output.txt\n"
"Where monomerFile is a list of reads with monomers parsed out, one read per\n"
"line, with the first word in the line being the read id and subsequent words the monomers\n"
"within the read. The monomerOrder.txt has one line per major monomer type with a word for\n"
"each variant. The lines are in the same order the monomers appear, with the last line\n"
"being followed in order by the first since they repeat. The output.txt contains one line\n"
"for each monomer in the output, just containing the monomer symbol.\n"
"options:\n"
" -size=N - Set max chain size, default %d\n"
" -fullOnly - Only output chains of size above\n"
" -chain=fileName - Write out word chain to file\n"
" -afterChain=fileName - Write out word chain after faux generation to file for debugging\n"
" -initialOutSize=N - Output this many words. Default %d\n"
" -maxOutSize=N - Expand output up to this many words if not all monomers output initially\n"
" -maxToMiss=N - How many monomers may be missing from output. Default %d \n"
" -pseudoCount=N - Add this number to observed quantities - helps compensate for what's not\n"
" observed. Default %d\n"
" -seed=N - Initialize random number with this seed for consistent results, otherwise\n"
" it will generate different results each time it's run.\n"
" -betweens - Add <m> lines in output that indicate level of markov model used join\n"
" -unsubbed=fileName - Write output before substitution of missing monomers to file\n"
, maxChainSize, initialOutSize, maxToMiss, pseudoCount
);
}
/* Command line validation table. */
static struct optionSpec options[] = {
{"size", OPTION_INT},
{"chain", OPTION_STRING},
{"afterChain", OPTION_STRING},
{"fullOnly", OPTION_BOOLEAN},
{"initialOutSize", OPTION_INT},
{"maxOutSize", OPTION_INT},
{"maxToMiss", OPTION_INT},
{"pseudoCount", OPTION_INT},
{"seed", OPTION_INT},
{"unsubbed", OPTION_STRING},
{"betweens", OPTION_BOOLEAN},
{NULL, 0},
};
/* Some structures to keep track of words (which correspond to satellight monomers)
* seen in input. */
struct monomer
/* Basic information on a monomer including how many times it is seen in input and output
* streams. Unlike the wordTree, this is flat, and does not include predecessors. */
{
struct monomer *next; /* Next in list of all words. */
char *word; /* The word used to represent monomer. Not allocated here. */
int useCount; /* Number of times used. */
int outTarget; /* Number of times want to output word. */
int outCount; /* Number of times have output word so far. */
struct monomerType *type; /* The type of the monomer. */
struct slRef *readList; /* List of references to reads this is in. */
int subbedOutCount; /* Output count after substitution. */
};
struct monomerRef
/* A reference to a monomer. */
{
struct monomerRef *next; /* Next in list */
struct monomer *val; /* The word referred to. */
};
struct monomerType
/* A collection of words of the same type - or monomers of same type. */
{
struct monomerType *next; /* Next monomerType */
char *name; /* Short name of type */
struct monomerRef *list; /* List of all words of that type */
};
struct alphaRead
/* A read that's been parsed into alpha variants. */
{
struct alphaRead *next; /* Next in list */
char *name; /* Id of read, not allocated here. */
struct monomerRef *list; /* List of alpha subunits */
};
struct alphaStore
/* Stores info on all monomers */
{
struct monomer *monomerList; /* List of words, fairly arbitrary order. */
struct hash *monomerHash; /* Hash of monomer, keyed by word. */
struct alphaRead *readList; /* List of all reads. */
struct hash *readHash; /* Hash of all reads keyed by read ID. */
struct wordTree *markovChains; /* Tree of words that follow other words. */
struct wordTree *markovChainsNoOrphans; /* Markov tree before orphans are added. */
int maxChainSize; /* Maximum depth of tree. */
struct monomerType *typeList; /* List of all types. */
struct hash *typeHash; /* Hash with monomerType values, keyed by all words. */
int typeCount; /* Count of types. */
struct monomerType **typeArray; /* Array as opposed to list of types */
};
/* The wordTree structure below is the central data structure for this program. It is
* used to build up a tree that contains all observed N-word-long sequences observed in
* the text, where N corresponds to the "size" command line option which defaults to 3,
* an option that in turn is stored in the maxChainSize variable. At this chain size the
* text
* this is the black dog and the black cat
* would have the chains
* this is the
* is the black
* the black dog
* black dog and
* dog and the
* and the black
* the black cat
* and turn into the tree
* this
* is
* the
* is
* the
* black
* the
* black
* dog
* cat
* black
* dog
* and
* dog
* and
* the
* and
* the
* black
* Note how the tree is able to compress the two chains "the black dog" and "the black cat."
*
* A node in the tree can have as many children as it needs to at each node. The depth of
* the tree is the same as the chain size, by default 3. At each node in the tree you get
* a word, and a list of all words that are observed in the text to follow that word.
*
* Once the program has build up the wordTree, it can output it in a couple of fashions. */
struct wordTree
/* A node in a tree of words. The head of the tree is a node with word value the empty string. */
{
struct wordTree *next; /* Next sibling */
struct wordTree *children; /* Children in list. */
struct wordTree *parent; /* Parent of this node or NULL for root. */
struct monomer *monomer; /* The info on the word itself. */
int useCount; /* Number of times word used in input with given predecessors. */
int outTarget; /* Number of times want to output word with given predecessors. */
int outCount; /* Number of times actually output with given predecessors. */
double normVal; /* value to place the normalization value */
};
struct wordTree *wordTreeNew(struct monomer *monomer)
/* Create and return new wordTree element. */
{
struct wordTree *wt;
AllocVar(wt);
wt->monomer = monomer;
return wt;
}
int wordTreeCmpWord(const void *va, const void *vb)
/* Compare two wordTree for slSort. */
{
const struct wordTree *a = *((struct wordTree **)va);
const struct wordTree *b = *((struct wordTree **)vb);
return cmpStringsWithEmbeddedNumbers(a->monomer->word, b->monomer->word);
}
static void wordTreeSort(struct wordTree *wt)
/* Sort all children lists in tree. */
{
slSort(&wt->children, wordTreeCmpWord);
struct wordTree *child;
for (child = wt->children; child != NULL; child = child->next)
wordTreeSort(child);
}
struct wordTree *wordTreeFindInList(struct wordTree *list, struct monomer *monomer)
/* Return wordTree element in list that has given word, or NULL if none. */
{
struct wordTree *wt;
for (wt = list; wt != NULL; wt = wt->next)
if (wt->monomer == monomer)
break;
return wt;
}
struct wordTree *wordTreeAddFollowing(struct wordTree *wt, struct monomer *monomer)
/* Make word follow wt in tree. If word already exists among followers
* return it and bump use count. Otherwise create new one. */
{
struct wordTree *child = wordTreeFindInList(wt->children, monomer);
if (child == NULL)
{
child = wordTreeNew(monomer);
child->parent = wt;
slAddHead(&wt->children, child);
}
child->useCount += 1;
return child;
}
int wordTreeSumUseCounts(struct wordTree *list)
/* Sum up useCounts in list */
{
int total = 0;
struct wordTree *wt;
for (wt = list; wt != NULL; wt = wt->next)
total += wt->useCount;
return total;
}
int wordTreeSumOutTargets(struct wordTree *list)
/* Sum up useCounts in list */
{
int total = 0;
struct wordTree *wt;
for (wt = list; wt != NULL; wt = wt->next)
total += wt->outTarget;
return total;
}
void addChainToTree(struct wordTree *wt, struct dlList *chain)
/* Add chain of words to tree. */
{
struct dlNode *node;
wt->useCount += 1;
for (node = chain->head; !dlEnd(node); node = node->next)
{
struct monomer *monomer = node->val;
verbose(4, " adding %s\n", monomer->word);
wt = wordTreeAddFollowing(wt, monomer);
}
}
int useCountInTree(struct wordTree *wt, struct dlNode *nodeList, int chainSize)
/* Return number of times chainSize successive nodes from nodeList are found
* in wt, 0 if not found. */
{
int i;
struct wordTree *subTree = wt;
struct dlNode *node = nodeList;
for (i=0; i<chainSize; ++i)
{
struct monomer *monomer = node->val;
subTree = wordTreeFindInList(subTree->children, monomer);
if (subTree == NULL)
return FALSE;
node = node->next;
}
return subTree->useCount;
}
void findLongestSupportingMarkovChain(struct wordTree *wt, struct dlNode *node,
int *retChainSize, int *retReadCount)
/* See if chain of words is in tree tree. */
{
struct dlNode *start = node;
int chainSize = 1;
int readCount = 0;
for (;;)
{
int useCount = useCountInTree(wt, start, chainSize);
if (useCount == 0)
break;
readCount = useCount;
chainSize += 1;
start = start->prev;
if (dlStart(start))
break;
}
*retChainSize = chainSize;
*retReadCount = readCount;
}
static void writeMonomerListAndBetweens(struct alphaStore *store,
char *fileName, struct dlList *ll)
/* Write out monomer list to file. */
{
FILE *f = mustOpen(fileName, "w");
struct dlNode *node;
struct wordTree *origTree = store->markovChainsNoOrphans;
for (node = ll->head; !dlEnd(node); node = node->next)
{
struct monomer *monomer = node->val;
if (betweens)
{
int chainSize = 0, readCount = 0;
findLongestSupportingMarkovChain(origTree, node,
&chainSize, &readCount);
/* The -2 is for 1 extra for the empty tree root, and 1 extra to get
* from chain-size to markov model terminology. */
char between[24];
safef(between, sizeof(between), "<%d:%d:%d>", chainSize-2,
readCount, useCountInTree(origTree, node, 1));
fprintf(f, "%-11s\t", between);
}
fprintf(f, "%s\n", monomer->word);
}
carefulClose(&f);
}
int wordTreeAddPseudoCount(struct wordTree *wt, int pseudo)
/* Add pseudo to all leaves of tree and propagate counts up to parents. */
{
if (wt->children == NULL)
{
wt->useCount += pseudo;
return wt->useCount;
}
else
{
struct wordTree *child;
int oldChildTotal = 0;
for (child = wt->children; child != NULL; child = child->next)
oldChildTotal += child->useCount;
int oldDiff = wt->useCount - oldChildTotal;
if (oldDiff < 0) oldDiff = 0; // Necessary in rare cases, not sure why.
int total = 0;
for (child = wt->children; child != NULL; child = child->next)
total += wordTreeAddPseudoCount(child, pseudo);
wt->useCount = total + oldDiff + pseudo;
return total;
}
}
void wordTreeNormalize(struct wordTree *wt, double outTarget, double normVal)
/* Recursively set wt->normVal and wt->outTarget so each branch gets its share */
{
if (pseudoCount > 0)
wordTreeAddPseudoCount(wt, pseudoCount);
wt->normVal = normVal;
wt->outTarget = outTarget;
wt->outCount = 0;
int childrenTotalUses = wordTreeSumUseCounts(wt->children);
struct wordTree *child;
for (child = wt->children; child != NULL; child = child->next)
{
double childRatio = (double)child->useCount / childrenTotalUses;
wordTreeNormalize(child, childRatio*outTarget, childRatio*normVal);
}
}
char *wordTreeString(struct wordTree *wt)
/* Return something like '(a b c)' where c would be the value at wt itself, and
* a and b would be gotten by following parents. */
{
struct slName *list = NULL, *el;
for (;wt != NULL; wt = wt->parent)
{
char *word = wt->monomer->word;
if (!isEmpty(word)) // Avoid blank great grandparent at root of tree.
slNameAddHead(&list, word);
}
struct dyString *dy = dyStringNew(0);
dyStringAppendC(dy, '(');
for (el = list; el != NULL; el = el->next)
{
dyStringPrintf(dy, "%s", el->name);
if (el->next != NULL)
dyStringAppendC(dy, ' ');
}
dyStringAppendC(dy, ')');
slFreeList(&list);
return dyStringCannibalize(&dy);
}
char *dlListFragWords(struct dlNode *head)
/* Return string containing all words in list pointed to by head. */
{
struct dyString *dy = dyStringNew(0);
dyStringAppendC(dy, '{');
struct dlNode *node;
for (node = head; !dlEnd(node); node = node->next)
{
if (node != head)
dyStringAppendC(dy, ' ');
struct monomer *monomer = node->val;
dyStringAppend(dy, monomer->word);
}
dyStringAppendC(dy, '}');
return dyStringCannibalize(&dy);
}
void wordTreeDump(int level, struct wordTree *wt, int maxChainSize, FILE *f)
/* Write out wordTree to file. */
{
static char *words[64];
int i;
assert(level < ArraySize(words));
words[level] = wt->monomer->word;
if (!fullOnly || level == maxChainSize)
{
fprintf(f, "%d\t%d\t%d\t%d\t%f\t",
level, wt->useCount, wt->outTarget, wt->outCount, wt->normVal);
for (i=1; i<=level; ++i)
{
spaceOut(f, level*2);
fprintf(f, "%s ", words[i]);
}
fprintf(f, "\n");
}
struct wordTree *child;
for (child = wt->children; child != NULL; child = child->next)
wordTreeDump(level+1, child, maxChainSize, f);
}
struct wordTree *pickWeightedRandomFromList(struct wordTree *list)
/* Pick word from list randomly, but so that words with higher outTargets
* are picked more often. */
{
struct wordTree *picked = NULL;
/* Debug output. */
{
verbose(4, " pickWeightedRandomFromList(");
struct wordTree *wt;
for (wt = list; wt != NULL; wt = wt->next)
{
if (wt != list)
verbose(4, " ");
verbose(4, "%s:%d", wt->monomer->word, wt->outTarget);
}
verbose(4, ") total %d\n", wordTreeSumOutTargets(list));
}
/* Figure out total number of outputs left, and a random number between 0 and that total. */
int total = wordTreeSumOutTargets(list);
if (total > 0)
{
int threshold = rand() % total;
verbose(4, " threshold %d\n", threshold);
/* Loop through list returning selection corresponding to random threshold. */
int binStart = 0;
struct wordTree *wt;
for (wt = list; wt != NULL; wt = wt->next)
{
int size = wt->outTarget;
int binEnd = binStart + size;
verbose(4, " %s size %d, binEnd %d\n", wt->monomer->word, size, binEnd);
if (threshold < binEnd)
{
picked = wt;
verbose(4, " picked %s\n", wt->monomer->word);
break;
}
binStart = binEnd;
}
}
return picked;
}
int totUseZeroCount = 0;
struct monomer *pickRandomFromType(struct monomerType *type)
/* Pick a random word, weighted by outTarget, from all available of given type */
{
/* Figure out total on list */
int total = 0;
struct monomerRef *ref;
for (ref = type->list; ref != NULL; ref = ref->next)
total += ref->val->outTarget;
verbose(3, "pickRandomFromType %s total of outTarget=%d\n", type->name, total);
/* Loop through list returning selection corresponding to random threshold. */
if (total > 0)
{
int threshold = rand() % total;
int binStart = 0;
for (ref = type->list; ref != NULL; ref = ref->next)
{
struct monomer *monomer = ref->val;
int size = monomer->outTarget;
int binEnd = binStart + size;
if (threshold < binEnd)
return monomer;
binStart = binEnd;
}
}
verbose(3, "Backup plan for %s in pickRandomFromType\n", type->name);
/* Try again based on use counts. */
total = 0;
for (ref = type->list; ref != NULL; ref = ref->next)
total += ref->val->useCount;
if (total > 0)
{
int threshold = rand() % total;
int binStart = 0;
for (ref = type->list; ref != NULL; ref = ref->next)
{
struct monomer *monomer = ref->val;
int size = monomer->useCount;
int binEnd = binStart + size;
if (threshold < binEnd)
return monomer;
binStart = binEnd;
}
}
errAbort("Fell off end in pickRandomFromType on %s", type->name);
return NULL;
}
struct wordTree *predictNextFromAllPredecessors(struct wordTree *wt, struct dlNode *list)
/* Predict next word given tree and recently used word list. If tree doesn't
* have statistics for what comes next given the words in list, then it returns
* NULL. */
{
if (verboseLevel() >= 4)
verbose(4, " predictNextFromAllPredecessors(%s, %s)\n", wordTreeString(wt), dlListFragWords(list));
struct dlNode *node;
for (node = list; !dlEnd(node); node = node->next)
{
struct monomer *monomer = node->val;
wt = wordTreeFindInList(wt->children, monomer);
if (verboseLevel() >= 4)
verbose(4, " wordTreeFindInList(%s) = %p %s\n", monomer->word, wt, wordTreeString(wt));
if (wt == NULL || wt->children == NULL)
break;
}
struct wordTree *result = NULL;
if (wt != NULL && wt->children != NULL)
result = pickWeightedRandomFromList(wt->children);
return result;
}
struct wordTree *predictFromWordTree(struct wordTree *wt, struct dlNode *recent)
/* Predict next word given tree and recently used word list. Will use all words in
* recent list if can, but if there is not data in tree, will back off, and use
* progressively less previous words. */
{
struct dlNode *node;
if (verboseLevel() >= 4)
verbose(4, " predictNextFromWordTree(%s)\n", wordTreeString(wt));
for (node = recent; !dlEnd(node); node = node->next)
{
struct wordTree *result = predictNextFromAllPredecessors(wt, node);
if (result != NULL)
return result;
}
return NULL;
}
struct dlNode *nodesFromTail(struct dlList *list, int count)
/* Return count nodes from tail of list. If list is shorter than count, it returns the
* whole list. */
{
int i;
struct dlNode *node;
for (i=0, node = list->tail; i<count; ++i)
{
if (dlStart(node))
return list->head;
node = node->prev;
}
return node;
}
struct monomerType *typeAfter(struct alphaStore *store, struct monomerType *oldType,
int amount)
/* Skip forward amount in typeList from oldType. If get to end of list start
* again at the beginning */
{
int i;
struct monomerType *type = oldType;
for (i=0; i<amount; ++i)
{
type = type->next;
if (type == NULL)
type = store->typeList;
}
return type;
}
struct monomerType *typeBefore(struct alphaStore *store, struct monomerType *oldType, int amount)
/* Pick type that comes amount before given type. */
{
int typeIx = ptArrayIx(oldType, store->typeArray, store->typeCount);
typeIx -= amount;
while (typeIx < 0)
typeIx += store->typeCount;
return store->typeArray[typeIx];
}
struct wordTree *predictFromPreviousTypes(struct alphaStore *store, struct dlList *past)
/* Predict next based on general pattern of monomer order. */
{
/* This routine is now a bit more complex than necessary but it still works. It
* these days only needs to look back 1 because of the read-based type fill-in. */
int maxToLookBack = 3;
{ /* Debugging block */
struct dlNode *node = nodesFromTail(past, maxToLookBack);
verbose(4, "predictFromPreviousTypes(");
for (; !dlEnd(node); node = node->next)
{
struct monomer *monomer = node->val;
verbose(4, "%s, ", monomer->word);
}
verbose(4, ")\n");
}
int pastDepth;
struct dlNode *node;
for (pastDepth = 1, node = past->tail; pastDepth <= maxToLookBack; ++pastDepth)
{
if (dlStart(node))
{
verbose(3, "predictFromPreviousTypes with empty past\n");
return NULL;
}
struct monomer *monomer = node->val;
struct monomerType *prevType = hashFindVal(store->typeHash, monomer->word);
if (prevType != NULL)
{
struct monomerType *curType = typeAfter(store, prevType, pastDepth);
struct monomer *curInfo = pickRandomFromType(curType);
struct wordTree *curTree = wordTreeFindInList(store->markovChains->children, curInfo);
verbose(4, "predictFromPreviousType pastDepth %d, curInfo %s, curTree %p %s\n",
pastDepth, curInfo->word, curTree, curTree->monomer->word);
return curTree;
}
node = node->prev;
}
verbose(3, "predictFromPreviousTypes past all unknown types\n");
return NULL;
}
struct wordTree *predictNext(struct alphaStore *store, struct dlList *past)
/* Given input data store and what is known from the past, predict the next word. */
{
struct dlNode *recent = nodesFromTail(past, store->maxChainSize);
struct wordTree *pick = predictFromWordTree(store->markovChains, recent);
if (pick == NULL)
pick = predictFromPreviousTypes(store, past);
if (pick == NULL)
{
pick = pickWeightedRandomFromList(store->markovChains->children);
verbose(3, "in predictNext() last resort pick of %s\n", pick->monomer->word);
}
return pick;
}
void decrementOutputCountsInTree(struct wordTree *wt)
/* Decrement output count of self and parents. */
{
while (wt != NULL)
{
/* Decrement target count, but don't let it fall below sum of counts of all children.
* This can happen with incomplete data if we don't prevent it. This
* same code also prevents us from having negative outTarget. */
int outTarget = wt->outTarget - 1;
int kidSum = wordTreeSumOutTargets(wt->children);
if (outTarget < kidSum)
outTarget = kidSum;
wt->outTarget = outTarget;
/* Always bump outCount to help us debug (only real use of outCount). */
wt->outCount += 1;
wt = wt->parent;
}
}
static struct dlList *wordTreeGenerateList(struct alphaStore *store, int maxSize,
struct wordTree *firstWord, int maxOutputWords)
/* Make a list of words based on probabilities in tree. */
{
struct dlList *ll = dlListNew();
int chainSize = 0;
int outputWords = 0;
struct dlNode *chainStartNode = NULL;
for (;;)
{
if (++outputWords > maxOutputWords)
break;
struct dlNode *node;
struct wordTree *picked;
/* Get next predicted word. */
AllocVar(node);
if (chainSize == 0)
{
chainStartNode = node;
++chainSize;
picked = firstWord;
}
else if (chainSize >= maxSize)
{
chainStartNode = chainStartNode->next;
picked = predictNext(store, ll);
}
else
{
picked = predictNext(store, ll);
++chainSize;
}
if (picked == NULL)
break;
/* Add word from whatever level we fetched back to our output chain. */
struct monomer *monomer = picked->monomer;
node->val = monomer;
dlAddTail(ll, node);
decrementOutputCountsInTree(picked);
monomer->outTarget -= 1;
monomer->outCount += 1;
}
verbose(3, "totUseZeroCount = %d\n", totUseZeroCount);
return ll;
}
struct slRef *listUnusedMonomers(struct alphaStore *store, struct dlList *ll)
/* Return list of references to monomers that are in store but not on ll. */
{
struct slRef *refList = NULL, *ref;
struct hash *usedHash = hashNew(0);
struct dlNode *node;
/* Make hash of used monomers. */
for (node = ll->head; !dlEnd(node); node = node->next)
{
struct monomer *monomer = node->val;
hashAdd(usedHash, monomer->word, monomer);
}
/* Stream through all monomers looking for ones not used and adding to list. */
struct monomer *monomer;
for (monomer = store->monomerList; monomer != NULL; monomer = monomer->next)
{
if (isEmpty(monomer->word))
continue;
if (!hashLookup(usedHash, monomer->word))
{
AllocVar(ref);
ref->val = monomer;
slAddHead(&refList, ref);
}
}
hashFree(&usedHash);
slReverse(&refList);
return refList;
}
int monomerRefIx(struct monomerRef *list, struct monomer *monomer)
/* Return index of monomer in list. */
{
int i;
struct monomerRef *ref;
for (i=0, ref = list; ref != NULL; ref = ref->next, ++i)
{
if (ref->val == monomer)
return i;
}
errAbort("Monomer %s not on list\n", monomer->word);
return -1;
}
struct monomerRef *findNeighborhoodFromReads(struct monomer *center)
/* Find if possible one monomer to either side of center */
{
struct slRef *readRef;
struct monomerRef *before = NULL, *after = NULL;
/* Loop through reads hoping to find a case where center is flanked by two monomers in
* same read. As a fallback, keep track of a monomer before and a monomer after in
* any read. */
for (readRef = center->readList; readRef != NULL; readRef = readRef->next)
{
struct alphaRead *read = readRef->val;
int readSize = slCount(read->list);
int centerIx = monomerRefIx(read->list, center);
if (readSize >= 3 && centerIx > 0 && centerIx < readSize-1)
{
before = slElementFromIx(read->list, centerIx-1);
after = slElementFromIx(read->list, centerIx+1);
break;
}
else if (readSize >= 2)
{
if (centerIx == 0)
after = slElementFromIx(read->list, centerIx+1);
else
before = slElementFromIx(read->list, centerIx-1);
}
}
/* Make up list from end to start. */
struct monomerRef *retList = NULL, *monoRef;
if (after)
{
AllocVar(monoRef);
monoRef->val = after->val;
slAddHead(&retList, monoRef);
}
AllocVar(monoRef);
monoRef->val = center;
slAddHead(&retList, monoRef);
if (before)
{
AllocVar(monoRef);
monoRef->val = before->val;
slAddHead(&retList, monoRef);
}
return retList;
}
struct dlNode *matchExceptCenter(struct dlNode *node, struct monomerRef *neighborhood, struct monomer *center)
/* Return center node if node matches neighborhood except for center. */
{
struct dlNode *centerNode = NULL;
struct monomerRef *neighbor;
struct dlNode *n;
for (n = node, neighbor=neighborhood; ; n = n->next, neighbor = neighbor->next)
{
if (neighbor == NULL)
break;
if (dlEnd(n))
return NULL;
if (neighbor->val == center)
centerNode = n;
else if (n->val != neighbor->val)
return NULL;
}
return centerNode;
}
void printMonomerRefList(struct monomerRef *refList, FILE *f)
/* Print out a line to file with the list of monomers. */
{
struct monomerRef *ref;
for (ref = refList; ref != NULL; ref = ref->next)
fprintf(f, "%s ", ref->val->word);
fprintf(f, "\n");
}
struct slRef *refsToPossibleCenters(struct monomer *center, struct monomerRef *neighborhood, struct dlList *ll)
/* Return a list of dlNodes where neighborhood, but not center matches. */
{
struct slRef *list = NULL;
struct dlNode *node;
for (node = ll->head; !dlEnd(node); node = node->next)
{
struct dlNode *centerNode = matchExceptCenter(node, neighborhood, center);
if (centerNode != NULL)
refAdd(&list, centerNode);
}
return list;
}
void mostCommonMonomerWord(struct slRef *refList, char **retWord, int *retCount)
/* Given refs to dlNodes containing monomers, find word associated with most common monomer. */
{
/* Make up a hash that contains counts of all monomers. */
struct hash *countHash = hashNew(0);
struct slRef *ref;
for (ref = refList; ref != NULL; ref = ref->next)
{
struct dlNode *node = ref->val;
struct monomer *monomer = node->val;
hashIncInt(countHash, monomer->word);
}
/* Iterate through hash finding max value. */
char *maxWord = NULL;
int maxCount = 0;
struct hashEl *hel;
struct hashCookie cookie = hashFirst(countHash);
while ((hel = hashNext(&cookie)) != NULL)
{
int count = ptToInt(hel->val);
if (count > maxCount)
{
maxCount = count;
maxWord = hel->name;
}
}
*retWord = maxWord;
*retCount = maxCount;
hashFree(&countHash);
}
boolean subCommonCenter(struct alphaStore *store,
struct monomer *center, struct monomerRef *neighborhood, struct dlList *ll)
/* Scan list for places where have all items in neighborhood (except for center) matching.
* Substitute in center at one of these places chosen at random and return TRUE if possible. */
{
struct slRef *centerRefList = refsToPossibleCenters(center, neighborhood, ll);
verbose(4, "sub %s in neighborhood: ", center->word);
if (verboseLevel() >= 4)
printMonomerRefList(neighborhood, stderr);
verbose(4, "Got %d possible centers\n", slCount(centerRefList));
if (centerRefList == NULL)
return FALSE;
int commonCount = 0;
char *commonWord = NULL;
mostCommonMonomerWord(centerRefList, &commonWord, &commonCount);
struct monomer *commonMonomer = hashFindVal(store->monomerHash, commonWord);
verbose(4, "Commonest word to displace with %s is %s which occurs %d times in context and %d overall\n", center->word, commonWord, commonCount, commonMonomer->subbedOutCount);
if (commonMonomer->subbedOutCount < 2)
{
verbose(3, "Want to substitute %s for %s, but %s only occurs %d time.\n",
center->word, commonWord, commonWord, commonMonomer->subbedOutCount);
return FALSE;
}
/* Select a random one of the most commonly occuring possible centers. */
int targetIx = rand() % commonCount;
struct slRef *ref;
int currentIx = 0;
for (ref = centerRefList; ref != NULL; ref = ref->next)
{
struct dlNode *node = ref->val;
struct monomer *monomer = node->val;
if (sameString(monomer->word, commonWord))
{
if (currentIx == targetIx)
{
verbose(3, "Substituting %s for %s in context of %d\n", center->word, commonWord, slCount(neighborhood));
struct monomer *oldCenter = node->val;
if (oldCenter->type != center->type)
verbose(3, "Type mismatch subbig %s vs %s\n", oldCenter->word, center->word);
node->val = center;
oldCenter->subbedOutCount -= 1;
center->subbedOutCount += 1;
return TRUE;
}
++currentIx;
}
}
internalErr(); // Should not get here.
return FALSE;
}
boolean subCenterInNeighborhood(struct alphaStore *store,
struct monomer *center, struct monomerRef *neighborhood, struct dlList *ll)
/* Scan ll for cases where neighborhood around center matches. Replace one of these
* cases with center. */
{
int size = slCount(neighborhood);
assert(size == 3 || size == 2);
if (subCommonCenter(store, center, neighborhood, ll))
return TRUE;
if (size == 3)
{
if (subCommonCenter(store, center, neighborhood->next, ll))
return TRUE;
struct monomerRef *third = neighborhood->next->next;
neighborhood->next->next = NULL;
boolean ok = subCommonCenter(store, center, neighborhood, ll);
neighborhood->next->next = third;
return ok;
}
else
return FALSE;
}
struct monomer *mostCommonInType(struct monomerType *type)
/* Return most common monomer of given type */
{
struct monomerRef *ref;
int commonCount = 0;
struct monomer *common = NULL;
for (ref = type->list; ref != NULL; ref = ref->next)
{
struct monomer *monomer = ref->val;
if (monomer->subbedOutCount > commonCount)
{
commonCount = monomer->subbedOutCount;
common = monomer;
}
}
return common;
}
boolean subIntoFirstMostCommonOfType(struct alphaStore *store, struct monomer *unused,
struct dlList *ll)
/* Substitute unused for first occurence of most common monomer of same type. */
{
struct monomer *common = mostCommonInType(unused->type);
if (common == NULL)
{
verbose(3, "No monomers of type %s used at all!\n", unused->type->name);
return FALSE;
}
if (common->subbedOutCount < 2)
{
verbose(3, "Trying to sub in %s, but there's no monomers of type %s that are used more than once.\n",
unused->word, unused->type->name);
return FALSE;
}
struct dlNode *node;
for (node = ll->head; !dlEnd(node); node = node->next)
{
struct monomer *monomer = node->val;
if (monomer == common)
{
verbose(3, "Subbing %s for %s of type %s\n", unused->word, monomer->word, unused->type->name);
node->val = unused;
unused->subbedOutCount += 1;
monomer->subbedOutCount -= 1;
break;
}
}
return TRUE;
}
void setInitialSubbedOutCount(struct alphaStore *store, struct dlList *ll)
/* Set subbedOutCount based on how many times monomers occur in list. */
{
struct dlNode *node;
for (node = ll->head; !dlEnd(node); node = node->next)
{
struct monomer *monomer = node->val;
monomer->subbedOutCount += 1;
}
#ifdef PARANOID
/* As a check see if subbedOutCount agrees with outCount. */
int mismatchCount = 0;
struct monomer *monomer;
for (monomer = store->monomerList; monomer != NULL; monomer = monomer->next)
{
uglyf("%s %d %d\n", monomer->word, monomer->outCount, monomer->subbedOutCount);
if (monomer->outCount != monomer->subbedOutCount)
++mismatchCount;
}
uglyf("mismatch count = %d\n", mismatchCount);
#endif /* PARANOID */
}
void subInMissing(struct alphaStore *store, struct dlList *ll)
/* Go figure out missing monomers in ll, and attempt to substitute them in somewhere they would fit. */
{
setInitialSubbedOutCount(store, ll);
struct slRef *unusedList = listUnusedMonomers(store, ll);
verbose(3, "%d monomers, %d unused\n", slCount(store->monomerList), slCount(unusedList));
struct slRef *unusedRef;
for (unusedRef = unusedList; unusedRef != NULL; unusedRef = unusedRef->next)
{
struct monomer *unused = unusedRef->val;
struct monomerRef *neighborhood = findNeighborhoodFromReads(unused);
if (!subCenterInNeighborhood(store, unused, neighborhood, ll))
{
verbose(3, "Couldn't substitute in %s with context, falling back to type logic\n",
unused->word);
subIntoFirstMostCommonOfType(store, unused, ll);
}
slFreeList(&neighborhood);
}
}
static void writeMonomerList(char *fileName, struct dlList *ll)
/* Write out monomer list to file. */
{
FILE *f = mustOpen(fileName, "w");
struct dlNode *node;
for (node = ll->head; !dlEnd(node); node = node->next)
{
struct monomer *monomer = node->val;
fprintf(f, "%s\n", monomer->word);
}
carefulClose(&f);
}
static struct dlList *wordTreeMakeList(struct alphaStore *store, int maxSize,
struct wordTree *firstWord, int maxOutputWords)
/* Create word list base on tree probabilities, and then substituting in unused
* monomers if possible. */
{
struct dlList *ll = wordTreeGenerateList(store, maxSize, firstWord, maxOutputWords);
verbose(2, "Generated initial output list\n");
char *unsubbedFile = optionVal("unsubbed", NULL);
if (unsubbedFile)
writeMonomerList(unsubbedFile, ll);
subInMissing(store, ll);
verbose(2, "Substituted in missing rare monomers\n");
return ll;
}
struct alphaStore *alphaStoreNew(int maxChainSize)
/* Allocate and initialize a new word store. */
{
struct alphaStore *store;
AllocVar(store);
store->maxChainSize = maxChainSize;
store->monomerHash = hashNew(0);
store->typeHash = hashNew(0);
store->readHash = hashNew(0);
return store;
}
struct monomer *alphaStoreAddMonomer(struct alphaStore *store, char *word)
/* Add word to store, incrementing it's useCount if it's already there, otherwise
* making up a new record for it. */
{
struct monomer *monomer = hashFindVal(store->monomerHash, word);
if (monomer == NULL)
{
AllocVar(monomer);
hashAddSaveName(store->monomerHash, word, monomer, &monomer->word);
slAddHead(&store->monomerList, monomer);
}
monomer->useCount += 1;
monomer->outTarget = monomer->useCount; /* Set default value, may be renormalized. */
return monomer;
}
void connectReadsToMonomers(struct alphaStore *store)
/* Add each read monomer appears in to monomer's readList. */
{
struct alphaRead *read;
for (read = store->readList; read != NULL; read = read->next)
{
struct monomerRef *ref;
for (ref = read->list; ref != NULL; ref = ref->next)
{
struct monomer *monomer = ref->val;
refAdd(&monomer->readList, read);
}
}
}
void alphaReadListFromFile(char *fileName, struct alphaStore *store)
/* Read in file and turn it into a list of alphaReads. */
{
/* Stuff for processing file a line at a time. */
struct lineFile *lf = lineFileOpen(fileName, TRUE);
char *line, *word;
/* Loop through each line of file making up a read for it. */
struct alphaRead *readList = NULL;
while (lineFileNextReal(lf, &line))
{
/* Parse out first word of line into name, and rest into list. */
char *name = nextWord(&line);
struct monomerRef *list = NULL;
while ((word = nextWord(&line)) != NULL)
{
struct monomer *monomer = alphaStoreAddMonomer(store, word);
struct monomerRef *ref;
AllocVar(ref);
ref->val = monomer;
slAddHead(&list, ref);
}
slReverse(&list);
if (list == NULL)
errAbort("Line %d of %s has no alpha monomers.", lf->lineIx, lf->fileName);
/* Create data structure and add read to list and hash */
if (hashLookup(store->readHash, name))
errAbort("Read ID %s is repeated line %d of %s", name, lf->lineIx, lf->fileName);
struct alphaRead *read;
AllocVar(read);
read->list = list;
hashAddSaveName(store->readHash, name, read, &read->name);
slAddHead(&readList, read);
}
slReverse(&readList);
store->readList = readList;
if (store->readList == NULL)
errAbort("%s contains no reads", lf->fileName);
lineFileClose(&lf);
connectReadsToMonomers(store);
}
struct alphaOrphan
/* Information about an orphan - something without great joining information. */
{
struct alphaOrphan *next; /* Next in list */
struct monomer *monomer; /* Pointer to orphan */
boolean paired; /* True if has been paired with somebody. */
};
struct alphaOrphan *findOrphanStarts(struct alphaRead *readList, struct alphaStore *store)
/* Return list of monomers that are found only at start of reads. */
{
struct alphaOrphan *orphanList = NULL;
/* Build up hash of things seen later in reads. */
struct alphaRead *read;
struct hash *later = hashNew(0); /* Hash of monomers found later. */
for (read = readList; read != NULL; read = read->next)
{
struct monomerRef *ref;
for (ref = read->list->next; ref != NULL; ref = ref->next)
{
hashAdd(later, ref->val->word, NULL);
}
}
/* Pass through again collecting orphans. */
struct hash *orphanHash = hashNew(0);
for (read = readList; read != NULL; read = read->next)
{
struct monomer *monomer = read->list->val;
char *word = monomer->word;
if (!hashLookup(later, word))
{
struct alphaOrphan *orphan = hashFindVal(orphanHash, word);
if (orphan == NULL)
{
AllocVar(orphan);
orphan->monomer = monomer;
slAddHead(&orphanList, orphan);
hashAdd(orphanHash, word, orphan);
verbose(3, "Adding orphan start %s\n", word);
}
}
}
hashFree(&later);
hashFree(&orphanHash);
slReverse(&orphanList);
return orphanList;
}
struct alphaOrphan *findOrphanEnds(struct alphaRead *readList, struct alphaStore *store)
/* Return list of monomers that are found only at end of reads. */
{
struct alphaOrphan *orphanList = NULL;
/* Build up hash of things seen sooner in reads. */
struct alphaRead *read;
struct hash *sooner = hashNew(0); /* Hash of monomers found sooner. */
for (read = readList; read != NULL; read = read->next)
{
struct monomerRef *ref;
/* Loop over all but last. */
for (ref = read->list; ref->next != NULL; ref = ref->next)
{
hashAdd(sooner, ref->val->word, NULL);
}
}
/* Pass through again collecting orphans. */
struct hash *orphanHash = hashNew(0);
for (read = readList; read != NULL; read = read->next)
{
struct monomerRef *lastRef = slLastEl(read->list);
struct monomer *monomer = lastRef->val;
if (!hashLookup(sooner, monomer->word))
{
struct alphaOrphan *orphan = hashFindVal(orphanHash, monomer->word);
if (orphan == NULL)
{
AllocVar(orphan);
orphan->monomer = monomer;
slAddHead(&orphanList, orphan);
hashAdd(orphanHash, monomer->word, orphan);
verbose(3, "Adding orphan end %s\n", monomer->word);
}
}
}
hashFree(&sooner);
slReverse(&orphanList);
hashFree(&orphanHash);
return orphanList;
}
struct alphaRead *addReadOfTwo(struct alphaStore *store, struct monomer *a, struct monomer *b)
/* Make up a fake read that goes from a to b and add it to store. */
{
/* Create fake name and start fake read with it. */
static int fakeId = 0;
char name[32];
safef(name, sizeof(name), "fake%d", ++fakeId);
/* Allocate fake read. */
struct alphaRead *read;
AllocVar(read);
/* Add a and b to the read. */
struct monomerRef *aRef, *bRef;
AllocVar(aRef);
aRef->val = a;
AllocVar(bRef);
bRef->val = b;
aRef->next = bRef;
read->list = aRef;
/* Add read to the store. */
slAddHead(&store->readList, read);
hashAddSaveName(store->readHash, name, read, &read->name);
/* Add read to the monomers. */
refAdd(&a->readList, read);
refAdd(&b->readList, read);
a->useCount += 1;
b->useCount += 1;
return read;
}
void integrateOrphans(struct alphaStore *store)
/* Make up fake reads that integrate orphans (monomers only found at beginning or end
* of a read) better. */
{
struct alphaOrphan *orphanStarts = findOrphanStarts(store->readList, store);
struct alphaOrphan *orphanEnds = findOrphanEnds(store->readList, store);
verbose(3, "orphanStarts has %d items, orphanEnds %d\n",
slCount(orphanStarts), slCount(orphanEnds));
/* First look for the excellent situation where you can pair up orphans with each
* other. For Y at least this happens half the time. */
struct alphaOrphan *start, *end;
for (start = orphanStarts; start != NULL; start = start->next)
{
struct monomerType *startType = start->monomer->type;
if (startType == NULL)
continue;
for (end = orphanEnds; end != NULL && !start->paired; end = end->next)
{
struct monomerType *endType = end->monomer->type;
if (endType == NULL)
continue;
if (!end->paired)
{
struct monomerType *nextType = typeAfter(store, endType, 1);
if (nextType == startType)
{
end->paired = TRUE;
start->paired = TRUE;
addReadOfTwo(store, end->monomer, start->monomer);
verbose(3, "Pairing %s with %s\n", end->monomer->word, start->monomer->word);
}
}
}
}
/* Ok, now have to just manufacture other side of orphan starts out of thin air. */
for (start = orphanStarts; start != NULL; start = start->next)
{
if (start->paired)
continue;
struct monomer *startMono = start->monomer;
struct monomerType *startType = startMono->type;
if (startType == NULL)
continue;
struct monomerType *newType = typeBefore(store, startType, 1);
verbose(3, "Trying to find end of type %s\n", newType->name);
struct monomer *newMono = pickRandomFromType(newType);
addReadOfTwo(store, newMono, startMono);
verbose(3, "Pairing new %s with start %s\n", newMono->word, startMono->word);
}
/* Ok, now have to just manufacture other side of orphan ends out of thin air. */
for (end = orphanEnds; end != NULL; end = end->next)
{
if (end->paired)
continue;
struct monomer *endMono = end->monomer;
struct monomerType *endType = endMono->type;
if (endType == NULL)
continue;
struct monomerType *newType = typeAfter(store, endType, 1);
verbose(3, "Trying to find start of type %s\n", newType->name);
struct monomer *newMono = pickRandomFromType(newType);
addReadOfTwo(store, endMono, newMono);
verbose(3, "Pairing end %s with new %s\n", endMono->word, newMono->word);
}
}
struct wordTree *makeMarkovChains(struct alphaStore *store)
/* Return wordTree containing all words, and also all chains-of-words of length
* chainSize seen in file. */
{
/* We'll build up the tree starting with an empty root node. */
struct wordTree *wt = wordTreeNew(alphaStoreAddMonomer(store, ""));
int chainSize = store->maxChainSize;
/* Loop through each read. There's special cases at the beginning and end of read, and for
* short reads. In the main case we'll be maintaining a chain (doubly linked list) of maxChainSize
* words, * popping off one word from the start, and adding one word to the end for each
* new word we encounter. This list is added to the tree each iteration. */
struct alphaRead *read;
for (read = store->readList; read != NULL; read = read->next)
{
/* We'll keep a chain of three or so words in a doubly linked list. */
struct dlNode *node;
struct dlList *chain = dlListNew();
int curSize = 0;
int wordCount = 0;
struct monomerRef *ref;
for (ref = read->list; ref != NULL; ref = ref->next)
{
struct monomer *monomer = ref->val;
/* For the first few words in the file after ID, we'll just build up the chain,
* only adding it to the tree when we finally do get to the desired
* chain size. Once past the initial section of the file we'll be
* getting rid of the first link in the chain as well as adding a new
* last link in the chain with each new word we see. */
if (curSize < chainSize)
{
dlAddValTail(chain, monomer);
++curSize;
if (curSize == chainSize)
addChainToTree(wt, chain);
}
else
{
/* Reuse doubly-linked-list node, but give it a new value, as we move
* it from head to tail of list. */
node = dlPopHead(chain);
node->val = monomer;
dlAddTail(chain, node);
addChainToTree(wt, chain);
}
++wordCount;
}
/* Handle last few words in line, where can't make a chain of full size. Also handles
* lines that have fewer than chain size words. */
if (curSize < chainSize)
addChainToTree(wt, chain);
while ((node = dlPopHead(chain)) != NULL)
{
if (!dlEmpty(chain))
addChainToTree(wt, chain);
freeMem(node);
}
dlListFree(&chain);
}
wordTreeSort(wt); // Make output of chain file prettier
return wt;
}
void wordTreeWrite(struct wordTree *wt, int maxChainSize, char *fileName)
/* Write out tree to file */
{
FILE *f = mustOpen(fileName, "w");
fprintf(f, "#level\tuseCount\toutTarget\toutCount\tnormVal\tmonomers\n");
wordTreeDump(0, wt, maxChainSize, f);
carefulClose(&f);
}
void alphaStoreLoadMonomerOrder(struct alphaStore *store, char *readsFile, char *fileName)
/* Read in a file with one line for each monomer type, where first word is type name,
* and rest of words are all the actually variants of that type.
* Requires all variants already be in store. The readsFile is passed
* just for nicer error reporting. */
{
/* Stuff for processing file a line at a time. */
struct lineFile *lf = lineFileOpen(fileName, TRUE);
char *line, *word;
struct hash *uniq = hashNew(0);
/* Set up variables we'll put results in in store. */
store->typeList = NULL;
while (lineFileNextReal(lf, &line))
{
char *name = nextWord(&line);
if (hashLookup(uniq, name) != NULL)
errAbort("Type name '%s' repeated line %d of %s\n", name, lf->lineIx, lf->fileName);
struct monomerType *type;
AllocVar(type);
type->name = cloneString(name);
slAddHead(&store->typeList, type);
while ((word = nextWord(&line)) != NULL)
{
struct monomer *monomer = hashFindVal(store->monomerHash, word);
if (monomer == NULL)
errAbort("%s is in %s but not %s", word, lf->fileName, readsFile);
struct monomerRef *ref;
AllocVar(ref);
ref->val = monomer;
slAddHead(&type->list, ref);
hashAddUnique(store->typeHash, word, type);
}
if (type->list == NULL)
errAbort("Short line %d of %s. Format should be:\ntype list-of-monomers-of-type\n",
lf->lineIx, lf->fileName);
}
slReverse(&store->typeList);
if (store->typeList == NULL)
errAbort("%s is empty", lf->fileName);
lineFileClose(&lf);
hashFree(&uniq);
verbose(3, "Added %d types containing %d words from %s\n",
slCount(store->typeList), store->typeHash->elCount, fileName);
/* Create type array */
store->typeCount = slCount(store->typeList);
struct monomerType **types = AllocArray(store->typeArray, store->typeCount);
struct monomerType *type;
int i;
for (i=0, type = store->typeList; i<store->typeCount; ++i, type = type->next)
types[i] = type;
}
void crossCheckMonomerOrderAndReads(struct alphaStore *store, char *orderedPrefix, char *readFile, char *typeFile)
/* Make sure all monomer that begin with ordered prefix are present in monomer order file. */
{
/* Make hash of all monomers that have type info. */
struct hash *orderHash = hashNew(0);
struct monomerType *type;
for (type = store->typeList; type != NULL; type = type->next)
{
struct monomerRef *ref;
for (ref = type->list; ref != NULL; ref = ref->next)
hashAdd(orderHash, ref->val->word, ref->val);
}
/* Go through all monomers and make sure ones with correct prefix are in list. */
struct monomer *mon;
for (mon = store->monomerList; mon != NULL; mon = mon->next)
{
char *word = mon->word;
if (startsWith(orderedPrefix, word) && !hashLookup(orderHash, word))
{
errAbort("%s is in %s but not %s", word, readFile, typeFile);
}
}
hashFree(&orderHash);
}
void monomerListNormalise(struct monomer *list, int totalCount, int outputSize)
/* Set outTarget field in all of list to be normalized to outputSize */
{
struct monomer *monomer;
double scale = (double)outputSize/totalCount;
for (monomer = list; monomer != NULL; monomer = monomer->next)
{
monomer->outCount = 0;
monomer->outTarget = round(scale * monomer->useCount);
}
}
void alphaStoreNormalize(struct alphaStore *store, int outputSize)
/* Set up output counts on each word to make sure it gets it's share of output size */
{
struct wordTree *wt = store->markovChains;
wordTreeNormalize(wt, outputSize, 1.0);
monomerListNormalise(store->monomerList, wt->useCount, outputSize);
}
struct monomerType *fillInTypeFromReads(struct monomer *monomer, struct alphaStore *store)
/* Look through read list trying to find best supported type for this monomer. */
{
/* The algorithm here could be better. It picks the closest nearby monomer that is typed
* to fill in from. When have information from both before and after the program arbitrarily
* uses before preferentially. When have information that is equally close from multiple reads,
* it just uses info from first read. Fortunately the data, at least on Y, shows a lot of
* consistency, so it's probably not actually worth a more sophisticated algorithm that would
* instead take the most popular choice rather than the first one. */
verbose(3, "fillInTypeFromReads on %s from %d reads\n", monomer->word, slCount(monomer->readList));
struct monomerType *bestType = NULL;
int bestPos = 0;
boolean bestIsAfter = FALSE;
struct slRef *readRef;
for (readRef = monomer->readList; readRef != NULL; readRef = readRef->next)
{
struct alphaRead *read = readRef->val;
struct monomerRef *ref;
{
verbose(3, " read %s (%d els):", read->name, slCount(read->list));
for (ref = read->list; ref != NULL; ref = ref->next)
{
struct monomer *m = ref->val;
verbose(3, " %s", m->word);
}
verbose(3, "\n");
}
struct monomerType *beforeType = NULL;
int beforePos = 0;
/* Look before. */
for (ref = read->list; ref != NULL; ref = ref->next)
{
struct monomer *m = ref->val;
if (m == monomer)
break;
if (m->type != NULL)
{
beforeType = m->type;
beforePos = 0;
}
++beforePos;
}
/* Look after. */
struct monomerType *afterType = NULL;
int afterPos = 0;
assert(ref != NULL && ref->val == monomer);
for (ref = ref->next; ref != NULL; ref = ref->next)
{
struct monomer *m = ref->val;
++afterPos;
if (m->type != NULL)
{
afterType = m->type;
break;
}
}
if (beforeType != NULL)
{
if (bestType == NULL || beforePos < bestPos)
{
bestType = beforeType;
bestPos = beforePos;
bestIsAfter = FALSE;
}
}
if (afterType != NULL)
{
if (bestType == NULL || afterPos < bestPos)
{
bestType = afterType;
bestPos = afterPos;
bestIsAfter = TRUE;
}
}
}
/* Now have found a type that is at a known position relative to ourselves. From this
* infer our own type. */
struct monomerType *chosenType = NULL;
if (bestType != NULL)
{
if (bestIsAfter)
chosenType = typeBefore(store, bestType, bestPos);
else
chosenType = typeAfter(store, bestType, bestPos);
}
verbose(3, "chosenType for %s is %s\n", monomer->word,
(bestType == NULL ? "(null)" : chosenType->name));
return chosenType;
}
void fillInTypes(struct alphaStore *store)
/* We have types for most but not all monomers. Try and fill out types for most of
* the rest by looking for position in reads they are in that do contain known types */
{
/* Do first pass on ones defined - just have to look them up in hash. */
struct monomer *monomer;
for (monomer = store->monomerList; monomer != NULL; monomer = monomer->next)
monomer->type = hashFindVal(store->typeHash, monomer->word);
/* Do second pass on ones that are not yet defined */
for (monomer = store->monomerList; monomer != NULL; monomer = monomer->next)
{
if (monomer->type == NULL)
{
monomer->type = fillInTypeFromReads(monomer, store);
}
}
}
struct dlList *linearSatOneSize(struct alphaStore *store, int outSize)
/* linearSat - assemble alpha repeat regions such as centromeres from reads that have
* been parsed into various repeat monomer variants. Cycles of these variants tend to
* form higher order repeats. Returns list of outSize monomers. */
{
struct wordTree *wt = store->markovChains;
alphaStoreNormalize(store, outSize);
verbose(2, "Normalized Markov Chains\n");
if (optionExists("chain"))
{
char *fileName = optionVal("chain", NULL);
wordTreeWrite(wt, store->maxChainSize, fileName);
}
struct dlList *ll = wordTreeMakeList(store, store->maxChainSize,
pickWeightedRandomFromList(wt->children), outSize);
if (optionExists("afterChain"))
{
char *fileName = optionVal("afterChain", NULL);
wordTreeWrite(wt, store->maxChainSize, fileName);
}
return ll;
}
int countMissingMonomers(struct dlList *ll, struct monomer *monomerList)
/* Set the outCounts in monomer list to match how often they occur in ll.
* Return number of monomers that do not occur at all in ll. */
{
/* Zero out output counts. */
struct monomer *monomer;
for (monomer = monomerList; monomer != NULL; monomer = monomer->next)
monomer->outCount = 0;
/* Increase output count each time a monomer is used. */
struct dlNode *node;
for (node = ll->head; !dlEnd(node); node = node->next)
{
monomer = node->val;
monomer->outCount += 1;
}
/* Count up unused. */
int missing = 0;
for (monomer = monomerList; monomer != NULL; monomer = monomer->next)
if (monomer->outCount == 0 && !sameString(monomer->word, ""))
missing += 1;
return missing;
}
void linearSat(char *readsFile, char *monomerOrderFile, char *outFile)
/* linearSat - assemble alpha repeat regions such as centromeres from reads that have
* been parsed into various repeat monomer variants. Cycles of these variants tend to
* form higher order repeats. */
{
/* This routine reads in the input, and then calls a routine that produces the
* output for a given size. If not all monomers are included in the output, then it
* will try to find the minimum output size needed to include all monomers. */
/* Read in inputs, and put in "store" */
struct alphaStore *store = alphaStoreNew(maxChainSize);
alphaReadListFromFile(readsFile, store);
alphaStoreLoadMonomerOrder(store, readsFile, monomerOrderFile);
verbose(2, "Loaded input reads and monomer order\n");
if (betweens)
{
store->markovChainsNoOrphans = makeMarkovChains(store);
verbose(2, "Made initial markov chains\n");
}
/* Do some cross checking and filling out a bit for missing data. */
crossCheckMonomerOrderAndReads(store, "m", readsFile, monomerOrderFile);
fillInTypes(store);
integrateOrphans(store);
verbose(2, "Filled in missing types and integrated orphan ends\n");
/* Make the main markov chains out of the reads. */
store->markovChains = makeMarkovChains(store);
verbose(2, "Made Markov Chains\n");
/* Loop gradually increasing size of output we make until get to maxOutSize or until
* we generate output that includes all input monomers. */
struct dlList *ll;
int outSize = initialOutSize;
while (outSize <= maxOutSize)
{
ll = linearSatOneSize(store, outSize);
assert(outSize == dlCount(ll));
int missing = countMissingMonomers(ll, store->monomerList);
if (missing <= maxToMiss)
break;
if (outSize == maxOutSize)
{
errAbort("Could not include all monomers. Missing %d.\n"
"consider increasing maxOutSize (now %d) or increasing maxToMiss (now %d)",
missing, maxOutSize, maxToMiss);
break;
}
dlListFree(&ll);
outSize *= 1.1; /* Grow by 10% */
if (outSize > maxOutSize)
outSize = maxOutSize;
verbose(1, "%d missing. Trying again with outSize=%d (initialOutSize %d, maxOutSize %d)\n",
missing, outSize, initialOutSize, maxOutSize);
}
writeMonomerListAndBetweens(store, outFile, ll);
verbose(2, "Wrote primary output\n");
dlListFree(&ll);
}
int main(int argc, char *argv[])
/* Process command line. */
{
optionInit(&argc, argv, options);
if (argc != 4)
usage();
maxChainSize = optionInt("size", maxChainSize);
initialOutSize = optionInt("initialOutSize", initialOutSize);
maxOutSize = optionInt("maxOutSize", initialOutSize); // Defaults to same as initialOutSize
if (maxOutSize < initialOutSize)
errAbort("maxOutSize (%d) needs to be bigger than initialOutSize (%d)\n",
maxOutSize, initialOutSize);
maxToMiss = optionInt("maxToMiss", maxToMiss);
fullOnly = optionExists("fullOnly");
pseudoCount = optionInt("pseudoCount", pseudoCount);
betweens = optionExists("betweens");
int seed = optionInt("seed", 0);
srand(seed);
linearSat(argv[1], argv[2], argv[3]);
return 0;
}
| 31.805011 | 175 | 0.675155 | [
"model"
] |
35d7ba5a269d1deab9dfbb99140a7c18256feeb5 | 1,193 | c | C | inter/inter.c | kortescode/Raytracer | 77ebf22164c50693b66e34fd4aa73465de502950 | [
"Apache-2.0"
] | null | null | null | inter/inter.c | kortescode/Raytracer | 77ebf22164c50693b66e34fd4aa73465de502950 | [
"Apache-2.0"
] | null | null | null | inter/inter.c | kortescode/Raytracer | 77ebf22164c50693b66e34fd4aa73465de502950 | [
"Apache-2.0"
] | null | null | null | #include "main.h"
#include "inter.h"
#include "movements.h"
t_inter inter[] =
{
{inter_plan},
{inter_sphere},
{inter_cylinder},
{inter_cone},
{inter_paraboloid},
{inter_hyperboloid},
{0},
};
void inter_calculs(t_rt *rt)
{
t_obj *objs;
objs = rt->obj;
while (objs)
{
translate(rt->eye.eye, -objs->position[X],
-objs->position[Y], -objs->position[Z]);
rev_rotate(rt->eye.eye, -objs->rotation[X],
-objs->rotation[Y], -objs->rotation[Z]);
rev_rotate(rt->eye.vector, -objs->rotation[X],
-objs->rotation[Y], -objs->rotation[Z]);
inter[objs->object].func(rt, objs);
rotate(rt->eye.vector, objs->rotation[X],
objs->rotation[Y], objs->rotation[Z]);
rotate(rt->eye.eye, objs->rotation[X],
objs->rotation[Y], objs->rotation[Z]);
translate(rt->eye.eye, objs->position[X],
objs->position[Y], objs->position[Z]);
objs = objs->next;
}
}
void inter_point_calcul(t_obj *object, double point[], double vector[])
{
object->point[X] = point[X] + (object->k * vector[X]);
object->point[Y] = point[Y] + (object->k * vector[Y]);
object->point[Z] = point[Z] + (object->k * vector[Z]);
}
| 25.934783 | 72 | 0.595977 | [
"object",
"vector"
] |
35da63437fba54d74ef88ade43a2add7ddb31c03 | 2,809 | h | C | src/core/multi_projector.h | Lab-RoCoCo/fps_mapper | 376e557c8f5012e05187fe85ee3f4044f99f944a | [
"BSD-3-Clause"
] | 1 | 2017-12-01T14:57:16.000Z | 2017-12-01T14:57:16.000Z | src/core/multi_projector.h | Lab-RoCoCo/fps_mapper | 376e557c8f5012e05187fe85ee3f4044f99f944a | [
"BSD-3-Clause"
] | null | null | null | src/core/multi_projector.h | Lab-RoCoCo/fps_mapper | 376e557c8f5012e05187fe85ee3f4044f99f944a | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#include "cloud.h"
#include "base_projector.h"
#include <stack>
namespace fps_mapper {
using namespace std;
/**
This class encapsulates algorithm and parameters to project a 3D model onto an image,
through a pinhole model.
*/
class MultiProjector : public BaseProjector{
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
MultiProjector();
//! ctor, initializes the inner fields
//! the projectors are OWNED by the multi guy
MultiProjector(std::vector<BaseProjector*>& projectors_);
virtual ~MultiProjector();
/** does the projection, taking into account the normals and the occlusions.
@param zbuffer: a float matrix used to handle occlusions, filled by the method
@param indices: an int image, filled by the algorithm. Each cell contains the index of the point in model, that projects onto a pixel
@param T: the transform world_to_camera applied before the projection
@param model: input
*/
virtual void project(FloatImage& zbuffer,
IndexImage& indices,
const Eigen::Isometry3f& T,
const Cloud& model) const;
// Throws and exception
virtual void project(FloatImage& zbuffer,
IndexImage& indices,
const Eigen::Isometry3f& T,
const FloatImage& src_zbuffer,
const IntImage& src_indices,
float src_scale=1,
int subsample = 1) const;
virtual void unproject(Cloud& cloud, const RawDepthImage& depth_image, const RGBImage& rgb_image=RGBImage());
//! overridden from base class
//! applies a scaling factor to the camera, not the image
//! computes the center so that it is the center of the image
//! @param s: the scale (s=0.5 corresponds to half the image)
virtual void scaleCamera(float s);
//! overridden from base class Pushes the state of all projectors in the pool
virtual void pushState();
//! overridden from base class pops the state of all projectors in the pool
virtual void popState();
virtual void setImageSize(int r, int c);
inline std::vector<BaseProjector*>& projectors() { return _projectors; }
virtual void setCameraInfo(BaseCameraInfo* _camera_info);
virtual void initFromCameraInfo(BaseCameraInfo* _camera_info);
virtual void setMinDistance(float d);
virtual void setMaxDistance(float d);
protected:
// performs the inverse depth projection, to be specialized in derived classes
virtual void unprojectPoints(const RawDepthImage& depth_image);
std::vector<BaseProjector*> _projectors;
int _mono_rows;
struct State {
State(const Eigen::Isometry3f& offset, int rows, int cols);
int image_rows;
int image_cols;
Eigen::Isometry3f offset;
};
std::stack<State, std::deque< State, Eigen::aligned_allocator<State> > > _states;
};
}
| 29.882979 | 134 | 0.709505 | [
"vector",
"model",
"transform",
"3d"
] |
35db32eae64c30f6b3c742155d0b44ac97d3b833 | 1,306 | h | C | PingPongComplete/Game.h | hanftins/PongGame-v2 | bc8c5aef2e1f38b2e0a89787882270ab3f689a1b | [
"MIT"
] | null | null | null | PingPongComplete/Game.h | hanftins/PongGame-v2 | bc8c5aef2e1f38b2e0a89787882270ab3f689a1b | [
"MIT"
] | null | null | null | PingPongComplete/Game.h | hanftins/PongGame-v2 | bc8c5aef2e1f38b2e0a89787882270ab3f689a1b | [
"MIT"
] | null | null | null | #include"BotPlay.h"
#include "bb_state.h"
using namespace std;
class Game
{
private:
void processEvents(bool& CloseMode);
void update(sf::Time deltatime);
void render();
private:
Ball ball;
Paddle PaddleLeft;
Paddle PaddleRight;
sf::RenderWindow Window;
sf::RectangleShape Outline1;
sf::RectangleShape Outline2;
sf::RectangleShape Outline3;
sf::RectangleShape Outline4;
sf::RectangleShape middle;
sf::CircleShape Bard[60];
sf::Font font;
sf::Text text;
sf::Text Exit;
sf::Text Winner;
sf::Text Player1Point;
sf::Text Player2Point;
sf::Time Fps;
sf::Texture BackGround;
sf::Sprite sprite;
int iPlayer1Point;
int iPlayer2Point;
public:
Game();
void CreateOutline();
void CreateText();
void CreatePaddle();
void CreateBard();
void DrawBard();
void DrawOutline();
void DrawText();
void DrawPaddle();
void StrikeAngle(int pc, Paddle p, Ball &ball);
void MoveBall(sf::Time deltatime);
void MovePaddle(sf::Time deltatime);
int TouchPaddleLeft();
int TouchPaddleRight();
bool TouchWall();
void TouchBard();
void PressedKey(sf::Keyboard::Key key, bool Pressed, bool& CloseMode);
void DisplayScore();
bool LoseTheGame();
void WinnerDisplay();
void CleanScreen();
void RestartGame(sf::Time deltatime);
void run(bool& CloseMode);
};
class game :
public BBState {
};
| 20.730159 | 71 | 0.729709 | [
"render"
] |
35dcd9359435e4d78f085414ffc20614a85e2f8c | 1,141 | h | C | get_faces.h | goloskokovic/dlib-java | 2ac4a170e86992d636e070506a95a3f7c232e144 | [
"BSL-1.0"
] | 6 | 2017-11-21T14:54:41.000Z | 2020-03-09T03:36:33.000Z | get_faces.h | goloskokovic/dlib-java | 2ac4a170e86992d636e070506a95a3f7c232e144 | [
"BSL-1.0"
] | null | null | null | get_faces.h | goloskokovic/dlib-java | 2ac4a170e86992d636e070506a95a3f7c232e144 | [
"BSL-1.0"
] | 6 | 2017-01-14T20:19:31.000Z | 2020-08-05T03:39:47.000Z | #include <dlib/image_processing/frontal_face_detector.h>
#include <dlib/image_processing.h>
#include <dlib/image_io.h>
#include <iostream>
int get_faces(char* image_path)
{
dlib::frontal_face_detector detector = dlib::get_frontal_face_detector();
dlib::array2d<dlib::rgb_pixel> img;
dlib::load_image(img, image_path);
// Make the image bigger by a factor of two. This is useful since
// the face detector looks for faces that are about 80 by 80 pixels
// or larger. Therefore, if you want to find faces that are smaller
// than that then you need to upsample the image as we do here by
// calling pyramid_up(). So this will allow it to detect faces that
// are at least 40 by 40 pixels in size. We could call pyramid_up()
// again to find even smaller faces, but note that every time we
// upsample the image we make the detector run slower since it must
// process a larger image.
pyramid_up(img);
// Now tell the face detector to give us a list of bounding boxes
// around all the faces it can find in the image.
std::vector<dlib::rectangle> dets = detector(img);
int faces = dets.size();
return faces;
}
| 36.806452 | 74 | 0.73532 | [
"vector"
] |
35df03140afda2dd7b5b3c515ac6e50cdc27c868 | 13,042 | h | C | vendor/openamq/tooling/base2/ipr/ipr_dict_table.h | cookrn/imatix_base | c1f7b509838f4cef5cc85eecfc744974db582944 | [
"MIT"
] | null | null | null | vendor/openamq/tooling/base2/ipr/ipr_dict_table.h | cookrn/imatix_base | c1f7b509838f4cef5cc85eecfc744974db582944 | [
"MIT"
] | null | null | null | vendor/openamq/tooling/base2/ipr/ipr_dict_table.h | cookrn/imatix_base | c1f7b509838f4cef5cc85eecfc744974db582944 | [
"MIT"
] | null | null | null | /*---------------------------------------------------------------------------
ipr_dict_table.h - ipr_dict_table component
This class implements the hash table container for ipr_dict. Note
that this class is not thread safe and uses no rwlocks. The table
allows linking for reference counting.
Generated from ipr_dict_table.icl by icl_gen using GSL/4.
Copyright (c) 1996-2009 iMatix Corporation
All rights reserved.
This file is licensed under the BSD license as follows:
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 iMatix Corporation 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 IMATIX CORPORATION "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 IMATIX CORPORATION 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.
These header files use macros to implement a split inclusion in which all
safe definitions (those that do not depend on the presence of other
definitions) are done first, and all unsafe definitions are done in a
second pass through the same headers.
The first header file included from the main C program defines itself as
the "root" and thus controls the inclusion of the safe/unsafe pieces of
the other headers.
*---------------------------------------------------------------------------*/
#if !defined (ICL_IMPORT_HEADERS) || (ICL_IMPORT_HEADERS == 1)
# ifndef INCLUDE_IPR_DICT_TABLE_SAFE
# define INCLUDE_IPR_DICT_TABLE_SAFE
# define INCLUDE_IPR_DICT_TABLE_ACTIVE
# if !defined (ICL_IMPORT_HEADERS)
# define ICL_IMPORT_IPR_DICT_TABLE_ROOT
# define ICL_IMPORT_HEADERS 1
# endif
# ifdef __cplusplus
extern "C" {
# endif
// Our own class typedef
typedef struct _ipr_dict_table_t ipr_dict_table_t;
#if defined (DEBUG) || defined (BASE_HISTORY) || defined (BASE_HISTORY_IPR_DICT_TABLE)
# define IPR_DICT_TABLE_HISTORY_LENGTH 32
#endif
#define IPR_DICT_TABLE_ALIVE 0xFABB
#define IPR_DICT_TABLE_DEAD 0xDEAD
#define IPR_DICT_TABLE_ASSERT_SANE(self)\
{\
if (!self) {\
icl_system_panic ("", "FATAL ERROR at %s:%u, in %s\n", __FILE__, __LINE__, ICL_ASSERT_SANE_FUNCTION);\
icl_system_panic ("", "Attempting to work with a NULL ipr_dict_table\n");\
icl_system_panic ("", "Please report this to openamq-dev@lists.openamq.org\n");\
abort ();\
}\
if (self->object_tag != IPR_DICT_TABLE_ALIVE) {\
icl_system_panic ("", "FATAL ERROR at %s:%u, in %s\n", __FILE__, __LINE__, ICL_ASSERT_SANE_FUNCTION);\
icl_system_panic ("", "ipr_dict_table at %p expected object_tag=0x%x, actual object_tag=0x%x\n", self, IPR_DICT_TABLE_ALIVE, self->object_tag);\
ipr_dict_table_show (self, ICL_CALLBACK_DUMP, stderr);\
icl_system_panic ("", "Please report this to openamq-dev@lists.openamq.org\n");\
abort ();\
}\
}
# ifdef __cplusplus
}
# endif
# include "ipr_dict.h"
# include "ipr_bucket.h"
# include "ipr_str.h"
# include "ipr_http.h"
# include "icl_mem.h"
# include "icl_system.h"
# ifdef __cplusplus
extern "C" {
# endif
# ifdef __cplusplus
}
# endif
# undef INCLUDE_IPR_DICT_TABLE_ACTIVE
# if defined (ICL_IMPORT_IPR_DICT_TABLE_ROOT)
# undef ICL_IMPORT_HEADERS
# define ICL_IMPORT_HEADERS 2
# endif
# endif
#endif
#if !defined (ICL_IMPORT_HEADERS) || (ICL_IMPORT_HEADERS == 2)
# ifndef INCLUDE_IPR_DICT_TABLE_UNSAFE
# define INCLUDE_IPR_DICT_TABLE_UNSAFE
# define INCLUDE_IPR_DICT_TABLE_ACTIVE
# include "ipr_dict.h"
# include "ipr_bucket.h"
# include "ipr_str.h"
# include "ipr_http.h"
# include "icl_mem.h"
# include "icl_system.h"
# ifdef __cplusplus
extern "C" {
# endif
// Global variables
extern Bool
ipr_dict_table_animating;
#define IPR_DICT_TABLE_INITIAL_SIZE 65535
#define IPR_DICT_TABLE_LOAD_FACTOR 75
#define IPR_DICT_TABLE_GROWTH_FACTOR 200
typedef void (ipr_dict_table_callback_fn) (ipr_dict_t *item, void *argument);
// Structure of the ipr_dict_table object
struct _ipr_dict_table_t {
volatile int
links; // Number of links to the item
volatile qbyte
zombie; // Object destroyed but not freed
#if defined (DEBUG) || defined (BASE_HISTORY) || defined (BASE_HISTORY_IPR_DICT_TABLE)
// Possession history, for tracing
volatile qbyte
history_last;
char
*history_file [IPR_DICT_TABLE_HISTORY_LENGTH];
int
history_line [IPR_DICT_TABLE_HISTORY_LENGTH];
char
*history_type [IPR_DICT_TABLE_HISTORY_LENGTH];
int
history_links [IPR_DICT_TABLE_HISTORY_LENGTH];
#endif
dbyte
object_tag; // Object validity marker
size_t
nbr_items;
size_t
max_items;
ipr_dict_t
**table_items;
ipr_dict_list_t
*list; // List of all dictionary items
char
*file_name; // If data was loaded from file
int64_t
file_size; // Size of loaded file
apr_time_t
file_time; // Time of loaded file
};
# ifdef __cplusplus
}
# endif
# ifdef __cplusplus
extern "C" {
# endif
// Method prototypes
#define ipr_dict_table_new() ipr_dict_table_new_ (__FILE__, __LINE__)
ipr_dict_table_t *
ipr_dict_table_new_ (
char * file, // Source file for call
size_t line // Line number for call
);
int
ipr_dict_table_insert (
ipr_dict_table_t * self, // Reference to object
char * key, // Hash key
ipr_dict_t * item // Item to insert
);
int
ipr_dict_table_remove (
ipr_dict_t * item // Item to remove
);
char *
ipr_dict_table_lookup (
ipr_dict_table_t * self, // Reference to self
char * name // Field to look for
);
int
ipr_dict_table_matches (
ipr_dict_table_t * self, // Reference to object
char * name, // Name of item to look for
char * match // Regular expression to check
);
char *
ipr_dict_table_template (
ipr_dict_table_t * self, // Symbol table
char * string // Original string
);
char **
ipr_dict_table_export (
ipr_dict_table_t * self, // Reference to self
Bool env, // Format as environment
char * prefix // Optional prefix for exported names
);
int
ipr_dict_table_import (
ipr_dict_table_t * self, // Reference to object
char ** strings, // Array of strings to import
Bool lower // Format names into lower case
);
int
ipr_dict_table_headers_load (
ipr_dict_table_t * self, // Reference to object
char * headers, // Headers block to import
Bool trace // Trace headers?
);
ipr_bucket_t *
ipr_dict_table_headers_save (
ipr_dict_table_t * self, // Reference to self
icl_longstr_t * prefix, // Bucket prefix
Bool trace // Trace headers?
);
char *
ipr_dict_table_headers_search (
ipr_dict_table_t * self, // Reference to self
char * name // Field to look for
);
int
ipr_dict_table_uri_load (
ipr_dict_table_t * self, // Reference to object
char * arguments // Arguments to import
);
int
ipr_dict_table_props_load (
ipr_dict_table_t * self, // Reference to object
char * string // Properties to import
);
int
ipr_dict_table_file_load (
ipr_dict_table_t * self, // Reference to object
char * filename, // Name of file to import
char * pattern // Regexp to match each line
);
int
ipr_dict_table_file_save (
ipr_dict_table_t * self, // Reference to object
char * filename, // Name of file to import
char * pattern // Pattern for saved lines
);
int
ipr_dict_table_file_sync (
ipr_dict_table_t ** self_p, // Pointer to table reference
char * filename, // Name of file to import
char * pattern // Regexp to match each line
);
void
ipr_dict_table_selftest (
void);
ipr_dict_t *
ipr_dict_table_search (
ipr_dict_table_t * self, // Table to search
char * key // Hash key
);
void
ipr_dict_table_apply (
ipr_dict_table_t * self, // Table to iterate
ipr_dict_table_callback_fn * callback, // Not documented
void * argument // Arbitrary argument pointer
);
void
ipr_dict_table_terminate (
void);
#define ipr_dict_table_show(item,opcode,trace_file) ipr_dict_table_show_ (item, opcode, trace_file, __FILE__, __LINE__)
void
ipr_dict_table_show_ (
void * item, // The opaque pointer
int opcode, // The callback opcode
FILE * trace_file, // File to print to
char * file, // Source file
size_t line // Line number
);
#define ipr_dict_table_destroy(self) ipr_dict_table_destroy_ (self, __FILE__, __LINE__)
void
ipr_dict_table_destroy_ (
ipr_dict_table_t * ( * self_p ), // Reference to object reference
char * file, // Source fileSource file
size_t line // Line numberLine number
);
#define ipr_dict_table_link(self) ipr_dict_table_link_ (self, __FILE__, __LINE__)
ipr_dict_table_t *
ipr_dict_table_link_ (
ipr_dict_table_t * self, // Not documented
char * file, // Source file for call
size_t line // Line number for call
);
#define ipr_dict_table_unlink(self) ipr_dict_table_unlink_ (self, __FILE__, __LINE__)
void
ipr_dict_table_unlink_ (
ipr_dict_table_t * ( * self_p ), // Reference to object reference
char * file, // Source file for call
size_t line // Line number for call
);
void
ipr_dict_table_show_animation (
Bool enabled // Are we enabling or disabling animation?
);
#define ipr_dict_table_new_in_scope(self_p,_scope) ipr_dict_table_new_in_scope_ (self_p, _scope, __FILE__, __LINE__)
void
ipr_dict_table_new_in_scope_ (
ipr_dict_table_t * * self_p, // Not documented
icl_scope_t * _scope, // Not documented
char * file, // Source file for call
size_t line // Line number for call
);
# ifdef __cplusplus
}
# endif
# undef INCLUDE_IPR_DICT_TABLE_ACTIVE
# if defined (ICL_IMPORT_IPR_DICT_TABLE_ROOT)
# undef ICL_IMPORT_HEADERS
# define ICL_IMPORT_HEADERS 3
# endif
# endif
#endif
#if !defined (ICL_IMPORT_HEADERS) || (ICL_IMPORT_HEADERS == 3)
# if !defined (INCLUDE_IPR_DICT_TABLE_INLINE)
# define INCLUDE_IPR_DICT_TABLE_INLINE
# define INCLUDE_IPR_DICT_TABLE_ACTIVE
# include "ipr_dict.h"
# include "ipr_bucket.h"
# include "ipr_str.h"
# include "ipr_http.h"
# include "icl_mem.h"
# include "icl_system.h"
# ifdef __cplusplus
extern "C" {
# endif
# ifdef __cplusplus
}
# endif
# undef INCLUDE_IPR_DICT_TABLE_ACTIVE
# if defined (ICL_IMPORT_IPR_DICT_TABLE_ROOT)
# undef ICL_IMPORT_HEADERS
# undef ICL_IMPORT_IPR_DICT_TABLE_ROOT
# endif
# endif
#endif
| 33.017722 | 152 | 0.628738 | [
"object"
] |
35ef0e3b02e2b4f993c0940e34cb659fc0b03000 | 2,635 | h | C | components/web_modal/single_web_contents_dialog_manager.h | kjthegod/chromium | cf940f7f418436b77e15b1ea23e6fa100ca1c91a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2020-01-25T10:18:18.000Z | 2021-01-23T15:29:56.000Z | components/web_modal/single_web_contents_dialog_manager.h | kjthegod/chromium | cf940f7f418436b77e15b1ea23e6fa100ca1c91a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2018-02-10T21:00:08.000Z | 2018-03-20T05:09:50.000Z | components/web_modal/single_web_contents_dialog_manager.h | kjthegod/chromium | cf940f7f418436b77e15b1ea23e6fa100ca1c91a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2015-03-27T11:15:39.000Z | 2016-08-17T14:19:56.000Z | // Copyright 2014 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 COMPONENTS_WEB_MODAL_SINGLE_WEB_CONTENTS_DIALOG_MANAGER_H_
#define COMPONENTS_WEB_MODAL_SINGLE_WEB_CONTENTS_DIALOG_MANAGER_H_
#include "components/web_modal/native_web_contents_modal_dialog.h"
namespace content {
class WebContents;
} // namespace content
namespace web_modal {
class WebContentsModalDialogHost;
// Interface from SingleWebContentsDialogManager to
// WebContentsModalDialogManager.
class SingleWebContentsDialogManagerDelegate {
public:
SingleWebContentsDialogManagerDelegate() {}
virtual ~SingleWebContentsDialogManagerDelegate() {}
virtual content::WebContents* GetWebContents() const = 0;
// Notify the delegate that the dialog is closing. The native
// manager will be deleted before the end of this call.
virtual void WillClose(NativeWebContentsModalDialog dialog) = 0;
private:
DISALLOW_COPY_AND_ASSIGN(SingleWebContentsDialogManagerDelegate);
};
// Provides an interface for platform-specific UI implementation for the web
// contents modal dialog. Each object will manage a single
// NativeWebContentsModalDialog during its lifecycle.
//
// Implementation classes should accept a NativeWebContentsModalDialog at
// construction time and register to be notified when the dialog is closing,
// so that it can notify its delegate (WillClose method).
class SingleWebContentsDialogManager {
public:
virtual ~SingleWebContentsDialogManager() {}
// Makes the web contents modal dialog visible. Only one web contents modal
// dialog is shown at a time per tab.
virtual void Show() = 0;
// Hides the web contents modal dialog without closing it.
virtual void Hide() = 0;
// Closes the web contents modal dialog.
// If this method causes a WillClose() call to the delegate, the manager
// will be deleted at the close of that invocation.
virtual void Close() = 0;
// Sets focus on the web contents modal dialog.
virtual void Focus() = 0;
// Runs a pulse animation for the web contents modal dialog.
virtual void Pulse() = 0;
// Called when the host view for the dialog has changed.
virtual void HostChanged(WebContentsModalDialogHost* new_host) = 0;
// Return the dialog under management by this object.
virtual NativeWebContentsModalDialog dialog() = 0;
protected:
SingleWebContentsDialogManager() {}
private:
DISALLOW_COPY_AND_ASSIGN(SingleWebContentsDialogManager);
};
} // namespace web_modal
#endif // COMPONENTS_WEB_MODAL_SINGLE_WEB_CONTENTS_DIALOG_MANAGER_H_
| 32.9375 | 77 | 0.782922 | [
"object"
] |
c40415dcff17c9559323f83f1f6d9f18684a50d5 | 52,377 | c | C | misc/xpr/xpr.c | marshallmidden/m4 | 8ff1cb050efdefe6963c6d7f459fd6f3d25eea94 | [
"BSD-2-Clause"
] | null | null | null | misc/xpr/xpr.c | marshallmidden/m4 | 8ff1cb050efdefe6963c6d7f459fd6f3d25eea94 | [
"BSD-2-Clause"
] | null | null | null | misc/xpr/xpr.c | marshallmidden/m4 | 8ff1cb050efdefe6963c6d7f459fd6f3d25eea94 | [
"BSD-2-Clause"
] | null | null | null | /* $XConsortium: xpr.c,v 1.59 94/10/14 21:22:08 kaleb Exp $ */
/*
Copyright (c) 1985 X Consortium
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 X CONSORTIUM 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.
Except as contained in this notice, the name of the X Consortium shall
not be used in advertising or otherwise to promote the sale, use or
other dealings in this Software without prior written authorization
from the X Consortium.
*/
/*
* XPR - process xwd(1) files for various printers
*
* Author: Michael R. Gretzinger, MIT Project Athena
*
* Modified by Marvin Solomon, Univeristy of Wisconsin, to handle Apple
* Laserwriter (PostScript) devices (-device ps).
* Also accepts the -compact flag that produces more compact output
* by using run-length encoding on white (1) pixels.
* This version does not (yet) support the following options
* -append -dump -noff -nosixopt -split
*
* Changes
* Copyright 1986 by Marvin Solomon and the University of Wisconsin
*
* Permission to use, copy, modify, and distribute this
* software and its documentation for any purpose and without
* fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright
* notice and this permission notice appear in supporting
* documentation, and that the names of Marvin Solomon and
* the University of Wisconsin not be used in
* advertising or publicity pertaining to distribution of the
* software without specific, written prior permission.
* Neither Marvin Solomon nor the University of Wisconsin
* makes any representations about the suitability of
* this software for any purpose. It is provided "as is"
* without express or implied warranty.
*
* Modified by Bob Scheifler for 2x2 grayscale, then ...
* Modified by Angela Bock and E. Mike Durbin, Rich Inc., to produce output
* using 2x2, 3x3, or 4x4 grayscales. This version modifies the grayscale
* conversion option of -gray to accept an input of 2, 3, or 4 to signify
* the gray level desired. The output is produced, using 5, 10, or 17-level
* gray scales, respectively.
*
* Modifications by Larry Rupp, Hewlett-Packard Company, to support HP
* LaserJet, PaintJet, and other PCL printers. Added "ljet" and "pjet"
* to devices recognized. Also added -density, -cutoff, and -noposition
* command line options.
*
*/
#include <X11/Xos.h>
#include <X11/Xfuncs.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <stdio.h>
#ifndef WIN32
#include <pwd.h>
#endif
#include "lncmd.h"
#include "xpr.h"
#include <X11/XWDFile.h>
#include <X11/Xmu/SysUtil.h>
#ifndef O_BINARY
#define O_BINARY 0
#endif
#ifdef NLS16
#ifndef NLS
#define NLS
#endif
#endif
#ifndef NLS
#define catgets(i, sn,mn,s) (s)
#else /* NLS */
#define NL_SETN 1 /* set number */
#include <nl_types.h>
nl_catd nlmsg_fd;
#endif /* NLS */
int debug = 0;
#define W_MAX 2400
#define H_MAX 3150
#define W_MARGIN 75
#define H_MARGIN 37
#define W_PAGE 2550
#define H_PAGE 3225
#ifdef NOINLINE
#define min(x,y) (((x)<(y))?(x):(y))
#endif /* NOINLINE */
#define F_PORTRAIT 1
#define F_LANDSCAPE 2
#define F_DUMP 4
#define F_NOSIXOPT 8
#define F_APPEND 16
#define F_NOFF 32
#define F_REPORT 64
#define F_COMPACT 128
#define F_INVERT 256
#define F_GRAY 512
#define F_NPOSITION 1024
#define F_SLIDE 2048
#define DEFAULT_CUTOFF ((unsigned int) (0xFFFF * 0.50))
char *infilename = NULL;
char *progname;
char *convert_data();
typedef struct _grayRec {
int level;
int sizeX, sizeY; /* 2x2, 3x3, 4x4 */
unsigned long *grayscales; /* pointer to the encoded pixels */
} GrayRec, *GrayPtr;
unsigned long grayscale2x2[] =
{0, 1, 9, 11, 15};
unsigned long grayscale3x3[] =
{0, 16, 68, 81, 325, 341, 349, 381, 383, 511};
unsigned long grayscale4x4[] =
{0, 64, 4160, 4161, 20545, 21057, 23105,
23113, 23145, 24169, 24171, 56939, 55275, 55279,
57327, 65519, 65535};
GrayRec gray2x2 = {sizeof(grayscale2x2)/sizeof(long), 2, 2, grayscale2x2};
GrayRec gray3x3 = {sizeof(grayscale3x3)/sizeof(long), 3, 3, grayscale3x3};
GrayRec gray4x4 = {sizeof(grayscale4x4)/sizeof(long), 4, 4, grayscale4x4};
main(argc, argv)
char **argv;
{
unsigned long swaptest = 1;
XWDFileHeader win;
register unsigned char (*sixmap)[];
register int i;
register int iw;
register int ih;
register int sixel_count;
char *w_name;
int scale, width, height, flags, split;
int left, top;
int top_margin, left_margin;
int hpad;
char *header, *trailer;
int plane;
int density, render;
unsigned int cutoff;
float gamma;
GrayPtr gray;
char *data;
long size;
enum orientation orientation;
enum device device;
XColor *colors = (XColor *)NULL;
if (!(progname = argv[0]))
progname = "xpr";
#ifdef NLS
nlmsg_fd = catopen("xpr", 0);
#endif
parse_args (argc, argv, &scale, &width, &height, &left, &top, &device,
&flags, &split, &header, &trailer, &plane, &gray,
&density, &cutoff, &gamma, &render);
if (device == PP) {
x2pmp(stdin, stdout, scale,
width >= 0? inch2pel((float)width/300.0): X_MAX_PELS,
height >= 0? inch2pel((float)height/300.0): Y_MAX_PELS,
left >= 0? inch2pel((float)left/300.0): inch2pel(0.60),
top >= 0? inch2pel((float)top/300.0): inch2pel(0.70),
header, trailer,
(flags & F_PORTRAIT)? PORTRAIT:
((flags & F_LANDSCAPE)? LANDSCAPE: UNSPECIFIED),
(flags & F_INVERT));
exit(0);
} else if ((device == LJET) || (device == PJET) || (device == PJETXL)) {
x2jet(stdin, stdout, scale, density, width, height, left, top,
header, trailer,
(flags & F_PORTRAIT)? PORTRAIT:
((flags & F_LANDSCAPE)? LANDSCAPE: UNSPECIFIED),
(flags & F_INVERT),
((flags & F_APPEND) && !(flags & F_NOFF)),
!(flags & F_NPOSITION),
(flags & F_SLIDE),
device, cutoff, gamma, render);
exit(0);
}
/* read in window header */
fullread(0, (char *)&win, sizeof win);
if (*(char *) &swaptest)
_swaplong((char *) &win, (long)sizeof(win));
if (win.file_version != XWD_FILE_VERSION) {
fprintf(stderr,"xpr: file format version missmatch.\n");
exit(1);
}
if (win.header_size < sizeof(win)) {
fprintf(stderr,"xpr: header size is too small.\n");
exit(1);
}
w_name = malloc((unsigned)(win.header_size - sizeof win));
fullread(0, w_name, (int) (win.header_size - sizeof win));
if(win.ncolors) {
XWDColor xwdcolor;
colors = (XColor *)malloc((unsigned) (win.ncolors * sizeof(XColor)));
for (i = 0; i < win.ncolors; i++) {
fullread(0, (char*)&xwdcolor, (int) sizeof xwdcolor);
colors[i].pixel = xwdcolor.pixel;
colors[i].red = xwdcolor.red;
colors[i].green = xwdcolor.green;
colors[i].blue = xwdcolor.blue;
colors[i].flags = xwdcolor.flags;
}
if (*(char *) &swaptest) {
for (i = 0; i < win.ncolors; i++) {
_swaplong((char *) &colors[i].pixel, (long)sizeof(long));
_swapshort((char *) &colors[i].red, (long) (3 * sizeof(short)));
}
}
if ((win.ncolors == 2) &&
(INTENSITY(&colors[0]) > INTENSITY(&colors[1])))
flags ^= F_INVERT;
}
if (plane >= (long)win.pixmap_depth) {
fprintf(stderr,"xpr: plane number exceeds image depth\n");
exit(1);
}
size = win.bytes_per_line * win.pixmap_height;
if (win.pixmap_format == XYPixmap)
size *= win.pixmap_depth;
data = malloc((unsigned)size);
fullread(0, data, (int)size);
if ((win.pixmap_depth > 1) || (win.byte_order != win.bitmap_bit_order)) {
data = convert_data(&win, data, plane, gray, colors, flags);
size = win.bytes_per_line * win.pixmap_height;
}
if (win.bitmap_bit_order == MSBFirst) {
_swapbits((unsigned char *)data, size);
win.bitmap_bit_order = LSBFirst;
}
if (flags & F_INVERT)
_invbits((unsigned char *)data, size);
/* calculate orientation and scale */
setup_layout(device, (int) win.pixmap_width, (int) win.pixmap_height,
flags, width, height, header, trailer, &scale, &orientation);
if (device == PS) {
iw = win.pixmap_width;
ih = win.pixmap_height;
} else {
/* calculate w and h cell count */
iw = win.pixmap_width;
ih = (win.pixmap_height + 5) / 6;
hpad = (ih * 6) - win.pixmap_height;
/* build pixcells from input file */
sixel_count = iw * ih;
sixmap = (unsigned char (*)[])malloc((unsigned)sixel_count);
build_sixmap(iw, ih, sixmap, hpad, &win, data);
}
/* output commands and sixel graphics */
if (device == LN03) {
/* ln03_grind_fonts(sixmap, iw, ih, scale, &pixmap); */
ln03_setup(iw, ih, orientation, scale, left, top,
&left_margin, &top_margin, flags, header, trailer);
ln03_output_sixels(sixmap, iw, ih, (flags & F_NOSIXOPT), split,
scale, top_margin, left_margin);
ln03_finish();
} else if (device == LA100) {
la100_setup(iw, ih, scale);
la100_output_sixels(sixmap, iw, ih, (flags & F_NOSIXOPT));
la100_finish();
} else if (device == PS) {
ps_setup(iw, ih, orientation, scale, left, top,
flags, header, trailer, w_name);
ps_output_bits(iw, ih, flags, orientation, &win, data);
ps_finish();
} else {
fprintf(stderr, "xpr: device not supported\n");
}
/* print some statistics */
if (flags & F_REPORT) {
fprintf(stderr, "Name: %s\n", w_name);
fprintf(stderr, "Width: %d, Height: %d\n", win.pixmap_width,
win.pixmap_height);
fprintf(stderr, "Orientation: %s, Scale: %d\n",
(orientation==PORTRAIT) ? "Portrait" : "Landscape", scale);
}
if (((device == LN03) || (device == LA100)) && (flags & F_DUMP))
dump_sixmap(sixmap, iw, ih);
exit(0);
}
usage()
{
fprintf(stderr, "usage: %s [options] [file]\n", progname);
fprintf(stderr, " -append <file> -noff -output <file>\n");
fprintf(stderr, " -compact\n");
fprintf(stderr, " -device {ln03 | la100 | ps | lw | pp | ljet | pjet | pjetxl}\n");
fprintf(stderr, " -dump\n");
fprintf(stderr, " -gamma <correction>\n");
fprintf(stderr, " -gray {2 | 3 | 4}\n");
fprintf(stderr, " -height <inches> -width <inches>\n");
fprintf(stderr, " -header <string> -trailer <string>\n");
fprintf(stderr, " -landscape -portrait\n");
fprintf(stderr, " -left <inches> -top <inches>\n");
fprintf(stderr, " -noposition\n");
fprintf(stderr, " -nosixopt\n");
fprintf(stderr, " -plane <n>\n");
fprintf(stderr, " -psfig\n");
fprintf(stderr, " -render <type>\n");
fprintf(stderr, " -report\n");
fprintf(stderr, " -rv\n");
fprintf(stderr, " -scale <scale>\n");
fprintf(stderr, " -slide\n");
fprintf(stderr, " -split <n-pages>\n");
exit(1);
}
parse_args(argc, argv, scale, width, height, left, top, device, flags,
split, header, trailer, plane, gray, density, cutoff, gamma, render)
register int argc;
register char **argv;
int *scale;
int *width;
int *height;
int *left;
int *top;
enum device *device;
int *flags;
int *split;
char **header;
char **trailer;
int *plane;
GrayPtr *gray;
int *density;
unsigned int *cutoff;
float *gamma;
int *render;
{
register char *output_filename;
register int f;
register int len;
register int pos;
#ifdef X_NOT_STDC_ENV
double atof();
int atoi();
#endif
output_filename = NULL;
*device = PS; /* default */
*flags = 0;
*scale = 0;
*split = 1;
*width = -1;
*height = -1;
*top = -1;
*left = -1;
*header = NULL;
*trailer = NULL;
*plane = -1;
*gray = (GrayPtr)NULL;
*density = 0;
*cutoff = DEFAULT_CUTOFF;
*gamma = -1.0;
*render = 0;
for (argc--, argv++; argc > 0; argc--, argv++) {
if (argv[0][0] != '-') {
infilename = *argv;
continue;
}
len = strlen(*argv);
switch (argv[0][1]) {
case 'a': /* -append <filename> */
if (!bcmp(*argv, "-append", len)) {
argc--; argv++;
if (argc == 0) usage();
output_filename = *argv;
*flags |= F_APPEND;
} else
usage();
break;
case 'c': /* -compact | -cutoff <intensity> */
if (len <= 2 )
usage();
if (!bcmp(*argv, "-compact", len)) {
*flags |= F_COMPACT;
} else if (!bcmp(*argv, "-cutoff", len)) {
argc--; argv++;
if (argc == 0) usage();
*cutoff = min((atof(*argv) / 100.0 * 0xFFFF), 0xFFFF);
} else
usage();
break;
case 'd': /* -density <num> | -device <dev> | -dump */
if (len <= 2)
usage();
if (!bcmp(*argv, "-dump", len)) {
*flags |= F_DUMP;
} else if (len <= 3) {
usage();
} else if (!bcmp(*argv, "-density", len)) {
argc--; argv++;
if (argc == 0) usage();
*density = atoi(*argv);
} else if (!bcmp(*argv, "-device", len)) {
argc--; argv++;
if (argc == 0) usage();
len = strlen(*argv);
if (len < 2)
usage();
if (!bcmp(*argv, "ln03", len)) {
*device = LN03;
} else if (!bcmp(*argv, "la100", len)) {
*device = LA100;
} else if (!bcmp(*argv, "ps", len)) {
*device = PS;
} else if (!bcmp(*argv, "lw", len)) {
*device = PS;
} else if (!bcmp(*argv, "pp", len)) {
*device = PP;
} else if (!bcmp(*argv, "ljet", len)) {
*device = LJET;
} else if (!bcmp(*argv, "pjet", len)) {
*device = PJET;
} else if (!bcmp(*argv, "pjetxl", len)) {
*device = PJETXL;
} else
usage();
} else
usage();
break;
case 'g': /* -gamma <float> | -gray <num> */
if (len <= 2)
usage();
if (!bcmp(*argv, "-gamma", len)) {
argc--; argv++;
if (argc == 0) usage();
*gamma = atof(*argv);
} else if (!bcmp(*argv, "-gray", len) ||
!bcmp(*argv, "-grey", len)) {
argc--; argv++;
if (argc == 0) usage();
switch (atoi(*argv)) {
case 2:
*gray = &gray2x2;
break;
case 3:
*gray = &gray3x3;
break;
case 4:
*gray = &gray4x4;
break;
default:
usage();
}
*flags |= F_GRAY;
} else
usage();
break;
case 'h': /* -height <inches> | -header <string> */
if (len <= 3)
usage();
if (!bcmp(*argv, "-height", len)) {
argc--; argv++;
if (argc == 0) usage();
*height = (int)(300.0 * atof(*argv));
} else if (!bcmp(*argv, "-header", len)) {
argc--; argv++;
if (argc == 0) usage();
*header = *argv;
} else
usage();
break;
case 'l': /* -landscape | -left <inches> */
if (len <= 2)
usage();
if (!bcmp(*argv, "-landscape", len)) {
*flags |= F_LANDSCAPE;
} else if (!bcmp(*argv, "-left", len)) {
argc--; argv++;
if (argc == 0) usage();
*left = (int)(300.0 * atof(*argv));
} else
usage();
break;
case 'n': /* -nosixopt | -noff | -noposition */
if (len <= 3)
usage();
if (!bcmp(*argv, "-nosixopt", len)) {
*flags |= F_NOSIXOPT;
} else if (!bcmp(*argv, "-noff", len)) {
*flags |= F_NOFF;
} else if (!bcmp(*argv, "-noposition", len)) {
*flags |= F_NPOSITION;
} else
usage();
break;
case 'o': /* -output <filename> */
if (!bcmp(*argv, "-output", len)) {
argc--; argv++;
if (argc == 0) usage();
output_filename = *argv;
} else
usage();
break;
case 'p': /* -portrait | -plane <n> */
if (len <= 2)
usage();
if (!bcmp(*argv, "-portrait", len)) {
*flags |= F_PORTRAIT;
} else if (!bcmp(*argv, "-plane", len)) {
argc--; argv++;
if (argc == 0) usage();
*plane = atoi(*argv);
} else if (!bcmp(*argv, "-psfig", len)) {
*flags |= F_NPOSITION;
} else
usage();
break;
case 'r': /* -render <type> | -report | -rv */
if (len <= 2)
usage();
if (!bcmp(*argv, "-rv", len)) {
*flags |= F_INVERT;
} else if (len <= 3) {
usage();
} else if (!bcmp(*argv, "-render", len)) {
argc--; argv++;
if (argc == 0) usage();
*render = atoi(*argv);
} else if (!bcmp(*argv, "-report", len)) {
*flags |= F_REPORT;
} else
usage();
break;
case 's': /* -scale <scale> | -slide | -split <n-pages> */
if (len <= 2)
usage();
if (!bcmp(*argv, "-scale", len)) {
argc--; argv++;
if (argc == 0) usage();
*scale = atoi(*argv);
} else if (!bcmp(*argv, "-slide", len)) {
*flags |= F_SLIDE;
} else if (!bcmp(*argv, "-split", len)) {
argc--; argv++;
if (argc == 0) usage();
*split = atoi(*argv);
} else
usage();
break;
case 't': /* -top <inches> | -trailer <string> */
if (len <= 2)
usage();
if (!bcmp(*argv, "-top", len)) {
argc--; argv++;
if (argc == 0) usage();
*top = (int)(300.0 * atof(*argv));
} else if (!bcmp(*argv, "-trailer", len)) {
argc--; argv++;
if (argc == 0) usage();
*trailer = *argv;
} else
usage();
break;
case 'w': /* -width <inches> */
if (!bcmp(*argv, "-width", len)) {
argc--; argv++;
if (argc == 0) usage();
*width = (int)(300.0 * atof(*argv));
} else
usage();
break;
default:
usage();
break;
}
}
if (infilename) {
f = open(infilename, O_RDONLY|O_BINARY, 0);
if (f < 0) {
fprintf(stderr, "xpr: error opening \"%s\" for input\n",
infilename);
perror("");
exit(1);
}
dup2(f, 0);
close(f);
} else
infilename = "stdin";
if (output_filename != NULL) {
if (!(*flags & F_APPEND)) {
f = open(output_filename, O_CREAT|O_WRONLY|O_TRUNC, 0664);
} else {
f = open(output_filename, O_WRONLY, 0);
}
if (f < 0) {
fprintf(stderr, "xpr: error opening \"%s\" for output\n",
output_filename);
perror("xpr");
exit(1);
}
if (*flags & F_APPEND) {
pos = lseek(f, 0, 2); /* get eof position */
if ((*flags & F_NOFF) &&
!(*device == LJET || *device == PJET || *device == PJETXL))
pos -= 3; /* set position before trailing */
/* formfeed and reset */
lseek(f, pos, 0); /* set pointer */
}
dup2(f, 1);
close(f);
}
}
setup_layout(device, win_width, win_height, flags, width, height,
header, trailer, scale, orientation)
enum device device;
int win_width;
int win_height;
int flags;
int width;
int height;
char *header;
char *trailer;
int *scale;
enum orientation *orientation;
{
register int w_scale;
register int h_scale;
register int iscale = *scale;
register int w_max;
register int h_max;
if (header != NULL) win_height += 75;
if (trailer != NULL) win_height += 75;
/* check maximum width and height; set orientation and scale*/
if (device == LN03 || device == PS) {
if ((win_width < win_height || (flags & F_PORTRAIT)) &&
!(flags & F_LANDSCAPE)) {
*orientation = PORTRAIT;
w_max = (width > 0)? width : W_MAX;
h_max = (height > 0)? height : H_MAX;
w_scale = w_max / win_width;
h_scale = h_max / win_height;
*scale = min(w_scale, h_scale);
} else {
*orientation = LANDSCAPE;
w_max = (width > 0)? width : H_MAX;
h_max = (height > 0)? height : W_MAX;
w_scale = w_max / win_width;
h_scale = h_max / win_height;
*scale = min(w_scale, h_scale);
}
} else { /* device == LA100 */
*orientation = PORTRAIT;
*scale = W_MAX / win_width;
}
if (*scale == 0) *scale = 1;
if (*scale > 6) *scale = 6;
if (iscale > 0 && iscale < *scale) *scale = iscale;
}
char *
convert_data(win, data, plane, gray, colors, flags)
register XWDFileHeader *win;
char *data;
int plane;
register GrayPtr gray;
XColor *colors;
int flags;
{
XImage in_image_struct, out_image_struct;
register XImage *in_image, *out_image;
register int x, y;
if ((win->pixmap_format == XYPixmap) && (plane >= 0)) {
data += win->bytes_per_line * win->pixmap_height *
(win->pixmap_depth - (plane + 1));
win->pixmap_format = XYBitmap;
win->pixmap_depth = 1;
return data;
}
/* initialize the input image */
in_image = &in_image_struct;
in_image->byte_order = win->byte_order;
in_image->bitmap_unit = win->bitmap_unit;
in_image->bitmap_bit_order = win->bitmap_bit_order;
in_image->depth = win->pixmap_depth;
in_image->bits_per_pixel = win->bits_per_pixel;
in_image->format = win->pixmap_format,
in_image->xoffset = win->xoffset,
in_image->data = data;
in_image->width = win->pixmap_width;
in_image->height = win->pixmap_height;
in_image->bitmap_pad = win->bitmap_pad;
in_image->bytes_per_line = win->bytes_per_line;
in_image->red_mask = win->red_mask;
in_image->green_mask = win->green_mask;
in_image->blue_mask = win->blue_mask;
in_image->obdata = NULL;
if (!XInitImage(in_image)) {
fprintf(stderr,"xpr: bad input image header data.\n");
exit(1);
}
if ((flags & F_GRAY) && (in_image->depth > 1) && (plane < 0)) {
win->pixmap_width *= gray->sizeX;
win->pixmap_height *= gray->sizeY;
}
win->xoffset = 0;
win->pixmap_format = XYBitmap;
win->byte_order = LSBFirst;
win->bitmap_unit = 8;
win->bitmap_bit_order = LSBFirst;
win->bitmap_pad = 8;
win->pixmap_depth = 1;
win->bits_per_pixel = 1;
win->bytes_per_line = (win->pixmap_width + 7) >> 3;
out_image = &out_image_struct;
out_image->byte_order = win->byte_order;
out_image->bitmap_unit = win->bitmap_unit;
out_image->bitmap_bit_order = win->bitmap_bit_order;
out_image->depth = win->pixmap_depth;
out_image->bits_per_pixel = win->bits_per_pixel;
out_image->format = win->pixmap_format;
out_image->xoffset = win->xoffset,
out_image->width = win->pixmap_width;
out_image->height = win->pixmap_height;
out_image->bitmap_pad = win->bitmap_pad;
out_image->bytes_per_line = win->bytes_per_line;
out_image->red_mask = 0;
out_image->green_mask = 0;
out_image->blue_mask = 0;
out_image->obdata = NULL;
out_image->data = malloc((unsigned)out_image->bytes_per_line *
out_image->height);
if (!XInitImage(out_image)) {
fprintf(stderr,"xpr: bad output image header data.\n");
exit(1);
}
if ((in_image->depth > 1) && (plane > 0)) {
for (y = 0; y < in_image->height; y++)
for (x = 0; x < in_image->width; x++)
XPutPixel(out_image, x, y,
(XGetPixel(in_image, x, y) >> plane) & 1);
} else if (plane == 0) {
for (y = 0; y < in_image->height; y++)
for (x = 0; x < in_image->width; x++)
XPutPixel(out_image, x, y, XGetPixel(in_image, x, y));
} else if ((in_image->depth > 1) &&
((win->visual_class == TrueColor) ||
(win->visual_class == DirectColor))) {
XColor color;
int direct = 0;
unsigned long rmask, gmask, bmask;
int rshift = 0, gshift = 0, bshift = 0;
rmask = win->red_mask;
while (!(rmask & 1)) {
rmask >>= 1;
rshift++;
}
gmask = win->green_mask;
while (!(gmask & 1)) {
gmask >>= 1;
gshift++;
}
bmask = win->blue_mask;
while (!(bmask & 1)) {
bmask >>= 1;
bshift++;
}
if ((win->ncolors == 0) || (win->visual_class == DirectColor))
direct = 1;
if (flags & F_GRAY) {
register int ox, oy;
int ix, iy;
unsigned long bits;
for (y = 0, oy = 0; y < in_image->height; y++, oy += gray->sizeY)
for (x = 0, ox = 0; x < in_image->width; x++, ox += gray->sizeX)
{
color.pixel = XGetPixel(in_image, x, y);
color.red = (color.pixel >> rshift) & rmask;
color.green = (color.pixel >> gshift) & gmask;
color.blue = (color.pixel >> bshift) & bmask;
if (!direct) {
color.red = colors[color.red].red;
color.green = colors[color.green].green;
color.blue = colors[color.blue].blue;
}
bits = gray->grayscales[(int)(gray->level *
INTENSITY(&color)) /
(INTENSITYPER(100) + 1)];
for (iy = 0; iy < gray->sizeY; iy++)
for (ix = 0; ix < gray->sizeX; ix++, bits >>= 1)
XPutPixel(out_image, ox + ix, oy + iy, bits);
}
} else {
for (y = 0; y < in_image->height; y++)
for (x = 0; x < in_image->width; x++) {
color.pixel = XGetPixel(in_image, x, y);
color.red = (color.pixel >> rshift) & rmask;
color.green = (color.pixel >> gshift) & gmask;
color.blue = (color.pixel >> bshift) & bmask;
if (!direct) {
color.red = colors[color.red].red;
color.green = colors[color.green].green;
color.blue = colors[color.blue].blue;
}
XPutPixel(out_image, x, y,
INTENSITY(&color) > HALFINTENSITY);
}
}
} else if (flags & F_GRAY) {
register int ox, oy;
int ix, iy;
unsigned long bits;
if (win->ncolors == 0) {
fprintf(stderr, "no colors in data, can't remap\n");
exit(1);
}
for (x = 0; x < win->ncolors; x++) {
register XColor *color = &colors[x];
color->pixel = gray->grayscales[(gray->level * INTENSITY(color)) /
(INTENSITYPER(100) + 1)];
}
for (y = 0, oy = 0; y < in_image->height; y++, oy += gray->sizeY)
for (x = 0, ox = 0; x < in_image->width; x++, ox += gray->sizeX) {
bits = colors[XGetPixel(in_image, x, y)].pixel;
for (iy = 0; iy < gray->sizeY; iy++)
for (ix = 0; ix < gray->sizeX; ix++, bits >>= 1)
XPutPixel(out_image, ox + ix, oy + iy, bits);
}
} else {
if (win->ncolors == 0) {
fprintf(stderr, "no colors in data, can't remap\n");
exit(1);
}
for (x = 0; x < win->ncolors; x++) {
register XColor *color = &colors[x];
color->pixel = (INTENSITY(color) > HALFINTENSITY);
}
for (y = 0; y < in_image->height; y++)
for (x = 0; x < in_image->width; x++)
XPutPixel(out_image, x, y,
colors[XGetPixel(in_image, x, y)].pixel);
}
free(data);
return (out_image->data);
}
dump_sixmap(sixmap, iw, ih)
register unsigned char (*sixmap)[];
int iw;
int ih;
{
register int i, j;
register unsigned char *c;
c = (unsigned char *)sixmap;
fprintf(stderr, "Sixmap:\n");
for (i = 0; i < ih; i++) {
for (j = 0; j < iw; j++) {
fprintf(stderr, "%02X ", *c++);
}
fprintf(stderr, "\n\n");
}
}
build_sixmap(iw, ih, sixmap, hpad, win, data)
int ih;
int iw;
unsigned char (*sixmap)[];
int hpad;
XWDFileHeader *win;
char *data;
{
int iwb = win->bytes_per_line;
unsigned char *line[6];
register unsigned char *c;
register int i, j;
#ifdef NOINLINE
register int w;
#endif
register int sixel;
unsigned char *buffer = (unsigned char *)data;
c = (unsigned char *)sixmap;
while (--ih >= 0) {
for (i = 0; i <= 5; i++) {
line[i] = buffer;
buffer += iwb;
}
if ((ih == 0) && (hpad > 0)) {
unsigned char *ffbuf;
ffbuf = (unsigned char *)malloc((unsigned)iwb);
for (j = 0; j < iwb; j++)
ffbuf[j] = 0xFF;
for (; --hpad >= 0; i--)
line[i] = ffbuf;
}
#ifndef NOINLINE
for (i = 0; i < iw; i++) {
sixel = extzv(line[0], i, 1);
sixel |= extzv(line[1], i, 1) << 1;
sixel |= extzv(line[2], i, 1) << 2;
sixel |= extzv(line[3], i, 1) << 3;
sixel |= extzv(line[4], i, 1) << 4;
sixel |= extzv(line[5], i, 1) << 5;
*c++ = sixel;
}
#else
for (i = 0, w = iw; w > 0; i++) {
for (j = 0; j <= 7; j++) {
sixel = ((line[0][i] >> j) & 1);
sixel |= ((line[1][i] >> j) & 1) << 1;
sixel |= ((line[2][i] >> j) & 1) << 2;
sixel |= ((line[3][i] >> j) & 1) << 3;
sixel |= ((line[4][i] >> j) & 1) << 4;
sixel |= ((line[5][i] >> j) & 1) << 5;
*c++ = sixel;
if (--w == 0) break;
}
}
#endif
}
}
build_output_filename(name, device, oname)
register char *name, *oname;
enum device device;
{
while (*name && *name != '.') *oname++ = *name++;
switch (device) {
case LN03: bcopy(".ln03", oname, 6); break;
case LA100: bcopy(".la100", oname, 7); break;
}
}
/*
ln03_grind_fonts(sixmap, iw, ih, scale, pixmap)
unsigned char (*sixmap)[];
int iw;
int ih;
int scale;
struct pixmap (**pixmap)[];
{
}
*/
ln03_setup(iw, ih, orientation, scale, left, top, left_margin, top_margin,
flags, header, trailer)
int iw;
int ih;
enum orientation orientation;
int scale;
int left;
int top;
int *left_margin;
int *top_margin;
int flags;
char *header;
char *trailer;
{
register int i;
register int lm, tm, xm;
char buf[256];
register char *bp = buf;
if (!(flags & F_APPEND)) {
sprintf(bp, LN_STR); bp += 4;
sprintf(bp, LN_SSU, 7); bp += 5;
sprintf(bp, LN_PUM_SET); bp += sizeof LN_PUM_SET - 1;
}
if (orientation == PORTRAIT) {
lm = (left > 0)? left : (((W_MAX - scale * iw) / 2) + W_MARGIN);
tm = (top > 0)? top : (((H_MAX - scale * ih * 6) / 2) + H_MARGIN);
sprintf(bp, LN_PFS, "?20"); bp += 7;
sprintf(bp, LN_DECOPM_SET); bp += sizeof LN_DECOPM_SET - 1;
sprintf(bp, LN_DECSLRM, lm, W_PAGE - lm); bp += strlen(bp);
} else {
lm = (left > 0)? left : (((H_MAX - scale * iw) / 2) + H_MARGIN);
tm = (top > 0)? top : (((W_MAX - scale * ih * 6) / 2) + W_MARGIN);
sprintf(bp, LN_PFS, "?21"); bp += 7;
sprintf(bp, LN_DECOPM_SET); bp += sizeof LN_DECOPM_SET - 1;
sprintf(bp, LN_DECSLRM, lm, H_PAGE - lm); bp += strlen(bp);
}
if (header != NULL) {
sprintf(bp, LN_VPA, tm - 100); bp += strlen(bp);
i = strlen(header);
xm = (((scale * iw) - (i * 30)) / 2) + lm;
sprintf(bp, LN_HPA, xm); bp += strlen(bp);
sprintf(bp, LN_SGR, 3); bp += strlen(bp);
bcopy(header, bp, i);
bp += i;
}
if (trailer != NULL) {
sprintf(bp, LN_VPA, tm + (scale * ih * 6) + 75); bp += strlen(bp);
i = strlen(trailer);
xm = (((scale * iw) - (i * 30)) / 2) + lm;
sprintf(bp, LN_HPA, xm); bp += strlen(bp);
sprintf(bp, LN_SGR, 3); bp += strlen(bp);
bcopy(trailer, bp, i);
bp += i;
}
sprintf(bp, LN_HPA, lm); bp += strlen(bp);
sprintf(bp, LN_VPA, tm); bp += strlen(bp);
sprintf(bp, LN_SIXEL_GRAPHICS, 9, 0, scale); bp += strlen(bp);
sprintf(bp, "\"1;1"); bp += 4; /* Pixel aspect ratio */
write(1, buf, bp-buf);
*top_margin = tm;
*left_margin = lm;
}
ln03_finish()
{
char buf[256];
register char *bp = buf;
sprintf(bp, LN_DECOPM_RESET); bp += sizeof LN_DECOPM_SET - 1;
sprintf(bp, LN_LNM); bp += 5;
sprintf(bp, LN_PUM); bp += 5;
sprintf(bp, LN_PFS, "?20"); bp += 7;
sprintf(bp, LN_SGR, 0); bp += strlen(bp);
sprintf(bp, LN_HPA, 1); bp += strlen(bp);
sprintf(bp, LN_VPA, 1); bp += strlen(bp);
write(1, buf, bp-buf);
}
/*ARGSUSED*/
la100_setup(iw, ih, scale)
{
char buf[256];
register char *bp;
int lm, tm;
bp = buf;
lm = ((80 - (int)((double)iw / 6.6)) / 2) - 1;
if (lm < 1) lm = 1;
tm = ((66 - (int)((double)ih / 2)) / 2) - 1;
if (tm < 1) tm = 1;
sprintf(bp, "\033[%d;%ds", lm, 81-lm); bp += strlen(bp);
sprintf(bp, "\033[?7l"); bp += 5;
sprintf(bp, "\033[%dd", tm); bp += strlen(bp);
sprintf(bp, "\033[%d`", lm); bp += strlen(bp);
sprintf(bp, "\033P0q"); bp += 4;
write(1, buf, bp-buf);
}
#define LA100_RESET "\033[1;80s\033[?7h"
la100_finish()
{
write(1, LA100_RESET, sizeof LA100_RESET - 1);
}
#define COMMENTVERSION "PS-Adobe-1.0"
#ifdef XPROLOG
/* for debugging, get the prolog from a file */
dump_prolog(flags) {
char *fname=(flags & F_COMPACT) ? "prolog.compact" : "prolog";
FILE *fi = fopen(fname,"r");
char buf[1024];
if (fi==NULL) {
perror(fname);
exit(1);
}
while (fgets(buf,1024,fi)) fputs(buf,stdout);
fclose(fi);
}
#else /* XPROLOG */
/* postscript "programs" to unpack and print the bitmaps being sent */
char *ps_prolog_compact[] = {
"%%Pages: 1",
"%%EndProlog",
"%%Page: 1 1",
"",
"/bitgen",
" {",
" /nextpos 0 def",
" currentfile bufspace readhexstring pop % get a chunk of input",
" % interpret each byte of the input",
" {",
" flag { % if the previous byte was FF",
" /len exch def % this byte is a count",
" result",
" nextpos",
" FFstring 0 len getinterval % grap a chunk of FF's",
" putinterval % and stuff them into the result",
" /nextpos nextpos len add def",
" /flag false def",
" }{ % otherwise",
" dup 255 eq { % if this byte is FF",
" /flag true def % just set the flag",
" pop % and toss the FF",
" }{ % otherwise",
" % move this byte to the result",
" result nextpos",
" 3 -1 roll % roll the current byte back to the top",
" put",
" /nextpos nextpos 1 add def",
" } ifelse",
" } ifelse",
" } forall",
" % trim unused space from end of result",
" result 0 nextpos getinterval",
" } def",
"",
"",
"/bitdump % stk: width, height, iscale",
" % dump a bit image with lower left corner at current origin,",
" % scaling by iscale (iscale=1 means 1/300 inch per pixel)",
" {",
" % read arguments",
" /iscale exch def",
" /height exch def",
" /width exch def",
"",
" % scale appropriately",
" width iscale mul height iscale mul scale",
"",
" % data structures:",
"",
" % allocate space for one line of input",
" /bufspace 36 string def",
"",
" % string of FF's",
" /FFstring 256 string def",
" % for all i FFstring[i]=255",
" 0 1 255 { FFstring exch 255 put } for",
"",
" % 'escape' flag",
" /flag false def",
"",
" % space for a chunk of generated bits",
" /result 4590 string def",
"",
" % read and dump the image",
" width height 1 [width 0 0 height neg 0 height]",
" { bitgen }",
" image",
" } def",
0
};
char *ps_prolog[] = {
"%%Pages: 1",
"%%EndProlog",
"%%Page: 1 1",
"",
"/bitdump % stk: width, height, iscale",
"% dump a bit image with lower left corner at current origin,",
"% scaling by iscale (iscale=1 means 1/300 inch per pixel)",
"{",
" % read arguments",
" /iscale exch def",
" /height exch def",
" /width exch def",
"",
" % scale appropriately",
" width iscale mul height iscale mul scale",
"",
" % allocate space for one scanline of input",
" /picstr % picstr holds one scan line",
" width 7 add 8 idiv % width of image in bytes = ceiling(width/8)",
" string",
" def",
"",
" % read and dump the image",
" width height 1 [width 0 0 height neg 0 height]",
" { currentfile picstr readhexstring pop }",
" image",
"} def",
0
};
dump_prolog(flags) {
char **p = (flags & F_COMPACT) ? ps_prolog_compact : ps_prolog;
while (*p) printf("%s\n",*p++);
}
#endif /* XPROLOG */
#define PAPER_WIDTH 85*30 /* 8.5 inches */
#define PAPER_LENGTH 11*300 /* 11 inches */
static int
points(n)
{
/* scale n from pixels (1/300 inch) to points (1/72 inch) */
n *= 72;
return n/300;
}
static char *
escape(s)
char *s;
{
/* make a version of s in which control characters are deleted and
* special characters are escaped.
*/
static char buf[200];
char *p = buf;
for (;*s;s++) {
if (*s < ' ' || *s > 0176) continue;
if (*s==')' || *s=='(' || *s == '\\') {
sprintf(p,"\\%03o",*s);
p += 4;
}
else *p++ = *s;
}
*p = 0;
return buf;
}
ps_setup(iw, ih, orientation, scale, left, top,
flags, header, trailer, name)
int iw;
int ih;
enum orientation orientation;
int scale;
int left;
int top;
int flags;
char *header;
char *trailer;
char *name;
{
char hostname[256];
#ifdef WIN32
char *username;
#else
struct passwd *pswd;
#endif
long clock;
int lm, bm; /* left (bottom) margin */
/* calculate margins */
if (orientation==PORTRAIT) {
lm = (left > 0)? left : ((PAPER_WIDTH - scale * iw) / 2);
bm = (top > 0)? (PAPER_LENGTH - top - scale * ih)
: ((PAPER_LENGTH - scale * ih) / 2);
} else { /* orientation == LANDSCAPE */
lm = (top > 0)? (PAPER_WIDTH - top - scale * ih)
: ((PAPER_WIDTH - scale * ih) / 2);
bm = (left > 0)? (PAPER_LENGTH - left - scale * iw)
: ((PAPER_LENGTH - scale * iw) / 2);
}
printf ("%%!%s\n", COMMENTVERSION);
printf ("%%%%BoundingBox: %d %d %d %d\n",
(flags & F_NPOSITION) ? points(lm) : 0,
(flags & F_NPOSITION) ? points(bm) : 0,
points(iw * scale), points(ih * scale));
(void) XmuGetHostname (hostname, sizeof hostname);
#ifdef WIN32
username = getenv("USERNAME");
printf ("%%%%Creator: %s:%s\n", hostname,
username ? username : "unknown");
#else
pswd = getpwuid (getuid ());
printf ("%%%%Creator: %s:%s (%s)\n", hostname,
pswd->pw_name, pswd->pw_gecos);
#endif
printf ("%%%%Title: %s (%s)\n", infilename,name);
printf ("%%%%CreationDate: %s",
(time (&clock), ctime (&clock)));
printf ("%%%%EndComments\n");
dump_prolog(flags);
if (orientation==PORTRAIT) {
if (header || trailer) {
printf("gsave\n");
printf("/Times-Roman findfont 15 scalefont setfont\n");
/* origin at bottom left corner of image */
printf("%d %d translate\n",points(lm),points(bm));
if (header) {
char *label = escape(header);
printf("%d (%s) stringwidth pop sub 2 div %d moveto\n",
points(iw*scale), label, points(ih*scale) + 10);
printf("(%s) show\n",label);
}
if (trailer) {
char *label = escape(trailer);
printf("%d (%s) stringwidth pop sub 2 div -20 moveto\n",
points(iw*scale), label);
printf("(%s) show\n",label);
}
printf("grestore\n");
}
/* set resolution to device units (300/inch) */
printf("72 300 div dup scale\n");
/* move to lower left corner of image */
if (!(flags & F_NPOSITION))
printf("%d %d translate\n",lm,bm);
/* dump the bitmap */
printf("%d %d %d bitdump\n",iw,ih,scale);
} else { /* orientation == LANDSCAPE */
if (header || trailer) {
printf("gsave\n");
printf("/Times-Roman findfont 15 scalefont setfont\n");
/* origin at top left corner of image */
printf("%d %d translate\n",points(lm),points(bm + scale * iw));
/* rotate to print the titles */
printf("-90 rotate\n");
if (header) {
char *label = escape(header);
printf("%d (%s) stringwidth pop sub 2 div %d moveto\n",
points(iw*scale), label, points(ih*scale) + 10);
printf("(%s) show\n",label);
}
if (trailer) {
char *label = escape(trailer);
printf("%d (%s) stringwidth pop sub 2 div -20 moveto\n",
points(iw*scale), label);
printf("(%s) show\n",label);
}
printf("grestore\n");
}
/* set resolution to device units (300/inch) */
printf("72 300 div dup scale\n");
/* move to lower left corner of image */
if (!(flags & F_NPOSITION))
printf("%d %d translate\n",lm,bm);
/* dump the bitmap */
printf("%d %d %d bitdump\n",ih,iw,scale);
}
}
char *ps_epilog[] = {
"",
"showpage",
"%%Trailer",
0
};
ps_finish()
{
char **p = ps_epilog;
while (*p) printf("%s\n",*p++);
}
ln03_alter_background(sixmap, iw, ih)
unsigned char (*sixmap)[];
int iw;
int ih;
{
register unsigned char *c, *stopc;
register unsigned char *startc;
register int n;
c = (unsigned char *)sixmap;
stopc = c + (iw * ih);
n = 0;
while (c < stopc) {
switch (*c) {
case 0x08: case 0x11: case 0x04: case 0x22:
case 0x20: case 0x21: case 0x24: case 0x00:
if (n == 0) startc = c;
n++;
break;
default:
if (n >= 2) {
while (n-- > 0) *startc++ = 0x00;
} else {
n = 0;
}
break;
}
c++;
}
}
ln03_output_sixels(sixmap, iw, ih, nosixopt, split, scale, top_margin,
left_margin)
unsigned char (*sixmap)[];
int iw;
int ih;
int nosixopt;
int split;
int top_margin;
int left_margin;
{
unsigned char *buf;
register unsigned char *bp;
int i;
int j;
register int k;
register unsigned char *c;
register int lastc;
register int count;
char snum[6];
register char *snp;
bp = (unsigned char *)malloc((unsigned)(iw*ih+512));
buf = bp;
count = 0;
lastc = -1;
c = (unsigned char *)sixmap;
split = ih / split; /* number of lines per page */
iw--; /* optimization */
for (i = 0; i < ih; i++) {
for (j = 0; j <= iw; j++) {
if (!nosixopt) {
if (*c == lastc && j < iw) {
count++;
c++;
continue;
}
if (count >= 3) {
bp--;
count++;
*bp++ = '!';
snp = snum;
while (count > 0) {
k = count / 10;
*snp++ = count - (k * 10) + '0';
count = k;
}
while (--snp >= snum) *bp++ = *snp;
*bp++ = (~lastc & 0x3F) + 0x3F;
} else if (count > 0) {
lastc = (~lastc & 0x3F) + 0x3F;
do {
*bp++ = lastc;
} while (--count > 0);
}
}
lastc = *c++;
*bp++ = (~lastc & 0x3F) + 0x3F;
}
*bp++ = '-'; /* New line */
lastc = -1;
if ((i % split) == 0 && i != 0) {
sprintf((char *)bp, LN_ST); bp += sizeof LN_ST - 1;
*bp++ = '\f';
sprintf((char *)bp, LN_VPA, top_margin + (i * 6 * scale));
bp += strlen((char *)bp);
sprintf((char *)bp, LN_HPA, left_margin);
bp += strlen((char *)bp);
sprintf((char *)bp, LN_SIXEL_GRAPHICS, 9, 0, scale);
bp += strlen((char *)bp);
sprintf((char *)bp, "\"1;1"); bp += 4;
}
}
sprintf((char *)bp, LN_ST); bp += sizeof LN_ST - 1;
write(1, (char *)buf, bp-buf);
}
/*ARGSUSED*/
la100_output_sixels(sixmap, iw, ih, nosixopt)
unsigned char (*sixmap)[];
int iw;
int ih;
int nosixopt;
{
unsigned char *buf;
register unsigned char *bp;
int i;
register int j, k;
register unsigned char *c;
register int lastc;
register int count;
char snum[6];
bp = (unsigned char *)malloc((unsigned)(iw*ih+512));
buf = bp;
count = 0;
lastc = -1;
c = (unsigned char *)sixmap;
for (i = 0; i < ih; i++) {
for (j = 0; j < iw; j++) {
if (*c == lastc && (j+1) < iw) {
count++;
c++;
continue;
}
if (count >= 2) {
bp -= 2;
count = 2 * (count + 1);
*bp++ = '!';
k = 0;
while (count > 0) {
snum[k++] = (count % 10) + '0';
count /= 10;
}
while (--k >= 0) *bp++ = snum[k];
*bp++ = (~lastc & 0x3F) + 0x3F;
count = 0;
} else if (count > 0) {
lastc = (~lastc & 0x3F) + 0x3F;
do {
*bp++ = lastc;
*bp++ = lastc;
} while (--count > 0);
}
lastc = (~*c & 0x3F) + 0x3F;
*bp++ = lastc;
*bp++ = lastc;
lastc = *c++;
}
*bp++ = '-'; /* New line */
lastc = -1;
}
sprintf((char *)bp, LN_ST); bp += sizeof LN_ST - 1;
*bp++ = '\f';
write(1, (char *)buf, bp-buf);
}
#define LINELEN 72 /* number of CHARS (bytes*2) per line of bitmap output */
ps_output_bits(iw, ih, flags, orientation, win, data)
int iw;
int ih;
int flags;
XWDFileHeader *win;
enum orientation orientation;
char *data;
{
unsigned long swaptest = 1;
int iwb = win->bytes_per_line;
register int i;
int bytes;
unsigned char *buffer = (unsigned char *)data;
register int ocount=0;
extern char hex1[],hex2[];
static char hex[] = "0123456789abcdef";
if (orientation == LANDSCAPE) {
/* read in and rotate the entire image */
/* The Postscript language has a rotate operator, but using it
* seem to make printing (at least on the Apple Laserwriter
* take about 10 times as long (40 minutes for a 1024x864 full-screen
* dump)! Therefore, we rotate the image here.
*/
int ocol = ih;
int owidth = (ih+31)/32; /* width of rotated image, in bytes */
int oheight = (iw+31)/32; /* height of rotated image, in scanlines */
register char *p, *q;
char *obuf;
unsigned char *ibuf;
owidth *= 4;
oheight *= 32;
/* Allocate buffer for the entire rotated image (output).
* Owidth and Oheight are rounded up to a multiple of 32 bits,
* to avoid special cases at the boundaries
*/
obuf = malloc((unsigned)(owidth*oheight));
if (obuf==0) {
fprintf(stderr,"xpr: cannot allocate %d bytes\n",owidth*oheight);
exit(1);
}
bzero(obuf,owidth*oheight);
ibuf = (unsigned char *)malloc((unsigned)(iwb + 3));
for (i=0;i<ih;i++) {
bcopy((char *)buffer, (char *)ibuf, iwb);
buffer += iwb;
if (!(*(char *) &swaptest))
_swaplong((char *)ibuf,(long)iwb);
ps_bitrot(ibuf,iw,--ocol,owidth,obuf);
}
if (!(*(char *) &swaptest))
_swaplong(obuf,(long)(iw*owidth));
q = &obuf[iw*owidth];
bytes = (ih+7)/8;
for (p=obuf;p<q;p+=owidth)
ocount = ps_putbuf((unsigned char *)p,bytes,ocount,flags&F_COMPACT);
}
else {
for (i=0;i<ih;i++) {
ocount = ps_putbuf(buffer,(iw+7)/8,ocount,flags&F_COMPACT);
buffer += iwb;
}
}
if (flags & F_COMPACT) {
if (ocount) {
/* pad to an integral number of lines */
while (ocount++ < LINELEN)
/* for debugging, pad with a "random" value */
putchar(hex[ocount&15]);
putchar('\n');
}
}
}
unsigned char _reverse_byte[0x100] = {
0x00, 0x80, 0x40, 0xc0, 0x20, 0xa0, 0x60, 0xe0,
0x10, 0x90, 0x50, 0xd0, 0x30, 0xb0, 0x70, 0xf0,
0x08, 0x88, 0x48, 0xc8, 0x28, 0xa8, 0x68, 0xe8,
0x18, 0x98, 0x58, 0xd8, 0x38, 0xb8, 0x78, 0xf8,
0x04, 0x84, 0x44, 0xc4, 0x24, 0xa4, 0x64, 0xe4,
0x14, 0x94, 0x54, 0xd4, 0x34, 0xb4, 0x74, 0xf4,
0x0c, 0x8c, 0x4c, 0xcc, 0x2c, 0xac, 0x6c, 0xec,
0x1c, 0x9c, 0x5c, 0xdc, 0x3c, 0xbc, 0x7c, 0xfc,
0x02, 0x82, 0x42, 0xc2, 0x22, 0xa2, 0x62, 0xe2,
0x12, 0x92, 0x52, 0xd2, 0x32, 0xb2, 0x72, 0xf2,
0x0a, 0x8a, 0x4a, 0xca, 0x2a, 0xaa, 0x6a, 0xea,
0x1a, 0x9a, 0x5a, 0xda, 0x3a, 0xba, 0x7a, 0xfa,
0x06, 0x86, 0x46, 0xc6, 0x26, 0xa6, 0x66, 0xe6,
0x16, 0x96, 0x56, 0xd6, 0x36, 0xb6, 0x76, 0xf6,
0x0e, 0x8e, 0x4e, 0xce, 0x2e, 0xae, 0x6e, 0xee,
0x1e, 0x9e, 0x5e, 0xde, 0x3e, 0xbe, 0x7e, 0xfe,
0x01, 0x81, 0x41, 0xc1, 0x21, 0xa1, 0x61, 0xe1,
0x11, 0x91, 0x51, 0xd1, 0x31, 0xb1, 0x71, 0xf1,
0x09, 0x89, 0x49, 0xc9, 0x29, 0xa9, 0x69, 0xe9,
0x19, 0x99, 0x59, 0xd9, 0x39, 0xb9, 0x79, 0xf9,
0x05, 0x85, 0x45, 0xc5, 0x25, 0xa5, 0x65, 0xe5,
0x15, 0x95, 0x55, 0xd5, 0x35, 0xb5, 0x75, 0xf5,
0x0d, 0x8d, 0x4d, 0xcd, 0x2d, 0xad, 0x6d, 0xed,
0x1d, 0x9d, 0x5d, 0xdd, 0x3d, 0xbd, 0x7d, 0xfd,
0x03, 0x83, 0x43, 0xc3, 0x23, 0xa3, 0x63, 0xe3,
0x13, 0x93, 0x53, 0xd3, 0x33, 0xb3, 0x73, 0xf3,
0x0b, 0x8b, 0x4b, 0xcb, 0x2b, 0xab, 0x6b, 0xeb,
0x1b, 0x9b, 0x5b, 0xdb, 0x3b, 0xbb, 0x7b, 0xfb,
0x07, 0x87, 0x47, 0xc7, 0x27, 0xa7, 0x67, 0xe7,
0x17, 0x97, 0x57, 0xd7, 0x37, 0xb7, 0x77, 0xf7,
0x0f, 0x8f, 0x4f, 0xcf, 0x2f, 0xaf, 0x6f, 0xef,
0x1f, 0x9f, 0x5f, 0xdf, 0x3f, 0xbf, 0x7f, 0xff
};
_invbits (b, n)
register unsigned char *b;
register long n;
{
do {
*b = ~*b;
b++;
} while (--n > 0);
}
/* copied from lib/X/XPutImage.c */
_swapbits (b, n)
register unsigned char *b;
register long n;
{
do {
*b = _reverse_byte[*b];
b++;
} while (--n > 0);
}
_swapshort (bp, n)
register char *bp;
register long n;
{
register char c;
register char *ep = bp + n;
do {
c = *bp;
*bp = *(bp + 1);
bp++;
*bp = c;
bp++;
}
while (bp < ep);
}
_swaplong (bp, n)
register char *bp;
register long n;
{
register char c;
register char *ep = bp + n;
register char *sp;
do {
sp = bp + 3;
c = *sp;
*sp = *bp;
*bp++ = c;
sp = bp + 1;
c = *sp;
*sp = *bp;
*bp++ = c;
bp += 2;
}
while (bp < ep);
}
/* Dump some bytes in hex, with bits in each byte reversed
* Ocount is number of chacters that have been written to the current
* output line. It's new value is returned as the result of the function.
* Ocount is ignored (and the return value is meaningless) if compact==0.
*/
int
ps_putbuf(s, n, ocount, compact)
register unsigned char *s; /* buffer to dump */
register int n; /* number of BITS to dump */
register int ocount; /* position on output line for next char */
int compact; /* if non-zero, do compaction (see below) */
{
register int ffcount = 0;
extern char hex1[],hex2[];
static char hex[] = "0123456789abcdef";
#define PUT(c) { putchar(c); if (++ocount>=LINELEN) \
{ putchar('\n'); ocount=0; }}
if (compact) {
/* The following loop puts out the bits of the image in hex,
* compressing runs of white space (represented by one bits)
* according the the following simple algorithm: A run of n
* 'ff' bytes (i.e., bytes with value 255--all ones), where
* 1<=n<=255, is represented by a single 'ff' byte followed by a
* byte containing n.
* On a typical dump of a full screen pretty much covered by
* black-on-white text windows, this compression decreased the
* size of the file from 223 Kbytes to 63 Kbytes.
* Of course, another factor of two could be saved by sending
* the bytes 'as is' rather than in hex, using some sort of
* escape convention to avoid problems with control characters.
* Another popular encoding is to pack three bytes into 4 'sixels'
* as in the LN03, etc, but I'm too lazy to write the necessary
* PostScript code to unpack fancier representations.
*/
while (n--) {
if (*s == 0xff) {
if (++ffcount == 255) {
PUT('f'); PUT('f');
PUT('f'); PUT('f');
ffcount = 0;
}
}
else {
if (ffcount) {
PUT('f'); PUT('f');
PUT(hex[ffcount >> 4]);
PUT(hex[ffcount & 0xf]);
ffcount = 0;
}
PUT(hex1[*s]);
PUT(hex2[*s]);
}
s++;
}
if (ffcount) {
PUT('f'); PUT('f');
PUT(hex[ffcount >> 4]);
PUT(hex[ffcount & 0xf]);
ffcount = 0;
}
}
else { /* no compaction: just dump the image in hex (bits reversed) */
while (n--) {
putchar(hex1[*s]);
putchar(hex2[*s++]);
}
putchar('\n');
}
return ocount;
}
ps_bitrot(s,n,col,owidth,obuf)
unsigned char *s;
register int n;
int col;
register int owidth;
char *obuf;
/* s points to a chunk of memory and n is its width in bits.
* The algorithm is, roughly,
* for (i=0;i<n;i++) {
* OR the ith bit of s into the ith row of the
* (col)th column of obuf
* }
* Assume VAX bit and byte ordering for s:
* The ith bit of s is s[j]&(1<<k) where i=8*j+k.
* It can also be retrieved as t[j]&(1<<k), where t=(int*)s and i=32*j+k.
* Also assume VAX bit and byte ordering for each row of obuf.
* Ps_putbuf() takes care of converting to Motorola 68000 byte and bit
* ordering. The following code is very carefully tuned to yield a very
* tight loop on the VAX, since it easily dominates the entire running
* time of this program. In particular, iwordp is declared last, since
* there aren't enough registers, and iwordp is referenced only once
* every 32 times through the loop.
*/
{
register int mask = 1<<(col%32);
register int iword; /* current input word (*iwordp) */
register int b = 0; /* number of bits in iword left to examine */
register char *opos = obuf + (col/32)*4;
/* pointer to word of obuf to receive next output bit */
register int *iwordp = (int *) s; /* pointer to next word of s */
while (--n>=0) {
if (--b < 0) {
iword = *iwordp++;
b = 31;
}
if (iword & 1) {
*(int *)opos |= mask;
}
opos += owidth;
iword >>= 1;
}
}
/* fullread() is the same as read(), except that it guarantees to
read all the bytes requested. */
fullread (file, data, nbytes)
int file;
char *data;
int nbytes;
{
int bytes_read;
while ((bytes_read = read(file, data, nbytes)) != nbytes) {
if (bytes_read < 0) {
perror ("error while reading standard input");
return;
}
else if (bytes_read == 0) {
fprintf (stderr, "xpr: premature end of file\n");
return;
}
nbytes -= bytes_read;
data += bytes_read;
}
}
/* mapping tables to map a byte in to the hex representation of its
* bit-reversal
*/
char hex1[]="084c2a6e195d3b7f084c2a6e195d3b7f084c2a6e195d3b7f084c2a6e195d3b7f\
084c2a6e195d3b7f084c2a6e195d3b7f084c2a6e195d3b7f084c2a6e195d3b7f\
084c2a6e195d3b7f084c2a6e195d3b7f084c2a6e195d3b7f084c2a6e195d3b7f\
084c2a6e195d3b7f084c2a6e195d3b7f084c2a6e195d3b7f084c2a6e195d3b7f";
char hex2[]="000000000000000088888888888888884444444444444444cccccccccccccccc\
2222222222222222aaaaaaaaaaaaaaaa6666666666666666eeeeeeeeeeeeeeee\
111111111111111199999999999999995555555555555555dddddddddddddddd\
3333333333333333bbbbbbbbbbbbbbbb7777777777777777ffffffffffffffff";
| 27.336639 | 90 | 0.586383 | [
"render"
] |
c4046c5e4509a3766a77cd14203f4e3c5dbbb537 | 204 | h | C | src/dft.h | ChrisThrasher/fourier-draw | c215852d588fa8458f07f1beac11698910c2add2 | [
"MIT"
] | 1 | 2022-02-08T18:46:55.000Z | 2022-02-08T18:46:55.000Z | src/dft.h | ChrisThrasher/fourier-draw | c215852d588fa8458f07f1beac11698910c2add2 | [
"MIT"
] | null | null | null | src/dft.h | ChrisThrasher/fourier-draw | c215852d588fa8458f07f1beac11698910c2add2 | [
"MIT"
] | null | null | null | #pragma once
#include <vector>
struct DftData {
float amplitude;
float frequency;
float phase;
};
auto discrete_fourier_transform(const std::vector<float>& signal) -> std::vector<DftData>;
| 17 | 90 | 0.710784 | [
"vector"
] |
c407ac1f419f3504647380302b9b86db2511ca9b | 11,159 | h | C | zzz_generated/placeholder/app2/zap-generated/CHIPClientCallbacks.h | SuGlider/connectedhomeip | 84c150a1b98746811b4931036d5ac3be0b2c592c | [
"Apache-2.0"
] | null | null | null | zzz_generated/placeholder/app2/zap-generated/CHIPClientCallbacks.h | SuGlider/connectedhomeip | 84c150a1b98746811b4931036d5ac3be0b2c592c | [
"Apache-2.0"
] | null | null | null | zzz_generated/placeholder/app2/zap-generated/CHIPClientCallbacks.h | SuGlider/connectedhomeip | 84c150a1b98746811b4931036d5ac3be0b2c592c | [
"Apache-2.0"
] | null | null | null | /*
*
* Copyright (c) 2022 Project CHIP Authors
*
* 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.
*/
// THIS FILE IS GENERATED BY ZAP
#pragma once
#include <app-common/zap-generated/af-structs.h>
#include <app-common/zap-generated/cluster-objects.h>
#include <app/InteractionModelEngine.h>
#include <app/data-model/DecodableList.h>
#include <app/util/af-enums.h>
#include <app/util/attribute-filter.h>
#include <app/util/im-client-callbacks.h>
#include <inttypes.h>
#include <lib/support/FunctionTraits.h>
#include <lib/support/Span.h>
// List specific responses
void ApplicationBasicClusterAllowedVendorListListAttributeFilter(chip::TLV::TLVReader * data,
chip::Callback::Cancelable * onSuccessCallback,
chip::Callback::Cancelable * onFailureCallback);
typedef void (*ApplicationBasicAllowedVendorListListAttributeCallback)(
void * context, const chip::app::DataModel::DecodableList<chip::VendorId> & data);
void ApplicationBasicClusterServerGeneratedCommandListListAttributeFilter(chip::TLV::TLVReader * data,
chip::Callback::Cancelable * onSuccessCallback,
chip::Callback::Cancelable * onFailureCallback);
typedef void (*ApplicationBasicServerGeneratedCommandListListAttributeCallback)(
void * context, const chip::app::DataModel::DecodableList<chip::CommandId> & data);
void ApplicationBasicClusterClientGeneratedCommandListListAttributeFilter(chip::TLV::TLVReader * data,
chip::Callback::Cancelable * onSuccessCallback,
chip::Callback::Cancelable * onFailureCallback);
typedef void (*ApplicationBasicClientGeneratedCommandListListAttributeCallback)(
void * context, const chip::app::DataModel::DecodableList<chip::CommandId> & data);
void ApplicationBasicClusterAttributeListListAttributeFilter(chip::TLV::TLVReader * data,
chip::Callback::Cancelable * onSuccessCallback,
chip::Callback::Cancelable * onFailureCallback);
typedef void (*ApplicationBasicAttributeListListAttributeCallback)(
void * context, const chip::app::DataModel::DecodableList<chip::AttributeId> & data);
void ContentLauncherClusterAcceptHeaderListAttributeFilter(chip::TLV::TLVReader * data,
chip::Callback::Cancelable * onSuccessCallback,
chip::Callback::Cancelable * onFailureCallback);
typedef void (*ContentLauncherAcceptHeaderListAttributeCallback)(void * context,
const chip::app::DataModel::DecodableList<chip::CharSpan> & data);
void ContentLauncherClusterServerGeneratedCommandListListAttributeFilter(chip::TLV::TLVReader * data,
chip::Callback::Cancelable * onSuccessCallback,
chip::Callback::Cancelable * onFailureCallback);
typedef void (*ContentLauncherServerGeneratedCommandListListAttributeCallback)(
void * context, const chip::app::DataModel::DecodableList<chip::CommandId> & data);
void ContentLauncherClusterClientGeneratedCommandListListAttributeFilter(chip::TLV::TLVReader * data,
chip::Callback::Cancelable * onSuccessCallback,
chip::Callback::Cancelable * onFailureCallback);
typedef void (*ContentLauncherClientGeneratedCommandListListAttributeCallback)(
void * context, const chip::app::DataModel::DecodableList<chip::CommandId> & data);
void ContentLauncherClusterAttributeListListAttributeFilter(chip::TLV::TLVReader * data,
chip::Callback::Cancelable * onSuccessCallback,
chip::Callback::Cancelable * onFailureCallback);
typedef void (*ContentLauncherAttributeListListAttributeCallback)(
void * context, const chip::app::DataModel::DecodableList<chip::AttributeId> & data);
void GeneralCommissioningClusterServerGeneratedCommandListListAttributeFilter(chip::TLV::TLVReader * data,
chip::Callback::Cancelable * onSuccessCallback,
chip::Callback::Cancelable * onFailureCallback);
typedef void (*GeneralCommissioningServerGeneratedCommandListListAttributeCallback)(
void * context, const chip::app::DataModel::DecodableList<chip::CommandId> & data);
void GeneralCommissioningClusterClientGeneratedCommandListListAttributeFilter(chip::TLV::TLVReader * data,
chip::Callback::Cancelable * onSuccessCallback,
chip::Callback::Cancelable * onFailureCallback);
typedef void (*GeneralCommissioningClientGeneratedCommandListListAttributeCallback)(
void * context, const chip::app::DataModel::DecodableList<chip::CommandId> & data);
void GeneralCommissioningClusterAttributeListListAttributeFilter(chip::TLV::TLVReader * data,
chip::Callback::Cancelable * onSuccessCallback,
chip::Callback::Cancelable * onFailureCallback);
typedef void (*GeneralCommissioningAttributeListListAttributeCallback)(
void * context, const chip::app::DataModel::DecodableList<chip::AttributeId> & data);
void KeypadInputClusterServerGeneratedCommandListListAttributeFilter(chip::TLV::TLVReader * data,
chip::Callback::Cancelable * onSuccessCallback,
chip::Callback::Cancelable * onFailureCallback);
typedef void (*KeypadInputServerGeneratedCommandListListAttributeCallback)(
void * context, const chip::app::DataModel::DecodableList<chip::CommandId> & data);
void KeypadInputClusterClientGeneratedCommandListListAttributeFilter(chip::TLV::TLVReader * data,
chip::Callback::Cancelable * onSuccessCallback,
chip::Callback::Cancelable * onFailureCallback);
typedef void (*KeypadInputClientGeneratedCommandListListAttributeCallback)(
void * context, const chip::app::DataModel::DecodableList<chip::CommandId> & data);
void KeypadInputClusterAttributeListListAttributeFilter(chip::TLV::TLVReader * data, chip::Callback::Cancelable * onSuccessCallback,
chip::Callback::Cancelable * onFailureCallback);
typedef void (*KeypadInputAttributeListListAttributeCallback)(void * context,
const chip::app::DataModel::DecodableList<chip::AttributeId> & data);
void OperationalCredentialsClusterFabricsListAttributeFilter(chip::TLV::TLVReader * data,
chip::Callback::Cancelable * onSuccessCallback,
chip::Callback::Cancelable * onFailureCallback);
typedef void (*OperationalCredentialsFabricsListAttributeCallback)(
void * context,
const chip::app::DataModel::DecodableList<
chip::app::Clusters::OperationalCredentials::Structs::FabricDescriptor::DecodableType> & data);
void OperationalCredentialsClusterTrustedRootCertificatesListAttributeFilter(chip::TLV::TLVReader * data,
chip::Callback::Cancelable * onSuccessCallback,
chip::Callback::Cancelable * onFailureCallback);
typedef void (*OperationalCredentialsTrustedRootCertificatesListAttributeCallback)(
void * context, const chip::app::DataModel::DecodableList<chip::ByteSpan> & data);
void TargetNavigatorClusterTargetListListAttributeFilter(chip::TLV::TLVReader * data,
chip::Callback::Cancelable * onSuccessCallback,
chip::Callback::Cancelable * onFailureCallback);
typedef void (*TargetNavigatorTargetListListAttributeCallback)(
void * context,
const chip::app::DataModel::DecodableList<chip::app::Clusters::TargetNavigator::Structs::TargetInfo::DecodableType> & data);
void TargetNavigatorClusterServerGeneratedCommandListListAttributeFilter(chip::TLV::TLVReader * data,
chip::Callback::Cancelable * onSuccessCallback,
chip::Callback::Cancelable * onFailureCallback);
typedef void (*TargetNavigatorServerGeneratedCommandListListAttributeCallback)(
void * context, const chip::app::DataModel::DecodableList<chip::CommandId> & data);
void TargetNavigatorClusterClientGeneratedCommandListListAttributeFilter(chip::TLV::TLVReader * data,
chip::Callback::Cancelable * onSuccessCallback,
chip::Callback::Cancelable * onFailureCallback);
typedef void (*TargetNavigatorClientGeneratedCommandListListAttributeCallback)(
void * context, const chip::app::DataModel::DecodableList<chip::CommandId> & data);
void TargetNavigatorClusterAttributeListListAttributeFilter(chip::TLV::TLVReader * data,
chip::Callback::Cancelable * onSuccessCallback,
chip::Callback::Cancelable * onFailureCallback);
typedef void (*TargetNavigatorAttributeListListAttributeCallback)(
void * context, const chip::app::DataModel::DecodableList<chip::AttributeId> & data);
| 82.051471 | 132 | 0.608298 | [
"model"
] |
c40990d1e087b4b70f5f654d36f65610a0e1ea98 | 7,150 | h | C | ext/tasks_generator/variants.h | iAppleJack/task_generator_mephi | a0fd4185cdb567af6dd93b9af37a4a31d70ea17e | [
"MIT"
] | null | null | null | ext/tasks_generator/variants.h | iAppleJack/task_generator_mephi | a0fd4185cdb567af6dd93b9af37a4a31d70ea17e | [
"MIT"
] | null | null | null | ext/tasks_generator/variants.h | iAppleJack/task_generator_mephi | a0fd4185cdb567af6dd93b9af37a4a31d70ea17e | [
"MIT"
] | null | null | null | #pragma once
#include <vector>
#include "question.h"
namespace ailab {
class variants_t {
mutable double fitness;
mutable bool changed;
config_t const &config;
size_t questions_count;
std::vector<std::vector<question_t>> questions;
public:
variants_t(config_t const &config = config_t()) noexcept :
fitness(0),
changed(true),
config(config),
questions(config.variants_count) {
}
variants_t(variants_t const &v) noexcept :
fitness(v.fitness),
changed(v.changed),
config(v.config),
questions(v.questions) {
}
variants_t(variants_t &&v) noexcept :
config(v.config) {
std::swap(fitness, v.fitness);
std::swap(changed, v.changed);
std::swap(questions, v.questions);
}
variants_t &operator = (variants_t &&v) noexcept {
std::swap(fitness, v.fitness);
std::swap(changed, v.changed);
std::swap(questions, v.questions);
return *this;
}
variants_t &operator = (variants_t const &v) noexcept {
fitness = v.fitness;
changed = v.changed;
questions = v.questions;
return *this;
}
void push_back(std::vector<question_t> const &q) noexcept {
questions.push_back(q);
}
size_t size() const noexcept {
return questions.size();
}
std::vector<std::vector<question_t>>::iterator begin() noexcept {
return questions.begin();
}
std::vector<std::vector<question_t>>::iterator end() noexcept {
return questions.end();
}
double calculate_fitness_function() const noexcept {
if (!changed)
return fitness;
size_t questions_count = 0;
for (auto const &v : questions)
questions_count += v.size();
{
size_t buffer[questions_count];
for (size_t i = 0; i < questions.size(); ++i)
for (size_t j = 0; j < questions[i].size(); ++j)
buffer[i * config.questions_count + j] = questions[i][j].get_question_id();
std::sort(buffer, buffer + questions_count);
size_t count = 1;
for (size_t i = 1; i < questions_count; ++i)
count += buffer[i] != buffer[i - 1];
fitness = double(count) / questions_count;
}
{
for (size_t i = 0; i < questions.size(); ++i) {
size_t buffer[questions[i].size()];
for (size_t j = 0; j < questions[i].size(); ++j)
buffer[j] = questions[i][j].get_parent_topic_id();
std::sort(buffer, buffer + questions[i].size());
size_t count = 1;
for (size_t j = 1; j < questions[i].size(); ++j)
count += buffer[j] != buffer[j - 1];
fitness += double(count) / questions[i].size();
}
}
{
for (size_t i = 0; i < questions.size(); ++i) {
size_t buffer[questions[i].size()];
for (size_t j = 0; j < questions[i].size(); ++j)
buffer[j] = questions[i][j].get_second_level_topic_id();
std::sort(buffer, buffer + questions[i].size());
size_t count = 1;
for (size_t j = 1; j < questions[i].size(); ++j)
count += buffer[j] != buffer[j - 1];
fitness += double(count) / questions[i].size();
}
}
{
for (size_t i = 0; i < questions.size(); ++i) {
size_t buffer[questions[i].size()];
for (size_t j = 0; j < questions[i].size(); ++j)
buffer[j] = questions[i][j].get_question_id();
std::sort(buffer, buffer + questions[i].size());
size_t count = 1;
for (size_t j = 1; j < questions[i].size(); ++j)
count += buffer[j] != buffer[j - 1];
fitness += count == questions[i].size();
}
}
{
for (size_t i = 0; i < questions.size(); ++i) {
size_t buffer[questions[i].size()];
for (size_t j = 0; j < questions[i].size(); ++j)
buffer[j] = questions[i][j].get_topic_id();
std::sort(buffer, buffer + questions[i].size());
size_t count = 1;
for (size_t j = 1; j < questions[i].size(); ++j)
count += buffer[j] != buffer[j - 1];
fitness += double(count) / questions[i].size();
}
}
{
double buffer[questions_count];
for (size_t i = 0; i < questions.size(); ++i)
for (size_t j = 0; j < questions[i].size(); ++j)
buffer[i * config.questions_count + j] = questions[i][j].get_difficulty();
double avg = 0;
for (size_t i = 0; i < questions_count; ++i)
avg += buffer[i];
avg /= questions_count;
double x = 0;
for (size_t i = 0; i < questions_count; ++i)
x += (buffer[i] - avg) * (buffer[i] - avg);
x /= questions_count;
x = sqrt(x);
fitness += x;
}
{
for (size_t i = 0; i < questions.size(); ++i) {
size_t buffer[questions[i].size()];
for (size_t j = 0; j < questions[i].size(); ++j)
buffer[j] = questions[i][j].get_topic_id();
std::sort(buffer, buffer + questions[i].size());
size_t count = 1;
for (size_t j = 1; j < questions[i].size(); ++j)
count += buffer[j] != buffer[j - 1];
struct pair {
size_t first;
size_t second;
};
pair counter[count];
for (size_t i = 0; i < count; ++i)
counter[i].first = counter[i].second = 0;
ssize_t k = -1;
for (size_t j = 0; j < questions[i].size(); ++j) {
if (k == -1 || buffer[j] != counter[k].first) {
++k;
counter[k].second = 0;
}
++counter[k].second;
}
std::sort(counter, counter + count, [] (pair const &a, pair const &b) -> bool {
return a.second > b.second;
});
double x = 0;
for (size_t j = 1; j < count; ++j)
x += counter[j].second / counter[j - 1].second;
fitness += x;
}
}
changed = false;
return fitness;
}
variants_t crossover(variants_t const &v) const noexcept {
variants_t result(*this);
size_t questions_count = 0;
for (auto const &v : questions)
questions_count += v.size();
size_t to_swap = rand() % questions_count;
for (size_t i = 0; i < result.questions.size() && to_swap; ++i)
for (size_t j = 0; j < result.questions[i].size() && to_swap; ++j, --to_swap)
result.questions[i][j] = v.questions[i][j];
return result;
}
std::vector<question_t> &operator [] (size_t i) noexcept {
changed = true;
return questions[i];
}
std::vector<question_t> const &operator [] (size_t i) const noexcept {
return questions[i];
}
void strong_mutation(question_shaker_t const &shaker) noexcept {
for (std::vector<question_t> &q : *this) {
std::sort(q.begin(), q.end(), [] (question_t const &a, question_t const &b) -> bool {
return a.get_question_id() < b.get_question_id();
});
for (size_t i = 1; i < q.size(); ++i) {
if (q[i].get_question_id() == q[i - 1].get_question_id()) {
size_t r = rand() % config.topics.size();
q[i - 1] = shaker.get_question(config.topics[r]);
}
}
}
changed = true;
}
std::vector<std::vector<question_t>> const &get_questions() const noexcept {
return questions;
}
};
}
| 30.818966 | 91 | 0.550629 | [
"vector"
] |
c4112139ed8213d430307ada3ea79bbda7e5c0ed | 2,323 | h | C | SSYTreeTransformer.h | jerrykrinock/ClassesObjC | b680efaf27c0a20440fc47b4fdc320a9903b5f2a | [
"Apache-2.0"
] | 15 | 2015-01-03T20:52:46.000Z | 2020-08-18T13:16:40.000Z | SSYTreeTransformer.h | jerrykrinock/ClassesObjC | b680efaf27c0a20440fc47b4fdc320a9903b5f2a | [
"Apache-2.0"
] | 1 | 2015-08-30T19:52:41.000Z | 2015-08-30T20:18:29.000Z | SSYTreeTransformer.h | jerrykrinock/ClassesObjC | b680efaf27c0a20440fc47b4fdc320a9903b5f2a | [
"Apache-2.0"
] | 1 | 2019-07-08T06:18:02.000Z | 2019-07-08T06:18:02.000Z | #import <Foundation/Foundation.h>
/* This class is a "transformer" which can be used for creating a tree of
NSMutableDictionaries from a prototype tree of NSMutableDictionaries, where
the two trees have different formats; that is, different keys and sub-keys.
*/
@interface SSYTreeTransformer : NSObject
{
SEL _reformatter;
SEL _childrenInExtractor ;
SEL _newParentMover ;
id _contextObject ;
}
+ (SSYTreeTransformer*)treeTransformerWithReformatter:(SEL)reformatter
childrenInExtractor:(SEL)childrenInExtractor
newParentMover:(SEL)newParentMover
contextObject:(id)contextObject ;
/*
reformatter must be an selector which, when sent to an instance of the
input class, returns an instance of the output class, autoreleased,
representing the a shallow copy of the receiver in the output class,
or nil if the receiver cannot be transformed due to missing keys or
other corruption. If the receiver has children, the returned
object should have no children, but shall accept children when
newParentMover is executed with the return object as parameter.
reformatter may optionally accept one argument. There are thus two
alternative prototypes:
(id)reformat ;
(id)reformatWithContext: ;
childrenInExtractor must be a selector which, when sent to an object
of the input class, will return an autoreleased NSArray of the
receiver's children, or nil if no children. Prototype:
(NSArray*)children ;
newParentMover must be selector which, when sent to an object of the
output class, with a parameter equal to another object of the output
class, will append the receiver to the children of the other object.
Prototype:
(void)moveToNewParent:(NSMutableDictionary*)newParent ;
contextObject is an object that will be passed as an argument to the
reformatter. If reformatter does not have an argument, contextObject
must be nil. If reformatter does have an argument, contextObject must
not be nil.
*/
+ (SSYTreeTransformer*)treeTransformerWithReformatter:(SEL)reformatter
childrenInExtractor:(SEL)childrenInExtractor
newParentMover:(SEL)newParentMover ;
/*
Same as previous method, specialized to the case of no reformatter argument */
- (id)copyDeepTransformOf:(id)nodeIn ;
/* returns a copy which the invoking method must release */
@end
| 37.467742 | 78 | 0.777873 | [
"object"
] |
dbb23486825da9177ba3c3818413d40ded13a396 | 2,221 | h | C | fancy2d/Renderer/f2dParticle.h | Legacy-LuaSTG-Engine/LuaSTG-Sub | c7d21da53fc86efe4e3907738f8fed324581dee0 | [
"MIT"
] | 6 | 2022-02-26T09:21:40.000Z | 2022-02-28T11:03:23.000Z | fancy2d/Renderer/f2dParticle.h | Legacy-LuaSTG-Engine/LuaSTG-Sub | c7d21da53fc86efe4e3907738f8fed324581dee0 | [
"MIT"
] | null | null | null | fancy2d/Renderer/f2dParticle.h | Legacy-LuaSTG-Engine/LuaSTG-Sub | c7d21da53fc86efe4e3907738f8fed324581dee0 | [
"MIT"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////
/// @file f2dParticle.h
/// @brief fancy2D 2D粒子
////////////////////////////////////////////////////////////////////////////////
#pragma once
#include "fcyRefObj.h"
#include "f2dRenderer.h"
#include <vector>
#include "fcyMisc\fcyRandom.h"
////////////////////////////////////////////////////////////////////////////////
/// @brief fancy2D 2D粒子池实现
////////////////////////////////////////////////////////////////////////////////
class f2dParticlePoolImpl :
public fcyRefObjImpl<f2dParticlePool>
{
public:
struct Particle
{
f2dSprite* pSprite;
fBool bInUse;
float CurTime; // 当前生命值
float Angle; // 当前角度
fcyVec2 Pos;
fcyVec2 CreatePos;
fcyVec2 V; // 速度
float RA; // 法向加速度
float TA; // 切向加速度
float Spin; // 自旋速度
float LifeTime; // 生命值
float RandomSeed; // 随机数
fcyColor CurColor; // 当前颜色
fcyColor StartColor; // 开始颜色
fcyColor EndColor; // 终止颜色
fcyVec2 CurScale; // 当前缩放
fcyVec2 StartScale; // 开始缩放
fcyVec2 EndScale; // 终止缩放
};
protected:
fcyRandomWELL512 m_Randomizer;
std::vector<Particle> m_ParticlePool;
std::vector<f2dParticleForce*> m_ForcePool;
fuInt m_ParticleCount;
public: // 接口实现
fuInt GetRandomSeed()
{
return m_Randomizer.GetRandSeed();
}
void SetRandomSeed(fuInt Seed)
{
m_Randomizer.SetSeed(Seed);
}
fFloat RandFloat(fFloat Min, fFloat Max)
{
return m_Randomizer.GetRandFloat(Min, Max);
}
fuInt GetCount()
{
return m_ParticleCount;
}
fuInt GetCapacity()
{
return m_ParticlePool.size();
}
void Clear()
{
// 处理所有粒子
std::vector<Particle>::iterator i = m_ParticlePool.begin();
while(i != m_ParticlePool.end())
{
FCYSAFEKILL(i->pSprite);
++i;
}
m_ParticlePool.clear();
}
fResult AppendForce(f2dParticleForce* pForce);
bool RemoveForce(f2dParticleForce* pForce);
void ClearForce();
fResult Emitted(f2dSprite* pSprite, const fcyVec2& Center, const fcyVec2& EmittedCountRange, const f2dParticleCreationDesc& Desc);
void Update(fFloat ElapsedTime);
void Render(f2dGraphics2D* pGraph);
public:
f2dParticlePoolImpl()
: m_ParticleCount(0) {}
~f2dParticlePoolImpl();
};
| 21.355769 | 131 | 0.589374 | [
"render",
"vector"
] |
dbbaee063bc4b6e4bbed1668b53c65ab82e8cd53 | 1,159 | h | C | src/backend/IOFactory.h | salilab/rmf | 4895bff9d22381882ac38180bdd025e22bdc7c00 | [
"Apache-2.0"
] | 2 | 2017-12-22T18:09:47.000Z | 2019-12-18T05:00:50.000Z | src/backend/IOFactory.h | salilab/rmf | 4895bff9d22381882ac38180bdd025e22bdc7c00 | [
"Apache-2.0"
] | 5 | 2015-03-07T19:32:39.000Z | 2021-04-22T20:00:10.000Z | src/backend/IOFactory.h | salilab/rmf | 4895bff9d22381882ac38180bdd025e22bdc7c00 | [
"Apache-2.0"
] | 2 | 2015-03-12T18:34:23.000Z | 2015-06-19T20:15:14.000Z | /**
* \file RMF/internal/SharedData.h
* \brief Handle read/write of Model data from/to files.
*
* Copyright 2007-2021 IMP Inventors. All rights reserved.
*
*/
#ifndef RMF_INTERNAL_IO_FACTORY_H
#define RMF_INTERNAL_IO_FACTORY_H
#include "RMF/config.h"
#include "RMF/internal/SharedData.h"
#include "RMF/BufferHandle.h"
#include "RMF/BufferConstHandle.h"
#include "RMF/infrastructure_macros.h"
#include <boost/shared_ptr.hpp>
RMF_ENABLE_WARNINGS
namespace RMF {
namespace backends {
class IOFactory {
public:
virtual std::string get_file_extension() const = 0;
virtual boost::shared_ptr<IO> read_buffer(BufferConstHandle) const {
return boost::shared_ptr<IO>();
}
virtual boost::shared_ptr<IO> read_file(const std::string &) const {
return boost::shared_ptr<IO>();
}
virtual boost::shared_ptr<IO> create_buffer(BufferHandle) const {
return boost::shared_ptr<IO>();
}
virtual boost::shared_ptr<IO> create_file(const std::string &) const {
return boost::shared_ptr<IO>();
}
virtual ~IOFactory() {}
};
} // namespace internal
} /* namespace RMF */
RMF_DISABLE_WARNINGS
#endif /* RMF_INTERNAL_IO_FACTORY_H */
| 23.653061 | 72 | 0.726488 | [
"model"
] |
dbc406269f02b70d65f8c53ff408a7eb074b4726 | 2,254 | h | C | cases/comparison_navigators/param/post/objects/surfer__us_15o58__surftimeconst_4o0__reorientationtime_0o5/parameters.h | C0PEP0D/sheld0n | 497d4ee8b6b1815cd5fa1b378d1b947ee259f4bc | [
"MIT"
] | null | null | null | cases/comparison_navigators/param/post/objects/surfer__us_15o58__surftimeconst_4o0__reorientationtime_0o5/parameters.h | C0PEP0D/sheld0n | 497d4ee8b6b1815cd5fa1b378d1b947ee259f4bc | [
"MIT"
] | null | null | null | cases/comparison_navigators/param/post/objects/surfer__us_15o58__surftimeconst_4o0__reorientationtime_0o5/parameters.h | C0PEP0D/sheld0n | 497d4ee8b6b1815cd5fa1b378d1b947ee259f4bc | [
"MIT"
] | null | null | null | #ifndef C0P_PARAM_POST_OBJECTS_SURFER__US_15O58__SURFTIMECONST_4O0__REORIENTATIONTIME_0O5_PARAMETERS_H
#define C0P_PARAM_POST_OBJECTS_SURFER__US_15O58__SURFTIMECONST_4O0__REORIENTATIONTIME_0O5_PARAMETERS_H
#pragma once
// THIS FILE SHOULD NOT BE EDITED DIRECTLY BY THE USERS.
// THIS FILE WILL BE AUTOMATICALLY EDITED WHEN THE
// COPY/REMOVE COMMANDS ARE USED
// std include
#include <memory> // shared_ptr
#include <vector>
#include <string>
// app include
#include "core/post/objects/object/post/core.h"
// FLAG: INCLUDE POST BEGIN
#include "param/post/objects/surfer__us_15o58__surftimeconst_4o0__reorientationtime_0o5/px/choice.h"
#include "param/post/objects/surfer__us_15o58__surftimeconst_4o0__reorientationtime_0o5/py/choice.h"
#include "param/post/objects/surfer__us_15o58__surftimeconst_4o0__reorientationtime_0o5/pz/choice.h"
// FLAG: INCLUDE POST END
namespace c0p {
// SurferUs15O58Surftimeconst4O0Reorientationtime0O5 post processing parameters
template<typename TypeSurferUs15O58Surftimeconst4O0Reorientationtime0O5Step>
struct PostSurferUs15O58Surftimeconst4O0Reorientationtime0O5Parameters {
std::string name = "surfer__us_15o58__surftimeconst_4o0__reorientationtime_0o5";
// make data
std::vector<std::shared_ptr<PostPostPost<TypeSurferUs15O58Surftimeconst4O0Reorientationtime0O5Step>>> data;
PostSurferUs15O58Surftimeconst4O0Reorientationtime0O5Parameters(std::shared_ptr<TypeSurferUs15O58Surftimeconst4O0Reorientationtime0O5Step> sSurferUs15O58Surftimeconst4O0Reorientationtime0O5Step) {
// FLAG: MAKE POST BEGIN
data.push_back(std::make_shared<PostSurferUs15O58Surftimeconst4O0Reorientationtime0O5Px<TypeSurferUs15O58Surftimeconst4O0Reorientationtime0O5Step>>(sSurferUs15O58Surftimeconst4O0Reorientationtime0O5Step));
data.push_back(std::make_shared<PostSurferUs15O58Surftimeconst4O0Reorientationtime0O5Py<TypeSurferUs15O58Surftimeconst4O0Reorientationtime0O5Step>>(sSurferUs15O58Surftimeconst4O0Reorientationtime0O5Step));
data.push_back(std::make_shared<PostSurferUs15O58Surftimeconst4O0Reorientationtime0O5Pz<TypeSurferUs15O58Surftimeconst4O0Reorientationtime0O5Step>>(sSurferUs15O58Surftimeconst4O0Reorientationtime0O5Step));
// FLAG: MAKE POST END
}
};
}
#endif
| 54.97561 | 213 | 0.858917 | [
"object",
"vector"
] |
dbddfd1f798021767df6b360125f44254f55a5a1 | 2,725 | h | C | cartographer/mapping/internal/testing/mock_pose_graph.h | laotie/cartographer | b8228ee6564f5a7ad0d6d0b9a30516521cff2ee9 | [
"Apache-2.0"
] | 5,196 | 2016-08-04T14:52:31.000Z | 2020-04-02T18:30:00.000Z | cartographer/mapping/internal/testing/mock_pose_graph.h | laotie/cartographer | b8228ee6564f5a7ad0d6d0b9a30516521cff2ee9 | [
"Apache-2.0"
] | 1,206 | 2016-08-03T14:27:00.000Z | 2020-03-31T21:14:18.000Z | cartographer/mapping/internal/testing/mock_pose_graph.h | laotie/cartographer | b8228ee6564f5a7ad0d6d0b9a30516521cff2ee9 | [
"Apache-2.0"
] | 1,810 | 2016-08-03T05:45:02.000Z | 2020-04-02T03:44:18.000Z | /*
* Copyright 2018 The Cartographer Authors
*
* 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 CARTOGRAPHER_MAPPING_INTERNAL_TESTING_MOCK_POSE_GRAPH_H_
#define CARTOGRAPHER_MAPPING_INTERNAL_TESTING_MOCK_POSE_GRAPH_H_
#include "cartographer/mapping/pose_graph_interface.h"
#include "glog/logging.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
namespace cartographer {
namespace mapping {
namespace testing {
class MockPoseGraph : public mapping::PoseGraphInterface {
public:
MockPoseGraph() = default;
~MockPoseGraph() override = default;
MOCK_METHOD0(RunFinalOptimization, void());
MOCK_CONST_METHOD0(GetAllSubmapData,
mapping::MapById<mapping::SubmapId, SubmapData>());
MOCK_CONST_METHOD1(GetSubmapData, SubmapData(const SubmapId&));
MOCK_CONST_METHOD0(GetAllSubmapPoses,
mapping::MapById<mapping::SubmapId, SubmapPose>());
MOCK_CONST_METHOD1(GetLocalToGlobalTransform, transform::Rigid3d(int));
MOCK_CONST_METHOD0(
GetTrajectoryNodes,
mapping::MapById<mapping::NodeId, mapping::TrajectoryNode>());
MOCK_CONST_METHOD0(
GetTrajectoryNodePoses,
mapping::MapById<mapping::NodeId, mapping::TrajectoryNodePose>());
MOCK_CONST_METHOD0(
GetTrajectoryStates,
std::map<int, mapping::PoseGraphInterface::TrajectoryState>());
MOCK_CONST_METHOD0(GetLandmarkPoses,
std::map<std::string, transform::Rigid3d>());
MOCK_METHOD3(SetLandmarkPose,
void(const std::string&, const transform::Rigid3d&, const bool));
MOCK_METHOD1(DeleteTrajectory, void(int));
MOCK_CONST_METHOD1(IsTrajectoryFinished, bool(int));
MOCK_CONST_METHOD1(IsTrajectoryFrozen, bool(int));
MOCK_CONST_METHOD0(
GetTrajectoryData,
std::map<int, mapping::PoseGraphInterface::TrajectoryData>());
MOCK_CONST_METHOD0(constraints, std::vector<Constraint>());
MOCK_CONST_METHOD1(ToProto, mapping::proto::PoseGraph(bool));
MOCK_METHOD1(SetGlobalSlamOptimizationCallback,
void(GlobalSlamOptimizationCallback callback));
};
} // namespace testing
} // namespace mapping
} // namespace cartographer
#endif // CARTOGRAPHER_MAPPING_INTERNAL_TESTING_MOCK_POSE_GRAPH_H_
| 38.380282 | 80 | 0.748257 | [
"vector",
"transform"
] |
dbde1de33f9acf8e015a3553351d9eb6f164f9a3 | 16,775 | h | C | RStein.AsyncCpp/Actors/ReplyActor.h | renestein/Rstein.AsyncCpp | 8f020ad271250479f600d7e2e862f701472c3a48 | [
"MIT"
] | 41 | 2020-05-04T05:58:24.000Z | 2022-03-25T07:21:45.000Z | RStein.AsyncCpp/Actors/ReplyActor.h | renestein/Rstein.AsyncCpp | 8f020ad271250479f600d7e2e862f701472c3a48 | [
"MIT"
] | 15 | 2021-02-03T16:05:19.000Z | 2021-08-17T17:09:28.000Z | RStein.AsyncCpp/Actors/ReplyActor.h | renestein/Rstein.AsyncCpp | 8f020ad271250479f600d7e2e862f701472c3a48 | [
"MIT"
] | 4 | 2020-05-04T15:41:37.000Z | 2021-08-24T00:59:18.000Z | #pragma once
#include "IReplyActor.h"
#include "../DataFlow/ActionBlock.h"
#include "../DataFlow/DataflowAsyncFactory.h"
#include "../DataFlow/DataFlowSyncFactory.h"
#include "../Tasks/TaskCompletionSource.h"
namespace RStein::AsyncCpp::Actors
{
template<typename TMessage, typename TResult>
class StatelessReplyActor : public IReplyActor<TMessage, TResult>
{
public:
using Async_Func_Type = std::function<Tasks::Task<TResult>(TMessage)>;
using Sync_Func_Type = std::function<TResult(TMessage)>;
explicit StatelessReplyActor(Async_Func_Type processMessageFunc);
explicit StatelessReplyActor(Sync_Func_Type processMessageFunc);
StatelessReplyActor(const StatelessReplyActor& other) = delete;
StatelessReplyActor(StatelessReplyActor&& other) noexcept = delete;
StatelessReplyActor& operator=(const StatelessReplyActor& other) = delete;
StatelessReplyActor& operator=(StatelessReplyActor&& other) noexcept = delete;
virtual ~StatelessReplyActor();
Tasks::Task<TResult> Ask(TMessage message) override;
Tasks::Task<void> Completion() override;
void Complete() override;
private:
typename DataFlow::ActionBlock<std::pair<TMessage, Tasks::TaskCompletionSource<TResult>>>::InputBlockPtr _actorQueue;
};
template <typename TMessage, typename TResult>
StatelessReplyActor<TMessage, TResult>::StatelessReplyActor(Async_Func_Type processMessageFunc) : IReplyActor<TMessage, TResult>{},
_actorQueue{ DataFlow::DataFlowAsyncFactory::CreateActionBlock<std::pair<TMessage, Tasks::TaskCompletionSource<TResult>>>([processMessageFunc](const std::pair<TMessage, Tasks::TaskCompletionSource<TResult>>& message)-> Tasks::Task<void>
{
auto& [innerMessage, tcs] = message;
//non-const object
//TODO: Handle error in copy ctor
auto tcsCopy = tcs;
try
{
auto result = co_await processMessageFunc(innerMessage).ConfigureAwait(false);
tcsCopy.SetResult(std::move(result));
}
catch (...)
{
tcsCopy.SetException(std::current_exception());
}
})}
{
_actorQueue->Start();
}
template <typename TMessage, typename TResult>
StatelessReplyActor<TMessage, TResult>::StatelessReplyActor(Sync_Func_Type processMessageFunc) : IReplyActor<TMessage, TResult>{},
_actorQueue{ DataFlow::DataFlowSyncFactory::CreateActionBlock<std::pair<TMessage, Tasks::TaskCompletionSource<TResult>>>([processMessageFunc](const std::pair<TMessage, Tasks::TaskCompletionSource<TResult>>& message)
{
auto& [innerMessage, tcs] = message;
//non-const object
//TODO: Handle error in copy ctor
auto tcsCopy = tcs;
try
{
auto result = processMessageFunc(innerMessage);
tcsCopy.SetResult(result);
}
catch (...)
{
tcsCopy.SetException(std::current_exception());
}
})}
{
_actorQueue->Start();
}
template <typename TMessage, typename TResult>
StatelessReplyActor<TMessage, TResult>::~StatelessReplyActor()
{
try
{
_actorQueue->Complete();
_actorQueue->Completion().Wait();
}
catch (...)
{
}
}
template <typename TMessage, typename TResult>
Tasks::Task<TResult> StatelessReplyActor<TMessage, TResult>::Ask(TMessage message)
{
Tasks::TaskCompletionSource<TResult> tcs{};
_actorQueue->AcceptInputAsync(std::make_pair(message, tcs)).Wait();
return tcs.GetTask();
}
template <typename TMessage, typename TResult>
Tasks::Task<void> StatelessReplyActor<TMessage, TResult>::Completion()
{
return _actorQueue->Completion();
}
template <typename TMessage, typename TResult>
void StatelessReplyActor<TMessage, TResult>::Complete()
{
return _actorQueue->Complete();
}
template<typename TMessage, typename TResult, typename TState>
class StatefulReplyActor : public IReplyActor<TMessage, TResult>
{
public:
using Sync_Func_Type = std::function<std::pair<TResult, TState>(TMessage, TState)>;
using Async_Func_Type = std::function<Tasks::Task<std::pair<TResult, TState>>(TMessage, TState)>;
StatefulReplyActor(Sync_Func_Type processMessageFunc, TState initialState);
StatefulReplyActor(Async_Func_Type processMessageFunc, TState initialState);
StatefulReplyActor(const StatefulReplyActor& other) = delete;
StatefulReplyActor(StatefulReplyActor&& other) noexcept = delete;
StatefulReplyActor& operator=(const StatefulReplyActor& other) = delete;
StatefulReplyActor& operator=(StatefulReplyActor&& other) noexcept = delete;
virtual ~StatefulReplyActor();
Tasks::Task<TResult> Ask(TMessage message) override;
Tasks::Task<void> Completion() override;
void Complete() override;
private:
typename DataFlow::ActionBlock<std::tuple<TMessage, Tasks::TaskCompletionSource<TResult>>>::InputBlockPtr _actorQueue;
TState _state;
};
template <typename TMessage, typename TResult, typename TState>
StatefulReplyActor<TMessage, TResult, TState>::StatefulReplyActor(Sync_Func_Type processMessageFunc, TState initialState) : _actorQueue{DataFlow::DataFlowSyncFactory::CreateActionBlock<std::tuple<TMessage, Tasks::TaskCompletionSource<TResult>>>([processMessageFunc, this](const std::tuple<TMessage, Tasks::TaskCompletionSource<TResult>>& message)
{
auto& [innerMessage, tcs] = message;
//non-const object
//TODO: Handle error in copy ctor
auto tcsCopy = tcs;
try
{
auto [result, newState] = processMessageFunc( innerMessage, _state);
_state = std::move(newState);
tcsCopy.SetResult(std::move(result));
}
catch (...)
{
tcsCopy.SetException(std::current_exception());
}
})},
_state{initialState}
{
_actorQueue->Start();
}
template <typename TMessage, typename TResult, typename TState>
StatefulReplyActor<TMessage, TResult, TState>::StatefulReplyActor( Async_Func_Type processMessageFunc, TState initialState) : _actorQueue{DataFlow::DataFlowAsyncFactory::CreateActionBlock<std::tuple<TMessage, Tasks::TaskCompletionSource<TResult>>>([processMessageFunc, this](const std::tuple<TMessage, Tasks::TaskCompletionSource<TResult>>& message)-> Tasks::Task<void>
{
const auto& [innerMessage, tcs] = message;
//non-const object
//TODO: Handle error in copy ctor
auto tcsCopy = tcs;
try
{
auto [result, newState] = co_await processMessageFunc(innerMessage, _state).ConfigureAwait(false);
_state = std::move(newState);
tcsCopy.SetResult(std::move(result));
}
catch (...)
{
tcsCopy.SetException(std::current_exception());
}
})},
_state{initialState}
{
_actorQueue->Start();
}
template <typename TMessage, typename TResult, typename TState>
StatefulReplyActor<TMessage, TResult, TState>::~StatefulReplyActor()
{
try
{
_actorQueue->Complete();
_actorQueue->Completion().Wait();
}
catch (...)
{
}
}
template <typename TMessage, typename TResult, typename TState>
Tasks::Task<TResult> StatefulReplyActor<TMessage, TResult, TState>::Ask(TMessage message)
{
Tasks::TaskCompletionSource<TResult> tcs{};
auto messageTcsPair = std::make_tuple(message, tcs);
_actorQueue->AcceptInputAsync(messageTcsPair).Wait();
return tcs.GetTask();
}
template <typename TMessage, typename TResult, typename TState>
Tasks::Task<void> StatefulReplyActor<TMessage, TResult, TState>::Completion()
{
return _actorQueue->Completion();
}
template <typename TMessage, typename TResult, typename TState>
void StatefulReplyActor<TMessage, TResult, TState>::Complete()
{
return _actorQueue->Complete();
}
template<typename TMessage, typename TResult>
std::unique_ptr<IReplyActor<TMessage, TResult>> CreateReplyActor(typename StatelessReplyActor<TMessage, TResult>::Sync_Func_Type processMessageFunc)
{
return std::make_unique<StatelessReplyActor<TMessage, TResult>>(processMessageFunc);
}
template<typename TMessage, typename TResult>
std::unique_ptr<IReplyActor<TMessage, TResult>> CreateAsyncReplyActor(typename StatelessReplyActor<TMessage, TResult>::Async_Func_Type processMessageFunc)
{
return std::make_unique<StatelessReplyActor<TMessage, TResult>>(processMessageFunc);
}
template<typename TMessage, typename TResult, typename TState>
std::unique_ptr<IReplyActor<TMessage, TResult>>CreateReplyActor(typename StatefulReplyActor<TMessage, TResult, TState>::Sync_Func_Type processMessageFunc, TState initialState)
{
return std::make_unique<StatefulReplyActor<TMessage, TResult, TState>>(processMessageFunc, initialState);
}
template<typename TMessage, typename TResult, typename TState>
std::unique_ptr<IReplyActor<TMessage, TResult>> CreateAsyncReplyActor(typename StatefulReplyActor<TMessage, TResult, TState>::Async_Func_Type processMessageFunc, TState initialState)
{
return std::make_unique<StatefulReplyActor<TMessage, TResult, TState>>(processMessageFunc, initialState);
}
}
| 67.369478 | 371 | 0.391654 | [
"object"
] |
dbe2659d713c9d120e4fe3a96323a9d875656607 | 27,946 | h | C | ligra/IO.h | meng-sun/ligra | 223d0824d06b2dc3d7ee46459ce019e2a3579176 | [
"MIT"
] | null | null | null | ligra/IO.h | meng-sun/ligra | 223d0824d06b2dc3d7ee46459ce019e2a3579176 | [
"MIT"
] | null | null | null | ligra/IO.h | meng-sun/ligra | 223d0824d06b2dc3d7ee46459ce019e2a3579176 | [
"MIT"
] | null | null | null | // This code is part of the project "Ligra: A Lightweight Graph Processing
// Framework for Shared Memory", presented at Principles and Practice of
// Parallel Programming, 2013.
// Copyright (c) 2013 Julian Shun and Guy Blelloch
//
// 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 <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <cmath>
#include <fstream>
#include <iostream>
#include <memory>
#include <vector>
#include "blockRadixSort.h"
#include "graph.h"
#include "parallel.h"
#include "quickSort.h"
#include "utils.h"
//#include <pmem_allocator.h>
#include <libpmem.h>
#include "nodePartitioner.h"
using namespace std;
typedef pair<uintE, uintE> intPair;
typedef pair<uintE, pair<uintE, intE> > intTriple;
template <class E>
struct pairFirstCmp {
bool operator()(pair<uintE, E> a, pair<uintE, E> b) {
return a.first < b.first;
}
};
template <class E>
struct getFirst {
uintE operator()(pair<uintE, E> a) { return a.first; }
};
template <class IntType>
struct pairBothCmp {
bool operator()(pair<uintE, IntType> a, pair<uintE, IntType> b) {
if (a.first != b.first) return a.first < b.first;
return a.second < b.second;
}
};
/*
// A structure that keeps a sequence of strings all allocated from
// the same block of memory
struct words {
long n; // total number of characters
char* Chars; // array storing all strings
long m; // number of substrings
char** Strings; // pointers to strings (all should be null terminated)
words() {}
words(char* C, long nn, char** S, long mm)
: Chars(C), n(nn), Strings(S), m(mm) {}
void del() {free(Chars); free(Strings);}
};
*/
inline bool isSpace(char c) {
switch (c) {
case '\r':
case '\t':
case '\n':
case 0:
case ' ':
return true;
default:
return false;
}
}
_seq<char> mmapStringFromFile(const char* filename) {
struct stat sb;
int fd = open(filename, O_RDONLY);
if (fd == -1) {
perror("open");
exit(-1);
}
if (fstat(fd, &sb) == -1) {
perror("fstat");
exit(-1);
}
if (!S_ISREG(sb.st_mode)) {
perror("not a file\n");
exit(-1);
}
char* p =
static_cast<char*>(mmap(0, sb.st_size, PROT_READ, MAP_PRIVATE, fd, 0));
if (p == MAP_FAILED) {
perror("mmap");
exit(-1);
}
if (close(fd) == -1) {
perror("close");
exit(-1);
}
size_t n = sb.st_size;
// char *bytes = newA(char, n);
// parallel_for(size_t i=0; i<n; i++) {
// bytes[i] = p[i];
// }
// if (munmap(p, sb.st_size) == -1) {
// perror("munmap");
// exit(-1);
// }
// cout << "mmapped" << endl;
// free(bytes);
// exit(0);
return _seq<char>(p, n);
}
_seq<char> readStringFromFile(char* fileName) {
ifstream file(fileName, ios::in | ios::binary | ios::ate);
if (!file.is_open()) {
std::cout << "Unable to open file: " << fileName << std::endl;
abort();
}
long end = file.tellg();
file.seekg(0, ios::beg);
long n = end - file.tellg();
char* bytes = newA(char, n + 1);
file.read(bytes, n);
file.close();
return _seq<char>(bytes, n);
}
// parallel code for converting a string to words
words stringToWords(char* Str, long n) {
{ parallel_for(long i = 0; i < n; i++) if (isSpace(Str[i])) Str[i] = 0; }
// mark start of words
bool* FL = newA(bool, n);
FL[0] = Str[0];
{ parallel_for(long i = 1; i < n; i++) FL[i] = Str[i] && !Str[i - 1]; }
// offset for each start of word
_seq<long> Off = sequence::packIndex<long>(FL, n);
long m = Off.n;
long* offsets = Off.A;
// pointer to each start of word
char** SA = newA(char*, m);
{ parallel_for(long j = 0; j < m; j++) SA[j] = Str + offsets[j]; }
free(offsets);
free(FL);
return words(Str, n, SA, m);
}
// re write this to get the largest idx possible
//------------
size_t binarySearch(uintT* a, size_t low, size_t high, size_t m) {
if ((high - low) <= 1) {
if ((a[low + 1] > m) && (a[low] <= m)) {
return low;
} else {
std::cerr << "binsearch error: "
<< " l " << low << " h " << high << " m " << m << "\n";
exit(1);
}
} else if (high > low) {
size_t mid = low + (high - low) / 2;
if (a[mid] > m) return binarySearch(a, low, mid, m);
return binarySearch(a, mid, high, m);
} else {
std::cerr << "binsearch error: "
<< " l " << low << " h " << high << " m " << m << "\n";
exit(1);
}
}
//------------
template <class vertex>
graph<vertex> readGraphFromFile(char* fname, bool isSymmetric, bool mmap,
long capacity = 0, char* npf = nullptr,
bool rmetis = false) {
words W;
if (mmap) {
_seq<char> S = mmapStringFromFile(fname);
char* bytes = newA(char, S.n);
// Cannot mutate the graph unless we copy.
parallel_for(size_t i = 0; i < S.n; i++) { bytes[i] = S.A[i]; }
if (munmap(S.A, S.n) == -1) {
perror("munmap");
exit(-1);
}
S.A = bytes;
W = stringToWords(S.A, S.n);
} else {
_seq<char> S = readStringFromFile(fname);
W = stringToWords(S.A, S.n);
}
#ifndef WEIGHTED
if (W.Strings[0] != (string) "AdjacencyGraph") {
#else
if (W.Strings[0] != (string) "WeightedAdjacencyGraph") {
#endif
cout << "Bad input file l0" << endl;
abort();
}
long len = W.m - 1;
long n = atol(W.Strings[1]);
long m = atol(W.Strings[2]);
#ifndef WEIGHTED
if (len != n + m + 2) {
#else
if (len != n + 2 * m + 2) {
#endif
cout << "Bad input file count" << endl;
abort();
}
string path = "/mnt/pmem0/mina";
char* pmemaddr;
int is_pmem;
size_t mapped_len;
ifstream f(path.c_str());
const static size_t PMEMGRAPHSIZE = 200000000000;
if (f.good()) {
pmemaddr =
(char*)pmem_map_file(path.c_str(), PMEMGRAPHSIZE, PMEM_FILE_CREATE,
0666, &mapped_len, &is_pmem);
} else {
pmemaddr = (char*)pmem_map_file(path.c_str(), PMEMGRAPHSIZE,
PMEM_FILE_CREATE | PMEM_FILE_EXCL, 0666,
&mapped_len, &is_pmem);
}
if (pmemaddr == NULL) {
perror("pmem_map_file");
exit(1);
}
if (is_pmem) {
cout << "Pmem successfully allocated" << endl;
} else {
cout << "Error not pmem" << endl;
exit(1);
}
uintE* nv = reinterpret_cast<uintE*>(pmemaddr);
// libmemkind::pmem::allocator<uintE> alc{ "/mnt/pmem12", 102400 };
// std::allocator<uintE> alc;
// increase size of offsets to n+1
uintT* offsets = newA(uintT, n + 1);
#ifndef WEIGHTED
uintE* edges = newA(uintE, m);
// memmove(&nv[0], pmemaddr, sizeof(nv))
// uintE* nv = alc.allocate(m);
#else
intE* edges = newA(intE, 2 * m);
#endif
{
parallel_for(long i = 0; i < n; i++) {
offsets[i] = atol(W.Strings[i + 3]);
// if ((i == 37296) || (i == 37302) || (i== 37303))
// std::cout << "offsets og " << offsets[i] << " and atol from " << i+3
// << std::endl;
}
}
// can remove the if conditions
offsets[n] = m;
NodePartitioner* np;
uintT* tOffsets = newA(uintE, n);
memset(tOffsets, 0, n * sizeof(uintT));
if (npf != nullptr) {
_seq<char> dn = readStringFromFile(npf);
words dnw = stringToWords(dn.A, dn.n);
// std::cerr << "got to this point: dn | " << dn.n << " " << (bool) dn.A[0]
// << std::endl;
// for (size_t i = 0; i<n; i++)
// std::cout << "NP| " << i << " " << np->dram_nodes[i] << " " <<
// np->if_dram(i) << " : " << np->partition_offset(i) << std::endl;
if (!isSymmetric) {
parallel_for(int i = 0; i < m; i++) {
writeAdd(&tOffsets[atol(W.Strings[i + n + 3])], (uintT)1);
}
np = new NodePartitioner(n, m, offsets, tOffsets, dnw, rmetis);
long collect_sum = 0;
for (int i = 0; i < n; i++) {
long tmp = collect_sum;
collect_sum += tOffsets[i];
tOffsets[i] = tmp;
}
} else {
np = new NodePartitioner(n, m, offsets, dnw, rmetis);
}
} else {
if (!isSymmetric) {
parallel_for(int i = 0; i < m; i++) {
writeAdd(&tOffsets[atol(W.Strings[i + n + 3])], (uintT)1);
}
np = new NodePartitioner(n, m, offsets, tOffsets, capacity);
long collect_sum = 0;
for (int i = 0; i < n; i++) {
long tmp = collect_sum;
collect_sum += tOffsets[i];
tOffsets[i] = tmp;
}
} else {
np = new NodePartitioner(n, m, offsets, capacity);
}
}
// for debugging
size_t edge_count = 0;
size_t node_count = 0;
for (size_t i = 0; i < n; i++) {
if (np->if_dram(i)) {
edge_count += ((i == n - 1) ? m : offsets[i + 1]) - offsets[i];
node_count++;
}
}
if (isSymmetric) {
std::cout << "Percent of all nodes on dram: " << node_count << "/" << n
<< std::endl;
std::cout << "Percent of all edges on dram: " << edge_count << "/" << m
<< std::endl;
} else {
std::cout << "Percent of all (out) nodes on dram: " << node_count << "/"
<< n << std::endl;
std::cout << "Percent of all (out) edges on dram: " << edge_count << "/"
<< m << std::endl;
size_t in_edge_count = 0;
size_t in_node_count = 0;
for (size_t i = 0; i < n; i++) {
if (np->if_dram(i + n)) {
in_edge_count += ((i == n - 1) ? m : tOffsets[i + 1]) - tOffsets[i];
in_node_count++;
}
}
std::cout << "Percent of all (in) nodes on dram: " << in_node_count << "/"
<< n << std::endl;
std::cout << "Percent of all (in) edges on dram: " << in_edge_count << "/"
<< m << std::endl;
}
// for (size_t i = 0; i<n; i++)
// std::cout << "NP| " << i << " " << np->if_dram(i) << " : " <<
// np->partition_offset(i) << std::endl; why not marked as volatile???
uintT dram_partition_split = 0;
{
parallel_for(long i = 0; i < m; i++) {
#ifndef WEIGHTED
// size_t binary_search(Sequence I, typename Sequence::T v, const F& less)
// {
size_t j = binarySearch(offsets, 0, n, i); // rename this better
// while(i > offsets[j]) j++;
uintT po = np->partition_offset(j);
uintT l = ((j == n - 1) ? m : offsets[j + 1]) - offsets[j];
// if ((i == 112442) || (j == 37302) || (i== 112441) || (i== 112440))
// std::cout << " n " << j << " m " << i << " l " << l << " offsets " <<
// offsets[j] << " " << offsets[j+1] << std::endl;
if (np->if_dram(j)) {
edges[po + (i - offsets[j])] = atol(W.Strings[i + n + 3]);
// if ((i == 112442) || (j == 37302) || (i== 112441))
// std::cerr << "writing edges | n " << j << " m:" << i << " d " <<
// W.Strings[i+n+3] \
// << " from idx " << i+n+3 << " poff: " << np->partition_offset(j) +
// (i - offsets[j])<< std::endl;
pbbs::write_min(&dram_partition_split, po + l, std::greater<uintT>());
// std::cout << "dram partition split new | " << dram_partition_split <<
// " = " << po << "+" << l << std::endl;
} else {
// if ((i == 112442) || (j == 37302) || (i== 112441))
// std::cerr << "writing nv edges |n " << j << " m:" << i << " d " <<
// W.Strings[i+n+3] \
// << " poff: " << np->partition_offset(j) + (i - offsets[j]) <<
// std::endl;
nv[po + (i - offsets[j])] = atol(W.Strings[i + n + 3]);
}
#else
edges[2 * i] = atol(W.Strings[i + n + 3]);
edges[2 * i + 1] = atol(W.Strings[i + n + m + 3]);
#endif
}
}
// W.del(); // to deal with performance bug in malloc
// for(size_t i=0;i<2*m;i++) std::cout << "edges check " << edges[i] << " a:"
// << &edges[i] << std::endl; for(size_t i=0;i<2*m;i++) std::cout << "nv edges
// check " << nv[i] << " a:" << &nv[i] << std::endl; std::cout << "Made
// edges\n";
vertex* v = newA(vertex, n);
{
parallel_for(uintT i = 0; i < n; i++) {
uintT o = offsets[i];
uintT l = ((i == n - 1) ? m : offsets[i + 1]) - offsets[i];
v[i].setOutDegree(l);
#ifndef WEIGHTED
if (np->if_dram(i)) {
v[i].setOutNeighbors(edges + np->partition_offset(i));
// TODO fix the offsets or array of pointer problem
// if (pmem_is_pmem(edges+o, l*sizeof(uintE))) { std::cerr << "pmem when
// its not" << i << " " << (void*)(edges+o) << std::endl; } if (i ==
// 37302)
// std::cout << "added out neighbor dram| " << i << " " <<
// np->partition_offset(i) << " with degr " << l << \
// " from " << offsets[i+1] << " - " << offsets[i] << std::endl;
// if (i<5) std::cout << "first outNeighbor dram| " << i << " " <<
// v[i].getOutNeighbor(0) << std::endl;
} else {
v[i].setOutNeighbors(nv + np->partition_offset(i));
// if (!pmem_is_pmem(nv+o, l*sizeof(uintE))) { std::cerr << "not pmem "
// << i << " " << (void*)(nv+o) << std::endl; } std::cout << "added out
// neighbor nvram| " << i << " " << np->partition_offset(i) <<
// std::endl; if (i<5) std::cout << "first outNeighbor nvram| " << i <<
// " " << v[i].getOutNeighbor(0) << std::endl;
}
#else
v[i].setOutNeighbors(edges + 2 * o);
#endif
}
}
// std::cout << "Made outneighbors\n";
// for(size_t i=0;i<2*m;i++) std::cout << "edges check " << edges[i] << " a:"
// << &edges[i] << std::endl; for(size_t i=0;i<2*m;i++) std::cout << "nv edges
// check " << nv[i] << " a:" << &nv[i] << std::endl; for (size_t i=0; i<n;
// i++)
// {
// for (size_t j=0; j<v[i].getOutDegree(); j++)
// std::cout << "outneighbors check " << i << "-" << j << " : " <<
// v[i].getOutNeighbor(j) << " a:" << v[i].getOutNeighbor(j) << std::endl;
//}
if (!isSymmetric) {
// this should all be moved to nvram
// rn it doesnt matter that its on dram but it should be nvram
// uintT* tOffsets = newA(uintT,n);
//{parallel_for(long i=0;i<n;i++) tOffsets[i] = INT_T_MAX;}
#ifndef WEIGHTED
intPair* temp = newA(intPair, m);
#else
intTriple* temp = newA(intTriple, m);
#endif
{
parallel_for(long i = 0; i < n; i++) {
uintT o = offsets[i];
for (uintT j = 0; j < v[i].getOutDegree(); j++) {
#ifndef WEIGHTED
temp[o + j] = make_pair(v[i].getOutNeighbor(j), i);
// std::cout << "temp init " << j << " : " << v[i].getOutNeighbor(j)
// << ", " << i << std::endl;
assert(v[i].getOutNeighbor(j) < 16777216);
#else
temp[o + j] = make_pair(v[i].getOutNeighbor(j),
make_pair(i, v[i].getOutWeight(j)));
#endif
}
}
}
free(offsets);
#ifndef WEIGHTED
#ifndef LOWMEM
intSort::iSort(temp, m, n + 1, getFirst<uintE>());
#else
quickSort(temp, m, pairFirstCmp<uintE>());
#endif
#else
#ifndef LOWMEM
intSort::iSort(temp, m, n + 1, getFirst<intPair>());
#else
quickSort(temp, m, pairFirstCmp<intPair>());
#endif
#endif
std::cout << "Made sort\n";
// tOffsets[temp[0].first] = 0;
#ifndef WEIGHTED
uintE* inEdges = newA(uintE, m);
// inEdges[0] = temp[0].second;
// uintE* niv = alc.allocate(m);
// uintE* niv = bufaddr + m + 2;
// niv[0] = temp[0].second;
// for(size_t i=0;i<m;i++) std::cout << "edges check " << inEdges[i] << "
// a:" << &(inEdges[i]) << std::endl;
#else
intE* inEdges = newA(intE, 2 * m);
inEdges[0] = temp[0].second.first;
inEdges[1] = temp[0].second.second;
#endif
// for (size_t i=0; i<m; i++) std::cout << "temp " << temp[i].first << " "
// << temp[i].second << std::endl; std::cout << "dram_partition_split " <<
// dram_partition_split << std::endl;
{
parallel_for(long i = 0; i < m; i++) { //
#ifndef WEIGHTED
size_t j = temp[i].first;
if (np->if_dram(j + n)) {
// std::cerr << "writing edges | n " << j << " m:" << i << " ";
// std::cerr << "d " << temp[i].second << " poff: " <<
// np->partition_offset(j+n) + \
// (i - tOffsets[j]) - dram_partition_split << std::endl;
// std::cerr << " po: " << np->partition_offset(j+n) << " i: " << i <<
// "tOffsets[j]: " << \
// tOffsets[j] << " dps: " << dram_partition_split << std::endl;
inEdges[np->partition_offset(j + n) + (i - tOffsets[j]) -
dram_partition_split] = temp[i].second;
} else {
// std::cerr << "writing nv edges |n " << j << " m:" << i << " ";
// std::cerr << " d " << temp[i].second << " poff: " <<
// np->partition_offset(j+n) + \
// (i - tOffsets[j]) << " po: " << np->partition_offset(j+n) << " i:
// " << i << "tOffsets[j]: " << tOffsets[j] << std::endl;
nv[np->partition_offset(j + n) + (i - tOffsets[j])] = temp[i].second;
}
// inEdges[i] = temp[i].second;
// niv[i] = temp[i].second;
#else
inEdges[2 * i] = temp[i].second.first;
inEdges[2 * i + 1] = temp[i].second.second;
#endif
// if(temp[i].first != temp[i-1].first) {
// tOffsets[temp[i].first] = i;
//}
}
}
// std::cout << "Made inedges\n";
free(temp);
// fill in offsets of degree 0 vertices by taking closest non-zero
// offset to the right
// sequence::scanIBack(tOffsets,tOffsets,n,minF<uintT>(),(uintT)m);
// why cant I run this with one thread?
{
parallel_for(long i = 0; i < n; i++) {
uintT o = tOffsets[i];
uintT l = ((i == n - 1) ? m : tOffsets[i + 1]) - tOffsets[i];
// std::cout << "tOffsets " << i << ":" << l << std::endl;
v[i].setInDegree(l);
#ifndef WEIGHTED
// v[i].setInNeighbors(inEdges+o);
// v[i].setInNeighbors(niv+o);
if (np->if_dram(i + n)) {
v[i].setInNeighbors(inEdges + np->partition_offset(i + n) -
dram_partition_split);
// TODO fix the offsets or array of pointer problem
// if (pmem_is_pmem(edges+o, l*sizeof(uintE))) { std::cerr << "pmem
// when its not" << i << " " << (void*)(edges+o) << std::endl; }
// std::cout << "added in neighbor dram| " << i << " " <<
// np->partition_offset(i+n)-dram_partition_split << std::endl; if
// (i<5) std::cout << "first outNeighbor dram| " << i << " " <<
// v[i].getOutNeighbor(0) << std::endl;
} else {
v[i].setInNeighbors(nv + np->partition_offset(i + n));
// if (!pmem_is_pmem(nv+o, l*sizeof(uintE))) { std::cerr << "not pmem
// " << i << " " << (void*)(nv+o) << std::endl; } std::cout << "added
// in neighbor nvram| " << i << " " << np->partition_offset(i+n) <<
// std::endl; if (i<5) std::cout << "first outNeighbor nvram| " << i
// << " " << v[i].getOutNeighbor(0) << std::endl;
}
#else
v[i].setInNeighbors(inEdges + 2 * o);
#endif
}
}
// for(size_t i=0;i<m;i++) std::cout << "edges check " << inEdges[i] << "
// a:" << &(inEdges[i]) << std::endl; for(size_t i=0;i<2*m;i++) std::cout <<
// "nv edges check " << nv[i] << " a:" << &nv[i] << std::endl; for (size_t
// i=0; i<n; i++) {
// for (size_t j=0; j<v[i].getInDegree(); j++)
// std::cout << "inneighbors check " << i << "-" << j << " : " <<
// v[i].getInNeighbor(j) << std::endl;
//}
// std::cout << "Made inneighbors\n";
free(tOffsets);
Uncompressed_Mem<vertex>* mem =
new Uncompressed_Mem<vertex>(v, n, m, edges, inEdges);
return graph<vertex>(v, n, m, mem);
} else {
free(offsets);
Uncompressed_Mem<vertex>* mem =
new Uncompressed_Mem<vertex>(v, n, m, edges);
return graph<vertex>(v, n, m, mem);
}
}
template <class vertex>
graph<vertex> readGraphFromBinary(char* iFile, bool isSymmetric) {
char* config = (char*)".config";
char* adj = (char*)".adj";
char* idx = (char*)".idx";
char configFile[strlen(iFile) + strlen(config) + 1];
char adjFile[strlen(iFile) + strlen(adj) + 1];
char idxFile[strlen(iFile) + strlen(idx) + 1];
*configFile = *adjFile = *idxFile = '\0';
strcat(configFile, iFile);
strcat(adjFile, iFile);
strcat(idxFile, iFile);
strcat(configFile, config);
strcat(adjFile, adj);
strcat(idxFile, idx);
ifstream in(configFile, ifstream::in);
long n;
in >> n;
in.close();
ifstream in2(adjFile, ifstream::in | ios::binary); // stored as uints
in2.seekg(0, ios::end);
long size = in2.tellg();
in2.seekg(0);
#ifdef WEIGHTED
long m = size / (2 * sizeof(uint));
#else
long m = size / sizeof(uint);
#endif
char* s = (char*)malloc(size);
in2.read(s, size);
in2.close();
uintE* edges = (uintE*)s;
ifstream in3(idxFile, ifstream::in | ios::binary); // stored as longs
in3.seekg(0, ios::end);
size = in3.tellg();
in3.seekg(0);
if (n != size / sizeof(intT)) {
cout << "File size wrong\n";
abort();
}
char* t = (char*)malloc(size);
in3.read(t, size);
in3.close();
uintT* offsets = (uintT*)t;
vertex* v = newA(vertex, n);
#ifdef WEIGHTED
intE* edgesAndWeights = newA(intE, 2 * m);
{
parallel_for(long i = 0; i < m; i++) {
edgesAndWeights[2 * i] = edges[i];
edgesAndWeights[2 * i + 1] = edges[i + m];
}
}
// free(edges);
#endif
{
parallel_for(long i = 0; i < n; i++) {
uintT o = offsets[i];
uintT l = ((i == n - 1) ? m : offsets[i + 1]) - offsets[i];
v[i].setOutDegree(l);
#ifndef WEIGHTED
v[i].setOutNeighbors((uintE*)edges + o);
#else
v[i].setOutNeighbors(edgesAndWeights + 2 * o);
#endif
}
}
if (!isSymmetric) {
uintT* tOffsets = newA(uintT, n);
{ parallel_for(long i = 0; i < n; i++) tOffsets[i] = INT_T_MAX; }
#ifndef WEIGHTED
intPair* temp = newA(intPair, m);
#else
intTriple* temp = newA(intTriple, m);
#endif
{
parallel_for(intT i = 0; i < n; i++) {
uintT o = offsets[i];
for (uintT j = 0; j < v[i].getOutDegree(); j++) {
#ifndef WEIGHTED
temp[o + j] = make_pair(v[i].getOutNeighbor(j), i);
#else
temp[o + j] = make_pair(v[i].getOutNeighbor(j),
make_pair(i, v[i].getOutWeight(j)));
#endif
}
}
}
free(offsets);
#ifndef WEIGHTED
#ifndef LOWMEM
intSort::iSort(temp, m, n + 1, getFirst<uintE>());
#else
quickSort(temp, m, pairFirstCmp<uintE>());
#endif
#else
#ifndef LOWMEM
intSort::iSort(temp, m, n + 1, getFirst<intPair>());
#else
quickSort(temp, m, pairFirstCmp<intPair>());
#endif
#endif
tOffsets[temp[0].first] = 0;
#ifndef WEIGHTED
uintE* inEdges = newA(uintE, m);
inEdges[0] = temp[0].second;
#else
intE* inEdges = newA(intE, 2 * m);
inEdges[0] = temp[0].second.first;
inEdges[1] = temp[0].second.second;
#endif
{
parallel_for(long i = 1; i < m; i++) {
#ifndef WEIGHTED
inEdges[i] = temp[i].second;
#else
inEdges[2 * i] = temp[i].second.first;
inEdges[2 * i + 1] = temp[i].second.second;
#endif
if (temp[i].first != temp[i - 1].first) {
tOffsets[temp[i].first] = i;
}
}
}
free(temp);
// fill in offsets of degree 0 vertices by taking closest non-zero
// offset to the right
sequence::scanIBack(tOffsets, tOffsets, n, minF<uintT>(), (uintT)m);
{
parallel_for(long i = 0; i < n; i++) {
uintT o = tOffsets[i];
uintT l = ((i == n - 1) ? m : tOffsets[i + 1]) - tOffsets[i];
v[i].setInDegree(l);
#ifndef WEIGHTED
v[i].setInNeighbors((uintE*)inEdges + o);
#else
v[i].setInNeighbors((intE*)(inEdges + 2 * o));
#endif
}
}
free(tOffsets);
#ifndef WEIGHTED
Uncompressed_Mem<vertex>* mem =
new Uncompressed_Mem<vertex>(v, n, m, edges, inEdges);
return graph<vertex>(v, n, m, mem);
#else
Uncompressed_Mem<vertex>* mem =
new Uncompressed_Mem<vertex>(v, n, m, edgesAndWeights, inEdges);
return graph<vertex>(v, n, m, mem);
#endif
}
free(offsets);
#ifndef WEIGHTED
Uncompressed_Mem<vertex>* mem = new Uncompressed_Mem<vertex>(v, n, m, edges);
return graph<vertex>(v, n, m, mem);
#else
Uncompressed_Mem<vertex>* mem =
new Uncompressed_Mem<vertex>(v, n, m, edgesAndWeights);
return graph<vertex>(v, n, m, mem);
#endif
}
template <class vertex>
graph<vertex> readGraph(char* iFile, bool compressed, bool symmetric,
bool binary, bool mmap, long capacity = 0,
char* npf = nullptr, bool rmetis = false) {
if (binary)
return readGraphFromBinary<vertex>(iFile, symmetric);
else
return readGraphFromFile<vertex>(iFile, symmetric, mmap, capacity, npf,
rmetis);
}
template <class vertex>
graph<vertex> readCompressedGraph(char* fname, bool isSymmetric, bool mmap) {
char* s;
if (mmap) {
_seq<char> S = mmapStringFromFile(fname);
// Cannot mutate graph unless we copy.
char* bytes = newA(char, S.n);
parallel_for(size_t i = 0; i < S.n; i++) { bytes[i] = S.A[i]; }
if (munmap(S.A, S.n) == -1) {
perror("munmap");
exit(-1);
}
s = bytes;
} else {
ifstream in(fname, ifstream::in | ios::binary);
in.seekg(0, ios::end);
long size = in.tellg();
in.seekg(0);
cout << "size = " << size << endl;
s = (char*)malloc(size);
in.read(s, size);
in.close();
}
long* sizes = (long*)s;
long n = sizes[0], m = sizes[1], totalSpace = sizes[2];
cout << "n = " << n << " m = " << m << " totalSpace = " << totalSpace << endl;
cout << "reading file..." << endl;
uintT* offsets = (uintT*)(s + 3 * sizeof(long));
long skip = 3 * sizeof(long) + (n + 1) * sizeof(intT);
uintE* Degrees = (uintE*)(s + skip);
skip += n * sizeof(intE);
uchar* edges = (uchar*)(s + skip);
uintT* inOffsets;
uchar* inEdges;
uintE* inDegrees;
if (!isSymmetric) {
skip += totalSpace;
uchar* inData = (uchar*)(s + skip);
sizes = (long*)inData;
long inTotalSpace = sizes[0];
cout << "inTotalSpace = " << inTotalSpace << endl;
skip += sizeof(long);
inOffsets = (uintT*)(s + skip);
skip += (n + 1) * sizeof(uintT);
inDegrees = (uintE*)(s + skip);
skip += n * sizeof(uintE);
inEdges = (uchar*)(s + skip);
} else {
inOffsets = offsets;
inEdges = edges;
inDegrees = Degrees;
}
vertex* V = newA(vertex, n);
parallel_for(long i = 0; i < n; i++) {
long o = offsets[i];
uintT d = Degrees[i];
V[i].setOutDegree(d);
V[i].setOutNeighbors(edges + o);
}
if (sizeof(vertex) == sizeof(compressedAsymmetricVertex)) {
parallel_for(long i = 0; i < n; i++) {
long o = inOffsets[i];
uintT d = inDegrees[i];
V[i].setInDegree(d);
V[i].setInNeighbors(inEdges + o);
}
}
cout << "creating graph..." << endl;
Compressed_Mem<vertex>* mem = new Compressed_Mem<vertex>(V, s);
graph<vertex> G(V, n, m, mem);
return G;
}
| 31.577401 | 80 | 0.539719 | [
"vector"
] |
dbe4522c569afccd40011544db2c9b483bcb03c2 | 752 | h | C | Source/Engine/Render/Viewport.h | kukiric/SomeGame | 8c058d82a93bc3f276bbb3ec57a3978ae57de82c | [
"MIT"
] | null | null | null | Source/Engine/Render/Viewport.h | kukiric/SomeGame | 8c058d82a93bc3f276bbb3ec57a3978ae57de82c | [
"MIT"
] | null | null | null | Source/Engine/Render/Viewport.h | kukiric/SomeGame | 8c058d82a93bc3f276bbb3ec57a3978ae57de82c | [
"MIT"
] | null | null | null | #ifndef CAMERA_H
#define CAMERA_H
#include <Engine/Base/Types/Shared.h>
namespace Render {
class api_public Viewport
{
protected:
Mat4 viewProjectionMatrix;
float aspectRatio;
float fieldOfView;
float nearz, farz;
bool perspective;
public:
Viewport(float vfov, float aspect, float near, float far);
virtual ~Viewport();
virtual void spawn();
virtual void think();
void setAspect(float aspect);
void setClip(float near, float far);
void setPerspective(float vfov);
void setOrtographic(float width);
float getPerspectiveFov() const;
const Mat4& getMatrix() const;
};
}
#endif // CAMERA_H
| 24.258065 | 67 | 0.607713 | [
"render"
] |
dbfa0c812bdf7f18f50b81d2aeade6a244ad098b | 2,493 | h | C | include/auxkernels/SimpleGasEffectivePoreDiffusivity.h | coelectrolyzer/cats | 21f8e6f5f176767ec403ad2738c80a5a71fba959 | [
"MIT"
] | null | null | null | include/auxkernels/SimpleGasEffectivePoreDiffusivity.h | coelectrolyzer/cats | 21f8e6f5f176767ec403ad2738c80a5a71fba959 | [
"MIT"
] | null | null | null | include/auxkernels/SimpleGasEffectivePoreDiffusivity.h | coelectrolyzer/cats | 21f8e6f5f176767ec403ad2738c80a5a71fba959 | [
"MIT"
] | null | null | null | /*!
* \file SimpleGasEffectivePoreDiffusivity.h
* \brief AuxKernel kernel to calculate effective pore diffusion coefficients in microscale
* \details This file is responsible for calculating the effective pore diffusivity
* for the microscale given some simple properties. Calculation is based
* diffusivities that are corrected via an Arrhenius like
* expression from a reference diffusivity and reference temperature.
* User provides input units for specific parameters and provides
* desired unit basis of the calculation of diffusivity.
*
* \note This aux kernel differs from PoreDiffusivity in that the value calculated
* will be put DIRECTLY into the Microscale physics kernels such that the
* base units of the full microscale mass balance are in units of per
* microscale volume or per total volume. Depending on how you formulate
* your mass balance, this may or may not be important.
*
*
* \author Austin Ladshaw
* \date 09/15/2021
* \copyright This kernel was designed and built at Oak Ridge National
* Laboratory by Austin Ladshaw for research in catalyst
* performance for new vehicle technologies.
*
* Austin Ladshaw does not claim any ownership or copyright to the
* MOOSE framework in which these kernels are constructed, only
* the kernels themselves. The MOOSE framework copyright is held
* by the Battelle Energy Alliance, LLC (c) 2010, all rights reserved.
*/
#pragma once
#include "SimpleGasPropertiesBase.h"
/// SimpleGasPoreDiffusivity class object inherits from SimpleGasPropertiesBase object
class SimpleGasEffectivePoreDiffusivity : public SimpleGasPropertiesBase
{
public:
/// Required new syntax for InputParameters
static InputParameters validParams();
/// Required constructor for objects in MOOSE
SimpleGasEffectivePoreDiffusivity(const InputParameters & parameters);
protected:
/// Required MOOSE function override
virtual Real computeValue() override;
private:
std::string _output_length_unit; ///< Units of the length term in transfer coef (m, cm, mm)
std::string _output_time_unit; ///< Units of the time term in transfer coef (hr, min, s)
bool _PerSolidsVolume; ///< Boolean to determine if ratio to be calculated is per solid volume or per total volume
};
| 46.166667 | 122 | 0.704773 | [
"object",
"solid"
] |
dbfa251139652a298d55e771a92e3f3a457dc898 | 2,028 | h | C | src/include/TempLat/session/sessionguard.h | cosmolattice/cosmolattice | bd9a31a026c0b47d53ff486db23448797dbe2fe0 | [
"MIT"
] | 12 | 2021-02-01T16:04:54.000Z | 2022-03-18T08:27:46.000Z | src/include/TempLat/session/sessionguard.h | cosmolattice/cosmolattice | bd9a31a026c0b47d53ff486db23448797dbe2fe0 | [
"MIT"
] | 1 | 2021-04-24T10:09:35.000Z | 2021-04-24T10:09:35.000Z | src/include/TempLat/session/sessionguard.h | cosmolattice/cosmolattice | bd9a31a026c0b47d53ff486db23448797dbe2fe0 | [
"MIT"
] | 2 | 2021-08-11T07:35:25.000Z | 2022-03-07T21:33:30.000Z | #ifndef TEMPLAT_SESSION_SESSIONGUARD_H
#define TEMPLAT_SESSION_SESSIONGUARD_H
/* This file is part of CosmoLattice, available at www.cosmolattice.net .
Copyright Daniel G. Figueroa, Adrien Florio, Francisco Torrenti and Wessel Valkenburg.
Released under the MIT license, see LICENSE.md. */
// File info: Main contributor(s): Wessel Valkenburg, Year: 2019
#include "TempLat/util/tdd/tdd.h"
#include "TempLat/util/exception.h"
#include "TempLat/fft/fftlibraryselector.h"
#include "TempLat/parallel/mpi/session/mpiguard.h"
namespace TempLat {
MakeException(SessionGuardInstantiationException);
/** \brief A class which holds all the guards: fftw, pfft and mpi.
* Only one instance per process is allowed. Throws an exception if
* that condition is violated.
*
* Unit test: make test-sessionguard
**/
class SessionGuard {
public:
/* Put public methods here. These should change very little over time. */
SessionGuard(int argc, char* argv[], bool verbose = true) :
instanceProtectionKey(InstanceCounter(1)),
mMPIGuard(argc, argv, verbose),
mFFTSessionGuards(FFTLibrarySelector::getSessionGuards(verbose))
{
}
private:
/* Put all member variables and private methods here. These may change arbitrarily. */
int instanceProtectionKey;
MPIGuard mMPIGuard;
std::vector<std::shared_ptr<FFTLibraryInterface::SessionGuard>> mFFTSessionGuards;
static inline int InstanceCounter(int delta = 0) {
static int counter = 0;
counter += delta;
if ( counter > 1) throw SessionGuardInstantiationException("Per process, the MPIGuard can be instantiated only once. This should be done in `int main()`. This is wrong. Instances:", counter);
return counter;
}
public:
#ifdef TEMPLATTEST
static inline void Test(TDDAssertion& tdd);
#endif
};
}
#ifdef TEMPLATTEST
#include "TempLat/session/sessionguard_test.h"
#endif
#endif
| 31.6875 | 203 | 0.695266 | [
"vector"
] |
e00099604a875c9b43c4c502497c6393ab511d5b | 2,485 | h | C | samples/deeplearning/pytorch/xsmmptex/mlpcell/mc_funcs.h | breuera/libxsmm | 8438ddd1d57e97f94848aeb55253c800a6ccc882 | [
"BSD-3-Clause"
] | 651 | 2015-03-14T23:18:44.000Z | 2022-01-19T14:08:28.000Z | samples/deeplearning/pytorch/xsmmptex/mlpcell/mc_funcs.h | breuera/libxsmm | 8438ddd1d57e97f94848aeb55253c800a6ccc882 | [
"BSD-3-Clause"
] | 362 | 2015-01-26T16:20:28.000Z | 2022-01-26T06:19:23.000Z | samples/deeplearning/pytorch/xsmmptex/mlpcell/mc_funcs.h | breuera/libxsmm | 8438ddd1d57e97f94848aeb55253c800a6ccc882 | [
"BSD-3-Clause"
] | 169 | 2015-09-28T17:06:28.000Z | 2021-12-18T16:02:49.000Z | #ifndef MC_FUNCS
#define MC_FUNCS
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <sys/time.h>
#include <assert.h>
#include <string>
#include <iomanip>
#include <stdint.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>
#include <torch/extension.h>
#include <ATen/record_function.h>
#include <torch/csrc/autograd/VariableTypeUtils.h>
#include <vector>
#include <iostream>
#ifdef _OPENMP
#include <omp.h>
#pragma message "Using OpenMP"
#else
#define omp_get_max_threads() 1
#define omp_get_num_threads() 1
#define omp_get_thread_num() 0
#endif
#include <libxsmm.h>
//#include <libxsmm_intrinsics_x86.h>
#include <immintrin.h>
static thread_local unsigned int *rnd_state = NULL;
void set_rnd_seed(unsigned int seed)
{
#pragma omp parallel
{
int tid = omp_get_thread_num();
if(rnd_state) {
libxsmm_rng_destroy_extstate(rnd_state);
rnd_state = NULL;
}
rnd_state = libxsmm_rng_create_extstate(seed+tid);
}
}
void init_libxsmm()
{
libxsmm_init();
set_rnd_seed(0);
}
struct f32
{
std::vector<at::Tensor> dropout_forward(torch::Tensor input, float p, bool train);
at::Tensor dropout_backward(torch::Tensor input, torch::Tensor dropout_mask, float p);
};
// --------------------------------------- copy() -----------------------------------------------------------------
inline void f32_copy(int N, int M, int LDO, int LDI, libxsmm_meltw_unary_param *params)
{
libxsmm_meltw_unary_flags unary_flags = LIBXSMM_MELTW_FLAG_UNARY_NONE;
libxsmm_meltw_unary_type unary_type = LIBXSMM_MELTW_TYPE_UNARY_IDENTITY;
libxsmm_datatype compute_dtype = LIBXSMM_DATATYPE_F32;
libxsmm_meltwfunction_unary kernel = libxsmm_dispatch_meltw_unary(M, N, &LDI, &LDO, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, compute_dtype, unary_flags, unary_type);
if ( kernel == NULL )
{
fprintf( stderr, "JIT for f32 to f32 copy failed. Bailing...!\n");
exit(-1);
}
kernel(params);
}
inline void zero(int M, libxsmm_meltw_unary_param *params)
{
libxsmm_meltw_unary_flags unary_flags = LIBXSMM_MELTW_FLAG_UNARY_NONE;
libxsmm_meltw_unary_type unary_type = LIBXSMM_MELTW_TYPE_UNARY_XOR;
libxsmm_datatype dtype = LIBXSMM_DATATYPE_F32;
libxsmm_meltwfunction_unary kernel = libxsmm_dispatch_meltw_unary(M, 1, &M, &M, dtype, dtype, dtype, unary_flags, unary_type);
if ( kernel == NULL )
{
fprintf( stderr, "JIT for zero kernel failed. Bailing...!\n");
exit(-1);
}
kernel(params);
}
#endif
| 24.126214 | 170 | 0.708249 | [
"vector"
] |
e0080e314f72b7880e0edc6fedb9a18a68ec248f | 3,978 | h | C | src/uvmsc/base/uvm_event.h | stoitchog/uvm-systemc-1.0-beta2 | 67a445dc5f587d2fd16c5b5ee913d086b2242583 | [
"ECL-2.0",
"Apache-2.0"
] | 4 | 2021-11-04T14:37:00.000Z | 2022-03-14T12:57:50.000Z | src/uvmsc/base/uvm_event.h | stoitchog/uvm-systemc-1.0-beta2 | 67a445dc5f587d2fd16c5b5ee913d086b2242583 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | src/uvmsc/base/uvm_event.h | stoitchog/uvm-systemc-1.0-beta2 | 67a445dc5f587d2fd16c5b5ee913d086b2242583 | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2021-02-22T05:46:04.000Z | 2021-02-22T05:46:04.000Z | //----------------------------------------------------------------------
// Copyright 2013-2016 NXP B.V.
// Copyright 2007-2010 Mentor Graphics Corporation
// Copyright 2007-2011 Cadence Design Systems, Inc.
// Copyright 2010 Synopsys, Inc.
// All Rights Reserved Worldwide
//
// 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 UVM_EVENT_H_
#define UVM_EVENT_H_
#include <systemc>
#include <vector>
#include <memory>
#include "uvmsc/base/uvm_object.h"
// forward declaration of uvm_packer used in uvm_object
class uvm_object;
class uvm_event_callback;
class uvm_printer;
namespace uvm {
//----------------------------------------------------------------------
// CLASS: uvm_event
//
//! The class uvm_event is a wrapper class around the SystemC event
//! construct. It provides some additional standardized UVM services
//! such as setting callbacks and maintaining the number of waiters.
//----------------------------------------------------------------------
class uvm_event : public uvm_object
{
public:
// Constructor creates a new event object.
uvm_event( const std::string& name="" );
//---------
// waiting
//---------
virtual void wait_on ( bool delta = false );
virtual void wait_off ( bool delta = false );
virtual void wait_trigger();
virtual void wait_ptrigger();
virtual void wait_trigger_data( uvm_object*& data );
virtual void wait_ptrigger_data( uvm_object*& data );
//------------
// triggering
//------------
virtual void trigger( uvm_object* data = NULL );
virtual uvm_object* get_trigger_data();
virtual sc_core::sc_time get_trigger_time();
//-------
// state
//-------
virtual bool is_on();
virtual bool is_off();
virtual void reset( bool wakeup = false );
//-----------
// callbacks
//-----------
virtual void add_callback( uvm_event_callback* cb, bool append = true );
virtual void delete_callback( uvm_event_callback* cb );
//--------------
// waiters list
//--------------
virtual void cancel();
virtual int get_num_waiters() const;
virtual uvm_object* create( const std::string& name = "" );
virtual const std::string get_type_name() const;
virtual void do_print( const uvm_printer& printer ) const;
virtual void do_copy( const uvm_object& rhs );
/////////////////////////////////////////////////////
/////////////////////////////////////////////////////
// Implementation-defined member functions below,
// not part of UVM Class reference / LRM
/////////////////////////////////////////////////////
/////////////////////////////////////////////////////
virtual ~uvm_event();
uvm_event( const uvm_event& ev );
uvm_event& operator=( const uvm_event& ev );
private:
void m_clean();
void m_init_event( const uvm_event& ev );
// data members
const static std::string type_name;
bool m_event_val;
sc_core::sc_event* m_event;
std::vector<uvm_event*> m_event_list;
int m_num_waiters;
bool on;
sc_core::sc_event* m_on_ev;
sc_core::sc_time trigger_time;
uvm_object* trigger_data;
std::vector<uvm_event_callback*> callbacks;
typedef std::vector<uvm_event_callback*>::iterator callbacks_itt;
// TODO: unused
/* int m_cnt; */
static int g_cnt;
}; // class uvm_event
} // namespace uvm
#endif // UVM_EVENT_H_
| 24.8625 | 74 | 0.587984 | [
"object",
"vector"
] |
e0221c7e34a0ff0a7e951c2f36f721dc7e0ec95c | 10,915 | c | C | source/renderer/vulkan/vulkan_texture.c | ravi688/VulkanRenderer | 2e4d15cd53a7fef49fc2e6fe27643746ca1245da | [
"MIT"
] | null | null | null | source/renderer/vulkan/vulkan_texture.c | ravi688/VulkanRenderer | 2e4d15cd53a7fef49fc2e6fe27643746ca1245da | [
"MIT"
] | 3 | 2022-01-28T23:19:13.000Z | 2022-02-02T07:51:30.000Z | source/renderer/vulkan/vulkan_texture.c | ravi688/VulkanRenderer | 2e4d15cd53a7fef49fc2e6fe27643746ca1245da | [
"MIT"
] | null | null | null | #include <renderer/internal/vulkan/vulkan_defines.h>
#include <renderer/internal/vulkan/vulkan_texture.h>
#include <renderer/internal/vulkan/vulkan_renderer.h>
#include <renderer/internal/vulkan/vulkan_image.h>
#include <renderer/internal/vulkan/vulkan_buffer.h>
#include <renderer/internal/vulkan/vulkan_result.h>
#include <renderer/memory_allocator.h>
#include <renderer/assert.h>
/*
description:
creates a default sampler with linear filtering and repeat mode
params:
renderer: pointer to vulkan_renderer_t object
returns:
VkSampler object
*/
static VkSampler get_default_sampler(vulkan_renderer_t* renderer);
/*
description:
creates a cube sampler with linear filtering and clamped mode
params:
renderer: pointer to vulkan_renderer_t object
returns:
VkSampler object
*/
static VkSampler get_cubmap_sampler(vulkan_renderer_t* renderer);
/*
description:
creats a 2d vulkan texture object
params:
texture: pointer to the vulkan_texture_t object created with vulkan_texture_new()
data: pointer to the vulkan_texture_data_t object (representing only 1 object)
type: valid values are VULKAN_TEXTURE_TYPE_ALBEDO and VULKAN_TEXTURE_TYPE_NORMAL. VULKAN_TEXTURE_TYPE_CUBE shouldn't be used here, though no error would occur.
returns:
nothing
*/
static void vulkan_texture_create_2d(vulkan_texture_t* texture, vulkan_texture_data_t* data, vulkan_texture_type_t type);
/*
description:
creats a 3d vulkan texture object
params:
texture: pointer to the vulkan_texture_t object created with vulkan_texture_new()
data: pointer to the vulkan_texture_data_t object (representing only 1 object)
returns:
nothing
*/
static void vulkan_texture_create_3d(vulkan_texture_t* texture, vulkan_texture_data_t* data);
/*
description:
creats a cube map vulkan texture object
params:
texture: pointer to the vulkan_texture_t object created with vulkan_texture_new()
data: pointer to the vulkan_texture_data_t object (representing array of texture data)
count: number of vulkan_texture_data_t object that 'data' points to; valid values are 1 and 6 only
returns:
nothing
*/
static void vulkan_texture_create_cube(vulkan_texture_t* texture, vulkan_texture_data_t* data, u32 count);
RENDERER_API vulkan_texture_t* vulkan_texture_new()
{
vulkan_texture_t* texture = heap_new(vulkan_texture_t);
memset(texture, 0, sizeof(vulkan_texture_t));
return texture;
}
RENDERER_API vulkan_texture_t* vulkan_texture_create(vulkan_renderer_t* renderer, vulkan_texture_create_info_t* create_info)
{
assert(create_info != NULL);
assert(create_info->data != NULL);
assert(create_info->data_count != 0);
// for now every texture must have channel count equals to 4
#ifdef GLOBAL_DEBUG
for(u32 i = 0; i < create_info->data_count; i++)
assert(create_info->data[i].channel_count == 4);
#endif // GLOBAL_DEBUG
vulkan_texture_t* texture = vulkan_texture_new();
texture->renderer = renderer;
switch(create_info->type)
{
case VULKAN_TEXTURE_TYPE_ALBEDO:
case VULKAN_TEXTURE_TYPE_NORMAL:
vulkan_texture_create_2d(texture, create_info->data, create_info->type);
break;
case VULKAN_TEXTURE_TYPE_CUBE:
vulkan_texture_create_cube(texture, create_info->data, create_info->data_count);
break;
default:
LOG_FETAL_ERR("Invalid vulkan texture type\n");
}
return texture;
}
RENDERER_API void vulkan_texture_destroy(vulkan_texture_t* texture)
{
assert(texture != NULL);
vkDestroySampler(texture->renderer->logical_device->handle, texture->image_sampler, NULL);
vulkan_image_view_destroy(texture->image_view);
vulkan_image_destroy(texture->image);
}
RENDERER_API void vulkan_texture_release_resources(vulkan_texture_t* texture)
{
assert(texture != NULL);
vulkan_image_view_release_resources(texture->image_view);
vulkan_image_release_resources(texture->image);
heap_free(texture);
}
static void vulkan_texture_create_2d(vulkan_texture_t* texture, vulkan_texture_data_t* data, vulkan_texture_type_t type)
{
void* texture_data = data->data;
u32 texture_width = data->width;
u32 texture_height = data->height;
u32 texture_size = texture_width * texture_height * 4;
// prepare staging buffer
vulkan_buffer_create_info_t staging_buffer_info =
{
.data = texture_data,
.size = texture_size,
.usage_flags = VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
.sharing_mode = VK_SHARING_MODE_EXCLUSIVE,
.memory_property_flags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT
};
vulkan_buffer_t* staging_buffer = vulkan_buffer_create(texture->renderer, &staging_buffer_info);
// create image
VkFormat format;
switch(type)
{
// for albedo the format should be VK_FORMAT_R8G8B8A8_SRGB for best color
case VULKAN_TEXTURE_TYPE_ALBEDO:
format = VK_FORMAT_R8G8B8A8_SRGB;
break;
case VULKAN_TEXTURE_TYPE_NORMAL:
format = VK_FORMAT_R8G8B8A8_UNORM;
break;
}
vulkan_image_create_info_t image_info =
{
.flags = 0, // optional
.type = VK_IMAGE_TYPE_2D,
.width = texture_width,
.height = texture_height,
.depth = 1,
.layer_count = 1,
.format = format,
.tiling = VK_IMAGE_TILING_OPTIMAL,
.layout = VK_IMAGE_LAYOUT_UNDEFINED,
.usage_mask = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT,
.memory_properties_mask = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
.aspect_mask = VK_IMAGE_ASPECT_COLOR_BIT
};
texture->image = vulkan_image_create(texture->renderer, &image_info);
// transition image layout from undefined to transfer destination optimal
vulkan_image_transition_layout_to(texture->image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
// copy device memory of staging buffer to the device memory of the image
vulkan_image_copy_from_buffer(texture->image, staging_buffer);
// transition image layout from transfer destination optimal to shader read only optimal
vulkan_image_transition_layout_to(texture->image, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
// destroy staging buffer and it's device memory
vulkan_buffer_destroy(staging_buffer);
vulkan_buffer_release_resources(staging_buffer);
// create 2d image view
texture->image_view = vulkan_image_view_create(texture->image, VULKAN_IMAGE_VIEW_TYPE_2D);
// create default sampler
texture->image_sampler = get_default_sampler(texture->renderer);
}
static void vulkan_texture_create_3d(vulkan_texture_t* texture, vulkan_texture_data_t* data);
static void vulkan_texture_create_cube(vulkan_texture_t* texture, vulkan_texture_data_t* data, u32 count)
{
// for now, we will be using 6 separate textures for a cube map texture
assert(count == 6);
u32 texture_width = data->width;
u32 texture_height = data->height;
u32 texture_size = texture_width * texture_height * 4;
u8 channel_count = data->channel_count;
// check if all vulkan_texture_data_t objects have identical dimensions and channel count
for(u32 i = 1; i < 6; i++)
if((texture_width != data[i].width) || (texture_height != data[i].height) || (channel_count != data[i].channel_count))
LOG_FETAL_ERR("For cube map all 6 textures must have identical dimensions and number of channels\n");
// prepare staging buffer
vulkan_buffer_create_info_t staging_buffer_info =
{
.data = NULL, // optional
.stride = texture_size,
.count = 6,
.usage_flags = VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
.sharing_mode = VK_SHARING_MODE_EXCLUSIVE,
.memory_property_flags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT
};
vulkan_buffer_t* staging_buffer = vulkan_buffer_create(texture->renderer, &staging_buffer_info);
// copy textures sequentially into the staging buffer
for(u32 i = 0; i < 6; i++)
vulkan_buffer_copy_data(staging_buffer, texture_size * i, data[i].data, texture_size);
// create image
vulkan_image_create_info_t image_info =
{
.flags = VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT, // required for cube map images
.type = VK_IMAGE_TYPE_2D,
.width = texture_width,
.height = texture_height,
.depth = 1,
.layer_count = 6,
// for VULKAN_TEXTURE_TYPE_CUBE, format should be VK_FORMAT_R8G8B8A8_SRGB for best color
.format = VK_FORMAT_R8G8B8A8_SRGB,
.tiling = VK_IMAGE_TILING_OPTIMAL,
.layout = VK_IMAGE_LAYOUT_UNDEFINED,
.usage_mask = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT,
.memory_properties_mask = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
.aspect_mask = VK_IMAGE_ASPECT_COLOR_BIT
};
texture->image = vulkan_image_create(texture->renderer, &image_info);
// transition image layout from undefined to transfer destination optimal
vulkan_image_transition_layout_to(texture->image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
// copy device memory of staging buffer to the device memory of the image
vulkan_image_copy_from_buffer(texture->image, staging_buffer);
// transition image layout from transfer destination optimal to shader read only optimal
vulkan_image_transition_layout_to(texture->image, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
// destroy staging buffer and it's device memory
vulkan_buffer_destroy(staging_buffer);
vulkan_buffer_release_resources(staging_buffer);
// create 2d image view
texture->image_view = vulkan_image_view_create(texture->image, VULKAN_IMAGE_VIEW_TYPE_CUBE);
// create default sampler
texture->image_sampler = get_cubmap_sampler(texture->renderer);
}
static VkSampler get_default_sampler(vulkan_renderer_t* renderer)
{
VkSamplerCreateInfo create_info =
{
.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO,
.magFilter = VK_FILTER_LINEAR,
.minFilter = VK_FILTER_LINEAR,
.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT,
.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT,
.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT,
.anisotropyEnable = VK_FALSE,
.maxAnisotropy = 1.0f,
.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE,
.unnormalizedCoordinates = VK_FALSE,
.compareEnable = VK_FALSE,
.compareOp = VK_COMPARE_OP_NEVER,
.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR,
.mipLodBias = 0.0f,
.minLod = 0.0f,
.maxLod = 0.0f
};
VkSampler sampler;
vkCall(vkCreateSampler(renderer->logical_device->handle, &create_info, NULL, &sampler));
return sampler;
}
static VkSampler get_cubmap_sampler(vulkan_renderer_t* renderer)
{
VkSamplerCreateInfo create_info =
{
.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO,
.magFilter = VK_FILTER_LINEAR,
.minFilter = VK_FILTER_LINEAR,
.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
.anisotropyEnable = VK_FALSE,
.maxAnisotropy = 1.0f,
.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE,
.unnormalizedCoordinates = VK_FALSE,
.compareEnable = VK_FALSE,
.compareOp = VK_COMPARE_OP_NEVER,
.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR,
.mipLodBias = 0.0f,
.minLod = 0.0f,
.maxLod = 0.0f
};
VkSampler sampler;
vkCall(vkCreateSampler(renderer->logical_device->handle, &create_info, NULL, &sampler));
return sampler;
}
| 35.096463 | 161 | 0.793678 | [
"object",
"3d"
] |
e02e1e1b9bc797b69908c420238c80aa3a4ce0c7 | 8,662 | c | C | gnutls/gnutls/src/libopts/init.c | rhausam/wine-crossover | b954f98f25f195f9de29c28c41fcb074d77de0f0 | [
"MIT"
] | null | null | null | gnutls/gnutls/src/libopts/init.c | rhausam/wine-crossover | b954f98f25f195f9de29c28c41fcb074d77de0f0 | [
"MIT"
] | null | null | null | gnutls/gnutls/src/libopts/init.c | rhausam/wine-crossover | b954f98f25f195f9de29c28c41fcb074d77de0f0 | [
"MIT"
] | null | null | null | /**
* \file initialize.c
*
* initialize the libopts data structures.
*
* @addtogroup autoopts
* @{
*/
/*
* This file is part of AutoOpts, a companion to AutoGen.
* AutoOpts is free software.
* AutoOpts is Copyright (C) 1992-2015 by Bruce Korb - all rights reserved
*
* AutoOpts is available under any one of two licenses. The license
* in use must be one of these two and the choice is under the control
* of the user of the license.
*
* The GNU Lesser General Public License, version 3 or later
* See the files "COPYING.lgplv3" and "COPYING.gplv3"
*
* The Modified Berkeley Software Distribution License
* See the file "COPYING.mbsd"
*
* These files have the following sha256 sums:
*
* 8584710e9b04216a394078dc156b781d0b47e1729104d666658aecef8ee32e95 COPYING.gplv3
* 4379e7444a0e2ce2b12dd6f5a52a27a4d02d39d247901d3285c88cf0d37f477b COPYING.lgplv3
* 13aa749a5b0a454917a944ed8fffc530b784f5ead522b1aacaf4ec8aa55a6239 COPYING.mbsd
*/
/* = = = START-STATIC-FORWARD = = = */
static tSuccess
do_presets(tOptions * opts);
/* = = = END-STATIC-FORWARD = = = */
/**
* Make sure the option descriptor is there and that we understand it.
* This should be called from any user entry point where one needs to
* worry about validity. (Some entry points are free to assume that
* the call is not the first to the library and, thus, that this has
* already been called.)
*
* Upon successful completion, pzProgName and pzProgPath are set.
*
* @param[in,out] opts program options descriptor
* @param[in] pname name of program, from argv[]
* @returns SUCCESS or FAILURE
*/
LOCAL tSuccess
validate_struct(tOptions * opts, char const * pname)
{
if (opts == NULL) {
fputs(zno_opt_arg, stderr);
return FAILURE;
}
print_exit = ((opts->fOptSet & OPTPROC_SHELL_OUTPUT) != 0);
/*
* IF the client has enabled translation and the translation procedure
* is available, then go do it.
*/
if ( ((opts->fOptSet & OPTPROC_TRANSLATE) != 0)
&& (opts->pTransProc != NULL)
&& (option_xlateable_txt.field_ct != 0) ) {
/*
* If option names are not to be translated at all, then do not do
* it for configuration parsing either. (That is the bit that really
* gets tested anyway.)
*/
if ((opts->fOptSet & OPTPROC_NO_XLAT_MASK) == OPTPROC_NXLAT_OPT)
opts->fOptSet |= OPTPROC_NXLAT_OPT_CFG;
opts->pTransProc();
}
/*
* IF the struct version is not the current, and also
* either too large (?!) or too small,
* THEN emit error message and fail-exit
*/
if ( ( opts->structVersion != OPTIONS_STRUCT_VERSION )
&& ( (opts->structVersion > OPTIONS_STRUCT_VERSION )
|| (opts->structVersion < OPTIONS_MINIMUM_VERSION )
) ) {
fprintf(stderr, zwrong_ver, pname, NUM_TO_VER(opts->structVersion));
if (opts->structVersion > OPTIONS_STRUCT_VERSION )
fputs(ztoo_new, stderr);
else
fputs(ztoo_old, stderr);
fwrite(ao_ver_string, sizeof(ao_ver_string) - 1, 1, stderr);
return FAILURE;
}
/*
* If the program name hasn't been set, then set the name and the path
* and the set of equivalent characters.
*/
if (opts->pzProgName == NULL) {
char const * pz = strrchr(pname, DIRCH);
char const ** pp =
(char const **)(void **)&(opts->pzProgName);
if (pz != NULL)
*pp = pz+1;
else
*pp = pname;
pz = pathfind(getenv("PATH"), (char *)pname, "rx");
if (pz != NULL)
pname = VOIDP(pz);
pp = (char const **)VOIDP(&(opts->pzProgPath));
*pp = pname;
/*
* when comparing long names, these are equivalent
*/
strequate(zSepChars);
}
return SUCCESS;
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* DO PRESETS
*
* The next several routines do the immediate action pass on the command
* line options, then the environment variables, then the config files in
* reverse order. Once done with that, the order is reversed and all
* the config files and environment variables are processed again, this
* time only processing the non-immediate action options. do_presets()
* will then return for optionProcess() to do the final pass on the command
* line arguments.
*/
/**
* scan the command line for immediate action options.
* This is only called the first time through.
* While this procedure is active, the OPTPROC_IMMEDIATE is true.
*
* @param pOpts program options descriptor
* @returns SUCCESS or FAILURE
*/
LOCAL tSuccess
immediate_opts(tOptions * opts)
{
tSuccess res;
opts->fOptSet |= OPTPROC_IMMEDIATE;
opts->curOptIdx = 1; /* start by skipping program name */
opts->pzCurOpt = NULL;
/*
* Examine all the options from the start. We process any options that
* are marked for immediate processing.
*/
for (;;) {
tOptState opt_st = OPTSTATE_INITIALIZER(PRESET);
res = next_opt(opts, &opt_st);
switch (res) {
case FAILURE: goto failed_option;
case PROBLEM: res = SUCCESS; goto leave;
case SUCCESS: break;
}
/*
* IF this is an immediate-attribute option, then do it.
*/
if (! DO_IMMEDIATELY(opt_st.flags))
continue;
if (! SUCCESSFUL(handle_opt(opts, &opt_st)))
break;
} failed_option:;
if ((opts->fOptSet & OPTPROC_ERRSTOP) != 0)
(*opts->pUsageProc)(opts, EXIT_FAILURE);
leave:
opts->fOptSet &= ~OPTPROC_IMMEDIATE;
return res;
}
/**
* check for preset values from a config files or envrionment variables
*
* @param[in,out] opts the structure with the option names to check
*/
static tSuccess
do_presets(tOptions * opts)
{
tOptDesc * od = NULL;
if (! SUCCESSFUL(immediate_opts(opts)))
return FAILURE;
/*
* IF this option set has a --save-opts option, then it also
* has a --load-opts option. See if a command line option has disabled
* option presetting.
*/
if ( (opts->specOptIdx.save_opts != NO_EQUIVALENT)
&& (opts->specOptIdx.save_opts != 0)) {
od = opts->pOptDesc + opts->specOptIdx.save_opts + 1;
if (DISABLED_OPT(od))
return SUCCESS;
}
/*
* Until we return from this procedure, disable non-presettable opts
*/
opts->fOptSet |= OPTPROC_PRESETTING;
/*
* IF there are no config files,
* THEN do any environment presets and leave.
*/
if (opts->papzHomeList == NULL) {
env_presets(opts, ENV_ALL);
}
else {
env_presets(opts, ENV_IMM);
/*
* Check to see if environment variables have disabled presetting.
*/
if ((od != NULL) && ! DISABLED_OPT(od))
intern_file_load(opts);
/*
* ${PROGRAM_LOAD_OPTS} value of "no" cannot disable other environment
* variable options. Only the loading of .rc files.
*/
env_presets(opts, ENV_NON_IMM);
}
opts->fOptSet &= ~OPTPROC_PRESETTING;
return SUCCESS;
}
/**
* AutoOpts initialization
*
* @param[in,out] opts the structure to initialize
* @param[in] a_ct program argument count
* @param[in] a_v program argument vector
*/
LOCAL bool
ao_initialize(tOptions * opts, int a_ct, char ** a_v)
{
if ((opts->fOptSet & OPTPROC_INITDONE) != 0)
return true;
opts->origArgCt = (unsigned int)a_ct;
opts->origArgVect = a_v;
opts->fOptSet |= OPTPROC_INITDONE;
if (HAS_pzPkgDataDir(opts))
program_pkgdatadir = opts->pzPkgDataDir;
if (! SUCCESSFUL(do_presets(opts)))
return false;
/*
* IF option name conversion was suppressed but it is not suppressed
* for the command line, then it's time to translate option names.
* Usage text will not get retranslated.
*/
if ( ((opts->fOptSet & OPTPROC_TRANSLATE) != 0)
&& (opts->pTransProc != NULL)
&& ((opts->fOptSet & OPTPROC_NO_XLAT_MASK) == OPTPROC_NXLAT_OPT_CFG)
) {
opts->fOptSet &= ~OPTPROC_NXLAT_OPT_CFG;
(*opts->pTransProc)();
}
if ((opts->fOptSet & OPTPROC_REORDER) != 0)
optionSort(opts);
opts->curOptIdx = 1;
opts->pzCurOpt = NULL;
return true;
}
/** @}
*
* Local Variables:
* mode: C
* c-file-style: "stroustrup"
* indent-tabs-mode: nil
* End:
* end of autoopts/initialize.c */
| 29.362712 | 84 | 0.615793 | [
"vector"
] |
e03943e6380a6dfec2438c379d27674f0d69293b | 9,124 | c | C | drivers/platform/x86/intel/int1092/intel_sar.c | jainsakshi2395/linux | 7ccb860232bb83fb60cd6bcf5aaf0c008d903acb | [
"Linux-OpenIB"
] | 44 | 2022-03-16T08:32:31.000Z | 2022-03-31T16:02:35.000Z | drivers/platform/x86/intel/int1092/intel_sar.c | jainsakshi2395/linux | 7ccb860232bb83fb60cd6bcf5aaf0c008d903acb | [
"Linux-OpenIB"
] | 1 | 2021-01-27T01:29:47.000Z | 2021-01-27T01:29:47.000Z | drivers/platform/x86/intel/int1092/intel_sar.c | jainsakshi2395/linux | 7ccb860232bb83fb60cd6bcf5aaf0c008d903acb | [
"Linux-OpenIB"
] | 18 | 2022-03-19T04:41:04.000Z | 2022-03-31T03:32:12.000Z | // SPDX-License-Identifier: GPL-2.0-only
/*
* Copyright (c) 2021, Intel Corporation.
*/
#include <linux/acpi.h>
#include <linux/kobject.h>
#include <linux/platform_device.h>
#include <linux/sysfs.h>
#include "intel_sar.h"
/**
* get_int_value: Retrieve integer values from ACPI Object
* @obj: acpi_object pointer which has the integer value
* @out: output pointer will get integer value
*
* Function is used to retrieve integer value from acpi object.
*
* Return:
* * 0 on success
* * -EIO if there is an issue in acpi_object passed.
*/
static int get_int_value(union acpi_object *obj, int *out)
{
if (!obj || obj->type != ACPI_TYPE_INTEGER)
return -EIO;
*out = (int)obj->integer.value;
return 0;
}
/**
* update_sar_data: sar data is updated based on regulatory mode
* @context: pointer to driver context structure
*
* sar_data is updated based on regulatory value
* context->reg_value will never exceed MAX_REGULATORY
*/
static void update_sar_data(struct wwan_sar_context *context)
{
struct wwan_device_mode_configuration *config =
&context->config_data[context->reg_value];
if (config->device_mode_info &&
context->sar_data.device_mode < config->total_dev_mode) {
int itr = 0;
for (itr = 0; itr < config->total_dev_mode; itr++) {
if (context->sar_data.device_mode ==
config->device_mode_info[itr].device_mode) {
struct wwan_device_mode_info *dev_mode =
&config->device_mode_info[itr];
context->sar_data.antennatable_index = dev_mode->antennatable_index;
context->sar_data.bandtable_index = dev_mode->bandtable_index;
context->sar_data.sartable_index = dev_mode->sartable_index;
break;
}
}
}
}
/**
* parse_package: parse acpi package for retrieving SAR information
* @context: pointer to driver context structure
* @item : acpi_object pointer
*
* Given acpi_object is iterated to retrieve information for each device mode.
* If a given package corresponding to a specific device mode is faulty, it is
* skipped and the specific entry in context structure will have the default value
* of zero. Decoding of subsequent device modes is realized by having "continue"
* statements in the for loop on encountering error in parsing given device mode.
*
* Return:
* AE_OK if success
* AE_ERROR on error
*/
static acpi_status parse_package(struct wwan_sar_context *context, union acpi_object *item)
{
struct wwan_device_mode_configuration *data;
int value, itr, reg;
union acpi_object *num;
num = &item->package.elements[0];
if (get_int_value(num, &value) || value < 0 || value >= MAX_REGULATORY)
return AE_ERROR;
reg = value;
data = &context->config_data[reg];
if (data->total_dev_mode > MAX_DEV_MODES || data->total_dev_mode == 0 ||
item->package.count <= data->total_dev_mode)
return AE_ERROR;
data->device_mode_info = kmalloc_array(data->total_dev_mode,
sizeof(struct wwan_device_mode_info), GFP_KERNEL);
if (!data->device_mode_info)
return AE_ERROR;
for (itr = 0; itr < data->total_dev_mode; itr++) {
struct wwan_device_mode_info temp = { 0 };
num = &item->package.elements[itr + 1];
if (num->type != ACPI_TYPE_PACKAGE || num->package.count < TOTAL_DATA)
continue;
if (get_int_value(&num->package.elements[0], &temp.device_mode))
continue;
if (get_int_value(&num->package.elements[1], &temp.bandtable_index))
continue;
if (get_int_value(&num->package.elements[2], &temp.antennatable_index))
continue;
if (get_int_value(&num->package.elements[3], &temp.sartable_index))
continue;
data->device_mode_info[itr] = temp;
}
return AE_OK;
}
/**
* sar_get_device_mode: Extraction of information from BIOS via DSM calls
* @device: ACPI device for which to retrieve the data
*
* Retrieve the current device mode information from the BIOS.
*
* Return:
* AE_OK on success
* AE_ERROR on error
*/
static acpi_status sar_get_device_mode(struct platform_device *device)
{
struct wwan_sar_context *context = dev_get_drvdata(&device->dev);
acpi_status status = AE_OK;
union acpi_object *out;
u32 rev = 0;
int value;
out = acpi_evaluate_dsm(context->handle, &context->guid, rev,
COMMAND_ID_DEV_MODE, NULL);
if (get_int_value(out, &value)) {
dev_err(&device->dev, "DSM cmd:%d Failed to retrieve value\n", COMMAND_ID_DEV_MODE);
status = AE_ERROR;
goto dev_mode_error;
}
context->sar_data.device_mode = value;
update_sar_data(context);
sysfs_notify(&device->dev.kobj, NULL, SYSFS_DATANAME);
dev_mode_error:
ACPI_FREE(out);
return status;
}
static const struct acpi_device_id sar_device_ids[] = {
{ "INTC1092", 0},
{}
};
MODULE_DEVICE_TABLE(acpi, sar_device_ids);
static ssize_t intc_data_show(struct device *dev, struct device_attribute *attr, char *buf)
{
struct wwan_sar_context *context = dev_get_drvdata(dev);
return sysfs_emit(buf, "%d %d %d %d\n", context->sar_data.device_mode,
context->sar_data.bandtable_index,
context->sar_data.antennatable_index,
context->sar_data.sartable_index);
}
static DEVICE_ATTR_RO(intc_data);
static ssize_t intc_reg_show(struct device *dev, struct device_attribute *attr, char *buf)
{
struct wwan_sar_context *context = dev_get_drvdata(dev);
return sysfs_emit(buf, "%d\n", context->reg_value);
}
static ssize_t intc_reg_store(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct wwan_sar_context *context = dev_get_drvdata(dev);
unsigned int value;
int read;
if (!count)
return -EINVAL;
read = kstrtouint(buf, 10, &value);
if (read < 0)
return read;
if (value >= MAX_REGULATORY)
return -EOVERFLOW;
context->reg_value = value;
update_sar_data(context);
sysfs_notify(&dev->kobj, NULL, SYSFS_DATANAME);
return count;
}
static DEVICE_ATTR_RW(intc_reg);
static struct attribute *intcsar_attrs[] = {
&dev_attr_intc_data.attr,
&dev_attr_intc_reg.attr,
NULL
};
static struct attribute_group intcsar_group = {
.attrs = intcsar_attrs,
};
static void sar_notify(acpi_handle handle, u32 event, void *data)
{
struct platform_device *device = data;
if (event == SAR_EVENT) {
if (sar_get_device_mode(device) != AE_OK)
dev_err(&device->dev, "sar_get_device_mode error");
}
}
static void sar_get_data(int reg, struct wwan_sar_context *context)
{
union acpi_object *out, req;
u32 rev = 0;
req.type = ACPI_TYPE_INTEGER;
req.integer.value = reg;
out = acpi_evaluate_dsm(context->handle, &context->guid, rev,
COMMAND_ID_CONFIG_TABLE, &req);
if (!out)
return;
if (out->type == ACPI_TYPE_PACKAGE && out->package.count >= 3 &&
out->package.elements[0].type == ACPI_TYPE_INTEGER &&
out->package.elements[1].type == ACPI_TYPE_INTEGER &&
out->package.elements[2].type == ACPI_TYPE_PACKAGE &&
out->package.elements[2].package.count > 0) {
context->config_data[reg].version = out->package.elements[0].integer.value;
context->config_data[reg].total_dev_mode =
out->package.elements[1].integer.value;
if (context->config_data[reg].total_dev_mode <= 0 ||
context->config_data[reg].total_dev_mode > MAX_DEV_MODES) {
ACPI_FREE(out);
return;
}
parse_package(context, &out->package.elements[2]);
}
ACPI_FREE(out);
}
static int sar_probe(struct platform_device *device)
{
struct wwan_sar_context *context;
int reg;
int result;
context = kzalloc(sizeof(*context), GFP_KERNEL);
if (!context)
return -ENOMEM;
context->sar_device = device;
context->handle = ACPI_HANDLE(&device->dev);
dev_set_drvdata(&device->dev, context);
result = guid_parse(SAR_DSM_UUID, &context->guid);
if (result) {
dev_err(&device->dev, "SAR UUID parse error: %d\n", result);
goto r_free;
}
for (reg = 0; reg < MAX_REGULATORY; reg++)
sar_get_data(reg, context);
if (sar_get_device_mode(device) != AE_OK) {
dev_err(&device->dev, "Failed to get device mode\n");
result = -EIO;
goto r_free;
}
result = sysfs_create_group(&device->dev.kobj, &intcsar_group);
if (result) {
dev_err(&device->dev, "sysfs creation failed\n");
goto r_free;
}
if (acpi_install_notify_handler(ACPI_HANDLE(&device->dev), ACPI_DEVICE_NOTIFY,
sar_notify, (void *)device) != AE_OK) {
dev_err(&device->dev, "Failed acpi_install_notify_handler\n");
result = -EIO;
goto r_sys;
}
return 0;
r_sys:
sysfs_remove_group(&device->dev.kobj, &intcsar_group);
r_free:
kfree(context);
return result;
}
static int sar_remove(struct platform_device *device)
{
struct wwan_sar_context *context = dev_get_drvdata(&device->dev);
int reg;
acpi_remove_notify_handler(ACPI_HANDLE(&device->dev),
ACPI_DEVICE_NOTIFY, sar_notify);
sysfs_remove_group(&device->dev.kobj, &intcsar_group);
for (reg = 0; reg < MAX_REGULATORY; reg++)
kfree(context->config_data[reg].device_mode_info);
kfree(context);
return 0;
}
static struct platform_driver sar_driver = {
.probe = sar_probe,
.remove = sar_remove,
.driver = {
.name = DRVNAME,
.acpi_match_table = ACPI_PTR(sar_device_ids)
}
};
module_platform_driver(sar_driver);
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("Platform device driver for INTEL MODEM BIOS SAR");
MODULE_AUTHOR("Shravan Sudhakar <s.shravan@intel.com>");
| 28.160494 | 91 | 0.724682 | [
"object"
] |
e03d1396574ef9b8e75ebd1d537fd2243ddaa92e | 404 | c | C | d/player.village/key.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 13 | 2019-07-19T05:24:44.000Z | 2021-11-18T04:08:19.000Z | d/player.village/key.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 4 | 2021-03-15T18:56:39.000Z | 2021-08-17T17:08:22.000Z | d/player.village/key.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 13 | 2019-09-12T06:22:38.000Z | 2022-01-31T01:15:12.000Z | #include "pvillage.h"
inherit OBJECT;
string filename,player;
void create() {
::create();
set_id( ({"key"}) );
set_short("key");
set_long("key");
set_weight(0);
set_value(0);
}
drop(){return 1;}
restore_me(){ ::restore_me();restore_object(KEYS+filename,1); }
save_me(){ save_object(KEYS+filename,1); }
void set_player(string str){
player = str;
filename = player+"key";
}
| 16.16 | 63 | 0.633663 | [
"object"
] |
e04606c36177ca219c3372e187c234d6ebc9003a | 3,860 | h | C | VirtualBox-5.0.0/src/VBox/Frontends/VirtualBox/src/widgets/UIPortForwardingTable.h | egraba/vbox_openbsd | 6cb82f2eed1fa697d088cecc91722b55b19713c2 | [
"MIT"
] | 1 | 2015-04-30T14:18:45.000Z | 2015-04-30T14:18:45.000Z | VirtualBox-5.0.0/src/VBox/Frontends/VirtualBox/src/widgets/UIPortForwardingTable.h | egraba/vbox_openbsd | 6cb82f2eed1fa697d088cecc91722b55b19713c2 | [
"MIT"
] | null | null | null | VirtualBox-5.0.0/src/VBox/Frontends/VirtualBox/src/widgets/UIPortForwardingTable.h | egraba/vbox_openbsd | 6cb82f2eed1fa697d088cecc91722b55b19713c2 | [
"MIT"
] | null | null | null | /* $Id: UIPortForwardingTable.h $ */
/** @file
* VBox Qt GUI - UIPortForwardingTable class declaration.
*/
/*
* Copyright (C) 2010-2013 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*/
#ifndef __UIPortForwardingTable_h__
#define __UIPortForwardingTable_h__
/* Qt includes: */
#include <QWidget>
/* GUI includes: */
#include "QIWithRetranslateUI.h"
/* COM includes: */
#include "COMEnums.h"
/* Forward declarations: */
class QITableView;
class UIToolBar;
class QIDialogButtonBox;
class UIPortForwardingModel;
/* Name data: */
class NameData : public QString
{
public:
NameData() : QString() {}
NameData(const QString &strName) : QString(strName) {}
};
Q_DECLARE_METATYPE(NameData);
/* Ip data: */
class IpData : public QString
{
public:
IpData() : QString() {}
IpData(const QString &strIP) : QString(strIP) {}
};
Q_DECLARE_METATYPE(IpData);
/* Port data: */
class PortData
{
public:
PortData() : m_uValue(0) {}
PortData(ushort uValue) : m_uValue(uValue) {}
PortData(const PortData &other) : m_uValue(other.value()) {}
bool operator==(const PortData &other) { return m_uValue == other.m_uValue; }
ushort value() const { return m_uValue; }
private:
ushort m_uValue;
};
Q_DECLARE_METATYPE(PortData);
/* Port forwarding data: */
struct UIPortForwardingData
{
UIPortForwardingData(const NameData &strName, KNATProtocol protocol,
const IpData &strHostIP, PortData uHostPort,
const IpData &strGuestIP, PortData uGuestPort)
: name(strName), protocol(protocol)
, hostIp(strHostIP), hostPort(uHostPort)
, guestIp(strGuestIP), guestPort(uGuestPort) {}
bool operator==(const UIPortForwardingData &other)
{
return name == other.name &&
protocol == other.protocol &&
hostIp == other.hostIp &&
hostPort == other.hostPort &&
guestIp == other.guestIp &&
guestPort == other.guestPort;
}
NameData name;
KNATProtocol protocol;
IpData hostIp;
PortData hostPort;
IpData guestIp;
PortData guestPort;
};
/* Port forwarding data list: */
typedef QList<UIPortForwardingData> UIPortForwardingDataList;
/* Port forwarding dialog: */
class UIPortForwardingTable : public QIWithRetranslateUI<QWidget>
{
Q_OBJECT;
public:
/* Constructor: */
UIPortForwardingTable(const UIPortForwardingDataList &rules, bool fIPv6);
/* API: Rules stuff: */
const UIPortForwardingDataList& rules() const;
bool validate() const;
bool discard() const;
private slots:
/* Handlers: Table operation stuff: */
void sltAddRule();
void sltCopyRule();
void sltDelRule();
/* Handlers: Table stuff: */
void sltTableDataChanged();
void sltCurrentChanged();
void sltShowTableContexMenu(const QPoint &position);
void sltAdjustTable();
private:
/* Handler: Translation stuff: */
void retranslateUi();
/* Handlers: Event-processing stuff: */
bool eventFilter(QObject *pObject, QEvent *pEvent);
/* Flags: */
bool m_fIsTableDataChanged;
/* Widgets: */
QITableView *m_pTableView;
UIToolBar *m_pToolBar;
/* Model: */
UIPortForwardingModel *m_pModel;
/* Actions: */
QAction *m_pAddAction;
QAction *m_pCopyAction;
QAction *m_pDelAction;
};
#endif // __UIPortForwardingTable_h__
| 24.903226 | 81 | 0.674352 | [
"model"
] |
e04a46c926687eba9acbde57333f1da8c99000e9 | 25,535 | h | C | TinyEngineWindows/TinyEngine.h | pawel-mazurkiewicz/SimpleHydrologyWindows | 45ad184d5635458d91b8a6357068fe6f159525e5 | [
"MIT"
] | 5 | 2020-10-22T12:20:02.000Z | 2021-09-25T04:36:54.000Z | TinyEngineWindows/TinyEngine.h | pawel-mazurkiewicz/SimpleHydrologyWindows | 45ad184d5635458d91b8a6357068fe6f159525e5 | [
"MIT"
] | null | null | null | TinyEngineWindows/TinyEngine.h | pawel-mazurkiewicz/SimpleHydrologyWindows | 45ad184d5635458d91b8a6357068fe6f159525e5 | [
"MIT"
] | null | null | null | #pragma once
#include <functional>
#include <deque>
using Handle = std::function<void()>;
#include <initializer_list>
using slist = std::initializer_list<std::string>;
//Interface Dependencies (DearImGUI)
#include "include/imgui/imgui.h"
#include "include/imgui/imgui_impl_sdl.h"
#include "include/imgui/imgui_impl_opengl3.h"
//#define IMGUI_IMPL_OPENGL_LOADER_GLEW
//#define GLEW_STATIC
//Drawing Dependencies
#include <GL/glew.h>
#include <SDL.h>
#include <SDL_image.h>
#include <SDL_ttf.h>
#include <SDL_mixer.h>
#include <glm/glm.hpp>
#include "glm/gtc/matrix_transform.hpp"
//File IO
#include <sstream>
#include <iostream>
#include <fstream>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
//Helpers
#include "include/helpers/helper.h"
#include "include/helpers/ease.h"
#include "include/helpers/color.h"
#include "include/helpers/draw.h"
#include "include/helpers/image.h"
#include "include/helpers/timer.h"
//Utility Classes for the Engine
//#include "include/utility/texture.cpp"
//#include "include/utility/shader.cpp"
//#include "include/utility/sprite.cpp"
//#include "include/utility/particle.cpp"
//#include "include/utility/billboard.cpp"
//#include "include/utility/model.cpp"
//#include "include/view.cpp"
//#include "include/event.cpp"
//#include "include/audio.cpp"
/* TINY ENGINE */
class Billboard {
public:
Billboard(int width, int height, bool depthOnly) {
setup();
drawable(width, height, depthOnly);
};
~Billboard() {
cleanup();
}
//Rendering Data
unsigned int WIDTH, HEIGHT;
GLuint vao, vbo[2];
void setup();
void cleanup();
bool depth;
//Vertex and Texture Positions
const GLfloat vert[8] = { -1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0 };
const GLfloat tex[8] = { 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0 };
//Rendering Position
glm::mat4 model = glm::mat4(1.0f); //Model Matrix
void move(glm::vec2 pos, glm::vec2 scale);
//Textures and FBO
GLuint fbo; //We need an FBO to render scene to screen
GLuint texture;
GLuint depthTexture;
void raw(SDL_Surface* s);
bool drawable(int width, int height, bool depthOnly);
void target(); //Billboard as render target
void target(glm::vec3 clear); //Billboard as render target with clear color
void render(); //Render this billboard
};
void Billboard::setup() {
//Setup the VAO
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
//Setup the VBOs
glGenBuffers(2, &vbo[0]);
glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);
glBufferData(GL_ARRAY_BUFFER, 8 * sizeof(GLfloat), &vert[0], GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0);
glBindBuffer(GL_ARRAY_BUFFER, vbo[1]);
glBufferData(GL_ARRAY_BUFFER, 8 * sizeof(GLfloat), &tex[0], GL_STATIC_DRAW);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, 0);
//Generate Textures
glGenTextures(1, &texture);
glGenTextures(1, &depthTexture);
}
void Billboard::cleanup() {
glDeleteTextures(1, &texture);
glDeleteTextures(1, &depthTexture);
glDeleteFramebuffers(1, &fbo);
glDisableVertexAttribArray(vao);
glDeleteBuffers(2, vbo);
glDeleteVertexArrays(1, &vao);
}
void Billboard::raw(SDL_Surface* s) {
glBindTexture(GL_TEXTURE_2D, texture);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, s->w, s->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, s->pixels);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
}
void Billboard::move(glm::vec2 pos, glm::vec2 scale) {
model = glm::translate(glm::mat4(1.0), glm::vec3(2.0*pos.x - 1.0 + scale.x, 2.0*pos.y - 1.0 + scale.y, 0.0));
model = glm::scale(model, glm::vec3(scale.x, scale.y, 1.0));
}
bool Billboard::drawable(int width, int height, bool depthOnly) {
glGenFramebuffers(1, &fbo); //Frame Buffer Object for drawing
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
depth = depthOnly;
WIDTH = width;
HEIGHT = height;
if (!depthOnly) {
glBindTexture(GL_TEXTURE_2D, texture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, WIDTH, HEIGHT, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0);
}
glBindTexture(GL_TEXTURE_2D, depthTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, WIDTH, HEIGHT, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depthTexture, 0);
if (depth) glDrawBuffer(GL_NONE);
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
std::cout << "Failed to construct framebuffer object." << std::endl;
return false;
}
glBindFramebuffer(GL_FRAMEBUFFER, 0);
return true;
}
void Billboard::target() {
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glViewport(0, 0, WIDTH, HEIGHT);
if (depth) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
void Billboard::target(glm::vec3 clear) {
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glViewport(0, 0, WIDTH, HEIGHT);
glClearColor(clear.x, clear.y, clear.z, 1.0f); //Blue
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
void Billboard::render() {
glBindVertexArray(vao);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
}
class Model {
public:
Model() { setup(); };
Model(std::function<void(Model* m)> c) {
setup();
construct(c);
};
~Model() {
glDisableVertexAttribArray(vao);
glDeleteBuffers(3, vbo);
glDeleteBuffers(1, &ibo);
glDeleteVertexArrays(1, &vao);
}
std::vector<GLfloat> positions;
std::vector<GLfloat> normals;
std::vector<GLfloat> colors;
std::vector<GLuint> indices;
GLuint vbo[3], vao, ibo;
glm::mat4 model = glm::mat4(1.0f); //Model Matrix
glm::vec3 pos = glm::vec3(0.0f); //Model Position
void setup();
void update();
void construct(std::function<void(Model* m)> constructor) {
positions.clear(); //Clear all Data
normals.clear();
colors.clear();
indices.clear();
(constructor)(this); //Call user-defined constructor
update(); //Update VAO / VBO / IBO
};
void translate(const glm::vec3 &axis);
void rotate(const glm::vec3 &axis, float angle);
void render(GLenum T);
};
void Model::setup() {
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
glGenBuffers(3, vbo);
glGenBuffers(1, &ibo);
}
void Model::update() {
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo[0]); //Positions
glBufferData(GL_ARRAY_BUFFER, positions.size() * sizeof(GLfloat), &positions[0], GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glBindBuffer(GL_ARRAY_BUFFER, vbo[1]); //Normals
glBufferData(GL_ARRAY_BUFFER, normals.size() * sizeof(GLfloat), &normals[0], GL_STATIC_DRAW);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, 0);
glBindBuffer(GL_ARRAY_BUFFER, vbo[2]); //Colors
glBufferData(GL_ARRAY_BUFFER, colors.size() * sizeof(GLfloat), &colors[0], GL_STATIC_DRAW);
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, 0, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo); //Indices
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(GLuint), &indices[0], GL_STATIC_DRAW);
}
void Model::translate(const glm::vec3 &axis) {
model = glm::translate(model, axis);
pos += axis;
}
void Model::rotate(const glm::vec3 &axis, float angle) {
model = glm::translate(glm::rotate(glm::translate(model, -pos), angle, axis), pos);
}
void Model::render(GLenum T) {
glBindVertexArray(vao);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
glDrawElements(T, indices.size(), GL_UNSIGNED_INT, 0);
}
class Particle {
public:
Particle() { //Construct from an SDL Surface
setup();
};
~Particle() {
cleanup();
}
//Rendering Data
GLuint vao, vbo[2], instance;
void setup();
void update();
void cleanup();
//Vertex and Texture Positions
const GLfloat vert[12] = { -1.0, -1.0, 0.0,
-1.0, 1.0, 0.0,
1.0, -1.0, 0.0,
1.0, 1.0, 0.0 };
const GLfloat tex[8] = { 0.0, 1.0,
0.0, 0.0,
1.0, 1.0,
1.0, 0.0 };
//Rendering Position
std::vector<glm::mat4> models;
void render(); //Render this billboard
};
void Particle::setup() {
//Setup the VAO
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
//Setup the VBOs
glGenBuffers(2, &vbo[0]);
glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);
glBufferData(GL_ARRAY_BUFFER, 12 * sizeof(GLfloat), &vert[0], GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glBindBuffer(GL_ARRAY_BUFFER, vbo[1]);
glBufferData(GL_ARRAY_BUFFER, 8 * sizeof(GLfloat), &tex[0], GL_STATIC_DRAW);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, 0);
//Setup Instance VBO
glGenBuffers(1, &instance);
}
void Particle::update() {
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, instance);
glBufferData(GL_ARRAY_BUFFER, models.size() * sizeof(glm::mat4), &models[0], GL_STATIC_DRAW);
std::size_t vec4Size = sizeof(glm::vec4);
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, 4 * vec4Size, (void*)0);
glEnableVertexAttribArray(3);
glVertexAttribPointer(3, 4, GL_FLOAT, GL_FALSE, 4 * vec4Size, (void*)(1 * vec4Size));
glEnableVertexAttribArray(4);
glVertexAttribPointer(4, 4, GL_FLOAT, GL_FALSE, 4 * vec4Size, (void*)(2 * vec4Size));
glEnableVertexAttribArray(5);
glVertexAttribPointer(5, 4, GL_FLOAT, GL_FALSE, 4 * vec4Size, (void*)(3 * vec4Size));
glVertexAttribDivisor(2, 1);
glVertexAttribDivisor(3, 1);
glVertexAttribDivisor(4, 1);
glVertexAttribDivisor(5, 1);
}
void Particle::cleanup() {
//Delete Textures and VAO
glDisableVertexAttribArray(vao);
glDeleteBuffers(2, vbo);
glDeleteBuffers(1, &instance);
glDeleteVertexArrays(1, &vao);
}
void Particle::render() {
glBindVertexArray(vao);
glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, models.size());
}
class Shader {
public:
Shader(std::string vs, std::string fs, slist _list) {
setup(vs, fs); //Setup the Shader
for (auto &n : _list) //Add all Attributes of Shader
addInput(&n - _list.begin(), n);
link();
};
~Shader() {
glDeleteProgram(shaderProgram);
glDeleteShader(fragmentShader);
glDeleteShader(vertexShader);
}
GLuint shaderProgram; //Shader Program ID
GLuint vertexShader, fragmentShader;
void setup(std::string vs, std::string fs);
void addInput(int pos, std::string attrName);
void cleanup();
int addProgram(std::string fileName, GLenum shaderType); //General Shader Addition
std::string readGLSLFile(std::string fileName, int32_t &size); //Read File
void compile(GLuint shader); //Compile and Add File
void link(); //Link the entire program
void use(); //Use the program
// Uniform Setters
void setBool(std::string name, bool value);
void setInt(std::string name, int value);
void setFloat(std::string name, float value);
void setVec2(std::string name, const glm::vec2 vec);
void setVec3(std::string name, const glm::vec3 vec);
void setVec4(std::string name, const glm::vec4 vec);
void setMat3(std::string name, const glm::mat3 mat);
void setMat4(std::string name, const glm::mat4 mat);
};
void Shader::setup(std::string vs, std::string fs) {
shaderProgram = glCreateProgram(); //Generate Shader
boost::filesystem::path data_dir(boost::filesystem::current_path());
vertexShader = addProgram((data_dir / vs).string(), GL_VERTEX_SHADER);
fragmentShader = addProgram((data_dir / fs).string(), GL_FRAGMENT_SHADER);
}
int Shader::addProgram(std::string fileName, GLenum shaderType) {
//Read Shader Program from Source
char* src; int32_t size;
std::string result = readGLSLFile(fileName, size);
src = const_cast<char*>(result.c_str());
//Create and Compile Shader
int shaderID = glCreateShader(shaderType);
glShaderSource(shaderID, 1, &src, &size);
compile(shaderID);
return shaderID;
}
void Shader::addInput(int pos, std::string attrName) {
glBindAttribLocation(shaderProgram, pos, attrName.c_str());
}
void Shader::compile(GLuint shader) {
glCompileShader(shader);
int success, maxLength; ///Error Handling
glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
if (success) {
glAttachShader(shaderProgram, shader);
return;
}
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &maxLength);
char* shaderInfoLog = new char[maxLength];
glGetShaderInfoLog(shader, maxLength, &maxLength, shaderInfoLog);
std::cout << "Linker error message : " << shaderInfoLog << std::endl;
delete shaderInfoLog;
}
void Shader::link() {
glLinkProgram(shaderProgram);
int success, maxLength; //Error Handling
glGetProgramiv(shaderProgram, GL_LINK_STATUS, (int *)&success);
if (success) return; //Yay
glGetProgramiv(shaderProgram, GL_INFO_LOG_LENGTH, &maxLength);
char* shaderProgramInfoLog = new char[maxLength];
glGetProgramInfoLog(shaderProgram, maxLength, &maxLength, shaderProgramInfoLog);
std::cout << "Linker error message: " << shaderProgramInfoLog << std::endl;
delete shaderProgramInfoLog;
}
void Shader::use() {
glUseProgram(shaderProgram);
}
std::string Shader::readGLSLFile(std::string file, int32_t &size) {
std::ifstream t;
std::string fileContent;
t.open(file); //Read GLSL File Contents
if (t.is_open()) {
std::stringstream buffer;
buffer << t.rdbuf();
fileContent = buffer.str();
}
else std::cout << "File opening failed" << std::endl;
t.close();
size = fileContent.length(); //Set the Size
return fileContent;
}
/* Uniform Setters */
void Shader::setBool(std::string name, bool value) {
glUniform1i(glGetUniformLocation(shaderProgram, name.c_str()), value);
}
void Shader::setInt(std::string name, int value) {
glUniform1i(glGetUniformLocation(shaderProgram, name.c_str()), value);
}
void Shader::setFloat(std::string name, float value) {
glUniform1f(glGetUniformLocation(shaderProgram, name.c_str()), value);
}
void Shader::setVec2(std::string name, const glm::vec2 vec) {
glUniform2fv(glGetUniformLocation(shaderProgram, name.c_str()), 1, &vec[0]);
}
void Shader::setVec3(std::string name, const glm::vec3 vec) {
glUniform3fv(glGetUniformLocation(shaderProgram, name.c_str()), 1, &vec[0]);
}
void Shader::setVec4(std::string name, const glm::vec4 vec) {
glUniform4fv(glGetUniformLocation(shaderProgram, name.c_str()), 1, &vec[0]);
}
void Shader::setMat3(std::string name, const glm::mat3 mat) {
glUniformMatrix3fv(glGetUniformLocation(shaderProgram, name.c_str()), 1, GL_FALSE, &mat[0][0]);
}
void Shader::setMat4(std::string name, const glm::mat4 mat) {
glUniformMatrix4fv(glGetUniformLocation(shaderProgram, name.c_str()), 1, GL_FALSE, &mat[0][0]);
}
class Sprite {
public:
Sprite(SDL_Surface* s) { //Construct from an SDL Surface
setup();
update(s);
};
Sprite() { //Only construct (empty texture)
setup();
};
~Sprite() {
cleanup();
}
//Rendering Data
GLuint vao, vbo[2];
void setup();
void cleanup();
//Vertex and Texture Positions
const GLfloat vert[12] = { -1.0, -1.0, 0.0,
-1.0, 1.0, 0.0,
1.0, -1.0, 0.0,
1.0, 1.0, 0.0 };
const GLfloat tex[8] = { 0.0, 1.0,
0.0, 0.0,
1.0, 1.0,
1.0, 0.0 };
//Rendering Position
glm::vec3 pos = glm::vec3(0.0);
glm::mat4 model = glm::mat4(1.0f); //Model Matrix
void move(glm::vec2 pos, glm::vec2 scale);
void update(SDL_Surface* TextureImage);
void render(); //Render this billboard
};
void Sprite::setup() {
//Setup the VAO
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
//Setup the VBOs
glGenBuffers(2, &vbo[0]);
glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);
glBufferData(GL_ARRAY_BUFFER, 12 * sizeof(GLfloat), &vert[0], GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glBindBuffer(GL_ARRAY_BUFFER, vbo[1]);
glBufferData(GL_ARRAY_BUFFER, 8 * sizeof(GLfloat), &tex[0], GL_STATIC_DRAW);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, 0);
}
void Sprite::cleanup() {
//Delete Textures and VAO
glDisableVertexAttribArray(vao);
glDeleteBuffers(2, vbo);
glDeleteVertexArrays(1, &vao);
}
void Sprite::render() {
glBindVertexArray(vao);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
}
class Texture {
public:
Texture(SDL_Surface* s) { //Construct from an SDL Surface
setup();
raw(s);
};
Texture() { //Only construct (empty texture)
setup();
};
~Texture() {
cleanup();
}
//Rendering Data
GLuint texture;
void setup();
void cleanup();
void raw(SDL_Surface* TextureImage);
};
void Texture::setup() {
glGenTextures(1, &texture);
}
void Texture::cleanup() {
glDeleteTextures(1, &texture);
}
void Texture::raw(SDL_Surface* s) {
glBindTexture(GL_TEXTURE_2D, texture);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, s->w, s->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, s->pixels);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
}
class View {
public:
bool init(std::string windowName, int width, int height);
void cleanup();
unsigned int WIDTH, HEIGHT;
SDL_Window* gWindow; //Window Pointer
SDL_GLContext gContext; //Render Context
ImGuiIO io;
Handle interface; //User defined Interface
bool showInterface = false;
void drawInterface();
Handle pipeline; //User defined Pipeline
void render();
void target(glm::vec3 clearcolor); //Target main window for drawing
//Flags
bool fullscreen = false;
bool vsync = true;
};
bool View::init(std::string _name, int _width, int _height) {
WIDTH = _width;
HEIGHT = _height;
//Initialize the Window and Context
gWindow = SDL_CreateWindow(_name.c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIDTH, HEIGHT, SDL_WINDOW_OPENGL);
if (gWindow == NULL) {
printf("Window could not be created! SDL_Error: %s\n", SDL_GetError());
return false;
}
SDL_SetWindowResizable(gWindow, SDL_TRUE);
gContext = SDL_GL_CreateContext(gWindow);
//Initialize OPENGL Stuff
SDL_GL_SetSwapInterval(vsync);
glewExperimental = GL_TRUE;
glewInit();
//Setup the Guy
IMGUI_CHECKVERSION();
ImGui::CreateContext();
io = ImGui::GetIO(); (void)io;
ImGui_ImplSDL2_InitForOpenGL(gWindow, gContext);
ImGui_ImplOpenGL3_Init("#version 130");
ImGui::StyleColorsCustom();
//Configure Global OpenGL State
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_CULL_FACE);
glFrontFace(GL_CW);
glLineWidth(1.0f);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
return true;
}
void View::cleanup() {
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplSDL2_Shutdown();
ImGui::DestroyContext();
SDL_GL_DeleteContext(gContext);
SDL_DestroyWindow(gWindow);
}
void View::render() {
//User-defined rendering pipeline
(pipeline)();
if (showInterface)
drawInterface();
SDL_GL_SwapWindow(gWindow); //Update Window
}
void View::drawInterface() {
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplSDL2_NewFrame(gWindow);
ImGui::NewFrame();
(interface)(); //Draw user-defined interface
//ImGui::ShowDemoWindow();
ImGui::Render();
glViewport(0, 0, (int)io.DisplaySize.x, (int)io.DisplaySize.y);
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
}
void View::target(glm::vec3 clearcolor) {
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glViewport(0, 0, WIDTH, HEIGHT);
glClearColor(clearcolor.x, clearcolor.y, clearcolor.z, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
class Event {
private:
SDL_Event in;
public:
bool quit = false;
void input(); //Take inputs and add them to stack
void handle(View &view); //General Event Handler
Handle handler; //User defined event Handler
bool fullscreenToggle = false;
std::deque<SDL_Event> keys;
bool keyEventTrigger = false;
std::deque<SDL_Event> scroll; //Scrolling Motion Inputs
SDL_Event windowEvent; //Window Resizing Event
bool windowEventTrigger = false;
SDL_Event mouseEvent; //Mouse Click Event
bool mouseEventTrigger = false;
SDL_Event moveEvent; //Mouse Movement Events
bool moveEventTrigger = false;
};
void Event::input() {
if (SDL_PollEvent(&in) == 0) return;
if (in.type == SDL_QUIT) quit = true;
ImGui_ImplSDL2_ProcessEvent(&in);
if (in.type == SDL_KEYUP) {
if (in.key.keysym.sym == SDLK_F11) fullscreenToggle = true;
else keys.push_front(in);
return;
}
if (in.type == SDL_MOUSEWHEEL) {
scroll.push_front(in);
return;
}
if (in.type == SDL_MOUSEBUTTONDOWN ||
in.type == SDL_MOUSEBUTTONUP) {
mouseEvent = in;
mouseEventTrigger = true;
return;
}
if (in.type == SDL_WINDOWEVENT) {
windowEvent = in;
windowEventTrigger = true;
return;
}
}
void Event::handle(View &view)
{
(handler)(); //Call user-defined handler first
if (fullscreenToggle) {
view.fullscreen = !view.fullscreen; //Toggle Fullscreen!
if (!view.fullscreen) SDL_SetWindowFullscreen(view.gWindow, SDL_WINDOW_FULLSCREEN_DESKTOP);
else SDL_SetWindowFullscreen(view.gWindow, 0);
fullscreenToggle = false;
}
if (windowEventTrigger && windowEvent.window.event == SDL_WINDOWEVENT_RESIZED) {
view.WIDTH = windowEvent.window.data1;
view.HEIGHT = windowEvent.window.data2;
windowEventTrigger = false;
}
if (!keys.empty() && keys.back().key.keysym.sym == SDLK_ESCAPE) {
view.showInterface = !view.showInterface;
}
if (!scroll.empty()) scroll.pop_back();
if (!keys.empty()) keys.pop_back();
}
/*
WORK IN PROGRESS
*/
class Audio {
public:
//Storage for unprocessed soundbytes
// std::vector<SoundByte> unprocessed;
//Vector containing the guy
Mix_Chunk *med = NULL;
Mix_Chunk *hit = NULL;
bool init();
bool cleanup();
void process();
};
bool Audio::init() {
//Intialize Interface
if (Mix_OpenAudio(22050, MIX_DEFAULT_FORMAT, 2, 4096) == -1) return false;
/*
//Load the sound effects
med = Mix_LoadWAV( "resource/audio/acoustic.wav" );
hit = Mix_LoadWAV( "resource/audio/medium.wav" );
//If there was a problem loading the sound effects
if( med == NULL ) return false;
if( hit == NULL ) return false;
*/
//If everything loaded fine
return true;
}
bool Audio::cleanup() {
//Free the Chunks
Mix_FreeChunk(med);
Mix_FreeChunk(hit);
//Close the Audio Interface
Mix_CloseAudio();
return true;
}
void Audio::process() {
/*
In the future, we can also save the position where the sound-effect was emitted
-> to make sure that volume effects play a role.
I need to be able to play sounds based on queues
with a specific volume
and maybe a bunch of other possible effects...
*/
/*
while(!unprocessed.empty()){
if(unprocessed.back() != SOUND_NONE) Mix_PlayChannel( -1, hit, 0 );
//Play the corresponding sound-effect and remove it from the unprocessed list.
unprocessed.pop_back();
}
*/
}
namespace Tiny {
//Main Engine Elements
static View view; //Window and Interface
static Event event; //Event Handler
static Audio audio; //Audio Processor
bool init(std::string windowName, int width, int height) {
//Initialize SDL Core
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
printf("SDL could not initialize! Error: %s\n", SDL_GetError());
return false;
}
//Initialize SDL_Image
if (!(IMG_Init(IMG_INIT_PNG) & IMG_INIT_PNG)) {
printf("SDL_Image could not initialize! Error: %s\n", IMG_GetError());
return false;
}
//Initialize SDL_TTF
TTF_Init();
//Initialize the View
if (!view.init(windowName, width, height)) {
std::cout << "Failed to launch visual interface." << std::endl;
return false;
}
if (!audio.init()) {
std::cout << "Failed to launch audio interface." << std::endl;
return false;
}
}
void quit() {
view.cleanup();
audio.cleanup();
TTF_Quit();
SDL_Quit();
};
template<typename F, typename... Args>
void loop(F function, Args&&... args) {
while (!event.quit) {
event.input(); //Handle Input
event.handle(view);
audio.process(); //Audio Processor
function(args...); //User-defined Game Loop
view.render(); //Render View
}
};
//End of Namespace
}; | 27.486545 | 128 | 0.683376 | [
"render",
"object",
"vector",
"model"
] |
e0526cf8f3f3d190449ce00c2cf8558a8b1e1ce8 | 701 | h | C | hmwk/2/monte_carlo.h | ForrestHurley/compPhys | 34c2d93b77858150a1c099deff812d961ab6378d | [
"MIT"
] | null | null | null | hmwk/2/monte_carlo.h | ForrestHurley/compPhys | 34c2d93b77858150a1c099deff812d961ab6378d | [
"MIT"
] | null | null | null | hmwk/2/monte_carlo.h | ForrestHurley/compPhys | 34c2d93b77858150a1c099deff812d961ab6378d | [
"MIT"
] | null | null | null | #ifndef MONTE_CARLO_H
#define MONTE_CARLO_H
#include <vector>
#include "monte_carlo_object.h"
class monte_carlo
{
private:
std::vector<double> hamiltonian_list;
mc_object* working_model;
double beta;
static constexpr double k = 4.3806e-23;
public:
monte_carlo(double temperature = 10.);
monte_carlo(mc_object* model, double temperature = 10.);
void set_mc_object(mc_object* model);
void set_beta(double new_beta);
double get_beta();
void set_temperature(double new_temperature);
double get_temperature();
std::vector<double> get_hamiltonian_list();
void run_iterations(int iterations, int burn_in = 0, bool verbose = false);
};
#endif
| 20.617647 | 79 | 0.717546 | [
"vector",
"model"
] |
e05b554e77ffb89c77fabad25ea9353880f2e532 | 13,736 | h | C | ash/app_list/views/paged_apps_grid_view.h | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | ash/app_list/views/paged_apps_grid_view.h | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | ash/app_list/views/paged_apps_grid_view.h | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2021 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 ASH_APP_LIST_VIEWS_PAGED_APPS_GRID_VIEW_H_
#define ASH_APP_LIST_VIEWS_PAGED_APPS_GRID_VIEW_H_
#include <memory>
#include <vector>
#include "ash/app_list/app_list_metrics.h"
#include "ash/app_list/views/apps_grid_view.h"
#include "ash/ash_export.h"
#include "ash/public/cpp/pagination/pagination_model.h"
#include "ash/public/cpp/pagination/pagination_model_observer.h"
#include "ash/public/cpp/presentation_time_recorder.h"
#include "base/memory/ref_counted.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/compositor/layer_animation_observer.h"
#include "ui/compositor/throughput_tracker.h"
#include "ui/events/types/event_type.h"
#include "ui/gfx/geometry/point_f.h"
namespace gfx {
class Vector2d;
} // namespace gfx
namespace ui {
class Layer;
} // namespace ui
namespace ash {
class ContentsView;
class PaginationController;
// An apps grid that shows the apps on a series of fixed-size pages.
// Used for the peeking/fullscreen launcher, home launcher and folders.
// Created by and is a child of AppsContainerView. Observes layer animations
// for the transition into and out of the "cardified" state.
class ASH_EXPORT PagedAppsGridView : public AppsGridView,
public PaginationModelObserver,
public ui::ImplicitAnimationObserver {
public:
class ContainerDelegate {
public:
virtual ~ContainerDelegate() = default;
// Returns true if |point| lies within the bounds of this grid view plus a
// buffer area surrounding it that can trigger page flip.
virtual bool IsPointWithinPageFlipBuffer(const gfx::Point& point) const = 0;
// Returns whether |point| is in the bottom drag buffer, and not over the
// shelf.
virtual bool IsPointWithinBottomDragBuffer(
const gfx::Point& point,
int page_flip_zone_size) const = 0;
};
PagedAppsGridView(ContentsView* contents_view,
AppListA11yAnnouncer* a11y_announcer,
AppsGridViewFolderDelegate* folder_delegate,
AppListFolderController* folder_controller,
ContainerDelegate* container_delegate);
PagedAppsGridView(const PagedAppsGridView&) = delete;
PagedAppsGridView& operator=(const PagedAppsGridView&) = delete;
~PagedAppsGridView() override;
// Called when tablet mode starts and ends.
void OnTabletModeChanged(bool started);
// Updates the opacity of all the items in the grid when the grid itself is
// being dragged. The app icons fade out as the launcher slides off the bottom
// of the screen.
// `apps_opacity_change_start` and `apps_opacity_change_end` define the range
// of height of centerline above screen bottom in which apps should change
// opacity (from 0 to 1).
void UpdateOpacity(bool restore_opacity,
float apps_opacity_change_start,
float apps_opacity_change_end);
// Sets the number of max rows and columns in grid pages. Special-cases the
// first page, which may allow smaller number of rows in certain cases (to
// make room for other UI elements like continue section).
// For non-folder item grid, this generally describes the number of slots
// shown in the page. For folders, the number of displayed slots will also
// depend on number of items in the grid (e.g. folder with 4 items will have
// 2x2 grid).
void SetMaxColumnsAndRows(int max_columns,
int max_rows_on_first_page,
int max_rows);
// ui::EventHandler:
void OnGestureEvent(ui::GestureEvent* event) override;
void OnMouseEvent(ui::MouseEvent* event) override;
// views::View:
void Layout() override;
// AppsGridView:
gfx::Size GetTileViewSize() const override;
gfx::Insets GetTilePadding(int page) const override;
gfx::Size GetTileGridSize() const override;
int GetPaddingBetweenPages() const override;
int GetTotalPages() const override;
int GetSelectedPage() const override;
bool IsScrollAxisVertical() const override;
void UpdateBorder() override;
void MaybeStartCardifiedView() override;
void MaybeEndCardifiedView() override;
void MaybeStartPageFlip() override;
void MaybeStopPageFlip() override;
bool MaybeAutoScroll() override;
void StopAutoScroll() override {}
void HandleScrollFromParentView(const gfx::Vector2d& offset,
ui::EventType type) override;
void SetFocusAfterEndDrag() override;
void RecordAppMovingTypeMetrics(AppListAppMovingType type) override;
int GetMaxRowsInPage(int page) const override;
gfx::Vector2d GetGridCenteringOffset(int page) const override;
void UpdatePaging() override;
void RecordPageMetrics() override;
const gfx::Vector2d CalculateTransitionOffset(
int page_of_view) const override;
void EnsureViewVisible(const GridIndex& index) override;
// PaginationModelObserver:
void TotalPagesChanged(int previous_page_count, int new_page_count) override;
void SelectedPageChanged(int old_selected, int new_selected) override;
void TransitionStarting() override;
void TransitionStarted() override;
void TransitionChanged() override;
void TransitionEnded() override;
void ScrollStarted() override;
void ScrollEnded() override;
// ui::ImplicitAnimationObserver:
void OnImplicitAnimationsCompleted() override;
bool FirePageFlipTimerForTest();
bool cardified_state_for_testing() const { return cardified_state_; }
int BackgroundCardCountForTesting() const { return background_cards_.size(); }
// Returns bounds within the apps grid view for the background card layer
// with provided card index.
gfx::Rect GetBackgroundCardBoundsForTesting(size_t card_index);
void set_page_flip_delay_for_testing(base::TimeDelta page_flip_delay) {
page_flip_delay_ = page_flip_delay;
}
// Gets the PaginationModel used for the grid view.
PaginationModel* pagination_model() { return &pagination_model_; }
// Sets `first_page_offset_` and `shown_under_recent_apps_`, which are used to
// calculate the first apps grid page layout (number of rows and the padding
// between them).
// `offset` is reserved space for continue section in the apps
// container (which is shown above the grid on the first app list page with
// productivity launcher).
// `shown_under_recent_apps` indicates whether the
// continue section contains list of recent apps. If this is the case, the
// apps grid will add additional padding above the apps grid (i.e. treat the
// recent apps row as additional row of apps).
// Returns whether the first page configuration changed.
bool ConfigureFirstPagePadding(int offset, bool shown_under_recent_apps);
// Calculates the maximum number of rows on the first page. Relies on tile
// size, `first_page_offset_`, `shown_under_recent_apps_` and the bounds of
// the apps grid.
int CalculateFirstPageMaxRows(int available_height, int preferred_rows);
// Calculates the maximum number of rows. Relies on tile size and the bounds
// of the apps grid.
int CalculateMaxRows(int available_height, int preferred_rows);
int GetFirstPageRowsForTesting() const { return max_rows_on_first_page_; }
int GetRowsForTesting() const { return max_rows_; }
private:
friend class test::AppsGridViewTest;
class FadeoutLayerDelegate;
// Gets the leading padding for app list item grid on the first app list page.
// Includes the space reserved for the continue seaction of the app list UI,
// and additional vertical tile padding before the first row of apps when
// needed (i.e. if the grid is shown under a row of recent apps).
int GetTotalTopPaddingOnFirstPage() const;
// Returns the size reserved for a single apps grid page. May not match the
// tile grid size when the first page selected, as the first page may have
// reduced number of tiles.
gfx::Size GetPageSize() const;
// Gets the tile grid size on the provided apps grid page.
gfx::Size GetTileGridSizeForPage(int page) const;
// Indicates whether the drag event (from the gesture or mouse) should be
// handled by PagedAppsGridView.
bool ShouldHandleDragEvent(const ui::LocatedEvent& event);
// Creates a layer mask for gradient alpha when the feature is enabled. The
// gradient appears at the top and bottom of the apps grid to create a
// "fade out" effect when dragging the whole page.
void MaybeCreateGradientMask();
// Returns true if the page is the right target to flip to.
bool IsValidPageFlipTarget(int page) const;
// Obtains the target page to flip for |drag_point|.
int GetPageFlipTargetForDrag(const gfx::Point& drag_point);
// Starts the page flip timer if |drag_point| is in left/right side page flip
// zone or is over page switcher.
void MaybeStartPageFlipTimer(const gfx::Point& drag_point);
// Invoked when |page_flip_timer_| fires.
void OnPageFlipTimer();
// Stops the timer that triggers a page flip during a drag.
void StopPageFlipTimer();
// Helper functions to start the Apps Grid Cardified state.
// The cardified state scales down apps and is shown when the user drags an
// app in the AppList.
void StartAppsGridCardifiedView();
// Ends the Apps Grid Cardified state and sets it to normal.
void EndAppsGridCardifiedView();
// Animates individual elements of the apps grid to and from cardified state.
void AnimateCardifiedState();
// Call OnBoundsAnimatorDone when all layer animations finish.
void MaybeCallOnBoundsAnimatorDone();
// Translates the items container view to center the current page in the apps
// grid.
void RecenterItemsContainer();
// Calculates the background bounds for the grid depending on the value of
// |cardified_state_|
gfx::Rect BackgroundCardBounds(int new_page_index);
// Appends a background card to the back of |background_cards_|.
void AppendBackgroundCard();
// Removes the background card at the end of |background_cards_|.
void RemoveBackgroundCard();
// Masks the apps grid container to background cards bounds.
void MaskContainerToBackgroundBounds();
// Removes all background cards from |background_cards_|.
void RemoveAllBackgroundCards();
// Updates the highlighted background card. Used only for cardified state.
void SetHighlightedBackgroundCard(int new_highlighted_page);
// Update the padding of tile view based on the contents bounds.
void UpdateTilePadding();
// Created by AppListMainView, owned by views hierarchy.
ContentsView* const contents_view_;
// Used to get information about whether a point is within the page flip drag
// buffer area around this view.
ContainerDelegate* const container_delegate_;
// Depends on |pagination_model_|.
std::unique_ptr<PaginationController> pagination_controller_;
// Timer to auto flip page when dragging an item near the left/right edges.
base::OneShotTimer page_flip_timer_;
// Target page to switch to when |page_flip_timer_| fires.
int page_flip_target_ = -1;
// Delay for when |page_flip_timer_| should fire after user drags an item near
// the edge.
base::TimeDelta page_flip_delay_;
// Whether the grid is in mouse drag. Used for between-item drags that move
// the entire grid, not for app icon drags.
bool is_in_mouse_drag_ = false;
// The initial mouse drag location in root window coordinate. Updates when the
// drag on PagedAppsGridView starts. Used for between-item drags that move the
// entire grid, not for app icon drags.
gfx::PointF mouse_drag_start_point_;
// The last mouse drag location in root window coordinate. Used for
// between-item drags that move the entire grid, not for app icon drags.
gfx::PointF last_mouse_drag_point_;
// Implements a "fade out" gradient at the top and bottom of the grid. Used
// during page flip transitions and for cardified drags.
std::unique_ptr<FadeoutLayerDelegate> fadeout_layer_delegate_;
// Records smoothness of pagination animation.
absl::optional<ui::ThroughputTracker> pagination_metrics_tracker_;
// Records the presentation time for apps grid dragging.
std::unique_ptr<PresentationTimeRecorder> presentation_time_recorder_;
// The highlighted page during cardified state.
int highlighted_page_ = -1;
// Layer array for apps grid background cards. Used to display the background
// card during cardified state.
std::vector<std::unique_ptr<ui::Layer>> background_cards_;
// Whether the feature ProductivityLauncher is enabled.
const bool is_productivity_launcher_enabled_;
// Maximum number of rows on the first grid page.
int max_rows_on_first_page_ = 0;
// Maximum number of rows allowed in apps grid pages.
int max_rows_ = 0;
PaginationModel pagination_model_{this};
// The amount that tiles need to be offset on the y-axis to avoid overlap
// with the recent apps and continue section.
int first_page_offset_ = 0;
// Whether the apps grid is shown underneath recent apps container. If this is
// the case, layout will add additional vertical tile padding before the first
// apps grid row on the first page.
bool shown_under_recent_apps_ = false;
// Vertical tile spacing between the tile views on the first page.
int first_page_vertical_tile_padding_ = 0;
// Cardified animation observers.
std::vector<std::unique_ptr<ui::ImplicitAnimationObserver>>
animation_observers_;
base::WeakPtrFactory<PagedAppsGridView> weak_ptr_factory_{this};
};
} // namespace ash
#endif // ASH_APP_LIST_VIEWS_PAGED_APPS_GRID_VIEW_H_
| 41.002985 | 80 | 0.750946 | [
"geometry",
"vector"
] |
e061f465cd5b9878a582516d052984edfe03b4a4 | 19,227 | h | C | keistd.h | idinev/pub_toys | c5518c1b974ab0d921d16d806cc3924f03a66989 | [
"Unlicense"
] | null | null | null | keistd.h | idinev/pub_toys | c5518c1b974ab0d921d16d806cc3924f03a66989 | [
"Unlicense"
] | null | null | null | keistd.h | idinev/pub_toys | c5518c1b974ab0d921d16d806cc3924f03a66989 | [
"Unlicense"
] | null | null | null | //#define KEISTD_IMPL
#ifndef _KEISTD_H_
#define _KEISTD_H_
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <memory.h>
typedef unsigned int uint;
typedef unsigned long long ui64;
typedef signed long long si64;
typedef unsigned short ushort;
typedef unsigned char uchar;
typedef signed char schar;
#define null 0
#define loopi(count) for(int i=0;i<count;i++)
#define loopui(count) for(uint i=0;i<count;i++)
#define loop(var, count) for(int var=0;var<count; var++)
#define arraysize(array) ((int)(sizeof(array)/sizeof(array[0])))
#define foreach_pvec(var, pvector) for(auto EDXPTR = (pvector).items; auto var = *EDXPTR++; )
#define likely_if(cond) if(__builtin_expect(!!(cond), 1))
#define unlikely_if(cond) if(__builtin_expect(!!(cond), 0))
#define unlikely_while(cond) while(__builtin_expect(!!(cond), 0))
#define noinline __attribute__((noinline))
#define restrict __restrict__
#define UnusedArg(arg) ((void)(arg))
#define UnusedArgs2(arg1,arg2) ((void)(arg1));((void)(arg2))
#define UnusedArgs3(arg1,arg2,arg3) ((void)(arg1));((void)(arg2));((void)(arg3))
#define UnusedArgs4(arg1,arg2,arg3,arg4) ((void)(arg1));((void)(arg2));((void)(arg3));((void)(arg4))
#define not_implemented assert(0)
#define ArrSize(arr) (int(sizeof(arr)/sizeof(arr[0])))
#define Bit32Siz(num) (((num)+31)/32)
#define IsBit32Set(name, idx) (name[(idx)>>5] & (1 << ((idx)&31)))
#define Bit32SetTo1(name, idx) name[(idx)>>5] |= (1 << ((idx) & 31))
#define Bit32ClearTo0(name, idx) name[(idx)>>5] &= ~(1 << ((idx) & 31))
// provides a valid 'curBitIdx', with values [0;numDwords*32-1]
#define Bit32IterateValid(bitField, numDwords) for(int _bitWordIdx=0;_bitWordIdx<(numDwords);_bitWordIdx++)\
if(uint _bitWordVal = (uint) (bitField[_bitWordIdx]))\
for(int curBitIdx = (_bitWordIdx<<5); _bitWordVal; _bitWordVal >>= 1, curBitIdx++)\
if(_bitWordVal & 1)
#define print(x) DebugPrint(#x,x)
#define prints(x) DebugPrint(x)
#define printID(x) DebugPrintID(#x,x)
#define printh(x) DebugPrintHex(#x,(int)x)
#define printi(x) DebugPrint(#x,(int)x)
#define PrintLine DebugPrintLine()
#define printOnce(x) {static bool yep=false; if(!yep){yep=true;print(x);}}
#define printArray(x,asize) {DebugPrint(#x,"{"); for(int _iii=0;_iii<asize;_iii++){trace(" [%d]",_iii);DebugPrint(" ",x[_iii]);}DebugPrint("}");}
void DebugPrint(const char* x);
void DebugPrint(const char* name, int x);
void DebugPrint(const char* name, double x);
void DebugPrint(const char* name, const char* x);
void DebugPrintHex(const char* name, int x);
void _onUAssertFail();
#define BreakpointInt3 asm("int3")
#define AUTOCALL_ON_START(func) static BootupCaller _autocall##func(func)
#ifdef assert
#warning "Assert was already defined"
#else
#ifndef NDEBUG
#define assert(cond) if(!(cond)) _onUAssertFail()
#else
#define assert(cond)
#endif
#endif
#define CAN_ERR __attribute__ ((warn_unused_result))
#define memzero(obj) memset(&(obj), 0, sizeof(obj))
void* memclone(const void* ptr,int size);
char* uffetch(const char* fname, int* len=null, int padEnd=1, int padStart=0);
bool ufdump(const char* fname, const void* data, int len);
bool ufopenRead(const char* fname);
void ufcloseRead();
int ufread4();
short ufread2();
char ufread1();
float ufreadF();
bool ufread(void* data, int len);
void ufreadSkip(int offs);
char* ufreadStr();
void* ufreadAlloc(int len);
bool ufopenWrite(const char* fname);
void ufcloseWrite();
bool ufwrite4(int x);
bool ufwrite2(short x);
bool ufwrite1(char x);
bool ufwriteF(float x);
bool ufwrite(const void* data, int len);
bool ufwriteStr(const char* str);
char* strclone(const char* data);
void itoaComma(char* str, int x);
char* strfirst(char* str, char c);
char* strfirst(char* str, char c1, char c2);
char* strlast(char* str, char c);
char* strlast(char* str, char c1, char c2);
void strSkipWhitespace(char** str);
int strRemoveChars(char* data,char c); // returns resulting strlen()
#define BenchEnd(name) { static int bindex=0; _BenchEndFunc(name, bindex); }
void BenchStart();
uint _BenchEndFunc(const char* name, int& index);
void BenchPrint();
void SSE_DenormalsAreZero_FlushToZero();
//================= misc utils ======================================
// Return -1 if not found, otherwise [0;numDwords*32-1]
inline int Bit32FindFirstZero(const int* bitField, int numDwords){
for(int idxDword=0; idxDword < numDwords; idxDword++){
int curDword = bitField[idxDword];
if(curDword == -1)continue;
for(int i=0;;i++,curDword >>= 1){
if(curDword & 1) continue;
return (idxDword<<5) | i;
}
}
return -1; // not found
}
//=================== math utils =================================
union UI6432{ // view ui64 as uints
ui64 whole;
uint halfes[2];
};
union F2I{ // view floats as ints
int i;
uint u;
float f;
};
struct IPOINT{
int x,y;
};
struct IRECT{
int x,y,x2,y2;
};
struct FPOINT{
float x,y;
};
inline IPOINT operator+(const IPOINT& a,const IPOINT& b){ IPOINT c; c.x=a.x+b.x; c.y=a.y+b.y; return c;}
inline IPOINT operator-(const IPOINT& a,const IPOINT& b){ IPOINT c; c.x=a.x-b.x; c.y=a.y-b.y; return c;}
inline int fast_abs(int x){
int sign = (x>>31);
return (x^sign) - sign;
}
inline int fast_min(int a, int b){
int c = a-b;
return b + (c & (c>>31));
}
inline int fast_max(int a, int b){
int c = a-b;
return a - (c & (c>>31));
}
inline int fast_negsign(int x){ // (x>=0 ? 0 : -1)
return x>>31;
}
inline int fast_possign(int x){ // (x>=0 ? +1 : 0)
return x>>31;
}
inline int fast_signsign(int x){ // (x>=0 ? +1 : -1)
return (x>>31) | 1;
}
inline int fast_signdir(int x){ // x>0 ? +1 : (x<0 ? -1 : 0)
return (x>>31) - (-x>>31);
}
inline int fast_clamp(int x, int xmin, int xmax){ // clamps to [xmin,xmax]
int c = x;
unlikely_if(x > xmax) c=xmax;
else unlikely_if(x < xmin)c=xmin;
return c;
}
inline int fast_clamp(int x, int xmax){ // clamps to [0; xmax]. Assumes xmax >= 0
int c = x;
unlikely_if(x > xmax) c=xmax;
else unlikely_if(x < 0)c=0;
return c;
}
inline float mix(float start, float end, float t){ // lerp. t=[0.0;1.0]
return start + t*(end-start);
}
inline float saturate(float x){ // clamp x between [0.0;1.0]
F2I d; d.f = x;
unlikely_if(d.i > 0x3F800000) d.i = 0x3F800000;
else unlikely_if(d.i < 0 ) d.i = 0;
return d.f;
}
inline float smoothstep(float t){ // t = [0;1]
return t * t * (3.0f - 2.0f * t);
}
struct HStr{
const char* str;
int len;
int hash;
bool equ(const char* var) const{
likely_if(strlen(var)!=(size_t)len) return false;
if(strncmp(str,var,len)) return false;
return true;
}
bool equ(const char* var, int vlen) const{
likely_if(vlen!=len) return false;
if(strncmp(str,var,len)) return false;
return true;
}
bool equ(const HStr* var) const{
likely_if(var->hash != hash) return false;
if(var->len != len) return false;
if(strncmp(str,var->str,len)) return false;
return true;
}
bool equ(const HStr& var) const{
likely_if(var.hash != hash) return false;
if(var.len != len) return false;
if(strncmp(str,var.str,len)) return false;
return true;
}
void calcHash(){
int h = 64613467;
for(int i=0;i<len;i++) h = h * (15612357 + str[i]) + 178;
hash = h;
}
bool hasChar(char c) const {
for(int i=0;i<len;i++)
unlikely_if(str[i]==c)return true;
return false;
}
int toInt() const{
return strtol(str,0,0);
}
const char* toStr(char* dest, int destSize) const;
char* toStr() const;
void initWith(const char* someStr){
str = someStr;
len = strlen(someStr);
calcHash();
}
inline void initZero(){
str = null;
len = 0;
hash = 0;
}
static HStr make(const char* someStr){
HStr s; s.initWith(someStr);
return s;
}
static HStr getTok(const char** pstr, bool skipNewline=false, int* pkind=0);
};
//================================ fast vector templates =======================================================
template<typename T>
struct ARR{
int num;
T* items;
ARR(){num=0;items=null;}
~ARR(){free(items);}
void resize(int nsize){
num = nsize; items = (T*)realloc(items,num*sizeof(T));
}
void append(const T& val){
resize(num+1);
items[num-1] = val;
}
T* steal(){
T* res = items; num=0; items=null; return res;
}
void deleteAll(){
loopi(num) delete[] items[i];
resize(0);
}
};
template<typename T>
struct PVEC{
T** items;
int num;
PVEC(){
num=0; items=(T**)malloc(sizeof(void*)); items[0]=null;
}
~PVEC(){free(items);}
void add(T* data){
if((num & (num-1))){
items[num++] = data;
items[num]= null;
}else{
int nsize = num ? num*2 : 1;
items = (T**) realloc(items, (nsize+1)*sizeof(void*));
items[num++] = data;
items[num]= null;
}
}
void remove(int idx){
assert(num);
num--;
for(int i=idx;i<num;i++)items[i] = items[i+1];
items[num]=null;
unlikely_if((num & (num-1))==0){
items = (T**) realloc(items, (num+1)*sizeof(void*));
}
}
void fastRemove(int idx){
assert(idx >= 0 && idx < num);
num--;
items[idx] = items[num];
items[num]=null;
unlikely_if((num & (num-1))==0){
items = (T**) realloc(items, (num+1)*sizeof(void*));
}
}
int find(T* data){
loopi(num) if(items[i]==data) return i+1;
return 0;
}
void fastRemove(T* data){
int idx = find(data);
if(idx) fastRemove(idx-1);
}
void deleteAll(){
loopi(num) delete[] items[i];
num = 0;
items = (T**)realloc(items, sizeof(void*)); items[0] = null;
}
};
class BootupCaller{
public:
BootupCaller(void (*callback)()){ callback();}
};
//================================ IMPLEMENTATION ===========================================================================
#ifdef KEISTD_IMPL
void DebugPrint(const char* x){ printf("%s\n",x);}
void DebugPrint(const char* name, int x){ printf("%s = %d\n", name,x);}
void DebugPrint(const char* name, double x){ printf("%s = %f\n", name,x);}
void DebugPrint(const char* name, const char* x){ printf("%s = %s\n", name,x);}
void DebugPrintHex(const char* name, int x){ printf("%s = 0x%08X\n", name,x);}
void _onUAssertFail(){
fprintf(stderr,"Assert hit\n"); fflush(stderr);
BreakpointInt3;
}
void* memclone(const void* ptr,int size){
void* data = malloc(size);
memcpy(data, ptr, size);
return data;
}
char* uffetch(const char* fname, int* len, int padEnd, int padStart){
FILE* f1 = fopen(fname, "rb"); if(!f1)return null;
fseek(f1,0, SEEK_END); int siz = ftell(f1); fseek(f1, 0, SEEK_SET);
char* data = (char*)malloc(siz+padEnd+padStart); if(!data) { fclose(f1); return null; }
if(padStart)memset(data, 0, padStart);
if(padEnd)memset(data+(padStart+siz), 0, padEnd);
fread(data + padStart, 1, siz, f1);
fclose(f1);
if(len) *len = siz;
return data;
}
bool ufdump(const char* fname, const void* data, int len){
FILE* f1 = fopen(fname, "wb"); if(!f1)return false;
bool result = (fwrite(data, 1, len, f1) == (size_t)len);
fclose(f1);
return result;
}
static FILE *_kei_fread = 0, *_kei_fwrite=0;
bool ufopenRead(const char* fname){
FILE* f1 = fopen(fname,"rb"); if(!f1)return false;
if(_kei_fread)fclose(_kei_fread);
_kei_fread = f1;
return true;
}
void ufcloseRead(){ if(_kei_fread)fclose(_kei_fread); _kei_fread = null; }
int ufread4(){ int x = 0; fread(&x,sizeof(x),1,_kei_fread); return x;}
short ufread2(){ short x = 0; fread(&x,sizeof(x),1,_kei_fread); return x;}
char ufread1(){ char x = 0; fread(&x,sizeof(x),1,_kei_fread); return x;}
float ufreadF(){ float x = 0.0f; fread(&x,sizeof(x),1,_kei_fread); return x;}
bool ufread(void* data, int len){ return (size_t)len == fread(data, 1, len, _kei_fread);}
void ufreadSkip(int offs){ fseek(_kei_fread, offs, SEEK_CUR);}
void* ufreadAlloc(int len){
char* p = (char*)malloc(len+1);
if(p){ fread(p, 1, len, _kei_fread); p[len]=0;}
return p;
}
char* ufreadStr(){
int len = ufread4();
if(len)return (char*)ufreadAlloc(len);
return null;
}
bool ufopenWrite(const char* fname){
FILE* f1 = fopen(fname,"wb"); if(!f1)return false;
if(_kei_fwrite)fclose(_kei_fwrite);
_kei_fwrite = f1;
return true;
}
void ufcloseWrite(){ if(_kei_fwrite)fclose(_kei_fwrite); _kei_fwrite = null; }
bool ufwrite4(int x){ return fwrite(&x, sizeof(x), 1, _kei_fwrite) == sizeof(x);}
bool ufwrite2(short x){ return fwrite(&x, sizeof(x), 1, _kei_fwrite) == sizeof(x);}
bool ufwrite1(char x){ return fwrite(&x, sizeof(x), 1, _kei_fwrite) == sizeof(x);}
bool ufwriteF(float x){ return fwrite(&x, sizeof(x), 1, _kei_fwrite) == sizeof(x);}
bool ufwrite(const void* data, int len){ return fwrite(data, 1, len, _kei_fwrite) == (size_t)len;}
bool ufwriteStr(const char* str){
if(str){
int len = 1 + strlen(str);
if(!ufwrite4(len))return false;
if(!ufwrite(str, len))return false;
}else{
if(!ufwrite4(0))return false;
}
return true;
}
char* strclone(const char* data){
if(data){
char* res = new char[strlen(data)+1];
strcpy(res,data);
return res;
}
return null;
}
void itoaComma(char* str, int x){
if(x < 0){ *str++ ='-';x=-x;}
int w=0,three=0;
for(;;){
three++;
if(three==4){three=1; str[w++]=',';}
int nx = x/10;
str[w++]=(char)('0'+ x-nx*10);
x=nx;
if(x==0)break;
}
str[w]=0;
// reverse string
for(int i=0;i<w;i++){
w--;
char c=str[w];
str[w]=str[i];
str[i]=c;
}
}
char* strfirst(char* str, char c){
for(;;){
char t = *str;
if(t==c) return str;
if(!t)return null;
str++;
}
}
char* strfirst(char* str, char c1, char c2){
for(;;){
char t = *str;
if(t==c1 || t==c2) return str;
if(!t)return null;
str++;
}
}
char* strlast(char* str, char c){
char* res = null;
for(;;){
char t = *str;
if(t==c) res = str;
if(!t)break;
str++;
}
return res;
}
char* strlast(char* str, char c1, char c2){
char* res = null;
for(;;){
char t = *str;
if(t==c1 || t==c2) res = str;
if(!t)break;
str++;
}
return res;
}
void strSkipWhitespace(char** str){
char* ptr = *str;
for(;;){
char c = *ptr;
if(c==9 || c==32 || c==10 || c==13)ptr++;
else break;
}
*str = ptr;
}
int strRemoveChars(char* data,char c){
if(!data)return 0;
char *esi=data,*edi=data,*base=data,t;
do{
t = *esi++;
if(t!=c) *edi++ = t;
}while(t);
return edi - base;
}
const char* HStr::toStr(char* dest, int destSize) const {
destSize--;
if(destSize > len) destSize = len;
memcpy(dest, str, destSize);
dest[destSize] = 0;
return dest;
}
char* HStr::toStr() const{
char* res = new char[len];
memcpy(res, str, len);
res[len] = 0;
return res;
}
HStr HStr::getTok(const char** pstr, bool skipNewline, int* pkind){
int kind;
const char* str = *pstr;
char c;
c = *str++;
while(c==32 || c==9 || c==13 || (c==10 && skipNewline)){
c = *str++;
}
const char* base = str;
if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c=='_' || c=='@'){
// identifier
kind = 256+'i';
c = *str++;
while((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c=='_' || c=='@'){
c = *str++;
}
}else if(c >= '0' && c <= '9'){
// number
kind = 256+'n';
c = *str++;
if(c!='x'){
// decimal number
while(c >= '0' && c <= '9'){
c = *str++;
}
}else{
// hexadecimal number
c = *str++;
while((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')){
c = *str++;
}
}
}else if(c=='"'){
// quote
kind = 256+'q';
char prevC;
for(;;){
prevC = c;
c = *str++;
if(c=='"' && prevC!='\\'){ str++; break;}
if(c==0)break;
if(c==10 && !skipNewline)break;
}
}else{
// others. Null and NewLine fall here
kind = (int)c;
str++;
}
// return results
base--; str--;
if(pkind) *pkind = kind;
*pstr = str;
HStr res;
res.str = base;
res.len = str - base;
res.calcHash();
return res;
}
// ================= benchmarking ==========================
struct _kei_BenchResult{
const char* name;
uint minTime;
uint lastTime;
uint maxTime;
double avgTime;
double avgTime2;
bool used;
uint numTimesUsed;
};
static uint _kei_BenchStartTick[8],_kei_BenchStartTickIDX=0;
static uint _kei_BenchNumObjects=0;
static _kei_BenchResult _kei_BenchResults[16];
static uint _RDTSC(){
uint x,upper;
#ifdef __GNUC__
asm volatile ("rdtsc": "=a" (x), "=d" (upper));
#else
__asm{
RDTSC;
mov x,eax;
}
#endif
return x;
}
void BenchStart(){
_kei_BenchStartTick[_kei_BenchStartTickIDX] = _RDTSC();
_kei_BenchStartTickIDX++;
_kei_BenchStartTickIDX&=7;
}
uint _BenchEndFunc(const char* name, int& index){
uint time = _RDTSC();
_kei_BenchStartTickIDX--;
_kei_BenchStartTickIDX&=7;
time = time-_kei_BenchStartTick[_kei_BenchStartTickIDX];
unlikely_if(name==null)return time;
unlikely_if(index==0){
_kei_BenchNumObjects++; index = _kei_BenchNumObjects;
_kei_BenchResults[index-1].used = false;
}
_kei_BenchResult* edx = &_kei_BenchResults[index-1];
likely_if(edx->used) {
edx->numTimesUsed++;
edx->lastTime=time;
if(edx->minTime>time)edx->minTime=time;
if(edx->maxTime<time)edx->maxTime=time;
edx->avgTime+= (double)time;
edx->avgTime2 = (edx->avgTime2*0.9999) + (time*0.0001);
return time;
}else{
edx->name = name;
edx->minTime=time;
edx->lastTime=time;
edx->maxTime=time;
edx->avgTime=(double)time;
edx->avgTime2=(double)time;
edx->used=true;
edx->numTimesUsed=1;
return time;
}
}
static char* _itoaComma(char* dest, int x){ itoaComma(dest, x); return dest;}
void BenchPrint(){
if(!_kei_BenchNumObjects)return;
bool oki=false;
loopui(_kei_BenchNumObjects){
_kei_BenchResult* edx = &_kei_BenchResults[i];
if(!edx->used)continue;
if(!oki){
prints("Bench results:");
oki=true;
}
edx->avgTime/= (double)edx->numTimesUsed;
char str[32];
//printf(" %-30s: avg1=%-10d avg2=%-10d min=%-10d last=%-10d max=%-10d, count=%-10d\n",
// edx->name,(int)edx->avgTime,(int)edx->avgTime2,edx->minTime,edx->lastTime,edx->maxTime,edx->numTimesUsed);
printf(" %-16s: ",edx->name);
printf("avg1: %-14s ", _itoaComma(str, (int)edx->avgTime));
printf("avg2: %-14s ", _itoaComma(str, (int)edx->avgTime2));
printf("min: %-14s ", _itoaComma(str, edx->minTime));
printf("last: %-14s ", _itoaComma(str, edx->lastTime));
printf("max: %-14s ", _itoaComma(str, edx->maxTime));
printf("count: %-14s ", _itoaComma(str, edx->numTimesUsed));
printf("\n");
edx->used=false;
}
}
void SSE_DenormalsAreZero_FlushToZero(){
#ifndef __GNUC__
int sse_cr;
__asm{
STMXCSR sse_cr
or sse_cr,8040h
LDMXCSR sse_cr
};
#else
unsigned int mxcsr;
__asm__ __volatile__ ("stmxcsr (%0)" : : "r"(&mxcsr) : "memory");
mxcsr = (mxcsr | (1<<15) | (1<<6));
__asm__ __volatile__ ("ldmxcsr (%0)" : : "r"(&mxcsr));
#endif
}
#endif
#endif // _KEISTD_H_
| 26.123641 | 146 | 0.60051 | [
"vector"
] |
e068da3bd73b1a2e4fb00c3b7919b29566339fff | 5,857 | h | C | aws-cpp-sdk-ec2/include/aws/ec2/model/InstanceState.h | julio-gorge/aws-sdk-cpp | 06b0d54110172b3cf9b3f5602060304e36afd225 | [
"Apache-2.0"
] | 2 | 2019-03-11T15:50:55.000Z | 2020-02-27T11:40:27.000Z | aws-cpp-sdk-ec2/include/aws/ec2/model/InstanceState.h | isubscribed/aws-sdk-cpp | 4689ffab8c5601976e73ac185f20e12a2a0fbc37 | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-ec2/include/aws/ec2/model/InstanceState.h | isubscribed/aws-sdk-cpp | 4689ffab8c5601976e73ac185f20e12a2a0fbc37 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2010-2017 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.
*/
#pragma once
#include <aws/ec2/EC2_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSStreamFwd.h>
#include <aws/ec2/model/InstanceStateName.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Xml
{
class XmlNode;
} // namespace Xml
} // namespace Utils
namespace EC2
{
namespace Model
{
/**
* <p>Describes the current state of an instance.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/InstanceState">AWS
* API Reference</a></p>
*/
class AWS_EC2_API InstanceState
{
public:
InstanceState();
InstanceState(const Aws::Utils::Xml::XmlNode& xmlNode);
InstanceState& operator=(const Aws::Utils::Xml::XmlNode& xmlNode);
void OutputToStream(Aws::OStream& ostream, const char* location, unsigned index, const char* locationValue) const;
void OutputToStream(Aws::OStream& oStream, const char* location) const;
/**
* <p>The state of the instance as a 16-bit unsigned integer. </p> <p>The high byte
* is all of the bits between 2^8 and (2^16)-1, which equals decimal values between
* 256 and 65,535. These numerical values are used for internal purposes and should
* be ignored.</p> <p>The low byte is all of the bits between 2^0 and (2^8)-1,
* which equals decimal values between 0 and 255. </p> <p>The valid values for
* instance-state-code will all be in the range of the low byte and they are:</p>
* <ul> <li> <p> <code>0</code> : <code>pending</code> </p> </li> <li> <p>
* <code>16</code> : <code>running</code> </p> </li> <li> <p> <code>32</code> :
* <code>shutting-down</code> </p> </li> <li> <p> <code>48</code> :
* <code>terminated</code> </p> </li> <li> <p> <code>64</code> :
* <code>stopping</code> </p> </li> <li> <p> <code>80</code> : <code>stopped</code>
* </p> </li> </ul> <p>You can ignore the high byte value by zeroing out all of the
* bits above 2^8 or 256 in decimal.</p>
*/
inline int GetCode() const{ return m_code; }
/**
* <p>The state of the instance as a 16-bit unsigned integer. </p> <p>The high byte
* is all of the bits between 2^8 and (2^16)-1, which equals decimal values between
* 256 and 65,535. These numerical values are used for internal purposes and should
* be ignored.</p> <p>The low byte is all of the bits between 2^0 and (2^8)-1,
* which equals decimal values between 0 and 255. </p> <p>The valid values for
* instance-state-code will all be in the range of the low byte and they are:</p>
* <ul> <li> <p> <code>0</code> : <code>pending</code> </p> </li> <li> <p>
* <code>16</code> : <code>running</code> </p> </li> <li> <p> <code>32</code> :
* <code>shutting-down</code> </p> </li> <li> <p> <code>48</code> :
* <code>terminated</code> </p> </li> <li> <p> <code>64</code> :
* <code>stopping</code> </p> </li> <li> <p> <code>80</code> : <code>stopped</code>
* </p> </li> </ul> <p>You can ignore the high byte value by zeroing out all of the
* bits above 2^8 or 256 in decimal.</p>
*/
inline void SetCode(int value) { m_codeHasBeenSet = true; m_code = value; }
/**
* <p>The state of the instance as a 16-bit unsigned integer. </p> <p>The high byte
* is all of the bits between 2^8 and (2^16)-1, which equals decimal values between
* 256 and 65,535. These numerical values are used for internal purposes and should
* be ignored.</p> <p>The low byte is all of the bits between 2^0 and (2^8)-1,
* which equals decimal values between 0 and 255. </p> <p>The valid values for
* instance-state-code will all be in the range of the low byte and they are:</p>
* <ul> <li> <p> <code>0</code> : <code>pending</code> </p> </li> <li> <p>
* <code>16</code> : <code>running</code> </p> </li> <li> <p> <code>32</code> :
* <code>shutting-down</code> </p> </li> <li> <p> <code>48</code> :
* <code>terminated</code> </p> </li> <li> <p> <code>64</code> :
* <code>stopping</code> </p> </li> <li> <p> <code>80</code> : <code>stopped</code>
* </p> </li> </ul> <p>You can ignore the high byte value by zeroing out all of the
* bits above 2^8 or 256 in decimal.</p>
*/
inline InstanceState& WithCode(int value) { SetCode(value); return *this;}
/**
* <p>The current state of the instance.</p>
*/
inline const InstanceStateName& GetName() const{ return m_name; }
/**
* <p>The current state of the instance.</p>
*/
inline void SetName(const InstanceStateName& value) { m_nameHasBeenSet = true; m_name = value; }
/**
* <p>The current state of the instance.</p>
*/
inline void SetName(InstanceStateName&& value) { m_nameHasBeenSet = true; m_name = std::move(value); }
/**
* <p>The current state of the instance.</p>
*/
inline InstanceState& WithName(const InstanceStateName& value) { SetName(value); return *this;}
/**
* <p>The current state of the instance.</p>
*/
inline InstanceState& WithName(InstanceStateName&& value) { SetName(std::move(value)); return *this;}
private:
int m_code;
bool m_codeHasBeenSet;
InstanceStateName m_name;
bool m_nameHasBeenSet;
};
} // namespace Model
} // namespace EC2
} // namespace Aws
| 41.539007 | 118 | 0.634625 | [
"model"
] |
e06e824be833daa12fa046f7a8089347957f4341 | 15,080 | c | C | kernel/mm.c | skordal/mordax | 29cd337677c6cb27a546873705ff39c2f270554e | [
"BSD-3-Clause"
] | 10 | 2017-02-11T20:55:52.000Z | 2021-12-23T04:14:43.000Z | kernel/mm.c | skordal/mordax | 29cd337677c6cb27a546873705ff39c2f270554e | [
"BSD-3-Clause"
] | null | null | null | kernel/mm.c | skordal/mordax | 29cd337677c6cb27a546873705ff39c2f270554e | [
"BSD-3-Clause"
] | null | null | null | // The Mordax Microkernel
// (c) Kristian Klomsten Skordal 2013 <kristian.skordal@gmail.com>
// Report bugs and issues on <http://github.com/skordal/mordax/issues>
#include "debug.h"
#include "kernel.h"
#include "mm.h"
#include "mmu.h"
#include "stack.h"
#include "utils.h"
#ifndef CONFIG_PAGE_SIZE
#error "page size not set, define CONFIG_PAGE_SIZE with the proper page size"
#endif
#ifndef CONFIG_MIN_FREE_MEM
#error "minimum free memory amount not set, define CONFIG_MIN_FREE_MEM with the proper value"
#endif
#ifndef MINIMUM_BLOCK_SIZE
#define MINIMUM_BLOCK_SIZE MM_DEFAULT_ALIGNMENT
#endif
#ifndef MINIMUM_EXPAND_SIZE
#define MINIMUM_EXPAND_SIZE 4 * CONFIG_PAGE_SIZE
#endif
// Virtual memory block:
struct memory_block
{
size_t size;
void * start;
bool used;
struct memory_block * next, * prev;
};
// Physical memory zone:
struct memory_zone
{
size_t size;
unsigned int flags;
physical_ptr start;
struct memory_zone * next;
uint8_t ** buddy_lists;
};
// Object stack:
struct mm_object_stack
{
size_t object_size;
unsigned object_alignment;
unsigned expand_elements;
unsigned available;
struct stack * object_stack;
};
// Imported from the linker script:
extern void * bss_end;
// Pointer to the end of the mapped kernel dataspace, may be updated by the
// platform initialization code:
void * kernel_dataspace_end = &bss_end;
// Head of the list of memory blocks:
struct memory_block * memory_list = (void *) &bss_end;
// Head of the list of physical memory zones:
struct memory_zone * physical_memory_list = 0;
// Total amount of free memory:
static size_t total_free_memory = 0;
// Expands the kernel heap:
static bool expand_heap(size_t size);
// Splits a block at the specified offset:
static struct memory_block * mm_split(struct memory_block *, unsigned offset);
// Allocates a physical memory block of the specified order in the specified zone:
static physical_ptr mm_allocate_order(struct memory_zone * zone, unsigned order);
// Helper function for freeing a block with the specified bit number in the buddy list
// for the specified order. This function takes care of coalescing blocks when possible.
static void mm_free_order(struct memory_zone * zone, unsigned order, unsigned bitnum);
// Reserves a block of physical memory:
static void mm_reserve_block(struct memory_zone * zone, unsigned order, unsigned bitnum);
// Calculates the order of physical block needed to allocate the specified amount
// of memory:
static inline unsigned size_to_order(size_t size);
// Calculates the number of bits required to represent a memory area of size
// at the specified order in the buddy lists:
static inline unsigned order_bits(unsigned order, size_t size);
// Calculates the size of a physical memory block of the specified order:
static inline size_t order_blocksize(unsigned order);
void print_blocks(void)
{
struct memory_block * current= memory_list;
while(current != 0)
{
debug_printf("Block @ %p\n", current);
debug_printf("\tstart: %p\n", current->start);
debug_printf("\tnext: %p\n", current->next);
debug_printf("\tprev: %p\n", current->prev);
debug_printf("\tsize: %d\n", (unsigned int) current->size);
debug_printf("\tused: %s\n", current->used ? "true" : "false");
current = current->next;
}
}
void mm_initialize(void)
{
struct memory_block * first_block = memory_list;
memclr(first_block, sizeof(struct memory_block));
first_block->start = (void *) ((uint32_t) memory_list + sizeof(struct memory_block));
first_block->size = ((uint32_t) kernel_dataspace_end - (uint32_t) &bss_end - sizeof(struct memory_block));
total_free_memory = first_block->size;
}
void * mm_allocate(size_t size, unsigned int alignment, unsigned int flags)
{
void * retval = 0;
if(alignment < MM_DEFAULT_ALIGNMENT)
alignment = MM_DEFAULT_ALIGNMENT;
if(size < MINIMUM_BLOCK_SIZE)
size = MINIMUM_BLOCK_SIZE;
size += 3;
size &= -4;
while(total_free_memory <= size)
expand_heap(size);
struct memory_block * current = memory_list;
do {
if(current->size >= size && !current->used)
{
uint32_t block_address = (uint32_t) current->start;
uint32_t offset = ((block_address + alignment - 1) & -alignment) - block_address;
if(offset == 0)
{
if(current->size > size)
mm_split(current, size);
current->used = true;
total_free_memory -= current->size;
retval = current->start;
break;
} else if(current->size - (offset + sizeof(struct memory_block)) >= size
&& offset >= sizeof(struct memory_block) + MINIMUM_BLOCK_SIZE)
{
struct memory_block * split_block = mm_split(current, offset - sizeof(struct memory_block));
if(split_block != 0)
{
if(split_block->size > size)
mm_split(split_block, size);
split_block->used = true;
total_free_memory -= split_block->size;
retval = split_block->start;
break;
}
}
}
current = current->next;
} while(current != 0);
return retval;
}
void mm_free(void * area)
{
struct memory_block * block = (void *) ((uint32_t) area - sizeof(struct memory_block));
block->used = false;
total_free_memory += block->size;
if(block->prev != 0 && !block->prev->used)
{
block->prev->size += block->size + sizeof(struct memory_block);
total_free_memory += sizeof(struct memory_block);
block->prev->next = block->next;
if(block->next)
block->next->prev = block->prev;
block = block->prev;
}
if(block->next != 0 && !block->next->used)
{
block->size += block->next->size + sizeof(struct memory_block);
total_free_memory += sizeof(struct memory_block);
if(block->next->next)
block->next->next->prev = block;
block->next = block->next->next;
}
}
static bool expand_heap(size_t size)
{
if(size < MINIMUM_EXPAND_SIZE)
size = MINIMUM_EXPAND_SIZE;
size = (size + CONFIG_PAGE_SIZE - 1) & -CONFIG_PAGE_SIZE;
debug_printf("Expanding heap by %d bytes\n", size);
// Prepare a new block for the allocated memory, if neccessary:
struct memory_block * new_block = kernel_dataspace_end;
// FIXME: This function will not work for memory blocks larger than the maximum buddy block size!
if(size > order_blocksize(CONFIG_BUDDY_MAX_ORDER))
kernel_panic("cannot expand heap due to too much memory requested");
// Allocate and map new memory:
struct mm_physical_memory new_memory;
if(!mm_allocate_physical(size, &new_memory))
kernel_panic("out of memory");
mmu_map(0, new_memory.base, kernel_dataspace_end, new_memory.size,
MORDAX_TYPE_DATA, MORDAX_PERM_RW_NA);
kernel_dataspace_end = (void *) ((uint32_t) kernel_dataspace_end + (uint32_t) new_memory.size);
// Append the allocated memory to the last block (if unused):
struct memory_block * last_block;
struct memory_block * current = memory_list;
while(current->next != 0)
current = current->next;
last_block = current;
if(last_block->used)
{
memclr(new_block, sizeof(struct memory_block));
new_block->used = false;
new_block->size = new_memory.size - sizeof(struct memory_block);
total_free_memory += new_memory.size - sizeof(struct memory_block);
last_block->next = new_block;
new_block->prev = last_block;
} else {
last_block->size += new_memory.size;
total_free_memory += new_memory.size;
}
return true;
}
static struct memory_block * mm_split(struct memory_block * block, unsigned offset)
{
if(block->size <= offset + sizeof(struct memory_block) + MINIMUM_BLOCK_SIZE)
return 0;
size_t new_block_size = block->size - (offset + sizeof(struct memory_block));
if(new_block_size >= MINIMUM_BLOCK_SIZE)
{
struct memory_block * retval = (struct memory_block *) ((uint32_t) block->start + offset);
retval->size = new_block_size;
retval->start = (void *) ((uint32_t) retval + sizeof(struct memory_block));
retval->prev = block;
retval->next = block->next;
retval->used = false;
if(block->next != 0)
block->next->prev = retval;
block->next = retval;
block->size = offset;
total_free_memory -= sizeof(struct memory_block);
return retval;
} else
return 0;
}
struct mm_object_stack * mm_object_stack_create(size_t object_size, unsigned alignment, unsigned number, unsigned expand)
{
struct mm_object_stack * retval = mm_allocate(sizeof(struct mm_object_stack), MM_DEFAULT_ALIGNMENT, MM_MEM_NORMAL);
retval->object_size = object_size;
retval->object_alignment = alignment;
retval->expand_elements = expand;
retval->available = number;
retval->object_stack = stack_new();
// Add initial elements to the stack:
for(unsigned i = 0; i < number; ++i)
stack_push(retval->object_stack, mm_allocate(retval->object_size, retval->object_alignment, MM_MEM_NORMAL));
return retval;
}
void * mm_object_stack_allocate(struct mm_object_stack * s)
{
void * retval = 0;
if(!stack_pop(s->object_stack, &retval))
{
mm_object_stack_expand(s);
stack_pop(s->object_stack, &retval);
}
--s->available;
return retval;
}
void mm_object_stack_free(struct mm_object_stack * s, void * object)
{
stack_push(s->object_stack, object);
++s->available;
}
unsigned mm_object_stack_available(struct mm_object_stack * s)
{
return s->available;
}
void mm_object_stack_expand(struct mm_object_stack * s)
{
for(unsigned i = 0; i < s->expand_elements; ++i)
stack_push(s->object_stack, mm_allocate(s->object_size, s->object_alignment, MM_MEM_NORMAL));
s->available += s->expand_elements;
}
void mm_object_stack_destroy(struct mm_object_stack * s)
{
stack_free(s->object_stack, mm_free);
mm_free(s);
}
void mm_add_physical(physical_ptr address, size_t size, unsigned int flags)
{
struct memory_zone * new_zone = mm_allocate(sizeof(struct memory_zone), MM_DEFAULT_ALIGNMENT, MM_MEM_NORMAL);
new_zone->start = address;
new_zone->size = size & -CONFIG_PAGE_SIZE;
new_zone->flags = flags;
new_zone->next = physical_memory_list;
new_zone->buddy_lists = mm_allocate(sizeof(uint8_t *) * (CONFIG_BUDDY_MAX_ORDER + 1), MM_DEFAULT_ALIGNMENT,
MM_MEM_NORMAL);
memclr(new_zone->buddy_lists, sizeof(uint8_t *) * (CONFIG_BUDDY_MAX_ORDER + 1));
// Allocate buddy lists:
for(unsigned i = 0; i <= CONFIG_BUDDY_MAX_ORDER; ++i)
{
new_zone->buddy_lists[i] = mm_allocate(sizeof(uint8_t *) * ((order_bits(i, size) + 7) / 8),
MM_DEFAULT_ALIGNMENT, MM_MEM_NORMAL);
memclr(new_zone->buddy_lists[i], sizeof(uint8_t *) * (((size & -CONFIG_PAGE_SIZE) >> (log2(CONFIG_PAGE_SIZE) + i)) >> 3));
}
// Set all maximum order blocks as unused:
for(unsigned i = 0; i < (order_bits(CONFIG_BUDDY_MAX_ORDER, size) + 7) >> 3; ++i)
new_zone->buddy_lists[CONFIG_BUDDY_MAX_ORDER][i] = 0xff;
struct memory_zone * prev_zone = physical_memory_list;
if(prev_zone == 0)
physical_memory_list = new_zone;
else {
while(prev_zone->next != 0)
prev_zone = prev_zone->next;
prev_zone->next = new_zone;
}
}
bool mm_allocate_physical(size_t size, struct mm_physical_memory * retval)
{
struct memory_zone * zone = physical_memory_list; // TODO: find a proper zone
unsigned order = size_to_order(size);
if(order > CONFIG_BUDDY_MAX_ORDER)
kernel_panic("cannot satisfy physical memory request, requested block is too large");
// Allocates a block of the specified order:
retval->base = mm_allocate_order(zone, order);
retval->size = order_blocksize(order);
retval->flags = zone->flags;
return true;
}
static physical_ptr mm_allocate_order(struct memory_zone * zone, unsigned order)
{
if(order == CONFIG_BUDDY_MAX_ORDER + 1)
return 0;
for(unsigned i = 0; i < order_bits(order, zone->size); ++i)
{
if(zone->buddy_lists[order][i >> 3] & (1 << (i % 8)))
{
zone->buddy_lists[order][i >> 3] &= ~(1 << (i % 8));
return (physical_ptr) ((uint32_t) zone->start + (i * order_blocksize(order)));
}
}
// If no block was found, split a larger order block:
physical_ptr split_block = mm_allocate_order(zone, order + 1);
unsigned split_bits = ((uint32_t) split_block - (uint32_t) zone->start) >> log2(order_blocksize(order));
// Return the first part of the split block, and set the other as unused:
zone->buddy_lists[order][(split_bits + 1) >> 3] |= (1 << ((split_bits + 1) % 8));
zone->buddy_lists[order][(split_bits) >> 3] &= ~(1 << ((split_bits) % 8));
return split_block;
}
bool mm_is_physical_managed(physical_ptr address)
{
struct memory_zone * zone = physical_memory_list;
uint32_t test_address = (uint32_t) address;
while(zone != 0)
{
if(test_address >= (uint32_t) zone->start && test_address < (uint32_t) zone->start + zone->size)
return true;
zone = zone->next;
}
return false;
}
void mm_free_physical(struct mm_physical_memory * block)
{
struct memory_zone * zone = physical_memory_list;
while(zone != 0)
{
if((uint32_t) block->base >= (uint32_t) zone->start
&& (uint32_t) block->base + block->size <= (uint32_t) zone->start + zone->size)
break;
zone = zone->next;
}
if(zone == 0)
return;
unsigned order = size_to_order(block->size);
unsigned bitnum = ((uint32_t) block->base - (uint32_t) zone->start) >> (log2(CONFIG_PAGE_SIZE) + order);
mm_free_order(zone, order, bitnum);
}
static void mm_free_order(struct memory_zone * zone, unsigned order, unsigned bitnum)
{
if(order == CONFIG_BUDDY_MAX_ORDER + 1)
return;
zone->buddy_lists[order][bitnum >> 3] |= (1 << (bitnum % 8));
if(order == CONFIG_BUDDY_MAX_ORDER)
return;
if(bitnum & 1)
{
if(zone->buddy_lists[order][(bitnum - 1) >> 3] & (1 << ((bitnum - 1) % 8)))
{
zone->buddy_lists[order][(bitnum - 1) >> 3] &= ~((3 << (bitnum - 1) % 8));
mm_free_order(zone, order + 1, (bitnum - 1) >> 1);
}
} else {
if(zone->buddy_lists[order][(bitnum + 1) >> 3] & (1 << ((bitnum + 1) % 8)))
{
zone->buddy_lists[order][bitnum >> 3] &= ~((3 << bitnum % 8));
mm_free_order(zone, order + 1, bitnum >> 1);
}
}
}
void mm_reserve_physical(physical_ptr address, size_t size)
{
struct memory_zone * zone = physical_memory_list;
while(zone != 0)
{
if((uint32_t) address >= (uint32_t) zone->start
&& (uint32_t) address + size <= (uint32_t) zone->start + zone->size)
break;
zone = zone->next;
}
if(zone == 0)
return;
unsigned first_bitnum = ((uint32_t) address - (uint32_t) zone->start) >> log2(CONFIG_PAGE_SIZE);
unsigned last_bitnum = (((uint32_t) address - (uint32_t) zone->start) + size) >> log2(CONFIG_PAGE_SIZE);
for(unsigned i = first_bitnum; i < last_bitnum; ++i)
mm_reserve_block(zone, 0, i);
}
static void mm_reserve_block(struct memory_zone * zone, unsigned order, unsigned bitnum)
{
zone->buddy_lists[order][bitnum >> 3] &= ~(1 << (bitnum % 8));
if(order == CONFIG_BUDDY_MAX_ORDER)
return;
mm_reserve_block(zone, order + 1, bitnum >> 1);
}
static inline unsigned size_to_order(size_t size)
{
size_t fullsize = (size + CONFIG_PAGE_SIZE - 1) & -CONFIG_PAGE_SIZE;
unsigned order;
for(order = CONFIG_BUDDY_MAX_ORDER; order >= 0; --order)
if((fullsize & -(1 << (log2(CONFIG_PAGE_SIZE) + order))) == fullsize)
break;
return order;
}
static inline unsigned order_bits(unsigned order, size_t size)
{
return (size & -CONFIG_PAGE_SIZE) >> (log2(CONFIG_PAGE_SIZE) + order);
}
static inline size_t order_blocksize(unsigned order)
{
return 1 << (log2(CONFIG_PAGE_SIZE) + order);
}
| 29.395712 | 124 | 0.713395 | [
"object"
] |
e075d620e8436822ade1246eed34d8d69277e0e9 | 12,355 | h | C | src/segment.h | SiriusTR/dle-experimental | 2ee17b4277b68eef57960d5cf9762dd986eaa0d9 | [
"MIT"
] | null | null | null | src/segment.h | SiriusTR/dle-experimental | 2ee17b4277b68eef57960d5cf9762dd986eaa0d9 | [
"MIT"
] | 3 | 2019-09-10T03:50:40.000Z | 2019-09-23T04:20:14.000Z | src/segment.h | SiriusTR/dle-experimental | 2ee17b4277b68eef57960d5cf9762dd986eaa0d9 | [
"MIT"
] | 1 | 2021-10-02T14:16:28.000Z | 2021-10-02T14:16:28.000Z | // Segment.h
#ifndef __segment_h
#define __segment_h
#include "define.h"
#include "Types.h"
#include "side.h"
#include "FileManager.h"
// -----------------------------------------------------------------------------
// define points for a given side
extern ubyte sideVertexTable [6][4];
extern ubyte oppSideTable [6];
extern ubyte oppSideVertexTable [6][4];
extern ubyte edgeVertexTable [12][2];
extern ubyte vertexEdgeTable [8][3];
extern ubyte sideEdgeTable [6][4];
extern ubyte edgeSideTable [12][2];
extern ubyte adjacentPointTable [8][3];
extern ubyte adjacentSideTable [8][3];
extern ubyte pointCornerTable [8][3];
extern int sideChildTable[6][4];
// -----------------------------------------------------------------------------
// Returns true if nSegment references a child, else returns false.
// Note that -1 means no connection, -2 means a connection to the outside world.
#define IS_CHILD(nSegment) (nSegment > -1)
#define SEGMENT_TYPE_NONE 0
#define SEGMENT_TYPE_PRODUCER 1
#define SEGMENT_TYPE_REPAIRCEN 2
#define SEGMENT_TYPE_CONTROLCEN 3
#define SEGMENT_TYPE_ROBOTMAKER 4
#define MAX_SEGMENT_TYPES1 5
#define SEGMENT_TYPE_GOAL_BLUE 5 // Descent 2 only
#define SEGMENT_TYPE_GOAL_RED 6 // Descent 2 only
#define SEGMENT_TYPE_WATER 7
#define SEGMENT_TYPE_LAVA 8
#define SEGMENT_TYPE_TEAM_BLUE 9
#define SEGMENT_TYPE_TEAM_RED 10
#define SEGMENT_TYPE_SPEEDBOOST 11
#define SEGMENT_TYPE_BLOCKED 12
#define SEGMENT_TYPE_NODAMAGE 13
#define SEGMENT_TYPE_SKYBOX 14
#define SEGMENT_TYPE_EQUIPMAKER 15 // matcen for powerups
#define SEGMENT_TYPE_OUTDOORS 16
#define MAX_SEGMENT_TYPES2 17 // Descent 2 only
#define SEGMENT_FUNC_NONE 0
#define SEGMENT_FUNC_PRODUCER 1
#define SEGMENT_FUNC_REPAIRCEN 2
#define SEGMENT_FUNC_REACTOR 3
#define SEGMENT_FUNC_ROBOTMAKER 4
#define SEGMENT_FUNC_GOAL_BLUE 5
#define SEGMENT_FUNC_GOAL_RED 6
#define SEGMENT_FUNC_TEAM_BLUE 7
#define SEGMENT_FUNC_TEAM_RED 8
#define SEGMENT_FUNC_SPEEDBOOST 9
#define SEGMENT_FUNC_SKYBOX 10
#define SEGMENT_FUNC_EQUIPMAKER 11
#define MAX_SEGMENT_FUNCTIONS 12
#define SEGMENT_PROP_NONE 0
#define SEGMENT_PROP_WATER 1
#define SEGMENT_PROP_LAVA 2
#define SEGMENT_PROP_BLOCKED 4
#define SEGMENT_PROP_NODAMAGE 8
#define SEGMENT_PROP_SELF_ILLUMINATE 16
#define SEGMENT_PROP_LIGHT_FOG 32
#define SEGMENT_PROP_DENSE_FOG 64
#define SEGMENT_PROP_FOG (SEGMENT_PROP_LIGHT_FOG | SEGMENT_PROP_DENSE_FOG)
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
class CEdgeIndex {
public:
ushort m_nEdge;
ubyte m_sides [2];
ubyte m_nSides;
CEdgeIndex () { Reset (); }
void Reset (void) {
m_nEdge = 0xffff;
m_sides [0] = m_sides [1] = 0xff;
m_nSides = 0;
}
};
// -----------------------------------------------------------------------------
class CEdgeList {
public:
CEdgeIndex m_edgeList [12];
int m_nEdges;
CEdgeList () : m_nEdges (0) {
for (int i = 0; i < 12; i++)
m_edgeList [i].Reset ();
}
static inline ushort Key (ushort v1, ushort v2) { return (v1 < v2) ? v2 + (v1 << 8) : v1 + (v2 << 8); }
inline void Reset (void) { m_nEdges = 0; }
int Add (ubyte nSide, ubyte v1, ubyte v2);
inline int Count (void) { return m_nEdges; }
inline bool Get (int i, ubyte& side1, ubyte& side2, ubyte &v1, ubyte& v2) {
if (i >= m_nEdges)
return false;
side1 = m_edgeList [i].m_sides [0];
side2 = m_edgeList [i].m_sides [1];
ushort nEdge = m_edgeList [i].m_nEdge;
v1 = ubyte (nEdge & 0xff);
v2 = ubyte (nEdge >> 8);
return true;
}
int Find (int i, ubyte& side1, ubyte& side2, ubyte v1, ubyte v2);
};
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
typedef struct tSegment {
int staticLight; // average static light in segment
ushort vertexIds [MAX_VERTICES_PER_SEGMENT]; // vertex ids of 4 front and 4 back vertices
short damage [2];
short nProducer; // which object producer the segment is associated with
short value; // index of producer the segment is associated with
short mapBitmask; // which lines are drawn when displaying wireframe
ubyte function; // general function (robot maker, energy center, ... - mutually exclusive)
ubyte props; // special property of a segment (such as damaging, trigger, etc.)
ubyte flags; // internally used
ubyte childFlags; // bit0 to 5: children, bit6: unused, bit7: special
ubyte wallFlags; // bit0 to 5: door/walls, bit6: deleted, bit7: marked segment
ubyte bTunnel; // part of a tunnel?
char owner;
char group;
} tSegment;
// -----------------------------------------------------------------------------
class CSegment : public CGameItem {
public:
tSegment m_info;
CSide m_sides [MAX_SIDES_PER_SEGMENT]; // 6 sides
CVertex m_vCenter;
ubyte m_nShape;
public:
void Upgrade (void);
void Read (CFileManager* fp);
void Write (CFileManager* fp);
void ReadExtras (CFileManager* fp, bool bExtras);
void WriteExtras (CFileManager* fp, bool bExtras);
virtual void Clear (void) {
memset (&m_info, 0, sizeof (m_info));
for (int i = 0; i < MAX_SIDES_PER_SEGMENT; i++)
m_sides [i].Clear ();
}
inline tSegment& Info (void) { return m_info; }
void Setup (void);
void SetUV (short nSide, double x, double y);
void GetTriangleUVs (CDoubleVector (&triangleUVs) [3], const CDoubleVector (&triangleVecs) [3]);
//void Read (CFileManager* fp, bool bFlag = false) {}
//void Write (CFileManager* fp, bool bFlag = false) {}
inline short SideIndex (CSide* pSide) { return short (pSide - &m_sides [0]); }
inline CSide _const_ * Side (short i = 0) _const_ { return ((i < 0) || (i > 6)) ? null : &m_sides [i]; }
inline CSide _const_ * OppositeSide (short i) _const_ { return Side (oppSideTable [i]); }
CVertex _const_ * Vertex (ushort nVertex) _const_;
CVertex _const_ * Vertex (ushort nSide, short nIndex) _const_;
inline ushort* VertexIds (void) { return m_info.vertexIds; }
inline ushort VertexId (short i) { return m_info.vertexIds [i]; }
inline ubyte VertexIdIndex (short nSide, short nPoint) { return m_sides [nSide].VertexIdIndex (ubyte (nPoint)); }
inline ushort VertexId (short nSide, short nPoint) { return VertexId (VertexIdIndex (nSide, nPoint)); }
inline void SetVertexId (short i, ushort nId) { m_info.vertexIds [i] = nId; }
inline void SetVertexId (short nSide, short nPoint, ushort nId) { SetVertexId (VertexIdIndex (nSide, nPoint), nId); }
int UpdateVertexId (ushort nOldId, ushort nNewId);
inline short ChildId (short nSide) _const_ { return (m_sides [nSide].m_nShape > SIDE_SHAPE_TRIANGLE) ? -1 : m_sides [nSide].m_info.nChild; }
CSegment* Child (short nSide) _const_;
short SetChild (short nSide, short nSegment);
bool ReplaceChild (short nOldSeg, short nNewSeg);
inline bool RemoveChild (short nSegment) { return ReplaceChild (nSegment, -1); }
bool HasChild (short nChild) { return (m_info.childFlags & (1 << nChild)) != 0; }
void Reset (short nSide = -1);
void UpdateChildren (short nOldChild, short nNewChild);
virtual CGameItem* Clone (void);
virtual void Backup (eEditType editType = opModify);
virtual CGameItem* Copy (CGameItem* pDest);
virtual void Redo (void);
virtual void Undo (void);
inline CUVL _const_ * Uvls (short nSide) _const_ { return Side (nSide)->Uvls (); }
void Tag (ubyte mask = TAGGED_MASK);
void UnTag (ubyte mask = TAGGED_MASK);
void ToggleTag (ubyte mask = TAGGED_MASK);
inline bool IsTagged (ubyte mask = TAGGED_MASK) { return (m_info.flags & mask) != 0; }
void Tag (short nSide, ubyte mask = TAGGED_MASK);
void UnTag (short nSide, ubyte mask = TAGGED_MASK);
void ToggleTag (short nSide, ubyte mask = TAGGED_MASK);
bool IsTagged (short nSide, ubyte mask = TAGGED_MASK);
void TagVertices (ubyte mask = TAGGED_MASK, short nSide = -1);
void UnTagVertices (ubyte mask = TAGGED_MASK, short nSide = -1);
bool HasTaggedVertices (ubyte mask = TAGGED_MASK, short nSide = -1);
inline bool IsD2X (void) { return (m_info.function >= SEGMENT_FUNC_TEAM_BLUE) || (m_info.props != 0); }
bool HasVertex (ushort nVertex);
bool HasVertex (short nSide, ubyte nIndex);
bool HasEdge (short nSide, ushort nVertex1, ushort nVertex2);
inline CSide _const_ & operator[] (uint i) _const_ { return m_sides [i]; }
short FindSide (short nSide, short nVertices, ushort* vertices);
short CommonVertices (short nOtherSeg, short nMaxVertices = 4, ushort* vertices = null);
short CommonSides (short nOtherSeg, short& nOtherSide);
short CommonSide (short nSide, ushort* vertices);
short VertexIndex (short nVertexId);
short SideVertexIndex (short nSide, ubyte nPoint);
inline ubyte& Function (void) { return m_info.function; }
inline ubyte& Props (void) { return m_info.props; }
short AdjacentSide (short nIgnoreSide, ushort* nEdgeVerts);
inline CVertex& Center (void) { return m_vCenter; }
int BuildEdgeList (CEdgeList& edgeList, ubyte nSide, bool bSparse = false);
int BuildEdgeList (CEdgeList& edgeList, bool bSparse = false);
void CreateOppVertexIndex (short nSide, ubyte* oppVertexIndex);
inline void SetShape (ubyte nShape) { m_nShape = nShape; }
inline ubyte Shape (void) { return m_nShape; }
double MinEdgeLength (void);
bool GetEdgeVertices (short nSide, short nLine, ushort& v1, ushort& v2);
ubyte OppSideVertex (short nSide, short nIndex);
void UpdateVertexIdIndex (ubyte nIndex);
void ShiftVertices (short nSide);
CVertex& ComputeCenter (bool bView = false);
CVertex& ComputeCenter (short nSide);
inline CVertex& ComputeCenter (CSide* pSide) { return ComputeCenter (SideIndex (pSide)); }
void ComputeNormals (short nSide, bool bView = false);
void UpdateTexCoords (ushort nVertexId, bool bMove, short nIgnoreSide = -1);
short IsSelected (CRect& viewport, long xMouse, long yMouse, short nSide, bool bSegments);
short Edge (short nSide, ushort v1, ushort v2);
void MakeCoplanar (short nSide);
CSegment () : CGameItem (itSegment) {}
private:
ubyte ReadWalls (CFileManager* fp);
ubyte WriteWalls (CFileManager* fp);
};
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
typedef struct tProducer {
int objFlags [2]; // Up to 32 different Descent 1 robots
int hitPoints; // How hard it is to destroy this particular matcen
int interval; // Interval between materializations
short nSegment; // Segment this is attached to.
short nProducer; // Index in PRODUCER array.
} tProducer;
// -----------------------------------------------------------------------------
class CObjectProducer : public CGameItem {
public:
tProducer m_info;
void Read (CFileManager* fp, bool bFlag = false);
void Write (CFileManager* fp, bool bFlag = false);
void Setup (short nSegment, short nIndex, int nFlags) {
Clear ();
m_info.nSegment = nSegment;
m_info.objFlags [0] = nFlags;
m_info.nProducer = nIndex;
};
inline tProducer& Info (void) { return m_info; }
virtual void Clear (void) { memset (&m_info, 0, sizeof (m_info)); }
virtual CGameItem* Clone (void);
virtual void Backup (eEditType editType = opModify);
virtual CGameItem* Copy (CGameItem* pDest);
inline bool operator< (CObjectProducer& other) { return m_info.nSegment < other.m_info.nSegment; }
inline bool operator> (CObjectProducer& other) { return m_info.nSegment > other.m_info.nSegment; }
inline CObjectProducer& operator= (CObjectProducer& other) {
m_info = other.m_info;
return *this;
}
//virtual void Undo (void);
//virtual void Redo (void);
};
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
#endif //__segment_h | 31.517857 | 141 | 0.637313 | [
"object",
"shape"
] |
e078a780f00634a788c03d94f1554fba054d6540 | 634 | h | C | Angel/Infrastructure/DebugDraw.h | Tifox/Grog-Knight | 377a661286cda7ee3b2b2d0099641897938c2f8f | [
"Apache-2.0"
] | 171 | 2015-01-08T10:35:56.000Z | 2021-07-03T12:35:10.000Z | Angel/Infrastructure/DebugDraw.h | Tifox/Grog-Knight | 377a661286cda7ee3b2b2d0099641897938c2f8f | [
"Apache-2.0"
] | 11 | 2015-01-30T05:30:54.000Z | 2017-04-08T23:34:33.000Z | Angel/Infrastructure/DebugDraw.h | Tifox/Grog-Knight | 377a661286cda7ee3b2b2d0099641897938c2f8f | [
"Apache-2.0"
] | 59 | 2015-02-01T03:43:00.000Z | 2020-12-01T02:08:57.000Z | #include "Vector2.h"
/* abstract */ class DebugDrawBase
{
protected:
friend class World;
virtual ~DebugDrawBase() {}
virtual void Draw() = 0;
void SetupDraw()
{
glColor4f( _color.R, _color.G, _color.B, _color.A );
}
float _timeRemaining;
bool _bPermanent;
Color _color;
};
class DebugLine : public DebugDrawBase
{
protected:
friend class World;
virtual void Draw()
{
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(2, GL_FLOAT, 0, _points);
glDrawArrays(GL_LINES, 0, 2);
}
float _points[4];
};
typedef std::vector< DebugDrawBase* >::iterator DebugDrawIterator;
| 17.135135 | 68 | 0.670347 | [
"vector"
] |
e0851eaf02dace293abead6be76b6fcc600d0068 | 10,184 | h | C | src/include/core/pack/pack.h | amit1144576/Advance-Database-Systems-Memory-Pooling | 2e52f8f4d983903292fe7e01f00d0845a3bdfad7 | [
"MIT"
] | 2 | 2019-06-11T14:05:58.000Z | 2019-06-11T14:25:45.000Z | src/include/core/pack/pack.h | RAO-29/SG-1-Memory-Pooling | 2e52f8f4d983903292fe7e01f00d0845a3bdfad7 | [
"MIT"
] | null | null | null | src/include/core/pack/pack.h | RAO-29/SG-1-Memory-Pooling | 2e52f8f4d983903292fe7e01f00d0845a3bdfad7 | [
"MIT"
] | null | null | null | /**
* Copyright 2018 Marcus Pinnecke
*
* 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 NG5_ARCHIVE_COMPR_H
#define NG5_ARCHIVE_COMPR_H
#include "core/pack/pack_none.h"
#include "core/pack/huffman.h"
#include "coding/coding_huffman.h"
#include "shared/common.h"
#include "shared/types.h"
NG5_BEGIN_DECL
/**
* Unique tag identifying a specific implementation for compressing/decompressing string in a CARBON archives
* string table.
*/
enum packer_type {
PACK_NONE, PACK_HUFFMAN
};
/**
* Main interface for the compressor framework. A compressor is used to encode/decode strings stored in a
* CARBON archive.
*/
struct packer {
/** Tag identifying the implementation of this compressor */
enum packer_type tag;
/** Implementation-specific storage */
void *extra;
/**
* Constructor for implementation-dependent initialization of the compressor at hand.
*
* Depending on the implementation, the compressor might allocate dynamic memory for
* <code>extra</code> for book-keeping purposes.
*
* @param self A pointer to itself
* @return <b>true</b> in case of success, or <b>false</b> otherwise.
*
* @author Marcus Pinnecke
* @since 0.1.00.05
*/
bool (*create)(struct packer *self);
/**
* Destructor for implementation-dependent deinitialization of the compressor at hand.
*
* If the implementation acquired dynamic memory during a call to <code>create</code>,
* a call to this function frees up this memory.
*
* @param self A pointer to itself
* @return <b>true</b> in case of success, or <b>false</b> otherwise.
*
* @author Marcus Pinnecke
* @since 0.1.00.05
*/
bool (*drop)(struct packer *self);
/**
* Perform a hard-copy of this compressor to dst
*
* @param self A pointer to itself
* @param dst A pointer to the copy target
*
* @return <b>true</b> in case of success, or <b>false</b> otherwise.
*
* @author Marcus Pinnecke
* @since 0.1.00.05
*/
bool (*cpy)(const struct packer *self, struct packer *dst);
/**
* Function to construct and serialize an implementation-specific dictionary, book-keeping data, or extra data
* (e.g., a code table)
*
* Depending on the implementation, a set of book-keeping data must be managed for a compressor. For instance,
* in case of a huffman encoded this book-keeping is the code table that maps letters to prefix codes. This
* function is invoked before any string gets encoded, and implements a compressor-specific management and
* serialization of that book-keeping data. After internal construction of this book-keeping data,
* this data is serialized into the <code>dst</code> parameter.
*
* Reverse function of <code>read_extra</code>.
*
* @note single strings must not be encoded; this is is done when the framework invokes <code>encode_string</code>
*
* @param self A pointer to the compressor that is used; maybe accesses <code>extra</code>
* @param dst A memory file in which the book-keeping data (<code>extra</code>) for this compressor is serialized
* @param strings The set of all strings that should be encoded. Used for tweaking the compressor;
* <b>not</b> for serialization into <code>dst</code>
*
* @note strings in <code>strings</code> are unique (but not sorted)
*
* @author Marcus Pinnecke
* @since 0.1.00.05
* */
bool (*write_extra)(struct packer *self, struct memfile *dst,
const struct vector ofType (const char *) *strings);
/**
* Function to reconstruct implementation-specific dictionary, book-keeping or extra data by deserialization (
* e.g., a code table)
*
* Reverse function of <code>write_extra</code>.
*
* @param self A pointer to the compressor that is used; maybe accesses <code>extra</code>
* @param src A file where the cursor is moved to the first byte of the extra field previously serialized with 'write_extra'
* @param nbytes Number of bytes written when 'write_extra' was called. Intended to read read to restore the extra field.
* @return The implementer must return <code>true</code> on success, and <code>false</code> otherwise.
*/
bool (*read_extra)(struct packer *self, FILE *src, size_t nbytes);
/**
* Encodes an input string and writes its encoded version into a memory file.
*
* @param self A pointer to the compressor that is used; maybe accesses <code>extra</code>
* @param dst A memory file in which the encoded string should be stored
* @param err An error information
* @param string The string that should be encoded
*
* @return <b>true</b> in case of success, or <b>false</b> otherwise.
*
* @author Marcus Pinnecke
* @since 0.1.00.05
*/
bool (*encode_string)(struct packer *self, struct memfile *dst, struct err *err, const char *string);
bool (*decode_string)(struct packer *self, char *dst, size_t strlen, FILE *src);
/**
* Reads implementation-specific book-keeping, meta or extra data from the input memory file and
* prints its contents in a human-readable version to <code>file</code>
*
* @param self A pointer to the compressor that is used; potentially accessing <code>extra</code>
* @param file A file to which a human-readable version of <code>extra</code> is printed (if any)
* @param src A memory file which cursor is positioned at the begin of the serialized extra field. After
* a call to this function, the memory file cursor must be positioned after the serialized extra
* field (i.e., the entire entry must be read (if any))
*
* @return <b>true</b> in case of success, or <b>false</b> otherwise.
*
* @author Marcus Pinnecke
* @since 0.1.00.05
*/
bool (*print_extra)(struct packer *self, FILE *file, struct memfile *src);
/**
* Reads an implementation-specific encoded string from a memory file <code>src</code>, and prints
* the encoded string in a human-readable version to <code>file</code>
*
* @param self A pointer to the compressor that is used; potentially accessing <code>extra</code>
* @param file A file to which a human-readable version of the encoded string is printed.
* @param src A memory file which cursor is positioned at the begin of the encoded string. After a call
* to this function, the memory file cursor must be positioned after the encoded string (i.e.,
* the entire encoded string must be read)
* @param decompressed_strlen The length of the decoded string in number of characters
*
* @return <b>true</b> in case of success, or <b>false</b> otherwise.
*
* @author Marcus Pinnecke
* @since 0.1.00.05
*/
bool (*print_encoded)(struct packer *self, FILE *file, struct memfile *src, u32 decompressed_strlen);
};
NG5_EXPORT(void) pack_none_create(struct packer *strategy);
NG5_EXPORT(void) pack_huffman_create(struct packer *strategy);
extern struct compressor_strategy_entry {
enum packer_type type;
const char *name;
void (*create)(struct packer *strategy);
u8 flag_bit;
} compressor_strategy_register[];
NG5_EXPORT(size_t) pack_get_num_registered_strategies();
NG5_EXPORT(bool) pack_by_type(struct err *err, struct packer *strategy, enum packer_type type);
NG5_EXPORT(u8) pack_flagbit_by_type(enum packer_type type);
NG5_EXPORT(bool) pack_by_flags(struct packer *strategy, u8 flags);
NG5_EXPORT(bool) pack_by_name(enum packer_type *type, const char *name);
NG5_EXPORT(bool) pack_cpy(struct err *err, struct packer *dst, const struct packer *src);
NG5_EXPORT(bool) pack_drop(struct err *err, struct packer *self);
NG5_EXPORT(bool) pack_write_extra(struct err *err, struct packer *self, struct memfile *dst,
const struct vector ofType (const char *) *strings);
NG5_EXPORT(bool) pack_read_extra(struct err *err, struct packer *self, FILE *src, size_t nbytes);
NG5_EXPORT(bool) pack_encode(struct err *err, struct packer *self, struct memfile *dst, const char *string);
NG5_EXPORT(bool) pack_decode(struct err *err, struct packer *self, char *dst, size_t strlen, FILE *src);
NG5_EXPORT(bool) pack_print_extra(struct err *err, struct packer *self, FILE *file, struct memfile *src);
NG5_EXPORT(bool) pack_print_encoded(struct err *err, struct packer *self, FILE *file, struct memfile *src,
u32 decompressed_strlen);
NG5_END_DECL
#endif
| 44.666667 | 132 | 0.660841 | [
"vector"
] |
e0a41953b231edc76003e633fa4e732d3d6b8c01 | 2,303 | h | C | libvmaf/src/model.h | quink-black/vmaf | 067c423209721d80183ef19934383028b7687915 | [
"BSD-2-Clause-Patent"
] | 2,874 | 2016-06-06T16:11:37.000Z | 2022-03-31T10:10:22.000Z | libvmaf/src/model.h | REO-RAO/vmaf | e768a2be57116c76bf33be7f8ee3566d8b774664 | [
"BSD-2-Clause-Patent"
] | 619 | 2016-06-07T19:30:53.000Z | 2022-03-31T16:36:05.000Z | libvmaf/src/model.h | REO-RAO/vmaf | e768a2be57116c76bf33be7f8ee3566d8b774664 | [
"BSD-2-Clause-Patent"
] | 723 | 2016-06-05T02:44:33.000Z | 2022-03-31T03:29:12.000Z | /**
*
* Copyright 2016-2020 Netflix, Inc.
*
* Licensed under the BSD+Patent 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://opensource.org/licenses/BSDplusPatent
*
* 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 __VMAF_SRC_MODEL_H__
#define __VMAF_SRC_MODEL_H__
#include <stdbool.h>
#include "dict.h"
#include "libvmaf/model.h"
enum VmafModelType {
VMAF_MODEL_TYPE_UNKNOWN = 0,
VMAF_MODEL_TYPE_SVM_NUSVR,
VMAF_MODEL_BOOTSTRAP_SVM_NUSVR,
VMAF_MODEL_RESIDUE_BOOTSTRAP_SVM_NUSVR,
};
enum VmafModelNormalizationType {
VMAF_MODEL_NORMALIZATION_TYPE_UNKNOWN = 0,
VMAF_MODEL_NORMALIZATION_TYPE_NONE,
VMAF_MODEL_NORMALIZATION_TYPE_LINEAR_RESCALE,
};
typedef struct {
char *name;
double slope, intercept;
VmafDictionary *opts_dict;
} VmafModelFeature;
typedef struct {
double x;
double y;
} VmafPoint;
typedef struct VmafModel {
char *path;
char *name;
enum VmafModelType type;
double slope, intercept;
VmafModelFeature *feature;
unsigned n_features;
struct {
bool enabled;
double min, max;
} score_clip;
enum VmafModelNormalizationType norm_type;
struct {
bool enabled;
struct {
bool enabled;
double value;
} p0, p1, p2;
struct {
bool enabled;
VmafPoint *list;
unsigned n_knots;
} knots;
bool out_lte_in, out_gte_in;
} score_transform;
struct svm_model *svm;
} VmafModel;
typedef struct VmafModelCollection {
VmafModel **model;
unsigned cnt, size;
enum VmafModelType type;
const char *name;
} VmafModelCollection;
char *vmaf_model_generate_name(VmafModelConfig *cfg);
int vmaf_model_collection_append(VmafModelCollection **model_collection,
VmafModel *model);
#endif /* __VMAF_SRC_MODEL_H__ */
| 25.032609 | 79 | 0.680851 | [
"model"
] |
e0a72832c7b1d1a1411314ddcc2003e334ebae74 | 10,024 | h | C | src/cpp/SPL/CodeGen/Literal.h | IBMStreams/OSStreams | c6287bd9ec4323f567d2faf59125baba8604e1db | [
"Apache-2.0"
] | 10 | 2021-02-19T20:19:24.000Z | 2021-09-16T05:11:50.000Z | src/cpp/SPL/CodeGen/Literal.h | xguerin/openstreams | 7000370b81a7f8778db283b2ba9f9ead984b7439 | [
"Apache-2.0"
] | 7 | 2021-02-20T01:17:12.000Z | 2021-06-08T14:56:34.000Z | src/cpp/SPL/CodeGen/Literal.h | IBMStreams/OSStreams | c6287bd9ec4323f567d2faf59125baba8604e1db | [
"Apache-2.0"
] | 4 | 2021-02-19T18:43:10.000Z | 2022-02-23T14:18:16.000Z | /*
* Copyright 2021 IBM Corporation
*
* 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 LITERAL_H
#define LITERAL_H
#include <UTILS/HashMapHelpers.h>
#include <string>
#include <vector>
namespace SPL {
class Expression;
class ExpressionValue;
class RootTyp;
class FunctionHeadSym;
class LiteralReplacer;
//! Hold Literals at compile time
class Literal
{
public:
enum Kind
{
Invalid, //!< <not a valid kind>
Primitive, //!< int/float/decimal/rstring/etc.
Expn, //!< non-constant int/float/decimal/rstring/etc.
List, //!< [ literal,* ]
Set, //!< { literal,* }
Map, //!< { (literal : literal),* }
Tuple, //!< { (id = literal),* }
XML, //!< "<doc><a/></doc>"x
Nul //!< null
};
struct MapLiteral
{
Literal* _key;
Literal* _value;
};
struct TupleLiteral
{
std::string _id;
Literal* _value;
};
/// Constructor (can't hold a value)
Literal();
/// Constructor
/// @param type of literal primitive/list/set/map/tuple
/// _kind is set from type
/// @param v Value of literal if primitive
Literal(const RootTyp& type, const ExpressionValue* v);
/// Constructor
/// @param type of literal primitive/list/set/map/tuple
/// _kind is set from type
/// @param varType Type if variable this literal would initialize
/// @param v Value of literal if primitive
Literal(const RootTyp& type, const RootTyp& varType, const ExpressionValue* v);
/// Constructor
/// @param type of literal primitive/list/set/map/tuple
/// _kind is set from type
/// @param varType Type if variable this literal would initialize
/// @param v Value of literal if primitive
/// @param enumValueName For converted enum values, the string name of the enum value
Literal(const RootTyp& type, const ExpressionValue* v, const std::string& enumValueName);
/// Copy Constructor
/// @param rhs Literal to copy
Literal(const Literal& rhs);
/// Constructor
/// @param exp an expression
Literal(Expression& exp);
/// Destructor
~Literal();
/// Assignment Operator
/// @param rhs Literal to assign
/// @return updated literal (this)
Literal& operator=(const Literal& rhs);
/// Return the kind of the literal
/// @return kind
Kind getKind() const { return _kind; }
/// Return the type of the literal
/// @return type
const RootTyp& getType() const { return (NULL != _varType) ? *_varType : *_type; }
/// Return the type of variable this literal is assiciated with
/// Generally this would be the same as _type, T, unless the the type is optional<T>
const RootTyp& getVarType() const { return *_varType; }
/// Add a literal to a list
/// @pre getKind() == List
/// @param l literal
void addListElement(Literal& l);
/// Add a literal to a set
/// @pre getKind() == Set
/// @param l literal
/// @return 'true' if literal already present in the set
bool addSetElement(Literal& l);
/// Add a literal pair to a map
/// @pre getKind() == Map
/// @param k key
/// @param v value
/// @return 'true' if key already present in the set (Literal unchanged)
bool addMapElement(Literal& k, Literal& v);
/// Add a literal pair to a tuple
/// @pre getKind() == Tuple
/// @param k id
/// @param v value
/// @return 'true' if key already present in the set (Literal unchanged)
bool addTupleElement(const std::string& k, Literal& v);
/// Return the number of elements in a composite literal
/// @pre getKind() != Primitive
/// @return number of elements
uint32_t numElements() const;
/// Return Value of a primitive
/// @pre getKind() == Primitive
/// @return value
const ExpressionValue& primitive() const;
/// Return Value of an expression
/// @pre getKind() == Expn
/// @return value
const Expression& expression() const;
/// Return Value of an expression
/// @pre getKind() == Expn
/// @return value
Expression& expression();
/// Return the i-th of element of a set/list
/// @pre getKind() == List || getKind() == Set
/// @pre i < numberOfElements()
/// @param i element number
/// @return The i-th literal in the list/set
const Literal& listSetElement(uint32_t i) const;
/// Return the i-th of element of a set/list
/// @pre getKind() == List || getKind() == Set
/// @pre i < numberOfElements()
/// @param i element number
/// @return The i-th literal in the list/set
Literal& listSetElement(uint32_t i);
/// Return the i-th of element of a map
/// @pre getKind() == Map
/// @pre i < numberOfElements()
/// @param i element number
/// @return The i-th literal in the list/set
const MapLiteral& mapElement(uint32_t i) const;
/// Return the i-th of element of a map
/// @pre getKind() == Map
/// @pre i < numberOfElements()
/// @param i element number
/// @return The i-th literal in the list/set
MapLiteral& mapElement(uint32_t i);
/// Return the i-th of element of a tuple
/// @pre getKind() == Tuple
/// @pre i < numberOfElements()
/// @param i element number
/// @return The i-th literal in the tuple
const TupleLiteral& tupleElement(uint32_t i) const;
/// Return the i-th of element of a tuple
/// @pre getKind() == Tuple
/// @pre i < numberOfElements()
/// @param i element number
/// @return The i-th literal in the tuple
TupleLiteral& tupleElement(uint32_t i);
/// Compare two Literals for Equality
/// @param rhs Literal to compare to
/// @return true if identical
bool operator==(const Literal& rhs) const;
/// Compare two Literals for Inequality
/// @param rhs Literal to compare to
/// @return true if not identical
bool operator!=(const Literal& rhs) const { return !((*this) == rhs); }
/// Compare two Literals for Greater Than
/// @param rhs Literal to compare to
/// @return true *this > rhs
bool operator>(const Literal& rhs) const;
/// Clone a literal
/// @return a copy of the literal
Literal& clone() const;
/// Generate C++ for a primitive value
/// @param ostr stream to generate code on
/// @param justInitializer 'true' if just the initializer expression is to be generated
/// @param genTemplate Generate a template for C++ code for SPL expression tree
void generate(std::ostream& ostr, bool justInitializer, bool genTemplate = false) const;
/// Does this literal contain only compile time evaluatable values?
/// @return 'false' if it contains a runtime literal, otherwise 'true'
bool compileTimeEvaluatable() const;
/// Does this literal contain expressions with side effects?
/// @return 'true' if it contains an expression with side effects,
/// otherwise 'false'
bool hasSideEffects(void) const;
/// Does this literal contain expressions that read state
/// @return 'true' if it contains an expression that read state, otherwise false
bool readsState() const;
/// Does this literal contain composite literals with no members?
/// @return 'true' if it contains composite literals with no members?
/// otherwise 'false'
bool hasEmptyCompositeLiterals(void) const;
/// Return the name of an enum value (if any)
/// @return string name of the enum value, or NULL if not derived from an enum
const std::string* enumValueName() const;
/// Collect Type and Function Information
/// @param types if non-NULL, named types will be added
/// @param fcns if non-NULL, referenced functions will be added
/// @param inFcns if true, walk into referenced functions
void collectTypeAndFunctions(std::tr1::unordered_set<const RootTyp*>* types,
std::tr1::unordered_set<const FunctionHeadSym*>* fcns,
bool inFcns) const;
/// Replace Literals in an expression literal
/// @param lit Literal Replacer to be used
/// @return existing literal, or new literal with new expression
Literal* replaceLits(LiteralReplacer& lit);
/// Is this an empty tuple literal?
/// @return 'true' if this is tuple literal with no fields
bool emptyTupleLiteral() const { return _kind == Tuple && _tuple->empty(); }
// @return true if this literal is allowed to have its code moved for optimization
bool shouldAllowBackwardsCodeMotion() const;
private:
Literal(const RootTyp& type, const RootTyp* varType, Expression& exp);
Kind _kind; // What we represent - derived from _type
const RootTyp* _type; // SPL type of the literal
const RootTyp* _varType; // SPL type of the variable for this literal
union
{
Expression* _expn;
const ExpressionValue* _primitives;
std::vector<Literal*>* _listSet;
std::vector<MapLiteral>* _map;
std::vector<TupleLiteral>* _tuple;
};
void initialize(const ExpressionValue* v);
static std::tr1::unordered_map<const Literal*, std::string> _enumMap;
inline void destroy();
inline void copy(const Literal& rhs);
};
std::ostream& operator<<(std::ostream& ostr, const Literal& v);
std::ostream& operator<<(std::ostream& ostr, Literal::Kind v);
};
#endif /* LITERAL_H */
| 34.328767 | 93 | 0.639366 | [
"vector"
] |
6d6daec373fb8d45604b124704b3bad215c5dc0c | 144,472 | c | C | pkg/kernelcache/ref/joker.c | CrackerCat/ipsw | 94af9fb4012d8c31bdefddf7f400cf8a9588fd5f | [
"MIT"
] | 566 | 2018-10-08T03:19:13.000Z | 2022-03-31T11:57:46.000Z | pkg/kernelcache/ref/joker.c | CrackerCat/ipsw | 94af9fb4012d8c31bdefddf7f400cf8a9588fd5f | [
"MIT"
] | 83 | 2018-12-04T00:16:41.000Z | 2022-03-30T22:59:00.000Z | pkg/kernelcache/ref/joker.c | CrackerCat/ipsw | 94af9fb4012d8c31bdefddf7f400cf8a9588fd5f | [
"MIT"
] | 58 | 2018-10-14T15:07:43.000Z | 2022-03-25T18:58:25.000Z | /**
*
* A relatively simple program to home in on XNU's system call table.
* Coded specifically for iOS kernels, but works just as well on OS X.
* Seeks XNU version string and signature of beginning of system call table.
* Then dumps all system calls. Can work on the kernel proper, or the kernel cache.
*
* System call names auto-generated from iOS's <sys/syscall.h>
* (/Developer/Platforms/iPhoneOS.platform/DeviceSupport/Latest/Symbols/usr/include/sys)
*
* can also be generated from OS X's <sys/syscall.h>, with minor tweaks (e.g. include
* ledger, pid_shutdown_sockets, etc..)
*
* Note, that just because a syscall is present, doesn't imply it's implemented -
* System calls can either point to nosys, or can be stubs returning an error code,
* as is the case with audit syscalls (350-359), among others.
*
* Tested on iOS 2.0 through 9.3
*
* 03/20/14: Updated to dump sysctls, code cleaned, more messy code added
*
* 01/08/16: v2.0: dumps 64-bit, jtool companion file support
* v2.1: dumps MIG tables
* 01/16/16:
* ---------
* This tool has been around for years, and I'm happy to know it helped people.
* It does not promote piracy in any way, form, or manner.
*
* What it DOES promote, PROUDLY, is jailbreaking, and kernel research, in the
* hands of the many, not the elitist, condescending little idiot that @i0n1c is.
*
* And if you have a problem with that, then tough.
*
* 03/17/16: v2.3b: symbolicates kext callouts, better resilience on bad Mach-O headers
*
* 06/16/16: And now that Apple decrypts its kernelcaches, this tool has become
* even more useful!
*
* 05/03/16: v2.3.1: correctly gets all kext names!
* 05/27/16: Tight machlib integration, symbolicates by auto-disassembly with callbacks :-)
*
* 06/16/16 v3b2 (Hatsune): Allowed method switch, Fixed ID= in kexts, now handles 10b2
* segment split kexts!
*
* 08/06/16: cykey fix (no crash on 32-bit), beta 3 with kpp finding
* v2.2.1: kextracts
*
*
* 08/21/16 v3b6 (Hatsune): Split kexts correctly reassembled. Symbolication needs to be fixed, though..
*
* 09/01/16 v3b8 (Hatsune): Got symbolication working, too
*
* 09/08/16 v3.0.1: Got Sandbox collections kind of working, and can now operate on complzss directly
*
*
*
* Coded by Jonathan Levin (a.k.a @Morpheus______), http://newosxbook.com
*
**/
#include <sys/mman.h> // For mmap(2)
#include <sys/stat.h> // For stat(2)
#include <unistd.h> // For everything else
#include <fcntl.h> // O_RDONLY
#include <stdio.h> // printf!
#include <string.h> // strstr..
#ifndef LINUX
#include <CoreFoundation/CoreFoundation.h>
#else
typedef unsigned char u_int8_t;
typedef unsigned int u_int32_t;
typedef unsigned long uint64_t;
typedef unsigned int uint32_t;
#define strnstr(a, b, c) strstr(a, b)
#endif
static int is64 = 0;
static int wantJToolOut = 0;
#define HAVE_LZSS
#ifdef HAVE_LZSS
#include "lzss.c"
#endif
// Mac Policy support
struct mac_policy_conf_64
{
uint64_t mpc_name; /** policy name */
uint64_t mpc_fullname; /** full name */
uint64_t mpc_labelnames; /** managed label namespaces */
uint64_t mpc_labelname_count; /** number of managed label namespaces */
uint64_t mpc_ops; /** operation vector */
uint64_t mpc_loadtime_flags; /** load time flags */
uint64_t mpc_field_off; /** label slot */
uint64_t mpc_runtime_flags; /** run time flags */
uint64_t mpc_list; /** List reference */
uint64_t mpc_data; /** module data */
}; // _mac_policy_conf_64
struct mac_policy_conf_32
{
uint32_t mpc_name; /** policy name */
uint32_t mpc_fullname; /** full name */
uint32_t mpc_labelnames; /** managed label namespaces */
uint32_t mpc_labelname_count; /** number of managed label namespaces */
uint32_t mpc_ops; /** operation vector */
uint32_t mpc_loadtime_flags; /** load time flags */
uint32_t mpc_field_off; /** label slot */
uint32_t mpc_runtime_flags; /** run time flags */
uint32_t mpc_list; /** List reference */
uint32_t mpc_data; /** module data */
}; // _mac_policy_conf_32
char *mac_policy_ops_names[] = {
//"mpo_audit_check_postselect",
"mpo_audit_check_preselect",
"mpo_audit_check_preselect",
"mpo_bpfdesc_label_associate",
"mpo_bpfdesc_label_destroy",
"mpo_bpfdesc_label_init",
"mpo_bpfdesc_check_receive",
"mpo_cred_check_label_update_execve",
"mpo_cred_check_label_update",
"mpo_cred_check_visible",
"mpo_cred_label_associate_fork",
"mpo_cred_label_associate_kernel",
"mpo_cred_label_associate",
"mpo_cred_label_associate_user",
"mpo_cred_label_destroy",
"mpo_cred_label_externalize_audit",
"mpo_cred_label_externalize",
"mpo_cred_label_init",
"mpo_cred_label_internalize",
"mpo_cred_label_update_execve",
"mpo_cred_label_update",
"mpo_devfs_label_associate_device",
"mpo_devfs_label_associate_directory",
"mpo_devfs_label_copy",
"mpo_devfs_label_destroy",
"mpo_devfs_label_init",
"mpo_devfs_label_update",
"mpo_file_check_change_offset",
"mpo_file_check_create",
"mpo_file_check_dup",
"mpo_file_check_fcntl",
"mpo_file_check_get_offset",
"mpo_file_check_get",
"mpo_file_check_inherit",
"mpo_file_check_ioctl",
"mpo_file_check_lock",
"mpo_file_check_mmap_downgrade",
"mpo_file_check_mmap",
"mpo_file_check_receive",
"mpo_file_check_set",
"mpo_file_label_init",
"mpo_file_label_destroy",
"mpo_file_label_associate",
"mpo_ifnet_check_label_update",
"mpo_ifnet_check",
"mpo_ifnet_label_associate",
"mpo_ifnet_label_copy",
"mpo_ifnet_label_destroy",
"mpo_ifnet_label_externalize",
"mpo_ifnet_label_init",
"mpo_ifnet_label_internalize",
"mpo_ifnet_label_update",
"mpo_ifnet_label_recycle",
"mpo_inpcb_check_deliver",
"mpo_inpcb_label_associate",
"mpo_inpcb_label_destroy",
"mpo_inpcb_label_init",
"mpo_inpcb_label_recycle",
"mpo_inpcb_label_update",
"mpo_iokit_check_device",
"mpo_ipq_label_associate",
"mpo_ipq_label_compare",
"mpo_ipq_label_destroy",
"mpo_ipq_label_init",
"mpo_ipq_label_update",
"mpo_reserved1_hook",
"mpo_reserved2_hook",
"mpo_reserved3_hook",
"mpo_reserved4_hook",
"mpo_reserved5_hook",
"mpo_reserved6_hook",
"mpo_reserved7_hook",
"mpo_reserved8_hook",
"mpo_reserved9_hook",
"mpo_mbuf_label_associate_bpfdesc",
"mpo_mbuf_label_associate_ifnet",
"mpo_mbuf_label_associate_inpcb",
"mpo_mbuf_label_associate_ipq",
"mpo_mbuf_label_associate_linklayer",
"mpo_mbuf_label_associate_multicast_encap",
"mpo_mbuf_label_associate_netlayer",
"mpo_mbuf_label_associate_socket",
"mpo_mbuf_label_copy",
"mpo_mbuf_label_destroy",
"mpo_mbuf_label_init",
"mpo_mount_check_fsctl",
"mpo_mount_check_getattr",
"mpo_mount_check_label_update",
"mpo_mount_check_mount",
"mpo_mount_check_remount",
"mpo_mount_check_setattr",
"mpo_mount_check_stat",
"mpo_mount_check_umount",
"mpo_mount_label_associate",
"mpo_mount_label_destroy",
"mpo_mount_label_externalize",
"mpo_mount_label_init",
"mpo_mount_label_internalize",
"mpo_netinet_fragment",
"mpo_netinet_icmp_reply",
"mpo_netinet",
"mpo_pipe_check_ioctl",
"mpo_pipe_check_kqfilter",
"mpo_pipe_check_label_update",
"mpo_pipe_check_read",
"mpo_pipe_check_select",
"mpo_pipe_check_stat",
"mpo_pipe_check_write",
"mpo_pipe_label_associate",
"mpo_pipe_label_copy",
"mpo_pipe_label_destroy",
"mpo_pipe_label_externalize",
"mpo_pipe_label_init",
"mpo_pipe_label_internalize",
"mpo_pipe_label_update",
"mpo_policy_destroy",
"mpo_policy_init",
"mpo_policy_initbsd",
"mpo_policy_syscall",
"mpo_system_check_sysctlbyname",
"mpo_proc_check_inherit_ipc_ports",
"mpo_vnode_check_rename",
"mpo_kext_check_query",
"mpo_iokit_check_nvram_get",
"mpo_iokit_check_nvram_set",
"mpo_iokit_check_nvram_delete",
"mpo_proc_check_expose",
"mpo_proc_check_set_host_special_port",
"mpo_proc_check_set_host_exception_port",
"mpo_reserved10_hook",
"mpo_reserved11_hook",
"mpo_reserved12_hook",
"mpo_reserved13_hook",
"mpo_reserved14_hook",
"mpo_reserved15_hook",
"mpo_reserved16_hook",
"mpo_reserved17_hook",
"mpo_reserved18_hook",
"mpo_reserved19_hook",
"mpo_reserved20_hook",
"mpo_reserved21_hook",
"mpo_posixsem_check_create",
"mpo_posixsem_check_open",
"mpo_posixsem_check_post",
"mpo_posixsem_check_unlink",
"mpo_posixsem_check_wait",
"mpo_posixsem_label_associate",
"mpo_posixsem_label_destroy",
"mpo_posixsem_label_init",
"mpo_posixshm_check_create",
"mpo_posixshm_check_mmap",
"mpo_posixshm_check_open",
"mpo_posixshm_check_stat",
"mpo_posixshm_check",
"mpo_posixshm_check_unlink",
"mpo_posixshm_label_associate",
"mpo_posixshm_label_destroy",
"mpo_posixshm_label_init",
"mpo_proc_check_debug",
"mpo_proc_check_fork",
"mpo_proc_check_get_task_name",
"mpo_proc_check_get_task",
"mpo_proc_check_getaudit",
"mpo_proc_check_getauid",
"mpo_proc_check_getlcid",
"mpo_proc_check_mprotect",
"mpo_proc_check_sched",
"mpo_proc_check_setaudit",
"mpo_proc_check_setauid",
"mpo_proc_check_setlcid",
"mpo_proc_check_signal",
"mpo_proc_check_wait",
"mpo_proc_label_destroy",
"mpo_proc_label_init",
"mpo_socket_check_accept",
"mpo_socket_check_accepted",
"mpo_socket_check_bind",
"mpo_socket_check_connect",
"mpo_socket_check_create",
"mpo_socket_check_deliver",
"mpo_socket_check_kqfilter",
"mpo_socket_check_label_update",
"mpo_socket_check_listen",
"mpo_socket_check_receive",
"mpo_socket_check_received",
"mpo_socket_check_select",
"mpo_socket_check_send",
"mpo_socket_check_stat",
"mpo_socket_check_setsockopt",
"mpo_socket_check_getsockopt",
"mpo_socket_label_associate_accept",
"mpo_socket_label_associate",
"mpo_socket_label_copy",
"mpo_socket_label_destroy",
"mpo_socket_label_externalize",
"mpo_socket_label_init",
"mpo_socket_label_internalize",
"mpo_socket_label_update",
"mpo_socketpeer_label_associate_mbuf",
"mpo_socketpeer_label_associate_socket",
"mpo_socketpeer_label_destroy",
"mpo_socketpeer_label_externalize",
"mpo_socketpeer_label_init",
"mpo_system_check_acct",
"mpo_system_check_audit",
"mpo_system_check_auditctl",
"mpo_system_check_auditon",
"mpo_system_check_host_priv",
"mpo_system_check_nfsd",
"mpo_system_check_reboot",
"mpo_system_check_settime",
"mpo_system_check_swapoff",
"mpo_system_check_swapon",
"mpo_reserved22_hook",
"mpo_sysvmsg_label_associate",
"mpo_sysvmsg_label_destroy",
"mpo_sysvmsg_label_init",
"mpo_sysvmsg_label_recycle",
"mpo_sysvmsq_check_enqueue",
"mpo_sysvmsq_check_msgrcv",
"mpo_sysvmsq_check_msgrmid",
"mpo_sysvmsq_check_msqctl",
"mpo_sysvmsq_check_msqget",
"mpo_sysvmsq_check_msqrcv",
"mpo_sysvmsq_check_msqsnd",
"mpo_sysvmsq_label_associate",
"mpo_sysvmsq_label_destroy",
"mpo_sysvmsq_label_init",
"mpo_sysvmsq_label_recycle",
"mpo_sysvsem_check_semctl",
"mpo_sysvsem_check_semget",
"mpo_sysvsem_check_semop",
"mpo_sysvsem_label_associate",
"mpo_sysvsem_label_destroy",
"mpo_sysvsem_label_init",
"mpo_sysvsem_label_recycle",
"mpo_sysvshm_check_shmat",
"mpo_sysvshm_check_shmctl",
"mpo_sysvshm_check_shmdt",
"mpo_sysvshm_check_shmget",
"mpo_sysvshm_label_associate",
"mpo_sysvshm_label_destroy",
"mpo_sysvshm_label_init",
"mpo_sysvshm_label_recycle",
"mpo_reserved23_hook",
"mpo_reserved24_hook",
"mpo_reserved25_hook",
"mpo_mount_check_snapshot_create",
"mpo_check_snapshot_delete",
"mpo_vnode_check_clone",
"mpo_proc_check_get_cs_info",
"mpo_proc_check_set_cs_info",
"mpo_iokit_check_hid_control",
"mpo_vnode_check_access",
"mpo_vnode_check_chdir",
"mpo_vnode_check_chroot",
"mpo_vnode_check_create",
"mpo_vnode_check_deleteextattr",
"mpo_vnode_check_exchangedata",
"mpo_vnode_check_exec",
"mpo_vnode_check_getattrlist",
"mpo_vnode_check_getextattr",
"mpo_vnode_check_ioctl",
"mpo_vnode_check_kqfilter",
"mpo_vnode_check_label_update",
"mpo_vnode_check_link",
"mpo_vnode_check_listextattr",
"mpo_vnode_check_lookup",
"mpo_vnode_check_open",
"mpo_vnode_check_read",
"mpo_vnode_check_readdir",
"mpo_vnode_check_readlink",
"mpo_vnode_check_rename_from",
"mpo_vnode_check_rename",
"mpo_vnode_check_revoke",
"mpo_vnode_check_select",
"mpo_vnode_check_setattrlist",
"mpo_vnode_check_setextattr",
"mpo_vnode_check_setflags",
"mpo_vnode_check_setmode",
"mpo_vnode_check_setowner",
"mpo_vnode_check_setutimes",
"mpo_vnode_check_stat",
"mpo_vnode_check",
"mpo_vnode_check_unlink",
"mpo_vnode_check_write",
"mpo_vnode_label_associate_devfs",
"mpo_vnode_label_associate_extattr",
"mpo_vnode_label_associate_file",
"mpo_vnode_label_associate_pipe",
"mpo_vnode_label_associate_posixsem",
"mpo_vnode_label_associate_posixshm",
"mpo_vnode_label_associate_singlelabel",
"mpo_vnode_label_associate_socket",
"mpo_vnode_label_copy",
"mpo_vnode_label_destroy",
"mpo_vnode_label_externalize_audit",
"mpo_vnode_label_externalize",
"mpo_vnode_label_init",
"mpo_vnode_label_internalize",
"mpo_vnode_label_recycle",
"mpo_vnode_label_store",
"mpo_vnode_label_update_extattr",
"mpo_vnode_label_update",
"mpo_vnode_notify_create",
"mpo_vnode_check_signature",
"mpo_vnode_check_uipc_bind",
"mpo_vnode_check_uipc_connect",
"mpo_proc_check_run_cs_invalid",
"mpo_proc_check_suspend_resume",
"mpo_thread_userret",
"mpo_iokit_check_set_properties",
"mpo_system_check_chud",
"mpo_vnode_check_searchfs",
"mpo_priv_check",
"mpo_priv_grant",
"mpo_proc_check_map_anon",
"mpo_vnode_check_fsgetpath",
"mpo_iokit_check_open",
"mpo_proc_check_ledger",
"mpo_vnode_notify_rename",
"mpo_vnode_check_setacl",
"mpo_system_check_kas_info",
"mpo_proc_check_cpumon",
"mpo_vnode_notify_open",
"mpo_system_check_info",
"mpo_pty_notify_grant",
"mpo_pty_notify_close",
"mpo_vnode_find_sigs",
"mpo_kext_check_load",
"mpo_kext_check_unload",
"mpo_proc_check_proc_info",
"mpo_vnode_notify_link",
"mpo_iokit_check_filter_properties",
"mpo_iokit_check_get_property",
NULL
};
#include <mach-o/loader.h> // struct mach_header
#include "machlib.h" // from jtool
#include "common.h" // from jtool
#include "companion.h" // from jtool
#include "jtoolsyms.h"
int jtoolOutFD = 0;
char *mmapped = NULL;
int xnu3757_and_later = 0;
int g_jdebug = 0;
int g_dec = 0;
uint64_t prelink_data_data_addr = 0;
uint64_t prelink_data_data_offset = 0;
uint64_t prelink_data_data_size = 0;
struct symtabent *kernelSymTable = NULL;
void register_disassembled_function_call_callback(void *Func);
char *filename = NULL;
void **segments = NULL;
typedef struct
{
char *sig;
char *name;
} kext_sig;
// 2.3 kext sigs
kext_sig KextSigs[] = {
// The Magnificent Seven can be identified by their symbols (supported in all archs :)
// plus by the fact that they have no __TEXT.__cstring
{"MD5Init", "Libkern Pseudoextension (com.apple.kpi.libkern)"},
{"lock_get_calendar_microti", "Mach Kernel Pseudoextension (com.apple.kpi.mach)"},
{"IOBSDNameMatching", "I/O Kit Pseudoextension"},
{"VNOP_BWRITE", "BSD Kernel Pseudoextension (com.apple.kpi.bsd)"},
{"ifnet_poll_params", "Private Pseudoextension (com.apple.kpi.private)"},
{"KUNCExecute", "Unsupported Pseudoextension (com.apple.kpi.unsupported)"},
{"mac_iokit_check_nvram", "MAC Framework Pseudoextension (com.apple.kpi.dsep)"},
{"com.apple.driver.AppleSynopsysMIPIDSI", "(com.apple.driver.AppleSynopsysMIPIDSI)"},
{"com.apple.nke.pptp", "(com.apple.nke.pptp)"},
{"com.apple.kec.Libm", "com.apple.kec.Libm"},
{"com.apple.driver.AppleEmbeddedAccelerometer", "(com.apple.driver.AppleEmbeddedAccelerometer)"},
{"com.apple.driver.AppleSamsungI2S", "(com.apple.driver.AppleSamsungI2S)"},
{"com.apple.driver.AppleT7000PMGR", "(com.apple.driver.AppleT7000PMGR)"},
{"com.apple.driver.AppleS5L8960XUSBEHCI", "(com.apple.driver.AppleS5L8960XUSBEHCI)"},
{"com.apple.driver.AppleT7000CLPC", "(com.apple.driver.AppleT7000CLPC)"},
{"com.apple.driver.AppleT7000", "(com.apple.driver.AppleT7000)"},
{"com.apple.driver.AppleS5L8960XUSBHSIC", "(com.apple.driver.AppleS5L8960XUSBHSIC)"},
{"com.apple.driver.AppleUSBHSIC", "(com.apple.driver.USBHSIC)"},
{"com.apple.driver.AppleUSBEHCIARM", "(com.apple.driver.AppleUSBEHCIARM)"},
{"com.apple.driver.AppleS5L8960XGPIOIC", "(com.apple.driver.AppleS5L8960XGPIOIC)"},
{"com.apple.driver.AppleInterruptController", "(com.apple.driver.AppleInterruptController)"},
{"com.apple.driver.DiskImages.ReadWriteDiskImage", "(com.apple.driver.DiskImages.ReadWriteDiskImage)"},
{"com.apple.iokit.IOMikeyBusFamily", "(com.apple.iokit.IOMikeyBusFamily)"},
{"com.apple.iokit.AppleARMIISAudio", "(com.apple.iokit.AppleARMIISAudio)"},
{"com.apple.driver.AppleEmbeddedAudio", "(com.apple.driver.AppleEmbeddedAudio)"},
{"com.apple.driver.AppleCS35L19Amp", "(com.apple.driver.AppleCS35L19Amp)"},
{"com.apple.AppleFSCompression.AppleFSCompressionTypeZlib", "(com.apple.AppleFSCompression.AppleFSCompressionTypeZlib)"},
{"com.apple.nke.l2tp", "(com.apple.nke.l2tp)"},
// Others have very unique strings
{"bsdthread_terminate", "Pthread (com.apple.kec.pthread)"},
// All the rest can be identified by their IO Objects (can't obfuscate this, AAPL.. ;-)
// or other strings (in cases where they're still chatty)
{"lzvn_decode"
"AppleFSCompressionTypeZlib (com.apple.AppleFSCompressionTypeZlib)"},
{"AppleVXD393PriorityQueue", "AppleVXD393 (com.apple.driver.AppleVXD393)"},
{"AppleS5L8940XDWI", "AppleS5L8940XDWI (com.apple.driver.AppleS5L8940XDWI)"},
{"AppleD2186PMU", "AppleD2186PMU (com.apple.driver.AppleD2186PMU)"},
{"AppleDialogPMU::", "AppleDialogPMU (com.apple.driver.AppleDialogPMU)"},
{"com_apple_driver_KeyDeliveryIOKitMSE", "LSDIOKitMSE (com.apple.driver.LSDIOKitMSE)"},
{"com_apple_driver_KeyDeliveryIOKit", "LSDIOKit (com.apple.driver.LSDIOKit)"},
{"Sandbox extension sentinel", "Seatbelt (com.apple.security.sandbox)"},
{"IOSlowAdaptiveClockingDomain", "IOSlowAdaptiveClockingFamily (com.apple.iokit.IOSlowAdaptiveClockingFamily)"},
{"AppleSEPManager::", "AppleSEPManager (com.apple.driver.AppleSEPManager)"},
{"AppleSEPKeyStore::", "AppleSEPKeyStore (com.apple.driver.AppleSEPKeyStore)"},
{"AppleOscarAsyncEventSource", "AppleOscar (com.apple.driver.AppleOscar)"},
{"IOSurface::", "IOSurface (com.apple.iokit.IOSurface)"},
{"AppleS5L8960XDART::", "AppleS5L8960XDART (com.apple.driver.AppleS5L8960XDART)"}, // 42
{"IODART::", "IODARTFamily (com.apple.driver.IODARTFamily)"},
{"IOBlockStorageDriver]:", "I/O Kit Storage Family (com.apple.iokit.IOStorageFamily)"}, // 43
{"IOHDIXControllerUserClient::", "AppleDiskImageDriver (com.apple.driver.DiskImages)"},
{"IOHDIXHDDriveInKernel", "AppleDiskImagesKernelBacked (com.apple.driver.DiskImages.KernelBacked)"}, // 45
{"KDIRAMBackingStore", "AppleDiskImagesRAMBackingStore (com.apple.driver.DiskImages.RAMBackingStore)"},
{"AppleAJPEGHal::", "AppleJPEGDriver (com.apple.driver.AppleJPEGDriver)"}, // 47
{"AppleUSBHostMergePropertie", "I/O Kit Driver for USB Devices (com.apple.driver.AppleUSBHostMergeProperties)"},
{"IOUSBDeviceConfigurator:", "IOUSBDeviceFamily (com.apple.iokit.IOUSBDeviceFamily)"},
{"ORS232SerialStreamSync", "IOKit Serial Port Family (com.apple.iokit.IOSerialFamily)"},
{"AppleOnboardSerialBSDClient:", "AppleOnboardSerial (com.apple.driver.AppleOnboardSerial)"},
{"AppleS5L8940XI2CController:", "AppleS5L8940XI2CController (com.apple.driver.AppleS5L8940XI2C)"},
{"AppleCS46L71Device", "AppleCS42L71Audio (com.apple.driver.AppleCS42L71Audio)"},
{"AppleCS46L21Device", "AppleCS42L21Audio (com.apple.driver.AppleCS42L21Audio)"},
{"IOAccessoryPrimaryDevicePort", "IOAccessoryManager (com.apple.iokit.IOAccessoryManager)"},
//AppleBasebandPCIPDPManager/com.apple.driver.AppleBasebandPCIMAVPDP AppleSSE/com.apple.driver.AppleSSE nke.tls
{"AppleSynopsysOTG3Device", "AppleSynopsysOTGDevice (com.apple.driver.AppleSynopsysOTGDevice)"},
{"CCLogStream:", "CoreCapture (com.apple.driver.CoreCapture)"},
{"CoreCaptureResponder", "CoreCaptureResponder (com.apple.driver.CoreCaptureResponder)"},
{"com_apple_driver_FairPlayIOKitUserClient", "FairPlayIOKit (com.apple.driver.FairPlayIOKit)"},
{"AppleTVIRUserClient", "AppleTVIR (com.apple.driver.AppleTVIR)"}, // TvOS
{"AppleMobileApNonce::"
"AppleMobileApNonce (com.apple.driver.AppleMobileApNonce)"},
{"AppleStorageProcessorNode", "AppleStorageProcessorNodes (com.apple.driver.ASPSupportNodes"},
{"ApplePinotLCD:", "ApplePinotLCD (com.apple.driver.ApplePinotLCD)"},
{"IOAccelDevice", "IOAcceleratorFamily (com.apple.iokit.IOAcceleratorFamily2)"},
{"AppleUSBEthernetHost::", "AppleUSBEthernetHost (com.apple.driver.AppleUSBEthernetHost"},
{"AppleIDAMInterface", "AppleIDAMInterface (com.apple.driver.AppleIDAMInterface)"},
{"com.apple.kext.tlsnke", "TLS NKE (com.apple.kext.tlsnke)"},
{"AppleSSEUserClient", "AppleSSE (com.apple.driver.AppleSSE)"},
{"AppleM2Scaler", "Apple M2 Scaler and Color Space Converter Driver (com.apple.driver.AppleM2ScalerCSCDriver)"},
{"IOStreamAudio", "IOStreamAudioFamily (com.apple.iokit.IOStreamAudioFamily)"},
{"Cyclone", "AppleCycloneErrorHandler (com.apple.driver.AppleCycloneErrorHander"},
{"IOAudio2TransformerUserClient", "IOAudio2Family (com.apple.iokit.IOAudio2Family)"},
{"IOCECUserClient::", "IOCECFamily (com.apple.iokit.IOCECFamily)"},
{"IOAVController", "IOAVFamily (com.apple.iokit.IOAVFamily)"},
{
"AppleDiagnosticDataAccessReadOnly",
"AppleDiagnosticDataAcccessReadOnly (com.apple.driver.AppleDiagnosticDataAccessReadOnly",
}, // 174
{"AppleBiometricServices", "AppleBiometricServices (com.apple.driver.AppleBiometricServices)"},
{"IOPDPPlumbers::", "AppleBasebandPCI (com.apple.driver.AppleBasebandPCI"},
{"IOMobileFramebufferUserClient::", "IOMobileGraphicsFamily (com.apple.iokit.IOMobileGraphicsFamily)"}, // 26
{"AppleMobileADBE0", "AppleH8ADBE0 (com.apple.driver.AppleH8ADBE0)"},
{"IOEthernetController:", "I/O Kit Networking Family (com.apple.iokit.IONetworkingFamily)"},
{"ApplePMGR::", "ApplePMGR (com.apple.driver.ApplePMGR)"},
{"AppleS8000PMGR:", "AppleS8000PMGR (com.apple.driver.AppleS8000PMGR)"},
{"IOPCIDevice::", "I/O Kit PCI Family (com.apple.iokit.IOPCIFamily)"},
{"AppleS800xPCIe:", "AppleS8000PCIe (com.apple.driver.AppleS8000PCIe)"}, // 35
{"AppleSPIBiometricSensor:", "AppleBiometricSensor (com.apple.driver.AppleBiometricSensor)"},
{"ProvInfo", "ProvInfoIOKit (com.apple.driver.ProvInfoIOKit)"}, // 40
{"AppleBCMWLANTimeKeeper", "AppleBCMWLANCore (com.apple.driver.driver.AppleBCMWLANCore)"},
{"AppleBCMWLANChipManagerPCIe", "AppleBCMWLANBusInterfacePCIe (com.apple.driver.driver.AppleBCMWLANBusInterfacePCIe)"},
{"AppleStockholmControlUserClient", "AppleStockholmControl (com.apple.driver.AppleStockholmControl)"},
{"AppleMesaSEPDriver", "AppleMesaSEPDriver (com.apple.driver.AppleMesaSEPDriver)"}, // also found in StockholmControl...
// Die, Die, DIE, YOU $%#$%$##$%!!!!!
{"AppleMobileFileIntegrityUser", "AppleMobileFileIntegrity (com.apple.driver.AppleMobileFileIntegrity)"},
{"AppleEmbeddedI2CLightSensor", "AppleEmbeddedLightSensor (com.apple.driver.AppleEmbeddedLightSensor)"},
// Make this T7/8/9 agnostic by looking at suffix..
{"TempSensorUserClient", "AppleEmbeddedTempSensor (com.apple.driver.AppleEmbeddedTempSensor)"},
{
"IONetworkUserClient",
"iokit.IONetworkingFamily)",
},
{"corecrypto_kext", "corecrypto (com.apple.kec.corecrypto)"},
{"IOReportFamily", "IOReportFamily (com.apple.iokit.IOReportFamily)"},
{"AppleARMCPU", "AppleARMPlatform (com.apple.driver.AppleARMPlatform)"},
{"AppleSamsungSPI", "AppleSamsungSPI (com.apple.driver.AppleSamsungSPI)"},
{"IOAESAccelerator::", "IOAESAccelerator"},
{"AppleEffaceableStorageUserClient::", "AppleEffaceableStorage (com.apple.driver.AppleEffaceableStorage)"},
{"AppleH6CamIn::", "AppleH6CamIn"},
{"AppleUSB20HubPort", "AppleUSB20HubPort"},
{"IO80211AWDLMulti", "AWDL"},
{"AppleUSBHostDevice", "AppleUSBHostDevice"},
{"KDIUDIFDiskImage", "KDIUDIFDiskImage"},
{"AppleUSBDeviceMux", "AppleUSBDeviceMux"},
{"mDNSOffloadUserClient:", "mDNSOffloadUserClient"},
{"AppleNANDConfigAccess", "AppleNANDConfigAccess"},
{"AGXFirmwareKextG4P", "AGXFirmwareKextG4P"}, // AppleTV
{"BTReset", "BlueTooth-unknown-yet"},
{"AppleS5L8920XPWM", "AppleS5L8920XPWM (com.apple.driver.AppleS5L8920XPWM)"},
{"AppleSN2400ChargerFunction", "AppleSN2400Charger (com.apple.driver.AppleSN2400Charger)"},
{"AppleIPAppenderUserClient", "AppleIPAppender (com.apple.driver.AppleIPAppender)"},
{"AppleMultitouchSPI", "AppleMultitouchSPI (com.apple.driver.AppleMultitouchSPI)"},
{"H264IOSurfaceBuf", "H264 Video Encoder (com.apple.driver.AppleAVE)"},
{"IOSlaveMemory", "IOSlaveProcessor (com.apple.driver.IOSlaveProcessor)"},
{"ApplePCIEMSIController", "ApplePCIEMSIController (com.apple.driver.AppleEmbeddedPCIE)"},
{"IOHIDLibUserClient", "IOHIDFamily (com.apple.iokit.IOHIDFamily)"},
{"AppleA7IOP", "AppleA7IOP (com.apple.driver.AppleA7IOP)"},
{NULL, NULL}};
int g_kct = 0;
char *g_kcs;
char *getKernelCacheStart(void) { return g_kcs; }
void setKernelCacheStart(char *Cache) { g_kcs = Cache; }
int getKernelCacheArch(void)
{
return g_kct;
}
void setKernelCacheArch(int Kct)
{
g_kct = Kct;
}
char *getPtr(char *mmapped, uint64_t loadAddr, uint64_t ptr)
{
if (!ptr)
return NULL;
printf("...Getting value : %p\n", ptr);
uint32_t off = 0;
char *sect = MachOGetSectionNameContainingAddress(ptr);
uint64_t addr = MachOGetSectionAddr(mmapped, sect);
if (sect)
{
off = MachOGetSectionOffset(mmapped, sect);
}
if (off)
return (mmapped + (ptr - addr) + off);
else
return 0;
}
void dumpOps(void *OpsPtr)
{
// Assuming 64 for now
int op = 0;
uint64_t *ops = (uint64_t *)OpsPtr;
while (mac_policy_ops_names[op])
{
if (ops[op])
{
if (jtoolOutFD)
{
char buf[1024];
sprintf(buf, "0x%llx:_%s\n", ops[op], mac_policy_ops_names[op]);
write(jtoolOutFD, buf, strlen(buf));
}
else
printf("\t\t0x%llx:%s (%d)\n", ops[op], mac_policy_ops_names[op], op);
}
op++;
}
if (op)
fprintf(stderr, "Dumped %d MAC Policy ops!\n", op);
return;
};
#ifndef NOSB
#define MAX_SB_OPERATION_NAMES 200 // should last until Sandbox-949, at current rate of expansion :-)
int num_sandbox_operations = 0;
int profile_size = 0;
char **sb_operation_names = NULL;
int doSandboxOperationNames(char *KextBundleHeader, char *Segment)
{
// Also Only in 64, at least for now
if (!is64)
return 0;
// Structured approach would be parsing __DATA.__const and getting the pointers to
// the strings. Faster, though, is to get the CStrings directly.
// No risk of AAPL pulling operation names - they need them in kext for sandbox_check :-)
struct section_64 *sec64TC = MachOGetSection(Segment);
if (!sec64TC)
{
fprintf(stderr, "Unable to get operation names from %s\n", Segment);
return 1;
}
char *opName = memmem(KextBundleHeader + sec64TC->offset,
sec64TC->size,
"default\0",
8);
if (!opName)
{
fprintf(stderr, "Unable to find default profile name in %s\n", Segment);
return 1;
}
// Get operation names
sb_operation_names = calloc(MAX_SB_OPERATION_NAMES, sizeof(char *));
sb_operation_names[0] = opName; // "default"
opName += (strlen(opName) + 1);
int done = 0;
int name = 0;
for (name = 1;
name < MAX_SB_OPERATION_NAMES && !done;
name++)
{
sb_operation_names[name] = opName;
if (strstr(opName, "system-swap"))
done++;
opName += (strlen(opName) + 1);
}
num_sandbox_operations = name;
profile_size = (num_sandbox_operations + 1) + 1; // this is shorts, remember!
fprintf(stderr, "Expecting profile size to be %d shorts\n", profile_size);
return 0;
};
int doSandboxProfiles(char *KextBundleHeader, char *Section)
{
// Also Only in 64, at least for now
if (!is64)
return 0;
struct section_64 *sec64TC = MachOGetSection(Section);
uint64_t addr = sec64TC->addr;
int off = sec64TC->offset;
int size = sec64TC->size;
uint64_t zeros[2] = {0};
//uint16_t *profiles = memmem(KextBundleHeader + off, size, "\x02\x00\x88\x00\x9c\x86\x00\x00", 8);
char *profiles = memmem(KextBundleHeader + off, size, zeros, 16);
profiles = memmem(profiles + 16, size, zeros, 16);
if (!profiles)
{
fprintf(stderr, "FUD! Can't get profiles.. Please tell J about it and submit a sample!\n");
return 1;
}
profiles += 16;
addr += (profiles - (KextBundleHeader + off));
// Otherwise
uint16_t numProfiles = *((uint16_t *)(profiles + 10));
uint16_t *prof = (uint16_t *)(profiles + 12); // to point to 0x869c
int done = 0;
printf("Found profiles at offset %x, vmaddr %llx\n",
profiles - KextBundleHeader, addr);
printf("Got %d (0x%x) profiles, of size %d bytes each\n", numProfiles, numProfiles, profile_size * 2);
int profNum = 0;
uint16_t *lastProf = 0;
//int profile_size = 0x85; // In XNU 37xx and later, as measured in shorts
while (profNum < numProfiles && !done)
{
char *profName = (profiles + (*prof * 8)) + 4;
if (*profName)
{
printf("Got profile:0x%03hx = %llx - ", *prof, addr + (*prof * 8));
printf("%s\n", profName);
if ((lastProf) && ((prof - lastProf) != profile_size))
{
fprintf(stderr, "Warning: Profiles are 0x%x (not 0x%hx, %d) apart\n",
(prof - lastProf), profile_size, profile_size);
}
int op = 0;
for (op = 0; op < num_sandbox_operations; op++)
{
printf("%s:%s:", profName, sb_operation_names[op]);
uint16_t first = *((uint16_t *)(profiles + (*(prof + 2 + op) * 8)));
uint16_t second = *((uint16_t *)(profiles + (*(prof + 2 + op) * 8)) + 1);
int resolved = 0;
if (first == 1)
{
if (second == 5)
{
printf("deny");
resolved++;
}
else if (second == 0)
{
printf("allow");
resolved++;
}
}
if (!resolved)
{
printf( //" *0x%llx = "
" %04hx %04hx",
//(addr + (*(prof + 2 + op) * 8)),
first, second);
if (second > 0x6400)
printf("(%llx)",
addr + (second * 8));
}
printf("\n");
}
profNum++;
lastProf = prof;
}
else
{
printf("Got Profile, but no name\n");
}
prof += profile_size;
}
#if 0
// For now, just use "AGXCompiler" as a hook
char *profiles = memmem(KextBundleHeader, size,
"\x13\x00\x00\x00\x41\x47\x58\x43",
8);
if (!profiles)
{
fprintf(stderr,"FUD! Can't get profiles.. Please tell J about it and submit a sample!\n");
return 1;
}
else fprintf(stderr,"Got it\n");
// Ok. So we have our start.
char *currProfile = profiles;
int test = 0;
for (test = 0 ; test < 1700; test ++)
{
uint32_t *len = (uint32_t *) currProfile;
char *name = (char *) (len + 1);
if (*len == 7) {currProfile += 8; continue; }
printf ("Len: %d, Name: %s\n", *len,name);
if (name[*len-1] == '\xa') { printf("OK\n");}
else printf("NOT OK %x\n", name [*len-1]);
currProfile = name + *len ;
// Need to pad to 8
uint64_t pad = 8 - (((uint64_t) currProfile) % 8);
if (pad !=8) currProfile += pad;
printf ("Next: 0x%llx\n", (currProfile - profiles));
}
#endif
return (0);
} // doSandboxProfiles
#endif // NOSB
int doPolicyOps(char *KextBundleHeader, char *Segment)
{
// Only in 64
if (!is64)
return 0;
struct section_64 *sec64TC = MachOGetSection((unsigned char *)"__TEXT.__cstring");
struct section_64 *sec64DC = MachOGetSection((unsigned char *)Segment);
int doIt = 1;
int foundPolicy = 0;
if (!sec64TC)
{
doIt = 0;
fprintf(stderr, "Unable to get __TEXT.__cstring from kext - not symbolicating\n");
};
if (!sec64DC)
{
doIt = 0;
}
if (doIt)
{
int off = sec64DC->offset;
int size = sec64DC->size;
uint64_t *lookForAMFI = (uint64_t *)(KextBundleHeader + sec64DC->offset);
int i = 0;
for (i = 0;
i < sec64DC->size / 8;
i++)
{
if (*lookForAMFI && *lookForAMFI > sec64TC->addr &&
*lookForAMFI < sec64TC->addr + sec64TC->size)
{
char *str = KextBundleHeader + sec64TC->offset + (*lookForAMFI - sec64TC->addr);
if ((strcmp(str, "AMFI") == 0) || (strcmp(str, "Sandbox") == 0))
{
fprintf(stderr, "Found policy at %p\n", sec64DC->addr + i * sizeof(uint64_t));
struct mac_policy_conf_64 *mpc64 = (struct mac_policy_conf_64 *)lookForAMFI;
printf("\tPolicy name: %s\n", getPtr(KextBundleHeader, sec64TC->addr - sec64TC->offset, mpc64->mpc_name));
// printf("\tFull name of policy: %s\n", getPtr (KextBundleHeader, sec64TC->addr - sec64TC->offset, mpc64->mpc_fullname));
printf("\tFlags: %llx\n", mpc64->mpc_loadtime_flags);
//*((uint64_t *) getPtr (KextBundleHeader, sec64TC->addr - sec64TC->offset, mpc64->mpc_ops)));
if ((mpc64->mpc_ops & 0xffffff8000000000) == 0xffffff8000000000)
{
printf("\tOps: %llx\n", mpc64->mpc_ops);
dumpOps(getPtr(KextBundleHeader, sec64DC->addr - sec64DC->offset, mpc64->mpc_ops));
}
foundPolicy++;
}
}
lookForAMFI++;
}
}
return (foundPolicy);
}
char *identifyKextNew(char *KextBundleHeader, int Size, char *KernelCache)
{
static char returned[1024];
// Look at first page of Kext header
if (Size < 0x1000)
{
return ("this kext is too small!\n");
}
// MUCH better method: look at kext's __DATA.__data.
// This is guaranteed (well, mostly :-) to contain a com.apple...
// something
// So we process header, and get section data. Then get __DATA.__data
// and isolate "com.apple.XXXXXXX"
if (g_jdebug)
fprintf(stderr, "Processing kext...\n");
segments = processFile((unsigned char *)KextBundleHeader, Size, getKernelCacheArch(), 0, 0, 0);
uint32_t __DATA__data_off = MachOGetSectionOffset((unsigned char *)KextBundleHeader, "__DATA.__data");
uint32_t __DATA__data_size = MachOGetSectionSize((unsigned char *)KextBundleHeader, "__DATA.__data");
uint32_t __DATA__CONST_const_off = MachOGetSectionOffset((unsigned char *)KextBundleHeader, "__DATA_CONST.__const");
struct source_version_command *svc = (struct source_version_command *)findLoadCommand((unsigned char *)KextBundleHeader, LC_SOURCE_VERSION, NULL);
uint32_t __DATA__CONST_const_size = 0;
if (__DATA__CONST_const_off)
{
__DATA__CONST_const_size = MachOGetSectionSize((unsigned char *)KextBundleHeader, "__DATA_CONST.__const");
if (g_jdebug)
{
fprintf(stderr, "\ngot data const of kext %d at offset %d:\n", __DATA__CONST_const_size, __DATA__CONST_const_off);
// write (2, (unsigned char *) KernelCache+ __DATA__CONST_const_off, __DATA__CONST_const_size);
}
if (svc)
{
sprintf(returned, "Unknown(%ld.%d.%d.%d.%d)",
(long)((svc->version) >> 40),
(int)(svc->version >> 30) & 0x000003FF,
(int)(svc->version >> 20) & 0x000003FF,
(int)(svc->version >> 10) & 0x000003FF,
(int)(svc->version) & 0x000003FF);
}
}
if (!__DATA__data_off || !__DATA__data_size)
{
if (g_jdebug)
{
fprintf(stderr, "Unable to find __DATA.__data (%d, %d\n",
__DATA__data_off, __DATA__data_size);
return (NULL);
}
}
else if (g_jdebug)
{
fprintf(stderr, " __DATA.__data is @0x%x, Size %d bytes, Kext Size %d bytes\n",
__DATA__data_off, __DATA__data_size, Size);
}
if (__DATA__data_size > Size)
{
fprintf(stderr, "__DATA.__data size is %d, but total kext size is %d. Something is wrong with this\n");
return (NULL);
}
char *WhereFrom = (__DATA__CONST_const_off ? KernelCache : KextBundleHeader);
char *bundle = memmem(WhereFrom + __DATA__data_off, __DATA__data_size,
"com.apple.", strlen("com.apple."));
if (g_jdebug)
{
fprintf(stderr, "\n...got data data of kext %d at offset %d:\n", __DATA__data_size, __DATA__data_off);
//
}
char *lastmatch = NULL;
//if (!bundle) { fprintf(stderr,"NO BUNDLE\n");}
//else { fprintf(stderr," SO FAR OK\n");}
while (bundle)
{
lastmatch = bundle;
if (strcmp(bundle, "com.apple.security.sandbox") == 0)
break;
if (g_jdebug)
{
printf("Match: %s\n", lastmatch);
}
bundle = memmem(lastmatch + 1, (__DATA__data_size - (lastmatch - bundle)),
"com.apple.", strlen("com.apple."));
}
char *name = lastmatch;
// Even without kextracting we can use symbols in the kext to figure
// out symbols in the kernel. This is because, even though kexts are
// prelinked, stubs remain (you going to fix this now back at cupertino? ;-)
if (name && (strstr(name, "AppleMobileFile") ||
(strstr(name, "sandbox"))))
{
// From AMFI and Sandbox we can find mac_policy_register.
// This requires a little effort: First, get the policy from __DATA.__const,
// then disassemble to find where it is passed as a first argument
// then symbolicate both the stub, and the kernel symbol
char *segName = "__DATA.__const";
xnu3757_and_later = MachOGetSection("__DATA_CONST.__const");
if (xnu3757_and_later)
{
segName = "__DATA_CONST.__const";
}
int foundPolicy = doPolicyOps(KextBundleHeader, segName);
if (!foundPolicy && !xnu3757_and_later)
{
foundPolicy = doPolicyOps(KextBundleHeader, "__DATA.__data");
if (foundPolicy)
fprintf(stderr, "Found policy in __DATA.__data\n");
}
else
{
fprintf(stderr, "Found policy in %s\n", segName);
}
if (!foundPolicy && !strstr(name, "AppleMobileFile"))
{
fprintf(stderr, "MAC policy not found. This is fine for kernels prior to iOS 9.2, but please let J know if yours is newer\n");
}
} // AppleMobile
if (name)
{
strncpy(returned, name, 1024);
}
else
return (NULL); // strcpy(returned, "built-in?");
if (svc)
{
sprintf(returned + strlen(returned), "(%ld.%d.%d.%d.%d)",
(long)((svc->version) >> 40),
(int)(svc->version >> 30) & 0x000003FF,
(int)(svc->version >> 20) & 0x000003FF,
(int)(svc->version >> 10) & 0x000003FF,
(int)(svc->version) & 0x000003FF);
}
if (((svc->version >> 40) >= 570) && (name && (strstr(name, "sandbox"))))
{
fprintf(stderr, "This is the sandbox.kext, version %ld - Trying to get seatbelt-profiles\n",
svc->version >> 40);
if (doSandboxOperationNames(KextBundleHeader, "__TEXT.__cstring"))
{
fprintf(stderr, "Can't get profiles with sandbox operation names\n");
}
else
doSandboxProfiles(KextBundleHeader, "__TEXT.__const");
}
return (returned);
};
char *identifyKext(char *KextBundleHeader, int Size)
{
// Look at first page of Kext header
if (Size < 0x1000)
{
return ("this kext is too small!\n");
}
// This is CRUDE. I know. But hey, it works. It could be optimized in several ways,
// including:
//
// A) bailing on a false positive
// B) marking out kexts already found and skipping them
// and most importantly -
// C) Use machlib to just sift through the TEXT.__cstring section!
//
// (but this is fast, and works!)
int i = 0;
for (i = 0;
KextSigs[i].sig;
i++)
{
if (memmem(KextBundleHeader, Size, KextSigs[i].sig, strlen(KextSigs[i].sig)))
return KextSigs[i].name;
}
return NULL;
}
// 2.4
// For 64-bit
char output[1024];
int function_identifier(char *Symbol, uint64_t *Regs, int Call)
{
static int panic = 0;
// fprintf(stdout,"Called back : %llx\n", Regs[0]);
if (Regs[R0] > 0xfffffff000000000)
{
// @Todo: > 0xxx.... size of text cstring, also optimize func, mark checks
// in array when check done so can skip
char *sect = MachOGetSectionNameContainingAddress(Regs[0]);
if (sect && (strcmp(sect, "__TEXT.__cstring") == 0))
{
char *str = getPointerToAddr(Regs[0]);
if ((!panic) && strcmp(str, "\"%s[KERNEL]: %s\"") == 0)
{
fprintf(stderr, "GOT panic: 0x%llx\n", Regs[32]);
sprintf(output, "_panic");
addSymbolToCache(output, Regs[32], NULL);
panic++;
};
if (strcmp(str, "IOBSD") == 0)
{
sprintf(output, "__ZN9IOService15publishResourceEPKcP8OSObject");
fprintf(stderr, "GOT __ZN9IOService15publishResourceEPKcP8OSObject: 0x%llx\n", Regs[32]);
addSymbolToCache(output, Regs[32], NULL);
//sprintf(output,"%llx:__ZN9IOService15publishResourceEPKcP8OSObject\n", Regs[32]);
// write (jtoolOutFD, output, strlen(output));
}
if (strncmp(str, "BSD root: %s,", strlen("BSD root: %s,")) == 0)
{
fprintf(stderr, "GOT IOLog! 0x%llx\n", Regs[32]);
sprintf(output, "_IOLog");
addSymbolToCache(output, Regs[32], NULL);
//sprintf(output, "%llx:_IOLog\n", Regs[32]);
//write (jtoolOutFD, output, strlen(output));
}
if (strcmp(str, "#size-cells") == 0)
{
fprintf(stderr, "GOT __ZN8OSSymbol17withCStringNoCopyEPKc: 0x%llx\n", Regs[32]);
//sprintf(output, "%llx:___ZN8OSSymbol17withCStringNoCopyEPKc\n", Regs[32]);
//write (jtoolOutFD, output, strlen(output));
addSymbolToCache("__ZN8OSSymbol17withCStringNoCopyEPKc", Regs[32], NULL);
}
if (strcmp(str, "-zp") == 0)
{
fprintf(stderr, "GOT PE_Parse_boot_argn: 0x%llx\n", Regs[32]);
addSymbolToCache("_PE_Parse_boot_argn", Regs[32], NULL);
// sprintf(output, "%llx:_PE_Parse_boot_argn\n", Regs[32]);
// write (jtoolOutFD, output, strlen(output));
}
if (strcmp(str, "hw.memsize") == 0)
{
fprintf(stderr, "GOT PE_get_default: 0x%llx\n", Regs[32]);
// sprintf(output, "%llx:_PE_get_default\n", Regs[32]);
//owrite (jtoolOutFD, output, strlen(output));
addSymbolToCache("_PE_get_default", Regs[32], NULL);
// return (DISASSEMBLE_BREAK);
}
}
}
// TODO - optimize by prefetching and storing TEXT__CSTRING
if (Regs[R3] > 0xfffffff000000000)
{
char *sect = MachOGetSectionNameContainingAddress(Regs[R3]);
if (sect && (strcmp(sect, "__TEXT.__cstring") == 0))
{
char *str = getPointerToAddr(Regs[3]);
if (strcmp(str, "vstruct zone") == 0)
{
fprintf(stderr, "GOT zinit: 0x%llx\n", Regs[32]);
addSymbolToCache("_zinit", Regs[32], NULL);
// sprintf(output, "%llx:_zinit\n", Regs[32]);
// write (jtoolOutFD, output, strlen(output));
}
}
}
if (Regs[R2] > 0xfffffff000000000)
{
char *sect = MachOGetSectionNameContainingAddress(Regs[2]);
if (sect && (strcmp(sect, "__TEXT.__cstring") == 0))
{
char *str = getPointerToAddr(Regs[2]);
if (strcmp(str, "Jettisoning kext bootstrap segments.") == 0)
{
printf("GOT OSKextLog: 0x%llx\n", Regs[32]);
addSymbolToCache("_OSKextLog", Regs[32], NULL);
//return DISASSEMBLE_BREAK;
}
}
}
if (Regs[R1] > 0xfffffff000000000)
{
char *sect = MachOGetSectionNameContainingAddress(Regs[1]);
if (sect && (strcmp(sect, "__TEXT.__cstring") == 0))
{
char *str = getPointerToAddr(Regs[1]);
if (strcmp(str, "OSMalloc_tag") == 0)
{
fprintf(stderr, "GOT lck_grp_alloc_init: 0x%llx\n", Regs[32]);
// sprintf(output,"%llx:_lck_grp_alloc_init\n", Regs[32]);
// write (jtoolOutFD, output, strlen(output));
addSymbolToCache("_lck_grp_alloc_init", Regs[32], NULL);
}
if (strcmp(str, "vm_swap_data") == 0)
{
fprintf(stderr, "GOT lck_grp_init: 0x%llx\n", Regs[32]);
addSymbolToCache("_lck_grp_init", Regs[32], NULL);
// sprintf(output,"%llx:_lck_grp_init\n", Regs[32]);
// write (jtoolOutFD, output, strlen(output));
}
}
}
return 0;
}
// From Machlib's CS
void doSignature(void *Blob, int ShowEnt, unsigned char *MachOHeader){};
void *dumpBlob(unsigned char *blob, int ShowEnt, unsigned char *MachO){};
int validateBlob(unsigned char *Blob, unsigned int Size, void *SuperBlob){};
#
char *syscall_names[] = {"syscall", "exit", "fork", "read", "write", "open", "close", "wait4", "8 old creat", "link", "unlink", "11 old execv", "chdir", "fchdir", "mknod", "chmod", "chown", "17 old break", "getfsstat", "19 old lseek", "getpid", "21 old mount", "22 old umount", "setuid", "getuid", "geteuid", "ptrace", "recvmsg", "sendmsg", "recvfrom", "accept", "getpeername", "getsockname", "access", "chflags", "fchflags", "sync", "kill", "38 old stat", "getppid", "40 old lstat", "dup", "pipe", "getegid", "profil", "45 old ktrace", "sigaction", "getgid", "sigprocmask", "getlogin", "setlogin", "acct", "sigpending", "sigaltstack", "ioctl", "reboot", "revoke", "symlink", "readlink", "execve", "umask", "chroot", "62 old fstat", "63 used internally , reserved", "64 old getpagesize", "msync", "vfork", "67 old vread", "68 old vwrite", "69 old sbrk", "70 old sstk", "71 old mmap", "72 old vadvise", "munmap", "mprotect", "madvise", "76 old vhangup", "77 old vlimit", "mincore", "getgroups", "setgroups", "getpgrp", "setpgid", "setitimer", "84 old wait", "swapon", "getitimer", "87 old gethostname", "88 old sethostname", "getdtablesize", "dup2", "91 old getdopt", "fcntl", "select", "94 old setdopt", "fsync", "setpriority", "socket", "connect", "99 old accept", "getpriority", "101 old send", "102 old recv", "103 old sigreturn", "bind", "setsockopt", "listen", "107 old vtimes", "108 old sigvec", "109 old sigblock", "110 old sigsetmask", "sigsuspend", "112 old sigstack", "113 old recvmsg", "114 old sendmsg", "115 old vtrace", "gettimeofday", "getrusage", "getsockopt", "119 old resuba", "readv", "writev", "settimeofday", "fchown", "fchmod", "125 old recvfrom", "setreuid", "setregid", "rename", "129 old truncate", "130 old ftruncate", "flock", "mkfifo", "sendto", "shutdown", "socketpair", "mkdir", "rmdir", "utimes", "futimes", "adjtime", "141 old getpeername", "gethostuuid", "143 old sethostid", "144 old getrlimit", "145 old setrlimit", "146 old killpg", "setsid", "148 old setquota", "149 old qquota", "150 old getsockname", "getpgid", "setprivexec", "pread", "pwrite", "nfssvc", "156 old getdirentries", "statfs", "fstatfs", "unmount", "160 old async_daemon", "getfh", "162 old getdomainname", "163 old setdomainname", "164", "quotactl", "166 old exportfs", "mount", "168 old ustat", "csops", "csops_audittoken", "171 old wait3", "172 old rpause", "waitid", "174 old getdents", "175 old gc_control", "add_profil", "kdebug_typefilter", "kdebug_trace_string", "kdebug_trace64", "kdebug_trace", "setgid", "setegid", "seteuid", "sigreturn", "chud", "186", "fdatasync", "stat", "fstat", "lstat", "pathconf", "fpathconf", "193", "getrlimit", "setrlimit", "getdirentries", "mmap", "198 __syscall", "lseek", "truncate", "ftruncate", "__sysctl", "mlock", "munlock", "undelete", "ATsocket", "ATgetmsg", "ATputmsg", "ATPsndreq", "ATPsndrsp", "ATPgetreq", "ATPgetrsp", "213 Reserved for AppleTalk", "214", "215", "mkcomplex", "statv", "lstatv", "fstatv", "getattrlist", "setattrlist", "getdirentriesattr", "exchangedata", "224 old checkuseraccess / fsgetpath ( which moved to 427 )", "searchfs", "delete", "copyfile", "fgetattrlist", "fsetattrlist", "poll", "watchevent", "waitevent", "modwatch", "getxattr", "fgetxattr", "setxattr", "fsetxattr", "removexattr", "fremovexattr", "listxattr", "flistxattr", "fsctl", "initgroups", "posix_spawn", "ffsctl", "246", "nfsclnt", "fhopen", "249", "minherit", "semsys", "msgsys", "shmsys", "semctl", "semget", "semop", "257", "msgctl", "msgget", "msgsnd", "msgrcv", "shmat", "shmctl", "shmdt", "shmget", "shm_open", "shm_unlink", "sem_open", "sem_close", "sem_unlink", "sem_wait", "sem_trywait", "sem_post", "sem_getvalue", "sem_init", "sem_destroy", "open_extended", "umask_extended", "stat_extended", "lstat_extended", "fstat_extended", "chmod_extended", "fchmod_extended", "access_extended", "settid", "gettid", "setsgroups", "getsgroups", "setwgroups", "getwgroups", "mkfifo_extended", "mkdir_extended", "identitysvc", "shared_region_check_np", "shared_region_map_np", "vm_pressure_monitor", "psynch_rw_longrdlock", "psynch_rw_yieldwrlock", "psynch_rw_downgrade", "psynch_rw_upgrade", "psynch_mutexwait", "psynch_mutexdrop", "psynch_cvbroad", "psynch_cvsignal", "psynch_cvwait", "psynch_rw_rdlock", "psynch_rw_wrlock", "psynch_rw_unlock", "psynch_rw_unlock2", "getsid", "settid_with_pid", "psynch_cvclrprepost", "aio_fsync", "aio_return", "aio_suspend", "aio_cancel", "aio_error", "aio_read", "aio_write", "lio_listio", "321 old __pthread_cond_wait", "iopolicysys", "process_policy", "mlockall", "munlockall", "326", "issetugid", "__pthread_kill", "__pthread_sigmask", "__sigwait", "__disable_threadsignal", "__pthread_markcancel", "__pthread_canceled", "__semwait_signal", "335 old utrace", "proc_info", "sendfile", "stat64", "fstat64", "lstat64", "stat64_extended", "lstat64_extended", "fstat64_extended", "getdirentries64", "statfs64", "fstatfs64", "getfsstat64", "__pthread_chdir", "__pthread_fchdir", "audit", "auditon", "352", "getauid", "setauid", "getaudit", "setaudit", "getaudit_addr", "setaudit_addr", "auditctl", "bsdthread_create", "bsdthread_terminate", "kqueue", "kevent", "lchown", "stack_snapshot", "bsdthread_register", "workq_open", "workq_kernreturn", "kevent64", "__old_semwait_signal", "__old_semwait_signal_nocancel", "thread_selfid", "ledger", "kevent_qos", "375", "376", "377", "378", "379", "__mac_execve", "__mac_syscall", "__mac_get_file", "__mac_set_file", "__mac_get_link", "__mac_set_link", "__mac_get_proc", "__mac_set_proc", "__mac_get_fd", "__mac_set_fd", "__mac_get_pid", "__mac_get_lcid", "__mac_get_lctx", "__mac_set_lctx", "setlcid", "getlcid", "read_nocancel", "write_nocancel", "open_nocancel", "close_nocancel", "wait4_nocancel", "recvmsg_nocancel", "sendmsg_nocancel", "recvfrom_nocancel", "accept_nocancel", "msync_nocancel", "fcntl_nocancel", "select_nocancel", "fsync_nocancel", "connect_nocancel", "sigsuspend_nocancel", "readv_nocancel", "writev_nocancel", "sendto_nocancel", "pread_nocancel", "pwrite_nocancel", "waitid_nocancel", "poll_nocancel", "msgsnd_nocancel", "msgrcv_nocancel", "sem_wait_nocancel", "aio_suspend_nocancel", "__sigwait_nocancel", "__semwait_signal_nocancel", "__mac_mount", "__mac_get_mount", "__mac_getfsstat", "fsgetpath", "audit_session_self", "audit_session_join", "fileport_makeport", "fileport_makefd", "audit_session_port", "pid_suspend", "pid_resume", "pid_hibernate", "pid_shutdown_sockets", "437 old shared_region_slide_np", "shared_region_map_and_slide_np",
"kas_info", "memorystatus_control", "guarded_open_np", "guarded_close_np",
"guarded_kqueue_np",
"change_fdguard_np",
"proc_rlimit_control",
"proc_rlimit_control",
"proc_connectx",
"proc_disconnectx",
"proc_peeloff",
"proc_socket_delegate",
"proc_telemetry",
"proc_uuid_policy", // 452
"memorystatus_get_level", // 453
"system_override", // 454 - as of iOS8
"vfs_purge",
"sfi_ctl",
"sfi_pidctl",
"coalition",
"coalition_info",
"necp_match_policy", // 460
"getattrlistbulk", // 461
"clonefileat", // 462
"openat",
"openat_nocancel",
"renameat",
"faccessat",
"fchmodat",
"fchownat",
"fstatat",
"fstatat64", // 470
"linkat",
"unlinkat", // 472
"readlinkat",
"symlinkat",
"mkdirat",
"getattrlistat",
"proc_trace_log",
"bsdthread_ctl",
"openbyid_np",
"recvmsg_x", // 480
"sendmsg_x",
"thread_selfusage",
"csrctl",
"guarded_open_dprotected_np",
"guarded_write_np",
"guarded_pwrite_np",
"guarded_writev_np",
"rename_ext",
"mremap_encrypted",
// iOS 9/Xnu 3216
"netagent_trigger", // 490
"stack_snapshot_with_config",
"microstackshot",
"grab_pgo_data",
"persona",
"#495",
"#496",
"#497",
"#498",
"work_interval_ctl",
"getentropy ",
"necp_open ",
"necp_client_action",
"__nexus_open ",
"__nexus_register",
"__nexus_deregister",
"__nexus_create",
"__nexus_destroy",
"__nexus_get_opt",
"__nexus_set_opt",
"__channel_open",
"__channel_get_info",
"__channel_sync",
"__channel_get_opt",
"__channel_set_opt",
"ulock_wait ",
"ulock_wake ",
"fclonefileat ",
"fs_snapshot ",
"#519",
"terminate_with_payload",
"abort_with_payload",
NULL
};
// That MOV PC,R9 always gives it away , now..
const char *ARMExcVector = "\x09\xf0\xa0\xe1\xfe\xff\xff\xea";
const char *mach_syscall_name_table[128] = {
/* 0 */ "kern_invalid",
/* 1 */ "kern_invalid",
/* 2 */ "kern_invalid",
/* 3 */ "kern_invalid",
/* 4 */ "kern_invalid",
/* 5 */ "kern_invalid",
/* 6 */ "kern_invalid",
/* 7 */ "kern_invalid",
/* 8 */ "kern_invalid",
/* 9 */ "kern_invalid",
/* 10 */ "_kernelrpc_mach_vm_allocate_trap", // OS X : "kern_invalid",
/* 11 */ "_kernelrpc_vm_allocate_trap", // OS X : "kern_invalid",
/* 12 */ "_kernelrpc_mach_vm_deallocate_trap", // OS X: "kern_invalid",
/* 13 */ "_kernelrpc_vm_deallocate_trap", // "kern_invalid",
/* 14 */ "_kernelrpc_mach_vm_protect_trap", //"kern_invalid",
/* 15 */ "_kernelrpc_vm_protect_trap", // kern_invalid",
/* 16 */ "_kernelrpc_mach_port_allocate_trap", //"kern_invalid",
/* 17 */ "_kernelrpc_mach_port_destroy_trap", //"kern_invalid",
/* 18 */ "_kernelrpc_mach_port_deallocate_trap", // "kern_invalid",
/* 19 */ "_kernelrpc_mach_port_mod_refs_trap", //"kern_invalid",
/* 20 */ "_kernelrpc_mach_port_move_member_trap", //"kern_invalid",
/* 21 */ "_kernelrpc_mach_port_insert_right_trap", //"kern_invalid",
/* 22 */ "_kernelrpc_mach_port_insert_member_trap", // "kern_invalid",
/* 23 */ "_kernelrpc_mach_port_extract_member_trap", // "kern_invalid",
/* 24 */ "__kernelrpc_mach_port_construct_trap", // in 24xx, else "kern_invalid",
/* 25 */ "__kernelrpc_mach_port_destruct_trap", // in 24xx, "kern_invalid",
/* 26 */ "mach_reply_port",
/* 27 */ "thread_self_trap",
/* 28 */ "task_self_trap",
/* 29 */ "host_self_trap",
/* 30 */ "kern_invalid",
/* 31 */ "mach_msg_trap",
/* 32 */ "mach_msg_overwrite_trap",
/* 33 */ "semaphore_signal_trap",
/* 34 */ "semaphore_signal_all_trap",
/* 35 */ "semaphore_signal_thread_trap",
/* 36 */ "semaphore_wait_trap",
/* 37 */ "semaphore_wait_signal_trap",
/* 38 */ "semaphore_timedwait_trap",
/* 39 */ "semaphore_timedwait_signal_trap",
/* 40 */ "kern_invalid",
/* 41 */ "__kernelrpc_mach_port_guard_trap", // as of 24xx - else "kern_invalid",
/* 42 */ "__kernelrpc_mach_port_unguard_trap", // as of 24xx - else "kern_invalid",
/* 43 */ "map_fd", // invalidated in 27xx
/* 44 */ "task_name_for_pid",
/* 45 */ "task_for_pid",
/* 46 */ "pid_for_task",
/* 47 */ "kern_invalid",
/* 48 */ "macx_swapon",
/* 49 */ "macx_swapoff",
/* 50 */ "kern_invalid",
/* 51 */ "macx_triggers",
/* 52 */ "macx_backing_store_suspend",
/* 53 */ "macx_backing_store_recovery",
/* 54 */ "kern_invalid",
/* 55 */ "kern_invalid",
/* 56 */ "kern_invalid",
/* 57 */ "kern_invalid",
/* 58 */ "pfz_exit",
/* 59 */ "swtch_pri",
/* 60 */ "swtch",
/* 61 */ "thread_switch",
/* 62 */ "clock_sleep_trap",
/* 63 */ "kern_invalid",
/* traps 64 - 95 reserved (debo) */
/* 64 */ "kern_invalid",
/* 65 */ "kern_invalid",
/* 66 */ "kern_invalid",
/* 67 */ "kern_invalid",
/* 68 */ "kern_invalid",
/* 69 */ "kern_invalid",
/* 70 */ "kern_invalid",
/* 71 */ "kern_invalid",
/* 72 */ "kern_invalid",
/* 73 */ "kern_invalid",
/* 74 */ "kern_invalid",
/* 75 */ "kern_invalid",
/* 76 */ "kern_invalid",
/* 77 */ "kern_invalid",
/* 78 */ "kern_invalid",
/* 79 */ "kern_invalid",
/* 80 */ "kern_invalid",
/* 81 */ "kern_invalid",
/* 82 */ "kern_invalid",
/* 83 */ "kern_invalid",
/* 84 */ "kern_invalid",
/* 85 */ "kern_invalid",
/* 86 */ "kern_invalid",
/* 87 */ "kern_invalid",
/* 88 */ "kern_invalid",
/* 89 */ "mach_timebase_info_trap",
/* 90 */ "mach_wait_until_trap",
/* 91 */ "mk_timer_create_trap",
/* 92 */ "mk_timer_destroy_trap",
/* 93 */ "mk_timer_arm_trap",
/* 94 */ "mk_timer_cancel_trap",
/* 95 */ "kern_invalid",
/* traps 64 - 95 reserved (debo) */
/* 96 */ "kern_invalid",
/* 97 */ "kern_invalid",
/* 98 */ "kern_invalid",
/* 99 */ "kern_invalid",
/* traps 100-107 reserved for iokit (esb) */
/* 100 */ "iokit_user_client_trap",
/* 101 */ "kern_invalid",
/* 102 */ "kern_invalid",
/* 103 */ "kern_invalid",
/* 104 */ "kern_invalid",
/* 105 */ "kern_invalid",
/* 106 */ "kern_invalid",
/* 107 */ "kern_invalid",
/* traps 108-127 unused */
/* 108 */ "kern_invalid",
/* 109 */ "kern_invalid",
/* 110 */ "kern_invalid",
/* 111 */ "kern_invalid",
/* 112 */ "kern_invalid",
/* 113 */ "kern_invalid",
/* 114 */ "kern_invalid",
/* 115 */ "kern_invalid",
/* 116 */ "kern_invalid",
/* 117 */ "kern_invalid",
/* 118 */ "kern_invalid",
/* 119 */ "kern_invalid",
/* 120 */ "kern_invalid",
/* 121 */ "kern_invalid",
/* 122 */ "kern_invalid",
/* 123 */ "kern_invalid",
/* 124 */ "kern_invalid",
/* 125 */ "kern_invalid",
/* 126 */ "kern_invalid",
/* 127 */ "kern_invalid",
};
// Fixed this because as of iOS 9 or so Apple moved source cache to
// /Library/Caches/com.apple.xbs/Sources/xnu/xnu-3216.0.0.1.15
#define XNUSIG "/xnu-"
#define SYS_MAXSYSCALL 443
#define SYS_MAXSYSCALL_7 454
#define SYS_MAXSYSCALL_8 489
#define SYS_MAXSYSCALL_9 500
#define SYS_MAXSYSCALL_10 521
#define SIG1 "\x00\x00\x00\x00" \
"\x00\x00\x00\x00" \
"\x01\x00\x00\x00" \
"\x00\x00\x00\x00" \
"\x01\x00\x00\x00"
#define SIG1_SUF "\x00\x00\x00\x00" \
"\x00\x00\x00\x00" \
"\x00\x00\x00\x00" \
"\x04\x00\x00\x00"
#define SIG2 "\x00\x00\x00\x00" \
"\x00\x00\x00\x00" \
"\x01\x00\x00\x00" \
"\x1C\x00\x00\x00" \
"\x00\x00\x00\x00"
#define SIG1_IOS7X "\x00\x00\x00\x00" \
"\x00\x00\x00\x00" \
"\x01\x00\x00\x00" \
"\x00\x00\x00\x00"
#define SIG2_IOS7X "\x00\x00\x00\x00" \
"\x00\x00\x00\x00" \
"\x00\x00\x00\x00" \
"\x01\x00\x04\x00"
#define SIG1_IOS8X "\x00\x00\x00\x00\x01\x00\x04\x00"
#define SIG1_AFTER_0x18_IOS8X "\x06\x00\x00\x00" \
"\x03\x00\x0c\x00"
#define SIG_SYSCALL_3 "\x06\x00\x00\x00\x03\x00\x0c\x00"
#define SIG_MIG_MACH_VM "\xC0\x12\x00\x00\xD4\x12\x00\x00"
#define SIG_MIG_TASK "\x48\x0d\x00\x00\x72\x0d\x00\x00"
typedef struct mig_subsystem_struct
{
uint32_t min;
uint32_t max;
char *names;
} mig_subsys;
mig_subsys mach_vm_subsys = {0x12c0, 0x12d4, NULL};
mig_subsys task_subsys = {0xd48, 0xd7a, NULL};
mig_subsys mach_host_subsys_9 = {200, 230};
mig_subsys host_priv_subsys = {400, 426};
mig_subsys thread_act_subsys = {3600, 3628};
mig_subsys mach_port_subsys = {3200, 3236};
mig_subsys is_iokit_subsys = {2800, 2885};
mig_subsys is_iokit_subsys_9 = {2800, 2885};
mig_subsys processor_set_subsys = {4000, 4010};
mig_subsys host_security_subsys = {600, 602};
mig_subsys processor_subsys = {3000, 3006};
// It would be great if we could just get the _subsystem_to_name_map ... mig generated defines,
// but the iOS compiler complains. So no.
typedef struct mig_func_struct
{
char *name;
int num;
} mig_func_desc;
mig_func_desc processor_mig[] = {
{"processor_start", 3000},
{"processor_exit", 3001},
{"processor_info", 3002},
{"processor_control", 3003},
{"processor_assign", 3004},
{"processor_get_assignment", 3005},
{NULL, 3006}};
mig_func_desc mach_port_mig[] = {{"mach_port_names", 3200}, {"mach_port_type", 3201}, {"mach_port_rename", 3202}, {"mach_port_allocate_name", 3203}, {"mach_port_allocate", 3204}, {"mach_port_destroy", 3205}, {"mach_port_deallocate", 3206}, {"mach_port_get_refs", 3207}, {"mach_port_mod_refs", 3208}, {"mach_port_peek", 3209}, {"mach_port_set_mscount", 3210}, {"mach_port_get_set_status", 3211}, {"mach_port_move_member", 3212}, {"mach_port_request_notification", 3213}, {"mach_port_insert_right", 3214}, {"mach_port_extract_right", 3215}, {"mach_port_set_seqno", 3216}, {"mach_port_get_attributes", 3217}, {"mach_port_set_attributes", 3218}, {"mach_port_allocate_qos", 3219}, {"mach_port_allocate_full", 3220}, {"task_set_port_space", 3221}, {"mach_port_get_srights", 3222}, {"mach_port_space_info", 3223}, {"mach_port_dnrequest_info", 3224}, {"mach_port_kernel_object", 3225}, {"mach_port_insert_member", 3226}, {"mach_port_extract_member", 3227}, {"mach_port_get_context", 3228}, {"mach_port_set_context", 3229}, {"mach_port_kobject", 3230}, {"mach_port_construct", 3231}, {"mach_port_destruct", 3232}, {"mach_port_guard", 3233}, {"mach_port_unguard", 3234}, {"mach_port_space_basic_info", 3235}, {((void *)0), 3236}};
mig_func_desc host_security_mig[] = {{"host_security_create_task_token", 600},
{"host_security_set_task_token", 601},
{NULL, 602}};
mig_func_desc processor_set_mig[] = {
{"processor_set_statistics", 4000},
{"processor_set_destroy", 4001},
{"processor_set_max_priority", 4002},
{"processor_set_policy_enable", 4003},
{"processor_set_policy_disable", 4004},
{"processor_set_tasks", 4005},
{"processor_set_threads", 4006},
{"processor_set_policy_control", 4007},
{"processor_set_stack_usage", 4008},
{"processor_set_info", 4009},
{NULL, 4010}};
mig_func_desc iokit_mig[] = {
{"io_object_get_class", 2800},
{"io_object_conforms_to", 2801},
{"io_iterator_next", 2802},
{"io_iterator_reset", 2803},
{"io_service_get_matching_services", 2804},
{"io_registry_entry_get_property", 2805},
{"io_registry_create_iterator", 2806},
{"io_registry_iterator_enter_entry", 2807},
{"io_registry_iterator_exit_entry", 2808},
{"io_registry_entry_from_path", 2809},
{"io_registry_entry_get_name", 2810},
{"io_registry_entry_get_properties", 2811},
{"io_registry_entry_get_property_bytes", 2812},
{"io_registry_entry_get_child_iterator", 2813},
{"io_registry_entry_get_parent_iterator", 2814},
{"io_service_close", 2816},
{"io_connect_get_service", 2817},
{"io_connect_set_notification_port", 2818},
{"io_connect_map_memory", 2819},
{"io_connect_add_client", 2820},
{"io_connect_set_properties", 2821},
{"io_connect_method_scalarI_scalarO", 2822},
{"io_connect_method_scalarI_structureO", 2823},
{"io_connect_method_scalarI_structureI", 2824},
{"io_connect_method_structureI_structureO", 2825},
{"io_registry_entry_get_path", 2826},
{"io_registry_get_root_entry", 2827},
{"io_registry_entry_set_properties", 2828},
{"io_registry_entry_in_plane", 2829},
{"io_object_get_retain_count", 2830},
{"io_service_get_busy_state", 2831},
{"io_service_wait_quiet", 2832},
{"io_registry_entry_create_iterator", 2833},
{"io_iterator_is_valid", 2834},
{"io_catalog_send_data", 2836},
{"io_catalog_terminate", 2837},
{"io_catalog_get_data", 2838},
{"io_catalog_get_gen_count", 2839},
{"io_catalog_module_loaded", 2840},
{"io_catalog_reset", 2841},
{"io_service_request_probe", 2842},
{"io_registry_entry_get_name_in_plane", 2843},
{"io_service_match_property_table", 2844},
{"io_async_method_scalarI_scalarO", 2845},
{"io_async_method_scalarI_structureO", 2846},
{"io_async_method_scalarI_structureI", 2847},
{"io_async_method_structureI_structureO", 2848},
{"io_service_add_notification", 2849},
{"io_service_add_interest_notification", 2850},
{"io_service_acknowledge_notification", 2851},
{"io_connect_get_notification_semaphore", 2852},
{"io_connect_unmap_memory", 2853},
{"io_registry_entry_get_location_in_plane", 2854},
{"io_registry_entry_get_property_recursively", 2855},
{"io_service_get_state", 2856},
{"io_service_get_matching_services_ool", 2857},
{"io_service_match_property_table_ool", 2858},
{"io_service_add_notification_ool", 2859},
{"io_object_get_superclass", 2860},
{"io_object_get_bundle_identifier", 2861},
{"io_service_open_extended", 2862},
{"io_connect_map_memory_into_task", 2863},
{"io_connect_unmap_memory_from_task", 2864},
{"io_connect_method", 2865},
{"io_connect_async_method", 2866},
{"io_registry_entry_get_registry_entry_id", 2871},
{"io_connect_method_var_output", 2872},
{"io_service_get_matching_service", 2873},
{"io_service_get_matching_service_ool", 2874},
{"io_service_get_authorization_id", 2875},
{"io_service_set_authorization_id", 2876},
{"io_server_version", 2877},
{"io_registry_entry_get_properties_bin", 2878},
{"io_registry_entry_get_property_bin", 2879},
{"io_service_get_matching_service_bin", 2880},
{"io_service_get_matching_services_bin", 2881},
{"io_service_match_property_table_bin", 2882},
{"io_service_add_notification_bin", 2883},
{"io_registry_entry_get_path_ool", 2884},
{"io_registry_entry_from_path_ool", 2885},
{NULL, 2886}};
mig_func_desc mach_vm_mig[] = {
{"mach_vm_allocate", 4800},
{"mach_vm_deallocate", 4801},
{"mach_vm_protect", 4802},
{"mach_vm_inherit", 4803},
{"mach_vm_read", 4804},
{"mach_vm_read_list", 4805},
{"mach_vm_write", 4806},
{"mach_vm_copy", 4807},
{"mach_vm_read_overwrite", 4808},
{"mach_vm_msync", 4809},
{"mach_vm_behavior_set", 4810},
{"mach_vm_map", 4811},
{"mach_vm_machine_attribute", 4812},
{"mach_vm_remap", 4813},
{"mach_vm_page_query", 4814},
{"mach_vm_region_recurse", 4815},
{"mach_vm_region", 4816},
{"_mach_make_memory_entry", 4817},
{"mach_vm_purgable_control", 4818},
{"mach_vm_page_info", 4819},
{NULL, 4820}};
mig_func_desc mach_host_mig[] = {{"host_info", 200}, {"host_kernel_version", 201}, {"_host_page_size", 202}, {"mach_memory_object_memory_entry", 203}, {"host_processor_info", 204}, {"host_get_io_master", 205}, {"host_get_clock_service", 206}, {"kmod_get_info", 207}, {"host_zone_info", 208}, {"host_virtual_physical_table_info", 209}, {"processor_set_default", 213}, {"processor_set_create", 214}, {"mach_memory_object_memory_entry_64", 215}, {"host_statistics", 216}, {"host_request_notification", 217}, {"host_lockgroup_info", 218}, {"host_statistics64", 219}, {"mach_zone_info", 220}, {"host_create_mach_voucher", 222}, {"host_register_mach_voucher_attr_manager", 223}, {"host_register_well_known_mach_voucher_attr_manager", 224},
{"host_set_atm_diagnostic_flag", 225},
{"host_get_atm_diagnostic_flag", 226},
{"mach_memory_info", 227},
{"host_set_multiuser_config_flags", 228},
{"host_get_multiuser_config_flags", 229},
{"host_check_multiuser_mode", 230}
,
{((void *)0), 231}};
mig_func_desc task_mig[] = {{"task_create", 3400}, {"task_terminate", 3401}, {"task_threads", 3402}, {"mach_ports_register", 3403}, {"mach_ports_lookup", 3404}, {"task_info", 3405}, {"task_set_info", 3406}, {"task_suspend", 3407}, {"task_resume", 3408}, {"task_get_special_port", 3409}, {"task_set_special_port", 3410}, {"thread_create", 3411}, {"thread_create_running", 3412}, {"task_set_exception_ports", 3413}, {"task_get_exception_ports", 3414}, {"task_swap_exception_ports", 3415}, {"lock_set_create", 3416}, {"lock_set_destroy", 3417}, {"semaphore_create", 3418}, {"semaphore_destroy", 3419}, {"task_policy_set", 3420}, {"task_policy_get", 3421}, {"task_sample", 3422}, {"task_policy", 3423}, {"task_set_emulation", 3424}, {"task_get_emulation_vector", 3425}, {"task_set_emulation_vector", 3426}, {"task_set_ras_pc", 3427}, {"task_zone_info", 3428}, {"task_assign", 3429}, {"task_assign_default", 3430}, {"task_get_assignment", 3431}, {"task_set_policy", 3432}, {"task_get_state", 3433}, {"task_set_state", 3434}, {"task_set_phys_footprint_limit", 3435}, {"task_suspend2", 3436}, {"task_resume2", 3437}, {"task_purgable_info", 3438}, {"task_get_mach_voucher", 3439}, {"task_set_mach_voucher", 3440}, {"task_swap_mach_voucher", 3441}, {"task_generate_corpse", 3442}, {"task_map_corpse_info", 3443}, {"task_register_dyld_image_infos", 3444}, {"task_unregister_dyld_image_infos", 3445}, {"task_get_dyld_image_infos", 3446}, {"task_register_dyld_shared_cache_image_info", 3447}, {"task_register_dyld_set_dyld_state", 3448}, {"task_register_dyld_get_process_state", 3449}, {"task_map_corpse_info_64", 3450},
{((void *)0), 3451}};
mig_func_desc host_priv_mig[] = {
{"host_get_boot_info", 400},
{"host_reboot", 401},
{"host_priv_statistics", 402},
{"host_default_memory_manager", 403},
{"vm_wire", 404},
{"thread_wire", 405},
{"vm_allocate_cpm", 406},
{"host_processors", 407},
{"host_get_clock_control", 408},
{"kmod_create", 409},
{"kmod_destroy", 410},
{"kmod_control", 411},
{"host_get_special_port", 412},
{"host_set_special_port", 413},
{"host_set_exception_ports", 414},
{"host_get_exception_ports", 415},
{"host_swap_exception_ports", 416},
{"mach_vm_wire", 418},
{"host_processor_sets", 419},
{"host_processor_set_priv", 420},
{"set_dp_control_port", 421},
{"get_dp_control_port", 422},
{"host_set_UNDServer", 423},
{"host_get_UNDServer", 424},
{"kext_request", 425},
{NULL, 426}};
//mig_func_desc thread_act_mig [] = { subsystem_to_name_map_thread_act , { NULL, -1}};
mig_func_desc thread_act_mig[] = {{"thread_terminate", 3600}, {"act_get_state", 3601}, {"act_set_state", 3602}, {"thread_get_state", 3603}, {"thread_set_state", 3604}, {"thread_suspend", 3605}, {"thread_resume", 3606}, {"thread_abort", 3607}, {"thread_abort_safely", 3608}, {"thread_depress_abort", 3609}, {"thread_get_special_port", 3610}, {"thread_set_special_port", 3611}, {"thread_info", 3612}, {"thread_set_exception_ports", 3613}, {"thread_get_exception_ports", 3614}, {"thread_swap_exception_ports", 3615}, {"thread_policy", 3616}, {"thread_policy_set", 3617}, {"thread_policy_get", 3618}, {"thread_sample", 3619}, {"etap_trace_thread", 3620}, {"thread_assign", 3621}, {"thread_assign_default", 3622}, {"thread_get_assignment", 3623}, {"thread_set_policy", 3624}, {"thread_get_mach_voucher", 3625}, {"thread_set_mach_voucher", 3626}, {"thread_swap_mach_voucher", 3627}, {((void *)0), 3628}};
void dumpMIGSubsystem(mig_subsys *Subsys,
mig_subsys *OurSubSys,
int is64)
{
// Behind us is the server routine
char *func = (char *)((char *)(Subsys)-is64 ? 8 : 4);
uint64_t routineAddr;
uint64_t *routinePtr;
// if (is64) { serverRoutineAddr = *((uint64_t *) func); }
// else { serverRoutineAddr = *((uint64_t *) func); }
mig_func_desc *mig_subsystem_dumped;
if (Subsys->min == processor_mig[0].num)
{
mig_subsystem_dumped = processor_mig;
};
if (Subsys->min == processor_set_mig[0].num)
{
mig_subsystem_dumped = processor_set_mig;
};
if (Subsys->min == host_security_mig[0].num)
{
mig_subsystem_dumped = host_security_mig;
};
if (Subsys->min == iokit_mig[0].num)
{
mig_subsystem_dumped = iokit_mig;
};
if (Subsys->min == mach_port_mig[0].num)
{
mig_subsystem_dumped = mach_port_mig;
};
if (Subsys->min == mach_vm_mig[0].num)
{
mig_subsystem_dumped = mach_vm_mig;
};
if (Subsys->min == mach_host_mig[0].num)
{
mig_subsystem_dumped = mach_host_mig;
};
if (Subsys->min == host_priv_mig[0].num)
{
mig_subsystem_dumped = host_priv_mig;
};
if (Subsys->min == task_mig[0].num)
{
mig_subsystem_dumped = task_mig;
};
if (Subsys->min == thread_act_mig[0].num)
{
mig_subsystem_dumped = thread_act_mig;
};
if (mig_subsystem_dumped)
{
int f = 0;
int adv = (is64 ? 8 : 4);
routinePtr = (char *)Subsys + ((is64 ? 4 : 5) * adv);
int last = OurSubSys->max;
// printf("Max is %d , last is %d\n", Subsys->max, last);
// last - Subsys->min - 1);
if (last > Subsys->max)
last = Subsys->max;
while (mig_subsystem_dumped[f].num < last) //
// while (mig_subsystem_dumped[f].num > -1)
{
if (is64)
routineAddr = *routinePtr;
else
{
routineAddr = *((uint32_t *)routinePtr);
}
if (wantJToolOut)
{
char output[1024];
// sprintf(output,"0x%llx:__X%s\n", routineAddr, mig_subsystem_dumped[f].name);
sprintf(output, "__X%s", mig_subsystem_dumped[f].name);
addSymbolToCache(output, routineAddr, "");
// write (jtoolOutFD, output, strlen(output));
}
else
printf("\t__X%s: 0x%llx (%d)\n", mig_subsystem_dumped[f].name, routineAddr, mig_subsystem_dumped[f].num);
f++;
int skip = mig_subsystem_dumped[f].num - mig_subsystem_dumped[f - 1].num;
routinePtr = ((char *)routinePtr) + ((is64 ? 5 : 6) * skip * adv);
}
// If the last num we got to is not the subsystem's max, warn
if (last < Subsys->max - 1)
{
printf("\tWarning: This kernel is newer than joker is (%d < %d)!\n",
last, Subsys->max - 1);
}
}
else
{
printf("Unknown MIG system (%d-%d)\n", Subsys->min, Subsys->max);
}
} // dumpMIG
void dumpMachTraps(char *mach, int is64)
{
int i;
int thumb = 0;
uint64_t kernInvalid = *((uint64_t *)mach);
if (!is64)
kernInvalid = *((uint32_t *)mach);
if (mach)
printf("Kern invalid should be %llx. Ignoring those\n", kernInvalid);
;
for (i = 0; i < 128; i++)
{
uint64_t addr = *((int64_t *)(mach + 4 * 8 * i));
uint32_t addr32 = *((int *)(mach + 3 * 4 * i));
if (is64)
{
}
else
{
if (addr == *((int *)(mach + 4)))
continue;
if ((addr % 4) == 1)
{
addr--;
thumb++;
}
if ((addr % 4) == -3)
{
addr--;
thumb++;
}
if (addr % 4)
{
thumb = "-1";
}
}
if (addr && (addr != kernInvalid))
{
if (wantJToolOut)
{
char output[1024];
sprintf(output, "_%s", mach_syscall_name_table[i]);
addSymbolToCache(output, addr, NULL);
// sprintf(output,"%llx:%s:_Mach_Trap_%d\n", addr, mach_syscall_name_table[i], i);
// write (jtoolOutFD, output, strlen(output));
}
else
printf("%3d %-40s %llx %s\n", i, mach_syscall_name_table[i], is64 ? addr : addr32, (thumb ? "T" : "-"));
}
else
{ /* suppress, but also warn if it's not kern_invalid for whatever reason */
//printf("%llx Trap #%d should be kern_invalid, but isn't\n", addr, i);
}
} // end for < 128 ..
} // dumpMachTraps
int g_Verbose = 0;
char *MachOLookupSymbolAtAddress(uint64_t, unsigned char *File);
extern int disassARMInstr(unsigned char *Loc, uint64_t Address, disassembled_instruction *returned);
extern int disassARM64Instr(uint32_t *Loc, uint64_t Address, disassembled_instruction *returned);
extern int doInstr(disassembled_instruction *Instr, int Print);
uint32_t MachOGetSectionOffset(void *File, char *Name);
int symbolicateKextStubs(char *MMapped, int Size, char *Name, int Split)
{
// Name only actually used for debugging...
// @TODO: Could actually locate stub section by flags, rather than hard coded name. Machlib can do that.
char *splitKext = NULL;
char *d = getenv("JOKER_DIR");
if (!d)
d = "/tmp";
char buf[1024];
char filename[1024];
snprintf(buf, 1024, "%s/%s.kext", d, Name);
if (Split)
{
int fd = open(buf, O_RDWR);
if (fd < 0)
{
fprintf(stderr, "Unable to open %s.. can't symbolicate\n",
buf);
return -1;
}
struct stat stbuf;
int rc = fstat(fd, &stbuf);
int filesize = stbuf.st_size;
splitKext = mmap(NULL,
filesize, // size_t len,
PROT_READ, // int prot,
MAP_SHARED | MAP_FILE, // int flags,
fd, // int fd,
0); // off_t offset);
//zzzz
segments = processFile(splitKext, filesize, getKernelCacheArch(), 0, 0, 0);
if (g_jdebug)
fprintf(stderr, "This is a split kext.. %d (0x%x) bytes\n", filesize, filesize);
}
uint32_t stubs_off = MachOGetSectionOffset((unsigned char *)MMapped, "__TEXT.__stubs");
uint32_t stubs_size = MachOGetSectionSize((unsigned char *)MMapped, "__TEXT.__stubs");
uint64_t stubs_addr = MachOGetSectionAddr((unsigned char *)MMapped, "__TEXT.__stubs");
if (!stubs_size)
{
stubs_off = MachOGetSectionOffset((unsigned char *)MMapped, "__TEXT_EXEC.__stubs");
stubs_size = MachOGetSectionSize((unsigned char *)MMapped, "__TEXT_EXEC.__stubs");
stubs_addr = MachOGetSectionAddr((unsigned char *)MMapped, "__TEXT_EXEC.__stubs");
}
char *oh_my_got = "__DATA.__got";
uint32_t got_off = MachOGetSectionOffset((unsigned char *)MMapped, oh_my_got);
uint32_t got_size = MachOGetSectionSize((unsigned char *)MMapped, oh_my_got);
uint64_t got_addr = MachOGetSectionAddr((unsigned char *)MMapped, oh_my_got);
if (!got_size)
{
oh_my_got = "__DATA_CONST.__got";
got_off = MachOGetSectionOffset((unsigned char *)MMapped, oh_my_got);
got_size = MachOGetSectionSize((unsigned char *)MMapped, oh_my_got);
got_addr = MachOGetSectionAddr((unsigned char *)MMapped, oh_my_got);
}
int companionFileFD = 0;
if (!stubs_size)
{
fprintf(stderr, "Unable to find __TEXT.__stubs in kext %s. Won't symbolicate\n", Name);
return (-1);
}
// Otherwise, we're here, and found the stubs. Iterate over stubs section, instruction by instruction,
// Looking for following pattern:
// fffffff00405e664 d0000010 ADRP X16, 2 ; ->R16 = 0xfffffff004060000
// fffffff00405e668 f9400210 LDR X16, [X16, #0] ; -R16 = *(R16 + 0) = *(0xfffffff004060000) = 0xfffffff007578748 ... ?..
// fffffff00405e66c d61f0200 BR X16 ; 0xfffffff007578748
// And at the BR, attempt to see what it is we are branching to (based on X16's value).
// We can actually use our disassembly callback here, disassembling three instructions at a time
// But this shows another usage of machlib
// register_disassembled_register_call_callback (function_identifier);
int pos = 0;
if (g_jdebug)
fprintf(stderr, "Symbolicating stubs for %s from off 0x%x\n", Name, stubs_off);
while (pos < stubs_size)
{
// Take the scenic route and actually disassemble the instructions.
// This is longer, but certainly safer and more accurate should AAPL
// decide to ever change the format. It would have been simpler to
// iterate over the stubs themselves (in __DATA.__got) since compiler
// emits them in corresponding order..
disassembled_instruction inst1;
disassembled_instruction inst2;
disassembled_instruction inst3;
disassARM64Instr((splitKext ? splitKext : MMapped) + stubs_off + pos, stubs_addr + pos, &inst1);
disassARM64Instr((splitKext ? splitKext : MMapped) + stubs_off + pos + 4, stubs_addr + pos + 4, &inst2);
disassARM64Instr((splitKext ? splitKext : MMapped) + stubs_off + pos + 8, stubs_addr + pos + 8, &inst3);
if (strcmp(inst1.mnemonic, "ADRP") ||
strcmp(inst2.mnemonic, "LDR") ||
strcmp(inst3.mnemonic, "BR"))
{
fprintf(stderr, "0x%x\n", *((uint32_t *)((splitKext ? splitKext : MMapped) + stubs_off + pos)));
fprintf(stderr, "Warning: Error in disassembly - got %s,%s,%s..\n",
inst1.mnemonic, inst2.mnemonic, inst3.mnemonic);
}
else
{
// Can't use this just yet. @TODO
// We can also verify that the registers in all instructions match,
// (i.e. not necessarily R16, but that we ADRP, LDR and BR to same
// register. But that's unnecessary at this point.
//doInstr(&inst1, 0);
//doInstr(&inst2, 0);
//doInstr(&inst3, 0);
uint64_t reg = inst1.immediate;
uint64_t off = inst2.immediate;
uint64_t stub = reg + off;
struct symtabent *sym = NULL;
// if (g_jdebug)
char res[1024];
if (stub >= got_addr && stub <= got_addr + got_size)
{
// Can actually just go by offset in got.. don't need to get
// offset, because we know it's inside section
uint64_t *resolved = getPointerToAddr(stub);
if (splitKext || !resolved)
{
off = stub - got_addr + got_off;
resolved = ((uint64_t *)(splitKext + off));
}
if (g_jdebug)
fprintf(stderr, "Stub at 0x%llx (offset 0x%x) is 0x%llx\n", stub, off, *resolved);
if (resolved)
sym = getClosestSymbol(*resolved, // unsigned long long addr,
kernelSymTable); // struct symtabent *symtab);
if (!sym)
{
fprintf(stderr, "Unable to resolve kernel symbol at %llx (this is fine if it's a symbol from another kext)\n", *resolved);
sprintf(res, "unknown_0x%llx", resolved);
}
else
{
if (g_jdebug)
fprintf(stderr, "Symbol at 0x%llx is %s (0x%llx)\n",
resolved, sym->sym, sym->ptr);
strcpy(res, sym->sym);
}
if (!companionFileFD)
{
// time to open companionFileFD
sprintf(filename, "%s.ARM64.%s", buf, getUUID(mmapped));
companionFileFD = open(filename, O_RDWR | O_CREAT);
if (companionFileFD < 0)
{
fprintf(stderr, "Unable to open companion file %s.. Not symoblicating this kext\n");
return 0;
}
// else fprintf(stderr,"Opened companion file %s\n", filename);
fchmod(companionFileFD, 0666);
}
sprintf(buf, "%llx:%s.stub\n", stubs_addr + pos, res);
// if (jtoolOutFD > 0) write (jtoolOutFD, buf, strlen(buf));
write(companionFileFD, buf, strlen(buf));
}
else
fprintf(stderr, "Warning: Resolved stub in %s falls outside GOT (0x%llx not in 0x%llx-0x%llx)\n", Name, stub, got_addr, got_addr + got_size);
sym = NULL;
} //
pos += 12;
}
char *segName = NULL;
xnu3757_and_later = MachOGetSection("__DATA_CONST.__const");
if (xnu3757_and_later)
{
segName = "__DATA_CONST.__const";
jtoolOutFD = companionFileFD;
int foundPolicy = doPolicyOps(splitKext, segName);
jtoolOutFD = 0;
}
if (pos != stubs_size)
{
fprintf(stderr, "Warning: Disassembly left some unhandled instructions!\n");
}
close(companionFileFD);
fprintf(stderr, "Symbolicated stubs to %s\n", filename);
if (filename && (strstr(filename, "sandbox")))
{
if (xnu3757_and_later)
{
fprintf(stderr, "This is the sandbox.kext - Trying to get seatbelt-profiles\n");
if (doSandboxOperationNames(splitKext, "__TEXT.__cstring"))
{
fprintf(stderr, "Can't get profiles with sandbox operation names\n");
}
doSandboxProfiles(splitKext, "__TEXT.__const");
}
}
return 0;
}
int doKextract(char *mmapped, char *Name, int Size)
{
uint32_t magic = MH_MAGIC;
uint32_t magic64 = MH_MAGIC_64;
uint32_t *magicAtAddress = (uint32_t *)mmapped;
//printf("KEXTRACTING FROM %p\n", mmapped);
if ((*magicAtAddress != MH_MAGIC) &&
(*magicAtAddress != MH_MAGIC_64))
{
fprintf(stderr, "No magic at extraction address (0x%x)!\n", *magicAtAddress);
return -5;
}
// if (((int)mmapped) & 0xfff) return 0;
if (g_jdebug)
fprintf(stderr, "kextracting %s from %p\n", Name, mmapped);
// Extract - create a file, and seek from here to the next Magic
// YES, this will fail on the last kext. But hey - you can fix the
// code easily. I just never need this for anything but AMFI, Sandbox, etc..
char *nextMagic = mmapped + 0x1000;
while (memcmp(nextMagic, magicAtAddress, sizeof(uint32_t)) != 0)
{
nextMagic += 0x10;
// printf("Next %p\n",nextMagic);
}
Size = nextMagic - mmapped;
unsigned char *kextCopy = (unsigned char *)malloc(Size);
memcpy(kextCopy, mmapped, Size);
uint32_t __DATA__data_off = MachOGetSectionOffset(kextCopy, "__DATA.__data");
segments = processFile(kextCopy, Size, getKernelCacheArch(), 0, 0, 0);
uint32_t __DATA__data_size = MachOGetSectionSize(kextCopy, "__DATA.__data");
uint32_t __DATA__CONST_const_off = MachOGetSectionOffset(kextCopy, "__DATA_CONST.__const");
// Ok - we're here, so..
int split = 0;
char *d = getenv("JOKER_DIR");
if (!d)
d = "/tmp";
char dumped[1024];
snprintf(dumped, 1024, "%s/%s.kext", d, Name);
int fd = open(dumped, O_RDWR | O_CREAT | O_TRUNC);
printf("Writing kext out to %s\n", dumped);
if (fd < 0)
{
printf("Unable to create file %s!\n", Name);
return -2;
}
fchmod(fd, 0666);
if (__DATA__CONST_const_off ||
xnu3757_and_later)
{
split = 1;
if (g_jdebug)
fprintf(stderr, "This is a split kext. There's other parts, too...:\n");
// iterate over the segments
extern struct load_command *loadCommands[];
int lc = 0;
int writ = 0;
for (lc = 0; loadCommands[lc]; lc++)
{
// Segments hold both segments/sections. We can tell difference by value of SEGMENT_COMMAND
int bw = 0;
struct segment_command_64 *sc = (struct segment_command_64 *)loadCommands[lc];
if (sc->cmd == LC_SEGMENT_64)
{
if (g_jdebug)
fprintf(stderr, "Segment: %s at addr: 0x%llx-0x%llx, offset 0x%llx-0x%llx (Size: 0x%x)\n", sc->segname, sc->vmaddr, sc->vmaddr + sc->vmsize, sc->fileoff, sc->fileoff + sc->filesize, sc->filesize);
int off = lseek(fd, 0, SEEK_CUR);
char *from = mmapped + sc->fileoff;
if (sc->vmaddr >= prelink_data_data_addr &&
sc->vmaddr <= prelink_data_data_addr + prelink_data_data_size)
{
fprintf(stderr, "Workaround for Apple's offset bug in the kernelcache!\n");
from = getKernelCacheStart() + prelink_data_data_offset + (sc->vmaddr - prelink_data_data_addr);
}
bw = write(fd, from, sc->filesize);
if (bw < 0)
{
perror("write");
// this is a BUG in the sc->fileoff!
// have to go by vmaddr
fprintf(stderr, "Unable to write out segment %s of %x bytes (0x%llx) from offset 0x%x-0x%x! Failing!!!\n", sc->segname, sc->filesize, sc->vmaddr, sc->fileoff, sc->fileoff + sc->filesize);
exit(1);
}
// bw= write (fd, (getKernelCacheStart() + sc->fileoff), sc->filesize);
/// fprintf(stderr," BW is 0x%x\n", bw); }
else
{
if (g_jdebug)
fprintf(stderr, "Written out segment %s (0x%llx) from offset 0x%x\n", sc->segname, sc->vmaddr, sc->fileoff);
bw = 0;
}
if (g_jdebug)
{
// fprintf(stderr,"..Written %x bytes (%llx) to offset 0x%x (0x%x)\n", bw,writ, *((((unsigned char *)mmapped) + sc->fileoff)), off);
}
writ += bw;
int patch = sc->fileoff - off;
if (g_jdebug)
fprintf(stderr, "Patching load command %p in kextCopy %p from 0x%x to 0x%x\n", sc, kextCopy, sc->fileoff, off);
sc->fileoff = off;
// Should also do for segments:
int sect = 0;
struct section_64 *sec64 = (struct section_64 *)(sc + 1);
//int extra;
for (sect = 0; sect < sc->nsects; sect++)
{
// extra = sec64->addr & 0xfff;
if (sec64->offset)
{
if (g_jdebug)
{
fprintf(stderr, "Patching section %s from 0x%llx-0x%llx to 0x%llx.. (%llx bytes)\n",
sec64->sectname, sec64->offset, sec64->offset + sec64->size,
(sec64->offset - patch), patch);
}
}
if (sec64->offset)
{
/* char *extraPad = calloc (extra, 1);
write (fd, extraPad,extra);
free(extraPad);
// writ+= extra;
*/
sec64->offset = (sec64->offset - patch);
off += sec64->size;
}
sec64++;
}
off = lseek(fd, 0, SEEK_CUR);
// Pad to a page boundary!
if (off)
{
int pad = 0x1000 - (off % 0x1000);
char *padding = calloc(pad, 1);
if (g_jdebug)
fprintf(stderr, "Padding by 0x%x bytes\n", pad);
write(fd, padding, pad);
writ += pad;
free(padding);
}
} // lc_segment
} // end for
// Now patch header:
if (g_jdebug)
fprintf(stderr, "Applying patched header...\n");
int rc = lseek(fd, 0, 0);
rc = write(fd, kextCopy, 4096);
if (g_jdebug)
fprintf(stderr, " written %d bytes\n", writ);
}
else
{
// Simple case - we have all the kext.
write(fd, mmapped, nextMagic - mmapped);
}
close(fd);
// Want to get the Kext symbol Stubs now!
symbolicateKextStubs(mmapped, nextMagic - mmapped, Name, split);
//printf ("Extracted %s\n", Name);
return (0);
}
void doKexts(char *mmapped, char *kextractThis, int method)
{
int kexts = 0;
// To do the kexts, we load the dictionary of PRELINK_INFO
char *kextPrelinkInfo = (char *)malloc(1000000);
char *kextNamePtr;
char *kextLoadAddr;
char kextName[2560];
char loadAddr[24];
char *temp = kextPrelinkInfo;
char *loadAddrPtr;
char *prelinkAddr;
extern char *g_SegName;
g_SegName = "__PRELINK_INFO";
struct section *segPI = MachOGetSection((unsigned char *)"__PRELINK_INFO.__info");
struct section_64 *segPI64 = (struct section_64 *)segPI;
struct section *segPT = MachOGetSection((unsigned char *)"__PRELINK_TEXT.__text");
struct section_64 *segPT64 = (struct section_64 *)segPT;
if (!segPT64 || !segPI64)
return;
if (kextractThis)
{
if (g_jdebug)
fprintf(stderr, "Attempting to kextract %s\n", kextractThis);
};
uint64_t offsetCorrection = (is64 ? segPT64->addr - segPT64->offset : segPT->addr - segPT->offset);
int offset = (is64 ? segPI64->offset : segPI->offset);
// PRELINK_TEXT will look something link this:
// Mem: 0x8044f000-0x80eee000 File: 0x00406000-0x00ea5000
kextPrelinkInfo = (char *)(mmapped + offset);
temp = kextPrelinkInfo;
if (!temp)
{
printf("Unable to find __PRELINK_INFO\n");
return;
}
kextNamePtr = strstr(temp, "CFBundleName</key>");
if (method == 1)
// This is EXTREMELY quick and dirty, but I can't find a way to load a CFDictionary
// directly from XML data (and be cross platform), so it will do for now..
//
// ... and it's getting dirtier still but at least I fixed the ID=...
// Definitely clean this up sometime... especially now that INFO is used..
//
while (kextNamePtr)
{
temp = strstr(kextNamePtr, "</string>");
prelinkAddr = strstr(kextNamePtr, "_PrelinkExecutableLoadAddr");
if (!prelinkAddr)
{
// prelinkAddr= strstr(kextNamePtr, "_PrelinkExecutable");
if (!prelinkAddr)
{
fprintf(stderr, "Can't determine kext load addr.. This might be a really old kernelcache. Max - trying method #2 for you..\n");
break;
}
}
loadAddrPtr = strstr(prelinkAddr, "0x");
// overflow, etc..
memset(kextName, '\0', 2560);
// fix for ID=..
char *idFix = NULL;
// idFix = strstr(kextNamePtr, ">");
idFix = strnstr(kextNamePtr, "ID=\"", temp - kextNamePtr);
if (!idFix)
idFix = kextNamePtr + 26;
else
idFix = strstr(idFix + 5, "\">") + 2;
strncpy(kextName, idFix, temp - idFix);
// temp = strstr(loadAddrPtr, "</integer>");
char *endOfLoadAddr = strchr(loadAddrPtr, '<');
memset(loadAddr, '\0', 24);
strncpy(loadAddr, loadAddrPtr, 11 + (is64 ? 7 : -1));
if (!kextractThis)
printf("%s: %s ", loadAddr, kextName);
temp += 10;
kextNamePtr = strstr(temp, "CFBundleIdentifier");
if (kextNamePtr)
{
temp = strstr(kextNamePtr, "</string>");
memset(kextName, '\0', 256);
idFix = strnstr(kextNamePtr, "ID=\"", temp - kextNamePtr);
if (!idFix)
idFix = kextNamePtr + 32;
else
idFix = strstr(idFix + 5, "\">") + 2;
strncpy(kextName, idFix, temp - idFix);
if (!kextractThis)
printf("(%s)\n", kextName);
else
{
//printf("FOUND %s\n", kextName);
if ((strcmp(kextractThis, "all") == 0) || strstr(kextractThis, kextName))
{
uint64_t addr;
int rc = sscanf(loadAddr, "%llx", &addr);
if (!rc)
{
fprintf(stderr, "Unable to parse load address %x!\n", loadAddr);
exit(3);
}
printf("Found %s at load address: %llx, offset: %x\n", kextName, addr, addr - offsetCorrection);
(doKextract(mmapped + (addr - offsetCorrection), kextName, 0));
// zzzzz
}
}
}
kextNamePtr = strstr(temp, "CFBundleName</key>");
kexts++;
}
if (g_jdebug)
fprintf(stderr, "--METHOD: %d\n", method);
if (method == 1 && kexts > 50)
{
if (!kextractThis)
fprintf(stderr, "Got %d kexts %s\n", kexts, (kexts > 200 ? "(yowch!)" : ""));
return;
}
else
{
fprintf(stderr, "Number of kexts way too small.. Trying method #2\n", kexts);
}
// Method #2 - applicable for kernel dumps
fprintf(stderr, "Unable to get kexts from __PRELINK_INFO.. going straight for __PRELINK_TEXT\n");
if (!segPT)
{
printf("This is weird. Can't get offset of __PRELINK_TEXT. Giving up..\n");
return;
}
offset = (is64 ? segPT64->offset : segPT->offset);
int size = (is64 ? segPT64->size : segPT->size);
uint32_t machOSig = (is64 ? 0xfeedfacf : 0xfeedface);
int prev = 0;
int k = 1;
int i = 0;
for (i = 0;
i < size;
i += 0x1000)
{
if (memcmp(&mmapped[offset + i], &machOSig, sizeof(uint32_t)) == 0)
{
if (!prev)
{
prev = offset + i;
}
else
{
int kextSize = (offset + i - prev);
struct mach_header_64 *mh = (struct mach_header_64 *)((&mmapped[offset + i]));
if (mh->filetype != 0xb) // change to kext const
{
fprintf(stderr, "Got Mach-O magic but not a kext. Continuing\n");
continue;
}
if (g_jdebug)
fprintf(stderr, "IN KEXT %d (%d/%d), kextSize: %d\n", k,
i, size, kextSize);
if (kextSize + i > size)
{
fprintf(stderr, "kext size reported is greater than remaining dump bytes.. skipping\n");
i++;
continue;
}
char *kextID = identifyKextNew(&mmapped[prev], kextSize, mmapped);
// fallback to older method
if (!kextID)
kextID = identifyKext(&mmapped[prev], kextSize);
if (!kextID)
kextID = "unrecognized.or.unhandledyet.Please.Report.Me";
// process
if (kextractThis)
{
if ((strcmp(kextractThis, "all") == 0) || strstr(kextID, kextractThis))
{
char *kextfile = strdup(kextID);
char *space = strchr(kextfile, '(');
if (space)
space[0] = '\0';
char dumped[1024];
doKextract(mmapped + prev, kextfile, 0);
/*
snprintf(dumped, 1024, "%s/%d.%s.kext",d, k, kextfile);
printf("Writing kext out to %s\n",dumped);
int fd = open (dumped, O_WRONLY | O_TRUNC | O_CREAT);
if (fd < -1) { perror (dumped); }
else
{
fchmod(fd, 0600);
write (fd, &mmapped[prev], (offset +i - prev));
close(fd);
}
*/
free(kextfile);
}
}
else
{ // just print
printf("%d: %s at 0x%x (%x bytes)\n", k, kextID, prev, (offset + i - prev));
}
// if (kextractThis && strstr (kextID, kextractThis)) { exit (doKextract (mmapped + prev, kextractThis)); }
prev = offset + i;
k++;
}
}
} // end for
}
struct sysctl_oid
{
uint32_t ptr_oid_parent;
uint32_t ptr_oid_link;
int oid_number;
int oid_kind;
uint32_t oid_arg1;
int oid_arg2;
uint32_t ptr_oid_name;
uint32_t ptr_oid_handler;
uint32_t ptr_oid_fmt;
uint32_t ptr_oid_descr; /* offsetof() field / long description */
int oid_version;
int oid_refcnt;
};
struct sysctl_oid_64
{
uint64_t ptr_oid_parent;
uint64_t ptr_oid_link;
int oid_number;
int oid_kind;
uint64_t oid_arg1;
int oid_arg2;
uint64_t ptr_oid_name;
uint64_t ptr_oid_handler;
uint64_t ptr_oid_fmt;
uint64_t ptr_oid_descr; /* offsetof() field / long description */
int oid_version;
int oid_refcnt;
};
typedef struct sysctlNamespace
{
char *name;
uint64_t addr;
int resolved;
} sysctlNamespace_t;
sysctlNamespace_t sysctlNamespaces[256];
int sysctlNamespaceCount = 0;
void addSysctlNamespace(uint64_t addr, char *name)
{
// fprintf(stdout," Adding: 0x%llx - %s\n", addr, name);
sysctlNamespaces[sysctlNamespaceCount].name = name;
sysctlNamespaces[sysctlNamespaceCount].addr = addr;
sysctlNamespaces[sysctlNamespaceCount].resolved = (strstr(name, "0x")) ? 0 : 1;
sysctlNamespaceCount++;
}
char *getSysctlNamespaceName(uint64_t Addr)
{
int ns = 0;
for (ns = 0; ns < sysctlNamespaceCount; ns++)
{
if (sysctlNamespaces[ns].addr == Addr)
return sysctlNamespaces[ns].name;
}
return (NULL);
}
char *sysctlName(char *mmapped, uint64_t sysctlPtr)
{
char *name = malloc(1024);
name[0] = '\0';
uint32_t sysCtlOffsetInFile = MachOGetFileOffsetOfAddr(sysctlPtr);
if (sysCtlOffsetInFile == -1)
{
strcat(name, "?");
return (name);
}
struct sysctl_oid *sysctl = (mmapped + sysCtlOffsetInFile);
struct sysctl_oid_64 *sysctl64 = (struct sysctl_oid_64 *)sysctl;
char *parent = MachOLookupSymbolAtAddress((is64 ? sysctl64->ptr_oid_parent : sysctl->ptr_oid_parent),
(unsigned char *)mmapped);
struct section *sec = MachOGetSection((unsigned char *)"__DATA.__sysctl_set");
struct section_64 *sec64 = (struct section_64 *)sec;
if (!sec64)
{
fprintf(stderr, "Unable to get section!\n");
}
// printf("PARENT: %llx, sec: %llx-%llx\n", sysctl64->ptr_oid_parent, sec64->addr, sec64->addr+sec64->size);;
char *parentName = getSysctlNamespaceName(is64 ? sysctl64->ptr_oid_parent : sysctl->ptr_oid_parent);
if (parentName)
{
strcpy(name, parentName);
if (parentName[0])
strcat(name, ".");
}
if (!name)
{
char parentAddr[20];
sprintf(parentAddr, "0x%llx", (is64 ? sysctl64->ptr_oid_parent : sysctl->ptr_oid_parent));
strcpy(name, parentAddr);
strcat(name, ".");
}
uint32_t sysctlNameOffsetInFile = MachOGetFileOffsetOfAddr(is64 ? sysctl64->ptr_oid_name : sysctl->ptr_oid_name);
if (sysctlNameOffsetInFile == -1)
{
strcat(name, "?");
return (name);
}
strcat(name, mmapped + sysctlNameOffsetInFile);
return (name);
} //sysctlName
void doSysctls(char *mmapped, int is64)
{
// assume section 32 for now..
struct section *sec = MachOGetSection((unsigned char *)"__DATA.__sysctl_set");
struct section_64 *sec64 = (struct section_64 *)sec;
if (sec)
{
int numsysctls = (is64 ? sec64->size : sec->size) / (is64 ? sizeof(uint64_t) : sizeof(uint32_t));
int s = 0;
uint64_t offset = (is64 ? sec64->offset : sec->offset);
uint64_t addr = (is64 ? sec64->addr : sec->addr);
uint64_t size = (is64 ? sec64->size : sec->size);
printf("Dumping sysctl_set from 0x%llx (offset in file: 0x%llx), %x sysctls follow:\n", addr, offset, numsysctls);
int i = 0;
for (i = 0; i < 2; i++)
{
// First pass: get namespaces - works better in reverse!
for (s = numsysctls - 1; s >= 0; s--)
{
uint64_t sysctlPtr;
if (is64)
{
sysctlPtr = *((uint64_t *)(mmapped + offset + s * sizeof(uint64_t)));
}
else
sysctlPtr = *((uint32_t *)(mmapped + offset + s * sizeof(uint32_t)));
uint64_t sysctlOffsetInFile = MachOGetFileOffsetOfAddr(sysctlPtr);
// sanity check, anyone?
if (!is64 && (sysctlOffsetInFile > sec->offset + sec->size))
{
printf("(%llx outside __sysctl_set)\n", sysctlPtr);
continue;
};
if (is64 && (sysctlOffsetInFile > offset + size))
{
printf("(%llx is outside __sysctl_set)\n", sysctlPtr);
continue;
};
struct sysctl_oid *sysctl = (mmapped + sysctlOffsetInFile);
struct sysctl_oid_64 *sysctl64 = (struct sysctl_oid_64 *)sysctl;
uint32_t sysctlDescInFile = MachOGetFileOffsetOfAddr(is64 ? sysctl64->ptr_oid_descr : sysctl->ptr_oid_descr);
uint32_t sysctlFormatInFile = MachOGetFileOffsetOfAddr(is64 ? sysctl64->ptr_oid_fmt : sysctl->ptr_oid_fmt);
char *sysctlFormat = "?";
if (sysctlFormatInFile != -1)
{
sysctlFormat = mmapped + sysctlFormatInFile;
}
uint64_t handler = is64 ? sysctl64->ptr_oid_handler : sysctl->ptr_oid_handler;
if (!handler)
{
char *nsname = sysctlName(mmapped, sysctlPtr);
if ((i == 0))
{
if (strstr(nsname, "kperf"))
{
addSysctlNamespace(is64 ? sysctl64->ptr_oid_parent : sysctl->ptr_oid_parent, "");
}
}
else
addSysctlNamespace(is64 ? sysctl64->oid_arg1 : sysctl->oid_arg1, nsname);
}
}
} // 2 passes
// Second pass:
for (s = 0; s < numsysctls; s++)
{
uint64_t sysctlPtr;
if (is64)
{
sysctlPtr = *((uint64_t *)(mmapped + offset + s * sizeof(uint64_t)));
}
else
sysctlPtr = *((uint32_t *)(mmapped + offset + s * sizeof(uint32_t)));
uint64_t sysctlOffsetInFile = MachOGetFileOffsetOfAddr(sysctlPtr);
//printf ("0x%llx: ", sysctlPtr , sysctlOffsetInFile);
// sanity check, anyone?
if (!is64 && (sysctlOffsetInFile > sec->offset + sec->size))
{
printf("(outside __sysctl_set)\n");
continue;
};
if (is64 && (sysctlOffsetInFile > offset + size))
{
printf("(outside __sysctl_set)\n");
continue;
};
struct sysctl_oid *sysctl = (mmapped + sysctlOffsetInFile);
struct sysctl_oid_64 *sysctl64 = (struct sysctl_oid_64 *)sysctl;
uint32_t sysctlDescInFile = MachOGetFileOffsetOfAddr(is64 ? sysctl64->ptr_oid_descr : sysctl->ptr_oid_descr);
uint32_t sysctlFormatInFile = MachOGetFileOffsetOfAddr(is64 ? sysctl64->ptr_oid_fmt : sysctl->ptr_oid_fmt);
char *sysctlFormat = "?";
if (sysctlFormatInFile != -1)
{
sysctlFormat = mmapped + sysctlFormatInFile;
}
uint64_t handler = is64 ? sysctl64->ptr_oid_handler : sysctl->ptr_oid_handler;
if (!handler)
continue; // covered these in first pass...
printf("0x%llx: ", sysctlPtr, sysctlOffsetInFile);
char *name = sysctlName(mmapped, sysctlPtr);
uint64_t arg1 = is64 ? sysctl64->oid_arg1 : sysctl->oid_arg1;
printf((is64 ? "%s\tDescription: %s\n\t\tHandler: 0x%llx\n\t\tFormat: %s\n\t\tParent: 0x%llx\n\t\tArg1: %llx\n\t\tArg2: 0x%llx\n"
: "%s\tDescription: %s\n\t\tHandler: 0x%x\n\t\tFormat: %s\n\t\tParent: 0x%x\n\t\tArg1: %x\n\t\tArg2: 0x%x\n"),
name,
mmapped + sysctlDescInFile,
handler,
sysctlFormat,
is64 ? sysctl64->ptr_oid_parent : sysctl->ptr_oid_parent,
arg1,
is64 ? sysctl64->oid_arg2 : sysctl->oid_arg2);
if ((arg1 > 0x80000000) && wantJToolOut)
{
char output[1024];
addSymbolToCache(name, arg1, NULL);
// sprintf (output, "0x%llx:%s\n", arg1, name);
// write (jtoolOutFD, output, strlen(output));
}
}
}
} // doSysctls
void doMachTraps(char *mmapped, int xnu32xx)
{
char *zeros = calloc(24, 1);
struct section_64 *segDC = MachOGetSection((unsigned char *)"__DATA.__const");
if (!segDC)
segDC = MachOGetSection((unsigned char *)"__CONST.__constdata");
if (!segDC)
{
segDC = MachOGetSection((unsigned char *)"__DATA_CONST.__const");
}
if (!segDC)
{
fprintf(stderr, "No __DATA.__const or __CONST??!\n");
return;
}
struct section *segDC32 = (struct section *)segDC;
int offset = (is64 ? segDC->offset : segDC32->offset);
int adv = (is64 ? 8 : 4);
int i = 0;
char *mach = NULL;
char *pos = mmapped + offset;
uint64_t segAddr = (is64 ? segDC->addr : segDC32->addr);
uint32_t segOffset = (is64 ? segDC->offset : segDC32->offset);
int segSize = (is64 ? segDC->size : segDC32->size);
int skip = (is64 ? 3 : 5);
for (i = 0; i < segSize; i += adv)
// Ugly, I know, but works in both 32 and 64-bit cases
if ((((memcmp(&pos[i], zeros, skip * adv) == 0) &&
(memcmp(&pos[i + (skip + 1) * adv], zeros, skip * adv) == 0) &&
(memcmp(&pos[i + 2 * (skip + 1) * adv], zeros, skip * adv) == 0) &&
(memcmp(&pos[i + 3 * (skip + 1) * adv], zeros, skip * adv) == 0) &&
(memcmp(&pos[i + 4 * (skip + 1) * adv], zeros, skip * adv) == 0) &&
((*((uint64_t *)&pos[i - adv])) && *((int64_t *)&pos[i + skip * adv])))))
{
printf("mach_trap_table offset in file/memory (for patching purposes): 0x%x/%llx\n", segOffset + i, segAddr + i);
mach = &pos[i] - adv;
dumpMachTraps(mach, is64);
break;
}
} // doMachTraps
void doMIG(char *mmapped, int xnu32xx)
{
struct section_64 *segDC = MachOGetSection((unsigned char *)"__DATA.__const");
if (!segDC)
segDC = MachOGetSection((unsigned char *)"__CONST.__constdata");
if (!segDC)
{
segDC = MachOGetSection((unsigned char *)"__DATA_CONST.__const");
}
if (!segDC)
{
fprintf(stderr, "No __DATA.__const?!\n");
return;
}
struct section *segDC32 = (struct section *)segDC;
int offset = (is64 ? segDC->offset : segDC32->offset);
int adv = (is64 ? 8 : 4);
int i = 0;
char *pos = mmapped + offset;
uint32_t subsysMachVM = 0;
uint32_t subsysTask = 0;
uint64_t segAddr = (is64 ? segDC->addr : segDC32->addr);
int segSize = (is64 ? segDC->size : segDC32->size);
for (i = 0; i < segSize; i += adv)
{
if (memcmp(&pos[i], &mach_vm_subsys, 8) == 0)
{
printf("mach_vm_subsystem is @0x%llx!\n", segAddr + i - adv);
subsysMachVM = offset + i;
dumpMIGSubsystem((mig_subsys *)(pos + i), &mach_vm_subsys, is64);
}
if (memcmp(&pos[i], &thread_act_subsys, 8) == 0)
{
printf("thread_act_subsystem is @0x%llx!\n", segAddr + i - adv);
dumpMIGSubsystem((mig_subsys *)(pos + i), &thread_act_subsys, is64);
}
if (memcmp(&pos[i], &mach_port_subsys, 8) == 0)
{
printf("mach_port_subsystem is @0x%llx!\n", segAddr + i - adv);
dumpMIGSubsystem((mig_subsys *)(pos + i), &mach_port_subsys, is64);
}
if (memcmp(&pos[i], (xnu32xx ? &is_iokit_subsys_9 : &is_iokit_subsys), 4) == 0)
{
printf("is_iokit_subsystem is @0x%llx!\n", segAddr + i - adv);
dumpMIGSubsystem((mig_subsys *)(pos + i), &is_iokit_subsys, is64);
}
if (memcmp(&pos[i], (&processor_subsys), 8) == 0)
{
printf("processor_subsystem is @0x%llx!\n", segAddr + i - adv);
dumpMIGSubsystem((mig_subsys *)(pos + i), &processor_subsys, is64);
}
if (memcmp(&pos[i], (&processor_set_subsys), 8) == 0)
{
printf("processor_set_subsystem is @0x%llx!\n", segAddr + i - adv);
dumpMIGSubsystem((mig_subsys *)(pos + i), &processor_set_subsys, is64);
}
if (memcmp(&pos[i], (&host_security_subsys), 8) == 0)
{
printf("host_security_subsystem is @0x%llx!\n", segAddr + i - adv);
dumpMIGSubsystem((mig_subsys *)(pos + i), &host_security_subsys, is64);
}
if (memcmp(&pos[i], &host_priv_subsys, 8) == 0)
{
printf("host_priv_subsystem is @0x%llx!\n", segAddr + i - adv);
dumpMIGSubsystem((mig_subsys *)(pos + i), &host_priv_subsys, is64);
}
if (memcmp(&pos[i], (&mach_host_subsys_9), 4) == 0)
{
printf("mach_host_subsystem is @0x%llx!\n", segAddr + i - adv);
dumpMIGSubsystem((mig_subsys *)(pos + i), &mach_host_subsys_9, is64);
}
if (memcmp(&pos[i], &task_subsys, 4) == 0)
{
printf("task_subsystem is @0x%llx!\n", segAddr + i - adv);
subsysTask = offset + i;
dumpMIGSubsystem((mig_subsys *)(pos + i), &task_subsys, is64);
}
}
} //doMig
uint64_t look_for_inst(char *Func, uint32_t Inst, char *Where, int Size, uint64_t addr, int jtoolOutFD)
{
// fprintf(stderr,"Looking for %s ...\n", Func);
char *found = memmem(Where, Size, &Inst, 4);
if (found)
{
fprintf(stderr, "Found %s at offset 0x%x, Addr: 0x%llx\n",
Func,
found - (Where),
addr + (found - Where));
addSymbolToCache(Func, addr + (found - Where), NULL);
//char output[1024];
// sprintf(output, "%llx:_%s\n", addr + (found - Where), Func);
//write (jtoolOutFD, output, strlen(output));
}
return (addr + (found - Where));
} // look_for_inst
struct compHeader
{
char sig[8]; // "complzss"
uint32_t unknown; // Likely CRC32. But who cares, anyway?
uint32_t uncompressedSize;
uint32_t compressedSize;
uint32_t unknown1; // 1
};
char *tryLZSS(char *compressed, int *filesize)
{
struct compHeader *compHeader = strstr(compressed, "complzss");
if (!compHeader)
return (NULL);
fprintf(stderr, "Feeding me a compressed kernelcache, eh? That's fine, now. I can decompress! ");
if (!g_dec)
fprintf(stderr, "(Type -dec _file_ if you want to save to file)!");
fprintf(stderr, "\nCompressed Size: %d, Uncompressed: %d. Unknown: 0x%x, Unknown 1: 0x%x\n",
ntohl(compHeader->compressedSize),
ntohl(compHeader->uncompressedSize),
ntohl(compHeader->unknown),
ntohl(compHeader->unknown1));
int sig[2] = {0xfeedfacf, 0x0100000c};
// But check for KPP:
char *found = NULL;
if ((found = memmem(mmapped + 0x2000, *filesize, "__IMAGEEND", 8)))
{
// the 0xfeedfacf before that is kpp..
char *kpp = memmem(found - 0x1000, 0x1000, sig, 4);
if (kpp)
{
fprintf(stderr, "btw, KPP is at %lld (0x%x)", kpp - mmapped, kpp - mmapped);
int out = open("/tmp/kpp", O_TRUNC | O_CREAT | O_WRONLY);
if (out < 0)
{
fprintf(stderr, "But I can't save it for you\n");
exit(3);
}
fchmod(out, 0600);
write(out, kpp, *filesize - (kpp - mmapped));
close(out);
fprintf(stderr, "..And I saved it for you in /tmp/kpp\n");
}
}
// For lzss I'm using code verbatim from BootX, which, like Apple, is ripped from
// Haruhiko Okumura (CompuServe 74050,1022, if anyone can find him to thank him from me!)
// Code is: from BootX-81//bootx.tproj/sl.subproj/lzss.c
//
// The code is in the public domain, Stefan, I'm not stealing anything.
// Unlike people who never credit OpenSSL in their Apps ;-)
//
// I trust AAPL to report sizes and not give me a heap overflow now ;-)
char *decomp = malloc(ntohl(compHeader->uncompressedSize));
// find kernel 0xfeedfa... If I ever support 32-bit, I'll need faCE or faCF..
int MachOSig = 0xfeedfacf;
char *feed = memmem(mmapped + 64, 1024, &MachOSig, 3);
if (!feed)
{
fprintf(stderr, "Can't find kernel here.. Sorry. LZSS this yourself\n");
exit(5);
}
else
{
fprintf(stderr, "Got kernel at %d\n", feed - mmapped);
}
feed--;
int rc = decompress_lzss(decomp,
feed,
ntohl(compHeader->compressedSize));
if (rc != ntohl(compHeader->uncompressedSize))
{
fprintf(stderr, "Expected %d bytes ... Got %d bytes. Aborting\n",
ntohl(compHeader->uncompressedSize), rc);
}
*filesize = rc;
if (g_dec)
{
int fd = open("/tmp/kernel", O_WRONLY | O_CREAT | O_TRUNC);
if (fd < 0)
{
fprintf(stderr, "Can't write decompressed kernel to /tmp/kernel...\n");
}
else
{
fchmod(fd, 0600);
write(fd, decomp, ntohl(compHeader->uncompressedSize));
close(fd);
}
}
return (decomp);
} // compLZSS
int main(int argc, char **argv)
{
int xnu24xx = 0;
int xnu27xx = 0;
int xnu32xx = 0;
int xnu37xx = 0;
int iOS = 0;
g_jdebug = (getenv("JDEBUG") != NULL);
int fd;
int rc;
struct stat stbuf;
int filesize;
filename = argv[1];
struct mach_header *mh;
int i, j;
int magic;
char *sysent = NULL;
uint64_t sysentAddr;
char *mach = NULL;
char *xnuSig = NULL;
int showUNIX = 0, showMach = 0;
int suppressEnosys = 1;
int suppressOld = 1;
int showVersion = 0;
int showKexts = 0;
int showSysctls = 0;
char *kextName = NULL;
int kextract = 0;
FILE *jtoolOutFile = NULL;
if (!filename)
{
fprintf(stderr, "Usage: joker [-j] [-MmaSsKk] _filename_\n", argv[0]);
fprintf(stderr, " _filename_ should be a decrypted iOS kernelcache, or kernel dump. Tested on ARMv7/s 3.x-9.3, and ARM64 through 10.0.1GM\n\n");
fprintf(stderr, " -m: dump Mach Traps and MIG tables (NEW)\n");
fprintf(stderr, " -a: dump everything\n");
fprintf(stderr, " -k: dump kexts\n");
fprintf(stderr, " -K: kextract [kext_bundle_id_or_name_shown_in_-k|all] to JOKER_DIR or /tmp\n");
fprintf(stderr, " -S: dump sysctls\n");
fprintf(stderr, " -s: dump UNIX syscalls\n");
fprintf(stderr, " -j: Jtool compatible output (to companion file)\n");
fprintf(stderr, "\n-dec: Decompress kernelcache to /tmp/kernel (complzss only at this stage)\n");
fprintf(stderr, "\nKernels not included. Get your own dump or decrypted kernel from iPhoneWiki, or Apple itself (as of iOS 10b1! Thanks, guys!)\n");
fprintf(stderr, "\n3.0 with MACF Policies, stub symbolication, SPLIT KEXTS, Sandbox Profiles (beta, collections only at this point) , kpp and (coming soon) IOUserClients!\nCompiled on " __DATE__ "\n");
#ifdef HAVE_LZSS
fprintf(stderr, "\nContains code from Haruhiko Okumura (CompuServe 74050,1022) from BootX-81//bootx.tproj/sl.subproj/lzss.c\n");
#endif
exit(0);
}
if (filename[0] == '-')
{
showVersion = (filename[1] == 'v' ? 1 : 0);
filename = argv[2];
};
int arg = 0;
for (arg = 1; arg < argc - 1; arg++)
{
if (strcmp(argv[arg], "-k") == 0)
{
showKexts = 1;
showUNIX = 0;
showMach = 0;
};
if (strcmp(argv[arg], "-K") == 0)
{
kextract = 1;
kextName = argv[arg + 1];
filename = argv[argc - 1];
showUNIX = 0;
showMach = 0;
};
if (strcmp(argv[arg], "-S") == 0)
{
showSysctls = 1;
filename = argv[2];
};
if (strcmp(argv[arg], "-a") == 0)
{
showSysctls = 1;
showKexts = 1;
filename = argv[2];
showUNIX = showMach = 1;
};
if (strcmp(argv[arg], "-m") == 0)
{
showMach = 1;
};
if (strcmp(argv[arg], "-s") == 0)
{
showUNIX = 1;
};
if (strcmp(argv[arg], "-dec") == 0)
{
g_dec = 1;
}
if (strcmp(argv[arg], "-j") == 0)
{
wantJToolOut = 1;
}
}
filename = argv[argc - 1];
rc = stat(filename, &stbuf);
if (rc == -1)
{
perror(filename);
exit(1);
}
filesize = stbuf.st_size;
fd = open(filename, O_RDONLY);
if (fd < 0)
{
perror("open");
exit(2);
}
mmapped = mmap(NULL,
filesize, // size_t len,
PROT_READ, // int prot,
MAP_SHARED | MAP_FILE, // int flags,
fd, // int fd,
0); // off_t offset);
if (!mmapped)
{
perror("mmap");
exit(3);
}
int xnu = 0;
// Examine first
retry:
mh = (struct mach_header *)(mmapped);
if (mh->cputype == 12 || mh->cputype == 16777228) /* ARM */
{
iOS = 1;
}
else
{
iOS = 0;
}
switch (mh->magic)
{
case 0x496d6733: // IMG3
fprintf(stderr, "Not handling IMG3. 32-bit is passe', man\n");
exit(0);
case 0xFEEDFACE:
/* Good, this is a Mach-O */
// This is an ARM binary. Good.
setKernelCacheArch(CPU_TYPE_ARM);
setKernelCacheStart(mmapped);
segments = processFile((unsigned char *)mmapped, filesize, CPU_TYPE_ARM, 0, 0, 0);
break;
case 0xFEEDFACF:
setKernelCacheArch(CPU_TYPE_ARM64);
setKernelCacheStart(mmapped);
segments = processFile((unsigned char *)mmapped, filesize, CPU_TYPE_ARM64, 0, 0, 0);
is64++;
break;
case 0xbebafeca:
fprintf(stderr, "This is an Intel FAT binary, but I can't handle these yet\n");
exit(5);
default:
{
// Could be we were fed a kernelcache
int origSize = filesize;
char *mem = tryLZSS(mmapped, &filesize);
if (!mem)
{
fprintf(stderr, "I have no idea how to handle a file with a magic of 0%x\n", magic);
exit(6);
}
munmap(mmapped, origSize);
mmapped = mem;
goto retry;
}
}
// Got segments - get PLK_DATA_
prelink_data_data_addr = MachOGetSectionAddr(mmapped, "__PRELINK_DATA.__data");
prelink_data_data_offset = MachOGetSectionOffset(mmapped, "__PRELINK_DATA.__data");
prelink_data_data_size = MachOGetSectionSize(mmapped, "__PRELINK_DATA.__data");
struct source_version_command *svc = (struct source_version_command *)findLoadCommand((unsigned char *)mmapped, LC_SOURCE_VERSION, NULL);
struct uuid_command *uuidc = (struct uuid_command *)findLoadCommand((unsigned char *)mmapped, LC_UUID, NULL);
if (filesize > 2000000)
{
xnu = 1;
}
if (xnu && svc && (svc->version >> 40) >= 2423)
{
if ((svc->version >> 40) >= 3789)
{
xnu37xx = 1;
xnu3757_and_later = 1;
fprintf(stdout, "This is a %d-bit kernel from %s, or later ",
(is64 ? 64 : 32),
(iOS ? "iOS 10.x (b7+)" : "OS X (Sorry, \"MacOS\" 10.12b7)"));
}
else if ((svc->version >> 40) >= 3777)
{
xnu37xx = 1;
xnu3757_and_later = 1;
fprintf(stdout, "This is a %d-bit kernel from %s, or later ",
(is64 ? 64 : 32),
(iOS ? "iOS 10.x (b3+)" : "OS X (Sorry, \"MacOS\" 10.12b3)"));
}
else if ((svc->version >> 40) >= 3757)
{
xnu37xx = 1;
xnu3757_and_later = 1;
fprintf(stdout, "This is a %d-bit kernel from %s, or later ",
(is64 ? 64 : 32),
(iOS ? "iOS 10.x (b2+)" : "OS X (Sorry, \"MacOS\" 10.12)"));
}
else if ((svc->version >> 40) >= 3705)
{
xnu37xx = 1;
fprintf(stdout, "This is a %d-bit kernel from %s, or later ",
(is64 ? 64 : 32),
(iOS ? "iOS 10.x" : "OS X (Sorry, \"MacOS\" 10.12)"));
}
else if ((svc->version >> 40) >= 3216)
{
xnu32xx = 1;
fprintf(stdout, "This is a %d-bit kernel from %s, or later ",
(is64 ? 64 : 32),
(iOS ? "iOS 9.x" : "OS X 10.11"));
}
else if ((svc->version >> 40) >= 2780)
{
fprintf(stdout, "This is a %d-bit kernel from %s, or later ",
(is64 ? 64 : 32),
(iOS ? "iOS 8.x" : "OS X 10.10"));
xnu27xx = 1;
}
else
xnu24xx = 1;
}
//else this is a kext
if (!xnu)
{
fprintf(stdout, "This is %s\n", identifyKextNew(mmapped, filesize, mmapped));
}
else if (svc)
{
fprintf(stdout, "(%ld.%d.%d.%d.%d)\n",
(long)((svc->version) >> 40),
(int)(svc->version >> 30) & 0x000003FF,
(int)(svc->version >> 20) & 0x000003FF,
(int)(svc->version >> 10) & 0x000003FF,
(int)(svc->version) & 0x000003FF);
}
else
{
fprintf(stdout, "(No LC_SOURCE_VERSION.. your dump may be corrupt.. or this might be a really old kernel!)\n");
}
if (wantJToolOut)
{
extern char *g_fileName;
g_fileName = filename;
jtoolOutFD = openCompanionFileName(mmapped, 2);
if (jtoolOutFD)
fprintf(stderr, "Opening companion file\n");
}
uint32_t numSyms;
struct symtabent *symTable = MachOGetSymbols(mmapped, filesize, &numSyms); // uint32_t *numsyms)
//struct symtabent *symTable = NULL;
if (symTable)
{
if (g_jdebug)
fprintf(stderr, "Got %d syms from kernel\n", numSyms);
kernelSymTable = symTable;
}
else
{
if (xnu)
printf("Unable to get symbols from SYMTAB (fine for dumps)\n");
}
int wantDis = 1;
if (wantDis)
{
if (wantJToolOut)
{
char *seg = "__TEXT.__text";
uint64_t addr = MachOGetSectionAddr(mmapped, seg);
if (!addr)
{
seg = "__TEXT_EXEC.__text";
addr = MachOGetSectionAddr(mmapped, seg);
}
uint32_t offset = MachOGetSectionOffset(mmapped, seg);
uint32_t size = MachOGetSectionOffset(mmapped, seg);
uint32_t SMC_inst = 0xd4000223;
uint64_t SMC_inst_addr = look_for_inst("_secure_monitor", SMC_inst, mmapped + offset, size, addr, jtoolOutFD);
uint32_t start_cpu = 0xd5034fdf; // DAIFSet ... #15
uint64_t start_cpu_addr = look_for_inst("_start_cpu", start_cpu, mmapped + offset, size, addr, jtoolOutFD);
register_disassembled_function_call_callback(function_identifier);
printf("Auto-Disassembling %s from 0x%llx to find rest..\n", seg, addr);
printf("This may take a little while, but you only need to do this once\n");
disassemble(mmapped,
addr,
segments,
DISASSEMBLE_QUIET,
DISASSEMBLE_END_OF_SECTION);
}
}
//printf ("Entry point is 0x%llx..", getEntryPoint());
for (i = 0;
i < filesize - 50;
i++)
{
if (!xnu)
break;
if (!xnuSig && memcmp(&mmapped[i], XNUSIG, strlen(XNUSIG)) == 0)
{
/* Could actually get the version from LC_SOURCE_VERSION... */
char buf[80];
xnuSig = mmapped + i + strlen(XNUSIG);
memset(buf, '\0', 80);
strncpy(buf, xnuSig, 40);
// The signature we get is from a panic, with the full path to the
// xnu sources. Remove the "/" following the XNU version. Because the
// memory is mmap(2)ed read only, we have to copy this first.
char *temp = strstr(buf, "/");
if (temp)
{
*temp = '\0';
}
xnuSig = buf;
if (showVersion)
{
printf("This is XNU %s\n", xnuSig);
exit(0);
}
}
if (memcmp(&mmapped[i], ARMExcVector, 8) == 0)
{
sysentAddr = findAddressOfOffset(i - 28);
if (showUNIX)
printf("ARM Exception Vector is at file offset @0x%x (Addr: 0x%llx)\n", i - 28, findAddressOfOffset(i - 28));
}
int ARM64_exception_vector_base = 0xd5385201;
if (memcmp(&mmapped[i], &ARM64_exception_vector_base, 4) == 0)
{
if (!((i - 8) & 0xfff))
{
printf("ARM64 Exception Vector is at file offset @0x%x (Addr: 0x%llx)\n", i - 8, findAddressOfOffset(i - 8));
if (jtoolOutFD > 0)
{
char output[1024];
uint64_t addr = findAddressOfOffset(i - 8);
sprintf(output, "0x%llx:ARM64ExceptionVectorBase\n0x%llx:Synchronous_handler\n0x%llx:IRQ_vIRQ_handler\n0x%llx:FIQ_vFIQ\n0x%llx:SError_vSError\n",
addr, addr, addr + 0x80, addr + 0x100,
addr + 0x180);
/*
0x4100003000:synchronous_handler
0x4100003080:IRQ/vIRQ
0x4100003100:FIQ/vFIQ
0x4100003180:SError/vSError
0x4100003200:synchronous_SPx
0x4100003280:IRQ/vIRQ_SPx
0x4100003300:FIQ/vFIQ_SPx
0x4100003380:SError/vSError_SPx
0x4100003400:synchronous_Lower_EL
0x4100003480:IRQ/vIRQ_Lower_EL
0x4100003500:FIQ/vFIQ_SPx
0x4100003580:SError/vSError_Lower_EL
*/
write(jtoolOutFD, output, strlen(output));
output[0] = '\0';
}
}
}
if (xnu27xx || xnu32xx || xnu37xx)
{
if ((memcmp(&mmapped[i], SIG1_IOS8X, 8) == 0) &&
(memcmp(&mmapped[i + 0x18], SIG1_AFTER_0x18_IOS8X, 8) == 0))
{
sysentAddr = findAddressOfOffset(i - 0x10);
printf("Found iOS 8+ sysent table @%x (Addr: 0x%llx)\n", i - 0x10, findAddressOfOffset(i - 0x10));
sysent = mmapped + i - 0x10;
}
} // xnu27xx
else
{
if (memcmp(&mmapped[i], SIG1, 20) == 0)
{
if (memcmp(&mmapped[i + 24], SIG1_SUF, 16) == 0)
{
sysent = mmapped + i - 24;
// if (xnuSig) break;
}
}
if ((memcmp(&mmapped[i], SIG1_IOS7X, 16) == 0) &&
(memcmp(&mmapped[i + 20], SIG2_IOS7X, 16) == 0) &&
(memcmp(&mmapped[i + 40], SIG1_IOS7X, 16) == 0))
{
sysent = mmapped + i - 24;
// if (xnuSig) break;
}
} // ! iOS 8
// Can and should actually rewrite this to a) read from the __const section and b) be 32/64-bit agnostic
} // end for i..
if (xnu && !xnuSig)
{
fprintf(stderr, "This doesn't seem to be a kernel! Continuing anyway..\n");
}
if (!sysent && is64)
{
struct section_64 *segDC = MachOGetSection((unsigned char *)"__DATA.__const");
if (!segDC)
{
segDC = MachOGetSection((unsigned char *)"__CONST.__constdata");
}
if (!segDC)
{
segDC = MachOGetSection((unsigned char *)"__DATA_CONST.__const");
}
if (!segDC)
{
fprintf(stderr, "No __DATA.__const or CONST?!\n");
return 0;
}
int offset = (is64 ? segDC->offset : segDC->offset);
int i = 0;
char *pos = mmapped + offset;
int adv = 8;
for (i = 0; i < segDC->size; i += adv)
{
if (memcmp(&pos[i], SIG_SYSCALL_3, 8) == 0)
{
// if (memcmp (&pos[i] + 0x18, SIG_SYSCALL_3,8) == 0) printf("DOUBLE BINGO\n");
sysent = pos + i - 0x10 - (3 * 0x18);
sysentAddr = segDC->addr + i - 0x10 - (3 * 0x18);
// Can double check since same sig is also at + 0x18 from here..
// Bingo!
break;
}
}
}
if (showMach)
doMachTraps(mmapped, xnu32xx || xnu37xx);
if (showMach)
doMIG(mmapped, xnu32xx || xnu37xx);
if (showUNIX && sysent)
{
if (memcmp(&mmapped[i], "syscall\0exit", 12) == 0)
{
// syscall_names = &mmapped[i];
printf("Syscall names are @%x\n", i);
}
printf("Syscalls at address 0x%llx\n", sysentAddr);
if (is64)
printf("Sysent offset in file (for patching purposes): %lx\n", (sysent - mmapped));
uint64_t enosys, old = 0;
if (suppressEnosys)
{
enosys = (xnu27xx || xnu32xx || xnu37xx) ? *((int *)(sysent + 0x60)) : *((int *)(sysent + 20 + 24 * 4));
old = (xnu27xx || xnu32xx || xnu37xx) ? *((int *)(sysent + 0x60 + 30 * 12)) : *((int *)(sysent + 20 + 24 * 4));
if (is64)
{
// enosys is at syscall 0
enosys = *(uint64_t *)sysent;
// old is at syscall 8
old = *(((uint64_t *)sysent) + (8 * 0x3));
}
printf("Suppressing enosys (%llx) and old (%llx)\n", enosys, old);
}
int maxsyscall = SYS_MAXSYSCALL;
if (xnu24xx)
maxsyscall = SYS_MAXSYSCALL_7;
if (xnu27xx)
maxsyscall = SYS_MAXSYSCALL_8;
if (xnu32xx)
maxsyscall = SYS_MAXSYSCALL_9;
if (xnu37xx)
maxsyscall = SYS_MAXSYSCALL_10;
for (i = 0; i < maxsyscall; i++)
{
int suppress = 0;
int thumb = 0;
int jump = (xnu24xx ? 20 : 24);
if (xnu27xx || xnu32xx || xnu37xx)
jump = 12;
if (is64)
jump = 0x18;
uint64_t addr = *((int *)(sysent + 20 + jump * i));
if (xnu27xx || xnu32xx || xnu37xx)
addr = *((int *)(sysent + jump * i));
if (is64)
{
addr = *((uint64_t *)(sysent + jump * i));
}
if ((addr == enosys) || addr == old)
suppress = 1;
if (!is64)
{
if ((addr % 4) == 1)
{
addr--;
thumb++;
}
if ((addr % 4) == -3)
{
addr--;
thumb++;
}
}
if (!suppress)
{
if (wantJToolOut)
{
char output[1024];
sprintf(output, "_%s", syscall_names[i]);
addSymbolToCache(output, addr, NULL);
//
// sprintf (output, "0x%llx:_%s\n", addr, syscall_names[i]);
// write (jtoolOutFD, output, strlen(output));
}
else
{
if (is64)
{
printf("%d.. %-20s 0x%llx\n", i, syscall_names[i], addr);
}
else
printf("%d. %-20s %x %s\n", i, syscall_names[i], addr, (thumb ? "T" : "-"));
}
} // !suppress`
// skip to next post null byte - unfortunately wont work due to optimizations
// putting some of the system call name strings elsewhere (in their first appearance
// in the binary)
// for (; *syscall_names; syscall_names++);
// syscall_names++;
}
} // showUNIX
// Do KEXTs
void *seg = MachOGetSection((unsigned char *)"__DATA.__const");
if (!seg)
seg = MachOGetSection((unsigned char *)"__CONST.__constdata");
if (!seg)
{
seg = MachOGetSection((unsigned char *)"__DATA_CONST.__const");
}
if (!seg)
{
fprintf(stderr, "Unable to find const section. This shouldn't be happening.. continuting anyway, but can't look for sysent/mach_trap_table\n");
}
else
{
}
_sysctls:
if (showSysctls)
doSysctls(mmapped, is64);
_kexts:
_kextraction:
if (kextract || showKexts)
{
int meth = 2;
if (xnu37xx)
{
if (g_jdebug)
fprintf(stderr, "This is a XNU 37xx or later kernel, so defaulting to method #1 (__PRELINK_INFO)\n");
meth = 1;
if (getenv("METH2"))
meth = 2;
}
doKexts(mmapped, kextName, meth);
}
if (jtoolOutFD)
{
char *cfn = getCompanionFileName(mmapped);
printf("Output written to %s in Jtool-compatible format. Run jtool with --jtooldir . or set JTOOLDIR=\n",
cfn);
// merge cache syms
dumpSymbolCacheToFile(jtoolOutFD);
close(jtoolOutFD);
}
} | 36.22668 | 6,552 | 0.577344 | [
"vector",
"3d"
] |
6d6f63144037b512d0b7ad7efa21ac4ed938d006 | 2,427 | h | C | d3d8to11/d3d8to11_base.h | basecq/d3d8to11 | f830e567e020305d30fc2ad3751e2b367382a09f | [
"MIT"
] | 6 | 2020-03-17T01:47:18.000Z | 2021-11-30T19:16:23.000Z | d3d8to11/d3d8to11_base.h | basecq/d3d8to11 | f830e567e020305d30fc2ad3751e2b367382a09f | [
"MIT"
] | 10 | 2020-03-10T16:07:12.000Z | 2021-10-30T10:05:38.000Z | d3d8to11/d3d8to11_base.h | basecq/d3d8to11 | f830e567e020305d30fc2ad3751e2b367382a09f | [
"MIT"
] | 4 | 2020-03-12T23:29:34.000Z | 2022-02-26T10:22:38.000Z | #pragma once
#include <d3d11_1.h>
#include <vector>
#include "Unknown.h"
#include "d3d8types.hpp"
class Direct3DDevice8;
class __declspec(uuid("1DD9E8DA-1C77-4D40-B0CF-98FEFDFF9512")) Direct3D8;
class Direct3D8 : public Unknown
{
public:
Direct3D8(const Direct3D8&) = delete;
Direct3D8& operator=(const Direct3D8&) = delete;
Direct3D8() = default;
~Direct3D8() = default;
void create_native();
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppvObj) override;
ULONG STDMETHODCALLTYPE AddRef() override;
ULONG STDMETHODCALLTYPE Release() override;
virtual HRESULT STDMETHODCALLTYPE RegisterSoftwareDevice(void* pInitializeFunction);
virtual UINT STDMETHODCALLTYPE GetAdapterCount();
virtual HRESULT STDMETHODCALLTYPE GetAdapterIdentifier(UINT Adapter, DWORD Flags, D3DADAPTER_IDENTIFIER8* pIdentifier);
virtual UINT STDMETHODCALLTYPE GetAdapterModeCount(UINT Adapter);
virtual HRESULT STDMETHODCALLTYPE EnumAdapterModes(UINT Adapter, UINT Mode, D3DDISPLAYMODE* pMode);
virtual HRESULT STDMETHODCALLTYPE GetAdapterDisplayMode(UINT Adapter, D3DDISPLAYMODE* pMode);
virtual HRESULT STDMETHODCALLTYPE CheckDeviceType(UINT Adapter, D3DDEVTYPE CheckType, D3DFORMAT DisplayFormat, D3DFORMAT BackBufferFormat, BOOL bWindowed);
virtual HRESULT STDMETHODCALLTYPE CheckDeviceFormat(UINT Adapter, D3DDEVTYPE DeviceType, D3DFORMAT AdapterFormat, DWORD Usage, D3DRESOURCETYPE RType, D3DFORMAT CheckFormat);
virtual HRESULT STDMETHODCALLTYPE CheckDeviceMultiSampleType(UINT Adapter, D3DDEVTYPE DeviceType, D3DFORMAT SurfaceFormat, BOOL Windowed, D3DMULTISAMPLE_TYPE MultiSampleType);
virtual HRESULT STDMETHODCALLTYPE CheckDepthStencilMatch(UINT Adapter, D3DDEVTYPE DeviceType, D3DFORMAT AdapterFormat, D3DFORMAT RenderTargetFormat, D3DFORMAT DepthStencilFormat);
virtual HRESULT STDMETHODCALLTYPE GetDeviceCaps(UINT Adapter, D3DDEVTYPE DeviceType, D3DCAPS8* pCaps);
virtual HMONITOR STDMETHODCALLTYPE GetAdapterMonitor(UINT Adapter);
virtual HRESULT STDMETHODCALLTYPE CreateDevice(UINT Adapter, D3DDEVTYPE DeviceType, HWND hFocusWindow, DWORD BehaviorFlags, D3DPRESENT_PARAMETERS8* pPresentationParameters, Direct3DDevice8** ppReturnedDeviceInterface);
private:
static const UINT max_adapters = 8;
UINT current_adapter_count = 0;
UINT current_adapter_mode_count[max_adapters] = {};
std::vector<DXGI_MODE_DESC> current_adapter_modes[max_adapters];
};
| 51.638298 | 219 | 0.820354 | [
"vector"
] |
6d7179abdbd49bca8737dc813c987f0cfa566802 | 8,929 | h | C | Source/WebCore/platform/graphics/Region.h | jacadcaps/webkitty | 9aebd2081349f9a7b5d168673c6f676a1450a66d | [
"BSD-2-Clause"
] | 6 | 2021-07-05T16:09:39.000Z | 2022-03-06T22:44:42.000Z | Source/WebCore/platform/graphics/Region.h | jacadcaps/webkitty | 9aebd2081349f9a7b5d168673c6f676a1450a66d | [
"BSD-2-Clause"
] | 7 | 2022-03-15T13:25:39.000Z | 2022-03-15T13:25:44.000Z | Source/WebCore/platform/graphics/Region.h | jacadcaps/webkitty | 9aebd2081349f9a7b5d168673c6f676a1450a66d | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright (C) 2010, 2011 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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 Region_h
#define Region_h
#include "IntRect.h"
#include <wtf/Optional.h>
#include <wtf/PointerComparison.h>
#include <wtf/Vector.h>
namespace WebCore {
DECLARE_ALLOCATOR_WITH_HEAP_IDENTIFIER(Region);
class Region {
WTF_MAKE_FAST_ALLOCATED_WITH_HEAP_IDENTIFIER(Region);
public:
WEBCORE_EXPORT Region();
WEBCORE_EXPORT Region(const IntRect&);
WEBCORE_EXPORT Region(const Region&);
WEBCORE_EXPORT Region(Region&&);
WEBCORE_EXPORT ~Region();
WEBCORE_EXPORT Region& operator=(const Region&);
WEBCORE_EXPORT Region& operator=(Region&&);
IntRect bounds() const { return m_bounds; }
bool isEmpty() const { return m_bounds.isEmpty(); }
bool isRect() const { return !m_shape; }
WEBCORE_EXPORT Vector<IntRect, 1> rects() const;
WEBCORE_EXPORT void unite(const Region&);
WEBCORE_EXPORT void intersect(const Region&);
WEBCORE_EXPORT void subtract(const Region&);
WEBCORE_EXPORT void translate(const IntSize&);
// Returns true if the query region is a subset of this region.
WEBCORE_EXPORT bool contains(const Region&) const;
WEBCORE_EXPORT bool contains(const IntPoint&) const;
// Returns true if the query region intersects any part of this region.
WEBCORE_EXPORT bool intersects(const Region&) const;
WEBCORE_EXPORT uint64_t totalArea() const;
unsigned gridSize() const { return m_shape ? m_shape->gridSize() : 0; }
#ifndef NDEBUG
void dump() const;
#endif
template<class Encoder> void encode(Encoder&) const;
template<class Decoder> static Optional<Region> decode(Decoder&);
// FIXME: Remove legacy decode.
template<class Decoder> static WARN_UNUSED_RETURN bool decode(Decoder&, Region&);
private:
struct Span {
int y { 0 };
size_t segmentIndex { 0 };
template<class Encoder> void encode(Encoder&) const;
template<class Decoder> static Optional<Span> decode(Decoder&);
};
class Shape {
WTF_MAKE_FAST_ALLOCATED;
public:
Shape() = default;
Shape(const IntRect&);
IntRect bounds() const;
bool isEmpty() const { return m_spans.isEmpty(); }
bool isRect() const { return m_spans.size() <= 2 && m_segments.size() <= 2; }
unsigned gridSize() const { return m_spans.size() * m_segments.size(); }
typedef const Span* SpanIterator;
SpanIterator spans_begin() const;
SpanIterator spans_end() const;
typedef const int* SegmentIterator;
SegmentIterator segments_begin(SpanIterator) const;
SegmentIterator segments_end(SpanIterator) const;
static Shape unionShapes(const Shape& shape1, const Shape& shape2);
static Shape intersectShapes(const Shape& shape1, const Shape& shape2);
static Shape subtractShapes(const Shape& shape1, const Shape& shape2);
WEBCORE_EXPORT void translate(const IntSize&);
struct CompareContainsOperation;
struct CompareIntersectsOperation;
template<typename CompareOperation>
static bool compareShapes(const Shape& shape1, const Shape& shape2);
template<class Encoder> void encode(Encoder&) const;
template<class Decoder> static Optional<Shape> decode(Decoder&);
#ifndef NDEBUG
void dump() const;
#endif
private:
struct UnionOperation;
struct IntersectOperation;
struct SubtractOperation;
template<typename Operation>
static Shape shapeOperation(const Shape& shape1, const Shape& shape2);
void appendSegment(int x);
void appendSpan(int y);
void appendSpan(int y, SegmentIterator begin, SegmentIterator end);
void appendSpans(const Shape&, SpanIterator begin, SpanIterator end);
bool canCoalesce(SegmentIterator begin, SegmentIterator end);
Vector<int, 32> m_segments;
Vector<Span, 16> m_spans;
friend bool operator==(const Shape&, const Shape&);
};
std::unique_ptr<Shape> copyShape() const { return m_shape ? makeUnique<Shape>(*m_shape) : nullptr; }
void setShape(Shape&&);
IntRect m_bounds;
std::unique_ptr<Shape> m_shape;
friend bool operator==(const Region&, const Region&);
friend bool operator==(const Shape&, const Shape&);
friend bool operator==(const Span&, const Span&);
friend bool operator!=(const Span&, const Span&);
};
static inline Region intersect(const Region& a, const Region& b)
{
Region result(a);
result.intersect(b);
return result;
}
static inline Region subtract(const Region& a, const Region& b)
{
Region result(a);
result.subtract(b);
return result;
}
static inline Region translate(const Region& region, const IntSize& offset)
{
Region result(region);
result.translate(offset);
return result;
}
inline bool operator==(const Region& a, const Region& b)
{
return a.m_bounds == b.m_bounds && arePointingToEqualData(a.m_shape, b.m_shape);
}
inline bool operator!=(const Region& a, const Region& b)
{
return !(a == b);
}
inline bool operator==(const Region::Shape& a, const Region::Shape& b)
{
return a.m_spans == b.m_spans && a.m_segments == b.m_segments;
}
inline bool operator==(const Region::Span& a, const Region::Span& b)
{
return a.y == b.y && a.segmentIndex == b.segmentIndex;
}
inline bool operator!=(const Region::Span& a, const Region::Span& b)
{
return !(a == b);
}
WEBCORE_EXPORT WTF::TextStream& operator<<(WTF::TextStream&, const Region&);
template<class Encoder>
void Region::Span::encode(Encoder& encoder) const
{
encoder << y << static_cast<uint64_t>(segmentIndex);
}
template<class Decoder>
Optional<Region::Span> Region::Span::decode(Decoder& decoder)
{
Optional<int> y;
decoder >> y;
if (!y)
return { };
Optional<uint64_t> segmentIndex;
decoder >> segmentIndex;
if (!segmentIndex)
return { };
return { { *y, static_cast<size_t>(*segmentIndex) } };
}
template<class Encoder>
void Region::Shape::encode(Encoder& encoder) const
{
encoder << m_segments;
encoder << m_spans;
}
template<class Decoder>
Optional<Region::Shape> Region::Shape::decode(Decoder& decoder)
{
Optional<Vector<int>> segments;
decoder >> segments;
if (!segments)
return WTF::nullopt;
Optional<Vector<Region::Span>> spans;
decoder >> spans;
if (!spans)
return WTF::nullopt;
Shape shape;
shape.m_segments = WTFMove(*segments);
shape.m_spans = WTFMove(*spans);
return { shape };
}
template<class Encoder>
void Region::encode(Encoder& encoder) const
{
encoder << m_bounds;
bool hasShape = !!m_shape;
encoder << hasShape;
if (hasShape)
encoder << *m_shape;
}
template<class Decoder>
Optional<Region> Region::decode(Decoder& decoder)
{
Optional<IntRect> bounds;
decoder >> bounds;
if (!bounds)
return WTF::nullopt;
Optional<bool> hasShape;
decoder >> hasShape;
if (!hasShape)
return WTF::nullopt;
Region region = { *bounds };
if (*hasShape) {
Optional<Shape> shape;
decoder >> shape;
if (!shape)
return WTF::nullopt;
region.m_shape = makeUnique<Shape>(WTFMove(*shape));
}
return { region };
}
template<class Decoder>
bool Region::decode(Decoder& decoder, Region& region)
{
Optional<Region> decodedRegion;
decoder >> decodedRegion;
if (!decodedRegion)
return false;
region = WTFMove(*decodedRegion);
return true;
}
} // namespace WebCore
#endif // Region_h
| 28.527157 | 104 | 0.683727 | [
"shape",
"vector"
] |
6d73809815452b091f1a61fca08b4908484bd32b | 5,384 | h | C | Source Code/Graphs/Headers/Octree.h | IonutCava/trunk | 19dc976bbd7dc637f467785bd0ca15f34bc31ed5 | [
"MIT"
] | null | null | null | Source Code/Graphs/Headers/Octree.h | IonutCava/trunk | 19dc976bbd7dc637f467785bd0ca15f34bc31ed5 | [
"MIT"
] | null | null | null | Source Code/Graphs/Headers/Octree.h | IonutCava/trunk | 19dc976bbd7dc637f467785bd0ca15f34bc31ed5 | [
"MIT"
] | null | null | null | /*
Copyright (c) 2018 DIVIDE-Studio
Copyright (c) 2009 Ionut Cava
This file is part of DIVIDE Framework.
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
#ifndef _OCTREE_H_
#define _OCTREE_H_
#include "IntersectionRecord.h"
#include "Core/Math/BoundingVolumes/Headers/BoundingBox.h"
namespace Divide {
class Frustum;
class SceneGraphNode;
class BoundsComponent;
struct SGNIntersectionParams;
// ref: http://www.gamedev.net/page/resources/_/technical/game-programming/introduction-to-octrees-r3529
class Octree {
public:
explicit Octree(U16 nodeMask);
void update(U64 deltaTimeUS);
[[nodiscard]] bool addNode(SceneGraphNode* node);
[[nodiscard]] bool removeNode(SceneGraphNode* node);
[[nodiscard]] vector<IntersectionRecord> allIntersections(const Frustum& region, U16 typeFilterMask);
[[nodiscard]] vector<IntersectionRecord> allIntersections(const Ray& intersectionRay, F32 start, F32 end);
[[nodiscard]] vector<IntersectionRecord> allIntersections(const Ray& intersectionRay, F32 start, F32 end, U16 typeFilterMask);
[[nodiscard]] IntersectionRecord nearestIntersection(const Ray& intersectionRay, F32 start, F32 end, U16 typeFilterMask);
void getAllRegions(vector<BoundingBox>& regionsOut) const;
protected:
friend class SceneGraph;
void onNodeMoved(const SceneGraphNode& sgn);
protected:
friend class OctreeNode;
void onChildBuildTree();
void onChildStateChange(OctreeNode* node, bool state);
private:
void updateTree();
void handleIntersection(const IntersectionRecord& intersection) const;
protected:
eastl::unique_ptr<OctreeNode> _root = nullptr;
vector<const SceneGraphNode*> _intersectionsObjectCache;
eastl::queue<SceneGraphNode*> _pendingInsertion;
eastl::queue<SceneGraphNode*> _pendingRemoval;
Mutex _pendingInsertLock;
bool _treeReady = false;
bool _treeBuilt = false;
const U16 _nodeExclusionMask = 0u;
Mutex _linearObjectCacheLock;
vector<OctreeNode*> _linearObjectCache;
};
class OctreeNode {
public:
/// Minimum cube size is 1x1x1
static constexpr F32 MIN_SIZE = 1.0f;
static constexpr I32 MAX_LIFE_SPAN_LIMIT = 64;
explicit OctreeNode(OctreeNode* parent, U16 nodeMask, Octree* parentTree);
void update(U64 deltaTimeUS);
void getAllRegions(vector<BoundingBox>& regionsOut) const;
[[nodiscard]] const BoundingBox& getRegion() const noexcept { return _region; }
protected:
friend class Octree;
[[nodiscard]] U8 activeNodes() const noexcept;
void buildTree();
void insert(const SceneGraphNode* object);
void findEnclosingBox();
void findEnclosingCube();
[[nodiscard]] vector<IntersectionRecord> getIntersection(const Frustum& frustum, U16 typeFilterMask) const;
[[nodiscard]] vector<IntersectionRecord> getIntersection(const Ray& intersectRay, F32 start, F32 end, U16 typeFilterMask) const;
[[nodiscard]] size_t getTotalObjectCount() const;
void updateIntersectionCache(vector<const SceneGraphNode*>& parentObjects);
[[nodiscard]] bool getIntersection(BoundsComponent* bComp, const Frustum& frustum, IntersectionRecord& irOut) const noexcept;
[[nodiscard]] bool getIntersection(BoundsComponent* bComp1, BoundsComponent* bComp2, IntersectionRecord& irOut) const noexcept;
[[nodiscard]] bool getIntersection(BoundsComponent* bComp, const Ray& intersectRay, F32 start, F32 end, IntersectionRecord& irOut) const noexcept;
PROPERTY_R_IW(bool, active, false);
private:
Octree* const _parentTree = nullptr;
OctreeNode* const _parent = nullptr;
const U16 _nodeExclusionMask = 0u;
mutable SharedMutex _objectLock;
eastl::fixed_vector<const SceneGraphNode*, 8, true, eastl::dvd_allocator> _objects;
moodycamel::ConcurrentQueue<const SceneGraphNode*> _movedObjects;
vector<IntersectionRecord> _intersectionsCache;
BoundingBox _region;
I32 _curLife = -1;
I32 _maxLifespan = MAX_LIFE_SPAN_LIMIT / 8;
std::array<eastl::unique_ptr<OctreeNode>, 8> _childNodes;
//ToDo: make this work in a multi-threaded environment
mutable I8 _frustPlaneCache = -1;
};
}; // namespace Divide
#endif | 36.134228 | 151 | 0.730498 | [
"object",
"vector"
] |
6d828dbac255f2dc858a0ba2bca6ebc655e3ff39 | 16,725 | h | C | app/src/main/cpp/gstreamer-1.0/armv7/include/gstreamer-1.0/gst/gl/glprototypes/shaders.h | pierotofy/rosettadrone | 336fa43d3ebcb5f544f83884656db18cbbbf2b72 | [
"BSD-3-Clause"
] | 88 | 2018-05-17T20:37:10.000Z | 2022-03-09T04:34:28.000Z | app/src/main/cpp/gstreamer-1.0/armv7/include/gstreamer-1.0/gst/gl/glprototypes/shaders.h | pierotofy/rosettadrone | 336fa43d3ebcb5f544f83884656db18cbbbf2b72 | [
"BSD-3-Clause"
] | 23 | 2018-05-17T21:56:30.000Z | 2021-02-24T12:58:43.000Z | app/src/main/cpp/gstreamer-1.0/armv7/include/gstreamer-1.0/gst/gl/glprototypes/shaders.h | pierotofy/rosettadrone | 336fa43d3ebcb5f544f83884656db18cbbbf2b72 | [
"BSD-3-Clause"
] | 55 | 2018-06-05T20:33:43.000Z | 2022-03-17T05:47:35.000Z | /*
* GStreamer
* Copyright (C) 2012 Matthew Waters <ystreet00@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
/*
* Cogl
*
* An object oriented GL/GLES Abstraction/Utility Layer
*
* Copyright (C) 2009, 2011 Intel Corporation.
*
* This library 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 library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
/* This lists functions that are unique to GL 2.0 or GLES 2.0 and are
* not in the old GLSL extensions */
GST_GL_EXT_BEGIN (shaders_glsl_2_only,
GST_GL_API_OPENGL | GST_GL_API_OPENGL3 |
GST_GL_API_GLES2,
2, 0,
2, 0,
"\0",
"\0")
GST_GL_EXT_FUNCTION (GLuint, CreateProgram,
(void))
GST_GL_EXT_FUNCTION (GLuint, CreateShader,
(GLenum shaderType))
GST_GL_EXT_FUNCTION (void, DeleteShader,
(GLuint shader))
GST_GL_EXT_FUNCTION (void, AttachShader,
(GLuint program,
GLuint shader))
GST_GL_EXT_FUNCTION (void, UseProgram,
(GLuint program))
GST_GL_EXT_FUNCTION (void, DeleteProgram,
(GLuint program))
GST_GL_EXT_FUNCTION (void, GetShaderInfoLog,
(GLuint shader,
GLsizei maxLength,
GLsizei *length,
char *infoLog))
GST_GL_EXT_FUNCTION (void, GetProgramInfoLog,
(GLuint program,
GLsizei bufSize,
GLsizei *length,
char *infoLog))
GST_GL_EXT_FUNCTION (void, GetShaderiv,
(GLuint shader,
GLenum pname,
GLint *params))
GST_GL_EXT_FUNCTION (void, GetProgramiv,
(GLuint program,
GLenum pname,
GLint *params))
GST_GL_EXT_FUNCTION (void, DetachShader,
(GLuint program, GLuint shader))
GST_GL_EXT_FUNCTION (void, GetAttachedShaders,
(GLuint program,
GLsizei maxcount,
GLsizei* count,
GLuint* shaders))
GST_GL_EXT_FUNCTION (GLboolean, IsShader,
(GLuint shader))
GST_GL_EXT_FUNCTION (GLboolean, IsProgram,
(GLuint program))
GST_GL_EXT_END ()
/* These functions are provided by GL_ARB_shader_objects or are in GL
* 2.0 core */
GST_GL_EXT_BEGIN (shader_objects_or_gl2,
GST_GL_API_OPENGL | GST_GL_API_OPENGL3 |
GST_GL_API_GLES2,
2, 0,
2, 0,
"ARB\0",
"shader_objects\0")
GST_GL_EXT_FUNCTION (void, ShaderSource,
(GLuint shader,
GLsizei count,
const char **string,
const GLint *length))
GST_GL_EXT_FUNCTION (void, CompileShader,
(GLuint shader))
GST_GL_EXT_FUNCTION (void, LinkProgram,
(GLuint program))
GST_GL_EXT_FUNCTION (GLint, GetUniformLocation,
(GLuint program,
const char *name))
GST_GL_EXT_FUNCTION (void, Uniform1f,
(GLint location,
GLfloat v0))
GST_GL_EXT_FUNCTION (void, Uniform2f,
(GLint location,
GLfloat v0,
GLfloat v1))
GST_GL_EXT_FUNCTION (void, Uniform3f,
(GLint location,
GLfloat v0,
GLfloat v1,
GLfloat v2))
GST_GL_EXT_FUNCTION (void, Uniform4f,
(GLint location,
GLfloat v0,
GLfloat v1,
GLfloat v2,
GLfloat v3))
GST_GL_EXT_FUNCTION (void, Uniform1fv,
(GLint location,
GLsizei count,
const GLfloat * value))
GST_GL_EXT_FUNCTION (void, Uniform2fv,
(GLint location,
GLsizei count,
const GLfloat * value))
GST_GL_EXT_FUNCTION (void, Uniform3fv,
(GLint location,
GLsizei count,
const GLfloat * value))
GST_GL_EXT_FUNCTION (void, Uniform4fv,
(GLint location,
GLsizei count,
const GLfloat * value))
GST_GL_EXT_FUNCTION (void, Uniform1i,
(GLint location,
GLint v0))
GST_GL_EXT_FUNCTION (void, Uniform2i,
(GLint location,
GLint v0,
GLint v1))
GST_GL_EXT_FUNCTION (void, Uniform3i,
(GLint location,
GLint v0,
GLint v1,
GLint v2))
GST_GL_EXT_FUNCTION (void, Uniform4i,
(GLint location,
GLint v0,
GLint v1,
GLint v2,
GLint v3))
GST_GL_EXT_FUNCTION (void, Uniform1iv,
(GLint location,
GLsizei count,
const GLint * value))
GST_GL_EXT_FUNCTION (void, Uniform2iv,
(GLint location,
GLsizei count,
const GLint * value))
GST_GL_EXT_FUNCTION (void, Uniform3iv,
(GLint location,
GLsizei count,
const GLint * value))
GST_GL_EXT_FUNCTION (void, Uniform4iv,
(GLint location,
GLsizei count,
const GLint * value))
GST_GL_EXT_FUNCTION (void, UniformMatrix2fv,
(GLint location,
GLsizei count,
GLboolean transpose,
const GLfloat *value))
GST_GL_EXT_FUNCTION (void, UniformMatrix3fv,
(GLint location,
GLsizei count,
GLboolean transpose,
const GLfloat *value))
GST_GL_EXT_FUNCTION (void, UniformMatrix4fv,
(GLint location,
GLsizei count,
GLboolean transpose,
const GLfloat *value))
GST_GL_EXT_FUNCTION (void, GetUniformfv,
(GLuint program,
GLint location,
GLfloat *params))
GST_GL_EXT_FUNCTION (void, GetUniformiv,
(GLuint program,
GLint location,
GLint *params))
GST_GL_EXT_FUNCTION (void, GetActiveUniform,
(GLuint program,
GLuint index,
GLsizei bufsize,
GLsizei* length,
GLint* size,
GLenum* type,
GLchar* name))
GST_GL_EXT_FUNCTION (void, GetShaderSource,
(GLuint shader,
GLsizei bufsize,
GLsizei* length,
GLchar* source))
GST_GL_EXT_FUNCTION (void, ValidateProgram, (GLuint program))
GST_GL_EXT_END ()
/* These functions are provided by GL_ARB_vertex_shader or are in GL
* 2.0 core */
GST_GL_EXT_BEGIN (vertex_shaders,
GST_GL_API_OPENGL | GST_GL_API_OPENGL3 |
GST_GL_API_GLES2,
2, 0,
2, 0,
"ARB\0",
"vertex_shader\0")
GST_GL_EXT_FUNCTION (void, VertexAttribPointer,
(GLuint index,
GLint size,
GLenum type,
GLboolean normalized,
GLsizei stride,
const GLvoid *pointer))
GST_GL_EXT_FUNCTION (void, EnableVertexAttribArray,
(GLuint index))
GST_GL_EXT_FUNCTION (void, DisableVertexAttribArray,
(GLuint index))
GST_GL_EXT_FUNCTION (void, VertexAttrib1f, (GLuint indx, GLfloat x))
GST_GL_EXT_FUNCTION (void, VertexAttrib1fv,
(GLuint indx, const GLfloat* values))
GST_GL_EXT_FUNCTION (void, VertexAttrib2f, (GLuint indx, GLfloat x, GLfloat y))
GST_GL_EXT_FUNCTION (void, VertexAttrib2fv,
(GLuint indx, const GLfloat* values))
GST_GL_EXT_FUNCTION (void, VertexAttrib3f,
(GLuint indx, GLfloat x, GLfloat y, GLfloat z))
GST_GL_EXT_FUNCTION (void, VertexAttrib3fv,
(GLuint indx, const GLfloat* values))
GST_GL_EXT_FUNCTION (void, VertexAttrib4f,
(GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w))
GST_GL_EXT_FUNCTION (void, VertexAttrib4fv,
(GLuint indx, const GLfloat* values))
GST_GL_EXT_FUNCTION (void, GetVertexAttribfv,
(GLuint index, GLenum pname, GLfloat* params))
GST_GL_EXT_FUNCTION (void, GetVertexAttribiv,
(GLuint index, GLenum pname, GLint* params))
GST_GL_EXT_FUNCTION (void, GetVertexAttribPointerv,
(GLuint index, GLenum pname, GLvoid** pointer))
GST_GL_EXT_FUNCTION (GLint, GetAttribLocation,
(GLuint program, const char *name))
GST_GL_EXT_FUNCTION (void, BindAttribLocation,
(GLuint program,
GLuint index,
const GLchar* name))
GST_GL_EXT_FUNCTION (void, GetActiveAttrib,
(GLuint program,
GLuint index,
GLsizei bufsize,
GLsizei* length,
GLint* size,
GLenum* type,
GLchar* name))
GST_GL_EXT_END ()
/* These only list functions that come from the old GLSL extensions.
* Functions that are common to the extensions and GLSL 2.0 should
* instead be listed in cogl-glsl-functions.h */
GST_GL_EXT_BEGIN (shader_objects,
GST_GL_API_NONE,
255, 255,
255, 255, /* not in either GLES */
"ARB\0",
"shader_objects\0")
GST_GL_EXT_FUNCTION (GLuint, CreateProgramObject,
(void))
GST_GL_EXT_FUNCTION (GLuint, CreateShaderObject,
(GLenum shaderType))
GST_GL_EXT_FUNCTION (void, DeleteObject,
(GLuint obj))
GST_GL_EXT_FUNCTION (void, AttachObject,
(GLuint container, GLuint obj))
GST_GL_EXT_FUNCTION (void, UseProgramObject,
(GLuint programObj))
GST_GL_EXT_FUNCTION (void, GetInfoLog,
(GLuint obj,
GLsizei maxLength,
GLsizei *length,
char *infoLog))
GST_GL_EXT_FUNCTION (void, GetObjectParameteriv,
(GLuint obj,
GLenum pname,
GLint *params))
GST_GL_EXT_FUNCTION (void, DetachObject,
(GLuint container, GLuint obj))
GST_GL_EXT_FUNCTION (void, GetAttachedObjects,
(GLuint program,
GLsizei maxcount,
GLsizei* count,
GLuint* shaders))
GST_GL_EXT_END ()
/* ARB_fragment_program */
GST_GL_EXT_BEGIN (arbfp,
GST_GL_API_NONE,
255, 255,
255, 255, /* not in either GLES */
"ARB\0",
"fragment_program\0")
GST_GL_EXT_FUNCTION (void, GenPrograms,
(GLsizei n,
GLuint *programs))
GST_GL_EXT_FUNCTION (void, DeletePrograms,
(GLsizei n,
GLuint *programs))
GST_GL_EXT_FUNCTION (void, BindProgram,
(GLenum target,
GLuint program))
GST_GL_EXT_FUNCTION (void, ProgramString,
(GLenum target,
GLenum format,
GLsizei len,
const void *program))
GST_GL_EXT_FUNCTION (void, ProgramLocalParameter4fv,
(GLenum target,
GLuint index,
GLfloat *params))
GST_GL_EXT_END ()
/* This lists functions that are unique to GL 2.1 or GLES 3.0 and are
* not in the old GLSL extensions */
GST_GL_EXT_BEGIN (shaders_2_1,
GST_GL_API_OPENGL | GST_GL_API_OPENGL3 |
GST_GL_API_GLES2,
2, 1,
3, 0,
"\0",
"\0")
GST_GL_EXT_FUNCTION (void, UniformMatrix2x3fv,
(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value))
GST_GL_EXT_FUNCTION (void, UniformMatrix3x2fv,
(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value))
GST_GL_EXT_FUNCTION (void, UniformMatrix2x4fv,
(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value))
GST_GL_EXT_FUNCTION (void, UniformMatrix4x2fv,
(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value))
GST_GL_EXT_FUNCTION (void, UniformMatrix3x4fv,
(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value))
GST_GL_EXT_FUNCTION (void, UniformMatrix4x3fv,
(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value))
GST_GL_EXT_END ()
GST_GL_EXT_BEGIN (bind_frag_data,
GST_GL_API_OPENGL | GST_GL_API_OPENGL3,
3, 0,
255, 255,
"\0",
"\0")
GST_GL_EXT_FUNCTION (void, BindFragDataLocation,
(GLuint program, GLuint index, const GLchar * name))
GST_GL_EXT_END ()
| 44.6 | 96 | 0.489148 | [
"object"
] |
6d84271702c333a9a3e7accde0f06e825d90f8b1 | 54,001 | h | C | src/app/voltdb/voltdb_src/src/ee/common/tabletuple.h | OpenMPDK/SMDK | 8f19d32d999731242cb1ab116a4cb445d9993b15 | [
"BSD-3-Clause"
] | 44 | 2022-03-16T08:32:31.000Z | 2022-03-31T16:02:35.000Z | src/app/voltdb/voltdb_src/src/ee/common/tabletuple.h | H2O0Lee/SMDK | eff49bc17a55a83ea968112feb2e2f2ea18c4ff5 | [
"BSD-3-Clause"
] | 1 | 2022-03-29T02:30:28.000Z | 2022-03-30T03:40:46.000Z | src/app/voltdb/voltdb_src/src/ee/common/tabletuple.h | H2O0Lee/SMDK | eff49bc17a55a83ea968112feb2e2f2ea18c4ff5 | [
"BSD-3-Clause"
] | 18 | 2022-03-19T04:41:04.000Z | 2022-03-31T03:32:12.000Z | /* This file is part of VoltDB.
* Copyright (C) 2008-2020 VoltDB Inc.
*
* This file contains original code and/or modifications of original code.
* Any modifications made by VoltDB Inc. are licensed under the following
* terms and conditions:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
/* Copyright (C) 2008 by H-Store Project
* Brown University
* Massachusetts Institute of Technology
* Yale University
*
* 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 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 "common/common.h"
#include "common/LoadTableCaller.h"
#include "common/HiddenColumnFilter.h"
#include "common/TupleSchema.h"
#include "common/Pool.hpp"
#include "common/ValueFactory.hpp"
#include "common/ValuePeeker.hpp"
#include "common/FatalException.hpp"
#include "common/ExportSerializeIo.h"
#include "common/serializeio.h"
#include <common/debuglog.h>
#include <ostream>
#include <iostream>
#include <vector>
#include <json/json.h>
class CopyOnWriteTest_TestTableTupleFlags;
class TableTupleTest_HeaderDefaults;
namespace voltdb {
#define TUPLE_HEADER_SIZE 1
// Boolean status bits appear in the tuple header, which is the first
// byte of tuple storage.
//
// The default status bits are all zeros:
// not active
// not dirty
// not pending delete
// not pending delete on undo release
// inlined variable length data IS volatile
// non-inlined variable length data IS NOT volatile
#define ACTIVE_MASK 1
#define DIRTY_MASK 2
#define PENDING_DELETE_MASK 4
#define PENDING_DELETE_ON_UNDO_RELEASE_MASK 8
#define INLINED_NONVOLATILE_MASK 16
#define NONINLINED_VOLATILE_MASK 32
class TableColumn;
class TupleIterator;
class ElasticScanner;
class StandAloneTupleStorage;
class SetAndRestorePendingDeleteFlag;
class TableTuple {
// friend access is intended to allow write access to the tuple flags -- try not to abuse it...
friend class Table;
friend class TempTable;
friend class LargeTempTable;
friend class LargeTempTableBlock;
friend class PersistentTable;
friend class ElasticScanner;
friend class PoolBackedTupleStorage;
friend class CopyOnWriteIterator;
friend class CopyOnWriteContext;
friend class ::CopyOnWriteTest_TestTableTupleFlags;
friend class ::TableTupleTest_HeaderDefaults;
friend class StandAloneTupleStorage; // ... OK, this friend can also update m_schema.
friend class SetAndRestorePendingDeleteFlag;
public:
TableTuple() = default;
/** Copy constructor */
TableTuple(const TableTuple &rhs) = default;
/** Setup the tuple given a schema */
explicit TableTuple(const TupleSchema *schema);
/** Setup the tuple given the specified data location and schema **/
TableTuple(char *data, const voltdb::TupleSchema *schema);
/** Assignment operator */
TableTuple& operator=(const TableTuple&) = default;
/**
* Set the tuple to point toward a given address in a table's
* backing store
*/
inline void move(void *address) {
#ifndef NDEBUG
if (m_schema == NULL && address != NULL) {
StackTrace::printStackTrace();
}
#endif
vassert(m_schema != NULL || address == NULL);
m_data = reinterpret_cast<char*> (address);
}
/**
* Set the tuple to point toward a given address and initialize the tuple header to be used as a new tuple
*/
inline void moveAndInitialize(void *address) {
move(address);
resetHeader();
}
inline void moveNoHeader(void *address) {
vassert(m_schema);
// isActive() and all the other methods expect a header
m_data = reinterpret_cast<char*> (address) - TUPLE_HEADER_SIZE;
}
// Used to wrap read only tuples in indexing code. TODO Remove
// constedeness from indexing code so this cast isn't necessary.
inline void moveToReadOnlyTuple(const void *address) {
vassert(m_schema);
vassert(address);
//Necessary to move the pointer back TUPLE_HEADER_SIZE
// artificially because Tuples used as keys for indexes do not
// have the header.
m_data = reinterpret_cast<char*>(const_cast<void*>(address)) - TUPLE_HEADER_SIZE;
}
/** Get the address of this tuple in the table's backing store */
inline char* address() const {
return m_data;
}
/** Return the number of columns in this tuple */
inline int columnCount() const {
return m_schema->columnCount();
}
bool areAllCollumnsVarAndNull() const {
int cols = columnCount();
for (int i = 0; i < cols; ++i) {
if (!isVarLengthType(i) || !isNull(i)) {
return false;
}
}
return true;
}
/**
Determine the maximum number of bytes when serialized for Export.
Excludes the bytes required by the row header (which includes
the null bit indicators) and ignores the width of metadata cols.
*/
size_t maxExportSerializationSize() const {
size_t bytes = 0;
int cols = columnCount();
for (int i = 0; i < cols; ++i) {
bytes += maxExportSerializedColumnSize(i);
}
return bytes;
}
size_t maxDRSerializationSize() const {
size_t bytes = maxExportSerializationSize();
int hiddenCols = m_schema->hiddenColumnCount();
HiddenColumnFilter filter = HiddenColumnFilter::create(HiddenColumnFilter::EXCLUDE_MIGRATE, m_schema);
for (int i = 0; i < hiddenCols; ++i) {
if (filter.include(i)) {
bytes += maxExportSerializedHiddenColumnSize(i);
}
}
return bytes;
}
// return the number of bytes when serialized for regular usage (other
// than export and DR).
size_t serializationSize() const {
size_t bytes = sizeof(int32_t);
for (int colIdx = 0; colIdx < columnCount(); ++colIdx) {
bytes += maxSerializedColumnSize(colIdx);
}
return bytes;
}
/** Return the amount of memory needed to store the non-inlined
objects in this tuple in persistent, relocatable storage.
Note that this tuple may be in a temp table, or in a
persistent table, or not in a table at all. */
size_t getNonInlinedMemorySizeForPersistentTable() const {
size_t bytes = 0;
uint16_t nonInlinedColCount = m_schema->getUninlinedObjectColumnCount();
for (uint16_t i = 0; i < nonInlinedColCount; i++) {
uint16_t idx = m_schema->getUninlinedObjectColumnInfoIndex(i);
const TupleSchema::ColumnInfo *columnInfo = m_schema->getColumnInfo(idx);
voltdb::ValueType columnType = columnInfo->getVoltType();
if (isVariableLengthType(columnType) && !columnInfo->inlined) {
bytes += getNValue(idx).getAllocationSizeForObjectInPersistentStorage();
}
}
return bytes;
}
/** Return the amount of memory needed to store the non-inlined
objects in this tuple in temporary storage. Note that this
tuple may be in a temp table, or in a persistent table, or not
in a table at all. */
size_t getNonInlinedMemorySizeForTempTable() const {
size_t bytes = 0;
uint16_t nonInlinedColCount = m_schema->getUninlinedObjectColumnCount();
for (uint16_t i = 0; i < nonInlinedColCount; i++) {
uint16_t idx = m_schema->getUninlinedObjectColumnInfoIndex(i);
const TupleSchema::ColumnInfo *columnInfo = m_schema->getColumnInfo(idx);
voltdb::ValueType columnType = columnInfo->getVoltType();
if (isVariableLengthType(columnType) && !columnInfo->inlined) {
bytes += getNValue(idx).getAllocationSizeForObjectInTempStorage();
}
}
return bytes;
}
/* Utility function to shrink and set given NValue based. Uses data from it's column information to compute
* the length to shrink the NValue to. This function operates is intended only to be used on variable length
* columns ot type varchar and varbinary.
*/
void shrinkAndSetNValue(const int idx, const voltdb::NValue& value) {
vassert(m_schema);
const TupleSchema::ColumnInfo *columnInfo = m_schema->getColumnInfo(idx);
vassert(columnInfo);
const ValueType valueType = columnInfo->getVoltType();
// shrink is permissible only on variable length column and currently only for varchar and varbinary
vassert(valueType == ValueType::tVARBINARY || valueType == ValueType::tVARCHAR);
bool isColumnLngthInBytes = valueType == ValueType::tVARBINARY ? true : columnInfo->inBytes;
uint32_t columnLength = columnInfo->length;
// For the given NValue, compute the shrink length in bytes to shrink the nvalue based on
// current column length. Use the computed shrink length to create new NValue based so that
// it can fits in current tuple's column
int32_t nValueLength = 0;
const char* candidateValueBuffPtr = ValuePeeker::peekObject_withoutNull(value, &nValueLength);
// compute length for shrinked candidate key
int32_t neededLength;
if (isColumnLngthInBytes) {
neededLength = columnLength;
} else {
// column length is defined in characters. Obtain the number of bytes needed for those many characters
neededLength = static_cast<int32_t> (NValue::getIthCharPosition(
candidateValueBuffPtr, nValueLength, columnLength + 1) - candidateValueBuffPtr);
}
// create new nvalue using the computed length
NValue shrinkedNValue = ValueFactory::getTempStringValue(candidateValueBuffPtr, neededLength);
setNValue(columnInfo, shrinkedNValue, false);
}
/*
* This will put the NValue into this tuple at the idx-th field.
*
* If the NValue refers to inlined storage (points to storage
* interior to some tuple memory), and the storage is not inlined
* in this tuple, then this will allocate the un-inlined value in
* the temp string pool. So, don't use this to update a tuple in
* a persistent table!
*/
void setNValue(const int idx, voltdb::NValue const& value) {
vassert(m_schema);
const TupleSchema::ColumnInfo *columnInfo = m_schema->getColumnInfo(idx);
setNValue(columnInfo, value, false);
}
void setHiddenNValue(const TupleSchema::HiddenColumnInfo *columnInfo,
voltdb::NValue const& value) {
char *dataPtr = getWritableDataPtr(columnInfo);
value.serializeToTupleStorage(dataPtr, false, -1, false, false);
}
void setHiddenNValue(const int idx, voltdb::NValue const& value) {
vassert(m_schema);
const TupleSchema::HiddenColumnInfo *columnInfo = m_schema->getHiddenColumnInfo(idx);
setHiddenNValue(columnInfo, value);
}
/*
* Like the above method except for "hidden" fields, not
* accessible in the normal codepath.
*/
/*
* Copies range of NValues from one tuple to another.
*/
void setNValues(int beginIdx, TableTuple const& lhs, int begin, int end);
/*
* Version of setNValue that will allocate space to copy
* strings that can't be inlined rather then copying the
* pointer. Used when setting an NValue that will go into
* permanent storage in a persistent table. It is also possible
* to provide NULL for stringPool in which case the strings will
* be allocated in persistent, relocatable storage.
* The POOL argument may either be a Pool instance or an instance
* of a LargeTempTableBlock (Large temp table blocks store
* non-inlined data in the same buffer as tuples).
*/
template<class POOL>
void setNValueAllocateForObjectCopies(const int idx, voltdb::NValue const& value, POOL *dataPool) {
vassert(m_schema);
const TupleSchema::ColumnInfo *columnInfo = m_schema->getColumnInfo(idx);
setNValue(columnInfo, value, true, dataPool);
}
/** This method behaves very much like the method above except it
will copy non-inlined objects referenced in the tuple to
persistent, relocatable storage. */
void setNValueAllocateForObjectCopies(const int idx, voltdb::NValue const& value) {
setNValueAllocateForObjectCopies(idx, value, static_cast<Pool*>(NULL));
}
/** How long is a tuple? */
inline int tupleLength() const {
return m_schema->tupleLength() + TUPLE_HEADER_SIZE;
}
/** Is the tuple deleted or active? */
inline bool isActive() const {
return *(reinterpret_cast<const char*> (m_data)) & ACTIVE_MASK;
}
/** Is the tuple deleted or active? */
inline bool isDirty() const {
return *(reinterpret_cast<const char*> (m_data)) & DIRTY_MASK;
}
inline bool isPendingDelete() const {
return *(reinterpret_cast<const char*> (m_data)) & PENDING_DELETE_MASK;
}
inline bool isPendingDeleteOnUndoRelease() const {
return *(reinterpret_cast<const char*> (m_data)) & PENDING_DELETE_ON_UNDO_RELEASE_MASK;
}
/** Is variable-length data stored inside the tuple volatile (could data
change, or could storage be freed)? */
inline bool inlinedDataIsVolatile() const {
// This is a little counter-intuitive: If this bit is set to
// zero, then the inlined variable length data should be
// considered volatile.
return !(*(reinterpret_cast<const char*> (m_data)) & INLINED_NONVOLATILE_MASK);
}
/** Is variable-length data stored outside the tuple volatile
(could data change, or could storage be freed)? */
inline bool nonInlinedDataIsVolatile() const {
return *(reinterpret_cast<const char*> (m_data)) & NONINLINED_VOLATILE_MASK;
}
/** Is the column value null? */
inline bool isNull(const int idx) const {
return getNValue(idx).isNull();
}
/** Is the hidden column value null? */
inline bool isHiddenNull(const int idx) const {
return getHiddenNValue(idx).isNull();
}
inline bool isNullTuple() const {
return m_data == NULL;
}
/** Get the value of a specified column (const). */
inline const NValue getNValue(const int idx) const {
vassert(m_schema);
vassert(m_data);
vassert(idx < m_schema->totalColumnCount()); // column index might point to a hidden column of migrating table
const TupleSchema::ColumnInfo *columnInfo = m_schema->getColumnInfo(idx);
const voltdb::ValueType columnType = columnInfo->getVoltType();
const char* dataPtr = getDataPtr(columnInfo);
const bool isInlined = columnInfo->inlined;
const bool isVolatile = inferVolatility(columnInfo);
return NValue::initFromTupleStorage(dataPtr, columnType, isInlined, isVolatile);
}
/** Like the above method but for hidden columns. */
inline const NValue getHiddenNValue(const int idx) const {
vassert(m_schema);
vassert(m_data);
vassert(idx < m_schema->hiddenColumnCount());
const TupleSchema::HiddenColumnInfo *columnInfo = m_schema->getHiddenColumnInfo(idx);
const voltdb::ValueType columnType = columnInfo->getVoltType();
const char* dataPtr = getDataPtr(columnInfo);
return NValue::initFromTupleStorage(dataPtr, columnType, false, false);
}
inline const voltdb::TupleSchema* getSchema() const {
return m_schema;
}
inline void setSchema(const TupleSchema * schema) {
m_schema = schema;
}
/** Print out a human readable description of this tuple */
std::string debug(const std::string& tableName, bool skipNonInline = false) const;
std::string debug() const {
return debugNoHeader();
}
std::string debugNoHeader() const;
std::string debugSkipNonInlineData() const {
return debug("", true);
}
std::string toJsonArray() const {
int totalColumns = columnCount();
Json::Value array;
for (int i = 0; i < totalColumns; i++) {
array.append({getNValue(i).toString()});
}
return writeJson(array);
}
std::string toJsonString(const std::vector<std::string>& columnNames) const {
Json::Value object;
for (int i = 0; i < columnCount(); i++) {
object[columnNames[i]] = getNValue(i).toString();
}
return writeJson(object);
}
/** Copy values from one tuple into another. Any non-inlined
objects will be copied into the provided instance of Pool, or
into persistent, relocatable storage if no pool is provided.
Note that the POOL argument may also be an instance or
LargeTempTableBlock. */
template<class POOL>
void copyForPersistentInsert(const TableTuple &source, POOL *pool);
/** Similar to the above method except that any non-inlined objects
will be allocated in persistent, relocatable storage. */
void copyForPersistentInsert(const TableTuple &source) {
copyForPersistentInsert(source, static_cast<Pool*>(NULL));
}
// The vector "output" arguments detail the non-inline object memory management
// required of the upcoming release or undo.
void copyForPersistentUpdate(const TableTuple &source,
std::vector<char*> &oldObjects, std::vector<char*> &newObjects);
void copy(const TableTuple &source);
/** this does set NULL in addition to clear string count.*/
void setAllNulls();
/** When a large temp table block is reloaded from disk, we need to
update all addresses pointing to non-inline data. */
void relocateNonInlinedFields(std::ptrdiff_t offset);
bool equals(const TableTuple &other) const;
bool equalsNoSchemaCheck(const TableTuple &other, const HiddenColumnFilter *hiddenColumnFilter = NULL) const;
int compare(const TableTuple &other) const;
int compareNullAsMax(const TableTuple &other) const;
void deserializeFrom(voltdb::SerializeInputBE &tupleIn, Pool *stringPool,
const LoadTableCaller &caller);
void deserializeFromDR(voltdb::SerializeInputLE &tupleIn, Pool *stringPool);
void serializeTo(voltdb::SerializeOutput& output, const HiddenColumnFilter *filter = NULL) const;
size_t serializeToExport(voltdb::ExportSerializeOutput &io,
int colOffset, uint8_t *nullArray) const;
void serializeToDR(voltdb::ExportSerializeOutput &io, int colOffset, uint8_t *nullArray);
void freeObjectColumns() const;
size_t hashCode(size_t seed) const;
size_t hashCode() const;
private:
static string writeJson(Json::Value const& val) {
// ENG-15989: FastWriter is not thread-safe, and therefore cannot be made static.
Json::FastWriter writer;
writer.omitEndingLineFeed();
return writer.write(val);
}
inline void setActiveTrue() {
// treat the first "value" as a boolean flag
*(reinterpret_cast<char*> (m_data)) |= static_cast<char>(ACTIVE_MASK);
}
inline void setActiveFalse() {
// treat the first "value" as a boolean flag
*(reinterpret_cast<char*> (m_data)) &= static_cast<char>(~ACTIVE_MASK);
}
inline void setPendingDeleteOnUndoReleaseTrue() {
// treat the first "value" as a boolean flag
*(reinterpret_cast<char*> (m_data)) |= static_cast<char>(PENDING_DELETE_ON_UNDO_RELEASE_MASK);
}
inline void setPendingDeleteOnUndoReleaseFalse() {
// treat the first "value" as a boolean flag
*(reinterpret_cast<char*> (m_data)) &= static_cast<char>(~PENDING_DELETE_ON_UNDO_RELEASE_MASK);
}
inline void setPendingDeleteTrue() {
// treat the first "value" as a boolean flag
*(reinterpret_cast<char*> (m_data)) |= static_cast<char>(PENDING_DELETE_MASK);
}
inline void setPendingDeleteFalse() {
// treat the first "value" as a boolean flag
*(reinterpret_cast<char*> (m_data)) &= static_cast<char>(~PENDING_DELETE_MASK);
}
inline void setDirtyTrue() {
// treat the first "value" as a boolean flag
*(reinterpret_cast<char*> (m_data)) |= static_cast<char>(DIRTY_MASK);
}
inline void setDirtyFalse() {
// treat the first "value" as a boolean flag
*(reinterpret_cast<char*> (m_data)) &= static_cast<char>(~DIRTY_MASK);
}
/** Mark inlined variable length data in the tuple as subject to
change or deallocation. */
inline void setInlinedDataIsVolatileTrue() {
// This is a little counter-intuitive: If this bit is set to
// zero, then the inlined variable length data should be
// considered volatile.
*(reinterpret_cast<char*> (m_data)) &= static_cast<char>(~INLINED_NONVOLATILE_MASK);
}
/** Mark inlined variable length data in the tuple as not subject
to change or deallocation. */
inline void setInlinedDataIsVolatileFalse() {
// Set the bit to 1, indicating that inlined variable-length
// data is NOT volatile.
*(reinterpret_cast<char*> (m_data)) |= static_cast<char>(INLINED_NONVOLATILE_MASK);
}
/** Mark non-inlined variable length data referenced from the
tuple as subject to change or deallocation. */
inline void setNonInlinedDataIsVolatileTrue() {
*(reinterpret_cast<char*> (m_data)) |= static_cast<char>(NONINLINED_VOLATILE_MASK);
}
/** Mark non-inlined variable length data referenced from the
tuple as not subject to change or deallocation. */
inline void setNonInlinedDataIsVolatileFalse() {
*(reinterpret_cast<char*> (m_data)) &= static_cast<char>(~NONINLINED_VOLATILE_MASK);
}
inline bool inferVolatility(const TupleSchema::ColumnInfo *colInfo) const {
if (! isVariableLengthType(colInfo->getVoltType())) {
// NValue has 16 bytes of storage which can contain all
// the fixed-length types.
return false;
} else if (m_schema->isHeaderless()) {
// For index keys, there is no header byte to check status.
return false;
} else if (colInfo->inlined) {
return inlinedDataIsVolatile();
} else {
return nonInlinedDataIsVolatile();
}
}
inline void resetHeader() {
// treat the first "value" as a boolean flag
*(reinterpret_cast<char*> (m_data)) = 0;
}
/** The types of the columns in the tuple */
const TupleSchema *m_schema = nullptr;
/**
* The column data, padded at the front by 8 bytes
* representing whether the tuple is active or deleted
*/
char *m_data = nullptr;
inline char* getWritableDataPtr(const TupleSchema::ColumnInfoBase* colInfo) const {
vassert(m_schema);
vassert(m_data);
return &m_data[TUPLE_HEADER_SIZE + colInfo->offset];
}
inline const char* getDataPtr(const TupleSchema::ColumnInfoBase* colInfo) const {
vassert(m_schema);
vassert(m_data);
return &m_data[TUPLE_HEADER_SIZE + colInfo->offset];
}
inline size_t serializeColumnToExport(ExportSerializeOutput &io,
int offset, const NValue &value, uint8_t *nullArray) const {
// NULL doesn't produce any bytes for the NValue
// Handle it here to consolidate manipulation of
// the null array.
size_t sz = 0;
if (value.isNull()) {
// turn on offset'th bit of nullArray
int byte = offset >> 3;
int bit = offset % 8;
int mask = 0x80 >> bit;
nullArray[byte] = (uint8_t)(nullArray[byte] | mask);
} else {
sz = value.serializeToExport_withoutNull(io);
}
return sz;
}
inline void serializeHiddenColumnsToDR(ExportSerializeOutput &io) const {
// Exclude the hidden column for persistent table with stream
uint16_t hiddenColumnCount = m_schema->hiddenColumnCount();
uint8_t migrateColumn = m_schema->getHiddenColumnIndex(HiddenColumn::MIGRATE_TXN);
for (int colIdx = 0; colIdx < hiddenColumnCount; colIdx++) {
if (colIdx != migrateColumn) {
getHiddenNValue(colIdx).serializeToExport_withoutNull(io);
}
}
}
inline size_t maxExportSerializedColumnSize(int colIndex) const {
return maxExportSerializedColumnSizeCommon(colIndex, false);
}
inline size_t maxExportSerializedHiddenColumnSize(int colIndex) const {
return maxExportSerializedColumnSizeCommon(colIndex, true);
}
// exclude hidden column since it should nver be var-length type
inline bool isVarLengthType(int colIndex) const {
const TupleSchema::ColumnInfoBase *columnInfo = m_schema->getColumnInfo(colIndex);
ValueType columnType = columnInfo->getVoltType();
return columnType == ValueType::tVARCHAR || columnType == ValueType::tVARBINARY || columnType == ValueType::tGEOGRAPHY;
}
inline size_t maxExportSerializedColumnSizeCommon(int colIndex, bool isHidden) const {
const TupleSchema::ColumnInfoBase *columnInfo;
if (isHidden) {
columnInfo = m_schema->getHiddenColumnInfo(colIndex);
} else {
columnInfo = m_schema->getColumnInfo(colIndex);
}
voltdb::ValueType columnType = columnInfo->getVoltType();
switch (columnType) {
case ValueType::tTINYINT:
return sizeof (int8_t);
case ValueType::tSMALLINT:
return sizeof (int16_t);
case ValueType::tINTEGER:
return sizeof (int32_t);
case ValueType::tBIGINT:
case ValueType::tTIMESTAMP:
case ValueType::tDOUBLE:
return sizeof (int64_t);
case ValueType::tDECIMAL:
//1-byte scale, 1-byte precision, 16 bytes all the time right now
return 18;
case ValueType::tVARCHAR:
case ValueType::tVARBINARY:
case ValueType::tGEOGRAPHY:
{
bool isNullCol = isHidden ? isHiddenNull(colIndex) : isNull(colIndex);
if (isNullCol) {
return 0;
}
// 32 bit length preceding value and
// actual character data without null string terminator.
const NValue value = isHidden ? getHiddenNValue(colIndex) : getNValue(colIndex);
int32_t length;
ValuePeeker::peekObject_withoutNull(value, &length);
return sizeof(int32_t) + length;
}
case ValueType::tPOINT:
return sizeof (GeographyPointValue);
default:
// let caller handle this error
throwDynamicSQLException(
"Unknown ValueType %s found during Export serialization.",
valueToString(columnType).c_str() );
return 0;
}
}
inline size_t maxSerializedColumnSize(int colIndex) const {
const TupleSchema::ColumnInfo *columnInfo = m_schema->getColumnInfo(colIndex);
voltdb::ValueType columnType = columnInfo->getVoltType();
if (isVariableLengthType(columnType)) {
// Null variable length value doesn't take any bytes in
// export table.
if (isNull(colIndex)) {
return sizeof(int32_t);
}
} else if (columnType == ValueType::tDECIMAL) {
// Other than export and DR table, decimal column in regular table
// doesn't contain scale and precision bytes.
return 16;
}
return maxExportSerializedColumnSize(colIndex);
}
/** Write the given NValue into this tuple at the location
specified by columnInfo. If allocation of objects is
requested, then use the provided pool. If no pool is
provided, then objects will be copied into persistent,
relocatable storage.
Note that the POOL argument may be an instance of
LargeTempTableBlock which stores tuple data and non-inlined
objects in the same buffer. */
template<class POOL>
void setNValue(const TupleSchema::ColumnInfo *columnInfo, voltdb::NValue value,
bool allocateObjects, POOL* tempPool) {
vassert(m_data);
ValueType columnType = columnInfo->getVoltType();
value = value.castAs(columnType);
bool isInlined = columnInfo->inlined;
bool isInBytes = columnInfo->inBytes;
char *dataPtr = getWritableDataPtr(columnInfo);
int32_t columnLength = columnInfo->length;
// If the nvalue is not to be inlined, we will be storing a
// pointer in this tuple, and this pointer may be pointing to
// volatile storage (i.e., a large temp table block).
//
// So, if the NValue is volatile, not inlined, and
// allocateObjects has not been set, mark this tuple as having
// volatile non-inlined data.
if (value.getVolatile() && !isInlined && !allocateObjects) {
setNonInlinedDataIsVolatileTrue();
}
value.serializeToTupleStorage(dataPtr, isInlined, columnLength, isInBytes,
allocateObjects, tempPool);
}
/** This method is similar to the above method except no pool is
provided, so if allocation is requested it will be done in
persistent, relocatable storage. */
void setNValue(const TupleSchema::ColumnInfo *columnInfo,
voltdb::NValue const& value, bool allocateObjects) {
setNValue<Pool>(columnInfo, value, allocateObjects, nullptr);
}
};
/**
* Convenience class for Tuples that get their (inline) storage from a pool.
* The pool is specified on initial allocation and retained for later reallocations.
* The tuples can be used like normal tuples except for allocation/reallocation.
* The caller takes responsibility for consistently using the specialized methods below for that.
*/
class PoolBackedTupleStorage {
TableTuple m_tuple{};
Pool* m_pool = nullptr;
public:
void init(const TupleSchema* schema, Pool* pool) {
m_tuple.setSchema(schema);
m_pool = pool;
}
void allocateActiveTuple() {
char* storage = reinterpret_cast<char*>(m_pool->allocateZeroes(
m_tuple.getSchema()->tupleLength() + TUPLE_HEADER_SIZE));
m_tuple.moveAndInitialize(storage);
m_tuple.setActiveTrue();
m_tuple.setInlinedDataIsVolatileTrue();
}
/** Operator conversion to get an access to the underline tuple.
* To prevent clients from repointing the tuple to some other backing
* storage via move()or address() calls the tuple is returned by value
*/
operator TableTuple& () {
return m_tuple;
}
};
// A small class to hold together a standalone tuple (not backed by any table)
// and the associated tuple storage memory to keep the actual data.
// This class will also make a copy of the tuple schema passed in and delete the
// copy in its destructor (since instances of TupleSchema for persistent tables can
// go away in the event of TRUNCATE TABLE).
class StandAloneTupleStorage {
std::unique_ptr<char[]> m_tupleStorage{};
TableTuple m_tuple{};
TupleSchema* m_tupleSchema = nullptr;
public:
/** Creates an uninitialized tuple */
StandAloneTupleStorage() = default;
/** Allocates enough memory for a given schema
* and initialies tuple to point to this memory
*/
explicit StandAloneTupleStorage(const TupleSchema* schema) :
m_tupleStorage(), m_tuple(), m_tupleSchema(nullptr) {
init(schema);
}
~StandAloneTupleStorage() {
TupleSchema::freeTupleSchema(m_tupleSchema);
}
/** Allocates enough memory for a given schema
* and initializes tuple to point to this memory
*/
void init(const TupleSchema* schema) {
vassert(schema != NULL);
// TupleSchema can go away, so copy it here and keep it with our tuple.
if (m_tupleSchema != NULL) {
TupleSchema::freeTupleSchema(m_tupleSchema);
}
m_tupleSchema = TupleSchema::createTupleSchema(schema);
// note: apparently array new of the form
// new char[N]()
// will zero-initialize the allocated memory.
m_tupleStorage.reset(new char[m_tupleSchema->tupleLength() + TUPLE_HEADER_SIZE]());
m_tuple.m_schema = m_tupleSchema;
m_tuple.move(m_tupleStorage.get());
m_tuple.setAllNulls();
m_tuple.setActiveTrue();
m_tuple.setInlinedDataIsVolatileTrue();
}
/** Get the tuple that this object is wrapping.
* Returned const ref to avoid corrupting the tuples data and schema pointers
*/
TableTuple& tuple() {
return m_tuple;
}
};
inline TableTuple::TableTuple(const TupleSchema *schema) : m_schema(schema), m_data(NULL) {
vassert(m_schema);
}
/** Setup the tuple given the specified data location and schema **/
inline TableTuple::TableTuple(char *data, const voltdb::TupleSchema *schema) :
m_schema(schema), m_data(data){
vassert(data);
vassert(schema);
}
/** Multi column version. */
inline void TableTuple::setNValues(int beginIdx, TableTuple const& lhs, int begin, int end) {
vassert(m_schema);
vassert(lhs.getSchema());
vassert(beginIdx + end - begin <= columnCount());
while (begin != end) {
setNValue(beginIdx++, lhs.getNValue(begin++));
}
}
/*
* With a persistent insert the copy should do an allocation for all non-inlined strings
*/
template<class POOL>
inline void TableTuple::copyForPersistentInsert(const voltdb::TableTuple &source, POOL *pool) {
copy(source);
const uint16_t uninlineableObjectColumnCount = m_schema->getUninlinedObjectColumnCount();
if (uninlineableObjectColumnCount > 0) {
/*
* Copy each uninlined string column doing an allocation for string copies.
*/
for (uint16_t i = 0; i < uninlineableObjectColumnCount; i++) {
const uint16_t uinlineableObjectColumnIndex =
m_schema->getUninlinedObjectColumnInfoIndex(i);
setNValueAllocateForObjectCopies(uinlineableObjectColumnIndex,
source.getNValue(uinlineableObjectColumnIndex),
pool);
}
m_data[0] = source.m_data[0];
}
}
/*
* With a persistent update the copy should only do an allocation for
* a string if the source and destination pointers are different.
*/
inline void TableTuple::copyForPersistentUpdate(const TableTuple &source,
std::vector<char*> &oldObjects, std::vector<char*> &newObjects) {
vassert(m_schema);
vassert(m_schema->equals(source.m_schema));
const int columnCount = m_schema->columnCount();
const uint16_t uninlineableObjectColumnCount = m_schema->getUninlinedObjectColumnCount();
/*
* The source and target tuple have the same policy WRT to
* inlining strings because a TableTuple used for updating a
* persistent table uses the same schema as the persistent table.
*/
if (uninlineableObjectColumnCount > 0) {
uint16_t uninlineableObjectColumnIndex = 0;
uint16_t nextUninlineableObjectColumnInfoIndex = m_schema->getUninlinedObjectColumnInfoIndex(0);
/*
* Copy each column doing an allocation for string
* copies. Compare the source and target pointer to see if it
* is changed in this update. If it is changed then free the
* old string and copy/allocate the new one from the source.
*/
for (uint16_t ii = 0; ii < columnCount; ii++) {
if (ii == nextUninlineableObjectColumnInfoIndex) {
const TupleSchema::ColumnInfo *columnInfo = m_schema->getColumnInfo(ii);
char * *mPtr = reinterpret_cast<char**>(getWritableDataPtr(columnInfo));
const TupleSchema::ColumnInfo *sourceColumnInfo = source.getSchema()->getColumnInfo(ii);
char * const *oPtr = reinterpret_cast<char* const*>(source.getDataPtr(sourceColumnInfo));
if (*mPtr != *oPtr) {
// Make a copy of the input string. Don't want to delete the old string
// because it's either from the temp pool or persistently referenced elsewhere.
oldObjects.push_back(*mPtr);
// TODO: Here, it's known that the column is an object type, and yet
// setNValueAllocateForObjectCopies is called to figure this all out again.
setNValueAllocateForObjectCopies(ii, source.getNValue(ii));
// Yes, uses the same old pointer as two statements ago to get a new value. Neat.
newObjects.push_back(*mPtr);
}
uninlineableObjectColumnIndex++;
if (uninlineableObjectColumnIndex < uninlineableObjectColumnCount) {
nextUninlineableObjectColumnInfoIndex =
m_schema->getUninlinedObjectColumnInfoIndex(uninlineableObjectColumnIndex);
} else {
// This is completely optional -- the value from here on has to be one that can't
// be reached by incrementing from the current value.
// Zero works, but then again so does the current value.
nextUninlineableObjectColumnInfoIndex = 0;
}
} else {
// TODO: Here, it's known that the column value is some kind of scalar or inline, yet
// setNValueAllocateForObjectCopies is called to figure this all out again.
// This seriously complicated function is going to boil down to an incremental
// memcpy of a few more bytes of the tuple.
// Solution? It would likely be faster even for object-heavy tuples to work in three passes:
// 1) collect up all the "changed object pointer" offsets.
// 2) do the same wholesale tuple memcpy as in the no-objects "else" clause, below,
// 3) replace the object pointer at each "changed object pointer offset"
// with a pointer to an object copy of its new referent.
setNValueAllocateForObjectCopies(ii, source.getNValue(ii));
}
}
// Copy any hidden columns that follow normal visible ones.
if (m_schema->hiddenColumnCount() > 0) {
// If we ever add support for uninlined hidden columns,
// we'll need to do update this code.
vassert(m_schema->getUninlinedObjectHiddenColumnCount() == 0);
::memcpy(m_data + TUPLE_HEADER_SIZE + m_schema->offsetOfHiddenColumns(),
source.m_data + TUPLE_HEADER_SIZE + m_schema->offsetOfHiddenColumns(),
m_schema->lengthOfAllHiddenColumns());
}
// This obscure assignment is propagating the tuple flags rather than leaving it to the caller.
// TODO: It would be easier for the caller to simply set the values it wants upon return.
m_data[0] = source.m_data[0];
} else {
// copy the tuple flags and the data (all inline/scalars)
::memcpy(m_data, source.m_data, m_schema->tupleLength() + TUPLE_HEADER_SIZE);
}
}
inline void TableTuple::copy(const TableTuple &source) {
vassert(m_schema);
vassert(source.m_schema);
vassert(source.m_data);
vassert(m_data);
#ifndef NDEBUG
if(! m_schema->isCompatibleForMemcpy(source.m_schema, false)) {
std::ostringstream message;
message << "src tuple: " << source.debug("") << std::endl;
message << "src schema: " << source.m_schema->debug() << std::endl;
message << "dest schema: " << m_schema->debug() << std::endl;
throwFatalException("%s", message.str().c_str());
}
#endif
if (m_schema == source.m_schema) {
// identical schema so do full raw copy
::memcpy(m_data, source.m_data, tupleLength());
} else {
// copy the visible data AND the isActive flag
::memcpy(m_data, source.m_data, m_schema->visibleTupleLength() + TUPLE_HEADER_SIZE);
// copy or initialize the hidden columns
for (int i = 0; i < m_schema->hiddenColumnCount(); ++i) {
HiddenColumn::Type type = m_schema->getHiddenColumnInfo(i)->columnType;
uint8_t index = source.m_schema->getHiddenColumnIndex(type);
NValue value =
index == TupleSchema::UNSET_HIDDEN_COLUMN ?
HiddenColumn::getDefaultValue(type) : source.getHiddenNValue(index);
setHiddenNValue(i, value);
}
}
}
inline void TableTuple::deserializeFrom(voltdb::SerializeInputBE &tupleIn, Pool *dataPool,
const LoadTableCaller &caller) {
vassert(m_schema);
vassert(m_data);
const int32_t columnCount = m_schema->columnCount();
const int32_t hiddenColumnCount = m_schema->hiddenColumnCount();
tupleIn.readInt();
// ENG-14346, we may throw SQLException because of a too-wide VARCHAR column.
// In some systems, the uninitialized StringRef* is not NULL, which may result in
// unexpected errors during cleanup.
// This can only happen in the loadTable path, because we check the value length
// in Java for the normal transaction path.
// We explicitly initialize the StringRefs for those non-inlined columns here to
// prevent any surprises.
uint16_t nonInlinedColCount = m_schema->getUninlinedObjectColumnCount();
for (uint16_t i = 0; i < nonInlinedColCount; i++) {
uint16_t idx = m_schema->getUninlinedObjectColumnInfoIndex(i);
const TupleSchema::ColumnInfo *columnInfo = m_schema->getColumnInfo(idx);
char *dataPtr = getWritableDataPtr(columnInfo);
*reinterpret_cast<StringRef**>(dataPtr) = NULL;
}
for (int j = 0; j < columnCount; ++j) {
const TupleSchema::ColumnInfo *columnInfo = m_schema->getColumnInfo(j);
/**
* Hack hack. deserializeFrom is only called when we serialize
* and deserialize tables. The serialization format for
* Strings/Objects in a serialized table happens to have the
* same in memory representation as the Strings/Objects in a
* tabletuple. The goal here is to wrap the serialized
* representation of the value in an NValue and then serialize
* that into the tuple from the NValue. This makes it possible
* to push more value specific functionality out of
* TableTuple. The memory allocation will be performed when
* serializing to tuple storage.
*/
char *dataPtr = getWritableDataPtr(columnInfo);
NValue::deserializeFrom(tupleIn, dataPool, dataPtr, columnInfo->getVoltType(),
columnInfo->inlined, static_cast<int32_t>(columnInfo->length), columnInfo->inBytes);
}
for (int j = 0; j < hiddenColumnCount; ++j) {
const TupleSchema::HiddenColumnInfo *columnInfo = m_schema->getHiddenColumnInfo(j);
if (caller.useDefaultValue(columnInfo->columnType)) {
VOLT_DEBUG("Using default value for caller %d and hidden column %d", caller.getId(), columnInfo->columnType);
setHiddenNValue(columnInfo, HiddenColumn::getDefaultValue(columnInfo->columnType));
} else { // tupleIn may not have hidden column
if (!tupleIn.hasRemaining()) {
throwSerializableEEException(
"TableTuple::deserializeFrom table tuple doesn't have enough space to deserialize the hidden column "
"(index=%d) hidden column count=%d\n", j, m_schema->hiddenColumnCount());
}
char *dataPtr = getWritableDataPtr(columnInfo);
NValue::deserializeFrom(tupleIn, dataPool, dataPtr, columnInfo->getVoltType(), false, -1, false);
}
}
}
inline void TableTuple::deserializeFromDR(voltdb::SerializeInputLE &tupleIn, Pool *dataPool) {
vassert(m_schema);
vassert(m_data);
const int32_t columnCount = m_schema->columnCount();
int nullMaskLength = ((columnCount + 7) & -8) >> 3;
const uint8_t *nullArray = reinterpret_cast<const uint8_t*>(tupleIn.getRawPointer(nullMaskLength));
for (int j = 0; j < columnCount; j++) {
const TupleSchema::ColumnInfo *columnInfo = m_schema->getColumnInfo(j);
const uint32_t index = j >> 3;
const uint32_t bit = j % 8;
const uint8_t mask = (uint8_t) (0x80u >> bit);
const bool isNull = (nullArray[index] & mask);
if (isNull) {
NValue value = NValue::getNullValue(columnInfo->getVoltType());
setNValue(j, value);
} else {
char *dataPtr = getWritableDataPtr(columnInfo);
NValue::deserializeFrom<TUPLE_SERIALIZATION_DR, BYTE_ORDER_LITTLE_ENDIAN>(
tupleIn, dataPool, dataPtr,
columnInfo->getVoltType(), columnInfo->inlined,
static_cast<int32_t>(columnInfo->length), columnInfo->inBytes);
}
}
int32_t hiddenColumnCount = m_schema->hiddenColumnCount();
for (int i = 0; i < hiddenColumnCount; i++) {
const TupleSchema::HiddenColumnInfo * hiddenColumnInfo = m_schema->getHiddenColumnInfo(i);
if (hiddenColumnInfo->columnType == HiddenColumn::MIGRATE_TXN) {
// Set the hidden column for persistent table to null
NValue value = NValue::getNullValue(hiddenColumnInfo->getVoltType());
setHiddenNValue(i, value);
} else {
char *dataPtr = getWritableDataPtr(hiddenColumnInfo);
NValue::deserializeFrom<TUPLE_SERIALIZATION_DR, BYTE_ORDER_LITTLE_ENDIAN>(
tupleIn, dataPool, dataPtr, hiddenColumnInfo->getVoltType(), false, -1, false);
}
}
}
inline void TableTuple::serializeTo(voltdb::SerializeOutput &output, const HiddenColumnFilter *filter) const {
size_t start = output.reserveBytes(4);
for (int j = 0; j < m_schema->columnCount(); ++j) {
//int fieldStart = output.position();
NValue value = getNValue(j);
value.serializeTo(output);
}
if (filter) {
for (int j = 0; j < m_schema->hiddenColumnCount(); ++j) {
if (filter->include(j)) {
NValue value = getHiddenNValue(j);
value.serializeTo(output);
}
}
}
// write the length of the tuple
output.writeIntAt(start, static_cast<int32_t>(output.position() - start - sizeof(int32_t)));
}
inline size_t TableTuple::serializeToExport(ExportSerializeOutput &io,
int colOffset, uint8_t *nullArray) const {
size_t sz = 0;
for (int i = 0; i < columnCount(); i++) {
sz += serializeColumnToExport(io, colOffset + i, getNValue(i), nullArray);
}
return sz;
}
inline void TableTuple::serializeToDR(ExportSerializeOutput &io, int colOffset, uint8_t *nullArray) {
serializeToExport(io, colOffset, nullArray);
serializeHiddenColumnsToDR(io);
}
inline bool TableTuple::equals(const TableTuple &other) const {
if (!m_schema->equals(other.m_schema)) {
return false;
}
return equalsNoSchemaCheck(other);
}
inline bool TableTuple::equalsNoSchemaCheck(const TableTuple &other,
const HiddenColumnFilter *hiddenColumnFilter) const {
for (int ii = 0; ii < m_schema->columnCount(); ii++) {
const NValue lhs = getNValue(ii);
const NValue rhs = other.getNValue(ii);
if (lhs.op_notEquals(rhs).isTrue()) {
return false;
}
}
if (hiddenColumnFilter != NULL) {
for (int ii = 0; ii < m_schema->hiddenColumnCount(); ii++) {
if (hiddenColumnFilter->include(ii)) {
const NValue lhs = getHiddenNValue(ii);
const NValue rhs = other.getHiddenNValue(ii);
if (lhs.op_notEquals(rhs).isTrue()) {
return false;
}
}
}
}
return true;
}
inline void TableTuple::setAllNulls() {
vassert(m_schema);
vassert(m_data);
for (int ii = 0; ii < m_schema->columnCount(); ++ii) {
const TupleSchema::ColumnInfo *columnInfo = m_schema->getColumnInfo(ii);
NValue value = NValue::getNullValue(columnInfo->getVoltType());
setNValue(columnInfo, value, false);
}
for (int jj = 0; jj < m_schema->hiddenColumnCount(); ++jj) {
const TupleSchema::HiddenColumnInfo *hiddenColumnInfo = m_schema->getHiddenColumnInfo(jj);
NValue value = NValue::getNullValue(hiddenColumnInfo->getVoltType());
setHiddenNValue(hiddenColumnInfo, value);
}
}
inline void TableTuple::relocateNonInlinedFields(std::ptrdiff_t offset) {
uint16_t nonInlinedColCount = m_schema->getUninlinedObjectColumnCount();
for (uint16_t i = 0; i < nonInlinedColCount; i++) {
uint16_t idx = m_schema->getUninlinedObjectColumnInfoIndex(i);
const TupleSchema::ColumnInfo *columnInfo = m_schema->getColumnInfo(idx);
vassert(isVariableLengthType(columnInfo->getVoltType()) && !columnInfo->inlined);
char **dataPtr = reinterpret_cast<char**>(getWritableDataPtr(columnInfo));
if (*dataPtr != NULL) {
(*dataPtr) += offset;
NValue value = getNValue(idx);
value.relocateNonInlined(offset);
}
}
}
inline int TableTuple::compare(const TableTuple &other) const {
const int columnCount = m_schema->columnCount();
int diff;
for (int ii = 0; ii < columnCount; ii++) {
const NValue lhs = getNValue(ii);
const NValue rhs = other.getNValue(ii);
diff = lhs.compare(rhs);
if (diff) {
return diff;
}
}
return VALUE_COMPARE_EQUAL;
}
/**
* Compare two tuples. Null value in the rhs tuple will be treated as maximum.
*/
inline int TableTuple::compareNullAsMax(const TableTuple &other) const {
const int columnCount = m_schema->columnCount();
assert(columnCount == other.m_schema->columnCount());
int diff;
for (int ii = 0; ii < columnCount; ii++) {
const NValue& lhs = getNValue(ii);
const NValue& rhs = other.getNValue(ii);
diff = lhs.compareNullAsMax(rhs);
if (diff) {
return diff;
}
}
return VALUE_COMPARE_EQUAL;
}
inline size_t TableTuple::hashCode(size_t seed) const {
const int columnCount = m_schema->columnCount();
for (int i = 0; i < columnCount; i++) {
const NValue value = getNValue(i);
value.hashCombine(seed);
}
return seed;
}
inline size_t TableTuple::hashCode() const {
size_t seed = 0;
return hashCode(seed);
}
/**
* Release to the heap any memory allocated for any uninlined columns.
*/
inline void TableTuple::freeObjectColumns() const {
const uint16_t unlinlinedColumnCount = m_schema->getUninlinedObjectColumnCount();
std::vector<char*> oldObjects;
for (int ii = 0; ii < unlinlinedColumnCount; ii++) {
int idx = m_schema->getUninlinedObjectColumnInfoIndex(ii);
const TupleSchema::ColumnInfo *columnInfo = m_schema->getColumnInfo(idx);
char** dataPtr = reinterpret_cast<char**>(getWritableDataPtr(columnInfo));
oldObjects.push_back(*dataPtr);
}
NValue::freeObjectsFromTupleStorage(oldObjects);
}
/**
* Hasher for use with boost::unordered_map and similar
*/
struct TableTupleHasher : std::unary_function<TableTuple, std::size_t> {
/** Generate a 64-bit number for the key value */
size_t operator()(TableTuple const& tuple) const {
return tuple.hashCode();
}
};
/**
* Equality operator for use with boost::unrodered_map and similar
*/
class TableTupleEqualityChecker {
public:
bool operator()(const TableTuple& lhs, const TableTuple& rhs) const {
return lhs.equalsNoSchemaCheck(rhs);
}
};
}
| 40.724736 | 129 | 0.654043 | [
"object",
"vector"
] |
6d96296cb83e38303517e1f61bb42dd2ede36671 | 1,159 | h | C | Plugins/RPRPlugin/Source/RPRPlugin/Public/Scene/UMSControl.h | hi-ro-no/RadeonProRenderUE | dcbf2b6df80b104c6cd2994e047f5d2fef98f493 | [
"Apache-2.0"
] | 15 | 2020-05-13T17:23:40.000Z | 2022-01-08T04:19:42.000Z | Plugins/RPRPlugin/Source/RPRPlugin/Public/Scene/UMSControl.h | hi-ro-no/RadeonProRenderUE | dcbf2b6df80b104c6cd2994e047f5d2fef98f493 | [
"Apache-2.0"
] | 12 | 2020-05-17T08:06:45.000Z | 2021-12-20T18:07:59.000Z | Plugins/RPRPlugin/Source/RPRPlugin/Public/Scene/UMSControl.h | hi-ro-no/RadeonProRenderUE | dcbf2b6df80b104c6cd2994e047f5d2fef98f493 | [
"Apache-2.0"
] | 7 | 2020-05-15T16:07:44.000Z | 2021-07-14T08:38:54.000Z | /*************************************************************************
* Copyright 2020 Advanced Micro Devices
*
* 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 <string>
#include <string>
#include <vector>
#include <unordered_set>
#include <unordered_map>
namespace rpr
{
class UMSControl
{
public:
UMSControl();
~UMSControl();
void Clear();
void LoadControlData(const std::string& filename);
bool IsMaterialUMSEnabled(const std::string& name);
private:
bool matchAll = false;
std::unordered_map<std::string, bool> materialEnables;
};
}
| 25.195652 | 74 | 0.647972 | [
"vector"
] |
6d9bb360a08cfc929eea2468865bc33c3b37b4b9 | 1,900 | h | C | deps/cppdistract/dso.h | simpleton/profilo | 91ef4ba1a8316bad2b3080210316dfef4761e180 | [
"Apache-2.0"
] | null | null | null | deps/cppdistract/dso.h | simpleton/profilo | 91ef4ba1a8316bad2b3080210316dfef4761e180 | [
"Apache-2.0"
] | null | null | null | deps/cppdistract/dso.h | simpleton/profilo | 91ef4ba1a8316bad2b3080210316dfef4761e180 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2004-present, Facebook, Inc.
*
* 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 <initializer_list>
namespace facebook { namespace cppdistract {
/**
* RAII object wrapping dlopen() and dlsym()
*/
class dso {
public:
/**
* Opens the named library, using dlopen(2).
*
* Throws std::runtime_error if the library fails to load.
*/
explicit dso(char const* name);
~dso();
/**
* Returns the dlopen handle to this library.
*
* NOTA BENE: This is explicitly a _handle_. It is not necessarily the address of the library.
*/
void* get_handle() const;
/**
* Returns the named symbol exported by this library.
*
* Throws std::runtime_error if not found.
*/
template <typename T>
T* get_symbol(char const* name) const {
return get_symbol<T>({ name });
}
/**
* Takes a list of possible names, returns the first symbol among them that is found.
*
* Throws std::runtime_error if none are found.
*/
template<typename T>
T* get_symbol(std::initializer_list<char const*> const& names) const {
return reinterpret_cast<T*>(get_symbol_internal(names));
}
private:
void* const handle_;
void* get_symbol_internal(std::initializer_list<char const*> const& names) const;
};
} } // namespace facebook::cppdistract
| 27.142857 | 98 | 0.669474 | [
"object"
] |
6da086c27bbb157df3a9b968e0c660c601385689 | 2,850 | h | C | frc971/analysis/plotting/webgl2_plotter.h | Ewpratten/frc_971_mirror | 3a8a0c4359f284d29547962c2b4c43d290d8065c | [
"BSD-2-Clause"
] | null | null | null | frc971/analysis/plotting/webgl2_plotter.h | Ewpratten/frc_971_mirror | 3a8a0c4359f284d29547962c2b4c43d290d8065c | [
"BSD-2-Clause"
] | null | null | null | frc971/analysis/plotting/webgl2_plotter.h | Ewpratten/frc_971_mirror | 3a8a0c4359f284d29547962c2b4c43d290d8065c | [
"BSD-2-Clause"
] | null | null | null | #ifndef FRC971_ANALYSIS_PLOTTING_WEBGL2_PLOTTER_H_
#define FRC971_ANALYSIS_PLOTTING_WEBGL2_PLOTTER_H_
#include <vector>
#include <Eigen/Dense>
#define GL_GLEXT_PROTOTYPES
#include <GLES3/gl3.h>
#include <GLES3/gl2ext.h>
#include <GLES3/gl32.h>
namespace frc971 {
namespace plotting {
struct Color {
float r;
float g;
float b;
};
class Line {
public:
virtual ~Line() {}
virtual void SetPoints(const std::vector<Eigen::Vector2d> &pts) = 0;
virtual void SetColor(const Color &color) = 0;
virtual void Draw() = 0;
virtual Eigen::Vector2d MaxValues() const = 0;
virtual Eigen::Vector2d MinValues() const = 0;
virtual void SetLineWidth(const float width) = 0;
virtual void SetPointSize(const float point_size) = 0;
virtual bool HasUpdate() = 0;
};
// TODO(james): Actually do something with this interface; originally, I'd meant
// to look at writing some tests, but right now it's just extra boilerplate.
class Plotter {
public:
virtual Line *AddLine() = 0;
virtual void SetScale(const Eigen::Vector2d &scale) = 0;
virtual Eigen::Vector2d GetScale() const = 0;
virtual void SetOffset(const Eigen::Vector2d &offset) = 0;
virtual Eigen::Vector2d GetOffset() const = 0;
virtual void Redraw() = 0;
virtual Eigen::Vector2d MaxValues() const = 0;
virtual Eigen::Vector2d MinValues() const = 0;
virtual void ClearZoomRectangle() = 0;
virtual void SetZoomRectangle(const Eigen::Vector2d &corner1,
const Eigen::Vector2d &corner2) = 0;
virtual void RecordState() = 0;
virtual void Undo() = 0;
};
class WebglCanvasPlotter : public Plotter {
public:
WebglCanvasPlotter(const std::string &canvas_id,
GLuint attribute_location = 0);
Line *AddLine() override;
void SetScale(const Eigen::Vector2d &scale) override;
Eigen::Vector2d GetScale() const override;
void SetOffset(const Eigen::Vector2d &offset) override;
Eigen::Vector2d GetOffset() const override;
void Redraw() override;
Eigen::Vector2d MaxValues() const override;
Eigen::Vector2d MinValues() const override;
void ClearZoomRectangle() override;
void SetZoomRectangle(const Eigen::Vector2d &corner1,
const Eigen::Vector2d &corner2) override;
void RecordState() override;
void Undo() override;
private:
std::vector<std::unique_ptr<Line>> lines_;
std::unique_ptr<Line> zoom_rectangle_;
Eigen::Vector2d scale_{1.0, 1.0};
Eigen::Vector2d offset_{0.0, 0.0};
std::vector<Eigen::Vector2d> old_scales_;
std::vector<Eigen::Vector2d> old_offsets_;
Eigen::Vector2d last_scale_{1.0, 1.0};
Eigen::Vector2d last_offset_{0.0, 0.0};
GLuint program_;
GLuint scale_uniform_location_;
GLuint offset_uniform_location_;
GLuint gl_buffer_;
};
} // namespace plotting
} // namespace frc971
#endif // FRC971_ANALYSIS_PLOTTING_WEBGL2_PLOTTER_H_
| 32.022472 | 80 | 0.717193 | [
"vector"
] |
6da4d93be715051d40d111b567655ea65c7ec1e5 | 7,546 | c | C | lib/utility/libpfstream/pthread_routines.c | jreyes1108/antelope_contrib | be2354605d8463d6067029eb16464a0bf432a41b | [
"BSD-2-Clause",
"MIT"
] | 30 | 2015-02-20T21:44:29.000Z | 2021-09-27T02:53:14.000Z | lib/utility/libpfstream/pthread_routines.c | jreyes1108/antelope_contrib | be2354605d8463d6067029eb16464a0bf432a41b | [
"BSD-2-Clause",
"MIT"
] | 14 | 2015-07-07T19:17:24.000Z | 2020-12-19T19:18:53.000Z | lib/utility/libpfstream/pthread_routines.c | jreyes1108/antelope_contrib | be2354605d8463d6067029eb16464a0bf432a41b | [
"BSD-2-Clause",
"MIT"
] | 46 | 2015-02-06T16:22:41.000Z | 2022-03-30T11:46:37.000Z | #include <stdio.h>
/* This file currently has an include for pthread.h so we don't require it */
#include "brttutil.h"
#include "pfstream.h"
/* This is the arg struct passed to both read and write threads */
typedef struct pfsc {
FILE *fp;
Pmtfifo *mtf;
} Pfstream_control;
/* These are read and write functions that define control by one
thread that does in and out respectively. i.e. they are passed to
pthread_create. */
/* This is the read function. It simply reads data from the input
stream creating raw pf's that encapsulate all the data. These
are simply pushed onto to mtfifo.
The routine provides a redundant signal for end of data by
pushing a FINISHED boolean onto the pf set true. This provides
an mechanism to terminate cleanly on eoi. Other with a thread
reading and pushing I don't see how else to tell downstream
processors that this function is not just waiting for data
and the queue is empty.*/
void * pfstream_read_data(void *arg)
{
Pfstream_control *pfsc;
Pf *pf; /* Data read in as a single, raw pf object*/
pfsc = (Pfstream_control *)arg;
while( (pf=pfstream_read(pfsc->fp)) != NULL)
{
pfput_boolean(pf,"FINISHED",0);
pmtfifo_push(pfsc->mtf,(void *)pf);
}
pf=pfnew(PFFILE);
pfput_boolean(pf,"FINISHED",1);
pmtfifo_push(pfsc->mtf,(void *)pf);
fclose(pfsc->fp);
return(NULL);
}
/* This is the opposite of the previous */
void *pfstream_write_data(void *arg)
{
Pfstream_control *pfsc=(Pfstream_control *)arg;
Pf *pf,*pftest;
int fini;
int itest;
while(1)
{
pmtfifo_pop(pfsc->mtf,(void **)(&pf));
/* this is a safe test if FINISHED is not set.
Should not require user to have to do this */
itest = pfget(pf,"FINISHED",(void **)&pftest);
if(itest==PFINVALID)
{
fini=0;
pfput_boolean(pf,"FINISHED",0);
}
else
fini=pfget_boolean(pf,"FINISHED");
if(fini)
{
fprintf(pfsc->fp,"%s\n",END_OF_DATA_SENTINEL);
fflush(pfsc->fp);
sleep(20);
fclose(pfsc->fp);
break;
}
pfout(pfsc->fp,pf);
fprintf(pfsc->fp,"%s\n", ENDPF_SENTINEL);
fflush(pfsc->fp);
/* We have release the memory for pf here as the caller
is pushing this away a forgetting about it */
pffree(pf);
}
return(NULL);
}
/* Creates a new thread to read pfstream data from fname. Returns
a handle that defines the interface into the pfstream. This is implementd
here by Brtt's pmtfifo.
This function mostly just creates the data objects used for the interface
and then sets up and creates the read thread passed to pthread_create.
Author: Gary Pavlis
Written: october 2002
*/
#define PFSTREAM_MAXQUEUE 10 /* size of stack in pmtfifo queue */
Pfstream_handle *pfstream_start_read_thread(char *fname)
{
Pfstream_handle *pfh; /* Handle downstream functions can use to
access data from the pfstream */
Pfstream_control *pfsc; /* control structure passed to new thread */
/*These need to be created fromt he free store. If we
used a local variable in this function these would disappear when
this routine went out of scope screwing up the thread it was passed
to, and the return handle would get dropped.*/
allot(Pfstream_handle *,pfh,1);
allot(Pfstream_control *, pfsc, 1);
/* brttutil routine to create a multithreaded, posix compatible thread */
pfh->mtf = pmtfifo_create(PFSTREAM_MAXQUEUE,1,0);
if(pfh->mtf == NULL)
{
elog_log(1,"pfstream_start_read_thead: Could not create mtfifo\n");
free(pfh);
free(pfsc);
return(NULL);
}
pfsc->mtf=pfh->mtf;
/* open the stream and put the fp into the control structure */
pfsc->fp = fopen(fname,"r");
if(pfsc->fp==NULL)
{
elog_log(1,"pfstream_start_read_thread: Cannot open input stream %s\n",
fname);
pmtfifo_destroy(pfh->mtf,free);
free(pfh);
free(pfsc);
return(NULL);
}
/* This launches the i/o thread. It is assumed that all it does is
read data and push objects onto the Pmtfifo for downstream processors
to pop off and use. */
if(pthread_create(&(pfh->thread_id),NULL,
pfstream_read_data,(void *)pfsc)!=0)
{
elog_log(1,"pfstream_start_read_thread: cannot create read thread\n");
pmtfifo_destroy(pfh->mtf,free);
fclose(pfsc->fp);
free(pfh);
free(pfsc);
return(NULL);
}
return(pfh);
}
/* Parallel to above, but for output */
Pfstream_handle *pfstream_start_write_thread(char *fname)
{
Pfstream_handle *pfh; /* Handle downstream functions can use to
access data from the pfstream */
Pfstream_control *pfsc; /* control structure passed to new thread */
/*These need to be created fromt he free store. If we
used a local variable in this function these would disappear when
this routine went out of scope screwing up the thread it was passed
to, and the return handle would get dropped.*/
allot(Pfstream_handle *,pfh,1);
allot(Pfstream_control *, pfsc, 1);
/* brttutil routine to create a multithreaded, posix compatible thread */
pfh->mtf = pmtfifo_create(PFSTREAM_MAXQUEUE,1,0);
if(pfh->mtf == NULL)
{
elog_log(1,"pfstream_start_write_thead: Could not create mtfifo\n");
free(pfh);
free(pfsc);
return(NULL);
}
pfsc->mtf=pfh->mtf;
/* open the stream and put the fp into the control structure */
pfsc->fp = fopen(fname,"r+");
if(pfsc->fp==NULL)
{
elog_log(1,"pfstream_start_write_thread: Cannot open output stream %s\n",
fname);
pmtfifo_destroy(pfh->mtf,free);
free(pfh);
free(pfsc);
return(NULL);
}
/* This launches the write thread. This is assumed to do the
opposite of the read thread. That is, processing modules will
push data onto this mtfifo and the write routine handled by
this thread will pop them off and send the contents down the
stream now open as fp */
if(pthread_create(&(pfh->thread_id),NULL,pfstream_write_data,(void *)pfsc)!=0)
{
elog_log(1,"pfstream_start_write_thread: cannot create write thread\n");
pmtfifo_destroy(pfh->mtf,free);
fclose(pfsc->fp);
free(pfh);
free(pfsc);
return(NULL);
}
return(pfh);
}
/* This is the routine that uses data pushed onto the queue by the
read thread. All it does is call pmtfifo and handle error conditions.
pfh is the control structure returned by the read thread we use
to access the data contained in the fifo.
Returns a NULL to signal end of data. This can happen one of two ways.
If there is an error in pmtfifo_pop, complain is called and we return NULL.
This was done to allow a graceful exit from the caller. The warning message
may be too subtle, but I see now simple way to do this with plain C. This
is a case where I can see reasons for C++'s throw having a big advantage.
The function will also return NULL when it sees the end of data.
That is caught here by the FINISHED boolean in the pf.
*/
Pf *pfstream_get_next_ensemble(Pfstream_handle *pfh)
{
Pf *pf; /* Pf popped from Pmtfifo */
if(pmtfifo_pop(pfh->mtf,(void **)(&pf)) < 0)
{
elog_complain(1,"pfstream_get_next_ensemble: Attempt to fetch data from input fifo failed\nData stream was probably trunctated\nTrying to clean up before exit\n");
return(NULL);
}
if(pfget_boolean(pf,"FINISHED"))
{
pffree(pf);
return(NULL);
}
return(pf);
}
/* The opposite is equally simple. We assume the output has already been
encapsulated into a single pf. Returns 0 on success, -1 if problems
occur */
int pfstream_put_ensemble(Pfstream_handle *pfh, Pf *pf)
{
int iret;
iret = pmtfifo_push(pfh->mtf,(void *)pf);
if(iret<0)
{
elog_complain(0,"pfstream_put_ensemble: Attempt to push data to output fifo failed\n");
return(-1);
}
return(0);
}
| 30.550607 | 166 | 0.711238 | [
"object"
] |
6db340d7a991c46ad477c4184aa2d50b036b1723 | 18,034 | c | C | APPS/openssh-3.4p1/cipher.c | shkir/sctp-refimpl | 76d37a9a01919b1ba43eaa8b18229ff49c70a8f7 | [
"BSD-2-Clause"
] | 8 | 2015-07-20T19:33:58.000Z | 2019-10-27T10:02:23.000Z | APPS/openssh-3.4p1/cipher.c | shkir/sctp-refimpl | 76d37a9a01919b1ba43eaa8b18229ff49c70a8f7 | [
"BSD-2-Clause"
] | 2 | 2015-07-19T13:27:57.000Z | 2015-07-22T10:46:12.000Z | APPS/openssh-3.4p1/cipher.c | shkir/sctp-refimpl | 76d37a9a01919b1ba43eaa8b18229ff49c70a8f7 | [
"BSD-2-Clause"
] | 6 | 2015-07-19T12:20:24.000Z | 2019-11-30T23:56:41.000Z | /*
* Author: Tatu Ylonen <ylo@cs.hut.fi>
* Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
* All rights reserved
*
* As far as I am concerned, the code I have written for this software
* can be used freely for any purpose. Any derived versions of this
* software must be clearly marked as such, and if the derived work is
* incompatible with the protocol description in the RFC file, it must be
* called by a name other than "ssh" or "Secure Shell".
*
*
* Copyright (c) 1999 Niels Provos. All rights reserved.
* Copyright (c) 1999, 2000 Markus Friedl. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "includes.h"
RCSID("$OpenBSD: cipher.c,v 1.60 2002/06/23 03:26:52 deraadt Exp $");
#include "xmalloc.h"
#include "log.h"
#include "cipher.h"
#include <openssl/md5.h>
#if OPENSSL_VERSION_NUMBER < 0x00906000L
#define SSH_OLD_EVP
#define EVP_CIPHER_CTX_get_app_data(e) ((e)->app_data)
#endif
#if OPENSSL_VERSION_NUMBER < 0x00907000L
#include "rijndael.h"
static const EVP_CIPHER *evp_rijndael(void);
#endif
static const EVP_CIPHER *evp_ssh1_3des(void);
static const EVP_CIPHER *evp_ssh1_bf(void);
struct Cipher {
char *name;
int number; /* for ssh1 only */
u_int block_size;
u_int key_len;
const EVP_CIPHER *(*evptype)(void);
} ciphers[] = {
{ "none", SSH_CIPHER_NONE, 8, 0, EVP_enc_null },
{ "des", SSH_CIPHER_DES, 8, 8, EVP_des_cbc },
{ "3des", SSH_CIPHER_3DES, 8, 16, evp_ssh1_3des },
{ "blowfish", SSH_CIPHER_BLOWFISH, 8, 32, evp_ssh1_bf },
{ "3des-cbc", SSH_CIPHER_SSH2, 8, 24, EVP_des_ede3_cbc },
{ "blowfish-cbc", SSH_CIPHER_SSH2, 8, 16, EVP_bf_cbc },
{ "cast128-cbc", SSH_CIPHER_SSH2, 8, 16, EVP_cast5_cbc },
{ "arcfour", SSH_CIPHER_SSH2, 8, 16, EVP_rc4 },
#if OPENSSL_VERSION_NUMBER < 0x00907000L
{ "aes128-cbc", SSH_CIPHER_SSH2, 16, 16, evp_rijndael },
{ "aes192-cbc", SSH_CIPHER_SSH2, 16, 24, evp_rijndael },
{ "aes256-cbc", SSH_CIPHER_SSH2, 16, 32, evp_rijndael },
{ "rijndael-cbc@lysator.liu.se",
SSH_CIPHER_SSH2, 16, 32, evp_rijndael },
#else
{ "aes128-cbc", SSH_CIPHER_SSH2, 16, 16, EVP_aes_128_cbc },
{ "aes192-cbc", SSH_CIPHER_SSH2, 16, 24, EVP_aes_192_cbc },
{ "aes256-cbc", SSH_CIPHER_SSH2, 16, 32, EVP_aes_256_cbc },
{ "rijndael-cbc@lysator.liu.se",
SSH_CIPHER_SSH2, 16, 32, EVP_aes_256_cbc },
#endif
{ NULL, SSH_CIPHER_ILLEGAL, 0, 0, NULL }
};
/*--*/
u_int
cipher_blocksize(Cipher *c)
{
return (c->block_size);
}
u_int
cipher_keylen(Cipher *c)
{
return (c->key_len);
}
u_int
cipher_get_number(Cipher *c)
{
return (c->number);
}
u_int
cipher_mask_ssh1(int client)
{
u_int mask = 0;
mask |= 1 << SSH_CIPHER_3DES; /* Mandatory */
mask |= 1 << SSH_CIPHER_BLOWFISH;
if (client) {
mask |= 1 << SSH_CIPHER_DES;
}
return mask;
}
Cipher *
cipher_by_name(const char *name)
{
Cipher *c;
for (c = ciphers; c->name != NULL; c++)
if (strcasecmp(c->name, name) == 0)
return c;
return NULL;
}
Cipher *
cipher_by_number(int id)
{
Cipher *c;
for (c = ciphers; c->name != NULL; c++)
if (c->number == id)
return c;
return NULL;
}
#define CIPHER_SEP ","
int
ciphers_valid(const char *names)
{
Cipher *c;
char *ciphers, *cp;
char *p;
if (names == NULL || strcmp(names, "") == 0)
return 0;
ciphers = cp = xstrdup(names);
for ((p = strsep(&cp, CIPHER_SEP)); p && *p != '\0';
(p = strsep(&cp, CIPHER_SEP))) {
c = cipher_by_name(p);
if (c == NULL || c->number != SSH_CIPHER_SSH2) {
debug("bad cipher %s [%s]", p, names);
xfree(ciphers);
return 0;
} else {
debug3("cipher ok: %s [%s]", p, names);
}
}
debug3("ciphers ok: [%s]", names);
xfree(ciphers);
return 1;
}
/*
* Parses the name of the cipher. Returns the number of the corresponding
* cipher, or -1 on error.
*/
int
cipher_number(const char *name)
{
Cipher *c;
if (name == NULL)
return -1;
c = cipher_by_name(name);
return (c==NULL) ? -1 : c->number;
}
char *
cipher_name(int id)
{
Cipher *c = cipher_by_number(id);
return (c==NULL) ? "<unknown>" : c->name;
}
void
cipher_init(CipherContext *cc, Cipher *cipher,
const u_char *key, u_int keylen, const u_char *iv, u_int ivlen,
int encrypt)
{
static int dowarn = 1;
#ifdef SSH_OLD_EVP
EVP_CIPHER *type;
#else
const EVP_CIPHER *type;
#endif
int klen;
if (cipher->number == SSH_CIPHER_DES) {
if (dowarn) {
error("Warning: use of DES is strongly discouraged "
"due to cryptographic weaknesses");
dowarn = 0;
}
if (keylen > 8)
keylen = 8;
}
cc->plaintext = (cipher->number == SSH_CIPHER_NONE);
if (keylen < cipher->key_len)
fatal("cipher_init: key length %d is insufficient for %s.",
keylen, cipher->name);
if (iv != NULL && ivlen < cipher->block_size)
fatal("cipher_init: iv length %d is insufficient for %s.",
ivlen, cipher->name);
cc->cipher = cipher;
type = (*cipher->evptype)();
EVP_CIPHER_CTX_init(&cc->evp);
#ifdef SSH_OLD_EVP
if (type->key_len > 0 && type->key_len != keylen) {
debug("cipher_init: set keylen (%d -> %d)",
type->key_len, keylen);
type->key_len = keylen;
}
EVP_CipherInit(&cc->evp, type, (u_char *)key, (u_char *)iv,
(encrypt == CIPHER_ENCRYPT));
#else
if (EVP_CipherInit(&cc->evp, type, NULL, (u_char *)iv,
(encrypt == CIPHER_ENCRYPT)) == 0)
fatal("cipher_init: EVP_CipherInit failed for %s",
cipher->name);
klen = EVP_CIPHER_CTX_key_length(&cc->evp);
if (klen > 0 && keylen != klen) {
debug("cipher_init: set keylen (%d -> %d)", klen, keylen);
if (EVP_CIPHER_CTX_set_key_length(&cc->evp, keylen) == 0)
fatal("cipher_init: set keylen failed (%d -> %d)",
klen, keylen);
}
if (EVP_CipherInit(&cc->evp, NULL, (u_char *)key, NULL, -1) == 0)
fatal("cipher_init: EVP_CipherInit: set key failed for %s",
cipher->name);
#endif
}
void
cipher_crypt(CipherContext *cc, u_char *dest, const u_char *src, u_int len)
{
if (len % cc->cipher->block_size)
fatal("cipher_encrypt: bad plaintext length %d", len);
#ifdef SSH_OLD_EVP
EVP_Cipher(&cc->evp, dest, (u_char *)src, len);
#else
if (EVP_Cipher(&cc->evp, dest, (u_char *)src, len) == 0)
fatal("evp_crypt: EVP_Cipher failed");
#endif
}
void
cipher_cleanup(CipherContext *cc)
{
#ifdef SSH_OLD_EVP
EVP_CIPHER_CTX_cleanup(&cc->evp);
#else
if (EVP_CIPHER_CTX_cleanup(&cc->evp) == 0)
error("cipher_cleanup: EVP_CIPHER_CTX_cleanup failed");
#endif
}
/*
* Selects the cipher, and keys if by computing the MD5 checksum of the
* passphrase and using the resulting 16 bytes as the key.
*/
void
cipher_set_key_string(CipherContext *cc, Cipher *cipher,
const char *passphrase, int encrypt)
{
MD5_CTX md;
u_char digest[16];
MD5_Init(&md);
MD5_Update(&md, (const u_char *)passphrase, strlen(passphrase));
MD5_Final(digest, &md);
cipher_init(cc, cipher, digest, 16, NULL, 0, encrypt);
memset(digest, 0, sizeof(digest));
memset(&md, 0, sizeof(md));
}
/* Implementations for other non-EVP ciphers */
/*
* This is used by SSH1:
*
* What kind of triple DES are these 2 routines?
*
* Why is there a redundant initialization vector?
*
* If only iv3 was used, then, this would till effect have been
* outer-cbc. However, there is also a private iv1 == iv2 which
* perhaps makes differential analysis easier. On the other hand, the
* private iv1 probably makes the CRC-32 attack ineffective. This is a
* result of that there is no longer any known iv1 to use when
* choosing the X block.
*/
struct ssh1_3des_ctx
{
EVP_CIPHER_CTX k1, k2, k3;
};
static int
ssh1_3des_init(EVP_CIPHER_CTX *ctx, const u_char *key, const u_char *iv,
int enc)
{
struct ssh1_3des_ctx *c;
u_char *k1, *k2, *k3;
if ((c = EVP_CIPHER_CTX_get_app_data(ctx)) == NULL) {
c = xmalloc(sizeof(*c));
EVP_CIPHER_CTX_set_app_data(ctx, c);
}
if (key == NULL)
return (1);
if (enc == -1)
enc = ctx->encrypt;
k1 = k2 = k3 = (u_char *) key;
k2 += 8;
if (EVP_CIPHER_CTX_key_length(ctx) >= 16+8) {
if (enc)
k3 += 16;
else
k1 += 16;
}
EVP_CIPHER_CTX_init(&c->k1);
EVP_CIPHER_CTX_init(&c->k2);
EVP_CIPHER_CTX_init(&c->k3);
#ifdef SSH_OLD_EVP
EVP_CipherInit(&c->k1, EVP_des_cbc(), k1, NULL, enc);
EVP_CipherInit(&c->k2, EVP_des_cbc(), k2, NULL, !enc);
EVP_CipherInit(&c->k3, EVP_des_cbc(), k3, NULL, enc);
#else
if (EVP_CipherInit(&c->k1, EVP_des_cbc(), k1, NULL, enc) == 0 ||
EVP_CipherInit(&c->k2, EVP_des_cbc(), k2, NULL, !enc) == 0 ||
EVP_CipherInit(&c->k3, EVP_des_cbc(), k3, NULL, enc) == 0) {
memset(c, 0, sizeof(*c));
xfree(c);
EVP_CIPHER_CTX_set_app_data(ctx, NULL);
return (0);
}
#endif
return (1);
}
static int
ssh1_3des_cbc(EVP_CIPHER_CTX *ctx, u_char *dest, const u_char *src, u_int len)
{
struct ssh1_3des_ctx *c;
if ((c = EVP_CIPHER_CTX_get_app_data(ctx)) == NULL) {
error("ssh1_3des_cbc: no context");
return (0);
}
#ifdef SSH_OLD_EVP
EVP_Cipher(&c->k1, dest, (u_char *)src, len);
EVP_Cipher(&c->k2, dest, dest, len);
EVP_Cipher(&c->k3, dest, dest, len);
#else
if (EVP_Cipher(&c->k1, dest, (u_char *)src, len) == 0 ||
EVP_Cipher(&c->k2, dest, dest, len) == 0 ||
EVP_Cipher(&c->k3, dest, dest, len) == 0)
return (0);
#endif
return (1);
}
static int
ssh1_3des_cleanup(EVP_CIPHER_CTX *ctx)
{
struct ssh1_3des_ctx *c;
if ((c = EVP_CIPHER_CTX_get_app_data(ctx)) != NULL) {
memset(c, 0, sizeof(*c));
xfree(c);
EVP_CIPHER_CTX_set_app_data(ctx, NULL);
}
return (1);
}
static const EVP_CIPHER *
evp_ssh1_3des(void)
{
static EVP_CIPHER ssh1_3des;
memset(&ssh1_3des, 0, sizeof(EVP_CIPHER));
ssh1_3des.nid = NID_undef;
ssh1_3des.block_size = 8;
ssh1_3des.iv_len = 0;
ssh1_3des.key_len = 16;
ssh1_3des.init = ssh1_3des_init;
ssh1_3des.cleanup = ssh1_3des_cleanup;
ssh1_3des.do_cipher = ssh1_3des_cbc;
#ifndef SSH_OLD_EVP
ssh1_3des.flags = EVP_CIPH_CBC_MODE | EVP_CIPH_VARIABLE_LENGTH;
#endif
return (&ssh1_3des);
}
/*
* SSH1 uses a variation on Blowfish, all bytes must be swapped before
* and after encryption/decryption. Thus the swap_bytes stuff (yuk).
*/
static void
swap_bytes(const u_char *src, u_char *dst, int n)
{
u_char c[4];
/* Process 4 bytes every lap. */
for (n = n / 4; n > 0; n--) {
c[3] = *src++;
c[2] = *src++;
c[1] = *src++;
c[0] = *src++;
*dst++ = c[0];
*dst++ = c[1];
*dst++ = c[2];
*dst++ = c[3];
}
}
static int (*orig_bf)(EVP_CIPHER_CTX *, u_char *, const u_char *, u_int) = NULL;
static int
bf_ssh1_cipher(EVP_CIPHER_CTX *ctx, u_char *out, const u_char *in, u_int len)
{
int ret;
swap_bytes(in, out, len);
ret = (*orig_bf)(ctx, out, out, len);
swap_bytes(out, out, len);
return (ret);
}
static const EVP_CIPHER *
evp_ssh1_bf(void)
{
static EVP_CIPHER ssh1_bf;
memcpy(&ssh1_bf, EVP_bf_cbc(), sizeof(EVP_CIPHER));
orig_bf = ssh1_bf.do_cipher;
ssh1_bf.nid = NID_undef;
ssh1_bf.do_cipher = bf_ssh1_cipher;
ssh1_bf.key_len = 32;
return (&ssh1_bf);
}
#if OPENSSL_VERSION_NUMBER < 0x00907000L
/* RIJNDAEL */
#define RIJNDAEL_BLOCKSIZE 16
struct ssh_rijndael_ctx
{
rijndael_ctx r_ctx;
u_char r_iv[RIJNDAEL_BLOCKSIZE];
};
static int
ssh_rijndael_init(EVP_CIPHER_CTX *ctx, const u_char *key, const u_char *iv,
int enc)
{
struct ssh_rijndael_ctx *c;
if ((c = EVP_CIPHER_CTX_get_app_data(ctx)) == NULL) {
c = xmalloc(sizeof(*c));
EVP_CIPHER_CTX_set_app_data(ctx, c);
}
if (key != NULL) {
if (enc == -1)
enc = ctx->encrypt;
rijndael_set_key(&c->r_ctx, (u_char *)key,
8*EVP_CIPHER_CTX_key_length(ctx), enc);
}
if (iv != NULL)
memcpy(c->r_iv, iv, RIJNDAEL_BLOCKSIZE);
return (1);
}
static int
ssh_rijndael_cbc(EVP_CIPHER_CTX *ctx, u_char *dest, const u_char *src,
u_int len)
{
struct ssh_rijndael_ctx *c;
u_char buf[RIJNDAEL_BLOCKSIZE];
u_char *cprev, *cnow, *plain, *ivp;
int i, j, blocks = len / RIJNDAEL_BLOCKSIZE;
if (len == 0)
return (1);
if (len % RIJNDAEL_BLOCKSIZE)
fatal("ssh_rijndael_cbc: bad len %d", len);
if ((c = EVP_CIPHER_CTX_get_app_data(ctx)) == NULL) {
error("ssh_rijndael_cbc: no context");
return (0);
}
if (ctx->encrypt) {
cnow = dest;
plain = (u_char *)src;
cprev = c->r_iv;
for (i = 0; i < blocks; i++, plain+=RIJNDAEL_BLOCKSIZE,
cnow+=RIJNDAEL_BLOCKSIZE) {
for (j = 0; j < RIJNDAEL_BLOCKSIZE; j++)
buf[j] = plain[j] ^ cprev[j];
rijndael_encrypt(&c->r_ctx, buf, cnow);
cprev = cnow;
}
memcpy(c->r_iv, cprev, RIJNDAEL_BLOCKSIZE);
} else {
cnow = (u_char *) (src+len-RIJNDAEL_BLOCKSIZE);
plain = dest+len-RIJNDAEL_BLOCKSIZE;
memcpy(buf, cnow, RIJNDAEL_BLOCKSIZE);
for (i = blocks; i > 0; i--, cnow-=RIJNDAEL_BLOCKSIZE,
plain-=RIJNDAEL_BLOCKSIZE) {
rijndael_decrypt(&c->r_ctx, cnow, plain);
ivp = (i == 1) ? c->r_iv : cnow-RIJNDAEL_BLOCKSIZE;
for (j = 0; j < RIJNDAEL_BLOCKSIZE; j++)
plain[j] ^= ivp[j];
}
memcpy(c->r_iv, buf, RIJNDAEL_BLOCKSIZE);
}
return (1);
}
static int
ssh_rijndael_cleanup(EVP_CIPHER_CTX *ctx)
{
struct ssh_rijndael_ctx *c;
if ((c = EVP_CIPHER_CTX_get_app_data(ctx)) != NULL) {
memset(c, 0, sizeof(*c));
xfree(c);
EVP_CIPHER_CTX_set_app_data(ctx, NULL);
}
return (1);
}
static const EVP_CIPHER *
evp_rijndael(void)
{
static EVP_CIPHER rijndal_cbc;
memset(&rijndal_cbc, 0, sizeof(EVP_CIPHER));
rijndal_cbc.nid = NID_undef;
rijndal_cbc.block_size = RIJNDAEL_BLOCKSIZE;
rijndal_cbc.iv_len = RIJNDAEL_BLOCKSIZE;
rijndal_cbc.key_len = 16;
rijndal_cbc.init = ssh_rijndael_init;
rijndal_cbc.cleanup = ssh_rijndael_cleanup;
rijndal_cbc.do_cipher = ssh_rijndael_cbc;
#ifndef SSH_OLD_EVP
rijndal_cbc.flags = EVP_CIPH_CBC_MODE | EVP_CIPH_VARIABLE_LENGTH |
EVP_CIPH_ALWAYS_CALL_INIT;
#endif
return (&rijndal_cbc);
}
#endif
/*
* Exports an IV from the CipherContext required to export the key
* state back from the unprivileged child to the privileged parent
* process.
*/
int
cipher_get_keyiv_len(CipherContext *cc)
{
Cipher *c = cc->cipher;
int ivlen;
if (c->number == SSH_CIPHER_3DES)
ivlen = 24;
else
ivlen = EVP_CIPHER_CTX_iv_length(&cc->evp);
return (ivlen);
}
void
cipher_get_keyiv(CipherContext *cc, u_char *iv, u_int len)
{
Cipher *c = cc->cipher;
u_char *civ = NULL;
int evplen;
switch (c->number) {
case SSH_CIPHER_SSH2:
case SSH_CIPHER_DES:
case SSH_CIPHER_BLOWFISH:
evplen = EVP_CIPHER_CTX_iv_length(&cc->evp);
if (evplen == 0)
return;
if (evplen != len)
fatal("%s: wrong iv length %d != %d", __func__,
evplen, len);
#if OPENSSL_VERSION_NUMBER < 0x00907000L
if (c->evptype == evp_rijndael) {
struct ssh_rijndael_ctx *aesc;
aesc = EVP_CIPHER_CTX_get_app_data(&cc->evp);
if (aesc == NULL)
fatal("%s: no rijndael context", __func__);
civ = aesc->r_iv;
} else
#endif
{
civ = cc->evp.iv;
}
break;
case SSH_CIPHER_3DES: {
struct ssh1_3des_ctx *desc;
if (len != 24)
fatal("%s: bad 3des iv length: %d", __func__, len);
desc = EVP_CIPHER_CTX_get_app_data(&cc->evp);
if (desc == NULL)
fatal("%s: no 3des context", __func__);
debug3("%s: Copying 3DES IV", __func__);
memcpy(iv, desc->k1.iv, 8);
memcpy(iv + 8, desc->k2.iv, 8);
memcpy(iv + 16, desc->k3.iv, 8);
return;
}
default:
fatal("%s: bad cipher %d", __func__, c->number);
}
memcpy(iv, civ, len);
}
void
cipher_set_keyiv(CipherContext *cc, u_char *iv)
{
Cipher *c = cc->cipher;
u_char *div = NULL;
int evplen = 0;
switch (c->number) {
case SSH_CIPHER_SSH2:
case SSH_CIPHER_DES:
case SSH_CIPHER_BLOWFISH:
evplen = EVP_CIPHER_CTX_iv_length(&cc->evp);
if (evplen == 0)
return;
#if OPENSSL_VERSION_NUMBER < 0x00907000L
if (c->evptype == evp_rijndael) {
struct ssh_rijndael_ctx *aesc;
aesc = EVP_CIPHER_CTX_get_app_data(&cc->evp);
if (aesc == NULL)
fatal("%s: no rijndael context", __func__);
div = aesc->r_iv;
} else
#endif
{
div = cc->evp.iv;
}
break;
case SSH_CIPHER_3DES: {
struct ssh1_3des_ctx *desc;
desc = EVP_CIPHER_CTX_get_app_data(&cc->evp);
if (desc == NULL)
fatal("%s: no 3des context", __func__);
debug3("%s: Installed 3DES IV", __func__);
memcpy(desc->k1.iv, iv, 8);
memcpy(desc->k2.iv, iv + 8, 8);
memcpy(desc->k3.iv, iv + 16, 8);
return;
}
default:
fatal("%s: bad cipher %d", __func__, c->number);
}
memcpy(div, iv, evplen);
}
#if OPENSSL_VERSION_NUMBER < 0x00907000L
#define EVP_X_STATE(evp) &(evp).c
#define EVP_X_STATE_LEN(evp) sizeof((evp).c)
#else
#define EVP_X_STATE(evp) (evp).cipher_data
#define EVP_X_STATE_LEN(evp) (evp).cipher->ctx_size
#endif
int
cipher_get_keycontext(CipherContext *cc, u_char *dat)
{
Cipher *c = cc->cipher;
int plen = 0;
if (c->evptype == EVP_rc4) {
plen = EVP_X_STATE_LEN(cc->evp);
if (dat == NULL)
return (plen);
memcpy(dat, EVP_X_STATE(cc->evp), plen);
}
return (plen);
}
void
cipher_set_keycontext(CipherContext *cc, u_char *dat)
{
Cipher *c = cc->cipher;
int plen;
if (c->evptype == EVP_rc4) {
plen = EVP_X_STATE_LEN(cc->evp);
memcpy(EVP_X_STATE(cc->evp), dat, plen);
}
}
| 24.84022 | 80 | 0.674559 | [
"vector"
] |
6db3baa79cb5db81d913ecbbe465bc02471664f2 | 997 | h | C | controller/Controller.h | djnick/SuffixTable | f20ba568129ff9108c6ce17172dc397379a3cffe | [
"MIT"
] | null | null | null | controller/Controller.h | djnick/SuffixTable | f20ba568129ff9108c6ce17172dc397379a3cffe | [
"MIT"
] | 14 | 2020-10-26T18:53:32.000Z | 2020-11-12T00:09:01.000Z | controller/Controller.h | djnick/SuffixTable | f20ba568129ff9108c6ce17172dc397379a3cffe | [
"MIT"
] | null | null | null | //
// Created by djnic on 09.11.2020.
//
#ifndef SUFFIXTABLE_CONTROLLER_H
#define SUFFIXTABLE_CONTROLLER_H
#include "../model/AlgorithmExecutor.h"
#include "../model/FileExecutor.h"
#include "../model/PatternExecutor.h"
#include "../view/View.h"
class Controller {
View *view = new View();
FileExecutor *fileExecutor = new FileExecutor();
AlgorithmExecutor *algorithmExecutor;
PatternExecutor *patternExecutor;
std::string pathToTextFile;
std::string pathToResultFile;
std::string pathToPatternFile;
public:
virtual ~Controller();
void runApp(int argc, char *argv[]);
void populateParameters();
bool generateResults();
void shutDownApp();
void setPathToTextFile(const std::string &pathToTextFile);
void setPathToResultFile(const std::string &pathToResultFile);
void setPathToPatternFile(const std::string &pathToPatternFile);
void setAlgorithmExecutor(const std::string algorithm);
};
#endif //SUFFIXTABLE_CONTROLLER_H
| 22.659091 | 68 | 0.729188 | [
"model"
] |
6dc906a87596d85d94601bd2e252e6dd0786d73e | 2,476 | h | C | media_capabilities/common.h | Toromino/chromiumos-platform2 | 97e6ba18f0e5ab6723f3448a66f82c1a07538d87 | [
"BSD-3-Clause"
] | null | null | null | media_capabilities/common.h | Toromino/chromiumos-platform2 | 97e6ba18f0e5ab6723f3448a66f82c1a07538d87 | [
"BSD-3-Clause"
] | null | null | null | media_capabilities/common.h | Toromino/chromiumos-platform2 | 97e6ba18f0e5ab6723f3448a66f82c1a07538d87 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2021 The Chromium OS 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 MEDIA_CAPABILITIES_COMMON_H_
#define MEDIA_CAPABILITIES_COMMON_H_
#include <string>
#include <utility>
#include <vector>
#include <base/files/file_path.h>
enum class CameraDescription : int32_t {
kNone = 0,
kBuiltinUSBCamera,
kBuiltinMIPICamera,
kVividCamera,
kBuiltinCamera,
kBuiltinOrVividCamera,
};
enum class Profile : int32_t {
kNone = 0,
// TODO(hiroh): Think about adding h264 constrained baseline.
kH264Baseline,
kH264Main,
kH264High,
kVP8,
kVP9Profile0,
kVP9Profile2,
kAV1Main,
// TODO(b/172229001): Add HEVC and HEVC10 profiles.
kJPEG,
};
enum class Resolution : int32_t {
kNone = 0,
k1080p, // 1920x1080
k2160p, // 3840x2160
};
enum class Subsampling : int32_t {
kNone = 0,
kYUV420,
kYUV422,
kYUV444,
};
enum class ColorDepth : int32_t {
kNone = 0,
k8bit,
k10bit,
};
// TODO(b/172229001): Add encryption enum.
class Capability {
public:
// For codec capability.
Capability(Profile profile,
bool decode,
Resolution resolution,
Subsampling subsampling,
ColorDepth color_depth);
// For camera capability.
explicit Capability(CameraDescription camera_description);
~Capability() = default;
Capability(const Capability&) = default;
Capability& operator=(const Capability&) = default;
bool operator<(const Capability& other) const;
bool operator==(const Capability& other) const;
bool operator!=(const Capability& other) const;
std::string ToString() const;
private:
CameraDescription camera_description_;
Profile profile_;
bool decode_;
Resolution resolution_;
Subsampling subsampling_;
ColorDepth color_depth_;
};
// Gets paths of all existing files (not directories) with the specified prefix,
// |absolute_path|. For instance, if "/dev/video" is given, /dev/video0 and
// /dev/video-dec0 are returned if they exist.
std::vector<base::FilePath> GetAllFilesWithPrefix(
const base::FilePath& absolute_path);
// Executes an ioctl() retrying in case of a signal interruption.
int Ioctl(int fd, uint32_t request, void* args);
// Gets all Resolutions that are less than or equal to |resolution|.
std::vector<Resolution> GetInterestingResolutionsUpTo(
const std::pair<int, int>& resolution);
#endif // MEDIA_CAPABILITIES_COMMON_H_
| 25.010101 | 80 | 0.724152 | [
"vector"
] |
6dd1e55c10db63a6e4fda2038143042297f73f54 | 3,068 | h | C | CalibCalorimetry/EcalLaserAnalyzer/plugins/EcalABAnalyzer.h | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | CalibCalorimetry/EcalLaserAnalyzer/plugins/EcalABAnalyzer.h | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | CalibCalorimetry/EcalLaserAnalyzer/plugins/EcalABAnalyzer.h | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | #ifndef EcalABAnalyzer_h_
#define EcalABAnalyzer_h_
// $Id: EcalABAnalyzer.h
#include <memory>
#include <vector>
#include <map>
#include <FWCore/Framework/interface/EDAnalyzer.h>
class TShapeAnalysis;
class TAPDPulse;
class TMom;
// Define geometrical constants
// NOT the same for "EB" and "EE"
//
// "EB" "EE"
//
// 0 0
// 1 2 1 2
// 3 4
// 5 6
// 7 8
//
//
// "EB" geometry
#define NCRYSEB 1700 // Number of crystals per EB supermodule
// "EE" geometry
#define NCRYSEE 830 // Number of crystals per EE supermodule
class EcalABAnalyzer: public edm::EDAnalyzer{
public:
explicit EcalABAnalyzer(const edm::ParameterSet& iConfig);
~EcalABAnalyzer();
virtual void analyze( const edm::Event & e, const edm::EventSetup& c);
virtual void beginJob();
virtual void endJob();
enum VarCol { iBlue, iRed, nColor };
private:
int iEvent;
// Framework parameters
unsigned int _nsamples;
unsigned int _presample;
unsigned int _firstsample;
unsigned int _lastsample;
unsigned int _timingcutlow;
unsigned int _timingcuthigh;
unsigned int _timingquallow;
unsigned int _timingqualhigh;
double _ratiomincutlow;
double _ratiomincuthigh;
double _ratiomaxcutlow;
double _presamplecut;
unsigned int _niter ;
double _alpha ;
double _beta;
unsigned int _nevtmax;
double _noise;
double _chi2cut;
std::string _ecalPart;
int _fedid;
double _qualpercent;
int _debug;
TAPDPulse *APDPulse;
TMom *Delta01;
TMom *Delta12;
std::string resdir_;
std::string digiCollection_;
std::string digiProducer_;
std::string eventHeaderCollection_;
std::string eventHeaderProducer_;
// Output file names
std::string alphafile;
std::string alphainitfile;
TShapeAnalysis *shapana;
unsigned int nevtAB[NCRYSEB];
// Define geometrical constants
// Default values correspond to "EB" geometry (1700 crystals)
unsigned int nCrys;
bool doesABTreeExist;
bool _fitab;
// Identify run type
int runType;
int runNum;
int fedID;
int dccID;
int side;
int lightside;
int iZ;
// Temporary root files and trees
std::vector<int> colors;
std::map<int, int> channelMapEE;
std::vector<int> dccMEM;
std::vector<int> modules;
// Declaration of leaves types for temporary trees
int phi, eta;
int event ;
int color ;
double adc[10];
int adcG[10];
int channelIteratorEE;
int iEta[NCRYSEB],iPhi[NCRYSEB];
int iTowerID[NCRYSEB],iChannelID[NCRYSEB], idccID[NCRYSEB], iside[NCRYSEB];
// Quality Checks variables and flags
int nEvtBadGain[NCRYSEB];
int nEvtBadTiming[NCRYSEB];
int nEvtTot[NCRYSEB];
bool wasGainOK[NCRYSEB];
bool wasTimingOK[NCRYSEB];
bool isGainOK;
bool isTimingOK;
};
#endif
| 19.922078 | 77 | 0.631356 | [
"geometry",
"vector"
] |
6dd8866ad64c530170a8096d0501e4b0b3c3724f | 10,409 | c | C | packages/PIPS/pips/src/Libs/janusvalue/sc_janus_feasibility.c | DVSR1966/par4all | 86b33ca9da736e832b568c5637a2381f360f1996 | [
"MIT"
] | 51 | 2015-01-31T01:51:39.000Z | 2022-02-18T02:01:50.000Z | packages/PIPS/pips/src/Libs/janusvalue/sc_janus_feasibility.c | DVSR1966/par4all | 86b33ca9da736e832b568c5637a2381f360f1996 | [
"MIT"
] | 7 | 2017-05-29T09:29:00.000Z | 2019-03-11T16:01:39.000Z | packages/PIPS/pips/src/Libs/janusvalue/sc_janus_feasibility.c | DVSR1966/par4all | 86b33ca9da736e832b568c5637a2381f360f1996 | [
"MIT"
] | 12 | 2015-03-26T08:05:38.000Z | 2022-02-18T02:01:51.000Z | /*
$Id: sc_janus_feasibility.c 1539 2012-05-31 07:27:03Z maisonneuve $
Copyright 1989-2014 MINES ParisTech
This file is part of PIPS.
PIPS is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
PIPS 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 PIPS. If not, see <http://www.gnu.org/licenses/>.
*/
/* This file provides functions to convert a system
* of constraints into format of Janus.
*/
#ifdef HAVE_CONFIG_H
#include "pips_config.h"
#endif
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "linear.h"
#include "janusvalue.h"
/*sc must be consistant*/
static bool
sc_to_iproblem(Psysteme sc, Pinitpb I, Pproblem Z, FILE *fdebug)
{
Pcontrainte peq;
Pvecteur pv;
Value temp;
bool special_constraint_p = false;
/*Janus
int p6,p5,p4,p3,p2,p1;*/
int vi0,targ,pr,nblevel,mtlevel,tas;
int i,j,choix,vision,methode;
int par1,par2,par3,par4,par5,par6,par7;
/* int tfois = 1; for time measurement only. other initiation removed.*/
/* prefixed parameter for Janus - to be changed in futur */
tas=0; pr=0;
par1 = 0; par2 = 0; par3 = 0;
par4 = 0; /* no debug mode*/
par5 = 0; par6 = 1; par7 = 1;
/*have to remove this debug in the futur for exact time measument*/
if (par4) {
fdebug=fopen("jtrace.tex","w") ; /* file for trace */
}else {
fdebug = NULL;
}
Z->ftrace=fdebug;
/**************** BEGIN parameters into structure ************************/
Z->turbo=0; Z->remove=1;
mtlevel = par1; /* technique for hierarchical computation - 0 if simplex */
nblevel = par2; /* number of levels - 0 if simplex */
methode = par3; Z->met8 = methode/10000000;
methode -= 10000000*Z->met8;Z->met7 = methode/1000000;
methode -= 1000000*Z->met7; Z->met6 = methode/100000;
methode -= 100000*Z->met6; Z->met5 = methode/10000;
methode -= 10000*Z->met5; Z->met4 = methode/1000;
methode -= 1000*Z->met4; Z->met3 = methode/100;
methode -= 100*Z->met3; Z->met2 = methode/10;
methode -= 10*Z->met2; Z->meth = methode;
vision = par4; Z->dyn = vision/1000; /* dynamic visualization*/
vision -= 1000*Z->dyn; Z->ntrac3 = vision/100; /* amount of information */
vision -= 100*Z->ntrac3; Z->ntrac2 = vision/10; /* amount of information */
Z->ntrace = vision-10*Z->ntrac2; /* amount of information */
Z->fourier = par5; /* Fourier_Motzkin */
targ = par6; Z->forcer= targ/10;
targ -= 10*Z->forcer; Z->varc= targ; /*How to introduce constrained variables*/
choix = par7; Z->critermax = choix/100; /*Criterion max iterations*/
choix -= 100*Z->critermax; Z->choixprim = choix/10; /* Choice pivot primal */
Z->choixpiv = choix-10*Z->choixprim; /* Choice of the pivot for dual simplex */
/**************** END parameters into structure ************************/
/**************** BEGIN print debug into structure ************************/
if (Z->dyn) dynam(Z,0);
if (Z->ntrace||Z->ntrac2)
{fprintf(Z->ftrace,"\\documentstyle[fullpage,epic,eepic,fancybox]{article} \n");
fprintf(Z->ftrace,"\\begin{document}\n");
tableau_janus(I,Z);
}
/**************** END print debug into structure ************************/
/**************** BEGIN reset some parameters in the structures ************************/
Z->negal=0;Z->icout=0;Z->minimum=0;Z->mx=0;Z->nx=0;Z->ic1=0;Z->tmax=0;Z->niter=0;Z->itdirect=0;Z->nredun=0;Z->numero=0;Z->numax=0; Z->lastfree=0;Z->nub= 0;Z->ntp = 0;Z->vdum = 0;Z->nturb = 0;
/*
for ( i=1;i<=MAXLIGNES+1; i++) {
for (j=1; j<=MAXCOLONNES+1; j++)
value_assign(I->a[i][j],VALUE_ZERO);
}
for ( i=1 ; i <= MAXLIGNES +1 ; i++) {
value_assign(I->d[i],VALUE_ZERO);
}
for ( i=1 ; i <= MAXLIGNES +1 ; i++) {
I->e[i]=0;
}
for ( i=1;i<=AKLIGNES; i++) {
for (j=1; j<=AKCOLONNES; j++)
value_assign(Z->ak[i][j],VALUE_ZERO);
}
for ( i=1 ; i <= AKLIGNES ; i++) {
value_assign(Z->dk[i],VALUE_ZERO);
}
*/
/*TODO: If these parameters are already initialized before used in the code (which is not easy to see now),
then it's not necessary to reinitialize them here. If not, then we might have a bug.*/
/**************** END reset some parameters in the structures ************************/
/**************** BEGIN to insert DIMENSION with tests into structure *************/
/* removed reading from file. replace by direct assign*/
/* we can chosse probleme janus ou simplexe entier classique or other in this section*/
/*fscanf(fh,"%d",&Z->nvar); nombre total de variables */
Z->nvar = sc->dimension; /* to be verified */
if (Z->nvar < 0) { /*sc given is not correct (normally tested before)*/
ifscdebug(5) {
printf("\n[sc_to_iproblem]: Janus has a number of variables < 0 ");
}
return false;/* Janus cannot handle this system of constraints*/
}
if (Z->nvar> MAXCOLONNES) {
ifscdebug(5) {
printf("\n[sc_to_iproblem]: Too many variables %3d > max=%3d\n",Z->nvar,MAXCOLONNES);
}
return false;/* Janus cannot handle this system of constraints*/
}
/*fscanf(fh,"%d",&Z->mcontr); nombre de contraintes */
Z->mcontr = sc->nb_eq + sc->nb_ineq; /* sc's parameters must be true*/
if (Z->mcontr> MAXLIGNES) {
ifscdebug(5) {
printf("\n[sc_to_iproblem]: Too many constraints %3d > max = %3d \n",Z->mcontr,MAXLIGNES);
}
return false;/* Janus cannot handle this system of constraints*/
}
/*fscanf(fh,"%d",&Z->nvpos); nombre de variables >=0 donc: Z->nvpos<= Z->nvar */
Z->nvpos = 0; /* to be verified */
if (Z->nvpos > Z->nvar) {
ifscdebug(5) {
printf("\n[sc_to_iproblem]: %3d variables positives, greater than %3d\n",Z->nvpos,Z->nvar);
}
return false;/* ?? can we put nvpos = 0 here */
}
/*fscanf(fh,"%d",&vi0); unused parameter */
vi0 = 0;
/**************** END to insert DIMENSION into structure ********************/
/**************** BEGIN to insert MATRIX into structure*********************/
/* need exact DIMENSION, similar to sc_to_matrix*/
/* for ( i=1 ; i <= Z->mcontr ; i++)
{ fscanf(fh,"%d",&ventier) ; I->e[i]=ventier ;
for ( j=1 ; j <= Z->nvar ; j++)
{ fscanf(fh,"%d",&ventier) ; I->a[i][j]=ventier ;
}
fscanf(fh,"%d",&ventier) ; I->d[i]=ventier ;
}
*/
/*ATTENTION, first elements in array in struct initpb are not used. */
/*this array is not initiated. In use : rows 1 -> Z->mcontr, columns 1-> Z->nvar*/
/*DN: need to check the special inequality here: 0 < 1, mean a vector of one element.*/
for ( i=1 ; i <= Z->mcontr ; i++) /* differentiation eq and ineq, running by constraints*/
{
/*if egalite then 0, inegalite then -1. Put in egalites first*/
if (i<=sc->nb_eq) I->e[i]= 0;
else I->e[i]= -1;
}
/*included constant (or rhs) here, which is the last element in the vector, donot change the sign of constant
DN 6/11/02. use Marcos of Value. Needed Value in struct problem.*/
/*egalites coeffs, i for columns, j for rows*/
for (peq = sc->egalites, i = 1; !CONTRAINTE_UNDEFINED_P(peq); peq=peq->succ, i++)
{
for (pv=sc->base,j=1; !VECTEUR_NUL_P(pv); pv=pv->succ,j++)
{
value_assign(I->a[i][j],value_uminus(vect_coeff(vecteur_var(pv),peq->vecteur)));
}
value_assign(I->d[i],vect_coeff(TCST,peq->vecteur));
}
/*inegalites*/
for (peq = sc->inegalites; !CONTRAINTE_UNDEFINED_P(peq); peq=peq->succ, i++)
{
value_assign(temp,VALUE_ZERO);
for (pv=sc->base,j=1; !VECTEUR_NUL_P(pv); pv=pv->succ,j++)
{
value_assign( I->a[i][j],value_uminus(vect_coeff(vecteur_var(pv),peq->vecteur)));
value_addto(temp,value_abs(I->a[i][j]));
}
if value_zero_p(temp) {
special_constraint_p = true;
}
value_assign(I->d[i],vect_coeff(TCST,peq->vecteur));
}
if (special_constraint_p) {
/*sc_default_dump(sc);
TODO: what to do with this special constraint? if 0<1 ok, if 1 < 0 then not ok, return false */
}
/**************** END to insert MATRIX into structure *********************/
return true;
}
bool
sc_janus_feasibility(Psysteme sc)
{
FILE *fopen(), *fdebug;
initpb I;
problem Z;
bool ok = false;
int r = 0;
/**************** change format into Janus, using global struct iproblem */
ok = sc_to_iproblem(sc,&I,&Z,fdebug); /*Attention with dimension=0*/
/**************** BEGIN execution simplexe entier classique */
if (ok) r = isolve(&I,&Z,0);
else r = 9;/*DN janus should not be used here.*/
/* the third parameter means test only one time
only I is initialized. Z is still empty */
/*
if (r==VRFIN) printf("solution finie\n") ;
else if (r==VRVID) printf("polyedre vide\n") ;
else if (r==VRINF) printf("solution infinie\n") ;
else if (r==VRINS) printf("nombre insuffisant\n") ;
else if (r==VRDEB) printf("debordement tableaux\n") ;
else if (r==VRCAL) printf("some wrong parameter\n") ;
else if (r==VRBUG) printf("bug de programmation\n") ;
else if (r==VROVF) printf("data overflow\n") ;
else if (r==VREPS) printf("pivot anormalement petit\n") ;
*/
/* #define VRFIN 0 solution finie */
/* #define VRVID 1 polyedre vide */
/* #define VRINF 2 solution infinie */
/* #define VRINS 3 nombre de pivotages insuffisant, bouclage possible */
/* #define VRDEB 4 debordement de tableaux */
/* #define VRCAL 5 appel errone */
/* #define VRBUG 6 bug */
/* #define VROVF 7 overflow */
/***************** END execution simplexe entier classique */
if (Z.ntrace||Z.ntrac2)
{ fprintf(Z.ftrace,"\\end{document}\n");
}
if (fdebug) fclose(fdebug);/* DN: In Solaris, we can fclose(NULL), but in LINUX, we cannot.*/
if (r==VRFIN) {ok = true; return ok;}
else if ((r==VRVID)||(r==VRINF)) {ok = false;return ok;}
else return r; /* in case of failure then return r >=3
donnot want to use exception here, nor one more parameter,
while wanting to keep return bool for compatibility. To be changed.*/
}
| 36.780919 | 193 | 0.607839 | [
"vector",
"3d"
] |
6ddae920d68d2b27541543b0d1aa32215349eb6f | 60,526 | h | C | src/xenia/cpu/frontend/ppc_instr_tables.h | Parovozik/Xenia_UI | 3f12becc1845a8fc264ae74d25e28e543f61b5b4 | [
"BSD-3-Clause"
] | null | null | null | src/xenia/cpu/frontend/ppc_instr_tables.h | Parovozik/Xenia_UI | 3f12becc1845a8fc264ae74d25e28e543f61b5b4 | [
"BSD-3-Clause"
] | null | null | null | src/xenia/cpu/frontend/ppc_instr_tables.h | Parovozik/Xenia_UI | 3f12becc1845a8fc264ae74d25e28e543f61b5b4 | [
"BSD-3-Clause"
] | 1 | 2018-10-16T16:45:27.000Z | 2018-10-16T16:45:27.000Z | /**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2013 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#ifndef XENIA_FRONTEND_PPC_INSTR_TABLES_H_
#define XENIA_FRONTEND_PPC_INSTR_TABLES_H_
#include <cmath>
#include "xenia/base/math.h"
#include "xenia/base/string_buffer.h"
#include "xenia/cpu/frontend/ppc_instr.h"
namespace xe {
namespace cpu {
namespace frontend {
void Disasm_0(InstrData& i, StringBuffer* str);
void Disasm__(InstrData& i, StringBuffer* str);
void Disasm_X_FRT_FRB(InstrData& i, StringBuffer* str);
void Disasm_A_FRT_FRB(InstrData& i, StringBuffer* str);
void Disasm_A_FRT_FRA_FRB(InstrData& i, StringBuffer* str);
void Disasm_A_FRT_FRA_FRB_FRC(InstrData& i, StringBuffer* str);
void Disasm_X_RT_RA_RB(InstrData& i, StringBuffer* str);
void Disasm_X_RT_RA0_RB(InstrData& i, StringBuffer* str);
void Disasm_X_FRT_RA_RB(InstrData& i, StringBuffer* str);
void Disasm_X_FRT_RA0_RB(InstrData& i, StringBuffer* str);
void Disasm_D_RT_RA_I(InstrData& i, StringBuffer* str);
void Disasm_D_RT_RA0_I(InstrData& i, StringBuffer* str);
void Disasm_D_FRT_RA_I(InstrData& i, StringBuffer* str);
void Disasm_D_FRT_RA0_I(InstrData& i, StringBuffer* str);
void Disasm_DS_RT_RA_I(InstrData& i, StringBuffer* str);
void Disasm_DS_RT_RA0_I(InstrData& i, StringBuffer* str);
void Disasm_D_RA(InstrData& i, StringBuffer* str);
void Disasm_X_RA_RB(InstrData& i, StringBuffer* str);
void Disasm_XO_RT_RA_RB(InstrData& i, StringBuffer* str);
void Disasm_XO_RT_RA(InstrData& i, StringBuffer* str);
void Disasm_X_RA_RT_RB(InstrData& i, StringBuffer* str);
void Disasm_D_RA_RT_I(InstrData& i, StringBuffer* str);
void Disasm_X_RA_RT(InstrData& i, StringBuffer* str);
void Disasm_X_VX_RA0_RB(InstrData& i, StringBuffer* str);
void Disasm_VX1281_VD_RA0_RB(InstrData& i, StringBuffer* str);
void Disasm_VX1283_VD_VB(InstrData& i, StringBuffer* str);
void Disasm_VX1283_VD_VB_I(InstrData& i, StringBuffer* str);
void Disasm_VX_VD_VA_VB(InstrData& i, StringBuffer* str);
void Disasm_VX128_VD_VA_VB(InstrData& i, StringBuffer* str);
void Disasm_VX128_VD_VA_VD_VB(InstrData& i, StringBuffer* str);
void Disasm_VX1282_VD_VA_VB_VC(InstrData& i, StringBuffer* str);
void Disasm_VXA_VD_VA_VB_VC(InstrData& i, StringBuffer* str);
void Disasm_sync(InstrData& i, StringBuffer* str);
void Disasm_dcbf(InstrData& i, StringBuffer* str);
void Disasm_dcbz(InstrData& i, StringBuffer* str);
void Disasm_fcmp(InstrData& i, StringBuffer* str);
void Disasm_bx(InstrData& i, StringBuffer* str);
void Disasm_bcx(InstrData& i, StringBuffer* str);
void Disasm_bcctrx(InstrData& i, StringBuffer* str);
void Disasm_bclrx(InstrData& i, StringBuffer* str);
void Disasm_mfcr(InstrData& i, StringBuffer* str);
void Disasm_mfspr(InstrData& i, StringBuffer* str);
void Disasm_mtspr(InstrData& i, StringBuffer* str);
void Disasm_mftb(InstrData& i, StringBuffer* str);
void Disasm_mfmsr(InstrData& i, StringBuffer* str);
void Disasm_mtmsr(InstrData& i, StringBuffer* str);
void Disasm_cmp(InstrData& i, StringBuffer* str);
void Disasm_cmpi(InstrData& i, StringBuffer* str);
void Disasm_cmpli(InstrData& i, StringBuffer* str);
void Disasm_rld(InstrData& i, StringBuffer* str);
void Disasm_rlwim(InstrData& i, StringBuffer* str);
void Disasm_rlwnmx(InstrData& i, StringBuffer* str);
void Disasm_srawix(InstrData& i, StringBuffer* str);
void Disasm_sradix(InstrData& i, StringBuffer* str);
void Disasm_vpermwi128(InstrData& i, StringBuffer* str);
void Disasm_vrfin128(InstrData& i, StringBuffer* str);
void Disasm_vrlimi128(InstrData& i, StringBuffer* str);
void Disasm_vsldoi128(InstrData& i, StringBuffer* str);
void Disasm_vspltb(InstrData& i, StringBuffer* str);
void Disasm_vsplth(InstrData& i, StringBuffer* str);
void Disasm_vspltw(InstrData& i, StringBuffer* str);
void Disasm_vspltisb(InstrData& i, StringBuffer* str);
void Disasm_vspltish(InstrData& i, StringBuffer* str);
void Disasm_vspltisw(InstrData& i, StringBuffer* str);
namespace tables {
static InstrType** instr_table_prep(InstrType* unprep, size_t unprep_count,
int a, int b) {
int prep_count = (int)pow(2.0, b - a + 1);
InstrType** prep = (InstrType**)calloc(prep_count, sizeof(void*));
for (int n = 0; n < unprep_count; n++) {
int ordinal = select_bits(unprep[n].opcode, a, b);
prep[ordinal] = &unprep[n];
}
return prep;
}
static InstrType** instr_table_prep_63(InstrType* unprep, size_t unprep_count,
int a, int b) {
// Special handling for A format instructions.
int prep_count = (int)pow(2.0, b - a + 1);
InstrType** prep = (InstrType**)calloc(prep_count, sizeof(void*));
for (int n = 0; n < unprep_count; n++) {
int ordinal = select_bits(unprep[n].opcode, a, b);
if (unprep[n].format == kXEPPCInstrFormatA) {
// Must splat this into all of the slots that it could be in.
for (int m = 0; m < 32; m++) {
prep[ordinal + (m << 5)] = &unprep[n];
}
} else {
prep[ordinal] = &unprep[n];
}
}
return prep;
}
#define EMPTY(slot) \
{ 0 }
#define INSTRUCTION(name, opcode, format, type, disasm_fn, descr) \
{ \
opcode, 0, kXEPPCInstrFormat##format, kXEPPCInstrType##type, 0, \
Disasm_##disasm_fn, #name, 0, \
}
#define FLAG(t) kXEPPCInstrFlag##t
// This table set is constructed from:
// pem_64bit_v3.0.2005jul15.pdf, A.2
// PowerISA_V2.06B_V2_PUBLIC.pdf
// Opcode = 4, index = bits 11-0 (6)
static InstrType instr_table_4_unprep[] = {
// TODO: all of the vector ops
INSTRUCTION(mfvscr, 0x10000604, VX, General, 0,
"Move from Vector Status and Control Register"),
INSTRUCTION(mtvscr, 0x10000644, VX, General, 0,
"Move to Vector Status and Control Register"),
INSTRUCTION(vaddcuw, 0x10000180, VX, General, 0,
"Vector Add Carryout Unsigned Word"),
INSTRUCTION(vaddfp, 0x1000000A, VX, General, VX_VD_VA_VB,
"Vector Add Floating Point"),
INSTRUCTION(vaddsbs, 0x10000300, VX, General, 0,
"Vector Add Signed Byte Saturate"),
INSTRUCTION(vaddshs, 0x10000340, VX, General, 0,
"Vector Add Signed Half Word Saturate"),
INSTRUCTION(vaddsws, 0x10000380, VX, General, 0,
"Vector Add Signed Word Saturate"),
INSTRUCTION(vaddubm, 0x10000000, VX, General, 0,
"Vector Add Unsigned Byte Modulo"),
INSTRUCTION(vaddubs, 0x10000200, VX, General, 0,
"Vector Add Unsigned Byte Saturate"),
INSTRUCTION(vadduhm, 0x10000040, VX, General, 0,
"Vector Add Unsigned Half Word Modulo"),
INSTRUCTION(vadduhs, 0x10000240, VX, General, 0,
"Vector Add Unsigned Half Word Saturate"),
INSTRUCTION(vadduwm, 0x10000080, VX, General, 0,
"Vector Add Unsigned Word Modulo"),
INSTRUCTION(vadduws, 0x10000280, VX, General, 0,
"Vector Add Unsigned Word Saturate"),
INSTRUCTION(vand, 0x10000404, VX, General, VX_VD_VA_VB,
"Vector Logical AND"),
INSTRUCTION(vandc, 0x10000444, VX, General, VX_VD_VA_VB,
"Vector Logical AND with Complement"),
INSTRUCTION(vavgsb, 0x10000502, VX, General, 0,
"Vector Average Signed Byte"),
INSTRUCTION(vavgsh, 0x10000542, VX, General, 0,
"Vector Average Signed Half Word"),
INSTRUCTION(vavgsw, 0x10000582, VX, General, 0,
"Vector Average Signed Word"),
INSTRUCTION(vavgub, 0x10000402, VX, General, 0,
"Vector Average Unsigned Byte"),
INSTRUCTION(vavguh, 0x10000442, VX, General, 0,
"Vector Average Unsigned Half Word"),
INSTRUCTION(vavguw, 0x10000482, VX, General, 0,
"Vector Average Unsigned Word"),
INSTRUCTION(vcfsx, 0x1000034A, VX, General, 0,
"Vector Convert from Signed Fixed-Point Word"),
INSTRUCTION(vcfux, 0x1000030A, VX, General, 0,
"Vector Convert from Unsigned Fixed-Point Word"),
INSTRUCTION(vctsxs, 0x100003CA, VX, General, 0,
"Vector Convert to Signed Fixed-Point Word Saturate"),
INSTRUCTION(vctuxs, 0x1000038A, VX, General, 0,
"Vector Convert to Unsigned Fixed-Point Word Saturate"),
INSTRUCTION(vexptefp, 0x1000018A, VX, General, 0,
"Vector 2 Raised to the Exponent Estimate Floating Point"),
INSTRUCTION(vlogefp, 0x100001CA, VX, General, 0,
"Vector Log2 Estimate Floating Point"),
INSTRUCTION(vmaxfp, 0x1000040A, VX, General, 0,
"Vector Maximum Floating Point"),
INSTRUCTION(vmaxsb, 0x10000102, VX, General, 0,
"Vector Maximum Signed Byte"),
INSTRUCTION(vmaxsh, 0x10000142, VX, General, 0,
"Vector Maximum Signed Half Word"),
INSTRUCTION(vmaxsw, 0x10000182, VX, General, 0,
"Vector Maximum Signed Word"),
INSTRUCTION(vmaxub, 0x10000002, VX, General, 0,
"Vector Maximum Unsigned Byte"),
INSTRUCTION(vmaxuh, 0x10000042, VX, General, 0,
"Vector Maximum Unsigned Half Word"),
INSTRUCTION(vmaxuw, 0x10000082, VX, General, 0,
"Vector Maximum Unsigned Word"),
INSTRUCTION(vminfp, 0x1000044A, VX, General, 0,
"Vector Minimum Floating Point"),
INSTRUCTION(vminsb, 0x10000302, VX, General, 0,
"Vector Minimum Signed Byte"),
INSTRUCTION(vminsh, 0x10000342, VX, General, 0,
"Vector Minimum Signed Half Word"),
INSTRUCTION(vminsw, 0x10000382, VX, General, 0,
"Vector Minimum Signed Word"),
INSTRUCTION(vminub, 0x10000202, VX, General, 0,
"Vector Minimum Unsigned Byte"),
INSTRUCTION(vminuh, 0x10000242, VX, General, 0,
"Vector Minimum Unsigned Half Word"),
INSTRUCTION(vminuw, 0x10000282, VX, General, 0,
"Vector Minimum Unsigned Word"),
INSTRUCTION(vmrghb, 0x1000000C, VX, General, 0, "Vector Merge High Byte"),
INSTRUCTION(vmrghh, 0x1000004C, VX, General, 0,
"Vector Merge High Half Word"),
INSTRUCTION(vmrghw, 0x1000008C, VX, General, 0, "Vector Merge High Word"),
INSTRUCTION(vmrglb, 0x1000010C, VX, General, 0, "Vector Merge Low Byte"),
INSTRUCTION(vmrglh, 0x1000014C, VX, General, 0,
"Vector Merge Low Half Word"),
INSTRUCTION(vmrglw, 0x1000018C, VX, General, 0, "Vector Merge Low Word"),
INSTRUCTION(vmulesb, 0x10000308, VX, General, 0,
"Vector Multiply Even Signed Byte"),
INSTRUCTION(vmulesh, 0x10000348, VX, General, 0,
"Vector Multiply Even Signed Half Word"),
INSTRUCTION(vmuleub, 0x10000208, VX, General, 0,
"Vector Multiply Even Unsigned Byte"),
INSTRUCTION(vmuleuh, 0x10000248, VX, General, 0,
"Vector Multiply Even Unsigned Half Word"),
INSTRUCTION(vmulosb, 0x10000108, VX, General, 0,
"Vector Multiply Odd Signed Byte"),
INSTRUCTION(vmulosh, 0x10000148, VX, General, 0,
"Vector Multiply Odd Signed Half Word"),
INSTRUCTION(vmuloub, 0x10000008, VX, General, 0,
"Vector Multiply Odd Unsigned Byte"),
INSTRUCTION(vmulouh, 0x10000048, VX, General, 0,
"Vector Multiply Odd Unsigned Half Word"),
INSTRUCTION(vnor, 0x10000504, VX, General, VX_VD_VA_VB,
"Vector Logical NOR"),
INSTRUCTION(vor, 0x10000484, VX, General, VX_VD_VA_VB, "Vector Logical OR"),
INSTRUCTION(vpkpx, 0x1000030E, VX, General, 0, "Vector Pack Pixel"),
INSTRUCTION(vpkshss, 0x1000018E, VX, General, 0,
"Vector Pack Signed Half Word Signed Saturate"),
INSTRUCTION(vpkshus, 0x1000010E, VX, General, 0,
"Vector Pack Signed Half Word Unsigned Saturate"),
INSTRUCTION(vpkswss, 0x100001CE, VX, General, 0,
"Vector Pack Signed Word Signed Saturate"),
INSTRUCTION(vpkswus, 0x1000014E, VX, General, 0,
"Vector Pack Signed Word Unsigned Saturate"),
INSTRUCTION(vpkuhum, 0x1000000E, VX, General, 0,
"Vector Pack Unsigned Half Word Unsigned Modulo"),
INSTRUCTION(vpkuhus, 0x1000008E, VX, General, 0,
"Vector Pack Unsigned Half Word Unsigned Saturate"),
INSTRUCTION(vpkuwum, 0x1000004E, VX, General, 0,
"Vector Pack Unsigned Word Unsigned Modulo"),
INSTRUCTION(vpkuwus, 0x100000CE, VX, General, 0,
"Vector Pack Unsigned Word Unsigned Saturate"),
INSTRUCTION(vrefp, 0x1000010A, VX, General, 0,
"Vector Reciprocal Estimate Floating Point"),
INSTRUCTION(vrfim, 0x100002CA, VX, General, 0,
"Vector Round to Floating-Point Integer toward -Infinity"),
INSTRUCTION(vrfin, 0x1000020A, VX, General, 0,
"Vector Round to Floating-Point Integer Nearest"),
INSTRUCTION(vrfip, 0x1000028A, VX, General, 0,
"Vector Round to Floating-Point Integer toward +Infinity"),
INSTRUCTION(vrfiz, 0x1000024A, VX, General, 0,
"Vector Round to Floating-Point Integer toward Zero"),
INSTRUCTION(vrlb, 0x10000004, VX, General, 0,
"Vector Rotate Left Integer Byte"),
INSTRUCTION(vrlh, 0x10000044, VX, General, 0,
"Vector Rotate Left Integer Half Word"),
INSTRUCTION(vrlw, 0x10000084, VX, General, 0,
"Vector Rotate Left Integer Word"),
INSTRUCTION(vrsqrtefp, 0x1000014A, VX, General, 0,
"Vector Reciprocal Square Root Estimate Floating Point"),
INSTRUCTION(vsl, 0x100001C4, VX, General, 0, "Vector Shift Left"),
INSTRUCTION(vslb, 0x10000104, VX, General, VX_VD_VA_VB,
"Vector Shift Left Integer Byte"),
INSTRUCTION(vslh, 0x10000144, VX, General, 0,
"Vector Shift Left Integer Half Word"),
INSTRUCTION(vslo, 0x1000040C, VX, General, 0, "Vector Shift Left by Octet"),
INSTRUCTION(vslw, 0x10000184, VX, General, 0,
"Vector Shift Left Integer Word"),
INSTRUCTION(vspltb, 0x1000020C, VX, General, vspltb, "Vector Splat Byte"),
INSTRUCTION(vsplth, 0x1000024C, VX, General, vsplth,
"Vector Splat Half Word"),
INSTRUCTION(vspltisb, 0x1000030C, VX, General, vspltisb,
"Vector Splat Immediate Signed Byte"),
INSTRUCTION(vspltish, 0x1000034C, VX, General, vspltish,
"Vector Splat Immediate Signed Half Word"),
INSTRUCTION(vspltisw, 0x1000038C, VX, General, vspltisw,
"Vector Splat Immediate Signed Word"),
INSTRUCTION(vspltw, 0x1000028C, VX, General, vspltw, "Vector Splat Word"),
INSTRUCTION(vsr, 0x100002C4, VX, General, VX_VD_VA_VB,
"Vector Shift Right"),
INSTRUCTION(vsrab, 0x10000304, VX, General, VX_VD_VA_VB,
"Vector Shift Right Algebraic Byte"),
INSTRUCTION(vsrah, 0x10000344, VX, General, VX_VD_VA_VB,
"Vector Shift Right Algebraic Half Word"),
INSTRUCTION(vsraw, 0x10000384, VX, General, VX_VD_VA_VB,
"Vector Shift Right Algebraic Word"),
INSTRUCTION(vsrb, 0x10000204, VX, General, VX_VD_VA_VB,
"Vector Shift Right Byte"),
INSTRUCTION(vsrh, 0x10000244, VX, General, VX_VD_VA_VB,
"Vector Shift Right Half Word"),
INSTRUCTION(vsro, 0x1000044C, VX, General, VX_VD_VA_VB,
"Vector Shift Right Octet"),
INSTRUCTION(vsrw, 0x10000284, VX, General, VX_VD_VA_VB,
"Vector Shift Right Word"),
INSTRUCTION(vsubcuw, 0x10000580, VX, General, 0,
"Vector Subtract Carryout Unsigned Word"),
INSTRUCTION(vsubfp, 0x1000004A, VX, General, 0,
"Vector Subtract Floating Point"),
INSTRUCTION(vsubsbs, 0x10000700, VX, General, 0,
"Vector Subtract Signed Byte Saturate"),
INSTRUCTION(vsubshs, 0x10000740, VX, General, 0,
"Vector Subtract Signed Half Word Saturate"),
INSTRUCTION(vsubsws, 0x10000780, VX, General, 0,
"Vector Subtract Signed Word Saturate"),
INSTRUCTION(vsububm, 0x10000400, VX, General, 0,
"Vector Subtract Unsigned Byte Modulo"),
INSTRUCTION(vsububs, 0x10000600, VX, General, 0,
"Vector Subtract Unsigned Byte Saturate"),
INSTRUCTION(vsubuhm, 0x10000440, VX, General, 0,
"Vector Subtract Unsigned Half Word Modulo"),
INSTRUCTION(vsubuhs, 0x10000640, VX, General, 0,
"Vector Subtract Unsigned Half Word Saturate"),
INSTRUCTION(vsubuwm, 0x10000480, VX, General, 0,
"Vector Subtract Unsigned Word Modulo"),
INSTRUCTION(vsubuws, 0x10000680, VX, General, 0,
"Vector Subtract Unsigned Word Saturate"),
INSTRUCTION(vsumsws, 0x10000788, VX, General, 0,
"Vector Sum Across Signed Word Saturate"),
INSTRUCTION(vsum2sws, 0x10000688, VX, General, 0,
"Vector Sum Across Partial (1/2) Signed Word Saturate"),
INSTRUCTION(vsum4sbs, 0x10000708, VX, General, 0,
"Vector Sum Across Partial (1/4) Signed Byte Saturate"),
INSTRUCTION(vsum4shs, 0x10000648, VX, General, 0,
"Vector Sum Across Partial (1/4) Signed Half Word Saturate"),
INSTRUCTION(vsum4ubs, 0x10000608, VX, General, 0,
"Vector Sum Across Partial (1/4) Unsigned Byte Saturate"),
INSTRUCTION(vupkhpx, 0x1000034E, VX, General, 0,
"Vector Unpack High Pixel"),
INSTRUCTION(vupkhsb, 0x1000020E, VX, General, 0,
"Vector Unpack High Signed Byte"),
INSTRUCTION(vupkhsh, 0x1000024E, VX, General, 0,
"Vector Unpack High Signed Half Word"),
INSTRUCTION(vupklpx, 0x100003CE, VX, General, 0, "Vector Unpack Low Pixel"),
INSTRUCTION(vupklsb, 0x1000028E, VX, General, 0,
"Vector Unpack Low Signed Byte"),
INSTRUCTION(vupklsh, 0x100002CE, VX, General, 0,
"Vector Unpack Low Signed Half Word"),
INSTRUCTION(vxor, 0x100004C4, VX, General, VX_VD_VA_VB,
"Vector Logical XOR"),
};
static InstrType** instr_table_4 = instr_table_prep(
instr_table_4_unprep, xe::countof(instr_table_4_unprep), 0, 11);
// Opcode = 19, index = bits 10-1 (10)
static InstrType instr_table_19_unprep[] = {
INSTRUCTION(mcrf, 0x4C000000, XL, General, 0, NULL),
INSTRUCTION(bclrx, 0x4C000020, XL, BranchCond, bclrx,
"Branch Conditional to Link Register"),
INSTRUCTION(crnor, 0x4C000042, XL, General, 0, NULL),
INSTRUCTION(crandc, 0x4C000102, XL, General, 0, NULL),
INSTRUCTION(isync, 0x4C00012C, XL, General, 0, NULL),
INSTRUCTION(crxor, 0x4C000182, XL, General, 0, NULL),
INSTRUCTION(crnand, 0x4C0001C2, XL, General, 0, NULL),
INSTRUCTION(crand, 0x4C000202, XL, General, 0, NULL),
INSTRUCTION(creqv, 0x4C000242, XL, General, 0, NULL),
INSTRUCTION(crorc, 0x4C000342, XL, General, 0, NULL),
INSTRUCTION(cror, 0x4C000382, XL, General, 0, NULL),
INSTRUCTION(bcctrx, 0x4C000420, XL, BranchCond, bcctrx,
"Branch Conditional to Count Register"),
};
static InstrType** instr_table_19 = instr_table_prep(
instr_table_19_unprep, xe::countof(instr_table_19_unprep), 1, 10);
// Opcode = 30, index = bits 4-1 (4)
static InstrType instr_table_30_unprep[] = {
// Decoding these instrunctions in this table is difficult because the
// index bits are kind of random. This is special cased by an uber
// instruction handler.
INSTRUCTION(rld, 0x78000000, MD, General, rld, NULL),
// INSTRUCTION(rldiclx, 0x78000000, MD , General , 0),
// INSTRUCTION(rldicrx, 0x78000004, MD , General , 0),
// INSTRUCTION(rldicx, 0x78000008, MD , General , 0),
// INSTRUCTION(rldimix, 0x7800000C, MD , General , 0),
// INSTRUCTION(rldclx, 0x78000010, MDS, General , 0),
// INSTRUCTION(rldcrx, 0x78000012, MDS, General , 0),
};
static InstrType** instr_table_30 = instr_table_prep(
instr_table_30_unprep, xe::countof(instr_table_30_unprep), 0, 0);
// Opcode = 31, index = bits 10-1 (10)
static InstrType instr_table_31_unprep[] = {
INSTRUCTION(cmp, 0x7C000000, X, General, cmp, "Compare"),
INSTRUCTION(tw, 0x7C000008, X, General, X_RA_RB, "Trap Word"),
INSTRUCTION(lvsl, 0x7C00000C, X, General, X_VX_RA0_RB,
"Load Vector for Shift Left"),
INSTRUCTION(lvebx, 0x7C00000E, X, General, 0,
"Load Vector Element Byte Indexed"),
INSTRUCTION(subfcx, 0x7C000010, XO, General, XO_RT_RA_RB,
"Subtract From Carrying"),
INSTRUCTION(mulhdux, 0x7C000012, XO, General, XO_RT_RA_RB,
"Multiply High Doubleword Unsigned"),
INSTRUCTION(addcx, 0x7C000014, XO, General, XO_RT_RA_RB, "Add Carrying"),
INSTRUCTION(mulhwux, 0x7C000016, XO, General, XO_RT_RA_RB,
"Multiply High Word Unsigned"),
INSTRUCTION(mfcr, 0x7C000026, X, General, mfcr,
"Move From Condition Register"),
INSTRUCTION(lwarx, 0x7C000028, X, General, X_RT_RA0_RB,
"Load Word And Reserve Indexed"),
INSTRUCTION(ldx, 0x7C00002A, X, General, X_RT_RA0_RB,
"Load Doubleword Indexed"),
INSTRUCTION(lwzx, 0x7C00002E, X, General, X_RT_RA0_RB,
"Load Word and Zero Indexed"),
INSTRUCTION(slwx, 0x7C000030, X, General, X_RA_RT_RB, "Shift Left Word"),
INSTRUCTION(cntlzwx, 0x7C000034, X, General, X_RA_RT,
"Count Leading Zeros Word"),
INSTRUCTION(sldx, 0x7C000036, X, General, X_RA_RT_RB,
"Shift Left Doubleword"),
INSTRUCTION(andx, 0x7C000038, X, General, X_RA_RT_RB, "AND"),
INSTRUCTION(cmpl, 0x7C000040, X, General, cmp, "Compare Logical"),
INSTRUCTION(lvsr, 0x7C00004C, X, General, X_VX_RA0_RB,
"Load Vector for Shift Right"),
INSTRUCTION(lvehx, 0x7C00004E, X, General, 0,
"Load Vector Element Half Word Indexed"),
INSTRUCTION(subfx, 0x7C000050, XO, General, XO_RT_RA_RB, "Subtract From"),
INSTRUCTION(ldux, 0x7C00006A, X, General, X_RT_RA_RB,
"Load Doubleword with Update Indexed"),
INSTRUCTION(dcbst, 0x7C00006C, X, General, 0, NULL),
INSTRUCTION(lwzux, 0x7C00006E, X, General, X_RT_RA_RB,
"Load Word and Zero with Update Indexed"),
INSTRUCTION(cntlzdx, 0x7C000074, X, General, X_RA_RT,
"Count Leading Zeros Doubleword"),
INSTRUCTION(andcx, 0x7C000078, X, General, X_RA_RT_RB,
"AND with Complement"),
INSTRUCTION(td, 0x7C000088, X, General, X_RA_RB, "Trap Doubleword"),
INSTRUCTION(lvewx, 0x7C00008E, X, General, 0,
"Load Vector Element Word Indexed"),
INSTRUCTION(mulhdx, 0x7C000092, XO, General, XO_RT_RA_RB,
"Multiply High Doubleword"),
INSTRUCTION(mulhwx, 0x7C000096, XO, General, XO_RT_RA_RB,
"Multiply High Word"),
INSTRUCTION(mfmsr, 0x7C0000A6, X, General, mfmsr,
"Move From Machine State Register"),
INSTRUCTION(ldarx, 0x7C0000A8, X, General, X_RT_RA0_RB,
"Load Doubleword And Reserve Indexed"),
INSTRUCTION(dcbf, 0x7C0000AC, X, General, dcbf, "Data Cache Block Flush"),
INSTRUCTION(lbzx, 0x7C0000AE, X, General, X_RT_RA0_RB,
"Load Byte and Zero Indexed"),
INSTRUCTION(lvx, 0x7C0000CE, X, General, X_VX_RA0_RB,
"Load Vector Indexed"),
INSTRUCTION(negx, 0x7C0000D0, XO, General, XO_RT_RA, "Negate"),
INSTRUCTION(lbzux, 0x7C0000EE, X, General, X_RT_RA_RB,
"Load Byte and Zero with Update Indexed"),
INSTRUCTION(norx, 0x7C0000F8, X, General, X_RA_RT_RB, "NOR"),
INSTRUCTION(stvebx, 0x7C00010E, X, General, 0,
"Store Vector Element Byte Indexed"),
INSTRUCTION(subfex, 0x7C000110, XO, General, XO_RT_RA_RB,
"Subtract From Extended"),
INSTRUCTION(addex, 0x7C000114, XO, General, XO_RT_RA_RB, "Add Extended"),
INSTRUCTION(mtcrf, 0x7C000120, XFX, General, 0, NULL),
INSTRUCTION(mtmsr, 0x7C000124, X, General, mtmsr,
"Move To Machine State Register"),
INSTRUCTION(stdx, 0x7C00012A, X, General, X_RT_RA0_RB,
"Store Doubleword Indexed"),
INSTRUCTION(stwcx, 0x7C00012D, X, General, X_RT_RA0_RB,
"Store Word Conditional Indexed"),
INSTRUCTION(stwx, 0x7C00012E, X, General, X_RT_RA0_RB,
"Store Word Indexed"),
INSTRUCTION(stvehx, 0x7C00014E, X, General, 0,
"Store Vector Element Half Word Indexed"),
INSTRUCTION(mtmsrd, 0x7C000164, X, General, mtmsr,
"Move To Machine State Register Doubleword"),
INSTRUCTION(stdux, 0x7C00016A, X, General, X_RT_RA_RB,
"Store Doubleword with Update Indexed"),
INSTRUCTION(stwux, 0x7C00016E, X, General, X_RT_RA_RB,
"Store Word with Update Indexed"),
INSTRUCTION(stvewx, 0x7C00018E, X, General, 0,
"Store Vector Element Word Indexed"),
INSTRUCTION(subfzex, 0x7C000190, XO, General, XO_RT_RA,
"Subtract From Zero Extended"),
INSTRUCTION(addzex, 0x7C000194, XO, General, XO_RT_RA,
"Add to Zero Extended"),
INSTRUCTION(stdcx, 0x7C0001AD, X, General, X_RT_RA0_RB,
"Store Doubleword Conditional Indexed"),
INSTRUCTION(stbx, 0x7C0001AE, X, General, X_RT_RA0_RB,
"Store Byte Indexed"),
INSTRUCTION(stvx, 0x7C0001CE, X, General, 0, "Store Vector Indexed"),
INSTRUCTION(subfmex, 0x7C0001D0, XO, General, XO_RT_RA,
"Subtract From Minus One Extended"),
INSTRUCTION(mulldx, 0x7C0001D2, XO, General, XO_RT_RA_RB,
"Multiply Low Doubleword"),
INSTRUCTION(addmex, 0x7C0001D4, XO, General, XO_RT_RA,
"Add to Minus One Extended"),
INSTRUCTION(mullwx, 0x7C0001D6, XO, General, XO_RT_RA_RB,
"Multiply Low Word"),
INSTRUCTION(dcbtst, 0x7C0001EC, X, General, 0,
"Data Cache Block Touch for Store"),
INSTRUCTION(stbux, 0x7C0001EE, X, General, X_RT_RA_RB,
"Store Byte with Update Indexed"),
INSTRUCTION(addx, 0x7C000214, XO, General, XO_RT_RA_RB, "Add"),
INSTRUCTION(dcbt, 0x7C00022C, X, General, 0, "Data Cache Block Touch"),
INSTRUCTION(lhzx, 0x7C00022E, X, General, X_RT_RA0_RB,
"Load Halfword and Zero Indexed"),
INSTRUCTION(eqvx, 0x7C000238, X, General, X_RA_RT_RB, "Equivalent"),
INSTRUCTION(eciwx, 0x7C00026C, X, General, 0, NULL),
INSTRUCTION(lhzux, 0x7C00026E, X, General, X_RT_RA_RB,
"Load Halfword and Zero with Update Indexed"),
INSTRUCTION(xorx, 0x7C000278, X, General, X_RA_RT_RB, "XOR"),
INSTRUCTION(mfspr, 0x7C0002A6, XFX, General, mfspr,
"Move From Special Purpose Register"),
INSTRUCTION(lwax, 0x7C0002AA, X, General, X_RT_RA0_RB,
"Load Word Algebraic Indexed"),
INSTRUCTION(lhax, 0x7C0002AE, X, General, X_RT_RA0_RB,
"Load Halfword Algebraic Indexed"),
INSTRUCTION(lvxl, 0x7C0002CE, X, General, X_VX_RA0_RB,
"Load Vector Indexed LRU"),
INSTRUCTION(mftb, 0x7C0002E6, XFX, General, mftb, "Move From Time Base"),
INSTRUCTION(lwaux, 0x7C0002EA, X, General, X_RT_RA_RB,
"Load Word Algebraic with Update Indexed"),
INSTRUCTION(lhaux, 0x7C0002EE, X, General, 0, NULL),
INSTRUCTION(sthx, 0x7C00032E, X, General, X_RT_RA0_RB,
"Store Halfword Indexed"),
INSTRUCTION(orcx, 0x7C000338, X, General, X_RA_RT_RB, "OR with Complement"),
INSTRUCTION(ecowx, 0x7C00036C, X, General, 0, NULL),
INSTRUCTION(sthux, 0x7C00036E, X, General, X_RT_RA_RB,
"Store Halfword with Update Indexed"),
INSTRUCTION(orx, 0x7C000378, X, General, X_RA_RT_RB, "OR"),
INSTRUCTION(divdux, 0x7C000392, XO, General, XO_RT_RA_RB,
"Divide Doubleword Unsigned"),
INSTRUCTION(divwux, 0x7C000396, XO, General, XO_RT_RA_RB,
"Divide Word Unsigned"),
INSTRUCTION(mtspr, 0x7C0003A6, XFX, General, mtspr,
"Move To Special Purpose Register"),
INSTRUCTION(nandx, 0x7C0003B8, X, General, X_RA_RT_RB, "NAND"),
INSTRUCTION(stvxl, 0x7C0003CE, X, General, 0, "Store Vector Indexed LRU"),
INSTRUCTION(divdx, 0x7C0003D2, XO, General, XO_RT_RA_RB,
"Divide Doubleword"),
INSTRUCTION(divwx, 0x7C0003D6, XO, General, XO_RT_RA_RB, "Divide Word"),
INSTRUCTION(lvlx, 0x7C00040E, X, General, 0, "Load Vector Indexed"),
INSTRUCTION(ldbrx, 0x7C000428, X, General, X_RT_RA0_RB,
"Load Doubleword Byte-Reverse Indexed"),
INSTRUCTION(lswx, 0x7C00042A, X, General, 0, NULL),
INSTRUCTION(lwbrx, 0x7C00042C, X, General, X_RT_RA0_RB,
"Load Word Byte-Reverse Indexed"),
INSTRUCTION(lfsx, 0x7C00042E, X, General, X_FRT_RA0_RB,
"Load Floating-Point Single Indexed"),
INSTRUCTION(srwx, 0x7C000430, X, General, X_RA_RT_RB, "Shift Right Word"),
INSTRUCTION(srdx, 0x7C000436, X, General, X_RA_RT_RB,
"Shift Right Doubleword"),
INSTRUCTION(lfsux, 0x7C00046E, X, General, X_FRT_RA_RB,
"Load Floating-Point Single with Update Indexed"),
INSTRUCTION(lswi, 0x7C0004AA, X, General, 0, NULL),
INSTRUCTION(sync, 0x7C0004AC, X, General, sync, "Synchronize"),
INSTRUCTION(lfdx, 0x7C0004AE, X, General, X_FRT_RA0_RB,
"Load Floating-Point Double Indexed"),
INSTRUCTION(lfdux, 0x7C0004EE, X, General, X_FRT_RA_RB,
"Load Floating-Point Double with Update Indexed"),
INSTRUCTION(stdbrx, 0x7C000528, X, General, X_RT_RA0_RB,
"Store Doubleword Byte-Reverse Indexed"),
INSTRUCTION(stswx, 0x7C00052A, X, General, 0, NULL),
INSTRUCTION(stwbrx, 0x7C00052C, X, General, X_RT_RA0_RB,
"Store Word Byte-Reverse Indexed"),
INSTRUCTION(stfsx, 0x7C00052E, X, General, X_FRT_RA0_RB,
"Store Floating-Point Single Indexed"),
INSTRUCTION(stfsux, 0x7C00056E, X, General, X_FRT_RA_RB,
"Store Floating-Point Single with Update Indexed"),
INSTRUCTION(stswi, 0x7C0005AA, X, General, 0, NULL),
INSTRUCTION(stfdx, 0x7C0005AE, X, General, X_FRT_RA0_RB,
"Store Floating-Point Double Indexed"),
INSTRUCTION(stfdux, 0x7C0005EE, X, General, X_FRT_RA_RB,
"Store Floating-Point Double with Update Indexed"),
INSTRUCTION(lhbrx, 0x7C00062C, X, General, X_RT_RA0_RB,
"Load Halfword Byte-Reverse Indexed"),
INSTRUCTION(srawx, 0x7C000630, X, General, X_RA_RT_RB,
"Shift Right Algebraic Word"),
INSTRUCTION(sradx, 0x7C000634, X, General, X_RA_RT_RB,
"Shift Right Algebraic Doubleword"),
INSTRUCTION(srawix, 0x7C000670, X, General, srawix,
"Shift Right Algebraic Word Immediate"),
INSTRUCTION(sradix, 0x7C000674, XS, General, sradix,
"Shift Right Algebraic Doubleword Immediate"),
INSTRUCTION(sradix, 0x7C000674, XS, General, sradix,
"Shift Right Algebraic Doubleword Immediate"),
INSTRUCTION(sradix, 0x7C000676, XS, General, sradix,
"Shift Right Algebraic Doubleword Immediate"), // HACK
INSTRUCTION(eieio, 0x7C0006AC, X, General, _,
"Enforce In-Order Execution of I/O Instruction"),
INSTRUCTION(sthbrx, 0x7C00072C, X, General, X_RT_RA0_RB,
"Store Halfword Byte-Reverse Indexed"),
INSTRUCTION(extshx, 0x7C000734, X, General, X_RA_RT,
"Extend Sign Halfword"),
INSTRUCTION(extsbx, 0x7C000774, X, General, X_RA_RT, "Extend Sign Byte"),
INSTRUCTION(icbi, 0x7C0007AC, X, General, 0, NULL),
INSTRUCTION(stfiwx, 0x7C0007AE, X, General, X_FRT_RA0_RB,
"Store Floating-Point as Integer Word Indexed"),
INSTRUCTION(extswx, 0x7C0007B4, X, General, X_RA_RT, "Extend Sign Word"),
INSTRUCTION(dcbz, 0x7C0007EC, X, General, dcbz,
"Data Cache Block set to Zero"), // 0x7C2007EC = DCBZ128
INSTRUCTION(dst, 0x7C0002AC, XDSS, General, 0, NULL),
INSTRUCTION(dstst, 0x7C0002EC, XDSS, General, 0, NULL),
INSTRUCTION(dss, 0x7C00066C, XDSS, General, 0, NULL),
INSTRUCTION(lvebx, 0x7C00000E, X, General, 0,
"Load Vector Element Byte Indexed"),
INSTRUCTION(lvehx, 0x7C00004E, X, General, 0,
"Load Vector Element Half Word Indexed"),
INSTRUCTION(lvewx, 0x7C00008E, X, General, 0,
"Load Vector Element Word Indexed"),
INSTRUCTION(lvsl, 0x7C00000C, X, General, 0, "Load Vector for Shift Left"),
INSTRUCTION(lvsr, 0x7C00004C, X, General, 0, "Load Vector for Shift Right"),
INSTRUCTION(lvx, 0x7C0000CE, X, General, 0, "Load Vector Indexed"),
INSTRUCTION(lvxl, 0x7C0002CE, X, General, 0, "Load Vector Indexed LRU"),
INSTRUCTION(stvebx, 0x7C00010E, X, General, 0,
"Store Vector Element Byte Indexed"),
INSTRUCTION(stvehx, 0x7C00014E, X, General, 0,
"Store Vector Element Half Word Indexed"),
INSTRUCTION(stvewx, 0x7C00018E, X, General, 0,
"Store Vector Element Word Indexed"),
INSTRUCTION(stvx, 0x7C0001CE, X, General, X_VX_RA0_RB,
"Store Vector Indexed"),
INSTRUCTION(stvxl, 0x7C0003CE, X, General, X_VX_RA0_RB,
"Store Vector Indexed LRU"),
INSTRUCTION(lvlx, 0x7C00040E, X, General, X_VX_RA0_RB,
"Load Vector Left Indexed"),
INSTRUCTION(lvlxl, 0x7C00060E, X, General, X_VX_RA0_RB,
"Load Vector Left Indexed LRU"),
INSTRUCTION(lvrx, 0x7C00044E, X, General, X_VX_RA0_RB,
"Load Vector Right Indexed"),
INSTRUCTION(lvrxl, 0x7C00064E, X, General, X_VX_RA0_RB,
"Load Vector Right Indexed LRU"),
INSTRUCTION(stvlx, 0x7C00050E, X, General, X_VX_RA0_RB,
"Store Vector Left Indexed"),
INSTRUCTION(stvlxl, 0x7C00070E, X, General, X_VX_RA0_RB,
"Store Vector Left Indexed LRU"),
INSTRUCTION(stvrx, 0x7C00054E, X, General, X_VX_RA0_RB,
"Store Vector Right Indexed"),
INSTRUCTION(stvrxl, 0x7C00074E, X, General, X_VX_RA0_RB,
"Store Vector Right Indexed LRU"),
};
static InstrType** instr_table_31 = instr_table_prep(
instr_table_31_unprep, xe::countof(instr_table_31_unprep), 1, 10);
// Opcode = 58, index = bits 1-0 (2)
static InstrType instr_table_58_unprep[] = {
INSTRUCTION(ld, 0xE8000000, DS, General, DS_RT_RA0_I, "Load Doubleword"),
INSTRUCTION(ldu, 0xE8000001, DS, General, DS_RT_RA_I,
"Load Doubleword with Update"),
INSTRUCTION(lwa, 0xE8000002, DS, General, DS_RT_RA0_I,
"Load Word Algebraic"),
};
static InstrType** instr_table_58 = instr_table_prep(
instr_table_58_unprep, xe::countof(instr_table_58_unprep), 0, 1);
// Opcode = 59, index = bits 5-1 (5)
static InstrType instr_table_59_unprep[] = {
INSTRUCTION(fdivsx, 0xEC000024, A, General, A_FRT_FRA_FRB,
"Floating Divide [Single]"),
INSTRUCTION(fsubsx, 0xEC000028, A, General, A_FRT_FRA_FRB,
"Floating Subtract [Single]"),
INSTRUCTION(faddsx, 0xEC00002A, A, General, A_FRT_FRA_FRB,
"Floating Add [Single]"),
INSTRUCTION(fsqrtsx, 0xEC00002C, A, General, A_FRT_FRB,
"Floating Square Root [Single]"),
INSTRUCTION(fresx, 0xEC000030, A, General, A_FRT_FRB,
"Floating Reciprocal Estimate [Single]"),
INSTRUCTION(fmulsx, 0xEC000032, A, General, A_FRT_FRA_FRB,
"Floating Multiply [Single]"),
INSTRUCTION(fmsubsx, 0xEC000038, A, General, A_FRT_FRA_FRB_FRC,
"Floating Multiply-Subtract [Single]"),
INSTRUCTION(fmaddsx, 0xEC00003A, A, General, A_FRT_FRA_FRB_FRC,
"Floating Multiply-Add [Single]"),
INSTRUCTION(fnmsubsx, 0xEC00003C, A, General, A_FRT_FRA_FRB_FRC,
"Floating Negative Multiply-Subtract [Single]"),
INSTRUCTION(fnmaddsx, 0xEC00003E, A, General, A_FRT_FRA_FRB_FRC,
"Floating Negative Multiply-Add [Single]"),
};
static InstrType** instr_table_59 = instr_table_prep(
instr_table_59_unprep, xe::countof(instr_table_59_unprep), 1, 5);
// Opcode = 62, index = bits 1-0 (2)
static InstrType instr_table_62_unprep[] = {
INSTRUCTION(std, 0xF8000000, DS, General, DS_RT_RA0_I, "Store Doubleword"),
INSTRUCTION(stdu, 0xF8000001, DS, General, DS_RT_RA_I,
"Store Doubleword with Update"),
};
static InstrType** instr_table_62 = instr_table_prep(
instr_table_62_unprep, xe::countof(instr_table_62_unprep), 0, 1);
// Opcode = 63, index = bits 10-1 (10)
// NOTE: the A format instructions need some special handling because
// they only use 6bits to identify their index.
static InstrType instr_table_63_unprep[] = {
INSTRUCTION(fcmpu, 0xFC000000, X, General, fcmp,
"Floating Compare Unordered"),
INSTRUCTION(frspx, 0xFC000018, X, General, X_FRT_FRB,
"Floating Round to Single-Precision"),
INSTRUCTION(fctiwx, 0xFC00001C, X, General, X_FRT_FRB,
"Floating Convert To Integer Word"),
INSTRUCTION(fctiwzx, 0xFC00001E, X, General, X_FRT_FRB,
"Floating Convert To Integer Word with round toward Zero"),
INSTRUCTION(fdivx, 0xFC000024, A, General, A_FRT_FRA_FRB,
"Floating Divide [Single]"),
INSTRUCTION(fsubx, 0xFC000028, A, General, A_FRT_FRA_FRB,
"Floating Subtract [Single]"),
INSTRUCTION(faddx, 0xFC00002A, A, General, A_FRT_FRA_FRB,
"Floating Add [Single]"),
INSTRUCTION(fsqrtx, 0xFC00002C, A, General, A_FRT_FRB,
"Floating Square Root [Single]"),
INSTRUCTION(fselx, 0xFC00002E, A, General, A_FRT_FRA_FRB_FRC,
"Floating Select"),
INSTRUCTION(fmulx, 0xFC000032, A, General, A_FRT_FRA_FRB,
"Floating Multiply [Single]"),
INSTRUCTION(frsqrtex, 0xFC000034, A, General, A_FRT_FRB,
"Floating Reciprocal Square Root Estimate [Single]"),
INSTRUCTION(fmsubx, 0xFC000038, A, General, 0,
"Floating Multiply-Subtract [Single]"),
INSTRUCTION(fmaddx, 0xFC00003A, A, General, A_FRT_FRA_FRB_FRC,
"Floating Multiply-Add [Single]"),
INSTRUCTION(fnmsubx, 0xFC00003C, A, General, A_FRT_FRA_FRB_FRC,
"Floating Negative Multiply-Subtract [Single]"),
INSTRUCTION(fnmaddx, 0xFC00003E, A, General, A_FRT_FRA_FRB_FRC,
"Floating Negative Multiply-Add [Single]"),
INSTRUCTION(fcmpo, 0xFC000040, X, General, fcmp,
"Floating Compare Ordered"),
INSTRUCTION(mtfsb1x, 0xFC00004C, X, General, 0, NULL),
INSTRUCTION(fnegx, 0xFC000050, X, General, X_FRT_FRB, "Floating Negate"),
INSTRUCTION(mcrfs, 0xFC000080, X, General, 0, NULL),
INSTRUCTION(mtfsb0x, 0xFC00008C, X, General, 0, NULL),
INSTRUCTION(fmrx, 0xFC000090, X, General, X_FRT_FRB,
"Floating Move Register"),
INSTRUCTION(mtfsfix, 0xFC00010C, X, General, 0, NULL),
INSTRUCTION(fnabsx, 0xFC000110, X, General, X_FRT_FRB,
"Floating Negative Absolute Value"),
INSTRUCTION(fabsx, 0xFC000210, X, General, X_FRT_FRB,
"Floating Absolute Value"),
INSTRUCTION(mffsx, 0xFC00048E, X, General, 0, "Move from FPSCR"),
INSTRUCTION(mtfsfx, 0xFC00058E, XFL, General, 0, "Move to FPSCR Fields"),
INSTRUCTION(fctidx, 0xFC00065C, X, General, X_FRT_FRB,
"Floating Convert To Integer Doubleword"),
INSTRUCTION(
fctidzx, 0xFC00065E, X, General, X_FRT_FRB,
"Floating Convert To Integer Doubleword with round toward Zero"),
INSTRUCTION(fcfidx, 0xFC00069C, X, General, X_FRT_FRB,
"Floating Convert From Integer Doubleword"),
};
static InstrType** instr_table_63 = instr_table_prep_63(
instr_table_63_unprep, xe::countof(instr_table_63_unprep), 1, 10);
// Main table, index = bits 31-26 (6) : (code >> 26)
static InstrType instr_table_unprep[64] = {
INSTRUCTION(tdi, 0x08000000, D, General, D_RA, "Trap Doubleword Immediate"),
INSTRUCTION(twi, 0x0C000000, D, General, D_RA, "Trap Word Immediate"),
INSTRUCTION(mulli, 0x1C000000, D, General, D_RT_RA_I,
"Multiply Low Immediate"),
INSTRUCTION(subficx, 0x20000000, D, General, D_RT_RA_I,
"Subtract From Immediate Carrying"),
INSTRUCTION(cmpli, 0x28000000, D, General, cmpli,
"Compare Logical Immediate"),
INSTRUCTION(cmpi, 0x2C000000, D, General, cmpi, "Compare Immediate"),
INSTRUCTION(addic, 0x30000000, D, General, D_RT_RA_I,
"Add Immediate Carrying"),
INSTRUCTION(addicx, 0x34000000, D, General, D_RT_RA_I,
"Add Immediate Carrying and Record"),
INSTRUCTION(addi, 0x38000000, D, General, D_RT_RA0_I, "Add Immediate"),
INSTRUCTION(addis, 0x3C000000, D, General, D_RT_RA0_I,
"Add Immediate Shifted"),
INSTRUCTION(bcx, 0x40000000, B, BranchCond, bcx, "Branch Conditional"),
INSTRUCTION(sc, 0x44000002, SC, Syscall, 0, NULL),
INSTRUCTION(bx, 0x48000000, I, BranchAlways, bx, "Branch"),
INSTRUCTION(rlwimix, 0x50000000, M, General, rlwim,
"Rotate Left Word Immediate then Mask Insert"),
INSTRUCTION(rlwinmx, 0x54000000, M, General, rlwim,
"Rotate Left Word Immediate then AND with Mask"),
INSTRUCTION(rlwnmx, 0x5C000000, M, General, rlwnmx,
"Rotate Left Word then AND with Mask"),
INSTRUCTION(ori, 0x60000000, D, General, D_RA_RT_I, "OR Immediate"),
INSTRUCTION(oris, 0x64000000, D, General, D_RA_RT_I,
"OR Immediate Shifted"),
INSTRUCTION(xori, 0x68000000, D, General, D_RA_RT_I, "XOR Immediate"),
INSTRUCTION(xoris, 0x6C000000, D, General, D_RA_RT_I,
"XOR Immediate Shifted"),
INSTRUCTION(andix, 0x70000000, D, General, D_RA_RT_I, "AND Immediate"),
INSTRUCTION(andisx, 0x74000000, D, General, D_RA_RT_I,
"AND Immediate Shifted"),
INSTRUCTION(lwz, 0x80000000, D, General, D_RT_RA0_I, "Load Word and Zero"),
INSTRUCTION(lwzu, 0x84000000, D, General, D_RT_RA_I,
"Load Word and Zero with Udpate"),
INSTRUCTION(lbz, 0x88000000, D, General, D_RT_RA0_I, "Load Byte and Zero"),
INSTRUCTION(lbzu, 0x8C000000, D, General, D_RT_RA_I,
"Load Byte and Zero with Update"),
INSTRUCTION(stw, 0x90000000, D, General, D_RT_RA0_I, "Store Word"),
INSTRUCTION(stwu, 0x94000000, D, General, D_RT_RA_I,
"Store Word with Update"),
INSTRUCTION(stb, 0x98000000, D, General, D_RT_RA0_I, "Store Byte"),
INSTRUCTION(stbu, 0x9C000000, D, General, D_RT_RA_I,
"Store Byte with Update"),
INSTRUCTION(lhz, 0xA0000000, D, General, D_RT_RA0_I,
"Load Halfword and Zero"),
INSTRUCTION(lhzu, 0xA4000000, D, General, D_RT_RA_I,
"Load Halfword and Zero with Update"),
INSTRUCTION(lha, 0xA8000000, D, General, D_RT_RA0_I,
"Load Halfword Algebraic"),
INSTRUCTION(lhau, 0xAC000000, D, General, D_RT_RA_I, NULL),
INSTRUCTION(sth, 0xB0000000, D, General, D_RT_RA0_I, "Store Halfword"),
INSTRUCTION(sthu, 0xB4000000, D, General, D_RT_RA_I,
"Store Halfword with Update"),
INSTRUCTION(lmw, 0xB8000000, D, General, 0, NULL),
INSTRUCTION(stmw, 0xBC000000, D, General, 0, NULL),
INSTRUCTION(lfs, 0xC0000000, D, General, D_FRT_RA0_I,
"Load Floating-Point Single"),
INSTRUCTION(lfsu, 0xC4000000, D, General, D_FRT_RA_I,
"Load Floating-Point Single with Update"),
INSTRUCTION(lfd, 0xC8000000, D, General, D_FRT_RA0_I,
"Load Floating-Point Double"),
INSTRUCTION(lfdu, 0xCC000000, D, General, D_FRT_RA_I,
"Load Floating-Point Double with Update"),
INSTRUCTION(stfs, 0xD0000000, D, General, D_FRT_RA0_I,
"Store Floating-Point Single"),
INSTRUCTION(stfsu, 0xD4000000, D, General, D_FRT_RA_I,
"Store Floating-Point Single with Update"),
INSTRUCTION(stfd, 0xD8000000, D, General, D_FRT_RA0_I,
"Store Floating-Point Double"),
INSTRUCTION(stfdu, 0xDC000000, D, General, D_FRT_RA_I,
"Store Floating-Point Double with Update"),
};
static InstrType** instr_table = instr_table_prep(
instr_table_unprep, xe::countof(instr_table_unprep), 26, 31);
// Altivec instructions.
// TODO(benvanik): build a table like the other instructions.
// This table is looked up via linear scan of opcodes.
#define SCAN_INSTRUCTION(name, opcode, format, type, disasm_fn, descr) \
{ \
opcode, kXEPPCInstrMask##format, kXEPPCInstrFormat##format, \
kXEPPCInstrType##type, 0, Disasm_##disasm_fn, #name, 0, \
}
#define OP(x) ((((uint32_t)(x)) & 0x3f) << 26)
#define VX128(op, xop) (OP(op) | (((uint32_t)(xop)) & 0x3d0))
#define VX128_1(op, xop) (OP(op) | (((uint32_t)(xop)) & 0x7f3))
#define VX128_2(op, xop) (OP(op) | (((uint32_t)(xop)) & 0x210))
#define VX128_3(op, xop) (OP(op) | (((uint32_t)(xop)) & 0x7f0))
#define VX128_4(op, xop) (OP(op) | (((uint32_t)(xop)) & 0x730))
#define VX128_5(op, xop) (OP(op) | (((uint32_t)(xop)) & 0x10))
#define VX128_P(op, xop) (OP(op) | (((uint32_t)(xop)) & 0x630))
#define VX128_R(op, xop) (OP(op) | (((uint32_t)(xop)) & 0x390))
static InstrType instr_table_scan[] = {
SCAN_INSTRUCTION(vcmpbfp, 0x100003C6, VXR, General, 0,
"Vector Compare Bounds Floating Point"),
SCAN_INSTRUCTION(vcmpeqfp, 0x100000C6, VXR, General, 0,
"Vector Compare Equal-to Floating Point"),
SCAN_INSTRUCTION(vcmpequb, 0x10000006, VXR, General, 0,
"Vector Compare Equal-to Unsigned Byte"),
SCAN_INSTRUCTION(vcmpequh, 0x10000046, VXR, General, 0,
"Vector Compare Equal-to Unsigned Half Word"),
SCAN_INSTRUCTION(vcmpequw, 0x10000086, VXR, General, 0,
"Vector Compare Equal-to Unsigned Word"),
SCAN_INSTRUCTION(vcmpgefp, 0x100001C6, VXR, General, 0,
"Vector Compare Greater-Than-or-Equal-to Floating Point"),
SCAN_INSTRUCTION(vcmpgtfp, 0x100002C6, VXR, General, 0,
"Vector Compare Greater-Than Floating Point"),
SCAN_INSTRUCTION(vcmpgtsb, 0x10000306, VXR, General, 0,
"Vector Compare Greater-Than Signed Byte"),
SCAN_INSTRUCTION(vcmpgtsh, 0x10000346, VXR, General, 0,
"Vector Compare Greater-Than Signed Half Word"),
SCAN_INSTRUCTION(vcmpgtsw, 0x10000386, VXR, General, 0,
"Vector Compare Greater-Than Signed Word"),
SCAN_INSTRUCTION(vcmpgtub, 0x10000206, VXR, General, 0,
"Vector Compare Greater-Than Unsigned Byte"),
SCAN_INSTRUCTION(vcmpgtuh, 0x10000246, VXR, General, 0,
"Vector Compare Greater-Than Unsigned Half Word"),
SCAN_INSTRUCTION(vcmpgtuw, 0x10000286, VXR, General, 0,
"Vector Compare Greater-Than Unsigned Word"),
SCAN_INSTRUCTION(vmaddfp, 0x1000002E, VXA, General, VXA_VD_VA_VB_VC,
"Vector Multiply-Add Floating Point"),
SCAN_INSTRUCTION(
vmhaddshs, 0x10000020, VXA, General, VXA_VD_VA_VB_VC,
"Vector Multiply-High and Add Signed Signed Half Word Saturate"),
SCAN_INSTRUCTION(
vmhraddshs, 0x10000021, VXA, General, VXA_VD_VA_VB_VC,
"Vector Multiply-High Round and Add Signed Signed Half Word Saturate"),
SCAN_INSTRUCTION(vmladduhm, 0x10000022, VXA, General, VXA_VD_VA_VB_VC,
"Vector Multiply-Low and Add Unsigned Half Word Modulo"),
SCAN_INSTRUCTION(vmsummbm, 0x10000025, VXA, General, VXA_VD_VA_VB_VC,
"Vector Multiply-Sum Mixed-Sign Byte Modulo"),
SCAN_INSTRUCTION(vmsumshm, 0x10000028, VXA, General, VXA_VD_VA_VB_VC,
"Vector Multiply-Sum Signed Half Word Modulo"),
SCAN_INSTRUCTION(vmsumshs, 0x10000029, VXA, General, VXA_VD_VA_VB_VC,
"Vector Multiply-Sum Signed Half Word Saturate"),
SCAN_INSTRUCTION(vmsumubm, 0x10000024, VXA, General, VXA_VD_VA_VB_VC,
"Vector Multiply-Sum Unsigned Byte Modulo"),
SCAN_INSTRUCTION(vmsumuhm, 0x10000026, VXA, General, VXA_VD_VA_VB_VC,
"Vector Multiply-Sum Unsigned Half Word Modulo"),
SCAN_INSTRUCTION(vmsumuhs, 0x10000027, VXA, General, VXA_VD_VA_VB_VC,
"Vector Multiply-Sum Unsigned Half Word Saturate"),
SCAN_INSTRUCTION(vnmsubfp, 0x1000002F, VXA, General, VXA_VD_VA_VB_VC,
"Vector Negative Multiply-Subtract Floating Point"),
SCAN_INSTRUCTION(vperm, 0x1000002B, VXA, General, VXA_VD_VA_VB_VC,
"Vector Permute"),
SCAN_INSTRUCTION(vsel, 0x1000002A, VXA, General, VXA_VD_VA_VB_VC,
"Vector Conditional Select"),
SCAN_INSTRUCTION(vsldoi, 0x1000002C, VXA, General, VXA_VD_VA_VB_VC,
"Vector Shift Left Double by Octet Immediate"),
SCAN_INSTRUCTION(lvsl128, VX128_1(4, 3), VX128_1, General, VX1281_VD_RA0_RB,
"Load Vector128 for Shift Left"),
SCAN_INSTRUCTION(lvsr128, VX128_1(4, 67), VX128_1, General,
VX1281_VD_RA0_RB, "Load Vector128 for Shift Right"),
SCAN_INSTRUCTION(lvewx128, VX128_1(4, 131), VX128_1, General,
VX1281_VD_RA0_RB, "Load Vector128 Element Word Indexed"),
SCAN_INSTRUCTION(lvx128, VX128_1(4, 195), VX128_1, General,
VX1281_VD_RA0_RB, "Load Vector128 Indexed"),
SCAN_INSTRUCTION(stvewx128, VX128_1(4, 387), VX128_1, General,
VX1281_VD_RA0_RB, "Store Vector128 Element Word Indexed"),
SCAN_INSTRUCTION(stvx128, VX128_1(4, 451), VX128_1, General,
VX1281_VD_RA0_RB, "Store Vector128 Indexed"),
SCAN_INSTRUCTION(lvxl128, VX128_1(4, 707), VX128_1, General,
VX1281_VD_RA0_RB, "Load Vector128 Left Indexed"),
SCAN_INSTRUCTION(stvxl128, VX128_1(4, 963), VX128_1, General,
VX1281_VD_RA0_RB, "Store Vector128 Indexed LRU"),
SCAN_INSTRUCTION(lvlx128, VX128_1(4, 1027), VX128_1, General,
VX1281_VD_RA0_RB, "Load Vector128 Left Indexed LRU"),
SCAN_INSTRUCTION(lvrx128, VX128_1(4, 1091), VX128_1, General,
VX1281_VD_RA0_RB, "Load Vector128 Right Indexed"),
SCAN_INSTRUCTION(stvlx128, VX128_1(4, 1283), VX128_1, General,
VX1281_VD_RA0_RB, "Store Vector128 Left Indexed"),
SCAN_INSTRUCTION(stvrx128, VX128_1(4, 1347), VX128_1, General,
VX1281_VD_RA0_RB, "Store Vector128 Right Indexed"),
SCAN_INSTRUCTION(lvlxl128, VX128_1(4, 1539), VX128_1, General,
VX1281_VD_RA0_RB, "Load Vector128 Indexed LRU"),
SCAN_INSTRUCTION(lvrxl128, VX128_1(4, 1603), VX128_1, General,
VX1281_VD_RA0_RB, "Load Vector128 Right Indexed LRU"),
SCAN_INSTRUCTION(stvlxl128, VX128_1(4, 1795), VX128_1, General,
VX1281_VD_RA0_RB, "Store Vector128 Left Indexed LRU"),
SCAN_INSTRUCTION(stvrxl128, VX128_1(4, 1859), VX128_1, General,
VX1281_VD_RA0_RB, "Store Vector128 Right Indexed LRU"),
SCAN_INSTRUCTION(vsldoi128, VX128_5(4, 16), VX128_5, General, vsldoi128,
"Vector128 Shift Left Double by Octet Immediate"),
SCAN_INSTRUCTION(vperm128, VX128_2(5, 0), VX128_2, General,
VX1282_VD_VA_VB_VC, "Vector128 Permute"),
SCAN_INSTRUCTION(vaddfp128, VX128(5, 16), VX128, General, VX128_VD_VA_VB,
"Vector128 Add Floating Point"),
SCAN_INSTRUCTION(vsubfp128, VX128(5, 80), VX128, General, VX128_VD_VA_VB,
"Vector128 Subtract Floating Point"),
SCAN_INSTRUCTION(vmulfp128, VX128(5, 144), VX128, General, VX128_VD_VA_VB,
"Vector128 Multiply Floating-Point"),
SCAN_INSTRUCTION(vmaddfp128, VX128(5, 208), VX128, General,
VX128_VD_VA_VD_VB,
"Vector128 Multiply Add Floating Point"),
SCAN_INSTRUCTION(vmaddcfp128, VX128(5, 272), VX128, General,
VX128_VD_VA_VD_VB,
"Vector128 Multiply Add Floating Point"),
SCAN_INSTRUCTION(vnmsubfp128, VX128(5, 336), VX128, General, VX128_VD_VA_VB,
"Vector128 Negative Multiply-Subtract Floating Point"),
SCAN_INSTRUCTION(vmsum3fp128, VX128(5, 400), VX128, General, VX128_VD_VA_VB,
"Vector128 Multiply Sum 3-way Floating Point"),
SCAN_INSTRUCTION(vmsum4fp128, VX128(5, 464), VX128, General, VX128_VD_VA_VB,
"Vector128 Multiply Sum 4-way Floating-Point"),
SCAN_INSTRUCTION(vpkshss128, VX128(5, 512), VX128, General, 0,
"Vector128 Pack Signed Half Word Signed Saturate"),
SCAN_INSTRUCTION(vand128, VX128(5, 528), VX128, General, VX128_VD_VA_VB,
"Vector128 Logical AND"),
SCAN_INSTRUCTION(vpkshus128, VX128(5, 576), VX128, General, 0,
"Vector128 Pack Signed Half Word Unsigned Saturate"),
SCAN_INSTRUCTION(vandc128, VX128(5, 592), VX128, General, VX128_VD_VA_VB,
"Vector128 Logical AND with Complement"),
SCAN_INSTRUCTION(vpkswss128, VX128(5, 640), VX128, General, 0,
"Vector128 Pack Signed Word Signed Saturate"),
SCAN_INSTRUCTION(vnor128, VX128(5, 656), VX128, General, VX128_VD_VA_VB,
"Vector128 Logical NOR"),
SCAN_INSTRUCTION(vpkswus128, VX128(5, 704), VX128, General, 0,
"Vector128 Pack Signed Word Unsigned Saturate"),
SCAN_INSTRUCTION(vor128, VX128(5, 720), VX128, General, VX128_VD_VA_VB,
"Vector128 Logical OR"),
SCAN_INSTRUCTION(vpkuhum128, VX128(5, 768), VX128, General, 0,
"Vector128 Pack Unsigned Half Word Unsigned Modulo"),
SCAN_INSTRUCTION(vxor128, VX128(5, 784), VX128, General, VX128_VD_VA_VB,
"Vector128 Logical XOR"),
SCAN_INSTRUCTION(vpkuhus128, VX128(5, 832), VX128, General, 0,
"Vector128 Pack Unsigned Half Word Unsigned Saturate"),
SCAN_INSTRUCTION(vsel128, VX128(5, 848), VX128, General, 0,
"Vector128 Conditional Select"),
SCAN_INSTRUCTION(vpkuwum128, VX128(5, 896), VX128, General, 0,
"Vector128 Pack Unsigned Word Unsigned Modulo"),
SCAN_INSTRUCTION(vslo128, VX128(5, 912), VX128, General, 0,
"Vector128 Shift Left Octet"),
SCAN_INSTRUCTION(vpkuwus128, VX128(5, 960), VX128, General, 0,
"Vector128 Pack Unsigned Word Unsigned Saturate"),
SCAN_INSTRUCTION(vsro128, VX128(5, 976), VX128, General, VX128_VD_VA_VB,
"Vector128 Shift Right Octet"),
SCAN_INSTRUCTION(vpermwi128, VX128_P(6, 528), VX128_P, General, vpermwi128,
"Vector128 Permutate Word Immediate"),
SCAN_INSTRUCTION(vcfpsxws128, VX128_3(6, 560), VX128_3, General,
VX1283_VD_VB_I,
"Vector128 Convert From Floating-Point to Signed "
"Fixed-Point Word Saturate"),
SCAN_INSTRUCTION(vcfpuxws128, VX128_3(6, 624), VX128_3, General, 0,
"Vector128 Convert From Floating-Point to Unsigned "
"Fixed-Point Word Saturate"),
SCAN_INSTRUCTION(
vcsxwfp128, VX128_3(6, 688), VX128_3, General, VX1283_VD_VB_I,
"Vector128 Convert From Signed Fixed-Point Word to Floating-Point"),
SCAN_INSTRUCTION(
vcuxwfp128, VX128_3(6, 752), VX128_3, General, 0,
"Vector128 Convert From Unsigned Fixed-Point Word to Floating-Point"),
SCAN_INSTRUCTION(
vrfim128, VX128_3(6, 816), VX128_3, General, 0,
"Vector128 Round to Floating-Point Integer toward -Infinity"),
SCAN_INSTRUCTION(vrfin128, VX128_3(6, 880), VX128_3, General, vrfin128,
"Vector128 Round to Floating-Point Integer Nearest"),
SCAN_INSTRUCTION(
vrfip128, VX128_3(6, 944), VX128_3, General, 0,
"Vector128 Round to Floating-Point Integer toward +Infinity"),
SCAN_INSTRUCTION(vrfiz128, VX128_3(6, 1008), VX128_3, General, 0,
"Vector128 Round to Floating-Point Integer toward Zero"),
SCAN_INSTRUCTION(
vpkd3d128, VX128_4(6, 1552), VX128_4, General, 0,
"Vector128 Pack D3Dtype, Rotate Left Immediate and Mask Insert"),
SCAN_INSTRUCTION(vrefp128, VX128_3(6, 1584), VX128_3, General, 0,
"Vector128 Reciprocal Estimate Floating Point"),
SCAN_INSTRUCTION(
vrsqrtefp128, VX128_3(6, 1648), VX128_3, General, VX1283_VD_VB,
"Vector128 Reciprocal Square Root Estimate Floating Point"),
SCAN_INSTRUCTION(vexptefp128, VX128_3(6, 1712), VX128_3, General, 0,
"Vector128 Log2 Estimate Floating Point"),
SCAN_INSTRUCTION(vlogefp128, VX128_3(6, 1776), VX128_3, General, 0,
"Vector128 Log2 Estimate Floating Point"),
SCAN_INSTRUCTION(vrlimi128, VX128_4(6, 1808), VX128_4, General, vrlimi128,
"Vector128 Rotate Left Immediate and Mask Insert"),
SCAN_INSTRUCTION(vspltw128, VX128_3(6, 1840), VX128_3, General,
VX1283_VD_VB_I, "Vector128 Splat Word"),
SCAN_INSTRUCTION(vspltisw128, VX128_3(6, 1904), VX128_3, General,
VX1283_VD_VB_I, "Vector128 Splat Immediate Signed Word"),
SCAN_INSTRUCTION(vupkd3d128, VX128_3(6, 2032), VX128_3, General,
VX1283_VD_VB_I, "Vector128 Unpack D3Dtype"),
SCAN_INSTRUCTION(vcmpeqfp128, VX128_R(6, 0), VX128_R, General,
VX128_VD_VA_VB,
"Vector128 Compare Equal-to Floating Point"),
SCAN_INSTRUCTION(vrlw128, VX128(6, 80), VX128, General, 0,
"Vector128 Rotate Left Word"),
SCAN_INSTRUCTION(
vcmpgefp128,
VX128_R(6, 128), VX128_R, General, 0,
"Vector128 Compare Greater-Than-or-Equal-to Floating Point"),
SCAN_INSTRUCTION(vslw128, VX128(6, 208), VX128, General, VX128_VD_VA_VB,
"Vector128 Shift Left Integer Word"),
SCAN_INSTRUCTION(vcmpgtfp128, VX128_R(6, 256), VX128_R, General, 0,
"Vector128 Compare Greater-Than Floating-Point"),
SCAN_INSTRUCTION(vsraw128, VX128(6, 336), VX128, General, VX128_VD_VA_VB,
"Vector128 Shift Right Arithmetic Word"),
SCAN_INSTRUCTION(vcmpbfp128, VX128_R(6, 384), VX128_R, General, 0,
"Vector128 Compare Bounds Floating Point"),
SCAN_INSTRUCTION(vsrw128, VX128(6, 464), VX128, General, VX128_VD_VA_VB,
"Vector128 Shift Right Word"),
SCAN_INSTRUCTION(vcmpequw128, VX128_R(6, 512), VX128_R, General,
VX128_VD_VA_VB,
"Vector128 Compare Equal-to Unsigned Word"),
SCAN_INSTRUCTION(vmaxfp128, VX128(6, 640), VX128, General, 0,
"Vector128 Maximum Floating Point"),
SCAN_INSTRUCTION(vminfp128, VX128(6, 704), VX128, General, 0,
"Vector128 Minimum Floating Point"),
SCAN_INSTRUCTION(vmrghw128, VX128(6, 768), VX128, General, VX128_VD_VA_VB,
"Vector128 Merge High Word"),
SCAN_INSTRUCTION(vmrglw128, VX128(6, 832), VX128, General, VX128_VD_VA_VB,
"Vector128 Merge Low Word"),
SCAN_INSTRUCTION(vupkhsb128, VX128(6, 896), VX128, General, 0,
"Vector128 Unpack High Signed Byte"),
SCAN_INSTRUCTION(vupklsb128, VX128(6, 960), VX128, General, 0,
"Vector128 Unpack Low Signed Byte"),
};
#undef OP
#undef VX128
#undef VX128_1
#undef VX128_2
#undef VX128_3
#undef VX128_4
#undef VX128_5
#undef VX128_P
#undef FLAG
#undef INSTRUCTION
#undef EMPTY
} // namespace tables
} // namespace frontend
} // namespace cpu
} // namespace xe
#endif // XENIA_FRONTEND_PPC_INSTR_TABLES_H_
| 54.97366 | 80 | 0.652992 | [
"vector"
] |
6ddc86816f922d90cd49966e781bb664c8a35bf2 | 11,220 | h | C | YahooKeyKey-Source-1.1.2528/ModulePackages/OVOFAntiZhuyinwen/OVOFAntiZhuyinwen.h | linpc/yKeyKey | 81e05f070c070af65cac21e8da28ca4ff2d58905 | [
"BSD-3-Clause"
] | 31 | 2019-05-28T09:08:09.000Z | 2022-02-21T02:19:21.000Z | YahooKeyKey-Source-1.1.2528/ModulePackages/OVOFAntiZhuyinwen/OVOFAntiZhuyinwen.h | mhtxi3d/KeyKey | 24a21491398069317879ba07c95d9b0056806728 | [
"BSD-3-Clause"
] | null | null | null | YahooKeyKey-Source-1.1.2528/ModulePackages/OVOFAntiZhuyinwen/OVOFAntiZhuyinwen.h | mhtxi3d/KeyKey | 24a21491398069317879ba07c95d9b0056806728 | [
"BSD-3-Clause"
] | 19 | 2019-04-22T09:56:12.000Z | 2022-02-27T18:38:40.000Z | //
// OVOFAntiZhuyinwen.h
//
// Copyright (c) 2004-2010 The OpenVanilla Project (http://openvanilla.org)
// All rights reserved.
//
// 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 OVOFAntiZhuyinwen_h
#define OVOFAntiZhuyinwen_h
#if defined(__APPLE__)
#include <OpenVanilla/OpenVanilla.h>
#else
#include "OpenVanilla.h"
#endif
#include <vector>
namespace OpenVanilla {
using namespace std;
class OVOFAntiZhuyinwenContext : public OVEventHandlingContext {
public:
OVOFAntiZhuyinwenContext()
{
#ifndef _MSC_VER
m_bopomofo.push_back("ㄅ");
m_bopomofo.push_back("ㄆ");
m_bopomofo.push_back("ㄇ");
m_bopomofo.push_back("ㄈ");
m_bopomofo.push_back("ㄉ");
m_bopomofo.push_back("ㄊ");
m_bopomofo.push_back("ㄋ");
m_bopomofo.push_back("ㄌ");
m_bopomofo.push_back("ㄍ");
m_bopomofo.push_back("ㄎ");
m_bopomofo.push_back("ㄏ");
m_bopomofo.push_back("ㄐ");
m_bopomofo.push_back("ㄑ");
m_bopomofo.push_back("ㄒ");
m_bopomofo.push_back("ㄓ");
m_bopomofo.push_back("ㄔ");
m_bopomofo.push_back("ㄕ");
m_bopomofo.push_back("ㄖ");
m_bopomofo.push_back("ㄗ");
m_bopomofo.push_back("ㄘ");
m_bopomofo.push_back("ㄙ");
m_bopomofo.push_back("ㄧ");
m_bopomofo.push_back("ㄨ");
m_bopomofo.push_back("ㄩ");
m_bopomofo.push_back("ㄚ");
m_bopomofo.push_back("ㄛ");
m_bopomofo.push_back("ㄜ");
m_bopomofo.push_back("ㄝ");
m_bopomofo.push_back("ㄞ");
m_bopomofo.push_back("ㄟ");
m_bopomofo.push_back("ㄠ");
m_bopomofo.push_back("ㄡ");
m_bopomofo.push_back("ㄢ");
m_bopomofo.push_back("ㄣ");
m_bopomofo.push_back("ㄤ");
m_bopomofo.push_back("ㄥ");
m_bopomofo.push_back("ㄦ");
#else
m_bopomofo.push_back("\xE3\x84\x85");
m_bopomofo.push_back("\xE3\x84\x86");
m_bopomofo.push_back("\xE3\x84\x87");
m_bopomofo.push_back("\xE3\x84\x88");
m_bopomofo.push_back("\xE3\x84\x89");
m_bopomofo.push_back("\xE3\x84\x8A");
m_bopomofo.push_back("\xE3\x84\x8B");
m_bopomofo.push_back("\xE3\x84\x8C");
m_bopomofo.push_back("\xE3\x84\x8D");
m_bopomofo.push_back("\xE3\x84\x8E");
m_bopomofo.push_back("\xE3\x84\x8F");
m_bopomofo.push_back("\xE3\x84\x90");
m_bopomofo.push_back("\xE3\x84\x91");
m_bopomofo.push_back("\xE3\x84\x92");
m_bopomofo.push_back("\xE3\x84\x93");
m_bopomofo.push_back("\xE3\x84\x94");
m_bopomofo.push_back("\xE3\x84\x95");
m_bopomofo.push_back("\xE3\x84\x96");
m_bopomofo.push_back("\xE3\x84\x97");
m_bopomofo.push_back("\xE3\x84\x98");
m_bopomofo.push_back("\xE3\x84\x99");
m_bopomofo.push_back("\xE3\x84\xA7");
m_bopomofo.push_back("\xE3\x84\xA8");
m_bopomofo.push_back("\xE3\x84\xA9");
m_bopomofo.push_back("\xE3\x84\x9A");
m_bopomofo.push_back("\xE3\x84\x9B");
m_bopomofo.push_back("\xE3\x84\x9C");
m_bopomofo.push_back("\xE3\x84\x9D");
m_bopomofo.push_back("\xE3\x84\x9E");
m_bopomofo.push_back("\xE3\x84\x9F");
m_bopomofo.push_back("\xE3\x84\xA0");
m_bopomofo.push_back("\xE3\x84\xA1");
m_bopomofo.push_back("\xE3\x84\xA2");
m_bopomofo.push_back("\xE3\x84\xA3");
m_bopomofo.push_back("\xE3\x84\xA4");
m_bopomofo.push_back("\xE3\x84\xA5");
m_bopomofo.push_back("\xE3\x84\xA6");
#endif
}
virtual const string filterText(const string& inputText, OVLoaderService* loaderService);
virtual bool checkText(string theText);
private:
vector<string> m_bopomofo;
};
class OVOFAntiZhuyinwen : public OVOutputFilter {
public:
virtual const string localizedName(const string& locale)
{
#ifndef _MSC_VER
string tcname = "注音文過濾";
string scname = "注音文过滤";
#else
string tcname = "\xE6\xB3\xA8\xE9\x9F\xB3\xE6\x96\x87\xE9\x81\x8E\xE6\xBF\xBE";
string scname = "\xE6\xB3\xA8\xE9\x9F\xB3\xE6\x96\x87\xE8\xBF\x87\xE6\xBB\xA4";
#endif
if (locale == "zh_TW" || locale == "zh-hant")
return tcname;
else if (locale == "zh_CN" || locale == "zh-hans")
return scname;
else
return string("Anti-Zhuyinwen");
}
virtual const string identifier() const
{
return "OVOFAntiZhuyinwen";
}
virtual OVEventHandlingContext* createContext()
{
return new OVOFAntiZhuyinwenContext();
}
};
class OVOFAntiZhuyinwenReselectContext : public OVEventHandlingContext {
public:
OVOFAntiZhuyinwenReselectContext(OVKeyValueDataTableInterface* dataTable)
: m_dataTable(dataTable)
{
}
virtual bool handleKey(OVKey* key, OVTextBuffer* readingText, OVTextBuffer* composingText, OVCandidateService* candidateService, OVLoaderService* loaderService)
{
return false;
}
virtual bool handleDirectText(const string& text, OVTextBuffer* readingText, OVTextBuffer* composingText, OVCandidateService* candidateService, OVLoaderService* loaderService)
{
if (!text.size())
return false;
m_characters = OVUTF8Helper::SplitStringByCodePoint(text);
m_currentChar = m_characters.end();
for (vector<string>::iterator iter = m_characters.begin() ; iter != m_characters.end() ; ++iter) {
string current = *iter;
vector<string> results;
results = m_dataTable->valuesForKey(current);
loaderService->logger("process") << current << ": " << results.size() << endl;
if (results.size()) {
m_currentChar = iter;
OVOneDimensionalCandidatePanel* panel = candidateService->useVerticalCandidatePanel();
OVCandidateList* list = panel->candidateList();
list->addCandidates(results);
panel->setCandidatesPerPage(6);
panel->show();
panel->updateDisplay();
panel->yieldToCandidateEventHandler();
composingText->setText(text);
composingText->updateDisplay();
composingText->setCursorPosition((size_t)(iter - m_characters.begin()));
string locale = loaderService->locale();
#ifndef _MSC_VER
if (locale == "zh_TW" || locale == "zh-hant")
loaderService->notify("啟動注音文校正功能");
else if (locale == "zh_CN" || locale == "zh-hans")
loaderService->notify("启动注音文校正功能");
#else
if (locale == "zh_TW" || locale == "zh-hant")
loaderService->notify("\xE5\x95\x9F\xE5\x8B\x95\xE6\xB3\xA8\xE9\x9F\xB3\xE6\x96\x87\xE6\xA0\xA1\xE6\xAD\xA3\xE5\x8A\x9F\xE8\x83\xBD");
else if (locale == "zh_CN" || locale == "zh-hans")
loaderService->notify("\xE5\x90\xAF\xE5\x8A\xA8\xE6\xB3\xA8\xE9\x9F\xB3\xE6\x96\x87\xE6\xA0\xA1\xE6\xAD\xA3\xE5\x8A\x9F\xE8\x83\xBD");
#endif
else
loaderService->notify("Zhuyinwen correction activated");
return true;
}
}
composingText->setText(text);
composingText->commit();
return true;
}
virtual void candidateCanceled(OVCandidateService* candidateService, OVTextBuffer* readingText, OVTextBuffer* composingText, OVLoaderService* loaderService)
{
composingText->setText(OVUTF8Helper::CombineCodePoints(m_characters));
composingText->commit();
}
virtual bool candidateSelected(OVCandidateService* candidateService, const string& text, size_t index, OVTextBuffer* readingText, OVTextBuffer* composingText, OVLoaderService* loaderService)
{
*m_currentChar = text;
composingText->setText(OVUTF8Helper::CombineCodePoints(m_characters));
composingText->commit();
return true;
}
virtual bool candidateNonPanelKeyReceived(OVCandidateService* candidateService, const OVKey* key, OVTextBuffer* readingText, OVTextBuffer* composingText, OVLoaderService* loaderService)
{
return false;
}
protected:
vector<string> m_characters;
vector<string>::iterator m_currentChar;
OVKeyValueDataTableInterface* m_dataTable;
};
class OVOFAntiZhuyinwenReselect : public OVAroundFilter {
public:
virtual const string localizedName(const string& locale)
{
#ifndef _MSC_VER
string tcname = "注音文校正";
string scname = "注音文校正";
#else
string tcname = "\xE6\xB3\xA8\xE9\x9F\xB3\xE6\x96\x87\xE6\xA0\xA1\xE6\xAD\xA3";
string scname = "\xE6\xB3\xA8\xE9\x9F\xB3\xE6\x96\x87\xE6\xA0\xA1\xE6\xAD\xA3";
#endif
if (locale == "zh_TW" || locale == "zh-hant")
return tcname;
else if (locale == "zh_CN" || locale == "zh-hans")
return scname;
else
return string("Zhuyinwen Correction");
}
virtual const string identifier() const
{
return "OVOFAntiZhuyinwenReselect";
}
virtual OVEventHandlingContext* createContext()
{
return new OVOFAntiZhuyinwenReselectContext(m_dataTable);
}
virtual bool initialize(OVPathInfo* pathInfo, OVLoaderService* loaderService)
{
m_dataTable = loaderService->CINDatabaseService()->createKeyValueDataTableInterface("OVOFAntiZhuyinwen-zhuyinwen-reverse-lookup-cin");
if (!m_dataTable) {
loaderService->logger(identifier()) << "Cannot find table: " << "OVOFAntiZhuyinwen-zhuyinwen-reverse-lookup-cin" << endl;
return false;
}
loaderService->logger(identifier()) << "Table loaded: " << "OVOFAntiZhuyinwen-zhuyinwen-reverse-lookup-cin" << endl;
return true;
}
virtual void finalize()
{
delete m_dataTable;
}
protected:
OVKeyValueDataTableInterface* m_dataTable;
};
};
#endif | 36.547231 | 198 | 0.629055 | [
"vector"
] |
6ddc9e1cc633af6dc777c1f7d1cbb010760016a2 | 1,770 | c | C | tests/perf/addloop.c | divyeshbalar/libyang | 1df4458d289beaf223ea6fe97ba717fe89d12db8 | [
"BSD-3-Clause"
] | null | null | null | tests/perf/addloop.c | divyeshbalar/libyang | 1df4458d289beaf223ea6fe97ba717fe89d12db8 | [
"BSD-3-Clause"
] | null | null | null | tests/perf/addloop.c | divyeshbalar/libyang | 1df4458d289beaf223ea6fe97ba717fe89d12db8 | [
"BSD-3-Clause"
] | null | null | null | /**
* @file addloop.h
* @author Radek Krejci <rkrejci@cesnet.cz>
* @brief performance test - adding data.
*
* Copyright (c) 2016 CESNET, z.s.p.o.
*
* This source code is licensed under BSD 3-Clause 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://opensource.org/licenses/BSD-3-Clause
*/
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <libyang/libyang.h>
int main(int argc, char *argv[])
{
int fd, i;
struct ly_ctx *ctx = NULL;
char buf[30];
struct lyd_node *data = NULL, *next;
const struct lys_module *mod;
/* libyang context */
ctx = ly_ctx_new(NULL);
if (!ctx) {
fprintf(stderr, "Failed to create context.\n");
return 1;
}
/* schema */
if (!(mod = lys_parse_path(ctx, argv[1], LYS_IN_YIN))) {
fprintf(stderr, "Failed to load data model.\n");
goto cleanup;
}
/* data */
data = NULL;
fd = open("./addloop_result.xml", O_WRONLY | O_CREAT, 0666);
data = NULL;
for(i = 1; i <= 5000; i++) {
next = lyd_new(NULL, mod, "ptest1");
// if (i == 2091) {sprintf(buf, "%d", 1);} else {
sprintf(buf, "%d", i);//}
lyd_new_leaf(next, mod, "index", buf);
lyd_new_leaf(next, mod, "p1", buf);
if (!data) {
data = next;
} else {
lyd_insert_after(data->prev, next);
}
if (lyd_validate(&data, LYD_OPT_CONFIG, NULL)) {
goto cleanup;
}
//lyd_print_fd(fd, data, LYD_XML);
}
lyd_print_fd(fd, data, LYD_XML, LYP_WITHSIBLINGS | LYP_FORMAT);
close(fd);
cleanup:
lyd_free_withsiblings(data);
ly_ctx_destroy(ctx, NULL);
return 0;
}
| 23.918919 | 75 | 0.60565 | [
"model"
] |
6ddcc052d24d4b6a0351d974811cc52bf4905fb1 | 54,517 | c | C | mi/mioverlay.c | freedesktop-unofficial-mirror/xorg__xprint | 1e67eb53a5ecdfa2ca503a45366c77f5012db036 | [
"X11"
] | 2 | 2016-05-08T18:39:05.000Z | 2018-11-01T06:58:35.000Z | mi/mioverlay.c | freedesktop-unofficial-mirror/xorg__xprint | 1e67eb53a5ecdfa2ca503a45366c77f5012db036 | [
"X11"
] | null | null | null | mi/mioverlay.c | freedesktop-unofficial-mirror/xorg__xprint | 1e67eb53a5ecdfa2ca503a45366c77f5012db036 | [
"X11"
] | 1 | 2021-07-23T01:42:38.000Z | 2021-07-23T01:42:38.000Z |
#ifdef HAVE_DIX_CONFIG_H
#include <dix-config.h>
#endif
#include <X11/X.h>
#include "scrnintstr.h"
#include "validate.h"
#include "windowstr.h"
#include "mi.h"
#include "gcstruct.h"
#include "regionstr.h"
#include "privates.h"
#include "mivalidate.h"
#include "mioverlay.h"
#include "migc.h"
#include "globals.h"
typedef struct {
RegionRec exposed;
RegionRec borderExposed;
RegionPtr borderVisible;
DDXPointRec oldAbsCorner;
} miOverlayValDataRec, *miOverlayValDataPtr;
typedef struct _TreeRec {
WindowPtr pWin;
struct _TreeRec *parent;
struct _TreeRec *firstChild;
struct _TreeRec *lastChild;
struct _TreeRec *prevSib;
struct _TreeRec *nextSib;
RegionRec borderClip;
RegionRec clipList;
unsigned visibility;
miOverlayValDataPtr valdata;
} miOverlayTreeRec, *miOverlayTreePtr;
typedef struct {
miOverlayTreePtr tree;
} miOverlayWindowRec, *miOverlayWindowPtr;
typedef struct {
CloseScreenProcPtr CloseScreen;
CreateWindowProcPtr CreateWindow;
DestroyWindowProcPtr DestroyWindow;
UnrealizeWindowProcPtr UnrealizeWindow;
RealizeWindowProcPtr RealizeWindow;
miOverlayTransFunc MakeTransparent;
miOverlayInOverlayFunc InOverlay;
Bool underlayMarked;
Bool copyUnderlay;
} miOverlayScreenRec, *miOverlayScreenPtr;
static DevPrivateKey miOverlayWindowKey = &miOverlayWindowKey;
static DevPrivateKey miOverlayScreenKey = &miOverlayScreenKey;
static void RebuildTree(WindowPtr);
static Bool HasUnderlayChildren(WindowPtr);
static void MarkUnderlayWindow(WindowPtr);
static Bool CollectUnderlayChildrenRegions(WindowPtr, RegionPtr);
static Bool miOverlayCloseScreen(int, ScreenPtr);
static Bool miOverlayCreateWindow(WindowPtr);
static Bool miOverlayDestroyWindow(WindowPtr);
static Bool miOverlayUnrealizeWindow(WindowPtr);
static Bool miOverlayRealizeWindow(WindowPtr);
static void miOverlayMarkWindow(WindowPtr);
static void miOverlayReparentWindow(WindowPtr, WindowPtr);
static void miOverlayRestackWindow(WindowPtr, WindowPtr);
static Bool miOverlayMarkOverlappedWindows(WindowPtr, WindowPtr, WindowPtr*);
static void miOverlayMarkUnrealizedWindow(WindowPtr, WindowPtr, Bool);
static int miOverlayValidateTree(WindowPtr, WindowPtr, VTKind);
static void miOverlayHandleExposures(WindowPtr);
static void miOverlayMoveWindow(WindowPtr, int, int, WindowPtr, VTKind);
static void miOverlayWindowExposures(WindowPtr, RegionPtr, RegionPtr);
static void miOverlayResizeWindow(WindowPtr, int, int, unsigned int,
unsigned int, WindowPtr);
static void miOverlayClearToBackground(WindowPtr, int, int, int, int, Bool);
#ifdef SHAPE
static void miOverlaySetShape(WindowPtr);
#endif
static void miOverlayChangeBorderWidth(WindowPtr, unsigned int);
#define MIOVERLAY_GET_SCREEN_PRIVATE(pScreen) ((miOverlayScreenPtr) \
dixLookupPrivate(&(pScreen)->devPrivates, miOverlayScreenKey))
#define MIOVERLAY_GET_WINDOW_PRIVATE(pWin) ((miOverlayWindowPtr) \
dixLookupPrivate(&(pWin)->devPrivates, miOverlayWindowKey))
#define MIOVERLAY_GET_WINDOW_TREE(pWin) \
(MIOVERLAY_GET_WINDOW_PRIVATE(pWin)->tree)
#define IN_UNDERLAY(w) MIOVERLAY_GET_WINDOW_TREE(w)
#define IN_OVERLAY(w) !MIOVERLAY_GET_WINDOW_TREE(w)
#define MARK_OVERLAY(w) miMarkWindow(w)
#define MARK_UNDERLAY(w) MarkUnderlayWindow(w)
#define HasParentRelativeBorder(w) (!(w)->borderIsPixel && \
HasBorder(w) && \
(w)->backgroundState == ParentRelative)
_X_EXPORT Bool
miInitOverlay(
ScreenPtr pScreen,
miOverlayInOverlayFunc inOverlayFunc,
miOverlayTransFunc transFunc
){
miOverlayScreenPtr pScreenPriv;
if(!inOverlayFunc || !transFunc) return FALSE;
if(!dixRequestPrivate(miOverlayWindowKey, sizeof(miOverlayWindowRec)))
return FALSE;
if(!(pScreenPriv = xalloc(sizeof(miOverlayScreenRec))))
return FALSE;
dixSetPrivate(&pScreen->devPrivates, miOverlayScreenKey, pScreenPriv);
pScreenPriv->InOverlay = inOverlayFunc;
pScreenPriv->MakeTransparent = transFunc;
pScreenPriv->underlayMarked = FALSE;
pScreenPriv->CloseScreen = pScreen->CloseScreen;
pScreenPriv->CreateWindow = pScreen->CreateWindow;
pScreenPriv->DestroyWindow = pScreen->DestroyWindow;
pScreenPriv->UnrealizeWindow = pScreen->UnrealizeWindow;
pScreenPriv->RealizeWindow = pScreen->RealizeWindow;
pScreen->CloseScreen = miOverlayCloseScreen;
pScreen->CreateWindow = miOverlayCreateWindow;
pScreen->DestroyWindow = miOverlayDestroyWindow;
pScreen->UnrealizeWindow = miOverlayUnrealizeWindow;
pScreen->RealizeWindow = miOverlayRealizeWindow;
pScreen->ReparentWindow = miOverlayReparentWindow;
pScreen->RestackWindow = miOverlayRestackWindow;
pScreen->MarkOverlappedWindows = miOverlayMarkOverlappedWindows;
pScreen->MarkUnrealizedWindow = miOverlayMarkUnrealizedWindow;
pScreen->ValidateTree = miOverlayValidateTree;
pScreen->HandleExposures = miOverlayHandleExposures;
pScreen->MoveWindow = miOverlayMoveWindow;
pScreen->WindowExposures = miOverlayWindowExposures;
pScreen->ResizeWindow = miOverlayResizeWindow;
pScreen->MarkWindow = miOverlayMarkWindow;
pScreen->ClearToBackground = miOverlayClearToBackground;
#ifdef SHAPE
pScreen->SetShape = miOverlaySetShape;
#endif
pScreen->ChangeBorderWidth = miOverlayChangeBorderWidth;
return TRUE;
}
static Bool
miOverlayCloseScreen(int i, ScreenPtr pScreen)
{
miOverlayScreenPtr pScreenPriv = MIOVERLAY_GET_SCREEN_PRIVATE(pScreen);
pScreen->CloseScreen = pScreenPriv->CloseScreen;
pScreen->CreateWindow = pScreenPriv->CreateWindow;
pScreen->DestroyWindow = pScreenPriv->DestroyWindow;
pScreen->UnrealizeWindow = pScreenPriv->UnrealizeWindow;
pScreen->RealizeWindow = pScreenPriv->RealizeWindow;
xfree(pScreenPriv);
return (*pScreen->CloseScreen)(i, pScreen);
}
static Bool
miOverlayCreateWindow(WindowPtr pWin)
{
ScreenPtr pScreen = pWin->drawable.pScreen;
miOverlayScreenPtr pScreenPriv = MIOVERLAY_GET_SCREEN_PRIVATE(pScreen);
miOverlayWindowPtr pWinPriv = MIOVERLAY_GET_WINDOW_PRIVATE(pWin);
miOverlayTreePtr pTree = NULL;
Bool result = TRUE;
pWinPriv->tree = NULL;
if(!pWin->parent || !((*pScreenPriv->InOverlay)(pWin))) {
if(!(pTree = (miOverlayTreePtr)xcalloc(1, sizeof(miOverlayTreeRec))))
return FALSE;
}
if(pScreenPriv->CreateWindow) {
pScreen->CreateWindow = pScreenPriv->CreateWindow;
result = (*pScreen->CreateWindow)(pWin);
pScreen->CreateWindow = miOverlayCreateWindow;
}
if (pTree) {
if(result) {
pTree->pWin = pWin;
pTree->visibility = VisibilityNotViewable;
pWinPriv->tree = pTree;
if(pWin->parent) {
REGION_NULL(pScreen, &(pTree->borderClip));
REGION_NULL(pScreen, &(pTree->clipList));
RebuildTree(pWin);
} else {
BoxRec fullBox;
fullBox.x1 = 0;
fullBox.y1 = 0;
fullBox.x2 = pScreen->width;
fullBox.y2 = pScreen->height;
REGION_INIT(pScreen, &(pTree->borderClip), &fullBox, 1);
REGION_INIT(pScreen, &(pTree->clipList), &fullBox, 1);
}
} else xfree(pTree);
}
return TRUE;
}
static Bool
miOverlayDestroyWindow(WindowPtr pWin)
{
ScreenPtr pScreen = pWin->drawable.pScreen;
miOverlayScreenPtr pScreenPriv = MIOVERLAY_GET_SCREEN_PRIVATE(pScreen);
miOverlayTreePtr pTree = MIOVERLAY_GET_WINDOW_TREE(pWin);
Bool result = TRUE;
if (pTree) {
if(pTree->prevSib)
pTree->prevSib->nextSib = pTree->nextSib;
else if(pTree->parent)
pTree->parent->firstChild = pTree->nextSib;
if(pTree->nextSib)
pTree->nextSib->prevSib = pTree->prevSib;
else if(pTree->parent)
pTree->parent->lastChild = pTree->prevSib;
REGION_UNINIT(pScreen, &(pTree->borderClip));
REGION_UNINIT(pScreen, &(pTree->clipList));
xfree(pTree);
}
if(pScreenPriv->DestroyWindow) {
pScreen->DestroyWindow = pScreenPriv->DestroyWindow;
result = (*pScreen->DestroyWindow)(pWin);
pScreen->DestroyWindow = miOverlayDestroyWindow;
}
return result;
}
static Bool
miOverlayUnrealizeWindow(WindowPtr pWin)
{
ScreenPtr pScreen = pWin->drawable.pScreen;
miOverlayScreenPtr pScreenPriv = MIOVERLAY_GET_SCREEN_PRIVATE(pScreen);
miOverlayTreePtr pTree = MIOVERLAY_GET_WINDOW_TREE(pWin);
Bool result = TRUE;
if(pTree) pTree->visibility = VisibilityNotViewable;
if(pScreenPriv->UnrealizeWindow) {
pScreen->UnrealizeWindow = pScreenPriv->UnrealizeWindow;
result = (*pScreen->UnrealizeWindow)(pWin);
pScreen->UnrealizeWindow = miOverlayUnrealizeWindow;
}
return result;
}
static Bool
miOverlayRealizeWindow(WindowPtr pWin)
{
ScreenPtr pScreen = pWin->drawable.pScreen;
miOverlayScreenPtr pScreenPriv = MIOVERLAY_GET_SCREEN_PRIVATE(pScreen);
Bool result = TRUE;
if(pScreenPriv->RealizeWindow) {
pScreen->RealizeWindow = pScreenPriv->RealizeWindow;
result = (*pScreen->RealizeWindow)(pWin);
pScreen->RealizeWindow = miOverlayRealizeWindow;
}
/* we only need to catch the root window realization */
if(result && !pWin->parent && !((*pScreenPriv->InOverlay)(pWin)))
{
BoxRec box;
box.x1 = box.y1 = 0;
box.x2 = pWin->drawable.width;
box.y2 = pWin->drawable.height;
(*pScreenPriv->MakeTransparent)(pScreen, 1, &box);
}
return result;
}
static void
miOverlayReparentWindow(WindowPtr pWin, WindowPtr pPriorParent)
{
if(IN_UNDERLAY(pWin) || HasUnderlayChildren(pWin)) {
/* This could probably be more optimal */
RebuildTree(WindowTable[pWin->drawable.pScreen->myNum]->firstChild);
}
}
static void
miOverlayRestackWindow(WindowPtr pWin, WindowPtr oldNextSib)
{
if(IN_UNDERLAY(pWin) || HasUnderlayChildren(pWin)) {
/* This could probably be more optimal */
RebuildTree(pWin);
}
}
static Bool
miOverlayMarkOverlappedWindows(
WindowPtr pWin,
WindowPtr pFirst,
WindowPtr *pLayerWin
){
ScreenPtr pScreen = pWin->drawable.pScreen;
WindowPtr pChild, pLast;
Bool overMarked, underMarked, doUnderlay, markAll;
miOverlayTreePtr pTree = NULL, tLast, tChild;
BoxPtr box;
overMarked = underMarked = markAll = FALSE;
if(pLayerWin) *pLayerWin = pWin; /* hah! */
doUnderlay = (IN_UNDERLAY(pWin) || HasUnderlayChildren(pWin));
box = REGION_EXTENTS(pScreen, &pWin->borderSize);
if((pChild = pFirst)) {
pLast = pChild->parent->lastChild;
while (1) {
if (pChild == pWin) markAll = TRUE;
if(doUnderlay && IN_UNDERLAY(pChild))
pTree = MIOVERLAY_GET_WINDOW_TREE(pChild);
if(pChild->viewable) {
if (REGION_BROKEN (pScreen, &pChild->winSize))
SetWinSize (pChild);
if (REGION_BROKEN (pScreen, &pChild->borderSize))
SetBorderSize (pChild);
if (markAll ||
RECT_IN_REGION(pScreen, &pChild->borderSize, box))
{
MARK_OVERLAY(pChild);
overMarked = TRUE;
if(doUnderlay && IN_UNDERLAY(pChild)) {
MARK_UNDERLAY(pChild);
underMarked = TRUE;
}
if (pChild->firstChild) {
pChild = pChild->firstChild;
continue;
}
}
}
while (!pChild->nextSib && (pChild != pLast)) {
pChild = pChild->parent;
if(doUnderlay && IN_UNDERLAY(pChild))
pTree = MIOVERLAY_GET_WINDOW_TREE(pChild);
}
if(pChild == pWin) markAll = FALSE;
if (pChild == pLast) break;
pChild = pChild->nextSib;
}
if(overMarked)
MARK_OVERLAY(pWin->parent);
}
if(doUnderlay && !pTree) {
if(!(pTree = MIOVERLAY_GET_WINDOW_TREE(pWin))) {
pChild = pWin->lastChild;
while(1) {
if((pTree = MIOVERLAY_GET_WINDOW_TREE(pChild)))
break;
if(pChild->lastChild) {
pChild = pChild->lastChild;
continue;
}
while(!pChild->prevSib) pChild = pChild->parent;
pChild = pChild->prevSib;
}
}
}
if(pTree && pTree->nextSib) {
tChild = pTree->parent->lastChild;
tLast = pTree->nextSib;
while(1) {
if(tChild->pWin->viewable) {
if (REGION_BROKEN (pScreen, &tChild->pWin->winSize))
SetWinSize (tChild->pWin);
if (REGION_BROKEN (pScreen, &tChild->pWin->borderSize))
SetBorderSize (tChild->pWin);
if(RECT_IN_REGION(pScreen, &(tChild->pWin->borderSize), box))
{
MARK_UNDERLAY(tChild->pWin);
underMarked = TRUE;
}
}
if(tChild->lastChild) {
tChild = tChild->lastChild;
continue;
}
while(!tChild->prevSib && (tChild != tLast))
tChild = tChild->parent;
if(tChild == tLast) break;
tChild = tChild->prevSib;
}
}
if(underMarked) {
MARK_UNDERLAY(pTree->parent->pWin);
MIOVERLAY_GET_SCREEN_PRIVATE(pScreen)->underlayMarked = TRUE;
}
return (underMarked || overMarked);
}
static void
miOverlayComputeClips(
WindowPtr pParent,
RegionPtr universe,
VTKind kind,
RegionPtr exposed
){
ScreenPtr pScreen = pParent->drawable.pScreen;
int oldVis, newVis, dx, dy;
BoxRec borderSize;
RegionPtr borderVisible;
RegionRec childUniverse, childUnion;
miOverlayTreePtr tParent = MIOVERLAY_GET_WINDOW_TREE(pParent);
miOverlayTreePtr tChild;
Bool overlap;
borderSize.x1 = pParent->drawable.x - wBorderWidth(pParent);
borderSize.y1 = pParent->drawable.y - wBorderWidth(pParent);
dx = (int) pParent->drawable.x + (int) pParent->drawable.width +
wBorderWidth(pParent);
if (dx > 32767) dx = 32767;
borderSize.x2 = dx;
dy = (int) pParent->drawable.y + (int) pParent->drawable.height +
wBorderWidth(pParent);
if (dy > 32767) dy = 32767;
borderSize.y2 = dy;
oldVis = tParent->visibility;
switch (RECT_IN_REGION( pScreen, universe, &borderSize)) {
case rgnIN:
newVis = VisibilityUnobscured;
break;
case rgnPART:
newVis = VisibilityPartiallyObscured;
#ifdef SHAPE
{
RegionPtr pBounding;
if ((pBounding = wBoundingShape (pParent))) {
switch (miShapedWindowIn (pScreen, universe, pBounding,
&borderSize,
pParent->drawable.x,
pParent->drawable.y))
{
case rgnIN:
newVis = VisibilityUnobscured;
break;
case rgnOUT:
newVis = VisibilityFullyObscured;
break;
}
}
}
#endif
break;
default:
newVis = VisibilityFullyObscured;
break;
}
tParent->visibility = newVis;
dx = pParent->drawable.x - tParent->valdata->oldAbsCorner.x;
dy = pParent->drawable.y - tParent->valdata->oldAbsCorner.y;
switch (kind) {
case VTMap:
case VTStack:
case VTUnmap:
break;
case VTMove:
if ((oldVis == newVis) &&
((oldVis == VisibilityFullyObscured) ||
(oldVis == VisibilityUnobscured)))
{
tChild = tParent;
while (1) {
if (tChild->pWin->viewable) {
if (tChild->visibility != VisibilityFullyObscured) {
REGION_TRANSLATE( pScreen, &tChild->borderClip, dx, dy);
REGION_TRANSLATE( pScreen, &tChild->clipList, dx, dy);
tChild->pWin->drawable.serialNumber =
NEXT_SERIAL_NUMBER;
if (pScreen->ClipNotify)
(* pScreen->ClipNotify) (tChild->pWin, dx, dy);
}
if (tChild->valdata) {
REGION_NULL(pScreen, &tChild->valdata->borderExposed);
if (HasParentRelativeBorder(tChild->pWin)){
REGION_SUBTRACT(pScreen,
&tChild->valdata->borderExposed,
&tChild->borderClip,
&tChild->pWin->winSize);
}
REGION_NULL(pScreen, &tChild->valdata->exposed);
}
if (tChild->firstChild) {
tChild = tChild->firstChild;
continue;
}
}
while (!tChild->nextSib && (tChild != tParent))
tChild = tChild->parent;
if (tChild == tParent)
break;
tChild = tChild->nextSib;
}
return;
}
/* fall through */
default:
if (dx || dy) {
REGION_TRANSLATE( pScreen, &tParent->borderClip, dx, dy);
REGION_TRANSLATE( pScreen, &tParent->clipList, dx, dy);
}
break;
case VTBroken:
REGION_EMPTY (pScreen, &tParent->borderClip);
REGION_EMPTY (pScreen, &tParent->clipList);
break;
}
borderVisible = tParent->valdata->borderVisible;
REGION_NULL(pScreen, &tParent->valdata->borderExposed);
REGION_NULL(pScreen, &tParent->valdata->exposed);
if (HasBorder (pParent)) {
if (borderVisible) {
REGION_SUBTRACT( pScreen, exposed, universe, borderVisible);
REGION_DESTROY( pScreen, borderVisible);
} else
REGION_SUBTRACT( pScreen, exposed, universe, &tParent->borderClip);
if (HasParentRelativeBorder(pParent) && (dx || dy))
REGION_SUBTRACT( pScreen, &tParent->valdata->borderExposed,
universe, &pParent->winSize);
else
REGION_SUBTRACT( pScreen, &tParent->valdata->borderExposed,
exposed, &pParent->winSize);
REGION_COPY( pScreen, &tParent->borderClip, universe);
REGION_INTERSECT( pScreen, universe, universe, &pParent->winSize);
}
else
REGION_COPY( pScreen, &tParent->borderClip, universe);
if ((tChild = tParent->firstChild) && pParent->mapped) {
REGION_NULL(pScreen, &childUniverse);
REGION_NULL(pScreen, &childUnion);
for (; tChild; tChild = tChild->nextSib) {
if (tChild->pWin->viewable)
REGION_APPEND( pScreen, &childUnion, &tChild->pWin->borderSize);
}
REGION_VALIDATE( pScreen, &childUnion, &overlap);
for (tChild = tParent->firstChild;
tChild;
tChild = tChild->nextSib)
{
if (tChild->pWin->viewable) {
if (tChild->valdata) {
REGION_INTERSECT( pScreen, &childUniverse, universe,
&tChild->pWin->borderSize);
miOverlayComputeClips (tChild->pWin, &childUniverse,
kind, exposed);
}
if (overlap)
REGION_SUBTRACT( pScreen, universe, universe,
&tChild->pWin->borderSize);
}
}
if (!overlap)
REGION_SUBTRACT( pScreen, universe, universe, &childUnion);
REGION_UNINIT( pScreen, &childUnion);
REGION_UNINIT( pScreen, &childUniverse);
}
if (oldVis == VisibilityFullyObscured ||
oldVis == VisibilityNotViewable)
{
REGION_COPY( pScreen, &tParent->valdata->exposed, universe);
}
else if (newVis != VisibilityFullyObscured &&
newVis != VisibilityNotViewable)
{
REGION_SUBTRACT( pScreen, &tParent->valdata->exposed,
universe, &tParent->clipList);
}
/* HACK ALERT - copying contents of regions, instead of regions */
{
RegionRec tmp;
tmp = tParent->clipList;
tParent->clipList = *universe;
*universe = tmp;
}
pParent->drawable.serialNumber = NEXT_SERIAL_NUMBER;
if (pScreen->ClipNotify)
(* pScreen->ClipNotify) (pParent, dx, dy);
}
static void
miOverlayMarkWindow(WindowPtr pWin)
{
miOverlayTreePtr pTree = NULL;
WindowPtr pChild, pGrandChild;
miMarkWindow(pWin);
/* look for UnmapValdata among immediate children */
if(!(pChild = pWin->firstChild)) return;
for( ; pChild; pChild = pChild->nextSib) {
if(pChild->valdata == UnmapValData) {
if(IN_UNDERLAY(pChild)) {
pTree = MIOVERLAY_GET_WINDOW_TREE(pChild);
pTree->valdata = (miOverlayValDataPtr)UnmapValData;
continue;
} else {
if(!(pGrandChild = pChild->firstChild))
continue;
while(1) {
if(IN_UNDERLAY(pGrandChild)) {
pTree = MIOVERLAY_GET_WINDOW_TREE(pGrandChild);
pTree->valdata = (miOverlayValDataPtr)UnmapValData;
} else if(pGrandChild->firstChild) {
pGrandChild = pGrandChild->firstChild;
continue;
}
while(!pGrandChild->nextSib && (pGrandChild != pChild))
pGrandChild = pGrandChild->parent;
if(pChild == pGrandChild) break;
pGrandChild = pGrandChild->nextSib;
}
}
}
}
if(pTree) {
MARK_UNDERLAY(pTree->parent->pWin);
MIOVERLAY_GET_SCREEN_PRIVATE(
pWin->drawable.pScreen)->underlayMarked = TRUE;
}
}
static void
miOverlayMarkUnrealizedWindow(
WindowPtr pChild,
WindowPtr pWin,
Bool fromConfigure
){
if ((pChild != pWin) || fromConfigure) {
miOverlayTreePtr pTree;
REGION_EMPTY(pChild->drawable.pScreen, &pChild->clipList);
if (pChild->drawable.pScreen->ClipNotify)
(* pChild->drawable.pScreen->ClipNotify)(pChild, 0, 0);
REGION_EMPTY(pChild->drawable.pScreen, &pChild->borderClip);
if((pTree = MIOVERLAY_GET_WINDOW_TREE(pChild))) {
if(pTree->valdata != (miOverlayValDataPtr)UnmapValData) {
REGION_EMPTY(pChild->drawable.pScreen, &pTree->clipList);
REGION_EMPTY(pChild->drawable.pScreen, &pTree->borderClip);
}
}
}
}
static int
miOverlayValidateTree(
WindowPtr pParent,
WindowPtr pChild, /* first child effected */
VTKind kind
){
ScreenPtr pScreen = pParent->drawable.pScreen;
miOverlayScreenPtr pPriv = MIOVERLAY_GET_SCREEN_PRIVATE(pScreen);
RegionRec totalClip, childClip, exposed;
miOverlayTreePtr tParent, tChild, tWin;
Bool overlap;
WindowPtr newParent;
if(!pPriv->underlayMarked)
goto SKIP_UNDERLAY;
if (!pChild) pChild = pParent->firstChild;
REGION_NULL(pScreen, &totalClip);
REGION_NULL(pScreen, &childClip);
REGION_NULL(pScreen, &exposed);
newParent = pParent;
while(IN_OVERLAY(newParent))
newParent = newParent->parent;
tParent = MIOVERLAY_GET_WINDOW_TREE(newParent);
if(IN_UNDERLAY(pChild))
tChild = MIOVERLAY_GET_WINDOW_TREE(pChild);
else
tChild = tParent->firstChild;
if (REGION_BROKEN (pScreen, &tParent->clipList) &&
!REGION_BROKEN (pScreen, &tParent->borderClip))
{
kind = VTBroken;
REGION_COPY (pScreen, &totalClip, &tParent->borderClip);
REGION_INTERSECT (pScreen, &totalClip, &totalClip,
&tParent->pWin->winSize);
for (tWin = tParent->firstChild; tWin != tChild; tWin = tWin->nextSib) {
if (tWin->pWin->viewable)
REGION_SUBTRACT (pScreen, &totalClip, &totalClip,
&tWin->pWin->borderSize);
}
REGION_EMPTY (pScreen, &tParent->clipList);
} else {
for(tWin = tChild; tWin; tWin = tWin->nextSib) {
if(tWin->valdata)
REGION_APPEND(pScreen, &totalClip, &tWin->borderClip);
}
REGION_VALIDATE(pScreen, &totalClip, &overlap);
}
if(kind != VTStack)
REGION_UNION(pScreen, &totalClip, &totalClip, &tParent->clipList);
for(tWin = tChild; tWin; tWin = tWin->nextSib) {
if(tWin->valdata) {
if(tWin->pWin->viewable) {
REGION_INTERSECT(pScreen, &childClip, &totalClip,
&tWin->pWin->borderSize);
miOverlayComputeClips(tWin->pWin, &childClip, kind, &exposed);
REGION_SUBTRACT(pScreen, &totalClip, &totalClip,
&tWin->pWin->borderSize);
} else { /* Means we are unmapping */
REGION_EMPTY(pScreen, &tWin->clipList);
REGION_EMPTY( pScreen, &tWin->borderClip);
tWin->valdata = NULL;
}
}
}
REGION_UNINIT(pScreen, &childClip);
if(!((*pPriv->InOverlay)(newParent))) {
REGION_NULL(pScreen, &tParent->valdata->exposed);
REGION_NULL(pScreen, &tParent->valdata->borderExposed);
}
switch (kind) {
case VTStack:
break;
default:
if(!((*pPriv->InOverlay)(newParent)))
REGION_SUBTRACT(pScreen, &tParent->valdata->exposed, &totalClip,
&tParent->clipList);
/* fall through */
case VTMap:
REGION_COPY( pScreen, &tParent->clipList, &totalClip);
if(!((*pPriv->InOverlay)(newParent)))
newParent->drawable.serialNumber = NEXT_SERIAL_NUMBER;
break;
}
REGION_UNINIT( pScreen, &totalClip);
REGION_UNINIT( pScreen, &exposed);
SKIP_UNDERLAY:
miValidateTree(pParent, pChild, kind);
return 1;
}
static void
miOverlayHandleExposures(WindowPtr pWin)
{
ScreenPtr pScreen = pWin->drawable.pScreen;
miOverlayScreenPtr pPriv = MIOVERLAY_GET_SCREEN_PRIVATE(pScreen);
WindowPtr pChild;
ValidatePtr val;
void (* WindowExposures)(WindowPtr, RegionPtr, RegionPtr);
WindowExposures = pWin->drawable.pScreen->WindowExposures;
if(pPriv->underlayMarked) {
miOverlayTreePtr pTree;
miOverlayValDataPtr mival;
pChild = pWin;
while(IN_OVERLAY(pChild))
pChild = pChild->parent;
pTree = MIOVERLAY_GET_WINDOW_TREE(pChild);
while (1) {
if((mival = pTree->valdata)) {
if(!((*pPriv->InOverlay)(pTree->pWin))) {
if (REGION_NOTEMPTY(pScreen, &mival->borderExposed)) {
miPaintWindow(pTree->pWin, &mival->borderExposed,
PW_BORDER);
}
REGION_UNINIT(pScreen, &mival->borderExposed);
(*WindowExposures)(pTree->pWin,&mival->exposed,NullRegion);
REGION_UNINIT(pScreen, &mival->exposed);
}
xfree(mival);
pTree->valdata = NULL;
if (pTree->firstChild) {
pTree = pTree->firstChild;
continue;
}
}
while (!pTree->nextSib && (pTree->pWin != pChild))
pTree = pTree->parent;
if (pTree->pWin == pChild)
break;
pTree = pTree->nextSib;
}
pPriv->underlayMarked = FALSE;
}
pChild = pWin;
while (1) {
if ( (val = pChild->valdata) ) {
if(!((*pPriv->InOverlay)(pChild))) {
REGION_UNION(pScreen, &val->after.exposed, &val->after.exposed,
&val->after.borderExposed);
if (REGION_NOTEMPTY(pScreen, &val->after.exposed)) {
(*(MIOVERLAY_GET_SCREEN_PRIVATE(pScreen)->MakeTransparent))(
pScreen,
REGION_NUM_RECTS(&val->after.exposed),
REGION_RECTS(&val->after.exposed));
}
} else {
if (REGION_NOTEMPTY(pScreen, &val->after.borderExposed)) {
miPaintWindow(pChild, &val->after.borderExposed,
PW_BORDER);
}
(*WindowExposures)(pChild, &val->after.exposed, NullRegion);
}
REGION_UNINIT(pScreen, &val->after.borderExposed);
REGION_UNINIT(pScreen, &val->after.exposed);
xfree(val);
pChild->valdata = (ValidatePtr)NULL;
if (pChild->firstChild)
{
pChild = pChild->firstChild;
continue;
}
}
while (!pChild->nextSib && (pChild != pWin))
pChild = pChild->parent;
if (pChild == pWin)
break;
pChild = pChild->nextSib;
}
}
static void
miOverlayMoveWindow(
WindowPtr pWin,
int x,
int y,
WindowPtr pNextSib,
VTKind kind
){
ScreenPtr pScreen = pWin->drawable.pScreen;
miOverlayTreePtr pTree = MIOVERLAY_GET_WINDOW_TREE(pWin);
WindowPtr pParent, windowToValidate;
Bool WasViewable = (Bool)(pWin->viewable);
short bw;
RegionRec overReg, underReg;
DDXPointRec oldpt;
#ifdef DO_SAVE_UNDERS
Bool dosave = FALSE;
#endif
if (!(pParent = pWin->parent))
return ;
bw = wBorderWidth (pWin);
oldpt.x = pWin->drawable.x;
oldpt.y = pWin->drawable.y;
if (WasViewable) {
REGION_NULL(pScreen, &overReg);
REGION_NULL(pScreen, &underReg);
if(pTree) {
REGION_COPY(pScreen, &overReg, &pWin->borderClip);
REGION_COPY(pScreen, &underReg, &pTree->borderClip);
} else {
REGION_COPY(pScreen, &overReg, &pWin->borderClip);
CollectUnderlayChildrenRegions(pWin, &underReg);
}
(*pScreen->MarkOverlappedWindows)(pWin, pWin, NULL);
}
pWin->origin.x = x + (int)bw;
pWin->origin.y = y + (int)bw;
x = pWin->drawable.x = pParent->drawable.x + x + (int)bw;
y = pWin->drawable.y = pParent->drawable.y + y + (int)bw;
SetWinSize (pWin);
SetBorderSize (pWin);
(*pScreen->PositionWindow)(pWin, x, y);
windowToValidate = MoveWindowInStack(pWin, pNextSib);
ResizeChildrenWinSize(pWin, x - oldpt.x, y - oldpt.y, 0, 0);
if (WasViewable) {
miOverlayScreenPtr pPriv = MIOVERLAY_GET_SCREEN_PRIVATE(pScreen);
(*pScreen->MarkOverlappedWindows) (pWin, windowToValidate, NULL);
#ifdef DO_SAVE_UNDERS
if (DO_SAVE_UNDERS(pWin))
dosave = (*pScreen->ChangeSaveUnder)(pWin, windowToValidate);
#endif /* DO_SAVE_UNDERS */
(*pScreen->ValidateTree)(pWin->parent, NullWindow, kind);
if(REGION_NOTEMPTY(pScreen, &underReg)) {
pPriv->copyUnderlay = TRUE;
(* pWin->drawable.pScreen->CopyWindow)(pWin, oldpt, &underReg);
}
REGION_UNINIT(pScreen, &underReg);
if(REGION_NOTEMPTY(pScreen, &overReg)) {
pPriv->copyUnderlay = FALSE;
(* pWin->drawable.pScreen->CopyWindow)(pWin, oldpt, &overReg);
}
REGION_UNINIT(pScreen, &overReg);
(*pScreen->HandleExposures)(pWin->parent);
#ifdef DO_SAVE_UNDERS
if (dosave)
(*pScreen->PostChangeSaveUnder)(pWin, windowToValidate);
#endif /* DO_SAVE_UNDERS */
if (pScreen->PostValidateTree)
(*pScreen->PostValidateTree)(pWin->parent, NullWindow, kind);
}
if (pWin->realized)
WindowsRestructured ();
}
#ifndef RECTLIMIT
#define RECTLIMIT 25
#endif
static void
miOverlayWindowExposures(
WindowPtr pWin,
RegionPtr prgn,
RegionPtr other_exposed
){
RegionPtr exposures = prgn;
ScreenPtr pScreen = pWin->drawable.pScreen;
if ((prgn && !REGION_NIL(prgn)) ||
(exposures && !REGION_NIL(exposures)) || other_exposed)
{
RegionRec expRec;
int clientInterested;
clientInterested = (pWin->eventMask|wOtherEventMasks(pWin)) &
ExposureMask;
if (other_exposed) {
if (exposures) {
REGION_UNION(pScreen, other_exposed, exposures, other_exposed);
if (exposures != prgn)
REGION_DESTROY(pScreen, exposures);
}
exposures = other_exposed;
}
if (clientInterested && exposures &&
(REGION_NUM_RECTS(exposures) > RECTLIMIT))
{
miOverlayScreenPtr pPriv = MIOVERLAY_GET_SCREEN_PRIVATE(pScreen);
BoxRec box;
box = *REGION_EXTENTS(pScreen, exposures);
if (exposures == prgn) {
exposures = &expRec;
REGION_INIT(pScreen, exposures, &box, 1);
REGION_RESET(pScreen, prgn, &box);
} else {
REGION_RESET(pScreen, exposures, &box);
REGION_UNION(pScreen, prgn, prgn, exposures);
}
/* This is the only reason why we are replacing mi's version
of this file */
if(!((*pPriv->InOverlay)(pWin))) {
miOverlayTreePtr pTree = MIOVERLAY_GET_WINDOW_TREE(pWin);
REGION_INTERSECT(pScreen, prgn, prgn, &pTree->clipList);
} else
REGION_INTERSECT(pScreen, prgn, prgn, &pWin->clipList);
}
if (prgn && !REGION_NIL(prgn))
miPaintWindow(pWin, prgn, PW_BACKGROUND);
if (clientInterested && exposures && !REGION_NIL(exposures))
miSendExposures(pWin, exposures,
pWin->drawable.x, pWin->drawable.y);
if (exposures == &expRec) {
REGION_UNINIT(pScreen, exposures);
}
else if (exposures && exposures != prgn && exposures != other_exposed)
REGION_DESTROY(pScreen, exposures);
if (prgn)
REGION_EMPTY(pScreen, prgn);
}
else if (exposures && exposures != prgn)
REGION_DESTROY(pScreen, exposures);
}
typedef struct {
RegionPtr over;
RegionPtr under;
} miOverlayTwoRegions;
static int
miOverlayRecomputeExposures (
WindowPtr pWin,
pointer value
){
ScreenPtr pScreen;
miOverlayTwoRegions *pValid = (miOverlayTwoRegions*)value;
miOverlayTreePtr pTree = MIOVERLAY_GET_WINDOW_TREE(pWin);
/* This prevents warning about pScreen not being used. */
pWin->drawable.pScreen = pScreen = pWin->drawable.pScreen;
if (pWin->valdata) {
/*
* compute exposed regions of this window
*/
REGION_SUBTRACT(pScreen, &pWin->valdata->after.exposed,
&pWin->clipList, pValid->over);
/*
* compute exposed regions of the border
*/
REGION_SUBTRACT(pScreen, &pWin->valdata->after.borderExposed,
&pWin->borderClip, &pWin->winSize);
REGION_SUBTRACT(pScreen, &pWin->valdata->after.borderExposed,
&pWin->valdata->after.borderExposed, pValid->over);
}
if(pTree && pTree->valdata) {
REGION_SUBTRACT(pScreen, &pTree->valdata->exposed,
&pTree->clipList, pValid->under);
REGION_SUBTRACT(pScreen, &pTree->valdata->borderExposed,
&pTree->borderClip, &pWin->winSize);
REGION_SUBTRACT(pScreen, &pTree->valdata->borderExposed,
&pTree->valdata->borderExposed, pValid->under);
} else if (!pWin->valdata)
return WT_NOMATCH;
return WT_WALKCHILDREN;
}
static void
miOverlayResizeWindow(
WindowPtr pWin,
int x, int y,
unsigned int w, unsigned int h,
WindowPtr pSib
){
ScreenPtr pScreen = pWin->drawable.pScreen;
WindowPtr pParent;
miOverlayTreePtr tChild, pTree;
Bool WasViewable = (Bool)(pWin->viewable);
unsigned short width = pWin->drawable.width;
unsigned short height = pWin->drawable.height;
short oldx = pWin->drawable.x;
short oldy = pWin->drawable.y;
int bw = wBorderWidth (pWin);
short dw, dh;
DDXPointRec oldpt;
RegionPtr oldRegion = NULL, oldRegion2 = NULL;
WindowPtr pFirstChange;
WindowPtr pChild;
RegionPtr gravitate[StaticGravity + 1];
RegionPtr gravitate2[StaticGravity + 1];
unsigned g;
int nx, ny; /* destination x,y */
int newx, newy; /* new inner window position */
RegionPtr pRegion = NULL;
RegionPtr destClip, destClip2;
RegionPtr oldWinClip = NULL, oldWinClip2 = NULL;
RegionPtr borderVisible = NullRegion;
RegionPtr borderVisible2 = NullRegion;
Bool shrunk = FALSE; /* shrunk in an inner dimension */
Bool moved = FALSE; /* window position changed */
#ifdef DO_SAVE_UNDERS
Bool dosave = FALSE;
#endif
Bool doUnderlay;
/* if this is a root window, can't be resized */
if (!(pParent = pWin->parent))
return ;
pTree = MIOVERLAY_GET_WINDOW_TREE(pWin);
doUnderlay = ((pTree) || HasUnderlayChildren(pWin));
newx = pParent->drawable.x + x + bw;
newy = pParent->drawable.y + y + bw;
if (WasViewable)
{
/*
* save the visible region of the window
*/
oldRegion = REGION_CREATE(pScreen, NullBox, 1);
REGION_COPY(pScreen, oldRegion, &pWin->winSize);
if(doUnderlay) {
oldRegion2 = REGION_CREATE(pScreen, NullBox, 1);
REGION_COPY(pScreen, oldRegion2, &pWin->winSize);
}
/*
* categorize child windows into regions to be moved
*/
for (g = 0; g <= StaticGravity; g++)
gravitate[g] = gravitate2[g] = NULL;
for (pChild = pWin->firstChild; pChild; pChild = pChild->nextSib) {
g = pChild->winGravity;
if (g != UnmapGravity) {
if (!gravitate[g])
gravitate[g] = REGION_CREATE(pScreen, NullBox, 1);
REGION_UNION(pScreen, gravitate[g],
gravitate[g], &pChild->borderClip);
if(doUnderlay) {
if (!gravitate2[g])
gravitate2[g] = REGION_CREATE(pScreen, NullBox, 0);
if((tChild = MIOVERLAY_GET_WINDOW_TREE(pChild))) {
REGION_UNION(pScreen, gravitate2[g],
gravitate2[g], &tChild->borderClip);
} else
CollectUnderlayChildrenRegions(pChild, gravitate2[g]);
}
} else {
UnmapWindow(pChild, TRUE);
}
}
(*pScreen->MarkOverlappedWindows)(pWin, pWin, NULL);
oldWinClip = oldWinClip2 = NULL;
if (pWin->bitGravity != ForgetGravity) {
oldWinClip = REGION_CREATE(pScreen, NullBox, 1);
REGION_COPY(pScreen, oldWinClip, &pWin->clipList);
if(pTree) {
oldWinClip2 = REGION_CREATE(pScreen, NullBox, 1);
REGION_COPY(pScreen, oldWinClip2, &pTree->clipList);
}
}
/*
* if the window is changing size, borderExposed
* can't be computed correctly without some help.
*/
if (pWin->drawable.height > h || pWin->drawable.width > w)
shrunk = TRUE;
if (newx != oldx || newy != oldy)
moved = TRUE;
if ((pWin->drawable.height != h || pWin->drawable.width != w) &&
HasBorder (pWin))
{
borderVisible = REGION_CREATE(pScreen, NullBox, 1);
if(pTree)
borderVisible2 = REGION_CREATE(pScreen, NullBox, 1);
/* for tiled borders, we punt and draw the whole thing */
if (pWin->borderIsPixel || !moved)
{
if (shrunk || moved)
REGION_SUBTRACT(pScreen, borderVisible,
&pWin->borderClip,
&pWin->winSize);
else
REGION_COPY(pScreen, borderVisible,
&pWin->borderClip);
if(pTree) {
if (shrunk || moved)
REGION_SUBTRACT(pScreen, borderVisible,
&pTree->borderClip,
&pWin->winSize);
else
REGION_COPY(pScreen, borderVisible,
&pTree->borderClip);
}
}
}
}
pWin->origin.x = x + bw;
pWin->origin.y = y + bw;
pWin->drawable.height = h;
pWin->drawable.width = w;
x = pWin->drawable.x = newx;
y = pWin->drawable.y = newy;
SetWinSize (pWin);
SetBorderSize (pWin);
dw = (int)w - (int)width;
dh = (int)h - (int)height;
ResizeChildrenWinSize(pWin, x - oldx, y - oldy, dw, dh);
/* let the hardware adjust background and border pixmaps, if any */
(*pScreen->PositionWindow)(pWin, x, y);
pFirstChange = MoveWindowInStack(pWin, pSib);
if (WasViewable) {
pRegion = REGION_CREATE(pScreen, NullBox, 1);
(*pScreen->MarkOverlappedWindows)(pWin, pFirstChange, NULL);
pWin->valdata->before.resized = TRUE;
pWin->valdata->before.borderVisible = borderVisible;
if(pTree)
pTree->valdata->borderVisible = borderVisible2;
#ifdef DO_SAVE_UNDERS
if (DO_SAVE_UNDERS(pWin))
dosave = (*pScreen->ChangeSaveUnder)(pWin, pFirstChange);
#endif /* DO_SAVE_UNDERS */
(*pScreen->ValidateTree)(pWin->parent, pFirstChange, VTOther);
/*
* the entire window is trashed unless bitGravity
* recovers portions of it
*/
REGION_COPY(pScreen, &pWin->valdata->after.exposed, &pWin->clipList);
if(pTree)
REGION_COPY(pScreen, &pTree->valdata->exposed, &pTree->clipList);
}
GravityTranslate (x, y, oldx, oldy, dw, dh, pWin->bitGravity, &nx, &ny);
if (WasViewable) {
miOverlayScreenPtr pPriv = MIOVERLAY_GET_SCREEN_PRIVATE(pScreen);
miOverlayTwoRegions TwoRegions;
/* avoid the border */
if (HasBorder (pWin)) {
int offx, offy, dx, dy;
/* kruft to avoid double translates for each gravity */
offx = 0;
offy = 0;
for (g = 0; g <= StaticGravity; g++) {
if (!gravitate[g] && !gravitate2[g])
continue;
/* align winSize to gravitate[g].
* winSize is in new coordinates,
* gravitate[g] is still in old coordinates */
GravityTranslate (x, y, oldx, oldy, dw, dh, g, &nx, &ny);
dx = (oldx - nx) - offx;
dy = (oldy - ny) - offy;
if (dx || dy) {
REGION_TRANSLATE(pScreen, &pWin->winSize, dx, dy);
offx += dx;
offy += dy;
}
if(gravitate[g])
REGION_INTERSECT(pScreen, gravitate[g], gravitate[g],
&pWin->winSize);
if(gravitate2[g])
REGION_INTERSECT(pScreen, gravitate2[g], gravitate2[g],
&pWin->winSize);
}
/* get winSize back where it belongs */
if (offx || offy)
REGION_TRANSLATE(pScreen, &pWin->winSize, -offx, -offy);
}
/*
* add screen bits to the appropriate bucket
*/
if (oldWinClip2)
{
REGION_COPY(pScreen, pRegion, oldWinClip2);
REGION_TRANSLATE(pScreen, pRegion, nx - oldx, ny - oldy);
REGION_INTERSECT(pScreen, oldWinClip2, pRegion, &pTree->clipList);
for (g = pWin->bitGravity + 1; g <= StaticGravity; g++) {
if (gravitate2[g])
REGION_SUBTRACT(pScreen, oldWinClip2, oldWinClip2,
gravitate2[g]);
}
REGION_TRANSLATE(pScreen, oldWinClip2, oldx - nx, oldy - ny);
g = pWin->bitGravity;
if (!gravitate2[g])
gravitate2[g] = oldWinClip2;
else {
REGION_UNION(pScreen,gravitate2[g],gravitate2[g],oldWinClip2);
REGION_DESTROY(pScreen, oldWinClip2);
}
}
if (oldWinClip)
{
/*
* clip to new clipList
*/
REGION_COPY(pScreen, pRegion, oldWinClip);
REGION_TRANSLATE(pScreen, pRegion, nx - oldx, ny - oldy);
REGION_INTERSECT(pScreen, oldWinClip, pRegion, &pWin->clipList);
/*
* don't step on any gravity bits which will be copied after this
* region. Note -- this assumes that the regions will be copied
* in gravity order.
*/
for (g = pWin->bitGravity + 1; g <= StaticGravity; g++) {
if (gravitate[g])
REGION_SUBTRACT(pScreen, oldWinClip, oldWinClip,
gravitate[g]);
}
REGION_TRANSLATE(pScreen, oldWinClip, oldx - nx, oldy - ny);
g = pWin->bitGravity;
if (!gravitate[g])
gravitate[g] = oldWinClip;
else {
REGION_UNION(pScreen, gravitate[g], gravitate[g], oldWinClip);
REGION_DESTROY(pScreen, oldWinClip);
}
}
/*
* move the bits on the screen
*/
destClip = destClip2 = NULL;
for (g = 0; g <= StaticGravity; g++) {
if (!gravitate[g] && !gravitate2[g])
continue;
GravityTranslate (x, y, oldx, oldy, dw, dh, g, &nx, &ny);
oldpt.x = oldx + (x - nx);
oldpt.y = oldy + (y - ny);
/* Note that gravitate[g] is *translated* by CopyWindow */
/* only copy the remaining useful bits */
if(gravitate[g])
REGION_INTERSECT(pScreen, gravitate[g],
gravitate[g], oldRegion);
if(gravitate2[g])
REGION_INTERSECT(pScreen, gravitate2[g],
gravitate2[g], oldRegion2);
/* clip to not overwrite already copied areas */
if (destClip && gravitate[g]) {
REGION_TRANSLATE(pScreen, destClip, oldpt.x - x, oldpt.y - y);
REGION_SUBTRACT(pScreen, gravitate[g], gravitate[g], destClip);
REGION_TRANSLATE(pScreen, destClip, x - oldpt.x, y - oldpt.y);
}
if (destClip2 && gravitate2[g]) {
REGION_TRANSLATE(pScreen, destClip2, oldpt.x - x, oldpt.y - y);
REGION_SUBTRACT(pScreen,gravitate2[g],gravitate2[g],destClip2);
REGION_TRANSLATE(pScreen, destClip2, x - oldpt.x, y - oldpt.y);
}
/* and move those bits */
if (oldpt.x != x || oldpt.y != y) {
if(gravitate2[g]) {
pPriv->copyUnderlay = TRUE;
(*pWin->drawable.pScreen->CopyWindow)(
pWin, oldpt, gravitate2[g]);
}
if(gravitate[g]) {
pPriv->copyUnderlay = FALSE;
(*pWin->drawable.pScreen->CopyWindow)(
pWin, oldpt, gravitate[g]);
}
}
/* remove any overwritten bits from the remaining useful bits */
if(gravitate[g])
REGION_SUBTRACT(pScreen, oldRegion, oldRegion, gravitate[g]);
if(gravitate2[g])
REGION_SUBTRACT(pScreen, oldRegion2, oldRegion2, gravitate2[g]);
/*
* recompute exposed regions of child windows
*/
for (pChild = pWin->firstChild; pChild; pChild = pChild->nextSib) {
if (pChild->winGravity != g)
continue;
TwoRegions.over = gravitate[g];
TwoRegions.under = gravitate2[g];
TraverseTree (pChild, miOverlayRecomputeExposures,
(pointer)(&TwoRegions));
}
/*
* remove the successfully copied regions of the
* window from its exposed region
*/
if (g == pWin->bitGravity) {
if(gravitate[g])
REGION_SUBTRACT(pScreen, &pWin->valdata->after.exposed,
&pWin->valdata->after.exposed, gravitate[g]);
if(gravitate2[g] && pTree)
REGION_SUBTRACT(pScreen, &pTree->valdata->exposed,
&pTree->valdata->exposed, gravitate2[g]);
}
if(gravitate[g]) {
if (!destClip)
destClip = gravitate[g];
else {
REGION_UNION(pScreen, destClip, destClip, gravitate[g]);
REGION_DESTROY(pScreen, gravitate[g]);
}
}
if(gravitate2[g]) {
if (!destClip2)
destClip2 = gravitate2[g];
else {
REGION_UNION(pScreen, destClip2, destClip2, gravitate2[g]);
REGION_DESTROY(pScreen, gravitate2[g]);
}
}
}
REGION_DESTROY(pScreen, pRegion);
REGION_DESTROY(pScreen, oldRegion);
if(doUnderlay)
REGION_DESTROY(pScreen, oldRegion2);
if (destClip)
REGION_DESTROY(pScreen, destClip);
if (destClip2)
REGION_DESTROY(pScreen, destClip2);
(*pScreen->HandleExposures)(pWin->parent);
#ifdef DO_SAVE_UNDERS
if (dosave)
(*pScreen->PostChangeSaveUnder)(pWin, pFirstChange);
#endif /* DO_SAVE_UNDERS */
if (pScreen->PostValidateTree)
(*pScreen->PostValidateTree)(pWin->parent, pFirstChange, VTOther);
}
if (pWin->realized)
WindowsRestructured ();
}
#ifdef SHAPE
static void
miOverlaySetShape(WindowPtr pWin)
{
Bool WasViewable = (Bool)(pWin->viewable);
ScreenPtr pScreen = pWin->drawable.pScreen;
#ifdef DO_SAVE_UNDERS
Bool dosave = FALSE;
#endif
if (WasViewable) {
(*pScreen->MarkOverlappedWindows)(pWin, pWin, NULL);
if (HasBorder (pWin)) {
RegionPtr borderVisible;
borderVisible = REGION_CREATE(pScreen, NullBox, 1);
REGION_SUBTRACT(pScreen, borderVisible,
&pWin->borderClip, &pWin->winSize);
pWin->valdata->before.borderVisible = borderVisible;
pWin->valdata->before.resized = TRUE;
if(IN_UNDERLAY(pWin)) {
miOverlayTreePtr pTree = MIOVERLAY_GET_WINDOW_TREE(pWin);
RegionPtr borderVisible2;
borderVisible2 = REGION_CREATE(pScreen, NULL, 1);
REGION_SUBTRACT(pScreen, borderVisible2,
&pTree->borderClip, &pWin->winSize);
pTree->valdata->borderVisible = borderVisible2;
}
}
}
SetWinSize (pWin);
SetBorderSize (pWin);
ResizeChildrenWinSize(pWin, 0, 0, 0, 0);
if (WasViewable) {
(*pScreen->MarkOverlappedWindows)(pWin, pWin, NULL);
#ifdef DO_SAVE_UNDERS
if (DO_SAVE_UNDERS(pWin))
dosave = (*pScreen->ChangeSaveUnder)(pWin, pWin);
#endif /* DO_SAVE_UNDERS */
(*pScreen->ValidateTree)(pWin->parent, NullWindow, VTOther);
}
if (WasViewable) {
(*pScreen->HandleExposures)(pWin->parent);
#ifdef DO_SAVE_UNDERS
if (dosave)
(*pScreen->PostChangeSaveUnder)(pWin, pWin);
#endif /* DO_SAVE_UNDERS */
if (pScreen->PostValidateTree)
(*pScreen->PostValidateTree)(pWin->parent, NullWindow, VTOther);
}
if (pWin->realized)
WindowsRestructured ();
CheckCursorConfinement(pWin);
}
#endif
static void
miOverlayChangeBorderWidth(
WindowPtr pWin,
unsigned int width
){
int oldwidth;
ScreenPtr pScreen;
Bool WasViewable = (Bool)(pWin->viewable);
Bool HadBorder;
#ifdef DO_SAVE_UNDERS
Bool dosave = FALSE;
#endif
oldwidth = wBorderWidth (pWin);
if (oldwidth == width)
return;
HadBorder = HasBorder(pWin);
pScreen = pWin->drawable.pScreen;
if (WasViewable && (width < oldwidth))
(*pScreen->MarkOverlappedWindows)(pWin, pWin, NULL);
pWin->borderWidth = width;
SetBorderSize (pWin);
if (WasViewable) {
if (width > oldwidth) {
(*pScreen->MarkOverlappedWindows)(pWin, pWin, NULL);
if (HadBorder) {
RegionPtr borderVisible;
borderVisible = REGION_CREATE(pScreen, NULL, 1);
REGION_SUBTRACT(pScreen, borderVisible,
&pWin->borderClip, &pWin->winSize);
pWin->valdata->before.borderVisible = borderVisible;
if(IN_UNDERLAY(pWin)) {
miOverlayTreePtr pTree = MIOVERLAY_GET_WINDOW_TREE(pWin);
RegionPtr borderVisible2;
borderVisible2 = REGION_CREATE(pScreen, NULL, 1);
REGION_SUBTRACT(pScreen, borderVisible2,
&pTree->borderClip, &pWin->winSize);
pTree->valdata->borderVisible = borderVisible2;
}
}
}
#ifdef DO_SAVE_UNDERS
if (DO_SAVE_UNDERS(pWin))
dosave = (*pScreen->ChangeSaveUnder)(pWin, pWin->nextSib);
#endif /* DO_SAVE_UNDERS */
(*pScreen->ValidateTree)(pWin->parent, pWin, VTOther);
(*pScreen->HandleExposures)(pWin->parent);
#ifdef DO_SAVE_UNDERS
if (dosave)
(*pScreen->PostChangeSaveUnder)(pWin, pWin->nextSib);
#endif /* DO_SAVE_UNDERS */
if (pScreen->PostValidateTree)
(*pScreen->PostValidateTree)(pWin->parent, pWin, VTOther);
}
if (pWin->realized)
WindowsRestructured ();
}
/* We need this as an addition since the xf86 common code doesn't
know about the second tree which is static to this file. */
_X_EXPORT void
miOverlaySetRootClip(ScreenPtr pScreen, Bool enable)
{
WindowPtr pRoot = WindowTable[pScreen->myNum];
miOverlayTreePtr pTree = MIOVERLAY_GET_WINDOW_TREE(pRoot);
MARK_UNDERLAY(pRoot);
if(enable) {
BoxRec box;
box.x1 = 0;
box.y1 = 0;
box.x2 = pScreen->width;
box.y2 = pScreen->height;
REGION_RESET(pScreen, &pTree->borderClip, &box);
} else
REGION_EMPTY(pScreen, &pTree->borderClip);
REGION_BREAK(pScreen, &pTree->clipList);
}
static void
miOverlayClearToBackground(
WindowPtr pWin,
int x, int y,
int w, int h,
Bool generateExposures
)
{
miOverlayTreePtr pTree = MIOVERLAY_GET_WINDOW_TREE(pWin);
BoxRec box;
RegionRec reg;
RegionPtr pBSReg = NullRegion;
ScreenPtr pScreen = pWin->drawable.pScreen;
miOverlayScreenPtr pScreenPriv = MIOVERLAY_GET_SCREEN_PRIVATE(pScreen);
RegionPtr clipList;
BoxPtr extents;
int x1, y1, x2, y2;
x1 = pWin->drawable.x + x;
y1 = pWin->drawable.y + y;
if (w)
x2 = x1 + (int) w;
else
x2 = x1 + (int) pWin->drawable.width - (int) x;
if (h)
y2 = y1 + h;
else
y2 = y1 + (int) pWin->drawable.height - (int) y;
clipList = ((*pScreenPriv->InOverlay)(pWin)) ? &pWin->clipList :
&pTree->clipList;
extents = REGION_EXTENTS(pScreen, clipList);
if (x1 < extents->x1) x1 = extents->x1;
if (x2 > extents->x2) x2 = extents->x2;
if (y1 < extents->y1) y1 = extents->y1;
if (y2 > extents->y2) y2 = extents->y2;
if (x2 <= x1 || y2 <= y1)
x2 = x1 = y2 = y1 = 0;
box.x1 = x1; box.x2 = x2;
box.y1 = y1; box.y2 = y2;
REGION_INIT(pScreen, ®, &box, 1);
REGION_INTERSECT(pScreen, ®, ®, clipList);
if (generateExposures)
(*pScreen->WindowExposures)(pWin, ®, pBSReg);
else if (pWin->backgroundState != None)
miPaintWindow(pWin, ®, PW_BACKGROUND);
REGION_UNINIT(pScreen, ®);
if (pBSReg)
REGION_DESTROY(pScreen, pBSReg);
}
/****************************************************************/
/* not used */
_X_EXPORT Bool
miOverlayGetPrivateClips(
WindowPtr pWin,
RegionPtr *borderClip,
RegionPtr *clipList
){
miOverlayTreePtr pTree = MIOVERLAY_GET_WINDOW_TREE(pWin);
if(pTree) {
*borderClip = &(pTree->borderClip);
*clipList = &(pTree->clipList);
return TRUE;
}
*borderClip = *clipList = NULL;
return FALSE;
}
_X_EXPORT void
miOverlaySetTransFunction (
ScreenPtr pScreen,
miOverlayTransFunc transFunc
){
MIOVERLAY_GET_SCREEN_PRIVATE(pScreen)->MakeTransparent = transFunc;
}
_X_EXPORT Bool
miOverlayCopyUnderlay(ScreenPtr pScreen)
{
return MIOVERLAY_GET_SCREEN_PRIVATE(pScreen)->copyUnderlay;
}
_X_EXPORT void
miOverlayComputeCompositeClip(GCPtr pGC, WindowPtr pWin)
{
ScreenPtr pScreen = pGC->pScreen;
miOverlayTreePtr pTree = MIOVERLAY_GET_WINDOW_TREE(pWin);
RegionPtr pregWin;
Bool freeTmpClip, freeCompClip;
if(!pTree) {
miComputeCompositeClip(pGC, &pWin->drawable);
return;
}
if (pGC->subWindowMode == IncludeInferiors) {
pregWin = REGION_CREATE(pScreen, NullBox, 1);
freeTmpClip = TRUE;
if (pWin->parent || (screenIsSaved != SCREEN_SAVER_ON) ||
!HasSaverWindow (pScreen->myNum))
{
REGION_INTERSECT(pScreen,pregWin,&pTree->borderClip,&pWin->winSize);
}
} else {
pregWin = &pTree->clipList;
freeTmpClip = FALSE;
}
freeCompClip = pGC->freeCompClip;
if (pGC->clientClipType == CT_NONE) {
if (freeCompClip)
REGION_DESTROY(pScreen, pGC->pCompositeClip);
pGC->pCompositeClip = pregWin;
pGC->freeCompClip = freeTmpClip;
} else {
REGION_TRANSLATE(pScreen, pGC->clientClip,
pWin->drawable.x + pGC->clipOrg.x,
pWin->drawable.y + pGC->clipOrg.y);
if (freeCompClip) {
REGION_INTERSECT(pGC->pScreen, pGC->pCompositeClip,
pregWin, pGC->clientClip);
if (freeTmpClip)
REGION_DESTROY(pScreen, pregWin);
} else if (freeTmpClip) {
REGION_INTERSECT(pScreen, pregWin, pregWin, pGC->clientClip);
pGC->pCompositeClip = pregWin;
} else {
pGC->pCompositeClip = REGION_CREATE(pScreen, NullBox, 0);
REGION_INTERSECT(pScreen, pGC->pCompositeClip,
pregWin, pGC->clientClip);
}
pGC->freeCompClip = TRUE;
REGION_TRANSLATE(pScreen, pGC->clientClip,
-(pWin->drawable.x + pGC->clipOrg.x),
-(pWin->drawable.y + pGC->clipOrg.y));
}
}
_X_EXPORT Bool
miOverlayCollectUnderlayRegions(
WindowPtr pWin,
RegionPtr *region
){
miOverlayTreePtr pTree = MIOVERLAY_GET_WINDOW_TREE(pWin);
if(pTree) {
*region = &pTree->borderClip;
return FALSE;
}
*region = REGION_CREATE(pWin->drawable.pScreen, NullBox, 0);
CollectUnderlayChildrenRegions(pWin, *region);
return TRUE;
}
static miOverlayTreePtr
DoLeaf(
WindowPtr pWin,
miOverlayTreePtr parent,
miOverlayTreePtr prevSib
){
miOverlayTreePtr pTree = MIOVERLAY_GET_WINDOW_TREE(pWin);
pTree->parent = parent;
pTree->firstChild = NULL;
pTree->lastChild = NULL;
pTree->prevSib = prevSib;
pTree->nextSib = NULL;
if(prevSib)
prevSib->nextSib = pTree;
if(!parent->firstChild)
parent->firstChild = parent->lastChild = pTree;
else if(parent->lastChild == prevSib)
parent->lastChild = pTree;
return pTree;
}
static void
RebuildTree(WindowPtr pWin)
{
miOverlayTreePtr parent, prevSib, tChild;
WindowPtr pChild;
prevSib = tChild = NULL;
pWin = pWin->parent;
while(IN_OVERLAY(pWin))
pWin = pWin->parent;
parent = MIOVERLAY_GET_WINDOW_TREE(pWin);
pChild = pWin->firstChild;
parent->firstChild = parent->lastChild = NULL;
while(1) {
if(IN_UNDERLAY(pChild))
prevSib = tChild = DoLeaf(pChild, parent, prevSib);
if(pChild->firstChild) {
if(IN_UNDERLAY(pChild)) {
parent = tChild;
prevSib = NULL;
}
pChild = pChild->firstChild;
continue;
}
while(!pChild->nextSib) {
pChild = pChild->parent;
if(pChild == pWin) return;
if(IN_UNDERLAY(pChild)) {
prevSib = tChild = MIOVERLAY_GET_WINDOW_TREE(pChild);
parent = tChild->parent;
}
}
pChild = pChild->nextSib;
}
}
static Bool
HasUnderlayChildren(WindowPtr pWin)
{
WindowPtr pChild;
if(!(pChild = pWin->firstChild))
return FALSE;
while(1) {
if(IN_UNDERLAY(pChild))
return TRUE;
if(pChild->firstChild) {
pChild = pChild->firstChild;
continue;
}
while(!pChild->nextSib && (pWin != pChild))
pChild = pChild->parent;
if(pChild == pWin) break;
pChild = pChild->nextSib;
}
return FALSE;
}
static Bool
CollectUnderlayChildrenRegions(WindowPtr pWin, RegionPtr pReg)
{
WindowPtr pChild;
miOverlayTreePtr pTree;
Bool hasUnderlay;
if(!(pChild = pWin->firstChild))
return FALSE;
hasUnderlay = FALSE;
while(1) {
if((pTree = MIOVERLAY_GET_WINDOW_TREE(pChild))) {
REGION_APPEND(pScreen, pReg, &pTree->borderClip);
hasUnderlay = TRUE;
} else
if(pChild->firstChild) {
pChild = pChild->firstChild;
continue;
}
while(!pChild->nextSib && (pWin != pChild))
pChild = pChild->parent;
if(pChild == pWin) break;
pChild = pChild->nextSib;
}
if(hasUnderlay) {
Bool overlap;
REGION_VALIDATE(pScreen, pReg, &overlap);
}
return hasUnderlay;
}
static void
MarkUnderlayWindow(WindowPtr pWin)
{
miOverlayTreePtr pTree = MIOVERLAY_GET_WINDOW_TREE(pWin);
if(pTree->valdata) return;
pTree->valdata = (miOverlayValDataPtr)xnfalloc(sizeof(miOverlayValDataRec));
pTree->valdata->oldAbsCorner.x = pWin->drawable.x;
pTree->valdata->oldAbsCorner.y = pWin->drawable.y;
pTree->valdata->borderVisible = NullRegion;
}
| 27.272136 | 80 | 0.671112 | [
"shape"
] |
6ddfeed15793b58e4542f4ee0c6063e9c9bef62d | 985 | h | C | chrome/browser/ui/thumbnails/thumbnail_capture_info.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | chrome/browser/ui/thumbnails/thumbnail_capture_info.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | chrome/browser/ui/thumbnails/thumbnail_capture_info.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2020 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_UI_THUMBNAILS_THUMBNAIL_CAPTURE_INFO_H_
#define CHROME_BROWSER_UI_THUMBNAILS_THUMBNAIL_CAPTURE_INFO_H_
#include "ui/gfx/geometry/insets.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/size.h"
// Describes how a thumbnail bitmap should be generated from a target surface.
// All sizes are in pixels, not DIPs.
struct ThumbnailCaptureInfo {
// The total source size (including scrollbars).
gfx::Size source_size;
// Insets for scrollbars in the source image that should probably be
// ignored for thumbnailing purposes.
gfx::Insets scrollbar_insets;
// Cropping rectangle for the source canvas, in pixels.
gfx::Rect copy_rect;
// Size of the target bitmap in pixels.
gfx::Size target_size;
};
#endif // CHROME_BROWSER_UI_THUMBNAILS_THUMBNAIL_CAPTURE_INFO_H_
| 32.833333 | 78 | 0.77868 | [
"geometry"
] |
6dec288ef8ffbf2835ca18f8adb777bc9fb4c10e | 24,414 | h | C | src/include/execution/ast/type.h | cookieli/terrier | 409401fe34a364ac992569f2aefca6803e7145c7 | [
"MIT"
] | null | null | null | src/include/execution/ast/type.h | cookieli/terrier | 409401fe34a364ac992569f2aefca6803e7145c7 | [
"MIT"
] | null | null | null | src/include/execution/ast/type.h | cookieli/terrier | 409401fe34a364ac992569f2aefca6803e7145c7 | [
"MIT"
] | null | null | null | #pragma once
#include <cstdint>
#include <string>
#include "common/strong_typedef.h"
#include "execution/ast/identifier.h"
#include "execution/sql/storage_interface.h"
#include "execution/util/region.h"
#include "execution/util/region_containers.h"
#include "llvm/Support/Casting.h"
namespace terrier::execution::ast {
class Context;
// List of all concrete types
#define TYPE_LIST(F) \
F(BuiltinType) \
F(StringType) \
F(PointerType) \
F(ArrayType) \
F(MapType) \
F(StructType) \
F(FunctionType)
// Macro listing all builtin types. Accepts multiple callback functions to
// handle the different kinds of builtins.
//
// PRIM: A primitive builtin type (e.g., bool, int32_t etc.)
// Args: Kind, C++ type, TPL name (i.e., as it appears in TPL code)
// NON_PRIM: A builtin type that isn't primitive. These are pre-compiled C++
// classes that can be created and manipulated from TPL code.
// Args: Kind, C++ type
// SQL: These are full-blown SQL types. SQL types have backing C++
// implementations, but can also be created and manipulated from TPL
// code. We specialize these because we also want to add SQL-level
// type information to these builtins.
#define BUILTIN_TYPE_LIST(PRIM, NON_PRIM, SQL) \
/* Primitive types */ \
PRIM(Nil, uint8_t, "nil") \
PRIM(Bool, bool, "bool") \
PRIM(Int8, int8_t, "int8") \
PRIM(Int16, int16_t, "int16") \
PRIM(Int32, int32_t, "int32") \
PRIM(Int64, int64_t, "int64") \
PRIM(Uint8, uint8_t, "uint8") \
PRIM(Uint16, uint16_t, "uint16") \
PRIM(Uint32, uint32_t, "uint32") \
PRIM(Uint64, uint64_t, "uint64") \
PRIM(Int128, int128_t, "int128") \
PRIM(Uint128, uint128_t, "uint128") \
PRIM(Float32, float, "float32") \
PRIM(Float64, double, "float64") \
\
/* Non-primitive builtins */ \
NON_PRIM(AggregationHashTable, terrier::execution::sql::AggregationHashTable) \
NON_PRIM(AggregationHashTableIterator, terrier::execution::sql::AggregationHashTableIterator) \
NON_PRIM(AggOverflowPartIter, terrier::execution::sql::AggregationOverflowPartitionIterator) \
NON_PRIM(BloomFilter, terrier::execution::sql::BloomFilter) \
NON_PRIM(ExecutionContext, terrier::execution::exec::ExecutionContext) \
NON_PRIM(FilterManager, terrier::execution::sql::FilterManager) \
NON_PRIM(HashTableEntry, terrier::execution::sql::HashTableEntry) \
NON_PRIM(JoinHashTable, terrier::execution::sql::JoinHashTable) \
NON_PRIM(JoinHashTableVectorProbe, terrier::execution::sql::JoinHashTableVectorProbe) \
NON_PRIM(JoinHashTableIterator, terrier::execution::sql::JoinHashTableIterator) \
NON_PRIM(MemoryPool, terrier::execution::sql::MemoryPool) \
NON_PRIM(Sorter, terrier::execution::sql::Sorter) \
NON_PRIM(SorterIterator, terrier::execution::sql::SorterIterator) \
NON_PRIM(TableVectorIterator, terrier::execution::sql::TableVectorIterator) \
NON_PRIM(ThreadStateContainer, terrier::execution::sql::ThreadStateContainer) \
NON_PRIM(ProjectedColumnsIterator, terrier::execution::sql::ProjectedColumnsIterator) \
NON_PRIM(IndexIterator, terrier::execution::sql::IndexIterator) \
\
/* SQL Aggregate types (if you add, remember to update BuiltinType) */ \
NON_PRIM(CountAggregate, terrier::execution::sql::CountAggregate) \
NON_PRIM(CountStarAggregate, terrier::execution::sql::CountStarAggregate) \
NON_PRIM(IntegerAvgAggregate, terrier::execution::sql::AvgAggregate) \
NON_PRIM(IntegerMaxAggregate, terrier::execution::sql::IntegerMaxAggregate) \
NON_PRIM(IntegerMinAggregate, terrier::execution::sql::IntegerMinAggregate) \
NON_PRIM(IntegerSumAggregate, terrier::execution::sql::IntegerSumAggregate) \
NON_PRIM(RealAvgAggregate, terrier::execution::sql::AvgAggregate) \
NON_PRIM(RealMaxAggregate, terrier::execution::sql::RealMaxAggregate) \
NON_PRIM(RealMinAggregate, terrier::execution::sql::RealMinAggregate) \
NON_PRIM(RealSumAggregate, terrier::execution::sql::RealSumAggregate) \
\
/* SQL Table operations */ \
NON_PRIM(ProjectedRow, terrier::storage::ProjectedRow) \
NON_PRIM(TupleSlot, terrier::storage::TupleSlot) \
NON_PRIM(StorageInterface, terrier::execution::sql::StorageInterface) \
\
/* Non-primitive SQL Runtime Values */ \
SQL(Boolean, terrier::execution::sql::BoolVal) \
SQL(Integer, terrier::execution::sql::Integer) \
SQL(Real, terrier::execution::sql::Real) \
SQL(Decimal, terrier::execution::sql::Decimal) \
SQL(StringVal, terrier::execution::sql::StringVal) \
SQL(Date, terrier::execution::sql::Date) \
SQL(Timestamp, terrier::execution::sql::Timestamp)
// Ignore a builtin
#define IGNORE_BUILTIN_TYPE (...)
// Only consider the primitive builtin types
#define PRIMIMITIVE_BUILTIN_TYPE_LIST(F) BUILTIN_TYPE_LIST(F, IGNORE_BUILTIN_TYPE, IGNORE_BUILTIN_TYPE)
// Only consider the non-primitive builtin types
#define NON_PRIMITIVE_BUILTIN_TYPE_LIST(F) BUILTIN_TYPE_LIST(IGNORE_BUILTIN_TYPE, F, IGNORE_BUILTIN_TYPE)
// Only consider the SQL builtin types
#define SQL_BUILTIN_TYPE_LIST(F) BUILTIN_TYPE_LIST(IGNORE_BUILTIN_TYPE, IGNORE_BUILTIN_TYPE, F)
// Forward declare everything first
#define F(TypeClass) class TypeClass;
TYPE_LIST(F)
#undef F
/**
* The base of the TPL type hierarchy. Types, once created, are immutable. Only
* one instance of a particular type is ever created, and all instances are
* owned by the Context object that created it. Thus, one can use pointer
* equality to determine if two types are equal, but only if they were created
* within the same Context.
*/
class Type : public util::RegionObject {
public:
/**
* The enumeration of all concrete types
*/
enum class TypeId : uint8_t {
#define F(TypeId) TypeId,
TYPE_LIST(F)
#undef F
};
/**
* @return the context this type was allocated in
*/
Context *GetContext() const { return ctx_; }
/**
* @return the size of this type in bytes
*/
uint32_t Size() const { return size_; }
/**
* @return the alignment of this type in bytes
*/
uint32_t Alignment() const { return align_; }
/**
* @return the unique type ID of this type (e.g., int16, Array, Struct etc.)
*/
TypeId GetTypeId() const { return type_id_; }
/**
* Perform an "checked cast" to convert an instance of this base Type class
* into one of its derived types. If the target class isn't a subclass of
* Type, an assertion failure is thrown in debug mode. In release mode, such
* a call will fail.
*
* You should use this function when you have reasonable certainty that you
* know the concrete type. Example:
*
* @code
* if (!type->IsBuiltinType()) {
* return;
* }
* ...
* auto *builtin_type = type->As<ast::BuiltinType>();
* ...
* @endcode
*
* @tparam T type to cast to
* @return casted pointer
*/
template <typename T>
const T *As() const {
return llvm::cast<const T>(this);
}
/**
* Perform an "checked cast" to convert an instance of this base Type class
* into one of its derived types.
* @tparam T type to cast to
* @return casted pointer
*/
template <typename T>
T *As() {
return llvm::cast<T>(this);
}
/**
* Perform a "checking cast". This function checks to see if the target type
* is a subclass of Type, returning a pointer to the subclass if so, or
* returning a null pointer otherwise.
*
* You should use this in conditional or control-flow statements when you
* want to check if a type is a specific subtype **AND** get a pointer to the
* subtype, like so:
*
* @code
* if (auto *builtin_type = SafeAs<ast::BuiltinType>()) {
* // ...
* }
* @endcode
*
* @tparam T type to cast to.
* @return casted pointer.
*/
template <typename T>
const T *SafeAs() const {
return llvm::dyn_cast<const T>(this);
}
/**
* Perform a "checking cast". This function checks to see if the target type
* is a subclass of Type, returning a pointer to the subclass if so, or
* returning a null pointer otherwise.
* @tparam T type to cast to.
* @return casted pointer.
*/
template <typename T>
T *SafeAs() {
return llvm::dyn_cast<T>(this);
}
/*
* Type checks
*/
#define F(TypeClass) \
bool Is##TypeClass() const { return llvm::isa<TypeClass>(this); }
TYPE_LIST(F)
#undef F
/**
* Checks whether this is an arithmetic type
* @return true iff this is an arithmetic type.
*/
bool IsArithmetic() const;
/**
* Checks whether this is of the given builtin kind
* @param kind The kind to check
* @return true iff this is of the given kind.
*/
bool IsSpecificBuiltin(uint16_t kind) const;
/**
* Checks whether this is a nil type
* @return true iff this is a nil type.
*/
bool IsNilType() const;
/**
* Checks whether this is a bool type
* @return true iff this is a bool type.
*/
bool IsBoolType() const;
/**
* Checks whether this is an integer type
* @return true iff this is an integer type.
*/
bool IsIntegerType() const;
/**
* Checks whether this is a float type
* @return true iff this is a float type.
*/
bool IsFloatType() const;
/**
* Checks whether this is a sql value type
* @return true iff this is a sql value type.
*/
bool IsSqlValueType() const;
/**
* Checks whether this is a sql aggregator type
* @return true iff this is a sql aggregator type.
*/
bool IsSqlAggregatorType() const;
/**
* @return a type that is a pointer to the current type
*/
PointerType *PointerTo();
/**
* @return If this is a pointer type, return the type it points to, returning null otherwise.
*/
Type *GetPointeeType() const;
/**
* @return a string representation of the given type
*/
std::string ToString() const { return ToString(this); }
/**
* Get a string representation of the input type
* @param type type to represent
* @return a string representation of the fiven type
*/
static std::string ToString(const Type *type);
protected:
/**
* Protected constructor to indicate abstract base
* @param ctx ast context to use
* @param size size of the type
* @param alignment alignment of the type
* @param type_id id of the type
*/
Type(Context *ctx, uint32_t size, uint32_t alignment, TypeId type_id)
: ctx_(ctx), size_(size), align_(alignment), type_id_(type_id) {}
private:
// The context this type was created/unique'd in
Context *ctx_;
// The size of this type in bytes
uint32_t size_;
// The alignment of this type in bytes
uint32_t align_;
// The unique ID of this type
TypeId type_id_;
};
/**
* A builtin type (int32, float32, Integer, JoinHashTable etc.)
*/
class BuiltinType : public Type {
public:
#define F(BKind, ...) BKind,
/**
* Enum of builtin types
*/
enum Kind : uint16_t { BUILTIN_TYPE_LIST(F, F, F) };
#undef F
/**
* Get the name of the builtin as it appears in TPL code
* @return name of the builtin
*/
const char *TplName() const { return tpl_names[static_cast<uint16_t>(kind_)]; }
/**
* Get the name of the C++ type that backs this builtin. For primitive
* types like 32-bit integers, this will be 'int32'. For non-primitive types
* this will be the fully-qualified name of the class (i.e., the class name
* along with the namespace).
* @return the C++ type name
*/
const char *CppName() const { return cpp_names[static_cast<uint16_t>(kind_)]; }
/**
* Get the size of this builtin in bytes
* @return size of the builtin type
*/
uint64_t Size() const { return SIZES[static_cast<uint16_t>(kind_)]; }
/**
* Get the required alignment of this builtin in bytes
* @return alignment of this builtin type
*/
uint64_t Alignment() const { return ALIGNMENTS[static_cast<uint16_t>(kind_)]; }
/**
* @return Is this builtin a primitive?
*/
bool IsPrimitive() const { return PRIMITIVE_FLAGS[static_cast<uint16_t>(kind_)]; }
/**
* @return Is this builtin a primitive integer?
*/
bool IsInteger() const { return Kind::Int8 <= GetKind() && GetKind() <= Kind::Uint128; }
/**
* @return Is this builtin a primitive floating point number?
*/
bool IsFloatingPoint() const { return FLOATING_POINT_FLAGS[static_cast<uint16_t>(kind_)]; }
/**
* Is this type a SQL value type?
*/
bool IsSqlValue() const { return Kind::Boolean <= GetKind() && GetKind() <= Kind::Timestamp; }
/**
* Is this type a SQL aggregator type? IntegerSumAggregate, CountAggregate ...
*/
bool IsSqlAggregatorType() const { return Kind::CountAggregate <= GetKind() && GetKind() <= Kind::RealSumAggregate; }
/**
* @return the kind of this builtin
*/
Kind GetKind() const { return kind_; }
/**
* Return a builtin of the given kind.
* @param ctx ast context to use
* @param kind kind to get
* @return a builtin of the given kind.
*/
static BuiltinType *Get(Context *ctx, Kind kind);
/**
* Checks if this is the same as the given type
* @param type type to check
* @return true iff this is the same as the given type
*/
static bool classof(const Type *type) { return type->GetTypeId() == TypeId::BuiltinType; } // NOLINT
private:
friend class Context;
// Private constructor
BuiltinType(Context *ctx, uint32_t size, uint32_t alignment, Kind kind)
: Type(ctx, size, alignment, TypeId::BuiltinType), kind_(kind) {}
private:
Kind kind_;
private:
static const char *cpp_names[];
static const char *tpl_names[];
static const uint64_t SIZES[];
static const uint64_t ALIGNMENTS[];
static const bool PRIMITIVE_FLAGS[];
static const bool FLOATING_POINT_FLAGS[];
static const bool SIGNED_FLAGS[];
};
/**
* String type
*/
class StringType : public Type {
public:
/**
* Static Constructor
* @param ctx ast context to use
* @return a string type
*/
static StringType *Get(Context *ctx);
/**
* @param type checked type
* @return whether type is a string type.
*/
static bool classof(const Type *type) { return type->GetTypeId() == TypeId::StringType; } // NOLINT
private:
friend class Context;
// Private constructor
explicit StringType(Context *ctx) : Type(ctx, sizeof(int8_t *), alignof(int8_t *), TypeId::StringType) {}
};
/**
* Pointer type
*/
class PointerType : public Type {
public:
/**
* @return base type
*/
Type *Base() const { return base_; }
/**
* Static Constructor
* @param base type
* @return pointer to base type
*/
static PointerType *Get(Type *base);
/**
* @param type checked type
* @return whether type is a pointer type.
*/
static bool classof(const Type *type) { return type->GetTypeId() == TypeId::PointerType; } // NOLINT
private:
// Private constructor
explicit PointerType(Type *base)
: Type(base->GetContext(), sizeof(int8_t *), alignof(int8_t *), TypeId::PointerType), base_(base) {}
private:
Type *base_;
};
/**
* Array type
*/
class ArrayType : public Type {
public:
/**
* @return length of the array
*/
uint64_t Length() const { return length_; }
/**
* @return element type
*/
Type *ElementType() const { return elem_type_; }
/**
* @return whether the length is known
*/
bool HasKnownLength() const { return length_ != 0; }
/**
* @return whether the length is unknown
*/
bool HasUnknownLength() const { return !HasKnownLength(); }
/**
* Construction
* @param length of the array
* @param elem_type element type
* @return the array type
*/
static ArrayType *Get(uint64_t length, Type *elem_type);
/**
* @return whether type is an array type.
*/
static bool classof(const Type *type) { return type->GetTypeId() == TypeId::ArrayType; } // NOLINT
private:
// Private constructor
explicit ArrayType(uint64_t length, Type *elem_type)
: Type(elem_type->GetContext(),
(length == 0 ? sizeof(uint8_t *) : elem_type->Size() * static_cast<uint32_t>(length)),
(length == 0 ? alignof(uint8_t *) : elem_type->Alignment()), TypeId::ArrayType),
length_(length),
elem_type_(elem_type) {}
private:
uint64_t length_;
Type *elem_type_;
};
/**
* A field is a pair containing a name and a type. It is used to represent both fields within a struct, and parameters
* to a function.
*/
struct Field {
/**
* Name of the field
*/
Identifier name_;
/**
* Type of the field
*/
Type *type_;
/**
* Constructor
* @param name of the field
* @param type of the field
*/
Field(const Identifier &name, Type *type) : name_(name), type_(type) {}
/**
* @param other rhs of the comparison
* @return whether this == other
*/
bool operator==(const Field &other) const noexcept { return name_ == other.name_ && type_ == other.type_; }
};
/**
* Function type
*/
class FunctionType : public Type {
public:
/**
* @return list of parameters
*/
const util::RegionVector<Field> &Params() const { return params_; }
/**
* @return numner of parameters
*/
uint32_t NumParams() const { return static_cast<uint32_t>(Params().size()); }
/**
* @return return type of the function
*/
Type *ReturnType() const { return ret_; }
/**
* Static Constructor
* @param params list of parameters
* @param ret return type
* @return the function type
*/
static FunctionType *Get(util::RegionVector<Field> &¶ms, Type *ret);
/**
* @param type type to compare with
* @return whether type is of function type
*/
static bool classof(const Type *type) { return type->GetTypeId() == TypeId::FunctionType; } // NOLINT
private:
// Private constructor
explicit FunctionType(util::RegionVector<Field> &¶ms, Type *ret);
private:
util::RegionVector<Field> params_;
Type *ret_;
};
/**
* Hash-map type
*/
class MapType : public Type {
public:
/**
* @return type of the keys
*/
Type *KeyType() const { return key_type_; }
/**
* @return type of values
*/
Type *ValueType() const { return val_type_; }
/**
* Static Constructor
* @param key_type type of the keys
* @param value_type type of the values
* @return constructed map type
*/
static MapType *Get(Type *key_type, Type *value_type);
/**
* @param type to compare with
* @return whether type is of map type.
*/
static bool classof(const Type *type) { return type->GetTypeId() == TypeId::MapType; } // NOLINT
private:
// Private Constructor
MapType(Type *key_type, Type *val_type);
private:
Type *key_type_;
Type *val_type_;
};
/**
* Struct type
*/
class StructType : public Type {
public:
/**
* @return list of fields
*/
const util::RegionVector<Field> &Fields() const { return fields_; }
/**
* @param name field to lookup
* @return type of the field
*/
Type *LookupFieldByName(Identifier name) const {
for (const auto &field : Fields()) {
if (field.name_ == name) {
return field.type_;
}
}
return nullptr;
}
/**
* @param name field of to lookup
* @return offset of the field
*/
uint32_t GetOffsetOfFieldByName(Identifier name) const {
for (uint32_t i = 0; i < fields_.size(); i++) {
if (fields_[i].name_ == name) {
return field_offsets_[i];
}
}
return 0;
}
/**
* @param other struct to compare to
* @return whether this and other are identical
*/
bool IsLayoutIdentical(const StructType &other) const { return (this == &other || Fields() == other.Fields()); }
/**
* Note: fields cannot be empty!
* Static constructor
* @param ctx ast context
* @param fields list of types
* @return constructor type
*/
static StructType *Get(Context *ctx, util::RegionVector<Field> &&fields);
/**
* Static constructor
* @param fields list of types
* @return constructor type
*/
static StructType *Get(util::RegionVector<Field> &&fields);
/**
* @param type checked type
* @return whether type is a struct type.
*/
static bool classof(const Type *type) { return type->GetTypeId() == TypeId::StructType; } // NOLINT
private:
// Private constructor
explicit StructType(Context *ctx, uint32_t size, uint32_t alignment, util::RegionVector<Field> &&fields,
util::RegionVector<uint32_t> &&field_offsets);
private:
util::RegionVector<Field> fields_;
util::RegionVector<uint32_t> field_offsets_;
};
// ---------------------------------------------------------
// Type implementation below
// ---------------------------------------------------------
inline Type *Type::GetPointeeType() const {
if (auto *ptr_type = SafeAs<PointerType>()) {
return ptr_type->Base();
}
return nullptr;
}
inline bool Type::IsSpecificBuiltin(uint16_t kind) const {
if (auto *builtin_type = SafeAs<BuiltinType>()) {
return builtin_type->GetKind() == static_cast<BuiltinType::Kind>(kind);
}
return false;
}
inline bool Type::IsNilType() const { return IsSpecificBuiltin(BuiltinType::Nil); }
inline bool Type::IsBoolType() const { return IsSpecificBuiltin(BuiltinType::Bool); }
inline bool Type::IsIntegerType() const {
if (auto *builtin_type = SafeAs<BuiltinType>()) {
return builtin_type->IsInteger();
}
return false;
}
inline bool Type::IsFloatType() const {
if (auto *builtin_type = SafeAs<BuiltinType>()) {
return builtin_type->IsFloatingPoint();
}
return false;
}
inline bool Type::IsSqlValueType() const {
if (auto *builtin_type = SafeAs<BuiltinType>()) {
return builtin_type->IsSqlValue();
}
return false;
}
inline bool Type::IsSqlAggregatorType() const {
if (auto *builtin_type = SafeAs<BuiltinType>()) {
return builtin_type->IsSqlAggregatorType();
}
return false;
}
} // namespace terrier::execution::ast
| 31.501935 | 119 | 0.596379 | [
"object"
] |
6df058057f745bea7b4324fa7c1092753d21495c | 12,612 | h | C | src/core/options.h | spencersutton/nng | 9bc988bbb33d99c90da417474ce736c54e990b66 | [
"MIT"
] | null | null | null | src/core/options.h | spencersutton/nng | 9bc988bbb33d99c90da417474ce736c54e990b66 | [
"MIT"
] | null | null | null | src/core/options.h | spencersutton/nng | 9bc988bbb33d99c90da417474ce736c54e990b66 | [
"MIT"
] | null | null | null | //
// Copyright 2018 Staysail Systems, Inc. <info@staysail.tech>
// Copyright 2018 Capitar IT Group BV <info@capitar.com>
// Copyright 2018 Devolutions <info@devolutions.net>
//
// This software is supplied under the terms of the MIT License, a
// copy of which should be located in the distribution where this
// file was obtained (LICENSE.txt). A copy of the license may also be
// found online at https://opensource.org/licenses/MIT.
//
#ifndef CORE_OPTIONS_H
#define CORE_OPTIONS_H
// Integer limits.
#define NNI_MAXINT ((int) 2147483647)
#define NNI_MININT ((int) -2147483648)
// We limit the maximum size to 4GB. That's intentional because some of the
// underlying protocols cannot cope with anything bigger than 32-bits.
#define NNI_MINSZ (0)
#define NNI_MAXSZ ((size_t) 0xffffffff)
// Option helpers. These can be called from protocols or transports
// in their own option handling, centralizing the logic for dealing with
// variable sized options.
extern int nni_copyin_ms(nni_duration *, const void *, size_t, nni_type);
extern int nni_copyin_bool(bool *, const void *, size_t, nni_type);
extern int nni_copyin_int(int *, const void *, size_t, int, int, nni_type);
extern int nni_copyin_size(
size_t *, const void *, size_t, size_t, size_t, nni_type);
extern int nni_copyin_str(char *, const void *, size_t, size_t, nni_type);
extern int nni_copyin_ptr(void **, const void *, size_t, nni_type);
extern int nni_copyin_u64(uint64_t *, const void *, size_t, nni_type);
extern int nni_copyin_sockaddr(nng_sockaddr *, const void *, size_t, nni_type);
// nni_copyout_xxx copies out a type of the named value. It assumes that
// the type is aligned and the size correct, unless NNI_TYPE_OPAQUE is passed.
extern int nni_copyout(const void *, size_t, void *, size_t *);
extern int nni_copyout_bool(bool, void *, size_t *, nni_type);
extern int nni_copyout_int(int, void *, size_t *, nni_type);
extern int nni_copyout_ms(nng_duration, void *, size_t *, nni_type);
extern int nni_copyout_ptr(void *, void *, size_t *, nni_type);
extern int nni_copyout_size(size_t, void *, size_t *, nni_type);
extern int nni_copyout_sockaddr(
const nng_sockaddr *, void *, size_t *, nni_type);
extern int nni_copyout_u64(uint64_t, void *, size_t *, nni_type);
// nni_copyout_str copies out a string. If the type is NNI_TYPE_STRING,
// then it passes through a pointer, created by nni_strdup().
extern int nni_copyout_str(const char *, void *, size_t *, nni_type);
// nni_option is used for socket, protocol, transport, and similar options.
// Note that only for transports, the o_set member may be called with a NULL
// instance parameter, in which case the request should only validate the
// argument and do nothing further.
typedef struct nni_option_s nni_option;
struct nni_option_s {
// o_name is the name of the option.
const char *o_name;
// o_get is used to retrieve the value of the option. The
// size supplied will limit how much data is copied. Regardless,
// the actual size of the object that would have been copied
// is supplied by the function in the size. If the object did
// not fit, then NNG_EINVAL is returned.
int (*o_get)(void *, void *, size_t *, nni_type);
// o_set is used to set the value of the option. For transport
// endpoints only, the instance parameter (first argument) may be
// NULL, in which case only a generic validation of the parameters
// is performed. (This is used when setting socket options before
int (*o_set)(void *, const void *, size_t, nni_type);
};
typedef struct nni_chkoption_s nni_chkoption;
struct nni_chkoption_s {
const char *o_name;
// o_check can be NULL for read-only options
int (*o_check)(const void *, size_t, nni_type);
};
// nni_getopt and nni_setopt are helper functions to implement options
// based on arrays of nni_option structures.
extern int nni_getopt(
const nni_option *, const char *, void *, void *, size_t *, nni_type);
extern int nni_setopt(
const nni_option *, const char *, void *, const void *, size_t, nni_type);
extern int nni_chkopt(
const nni_chkoption *, const char *, const void *, size_t, nni_type);
//
// This next block sets up to define the various typed option functions.
// To make it easier to cover them all at once, we use macros.
//
#define NNI_DEFGET(base, pointer) \
int nng_##base##_get( \
nng_##base pointer s, const char *nm, void *vp, size_t *szp) \
{ \
return (nni_##base##_getx(s, nm, vp, szp, NNI_TYPE_OPAQUE)); \
}
#define NNI_DEFTYPEDGET(base, suffix, pointer, type, nnitype) \
int nng_##base##_get_##suffix( \
nng_##base pointer s, const char *nm, type *vp) \
{ \
size_t sz = sizeof(*vp); \
return (nni_##base##_getx(s, nm, vp, &sz, nnitype)); \
}
#define NNI_DEFGETALL(base) \
NNI_DEFGET(base, ) \
NNI_DEFTYPEDGET(base, int, , int, NNI_TYPE_INT32) \
NNI_DEFTYPEDGET(base, bool, , bool, NNI_TYPE_BOOL) \
NNI_DEFTYPEDGET(base, size, , size_t, NNI_TYPE_SIZE) \
NNI_DEFTYPEDGET(base, uint64, , uint64_t, NNI_TYPE_UINT64) \
NNI_DEFTYPEDGET(base, string, , char *, NNI_TYPE_STRING) \
NNI_DEFTYPEDGET(base, ptr, , void *, NNI_TYPE_POINTER) \
NNI_DEFTYPEDGET(base, ms, , nng_duration, NNI_TYPE_DURATION) \
NNI_DEFTYPEDGET(base, addr, , nng_sockaddr, NNI_TYPE_SOCKADDR)
#define NNI_DEFGETALL_PTR(base) \
NNI_DEFGET(base, *) \
NNI_DEFTYPEDGET(base, int, *, int, NNI_TYPE_INT32) \
NNI_DEFTYPEDGET(base, bool, *, bool, NNI_TYPE_BOOL) \
NNI_DEFTYPEDGET(base, size, *, size_t, NNI_TYPE_SIZE) \
NNI_DEFTYPEDGET(base, uint64, *, uint64_t, NNI_TYPE_UINT64) \
NNI_DEFTYPEDGET(base, string, *, char *, NNI_TYPE_STRING) \
NNI_DEFTYPEDGET(base, ptr, *, void *, NNI_TYPE_POINTER) \
NNI_DEFTYPEDGET(base, ms, *, nng_duration, NNI_TYPE_DURATION) \
NNI_DEFTYPEDGET(base, addr, *, nng_sockaddr, NNI_TYPE_SOCKADDR)
#define NNI_DEFSET(base, pointer) \
int nng_##base##_set( \
nng_##base pointer s, const char *nm, const void *vp, size_t sz) \
{ \
return (nni_##base##_setx(s, nm, vp, sz, NNI_TYPE_OPAQUE)); \
}
#define NNI_DEFTYPEDSETEX(base, suffix, pointer, type, len, nnitype) \
int nng_##base##_set_##suffix( \
nng_##base pointer s, const char *nm, type v) \
{ \
return (nni_##base##_setx(s, nm, &v, len, nnitype)); \
}
#define NNI_DEFTYPEDSET(base, suffix, pointer, type, nnitype) \
int nng_##base##_set_##suffix( \
nng_##base pointer s, const char *nm, type v) \
{ \
return (nni_##base##_setx(s, nm, &v, sizeof(v), nnitype)); \
}
#define NNI_DEFSTRINGSET(base, pointer) \
int nng_##base##_set_string( \
nng_##base pointer s, const char *nm, const char *v) \
{ \
return (nni_##base##_setx(s, nm, v, \
v != NULL ? strlen(v) + 1 : 0, NNI_TYPE_STRING)); \
}
#define NNI_DEFSOCKADDRSET(base, pointer) \
int nng_##base##_set_addr( \
nng_##base pointer s, const char *nm, const nng_sockaddr *v) \
{ \
return (nni_##base##_setx( \
s, nm, v, sizeof(*v), NNI_TYPE_SOCKADDR)); \
}
#define NNI_DEFSETALL(base) \
NNI_DEFSET(base, ) \
NNI_DEFTYPEDSET(base, int, , int, NNI_TYPE_INT32) \
NNI_DEFTYPEDSET(base, bool, , bool, NNI_TYPE_BOOL) \
NNI_DEFTYPEDSET(base, size, , size_t, NNI_TYPE_SIZE) \
NNI_DEFTYPEDSET(base, uint64, , uint64_t, NNI_TYPE_UINT64) \
NNI_DEFTYPEDSET(base, ms, , nng_duration, NNI_TYPE_DURATION) \
NNI_DEFTYPEDSET(base, ptr, , void *, NNI_TYPE_POINTER) \
NNI_DEFSTRINGSET(base, ) \
NNI_DEFSOCKADDRSET(base, )
#define NNI_DEFSETALL_PTR(base) \
NNI_DEFSET(base, *) \
NNI_DEFTYPEDSET(base, int, *, int, NNI_TYPE_INT32) \
NNI_DEFTYPEDSET(base, bool, *, bool, NNI_TYPE_BOOL) \
NNI_DEFTYPEDSET(base, size, *, size_t, NNI_TYPE_SIZE) \
NNI_DEFTYPEDSET(base, uint64, *, uint64_t, NNI_TYPE_UINT64) \
NNI_DEFTYPEDSET(base, ms, *, nng_duration, NNI_TYPE_DURATION) \
NNI_DEFTYPEDSET(base, ptr, *, void *, NNI_TYPE_POINTER) \
NNI_DEFSTRINGSET(base, *) \
NNI_DEFSOCKADDRSET(base, *)
#define NNI_LEGACY_DEFGET(base) \
int nng_##base##_getopt( \
nng_##base s, const char *nm, void *vp, size_t *szp) \
{ \
return (nng_##base##_get(s, nm, vp, szp)); \
}
#define NNI_LEGACY_DEFTYPEDGET(base, suffix, type) \
int nng_##base##_getopt_##suffix( \
nng_##base s, const char *nm, type *vp) \
{ \
return (nng_##base##_get_##suffix(s, nm, vp)); \
}
#define NNI_LEGACY_DEFSOCKADDRGET(base) \
int nng_##base##_getopt_sockaddr( \
nng_##base s, const char *nm, nng_sockaddr *vp) \
{ \
return (nng_##base##_get_addr(s, nm, vp)); \
}
#define NNI_LEGACY_DEFGETALL(base) \
NNI_LEGACY_DEFGET(base) \
NNI_LEGACY_DEFTYPEDGET(base, int, int) \
NNI_LEGACY_DEFTYPEDGET(base, bool, bool) \
NNI_LEGACY_DEFTYPEDGET(base, size, size_t) \
NNI_LEGACY_DEFTYPEDGET(base, uint64, uint64_t) \
NNI_LEGACY_DEFTYPEDGET(base, string, char *) \
NNI_LEGACY_DEFTYPEDGET(base, ptr, void *) \
NNI_LEGACY_DEFTYPEDGET(base, ms, nng_duration) \
NNI_LEGACY_DEFSOCKADDRGET(base)
#define NNI_LEGACY_DEFSET(base) \
int nng_##base##_setopt( \
nng_##base s, const char *nm, const void *vp, size_t sz) \
{ \
return (nng_##base##_set(s, nm, vp, sz)); \
}
#define NNI_LEGACY_DEFTYPEDSET(base, suffix, type) \
int nng_##base##_setopt_##suffix(nng_##base s, const char *nm, type v) \
{ \
return (nng_##base##_set_##suffix(s, nm, v)); \
}
#define NNI_LEGACY_DEFSTRINGSET(base) \
int nng_##base##_setopt_string( \
nng_##base s, const char *nm, const char *v) \
{ \
return (nng_##base##_set_string(s, nm, v)); \
}
#define NNI_LEGACY_DEFSOCKADDRSET(base) \
int nng_##base##_setopt_sockaddr( \
nng_##base s, const char *nm, const nng_sockaddr *v) \
{ \
return (nng_##base##_set_addr(s, nm, v)); \
}
#define NNI_LEGACY_DEFSETALL(base) \
NNI_LEGACY_DEFSET(base) \
NNI_LEGACY_DEFTYPEDSET(base, int, int) \
NNI_LEGACY_DEFTYPEDSET(base, bool, bool) \
NNI_LEGACY_DEFTYPEDSET(base, size, size_t) \
NNI_LEGACY_DEFTYPEDSET(base, ms, nng_duration) \
NNI_LEGACY_DEFTYPEDSET(base, ptr, void*) \
NNI_LEGACY_DEFSTRINGSET(base) \
NNI_LEGACY_DEFSOCKADDRSET(base)
#endif // CORE_OPTIONS_H
| 47.772727 | 80 | 0.562559 | [
"object"
] |
a304396b5fa22737dd81da853ce73baf85faa442 | 9,597 | h | C | include/tfrt/support/thread_local.h | freedomtan/tfrt | 61e8e4b4fc17e32a25723708eb39b66cc0de7adb | [
"Apache-2.0"
] | 1 | 2020-06-04T02:20:47.000Z | 2020-06-04T02:20:47.000Z | include/tfrt/support/thread_local.h | freedomtan/tfrt | 61e8e4b4fc17e32a25723708eb39b66cc0de7adb | [
"Apache-2.0"
] | null | null | null | include/tfrt/support/thread_local.h | freedomtan/tfrt | 61e8e4b4fc17e32a25723708eb39b66cc0de7adb | [
"Apache-2.0"
] | 1 | 2020-08-03T20:23:58.000Z | 2020-08-03T20:23:58.000Z | /*
* Copyright 2020 The TensorFlow Runtime Authors
*
* 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.
*/
//===- thread_local.h -------------------------------------------*- C++ -*-===//
//
// Thread local container that does not depend on `thread_local` storage.
//
// Unlike thread local storage, objects managed by a ThreadLocal instance are
// not bound to a thread's lifetime, but are destructed together with the
// ThreadLocal instance that created them. It is also possible to create
// multiple instances in the same function, unlike "real" thread_locals that are
// initialized the first time control passes through their declaration.
//
// When a thread requests a unique element from the ThreadLocal instance, it
// gets an element designated for that thread. It is possible to specify custom
// element constructor by providing the `Constructor` type parameter. By default
// elements are default constructed the first time they are accessed.
//
// As long as the number of unique threads accessing an intance of a ThreadLocal
// is smaller than `capacity`, it is lock-free and wait-free. After the number
// of stored elements reaches `capacity` it is using mutex for synchronization.
//
// WARNING: ThreadLocal uses the OS-specific value returned by
// std::this_thread::get_id() to identify threads. This value is not guaranteed
// to be unique except for the life of the thread. A newly created thread may
// get an OS-specific ID equal to that of an already destroyed thread. However
// this should not be a concern in practice, because it would still mean that
// only one thread can access an element, and because thread construction
// synchronizes with thread destruction it will be data race free. To the user
// program different threads sharing the same thread should be indistinguishable
// (unless it uses native thread_local storage).
//
// Example:
//
// ThreadLocal<T> container = ...
//
// std::thread([&]() { T& value = container.Local(); }).join(); // thread #1
// std::thread([&]() { T& value = container.Local(); }).join(); // thread #2
//
// If threads #1 and #2 happened to have the same thread id they will get a
// reference to the same element. However it is guaranteed that the element
// will not be shared between threads running concurrently.
//
//===----------------------------------------------------------------------===//
#ifndef TFRT_SUPPORT_THREAD_LOCAL_H_
#define TFRT_SUPPORT_THREAD_LOCAL_H_
#include <atomic>
#include <thread>
#include <unordered_map>
#include <vector>
#include "llvm/ADT/STLExtras.h"
#include "mutex.h"
#include "tfrt/support/forward_decls.h"
#include "tfrt/support/thread_annotations.h"
namespace tfrt {
namespace internal {
template <typename T>
struct DefaultConstructor {
T Construct() { return T(); }
};
} // namespace internal
template <typename T, typename Constructor = internal::DefaultConstructor<T>>
class ThreadLocal {
public:
// Computes optimal capacity for the number of threads that are expected to
// access an intance of a ThreadLocal. Lookup operation has a constant
// expected time, as long as load factor is less than one.
// Reference: https://en.wikipedia.org/wiki/Linear_probing#Analysis
static size_t Capacity(size_t num_threads) { return num_threads * 2; }
template <typename... Args>
explicit ThreadLocal(size_t capacity, Args... args)
: capacity_(capacity),
constructor_(std::forward<Args>(args)...),
num_lock_free_entries_(0) {
assert(capacity_ >= 0);
data_.resize(capacity);
ptrs_ = new std::atomic<Entry*>[capacity_];
for (int i = 0; i < capacity_; ++i) {
ptrs_[i].store(nullptr, std::memory_order_relaxed);
}
}
~ThreadLocal() { delete[] ptrs_; }
T& Local() {
std::thread::id this_thread = std::this_thread::get_id();
if (capacity_ == 0) return SpilledLocal(this_thread);
size_t h = std::hash<std::thread::id>()(this_thread);
const int start_idx = h % capacity_;
// NOTE: From the definition of `std::this_thread::get_id()` it is
// guaranteed that we never can have concurrent calls to this functions
// with the same thread id. If we didn't find an entry during the initial
// traversal, it is guaranteed that no one else could have inserted it
// concurrently.
// Check if we already have an entry for `this_thread`.
int idx = start_idx;
while (ptrs_[idx].load(std::memory_order_acquire) != nullptr) {
Entry& entry = *(ptrs_[idx].load());
if (entry.thread_id == this_thread) return entry.value;
idx += 1;
if (idx >= capacity_) idx -= capacity_;
if (idx == start_idx) break;
}
// If we are here, it means that we found an insertion point in lookup
// table at `idx`, or we did a full traversal and table is full.
// If lock-free storage is full, fallback on mutex.
if (num_lock_free_entries_.load(std::memory_order_relaxed) >= capacity_)
return SpilledLocal(this_thread);
// We double check that we still have space to insert an element into a lock
// free storage. If old value in `num_lock_free_entries_` is larger than
// capacity, it means that some other thread added an element while
// we were traversing lookup table.
int insertion_index =
num_lock_free_entries_.fetch_add(1, std::memory_order_relaxed);
if (insertion_index >= capacity_) return SpilledLocal(this_thread);
// At this point it's guaranteed that we can access
// data_[insertion_index_] without a data race.
data_[insertion_index] = {this_thread, constructor_.Construct()};
// That's the pointer we'll put into the lookup table.
Entry* inserted = data_[insertion_index].getPointer();
// We'll use nullptr pointer to Entry in a compare-and-swap loop.
Entry* empty = nullptr;
// Now we have to find an insertion point into the lookup table. We start
// from the `idx` that was identified as an insertion point above, it's
// guaranteed that we will have an empty entry somewhere in a lookup table
// (because we created an entry in the `data_`).
const int insertion_idx = idx;
do {
// Always start search from the original insertion candidate.
idx = insertion_idx;
while (ptrs_[idx].load(std::memory_order_relaxed) != nullptr) {
idx += 1;
if (idx >= capacity_) idx -= capacity_;
// If we did a full loop, it means that we don't have any free entries
// in the lookup table, and this means that something is terribly wrong.
assert(idx != insertion_idx);
}
// Atomic store of the pointer guarantees that any other thread, that will
// follow this pointer will see all the mutations in the `data_`.
} while (!ptrs_[idx].compare_exchange_weak(empty, inserted,
std::memory_order_release));
return inserted->value;
}
// WARN: It's not thread safe to call it concurrently with `local()`.
void ForEach(llvm::function_ref<void(std::thread::id, T&)> f) {
// Reading directly from `data_` is unsafe, because only store to the
// entry in `ptrs_` makes all changes visible to other threads.
for (int i = 0; i < capacity_; ++i) {
Entry* entry = ptrs_[i].load(std::memory_order_acquire);
if (entry == nullptr) continue;
f(entry->thread_id, entry->value);
}
// We did not spill into the map based storage.
if (num_lock_free_entries_.load(std::memory_order_relaxed) < capacity_)
return;
mutex_lock lock(mu_);
for (auto& kv : spilled_) {
f(kv.first, kv.second);
}
}
private:
struct Entry {
std::thread::id thread_id;
T value;
};
// Use synchronized unordered_map when lock-free storage is full.
T& SpilledLocal(std::thread::id this_thread) {
mutex_lock lock(mu_);
auto it = spilled_.find(this_thread);
if (it != spilled_.end()) return it->second;
auto inserted = spilled_.emplace(this_thread, constructor_.Construct());
assert(inserted.second);
return (*inserted.first).second;
}
const size_t capacity_;
Constructor constructor_;
// Storage that backs lock-free lookup table `ptrs_`. Entries stored
// contiguously starting from index 0. Entries stored as optional so that
// `T` can be non-default-constructible.
std::vector<Optional<Entry>> data_;
// Atomic pointers to the data stored in `data_`. Used as a lookup table for
// linear probing hash map (https://en.wikipedia.org/wiki/Linear_probing).
std::atomic<Entry*>* ptrs_;
// Number of entries stored in the lock free storage.
std::atomic<int> num_lock_free_entries_;
// When the lock-free storage is full we spill to the unordered map
// synchronized with a mutex. In practice this should never happen, if
// `capacity_` is a reasonable estimate of the number of unique threads that
// are expected to access this instance of ThreadLocal.
mutex mu_;
std::unordered_map<std::thread::id, T> spilled_ TFRT_GUARDED_BY(mu_);
};
} // namespace tfrt
#endif // TFRT_SUPPORT_THREAD_LOCAL_H_
| 39.331967 | 80 | 0.691779 | [
"vector"
] |
a3053a46eaeeea3480d6e97fb324c8447b9b83e8 | 1,502 | h | C | services/audiopolicy/engine/common/include/LastRemovableMediaDevices.h | Dreadwyrm/lhos_frameworks_av | 62c63ccfdf5c79a3ad9be4836f473da9398c671b | [
"Apache-2.0"
] | null | null | null | services/audiopolicy/engine/common/include/LastRemovableMediaDevices.h | Dreadwyrm/lhos_frameworks_av | 62c63ccfdf5c79a3ad9be4836f473da9398c671b | [
"Apache-2.0"
] | null | null | null | services/audiopolicy/engine/common/include/LastRemovableMediaDevices.h | Dreadwyrm/lhos_frameworks_av | 62c63ccfdf5c79a3ad9be4836f473da9398c671b | [
"Apache-2.0"
] | 2 | 2021-07-08T07:42:11.000Z | 2021-07-09T21:56:10.000Z | /*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_LAST_REMOVABLE_MEDIA_DEVICES_H
#define ANDROID_LAST_REMOVABLE_MEDIA_DEVICES_H
#include <vector>
#include <HwModule.h>
#include <system/audio_policy.h>
namespace android {
typedef enum {
GROUP_NONE = -1,
GROUP_WIRED,
GROUP_BT_A2DP,
NUM_GROUP
} device_out_group_t;
class LastRemovableMediaDevices
{
public:
void setRemovableMediaDevices(sp<DeviceDescriptor> desc, audio_policy_dev_state_t state);
std::vector<audio_devices_t> getLastRemovableMediaDevices(
device_out_group_t group = GROUP_NONE) const;
private:
struct DeviceGroupDescriptor {
sp<DeviceDescriptor> desc;
device_out_group_t group;
};
std::vector<DeviceGroupDescriptor> mMediaDevices;
device_out_group_t getDeviceOutGroup(audio_devices_t device) const;
};
} // namespace android
#endif // ANDROID_LAST_REMOVABLE_MEDIA_DEVICES_H
| 28.339623 | 93 | 0.756325 | [
"vector"
] |
a308e2ac1f5c3db375cfaeb1af173b5259ee43aa | 7,079 | h | C | aws-cpp-sdk-migrationhubstrategy/include/aws/migrationhubstrategy/model/SystemInfo.h | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-12T08:09:30.000Z | 2022-02-12T08:09:30.000Z | aws-cpp-sdk-migrationhubstrategy/include/aws/migrationhubstrategy/model/SystemInfo.h | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-migrationhubstrategy/include/aws/migrationhubstrategy/model/SystemInfo.h | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/migrationhubstrategy/MigrationHubStrategyRecommendations_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/migrationhubstrategy/model/OSInfo.h>
#include <aws/migrationhubstrategy/model/NetworkInfo.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace MigrationHubStrategyRecommendations
{
namespace Model
{
/**
* <p> Information about the server that hosts application components.
* </p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/migrationhubstrategy-2020-02-19/SystemInfo">AWS
* API Reference</a></p>
*/
class AWS_MIGRATIONHUBSTRATEGYRECOMMENDATIONS_API SystemInfo
{
public:
SystemInfo();
SystemInfo(Aws::Utils::Json::JsonView jsonValue);
SystemInfo& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p> CPU architecture type for the server. </p>
*/
inline const Aws::String& GetCpuArchitecture() const{ return m_cpuArchitecture; }
/**
* <p> CPU architecture type for the server. </p>
*/
inline bool CpuArchitectureHasBeenSet() const { return m_cpuArchitectureHasBeenSet; }
/**
* <p> CPU architecture type for the server. </p>
*/
inline void SetCpuArchitecture(const Aws::String& value) { m_cpuArchitectureHasBeenSet = true; m_cpuArchitecture = value; }
/**
* <p> CPU architecture type for the server. </p>
*/
inline void SetCpuArchitecture(Aws::String&& value) { m_cpuArchitectureHasBeenSet = true; m_cpuArchitecture = std::move(value); }
/**
* <p> CPU architecture type for the server. </p>
*/
inline void SetCpuArchitecture(const char* value) { m_cpuArchitectureHasBeenSet = true; m_cpuArchitecture.assign(value); }
/**
* <p> CPU architecture type for the server. </p>
*/
inline SystemInfo& WithCpuArchitecture(const Aws::String& value) { SetCpuArchitecture(value); return *this;}
/**
* <p> CPU architecture type for the server. </p>
*/
inline SystemInfo& WithCpuArchitecture(Aws::String&& value) { SetCpuArchitecture(std::move(value)); return *this;}
/**
* <p> CPU architecture type for the server. </p>
*/
inline SystemInfo& WithCpuArchitecture(const char* value) { SetCpuArchitecture(value); return *this;}
/**
* <p> File system type for the server. </p>
*/
inline const Aws::String& GetFileSystemType() const{ return m_fileSystemType; }
/**
* <p> File system type for the server. </p>
*/
inline bool FileSystemTypeHasBeenSet() const { return m_fileSystemTypeHasBeenSet; }
/**
* <p> File system type for the server. </p>
*/
inline void SetFileSystemType(const Aws::String& value) { m_fileSystemTypeHasBeenSet = true; m_fileSystemType = value; }
/**
* <p> File system type for the server. </p>
*/
inline void SetFileSystemType(Aws::String&& value) { m_fileSystemTypeHasBeenSet = true; m_fileSystemType = std::move(value); }
/**
* <p> File system type for the server. </p>
*/
inline void SetFileSystemType(const char* value) { m_fileSystemTypeHasBeenSet = true; m_fileSystemType.assign(value); }
/**
* <p> File system type for the server. </p>
*/
inline SystemInfo& WithFileSystemType(const Aws::String& value) { SetFileSystemType(value); return *this;}
/**
* <p> File system type for the server. </p>
*/
inline SystemInfo& WithFileSystemType(Aws::String&& value) { SetFileSystemType(std::move(value)); return *this;}
/**
* <p> File system type for the server. </p>
*/
inline SystemInfo& WithFileSystemType(const char* value) { SetFileSystemType(value); return *this;}
/**
* <p> Networking information related to a server. </p>
*/
inline const Aws::Vector<NetworkInfo>& GetNetworkInfoList() const{ return m_networkInfoList; }
/**
* <p> Networking information related to a server. </p>
*/
inline bool NetworkInfoListHasBeenSet() const { return m_networkInfoListHasBeenSet; }
/**
* <p> Networking information related to a server. </p>
*/
inline void SetNetworkInfoList(const Aws::Vector<NetworkInfo>& value) { m_networkInfoListHasBeenSet = true; m_networkInfoList = value; }
/**
* <p> Networking information related to a server. </p>
*/
inline void SetNetworkInfoList(Aws::Vector<NetworkInfo>&& value) { m_networkInfoListHasBeenSet = true; m_networkInfoList = std::move(value); }
/**
* <p> Networking information related to a server. </p>
*/
inline SystemInfo& WithNetworkInfoList(const Aws::Vector<NetworkInfo>& value) { SetNetworkInfoList(value); return *this;}
/**
* <p> Networking information related to a server. </p>
*/
inline SystemInfo& WithNetworkInfoList(Aws::Vector<NetworkInfo>&& value) { SetNetworkInfoList(std::move(value)); return *this;}
/**
* <p> Networking information related to a server. </p>
*/
inline SystemInfo& AddNetworkInfoList(const NetworkInfo& value) { m_networkInfoListHasBeenSet = true; m_networkInfoList.push_back(value); return *this; }
/**
* <p> Networking information related to a server. </p>
*/
inline SystemInfo& AddNetworkInfoList(NetworkInfo&& value) { m_networkInfoListHasBeenSet = true; m_networkInfoList.push_back(std::move(value)); return *this; }
/**
* <p> Operating system corresponding to a server. </p>
*/
inline const OSInfo& GetOsInfo() const{ return m_osInfo; }
/**
* <p> Operating system corresponding to a server. </p>
*/
inline bool OsInfoHasBeenSet() const { return m_osInfoHasBeenSet; }
/**
* <p> Operating system corresponding to a server. </p>
*/
inline void SetOsInfo(const OSInfo& value) { m_osInfoHasBeenSet = true; m_osInfo = value; }
/**
* <p> Operating system corresponding to a server. </p>
*/
inline void SetOsInfo(OSInfo&& value) { m_osInfoHasBeenSet = true; m_osInfo = std::move(value); }
/**
* <p> Operating system corresponding to a server. </p>
*/
inline SystemInfo& WithOsInfo(const OSInfo& value) { SetOsInfo(value); return *this;}
/**
* <p> Operating system corresponding to a server. </p>
*/
inline SystemInfo& WithOsInfo(OSInfo&& value) { SetOsInfo(std::move(value)); return *this;}
private:
Aws::String m_cpuArchitecture;
bool m_cpuArchitectureHasBeenSet;
Aws::String m_fileSystemType;
bool m_fileSystemTypeHasBeenSet;
Aws::Vector<NetworkInfo> m_networkInfoList;
bool m_networkInfoListHasBeenSet;
OSInfo m_osInfo;
bool m_osInfoHasBeenSet;
};
} // namespace Model
} // namespace MigrationHubStrategyRecommendations
} // namespace Aws
| 32.925581 | 163 | 0.672411 | [
"vector",
"model"
] |
a312a9d98f217f81b6fdf124ee8d5c92dcfb6e55 | 4,258 | h | C | i18n/xx/msg.h | JadedCtrl/citrine | 26f9e4279bfc32f69ae7de8e61010b3ba06dc579 | [
"BSD-2-Clause"
] | 92 | 2015-03-12T09:57:15.000Z | 2022-03-18T03:35:50.000Z | i18n/xx/msg.h | JadedCtrl/citrine | 26f9e4279bfc32f69ae7de8e61010b3ba06dc579 | [
"BSD-2-Clause"
] | 64 | 2016-01-26T06:51:50.000Z | 2021-03-21T11:26:23.000Z | i18n/xx/msg.h | JadedCtrl/citrine | 26f9e4279bfc32f69ae7de8e61010b3ba06dc579 | [
"BSD-2-Clause"
] | 21 | 2016-01-25T11:32:18.000Z | 2022-03-02T22:44:30.000Z | #define CTR_MSG_LANG_CODE "en_us"
#define CTR_MSG_WELCOME "Citrine Programming Language EN/US\n"
#define CTR_MSG_COPYRIGHT "Written by Gabor de Mooij © copyright 2019, Licensed BSD.\n"
#define CTR_MSG_USAGE_G "Not enough arguments. Usage: ctr -g file1.h file2.h"
#define CTR_MSG_USAGE_T "Not enough arguments. Usage: ctr -t d.dict program.ctr"
#define CTR_ERR_LEX "%s on line: %d. \n"
#define CTR_ERR_TOKBUFF "Token Buffer Exausted. Tokens may not exceed 255 bytes"
#define CTR_ERR_OOM "Out of memory."
#define CTR_ERR_SYNTAX "Parse error, unexpected %s ( %s: %d )\n"
#define CTR_ERR_LONG "Message too long.\n"
#define CTR_ERR_EXP_COLON "Expected colon.\n"
#define CTR_ERR_EXP_MSG "Expected message.\n"
#define CTR_ERR_EXP_PCLS "Expected ).\n"
#define CTR_ERR_EXP_DOT "Expected a dot (.).\n"
#define CTR_ERR_EXP_KEY "Key should always be followed by a property name!\n"
#define CTR_ERR_EXP_VAR "Pointing hand should always be followed by variable!\n"
#define CTR_ERR_EXP_RCP "Expected a message recipient.\n"
#define CTR_ERR_EXP_MSG2 "Recipient cannot be followed by colon.\n"
#define CTR_ERR_INV_LAS "Invalid left-hand assignment.\n"
#define CTR_ERR_EXP_BLK "Expected block."
#define CTR_ERR_EXP_ARR "Expected list."
#define CTR_ERR_EXP_NUM "Expected number."
#define CTR_ERR_EXP_STR "Expected string."
#define CTR_ERR_DIVZERO "Division by zero."
#define CTR_ERR_BOUNDS "Index out of bounds."
#define CTR_ERR_REGEX "Could not compile regular expression."
#define CTR_ERR_SIPHKEY "Key must be exactly 16 bytes long."
#define CTR_SYM_OBJECT "[Object]"
#define CTR_SYM_BLOCK "[Block]"
#define CTR_SYM_FILE "[File (no path)]"
#define CTR_ERR_OPEN "Unable to open: %s."
#define CTR_ERR_DELETE "Unable to delete."
#define CTR_ERR_FOPENED "File has already been opened."
#define CTR_ERR_SEEK "Seek failed."
#define CTR_ERR_LOCK "Unable to lock."
#define CTR_ERR_RET "Invalid return expression.\n"
#define CTR_ERR_SEND "Cannot send message to receiver of type: %d \n"
#define CTR_ERR_KEYINX "Key index exhausted."
#define CTR_ERR_ANOMALY "Detected message level anomaly.\n"
#define CTR_ERR_UNCAUGHT "Uncatched error has occurred.\n"
#define CTR_ERR_NODE "Runtime Error. Invalid parse node: %d %s \n"
#define CTR_ERR_MISSING "Missing parse node\n"
#define CTR_ERR_FOPEN "Error while opening the file.\n"
#define CTR_ERR_RNUM "Must return a number."
#define CTR_ERR_RSTR "Must return a string."
#define CTR_ERR_RBOOL "Must return a boolean."
#define CTR_ERR_NESTING "Too many nested calls."
#define CTR_ERR_KNF "Key not found: "
#define CTR_ERR_ASSIGN "Cannot assign to undefined variable: "
#define CTR_ERR_EXEC "Unable to execute command."
#define CTR_MSG_DSC_FILE "file"
#define CTR_MSG_DSC_FLDR "folder"
#define CTR_MSG_DSC_SLNK "symbolic link"
#define CTR_MSG_DSC_CDEV "character device"
#define CTR_MSG_DSC_BDEV "block device"
#define CTR_MSG_DSC_SOCK "socket"
#define CTR_MSG_DSC_NPIP "named pipe"
#define CTR_MSG_DSC_OTHR "other"
#define CTR_MSG_DSC_TYPE "type"
#define CTR_TERR_LMISMAT "Language mismatch."
#define CTR_TERR_LONG "Translation error, message too long."
#define CTR_TERR_DICT "Error opening dictionary."
#define CTR_TERR_KMISMAT "Error: key mismatch %s %s on line %d\n"
#define CTR_TERR_ELONG "Dictionary entry too long."
#define CTR_TERR_AMWORD "Ambiguous word in dictionary: %s."
#define CTR_TERR_AMTRANS "Ambiguous translation in dictionary: %s."
#define CTR_TERR_TMISMAT "Keyword/Binary mismatch:"
#define CTR_TERR_BUFF "Unable to copy translation to buffer."
#define CTR_TERR_WARN "Warning: Not translated: "
#define CTR_TERR_TOK "Token length exceeds maximum buffer size."
#define CTR_TERR_PART "Part of keyword message token exceeds buffer limit."
#define CTR_TERR_COLONS "Different no. of colons."
#define CTR_MSG_ERROR "Error."
#define CTR_MERR_OOM "Out of memory. Failed to allocate %lu bytes.\n"
#define CTR_MERR_MALLOC "Out of memory. Failed to allocate %lu bytes (malloc failed). \n"
#define CTR_MERR_POOL "Unable to allocate memory pool.\n"
#define CTR_STDDATEFRMT "%Y-%m-%d %H:%M:%S"
#define CTR_STDTIMEZONE "UTC" | 53.898734 | 91 | 0.747064 | [
"object"
] |
a314634426a3ee0a3d9ff6e753aeb1b5d8d60020 | 3,876 | c | C | src/jwiringx_spi.c | wiringX/wiringX-java | 6b5c351139a45d07d71b9891851f04fbbd08e8ad | [
"MIT"
] | null | null | null | src/jwiringx_spi.c | wiringX/wiringX-java | 6b5c351139a45d07d71b9891851f04fbbd08e8ad | [
"MIT"
] | null | null | null | src/jwiringx_spi.c | wiringX/wiringX-java | 6b5c351139a45d07d71b9891851f04fbbd08e8ad | [
"MIT"
] | null | null | null | /*
* MIT License
*
* Copyright (c) 2016 Josua Mayer <josua.mayer97@gmail.com>
*
* 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.
*/
// generated JNI declerations
#include "eu_jm0_wiringX_wiringX.h"
// object cache
#include "jni-cache.h"
// utlity functions
#include "jni-util.h"
// limits for converting numeric types
#include <limits.h>
// malloc/free
#include <stdlib.h>
// the real wiringX
#include <wiringX.h>
/*
* Most platforms today have char as an 8 bit wide type.
* However there are weird platforms which cannot easily be supported.
*/
#if CHAR_BIT != 8
#error size of char is not 8
#endif
jint Java_eu_jm0_wiringX_wiringX_SPIGetFd(JNIEnv *env, jclass class, jint channel) {
// check arguments for valid range
if(RANGE_CHECK(channel, INT_MIN, INT_MAX)) {
// throw exception
throw_new_exception_cached(env, "java/lang/IllegalArgumentException", "Value out of Range", CACHE_CLASS_java_lang_IllegalArgumentException);
// return to java, return value will be ignored
return 0;
}
// call original function
return wiringXSPIGetFd((int)channel);
}
jint Java_eu_jm0_wiringX_wiringX_SPIDataRW(JNIEnv *env, jclass class, jint channel, jbyteArray data) {
// check arguments for valid range
if(RANGE_CHECK(channel, INT_MIN, INT_MAX)) {
// throw exception
throw_new_exception_cached(env, "java/lang/IllegalArgumentException", "Value out of Range", CACHE_CLASS_java_lang_IllegalArgumentException);
// return to java, return value will be ignored
return 0;
}
// check that data exists
if(data == NULL) {
// throw exception
throw_new_exception_cached(env, "java/lang/NullPointerException", "data must not be null", CACHE_CLASS_java_lang_NullPointerException);
// return to java, return value will be ignored
return 0;
}
// retrieve data size
jint len = (*env)->GetArrayLength(env, data);
// map data to C array
jbyte *datac = (*env)->GetByteArrayElements(env, data, NULL);
if(datac == NULL) {
// exception was thrown already, return to java
return 0;
}
// call original function
// data is to be treated unsigned, Java code must perform the necessary transformations
int r = wiringXSPIDataRW((int)channel, (unsigned char *)datac, (int)len);
// write back changes and release C array
(*env)->ReleaseByteArrayElements(env, data, datac, JNI_COMMIT);
// deliver result
return r;
}
jint Java_eu_jm0_wiringX_wiringX_SPISetup(JNIEnv *env, jclass class, jint channel, jint speed) {
// check arguments for valid range
if(RANGE_CHECK2(channel, speed, INT_MIN, INT_MAX)) {
// throw exception
throw_new_exception_cached(env, "java/lang/IllegalArgumentException", "Value out of Range", CACHE_CLASS_java_lang_IllegalArgumentException);
// return to java, return value will be ignored
return 0;
}
// call original function
return wiringXSPISetup((int)channel, (int)speed);
}
| 32.847458 | 142 | 0.749742 | [
"object"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.