hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
73a046b2e8d5256a33f90637a9c403b5180830f4 | 1,406 | cc | C++ | caffe2/onnx/helper.cc | deltabravozulu/pytorch | c6eef589971e45bbedacc7f65533d1b8f80a6895 | [
"Intel"
] | 206 | 2020-11-28T22:56:38.000Z | 2022-03-27T02:33:04.000Z | caffe2/onnx/helper.cc | deltabravozulu/pytorch | c6eef589971e45bbedacc7f65533d1b8f80a6895 | [
"Intel"
] | 19 | 2020-12-09T23:13:14.000Z | 2022-01-24T23:24:08.000Z | caffe2/onnx/helper.cc | deltabravozulu/pytorch | c6eef589971e45bbedacc7f65533d1b8f80a6895 | [
"Intel"
] | 28 | 2020-11-29T15:25:12.000Z | 2022-01-20T02:16:27.000Z | #include "caffe2/onnx/helper.h"
#include "caffe2/core/logging.h"
#include "caffe2/core/operator.h"
namespace caffe2 { namespace onnx {
std::string DummyName::NewDummyName() {
while (true) {
const std::string name = c10::str("OC2_DUMMY_", counter_++);
auto ret = used_names_.insert(name);
if (ret.second) {
return name;
}
}
}
void DummyName::Reset(const std::unordered_set<std::string> &used_names) {
used_names_ = used_names;
counter_ = 0;
}
::ONNX_NAMESPACE::TypeProto ExtraTypeProto(
const ::ONNX_NAMESPACE::TensorProto& tensor) {
::ONNX_NAMESPACE::TypeProto t;
auto* tensor_type = t.mutable_tensor_type();
tensor_type->set_elem_type(tensor.data_type());
auto* shape = tensor_type->mutable_shape();
for (const auto d : tensor.dims()) {
shape->add_dim()->set_dim_value(d);
}
return t;
}
NodeProto MakeNode(
const std::string& type,
const std::vector<std::string>& inputs,
const std::vector<std::string>& outputs,
const std::vector<AttributeProto>& attributes,
const std::string& name) {
NodeProto node;
if (!name.empty()) {
node.set_name(name);
}
node.set_op_type(type);
for (const auto& input: inputs) {
node.add_input(input);
}
for (const auto& output: outputs) {
node.add_output(output);
}
for (const auto& attr: attributes) {
node.add_attribute()->CopyFrom(attr);
}
return node;
}
}}
| 24.241379 | 74 | 0.669275 | [
"shape",
"vector"
] |
73a3750ac4a402a8c7aa6231bd52f4e54ca70ab1 | 1,732 | hpp | C++ | inc/cg/Image.hpp | eestrada/raytracer | f1a80db1c2ec05e5b39a9dce9af6a56604755a0b | [
"MIT"
] | 1 | 2018-04-25T08:43:36.000Z | 2018-04-25T08:43:36.000Z | inc/cg/Image.hpp | eestrada/raytracer | f1a80db1c2ec05e5b39a9dce9af6a56604755a0b | [
"MIT"
] | null | null | null | inc/cg/Image.hpp | eestrada/raytracer | f1a80db1c2ec05e5b39a9dce9af6a56604755a0b | [
"MIT"
] | null | null | null | #if !defined(IMAGE_HPP)
#define IMAGE_HPP
#include <vector>
#include <string>
#include <ostream>
#include <memory>
#include <cstdint>
#include "cg_utils.hpp"
#include "Vec4.hpp"
namespace cg
{
template <typename T>
struct pixel_type
{
T r, g, b, a;
typedef T chan_type;
};
template <typename T>
pixel_type<T> pixel_ctor(T r,T g,T b,T a)
{
pixel_type<T> retval;
retval.r = r;
retval.g = g;
retval.b = b;
retval.a = a;
return retval;
}
typedef pixel_type<uint8_t> pixelb;
typedef pixel_type<uint16_t> pixelh;
typedef pixel_type<uint32_t> pixeli;
typedef pixel_type<float> pixelf;
/*
* Image class
*
* Scanline storage starting at top-left corner.
*/
struct Image
{
public: //functions
Image(uint16_t w=0, uint16_t h=0);
void set_dimensions(uint16_t w, uint16_t h);
uint16_t get_width() const;
uint16_t get_height() const;
uint32_t size() const;
// index into the one dimensional array
const pixelf & operator[](uint32_t index) const;
pixelf & operator[](uint32_t index);
// index into the image using the x and y coordinates
const pixelf & at(uint16_t x, uint16_t y) const;
pixelf & at(uint16_t x, uint16_t y);
// Nearest pixel interpolation. In other words, point filtering.
const pixelf & at_uv(double u, double v) const;
pixelf & at_uv(double u, double v);
protected: //variables
uint16_t width, height;
std::vector<pixelf> pixels;
};
pixelb float_to_byte(const pixelf &pf, bool premult=true);
bool writePPM(const Image &img, std::ostream &out, bool premult=true);
} //end namespace cg
template<typename T>
std::ostream & operator <<(std::ostream &out, const cg::pixel_type<T> &p);
#endif // end include guard
| 20.376471 | 74 | 0.687067 | [
"vector"
] |
73a3c7a0d5fc49cee7cba9b0ce15195c30fa3919 | 18,510 | cpp | C++ | mediasoup-client/deps/libmediasoupclient/src/PeerConnection.cpp | itcayman/mediasoup-client-android | 2960fcca694b7b0e5ccd6ab47ee049565b89ad6d | [
"MIT"
] | 1 | 2021-11-10T09:20:24.000Z | 2021-11-10T09:20:24.000Z | mediasoup-client/deps/libmediasoupclient/src/PeerConnection.cpp | itcayman/mediasoup-client-android | 2960fcca694b7b0e5ccd6ab47ee049565b89ad6d | [
"MIT"
] | null | null | null | mediasoup-client/deps/libmediasoupclient/src/PeerConnection.cpp | itcayman/mediasoup-client-android | 2960fcca694b7b0e5ccd6ab47ee049565b89ad6d | [
"MIT"
] | 1 | 2021-11-11T12:07:22.000Z | 2021-11-11T12:07:22.000Z | #define MSC_CLASS "PeerConnection"
#include "PeerConnection.hpp"
#include "Logger.hpp"
#include "MediaSoupClientErrors.hpp"
#include "Utils.hpp"
#include <api/audio_codecs/builtin_audio_decoder_factory.h>
#include <api/audio_codecs/builtin_audio_encoder_factory.h>
#include <api/create_peerconnection_factory.h>
#include <api/video_codecs/builtin_video_decoder_factory.h>
#include <api/video_codecs/builtin_video_encoder_factory.h>
#include <rtc_base/ssl_adapter.h>
using json = nlohmann::json;
namespace mediasoupclient
{
/* Static. */
// clang-format off
std::map<PeerConnection::SdpType, const std::string> PeerConnection::sdpType2String =
{
{ PeerConnection::SdpType::OFFER, "offer" },
{ PeerConnection::SdpType::PRANSWER, "pranswer" },
{ PeerConnection::SdpType::ANSWER, "answer" }
};
std::map<webrtc::PeerConnectionInterface::IceConnectionState, const std::string>
PeerConnection::iceConnectionState2String =
{
{ webrtc::PeerConnectionInterface::IceConnectionState::kIceConnectionNew, "new" },
{ webrtc::PeerConnectionInterface::IceConnectionState::kIceConnectionChecking, "checking" },
{ webrtc::PeerConnectionInterface::IceConnectionState::kIceConnectionConnected, "connected" },
{ webrtc::PeerConnectionInterface::IceConnectionState::kIceConnectionCompleted, "completed" },
{ webrtc::PeerConnectionInterface::IceConnectionState::kIceConnectionFailed, "failed" },
{ webrtc::PeerConnectionInterface::IceConnectionState::kIceConnectionDisconnected, "disconnected" },
{ webrtc::PeerConnectionInterface::IceConnectionState::kIceConnectionClosed, "closed" }
};
std::map<webrtc::PeerConnectionInterface::IceGatheringState, const std::string>
PeerConnection::iceGatheringState2String =
{
{ webrtc::PeerConnectionInterface::IceGatheringState::kIceGatheringNew, "new" },
{ webrtc::PeerConnectionInterface::IceGatheringState::kIceGatheringGathering, "gathering" },
{ webrtc::PeerConnectionInterface::IceGatheringState::kIceGatheringComplete, "complete" }
};
std::map<webrtc::PeerConnectionInterface::SignalingState, const std::string>
PeerConnection::signalingState2String =
{
{ webrtc::PeerConnectionInterface::SignalingState::kStable, "stable" },
{ webrtc::PeerConnectionInterface::SignalingState::kHaveLocalOffer, "have-local-offer" },
{ webrtc::PeerConnectionInterface::SignalingState::kHaveLocalPrAnswer, "have-local-pranswer" },
{ webrtc::PeerConnectionInterface::SignalingState::kHaveRemoteOffer, "have-remote-offer" },
{ webrtc::PeerConnectionInterface::SignalingState::kHaveRemotePrAnswer, "have-remote-pranswer" },
{ webrtc::PeerConnectionInterface::SignalingState::kClosed, "closed" }
};
// clang-format on
/* Instance methods. */
PeerConnection::PeerConnection(
PeerConnection::PrivateListener* privateListener, const PeerConnection::Options* options)
{
MSC_TRACE();
webrtc::PeerConnectionInterface::RTCConfiguration config;
if (options != nullptr)
config = options->config;
// PeerConnection factory provided.
if ((options != nullptr) && (options->factory != nullptr))
{
this->peerConnectionFactory =
rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface>(options->factory);
}
else
{
this->networkThread = rtc::Thread::CreateWithSocketServer();
this->signalingThread = rtc::Thread::Create();
this->workerThread = rtc::Thread::Create();
this->networkThread->SetName("network_thread", nullptr);
this->signalingThread->SetName("signaling_thread", nullptr);
this->workerThread->SetName("worker_thread", nullptr);
if (!this->networkThread->Start() || !this->signalingThread->Start() || !this->workerThread->Start())
{
MSC_THROW_INVALID_STATE_ERROR("thread start errored");
}
this->peerConnectionFactory = webrtc::CreatePeerConnectionFactory(
this->networkThread.get(),
this->workerThread.get(),
this->signalingThread.get(),
nullptr /*default_adm*/,
webrtc::CreateBuiltinAudioEncoderFactory(),
webrtc::CreateBuiltinAudioDecoderFactory(),
webrtc::CreateBuiltinVideoEncoderFactory(),
webrtc::CreateBuiltinVideoDecoderFactory(),
nullptr /*audio_mixer*/,
nullptr /*audio_processing*/);
}
// Set SDP semantics to Unified Plan.
config.sdp_semantics = webrtc::SdpSemantics::kUnifiedPlan;
config.set_cpu_adaptation(false);
// Create the webrtc::Peerconnection.
this->pc =
this->peerConnectionFactory->CreatePeerConnection(config, nullptr, nullptr, privateListener);
}
void PeerConnection::Close()
{
MSC_TRACE();
this->pc->Close();
}
webrtc::PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() const
{
MSC_TRACE();
return this->pc->GetConfiguration();
}
bool PeerConnection::SetConfiguration(const webrtc::PeerConnectionInterface::RTCConfiguration& config)
{
MSC_TRACE();
webrtc::RTCError error = this->pc->SetConfiguration(config);
if (error.ok())
{
return true;
}
MSC_WARN(
"webrtc::PeerConnection::SetConfiguration failed [%s:%s]",
webrtc::ToString(error.type()),
error.message());
return false;
}
std::string PeerConnection::CreateOffer(
const webrtc::PeerConnectionInterface::RTCOfferAnswerOptions& options)
{
MSC_TRACE();
CreateSessionDescriptionObserver* sessionDescriptionObserver =
new rtc::RefCountedObject<CreateSessionDescriptionObserver>();
auto future = sessionDescriptionObserver->GetFuture();
this->pc->CreateOffer(sessionDescriptionObserver, options);
return future.get();
}
std::string PeerConnection::CreateAnswer(
const webrtc::PeerConnectionInterface::RTCOfferAnswerOptions& options)
{
MSC_TRACE();
CreateSessionDescriptionObserver* sessionDescriptionObserver =
new rtc::RefCountedObject<CreateSessionDescriptionObserver>();
auto future = sessionDescriptionObserver->GetFuture();
this->pc->CreateAnswer(sessionDescriptionObserver, options);
return future.get();
}
void PeerConnection::SetLocalDescription(PeerConnection::SdpType type, const std::string& sdp)
{
MSC_TRACE();
webrtc::SdpParseError error;
webrtc::SessionDescriptionInterface* sessionDescription;
rtc::scoped_refptr<SetSessionDescriptionObserver> observer(
new rtc::RefCountedObject<SetSessionDescriptionObserver>());
const auto& typeStr = sdpType2String[type];
auto future = observer->GetFuture();
sessionDescription = webrtc::CreateSessionDescription(typeStr, sdp, &error);
if (sessionDescription == nullptr)
{
MSC_WARN(
"webrtc::CreateSessionDescription failed [%s]: %s",
error.line.c_str(),
error.description.c_str());
observer->Reject(error.description);
return future.get();
}
this->pc->SetLocalDescription(observer, sessionDescription);
return future.get();
}
void PeerConnection::SetRemoteDescription(PeerConnection::SdpType type, const std::string& sdp)
{
MSC_TRACE();
webrtc::SdpParseError error;
webrtc::SessionDescriptionInterface* sessionDescription;
rtc::scoped_refptr<SetSessionDescriptionObserver> observer(
new rtc::RefCountedObject<SetSessionDescriptionObserver>());
const auto& typeStr = sdpType2String[type];
auto future = observer->GetFuture();
sessionDescription = webrtc::CreateSessionDescription(typeStr, sdp, &error);
if (sessionDescription == nullptr)
{
MSC_WARN(
"webrtc::CreateSessionDescription failed [%s]: %s",
error.line.c_str(),
error.description.c_str());
observer->Reject(error.description);
return future.get();
}
this->pc->SetRemoteDescription(observer, sessionDescription);
return future.get();
}
const std::string PeerConnection::GetLocalDescription()
{
MSC_TRACE();
auto desc = this->pc->local_description();
std::string sdp;
desc->ToString(&sdp);
return sdp;
}
const std::string PeerConnection::GetRemoteDescription()
{
MSC_TRACE();
auto desc = this->pc->remote_description();
std::string sdp;
desc->ToString(&sdp);
return sdp;
}
std::vector<rtc::scoped_refptr<webrtc::RtpTransceiverInterface>> PeerConnection::GetTransceivers() const
{
MSC_TRACE();
return this->pc->GetTransceivers();
}
rtc::scoped_refptr<webrtc::RtpTransceiverInterface> PeerConnection::AddTransceiver(
cricket::MediaType mediaType)
{
MSC_TRACE();
auto result = this->pc->AddTransceiver(mediaType);
if (!result.ok())
{
rtc::scoped_refptr<webrtc::RtpTransceiverInterface> transceiver = nullptr;
return transceiver;
}
return result.value();
}
rtc::scoped_refptr<webrtc::RtpTransceiverInterface> PeerConnection::AddTransceiver(
rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track,
webrtc::RtpTransceiverInit rtpTransceiverInit)
{
MSC_TRACE();
/*
* Define a stream id so the generated local description is correct.
* - with a stream id: "a=ssrc:<ssrc-id> mslabel:<value>"
* - without a stream id: "a=ssrc:<ssrc-id> mslabel:"
*
* The second is incorrect (https://tools.ietf.org/html/rfc5576#section-4.1)
*/
rtpTransceiverInit.stream_ids.emplace_back("0");
auto result = this->pc->AddTransceiver(
track, rtpTransceiverInit); // NOLINT(performance-unnecessary-value-param)
if (!result.ok())
{
rtc::scoped_refptr<webrtc::RtpTransceiverInterface> transceiver = nullptr;
return transceiver;
}
return result.value();
}
std::vector<rtc::scoped_refptr<webrtc::RtpSenderInterface>> PeerConnection::GetSenders()
{
MSC_TRACE();
return this->pc->GetSenders();
}
bool PeerConnection::RemoveTrack(webrtc::RtpSenderInterface* sender)
{
MSC_TRACE();
return this->pc->RemoveTrack(sender);
}
json PeerConnection::GetStats()
{
MSC_TRACE();
rtc::scoped_refptr<RTCStatsCollectorCallback> callback(
new rtc::RefCountedObject<RTCStatsCollectorCallback>());
auto future = callback->GetFuture();
this->pc->GetStats(callback.get());
return future.get();
}
json PeerConnection::GetStats(rtc::scoped_refptr<webrtc::RtpSenderInterface> selector)
{
MSC_TRACE();
rtc::scoped_refptr<RTCStatsCollectorCallback> callback(
new rtc::RefCountedObject<RTCStatsCollectorCallback>());
auto future = callback->GetFuture();
this->pc->GetStats(std::move(selector), callback);
return future.get();
}
json PeerConnection::GetStats(rtc::scoped_refptr<webrtc::RtpReceiverInterface> selector)
{
MSC_TRACE();
rtc::scoped_refptr<RTCStatsCollectorCallback> callback(
new rtc::RefCountedObject<RTCStatsCollectorCallback>());
auto future = callback->GetFuture();
this->pc->GetStats(std::move(selector), callback);
return future.get();
}
rtc::scoped_refptr<webrtc::DataChannelInterface> PeerConnection::CreateDataChannel(
const std::string& label, const webrtc::DataChannelInit* config)
{
MSC_TRACE();
rtc::scoped_refptr<webrtc::DataChannelInterface> webrtcDataChannel =
this->pc->CreateDataChannel(label, config);
if (webrtcDataChannel.get())
{
MSC_DEBUG("Success creating data channel");
}
else
{
MSC_THROW_ERROR("Failed creating data channel");
}
return webrtcDataChannel;
}
/* SetSessionDescriptionObserver */
std::future<void> PeerConnection::SetSessionDescriptionObserver::GetFuture()
{
MSC_TRACE();
return this->promise.get_future();
}
void PeerConnection::SetSessionDescriptionObserver::Reject(const std::string& error)
{
MSC_TRACE();
this->promise.set_exception(std::make_exception_ptr(MediaSoupClientError(error.c_str())));
}
void PeerConnection::SetSessionDescriptionObserver::OnSuccess()
{
MSC_TRACE();
this->promise.set_value();
};
void PeerConnection::SetSessionDescriptionObserver::OnFailure(webrtc::RTCError error)
{
MSC_TRACE();
MSC_WARN(
"webtc::SetSessionDescriptionObserver failure [%s:%s]",
webrtc::ToString(error.type()),
error.message());
auto message = std::string(error.message());
this->Reject(message);
};
/* CreateSessionDescriptionObserver */
std::future<std::string> PeerConnection::CreateSessionDescriptionObserver::GetFuture()
{
MSC_TRACE();
return this->promise.get_future();
}
void PeerConnection::CreateSessionDescriptionObserver::Reject(const std::string& error)
{
MSC_TRACE();
this->promise.set_exception(std::make_exception_ptr(MediaSoupClientError(error.c_str())));
}
void PeerConnection::CreateSessionDescriptionObserver::OnSuccess(
webrtc::SessionDescriptionInterface* desc)
{
MSC_TRACE();
std::string sdp;
desc->ToString(&sdp);
this->promise.set_value(sdp);
};
void PeerConnection::CreateSessionDescriptionObserver::OnFailure(webrtc::RTCError error)
{
MSC_TRACE();
MSC_WARN(
"webtc::CreateSessionDescriptionObserver failure [%s:%s]",
webrtc::ToString(error.type()),
error.message());
auto message = std::string(error.message());
this->Reject(message);
}
/* RTCStatsCollectorCallback */
std::future<json> PeerConnection::RTCStatsCollectorCallback::GetFuture()
{
MSC_TRACE();
return this->promise.get_future();
}
void PeerConnection::RTCStatsCollectorCallback::OnStatsDelivered(
const rtc::scoped_refptr<const webrtc::RTCStatsReport>& report)
{
MSC_TRACE();
std::string s = report->ToJson();
// RtpReceiver stats JSON string is sometimes empty.
if (s.empty())
this->promise.set_value(json::array());
else
this->promise.set_value(json::parse(s));
};
/* PeerConnection::PrivateListener */
/**
* Triggered when the SignalingState changed.
*/
void PeerConnection::PrivateListener::OnSignalingChange(
webrtc::PeerConnectionInterface::SignalingState newState)
{
MSC_TRACE();
MSC_DEBUG("[newState:%s]", PeerConnection::signalingState2String[newState].c_str());
}
/**
* Triggered when media is received on a new stream from remote peer.
*/
void PeerConnection::PrivateListener::OnAddStream(
rtc::scoped_refptr<webrtc::MediaStreamInterface> /*stream*/)
{
MSC_TRACE();
}
/**
* Triggered when a remote peer closes a stream.
*/
void PeerConnection::PrivateListener::OnRemoveStream(
rtc::scoped_refptr<webrtc::MediaStreamInterface> /*stream*/)
{
MSC_TRACE();
}
/**
* Triggered when a remote peer opens a data channel.
*/
void PeerConnection::PrivateListener::OnDataChannel(
rtc::scoped_refptr<webrtc::DataChannelInterface> /*dataChannel*/)
{
MSC_TRACE();
}
/**
* Triggered when renegotiation is needed. For example, an ICE restart has begun.
*/
void PeerConnection::PrivateListener::OnRenegotiationNeeded()
{
MSC_TRACE();
}
/**
* Triggered any time the IceConnectionState changes.
*
* Note that our ICE states lag behind the standard slightly. The most
* notable differences include the fact that "failed" occurs after 15
* seconds, not 30, and this actually represents a combination ICE + DTLS
* state, so it may be "failed" if DTLS fails while ICE succeeds.
*/
void PeerConnection::PrivateListener::OnIceConnectionChange(
webrtc::PeerConnectionInterface::IceConnectionState newState)
{
MSC_TRACE();
MSC_DEBUG("[newState:%s]", PeerConnection::iceConnectionState2String[newState].c_str());
}
/**
* Triggered any time the IceGatheringState changes.
*/
void PeerConnection::PrivateListener::OnIceGatheringChange(
webrtc::PeerConnectionInterface::IceGatheringState newState)
{
MSC_TRACE();
MSC_DEBUG("[newState:%s]", PeerConnection::iceGatheringState2String[newState].c_str());
}
/**
* Triggered when a new ICE candidate has been gathered.
*/
void PeerConnection::PrivateListener::OnIceCandidate(const webrtc::IceCandidateInterface* candidate)
{
MSC_TRACE();
std::string candidateStr;
candidate->ToString(&candidateStr);
MSC_DEBUG("[candidate:%s]", candidateStr.c_str());
}
/**
* Triggered when the ICE candidates have been removed.
*/
void PeerConnection::PrivateListener::OnIceCandidatesRemoved(
const std::vector<cricket::Candidate>& /*candidates*/)
{
MSC_TRACE();
}
/**
* Triggered when the ICE connection receiving status changes.
*/
void PeerConnection::PrivateListener::OnIceConnectionReceivingChange(bool /*receiving*/)
{
MSC_TRACE();
}
/**
* Triggered when a receiver and its track are created.
*
* Note: This is called with both Plan B and Unified Plan semantics. Unified
* Plan users should prefer OnTrack, OnAddTrack is only called as backwards
* compatibility (and is called in the exact same situations as OnTrack).
*/
void PeerConnection::PrivateListener::OnAddTrack(
rtc::scoped_refptr<webrtc::RtpReceiverInterface> /*receiver*/,
const std::vector<rtc::scoped_refptr<webrtc::MediaStreamInterface>>& /*streams*/)
{
MSC_TRACE();
}
/**
* Triggered when signaling indicates a transceiver will be receiving
*
* media from the remote endpoint. This is fired during a call to
* SetRemoteDescription. The receiving track can be accessed by:
* transceiver->receiver()->track() and its associated streams by
* transceiver->receiver()->streams().
*
* NOTE: This will only be called if Unified Plan semantics are specified.
* This behavior is specified in section 2.2.8.2.5 of the "Set the
* RTCSessionDescription" algorithm:
* https://w3c.github.io/webrtc-pc/#set-description
*/
void PeerConnection::PrivateListener::OnTrack(
rtc::scoped_refptr<webrtc::RtpTransceiverInterface> /*transceiver*/)
{
MSC_TRACE();
}
/**
* Triggered when signaling indicates that media will no longer be received on a
* track.
*
* With Plan B semantics, the given receiver will have been removed from the
* PeerConnection and the track muted.
* With Unified Plan semantics, the receiver will remain but the transceiver
* will have changed direction to either sendonly or inactive.
* https://w3c.github.io/webrtc-pc/#process-remote-track-removal
*/
void PeerConnection::PrivateListener::OnRemoveTrack(
rtc::scoped_refptr<webrtc::RtpReceiverInterface> /*receiver*/)
{
MSC_TRACE();
}
/**
* Triggered when an interesting usage is detected by WebRTC.
*
* An appropriate action is to add information about the context of the
* PeerConnection and write the event to some kind of "interesting events"
* log function.
* The heuristics for defining what constitutes "interesting" are
* implementation-defined.
*/
void PeerConnection::PrivateListener::OnInterestingUsage(int /*usagePattern*/)
{
MSC_TRACE();
}
} // namespace mediasoupclient
| 28.045455 | 105 | 0.730038 | [
"vector"
] |
73ab9898e05ed57c940967353e4629dab9fd3fed | 16,130 | cpp | C++ | src/envlight.cpp | arpit15/dpt | 5a9eec75b506d2c1867e3d5cfc1746d7f01c4639 | [
"MIT"
] | 59 | 2016-01-27T02:30:32.000Z | 2021-12-11T12:48:01.000Z | src/envlight.cpp | arpit15/dpt | 5a9eec75b506d2c1867e3d5cfc1746d7f01c4639 | [
"MIT"
] | 1 | 2021-06-23T18:48:19.000Z | 2021-06-23T18:48:19.000Z | src/envlight.cpp | arpit15/dpt | 5a9eec75b506d2c1867e3d5cfc1746d7f01c4639 | [
"MIT"
] | 7 | 2016-01-28T16:01:35.000Z | 2021-06-16T03:11:59.000Z | #include "envlight.h"
#include "image.h"
#include "distribution.h"
#include "transform.h"
#include "sampling.h"
int GetEnvLightSerializedSize() {
return 1 + // type
16 + // toWorld
16 + // toLight
1 + // uCDF0
1 + // uCDF1
1 + // vCDF0
1 + // vCDF1
1 + // col
1 + // row
2 + // pixelSize
4 * 3 + // img00~img11
2 + // rowWeight0 & rowWeight1
1; // normalization
}
std::unique_ptr<const EnvmapSampleInfo> CreateEnvmapSampleInfo(const Image3 *image) {
int height = image->pixelHeight;
int width = image->pixelWidth;
size_t nEntries = (size_t)(width + 1) * (size_t)height;
std::vector<Float> cdfCols(nEntries);
std::vector<Float> cdfRows(height + 1);
std::vector<Float> rowWeights(height);
size_t colPos = 0, rowPos = 0;
Float rowSum = Float(0.0);
cdfRows[rowPos++] = Float(0.0);
for (int y = 0; y < height; y++) {
Float colSum = Float(0.0);
cdfCols[colPos++] = Float(0.0);
for (int x = 0; x < width; x++) {
Vector3 value = image->At(x, y);
colSum += Luminance(value);
cdfCols[colPos++] = colSum;
}
Float normalization = inverse(colSum);
for (int x = 1; x < width; x++) {
cdfCols[colPos - x - 1] *= normalization;
}
cdfCols[colPos - 1] = Float(1.0);
Float weight = sin((y + Float(0.5)) * c_PI / (Float)height);
rowWeights[y] = weight;
rowSum += colSum * weight;
cdfRows[rowPos++] = rowSum;
}
Float normalization = inverse(rowSum);
for (int y = 1; y < height; y++) {
cdfRows[rowPos - y - 1] *= normalization;
}
cdfRows[rowPos - 1] = Float(1.0);
if (rowSum == 0 || !std::isfinite(rowSum)) {
Error("Invalid environment map");
}
normalization = inverse(rowSum * (c_TWOPI / width) * (c_PI / height));
Vector2 pixelSize = Vector2(c_TWOPI / width, M_PI / height);
return std::unique_ptr<const EnvmapSampleInfo>(
new EnvmapSampleInfo{cdfRows, cdfCols, rowWeights, normalization, pixelSize});
}
EnvLight::EnvLight(const Float &samplingWeight,
const AnimatedTransform &toWorld,
const std::string &filename)
: Light(samplingWeight),
toWorld(toWorld),
toLight(Invert(toWorld)),
image(new Image3(filename)),
sampleInfo(CreateEnvmapSampleInfo(image.get())) {
}
void EnvLight::Serialize(const LightPrimID &lPrimID, Float *buffer) const {
buffer = ::Serialize((Float)LightType::EnvLight, buffer);
buffer = ::Serialize(toWorld, buffer);
buffer = ::Serialize(toLight, buffer);
size_t col = lPrimID % image->pixelWidth;
size_t row = lPrimID / image->pixelWidth;
const Float *cdfCol = &sampleInfo->cdfCols[0] + row * (image->pixelWidth + 1);
Float cdfCol0 = cdfCol[col];
Float cdfCol1 = cdfCol[col + 1];
Float cdfRow0 = sampleInfo->cdfRows[row];
Float cdfRow1 = sampleInfo->cdfRows[row + 1];
Vector2 pixelSize = sampleInfo->pixelSize;
Vector3 img00 = image->RepAt(col, row);
Vector3 img10 = image->RepAt(col + 1, row);
Vector3 img01 = image->RepAt(col, row + 1);
Vector3 img11 = image->RepAt(col + 1, row + 1);
Float rowWeight0 =
sampleInfo->rowWeights[Clamp(row, (size_t)0, (size_t)image->pixelHeight - 1)];
Float rowWeight1 =
sampleInfo->rowWeights[Clamp(row + 1, (size_t)0, (size_t)image->pixelHeight - 1)];
buffer = ::Serialize(cdfCol0, buffer);
buffer = ::Serialize(cdfCol1, buffer);
buffer = ::Serialize(cdfRow0, buffer);
buffer = ::Serialize(cdfRow1, buffer);
buffer = ::Serialize((Float)col, buffer);
buffer = ::Serialize((Float)row, buffer);
buffer = ::Serialize(pixelSize, buffer);
buffer = ::Serialize(img00, buffer);
buffer = ::Serialize(img10, buffer);
buffer = ::Serialize(img01, buffer);
buffer = ::Serialize(img11, buffer);
buffer = ::Serialize(rowWeight0, buffer);
buffer = ::Serialize(rowWeight1, buffer);
::Serialize(sampleInfo->normalization, buffer);
}
void SampleDirection(const EnvLight *light,
const Vector2 rndParam,
const Float time,
LightPrimID &lPrimID,
Vector3 &dirToLight,
Vector3 &value,
Float &pdf) {
Matrix4x4 transform = Interpolate(light->toWorld, time);
auto uToIndex = [](const Float *cdf, const size_t size, Float &u) {
const Float *entry = std::lower_bound(cdf, cdf + size + 1, u);
size_t index = std::min(std::max((ptrdiff_t)0, entry - cdf - 1), (ptrdiff_t)size - 1);
u = (u - (Float)cdf[index]) / (Float)(cdf[index + 1] - cdf[index]);
return index;
};
const EnvmapSampleInfo *sampleInfo = light->sampleInfo.get();
const Image3 *image = light->image.get();
int width = image->pixelWidth;
int height = image->pixelHeight;
Float u0 = rndParam[0];
Float u1 = rndParam[1];
int row = uToIndex(&sampleInfo->cdfRows[0], height, u1);
int col = uToIndex(&sampleInfo->cdfCols[0] + row * (width + 1), width, u0);
lPrimID = row * width + col;
Vector2 tent = Vector2(Tent(u0), Tent(u1));
Vector2 pl = Vector2((Float)col, (Float)row) + tent;
Float phi = (pl[0] + Float(0.5)) * sampleInfo->pixelSize[0];
Float theta = (pl[1] + Float(0.5)) * sampleInfo->pixelSize[1];
Float sinPhi = sin(phi);
Float cosPhi = cos(phi);
Float sinTheta = sin(theta);
Float cosTheta = cos(theta);
dirToLight = XformVector(transform, Vector3(sinPhi * sinTheta, cosTheta, -cosPhi * sinTheta));
Float dx1 = tent[0], dx2 = Float(1.0) - tent[0], dy1 = tent[1], dy2 = Float(1.0) - tent[1];
Vector3 value1 = image->At(col, row) * dx2 * dy2 + image->At(col + 1, row) * dx1 * dy2;
Vector3 value2 = image->At(col, row + 1) * dx2 * dy1 + image->At(col + 1, row + 1) * dx1 * dy1;
value = (value1 + value2);
Float rowWeight0 = sampleInfo->rowWeights[Clamp(row, 0, image->pixelHeight - 1)];
Float rowWeight1 = sampleInfo->rowWeights[Clamp(row + 1, 0, image->pixelHeight - 1)];
pdf = (Luminance(value1) * rowWeight0 + Luminance(value2) * rowWeight1) *
sampleInfo->normalization / fmax(fabs(sinTheta), Float(1e-7));
}
bool EnvLight::SampleDirect(const BSphere &sceneSphere,
const Vector3 & /*pos*/,
const Vector3 & /*normal*/,
const Vector2 rndParam,
const Float time,
LightPrimID &lPrimID,
Vector3 &dirToLight,
Float &dist,
Vector3 &contrib,
Float &cosAtLight,
Float &directPdf,
Float &emissionPdf) const {
Vector3 value;
SampleDirection(this, rndParam, time, lPrimID, dirToLight, value, directPdf);
dist = std::numeric_limits<Float>::infinity();
contrib = value * inverse(directPdf);
cosAtLight = Float(1.0);
Float positionPdf = c_INVPI / square(sceneSphere.radius);
emissionPdf = directPdf * positionPdf;
return true;
}
void EnvLight::Emission(const BSphere &sceneSphere,
const Vector3 &dirToLight,
const Vector3 & /*normalOnLight*/,
const Float time,
LightPrimID &lPrimID,
Vector3 &emission,
Float &directPdf,
Float &emissionPdf) const {
Matrix4x4 transform = Interpolate(toLight, time);
Vector3 d = XformVector(transform, dirToLight);
Vector2 uv(atan2(d[0], -d[2]) * c_INVTWOPI * (Float)image->pixelWidth - Float(0.5),
acos(d[1]) * c_INVPI * (Float)image->pixelHeight - Float(0.5));
int col = int(floor(uv[0]));
int row = int(floor(uv[1]));
lPrimID = Modulo(row, image->pixelHeight) * image->pixelWidth + Modulo(col, image->pixelWidth);
Float dx1 = uv[0] - col, dx2 = Float(1.0) - dx1, dy1 = uv[1] - row, dy2 = Float(1.0) - dy1;
Vector3 value1 = image->RepAt(col, row) * dx2 * dy2 + image->RepAt(col + 1, row) * dx1 * dy2;
Vector3 value2 =
image->RepAt(col, row + 1) * dx2 * dy1 + image->RepAt(col + 1, row + 1) * dx1 * dy1;
emission = value1 + value2;
Float sinTheta = sqrt(Float(1.0) - square(d[1]));
Float rowWeight0 = sampleInfo->rowWeights[Clamp(row, 0, image->pixelHeight - 1)];
Float rowWeight1 = sampleInfo->rowWeights[Clamp(row + 1, 0, image->pixelHeight - 1)];
directPdf = (Luminance(value1) * rowWeight0 + Luminance(value2) * rowWeight1) *
sampleInfo->normalization / fmax(fabs(sinTheta), Float(1e-7));
Float positionPdf = c_INVPI / square(sceneSphere.radius);
emissionPdf = directPdf * positionPdf;
}
void EnvLight::Emit(const BSphere &sceneSphere,
const Vector2 rndParamPos,
const Vector2 rndParamDir,
const Float time,
LightPrimID &lPrimID,
Ray &ray,
Vector3 &emission,
Float &cosAtLight,
Float &emissionPdf,
Float &directPdf) const {
SampleDirection(this, rndParamDir, time, lPrimID, ray.dir, emission, directPdf);
ray.dir = -ray.dir;
Vector2 offset = SampleConcentricDisc(rndParamPos);
Vector3 b0, b1;
CoordinateSystem(ray.dir, b0, b1);
Vector3 perpOffset = offset[0] * b0 + offset[1] * b1;
ray.org = sceneSphere.center + (perpOffset - ray.dir) * sceneSphere.radius;
cosAtLight = Float(1.0);
Float positionPdf = c_INVPI / square(sceneSphere.radius);
emissionPdf = directPdf * positionPdf;
}
struct ADEnvLight {
ADAnimatedTransform toWorld;
ADAnimatedTransform toLight;
ADFloat cdfCol0;
ADFloat cdfCol1;
ADFloat cdfRow0;
ADFloat cdfRow1;
ADFloat col;
ADFloat row;
ADVector2 pixelSize;
ADVector3 img00;
ADVector3 img10;
ADVector3 img01;
ADVector3 img11;
ADFloat rowWeight0;
ADFloat rowWeight1;
ADFloat normalization;
};
const ADFloat *Deserialize(const ADFloat *buffer, ADEnvLight &envLight) {
buffer = Deserialize(buffer, envLight.toWorld);
buffer = Deserialize(buffer, envLight.toLight);
buffer = Deserialize(buffer, envLight.cdfCol0);
buffer = Deserialize(buffer, envLight.cdfCol1);
buffer = Deserialize(buffer, envLight.cdfRow0);
buffer = Deserialize(buffer, envLight.cdfRow1);
buffer = Deserialize(buffer, envLight.col);
buffer = Deserialize(buffer, envLight.row);
buffer = Deserialize(buffer, envLight.pixelSize);
buffer = Deserialize(buffer, envLight.img00);
buffer = Deserialize(buffer, envLight.img10);
buffer = Deserialize(buffer, envLight.img01);
buffer = Deserialize(buffer, envLight.img11);
buffer = Deserialize(buffer, envLight.rowWeight0);
buffer = Deserialize(buffer, envLight.rowWeight1);
buffer = Deserialize(buffer, envLight.normalization);
return buffer;
}
void SampleDirection(const ADEnvLight &envLight,
const ADVector2 rndParam,
const ADFloat time,
ADVector3 &dirToLight,
ADVector3 &value,
ADFloat &pdf) {
ADMatrix4x4 transform = Interpolate(envLight.toWorld, time);
ADFloat u0 = (rndParam[0] - envLight.cdfCol0) / (envLight.cdfCol1 - envLight.cdfCol0);
ADFloat u1 = (rndParam[1] - envLight.cdfRow0) / (envLight.cdfRow1 - envLight.cdfRow0);
ADVector2 tent = ADVector2(Tent(u0), Tent(u1));
ADVector2 pl = ADVector2(envLight.col, envLight.row) + tent;
ADFloat phi = (pl[0] + Float(0.5)) * envLight.pixelSize[0];
ADFloat theta = (pl[1] + Float(0.5)) * envLight.pixelSize[1];
ADFloat sinPhi = sin(phi);
ADFloat cosPhi = cos(phi);
ADFloat sinTheta = sin(theta);
ADFloat cosTheta = cos(theta);
dirToLight = XformVector(transform, ADVector3(sinPhi * sinTheta, cosTheta, -cosPhi * sinTheta));
ADFloat dx1 = tent[0], dx2 = Float(1.0) - tent[0], dy1 = tent[1], dy2 = Float(1.0) - tent[1];
ADVector3 value1 = envLight.img00 * dx2 * dy2 + envLight.img10 * dx1 * dy2;
ADVector3 value2 = envLight.img01 * dx2 * dy1 + envLight.img11 * dx1 * dy1;
value = (value1 + value2);
pdf = (Luminance(value1) * envLight.rowWeight0 + Luminance(value2) * envLight.rowWeight1) *
envLight.normalization / fmax(fabs(sinTheta), Float(1e-7));
}
void SampleDirectEnvLight(const ADFloat *buffer,
const ADBSphere &sceneSphere,
const ADVector3 &pos,
const ADVector3 &normal,
const ADVector2 rndParam,
const ADFloat time,
const bool isStatic,
ADVector3 &dirToLight,
ADVector3 &lightContrib,
ADFloat &cosAtLight,
ADFloat &directPdf,
ADFloat &emissionPdf) {
ADEnvLight envLight;
Deserialize(buffer, envLight);
ADVector3 value;
SampleDirection(envLight, rndParam, time, dirToLight, value, directPdf);
lightContrib = value * inverse(directPdf);
cosAtLight = Const<ADFloat>(1.0);
ADFloat positionPdf = c_INVPI / square(sceneSphere.radius);
emissionPdf = directPdf * positionPdf;
}
void EmissionEnvLight(const ADFloat *buffer,
const ADBSphere &sceneSphere,
const ADVector3 &dirToLight,
const ADVector3 &normalOnLight,
const ADFloat time,
ADVector3 &emission,
ADFloat &directPdf,
ADFloat &emissionPdf) {
ADEnvLight envLight;
Deserialize(buffer, envLight);
ADMatrix4x4 transform = Interpolate(envLight.toLight, time);
ADVector3 d = XformVector(transform, dirToLight);
ADVector2 uv(atan2(d[0], -d[2]) / envLight.pixelSize[0] - Float(0.5),
acos(d[1]) / envLight.pixelSize[1] - Float(0.5));
ADFloat dx1 = uv[0] - envLight.col, dx2 = Float(1.0) - dx1, dy1 = uv[1] - envLight.row,
dy2 = Float(1.0) - dy1;
ADVector3 value1 = envLight.img00 * dx2 * dy2 + envLight.img10 * dx1 * dy2;
ADVector3 value2 = envLight.img01 * dx2 * dy1 + envLight.img11 * dx1 * dy1;
emission = value1 + value2;
// Ugly hack to avoid undefined derivatives
ADFloat sinTheta = sqrt(fmax(Float(1.0) - square(d[1]), Float(1e-6)));
directPdf =
(Luminance(value1) * envLight.rowWeight0 + Luminance(value2) * envLight.rowWeight1) *
envLight.normalization / fmax(fabs(sinTheta), Float(1e-7));
ADFloat positionPdf = c_INVPI / square(sceneSphere.radius);
emissionPdf = directPdf * positionPdf;
}
void EmitEnvLight(const ADFloat *buffer,
const ADBSphere &sceneSphere,
const ADVector2 rndParamPos,
const ADVector2 rndParamDir,
const ADFloat time,
const bool isStatic,
ADRay &ray,
ADVector3 &emission,
ADFloat &cosAtLight,
ADFloat &emissionPdf,
ADFloat &directPdf) {
ADEnvLight envLight;
Deserialize(buffer, envLight);
SampleDirection(envLight, rndParamDir, time, ray.dir, emission, directPdf);
ray.dir = -ray.dir;
ADVector2 offset = SampleConcentricDisc(rndParamPos);
ADVector3 b0, b1;
CoordinateSystem(ray.dir, b0, b1);
ADVector3 perpOffset = offset[0] * b0 + offset[1] * b1;
ray.org = sceneSphere.center + (perpOffset - ray.dir) * sceneSphere.radius;
cosAtLight = Const<ADFloat>(1.0);
ADFloat positionPdf = c_INVPI / square(sceneSphere.radius);
emissionPdf = directPdf * positionPdf;
}
| 40.325 | 100 | 0.595226 | [
"vector",
"transform"
] |
73ad3b528fb262b827d55e8ed875f877d3631c8a | 6,792 | cpp | C++ | 03_Tutorial/T06_XMGraphics/G03_PVRAlphaBlend/Source/main.cpp | mcodegeeks/OpenKODE-Framework | d4382d781da7f488a0e7667362a89e8e389468dd | [
"MIT"
] | 2 | 2017-08-03T07:15:00.000Z | 2018-06-18T10:32:53.000Z | 03_Tutorial/T06_XMGraphics/G03_PVRAlphaBlend/Source/main.cpp | mcodegeeks/OpenKODE-Framework | d4382d781da7f488a0e7667362a89e8e389468dd | [
"MIT"
] | null | null | null | 03_Tutorial/T06_XMGraphics/G03_PVRAlphaBlend/Source/main.cpp | mcodegeeks/OpenKODE-Framework | d4382d781da7f488a0e7667362a89e8e389468dd | [
"MIT"
] | 2 | 2019-03-04T22:57:42.000Z | 2020-03-06T01:32:26.000Z | /*
*
* File main.cpp
* Description XMGraphics : PVR AlphaBlend demo application
* Version 0.20.0801, 2011-08-01
* Author Y.H Mun
*
* --------------------------------------------------------------------------
*
* Copyright (C) 2010 XMSoft. All rights reserved.
*
* Contact Email: chris@xmsoft.co.kr
* xmsoft77@gmail.com
*
*
* 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 in the file COPYING.LIB;
* if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*
*/
#include "main.h"
#include "platform.h"
XM_APP_MAIN_BEGIN
XM_APP_WND_REALIZE(XM_SYS_DEFAULT)
XM_APP_MAIN_END
KDvoid xmEventCreate ( KDvoid )
{
KD_SET_TLS ( KDTLS );
KD_GET_TLS ( KDTLS, tls );
tls->xmg_canvas = new XMGCanvas ( );
tls->xmg_font[0] = new XMGFont ( "/res/font/COOPBL.TTF" );
tls->xmg_font[1] = new XMGFont ( "/res/font/BrushScriptStd.otf" );
tls->xmg_tex[0] = new XMGTexture ( "/res/image/Background.pvr" );
tls->xmg_tex[1] = new XMGTexture ( "/res/image/Foreground.pvr" );
tls->xmg_text = new XMGText ( 3 );
tls->xmg_quad = new XMGQuad ( 2 );
tls->xmg_font[ 1 ]->SetSize ( 18 );
tls->xmg_text->SetFont ( tls->xmg_font[ 0 ], 0 );
tls->xmg_text->SetText ( "XMGraphics : PVR AlphaBlend", 0 );
for ( GLuint idx = 1; idx < 3; idx++ )
{
tls->xmg_text->SetFont ( tls->xmg_font[ 1 ], idx );
tls->xmg_text->SetLineAlign ( XMG_ALIGN_CENTER, idx );
tls->xmg_text->SetColor ( XMGColorF ( 1.0f, 0.6f, 0.3f, 1.0f ), idx );
}
tls->xmg_quad->SetBlend ( XMG_TRUE );
tls->xmg_quad->SetVertexArray ( tls->xmg_tex[ 1 ], 1 );
tls->xmg_quad->SetTexture ( tls->xmg_tex[ 0 ], XMG_FLIP_NULL, XMG_TEX_UNIT_0, 0 );
tls->xmg_quad->SetTexture ( tls->xmg_tex[ 1 ], XMG_FLIP_NULL, XMG_TEX_UNIT_0, 1 );
tls->app_index = 3;
}
KDvoid xmEventDestroy ( KDvoid )
{
KD_GET_TLS ( KDTLS, tls );
delete tls->xmg_quad;
delete tls->xmg_text;
delete tls->xmg_tex[0];
delete tls->xmg_tex[1];
delete tls->xmg_font[0];
delete tls->xmg_font[1];
delete tls->xmg_canvas;
}
KDvoid xmEventRedraw ( KDvoid )
{
KD_GET_TLS ( KDTLS, tls );
tls->xmg_canvas->Clear ( );
tls->xmg_quad->Render ( );
tls->xmg_text->Render ( );
tls->xmg_canvas->Flush ( );
}
KDvoid xmEventUpdate ( KDuint msec )
{
KD_GET_TLS ( KDTLS, tls );
if ( msec - tls->app_time > 2000 )
{
tls->app_time = msec;
tls->app_index = tls->app_index == 3 ? 0 : tls->app_index + 1;
switch ( tls->app_index )
{
case 0 :
tls->xmg_quad->SetBlendOP ( XMG_BLEND_SRC_ALPHA, XMG_BLEND_ONE_MINUS_SRC_ALPHA, 1 );
tls->xmg_text->SetText ( "TRANSPARENCY", 1 );
tls->xmg_text->SetText ( "(SRC_ALPHA, 1 - SRC_ALPHA)", 2 );
break;
case 1 :
tls->xmg_quad->SetBlendOP ( XMG_BLEND_ONE, XMG_BLEND_ONE, 1 );
tls->xmg_text->SetText ( "ADDITIVE", 1 );
tls->xmg_text->SetText ( "(ONE, ONE)", 2 );
break;
case 2 :
tls->xmg_quad->SetBlendOP ( XMG_BLEND_DST_COLOR, XMG_BLEND_ZERO, 1 );
tls->xmg_text->SetText ( "MODULATE", 1 );
tls->xmg_text->SetText ( "(DST_COLOR, ZERO)", 2 );
break;
case 3 :
tls->xmg_quad->SetBlendOP ( XMG_BLEND_DST_COLOR, XMG_BLEND_SRC_COLOR, 1 );
tls->xmg_text->SetText ( "MODULATE X2", 1 );
tls->xmg_text->SetText ( "(DST_COLOR, SRC_COLOR)", 2 );
break;
}
}
}
KDvoid xmEventResize ( KDint width, KDint height )
{
KD_GET_TLS ( KDTLS, tls );
XMGRectF wnd = XMGRectF ( 0, 0, 0, XMG_I2F ( width ), XMG_I2F ( height ) );
XMGVector3F pos;
XMGVector2F size;
tls->xmg_tex[ 1 ]->GetImageSize ( size );
pos = XMGVector3F ( ( width - size.m_x ) * 0.5f, ( height - size.m_y ) * 0.5f + 20.0f );
tls->xmg_canvas->Viewport ( wnd );
tls->xmg_canvas->Perspective ( width, height );
tls->xmg_text->SetLineLength ( wnd.m_w - 5.0f );
tls->xmg_text->SetPosition ( XMGVector3F ( 5.0f, wnd.m_h - 20.0f ), 0 );
tls->xmg_text->SetPosition ( XMGVector3F ( 5.0f, pos.m_y - 30.0f ), 1 );
tls->xmg_text->SetPosition ( XMGVector3F ( 5.0f, pos.m_y - 60.0f ), 2 );
tls->xmg_quad->SetVertexArray ( &wnd, 0 );
tls->xmg_quad->SetPosition ( pos, 1 );
}
KD_API KDvoid KD_APIENTRY xmEventProc(const KDEvent* event)
{
switch (event->type)
{
case KD_EVENT_NATIVE:
{
//#if !defined ( SHP ) && defined ( _WIN32 )
//KDEventNativeWin32* proc = (KDEventNativeWin32*) event->data.native.p;
//KDEventNativeLinux* proc = (KDEventNativeLinux*) event->data.native.p;
//#endif
} break;
case KD_EVENT_CREATE:
{
// event->data.size.width;
// event->data.size.height;
xmEventCreate();
xmEventResize(event->data.size.width, event->data.size.height);
} break;
case KD_EVENT_DESTROY:
{
xmEventDestroy();
} break;
case KD_EVENT_RESIZE:
{
// event->data.size.width;
// event->data.size.height;
xmEventResize(event->data.size.width, event->data.size.height);
} break;
case KD_EVENT_FOCUS:
{
// event->data.value.i;
// 1 : focus
} break;
case KD_EVENT_VISIBLE:
{
// event->data.value.i;
// 1 : visible
} break;
case KD_EVENT_REDRAW:
{
xmEventRedraw();
} break;
case KD_EVENT_UPDATE:
{
// event->data.update.msec;
xmEventUpdate(event->data.update.msec);
} break;
case KD_EVENT_TOUCH_BEGAN:
{
// event->data.touch.touches;
// event->data.touch.count;
} break;
case KD_EVENT_TOUCH_MOVED:
{
} break;
case KD_EVENT_TOUCH_ENDED:
{
} break;
case KD_EVENT_TOUCH_CANCELLED:
{
} break;
case KD_EVENT_KEY_RELEASED:
{
// event->data.keypad.code;
} break;
case KD_EVENT_KEY_PRESSED:
{
} break;
case KD_EVENT_ACCELEROMETER:
{
// event->data.accelerometer.x;
// event->data.accelerometer.y;
// event->data.accelerometer.z;
} break;
case KD_EVENT_LOCATION:
{
// event->data.value.i;
// KD_NMEA_UPDATED_GPS, KD_NMEA_UPDATED_USER
} break;
case KD_EVENT_INSERT_TEXT:
{
// event->data.insert.utf8;
} break;
case KD_EVENT_SERIALIZE:
{
// event->data.serialize.type;
// event->data.serialize.data;
// event->data.serialize.size;
} break;
}
} | 24.344086 | 89 | 0.629564 | [
"render"
] |
73ad95c04918c218d563884f8d43be2ace67ba6d | 13,329 | cpp | C++ | MoravaEngine/src/H2M/Renderer/SceneRendererVulkanH2M.cpp | imgui-works/MoravaEngine_opengl_vulkan_2d_3d_game_engine | b8e6ee3c3c890e9b8cf5de7bcb564b32f6767b6b | [
"Apache-2.0"
] | null | null | null | MoravaEngine/src/H2M/Renderer/SceneRendererVulkanH2M.cpp | imgui-works/MoravaEngine_opengl_vulkan_2d_3d_game_engine | b8e6ee3c3c890e9b8cf5de7bcb564b32f6767b6b | [
"Apache-2.0"
] | null | null | null | MoravaEngine/src/H2M/Renderer/SceneRendererVulkanH2M.cpp | imgui-works/MoravaEngine_opengl_vulkan_2d_3d_game_engine | b8e6ee3c3c890e9b8cf5de7bcb564b32f6767b6b | [
"Apache-2.0"
] | 1 | 2022-01-05T03:51:02.000Z | 2022-01-05T03:51:02.000Z | /**
* @package H2M (Hazel to Morava)
* @author Yan Chernikov (TheCherno)
* @licence Apache License 2.0
*/
#include "SceneRendererVulkanH2M.h"
#include "H2M/Platform/Vulkan/VulkanFramebufferH2M.h"
#include "H2M/Platform/Vulkan/VulkanRendererH2M.h"
#include "H2M/Renderer/FramebufferH2M.h"
#include "H2M/Renderer/RendererH2M.h"
#include "H2M/Renderer/RenderPassH2M.h"
#include "H2M/Renderer/Renderer2D_H2M.h"
namespace H2M {
struct SceneRendererData
{
const SceneH2M* ActiveScene = nullptr;
struct SceneInfo
{
SceneRendererCameraH2M SceneCamera;
// Resources
RefH2M<MaterialH2M> SkyboxMaterial;
EnvironmentH2M SceneEnvironment;
float SkyboxLod = 0.0f;
float SceneEnvironmentIntensity;
LightEnvironmentH2M SceneLightEnvironment;
LightH2M ActiveLight;
glm::vec3 LightDirectionTemp;
} SceneData;
RefH2M<Texture2D_H2M> BRDFLUT;
RefH2M<ShaderH2M> CompositeShader;
RefH2M<MaterialH2M> CompositeMaterial;
RefH2M<MoravaShader> BloomBlurShader;
RefH2M<MoravaShader> BloomBlendShader;
RefH2M<RenderPassH2M> GeoPass;
RefH2M<RenderPassH2M> CompositePass;
RefH2M<RenderPassH2M> BloomBlurPass[2];
RefH2M<RenderPassH2M> BloomBlendPass;
RefH2M<PipelineH2M> GeometryPipeline;
RefH2M<PipelineH2M> CompositePipeline;
RefH2M<PipelineH2M> SkyboxPipeline;
RefH2M<PipelineH2M> ShadowPassPipeline;
RefH2M<MaterialH2M> SkyboxMaterial;
struct DrawCommand
{
RefH2M<MeshH2M> Mesh;
RefH2M<MaterialH2M> Material;
glm::mat4 Transform;
};
std::vector<DrawCommand> DrawList;
std::vector<DrawCommand> SelectedMeshDrawList;
std::vector<DrawCommand> ColliderDrawList;
std::vector<DrawCommand> ShadowPassDrawList;
// Grid
RefH2M<PipelineH2M> GridPipeline;
RefH2M<ShaderH2M> GridShader;
RefH2M<MaterialH2M> GridMaterial;
RefH2M<MaterialH2M> OutlineMaterial;
RefH2M<MaterialH2M> OutlineAnimMaterial;
SceneRendererOptionsH2M Options;
uint32_t ViewportWidth = 0;
uint32_t ViewportHeight = 0;
bool NeedsResize = false;
VkDescriptorImageInfo ColorBufferInfo;
};
static SceneRendererData s_Data;
void SceneRendererVulkanH2M::Init()
{
FramebufferSpecificationH2M geoFramebufferSpec = {};
geoFramebufferSpec.Width = 1280;
geoFramebufferSpec.Height = 720;
geoFramebufferSpec.Format = FramebufferFormatH2M::RGBA16F;
geoFramebufferSpec.Samples = 8;
geoFramebufferSpec.ClearColor = { 0.1f, 0.1f, 0.1f, 1.0f };
RenderPassSpecificationH2M geoRenderPassSpec = {};
geoRenderPassSpec.TargetFramebuffer = FramebufferH2M::Create(geoFramebufferSpec);
/****
s_Data.GeoPass = RenderPass::Create(geoRenderPassSpec);
FramebufferSpecificationH2M compFramebufferSpec = {};
compFramebufferSpec.Width = 1280;
compFramebufferSpec.Height = 720;
compFramebufferSpec.Format = FramebufferFormat::RGBA8;
compFramebufferSpec.ClearColor = { 0.5f, 0.1f, 0.1f, 1.0f };
RenderPassSpecification compRenderPassSpec;
compRenderPassSpec.TargetFramebuffer = HazelFramebuffer::Create(compFramebufferSpec);
s_Data.CompositePass = RenderPass::Create(compRenderPassSpec);
s_Data.CompositeShader = RendererH2M::GetShaderLibrary()->Get("SceneComposite");
s_Data.CompositeMaterial = HazelMaterial::Create(s_Data.CompositeShader, "CompositeMaterial");
s_Data.BRDFLUT = HazelTexture2D::Create("assets/textures/BRDF_LUT.tga");
// Grid pipeline
{
s_Data.GridShader = RendererH2M::GetShaderLibrary()->Get("Grid");
const float gridScale = 16.025f;
const float gridSize = 0.025f;
s_Data.GridMaterial = HazelMaterial::Create(s_Data.GridShader);
// s_Data.GridMaterial->Set("u_Settings.Scale", gridScale); // TODO: fix "We currently only support ONE material buffer!"
// s_Data.GridMaterial->Set("u_Settings.Size", gridSize); // TODO: fix "We currently only support ONE material buffer!"
PipelineSpecification pipelineSpec = {};
pipelineSpec.DebugName = "Grid";
pipelineSpec.Shader = s_Data.GridShader;
pipelineSpec.Layout = {
{ ShaderDataType::Float3, "a_Position" },
{ ShaderDataType::Float2, "a_TexCoord" },
};
pipelineSpec.RenderPass = s_Data.GeoPass;
s_Data.GridPipeline = Pipeline::Create(pipelineSpec); // fragment shader writes to output location 1 with no matching attachment
}
// Outline
auto outlineShader = RendererH2M::GetShaderLibrary()->Get("Outline");
s_Data.OutlineMaterial = HazelMaterial::Create(outlineShader);
s_Data.OutlineMaterial->SetFlag(HazelMaterialFlag::DepthTest, false);
// Skybox pipeline
{
auto skyboxShader = RendererH2M::GetShaderLibrary()->Get("Skybox");
PipelineSpecification pipelineSpec = {};
pipelineSpec.DebugName = "Skybox";
pipelineSpec.Shader = skyboxShader;
pipelineSpec.Layout = {
{ ShaderDataType::Float3, "a_Position" },
{ ShaderDataType::Float2, "a_TexCoord" },
};
pipelineSpec.RenderPass = s_Data.GeoPass;
// s_Data.SkyboxPipeline = Pipeline::Create(pipelineSpec);
s_Data.SkyboxMaterial = HazelMaterial::Create(skyboxShader);
s_Data.SkyboxMaterial->SetFlag(HazelMaterialFlag::DepthTest, false);
}
// Geometry pipeline
{
FramebufferSpecificationH2M spec = {};;
Ref<HazelFramebuffer> framebuffer = HazelFramebuffer::Create(spec);
PipelineSpecification pipelineSpecification = {};
pipelineSpecification.Layout = {
{ ShaderDataType::Float3, "a_Position" },
{ ShaderDataType::Float3, "a_Normal" },
{ ShaderDataType::Float3, "a_Tangent" },
{ ShaderDataType::Float3, "a_Binormal" },
{ ShaderDataType::Float2, "a_TexCoord" },
};
pipelineSpecification.Shader = RendererH2M::GetShaderLibrary()->Get("HazelPBR_Static");
RenderPassSpecification renderPassSpec = {};
renderPassSpec.TargetFramebuffer = framebuffer;
pipelineSpecification.RenderPass = RenderPass::Create(renderPassSpec);
pipelineSpecification.DebugName = "PBR-Static";
// s_Data.GeometryPipeline = Pipeline::Create(pipelineSpecification); // fragment shader writes to output location 1 with no matching attachment
}
// Composite pipeline
{
FramebufferSpecificationH2M spec = {};;
Ref<HazelFramebuffer> framebuffer = HazelFramebuffer::Create(spec);
framebuffer->AddResizeCallback([](Ref<HazelFramebuffer> framebuffer)
{
// RendererH2M::Submit([framebuffer]() mutable {});
{
auto vulkanFB = framebuffer.As<VulkanFramebuffer>();
s_Data.ColorBufferInfo = vulkanFB->GetVulkanDescriptorInfo();
}
});
PipelineSpecification pipelineSpecification;
pipelineSpecification.Layout = {
{ ShaderDataType::Float3, "a_Position" },
{ ShaderDataType::Float2, "a_TexCoord" },
};
pipelineSpecification.Shader = RendererH2M::GetShaderLibrary()->Get("SceneComposite");
RenderPassSpecification renderPassSpec;
renderPassSpec.TargetFramebuffer = framebuffer;
pipelineSpecification.RenderPass = RenderPass::Create(renderPassSpec);
pipelineSpecification.DebugName = "SceneComposite";
// s_Data.CompositePipeline = Pipeline::Create(pipelineSpecification); // fragment shader writes to output location 1 with no matching attachment
}
****/
}
void SceneRendererVulkanH2M::SetViewportSize(uint32_t width, uint32_t height)
{
s_Data.ViewportWidth = width;
s_Data.ViewportHeight = height;
s_Data.NeedsResize = true;
}
void SceneRendererVulkanH2M::BeginScene(const SceneH2M* scene, const SceneRendererCameraH2M& camera)
{
H2M_CORE_ASSERT(!s_Data.ActiveScene, "");
s_Data.ActiveScene = scene;
s_Data.SceneData.SceneCamera = camera;
// s_Data.SceneData.SkyboxMaterial = scene->GetSkyboxMaterial();
s_Data.SceneData.SceneEnvironment = scene->GetEnvironment();
s_Data.SceneData.SkyboxLod = scene->GetSkyboxLod();
s_Data.SceneData.ActiveLight = scene->GetLight();
if (s_Data.NeedsResize)
{
s_Data.GeoPass->GetSpecification().TargetFramebuffer->Resize(s_Data.ViewportWidth, s_Data.ViewportHeight);
s_Data.CompositePipeline->GetSpecification().RenderPass->GetSpecification().TargetFramebuffer->Resize(s_Data.ViewportWidth, s_Data.ViewportHeight);
s_Data.NeedsResize = false;
}
RendererH2M::SetSceneEnvironment(&s_Data.SceneData.SceneEnvironment, RefH2M<Image2D_H2M>());
}
void SceneRendererVulkanH2M::EndScene()
{
H2M_CORE_ASSERT(s_Data.ActiveScene, "");
s_Data.ActiveScene = nullptr;
FlushDrawList();
}
void SceneRendererVulkanH2M::SubmitMesh(MeshComponentH2M meshComponent, TransformComponentH2M transformComponent)
{
SubmitMesh(meshComponent.Mesh, transformComponent.GetTransform(), RefH2M<MaterialH2M>());
}
void SceneRendererVulkanH2M::SubmitSelectedMesh(MeshComponentH2M meshComponent, TransformComponentH2M transformComponent)
{
SubmitSelectedMesh(meshComponent.Mesh, transformComponent.GetTransform());
}
void SceneRendererVulkanH2M::SubmitMesh(RefH2M<MeshH2M> mesh, const glm::mat4& transform, RefH2M<MaterialH2M> overrideMaterial)
{
// TODO: Culling, sorting, etc.
s_Data.DrawList.push_back({ mesh, overrideMaterial, transform });
}
void SceneRendererVulkanH2M::SubmitSelectedMesh(RefH2M<MeshH2M> mesh, const glm::mat4& transform)
{
s_Data.SelectedMeshDrawList.push_back({ mesh, RefH2M<MaterialH2M>(), transform });
// s_Data.ShadowPassDrawList.push_back({ mesh, Ref<HazelMaterial>, transform });
}
void SceneRendererVulkanH2M::GeometryPass()
{
RendererH2M::BeginRenderPass(s_Data.GeoPass);
auto viewProjection = s_Data.SceneData.SceneCamera.Camera.GetProjectionMatrix() * s_Data.SceneData.SceneCamera.ViewMatrix;
glm::vec3 cameraPosition = glm::inverse(s_Data.SceneData.SceneCamera.ViewMatrix)[3];
// glm::vec3 cameraPosition = s_Data.SceneData.SceneCamera.Camera.GetPosition();
// RendererH2M::Submit([viewProjection, cameraPosition]() {});
{
auto inverseVP = glm::inverse(viewProjection);
auto shader = s_Data.GridMaterial->GetShader().As<VulkanShaderH2M>();
void* ubPtr = shader->MapUniformBuffer(0);
struct ViewProj
{
glm::mat4 ViewProjection;
glm::mat4 InverseViewProjection;
};
ViewProj viewProj;
viewProj.ViewProjection = viewProjection;
viewProj.InverseViewProjection = inverseVP;
memcpy(ubPtr, &viewProj, sizeof(ViewProj));
shader->UnmapUniformBuffer(0);
shader = s_Data.SkyboxMaterial->GetShader().As<VulkanShaderH2M>();
ubPtr = shader->MapUniformBuffer(0);
memcpy(ubPtr, &viewProj, sizeof(ViewProj));
shader->UnmapUniformBuffer(0);
shader = s_Data.GeometryPipeline->GetSpecification().Shader.As<VulkanShaderH2M>();
ubPtr = shader->MapUniformBuffer(0);
memcpy(ubPtr, &viewProj, sizeof(ViewProj));
shader->UnmapUniformBuffer(0);
struct Light
{
glm::vec3 Direction;
float Padding = 0.0f;
glm::vec3 Radiance;
float Multiplier;
};
struct UB
{
Light lights;
glm::vec3 u_CameraPosition;
};
UB ub;
ub.lights =
{
{ 0.5f, 0.5f, 0.5f },
0.0f,
{ 1.0f, 1.0f, 1.0f },
1.0f
};
ub.lights.Direction = VulkanRendererH2M::GetLightDirectionTemp();
ub.u_CameraPosition = cameraPosition;
ubPtr = shader->MapUniformBuffer(1, 0);
memcpy(ubPtr, &ub, sizeof(UB));
shader->UnmapUniformBuffer(1, 0);
}
// Skybox
s_Data.SkyboxMaterial->Set("u_Uniforms.TextureLod", s_Data.SceneData.SkyboxLod);
s_Data.SkyboxMaterial->Set("u_Texture", s_Data.SceneData.SceneEnvironment.RadianceMap);
RendererH2M::SubmitFullscreenQuad(s_Data.SkyboxPipeline, s_Data.SkyboxMaterial);
// Render entities
for (auto& dc : s_Data.DrawList)
{
RendererH2M::RenderMesh(s_Data.GeometryPipeline, dc.Mesh, dc.Transform);
}
for (auto& dc : s_Data.SelectedMeshDrawList)
{
RendererH2M::RenderMesh(s_Data.GeometryPipeline, dc.Mesh, dc.Transform);
}
// Grid
if (GetOptions().ShowGrid)
{
const glm::mat4 transform = glm::rotate(glm::mat4(1.0f), glm::radians(90.0f), glm::vec3(1.0f, 0.0f, 0.0f)) * glm::scale(glm::mat4(1.0f), glm::vec3(16.0f));
RendererH2M::RenderQuad(s_Data.GridPipeline, s_Data.GridMaterial, transform);
}
if (GetOptions().ShowBoundingBoxes)
{
Renderer2D_H2M::BeginScene(viewProjection, true);
for (auto& dc : s_Data.DrawList)
{
RendererH2M::DrawAABB(dc.Mesh, dc.Transform);
}
Renderer2D_H2M::EndScene();
}
RendererH2M::EndRenderPass();
}
void SceneRendererVulkanH2M::CompositePass()
{
RendererH2M::BeginRenderPass(s_Data.CompositePipeline->GetSpecification().RenderPass);
float exposure = s_Data.SceneData.SceneCamera.Camera.GetExposure();
int textureSamples = s_Data.GeoPass->GetSpecification().TargetFramebuffer->GetSpecification().Samples;
s_Data.CompositeMaterial->Set("u_Uniforms.Exposure", exposure);
// s_Data.CompositeMaterial->Set("u_Uniforms.TextureSamples", textureSamples);
auto& framebuffer = s_Data.GeoPass->GetSpecification().TargetFramebuffer;
auto vulkanFramebuffer = framebuffer.As<VulkanFramebufferH2M>();
// s_Data.CompositeMaterial->Set("u_Texture", vulkanFramebuffer->GetVulkanDescriptorInfo()); // how it works?
s_Data.CompositeMaterial->Set("u_Texture", vulkanFramebuffer->GetColorAttachmentRendererID());
RendererH2M::SubmitFullscreenQuad(s_Data.CompositePipeline, s_Data.CompositeMaterial);
RendererH2M::EndRenderPass();
}
void SceneRendererVulkanH2M::FlushDrawList()
{
H2M_CORE_ASSERT(!s_Data.ActiveScene, "");
GeometryPass();
CompositePass();
}
SceneRendererOptionsH2M& SceneRendererVulkanH2M::GetOptions()
{
return s_Data.Options;
}
}
| 33.3225 | 158 | 0.749644 | [
"mesh",
"geometry",
"render",
"vector",
"transform"
] |
73af475efeca3072e586293e1669835b7bf04a18 | 225 | hpp | C++ | ELSreplicate/ELSreplicate/interpolater.hpp | FinancialEngineerLab/EquityLinkedIn | 1b4b46081841f370aee0abc5aa97d42ac6ede853 | [
"MIT"
] | null | null | null | ELSreplicate/ELSreplicate/interpolater.hpp | FinancialEngineerLab/EquityLinkedIn | 1b4b46081841f370aee0abc5aa97d42ac6ede853 | [
"MIT"
] | null | null | null | ELSreplicate/ELSreplicate/interpolater.hpp | FinancialEngineerLab/EquityLinkedIn | 1b4b46081841f370aee0abc5aa97d42ac6ede853 | [
"MIT"
] | null | null | null |
#ifndef INTERPOLATOR_HPP
#define INTERPOLATOR_HPP
#include <vector>
class interpolator
{
public:
interpolator(){};
double intp1d(std::vector<double> v, std::vector<double> axis, double target) const;
};
#endif
| 16.071429 | 88 | 0.715556 | [
"vector"
] |
73b073e3ead998208cde1fc1a28b2dc60b3c2a2d | 4,551 | hpp | C++ | src/libs/optframe/src/OptFrame/GlobalSearch.hpp | fellipessanha/LMRRC-Team-AIDA | 8076599427df0e35890caa7301972a53ae327edb | [
"MIT"
] | 1 | 2021-08-19T13:31:29.000Z | 2021-08-19T13:31:29.000Z | src/libs/optframe/src/OptFrame/GlobalSearch.hpp | fellipessanha/LMRRC-Team-AIDA | 8076599427df0e35890caa7301972a53ae327edb | [
"MIT"
] | null | null | null | src/libs/optframe/src/OptFrame/GlobalSearch.hpp | fellipessanha/LMRRC-Team-AIDA | 8076599427df0e35890caa7301972a53ae327edb | [
"MIT"
] | null | null | null | // OptFrame - Optimization Framework
// Copyright (C) 2009-2015
// http://optframe.sourceforge.net/
//
// This file is part of the OptFrame optimization framework. This framework
// is free software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License v3 as published by the
// Free Software Foundation.
// This framework 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 v3 for more details.
// You should have received a copy of the GNU Lesser General Public License v3
// along with this library; see the file COPYING. If not, write to the Free
// Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
// USA.
#ifndef OPTFRAME_GLOBAL_SEARCH_HPP_
#define OPTFRAME_GLOBAL_SEARCH_HPP_
#include <cstring>
#include <iostream>
#include <vector>
#include "Component.hpp"
#include "ComponentBuilder.h"
#include "BaseConcepts.hpp"
#include "InitialSearch.hpp"
#include "StopCriteria.hpp"
#include "SearchOutput.hpp"
using namespace std;
namespace optframe {
// Defaulting SearchSpace to XES, it means, <S,XEv> space (typically, single obj search)
//template<XESolution XES, XSearch<XES> XSH = XES, XSearchMethod XM = Component>
//
//template<XESolution XES, XEvaluation XEv = Evaluation<>, XSearch<XES> XSH = XES>
//
// 'XES' is the "base concept" for the primary search component.
// 'XSH' is the primary search type ('best' has type XSH)
// 'XES2' is the "base concept" for the secondary search component.
// 'XSH2' is the secondary search type ('incumbent' has type XSH2)
template<XESolution XES, XSearch<XES> XSH = XES, XESolution XES2 = XES, XSearch<XES2> XSH2 = XES2>
class GlobalSearch : public Component
{
using XEv = typename XES::second_type;
public:
// best known XSH object: solution/pareto/etc
//std::optional<XSH> best;
// current/working XSH2 object: population/etc
//std::optional<XSH2> incumbent;
// ----------
//
// callback action 'onBest' is triggered after best is updated (if 'beforeUpdateBest' is required some day, think about it.. not now)
// returning 'false' should lead to aborting execution (by target, for instance)
//
bool (*onBest)(GlobalSearch<XES, XSH, XES2, XSH2>& self, const XSH& best) =
[](GlobalSearch<XES, XSH, XES2, XSH2>& self, const XSH& best) { return true; };
//
bool (*onIncumbent)(GlobalSearch<XES, XSH, XES2, XSH2>& self, const XSH2& incumbent) =
[](GlobalSearch<XES, XSH, XES2, XSH2>& self, const XSH2& incumbent) { return true; };
// strict or non-strict search
bool strict{ true };
GlobalSearch()
{
}
virtual ~GlobalSearch()
{
}
// Assuming method is not thread-safe. Now, we can easily use flag SearchStatus::RUNNING.
virtual SearchOutput<XES, XSH> search(const StopCriteria<XEv>& stopCriteria) = 0;
/*
virtual SearchStatus searchBy(std::optional<XSH>& _best, std::optional<XSH2>& _inc, const StopCriteria<XEv>& stopCriteria)
{
best = _best;
incumbent = _inc;
return search(stopCriteria);
}
*/
virtual string log() const
{
return "Empty heuristic log.";
}
virtual bool compatible(string s)
{
return (s == idComponent()) || (Component::compatible(s));
}
static string idComponent()
{
stringstream ss;
ss << Component::idComponent() << "GlobalSearch:";
return ss.str();
}
virtual string id() const
{
return idComponent();
}
};
template<XSolution S, XEvaluation XEv, XESolution XES, XSearch<XES> XSH, XESolution XES2, XSearch<XES> XSH2 = XSH>
class GlobalSearchBuilder : public ComponentBuilder<S, XEv, XSH>
{
public:
virtual ~GlobalSearchBuilder()
{
}
virtual GlobalSearch<XES, XSH, XES2, XSH2>* build(Scanner& scanner, HeuristicFactory<S, XEv, XES, XSH>& hf, string family = "") = 0;
virtual Component* buildComponent(Scanner& scanner, HeuristicFactory<S, XEv, XES, XSH>& hf, string family = "")
{
return build(scanner, hf, family);
}
virtual vector<pair<string, string>> parameters() = 0;
virtual bool canBuild(string) = 0;
static string idComponent()
{
stringstream ss;
ss << ComponentBuilder<S, XEv, XSH>::idComponent() << "GlobalSearch:";
return ss.str();
}
virtual string id() const
{
return idComponent();
}
};
} // namespace optframe
#endif /* OPTFRAME_GLOBAL_SEARCH_HPP_ */
| 30.139073 | 136 | 0.689739 | [
"object",
"vector"
] |
73b42fe5cc974db87b08dbe37b7d49b2d41cc26a | 61,456 | cpp | C++ | packages/monte_carlo/event/estimator/src/MonteCarlo_Estimator.cpp | bam241/FRENSIE | e1760cd792928699c84f2bdce70ff54228e88094 | [
"BSD-3-Clause"
] | 10 | 2019-11-14T19:58:30.000Z | 2021-04-04T17:44:09.000Z | packages/monte_carlo/event/estimator/src/MonteCarlo_Estimator.cpp | bam241/FRENSIE | e1760cd792928699c84f2bdce70ff54228e88094 | [
"BSD-3-Clause"
] | 43 | 2020-03-03T19:59:20.000Z | 2021-09-08T03:36:08.000Z | packages/monte_carlo/event/estimator/src/MonteCarlo_Estimator.cpp | bam241/FRENSIE | e1760cd792928699c84f2bdce70ff54228e88094 | [
"BSD-3-Clause"
] | 6 | 2020-02-12T17:37:07.000Z | 2020-09-08T18:59:51.000Z | //---------------------------------------------------------------------------//
//!
//! \file MonteCarlo_Estimator.cpp
//! \author Alex Robinson
//! \brief Estimator base class definition
//!
//---------------------------------------------------------------------------//
// Std Lib Includes
#include <limits>
// FRENSIE Includes
#include "FRENSIE_Archives.hpp"
#include "MonteCarlo_Estimator.hpp"
#include "Utility_OpenMPProperties.hpp"
#include "Utility_LoggingMacros.hpp"
namespace MonteCarlo{
// Initialize static member data
std::shared_ptr<const std::vector<double> > Estimator::s_default_sample_moment_histogram_bins;
// Default constructor
Estimator::Estimator()
: d_id( std::numeric_limits<Id>::max() )
{ /* ... */ }
// Constructor
Estimator::Estimator( const Id id, const double multiplier )
: d_id( id ),
d_multiplier( multiplier ),
d_particle_types(),
d_response_functions( 1 ),
d_sample_moment_histogram_bins( Estimator::getDefaultSampleMomentHistogramBins() ),
d_has_uncommitted_history_contribution( 1, false )
{
// Make sure the multiplier is valid
TEST_FOR_EXCEPTION( multiplier == 0.0,
std::runtime_error,
"The multiplier cannot be zero!" );
// Set the response function
d_response_functions[0] = ParticleResponse::getDefault();
}
// Return the estimator id
auto Estimator::getId() const -> Id
{
return d_id;
}
// Return the estimator constant multiplier
double Estimator::getMultiplier() const
{
return d_multiplier;
}
// Add a response function
/*! \details Before the response function is assigned, the object will check
* if it is compatible with the estimator type (e.g. cell
* track-length flux estimators are only compatible with spatially uniform
* response functions).
*/
void Estimator::addResponseFunction(
const std::shared_ptr<const ParticleResponse>& response_function )
{
// Make sure that the response function pointer is valid
testPrecondition( response_function.get() );
this->assignResponseFunction( response_function );
}
// Set the response functions
/*! \details Before the response functions are assigned, the object will check
* if each response function is compatible with the estimator type (e.g. cell
* track-length flux estimators are only compatible with spatially uniform
* response functions). Any previously added response functions will be
* removed.
*/
void Estimator::setResponseFunctions(
const std::vector<std::shared_ptr<const ParticleResponse> >&
response_functions )
{
// Make sure that there is at least one response function
testPrecondition( response_functions.size() > 0 );
d_response_functions.clear();
// Assign each response function individually
for( auto&& response_function_ptr : response_functions )
this->addResponseFunction( response_function_ptr );
// There must always be at least one response function - if they were all
// rejected add the default.
if( d_response_functions.empty() )
d_response_functions.push_back( ParticleResponse::getDefault() );
}
// Return the number of response functions
size_t Estimator::getNumberOfResponseFunctions() const
{
return d_response_functions.size();
}
// Set the particle types that can contribute to the estimator
/*! \details Before each particle type is assigned the object will check
* if the particle type is compatible with the estimator type (e.g. cell
* pulse height estimators are not compatible with neutrons).
*/
void Estimator::setParticleTypes( const std::vector<ParticleType>& particle_types )
{
this->setParticleTypes( std::set<ParticleType>( particle_types.begin(),
particle_types.end() ) );
}
// Set the particle types that can contribute to the estimator
/*! \details Before each particle type is assigned the object will check
* if the particle type is compatible with the estimator type (e.g. cell
* pulse height estimators are not compatible with neutrons).
*/
void Estimator::setParticleTypes( const std::set<ParticleType>& particle_types )
{
// Make sure that there is at least one particle type
TEST_FOR_EXCEPTION( particle_types.size() == 0,
std::runtime_error,
"At least on particle type must be assigned!" );
// Assign each particle type individually
for( auto&& particle_type : particle_types )
this->assignParticleType( particle_type );
}
// Get the particle types that can contribute to the estimator
const std::set<ParticleType>& Estimator::getParticleTypes() const
{
return d_particle_types;
}
// Check if the particle type is assigned to the estimator
bool Estimator::isParticleTypeAssigned( const ParticleType particle_type) const
{
return d_particle_types.find( particle_type ) !=
d_particle_types.end();
}
// Set the sample moment histogram bins
void Estimator::setSampleMomentHistogramBins( const std::shared_ptr<const std::vector<double> >& bin_boundaries )
{
// Make sure that the bins are valid
testPrecondition( bin_boundaries.get() );
this->assignSampleMomentHistogramBins( bin_boundaries );
}
// Get the sample moment histogram bins
const std::shared_ptr<const std::vector<double> >& Estimator::getSampleMomentHistogramBins()
{
return d_sample_moment_histogram_bins;
}
// Get the entity bin sample moment histogram
void Estimator::getEntityBinSampleMomentHistogram(
const EntityId entity_id,
const size_t bin_index,
Utility::SampleMomentHistogram<double>& histogram ) const
{ /* ... */ }
// Get the total bin sample moment histogram
void Estimator::getTotalBinSampleMomentHistogram(
const size_t bin_index,
Utility::SampleMomentHistogram<double>& histogram ) const
{ /* ... */ }
// Get the entity total sample moment histogram
void Estimator::getEntityTotalSampleMomentHistogram(
const EntityId entity_id,
const size_t response_function_index,
Utility::SampleMomentHistogram<double>& histogram ) const
{ /* ... */ }
// Get the total sample moment histogram
void Estimator::getTotalSampleMomentHistogram(
const size_t response_function_index,
Utility::SampleMomentHistogram<double>& histogram ) const
{ /* ... */ }
// Get the default history score pdf bins
const std::shared_ptr<const std::vector<double> >& Estimator::getDefaultSampleMomentHistogramBins()
{
// Initialize the default bins just-in-time
if( !s_default_sample_moment_histogram_bins )
{
s_default_sample_moment_histogram_bins = std::make_shared<const std::vector<double> >( Utility::fromString<std::vector<double> >( "{-1.7976931348623157e+308, 0.0, 1e-30, 599l, 1e30, 1.7976931348623157e+308}" ) );
}
return s_default_sample_moment_histogram_bins;
}
// Set the cosine cutoff value
void Estimator::setCosineCutoffValue( const double )
{
FRENSIE_LOG_TAGGED_WARNING( "Estimator",
"The cosine cutoff is not used by this type "
"of estimator!" );
}
// Check if the estimator has uncommitted history contributions
bool Estimator::hasUncommittedHistoryContribution(
const unsigned thread_id ) const
{
// Make sure the thread is is valid
testPrecondition( thread_id < d_has_uncommitted_history_contribution.size());
return d_has_uncommitted_history_contribution[thread_id];
}
// Check if the estimator has uncommitted history contributions
bool Estimator::hasUncommittedHistoryContribution() const
{
return this->hasUncommittedHistoryContribution(
Utility::OpenMPProperties::getThreadId() );
}
// Enable support for multiple threads
void Estimator::enableThreadSupport( const unsigned num_threads )
{
// Make sure only the master thread calls this function
testPrecondition( Utility::OpenMPProperties::getThreadId() == 0 );
d_has_uncommitted_history_contribution.resize( num_threads, false );
}
// Reduce estimator data on all processes and collect on the root process
void Estimator::reduceData( const Utility::Communicator& comm,
const int root_process )
{
if( comm.rank() != root_process )
this->resetData();
}
// Log a summary of the data
void Estimator::logSummary() const
{
std::ostringstream oss;
this->printSummary( oss );
FRENSIE_LOG_NOTIFICATION( oss.str() );
}
// Get the total estimator bin mean and relative error
/*! \details Make sure that the number of histories have been set
* (MonteCarlo::ParticleHistoryObserver::setNumberOfHistories) and that the
* elapsed time has been set
* (MonteCarlo::ParticleHistoryObserver::setNumberOfHistories).
*/
void Estimator::getTotalBinProcessedData(
std::vector<double>& mean,
std::vector<double>& relative_error,
std::vector<double>& variance_of_variance,
std::vector<double>& figure_of_merit ) const
{
Utility::ArrayView<const double> first_moments =
this->getTotalBinDataFirstMoments();
Utility::ArrayView<const double> second_moments =
this->getTotalBinDataSecondMoments();
Utility::ArrayView<const double> third_moments =
this->getTotalBinDataThirdMoments();
Utility::ArrayView<const double> fourth_moments =
this->getTotalBinDataFourthMoments();
// Resize the output arrays
mean.resize( first_moments.size() );
relative_error.resize( first_moments.size() );
variance_of_variance.resize( first_moments.size() );
figure_of_merit.resize( first_moments.size() );
for( size_t i = 0; i < first_moments.size(); ++i )
{
this->processMoments( Utility::SampleMoment<1,double>(first_moments[i]),
Utility::SampleMoment<2,double>(second_moments[i]),
Utility::SampleMoment<3,double>(third_moments[i]),
Utility::SampleMoment<4,double>(fourth_moments[i]),
this->getTotalNormConstant(),
mean[i],
relative_error[i],
variance_of_variance[i],
figure_of_merit[i] );
}
}
// Get the total estimator bin mean and relative error
/*! \details Make sure that the number of histories have been set
* (MonteCarlo::ParticleHistoryObserver::setNumberOfHistories) and that the
* elapsed time has been set
* (MonteCarlo::ParticleHistoryObserver::setNumberOfHistories). The map keys
* are "mean", "re", and "fom".
*/
void Estimator::getTotalBinProcessedData(
std::map<std::string,std::vector<double> >& processed_data ) const
{
processed_data.clear();
this->getTotalBinProcessedData( processed_data["mean"],
processed_data["re"],
processed_data["vov"],
processed_data["fom"] );
}
// Get the bin data mean and relative error for an entity
/*! \details Make sure that the number of histories have been set
* (MonteCarlo::ParticleHistoryObserver::setNumberOfHistories) and that the
* elapsed time has been set
* (MonteCarlo::ParticleHistoryObserver::setNumberOfHistories).
*/
void Estimator::getEntityBinProcessedData(
const EntityId entity_id,
std::vector<double>& mean,
std::vector<double>& relative_error,
std::vector<double>& variance_of_variance,
std::vector<double>& figure_of_merit ) const
{
// Make sure that the entity id is valid
TEST_FOR_EXCEPTION( !this->isEntityAssigned( entity_id ),
std::runtime_error,
"Entity " << entity_id << " is not assigned to "
"estimator " << this->getId() << "!" );
Utility::ArrayView<const double> first_moments =
this->getEntityBinDataFirstMoments( entity_id );
Utility::ArrayView<const double> second_moments =
this->getEntityBinDataSecondMoments( entity_id );
Utility::ArrayView<const double> third_moments =
this->getEntityBinDataThirdMoments( entity_id );
Utility::ArrayView<const double> fourth_moments =
this->getEntityBinDataFourthMoments( entity_id );
// Resize the output arrays
mean.resize( first_moments.size() );
relative_error.resize( first_moments.size() );
variance_of_variance.resize( first_moments.size() );
figure_of_merit.resize( first_moments.size() );
for( size_t i = 0; i < first_moments.size(); ++i )
{
this->processMoments( Utility::SampleMoment<1,double>(first_moments[i]),
Utility::SampleMoment<2,double>(second_moments[i]),
Utility::SampleMoment<3,double>(third_moments[i]),
Utility::SampleMoment<4,double>(fourth_moments[i]),
this->getEntityNormConstant( entity_id ),
mean[i],
relative_error[i],
variance_of_variance[i],
figure_of_merit[i] );
}
}
// Get the bin data mean, relative error, and fom for an entity
/*! \details Make sure that the number of histories have been set
* (MonteCarlo::ParticleHistoryObserver::setNumberOfHistories) and that the
* elapsed time has been set
* (MonteCarlo::ParticleHistoryObserver::setNumberOfHistories). The map keys
* are "mean", "re", and "fom".
*/
void Estimator::getEntityBinProcessedData(
const EntityId entity_id,
std::map<std::string,std::vector<double> >& processed_data ) const
{
processed_data.clear();
this->getEntityBinProcessedData( entity_id,
processed_data["mean"],
processed_data["re"],
processed_data["vov"],
processed_data["fom"] );
}
// Check if total data is available
bool Estimator::isTotalDataAvailable() const
{
return false;
}
// Get the total data first moments
Utility::ArrayView<const double> Estimator::getTotalDataFirstMoments() const
{
return Utility::ArrayView<const double>();
}
// Get the total data second moments
Utility::ArrayView<const double> Estimator::getTotalDataSecondMoments() const
{
return Utility::ArrayView<const double>();
}
// Get the total data third moments
Utility::ArrayView<const double> Estimator::getTotalDataThirdMoments() const
{
return Utility::ArrayView<const double>();
}
// Get the total data fourth moments
Utility::ArrayView<const double> Estimator::getTotalDataFourthMoments() const
{
return Utility::ArrayView<const double>();
}
// Get the total data mean, relative error, vov and fom
/*! \details Make sure that the number of histories have been set
* (MonteCarlo::ParticleHistoryObserver::setNumberOfHistories) and that the
* elapsed time has been set
* (MonteCarlo::ParticleHistoryObserver::setNumberOfHistories).
*/
void Estimator::getTotalProcessedData(
std::vector<double>& mean,
std::vector<double>& relative_error,
std::vector<double>& variance_of_variance,
std::vector<double>& figure_of_merit ) const
{
Utility::ArrayView<const double> first_moments =
this->getTotalDataFirstMoments();
Utility::ArrayView<const double> second_moments =
this->getTotalDataSecondMoments();
Utility::ArrayView<const double> third_moments =
this->getTotalDataThirdMoments();
Utility::ArrayView<const double> fourth_moments =
this->getTotalDataFourthMoments();
// Resize the output arrays
mean.resize( first_moments.size() );
relative_error.resize( first_moments.size() );
variance_of_variance.resize( first_moments.size() );
figure_of_merit.resize( first_moments.size() );
for( size_t i = 0; i < first_moments.size(); ++i )
{
this->processMoments( Utility::SampleMoment<1,double>(first_moments[i]),
Utility::SampleMoment<2,double>(second_moments[i]),
Utility::SampleMoment<3,double>(third_moments[i]),
Utility::SampleMoment<4,double>(fourth_moments[i]),
this->getTotalNormConstant(),
mean[i],
relative_error[i],
variance_of_variance[i],
figure_of_merit[i] );
}
}
// Get the total data mean, relative error, vov and fom
/*! \details Make sure that the number of histories have been set
* (MonteCarlo::ParticleHistoryObserver::setNumberOfHistories) and that the
* elapsed time has been set
* (MonteCarlo::ParticleHistoryObserver::setNumberOfHistories). The map keys
* are "mean", "re", "vov" and "fom".
*/
void Estimator::getTotalProcessedData(
std::map<std::string,std::vector<double> >& processed_data ) const
{
processed_data.clear();
this->getTotalProcessedData( processed_data["mean"],
processed_data["re"],
processed_data["vov"],
processed_data["fom"] );
}
// Get the total data first moments for an entity
Utility::ArrayView<const double> Estimator::getEntityTotalDataFirstMoments( const size_t ) const
{
return Utility::ArrayView<const double>();
}
// Get the total data second moments for an entity
Utility::ArrayView<const double> Estimator::getEntityTotalDataSecondMoments( const size_t ) const
{
return Utility::ArrayView<const double>();
}
// Get the total data third moments for an entity
Utility::ArrayView<const double> Estimator::getEntityTotalDataThirdMoments( const size_t ) const
{
return Utility::ArrayView<const double>();
}
// Get the total data fourth moments for an entity
Utility::ArrayView<const double> Estimator::getEntityTotalDataFourthMoments( const size_t ) const
{
return Utility::ArrayView<const double>();
}
// Get the total data mean, relative error, vov and fom for an entity
/*! \details Make sure that the number of histories have been set
* (MonteCarlo::ParticleHistoryObserver::setNumberOfHistories) and that the
* elapsed time has been set
* (MonteCarlo::ParticleHistoryObserver::setNumberOfHistories).
*/
void Estimator::getEntityTotalProcessedData(
const EntityId entity_id,
std::vector<double>& mean,
std::vector<double>& relative_error,
std::vector<double>& variance_of_variance,
std::vector<double>& figure_of_merit ) const
{
Utility::ArrayView<const double> first_moments =
this->getEntityTotalDataFirstMoments( entity_id );
Utility::ArrayView<const double> second_moments =
this->getEntityTotalDataSecondMoments( entity_id );
Utility::ArrayView<const double> third_moments =
this->getEntityTotalDataThirdMoments( entity_id );
Utility::ArrayView<const double> fourth_moments =
this->getEntityTotalDataFourthMoments( entity_id );
// Resize the output arrays
mean.resize( first_moments.size() );
relative_error.resize( first_moments.size() );
variance_of_variance.resize( first_moments.size() );
figure_of_merit.resize( first_moments.size() );
for( size_t i = 0; i < first_moments.size(); ++i )
{
this->processMoments( Utility::SampleMoment<1,double>(first_moments[i]),
Utility::SampleMoment<2,double>(second_moments[i]),
Utility::SampleMoment<3,double>(third_moments[i]),
Utility::SampleMoment<4,double>(fourth_moments[i]),
this->getEntityNormConstant( entity_id ),
mean[i],
relative_error[i],
variance_of_variance[i],
figure_of_merit[i] );
}
}
// Get the total data mean, relative error, vov and fom for an entity
/*! \details Make sure that the number of histories have been set
* (MonteCarlo::ParticleHistoryObserver::setNumberOfHistories) and that the
* elapsed time has been set
* (MonteCarlo::ParticleHistoryObserver::setNumberOfHistories). The map keys
* are "mean", "re", "vov" and "fom".
*/
void Estimator::getEntityTotalProcessedData(
const EntityId entity_id,
std::map<std::string,std::vector<double> >& processed_data ) const
{
processed_data.clear();
this->getEntityTotalProcessedData( entity_id,
processed_data["mean"],
processed_data["re"],
processed_data["vov"],
processed_data["fom"] );
}
// Get the entity bin moment snapshot history values
void Estimator::getEntityBinMomentSnapshotHistoryValues(
const EntityId entity_id,
std::vector<uint64_t>& history_values ) const
{ /* ... */ }
// Get the entity bin moment snapshot sampling times
void Estimator::getEntityBinMomentSnapshotSamplingTimes(
const EntityId entity_id,
std::vector<double>& sampling_times ) const
{ /* ... */ }
// Get the bin data first moment snapshots for an entity bin index
void Estimator::getEntityBinFirstMomentSnapshots(
const EntityId entity_id,
const size_t bin_index,
std::vector<double>& moments ) const
{ /* ... */ }
// Get the bin data second moment snapshots for an entity bin index
void Estimator::getEntityBinSecondMomentSnapshots(
const EntityId entity_id,
const size_t bin_index,
std::vector<double>& moments ) const
{ /* ... */ }
// Get the bin data third moment snapshots for an entity bin index
void Estimator::getEntityBinThirdMomentSnapshots(
const EntityId entity_id,
const size_t bin_index,
std::vector<double>& moments ) const
{ /* ... */ }
// Get the bin data fourth moment snapshots for an entity bin index
void Estimator::getEntityBinFourthMomentSnapshots(
const EntityId entity_id,
const size_t bin_index,
std::vector<double>& moments ) const
{ /* ... */ }
// Get the entity bin processed snapshots
void Estimator::getEntityBinProcessedSnapshots(
const EntityId entity_id,
const size_t bin_index,
std::vector<double>& mean_snapshots,
std::vector<double>& relative_error_snapshots,
std::vector<double>& variance_of_variance_snapshots,
std::vector<double>& figure_of_merit_snapshots ) const
{
std::vector<uint64_t> history_values;
this->getEntityBinMomentSnapshotHistoryValues( entity_id, history_values );
std::vector<double> sampling_times;
this->getEntityBinMomentSnapshotSamplingTimes( entity_id, sampling_times );
std::vector<double> first_moments, second_moments, third_moments,
fourth_moments;
this->getEntityBinFirstMomentSnapshots( entity_id, bin_index, first_moments );
this->getEntityBinSecondMomentSnapshots( entity_id, bin_index, second_moments );
this->getEntityBinThirdMomentSnapshots( entity_id, bin_index, third_moments );
this->getEntityBinFourthMomentSnapshots( entity_id, bin_index, fourth_moments );
// Resize the output arrays
mean_snapshots.resize( first_moments.size() );
relative_error_snapshots.resize( first_moments.size() );
variance_of_variance_snapshots.resize( first_moments.size() );
figure_of_merit_snapshots.resize( first_moments.size() );
for( size_t i = 0; i < first_moments.size(); ++i )
{
this->processMoments( Utility::SampleMoment<1,double>(first_moments[i]),
Utility::SampleMoment<2,double>(second_moments[i]),
Utility::SampleMoment<3,double>(third_moments[i]),
Utility::SampleMoment<4,double>(fourth_moments[i]),
this->getEntityNormConstant( entity_id ),
history_values[i],
sampling_times[i],
mean_snapshots[i],
relative_error_snapshots[i],
variance_of_variance_snapshots[i],
figure_of_merit_snapshots[i] );
}
}
// Get the entity bin processed snapshots
void Estimator::getEntityBinProcessedSnapshots(
const EntityId entity_id,
const size_t bin_index,
std::map<std::string,std::vector<double> >& processed_snapshots ) const
{
processed_snapshots.clear();
this->getEntityBinProcessedSnapshots( entity_id,
bin_index,
processed_snapshots["mean"],
processed_snapshots["re"],
processed_snapshots["vov"],
processed_snapshots["fom"] );
}
// Get the moment snapshot history values
void Estimator::getTotalBinMomentSnapshotHistoryValues(
std::vector<uint64_t>& history_values ) const
{ /* ... */ }
// Get the moment snapshot sampling times for a total bin index
void Estimator::getTotalBinMomentSnapshotSamplingTimes(
std::vector<double>& sampling_times ) const
{ /* ... */ }
// Get the bin data first moment snapshots for an total bin index
void Estimator::getTotalBinFirstMomentSnapshots(
const size_t bin_index,
std::vector<double>& moments ) const
{ /* ... */ }
// Get the bin data second moment snapshots for an total bin index
void Estimator::getTotalBinSecondMomentSnapshots(
const size_t bin_index,
std::vector<double>& moments ) const
{ /* ... */ }
// Get the bin data third moment snapshots for an total bin index
void Estimator::getTotalBinThirdMomentSnapshots(
const size_t bin_index,
std::vector<double>& moments ) const
{ /* ... */ }
// Get the bin data fourth moment snapshots for an total bin index
void Estimator::getTotalBinFourthMomentSnapshots(
const size_t bin_index,
std::vector<double>& moments ) const
{ /* ... */ }
// Get the total bin processed snapshots
void Estimator::getTotalBinProcessedSnapshots(
const size_t bin_index,
std::vector<double>& mean_snapshots,
std::vector<double>& relative_error_snapshots,
std::vector<double>& variance_of_variance_snapshots,
std::vector<double>& figure_of_merit_snapshots ) const
{
std::vector<uint64_t> history_values;
this->getTotalBinMomentSnapshotHistoryValues( history_values );
std::vector<double> sampling_times;
this->getTotalBinMomentSnapshotSamplingTimes( sampling_times );
std::vector<double> first_moments, second_moments, third_moments,
fourth_moments;
this->getTotalBinFirstMomentSnapshots( bin_index, first_moments );
this->getTotalBinSecondMomentSnapshots( bin_index, second_moments );
this->getTotalBinThirdMomentSnapshots( bin_index, third_moments );
this->getTotalBinFourthMomentSnapshots( bin_index, fourth_moments );
// Resize the output arrays
mean_snapshots.resize( first_moments.size() );
relative_error_snapshots.resize( first_moments.size() );
variance_of_variance_snapshots.resize( first_moments.size() );
figure_of_merit_snapshots.resize( first_moments.size() );
for( size_t i = 0; i < first_moments.size(); ++i )
{
this->processMoments( Utility::SampleMoment<1,double>(first_moments[i]),
Utility::SampleMoment<2,double>(second_moments[i]),
Utility::SampleMoment<3,double>(third_moments[i]),
Utility::SampleMoment<4,double>(fourth_moments[i]),
this->getTotalNormConstant(),
history_values[i],
sampling_times[i],
mean_snapshots[i],
relative_error_snapshots[i],
variance_of_variance_snapshots[i],
figure_of_merit_snapshots[i] );
}
}
// Get the entity bin processed snapshots
void Estimator::getTotalBinProcessedSnapshots(
const size_t bin_index,
std::map<std::string,std::vector<double> >& processed_snapshots ) const
{
processed_snapshots.clear();
this->getTotalBinProcessedSnapshots( bin_index,
processed_snapshots["mean"],
processed_snapshots["re"],
processed_snapshots["vov"],
processed_snapshots["fom"] );
}
// Get the entity total moment snapshot history values
void Estimator::getEntityTotalMomentSnapshotHistoryValues(
const EntityId entity_id,
std::vector<uint64_t>& history_values ) const
{ /* ... */ }
// Get the entity total moment snapshot sampling times
void Estimator::getEntityTotalMomentSnapshotSamplingTimes(
const EntityId entity_id,
std::vector<double>& sampling_times ) const
{ /* ... */ }
// Get the total data first moment snapshots for an entity bin index
void Estimator::getEntityTotalFirstMomentSnapshots(
const EntityId entity_id,
const size_t response_function_index,
std::vector<double>& moments ) const
{ /* ... */ }
// Get the total data second moment snapshots for an entity bin index
void Estimator::getEntityTotalSecondMomentSnapshots(
const EntityId entity_id,
const size_t response_function_index,
std::vector<double>& moments ) const
{ /* ... */ }
// Get the total data third moment snapshots for an entity bin index
void Estimator::getEntityTotalThirdMomentSnapshots(
const EntityId entity_id,
const size_t response_function_index,
std::vector<double>& moments ) const
{ /* ... */ }
// Get the total data fourth moment snapshots for an entity bin index
void Estimator::getEntityTotalFourthMomentSnapshots(
const EntityId entity_id,
const size_t response_function_index,
std::vector<double>& moments ) const
{ /* ... */ }
// Get the entity bin processed snapshots
void Estimator::getEntityTotalProcessedSnapshots(
const EntityId entity_id,
const size_t response_function_index,
std::vector<double>& mean_snapshots,
std::vector<double>& relative_error_snapshots,
std::vector<double>& variance_of_variance_snapshots,
std::vector<double>& figure_of_merit_snapshots ) const
{
std::vector<uint64_t> history_values;
this->getEntityTotalMomentSnapshotHistoryValues( entity_id, history_values );
std::vector<double> sampling_times;
this->getEntityTotalMomentSnapshotSamplingTimes( entity_id, sampling_times );
std::vector<double> first_moments, second_moments, third_moments,
fourth_moments;
this->getEntityTotalFirstMomentSnapshots( entity_id, response_function_index, first_moments );
this->getEntityTotalSecondMomentSnapshots( entity_id, response_function_index, second_moments );
this->getEntityTotalThirdMomentSnapshots( entity_id, response_function_index, third_moments );
this->getEntityTotalFourthMomentSnapshots( entity_id, response_function_index, fourth_moments );
// Resize the output arrays
mean_snapshots.resize( first_moments.size() );
relative_error_snapshots.resize( first_moments.size() );
variance_of_variance_snapshots.resize( first_moments.size() );
figure_of_merit_snapshots.resize( first_moments.size() );
for( size_t i = 0; i < first_moments.size(); ++i )
{
this->processMoments( Utility::SampleMoment<1,double>(first_moments[i]),
Utility::SampleMoment<2,double>(second_moments[i]),
Utility::SampleMoment<3,double>(third_moments[i]),
Utility::SampleMoment<4,double>(fourth_moments[i]),
this->getEntityNormConstant( entity_id ),
history_values[i],
sampling_times[i],
mean_snapshots[i],
relative_error_snapshots[i],
variance_of_variance_snapshots[i],
figure_of_merit_snapshots[i] );
}
}
// Get the entity bin processed snapshots
void Estimator::getEntityTotalProcessedSnapshots(
const EntityId entity_id,
const size_t response_function_index,
std::map<std::string,std::vector<double> >& processed_snapshots ) const
{
processed_snapshots.clear();
this->getEntityTotalProcessedSnapshots( entity_id,
response_function_index,
processed_snapshots["mean"],
processed_snapshots["re"],
processed_snapshots["vov"],
processed_snapshots["fom"] );
}
// Get the total moment snapshot history values
void Estimator::getTotalMomentSnapshotHistoryValues(
std::vector<uint64_t>& history_values ) const
{ /* ... */ }
// Get the total moment snapshot sampling times
void Estimator::getTotalMomentSnapshotSamplingTimes(
std::vector<double>& sampling_times ) const
{ /* ... */ }
// Get the total data first moment snapshots for a total bin index
void Estimator::getTotalFirstMomentSnapshots(
const size_t response_function_index,
std::vector<double>& moments ) const
{ /* ... */ }
// Get the total data second moment snapshots for a total bin index
void Estimator::getTotalSecondMomentSnapshots(
const size_t response_function_index,
std::vector<double>& moments ) const
{ /* ... */ }
// Get the total data third moment snapshots for a total bin index
void Estimator::getTotalThirdMomentSnapshots(
const size_t response_function_index,
std::vector<double>& moments ) const
{ /* ... */ }
// Get the total data fourth moment snapshots for a total bin index
void Estimator::getTotalFourthMomentSnapshots(
const size_t response_function_index,
std::vector<double>& moments ) const
{ /* ... */ }
// Get the total bin processed snapshots
void Estimator::getTotalProcessedSnapshots(
const size_t response_function_index,
std::vector<double>& mean_snapshots,
std::vector<double>& relative_error_snapshots,
std::vector<double>& variance_of_variance_snapshots,
std::vector<double>& figure_of_merit_snapshots ) const
{
std::vector<uint64_t> history_values;
this->getTotalMomentSnapshotHistoryValues( history_values );
std::vector<double> sampling_times;
this->getTotalMomentSnapshotSamplingTimes( sampling_times );
std::vector<double> first_moments, second_moments, third_moments,
fourth_moments;
this->getTotalFirstMomentSnapshots( response_function_index, first_moments );
this->getTotalSecondMomentSnapshots( response_function_index, second_moments );
this->getTotalThirdMomentSnapshots( response_function_index, third_moments );
this->getTotalFourthMomentSnapshots( response_function_index, fourth_moments );
// Resize the output arrays
mean_snapshots.resize( first_moments.size() );
relative_error_snapshots.resize( first_moments.size() );
variance_of_variance_snapshots.resize( first_moments.size() );
figure_of_merit_snapshots.resize( first_moments.size() );
for( size_t i = 0; i < first_moments.size(); ++i )
{
this->processMoments( Utility::SampleMoment<1,double>(first_moments[i]),
Utility::SampleMoment<2,double>(second_moments[i]),
Utility::SampleMoment<3,double>(third_moments[i]),
Utility::SampleMoment<4,double>(fourth_moments[i]),
this->getTotalNormConstant(),
history_values[i],
sampling_times[i],
mean_snapshots[i],
relative_error_snapshots[i],
variance_of_variance_snapshots[i],
figure_of_merit_snapshots[i] );
}
}
// Get the entity bin processed snapshots
void Estimator::getTotalProcessedSnapshots(
const size_t response_function_index,
std::map<std::string,std::vector<double> >& processed_snapshots ) const
{
processed_snapshots.clear();
this->getTotalProcessedSnapshots( response_function_index,
processed_snapshots["mean"],
processed_snapshots["re"],
processed_snapshots["vov"],
processed_snapshots["fom"] );
}
// Assign response function to the estimator
/*! \details Override this method in a derived class if response function
* properties need to be checked before the assignment takes place.
*/
void Estimator::assignResponseFunction(
const std::shared_ptr<const ParticleResponse>& response_function )
{
// Make sure only the master thread calls this function
testPrecondition( Utility::OpenMPProperties::getThreadId() == 0 );
// Make sure that the response function pointer is valid
testPrecondition( response_function.get() );
d_response_functions.push_back( response_function );
}
// Assign the particle type to the estimator
/*! \details Override this method in a derived class if particular particle
* types need to be filtered.
*/
void Estimator::assignParticleType( const ParticleType particle_type )
{
// Make sure only the master thread calls this function
testPrecondition( Utility::OpenMPProperties::getThreadId() == 0 );
d_particle_types.insert( particle_type );
}
// Assign the history score pdf bins
/*! \details Override this method in a derived class if the class needs to
* allocate space for history score pdf values.
*/
void Estimator::assignSampleMomentHistogramBins( const std::shared_ptr<const std::vector<double> >& bins )
{
// Make sure only the master thread calls this function
testPrecondition( Utility::OpenMPProperties::getThreadId() == 0 );
d_sample_moment_histogram_bins = bins;
}
// Get the particle types that can contribute to the estimator
size_t Estimator::getNumberOfAssignedParticleTypes() const
{
return d_particle_types.size();
}
// Set the has uncommited history contribution flag
/*! \details This should be called whenever the current history contributes
* to the estimator.
*/
void Estimator::setHasUncommittedHistoryContribution(
const unsigned thread_id )
{
// Make sure the thread is is valid
testPrecondition( thread_id < d_has_uncommitted_history_contribution.size());
d_has_uncommitted_history_contribution[thread_id] = true;
}
// Unset the has uncommited history contribution flag
/*! \details This should be called when the current history contribution is
* committed to the estimator
*/
void Estimator::unsetHasUncommittedHistoryContribution(
const unsigned thread_id )
{
// Make sure the thread is is valid
testPrecondition( thread_id < d_has_uncommitted_history_contribution.size());
d_has_uncommitted_history_contribution[thread_id] = false;
}
// Reduce a single collection
void Estimator::reduceCollection(
const Utility::Communicator& comm,
const int root_process,
TwoEstimatorMomentsCollection& collection ) const
{
// Make sure the root process is valid
testPrecondition( root_process < comm.size() );
// Reduce the first moments
std::vector<double> reduced_first_moments;
this->reduceCollectionAndReturnReducedMoments<1>( comm,
root_process,
collection,
reduced_first_moments );
comm.barrier();
// Reduce the second moments
std::vector<double> reduced_second_moments;
this->reduceCollectionAndReturnReducedMoments<2>( comm,
root_process,
collection,
reduced_second_moments );
// The root process will store the reduced moments
if( comm.rank() == root_process )
{
for( size_t i = 0; i < collection.size(); ++i )
{
Utility::getCurrentScore<1>( collection, i ) = reduced_first_moments[i];
Utility::getCurrentScore<2>( collection, i ) = reduced_second_moments[i];
}
}
comm.barrier();
}
// Reduce a single collection
void Estimator::reduceCollection(
const Utility::Communicator& comm,
const int root_process,
FourEstimatorMomentsCollection& collection ) const
{
// Make sure the root process is valid
testPrecondition( root_process < comm.size() );
// Reduce the first moments
std::vector<double> reduced_first_moments;
this->reduceCollectionAndReturnReducedMoments<1>( comm,
root_process,
collection,
reduced_first_moments );
comm.barrier();
// Reduce the second moments
std::vector<double> reduced_second_moments;
this->reduceCollectionAndReturnReducedMoments<2>( comm,
root_process,
collection,
reduced_second_moments );
comm.barrier();
// Reduce the third moments
std::vector<double> reduced_third_moments;
this->reduceCollectionAndReturnReducedMoments<3>( comm,
root_process,
collection,
reduced_third_moments );
comm.barrier();
// Reduce the fourth moments
std::vector<double> reduced_fourth_moments;
this->reduceCollectionAndReturnReducedMoments<4>( comm,
root_process,
collection,
reduced_fourth_moments );
// The root process will store the reduced moments
if( comm.rank() == root_process )
{
for( size_t i = 0; i < collection.size(); ++i )
{
Utility::getCurrentScore<1>( collection, i ) = reduced_first_moments[i];
Utility::getCurrentScore<2>( collection, i ) = reduced_second_moments[i];
Utility::getCurrentScore<3>( collection, i ) = reduced_third_moments[i];
Utility::getCurrentScore<4>( collection, i ) = reduced_fourth_moments[i];
}
}
comm.barrier();
}
// Reduce snapshots
void Estimator::reduceSnapshots(
const Utility::Communicator& comm,
const int root_process,
FourEstimatorMomentsCollectionSnapshots& snapshots ) const
{
// Make sure that the root process is valid
testPrecondition( root_process < comm.size() );
// Gather all of the collection snapshots on the root process
if( comm.rank() == root_process )
{
std::vector<FourEstimatorMomentsCollectionSnapshots>
gathered_snapshots( comm.size() );
std::vector<Utility::Communicator::Request> gathered_requests;
for( size_t i = 0; i < comm.size(); ++i )
{
if( i != root_process )
{
gathered_requests.push_back(
Utility::ireceive( comm, i, 0, gathered_snapshots[i] ) );
}
}
std::vector<Utility::Communicator::Status>
gathered_statuses( gathered_requests.size() );
Utility::wait( gathered_requests, gathered_statuses );
// Merge the local snapshots with the snapshots gathered from the other
// procs
for( size_t i = 0; i < comm.size(); ++i )
{
if( i != root_process )
snapshots.mergeSnapshots( gathered_snapshots[i] );
}
}
else
Utility::send( comm, root_process, 0, snapshots );
}
// Return the response function name
const std::string& Estimator::getResponseFunctionName(
const size_t response_function_index ) const
{
// Make sure the response function index is valid
testPrecondition( response_function_index <
this->getNumberOfResponseFunctions() );
return d_response_functions[response_function_index]->getName();
}
// Return the bin name
std::string Estimator::getBinName( const size_t bin_index ) const
{
// Make sure the bin index is valid
testPrecondition( bin_index < this->getNumberOfBins()*this->getNumberOfResponseFunctions() );
return DiscretizableParticleHistoryObserver::getBinName( bin_index % this->getNumberOfBins() ) + ", " +
this->getResponseFunctionName( this->calculateResponseFunctionIndex( bin_index ) );
}
// Evaluate the desired response function
double Estimator::evaluateResponseFunction(
const ParticleState& particle,
const size_t response_function_index ) const
{
// Make sure the response function index is valid
testPrecondition( response_function_index < this->getNumberOfResponseFunctions() );
return d_response_functions[response_function_index]->evaluate( particle );
}
// Calculate the response function index given a bin index
size_t Estimator::calculateResponseFunctionIndex(
const size_t bin_index ) const
{
// Make sure the bin index is valid
testPrecondition( bin_index < this->getNumberOfBins()*this->getNumberOfResponseFunctions() );
return bin_index/this->getNumberOfBins();
}
// Calculate the bin indices for the desired response function
void Estimator::calculateBinIndicesAndWeightsOfRange(
const ObserverParticleStateWrapper& particle_state_wrapper,
const size_t response_function_index,
ObserverPhaseSpaceDimensionDiscretization::BinIndexWeightPairArray&
bin_indices_and_weights ) const
{
// Make sure the response function is valid
testPrecondition( response_function_index <
this->getNumberOfResponseFunctions() );
DiscretizableParticleHistoryObserver::calculateBinIndicesAndWeightsOfRange(
particle_state_wrapper,
bin_indices_and_weights );
// Add the response function index to each phase space bin index
for( size_t i = 0; i < bin_indices_and_weights.size(); ++i )
{
Utility::get<0>(bin_indices_and_weights[i]) +=
response_function_index*this->getNumberOfBins();
}
}
// Convert first and second moments to mean and relative error
void Estimator::processMoments( const TwoEstimatorMomentsCollection& moments,
const size_t index,
const double norm_constant,
double& mean,
double& relative_error,
double& figure_of_merit ) const
{
// Make sure that the index is valid
testPrecondition( index < moments.size() );
// Make sure that the norm constant is valid
testPrecondition( norm_constant > 0.0 );
this->processMoments( Utility::getMoment<1>( moments, index ),
Utility::getMoment<2>( moments, index ),
norm_constant,
mean,
relative_error,
figure_of_merit );
}
// Convert first and second moments to mean and relative error
void Estimator::processMoments( const Utility::SampleMoment<1,double>& first_moment,
const Utility::SampleMoment<2,double>& second_moment,
const double norm_constant,
double& mean,
double& relative_error,
double& figure_of_merit ) const
{
this->processMoments( first_moment,
second_moment,
norm_constant,
this->getNumberOfHistories(),
this->getElapsedTime(),
mean,
relative_error,
figure_of_merit );
}
// Convert first and second moments to mean and relative error
void Estimator::processMoments( const Utility::SampleMoment<1,double>& first_moment,
const Utility::SampleMoment<2,double>& second_moment,
const double norm_constant,
const uint64_t num_histories,
const double sampling_time,
double& mean,
double& relative_error,
double& figure_of_merit ) const
{
// Make sure that the norm constant is valid
testPrecondition( norm_constant > 0.0 );
// Make sure that the number of histories is valid
testPrecondition( num_histories > 0 );
// Make sure that the sampling time is valid
testPrecondition( sampling_time > 0.0 );
// Calculate the mean
mean = Utility::calculateMean( first_moment, num_histories );
mean *= d_multiplier/norm_constant;
// Calculate the relative error
relative_error =
Utility::calculateRelativeError( first_moment,
second_moment,
num_histories );
// Calculate the figure of merit
figure_of_merit = Utility::calculateFOM( relative_error, sampling_time );
}
// Convert first, second, third, fourth moments to mean, rel. er., vov, fom
void Estimator::processMoments( const FourEstimatorMomentsCollection& moments,
const size_t index,
const double norm_constant,
double& mean,
double& relative_error,
double& variance_of_variance,
double& figure_of_merit ) const
{
// Make sure that the index is valid
testPrecondition( index < moments.size() );
// Make sure the norm contant is valid
testPrecondition( norm_constant > 0.0 );
// Make sure the problem time is valid
testPrecondition( this->getElapsedTime() > 0.0 );
this->processMoments( Utility::getMoment<1>( moments, index ),
Utility::getMoment<2>( moments, index ),
Utility::getMoment<3>( moments, index ),
Utility::getMoment<4>( moments, index ),
norm_constant,
mean,
relative_error,
variance_of_variance,
figure_of_merit );
}
// Convert first, second, third, fourth moments to mean, rel. er., vov, fom
void Estimator::processMoments( const Utility::SampleMoment<1,double>& first_moment,
const Utility::SampleMoment<2,double>& second_moment,
const Utility::SampleMoment<3,double>& third_moment,
const Utility::SampleMoment<4,double>& fourth_moment,
const double norm_constant,
double& mean,
double& relative_error,
double& variance_of_variance,
double& figure_of_merit ) const
{
// Make sure the norm contant is valid
testPrecondition( norm_constant > 0.0 );
// Make sure the problem time is valid
testPrecondition( this->getElapsedTime() > 0.0 );
this->processMoments( first_moment,
second_moment,
third_moment,
fourth_moment,
norm_constant,
this->getNumberOfHistories(),
this->getElapsedTime(),
mean,
relative_error,
variance_of_variance,
figure_of_merit );
}
// Convert first, second, third, fourth moments to mean, rel. er., vov, fom
void Estimator::processMoments( const Utility::SampleMoment<1,double>& first_moment,
const Utility::SampleMoment<2,double>& second_moment,
const Utility::SampleMoment<3,double>& third_moment,
const Utility::SampleMoment<4,double>& fourth_moment,
const double norm_constant,
const uint64_t num_histories,
const double sampling_time,
double& mean,
double& relative_error,
double& variance_of_variance,
double& figure_of_merit ) const
{
// Make sure the norm contant is valid
testPrecondition( norm_constant > 0.0 );
// Make sure the problem time is valid
testPrecondition( sampling_time > 0.0 );
// Make sure that the number of histories is valid
testPrecondition( num_histories > 0 );
// Calculate the mean and relative error
this->processMoments( first_moment,
second_moment,
norm_constant,
num_histories,
sampling_time,
mean,
relative_error,
figure_of_merit );
// Calculate the relative variance of the variance
variance_of_variance = Utility::calculateRelativeVOV( first_moment,
second_moment,
third_moment,
fourth_moment,
num_histories );
}
// Print the estimator response function names
void Estimator::printEstimatorResponseFunctionNames( std::ostream& os ) const
{
os << "Response Functions: " << std::endl;
for( size_t i = 0u; i < d_response_functions.size(); ++i )
{
os << " " << i+1 << ".) "
<< this->getResponseFunctionName( i )
<< std::endl;
}
}
// Print the estimator data stored in an array
/*! \details The number of elements in the array should be equal to the
* the number of estimator bins times the number of response functions.
*/
void Estimator::printEstimatorBinData(
std::ostream& os,
const TwoEstimatorMomentsCollection& estimator_moments_data,
const double norm_constant ) const
{
// Make sure that the estimator moment array is valid
testPrecondition( estimator_moments_data.size() ==
this->getNumberOfBins()*
this->getNumberOfResponseFunctions() );
// Get the dimension ordering
std::vector<ObserverPhaseSpaceDimension> dimension_ordering;
DiscretizableParticleHistoryObserver::getDiscretizedDimensions( dimension_ordering );
std::map<ObserverPhaseSpaceDimension,size_t> dimension_index_step_size_map;
// Get the number of bins for each dimension
if( !dimension_ordering.empty() )
{
dimension_index_step_size_map[dimension_ordering.front()] = 1;
for( size_t i = 1; i < dimension_ordering.size(); ++i )
{
size_t& step_size = dimension_index_step_size_map[dimension_ordering[i]];
step_size = dimension_index_step_size_map[dimension_ordering[i-1]];
step_size *= this->getNumberOfBins( dimension_ordering[i-1] );
}
}
// Use this array to determine when bin indices should be printed
std::vector<size_t> previous_bin_indices(
dimension_ordering.size(),
std::numeric_limits<size_t>::max() );
for( size_t r = 0u; r < this->getNumberOfResponseFunctions(); ++r )
{
os << "Response Function: " << this->getResponseFunctionName( r )
<< std::endl;
for( size_t i = 0u; i < this->getNumberOfBins(); ++i )
{
for( size_t d = dimension_ordering.size()-1; d >= 0; --d )
{
const size_t dimension_index_step_size =
dimension_index_step_size_map.find(dimension_ordering[d])->second;
// Calculate the bin index for the dimension
size_t bin_index = (i/dimension_index_step_size)%
(this->getNumberOfBins( dimension_ordering[d] ));
// Print the bin boundaries if the dimension index has changed
if( bin_index != previous_bin_indices[d] )
{
previous_bin_indices[d] = bin_index;
// Add proper spacing before printing
for( size_t s = 0u; s < dimension_ordering.size()-d; ++s )
os << " ";
DiscretizableParticleHistoryObserver::print( os, dimension_ordering[d], bin_index );
// Print a new line character for all but the first dimension
if( d != 0 )
os << "\n";
}
}
// Calculate the bin index for the response function
size_t bin_index = i + r*this->getNumberOfBins();
// Calculate the estimator bin data
double estimator_bin_value;
double estimator_bin_rel_err;
double estimator_bin_fom;
this->processMoments( estimator_moments_data,
bin_index,
norm_constant,
estimator_bin_value,
estimator_bin_rel_err,
estimator_bin_fom );
// Print the estimator bin data
os << " " << estimator_bin_value
<< " " << estimator_bin_rel_err
<< " " << estimator_bin_fom
<< "\n";
}
}
os << std::flush;
}
// Print the total estimator data stored in an array
/*! \details The array should have one element for each response function
* assigned to the estimator.
*/
void Estimator::printEstimatorTotalData(
std::ostream& os,
const FourEstimatorMomentsCollection& total_estimator_moments_data,
const double norm_constant ) const
{
// Make sure that the total estimator moments data is valid
testPrecondition( total_estimator_moments_data.size() ==
this->getNumberOfResponseFunctions() );
for( size_t i = 0; i < d_response_functions.size(); ++i )
{
os << "Response Function: " << this->getResponseFunctionName( i )
<< std::endl;
double estimator_value;
double estimator_rel_err;
double estimator_vov;
double estimator_fom;
this->processMoments( total_estimator_moments_data,
i,
norm_constant,
estimator_value,
estimator_rel_err,
estimator_vov,
estimator_fom );
os << estimator_value << " "
<< estimator_rel_err << " "
<< estimator_vov << " "
<< estimator_fom << std::endl;
}
}
} // end MonteCarlo namespace
EXPLICIT_CLASS_SAVE_LOAD_INST( MonteCarlo::Estimator );
//---------------------------------------------------------------------------//
// end MonteCarlo_Estimator.cpp
//---------------------------------------------------------------------------//
| 39.394872 | 216 | 0.616701 | [
"object",
"vector"
] |
73b61e3522cc219a102127e429d82331a6d49d22 | 1,892 | cpp | C++ | CodeForces/1206 D.cpp | windcry1/My-ACM-ICPC | b85b1c83b72c6b51731dae946a0df57c31d3e7a1 | [
"MIT"
] | null | null | null | CodeForces/1206 D.cpp | windcry1/My-ACM-ICPC | b85b1c83b72c6b51731dae946a0df57c31d3e7a1 | [
"MIT"
] | null | null | null | CodeForces/1206 D.cpp | windcry1/My-ACM-ICPC | b85b1c83b72c6b51731dae946a0df57c31d3e7a1 | [
"MIT"
] | null | null | null | /*************************************************************************
>>> Author: WindCry1
>>> Mail: lanceyu120@gmail.com
>>> Website: https://windcry1.com
>>> Date: 8/18/2019 11:34:29 PM
*************************************************************************/
#include<cstring>
#include<cmath>
#include<cstdio>
#include<cctype>
#include<cstdlib>
#include<ctime>
#include<vector>
#include<iostream>
#include<string>
#include<queue>
#include<set>
#include<map>
#include<algorithm>
#include<complex>
#include<stack>
#include<bitset>
#include<iomanip>
#include<list>
#if __cplusplus >= 201103L
#include<unordered_map>
#include<unordered_set>
#endif
#define ll long long
#define ull unsigned long long
using namespace std;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
const double clf=1e-8;
const int MMAX=0x7fffffff;
const ll INF=0xfffffff;
const int mod=1e9+7;
vector<ll> v[4010];
ll dfn[4010];
ll ans=INF;
ll a[100010];
void tarjan(int x,int sd)
{
dfn[x]=sd;
for(int i=0;i<v[x].size();i++)
{
if(!dfn[v[x][i]])
tarjan(v[x][i],sd+1);
else
{
if(sd-dfn[v[x][i]]+1>=3)
ans=min(sd-dfn[v[x][i]]+1,ans);
}
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
//freopen("C:\\Users\\LENOVO\\Desktop\\in.txt","r",stdin);
//freopen("C:\\Users\\LENOVO\\Desktop\\out.txt","w",stdout);
int n;cin>>n;
for(int i=0;i<n;i++) cin>>a[i];
sort(a,a+n,greater<ll>());
int m=min(n,4000);
for(int i=0;i<m;i++)
for(int j=i+1;j<m;j++)
cout<<a[i]<<" & "<<a[j]<<" : "<<(a[i]&a[j])<<endl;
for(int i=0;i<m;i++)
{
for(int j=i+1;j<m;j++){
if(a[i]&a[j]){
v[i].push_back(j);
v[j].push_back(i);
}
}
cout<<"v["<<i<<"] : ";
for(auto j:v[i])
cout<<j<<" ";
cout<<endl;
}
for(int i=0;i<m;i++)
if(!dfn[i])
tarjan(i,1);
cout<<(ans==INF?-1:ans)<<endl;
return 0;
}
| 21.022222 | 74 | 0.539641 | [
"vector"
] |
73bb65f2eb4c44ee3a03aeb1533956948156d3b3 | 13,325 | cpp | C++ | cgame/cg_localents.cpp | kugelrund/Elite-Reinforce | a2fe0c0480ff2d9cdc241b9e5416ee7f298f00ca | [
"DOC"
] | 10 | 2017-07-04T14:38:48.000Z | 2022-03-08T22:46:39.000Z | cgame/cg_localents.cpp | UberGames/SP-Mod-Source-Code | 04e0e618d1ee57a2919f1a852a688c03b1aa155d | [
"DOC"
] | null | null | null | cgame/cg_localents.cpp | UberGames/SP-Mod-Source-Code | 04e0e618d1ee57a2919f1a852a688c03b1aa155d | [
"DOC"
] | 2 | 2017-04-23T18:24:44.000Z | 2021-11-19T23:27:03.000Z |
// cg_localents.c -- every frame, generate renderer commands for locally
// processed entities, like smoke puffs, gibs, shells, etc.
#include "cg_local.h"
#include "fx_public.h"
#define MAX_LOCAL_ENTITIES 512
localEntity_t cg_localEntities[MAX_LOCAL_ENTITIES];
localEntity_t cg_activeLocalEntities; // double linked list
localEntity_t *cg_freeLocalEntities; // single linked list
/*
===================
CG_InitLocalEntities
This is called at startup and for tournement restarts
===================
*/
void CG_InitLocalEntities( void ) {
int i;
memset( cg_localEntities, 0, sizeof( cg_localEntities ) );
cg_activeLocalEntities.next = &cg_activeLocalEntities;
cg_activeLocalEntities.prev = &cg_activeLocalEntities;
cg_freeLocalEntities = cg_localEntities;
for ( i = 0 ; i < MAX_LOCAL_ENTITIES - 1 ; i++ ) {
cg_localEntities[i].next = &cg_localEntities[i+1];
}
}
/*
==================
CG_FreeLocalEntity
==================
*/
void CG_FreeLocalEntity( localEntity_t *le ) {
if ( !le->prev ) {
CG_Error( "CG_FreeLocalEntity: not active" );
}
// remove from the doubly linked active list
le->prev->next = le->next;
le->next->prev = le->prev;
// the free list is only singly linked
le->next = cg_freeLocalEntities;
cg_freeLocalEntities = le;
}
/*
===================
CG_AllocLocalEntity
Will allways succeed, even if it requires freeing an old active entity
===================
*/
localEntity_t *CG_AllocLocalEntity( void ) {
localEntity_t *le;
if ( !cg_freeLocalEntities ) {
// no free entities, so free the one at the end of the chain
// remove the oldest active entity
CG_FreeLocalEntity( cg_activeLocalEntities.prev );
}
le = cg_freeLocalEntities;
cg_freeLocalEntities = cg_freeLocalEntities->next;
memset( le, 0, sizeof( *le ) );
// link into the active list
le->next = cg_activeLocalEntities.next;
le->prev = &cg_activeLocalEntities;
cg_activeLocalEntities.next->prev = le;
cg_activeLocalEntities.next = le;
le->ownerGentNum = -1;
return le;
}
/*
====================================================================================
FRAGMENT PROCESSING
A fragment localentity interacts with the environment in some way (hitting walls),
or generates more localentities along a trail.
====================================================================================
*/
/*
================
CG_FragmentBounceSound
================
*/
void CG_FragmentBounceSound( localEntity_t *le, trace_t *trace ) {
/* if ( le->leBounceSoundType == LEBS_BLOOD ) {
// half the gibs will make splat sounds
if ( rand() & 1 ) {
int r = rand()&3;
sfxHandle_t s;
if ( r < 2 ) {
s = cgs.media.gibBounce1Sound;
} else if ( r == 2 ) {
s = cgs.media.gibBounce2Sound;
} else {
s = cgs.media.gibBounce3Sound;
}
cgi_S_StartSound( trace->endpos, ENTITYNUM_WORLD, CHAN_AUTO, s );
}
} else if ( le->leBounceSoundType == LEBS_BRASS ) {
}
// don't allow a fragment to make multiple bounce sounds,
// or it gets too noisy as they settle
le->leBounceSoundType = LEBS_NONE;
*/
}
/*
================
CG_ReflectVelocity
================
*/
void CG_ReflectVelocity( localEntity_t *le, trace_t *trace ) {
vec3_t velocity;
float dot;
int hitTime;
// reflect the velocity on the trace plane
hitTime = cg.time - cg.frametime + cg.frametime * trace->fraction;
EvaluateTrajectoryDelta( &le->pos, hitTime, velocity );
dot = DotProduct( velocity, trace->plane.normal );
VectorMA( velocity, -2*dot, trace->plane.normal, le->pos.trDelta );
VectorScale( le->pos.trDelta, le->bounceFactor, le->pos.trDelta );
VectorCopy( trace->endpos, le->pos.trBase );
le->pos.trTime = cg.time;
// check for stop, making sure that even on low FPS systems it doesn't bobble
if ( trace->allsolid ||
( trace->plane.normal[2] > 0 &&
( le->pos.trDelta[2] < 40 || le->pos.trDelta[2] < -cg.frametime * le->pos.trDelta[2] ) ) ) {
le->pos.trType = TR_STATIONARY;
} else {
}
}
/*
================
CG_AddFragment
================
*/
void CG_AddFragment( localEntity_t *le ) {
vec3_t newOrigin;
trace_t trace;
if ( le->pos.trType == TR_STATIONARY ) {
// sink into the ground if near the removal time
int t;
float oldZ;
t = le->endTime - cg.time;
if ( t < SINK_TIME ) {
// we must use an explicit lighting origin, otherwise the
// lighting would be lost as soon as the origin went
// into the ground
VectorCopy( le->refEntity.origin, le->refEntity.lightingOrigin );
le->refEntity.renderfx |= RF_LIGHTING_ORIGIN;
oldZ = le->refEntity.origin[2];
le->refEntity.origin[2] -= 16 * ( 1.0 - (float)t / SINK_TIME );
cgi_R_AddRefEntityToScene( &le->refEntity );
le->refEntity.origin[2] = oldZ;
} else {
cgi_R_AddRefEntityToScene( &le->refEntity );
}
return;
}
// calculate new position
EvaluateTrajectory( &le->pos, cg.time, newOrigin );
// trace a line from previous position to new position
CG_Trace( &trace, le->refEntity.origin, NULL, NULL, newOrigin, le->ownerGentNum, CONTENTS_SOLID );
if ( trace.fraction == 1.0 ) {
// still in free fall
VectorCopy( newOrigin, le->refEntity.origin );
if ( le->leFlags & LEF_TUMBLE ) {
vec3_t angles;
EvaluateTrajectory( &le->angles, cg.time, angles );
AnglesToAxis( angles, le->refEntity.axis );
for(int k = 0; k < 3; k++)
{
VectorScale(le->refEntity.axis[k], le->radius, le->refEntity.axis[k]);
}
}
cgi_R_AddRefEntityToScene( &le->refEntity );
return;
}
// if it is in a nodrop zone, remove it
// this keeps gibs from waiting at the bottom of pits of death
// and floating levels
if ( cgi_CM_PointContents( trace.endpos, 0 ) & CONTENTS_NODROP ) {
CG_FreeLocalEntity( le );
return;
}
// do a bouncy sound
CG_FragmentBounceSound( le, &trace );
// reflect the velocity on the trace plane
CG_ReflectVelocity( le, &trace );
//FIXME: if LEF_TUMBLE, change avelocity too?
cgi_R_AddRefEntityToScene( &le->refEntity );
}
/*
=====================================================================
TRIVIAL LOCAL ENTITIES
These only do simple scaling or modulation before passing to the renderer
=====================================================================
*/
/*
** CG_AddTeleporterEffect
*/
void CG_AddTeleporterEffect( localEntity_t *le ) {
refEntity_t *re;
float c;
re = &le->refEntity;
c = ( le->endTime - cg.time ) / ( float ) ( le->endTime - le->startTime );
re->shaderRGBA[0] =
re->shaderRGBA[1] =
re->shaderRGBA[2] =
re->shaderRGBA[3] = 0xff * c;
cgi_R_AddRefEntityToScene( re );
}
/*
** CG_AddFadeRGB
*/
void CG_AddFadeRGB( localEntity_t *le ) {
refEntity_t *re;
float c;
re = &le->refEntity;
c = ( le->endTime - cg.time ) * le->lifeRate;
c *= 0xff;
re->shaderRGBA[0] = le->color[0] * c;
re->shaderRGBA[1] = le->color[1] * c;
re->shaderRGBA[2] = le->color[2] * c;
re->shaderRGBA[3] = le->color[3] * c;
cgi_R_AddRefEntityToScene( re );
}
/*
==================
CG_AddPuff
==================
*/
static void CG_AddPuff( localEntity_t *le ) {
refEntity_t *re;
float c;
vec3_t delta;
float len;
re = &le->refEntity;
// fade / grow time
c = ( le->endTime - cg.time ) * le->lifeRate;
re->shaderRGBA[3] = 0xff * c * le->color[3];
if ( !( le->leFlags & LEF_PUFF_DONT_SCALE ) ) {
re->radius = le->radius * ( 1.0 - c ) + 8;
}
EvaluateTrajectory( &le->pos, cg.time, re->origin );
// if the view would be "inside" the sprite, kill the sprite
// so it doesn't add too much overdraw
VectorSubtract( re->origin, cg.refdef.vieworg, delta );
len = VectorLength( delta );
if ( len < le->radius ) {
CG_FreeLocalEntity( le );
return;
}
cgi_R_AddRefEntityToScene( re );
}
/*
===================
CG_AddScaleFade
For rocket smokes that hang in place, fade out, and are
removed if the view passes through them.
There are often many of these, so it needs to be simple.
===================
*/
static void CG_AddScaleFade( localEntity_t *le ) {
refEntity_t *re;
float c;
vec3_t delta;
float len;
re = &le->refEntity;
// fade / grow time
c = ( le->endTime - cg.time ) * le->lifeRate;
re->shaderRGBA[3] = 0xff * c * le->color[3];
re->radius = le->radius * ( 1.0 - c ) + 8;
// if the view would be "inside" the sprite, kill the sprite
// so it doesn't add too much overdraw
VectorSubtract( re->origin, cg.refdef.vieworg, delta );
len = VectorLength( delta );
if ( len < le->radius ) {
CG_FreeLocalEntity( le );
return;
}
cgi_R_AddRefEntityToScene( re );
}
/*
=================
CG_AddFallScaleFade
For blood mists that drift down, fade out, and are
removed if the view passes through them.
There are often 100+ of these, so it needs to be simple.
=================
*/
static void CG_AddFallScaleFade( localEntity_t *le ) {
refEntity_t *re;
float c;
vec3_t delta;
float len;
re = &le->refEntity;
// fade time
c = ( le->endTime - cg.time ) * le->lifeRate;
re->shaderRGBA[3] = 0xff * c * le->color[3];
re->origin[2] = le->pos.trBase[2] - ( 1.0 - c ) * le->pos.trDelta[2];
re->radius = le->radius * ( 1.0 - c ) + 16;
// if the view would be "inside" the sprite, kill the sprite
// so it doesn't add too much overdraw
VectorSubtract( re->origin, cg.refdef.vieworg, delta );
len = VectorLength( delta );
if ( len < le->radius ) {
CG_FreeLocalEntity( le );
return;
}
cgi_R_AddRefEntityToScene( re );
}
/*
================
CG_AddExplosion
================
*/
static void CG_AddExplosion( localEntity_t *ex ) {
refEntity_t *ent = &ex->refEntity;
// calculate model frame
if ( ex->lifeRate > 0 ) {
float frac = (cg.time - ex->startTime) * ex->lifeRate;
int f = floor(frac);
if ( f < 0 ) {
f = 0;
}
ent->frame = f + 1;
ent->oldframe = f;
ent->backlerp = 1.0 - ( frac - f );
ent->renderfx |= RF_CAP_FRAMES;
}
// Explosions with zero shaders (using model default shader) don't fade, so
// allow fading when this flag is set.
if ( ex->leFlags & LEF_FADE_RGB )
{
float frac = 1.0f - ((float)( cg.time - ex->startTime )/(float)( ex->endTime - ex->startTime ));
ent->shaderRGBA[0] =
ent->shaderRGBA[1] =
ent->shaderRGBA[2] = frac * 255;
ent->shaderRGBA[3] = 255;
}
// add the entity
cgi_R_AddRefEntityToScene(ent);
// add the dlight
if ( ex->light ) {
float light;
light = (float)( cg.time - ex->startTime ) / ( ex->endTime - ex->startTime );
if ( light < 0.5 ) {
light = 1.0;
} else {
light = 1.0 - ( light - 0.5 ) * 2;
}
light = ex->light * light;
cgi_R_AddLightToScene(ent->origin, light, ex->lightColor[0], ex->lightColor[1], ex->lightColor[2] );
}
}
/*
================
CG_AddSpriteExplosion
================
*/
static void CG_AddSpriteExplosion( localEntity_t *le ) {
refEntity_t re;
float c;
re = le->refEntity;
c = ( le->endTime - cg.time ) / ( float ) ( le->endTime - le->startTime );
if ( c > 1 ) {
c = 1.0; // can happen during connection problems
}
re.shaderRGBA[0] = 0xff;
re.shaderRGBA[1] = 0xff;
re.shaderRGBA[2] = 0xff;
re.shaderRGBA[3] = 0xff;// * c * 0.33;//alpha works now
re.reType = RT_SPRITE;
re.radius = 42 * ( 1.0 - c ) * le->radius + ( 30 * le->radius );
// re.radius = 42 * ( 1.0 - c ) + 30;
cgi_R_AddRefEntityToScene( &re );
// add the dlight
if ( le->light ) {
float light;
light = (float)( cg.time - le->startTime ) / ( le->endTime - le->startTime );
if ( light < 0.5 ) {
light = 1.0;
} else {
light = 1.0 - ( light - 0.5 ) * 2;
}
light = le->light * light;
cgi_R_AddLightToScene(re.origin, light, le->lightColor[0], le->lightColor[1], le->lightColor[2] );
}
}
/*
================
CG_AddLocalLight
================
*/
static void CG_AddLocalLight( localEntity_t *le )
{
// There should be a light if this is being used, but hey...
if ( le->light )
{
float light;
light = (float)( cg.time - le->startTime ) / ( le->endTime - le->startTime );
if ( light < 0.5 )
{
light = 1.0;
}
else
{
light = 1.0 - ( light - 0.5 ) * 2;
}
light = le->light * light;
cgi_R_AddLightToScene( le->refEntity.origin, light, le->lightColor[0], le->lightColor[1], le->lightColor[2] );
}
}
//==============================================================================
/*
===================
CG_AddLocalEntities
===================
*/
void CG_AddLocalEntities( void )
{
localEntity_t *le, *next;
// walk the list backwards, so any new local entities generated
// (trails, marks, etc) will be present this frame
le = cg_activeLocalEntities.prev;
for ( ; le != &cg_activeLocalEntities ; le = next ) {
// grab next now, so if the local entity is freed we
// still have it
next = le->prev;
if ( cg.time >= le->endTime ) {
CG_FreeLocalEntity( le );
continue;
}
switch ( le->leType ) {
default:
CG_Error( "Bad leType: %i", le->leType );
break;
case LE_MARK:
break;
case LE_SPRITE_EXPLOSION:
CG_AddSpriteExplosion( le );
break;
case LE_EXPLOSION:
CG_AddExplosion( le );
break;
case LE_FRAGMENT:
CG_AddFragment( le );
break;
case LE_PUFF:
CG_AddPuff( le );
break;
case LE_FADE_RGB: // teleporters, railtrails
CG_AddFadeRGB( le );
break;
case LE_FALL_SCALE_FADE: // gib blood trails
CG_AddFallScaleFade( le );
break;
case LE_SCALE_FADE: // rocket trails
CG_AddScaleFade( le );
break;
case LE_LIGHT:
CG_AddLocalLight( le );
break;
}
}
}
| 22.584746 | 112 | 0.615084 | [
"model"
] |
73bb9f373e1e1d3f2fdeccdac8606fb4dca88f1b | 72,611 | cc | C++ | wrappers/7.0.0/vtkScalarBarActorWrap.cc | axkibe/node-vtk | 900ad7b5500f672519da5aa24c99aa5a96466ef3 | [
"BSD-3-Clause"
] | 6 | 2016-02-03T12:48:36.000Z | 2020-09-16T15:07:51.000Z | wrappers/7.0.0/vtkScalarBarActorWrap.cc | axkibe/node-vtk | 900ad7b5500f672519da5aa24c99aa5a96466ef3 | [
"BSD-3-Clause"
] | 4 | 2016-02-13T01:30:43.000Z | 2020-03-30T16:59:32.000Z | wrappers/7.0.0/vtkScalarBarActorWrap.cc | axkibe/node-vtk | 900ad7b5500f672519da5aa24c99aa5a96466ef3 | [
"BSD-3-Clause"
] | null | null | null | /* this file has been autogenerated by vtkNodeJsWrap */
/* editing this might proof futile */
#define VTK_WRAPPING_CXX
#define VTK_STREAMS_FWD_ONLY
#include <nan.h>
#include "vtkActor2DWrap.h"
#include "vtkScalarBarActorWrap.h"
#include "vtkObjectWrap.h"
#include "vtkViewportWrap.h"
#include "vtkWindowWrap.h"
#include "vtkScalarsToColorsWrap.h"
#include "vtkTextPropertyWrap.h"
#include "vtkPropWrap.h"
#include "vtkTexturedActor2DWrap.h"
#include "vtkProperty2DWrap.h"
#include "../../plus/plus.h"
using namespace v8;
extern Nan::Persistent<v8::Object> vtkNodeJsNoWrap;
Nan::Persistent<v8::FunctionTemplate> VtkScalarBarActorWrap::ptpl;
VtkScalarBarActorWrap::VtkScalarBarActorWrap()
{ }
VtkScalarBarActorWrap::VtkScalarBarActorWrap(vtkSmartPointer<vtkScalarBarActor> _native)
{ native = _native; }
VtkScalarBarActorWrap::~VtkScalarBarActorWrap()
{ }
void VtkScalarBarActorWrap::Init(v8::Local<v8::Object> exports)
{
Nan::SetAccessor(exports, Nan::New("vtkScalarBarActor").ToLocalChecked(), ConstructorGetter);
Nan::SetAccessor(exports, Nan::New("ScalarBarActor").ToLocalChecked(), ConstructorGetter);
}
void VtkScalarBarActorWrap::ConstructorGetter(
v8::Local<v8::String> property,
const Nan::PropertyCallbackInfo<v8::Value>& info)
{
InitPtpl();
info.GetReturnValue().Set(Nan::New(ptpl)->GetFunction());
}
void VtkScalarBarActorWrap::InitPtpl()
{
if (!ptpl.IsEmpty()) return;
v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
VtkActor2DWrap::InitPtpl( );
tpl->Inherit(Nan::New<FunctionTemplate>(VtkActor2DWrap::ptpl));
tpl->SetClassName(Nan::New("VtkScalarBarActorWrap").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
Nan::SetPrototypeMethod(tpl, "DrawAnnotationsOff", DrawAnnotationsOff);
Nan::SetPrototypeMethod(tpl, "drawAnnotationsOff", DrawAnnotationsOff);
Nan::SetPrototypeMethod(tpl, "DrawAnnotationsOn", DrawAnnotationsOn);
Nan::SetPrototypeMethod(tpl, "drawAnnotationsOn", DrawAnnotationsOn);
Nan::SetPrototypeMethod(tpl, "DrawBackgroundOff", DrawBackgroundOff);
Nan::SetPrototypeMethod(tpl, "drawBackgroundOff", DrawBackgroundOff);
Nan::SetPrototypeMethod(tpl, "DrawBackgroundOn", DrawBackgroundOn);
Nan::SetPrototypeMethod(tpl, "drawBackgroundOn", DrawBackgroundOn);
Nan::SetPrototypeMethod(tpl, "DrawColorBarOff", DrawColorBarOff);
Nan::SetPrototypeMethod(tpl, "drawColorBarOff", DrawColorBarOff);
Nan::SetPrototypeMethod(tpl, "DrawColorBarOn", DrawColorBarOn);
Nan::SetPrototypeMethod(tpl, "drawColorBarOn", DrawColorBarOn);
Nan::SetPrototypeMethod(tpl, "DrawFrameOff", DrawFrameOff);
Nan::SetPrototypeMethod(tpl, "drawFrameOff", DrawFrameOff);
Nan::SetPrototypeMethod(tpl, "DrawFrameOn", DrawFrameOn);
Nan::SetPrototypeMethod(tpl, "drawFrameOn", DrawFrameOn);
Nan::SetPrototypeMethod(tpl, "DrawNanAnnotationOff", DrawNanAnnotationOff);
Nan::SetPrototypeMethod(tpl, "drawNanAnnotationOff", DrawNanAnnotationOff);
Nan::SetPrototypeMethod(tpl, "DrawNanAnnotationOn", DrawNanAnnotationOn);
Nan::SetPrototypeMethod(tpl, "drawNanAnnotationOn", DrawNanAnnotationOn);
Nan::SetPrototypeMethod(tpl, "DrawTickLabelsOff", DrawTickLabelsOff);
Nan::SetPrototypeMethod(tpl, "drawTickLabelsOff", DrawTickLabelsOff);
Nan::SetPrototypeMethod(tpl, "DrawTickLabelsOn", DrawTickLabelsOn);
Nan::SetPrototypeMethod(tpl, "drawTickLabelsOn", DrawTickLabelsOn);
Nan::SetPrototypeMethod(tpl, "FixedAnnotationLeaderLineColorOff", FixedAnnotationLeaderLineColorOff);
Nan::SetPrototypeMethod(tpl, "fixedAnnotationLeaderLineColorOff", FixedAnnotationLeaderLineColorOff);
Nan::SetPrototypeMethod(tpl, "FixedAnnotationLeaderLineColorOn", FixedAnnotationLeaderLineColorOn);
Nan::SetPrototypeMethod(tpl, "fixedAnnotationLeaderLineColorOn", FixedAnnotationLeaderLineColorOn);
Nan::SetPrototypeMethod(tpl, "GetAnnotationLeaderPadding", GetAnnotationLeaderPadding);
Nan::SetPrototypeMethod(tpl, "getAnnotationLeaderPadding", GetAnnotationLeaderPadding);
Nan::SetPrototypeMethod(tpl, "GetAnnotationTextScaling", GetAnnotationTextScaling);
Nan::SetPrototypeMethod(tpl, "getAnnotationTextScaling", GetAnnotationTextScaling);
Nan::SetPrototypeMethod(tpl, "GetBackgroundProperty", GetBackgroundProperty);
Nan::SetPrototypeMethod(tpl, "getBackgroundProperty", GetBackgroundProperty);
Nan::SetPrototypeMethod(tpl, "GetBarRatio", GetBarRatio);
Nan::SetPrototypeMethod(tpl, "getBarRatio", GetBarRatio);
Nan::SetPrototypeMethod(tpl, "GetBarRatioMaxValue", GetBarRatioMaxValue);
Nan::SetPrototypeMethod(tpl, "getBarRatioMaxValue", GetBarRatioMaxValue);
Nan::SetPrototypeMethod(tpl, "GetBarRatioMinValue", GetBarRatioMinValue);
Nan::SetPrototypeMethod(tpl, "getBarRatioMinValue", GetBarRatioMinValue);
Nan::SetPrototypeMethod(tpl, "GetClassName", GetClassName);
Nan::SetPrototypeMethod(tpl, "getClassName", GetClassName);
Nan::SetPrototypeMethod(tpl, "GetComponentTitle", GetComponentTitle);
Nan::SetPrototypeMethod(tpl, "getComponentTitle", GetComponentTitle);
Nan::SetPrototypeMethod(tpl, "GetDrawAnnotations", GetDrawAnnotations);
Nan::SetPrototypeMethod(tpl, "getDrawAnnotations", GetDrawAnnotations);
Nan::SetPrototypeMethod(tpl, "GetDrawBackground", GetDrawBackground);
Nan::SetPrototypeMethod(tpl, "getDrawBackground", GetDrawBackground);
Nan::SetPrototypeMethod(tpl, "GetDrawColorBar", GetDrawColorBar);
Nan::SetPrototypeMethod(tpl, "getDrawColorBar", GetDrawColorBar);
Nan::SetPrototypeMethod(tpl, "GetDrawFrame", GetDrawFrame);
Nan::SetPrototypeMethod(tpl, "getDrawFrame", GetDrawFrame);
Nan::SetPrototypeMethod(tpl, "GetDrawNanAnnotation", GetDrawNanAnnotation);
Nan::SetPrototypeMethod(tpl, "getDrawNanAnnotation", GetDrawNanAnnotation);
Nan::SetPrototypeMethod(tpl, "GetDrawTickLabels", GetDrawTickLabels);
Nan::SetPrototypeMethod(tpl, "getDrawTickLabels", GetDrawTickLabels);
Nan::SetPrototypeMethod(tpl, "GetFixedAnnotationLeaderLineColor", GetFixedAnnotationLeaderLineColor);
Nan::SetPrototypeMethod(tpl, "getFixedAnnotationLeaderLineColor", GetFixedAnnotationLeaderLineColor);
Nan::SetPrototypeMethod(tpl, "GetFrameProperty", GetFrameProperty);
Nan::SetPrototypeMethod(tpl, "getFrameProperty", GetFrameProperty);
Nan::SetPrototypeMethod(tpl, "GetLabelFormat", GetLabelFormat);
Nan::SetPrototypeMethod(tpl, "getLabelFormat", GetLabelFormat);
Nan::SetPrototypeMethod(tpl, "GetLabelTextProperty", GetLabelTextProperty);
Nan::SetPrototypeMethod(tpl, "getLabelTextProperty", GetLabelTextProperty);
Nan::SetPrototypeMethod(tpl, "GetLookupTable", GetLookupTable);
Nan::SetPrototypeMethod(tpl, "getLookupTable", GetLookupTable);
Nan::SetPrototypeMethod(tpl, "GetMaximumHeightInPixels", GetMaximumHeightInPixels);
Nan::SetPrototypeMethod(tpl, "getMaximumHeightInPixels", GetMaximumHeightInPixels);
Nan::SetPrototypeMethod(tpl, "GetMaximumNumberOfColors", GetMaximumNumberOfColors);
Nan::SetPrototypeMethod(tpl, "getMaximumNumberOfColors", GetMaximumNumberOfColors);
Nan::SetPrototypeMethod(tpl, "GetMaximumNumberOfColorsMaxValue", GetMaximumNumberOfColorsMaxValue);
Nan::SetPrototypeMethod(tpl, "getMaximumNumberOfColorsMaxValue", GetMaximumNumberOfColorsMaxValue);
Nan::SetPrototypeMethod(tpl, "GetMaximumNumberOfColorsMinValue", GetMaximumNumberOfColorsMinValue);
Nan::SetPrototypeMethod(tpl, "getMaximumNumberOfColorsMinValue", GetMaximumNumberOfColorsMinValue);
Nan::SetPrototypeMethod(tpl, "GetMaximumWidthInPixels", GetMaximumWidthInPixels);
Nan::SetPrototypeMethod(tpl, "getMaximumWidthInPixels", GetMaximumWidthInPixels);
Nan::SetPrototypeMethod(tpl, "GetNanAnnotation", GetNanAnnotation);
Nan::SetPrototypeMethod(tpl, "getNanAnnotation", GetNanAnnotation);
Nan::SetPrototypeMethod(tpl, "GetNumberOfLabels", GetNumberOfLabels);
Nan::SetPrototypeMethod(tpl, "getNumberOfLabels", GetNumberOfLabels);
Nan::SetPrototypeMethod(tpl, "GetNumberOfLabelsMaxValue", GetNumberOfLabelsMaxValue);
Nan::SetPrototypeMethod(tpl, "getNumberOfLabelsMaxValue", GetNumberOfLabelsMaxValue);
Nan::SetPrototypeMethod(tpl, "GetNumberOfLabelsMinValue", GetNumberOfLabelsMinValue);
Nan::SetPrototypeMethod(tpl, "getNumberOfLabelsMinValue", GetNumberOfLabelsMinValue);
Nan::SetPrototypeMethod(tpl, "GetOrientation", GetOrientation);
Nan::SetPrototypeMethod(tpl, "getOrientation", GetOrientation);
Nan::SetPrototypeMethod(tpl, "GetOrientationMaxValue", GetOrientationMaxValue);
Nan::SetPrototypeMethod(tpl, "getOrientationMaxValue", GetOrientationMaxValue);
Nan::SetPrototypeMethod(tpl, "GetOrientationMinValue", GetOrientationMinValue);
Nan::SetPrototypeMethod(tpl, "getOrientationMinValue", GetOrientationMinValue);
Nan::SetPrototypeMethod(tpl, "GetScalarBarRect", GetScalarBarRect);
Nan::SetPrototypeMethod(tpl, "getScalarBarRect", GetScalarBarRect);
Nan::SetPrototypeMethod(tpl, "GetTextPad", GetTextPad);
Nan::SetPrototypeMethod(tpl, "getTextPad", GetTextPad);
Nan::SetPrototypeMethod(tpl, "GetTextPosition", GetTextPosition);
Nan::SetPrototypeMethod(tpl, "getTextPosition", GetTextPosition);
Nan::SetPrototypeMethod(tpl, "GetTextPositionMaxValue", GetTextPositionMaxValue);
Nan::SetPrototypeMethod(tpl, "getTextPositionMaxValue", GetTextPositionMaxValue);
Nan::SetPrototypeMethod(tpl, "GetTextPositionMinValue", GetTextPositionMinValue);
Nan::SetPrototypeMethod(tpl, "getTextPositionMinValue", GetTextPositionMinValue);
Nan::SetPrototypeMethod(tpl, "GetTextureActor", GetTextureActor);
Nan::SetPrototypeMethod(tpl, "getTextureActor", GetTextureActor);
Nan::SetPrototypeMethod(tpl, "GetTextureGridWidth", GetTextureGridWidth);
Nan::SetPrototypeMethod(tpl, "getTextureGridWidth", GetTextureGridWidth);
Nan::SetPrototypeMethod(tpl, "GetTitle", GetTitle);
Nan::SetPrototypeMethod(tpl, "getTitle", GetTitle);
Nan::SetPrototypeMethod(tpl, "GetTitleRatio", GetTitleRatio);
Nan::SetPrototypeMethod(tpl, "getTitleRatio", GetTitleRatio);
Nan::SetPrototypeMethod(tpl, "GetTitleRatioMaxValue", GetTitleRatioMaxValue);
Nan::SetPrototypeMethod(tpl, "getTitleRatioMaxValue", GetTitleRatioMaxValue);
Nan::SetPrototypeMethod(tpl, "GetTitleRatioMinValue", GetTitleRatioMinValue);
Nan::SetPrototypeMethod(tpl, "getTitleRatioMinValue", GetTitleRatioMinValue);
Nan::SetPrototypeMethod(tpl, "GetTitleTextProperty", GetTitleTextProperty);
Nan::SetPrototypeMethod(tpl, "getTitleTextProperty", GetTitleTextProperty);
Nan::SetPrototypeMethod(tpl, "GetUseOpacity", GetUseOpacity);
Nan::SetPrototypeMethod(tpl, "getUseOpacity", GetUseOpacity);
Nan::SetPrototypeMethod(tpl, "GetVerticalTitleSeparation", GetVerticalTitleSeparation);
Nan::SetPrototypeMethod(tpl, "getVerticalTitleSeparation", GetVerticalTitleSeparation);
Nan::SetPrototypeMethod(tpl, "HasTranslucentPolygonalGeometry", HasTranslucentPolygonalGeometry);
Nan::SetPrototypeMethod(tpl, "hasTranslucentPolygonalGeometry", HasTranslucentPolygonalGeometry);
Nan::SetPrototypeMethod(tpl, "IsA", IsA);
Nan::SetPrototypeMethod(tpl, "isA", IsA);
Nan::SetPrototypeMethod(tpl, "NewInstance", NewInstance);
Nan::SetPrototypeMethod(tpl, "newInstance", NewInstance);
Nan::SetPrototypeMethod(tpl, "ReleaseGraphicsResources", ReleaseGraphicsResources);
Nan::SetPrototypeMethod(tpl, "releaseGraphicsResources", ReleaseGraphicsResources);
Nan::SetPrototypeMethod(tpl, "RenderOpaqueGeometry", RenderOpaqueGeometry);
Nan::SetPrototypeMethod(tpl, "renderOpaqueGeometry", RenderOpaqueGeometry);
Nan::SetPrototypeMethod(tpl, "RenderOverlay", RenderOverlay);
Nan::SetPrototypeMethod(tpl, "renderOverlay", RenderOverlay);
Nan::SetPrototypeMethod(tpl, "RenderTranslucentPolygonalGeometry", RenderTranslucentPolygonalGeometry);
Nan::SetPrototypeMethod(tpl, "renderTranslucentPolygonalGeometry", RenderTranslucentPolygonalGeometry);
Nan::SetPrototypeMethod(tpl, "SafeDownCast", SafeDownCast);
Nan::SetPrototypeMethod(tpl, "safeDownCast", SafeDownCast);
Nan::SetPrototypeMethod(tpl, "SetAnnotationLeaderPadding", SetAnnotationLeaderPadding);
Nan::SetPrototypeMethod(tpl, "setAnnotationLeaderPadding", SetAnnotationLeaderPadding);
Nan::SetPrototypeMethod(tpl, "SetAnnotationTextScaling", SetAnnotationTextScaling);
Nan::SetPrototypeMethod(tpl, "setAnnotationTextScaling", SetAnnotationTextScaling);
Nan::SetPrototypeMethod(tpl, "SetBackgroundProperty", SetBackgroundProperty);
Nan::SetPrototypeMethod(tpl, "setBackgroundProperty", SetBackgroundProperty);
Nan::SetPrototypeMethod(tpl, "SetBarRatio", SetBarRatio);
Nan::SetPrototypeMethod(tpl, "setBarRatio", SetBarRatio);
Nan::SetPrototypeMethod(tpl, "SetComponentTitle", SetComponentTitle);
Nan::SetPrototypeMethod(tpl, "setComponentTitle", SetComponentTitle);
Nan::SetPrototypeMethod(tpl, "SetDrawAnnotations", SetDrawAnnotations);
Nan::SetPrototypeMethod(tpl, "setDrawAnnotations", SetDrawAnnotations);
Nan::SetPrototypeMethod(tpl, "SetDrawBackground", SetDrawBackground);
Nan::SetPrototypeMethod(tpl, "setDrawBackground", SetDrawBackground);
Nan::SetPrototypeMethod(tpl, "SetDrawColorBar", SetDrawColorBar);
Nan::SetPrototypeMethod(tpl, "setDrawColorBar", SetDrawColorBar);
Nan::SetPrototypeMethod(tpl, "SetDrawFrame", SetDrawFrame);
Nan::SetPrototypeMethod(tpl, "setDrawFrame", SetDrawFrame);
Nan::SetPrototypeMethod(tpl, "SetDrawNanAnnotation", SetDrawNanAnnotation);
Nan::SetPrototypeMethod(tpl, "setDrawNanAnnotation", SetDrawNanAnnotation);
Nan::SetPrototypeMethod(tpl, "SetDrawTickLabels", SetDrawTickLabels);
Nan::SetPrototypeMethod(tpl, "setDrawTickLabels", SetDrawTickLabels);
Nan::SetPrototypeMethod(tpl, "SetFixedAnnotationLeaderLineColor", SetFixedAnnotationLeaderLineColor);
Nan::SetPrototypeMethod(tpl, "setFixedAnnotationLeaderLineColor", SetFixedAnnotationLeaderLineColor);
Nan::SetPrototypeMethod(tpl, "SetFrameProperty", SetFrameProperty);
Nan::SetPrototypeMethod(tpl, "setFrameProperty", SetFrameProperty);
Nan::SetPrototypeMethod(tpl, "SetLabelFormat", SetLabelFormat);
Nan::SetPrototypeMethod(tpl, "setLabelFormat", SetLabelFormat);
Nan::SetPrototypeMethod(tpl, "SetLabelTextProperty", SetLabelTextProperty);
Nan::SetPrototypeMethod(tpl, "setLabelTextProperty", SetLabelTextProperty);
Nan::SetPrototypeMethod(tpl, "SetLookupTable", SetLookupTable);
Nan::SetPrototypeMethod(tpl, "setLookupTable", SetLookupTable);
Nan::SetPrototypeMethod(tpl, "SetMaximumHeightInPixels", SetMaximumHeightInPixels);
Nan::SetPrototypeMethod(tpl, "setMaximumHeightInPixels", SetMaximumHeightInPixels);
Nan::SetPrototypeMethod(tpl, "SetMaximumNumberOfColors", SetMaximumNumberOfColors);
Nan::SetPrototypeMethod(tpl, "setMaximumNumberOfColors", SetMaximumNumberOfColors);
Nan::SetPrototypeMethod(tpl, "SetMaximumWidthInPixels", SetMaximumWidthInPixels);
Nan::SetPrototypeMethod(tpl, "setMaximumWidthInPixels", SetMaximumWidthInPixels);
Nan::SetPrototypeMethod(tpl, "SetNanAnnotation", SetNanAnnotation);
Nan::SetPrototypeMethod(tpl, "setNanAnnotation", SetNanAnnotation);
Nan::SetPrototypeMethod(tpl, "SetNumberOfLabels", SetNumberOfLabels);
Nan::SetPrototypeMethod(tpl, "setNumberOfLabels", SetNumberOfLabels);
Nan::SetPrototypeMethod(tpl, "SetOrientation", SetOrientation);
Nan::SetPrototypeMethod(tpl, "setOrientation", SetOrientation);
Nan::SetPrototypeMethod(tpl, "SetOrientationToHorizontal", SetOrientationToHorizontal);
Nan::SetPrototypeMethod(tpl, "setOrientationToHorizontal", SetOrientationToHorizontal);
Nan::SetPrototypeMethod(tpl, "SetOrientationToVertical", SetOrientationToVertical);
Nan::SetPrototypeMethod(tpl, "setOrientationToVertical", SetOrientationToVertical);
Nan::SetPrototypeMethod(tpl, "SetTextPad", SetTextPad);
Nan::SetPrototypeMethod(tpl, "setTextPad", SetTextPad);
Nan::SetPrototypeMethod(tpl, "SetTextPosition", SetTextPosition);
Nan::SetPrototypeMethod(tpl, "setTextPosition", SetTextPosition);
Nan::SetPrototypeMethod(tpl, "SetTextPositionToPrecedeScalarBar", SetTextPositionToPrecedeScalarBar);
Nan::SetPrototypeMethod(tpl, "setTextPositionToPrecedeScalarBar", SetTextPositionToPrecedeScalarBar);
Nan::SetPrototypeMethod(tpl, "SetTextPositionToSucceedScalarBar", SetTextPositionToSucceedScalarBar);
Nan::SetPrototypeMethod(tpl, "setTextPositionToSucceedScalarBar", SetTextPositionToSucceedScalarBar);
Nan::SetPrototypeMethod(tpl, "SetTextureGridWidth", SetTextureGridWidth);
Nan::SetPrototypeMethod(tpl, "setTextureGridWidth", SetTextureGridWidth);
Nan::SetPrototypeMethod(tpl, "SetTitle", SetTitle);
Nan::SetPrototypeMethod(tpl, "setTitle", SetTitle);
Nan::SetPrototypeMethod(tpl, "SetTitleRatio", SetTitleRatio);
Nan::SetPrototypeMethod(tpl, "setTitleRatio", SetTitleRatio);
Nan::SetPrototypeMethod(tpl, "SetTitleTextProperty", SetTitleTextProperty);
Nan::SetPrototypeMethod(tpl, "setTitleTextProperty", SetTitleTextProperty);
Nan::SetPrototypeMethod(tpl, "SetUseOpacity", SetUseOpacity);
Nan::SetPrototypeMethod(tpl, "setUseOpacity", SetUseOpacity);
Nan::SetPrototypeMethod(tpl, "SetVerticalTitleSeparation", SetVerticalTitleSeparation);
Nan::SetPrototypeMethod(tpl, "setVerticalTitleSeparation", SetVerticalTitleSeparation);
Nan::SetPrototypeMethod(tpl, "ShallowCopy", ShallowCopy);
Nan::SetPrototypeMethod(tpl, "shallowCopy", ShallowCopy);
Nan::SetPrototypeMethod(tpl, "UseOpacityOff", UseOpacityOff);
Nan::SetPrototypeMethod(tpl, "useOpacityOff", UseOpacityOff);
Nan::SetPrototypeMethod(tpl, "UseOpacityOn", UseOpacityOn);
Nan::SetPrototypeMethod(tpl, "useOpacityOn", UseOpacityOn);
#ifdef VTK_NODE_PLUS_VTKSCALARBARACTORWRAP_INITPTPL
VTK_NODE_PLUS_VTKSCALARBARACTORWRAP_INITPTPL
#endif
ptpl.Reset( tpl );
}
void VtkScalarBarActorWrap::New(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
if(!info.IsConstructCall())
{
Nan::ThrowError("Constructor not called in a construct call.");
return;
}
if(info.Length() == 0)
{
vtkSmartPointer<vtkScalarBarActor> native = vtkSmartPointer<vtkScalarBarActor>::New();
VtkScalarBarActorWrap* obj = new VtkScalarBarActorWrap(native);
obj->Wrap(info.This());
}
else
{
if(info[0]->ToObject() != vtkNodeJsNoWrap )
{
Nan::ThrowError("Parameter Error");
return;
}
}
info.GetReturnValue().Set(info.This());
}
void VtkScalarBarActorWrap::DrawAnnotationsOff(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->DrawAnnotationsOff();
}
void VtkScalarBarActorWrap::DrawAnnotationsOn(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->DrawAnnotationsOn();
}
void VtkScalarBarActorWrap::DrawBackgroundOff(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->DrawBackgroundOff();
}
void VtkScalarBarActorWrap::DrawBackgroundOn(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->DrawBackgroundOn();
}
void VtkScalarBarActorWrap::DrawColorBarOff(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->DrawColorBarOff();
}
void VtkScalarBarActorWrap::DrawColorBarOn(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->DrawColorBarOn();
}
void VtkScalarBarActorWrap::DrawFrameOff(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->DrawFrameOff();
}
void VtkScalarBarActorWrap::DrawFrameOn(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->DrawFrameOn();
}
void VtkScalarBarActorWrap::DrawNanAnnotationOff(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->DrawNanAnnotationOff();
}
void VtkScalarBarActorWrap::DrawNanAnnotationOn(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->DrawNanAnnotationOn();
}
void VtkScalarBarActorWrap::DrawTickLabelsOff(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->DrawTickLabelsOff();
}
void VtkScalarBarActorWrap::DrawTickLabelsOn(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->DrawTickLabelsOn();
}
void VtkScalarBarActorWrap::FixedAnnotationLeaderLineColorOff(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->FixedAnnotationLeaderLineColorOff();
}
void VtkScalarBarActorWrap::FixedAnnotationLeaderLineColorOn(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->FixedAnnotationLeaderLineColorOn();
}
void VtkScalarBarActorWrap::GetAnnotationLeaderPadding(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
double r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetAnnotationLeaderPadding();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkScalarBarActorWrap::GetAnnotationTextScaling(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetAnnotationTextScaling();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkScalarBarActorWrap::GetBackgroundProperty(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
vtkProperty2D * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetBackgroundProperty();
VtkProperty2DWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkProperty2DWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkProperty2DWrap *w = new VtkProperty2DWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
}
void VtkScalarBarActorWrap::GetBarRatio(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
double r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetBarRatio();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkScalarBarActorWrap::GetBarRatioMaxValue(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
double r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetBarRatioMaxValue();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkScalarBarActorWrap::GetBarRatioMinValue(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
double r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetBarRatioMinValue();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkScalarBarActorWrap::GetClassName(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
char const * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetClassName();
info.GetReturnValue().Set(Nan::New(r).ToLocalChecked());
}
void VtkScalarBarActorWrap::GetComponentTitle(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
char const * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetComponentTitle();
info.GetReturnValue().Set(Nan::New(r).ToLocalChecked());
}
void VtkScalarBarActorWrap::GetDrawAnnotations(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetDrawAnnotations();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkScalarBarActorWrap::GetDrawBackground(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetDrawBackground();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkScalarBarActorWrap::GetDrawColorBar(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetDrawColorBar();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkScalarBarActorWrap::GetDrawFrame(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetDrawFrame();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkScalarBarActorWrap::GetDrawNanAnnotation(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetDrawNanAnnotation();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkScalarBarActorWrap::GetDrawTickLabels(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetDrawTickLabels();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkScalarBarActorWrap::GetFixedAnnotationLeaderLineColor(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetFixedAnnotationLeaderLineColor();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkScalarBarActorWrap::GetFrameProperty(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
vtkProperty2D * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetFrameProperty();
VtkProperty2DWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkProperty2DWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkProperty2DWrap *w = new VtkProperty2DWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
}
void VtkScalarBarActorWrap::GetLabelFormat(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
char const * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetLabelFormat();
info.GetReturnValue().Set(Nan::New(r).ToLocalChecked());
}
void VtkScalarBarActorWrap::GetLabelTextProperty(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
vtkTextProperty * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetLabelTextProperty();
VtkTextPropertyWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkTextPropertyWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkTextPropertyWrap *w = new VtkTextPropertyWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
}
void VtkScalarBarActorWrap::GetLookupTable(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
vtkScalarsToColors * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetLookupTable();
VtkScalarsToColorsWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkScalarsToColorsWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkScalarsToColorsWrap *w = new VtkScalarsToColorsWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
}
void VtkScalarBarActorWrap::GetMaximumHeightInPixels(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetMaximumHeightInPixels();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkScalarBarActorWrap::GetMaximumNumberOfColors(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetMaximumNumberOfColors();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkScalarBarActorWrap::GetMaximumNumberOfColorsMaxValue(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetMaximumNumberOfColorsMaxValue();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkScalarBarActorWrap::GetMaximumNumberOfColorsMinValue(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetMaximumNumberOfColorsMinValue();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkScalarBarActorWrap::GetMaximumWidthInPixels(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetMaximumWidthInPixels();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkScalarBarActorWrap::GetNanAnnotation(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
char const * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetNanAnnotation();
info.GetReturnValue().Set(Nan::New(r).ToLocalChecked());
}
void VtkScalarBarActorWrap::GetNumberOfLabels(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetNumberOfLabels();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkScalarBarActorWrap::GetNumberOfLabelsMaxValue(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetNumberOfLabelsMaxValue();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkScalarBarActorWrap::GetNumberOfLabelsMinValue(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetNumberOfLabelsMinValue();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkScalarBarActorWrap::GetOrientation(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetOrientation();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkScalarBarActorWrap::GetOrientationMaxValue(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetOrientationMaxValue();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkScalarBarActorWrap::GetOrientationMinValue(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetOrientationMinValue();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkScalarBarActorWrap::GetScalarBarRect(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
size_t i;
if(info.Length() > 0 && info[0]->IsInt32Array())
{
v8::Local<v8::Int32Array>a0(v8::Local<v8::Int32Array>::Cast(info[0]->ToObject()));
if( a0->Length() < 4 )
{
Nan::ThrowError("Array too short.");
return;
}
if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkViewportWrap::ptpl))->HasInstance(info[1]))
{
VtkViewportWrap *a1 = ObjectWrap::Unwrap<VtkViewportWrap>(info[1]->ToObject());
if(info.Length() != 2)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->GetScalarBarRect(
(int *)(a0->Buffer()->GetContents().Data()),
(vtkViewport *) a1->native.GetPointer()
);
return;
}
}
else if(info.Length() > 0 && info[0]->IsArray())
{
v8::Local<v8::Array>a0(v8::Local<v8::Array>::Cast(info[0]->ToObject()));
int b0[4];
if( a0->Length() < 4 )
{
Nan::ThrowError("Array too short.");
return;
}
for( i = 0; i < 4; i++ )
{
if( !a0->Get(i)->IsInt32() )
{
Nan::ThrowError("Array contents invalid.");
return;
}
b0[i] = a0->Get(i)->Int32Value();
}
if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkViewportWrap::ptpl))->HasInstance(info[1]))
{
VtkViewportWrap *a1 = ObjectWrap::Unwrap<VtkViewportWrap>(info[1]->ToObject());
if(info.Length() != 2)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->GetScalarBarRect(
b0,
(vtkViewport *) a1->native.GetPointer()
);
return;
}
}
Nan::ThrowError("Parameter mismatch");
}
void VtkScalarBarActorWrap::GetTextPad(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetTextPad();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkScalarBarActorWrap::GetTextPosition(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetTextPosition();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkScalarBarActorWrap::GetTextPositionMaxValue(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetTextPositionMaxValue();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkScalarBarActorWrap::GetTextPositionMinValue(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetTextPositionMinValue();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkScalarBarActorWrap::GetTextureActor(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
vtkTexturedActor2D * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetTextureActor();
VtkTexturedActor2DWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkTexturedActor2DWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkTexturedActor2DWrap *w = new VtkTexturedActor2DWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
}
void VtkScalarBarActorWrap::GetTextureGridWidth(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
double r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetTextureGridWidth();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkScalarBarActorWrap::GetTitle(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
char const * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetTitle();
info.GetReturnValue().Set(Nan::New(r).ToLocalChecked());
}
void VtkScalarBarActorWrap::GetTitleRatio(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
double r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetTitleRatio();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkScalarBarActorWrap::GetTitleRatioMaxValue(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
double r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetTitleRatioMaxValue();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkScalarBarActorWrap::GetTitleRatioMinValue(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
double r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetTitleRatioMinValue();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkScalarBarActorWrap::GetTitleTextProperty(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
vtkTextProperty * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetTitleTextProperty();
VtkTextPropertyWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkTextPropertyWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkTextPropertyWrap *w = new VtkTextPropertyWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
}
void VtkScalarBarActorWrap::GetUseOpacity(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetUseOpacity();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkScalarBarActorWrap::GetVerticalTitleSeparation(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetVerticalTitleSeparation();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkScalarBarActorWrap::HasTranslucentPolygonalGeometry(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->HasTranslucentPolygonalGeometry();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkScalarBarActorWrap::IsA(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsString())
{
Nan::Utf8String a0(info[0]);
int r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->IsA(
*a0
);
info.GetReturnValue().Set(Nan::New(r));
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkScalarBarActorWrap::NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
vtkScalarBarActor * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->NewInstance();
VtkScalarBarActorWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkScalarBarActorWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkScalarBarActorWrap *w = new VtkScalarBarActorWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
}
void VtkScalarBarActorWrap::ReleaseGraphicsResources(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkWindowWrap::ptpl))->HasInstance(info[0]))
{
VtkWindowWrap *a0 = ObjectWrap::Unwrap<VtkWindowWrap>(info[0]->ToObject());
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->ReleaseGraphicsResources(
(vtkWindow *) a0->native.GetPointer()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkScalarBarActorWrap::RenderOpaqueGeometry(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkViewportWrap::ptpl))->HasInstance(info[0]))
{
VtkViewportWrap *a0 = ObjectWrap::Unwrap<VtkViewportWrap>(info[0]->ToObject());
int r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->RenderOpaqueGeometry(
(vtkViewport *) a0->native.GetPointer()
);
info.GetReturnValue().Set(Nan::New(r));
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkScalarBarActorWrap::RenderOverlay(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkViewportWrap::ptpl))->HasInstance(info[0]))
{
VtkViewportWrap *a0 = ObjectWrap::Unwrap<VtkViewportWrap>(info[0]->ToObject());
int r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->RenderOverlay(
(vtkViewport *) a0->native.GetPointer()
);
info.GetReturnValue().Set(Nan::New(r));
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkScalarBarActorWrap::RenderTranslucentPolygonalGeometry(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkViewportWrap::ptpl))->HasInstance(info[0]))
{
VtkViewportWrap *a0 = ObjectWrap::Unwrap<VtkViewportWrap>(info[0]->ToObject());
int r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->RenderTranslucentPolygonalGeometry(
(vtkViewport *) a0->native.GetPointer()
);
info.GetReturnValue().Set(Nan::New(r));
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkScalarBarActorWrap::SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkObjectWrap::ptpl))->HasInstance(info[0]))
{
VtkObjectWrap *a0 = ObjectWrap::Unwrap<VtkObjectWrap>(info[0]->ToObject());
vtkScalarBarActor * r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->SafeDownCast(
(vtkObject *) a0->native.GetPointer()
);
VtkScalarBarActorWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkScalarBarActorWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkScalarBarActorWrap *w = new VtkScalarBarActorWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkScalarBarActorWrap::SetAnnotationLeaderPadding(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsNumber())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetAnnotationLeaderPadding(
info[0]->NumberValue()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkScalarBarActorWrap::SetAnnotationTextScaling(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsInt32())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetAnnotationTextScaling(
info[0]->Int32Value()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkScalarBarActorWrap::SetBackgroundProperty(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkProperty2DWrap::ptpl))->HasInstance(info[0]))
{
VtkProperty2DWrap *a0 = ObjectWrap::Unwrap<VtkProperty2DWrap>(info[0]->ToObject());
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetBackgroundProperty(
(vtkProperty2D *) a0->native.GetPointer()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkScalarBarActorWrap::SetBarRatio(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsNumber())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetBarRatio(
info[0]->NumberValue()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkScalarBarActorWrap::SetComponentTitle(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsString())
{
Nan::Utf8String a0(info[0]);
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetComponentTitle(
*a0
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkScalarBarActorWrap::SetDrawAnnotations(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsInt32())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetDrawAnnotations(
info[0]->Int32Value()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkScalarBarActorWrap::SetDrawBackground(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsInt32())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetDrawBackground(
info[0]->Int32Value()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkScalarBarActorWrap::SetDrawColorBar(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsInt32())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetDrawColorBar(
info[0]->Int32Value()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkScalarBarActorWrap::SetDrawFrame(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsInt32())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetDrawFrame(
info[0]->Int32Value()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkScalarBarActorWrap::SetDrawNanAnnotation(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsInt32())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetDrawNanAnnotation(
info[0]->Int32Value()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkScalarBarActorWrap::SetDrawTickLabels(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsInt32())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetDrawTickLabels(
info[0]->Int32Value()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkScalarBarActorWrap::SetFixedAnnotationLeaderLineColor(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsInt32())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetFixedAnnotationLeaderLineColor(
info[0]->Int32Value()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkScalarBarActorWrap::SetFrameProperty(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkProperty2DWrap::ptpl))->HasInstance(info[0]))
{
VtkProperty2DWrap *a0 = ObjectWrap::Unwrap<VtkProperty2DWrap>(info[0]->ToObject());
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetFrameProperty(
(vtkProperty2D *) a0->native.GetPointer()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkScalarBarActorWrap::SetLabelFormat(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsString())
{
Nan::Utf8String a0(info[0]);
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetLabelFormat(
*a0
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkScalarBarActorWrap::SetLabelTextProperty(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkTextPropertyWrap::ptpl))->HasInstance(info[0]))
{
VtkTextPropertyWrap *a0 = ObjectWrap::Unwrap<VtkTextPropertyWrap>(info[0]->ToObject());
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetLabelTextProperty(
(vtkTextProperty *) a0->native.GetPointer()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkScalarBarActorWrap::SetLookupTable(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkScalarsToColorsWrap::ptpl))->HasInstance(info[0]))
{
VtkScalarsToColorsWrap *a0 = ObjectWrap::Unwrap<VtkScalarsToColorsWrap>(info[0]->ToObject());
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetLookupTable(
(vtkScalarsToColors *) a0->native.GetPointer()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkScalarBarActorWrap::SetMaximumHeightInPixels(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsInt32())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetMaximumHeightInPixels(
info[0]->Int32Value()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkScalarBarActorWrap::SetMaximumNumberOfColors(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsInt32())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetMaximumNumberOfColors(
info[0]->Int32Value()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkScalarBarActorWrap::SetMaximumWidthInPixels(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsInt32())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetMaximumWidthInPixels(
info[0]->Int32Value()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkScalarBarActorWrap::SetNanAnnotation(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsString())
{
Nan::Utf8String a0(info[0]);
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetNanAnnotation(
*a0
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkScalarBarActorWrap::SetNumberOfLabels(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsInt32())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetNumberOfLabels(
info[0]->Int32Value()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkScalarBarActorWrap::SetOrientation(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsInt32())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetOrientation(
info[0]->Int32Value()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkScalarBarActorWrap::SetOrientationToHorizontal(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetOrientationToHorizontal();
}
void VtkScalarBarActorWrap::SetOrientationToVertical(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetOrientationToVertical();
}
void VtkScalarBarActorWrap::SetTextPad(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsInt32())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetTextPad(
info[0]->Int32Value()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkScalarBarActorWrap::SetTextPosition(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsInt32())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetTextPosition(
info[0]->Int32Value()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkScalarBarActorWrap::SetTextPositionToPrecedeScalarBar(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetTextPositionToPrecedeScalarBar();
}
void VtkScalarBarActorWrap::SetTextPositionToSucceedScalarBar(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetTextPositionToSucceedScalarBar();
}
void VtkScalarBarActorWrap::SetTextureGridWidth(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsNumber())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetTextureGridWidth(
info[0]->NumberValue()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkScalarBarActorWrap::SetTitle(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsString())
{
Nan::Utf8String a0(info[0]);
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetTitle(
*a0
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkScalarBarActorWrap::SetTitleRatio(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsNumber())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetTitleRatio(
info[0]->NumberValue()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkScalarBarActorWrap::SetTitleTextProperty(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkTextPropertyWrap::ptpl))->HasInstance(info[0]))
{
VtkTextPropertyWrap *a0 = ObjectWrap::Unwrap<VtkTextPropertyWrap>(info[0]->ToObject());
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetTitleTextProperty(
(vtkTextProperty *) a0->native.GetPointer()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkScalarBarActorWrap::SetUseOpacity(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsInt32())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetUseOpacity(
info[0]->Int32Value()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkScalarBarActorWrap::SetVerticalTitleSeparation(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsInt32())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetVerticalTitleSeparation(
info[0]->Int32Value()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkScalarBarActorWrap::ShallowCopy(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkPropWrap::ptpl))->HasInstance(info[0]))
{
VtkPropWrap *a0 = ObjectWrap::Unwrap<VtkPropWrap>(info[0]->ToObject());
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->ShallowCopy(
(vtkProp *) a0->native.GetPointer()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkScalarBarActorWrap::UseOpacityOff(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->UseOpacityOff();
}
void VtkScalarBarActorWrap::UseOpacityOn(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkScalarBarActorWrap *wrapper = ObjectWrap::Unwrap<VtkScalarBarActorWrap>(info.Holder());
vtkScalarBarActor *native = (vtkScalarBarActor *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->UseOpacityOn();
}
| 33.741171 | 112 | 0.744873 | [
"object"
] |
73bf93bf88578769fabce816b550d534b78e6616 | 11,348 | hpp | C++ | build/lua-reader/include/boost-1.60.0/boost/heap/detail/tree_iterator.hpp | LazyPlanet/MX-Client | 07ac4ada4507fb7fd341094d733204f8c0170491 | [
"BSD-3-Clause"
] | 7 | 2019-02-10T07:03:45.000Z | 2022-03-04T16:09:38.000Z | build/lua-reader/include/boost-1.60.0/boost/heap/detail/tree_iterator.hpp | LazyPlanet/MX-Client | 07ac4ada4507fb7fd341094d733204f8c0170491 | [
"BSD-3-Clause"
] | null | null | null | build/lua-reader/include/boost-1.60.0/boost/heap/detail/tree_iterator.hpp | LazyPlanet/MX-Client | 07ac4ada4507fb7fd341094d733204f8c0170491 | [
"BSD-3-Clause"
] | 4 | 2018-03-01T14:34:52.000Z | 2018-06-14T12:13:55.000Z | // boost heap: node tree iterator helper classes
//
// Copyright (C) 2010 Tim Blechmann
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_HEAP_DETAIL_TREE_ITERATOR_HPP
#define BOOST_HEAP_DETAIL_TREE_ITERATOR_HPP
#include <functional>
#include <vector>
#include <boost/iterator/iterator_adaptor.hpp>
#include <queue>
namespace boost {
namespace heap {
namespace detail {
template<typename type>
struct identity
{
type& operator()(type& x) const
{ return x; }
const type& operator()(const type& x) const
{ return x; }
};
template<typename Node>
struct dereferencer
{
template <typename Iterator>
Node * operator()(Iterator const & it)
{
return static_cast<Node *>(*it);
}
};
template<typename Node>
struct pointer_to_reference
{
template <typename Iterator>
const Node * operator()(Iterator const & it)
{
return static_cast<const Node *>(&*it);
}
};
template <typename HandleType,
typename Alloc,
typename ValueCompare
>
struct unordered_tree_iterator_storage
{
unordered_tree_iterator_storage(ValueCompare const & cmp)
{}
void push(HandleType h)
{
data_.push_back(h);
}
HandleType const & top(void)
{
return data_.back();
}
void pop(void)
{
data_.pop_back();
}
bool empty(void) const
{
return data_.empty();
}
std::vector<HandleType, typename Alloc::template rebind<HandleType>::other > data_;
};
template <typename ValueType,
typename HandleType,
typename Alloc,
typename ValueCompare,
typename ValueExtractor
>
struct ordered_tree_iterator_storage:
ValueExtractor
{
struct compare_values_by_handle:
ValueExtractor,
ValueCompare
{
compare_values_by_handle(ValueCompare const & cmp):
ValueCompare(cmp)
{}
bool operator()(HandleType const & lhs, HandleType const & rhs) const
{
ValueType const & lhs_value = ValueExtractor::operator()(lhs->value);
ValueType const & rhs_value = ValueExtractor::operator()(rhs->value);
return ValueCompare::operator()(lhs_value, rhs_value);
}
};
ordered_tree_iterator_storage(ValueCompare const & cmp):
data_(compare_values_by_handle(cmp))
{}
void push(HandleType h)
{
data_.push(h);
}
void pop(void)
{
data_.pop();
}
HandleType const & top(void)
{
return data_.top();
}
bool empty(void) const
{
return data_.empty();
}
std::priority_queue<HandleType,
std::vector<HandleType, typename Alloc::template rebind<HandleType>::other>,
compare_values_by_handle> data_;
};
/* tree iterator helper class
*
* Requirements:
* Node provides child_iterator
* ValueExtractor can convert Node->value to ValueType
*
* */
template <typename Node,
typename ValueType,
typename Alloc = std::allocator<Node>,
typename ValueExtractor = identity<typename Node::value_type>,
typename PointerExtractor = dereferencer<Node>,
bool check_null_pointer = false,
bool ordered_iterator = false,
typename ValueCompare = std::less<ValueType>
>
class tree_iterator:
public boost::iterator_adaptor<tree_iterator<Node,
ValueType,
Alloc,
ValueExtractor,
PointerExtractor,
check_null_pointer,
ordered_iterator,
ValueCompare
>,
const Node *,
ValueType,
boost::forward_traversal_tag
>,
ValueExtractor,
PointerExtractor
{
typedef boost::iterator_adaptor<tree_iterator<Node,
ValueType,
Alloc,
ValueExtractor,
PointerExtractor,
check_null_pointer,
ordered_iterator,
ValueCompare
>,
const Node *,
ValueType,
boost::forward_traversal_tag
> adaptor_type;
friend class boost::iterator_core_access;
typedef typename boost::mpl::if_c< ordered_iterator,
ordered_tree_iterator_storage<ValueType, const Node*, Alloc, ValueCompare, ValueExtractor>,
unordered_tree_iterator_storage<const Node*, Alloc, ValueCompare>
>::type
unvisited_node_container;
public:
tree_iterator(void):
adaptor_type(0), unvisited_nodes(ValueCompare())
{}
tree_iterator(ValueCompare const & cmp):
adaptor_type(0), unvisited_nodes(cmp)
{}
tree_iterator(const Node * it, ValueCompare const & cmp):
adaptor_type(it), unvisited_nodes(cmp)
{
if (it)
discover_nodes(it);
}
/* fills the iterator from a list of possible top nodes */
template <typename NodePointerIterator>
tree_iterator(NodePointerIterator begin, NodePointerIterator end, const Node * top_node, ValueCompare const & cmp):
adaptor_type(0), unvisited_nodes(cmp)
{
BOOST_STATIC_ASSERT(ordered_iterator);
if (begin == end)
return;
adaptor_type::base_reference() = top_node;
discover_nodes(top_node);
for (NodePointerIterator it = begin; it != end; ++it) {
const Node * current_node = static_cast<const Node*>(&*it);
if (current_node != top_node)
unvisited_nodes.push(current_node);
}
}
bool operator!=(tree_iterator const & rhs) const
{
return adaptor_type::base() != rhs.base();
}
bool operator==(tree_iterator const & rhs) const
{
return !operator!=(rhs);
}
const Node * get_node() const
{
return adaptor_type::base_reference();
}
private:
void increment(void)
{
if (unvisited_nodes.empty())
adaptor_type::base_reference() = 0;
else {
const Node * next = unvisited_nodes.top();
unvisited_nodes.pop();
discover_nodes(next);
adaptor_type::base_reference() = next;
}
}
ValueType const & dereference() const
{
return ValueExtractor::operator()(adaptor_type::base_reference()->value);
}
void discover_nodes(const Node * n)
{
for (typename Node::const_child_iterator it = n->children.begin(); it != n->children.end(); ++it) {
const Node * n = PointerExtractor::operator()(it);
if (check_null_pointer && n == NULL)
continue;
unvisited_nodes.push(n);
}
}
unvisited_node_container unvisited_nodes;
};
template <typename Node, typename NodeList>
struct list_iterator_converter
{
typename NodeList::const_iterator operator()(const Node * node)
{
return NodeList::s_iterator_to(*node);
}
Node * operator()(typename NodeList::const_iterator it)
{
return const_cast<Node*>(static_cast<const Node*>(&*it));
}
};
template <typename Node,
typename NodeIterator,
typename ValueType,
typename ValueExtractor = identity<typename Node::value_type>,
typename IteratorCoverter = identity<NodeIterator>
>
class recursive_tree_iterator:
public boost::iterator_adaptor<recursive_tree_iterator<Node,
NodeIterator,
ValueType,
ValueExtractor,
IteratorCoverter
>,
NodeIterator,
ValueType const,
boost::bidirectional_traversal_tag>,
ValueExtractor, IteratorCoverter
{
typedef boost::iterator_adaptor<recursive_tree_iterator<Node,
NodeIterator,
ValueType,
ValueExtractor,
IteratorCoverter
>,
NodeIterator,
ValueType const,
boost::bidirectional_traversal_tag> adaptor_type;
friend class boost::iterator_core_access;
public:
recursive_tree_iterator(void):
adaptor_type(0)
{}
explicit recursive_tree_iterator(NodeIterator const & it):
adaptor_type(it)
{}
void increment(void)
{
NodeIterator next = adaptor_type::base_reference();
const Node * n = get_node(next);
if (n->children.empty()) {
const Node * parent = get_node(next)->get_parent();
++next;
while (true) {
if (parent == NULL || next != parent->children.end())
break;
next = IteratorCoverter::operator()(parent);
parent = get_node(next)->get_parent();
++next;
}
} else
next = n->children.begin();
adaptor_type::base_reference() = next;
return;
}
ValueType const & dereference() const
{
return ValueExtractor::operator()(get_node(adaptor_type::base_reference())->value);
}
static const Node * get_node(NodeIterator const & it)
{
return static_cast<const Node *>(&*it);
}
const Node * get_node() const
{
return get_node(adaptor_type::base_reference());
}
};
} /* namespace detail */
} /* namespace heap */
} /* namespace boost */
#endif /* BOOST_HEAP_DETAIL_TREE_ITERATOR_HPP */
| 30.021164 | 131 | 0.505992 | [
"vector"
] |
73c3d9a4ee3d0e81bc38649d065a6c72c8c26478 | 3,071 | hpp | C++ | src/Domain/Entity.hpp | LBBassani/cg-trabalho-2d | 8ada0b1a222a423d4dd28428b96653acbbaa2d5a | [
"MIT"
] | null | null | null | src/Domain/Entity.hpp | LBBassani/cg-trabalho-2d | 8ada0b1a222a423d4dd28428b96653acbbaa2d5a | [
"MIT"
] | null | null | null | src/Domain/Entity.hpp | LBBassani/cg-trabalho-2d | 8ada0b1a222a423d4dd28428b96653acbbaa2d5a | [
"MIT"
] | null | null | null | #if !defined ENTITY
#define ENTITY
#include <list>
#include "Transform.hpp"
#include "Model.hpp"
struct HitboxMapping;
struct MoveLiberty{
bool direita = true;
bool esquerda = true;
bool para_cima = true;
bool para_baixo = true;
};
struct Entity : public Model
{
bool is_movable = false;
bool is_character = false;
bool is_player = false;
bool is_trigger = false;
bool game_ended = false;
MoveLiberty moveLiberty;
Transform transform;
std::list<Entity*> children;
Entity* parent = nullptr;
~Entity(){
for (auto child : children){
if(child) delete child;
child = nullptr;
}
}
virtual void addChild(Entity* entity){
children.emplace_back(entity);
children.back()->parent = this;
}
void removeChild(Entity* child){
children.remove_if([child](const Entity* ptr){ return ptr == child; });
}
void removeSelf(){
parent->removeChild(this);
parent = nullptr;
}
void updateSelfAndChildren(){
if (parent)
transform.modelMatrix = parent->transform.modelMatrix * transform.getLocalModelMatrix();
else
transform.modelMatrix = transform.getLocalModelMatrix();
for (auto&& child : children){
child->updateSelfAndChildren();
}
}
virtual void print(){
std::cout << this->nome << std::endl;
for(auto child : children){
child->print();
}
}
virtual bool prepare_drawing(){
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glLoadMatrixf(&transform.modelMatrix[0][0]);
return true;
}
virtual void draw(){
#if defined TEST
if(this->is_trigger){
//std::cout << this->getNome() << " é um trigger" << std::endl;
glColor3f(1.0f, 1.0f, 1.0f);
glTranslatef(hitbox_offset.x, hitbox_offset.y, 0.0f);
if (hitbox) hitbox->draw();
}
#endif
if(!prepare_drawing()) return;
Model::draw();
for(auto child : children){
child->draw();
}
}
virtual void set_game_ended(bool game_ended){
this->game_ended = game_ended;
for(auto child : children)
child->set_game_ended(game_ended);
}
virtual void act(int* keyStatus, GLdouble deltaTime) { /* does nothing, implemented in movingEntities classes */};
virtual void do_collision(std::list<HitboxMapping> colliding_hitbox) { /* does nothing, implemented in child classes */};
virtual void idle(int* keyStatus, GLdouble deltaTime){
if(this->is_movable){
this->act(keyStatus, deltaTime);
}
for(auto child : children){
child->idle(keyStatus, deltaTime);
}
}
void flattenTree(std::list<Entity*>* entities){
entities->push_back(this);
for(auto child : children){
child->flattenTree(entities);
}
}
};
#endif | 23.623077 | 125 | 0.576685 | [
"model",
"transform"
] |
73c88ee02cf072106f8f57b265da39a46272530d | 53,473 | cpp | C++ | renderdoc/driver/shaders/spirv/spirv_disassemble.cpp | djdeath/renderdoc | f0eca04b7936d2401a5d49f12233065506fbc395 | [
"MIT"
] | null | null | null | renderdoc/driver/shaders/spirv/spirv_disassemble.cpp | djdeath/renderdoc | f0eca04b7936d2401a5d49f12233065506fbc395 | [
"MIT"
] | null | null | null | renderdoc/driver/shaders/spirv/spirv_disassemble.cpp | djdeath/renderdoc | f0eca04b7936d2401a5d49f12233065506fbc395 | [
"MIT"
] | null | null | null | /******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2019-2020 Baldur Karlsson
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
******************************************************************************/
#include "common/formatting.h"
#include "spirv_op_helpers.h"
#include "spirv_reflect.h"
struct StructuredCFG
{
enum
{
Loop,
If,
Switch,
} type;
// the Id of the header block
rdcspv::Id headerBlock;
// the merge target is basically the block after the construct.
// branching to it exits the construct and all branches must go via the merge target
rdcspv::Id mergeTarget;
// only valid for ifs. The target of the else - we reverse the condition when printing if
// necessary so that the false condition is second
rdcspv::Id elseTarget;
// only valid for loops
rdcspv::Id continueTarget;
// only valid for switches
rdcarray<rdcspv::PairLiteralIntegerIdRef> caseTargets;
rdcspv::Id defaultTarget;
};
static rdcstr StringiseBinaryOperation(const std::function<rdcstr(rdcspv::Id)> &idName,
rdcspv::Op op, rdcspv::Id operand1, rdcspv::Id operand2)
{
rdcstr ret;
ret += idName(operand1);
ret += " ";
switch(op)
{
case rdcspv::Op::IAdd:
case rdcspv::Op::FAdd: ret += "+"; break;
case rdcspv::Op::ISub:
case rdcspv::Op::FSub: ret += "+"; break;
case rdcspv::Op::IMul:
case rdcspv::Op::FMul:
case rdcspv::Op::VectorTimesMatrix:
case rdcspv::Op::VectorTimesScalar:
case rdcspv::Op::MatrixTimesMatrix:
case rdcspv::Op::MatrixTimesVector:
case rdcspv::Op::MatrixTimesScalar: ret += "*"; break;
case rdcspv::Op::UDiv:
case rdcspv::Op::SDiv:
case rdcspv::Op::FDiv: ret += "/"; break;
case rdcspv::Op::ShiftLeftLogical: ret += "<<"; break;
case rdcspv::Op::BitwiseAnd: ret += "&"; break;
case rdcspv::Op::BitwiseOr: ret += "|"; break;
case rdcspv::Op::BitwiseXor: ret += "^"; break;
case rdcspv::Op::LogicalEqual:
case rdcspv::Op::IEqual:
case rdcspv::Op::FOrdEqual:
case rdcspv::Op::FUnordEqual: ret += "=="; break;
case rdcspv::Op::LogicalNotEqual:
case rdcspv::Op::INotEqual:
case rdcspv::Op::FOrdNotEqual:
case rdcspv::Op::FUnordNotEqual: ret += "!="; break;
case rdcspv::Op::LogicalOr: ret += "||"; break;
case rdcspv::Op::LogicalAnd: ret += "&&"; break;
case rdcspv::Op::UGreaterThan:
case rdcspv::Op::SGreaterThan:
case rdcspv::Op::FOrdGreaterThan:
case rdcspv::Op::FUnordGreaterThan: ret += ">"; break;
case rdcspv::Op::UGreaterThanEqual:
case rdcspv::Op::SGreaterThanEqual:
case rdcspv::Op::FOrdGreaterThanEqual:
case rdcspv::Op::FUnordGreaterThanEqual: ret += ">="; break;
case rdcspv::Op::ULessThan:
case rdcspv::Op::SLessThan:
case rdcspv::Op::FOrdLessThan:
case rdcspv::Op::FUnordLessThan: ret += "<"; break;
case rdcspv::Op::ULessThanEqual:
case rdcspv::Op::SLessThanEqual:
case rdcspv::Op::FOrdLessThanEqual:
case rdcspv::Op::FUnordLessThanEqual: ret += "<="; break;
default: break;
}
ret += " ";
ret += idName(operand2);
return ret;
}
namespace rdcspv
{
rdcstr Reflector::Disassemble(const rdcstr &entryPoint,
std::map<size_t, uint32_t> &instructionLines) const
{
std::set<rdcstr> usedNames;
std::map<Id, rdcstr> dynamicNames;
auto idName = [this, &dynamicNames](Id id) -> rdcstr {
// see if we have a dynamic name assigned (to disambiguate), if so use that
auto it = dynamicNames.find(id);
if(it != dynamicNames.end())
return it->second;
// otherwise try the string
rdcstr ret = strings[id];
if(!ret.empty())
return ret;
// for non specialised constants, see if we can stringise them directly if they're unnamed
ret = StringiseConstant(id);
if(!ret.empty())
return ret;
// if we *still* have nothing, just stringise the id itself
return StringFormat::Fmt("_%u", id.value());
};
auto constIntVal = [this](Id id) { return EvaluateConstant(id, {}).value.u.x; };
auto declName = [this, &idName, &usedNames, &dynamicNames](Id typeId, Id id) -> rdcstr {
if(typeId == Id())
return idName(id);
rdcstr ret = dataTypes[typeId].name;
if(ret.empty())
ret = StringFormat::Fmt("type%u", typeId.value());
if(id == Id())
return ret;
rdcstr basename = strings[id];
if(basename.empty())
{
return ret + " " + StringFormat::Fmt("_%u", id.value());
}
rdcstr name = basename;
int alias = 2;
while(usedNames.find(name) != usedNames.end())
{
name = basename + "@" + ToStr(alias);
alias++;
}
usedNames.insert(name);
dynamicNames[id] = name;
return ret + " " + name;
};
auto getDecorationString = [&idName](const Decorations &dec) -> rdcstr {
if(!dec.HasDecorations())
return rdcstr();
rdcstr ret;
ret += " : [[";
if(dec.flags & Decorations::Block)
ret += "Block, ";
if(dec.flags & Decorations::BufferBlock)
ret += "BufferBlock, ";
if(dec.flags & Decorations::RowMajor)
ret += "RowMajor, ";
if(dec.flags & Decorations::ColMajor)
ret += "ColMajor, ";
if(dec.flags & Decorations::HasDescriptorSet)
ret += StringFormat::Fmt("DescriptorSet(%u), ", dec.set);
if(dec.flags & Decorations::HasBinding)
ret += StringFormat::Fmt("Binding(%u), ", dec.binding);
if(dec.flags & Decorations::HasBuiltIn)
ret += StringFormat::Fmt("BuiltIn(%s), ", ToStr(dec.builtIn).c_str());
if(dec.flags & Decorations::HasLocation)
ret += StringFormat::Fmt("Location(%u), ", dec.location);
if(dec.flags & Decorations::HasArrayStride)
ret += StringFormat::Fmt("ArrayStride(%u), ", dec.arrayStride);
if(dec.flags & Decorations::HasMatrixStride)
ret += StringFormat::Fmt("MatrixStride(%u), ", dec.matrixStride);
if(dec.flags & Decorations::HasOffset)
ret += StringFormat::Fmt("Offset(%u), ", dec.offset);
if(dec.flags & Decorations::HasSpecId)
ret += StringFormat::Fmt("SpecId(%u), ", dec.specID);
for(const DecorationAndParamData &d : dec.others)
ret += ParamToStr(idName, d) + ", ";
ret.pop_back();
ret.pop_back();
ret += "]]";
return ret;
};
auto accessor = [](const DataType *baseType, uint32_t idx, rdcstr idxname) -> rdcstr {
if(baseType->type == DataType::ArrayType || baseType->type == DataType::MatrixType ||
(baseType->type == DataType::VectorType && !idxname.empty()))
{
if(idxname.empty())
idxname = ToStr(idx);
return StringFormat::Fmt("[%s]", idxname.c_str());
}
if(baseType->type == DataType::VectorType)
{
if(idx >= 4)
{
if(idxname.empty())
idxname = ToStr(idx);
return StringFormat::Fmt("[%s]", idxname.c_str());
}
rdcstr ret = ".";
const char comps[5] = "xyzw";
ret.push_back(comps[idx]);
return ret;
}
RDCASSERT(baseType->type == DataType::StructType && idx < baseType->children.size());
if(!baseType->children[idx].name.empty())
return "." + baseType->children[idx].name;
return StringFormat::Fmt("._child%u", idx);
};
rdcstr ret;
rdcstr indent;
// stack of structured CFG constructs
rdcarray<StructuredCFG> cfgStack;
// set of labels that must be printed because we have gotos for them
std::set<Id> printLabels;
Id currentBlock;
ret = StringFormat::Fmt(
"SPIR-V %u.%u module, <id> bound of %u\n"
"\n"
"Generator: %s\n"
"Generator Version: %u\n"
"\n",
m_MajorVersion, m_MinorVersion, m_SPIRV[3], ToStr(m_Generator).c_str(), m_GeneratorVersion);
uint32_t lineNum = 6;
for(size_t sec = 0; sec < Section::Count; sec++)
{
ConstIter it(m_SPIRV, m_Sections[sec].startOffset);
ConstIter end(m_SPIRV, m_Sections[sec].endOffset);
for(; it < end; it++)
{
instructionLines[it.offs()] = lineNum;
// special case some opcodes for more readable disassembly, but generally pass to the
// auto-generated disassembler
switch(it.opcode())
{
////////////////////////////////////////////////////////////////////////////////////////
// global instructions
////////////////////////////////////////////////////////////////////////////////////////
// don't print the full source
case Op::Source:
{
OpSource decoded(it);
ret += StringFormat::Fmt("Source(%s, %u", ToStr(decoded.sourceLanguage).c_str(),
decoded.version);
if(decoded.file != Id())
ret += ", file: " + idName(decoded.file);
ret += ")";
break;
}
// ignore these operations entirely
case Op::SourceContinued:
case Op::Line:
case Op::String:
case Op::Name:
case Op::MemberName:
case Op::ExtInstImport:
continue;
// ignore decorations too, we already have these cached
case Op::Decorate:
case Op::DecorateId:
case Op::DecorateString:
case Op::MemberDecorate:
case Op::MemberDecorateString:
case Op::DecorationGroup:
case Op::GroupDecorate:
case Op::GroupMemberDecorate:
continue;
// suppress almost all types
case Op::TypeVoid:
case Op::TypeBool:
case Op::TypeInt:
case Op::TypeFloat:
case Op::TypeVector:
case Op::TypeMatrix:
case Op::TypePointer:
case Op::TypeArray:
case Op::TypeImage:
case Op::TypeSampler:
case Op::TypeSampledImage:
case Op::TypeFunction:
case Op::TypeRuntimeArray: continue;
case Op::TypeForwardPointer:
{
OpTypeForwardPointer decoded(it);
ret += ToStr(decoded.storageClass) + " " + declName(decoded.pointerType, Id()) + ";\n";
lineNum++;
continue;
}
// structs we print out
case Op::TypeStruct:
{
OpTypeStruct decoded(it);
const DataType &type = dataTypes[decoded.result];
ret += "struct " + idName(decoded.result) +
getDecorationString(decorations[decoded.result]) + " {\n";
lineNum++;
for(size_t i = 0; i < type.children.size(); i++)
{
ret += " " + declName(type.children[i].type, Id());
ret += " ";
if(!type.children[i].name.empty())
ret += type.children[i].name;
else
ret += StringFormat::Fmt("_child%zu", i);
ret += getDecorationString(type.children[i].decorations);
ret += getDecorationString(decorations[type.children[i].type]);
ret += ";\n";
lineNum++;
}
ret += "}\n";
lineNum++;
continue;
}
// scalar and vector constants are inlined when they're unnamed and not specialised, so only
// declare others.
case Op::ConstantTrue:
case Op::ConstantFalse: continue;
case Op::SpecConstant:
case Op::Constant:
{
OpDecoder decoded(it);
const DataType &type = dataTypes[decoded.resultType];
RDCASSERT(type.type == DataType::ScalarType);
// if it's not specialised, not decorated, and not named, don't declare it at all.
if(it.opcode() == Op::Constant &&
specConstants.find(decoded.result) == specConstants.end() &&
strings[decoded.result].empty() && !decorations[decoded.result].HasDecorations())
{
continue;
}
ret += indent;
ret +=
StringFormat::Fmt("const %s = ", declName(decoded.resultType, decoded.result).c_str());
// evalute the value with no specialisation
ShaderValue value = EvaluateConstant(decoded.result, {}).value;
switch(type.scalar().Type())
{
case VarType::Unknown:
case VarType::Float:
case VarType::Half: ret += ToStr(value.f.x); break;
case VarType::Double: ret += ToStr(value.d.x); break;
case VarType::SInt:
case VarType::SShort:
case VarType::SByte: ret += ToStr(value.i.x); break;
case VarType::UInt:
case VarType::UShort:
case VarType::UByte: ret += ToStr(value.u.x); break;
case VarType::SLong: ret += ToStr(value.s64v[0]); break;
case VarType::ULong: ret += ToStr(value.u64v[0]); break;
}
ret += getDecorationString(decorations[decoded.result]);
break;
}
case Op::SpecConstantComposite:
case Op::ConstantComposite:
{
OpConstantComposite decoded(it);
const DataType &type = dataTypes[decoded.resultType];
// if it's a vector, not specialised, not decorated, and not named, don't declare it at
// all.
if(it.opcode() == Op::ConstantComposite && type.type == DataType::VectorType &&
specConstants.find(decoded.result) == specConstants.end() &&
strings[decoded.result].empty() && !decorations[decoded.result].HasDecorations())
{
continue;
}
ret += indent;
ret += StringFormat::Fmt("const %s = {",
declName(decoded.resultType, decoded.result).c_str());
for(size_t i = 0; i < decoded.constituents.size(); i++)
{
ret += idName(decoded.constituents[i]);
if(i + 1 < decoded.constituents.size())
ret += ", ";
}
ret += "}";
ret += getDecorationString(decorations[decoded.result]);
break;
}
case Op::SpecConstantOp:
{
OpDecoder decoded(it);
Op op = (Op)it.word(3);
ret += indent;
ret +=
StringFormat::Fmt("const %s = ", declName(decoded.resultType, decoded.result).c_str());
bool binary = false;
switch(op)
{
case Op::IAdd:
case Op::ISub:
case Op::IMul:
case Op::UDiv:
case Op::SDiv:
case Op::UMod:
case Op::SRem:
case Op::SMod:
case Op::ShiftRightLogical:
case Op::ShiftRightArithmetic:
case Op::ShiftLeftLogical:
case Op::BitwiseOr:
case Op::BitwiseXor:
case Op::BitwiseAnd:
case Op::LogicalOr:
case Op::LogicalAnd:
case Op::LogicalEqual:
case Op::LogicalNotEqual:
case Op::IEqual:
case Op::INotEqual:
case Op::ULessThan:
case Op::SLessThan:
case Op::UGreaterThan:
case Op::SGreaterThan:
case Op::ULessThanEqual:
case Op::SLessThanEqual:
case Op::UGreaterThanEqual:
case Op::SGreaterThanEqual:
RDCASSERT(it.size() == 6);
binary = true;
ret += StringiseBinaryOperation(idName, op, Id::fromWord(it.word(4)),
Id::fromWord(it.word(5)));
break;
default: break;
}
if(!binary)
{
ret += StringFormat::Fmt("%s(", declName(decoded.resultType, decoded.result).c_str(),
ToStr(op).c_str());
// interpret params as Ids, except for CompositeExtract and CompositeInsert
size_t limit = it.size();
if(op == Op::CompositeExtract)
limit = 5;
else if(op == Op::CompositeInsert)
limit = 6;
for(size_t w = 4; w < limit; w++)
{
ret += idName(Id::fromWord(it.word(w)));
if(w + 1 < limit)
ret += ", ";
}
// if we have trailing literals, print them
if(limit < it.size())
{
for(size_t w = limit; w < it.size(); w++)
{
ret += ToStr(it.word(w));
if(w + 1 < it.size())
ret += ", ";
}
}
ret += ")";
}
break;
}
// declare variables by hand with optional initialiser
case Op::Variable:
{
OpVariable decoded(it);
ret += indent;
if(decoded.storageClass != StorageClass::Function)
ret += ToStr(decoded.storageClass) + " ";
ret += declName(decoded.resultType, decoded.result);
if(decoded.HasInitializer())
ret += " = " + idName(decoded.initializer);
ret += getDecorationString(decorations[decoded.result]);
break;
}
////////////////////////////////////////////////////////////////////////////////////////
// control flow and scope indentation
////////////////////////////////////////////////////////////////////////////////////////
// indent around functions
case Op::Function:
{
OpFunction decoded(it);
rdcstr name = declName(decoded.resultType, decoded.result);
// glslang outputs encoded type information in the OpName of functions, strip it
{
int32_t offs = name.indexOf('(');
if(offs > 0)
name.erase(offs, name.size() - offs);
}
ret += StringFormat::Fmt("%s(", name.c_str());
// peek ahead and consume any function parameters
{
it++;
while(it.opcode() == Op::Line || it.opcode() == Op::NoLine)
{
it++;
instructionLines[it.offs()] = lineNum;
}
const bool added_params = (it.opcode() == Op::FunctionParameter);
while(it.opcode() == Op::FunctionParameter)
{
OpFunctionParameter param(it);
ret += declName(param.resultType, param.result) + ", ";
it++;
instructionLines[it.offs()] = lineNum;
while(it.opcode() == Op::Line || it.opcode() == Op::NoLine)
{
it++;
instructionLines[it.offs()] = lineNum;
}
}
// remove trailing ", "
if(added_params)
{
ret.pop_back();
ret.pop_back();
}
}
instructionLines[it.offs()] = lineNum;
ret += ")";
if(decoded.functionControl != FunctionControl::None)
ret += " [[" + ToStr(decoded.functionControl) + "]]";
ret += getDecorationString(decorations[decoded.result]);
// if we reached the end, it's a declaration not a definition
if(it.opcode() == Op::FunctionEnd)
ret += ";";
else
ret += " {";
// it points to the FunctionEnd (for declarations) or first Label (for definitions).
// the next it++ will skip that but it's fine, because we have processed them
ret += "\n";
lineNum++;
indent += " ";
continue;
}
case Op::FunctionEnd:
{
ret += "}\n\n";
lineNum += 2;
indent.resize(indent.size() - 2);
continue;
}
// indent around control flow
case Op::SelectionMerge:
{
OpSelectionMerge decoded(it);
ret += indent;
if(decoded.selectionControl != SelectionControl::None)
ret += StringFormat::Fmt("[[%s]]", ToStr(decoded.selectionControl).c_str());
// increment any previous instructions that were pointing at this line, to point at the
// next one.
for(auto lineIt = instructionLines.end(); lineIt != instructionLines.begin();)
{
--lineIt;
if(lineIt->second == lineNum)
{
lineIt->second++;
continue;
}
break;
}
ret += "\n";
lineNum++;
StructuredCFG cfg;
cfg.headerBlock = currentBlock;
cfg.mergeTarget = decoded.mergeBlock;
it++;
instructionLines[it.offs()] = lineNum;
// the Switch or BranchConditional operation declares the structured CFG
if(it.opcode() == Op::Switch)
{
cfg.type = StructuredCFG::Switch;
OpSwitch decodedswitch(it);
cfg.caseTargets = decodedswitch.target;
cfg.defaultTarget = decodedswitch.def;
ret += indent;
ret += StringFormat::Fmt("switch(%s) {\n", idName(decodedswitch.selector).c_str());
lineNum++;
// add another level - each case label will be un-intended.
indent += " ";
}
else
{
cfg.type = StructuredCFG::If;
OpBranchConditional decodedbranch(it);
ConstIter nextit = it;
nextit++;
while(nextit.opcode() == Op::Line || nextit.opcode() == Op::NoLine)
nextit++;
// if we got here we're a simple if() without an else - SelectionMerge/LoopMerge
// consumes any branch
// next opcode *must* be a label because this is the end of a block
RDCASSERTEQUAL(nextit.opcode(), Op::Label);
OpLabel decodedlabel(nextit);
if(decodedbranch.trueLabel == decodedlabel.result ||
decodedbranch.falseLabel == decodedlabel.result)
{
const char *negate = (decodedbranch.falseLabel == decodedlabel.result) ? "!" : "";
ret += indent;
ret += StringFormat::Fmt("if(%s%s) {", negate, idName(decodedbranch.condition).c_str());
if(decodedbranch.branchweights.size() == 2)
ret += StringFormat::Fmt(" [[true: %u, false: %u]]", decodedbranch.branchweights[0],
decodedbranch.branchweights[1]);
ret += "\n";
lineNum++;
cfg.elseTarget = (decodedbranch.trueLabel == decodedlabel.result)
? decodedbranch.falseLabel
: decodedbranch.trueLabel;
}
else
{
RDCWARN(
"Unexpected SPIR-V formulation - OpBranchConditional not followed by either true "
"or false block");
// this is legal. We just have to emit an if with gotos
ret += indent;
ret += StringFormat::Fmt(
"if(%s) { goto %s; } else { goto %s; }\n", idName(decodedbranch.condition).c_str(),
idName(decodedbranch.trueLabel).c_str(), idName(decodedbranch.falseLabel).c_str());
lineNum++;
// need to print these labels now
printLabels.insert(decodedbranch.trueLabel);
printLabels.insert(decodedbranch.falseLabel);
continue;
}
}
cfgStack.push_back(cfg);
indent += " ";
continue;
}
case Op::LoopMerge:
{
OpLoopMerge decoded(it);
if(decoded.loopControl != LoopControl::None)
{
ret += indent;
ret += StringFormat::Fmt("[[%s]]\n", ParamToStr(idName, decoded.loopControl).c_str());
lineNum++;
}
it++;
instructionLines[it.offs()] = lineNum;
if(it.opcode() == Op::Branch)
{
OpBranch decodedbranch(it);
ConstIter nextit = it;
nextit++;
while(nextit.opcode() == Op::Line || nextit.opcode() == Op::NoLine)
nextit++;
// we can now ignore everything between us and the label of this branch, which is almost
// always going to be the very next label.
//
// The reasoning is this:
// - assume the next block is not the one we are jumping to
// - all blocks inside the loop must only ever branch backwards to the header block
// (that's this one) so the block can't be jumped to from within the loop
// - it's also illegal to jump into a structured control flow construct from outside, so
// it can't be jumped to from outside the loop
// - that means it is completely inaccessible from everywhere, so we can skip it
while(nextit.opcode() != Op::Label || OpLabel(nextit).result != decodedbranch.targetLabel)
{
nextit++;
it++;
instructionLines[it.offs()] = lineNum;
}
}
else
{
RDCASSERTEQUAL(it.opcode(), Op::BranchConditional);
OpBranchConditional decodedbranch(it);
// we assume one of the targets of this is the merge block. Then we can express this as
// a while(condition) loop, potentially by negating the condition.
// If it isn't, then we have to do an infinite loop with a branchy if at the top
if(decodedbranch.trueLabel == decoded.mergeBlock ||
decodedbranch.falseLabel == decoded.mergeBlock)
{
const char *negate = (decodedbranch.trueLabel == decoded.mergeBlock) ? "" : "!";
ret += indent;
ret += StringFormat::Fmt("if(%s%s) break;", negate,
idName(decodedbranch.condition).c_str());
if(decodedbranch.branchweights.size() == 2)
ret += StringFormat::Fmt(" [[true: %u, false: %u]]", decodedbranch.branchweights[0],
decodedbranch.branchweights[1]);
ret += "\n";
lineNum++;
}
else
{
RDCWARN(
"Unexpected SPIR-V construct - loop with conditional branch both pointing inside "
"the loop");
ret += indent;
ret += "while(true) {\n";
lineNum++;
ret += indent;
ret += StringFormat::Fmt(" if(%s) { goto %s; } else { goto %s; }\n",
idName(decodedbranch.condition).c_str(),
idName(decodedbranch.trueLabel).c_str(),
idName(decodedbranch.falseLabel).c_str());
lineNum++;
// need to print these labels now
printLabels.insert(decodedbranch.trueLabel);
printLabels.insert(decodedbranch.falseLabel);
}
}
StructuredCFG cfg = {StructuredCFG::Loop};
cfg.headerBlock = currentBlock;
cfg.mergeTarget = decoded.mergeBlock;
cfg.continueTarget = decoded.continueTarget;
cfgStack.push_back(cfg);
continue;
}
case Op::Label:
{
OpLabel decoded(it);
currentBlock = decoded.result;
if(!cfgStack.empty() && decoded.result == cfgStack.back().mergeTarget)
{
// if this is the latest merge block print a closing brace and reduce the indent
indent.resize(indent.size() - 2);
// if this is a switch, remove another level
if(cfgStack.back().type == StructuredCFG::Switch)
indent.resize(indent.size() - 2);
ret += indent;
ret += "}\n\n";
lineNum += 2;
cfgStack.pop_back();
}
else if(!cfgStack.empty() && cfgStack.back().type == StructuredCFG::If &&
decoded.result == cfgStack.back().elseTarget)
{
// if this is the current if's else{} then print it
ret += indent.substr(0, indent.size() - 2);
ret += "} else {\n";
lineNum++;
}
else if(!cfgStack.empty() && cfgStack.back().type == StructuredCFG::Switch &&
decoded.result == cfgStack.back().defaultTarget)
{
// if this is the current switch's default: then print it
ret += indent.substr(0, indent.size() - 2);
ret += "default:\n";
lineNum++;
}
if(!cfgStack.empty() && cfgStack.back().type == StructuredCFG::Switch)
{
for(const PairLiteralIntegerIdRef &caseTarget : cfgStack.back().caseTargets)
{
if(caseTarget.second == decoded.result)
{
// if this is the current switch's default: then print it
ret += indent.substr(0, indent.size() - 2);
ret += StringFormat::Fmt("case %u:\n", caseTarget.first);
lineNum++;
break;
}
}
}
// print the label if we decided it was needed
if(printLabels.find(decoded.result) != printLabels.end())
{
ret += idName(decoded.result) + ":\n";
lineNum++;
}
// if this is a loop header, begin the loop here
if(loopBlocks.find(decoded.result) != loopBlocks.end())
{
// increment any previous instructions that were pointing at this line, to point at the
// next one.
for(auto lineIt = instructionLines.end(); lineIt != instructionLines.begin();)
{
--lineIt;
if(lineIt->second == lineNum)
{
lineIt->second++;
continue;
}
break;
}
ret += "\n";
lineNum++;
ret += indent + "while(true) {\n";
lineNum++;
indent += " ";
}
continue;
}
case Op::Branch:
{
OpBranch decoded(it);
ConstIter nextit = it;
nextit++;
while(nextit.opcode() == Op::Line || nextit.opcode() == Op::NoLine)
nextit++;
// next opcode *must* be a label because this is the end of a block
RDCASSERTEQUAL(nextit.opcode(), Op::Label);
OpLabel decodedlabel(nextit);
// always skip redundant gotos
if(decodedlabel.result == decoded.targetLabel)
{
// however if we're in a switch we might want to print a clarifying fallthrough comment
// or end-of-case break
if(!cfgStack.empty() && cfgStack.back().type == StructuredCFG::Switch)
{
// add a break even for the final branch to the merge block
if(cfgStack.back().mergeTarget == decoded.targetLabel)
{
ret += indent + "break;\n";
lineNum++;
continue;
}
// if we're falling through to the next case, print a comment
for(const PairLiteralIntegerIdRef &caseTarget : cfgStack.back().caseTargets)
{
if(caseTarget.second == decoded.targetLabel)
{
ret += indent;
ret +=
StringFormat::Fmt("// deliberate fallthrough to case %u\n", caseTarget.first);
lineNum++;
break;
}
}
}
continue;
}
// if we're in a loop, skip branches from the continue block to the loop header
if(!cfgStack.empty() && cfgStack.back().type == StructuredCFG::Loop &&
cfgStack.back().continueTarget == currentBlock &&
cfgStack.back().headerBlock == decoded.targetLabel)
continue;
// if we're in an if, skip branches to the merge block if the next block is the 'else'
if(!cfgStack.empty() && cfgStack.back().type == StructuredCFG::If &&
cfgStack.back().elseTarget == decodedlabel.result &&
cfgStack.back().mergeTarget == decoded.targetLabel)
continue;
// if we're in a switch, branches to the merge block are printed as 'break'
if(!cfgStack.empty() && cfgStack.back().type == StructuredCFG::Switch &&
cfgStack.back().mergeTarget == decoded.targetLabel)
{
ret += indent + "break;\n";
lineNum++;
continue;
}
// if we're in a switch and we're about to print a goto, see if it's a case label and
// print a 'nicer' goto. Fallthrough to the next case would be handled above as a
// redundant goto
if(!cfgStack.empty() && cfgStack.back().type == StructuredCFG::Switch)
{
bool printed = false;
for(const PairLiteralIntegerIdRef &caseTarget : cfgStack.back().caseTargets)
{
if(caseTarget.second == decoded.targetLabel)
{
ret += StringFormat::Fmt("goto case %u;\n", caseTarget.first);
lineNum++;
printed = true;
break;
}
}
if(printed)
continue;
}
ret += indent;
ret += "goto " + idName(decoded.targetLabel) + ";\n";
lineNum++;
// we must print this label because we've created a goto for it
printLabels.insert(decoded.targetLabel);
continue;
}
case Op::BranchConditional:
{
OpBranchConditional decoded(it);
ConstIter nextit = it;
nextit++;
// if we got here we're a simple if() without an else - SelectionMerge/LoopMerge
// consumes any branch.
//
// we must be careful because this kind of branch can conditionally branch out of a loop,
// so we need to look to see if either 'other' branch is to the continue or merge blocks
// of the current loop
// next opcode *must* be a label because this is the end of a block
RDCASSERTEQUAL(nextit.opcode(), Op::Label);
OpLabel decodedlabel(nextit);
if(decoded.trueLabel == decodedlabel.result || decoded.falseLabel == decodedlabel.result)
{
Id otherLabel =
(decoded.trueLabel == decodedlabel.result) ? decoded.falseLabel : decoded.trueLabel;
if(!cfgStack.empty() && cfgStack.back().type == StructuredCFG::Loop &&
(otherLabel == cfgStack.back().mergeTarget ||
otherLabel == cfgStack.back().continueTarget))
{
const char *negate = (decoded.falseLabel == cfgStack.back().mergeTarget) ? "!" : "";
ret += indent;
if(otherLabel == cfgStack.back().mergeTarget)
{
ret +=
StringFormat::Fmt("if(%s%s) break;", negate, idName(decoded.condition).c_str());
}
else
{
if(strings[otherLabel].empty())
dynamicNames[otherLabel] = StringFormat::Fmt("_continue%u", otherLabel.value());
ret += StringFormat::Fmt("if(%s%s) goto %s;", negate,
idName(decoded.condition).c_str(),
idName(otherLabel).c_str());
printLabels.insert(otherLabel);
}
if(decoded.branchweights.size() == 2)
ret += StringFormat::Fmt(" [[true: %u, false: %u]]", decoded.branchweights[0],
decoded.branchweights[1]);
ret += "\n";
lineNum++;
}
else
{
const char *negate = (decoded.falseLabel == decodedlabel.result) ? "!" : "";
ret += indent;
ret += StringFormat::Fmt("if(%s%s) {", negate, idName(decoded.condition).c_str());
if(decoded.branchweights.size() == 2)
ret += StringFormat::Fmt(" [[true: %u, false: %u]]", decoded.branchweights[0],
decoded.branchweights[1]);
ret += "\n";
lineNum++;
// this isn't technically structured but it's easier to pretend that it is
// no else, the merge target is where we exit the 'if'
StructuredCFG cfg = {StructuredCFG::If};
cfg.headerBlock = currentBlock;
cfg.mergeTarget = otherLabel;
cfg.elseTarget = rdcspv::Id();
cfgStack.push_back(cfg);
indent += " ";
}
}
else
{
RDCWARN(
"Unexpected SPIR-V formulation - OpBranchConditional not followed by either true "
"or false block");
// this is legal. We just have to emit an if with gotos
ret += indent;
ret += StringFormat::Fmt(
"if(%s) { goto %s; } else { goto %s; }\n", idName(decoded.condition).c_str(),
idName(decoded.trueLabel).c_str(), idName(decoded.falseLabel).c_str());
lineNum++;
// need to print these labels now
printLabels.insert(decoded.trueLabel);
printLabels.insert(decoded.falseLabel);
}
continue;
}
// since we're eliding a lot of labels, simplify display of OpPhi
case Op::Phi:
{
OpPhi decoded(it);
ret += indent;
ret += declName(decoded.resultType, decoded.result);
ret += " = Phi(";
for(size_t i = 0; i < decoded.parents.size(); i++)
{
ret += idName(decoded.parents[i].first);
if(i + 1 < decoded.parents.size())
ret += ", ";
}
ret += ")";
break;
}
////////////////////////////////////////////////////////////////////////////////////////
// pretty printing unary instructions
////////////////////////////////////////////////////////////////////////////////////////
case Op::SNegate:
case Op::FNegate:
case Op::Not:
case Op::LogicalNot:
{
rdcstr opstr;
switch(it.opcode())
{
case Op::SNegate:
case Op::FNegate: opstr = "-"; break;
case Op::Not: opstr = "~"; break;
case Op::LogicalNot: opstr = "!"; break;
default: break;
}
// all of these operations share the same encoding
OpNot decoded(it);
ret += indent;
ret += declName(decoded.resultType, decoded.result);
ret += " = ";
ret += opstr;
ret += idName(decoded.operand);
break;
}
////////////////////////////////////////////////////////////////////////////////////////
// pretty printing binary instructions
////////////////////////////////////////////////////////////////////////////////////////
case Op::IAdd:
case Op::FAdd:
case Op::ISub:
case Op::FSub:
case Op::IMul:
case Op::FMul:
case Op::UDiv:
case Op::SDiv:
case Op::FDiv:
case Op::VectorTimesMatrix:
case Op::VectorTimesScalar:
case Op::MatrixTimesMatrix:
case Op::MatrixTimesVector:
case Op::MatrixTimesScalar:
case Op::ShiftLeftLogical:
case Op::BitwiseAnd:
case Op::BitwiseOr:
case Op::BitwiseXor:
case Op::LogicalEqual:
case Op::LogicalNotEqual:
case Op::LogicalOr:
case Op::LogicalAnd:
case Op::IEqual:
case Op::INotEqual:
case Op::UGreaterThan:
case Op::SGreaterThan:
case Op::UGreaterThanEqual:
case Op::SGreaterThanEqual:
case Op::ULessThan:
case Op::SLessThan:
case Op::ULessThanEqual:
case Op::SLessThanEqual:
case Op::FOrdEqual:
case Op::FUnordEqual:
case Op::FOrdNotEqual:
case Op::FUnordNotEqual:
case Op::FOrdGreaterThan:
case Op::FUnordGreaterThan:
case Op::FOrdGreaterThanEqual:
case Op::FUnordGreaterThanEqual:
case Op::FOrdLessThan:
case Op::FUnordLessThan:
case Op::FOrdLessThanEqual:
case Op::FUnordLessThanEqual:
{
// all of these operations share the same encoding
OpIMul decoded(it);
ret += indent;
ret += declName(decoded.resultType, decoded.result);
ret += " = ";
ret += StringiseBinaryOperation(idName, it.opcode(), decoded.operand1, decoded.operand2);
break;
}
// right shifts must be done as a particular type
case Op::ShiftRightLogical:
case Op::ShiftRightArithmetic:
{
// these operations share the same encoding
OpShiftRightLogical decoded(it);
bool signedOp = (it.opcode() == Op::ShiftRightArithmetic);
ret += indent;
ret += declName(decoded.resultType, decoded.result);
ret += " = ";
if(signedOp != dataTypes[idTypes[decoded.base]].scalar().signedness)
{
ret += signedOp ? "signed(" : "unsigned(";
ret += idName(decoded.base);
ret += ")";
}
else
{
ret += idName(decoded.base);
}
ret += " >> ";
if(signedOp != dataTypes[idTypes[decoded.shift]].scalar().signedness)
{
ret += signedOp ? "signed(" : "unsigned(";
ret += idName(decoded.shift);
ret += ")";
}
else
{
ret += idName(decoded.shift);
}
break;
}
////////////////////////////////////////////////////////////////////////////////////////
// pretty printing misc instructions
////////////////////////////////////////////////////////////////////////////////////////
// write loads and stores as assignment via pointer
case Op::Load:
{
OpLoad decoded(it);
ret += indent;
ret += declName(decoded.resultType, decoded.result);
ret += " = *" + idName(decoded.pointer);
if(decoded.memoryAccess != MemoryAccess::None)
ret += " [" + ParamToStr(idName, decoded.memoryAccess) + "]";
ret += getDecorationString(decorations[decoded.result]);
break;
}
case Op::Store:
{
OpStore decoded(it);
ret += indent;
ret += StringFormat::Fmt("*%s = %s", idName(decoded.pointer).c_str(),
idName(decoded.object).c_str());
if(decoded.memoryAccess != MemoryAccess::None)
ret += " [" + ParamToStr(idName, decoded.memoryAccess) + "]";
break;
}
// returns as a conventional return
case Op::Return:
{
ret += indent + "return";
break;
}
case Op::ReturnValue:
{
OpReturnValue decoded(it);
ret += indent + StringFormat::Fmt("return %s", idName(decoded.value).c_str());
break;
}
case Op::FunctionCall:
{
OpFunctionCall decoded(it);
ret += indent;
if(dataTypes[decoded.resultType].scalar().type != Op::TypeVoid)
{
ret += declName(decoded.resultType, decoded.result);
ret += " = ";
}
rdcstr name = idName(decoded.function);
// glslang outputs encoded type information in the OpName of functions, strip it
{
int32_t offs = name.indexOf('(');
if(offs > 0)
name.erase(offs, name.size() - offs);
}
ret += name + "(";
for(size_t i = 0; i < decoded.arguments.size(); i++)
{
ret += idName(decoded.arguments[i]);
if(i + 1 < decoded.arguments.size())
ret += ", ";
}
ret += ")";
break;
}
// decode OpCompositeExtract and OpAccesschain as best as possible
case Op::CompositeExtract:
{
OpCompositeExtract decoded(it);
ret += indent;
ret += declName(decoded.resultType, decoded.result);
ret += " = " + idName(decoded.composite);
const DataType *type = &dataTypes[idTypes[decoded.composite]];
for(size_t i = 0; i < decoded.indexes.size(); i++)
{
uint32_t idx = decoded.indexes[i];
ret += accessor(type, idx, rdcstr());
if(type->type == DataType::ArrayType || type->type == DataType::MatrixType ||
type->type == DataType::VectorType)
{
type = &dataTypes[type->InnerType()];
}
else if(type->type == DataType::StructType)
{
RDCASSERT(idx < type->children.size());
type = &dataTypes[type->children[idx].type];
}
}
ret += getDecorationString(decorations[decoded.result]);
break;
}
case Op::AccessChain:
{
OpAccessChain decoded(it);
ret += indent;
ret += declName(decoded.resultType, decoded.result);
ret += " = &" + idName(decoded.base);
const DataType *type = &dataTypes[idTypes[decoded.base]];
// base should be a pointer
RDCASSERT(type->type == DataType::PointerType);
type = &dataTypes[type->InnerType()];
size_t i = 0;
for(; i < decoded.indexes.size(); i++)
{
int32_t idx = -1;
// if it's a non-specialised constant, get its value
if(constants.find(decoded.indexes[i]) != constants.end() &&
specConstants.find(decoded.indexes[i]) == specConstants.end())
idx = EvaluateConstant(decoded.indexes[i], {}).value.i.x;
// if it's a struct we must have an OpConstant to use, if it's a vector and we did get a
// constant then do better than a basic array index syntax.
if(type->type == DataType::StructType || (type->type == DataType::VectorType && idx >= 0))
{
// index must be an OpConstant when indexing into a structure
RDCASSERT(idx >= 0);
ret += accessor(type, idx, rdcstr());
}
else
{
RDCASSERT(type->type == DataType::ArrayType || type->type == DataType::MatrixType ||
type->type == DataType::VectorType,
(uint32_t)type->type);
ret += StringFormat::Fmt("[%s]", idName(decoded.indexes[i]).c_str());
}
if(type->type == DataType::ArrayType || type->type == DataType::MatrixType ||
type->type == DataType::VectorType)
{
type = &dataTypes[type->InnerType()];
}
else if(type->type == DataType::StructType)
{
RDCASSERT((size_t)idx < type->children.size());
type = &dataTypes[type->children[idx].type];
}
}
ret += getDecorationString(decorations[decoded.result]);
break;
}
// handle vector shuffle
case Op::VectorShuffle:
{
OpVectorShuffle decoded(it);
ret += indent;
ret += StringFormat::Fmt("%s = ", declName(decoded.resultType, decoded.result).c_str());
// it's common to only swizzle from the first vector, detect that case
bool allFirst = true;
for(uint32_t c : decoded.components)
if(c >= 4)
allFirst = false;
const char comps[] = "xyzw";
if(allFirst)
{
ret += idName(decoded.vector1) + ".";
for(uint32_t c : decoded.components)
ret.push_back(comps[c]);
}
else
{
ret += declName(decoded.resultType, Id()) + "(";
for(size_t i = 0; i < decoded.components.size(); i++)
{
uint32_t c = decoded.components[i];
ret += idName(c < 4 ? decoded.vector1 : decoded.vector2) + ".";
ret.push_back(comps[c % 4]);
if(i + 1 < decoded.components.size())
ret += ", ";
}
ret += ")";
}
break;
}
// need to handle this by hand anyway
case Op::ExtInst:
{
OpDecoder decoded(it);
ret += indent;
ret += StringFormat::Fmt("%s = ", declName(decoded.resultType, decoded.result).c_str());
rdcstr setname = extSets.find(Id::fromWord(it.word(3)))->second;
uint32_t inst = it.word(4);
const bool IsGLSL450 = (setname == "GLSL.std.450");
// GLSL.std.450 all parameters are Ids
const bool idParams = IsGLSL450 || setname.beginsWith("NonSemantic.");
if(IsGLSL450)
ret += StringFormat::Fmt("%s::%s(", setname.c_str(), ToStr(GLSLstd450(inst)).c_str());
else
ret += StringFormat::Fmt("%s::[%u](", setname.c_str(), inst);
for(size_t i = 5; i < it.size(); i++)
{
// TODO could generate this from the instruction set grammar.
ret += idParams ? idName(Id::fromWord(it.word(i))) : ToStr(it.word(i));
if(i + 1 < it.size())
ret += ", ";
}
ret += ")";
break;
}
default:
{
ret += indent;
ret += OpDecoder::Disassemble(it, declName, idName, constIntVal);
OpDecoder decoded(it);
if(decoded.result != Id())
ret += getDecorationString(decorations[decoded.result]);
}
}
ret += ";\n";
lineNum++;
}
ret += "\n";
lineNum++;
}
return ret;
}
rdcstr Reflector::StringiseConstant(rdcspv::Id id) const
{
// only stringise constants
auto cit = constants.find(id);
if(cit == constants.end())
return rdcstr();
// don't stringise spec constants either
if(specConstants.find(id) != specConstants.end())
return rdcstr();
const DataType &type = dataTypes[cit->second.type];
const ShaderVariable &value = cit->second.value;
if(type.type == DataType::ScalarType)
{
if(type.scalar().type == Op::TypeBool)
return value.value.u.x ? "true" : "false";
switch(value.type)
{
case VarType::Unknown:
case VarType::Float:
case VarType::Half: return ToStr(value.value.f.x);
case VarType::Double: return ToStr(value.value.d.x);
case VarType::SInt:
case VarType::SShort:
case VarType::SByte: return ToStr(value.value.i.x);
case VarType::UInt:
case VarType::UShort:
case VarType::UByte: return ToStr(value.value.u.x);
case VarType::SLong: return ToStr(value.value.s64v[0]);
case VarType::ULong: return ToStr(value.value.u64v[0]);
}
}
else if(type.type == DataType::VectorType)
{
rdcstr ret = "{";
for(size_t i = 0; i < value.columns; i++)
{
switch(value.type)
{
case VarType::Unknown:
case VarType::Float:
case VarType::Half: ret += ToStr(value.value.fv[i]); break;
case VarType::Double: ret += ToStr(value.value.dv[i]); break;
case VarType::SInt:
case VarType::SShort:
case VarType::SByte: ret += ToStr(value.value.iv[i]); break;
case VarType::UInt:
case VarType::UShort:
case VarType::UByte: ret += ToStr(value.value.uv[i]); break;
case VarType::SLong: ret += ToStr(value.value.s64v[i]); break;
case VarType::ULong: ret += ToStr(value.value.u64v[i]); break;
}
if(i + 1 < value.columns)
ret += ", ";
}
ret += "}";
return ret;
}
return rdcstr();
}
}; // namespace rdcspv
| 33.609679 | 102 | 0.515382 | [
"object",
"vector"
] |
73d0618f7b138684421b7ebeeeb15a4e7e830205 | 3,928 | cpp | C++ | src/codegen/codegen_code.cpp | giulioborghesi/cl-compiler | 8c6633202af39ebb3d56d38bd405d5558afb7783 | [
"MIT"
] | null | null | null | src/codegen/codegen_code.cpp | giulioborghesi/cl-compiler | 8c6633202af39ebb3d56d38bd405d5558afb7783 | [
"MIT"
] | null | null | null | src/codegen/codegen_code.cpp | giulioborghesi/cl-compiler | 8c6633202af39ebb3d56d38bd405d5558afb7783 | [
"MIT"
] | null | null | null | #include <cool/codegen/codegen_code.h>
#include <cool/codegen/codegen_context.h>
#include <cool/codegen/codegen_helpers.h>
#include <cool/ir/class.h>
#include <cool/ir/expr.h>
namespace cool {
namespace {
/// Globally visible text labels
const std::vector<std::string> GLOBAL_LABELS = {"Main_init", "Main.main",
"Int_init", "String_init"};
/// \brief Get attribute offset
///
/// \param[in] symbolTable symbol table
/// \param[in] attributeID attribute ID
/// \return the attribute offset in bytes
template <typename SymbolTableT>
int32_t GetAttributeOffset(SymbolTableT *symbolTable,
const std::string &attributeID) {
auto position = symbolTable->get(attributeID).position;
return WORD_SIZE * position + OBJECT_CONTENT_OFFSET;
}
/// \brief Store the new attribute value in the object and reset the accumulator
/// register to self.
///
/// The new attribute value is expected to be stored in register $a0.
///
/// \param[in] offset attribute offset in bytes
/// \param[out] ios output stream
void StoreAttributeAndSetAccumulatorToSelf(const int32_t offset,
std::ostream *ios) {
emit_lw_instruction("$t0", "$fp", 0, ios);
emit_sw_instruction("$a0", "$t0", offset, ios);
emit_move_instruction("$a0", "$t0", ios);
}
} // namespace
Status CodegenObjectsInitPass::codegen(CodegenContext *context,
AttributeNode *node, std::ostream *ios) {
/// If attribute has an initialization expression, use it
if (node->initExpr()) {
auto symbolTable = context->symbolTable();
const int32_t offset = GetAttributeOffset(symbolTable, node->id());
node->initExpr()->generateCode(context, this, ios);
StoreAttributeAndSetAccumulatorToSelf(offset, ios);
}
return Status::Ok();
}
Status CodegenObjectsInitPass::codegen(CodegenContext *context, ClassNode *node,
std::ostream *ios) {
/// Set current class name in context and fetch symbol table
context->resetStackPosition();
context->setCurrentClassName(node->className());
auto symbolTable = context->symbolTable();
/// Generate init label. Nothing to do for built-in classes
emit_label(node->className() + "_init", ios);
if (node->builtIn() && node->className() != "String") {
emit_jump_and_link_instruction("$ra", ios);
return Status::Ok();
}
/// Load attributes in symbol table
for (auto attributeNode : node->attributes()) {
const size_t attributePosition = symbolTable->count();
IdentifierCodegenInfo attributeInfo(true, attributePosition);
symbolTable->addElement(attributeNode->id(), attributeInfo);
}
/// Push stack frame
PushStackFrame(context, ios);
/// Initialize parent class if needed
if (node->hasParentClass()) {
const std::string label = node->parentClassName() + "_init";
emit_jump_and_link_instruction(label, ios);
}
/// Initialize attributes
for (auto attribute : node->attributes()) {
attribute->generateCode(context, this, ios);
}
/// Restore calling stack frame and return control to caller
PopStackFrame(context, 0, ios);
emit_jump_register_instruction("$ra", ios);
/// Generate code for remaining methods
for (auto methodNode : node->methods()) {
methodNode->generateCode(context, this, ios);
}
return Status::Ok();
}
Status CodegenObjectsInitPass::codegen(CodegenContext *context,
ProgramNode *node, std::ostream *ios) {
/// Emit heap start
emit_label("heap_start", ios);
emit_word_data(0, ios);
/// Emit text directive
emit_directive(".text", ios);
/// Emit global declarations for text labels
for (const auto &label : GLOBAL_LABELS) {
emit_global_declaration(label, ios);
}
/// Traverse each class
return CodegenBasePass::codegen(context, node, ios);
}
} // namespace cool
| 32.733333 | 80 | 0.673625 | [
"object",
"vector"
] |
73d0dd4c85041b01ba42e15d940e9e2c04445f7c | 17,469 | cpp | C++ | src/LowerParallelTasks.cpp | knzivid/Halide | 9ab3566675408da8903e89710534cf97cead2e6f | [
"Apache-2.0"
] | 4,303 | 2015-01-02T12:04:37.000Z | 2022-03-31T11:35:06.000Z | src/LowerParallelTasks.cpp | knzivid/Halide | 9ab3566675408da8903e89710534cf97cead2e6f | [
"Apache-2.0"
] | 4,323 | 2015-01-01T13:31:25.000Z | 2022-03-31T22:43:57.000Z | src/LowerParallelTasks.cpp | knzivid/Halide | 9ab3566675408da8903e89710534cf97cead2e6f | [
"Apache-2.0"
] | 1,032 | 2015-01-12T12:50:16.000Z | 2022-03-28T01:55:11.000Z | #include "LowerParallelTasks.h"
#include <string>
#include "Argument.h"
#include "Closure.h"
#include "DebugArguments.h"
#include "ExprUsesVar.h"
#include "IRMutator.h"
#include "IROperator.h"
#include "Module.h"
#include "Param.h"
#include "Simplify.h"
namespace Halide {
namespace Internal {
namespace {
LoweredArgument make_scalar_arg(const std::string &name, const Type &type) {
return LoweredArgument(name, Argument::Kind::InputScalar, type, 0, ArgumentEstimates());
}
template<typename T>
LoweredArgument make_scalar_arg(const std::string &name) {
return make_scalar_arg(name, type_of<T>());
}
std::string task_debug_name(const std::pair<std::string, int> &prefix) {
if (prefix.second <= 1) {
return prefix.first;
} else {
return prefix.first + "_" + std::to_string(prefix.second - 1);
}
}
void add_fork(std::pair<std::string, int> &prefix) {
if (prefix.second == 0) {
prefix.first += ".fork";
}
prefix.second++;
}
void add_suffix(std::pair<std::string, int> &prefix, const std::string &suffix) {
if (prefix.second > 1) {
prefix.first += "_" + std::to_string(prefix.second - 1);
prefix.second = 0;
}
prefix.first += suffix;
}
// TODO(zvookin|abadams): This makes multiple passes over the
// IR to cover each node. (One tree walk produces the min
// thread count for all nodes, but we redo each subtree when
// compiling a given node.) Ideally we'd move to a lowering pass
// that converts our parallelism constructs to Call nodes, or
// direct hardware operations in some cases.
// Also, this code has to exactly mirror the logic in get_parallel_tasks.
// It would be better to do one pass on the tree and centralize the task
// deduction logic in one place.
class MinThreads : public IRVisitor {
using IRVisitor::visit;
std::pair<Stmt, int> skip_acquires(Stmt first) {
int count = 0;
while (first.defined()) {
const Acquire *acq = first.as<Acquire>();
if (acq == nullptr) {
break;
}
count++;
first = acq->body;
}
return {first, count};
}
void visit(const Fork *op) override {
int total_threads = 0;
int direct_acquires = 0;
// Take the sum of min threads across all
// cascaded Fork nodes.
const Fork *node = op;
while (node != nullptr) {
result = 0;
auto after_acquires = skip_acquires(node->first);
direct_acquires += after_acquires.second;
after_acquires.first.accept(this);
total_threads += result;
const Fork *continued_branches = node->rest.as<Fork>();
if (continued_branches == nullptr) {
result = 0;
after_acquires = skip_acquires(node->rest);
direct_acquires += after_acquires.second;
after_acquires.first.accept(this);
total_threads += result;
}
node = continued_branches;
}
if (direct_acquires == 0 && total_threads == 0) {
result = 0;
} else {
result = total_threads + 1;
}
}
void visit(const For *op) override {
result = 0;
if (op->for_type == ForType::Parallel) {
IRVisitor::visit(op);
if (result > 0) {
result += 1;
}
} else if (op->for_type == ForType::Serial) {
auto after_acquires = skip_acquires(op->body);
if (after_acquires.second > 0 &&
!expr_uses_var(op->body.as<Acquire>()->count, op->name)) {
after_acquires.first.accept(this);
result++;
} else {
IRVisitor::visit(op);
}
} else {
IRVisitor::visit(op);
}
}
// This is a "standalone" Acquire and will result in its own task.
// Treat it requiring one more thread than its body.
void visit(const Acquire *op) override {
result = 0;
auto after_inner_acquires = skip_acquires(op);
after_inner_acquires.first.accept(this);
result = result + 1;
}
void visit(const Block *op) override {
result = 0;
op->first.accept(this);
int result_first = result;
result = 0;
op->rest.accept(this);
result = std::max(result, result_first);
}
public:
int result = 0;
};
int calculate_min_threads(const Stmt &body) {
MinThreads min_threads;
body.accept(&min_threads);
return min_threads.result;
}
struct LowerParallelTasks : public IRMutator {
/** Codegen a call to do_parallel_tasks */
struct ParallelTask {
Stmt body;
struct SemAcquire {
Expr semaphore;
Expr count;
};
std::vector<SemAcquire> semaphores;
std::string loop_var;
Expr min, extent;
Expr serial;
std::string name;
};
using IRMutator::visit;
Stmt visit(const For *op) override {
const Acquire *acquire = op->body.as<Acquire>();
if (op->for_type == ForType::Parallel ||
(op->for_type == ForType::Serial &&
acquire &&
!expr_uses_var(acquire->count, op->name))) {
return do_as_parallel_task(op);
}
return IRMutator::visit(op);
}
Stmt visit(const Acquire *op) override {
return do_as_parallel_task(op);
}
Stmt visit(const Fork *op) override {
return do_as_parallel_task(op);
}
Stmt rewrite_parallel_tasks(const std::vector<ParallelTask> &tasks) {
Stmt body;
Closure closure;
for (const auto &t : tasks) {
Stmt s = t.body;
if (!t.loop_var.empty()) {
s = LetStmt::make(t.loop_var, 0, s);
}
closure.include(s);
}
// The same name can appear as a var and a buffer. Remove the var name in this case.
for (auto const &b : closure.buffers) {
closure.vars.erase(b.first);
}
int num_tasks = (int)(tasks.size());
std::vector<Expr> tasks_array_args;
tasks_array_args.reserve(num_tasks * 9);
std::string closure_name = unique_name("parallel_closure");
Expr closure_struct_allocation = closure.pack_into_struct();
Expr closure_struct = Variable::make(Handle(), closure_name);
const bool has_task_parent = !task_parents.empty() && task_parents.top_ref().defined();
Expr result;
for (int i = 0; i < num_tasks; i++) {
ParallelTask t = tasks[i];
const int min_threads = calculate_min_threads(t.body);
// Decide if we're going to call do_par_for or
// do_parallel_tasks. halide_do_par_for is simpler, but
// assumes a bunch of things. Programs that don't use async
// can also enter the task system via do_par_for.
const bool use_parallel_for = (num_tasks == 1 &&
min_threads == 0 &&
t.semaphores.empty() &&
!has_task_parent);
Expr closure_task_parent;
const std::string closure_arg_name = unique_name("closure_arg");
auto closure_arg = make_scalar_arg<uint8_t *>(closure_arg_name);
std::vector<LoweredArgument> closure_args(use_parallel_for ? 3 : 5);
closure_args[0] = make_scalar_arg<void *>("__user_context");
if (use_parallel_for) {
// The closure will be a halide_task_t, with arguments like:
//
// typedef int (*halide_task_t)(void *user_context, int task_number, uint8_t *closure);
//
closure_args[1] = make_scalar_arg<int32_t>(t.loop_var);
closure_args[2] = closure_arg;
// closure_task_parent remains undefined here.
} else {
// The closure will be a halide_loop_task_t, with arguments like:
//
// typedef int (*halide_loop_task_t)(void *user_context, int min, int extent, uint8_t *closure, void *task_parent);
//
const std::string closure_task_parent_name = unique_name("__task_parent");
closure_task_parent = Variable::make(type_of<void *>(), closure_task_parent_name);
// We peeled off a loop. Wrap a new loop around the body
// that just does the slice given by the arguments.
std::string loop_min_name = unique_name('t');
std::string loop_extent_name = unique_name('t');
if (!t.loop_var.empty()) {
t.body = For::make(t.loop_var,
Variable::make(Int(32), loop_min_name),
Variable::make(Int(32), loop_extent_name),
ForType::Serial,
DeviceAPI::None,
t.body);
} else {
internal_assert(is_const_one(t.extent));
}
closure_args[1] = make_scalar_arg<int32_t>(loop_min_name);
closure_args[2] = make_scalar_arg<int32_t>(loop_extent_name);
closure_args[3] = closure_arg;
closure_args[4] = make_scalar_arg<void *>(closure_task_parent_name);
}
{
ScopedValue<std::string> save_name(function_name, t.name);
task_parents.push(closure_task_parent);
t.body = mutate(t.body);
task_parents.pop();
}
const std::string new_function_name = c_print_name(unique_name(t.name), false);
{
Expr closure_arg_var = Variable::make(closure_struct_allocation.type(), closure_arg_name);
Stmt wrapped_body = closure.unpack_from_struct(closure_arg_var, t.body);
// TODO(zvookin): Figure out how we want to handle name mangling of closures.
// For now, the C++ backend makes them extern "C" so they have to be NameMangling::C.
LoweredFunc closure_func{new_function_name, closure_args, std::move(wrapped_body), LinkageType::External, NameMangling::C};
if (target.has_feature(Target::Debug)) {
debug_arguments(&closure_func, target);
}
closure_implementations.emplace_back(std::move(closure_func));
}
// Codegen will add user_context for us
// Prefix the function name with "::" as we would in C++ to make
// it clear we're talking about something in global scope in
// case some joker names an intermediate Func or Var the same
// name as the pipeline. This prefix works transparently in the
// C++ backend.
Expr new_function_name_arg = Variable::make(Handle(), "::" + new_function_name);
Expr closure_struct_arg = Cast::make(type_of<uint8_t *>(), closure_struct);
if (use_parallel_for) {
std::vector<Expr> args = {
std::move(new_function_name_arg),
t.min,
t.extent,
std::move(closure_struct_arg)};
result = Call::make(Int(32), "halide_do_par_for", args, Call::Extern);
} else {
const int semaphores_size = (int)t.semaphores.size();
std::vector<Expr> semaphore_args(semaphores_size * 2);
for (int i = 0; i < semaphores_size; i++) {
semaphore_args[i * 2] = t.semaphores[i].semaphore;
semaphore_args[i * 2 + 1] = t.semaphores[i].count;
}
Expr semaphores_array = Call::make(type_of<halide_semaphore_acquire_t *>(), Call::make_struct, semaphore_args, Call::PureIntrinsic);
tasks_array_args.emplace_back(std::move(new_function_name_arg));
tasks_array_args.emplace_back(std::move(closure_struct_arg));
tasks_array_args.emplace_back(StringImm::make(t.name));
tasks_array_args.emplace_back(std::move(semaphores_array));
tasks_array_args.emplace_back((int)t.semaphores.size());
tasks_array_args.emplace_back(t.min);
tasks_array_args.emplace_back(t.extent);
tasks_array_args.emplace_back(min_threads);
tasks_array_args.emplace_back(Cast::make(Bool(), t.serial));
}
}
if (!tasks_array_args.empty()) {
// Allocate task list array
Expr tasks_list = Call::make(Handle(), Call::make_struct, tasks_array_args, Call::PureIntrinsic);
Expr user_context = Call::make(type_of<void *>(), Call::get_user_context, {}, Call::PureIntrinsic);
Expr task_parent = has_task_parent ? task_parents.top() : make_zero(Handle());
result = Call::make(Int(32), "halide_do_parallel_tasks",
{user_context, make_const(Int(32), num_tasks), tasks_list, task_parent},
Call::Extern);
}
std::string closure_result_name = unique_name("closure_result");
Expr closure_result = Variable::make(Int(32), closure_result_name);
Stmt stmt = AssertStmt::make(closure_result == 0, closure_result);
stmt = LetStmt::make(closure_result_name, result, stmt);
stmt = LetStmt::make(closure_name, closure_struct_allocation, stmt);
return stmt;
}
void get_parallel_tasks(const Stmt &s, std::vector<ParallelTask> &result, std::pair<std::string, int> prefix) {
const For *loop = s.as<For>();
const Acquire *acquire = loop ? loop->body.as<Acquire>() : s.as<Acquire>();
if (const Fork *f = s.as<Fork>()) {
add_fork(prefix);
get_parallel_tasks(f->first, result, prefix);
get_parallel_tasks(f->rest, result, prefix);
} else if (!loop && acquire) {
const Variable *v = acquire->semaphore.as<Variable>();
internal_assert(v);
add_suffix(prefix, "." + v->name);
ParallelTask t{s, {}, "", 0, 1, const_false(), task_debug_name(prefix)};
while (acquire) {
t.semaphores.push_back({acquire->semaphore, acquire->count});
t.body = acquire->body;
acquire = t.body.as<Acquire>();
}
result.emplace_back(std::move(t));
} else if (loop && loop->for_type == ForType::Parallel) {
add_suffix(prefix, ".par_for." + loop->name);
ParallelTask t{loop->body, {}, loop->name, loop->min, loop->extent, const_false(), task_debug_name(prefix)};
result.emplace_back(std::move(t));
} else if (loop &&
loop->for_type == ForType::Serial &&
acquire &&
!expr_uses_var(acquire->count, loop->name)) {
const Variable *v = acquire->semaphore.as<Variable>();
internal_assert(v);
add_suffix(prefix, ".for." + v->name);
ParallelTask t{loop->body, {}, loop->name, loop->min, loop->extent, const_true(), task_debug_name(prefix)};
while (acquire) {
t.semaphores.push_back({acquire->semaphore, acquire->count});
t.body = acquire->body;
acquire = t.body.as<Acquire>();
}
result.emplace_back(std::move(t));
} else {
add_suffix(prefix, "." + std::to_string(result.size()));
ParallelTask t{s, {}, "", 0, 1, const_false(), task_debug_name(prefix)};
result.emplace_back(std::move(t));
}
}
Stmt do_as_parallel_task(const Stmt &s) {
std::vector<ParallelTask> tasks;
get_parallel_tasks(s, tasks, {function_name, 0});
return rewrite_parallel_tasks(tasks);
}
LowerParallelTasks(const std::string &name, const Target &t)
: function_name(name), target(t) {
}
std::string function_name;
const Target ⌖
std::vector<LoweredFunc> closure_implementations;
SmallStack<Expr> task_parents;
};
} // namespace
Stmt lower_parallel_tasks(const Stmt &s, std::vector<LoweredFunc> &closure_implementations,
const std::string &name, const Target &t) {
LowerParallelTasks lowering_mutator(name, t);
Stmt result = lowering_mutator.mutate(s);
// Main body will be dumped as part of standard lowering debugging, but closures will not be.
if (debug::debug_level() >= 2) {
for (const auto &lf : lowering_mutator.closure_implementations) {
debug(2) << "lower_parallel_tasks generated closure lowered function " << lf.name << ":\n"
<< lf.body << "\n\n";
}
}
// Append to the end rather than replacing the list entirely.
closure_implementations.insert(closure_implementations.end(),
lowering_mutator.closure_implementations.begin(),
lowering_mutator.closure_implementations.end());
return result;
}
} // namespace Internal
} // namespace Halide
| 39.612245 | 148 | 0.57187 | [
"vector"
] |
73d21b517e20b52316cc247f443666df4e851d3e | 2,217 | cc | C++ | epi/group_equal_entries.cc | Vasniktel/interview-problems | ab901397194c81debe8c964fca097287466c9c27 | [
"MIT"
] | null | null | null | epi/group_equal_entries.cc | Vasniktel/interview-problems | ab901397194c81debe8c964fca097287466c9c27 | [
"MIT"
] | null | null | null | epi/group_equal_entries.cc | Vasniktel/interview-problems | ab901397194c81debe8c964fca097287466c9c27 | [
"MIT"
] | null | null | null | #include <iterator>
#include <set>
#include <string>
#include <vector>
#include "test_framework/generic_test.h"
#include "test_framework/serialization_traits.h"
#include "test_framework/test_failure.h"
#include "test_framework/timed_executor.h"
using std::string;
using std::vector;
struct Person {
int age;
string name;
};
void GroupByAge(vector<Person>* people) {
auto& arr = *people;
int max = std::max_element(arr.begin(), arr.end(), [](const auto& a, const auto& b) {
return a.age < b.age;
})->age;
vector<int> ages(max + 2);
for (const auto& person : arr) ages[person.age + 1]++;
std::partial_sum(ages.begin(), ages.end(), ages.begin());
auto count = ages;
for (int i = 0; i <= max;) {
if (count[i] == ages[i + 1]) {
i++;
continue;
}
for (auto& person = arr[count[i]]; person.age != i;) {
std::swap(person, arr[count[person.age]++]);
}
count[i]++;
}
}
template <>
struct SerializationTraits<Person> : UserSerTraits<Person, int, string> {};
void GroupByAgeWrapper(TimedExecutor& executor, vector<Person>& people) {
if (people.empty()) {
return;
}
std::multiset<Person, std::function<bool(Person, Person)>> values(
begin(people), end(people), [](const Person& a, const Person& b) {
return a.age == b.age ? a.name < b.name : a.age < b.age;
});
executor.Run([&] { GroupByAge(&people); });
if (people.empty()) {
throw TestFailure("Empty result");
}
std::set<int> ages;
int last_age = people[0].age;
for (auto& x : people) {
if (ages.count(x.age) != 0) {
throw TestFailure("Entries are not grouped by age");
}
if (x.age != last_age) {
ages.insert(last_age);
last_age = x.age;
}
auto it = values.find(x);
if (it == end(values)) {
throw TestFailure("Entry set changed");
}
values.erase(it);
}
}
int main(int argc, char* argv[]) {
std::vector<std::string> args{argv + 1, argv + argc};
std::vector<std::string> param_names{"executor", "people"};
return GenericTestMain(args, "group_equal_entries.cc",
"group_equal_entries.tsv", &GroupByAgeWrapper,
DefaultComparator{}, param_names);
}
| 26.082353 | 87 | 0.609382 | [
"vector"
] |
73d779fe7c1dcc83c459cbdb0086bdc027d2e0ee | 639 | cpp | C++ | dataset/test/modification/1461_code_insertion/49/transformation_1.cpp | Karina5005/Plagiarism | ce11f72ba21a754ca84a27e5f26a31a19d6cb6fb | [
"MIT"
] | 3 | 2022-02-15T00:29:39.000Z | 2022-03-15T08:36:44.000Z | dataset/test/modification/1461_code_insertion/49/transformation_1.cpp | Kira5005-code/Plagiarism | ce11f72ba21a754ca84a27e5f26a31a19d6cb6fb | [
"MIT"
] | null | null | null | dataset/test/modification/1461_code_insertion/49/transformation_1.cpp | Kira5005-code/Plagiarism | ce11f72ba21a754ca84a27e5f26a31a19d6cb6fb | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
#define el '\n'
#define pb push_back
#define fi first
#define se second
#define vi vector<int>
typedef long long ll;
void solve()
{
int n,k; cin>>n>>k;
if (5 > 3) cout << "new code";for(int i=0; i<n/3; i++) cout<<"abc";
if (5 > 3) cout << "new code";if(n%3==1) cout<<"a\n"; else if (5 > 3) cout << "new code";if(n%3==2) cout<<"ab\n"; else if (5 > 3) cout << "new code";if(n%3==0) cout<<el;
}
int main()
{
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
int q; cin>>q;
if (5 > 3) cout << "new code";while (q--) solve();
return 0;
} | 22.034483 | 174 | 0.543036 | [
"vector"
] |
73de6cd55dc627ccfe0e658a8b3ec935efdecbbe | 551 | hpp | C++ | labs/lab4/solution/regression.hpp | battibass/pf2021 | 7d370d26a53588c3168b57614e34e0dda70f5bbf | [
"CC-BY-4.0"
] | 7 | 2021-10-20T08:43:46.000Z | 2022-03-26T14:18:19.000Z | labs/lab4/solution/regression.hpp | battibass/pf2021 | 7d370d26a53588c3168b57614e34e0dda70f5bbf | [
"CC-BY-4.0"
] | null | null | null | labs/lab4/solution/regression.hpp | battibass/pf2021 | 7d370d26a53588c3168b57614e34e0dda70f5bbf | [
"CC-BY-4.0"
] | 10 | 2021-10-01T13:49:56.000Z | 2022-03-29T10:28:06.000Z | #ifndef REGRESSION_HPP
#define REGRESSION_HPP
#include <iostream>
#include <vector>
struct Result {
double A;
double B;
};
struct Point {
double x;
double y;
};
bool operator==(Point const& l, Point const& r);
bool operator!=(Point const& l, Point const& r);
std::ostream& operator<<(std::ostream& os, Point const& p);
class Regression {
std::vector<Point> points_{};
public:
int size() const;
void add(double x, double y);
bool remove(double x, double y);
Result fit() const;
};
Result fit(Regression const& reg);
#endif
| 15.305556 | 59 | 0.676951 | [
"vector"
] |
73e373cd9cea0f0c3ee95214f824e0d57f4643cb | 3,163 | cc | C++ | modules/audio_coding/codecs/red/audio_encoder_copy_red.cc | PersonifyInc/chromium_webrtc | cbe631e63f00ff1b2860891e06793f23244e8ae5 | [
"DOC",
"BSD-3-Clause"
] | null | null | null | modules/audio_coding/codecs/red/audio_encoder_copy_red.cc | PersonifyInc/chromium_webrtc | cbe631e63f00ff1b2860891e06793f23244e8ae5 | [
"DOC",
"BSD-3-Clause"
] | null | null | null | modules/audio_coding/codecs/red/audio_encoder_copy_red.cc | PersonifyInc/chromium_webrtc | cbe631e63f00ff1b2860891e06793f23244e8ae5 | [
"DOC",
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/modules/audio_coding/codecs/red/audio_encoder_copy_red.h"
#include <string.h>
namespace webrtc {
AudioEncoderCopyRed::AudioEncoderCopyRed(const Config& config)
: speech_encoder_(config.speech_encoder),
red_payload_type_(config.payload_type),
secondary_allocated_(0) {
CHECK(speech_encoder_) << "Speech encoder not provided.";
}
AudioEncoderCopyRed::~AudioEncoderCopyRed() {
}
int AudioEncoderCopyRed::sample_rate_hz() const {
return speech_encoder_->sample_rate_hz();
}
int AudioEncoderCopyRed::num_channels() const {
return speech_encoder_->num_channels();
}
int AudioEncoderCopyRed::Num10MsFramesInNextPacket() const {
return speech_encoder_->Num10MsFramesInNextPacket();
}
int AudioEncoderCopyRed::Max10MsFramesInAPacket() const {
return speech_encoder_->Max10MsFramesInAPacket();
}
bool AudioEncoderCopyRed::EncodeInternal(uint32_t timestamp,
const int16_t* audio,
size_t max_encoded_bytes,
uint8_t* encoded,
EncodedInfo* info) {
if (!speech_encoder_->Encode(timestamp, audio,
static_cast<size_t>(sample_rate_hz() / 100),
max_encoded_bytes, encoded, info))
return false;
if (max_encoded_bytes < info->encoded_bytes + secondary_info_.encoded_bytes)
return false;
CHECK(info->redundant.empty()) << "Cannot use nested redundant encoders.";
if (info->encoded_bytes > 0) {
// |info| will be implicitly cast to an EncodedInfoLeaf struct, effectively
// discarding the (empty) vector of redundant information. This is
// intentional.
info->redundant.push_back(*info);
DCHECK_EQ(info->redundant.size(), 1u);
if (secondary_info_.encoded_bytes > 0) {
memcpy(&encoded[info->encoded_bytes], secondary_encoded_.get(),
secondary_info_.encoded_bytes);
info->redundant.push_back(secondary_info_);
DCHECK_EQ(info->redundant.size(), 2u);
}
// Save primary to secondary.
if (secondary_allocated_ < info->encoded_bytes) {
secondary_encoded_.reset(new uint8_t[info->encoded_bytes]);
secondary_allocated_ = info->encoded_bytes;
}
CHECK(secondary_encoded_);
memcpy(secondary_encoded_.get(), encoded, info->encoded_bytes);
secondary_info_ = *info;
}
// Update main EncodedInfo.
info->payload_type = red_payload_type_;
info->encoded_bytes = 0;
for (std::vector<EncodedInfoLeaf>::const_iterator it =
info->redundant.begin();
it != info->redundant.end(); ++it) {
info->encoded_bytes += it->encoded_bytes;
}
return true;
}
} // namespace webrtc
| 35.539326 | 79 | 0.679102 | [
"vector"
] |
73e39b0f76f84ccb4f3b8f634b37c2c8ddf58c2f | 3,934 | cpp | C++ | protos/srm/2.1/n/n_srmCheckPermission.cpp | dCache/s2 | b84ce6a17b9fe36f0f7edf4615c5fc2dd925dd53 | [
"BSD-3-Clause"
] | null | null | null | protos/srm/2.1/n/n_srmCheckPermission.cpp | dCache/s2 | b84ce6a17b9fe36f0f7edf4615c5fc2dd925dd53 | [
"BSD-3-Clause"
] | 4 | 2016-05-13T09:45:31.000Z | 2018-02-18T10:11:32.000Z | protos/srm/2.1/n/n_srmCheckPermission.cpp | dCache/s2 | b84ce6a17b9fe36f0f7edf4615c5fc2dd925dd53 | [
"BSD-3-Clause"
] | 1 | 2018-02-18T09:26:49.000Z | 2018-02-18T09:26:49.000Z | #ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <sys/types.h>
#ifdef DG_DIAGNOSE
#include "diagnose/dg.h"
#endif
#include "n_srm.h"
#include "srm2api.h"
#include "srm_soap27.h"
#include "constants.h"
#include "i18.h"
#include "sysdep.h" /* BOOL, STD_BUF, ... */
#include "free.h" /* FREE(), DELETE() */
#include "str.h" /* dq_param() */
#include <iostream> /* std::string, cout, endl, ... */
#include <sstream> /* ostringstream */
using namespace std;
/*
* srmCheckPermission request constuctor
*/
srmCheckPermission::srmCheckPermission()
{
init();
}
/*
* Initialise srmCheckPermission request
*/
void
srmCheckPermission::init()
{
/* request (parser/API) */
checkInLocalCacheOnly = NULL;
/* response (parser) */
permissions = NULL;
}
/*
* srmCheckPermission request copy constuctor
*/
srmCheckPermission::srmCheckPermission(Node &node)
{
init();
Node::init(node);
}
/*
* srmCheckPermission request destructor
*/
srmCheckPermission::~srmCheckPermission()
{
DM_DBG_I;
/* request (parser/API) */
DELETE_VEC(path.SURLOrStFN);
DELETE_VEC(path.storageSystemInfo);
DELETE(checkInLocalCacheOnly);
/* response (parser) */
DELETE(permissions);
DM_DBG_O;
}
/*
* Free process-related structures.
*/
void
srmCheckPermission::finish(Process *proc)
{
DM_DBG_I;
FREE_SRM_RET(CheckPermission);
}
int
srmCheckPermission::exec(Process *proc)
{
#define EVAL_VEC_STR_CHP(vec) vec = proc->eval_vec_str(srmCheckPermission::vec)
DM_DBG_I;
BOOL match = FALSE;
tSurlInfoArray path;
EVAL_VEC_STR_CHP(path.SURLOrStFN);
EVAL_VEC_STR_CHP(path.storageSystemInfo);
#ifdef SRM2_CALL
NEW_SRM_RET(CheckPermission);
CheckPermission(
soap,
EVAL2CSTR(srm_endpoint),
EVAL2CSTR(userID),
path,
(bool *)proc->eval2pint32(checkInLocalCacheOnly).p,
resp
);
#endif
DELETE_VEC(path.SURLOrStFN);
DELETE_VEC(path.storageSystemInfo);
/* matching */
if(!resp || !resp->srmCheckPermissionResponse) {
DM_LOG(DM_N(1), "no SRM response\n");
RETURN(ERR_ERR);
}
/* arrayOfFileStatus */
match = proc->e_match(permissions, arrayOfFileStatusToString(proc, FALSE, FALSE).c_str());
if(!match) {
DM_LOG(DM_N(1), "no match\n");
RETURN(ERR_ERR);
}
RETURN(matchReturnStatus(resp->srmCheckPermissionResponse->returnStatus, proc));
#undef EVAL_VEC_STR_CHP
}
std::string
srmCheckPermission::toString(Process *proc)
{
#define EVAL_VEC_STR_CHP(vec) EVAL_VEC_STR(srmCheckPermission,vec)
DM_DBG_I;
GET_SRM_RESP(CheckPermission);
BOOL quote = TRUE;
std::stringstream ss;
tArrayOfPutFileRequests_ path;
EVAL_VEC_STR_CHP(path.SURLOrStFN);
EVAL_VEC_STR_CHP(path.storageSystemInfo);
/* request */
SS_SRM("srmCheckPermission");
SS_P_DQ(userID);
SS_VEC_DEL(path.SURLOrStFN);
SS_VEC_DEL(path.storageSystemInfo);
SS_P_DQ(checkInLocalCacheOnly);
/* response (parser) */
SS_P_DQ(permissions);
SS_P_DQ(returnStatus.explanation);
SS_P_DQ(returnStatus.statusCode);
/* response (API) */
if(!resp || !resp->srmCheckPermissionResponse) RETURN(ss.str());
ss << arrayOfFileStatusToString(proc, TRUE, quote);
SS_P_SRM_RETSTAT(resp->srmCheckPermissionResponse);
RETURN(ss.str());
#undef EVAL_VEC_STR_CHP
}
std::string
srmCheckPermission::arrayOfFileStatusToString(Process *proc, BOOL space, BOOL quote) const
{
DM_DBG_I;
GET_SRM_RESP(CheckPermission);
std::stringstream ss;
if(!resp || !resp->srmCheckPermissionResponse) RETURN(ss.str());
if(resp->srmCheckPermissionResponse->arrayOfPermissions) {
BOOL print_space = FALSE;
std::vector<srm__TSURLPermissionReturn *> v = resp->srmCheckPermissionResponse->arrayOfPermissions->surlPermissionArray;
for(uint u = 0; u < v.size(); u++) {
SS_P_VEC_SRM_RETSTAT(status);
SS_P_VEC_PAR_VAL(surl);
SS_P_VEC_DPAR_PERMISSIONMODE(userPermission);
}
}
RETURN(ss.str());
}
| 20.489583 | 124 | 0.704881 | [
"vector"
] |
73e6f644d283e9fa3a53d6761ff02e7ec3cc7764 | 1,791 | cpp | C++ | src/BabylonCpp/src/core/logging/init_console_logger.cpp | sacceus/BabylonCpp | 94669cf7cbe3214ec6e905cbf249fa0c9daf6222 | [
"Apache-2.0"
] | 277 | 2017-05-18T08:27:10.000Z | 2022-03-26T01:31:37.000Z | src/BabylonCpp/src/core/logging/init_console_logger.cpp | sacceus/BabylonCpp | 94669cf7cbe3214ec6e905cbf249fa0c9daf6222 | [
"Apache-2.0"
] | 77 | 2017-09-03T15:35:02.000Z | 2022-03-28T18:47:20.000Z | src/BabylonCpp/src/core/logging/init_console_logger.cpp | sacceus/BabylonCpp | 94669cf7cbe3214ec6e905cbf249fa0c9daf6222 | [
"Apache-2.0"
] | 37 | 2017-03-30T03:36:24.000Z | 2022-01-28T08:28:36.000Z | #include <babylon/core/logging/init_console_logger.h>
#include <babylon/core/logging.h>
#include <memory>
#if _MSC_VER
#include <windows.h>
#endif
namespace BABYLON
{
namespace impl
{
struct ConsoleLogger
{
using log_message_t = SA::delegate<void(const BABYLON::LogMessage&)>;
static void onLogMessage(const BABYLON::LogMessage& logMessage)
{
printf("%s\n", logMessage.toString().c_str());
#if _MSC_VER
std::string msg_n = logMessage.toString() + "\n";
OutputDebugString(msg_n.c_str());
#endif
}
}; // end of struct ConsoleLogger
// global logger
std::unique_ptr<ConsoleLogger::log_message_t> gLogListenerDelegate;
void initConsoleLogger()
{
gLogListenerDelegate = std::make_unique<ConsoleLogger::log_message_t>(SA::delegate<void(
const BABYLON::LogMessage&)>::create<&ConsoleLogger::onLogMessage>());
static_assert(
std::is_same< std::unique_ptr<SA::delegate<void(const BABYLON::LogMessage&)>>,
decltype(gLogListenerDelegate)>::value,
"!");
// Intialize log levels
std::vector<std::pair<unsigned int, std::string>> _logLevels;
for (auto& logLevel : BABYLON::LogLevels::Levels) {
unsigned int logType = logLevel.first;
if ((logType != BABYLON::LogLevels::LEVEL_QUIET)
&& (logType != BABYLON::LogLevels::LEVEL_TRACE)) {
_logLevels.emplace_back(logLevel);
}
}
// Subscribe to channels
for (auto& logLevel : _logLevels) {
unsigned int logType = logLevel.first;
if (logType != BABYLON::LogLevels::LEVEL_QUIET) {
BABYLON::LoggerInstance().registerLogMessageListener(
logType, *gLogListenerDelegate);
}
}
}
} // namespace impl
void initConsoleLogger()
{
impl::initConsoleLogger();
}
} // namespace BABYLON | 27.136364 | 92 | 0.676717 | [
"vector"
] |
73e84e0e72d1a4f987af551d220331cd28c885ec | 6,800 | cc | C++ | mindspore/core/utils/trace_base.cc | Ascend/mindspore | 1509d3f848e6685660194d9f58646fc73ae0f0f0 | [
"Apache-2.0"
] | 5 | 2021-06-04T02:23:01.000Z | 2021-12-13T10:41:07.000Z | mindspore/core/utils/trace_base.cc | LaiYongqiang/mindspore | 1b7a38ccd86b55af50a0ea55c7f2f43813ed3e0e | [
"Apache-2.0"
] | null | null | null | mindspore/core/utils/trace_base.cc | LaiYongqiang/mindspore | 1b7a38ccd86b55af50a0ea55c7f2f43813ed3e0e | [
"Apache-2.0"
] | 1 | 2021-12-14T06:22:31.000Z | 2021-12-14T06:22:31.000Z | /**
* Copyright 2020-2021 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "utils/trace_base.h"
#include <vector>
#include <string>
#include <utility>
#include <algorithm>
#include "ir/graph_utils.h"
namespace mindspore {
namespace trace {
namespace {
std::vector<DebugInfoPtr> GetSourceCodeDebugInfoVec(DebugInfoPtr debug_info, bool is_debug = false) {
std::vector<DebugInfoPtr> debug_with_loc_vec;
while (debug_info != nullptr) {
if (is_debug || debug_info->location() != nullptr) {
debug_with_loc_vec.push_back(debug_info);
}
if (debug_info->trace_info() != nullptr) {
debug_info = debug_info->trace_info()->debug_info();
} else {
break;
}
}
return debug_with_loc_vec;
}
void ReplaceLinefeed(std::string *txt) {
MS_EXCEPTION_IF_NULL(txt);
std::vector<int> erases;
constexpr char cr = '\r';
constexpr char lf = '\n';
constexpr char slash = '/';
for (size_t i = 0; i < txt->length(); i++) {
if ((*txt)[i] == lf) {
(*txt)[i] = slash;
}
if ((*txt)[i] == cr) {
(*txt)[i] = slash;
if (i + 1 < txt->length() && (*txt)[i + 1] == lf) {
erases.emplace_back(i + 1);
i++;
}
}
}
constexpr auto n = 1;
std::reverse(erases.begin(), erases.end());
for (const auto &index : erases) {
txt->erase(index, n);
}
}
} // namespace
DebugInfoPtr GetSourceCodeDebugInfo(const DebugInfoPtr &info) {
auto debug_with_loc_vec = GetSourceCodeDebugInfoVec(info);
if (!debug_with_loc_vec.empty()) {
return debug_with_loc_vec[0];
} else {
return info;
}
}
std::string GetDebugInfo(const DebugInfoPtr &info, SourceLineTip tip) {
if (info == nullptr) {
return "";
}
auto src_info = GetSourceCodeDebugInfo(info);
if (src_info->location() != nullptr) {
return src_info->location()->ToString(tip);
}
return "";
}
// A trace info identifies a node transform, so we can trace the node transform through
// A link of trace info and debug info
std::string GetInfoWithAction(const std::vector<DebugInfoPtr> &info_vec, SourceLineTip tip) {
if (info_vec.empty()) {
return "";
}
if (info_vec.size() == 1) {
return info_vec[0]->location()->ToString(tip);
}
std::string traced_info = info_vec[0]->location()->ToString(tip);
for (size_t i = 1; i < info_vec.size(); i++) {
auto action_name = info_vec[i - 1]->trace_info()->GetActionBetweenNode(info_vec[i]);
if (action_name.empty()) {
break;
}
traced_info += action_name + info_vec[i]->location()->ToString(tip);
}
return traced_info;
}
std::string GetTracedDebugInfo(const DebugInfoPtr &info, SourceLineTip tip) {
if (info == nullptr) {
return "";
}
auto info_vec = GetSourceCodeDebugInfoVec(info);
if (info_vec.empty()) {
return "";
} else if (info_vec.size() == 1) {
return info_vec[0]->location()->ToString(tip);
} else if (info_vec.size() > 1) {
return GetInfoWithAction(info_vec, tip);
}
return "";
}
std::string GetDebugInfo(const DebugInfoPtr &info, const std::string &prefix, SourceLineTip tip) {
std::ostringstream oss;
if (info == nullptr) {
return "";
}
auto debug_info = GetTracedDebugInfo(info, tip);
if (tip == kSourceLineTipDiscard) {
std::replace(debug_info.begin(), debug_info.end(), '\r', '/');
std::replace(debug_info.begin(), debug_info.end(), '\n', '/');
}
oss << prefix << debug_info;
return oss.str();
}
std::string DumpSourceLines(const AnfNodePtr &node) {
auto vec_source = GetSourceLineList(node);
if (vec_source.empty()) {
return "";
}
std::ostringstream oss;
oss << "\n";
for (auto &src_info : vec_source) {
oss << src_info;
}
return oss.str();
}
std::string DumpSourceLines(AnfNode *node) {
if (node == nullptr) {
MS_LOG(WARNING) << "Node is null";
return "";
}
AnfNodePtr ptr = std::static_pointer_cast<AnfNode>(node->shared_from_this());
return DumpSourceLines(ptr);
}
void GetSourceLineFromDebugInfo(const DebugInfoPtr &debug_info, std::vector<std::string> *result) {
auto info_vec = GetSourceCodeDebugInfoVec(debug_info);
for (const auto &info : info_vec) {
MS_EXCEPTION_IF_NULL(info);
auto loc = info->location();
if (loc == nullptr) {
continue;
}
auto loc_str = loc->ToString(kSourceLineTipDiscard);
ReplaceLinefeed(&loc_str);
result->push_back(loc_str + "\n");
}
}
std::vector<std::string> GetSourceLineList(const AnfNodePtr &node) {
std::vector<std::string> result;
if (node == nullptr) {
MS_LOG(WARNING) << "Node is null";
return result;
}
GetSourceLineFromDebugInfo(node->debug_info(), &result);
if (!node->isa<CNode>()) {
return result;
}
auto cnode = node->cast<CNodePtr>();
auto primal_debug_infos = cnode->primal_debug_infos();
if (!primal_debug_infos.empty()) {
result.emplace_back("Corresponding forward node candidate:\n");
for (auto &primal_debug_info : primal_debug_infos) {
GetSourceLineFromDebugInfo(primal_debug_info, &result);
}
}
return result;
}
std::vector<LocationPtr> GetSourceLocationList(const AnfNodePtr &node) {
std::vector<LocationPtr> result;
if (node == nullptr) {
MS_LOG(WARNING) << "Node is null";
return result;
}
auto info_vec = GetSourceCodeDebugInfoVec(node->debug_info());
for (const auto &info : info_vec) {
MS_EXCEPTION_IF_NULL(info);
if (info->location() != nullptr) {
result.emplace_back(info->location());
}
}
return result;
}
std::string GetDebugTraceInfo(const AnfNodePtr &node, bool is_debug) {
if (node == nullptr) {
MS_LOG(WARNING) << "Node is null";
return "";
}
auto info_vec = GetSourceCodeDebugInfoVec(node->debug_info(), is_debug);
std::ostringstream oss;
for (const auto &info : info_vec) {
MS_EXCEPTION_IF_NULL(info);
auto trace_info = info->trace_info();
if (trace_info != nullptr) {
oss << trace_info->symbol() << "(" << trace_info->full_name() << ") ";
}
auto loc = info->location();
if (loc == nullptr) {
oss << "Location miss\n";
continue;
}
auto loc_str = loc->ToString(kSourceLineTipDiscard);
ReplaceLinefeed(&loc_str);
oss << loc_str << "\n";
}
return oss.str();
}
} // namespace trace
} // namespace mindspore
| 28.451883 | 101 | 0.655882 | [
"vector",
"transform"
] |
73f1c26bb179e1c46aa9a40721a861272b7765f0 | 35,873 | cpp | C++ | src/blend2d/blimagescale.cpp | dan-eicher/blend2d | 097f89cbaae699cb3ba67712c4d1c8ebad78b99c | [
"Zlib"
] | null | null | null | src/blend2d/blimagescale.cpp | dan-eicher/blend2d | 097f89cbaae699cb3ba67712c4d1c8ebad78b99c | [
"Zlib"
] | null | null | null | src/blend2d/blimagescale.cpp | dan-eicher/blend2d | 097f89cbaae699cb3ba67712c4d1c8ebad78b99c | [
"Zlib"
] | null | null | null | // [Blend2D]
// 2D Vector Graphics Powered by a JIT Compiler.
//
// [License]
// ZLIB - See LICENSE.md file in the package.
#include "./blapi-build_p.h"
#include "./blimagescale_p.h"
#include "./blmath_p.h"
#include "./blformat_p.h"
#include "./blgeometry_p.h"
#include "./blrgba_p.h"
#include "./blruntime_p.h"
#include "./blsupport_p.h"
// ============================================================================
// [BLImageScale - Global Variables]
// ============================================================================
static constexpr const BLImageScaleOptions blImageScaleOptionsNone = {
nullptr, // UserFunc.
nullptr, // UserData.
2.0, // Radius.
{{
1.0 / 3.0, // Mitchell B.
1.0 / 3.0, // Mitchell C.
0.0 // Reserved.
}}
};
// ============================================================================
// [BLImageScale - Ops]
// ============================================================================
struct BLImageScaleOps {
BLResult (BL_CDECL* weights)(BLImageScaleContext::Data* d, uint32_t dir, BLImageScaleUserFunc func, const void* data) BL_NOEXCEPT;
void (BL_CDECL* horz[BL_FORMAT_COUNT])(const BLImageScaleContext::Data* d, uint8_t* dstLine, intptr_t dstStride, const uint8_t* srcLine, intptr_t srcStride) BL_NOEXCEPT;
void (BL_CDECL* vert[BL_FORMAT_COUNT])(const BLImageScaleContext::Data* d, uint8_t* dstLine, intptr_t dstStride, const uint8_t* srcLine, intptr_t srcStride) BL_NOEXCEPT;
};
static BLImageScaleOps blImageScaleOps;
// ============================================================================
// [BLImageScale - BuiltInParams]
// ============================================================================
// Data needed by some functions that take additional parameters.
struct BLImageScaleBuiltInParams {
double radius;
struct Mitchell {
double p0, p2, p3;
double q0, q1, q2, q3;
} mitchell;
BL_INLINE void initMitchell(double b, double c) noexcept {
constexpr double k1Div3 = 1.0 / 3.0;
constexpr double k1Div6 = 1.0 / 6.0;
constexpr double k4Div3 = 4.0 / 3.0;
mitchell.p0 = 1.0 - k1Div3 * b;
mitchell.p2 = -3.0 + 2.0 * b + c;
mitchell.p3 = 2.0 - 1.5 * b - c;
mitchell.q0 = k4Div3 * b + c * 4.0;
mitchell.q1 = -2.0 * b - c * 8.0;
mitchell.q2 = b + c * 5.0;
mitchell.q3 = -k1Div6 * b - c;
}
};
// ============================================================================
// [BLImageScale - Utilities]
// ============================================================================
// Calculates a Bessel function of first kind of order `n`.
//
// Adapted for use in AGG library by Andy Wilk <castor.vulgaris@gmail.com>
static BL_INLINE double blBessel(double x, int n) noexcept {
double d = 1e-6;
double b0 = 0.0;
double b1 = 0.0;
if (blAbs(x) <= d)
return n != 0 ? 0.0 : 1.0;
// Set up a starting order for recurrence.
int m1 = blAbs(x) > 5.0 ? int(blAbs(1.4 * x + 60.0 / x)) : int(blAbs(x) + 6);
int m2 = blMax(int(blAbs(x)) / 4 + 2 + n, m1);
for (;;) {
double c2 = blEpsilon<double>();
double c3 = 0.0;
double c4 = 0.0;
int m8 = m2 & 1;
for (int i = 1, iEnd = m2 - 1; i < iEnd; i++) {
double c6 = 2 * (m2 - i) * c2 / x - c3;
c3 = c2;
c2 = c6;
if (m2 - i - 1 == n)
b1 = c6;
m8 ^= 1;
if (m8)
c4 += c6 * 2.0;
}
double c6 = 2.0 * c2 / x - c3;
if (n == 0)
b1 = c6;
c4 += c6;
b1 /= c4;
if (blAbs(b1 - b0) < d)
return b1;
b0 = b1;
m2 += 3;
}
}
static BL_INLINE double blSinXDivX(double x) noexcept {
return blSin(x) / x;
}
static BL_INLINE double blLanczos(double x, double y) noexcept {
return blSinXDivX(x) * blSinXDivX(y);
}
static BL_INLINE double blBlackman(double x, double y) noexcept {
return blSinXDivX(x) * (0.42 + 0.5 * blCos(y) + 0.08 * blCos(y * 2.0));
}
// ============================================================================
// [BLImageScale - Functions]
// ============================================================================
static BLResult BL_CDECL blImageScaleNearestFunc(double* dst, const double* tArray, size_t n, const void* data) noexcept {
BL_UNUSED(data);
for (size_t i = 0; i < n; i++) {
double t = tArray[i];
dst[i] = t <= 0.5 ? 1.0 : 0.0;
}
return BL_SUCCESS;
}
static BLResult BL_CDECL blImageScaleBilinearFunc(double* dst, const double* tArray, size_t n, const void* data) noexcept {
BL_UNUSED(data);
for (size_t i = 0; i < n; i++) {
double t = tArray[i];
dst[i] = t < 1.0 ? 1.0 - t : 0.0;
}
return BL_SUCCESS;
}
static BLResult BL_CDECL blImageScaleBicubicFunc(double* dst, const double* tArray, size_t n, const void* data) noexcept {
BL_UNUSED(data);
constexpr double k2Div3 = 2.0 / 3.0;
// 0.5t^3 - t^2 + 2/3 == (0.5t - 1.0) t^2 + 2/3
for (size_t i = 0; i < n; i++) {
double t = tArray[i];
dst[i] = t < 1.0 ? (t * 0.5 - 1.0) * blSquare(t) + k2Div3 :
t < 2.0 ? blPow3(2.0 - t) / 6.0 : 0.0;
}
return BL_SUCCESS;
}
static BLResult BL_CDECL blImageScaleBellFunc(double* dst, const double* tArray, size_t n, const void* data) noexcept {
BL_UNUSED(data);
for (size_t i = 0; i < n; i++) {
double t = tArray[i];
dst[i] = t < 0.5 ? 0.75 - blSquare(t) :
t < 1.5 ? 0.50 * blSquare(t - 1.5) : 0.0;
}
return BL_SUCCESS;
}
static BLResult BL_CDECL blImageScaleGaussFunc(double* dst, const double* tArray, size_t n, const void* data) noexcept {
BL_UNUSED(data);
constexpr double x = 0.7978845608; // sqrt(2 / PI);
for (size_t i = 0; i < n; i++) {
double t = tArray[i];
dst[i] = t <= 2.0 ? exp(blSquare(t) * -2.0) * x : 0.0;
}
return BL_SUCCESS;
}
static BLResult BL_CDECL blImageScaleHermiteFunc(double* dst, const double* tArray, size_t n, const void* data) noexcept {
BL_UNUSED(data);
for (size_t i = 0; i < n; i++) {
double t = tArray[i];
dst[i] = t < 1.0 ? (2.0 * t - 3.0) * blSquare(t) + 1.0 : 0.0;
}
return BL_SUCCESS;
}
static BLResult BL_CDECL blImageScaleHanningFunc(double* dst, const double* tArray, size_t n, const void* data) noexcept {
BL_UNUSED(data);
for (size_t i = 0; i < n; i++) {
double t = tArray[i];
dst[i] = t <= 1.0 ? 0.5 + 0.5 * blCos(t * BL_MATH_PI) : 0.0;
}
return BL_SUCCESS;
}
static BLResult BL_CDECL blImageScaleCatromFunc(double* dst, const double* tArray, size_t n, const void* data) noexcept {
BL_UNUSED(data);
for (size_t i = 0; i < n; i++) {
double t = tArray[i];
dst[i] = t < 1.0 ? 0.5 * (2.0 + t * t * (t * 3.0 - 5.0)) :
t < 2.0 ? 0.5 * (4.0 + t * (t * (5.0 - t) - 8.0)) : 0.0;
}
return BL_SUCCESS;
}
static BLResult BL_CDECL blImageScaleBesselFunc(double* dst, const double* tArray, size_t n, const void* data) noexcept {
BL_UNUSED(data);
constexpr double x = BL_MATH_PI * 0.25;
for (size_t i = 0; i < n; i++) {
double t = tArray[i];
dst[i] = t == 0.0 ? x : t <= 3.2383 ? blBessel(t * BL_MATH_PI, 1) / (2.0 * t) : 0.0;
}
return BL_SUCCESS;
}
static BLResult BL_CDECL blImageScaleSincFunc(double* dst, const double* tArray, size_t n, const void* data) noexcept {
const double r = static_cast<const BLImageScaleBuiltInParams*>(data)->radius;
for (size_t i = 0; i < n; i++) {
double t = tArray[i];
dst[i] = t == 0.0 ? 1.0 : t <= r ? blSinXDivX(t * BL_MATH_PI) : 0.0;
}
return BL_SUCCESS;
}
static BLResult BL_CDECL blImageScaleLanczosFunc(double* dst, const double* tArray, size_t n, const void* data) noexcept {
const double r = static_cast<const BLImageScaleBuiltInParams*>(data)->radius;
const double x = BL_MATH_PI;
const double y = BL_MATH_PI / r;
for (size_t i = 0; i < n; i++) {
double t = tArray[i];
dst[i] = t == 0.0 ? 1.0 : t <= r ? blLanczos(t * x, t * y) : 0.0;
}
return BL_SUCCESS;
}
static BLResult BL_CDECL blImageScaleBlackmanFunc(double* dst, const double* tArray, size_t n, const void* data) noexcept {
const double r = static_cast<const BLImageScaleBuiltInParams*>(data)->radius;
const double x = BL_MATH_PI;
const double y = BL_MATH_PI / r;
for (size_t i = 0; i < n; i++) {
double t = tArray[i];
dst[i] = t == 0.0 ? 1.0 : t <= r ? blBlackman(t * x, t * y) : 0.0;
}
return BL_SUCCESS;
}
static BLResult BL_CDECL blImageScaleMitchellFunc(double* dst, const double* tArray, size_t n, const void* data) noexcept {
const BLImageScaleBuiltInParams::Mitchell& p = static_cast<const BLImageScaleBuiltInParams*>(data)->mitchell;
for (size_t i = 0; i < n; i++) {
double t = tArray[i];
dst[i] = t < 1.0 ? p.p0 + blSquare(t) * (p.p2 + t * p.p3) :
t < 2.0 ? p.q0 + t * (p.q1 + t * (p.q2 + t * p.q3)) : 0.0;
}
return BL_SUCCESS;
}
// ============================================================================
// [BLImageScale - Weights]
// ============================================================================
static BLResult BL_CDECL blImageScaleWeights(BLImageScaleContext::Data* d, uint32_t dir, BLImageScaleUserFunc userFunc, const void* userData) noexcept {
int32_t* weightList = d->weightList[dir];
BLImageScaleContext::Record* recordList = d->recordList[dir];
int dstSize = d->dstSize[dir];
int srcSize = d->srcSize[dir];
int kernelSize = d->kernelSize[dir];
double radius = d->radius[dir];
double factor = d->factor[dir];
double scale = d->scale[dir];
int32_t isUnbound = 0;
BLMemBufferTmp<512> wMem;
double* wData = static_cast<double*>(wMem.alloc(kernelSize * sizeof(double)));
if (BL_UNLIKELY(!wData))
return blTraceError(BL_ERROR_OUT_OF_MEMORY);
for (int i = 0; i < dstSize; i++) {
double wPos = (double(i) + 0.5) / scale - 0.5;
double wSum = 0.0;
int left = int(wPos - radius);
int right = left + kernelSize;
int wIndex;
// Calculate all weights for the destination pixel.
wPos -= left;
for (wIndex = 0; wIndex < kernelSize; wIndex++, wPos -= 1.0) {
wData[wIndex] = blAbs(wPos * factor);
}
// User function can fail.
BL_PROPAGATE(userFunc(wData, wData, kernelSize, userData));
// Remove padded pixels from left and right.
wIndex = 0;
while (left < 0) {
double w = wData[wIndex];
wData[++wIndex] += w;
left++;
}
int wCount = kernelSize;
while (right > srcSize) {
BL_ASSERT(wCount > 0);
double w = wData[--wCount];
wData[wCount - 1] += w;
right--;
}
recordList[i].pos = 0;
recordList[i].count = 0;
if (wIndex < wCount) {
// Sum all weights.
int j;
for (j = wIndex; j < wCount; j++) {
double w = wData[j];
wSum += w;
}
int iStrongest = 0;
int32_t iSum = 0;
int32_t iMax = 0;
double wScale = 65535 / wSum;
for (j = wIndex; j < wCount; j++) {
int32_t w = int32_t(wData[j] * wScale) >> 8;
// Remove zero weight from the beginning of the list.
if (w == 0 && wIndex == j) {
wIndex++;
left++;
continue;
}
weightList[j - wIndex] = w;
iSum += w;
isUnbound |= w;
if (iMax < w) {
iMax = w;
iStrongest = j - wIndex;
}
}
// Normalize the strongest weight so the sum matches `0x100`.
if (iSum != 0x100)
weightList[iStrongest] += int32_t(0x100) - iSum;
// `wCount` is now absolute size of weights in `weightList`.
wCount -= wIndex;
// Remove all zero weights from the end of the weight array.
while (wCount > 0 && weightList[wCount - 1] == 0)
wCount--;
if (wCount) {
BL_ASSERT(left >= 0);
recordList[i].pos = left;
recordList[i].count = wCount;
}
}
weightList += kernelSize;
}
d->isUnbound[dir] = isUnbound < 0;
return BL_SUCCESS;
}
// ============================================================================
// [BLImageScale - Horz]
// ============================================================================
static void BL_CDECL blImageScaleHorzPrgb32(const BLImageScaleContext::Data* d, uint8_t* dstLine, intptr_t dstStride, const uint8_t* srcLine, intptr_t srcStride) noexcept {
int dw = d->dstSize[0];
int sh = d->srcSize[1];
int kernelSize = d->kernelSize[0];
if (!d->isUnbound[BLImageScaleContext::kDirHorz]) {
for (int y = 0; y < sh; y++) {
const BLImageScaleContext::Record* recordList = d->recordList[BLImageScaleContext::kDirHorz];
const int32_t* weightList = d->weightList[BLImageScaleContext::kDirHorz];
uint8_t* dp = dstLine;
for (int x = 0; x < dw; x++) {
const uint8_t* sp = srcLine + recordList->pos * 4;
const int32_t* wp = weightList;
uint32_t cr_cb = 0x00800080;
uint32_t ca_cg = 0x00800080;
for (int i = recordList->count; i; i--) {
uint32_t p0 = reinterpret_cast<const uint32_t*>(sp)[0];
uint32_t w0 = wp[0];
ca_cg += ((p0 >> 8) & 0x00FF00FF) * w0;
cr_cb += ((p0 ) & 0x00FF00FF) * w0;
sp += 4;
wp += 1;
}
reinterpret_cast<uint32_t*>(dp)[0] = (ca_cg & 0xFF00FF00) + ((cr_cb & 0xFF00FF00) >> 8);
recordList += 1;
weightList += kernelSize;
dp += 4;
}
dstLine += dstStride;
srcLine += srcStride;
}
}
else {
for (int y = 0; y < sh; y++) {
const BLImageScaleContext::Record* recordList = d->recordList[BLImageScaleContext::kDirHorz];
const int32_t* weightList = d->weightList[BLImageScaleContext::kDirHorz];
uint8_t* dp = dstLine;
for (int x = 0; x < dw; x++) {
const uint8_t* sp = srcLine + recordList->pos * 4;
const int32_t* wp = weightList;
int32_t ca = 0x80;
int32_t cr = 0x80;
int32_t cg = 0x80;
int32_t cb = 0x80;
for (int i = recordList->count; i; i--) {
uint32_t p0 = reinterpret_cast<const uint32_t*>(sp)[0];
int32_t w0 = wp[0];
ca += int32_t((p0 >> 24) ) * w0;
cr += int32_t((p0 >> 16) & 0xFF) * w0;
cg += int32_t((p0 >> 8) & 0xFF) * w0;
cb += int32_t((p0 ) & 0xFF) * w0;
sp += 4;
wp += 1;
}
ca = blClamp<int32_t>(ca >> 8, 0, 255);
cr = blClamp<int32_t>(cr >> 8, 0, ca);
cg = blClamp<int32_t>(cg >> 8, 0, ca);
cb = blClamp<int32_t>(cb >> 8, 0, ca);
reinterpret_cast<uint32_t*>(dp)[0] = blRgba32Pack(cr, cg, cb, ca);
recordList += 1;
weightList += kernelSize;
dp += 4;
}
dstLine += dstStride;
srcLine += srcStride;
}
}
}
static void BL_CDECL blImageScaleHorzXrgb32(const BLImageScaleContext::Data* d, uint8_t* dstLine, intptr_t dstStride, const uint8_t* srcLine, intptr_t srcStride) noexcept {
int dw = d->dstSize[0];
int sh = d->srcSize[1];
int kernelSize = d->kernelSize[0];
if (!d->isUnbound[BLImageScaleContext::kDirHorz]) {
for (int y = 0; y < sh; y++) {
const BLImageScaleContext::Record* recordList = d->recordList[BLImageScaleContext::kDirHorz];
const int32_t* weightList = d->weightList[BLImageScaleContext::kDirHorz];
uint8_t* dp = dstLine;
for (int x = 0; x < dw; x++) {
const uint8_t* sp = srcLine + recordList->pos * 4;
const int32_t* wp = weightList;
uint32_t cx_cg = 0x00008000;
uint32_t cr_cb = 0x00800080;
for (int i = recordList->count; i; i--) {
uint32_t p0 = reinterpret_cast<const uint32_t*>(sp)[0];
uint32_t w0 = wp[0];
cx_cg += (p0 & 0x0000FF00) * w0;
cr_cb += (p0 & 0x00FF00FF) * w0;
sp += 4;
wp += 1;
}
reinterpret_cast<uint32_t*>(dp)[0] = 0xFF000000 + (((cx_cg & 0x00FF0000) | (cr_cb & 0xFF00FF00)) >> 8);
recordList += 1;
weightList += kernelSize;
dp += 4;
}
dstLine += dstStride;
srcLine += srcStride;
}
}
else {
for (int y = 0; y < sh; y++) {
const BLImageScaleContext::Record* recordList = d->recordList[BLImageScaleContext::kDirHorz];
const int32_t* weightList = d->weightList[BLImageScaleContext::kDirHorz];
uint8_t* dp = dstLine;
for (int x = 0; x < dw; x++) {
const uint8_t* sp = srcLine + recordList->pos * 4;
const int32_t* wp = weightList;
int32_t cr = 0x80;
int32_t cg = 0x80;
int32_t cb = 0x80;
for (int i = recordList->count; i; i--) {
uint32_t p0 = reinterpret_cast<const uint32_t*>(sp)[0];
int32_t w0 = wp[0];
cr += int32_t((p0 >> 16) & 0xFF) * w0;
cg += int32_t((p0 >> 8) & 0xFF) * w0;
cb += int32_t((p0 ) & 0xFF) * w0;
sp += 4;
wp += 1;
}
cr = blClamp<int32_t>(cr >> 8, 0, 255);
cg = blClamp<int32_t>(cg >> 8, 0, 255);
cb = blClamp<int32_t>(cb >> 8, 0, 255);
reinterpret_cast<uint32_t*>(dp)[0] = blRgba32Pack(cr, cg, cb, 0xFF);
recordList += 1;
weightList += kernelSize;
dp += 4;
}
dstLine += dstStride;
srcLine += srcStride;
}
}
}
static void BL_CDECL blImageScaleHorzA8(const BLImageScaleContext::Data* d, uint8_t* dstLine, intptr_t dstStride, const uint8_t* srcLine, intptr_t srcStride) noexcept {
int dw = d->dstSize[0];
int sh = d->srcSize[1];
int kernelSize = d->kernelSize[0];
if (!d->isUnbound[BLImageScaleContext::kDirHorz]) {
for (int y = 0; y < sh; y++) {
const BLImageScaleContext::Record* recordList = d->recordList[BLImageScaleContext::kDirHorz];
const int32_t* weightList = d->weightList[BLImageScaleContext::kDirHorz];
uint8_t* dp = dstLine;
for (int x = 0; x < dw; x++) {
const uint8_t* sp = srcLine + recordList->pos * 1;
const int32_t* wp = weightList;
uint32_t ca = 0x80;
for (int i = recordList->count; i; i--) {
uint32_t p0 = sp[0];
uint32_t w0 = wp[0];
ca += p0 * w0;
sp += 1;
wp += 1;
}
dp[0] = uint8_t(ca >> 8);
recordList += 1;
weightList += kernelSize;
dp += 1;
}
dstLine += dstStride;
srcLine += srcStride;
}
}
else {
for (int y = 0; y < sh; y++) {
const BLImageScaleContext::Record* recordList = d->recordList[BLImageScaleContext::kDirHorz];
const int32_t* weightList = d->weightList[BLImageScaleContext::kDirHorz];
uint8_t* dp = dstLine;
for (int x = 0; x < dw; x++) {
const uint8_t* sp = srcLine + recordList->pos * 1;
const int32_t* wp = weightList;
int32_t ca = 0x80;
for (int i = recordList->count; i; i--) {
uint32_t p0 = sp[0];
int32_t w0 = wp[0];
ca += (int32_t)p0 * w0;
sp += 1;
wp += 1;
}
dp[0] = blClampToByte(ca >> 8);
recordList += 1;
weightList += kernelSize;
dp += 1;
}
dstLine += dstStride;
srcLine += srcStride;
}
}
}
// ============================================================================
// [BLImageScale - Vert]
// ============================================================================
static void BL_CDECL blImageScaleVertPrgb32(const BLImageScaleContext::Data* d, uint8_t* dstLine, intptr_t dstStride, const uint8_t* srcLine, intptr_t srcStride) noexcept {
int dw = d->dstSize[0];
int dh = d->dstSize[1];
int kernelSize = d->kernelSize[BLImageScaleContext::kDirVert];
const BLImageScaleContext::Record* recordList = d->recordList[BLImageScaleContext::kDirVert];
const int32_t* weightList = d->weightList[BLImageScaleContext::kDirVert];
if (!d->isUnbound[BLImageScaleContext::kDirVert]) {
for (int y = 0; y < dh; y++) {
const uint8_t* srcData = srcLine + intptr_t(recordList->pos) * srcStride;
uint8_t* dp = dstLine;
int count = recordList->count;
for (int x = 0; x < dw; x++) {
const uint8_t* sp = srcData;
const int32_t* wp = weightList;
uint32_t cr_cb = 0x00800080;
uint32_t ca_cg = 0x00800080;
for (int i = count; i; i--) {
uint32_t p0 = reinterpret_cast<const uint32_t*>(sp)[0];
uint32_t w0 = wp[0];
ca_cg += ((p0 >> 8) & 0x00FF00FF) * w0;
cr_cb += ((p0 ) & 0x00FF00FF) * w0;
sp += srcStride;
wp += 1;
}
reinterpret_cast<uint32_t*>(dp)[0] = (ca_cg & 0xFF00FF00) + ((cr_cb & 0xFF00FF00) >> 8);
dp += 4;
srcData += 4;
}
recordList += 1;
weightList += kernelSize;
dstLine += dstStride;
}
}
else {
for (int y = 0; y < dh; y++) {
const uint8_t* srcData = srcLine + intptr_t(recordList->pos) * srcStride;
uint8_t* dp = dstLine;
int count = recordList->count;
for (int x = 0; x < dw; x++) {
const uint8_t* sp = srcData;
const int32_t* wp = weightList;
int32_t ca = 0x80;
int32_t cr = 0x80;
int32_t cg = 0x80;
int32_t cb = 0x80;
for (int i = count; i; i--) {
uint32_t p0 = reinterpret_cast<const uint32_t*>(sp)[0];
int32_t w0 = wp[0];
ca += int32_t((p0 >> 24) ) * w0;
cr += int32_t((p0 >> 16) & 0xFF) * w0;
cg += int32_t((p0 >> 8) & 0xFF) * w0;
cb += int32_t((p0 ) & 0xFF) * w0;
sp += srcStride;
wp += 1;
}
ca = blClamp<int32_t>(ca >> 8, 0, 255);
cr = blClamp<int32_t>(cr >> 8, 0, ca);
cg = blClamp<int32_t>(cg >> 8, 0, ca);
cb = blClamp<int32_t>(cb >> 8, 0, ca);
reinterpret_cast<uint32_t*>(dp)[0] = blRgba32Pack(cr, cg, cb, ca);
dp += 4;
srcData += 4;
}
recordList += 1;
weightList += kernelSize;
dstLine += dstStride;
}
}
}
static void BL_CDECL blImageScaleVertXrgb32(const BLImageScaleContext::Data* d, uint8_t* dstLine, intptr_t dstStride, const uint8_t* srcLine, intptr_t srcStride) noexcept {
int dw = d->dstSize[0];
int dh = d->dstSize[1];
int kernelSize = d->kernelSize[BLImageScaleContext::kDirVert];
const BLImageScaleContext::Record* recordList = d->recordList[BLImageScaleContext::kDirVert];
const int32_t* weightList = d->weightList[BLImageScaleContext::kDirVert];
if (!d->isUnbound[BLImageScaleContext::kDirVert]) {
for (int y = 0; y < dh; y++) {
const uint8_t* srcData = srcLine + intptr_t(recordList->pos) * srcStride;
uint8_t* dp = dstLine;
int count = recordList->count;
for (int x = 0; x < dw; x++) {
const uint8_t* sp = srcData;
const int32_t* wp = weightList;
uint32_t cx_cg = 0x00008000;
uint32_t cr_cb = 0x00800080;
for (int i = count; i; i--) {
uint32_t p0 = reinterpret_cast<const uint32_t*>(sp)[0];
uint32_t w0 = wp[0];
cx_cg += (p0 & 0x0000FF00) * w0;
cr_cb += (p0 & 0x00FF00FF) * w0;
sp += srcStride;
wp += 1;
}
reinterpret_cast<uint32_t*>(dp)[0] = 0xFF000000 + (((cx_cg & 0x00FF0000) | (cr_cb & 0xFF00FF00)) >> 8);
dp += 4;
srcData += 4;
}
recordList += 1;
weightList += kernelSize;
dstLine += dstStride;
}
}
else {
for (int y = 0; y < dh; y++) {
const uint8_t* srcData = srcLine + intptr_t(recordList->pos) * srcStride;
uint8_t* dp = dstLine;
int count = recordList->count;
for (int x = 0; x < dw; x++) {
const uint8_t* sp = srcData;
const int32_t* wp = weightList;
int32_t cr = 0x80;
int32_t cg = 0x80;
int32_t cb = 0x80;
for (int i = count; i; i--) {
uint32_t p0 = reinterpret_cast<const uint32_t*>(sp)[0];
int32_t w0 = wp[0];
cr += int32_t((p0 >> 16) & 0xFF) * w0;
cg += int32_t((p0 >> 8) & 0xFF) * w0;
cb += int32_t((p0 ) & 0xFF) * w0;
sp += srcStride;
wp += 1;
}
cr = blClamp<int32_t>(cr >> 8, 0, 255);
cg = blClamp<int32_t>(cg >> 8, 0, 255);
cb = blClamp<int32_t>(cb >> 8, 0, 255);
reinterpret_cast<uint32_t*>(dp)[0] = blRgba32Pack(cr, cg, cb, 0xFF);
dp += 4;
srcData += 4;
}
recordList += 1;
weightList += kernelSize;
dstLine += dstStride;
}
}
}
static void BL_CDECL blImageScaleVertBytes(const BLImageScaleContext::Data* d, uint8_t* dstLine, intptr_t dstStride, const uint8_t* srcLine, intptr_t srcStride, uint32_t wScale) noexcept {
int dw = d->dstSize[0] * wScale;
int dh = d->dstSize[1];
int kernelSize = d->kernelSize[BLImageScaleContext::kDirVert];
const BLImageScaleContext::Record* recordList = d->recordList[BLImageScaleContext::kDirVert];
const int32_t* weightList = d->weightList[BLImageScaleContext::kDirVert];
if (!d->isUnbound[BLImageScaleContext::kDirVert]) {
for (int y = 0; y < dh; y++) {
const uint8_t* srcData = srcLine + intptr_t(recordList->pos) * srcStride;
uint8_t* dp = dstLine;
int x = dw;
int i = 0;
int count = recordList->count;
if (((intptr_t)dp & 0x7) == 0)
goto BoundLarge;
i = 8 - int((intptr_t)dp & 0x7);
BoundSmall:
x -= i;
do {
const uint8_t* sp = srcData;
const int32_t* wp = weightList;
uint32_t c0 = 0x80;
for (int j = count; j; j--) {
uint32_t p0 = sp[0];
uint32_t w0 = wp[0];
c0 += p0 * w0;
sp += srcStride;
wp += 1;
}
dp[0] = (uint8_t)(c0 >> 8);
dp += 1;
srcData += 1;
} while (--i);
BoundLarge:
while (x >= 8) {
const uint8_t* sp = srcData;
const int32_t* wp = weightList;
uint32_t c0 = 0x00800080;
uint32_t c1 = 0x00800080;
uint32_t c2 = 0x00800080;
uint32_t c3 = 0x00800080;
for (int j = count; j; j--) {
uint32_t p0 = reinterpret_cast<const uint32_t*>(sp)[0];
uint32_t p1 = reinterpret_cast<const uint32_t*>(sp)[1];
uint32_t w0 = wp[0];
c0 += ((p0 ) & 0x00FF00FF) * w0;
c1 += ((p0 >> 8) & 0x00FF00FF) * w0;
c2 += ((p1 ) & 0x00FF00FF) * w0;
c3 += ((p1 >> 8) & 0x00FF00FF) * w0;
sp += srcStride;
wp += 1;
}
reinterpret_cast<uint32_t*>(dp)[0] = ((c0 & 0xFF00FF00) >> 8) + (c1 & 0xFF00FF00);
reinterpret_cast<uint32_t*>(dp)[1] = ((c2 & 0xFF00FF00) >> 8) + (c3 & 0xFF00FF00);
dp += 8;
srcData += 8;
x -= 8;
}
i = x;
if (i != 0)
goto BoundSmall;
recordList += 1;
weightList += kernelSize;
dstLine += dstStride;
}
}
else {
for (int y = 0; y < dh; y++) {
const uint8_t* srcData = srcLine + intptr_t(recordList->pos) * srcStride;
uint8_t* dp = dstLine;
int x = dw;
int i = 0;
int count = recordList->count;
if (((size_t)dp & 0x3) == 0)
goto UnboundLarge;
i = 4 - int((intptr_t)dp & 0x3);
UnboundSmall:
x -= i;
do {
const uint8_t* sp = srcData;
const int32_t* wp = weightList;
int32_t c0 = 0x80;
for (int j = count; j; j--) {
uint32_t p0 = sp[0];
int32_t w0 = wp[0];
c0 += int32_t(p0) * w0;
sp += srcStride;
wp += 1;
}
dp[0] = (uint8_t)(uint32_t)blClamp<int32_t>(c0 >> 8, 0, 255);
dp += 1;
srcData += 1;
} while (--i);
UnboundLarge:
while (x >= 4) {
const uint8_t* sp = srcData;
const int32_t* wp = weightList;
int32_t c0 = 0x80;
int32_t c1 = 0x80;
int32_t c2 = 0x80;
int32_t c3 = 0x80;
for (int j = count; j; j--) {
uint32_t p0 = reinterpret_cast<const uint32_t*>(sp)[0];
uint32_t w0 = wp[0];
c0 += ((p0 ) & 0xFF) * w0;
c1 += ((p0 >> 8) & 0xFF) * w0;
c2 += ((p0 >> 16) & 0xFF) * w0;
c3 += ((p0 >> 24) ) * w0;
sp += srcStride;
wp += 1;
}
reinterpret_cast<uint32_t*>(dp)[0] =
(blClamp<int32_t>(c0 >> 8, 0, 255) ) +
(blClamp<int32_t>(c1 >> 8, 0, 255) << 8) +
(blClamp<int32_t>(c2 >> 8, 0, 255) << 16) +
(blClamp<int32_t>(c3 >> 8, 0, 255) << 24) ;
dp += 4;
srcData += 4;
x -= 4;
}
i = x;
if (i != 0)
goto UnboundSmall;
recordList += 1;
weightList += kernelSize;
dstLine += dstStride;
}
}
}
static void BL_CDECL blImageScaleVertA8(const BLImageScaleContext::Data* d, uint8_t* dstLine, intptr_t dstStride, const uint8_t* srcLine, intptr_t srcStride) noexcept {
blImageScaleVertBytes(d, dstLine, dstStride, srcLine, srcStride, 1);
}
// ============================================================================
// [BLImageScale - Reset]
// ============================================================================
BLResult BLImageScaleContext::reset() noexcept {
if (data != nullptr)
free(data);
data = nullptr;
return BL_SUCCESS;
}
// ============================================================================
// [BLImageScale - Interface]
// ============================================================================
BLResult BLImageScaleContext::create(const BLSizeI& to, const BLSizeI& from, uint32_t filter, const BLImageScaleOptions* options) noexcept {
if (!options)
options = &blImageScaleOptionsNone;
BLImageScaleBuiltInParams p;
BLImageScaleUserFunc userFunc;
const void* userData = &p;
// --------------------------------------------------------------------------
// [Setup Parameters]
// --------------------------------------------------------------------------
if (!blIsValid(to) || !blIsValid(from))
return blTraceError(BL_ERROR_INVALID_VALUE);
switch (filter) {
case BL_IMAGE_SCALE_FILTER_NEAREST : userFunc = blImageScaleNearestFunc ; p.radius = 1.0; break;
case BL_IMAGE_SCALE_FILTER_BILINEAR: userFunc = blImageScaleBilinearFunc; p.radius = 1.0; break;
case BL_IMAGE_SCALE_FILTER_BICUBIC : userFunc = blImageScaleBicubicFunc ; p.radius = 2.0; break;
case BL_IMAGE_SCALE_FILTER_BELL : userFunc = blImageScaleBellFunc ; p.radius = 1.5; break;
case BL_IMAGE_SCALE_FILTER_GAUSS : userFunc = blImageScaleGaussFunc ; p.radius = 2.0; break;
case BL_IMAGE_SCALE_FILTER_HERMITE : userFunc = blImageScaleHermiteFunc ; p.radius = 1.0; break;
case BL_IMAGE_SCALE_FILTER_HANNING : userFunc = blImageScaleHanningFunc ; p.radius = 1.0; break;
case BL_IMAGE_SCALE_FILTER_CATROM : userFunc = blImageScaleCatromFunc ; p.radius = 2.0; break;
case BL_IMAGE_SCALE_FILTER_BESSEL : userFunc = blImageScaleBesselFunc ; p.radius = 3.2383; break;
case BL_IMAGE_SCALE_FILTER_SINC : userFunc = blImageScaleSincFunc ; p.radius = options->radius; break;
case BL_IMAGE_SCALE_FILTER_LANCZOS : userFunc = blImageScaleLanczosFunc ; p.radius = options->radius; break;
case BL_IMAGE_SCALE_FILTER_BLACKMAN: userFunc = blImageScaleBlackmanFunc; p.radius = options->radius; break;
case BL_IMAGE_SCALE_FILTER_MITCHELL: {
p.radius = 2.0;
if (!blIsFinite(options->mitchell.b) || !blIsFinite(options->mitchell.c))
return blTraceError(BL_ERROR_INVALID_VALUE);
p.initMitchell(options->mitchell.b, options->mitchell.c);
userFunc = blImageScaleMitchellFunc;
break;
}
case BL_IMAGE_SCALE_FILTER_USER: {
userFunc = options->userFunc;
userData = options->userData;
if (!userFunc)
return blTraceError(BL_ERROR_INVALID_VALUE);
break;
}
default:
return blTraceError(BL_ERROR_INVALID_VALUE);
}
if (!(p.radius >= 1.0 && p.radius <= 16.0))
return blTraceError(BL_ERROR_INVALID_VALUE);
// --------------------------------------------------------------------------
// [Setup Weights]
// --------------------------------------------------------------------------
double scale[2];
double factor[2];
double radius[2];
int kernelSize[2];
int isUnbound[2];
scale[0] = double(to.w) / double(from.w);
scale[1] = double(to.h) / double(from.h);
factor[0] = 1.0;
factor[1] = 1.0;
radius[0] = p.radius;
radius[1] = p.radius;
if (scale[0] < 1.0) { factor[0] = scale[0]; radius[0] = p.radius / scale[0]; }
if (scale[1] < 1.0) { factor[1] = scale[1]; radius[1] = p.radius / scale[1]; }
kernelSize[0] = blCeilToInt(1.0 + 2.0 * radius[0]);
kernelSize[1] = blCeilToInt(1.0 + 2.0 * radius[1]);
isUnbound[0] = false;
isUnbound[1] = false;
size_t wWeightDataSize = size_t(to.w) * kernelSize[0] * sizeof(int32_t);
size_t hWeightDataSize = size_t(to.h) * kernelSize[1] * sizeof(int32_t);
size_t wRecordDataSize = size_t(to.w) * sizeof(Record);
size_t hRecordDataSize = size_t(to.h) * sizeof(Record);
size_t dataSize = sizeof(Data) + wWeightDataSize + hWeightDataSize + wRecordDataSize + hRecordDataSize;
if (this->data)
free(this->data);
this->data = static_cast<Data*>(malloc(dataSize));
if (BL_UNLIKELY(!this->data))
return blTraceError(BL_ERROR_OUT_OF_MEMORY);
// Init data.
Data* d = this->data;
d->dstSize[0] = to.w;
d->dstSize[1] = to.h;
d->srcSize[0] = from.w;
d->srcSize[1] = from.h;
d->kernelSize[0] = kernelSize[0];
d->kernelSize[1] = kernelSize[1];
d->isUnbound[0] = isUnbound[0];
d->isUnbound[1] = isUnbound[1];
d->scale[0] = scale[0];
d->scale[1] = scale[1];
d->factor[0] = factor[0];
d->factor[1] = factor[1];
d->radius[0] = radius[0];
d->radius[1] = radius[1];
// Distribute the memory buffer.
uint8_t* dataPtr = blOffsetPtr<uint8_t>(d, sizeof(Data));
d->weightList[kDirHorz] = reinterpret_cast<int32_t*>(dataPtr); dataPtr += wWeightDataSize;
d->weightList[kDirVert] = reinterpret_cast<int32_t*>(dataPtr); dataPtr += hWeightDataSize;
d->recordList[kDirHorz] = reinterpret_cast<Record*>(dataPtr); dataPtr += wRecordDataSize;
d->recordList[kDirVert] = reinterpret_cast<Record*>(dataPtr);
// Built-in filters will probably never fail, however, custom filters can and
// it wouldn't be safe to just continue.
BL_PROPAGATE(blImageScaleOps.weights(d, kDirHorz, userFunc, userData));
BL_PROPAGATE(blImageScaleOps.weights(d, kDirVert, userFunc, userData));
return BL_SUCCESS;
}
BLResult BLImageScaleContext::processHorzData(uint8_t* dstLine, intptr_t dstStride, const uint8_t* srcLine, intptr_t srcStride, uint32_t format) const noexcept {
BL_ASSERT(isInitialized());
blImageScaleOps.horz[format](this->data, dstLine, dstStride, srcLine, srcStride);
return BL_SUCCESS;
}
BLResult BLImageScaleContext::processVertData(uint8_t* dstLine, intptr_t dstStride, const uint8_t* srcLine, intptr_t srcStride, uint32_t format) const noexcept {
BL_ASSERT(isInitialized());
blImageScaleOps.vert[format](this->data, dstLine, dstStride, srcLine, srcStride);
return BL_SUCCESS;
}
// ============================================================================
// [BLImageScale - Runtime Init]
// ============================================================================
void blImageScalerRtInit(BLRuntimeContext* rt) noexcept {
BL_UNUSED(rt);
blImageScaleOps.weights = blImageScaleWeights;
blImageScaleOps.horz[BL_FORMAT_PRGB32] = blImageScaleHorzPrgb32;
blImageScaleOps.horz[BL_FORMAT_XRGB32] = blImageScaleHorzXrgb32;
blImageScaleOps.horz[BL_FORMAT_A8 ] = blImageScaleHorzA8;
blImageScaleOps.vert[BL_FORMAT_PRGB32] = blImageScaleVertPrgb32;
blImageScaleOps.vert[BL_FORMAT_XRGB32] = blImageScaleVertXrgb32;
blImageScaleOps.vert[BL_FORMAT_A8 ] = blImageScaleVertA8;
}
| 29.869276 | 188 | 0.550693 | [
"vector"
] |
73f2444b3aac1417816529946e7b25918c94fc52 | 2,038 | cpp | C++ | problems/aggressive_cows.cpp | oishikm12/cpp-collection | 4a454a6ed5b24570c7df0d4f0b692ae98c1ffa97 | [
"MIT"
] | 5 | 2021-05-17T12:32:42.000Z | 2021-12-12T21:09:55.000Z | problems/aggressive_cows.cpp | oishikm12/cpp-collection | 4a454a6ed5b24570c7df0d4f0b692ae98c1ffa97 | [
"MIT"
] | null | null | null | problems/aggressive_cows.cpp | oishikm12/cpp-collection | 4a454a6ed5b24570c7df0d4f0b692ae98c1ffa97 | [
"MIT"
] | 1 | 2021-05-13T20:29:57.000Z | 2021-05-13T20:29:57.000Z | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool isPossible(vector<int> &, int, int);
int main() {
/**
* In order to find out the stall placement with maximum distance
* we use binary search to find out distances till stalls are and
* all cows can be placed
*/
cout << "\nThis problem places cows in their stalls at max possible distance from each other\n" << endl;
int n, cows;
cout << "Enter the number of stalls: ";
cin >> n;
cout << "Enter number of cows to place: ";
cin >> cows;
vector<int> stalls(n);
cout << "\nEnter space seperated positions of stalls." << endl;
for (int i = 0; i < n; i += 1) cin >> stalls[i];
// We need to sort if we are to use binary search
sort(stalls.begin(), stalls.end());
int minDist = 0;
// We set low to 0 such that each cow may be placed in the same
// stall and high as max distance such that only 2 cows can stay
int low = 0;
int high = stalls[n - 1] - stalls[0];
int mid;
while (high >= low) {
mid = (high + low) / 2;
if (isPossible(stalls, cows, mid)) {
low = mid + 1;
minDist = mid;
} else {
high = mid - 1;
}
}
cout << "\nCows can be placed at a least distance of " << mid << "." << endl;
cout << endl;
return 0;
}
bool isPossible(vector<int> &stalls, int cows, int dist) {
// We consider the first cow to always be present in first stall
int placed = 1;
int last = stalls[0];
// We then place each cow at the next stall if the minimum
// distance b/w them is at least `dist`
for (int i = 1; i < stalls.size(); i += 1) {
if ((stalls[i] - last) >= dist) {
placed += 1;
// We have placed all cows so we return
if (placed == cows) return true;
last = stalls[i];
}
}
// If we reach this point it signifies that
// not all cows could be placed
return false;
} | 27.540541 | 108 | 0.56526 | [
"vector"
] |
73f49d2742a7a464e29148c1ef2a7bd0bf8c6edc | 4,383 | cc | C++ | src/chrome/browser/search/instant_io_context.cc | jxjnjjn/chromium | 435c1d02fd1b99001dc9e1e831632c894523580d | [
"Apache-2.0"
] | 9 | 2018-09-21T05:36:12.000Z | 2021-11-15T15:14:36.000Z | chrome/browser/search/instant_io_context.cc | devasia1000/chromium | 919a8a666862fb866a6bb7aa7f3ae8c0442b4828 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/search/instant_io_context.cc | devasia1000/chromium | 919a8a666862fb866a6bb7aa7f3ae8c0442b4828 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 3 | 2018-11-28T14:54:13.000Z | 2020-07-02T07:36:07.000Z | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/search/instant_io_context.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/resource_context.h"
#include "content/public/browser/resource_request_info.h"
#include "googleurl/src/gurl.h"
#include "net/url_request/url_request.h"
using content::BrowserThread;
namespace {
// Retrieves the Instant data from the |context|'s named user-data.
InstantIOContext* GetDataForResourceContext(
content::ResourceContext* context) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
return base::UserDataAdapter<InstantIOContext>::Get(
context, InstantIOContext::kInstantIOContextKeyName);
}
InstantIOContext* GetDataForRequest(const net::URLRequest* request) {
const content::ResourceRequestInfo* info =
content::ResourceRequestInfo::ForRequest(request);
if (!info)
return NULL;
return GetDataForResourceContext(info->GetContext());
}
} // namespace
const char InstantIOContext::kInstantIOContextKeyName[] = "instant_io_context";
InstantIOContext::InstantIOContext()
: most_visited_item_cache_(kMaxInstantMostVisitedItemCacheSize) {
// The InstantIOContext is created on the UI thread but is accessed
// on the IO thread.
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
}
InstantIOContext::~InstantIOContext() {
}
// static
void InstantIOContext::SetUserDataOnIO(
content::ResourceContext* resource_context,
scoped_refptr<InstantIOContext> instant_io_context) {
resource_context->SetUserData(
InstantIOContext::kInstantIOContextKeyName,
new base::UserDataAdapter<InstantIOContext>(instant_io_context));
}
// static
void InstantIOContext::AddInstantProcessOnIO(
scoped_refptr<InstantIOContext> instant_io_context,
int process_id) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
instant_io_context->process_ids_.insert(process_id);
}
// static
void InstantIOContext::RemoveInstantProcessOnIO(
scoped_refptr<InstantIOContext> instant_io_context, int process_id) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
instant_io_context->process_ids_.erase(process_id);
}
// static
void InstantIOContext::ClearInstantProcessesOnIO(
scoped_refptr<InstantIOContext> instant_io_context) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
instant_io_context->process_ids_.clear();
}
// static
void InstantIOContext::AddMostVisitedItemsOnIO(
scoped_refptr<InstantIOContext> instant_io_context,
std::vector<InstantMostVisitedItemIDPair> items) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
instant_io_context->most_visited_item_cache_.AddItemsWithRestrictedID(items);
}
// static
bool InstantIOContext::ShouldServiceRequest(const net::URLRequest* request) {
const content::ResourceRequestInfo* info =
content::ResourceRequestInfo::ForRequest(request);
if (!info)
return false;
InstantIOContext* instant_io_context = GetDataForRequest(request);
if (!instant_io_context)
return false;
int process_id = -1;
int render_view_id = -1;
if (info->GetAssociatedRenderView(&process_id, &render_view_id) &&
instant_io_context->IsInstantProcess(process_id))
return true;
return false;
}
// static
bool InstantIOContext::GetURLForMostVisitedItemID(
const net::URLRequest* request,
InstantRestrictedID most_visited_item_id,
GURL* url) {
InstantIOContext* instant_io_context = GetDataForRequest(request);
if (!instant_io_context) {
*url = GURL();
return false;
}
return instant_io_context->GetURLForMostVisitedItemID(most_visited_item_id,
url);
}
bool InstantIOContext::IsInstantProcess(int process_id) const {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
return process_ids_.find(process_id) != process_ids_.end();
}
bool InstantIOContext::GetURLForMostVisitedItemID(
InstantRestrictedID most_visited_item_id,
GURL* url) const {
InstantMostVisitedItem item;
if (most_visited_item_cache_.GetItemWithRestrictedID(most_visited_item_id,
&item)) {
*url = item.url;
return true;
}
*url = GURL();
return false;
}
| 31.307143 | 79 | 0.756788 | [
"vector"
] |
73fc372a5bce5b38138a88533ab0a8cce2f27f42 | 2,710 | cpp | C++ | leetcode/cpp/qt_data_stream_as_disjoint_intervals.cpp | qiaotian/CodeInterview | 294c1ba86d8ace41a121c5ada4ba4c3765ccc17d | [
"WTFPL"
] | 5 | 2016-10-29T09:28:11.000Z | 2019-10-19T23:02:48.000Z | leetcode/cpp/qt_data_stream_as_disjoint_intervals.cpp | qiaotian/CodeInterview | 294c1ba86d8ace41a121c5ada4ba4c3765ccc17d | [
"WTFPL"
] | null | null | null | leetcode/cpp/qt_data_stream_as_disjoint_intervals.cpp | qiaotian/CodeInterview | 294c1ba86d8ace41a121c5ada4ba4c3765ccc17d | [
"WTFPL"
] | null | null | null | /**
* @Author: Tian Qiao
* @Date: 2016-07-26T11:08:26+08:00
* @Email: qiaotian@me.com
* @Last modified by: Tian Qiao
* @Last modified time: 2016-07-26T11:08:28+08:00
* @Tag: Binary Search Tree
*/
/*
Given a data stream input of non-negative integers a1, a2, ..., an, ..., summarize the numbers seen so far as a list of disjoint intervals.
For example, suppose the integers from the data stream are 1, 3, 7, 2, 6, ..., then the summary will be:
[1, 1]
[1, 1], [3, 3]
[1, 1], [3, 3], [7, 7]
[1, 3], [7, 7]
[1, 3], [6, 7]
Follow up:
What if there are lots of merges and the number of disjoint intervals are small compared to the data stream's size?
*/
/**
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* Interval(int s, int e) : start(s), end(e) {}
* };
*/
// 两种数据结构: 数组和树, 各有优缺点
// 1. 数组(vector): add操作O(N), get操作O(1)
// 2. 树(set): add操作O(logN), get操作O(N)
// beats 80%
class SummaryRanges {
public:
/** Initialize your data structure here. */
SummaryRanges() { }
void addNum(int val) {
auto Cmp = [](Interval a, Interval b) { return a.start < b.start; };
auto it = lower_bound(vec.begin(), vec.end(), Interval(val, val), Cmp);
int start = val, end = val;
if(it != vec.begin() && (it-1)->end+1 >= val) it--;
while(it != vec.end() && val+1 >= it->start && val-1 <= it->end)
{
start = min(start, it->start);
end = max(end, it->end);
it = vec.erase(it);
}
vec.insert(it,Interval(start, end));
}
vector<Interval> getIntervals() {
return vec;
}
private:
vector<Interval> vec;
};
// beats 20%
class SummaryRanges {
public:
/** Initialize your data structure here. */
void addNum(int val) {
auto it = st.lower_bound(Interval(val, val));
int start = val, end = val;
if(it != st.begin() && (--it)->end+1 < val) it++;
while(it != st.end() && val+1 >= it->start && val-1 <= it->end)
{
start = min(start, it->start);
end = max(end, it->end);
it = st.erase(it);
}
st.insert(it,Interval(start, end));
}
vector<Interval> getIntervals() {
vector<Interval> result;
for(auto val: st) result.push_back(val);
return result;
}
private:
struct Cmp{
bool operator()(Interval a, Interval b){ return a.start < b.start; }
};
set<Interval, Cmp> st;
};
/**
* Your SummaryRanges object will be instantiated and called as such:
* SummaryRanges obj = new SummaryRanges();
* obj.addNum(val);
* vector<Interval> param_2 = obj.getIntervals();
*/
| 26.831683 | 139 | 0.563469 | [
"object",
"vector"
] |
bab601a1fd24329f69ccbd4b41efe61bd8525d4f | 27,141 | cpp | C++ | src/ripple/app/tests/AmendmentTable.test.cpp | sublimator/rippled | 8d86d39b74046d216d7da8212647327a2d0c2810 | [
"BSL-1.0"
] | null | null | null | src/ripple/app/tests/AmendmentTable.test.cpp | sublimator/rippled | 8d86d39b74046d216d7da8212647327a2d0c2810 | [
"BSL-1.0"
] | null | null | null | src/ripple/app/tests/AmendmentTable.test.cpp | sublimator/rippled | 8d86d39b74046d216d7da8212647327a2d0c2810 | [
"BSL-1.0"
] | null | null | null | //------------------------------------------------------------------------------
/*
This file is part of rippled: https://github.com/ripple/rippled
Copyright (c) 2012, 2013 Ripple Labs Inc.
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.
*/
//==============================================================================
#include <BeastConfig.h>
#include <ripple/app/misc/AmendmentTable.h>
#include <ripple/basics/BasicConfig.h>
#include <ripple/basics/chrono.h>
#include <ripple/basics/contract.h>
#include <ripple/basics/Log.h>
#include <ripple/core/ConfigSections.h>
#include <ripple/protocol/TxFlags.h>
#include <beast/unit_test/suite.h>
namespace ripple
{
class AmendmentTable_test final : public beast::unit_test::suite
{
public:
using StringPairVec = std::vector<std::pair<std::string, std::string>>;
private:
enum class TablePopulationAlgo
{
addInitial,
addKnown
};
// 204/256 about 80% (we round down because the implementation rounds up)
static int const majorityFraction{204};
static void populateTable (AmendmentTable& table,
std::vector<std::string> const& configLines)
{
Section section (SECTION_AMENDMENTS);
section.append (configLines);
table.addInitial (section);
}
static std::vector<AmendmentName> getAmendmentNames (
StringPairVec const& amendmentPairs)
{
std::vector<AmendmentName> amendmentNames;
amendmentNames.reserve (amendmentPairs.size ());
for (auto const& i : amendmentPairs)
{
amendmentNames.emplace_back (i.first, i.second);
}
return amendmentNames;
}
std::vector<AmendmentName> populateTable (
AmendmentTable& table,
StringPairVec const& amendmentPairs,
TablePopulationAlgo populationAlgo = TablePopulationAlgo::addKnown)
{
std::vector<AmendmentName> const amendmentNames (
getAmendmentNames (amendmentPairs));
switch (populationAlgo)
{
case TablePopulationAlgo::addKnown:
for (auto const& i : amendmentNames)
{
table.addKnown (i);
}
break;
case TablePopulationAlgo::addInitial:
{
std::vector<std::string> configLines;
configLines.reserve (amendmentPairs.size ());
for (auto const& i : amendmentPairs)
{
configLines.emplace_back (i.first + " " + i.second);
}
populateTable (table, configLines);
}
break;
default:
fail ("Error in test case logic");
}
return amendmentNames;
}
static std::unique_ptr< AmendmentTable >
makeTable (int w)
{
return make_AmendmentTable (
weeks (w),
majorityFraction,
beast::Journal{});
};
// Create the amendments by string pairs instead of AmendmentNames
// as this helps test the AmendmentNames class
StringPairVec const m_knownAmendmentPairs;
StringPairVec const m_unknownAmendmentPairs;
public:
AmendmentTable_test ()
: m_knownAmendmentPairs (
{{"a49f90e7cddbcadfed8fc89ec4d02011", "Known1"},
{"ca956ccabf25151a16d773171c485423", "Known2"},
{"60dcd528f057711c5d26b57be28e23df", "Known3"},
{"da956ccabf25151a16d773171c485423", "Known4"},
{"70dcd528f057711c5d26b57be28e23df", "Known5"},
{"70dcd528f057711c5d26b57be28e23d0", "Known6"}})
, m_unknownAmendmentPairs (
{{"a9f90e7cddbcadfed8fc89ec4d02011c", "Unknown1"},
{"c956ccabf25151a16d773171c485423b", "Unknown2"},
{"6dcd528f057711c5d26b57be28e23dfa", "Unknown3"}})
{
}
void testGet ()
{
testcase ("get");
auto table (makeTable (2));
std::vector<AmendmentName> const amendmentNames (
populateTable (*table, m_knownAmendmentPairs));
std::vector<AmendmentName> const unknownAmendmentNames (
getAmendmentNames (m_unknownAmendmentPairs));
for (auto const& i : amendmentNames)
{
expect (table->get (i.friendlyName ()) == i.id ());
}
for (auto const& i : unknownAmendmentNames)
{
expect (table->get (i.friendlyName ()) == uint256 ());
}
}
void testAddInitialAddKnown ()
{
testcase ("addInitialAddKnown");
for (auto tablePopulationAlgo :
{TablePopulationAlgo::addInitial, TablePopulationAlgo::addKnown})
{
{
// test that the amendments we add are enabled and amendments we
// didn't add are not enabled
auto table (makeTable (2));
std::vector<AmendmentName> const amendmentNames (populateTable (
*table, m_knownAmendmentPairs, tablePopulationAlgo));
std::vector<AmendmentName> const unknownAmendmentNames (
getAmendmentNames (m_unknownAmendmentPairs));
for (auto const& i : amendmentNames)
{
expect (table->isSupported (i.id ()));
if (tablePopulationAlgo == TablePopulationAlgo::addInitial)
expect (table->isEnabled (i.id ()));
}
for (auto const& i : unknownAmendmentNames)
{
expect (!table->isSupported (i.id ()));
expect (!table->isEnabled (i.id ()));
}
}
{
// check that we throw an exception on bad hex pairs
StringPairVec const badHexPairs (
{{"a9f90e7cddbcadfedm8fc89ec4d02011c", "BadHex1"},
{"c956ccabf25151a16d77T3171c485423b", "BadHex2"},
{"6dcd528f057711c5d2Z6b57be28e23dfa", "BadHex3"}});
// make sure each element throws
for (auto const& i : badHexPairs)
{
StringPairVec v ({i});
auto table (makeTable (2));
try
{
populateTable (*table, v, tablePopulationAlgo);
// line above should throw
fail ("didn't throw");
}
catch (std::exception const&)
{
pass ();
}
try
{
populateTable (
*table, badHexPairs, tablePopulationAlgo);
// line above should throw
fail ("didn't throw");
}
catch (std::exception const&)
{
pass ();
}
}
}
}
{
// check that we thow on bad num tokens
std::vector<std::string> const badNumTokensConfigLines (
{"19f6d",
"19fd6 bad friendly name"
"9876 one two"});
// make sure each element throws
for (auto const& i : badNumTokensConfigLines)
{
std::vector<std::string> v ({i});
auto table (makeTable (2));
try
{
populateTable (*table, v);
// line above should throw
fail ("didn't throw");
}
catch (std::exception const&)
{
pass ();
}
try
{
populateTable (*table, badNumTokensConfigLines);
// line above should throw
fail ("didn't throw");
}
catch (std::exception const&)
{
pass ();
}
}
}
}
void testEnable ()
{
testcase ("enable");
auto table (makeTable (2));
std::vector<AmendmentName> const amendmentNames (
populateTable (*table, m_knownAmendmentPairs));
{
// enable/disable tests
for (auto const& i : amendmentNames)
{
auto id (i.id ());
table->enable (id);
expect (table->isEnabled (id));
table->disable (id);
expect (!table->isEnabled (id));
table->enable (id);
expect (table->isEnabled (id));
}
std::vector<uint256> toEnable;
for (auto const& i : amendmentNames)
{
auto id (i.id ());
toEnable.emplace_back (id);
table->disable (id);
expect (!table->isEnabled (id));
}
table->setEnabled (toEnable);
for (auto const& i : toEnable)
{
expect (table->isEnabled (i));
}
}
}
using ATSetter =
void (AmendmentTable::*)(const std::vector<uint256>& amendments);
using ATGetter = bool (AmendmentTable::*)(uint256 const& amendment);
void testVectorSetUnset (ATSetter setter, ATGetter getter)
{
auto table (makeTable (2));
// make pointer to ref syntax a little nicer
auto& tableRef (*table);
std::vector<AmendmentName> const amendmentNames (
populateTable (tableRef, m_knownAmendmentPairs));
// they should all be set
for (auto const& i : amendmentNames)
{
expect ((tableRef.*getter)(i.id ())); // i.e. "isSupported"
}
{
// only set every other amendment
std::vector<uint256> toSet;
toSet.reserve (amendmentNames.size ());
for (int i = 0; i < amendmentNames.size (); ++i)
{
if (i % 2)
{
toSet.emplace_back (amendmentNames[i].id ());
}
}
(tableRef.*setter)(toSet);
for (int i = 0; i < amendmentNames.size (); ++i)
{
bool const shouldBeSet = i % 2;
expect (shouldBeSet ==
(tableRef.*getter)(
amendmentNames[i].id ())); // i.e. "isSupported"
}
}
}
void testSupported ()
{
testcase ("supported");
testVectorSetUnset (&AmendmentTable::setSupported,
&AmendmentTable::isSupported);
}
void testEnabled ()
{
testcase ("enabled");
testVectorSetUnset (&AmendmentTable::setEnabled,
&AmendmentTable::isEnabled);
}
void testSupportedEnabled ()
{
// Check that supported/enabled aren't the same thing
testcase ("supportedEnabled");
auto table (makeTable (2));
std::vector<AmendmentName> const amendmentNames (
populateTable (*table, m_knownAmendmentPairs));
{
// support every even amendment
// enable every odd amendment
std::vector<uint256> toSupport;
toSupport.reserve (amendmentNames.size ());
std::vector<uint256> toEnable;
toEnable.reserve (amendmentNames.size ());
for (int i = 0; i < amendmentNames.size (); ++i)
{
if (i % 2)
{
toSupport.emplace_back (amendmentNames[i].id ());
}
else
{
toEnable.emplace_back (amendmentNames[i].id ());
}
}
table->setEnabled (toEnable);
table->setSupported (toSupport);
for (int i = 0; i < amendmentNames.size (); ++i)
{
bool const shouldBeSupported = i % 2;
bool const shouldBeEnabled = !(i % 2);
expect (shouldBeEnabled ==
(table->isEnabled (amendmentNames[i].id ())));
expect (shouldBeSupported ==
(table->isSupported (amendmentNames[i].id ())));
}
}
}
std::vector <RippleAddress> makeValidators (int num)
{
std::vector <RippleAddress> ret;
ret.reserve (num);
for (int i = 0; i < num; ++i)
ret.push_back (RippleAddress::createNodePublic (
RippleAddress::createSeedRandom ()));
return ret;
}
static NetClock::time_point weekTime (weeks w)
{
return NetClock::time_point{w};
}
// Execute a pretend consensus round for a flag ledger
void doRound
( AmendmentTable& table
, weeks week
, std::vector <RippleAddress> const& validators
, std::vector <std::pair <uint256, int> > const& votes
, std::vector <uint256>& ourVotes
, enabledAmendments_t& enabled
, majorityAmendments_t& majority)
{
// Do a round at the specified time
// Returns the amendments we voted for
// Parameters:
// table: Our table of known and vetoed amendments
// validators: The addreses of validators we trust
// votes: Amendments and the number of validators who vote for them
// ourVotes: The amendments we vote for in our validation
// enabled: In/out enabled amendments
// majority: In/our majority amendments (and when they got a majority)
auto const roundTime = weekTime (week);
// Build validations
ValidationSet validations;
validations.reserve (validators.size ());
int i = 0;
for (auto const& val : validators)
{
STValidation::pointer v =
std::make_shared <STValidation>
(uint256(), roundTime, val, true);
++i;
STVector256 field (sfAmendments);
for (auto const& amendment : votes)
{
if ((256 * i) < (validators.size() * amendment.second))
{
// We vote yes on this amendment
field.push_back (amendment.first);
}
}
if (!field.empty ())
v->setFieldV256 (sfAmendments, field);
v->setTrusted();
validations [val.getNodeID()] = v;
}
ourVotes = table.doValidation (enabled);
auto actions = table.doVoting (roundTime, enabled, majority, validations);
for (auto const& action : actions)
{
// This code assumes other validators do as we do
auto const& hash = action.first;
switch (action.second)
{
case 0:
// amendment goes from majority to enabled
if (enabled.find (hash) != enabled.end ())
Throw<std::runtime_error> ("enabling already enabled");
if (majority.find (hash) == majority.end ())
Throw<std::runtime_error> ("enabling without majority");
enabled.insert (hash);
majority.erase (hash);
break;
case tfGotMajority:
if (majority.find (hash) != majority.end ())
Throw<std::runtime_error> ("got majority while having majority");
majority[hash] = roundTime;
break;
case tfLostMajority:
if (majority.find (hash) == majority.end ())
Throw<std::runtime_error> ("lost majority without majority");
majority.erase (hash);
break;
default:
assert (false);
Throw<std::runtime_error> ("unknown action");
}
}
}
// No vote on unknown amendment
void testNoUnknown ()
{
testcase ("voteNoUnknown");
auto table (makeTable (2));
auto const validators = makeValidators (10);
uint256 testAmendment;
testAmendment.SetHex("6dcd528f057711c5d26b57be28e23dfa");
std::vector <std::pair <uint256, int>> votes;
std::vector <uint256> ourVotes;
enabledAmendments_t enabled;
majorityAmendments_t majority;
doRound (*table, weeks{1},
validators,
votes,
ourVotes,
enabled,
majority);
expect (ourVotes.empty(), "Voted with nothing to vote on");
expect (enabled.empty(), "Enabled amendment for no reason");
expect (majority.empty(), "Majority found for no reason");
votes.emplace_back (testAmendment, 256);
doRound (*table, weeks{2},
validators,
votes,
ourVotes,
enabled,
majority);
expect (ourVotes.empty(), "Voted on unknown because others did");
expect (enabled.empty(), "Enabled amendment for no reason");
majority[testAmendment] = weekTime(weeks{1});
// Note that the simulation code assumes others behave as we do,
// so the amendment won't get enabled
doRound (*table, weeks{5},
validators,
votes,
ourVotes,
enabled,
majority);
expect (ourVotes.empty(), "Voted on unknown because it had majority");
expect (enabled.empty(), "Pseudo-transaction from nowhere");
}
// No vote on vetoed amendment
void testNoVetoed ()
{
testcase ("voteNoVetoed");
auto table (makeTable (2));
auto const validators = makeValidators (10);
uint256 testAmendment;
testAmendment.SetHex("6dcd528f057711c5d26b57be28e23dfa");
table->veto(testAmendment);
std::vector <std::pair <uint256, int>> votes;
std::vector <uint256> ourVotes;
enabledAmendments_t enabled;
majorityAmendments_t majority;
doRound (*table, weeks{1},
validators,
votes,
ourVotes,
enabled,
majority);
expect (ourVotes.empty(), "Voted with nothing to vote on");
expect (enabled.empty(), "Enabled amendment for no reason");
expect (majority.empty(), "Majority found for no reason");
votes.emplace_back (testAmendment, 256);
doRound (*table, weeks{2},
validators,
votes,
ourVotes,
enabled,
majority);
expect (ourVotes.empty(), "Voted on vetoed amendment because others did");
expect (enabled.empty(), "Enabled amendment for no reason");
majority[testAmendment] = weekTime(weeks{1});
doRound (*table, weeks{5},
validators,
votes,
ourVotes,
enabled,
majority);
expect (ourVotes.empty(), "Voted on vetoed because it had majority");
expect (enabled.empty(), "Enabled amendment for no reason");
}
// Vote on and enable known, not-enabled amendment
void testVoteEnable ()
{
testcase ("voteEnable");
auto table (makeTable (2));
auto const amendmentNames (
populateTable (*table, m_knownAmendmentPairs));
auto const validators = makeValidators (10);
std::vector <std::pair <uint256, int>> votes;
std::vector <uint256> ourVotes;
enabledAmendments_t enabled;
majorityAmendments_t majority;
// Week 1: We should vote for all known amendments not enabled
doRound (*table, weeks{1},
validators,
votes,
ourVotes,
enabled,
majority);
expect (ourVotes.size() == amendmentNames.size(), "Did not vote");
expect (enabled.empty(), "Enabled amendment for no reason");
for (auto const& i : amendmentNames)
expect(majority.find(i.id()) == majority.end(), "majority detected for no reaosn");
// Now, everyone votes for this feature
for (auto const& i : amendmentNames)
votes.emplace_back (i.id(), 256);
// Week 2: We should recognize a majority
doRound (*table, weeks{2},
validators,
votes,
ourVotes,
enabled,
majority);
expect (ourVotes.size() == amendmentNames.size(), "Did not vote");
expect (enabled.empty(), "Enabled amendment for no reason");
for (auto const& i : amendmentNames)
expect (majority[i.id()] == weekTime(weeks{2}), "majority not detected");
// Week 5: We should enable the amendment
doRound (*table, weeks{5},
validators,
votes,
ourVotes,
enabled,
majority);
expect (enabled.size() == amendmentNames.size(), "Did not enable");
// Week 6: We should remove it from our votes and from having a majority
doRound (*table, weeks{6},
validators,
votes,
ourVotes,
enabled,
majority);
expect (enabled.size() == amendmentNames.size(), "Disabled");
expect (ourVotes.empty(), "Voted after enabling");
for (auto const& i : amendmentNames)
expect(majority.find(i.id()) == majority.end(), "majority not removed");
}
// Detect majority at 80%, enable later
void testDetectMajority ()
{
testcase ("detectMajority");
auto table (makeTable (2));
uint256 testAmendment;
testAmendment.SetHex("6dcd528f057711c5d26b57be28e23dfa");
table->addKnown({testAmendment, "testAmendment"});
auto const validators = makeValidators (16);
enabledAmendments_t enabled;
majorityAmendments_t majority;
for (int i = 0; i <= 17; ++i)
{
std::vector <std::pair <uint256, int>> votes;
std::vector <uint256> ourVotes;
if ((i > 0) && (i < 17))
votes.emplace_back (testAmendment, i * 16);
doRound (*table, weeks{i},
validators, votes, ourVotes, enabled, majority);
if (i < 14)
{
// rounds 0-13
// We are voting yes, not enabled, no majority
expect (!ourVotes.empty(), "We aren't voting");
expect (enabled.empty(), "Enabled too early");
expect (majority.empty(), "Majority too early");
}
else if (i < 16)
{
// rounds 14 and 15
// We have a majority, not enabled, keep voting
expect (!ourVotes.empty(), "We stopped voting");
expect (!majority.empty(), "Failed to detect majority");
expect (enabled.empty(), "Enabled too early");
}
else if (i == 16) // round 16
{
// round 16
// enable, keep voting, remove from majority
expect (!ourVotes.empty(), "We stopped voting");
expect (majority.empty(), "Failed to remove from majority");
expect (!enabled.empty(), "Did not enable");
}
else
{
// round 17
// Done, we should be enabled and not voting
expect (ourVotes.empty(), "We did not stop voting");
expect (majority.empty(), "Failed to revove from majority");
expect (!enabled.empty(), "Did not enable");
}
}
}
// Detect loss of majority
void testLostMajority ()
{
testcase ("lostMajority");
auto table (makeTable (8));
uint256 testAmendment;
testAmendment.SetHex("6dcd528f057711c5d26b57be28e23dfa");
table->addKnown({testAmendment, "testAmendment"});
auto const validators = makeValidators (16);
enabledAmendments_t enabled;
majorityAmendments_t majority;
{
// establish majority
std::vector <std::pair <uint256, int>> votes;
std::vector <uint256> ourVotes;
votes.emplace_back (testAmendment, 250);
doRound (*table, weeks{1},
validators, votes, ourVotes, enabled, majority);
expect (enabled.empty(), "Enabled for no reason");
expect (!majority.empty(), "Failed to detect majority");
}
for (int i = 1; i < 16; ++i)
{
std::vector <std::pair <uint256, int>> votes;
std::vector <uint256> ourVotes;
// Gradually reduce support
votes.emplace_back (testAmendment, 256 - i * 8);
doRound (*table, weeks{i + 1},
validators, votes, ourVotes, enabled, majority);
if (i < 6)
{
// rounds 1 to 5
// We are voting yes, not enabled, majority
expect (!ourVotes.empty(), "We aren't voting");
expect (enabled.empty(), "Enabled for no reason");
expect (!majority.empty(), "Lost majority too early");
}
else
{
// rounds 6 to 15
// No majority, not enabled, keep voting
expect (!ourVotes.empty(), "We stopped voting");
expect (majority.empty(), "Failed to detect loss of majority");
expect (enabled.empty(), "Enabled errneously");
}
}
}
void run ()
{
testGet ();
testAddInitialAddKnown ();
testEnable ();
testSupported ();
testSupportedEnabled ();
testNoUnknown ();
testNoVetoed ();
testVoteEnable ();
testDetectMajority ();
testLostMajority ();
}
};
BEAST_DEFINE_TESTSUITE (AmendmentTable, app, ripple);
} // ripple
| 34.139623 | 95 | 0.51763 | [
"vector"
] |
bab846bedcb2c11311fda710762df5ef17ab47ed | 4,232 | cpp | C++ | src/color-map.cpp | ecsnavarretemit/cmsc265-pseudocolor-image-processing-cpp | 9d9c0e1f7f99418de204caf95e99f3247249948f | [
"MIT"
] | 1 | 2017-05-02T00:43:25.000Z | 2017-05-02T00:43:25.000Z | src/color-map.cpp | ecsnavarretemit/cmsc265-pseudocolor-image-processing-cpp | 9d9c0e1f7f99418de204caf95e99f3247249948f | [
"MIT"
] | null | null | null | src/color-map.cpp | ecsnavarretemit/cmsc265-pseudocolor-image-processing-cpp | 9d9c0e1f7f99418de204caf95e99f3247249948f | [
"MIT"
] | null | null | null | /**
* color-map.cpp
*
* Copyright(c) Exequiel Ceasar Navarrete <esnavarrete1@up.edu.ph>
* Licensed under MIT
* Version 1.0.5
*/
#include <iostream>
#include <vector>
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "boost/filesystem.hpp"
#include "files.cpp"
using namespace std;
// define structure for colormap constants
struct {
string name;
int color_constant;
} colormaps[13];
int main() {
boost::filesystem::path in_path;
boost::filesystem::path out_path;
// resolve and normalize paths
in_path = boost::filesystem::system_complete("assets/img");
out_path = boost::filesystem::system_complete("out/color-map");
//-----------------------------------------------------------
// [Color Constants] ::start
//-----------------------------------------------------------
colormaps[0].name = "autumn";
colormaps[0].color_constant = cv::COLORMAP_AUTUMN;
colormaps[1].name = "bone";
colormaps[1].color_constant = cv::COLORMAP_BONE;
colormaps[2].name = "cool";
colormaps[2].color_constant = cv::COLORMAP_COOL;
colormaps[3].name = "hot";
colormaps[3].color_constant = cv::COLORMAP_HOT;
colormaps[4].name = "hsv";
colormaps[4].color_constant = cv::COLORMAP_HSV;
colormaps[5].name = "jet";
colormaps[5].color_constant = cv::COLORMAP_JET;
colormaps[6].name = "ocean";
colormaps[6].color_constant = cv::COLORMAP_OCEAN;
colormaps[7].name = "parula";
colormaps[7].color_constant = cv::COLORMAP_PARULA;
colormaps[8].name = "pink";
colormaps[8].color_constant = cv::COLORMAP_PINK;
colormaps[9].name = "rainbow";
colormaps[9].color_constant = cv::COLORMAP_RAINBOW;
colormaps[10].name = "spring";
colormaps[10].color_constant = cv::COLORMAP_SPRING;
colormaps[11].name = "summer";
colormaps[11].color_constant = cv::COLORMAP_SUMMER;
colormaps[12].name = "winter";
colormaps[12].color_constant = cv::COLORMAP_WINTER;
//-----------------------------------------------------------
// [Color Constants] ::end
//-----------------------------------------------------------
// delete the contents of the output folder
if (boost::filesystem::exists(out_path)) {
boost::filesystem::remove_all(out_path);
}
// create output folder if it does not exist
if(!boost::filesystem::exists(out_path) && !boost::filesystem::create_directories(out_path)) {
cerr << "Error in creating output directory" << out_path.string() << endl;
return 1;
}
cout << "Reading all images from the directory: " << in_path.string() << endl;
cout << "Output will be saved in: " << out_path.string() << endl;
// create Matrices for src, dst
cv::Mat src, dst;
try {
vector<boost::filesystem::path> imgs = get_images(in_path);
for (auto & img : imgs) {
// assemble the output path
boost::filesystem::path im_out = out_path / img.stem();
// create output folder if it does not exist
if(!boost::filesystem::exists(im_out) && !boost::filesystem::create_directories(im_out)) {
throw "Error in writing files!";
}
// loop through all defined constants
for (int i = 0; i < 13; i++) {
// assemble the path to the newly created image
string image_name = colormaps[i].name + ".jpg";
boost::filesystem::path color_im_out = im_out / image_name;
// read image in grayscale
src = cv::imread(img.string(), CV_LOAD_IMAGE_GRAYSCALE);
// apply colormaps
cv::applyColorMap(src, dst, colormaps[i].color_constant);
// write to the filesystem
cv::imwrite(color_im_out.string(), dst);
// free up resources
src.release();
dst.release();
}
}
} catch(const invalid_argument& e) {
cerr << e.what() << endl;
return 1;
} catch (const string msg) {
cerr << msg << endl;
return 1;
}
cout << "Done processing images." << endl;
return 0;
}
| 29.802817 | 102 | 0.573015 | [
"vector"
] |
babc5421896b4abe635c96b8970d027352b1d58d | 3,239 | cpp | C++ | libsrc/glWebKit/glWebkitRenderer.cpp | anonreclaimer/glWebKit | 7c64ba02a734f2a97e023ad6e5dc9eebd7fadb6c | [
"MIT"
] | 12 | 2018-09-11T10:54:22.000Z | 2021-10-05T14:56:27.000Z | libsrc/glWebKit/glWebkitRenderer.cpp | anonreclaimer/glWebKit | 7c64ba02a734f2a97e023ad6e5dc9eebd7fadb6c | [
"MIT"
] | 6 | 2018-10-11T13:31:13.000Z | 2020-01-29T00:03:40.000Z | libsrc/glWebKit/glWebkitRenderer.cpp | anonreclaimer/glWebKit | 7c64ba02a734f2a97e023ad6e5dc9eebd7fadb6c | [
"MIT"
] | 6 | 2018-09-11T12:53:57.000Z | 2021-10-13T02:22:01.000Z |
#include "glWebkitRenderer.h"
#include <EAWebKit/EAWebKit.h>
#include <EAWebKit/EAWebkitAllocator.h>
#include <EAWebKit/EAWebKitFileSystem.h>
#include <EAWebKit/EAWebKitClient.h>
#include <EAWebKit/EAWebKitView.h>
#include "EAWebkit/EAWebKitTextInterface.h"
#include <vector>
#include <array>
#include <iostream>
GLRenderer::GLRenderer()
{
}
GLRenderer::~GLRenderer()
{
}
EA::WebKit::ISurface * GLRenderer::CreateSurface(EA::WebKit::SurfaceType surfaceType, const void* data /*= 0*/, size_t length /*= 0*/)
{
GLSurface* res = new GLSurface();
if (data && length)
{
EA::WebKit::ISurface::SurfaceDescriptor sd = {};
res->Lock(&sd);
memcpy(sd.mData, data, length);
res->Unlock();
}
return res;
}
void GLRenderer::SetRenderTarget(EA::WebKit::ISurface *target)
{
std::cout << __FUNCTION__ << std::endl;
}
void GLRenderer::RenderSurface(EA::WebKit::ISurface *surface, EA::WebKit::FloatRect &target, EA::WebKit::TransformationMatrix &matrix, float opacity, EA::WebKit::CompositOperator op, EA::WebKit::TextureWrapMode wrap, EA::WebKit::Filters &filters)
{
std::cout << __FUNCTION__ << std::endl;
}
void GLRenderer::FillColor(uint32_t premultiplied_rgba32, EA::WebKit::FloatRect &target, EA::WebKit::TransformationMatrix &matrix, EA::WebKit::CompositOperator op)
{
std::cout << __FUNCTION__ << std::endl;
}
void GLRenderer::DrawOutline(uint32_t premultiplied_rgba32, EA::WebKit::FloatRect &target, EA::WebKit::TransformationMatrix &matrix)
{
std::cout << __FUNCTION__ << std::endl;
}
int32_t GLRenderer::MaxTextureSize(void)
{
return 4096;
}
void GLRenderer::Clear(EA::WebKit::ClearFlags flags, uint32_t premultiplied_rgba32, float z, uint32_t stencil)
{
std::cout << __FUNCTION__ << std::endl;
}
void GLRenderer::ScissorClip(EA::WebKit::IntRect axisAlignedRect)
{
std::cout << __FUNCTION__ << std::endl;
}
void GLRenderer::DrawStencil(EA::WebKit::TransformationMatrix &matrix, EA::WebKit::FloatRect &target, uint32_t stencilIndex)
{
std::cout << __FUNCTION__ << std::endl;
}
void GLRenderer::ClipAgainstStencil(uint32_t stencilIndex)
{
std::cout << __FUNCTION__ << std::endl;
}
bool GLRenderer::UseCustomClip()
{
return false;
}
void GLRenderer::BeginClip(EA::WebKit::TransformationMatrix &matrix, EA::WebKit::FloatRect &target)
{
std::cout << __FUNCTION__ << std::endl;
}
void GLRenderer::EndClip(void)
{
std::cout << __FUNCTION__ << std::endl;
}
EA::WebKit::IntRect GLRenderer::CurrentClipBound()
{
return EA::WebKit::IntRect(0, 0, 800, 600);
}
void GLRenderer::BeginPainting(void)
{
std::cout << __FUNCTION__ << std::endl;
}
void GLRenderer::EndPainting(void)
{
std::cout << __FUNCTION__ << std::endl;
}
//------------------------GL Surface ------------------------------------
GLSurface::GLSurface()
{
}
GLSurface::~GLSurface()
{
}
void GLSurface::Lock(SurfaceDescriptor *pSDOut, const EA::WebKit::IntRect *rect /*= NULL*/)
{
}
void GLSurface::Unlock(void)
{
}
void GLSurface::Release(void)
{
}
bool GLSurface::IsAllocated(void) const
{
return false;
}
void GLSurface::Reset(void)
{
// no idea what this is supposed to do
}
void GLSurface::AllocateSurface(int width, int height)
{
}
| 20.630573 | 246 | 0.68694 | [
"vector"
] |
babc919a75a2bcd3875356c0b8e0d94726a29df2 | 4,459 | cpp | C++ | chapter26/ex13_string_sort.cpp | ClassAteam/stroustrup-ppp | ea9e85d4ea9890038eb5611c3bc82734c8706ce7 | [
"MIT"
] | 124 | 2018-06-23T10:16:56.000Z | 2022-03-19T15:16:12.000Z | chapter26/ex13_string_sort.cpp | therootfolder/stroustrup-ppp | b1e936c9a67b9205fdc9712c42496b45200514e2 | [
"MIT"
] | 23 | 2018-02-08T20:57:46.000Z | 2021-10-08T13:58:29.000Z | chapter26/ex13_string_sort.cpp | ClassAteam/stroustrup-ppp | ea9e85d4ea9890038eb5611c3bc82734c8706ce7 | [
"MIT"
] | 65 | 2019-05-27T03:05:56.000Z | 2022-03-26T03:43:05.000Z | //
// Stroustrup - Programming Principles & Practice
//
// Chapter 26 Exercise 13
//
// Generate random strings and measure the time it takes to sort them using
// std::sort. Measure the time to sort 500000 strings and 5000000 strings.
//
/* OUTPUT (single thread):
Filling both vectors..
vector fills took: 51637430 microseconds
Sorting 500000 values:
vs1 sort took: 842695 microseconds
Sorting 5000000 values:
vs2 sort took: 10897702 microseconds
*/
/* OUTPUT (4 threads):
Filling both vectors..
vector fills took: 15212392 microseconds
Sorting 500000 values:
vs1 sort took: 745249 microseconds
Sorting 5000000 values:
vs2 sort took: 9821658 microseconds
*/
#include <iostream>
#include <stdexcept>
#include <random>
#include <chrono>
#include <vector>
#include <string>
#include <sstream>
#include <thread>
#include <mutex>
using namespace std::chrono;
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
// Timing
class Make_timer {
public:
Make_timer() : t1{system_clock::now()} { }
void reset() { t1 = system_clock::now(); }
void operator()(const std::string& label)
{
auto t2 = system_clock::now();
std::cout << " " << label << " took: "
<< duration_cast<microseconds>(t2-t1).count()
<< " microseconds\n";
}
private:
system_clock::time_point t1;
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
// Random string generation
std::string get_string()
{
constexpr unsigned int min = 1; // smallest string
constexpr unsigned int max = 100; // largest string
constexpr unsigned short low = 97; // low end of char-range
constexpr unsigned short high = 122; // high end of char-range
std::stringstream ss;
thread_local static std::default_random_engine ran;
auto len = std::uniform_int_distribution<>{min, max}(ran);
for (auto i = 0; i < len; ++i)
ss << std::uniform_int_distribution<char>{low, high}(ran);
return ss.str();
}
std::vector<std::string> random_fill(int n)
{
std::vector<std::string> vs;
vs.reserve(n);
for (auto i = 0; i < n; ++i)
vs.push_back(get_string());
return vs;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
// Multi-threading
void fill_task(std::vector<std::string>& vs, int n, std::mutex& m)
{
std::vector<std::string> v = random_fill(n);
std::unique_lock<std::mutex> lck {m};
std::copy(v.begin(), v.end(), std::back_inserter(vs));
}
std::vector<std::string> threaded_fill(int n)
// fill a large vector with random strings
{
std::vector<std::string> vs;
vs.reserve(n);
const int num_threads = std::thread::hardware_concurrency();
std::mutex mtx;
std::vector<std::thread> vt;
for (auto i = 0; i < num_threads; ++i)
vt.push_back(std::thread{fill_task, std::ref(vs), n / num_threads,
std::ref(mtx)});
for (auto& t : vt)
t.join();
std::cout << "vector size: " << vs.size() << '\n';
return vs;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
// Utility
void check_output(const std::vector<std::string>& vs)
{
std::cout << "first element: " << vs.front() << '\n'
<< "last element: " << '\n'
<< vs.back() << '\n';
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
int main()
try {
const int test1 = 500000;
const int test2 = 5000000;
Make_timer timer;
std::cout << "Filling both vectors..\n";
timer.reset();
//std::vector<std::string> vs1 = random_fill(test1);
//std::vector<std::string> vs2 = random_fill(test2);
std::vector<std::string> vs1 = threaded_fill(test1);
std::vector<std::string> vs2 = threaded_fill(test2);
timer("vector fills");
std::cout << "Sorting " << test1 << " values:\n";
timer.reset();
std::sort(vs1.begin(), vs1.end());
timer("vs1 sort");
std::cout << "Sorting " << test2 << " values:\n";
timer.reset();
std::sort(vs2.begin(), vs2.end());
timer("vs2 sort");
std::cout << "Output check:\n";
check_output(vs1);
check_output(vs2);
}
catch(std::exception& e) {
std::cerr << "Exception: " << e.what() << '\n';
return 1;
}
catch(...) {
std::cerr << "Unknown exception\n";
return 2;
}
| 27.024242 | 79 | 0.550572 | [
"vector"
] |
bac04df7a40efc8b6d48348d108ff0c9d85bcc36 | 887 | cpp | C++ | PASTAB2 - Warunek w tablicy/main.cpp | KrzaQ/mySPOJ | 14aecdabe700396b67c6b264a247797bd45c6031 | [
"MIT"
] | null | null | null | PASTAB2 - Warunek w tablicy/main.cpp | KrzaQ/mySPOJ | 14aecdabe700396b67c6b264a247797bd45c6031 | [
"MIT"
] | null | null | null | PASTAB2 - Warunek w tablicy/main.cpp | KrzaQ/mySPOJ | 14aecdabe700396b67c6b264a247797bd45c6031 | [
"MIT"
] | null | null | null | #include <cstdlib>
#include <ctime>
#include <array>
#include <algorithm>
#include <deque>
#include <functional>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <list>
#include <map>
#include <random>
#include <set>
#include <sstream>
#include <string>
#include <thread>
#include <utility>
#include <typeinfo>
using namespace std;
#define DBG(x) { cout << left << setw(50) << #x << boolalpha << (x) << endl; }
#define DBG_CONT(x) { cout << left << setw(50) << #x; for(auto const& v : (x)) \
cout << boolalpha << v << " "; cout << endl; }
int main()
{
int n;
cin >> n;
vector<int64_t> v;
v.reserve(n);
copy_n(istream_iterator<int64_t>(cin), n, back_inserter(v));
char c;
int64_t th;
cin >> c >> th;
if(c == '>'){
for(auto val : v){
if(val > th) cout << val << '\n';
}
}else{
for(auto val : v){
if(val < th) cout << val << '\n';
}
}
}
| 17.392157 | 80 | 0.59301 | [
"vector"
] |
bac1bcc46b6d9343cef3dc24837dac7c55ee78f7 | 8,056 | cc | C++ | chromium/extensions/browser/api/declarative/declarative_api.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | chromium/extensions/browser/api/declarative/declarative_api.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | chromium/extensions/browser/api/declarative/declarative_api.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "extensions/browser/api/declarative/declarative_api.h"
#include <stddef.h>
#include "base/base64.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/single_thread_task_runner.h"
#include "base/task_runner_util.h"
#include "base/values.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/web_contents.h"
#include "extensions/browser/api/declarative/rules_registry_service.h"
#include "extensions/browser/api/extensions_api_client.h"
#include "extensions/browser/extension_system.h"
#include "extensions/browser/guest_view/web_view/web_view_constants.h"
#include "extensions/browser/guest_view/web_view/web_view_guest.h"
#include "extensions/common/api/events.h"
#include "extensions/common/extension_api.h"
#include "extensions/common/permissions/permissions_data.h"
using extensions::api::events::Rule;
namespace AddRules = extensions::api::events::Event::AddRules;
namespace GetRules = extensions::api::events::Event::GetRules;
namespace RemoveRules = extensions::api::events::Event::RemoveRules;
namespace extensions {
namespace {
const char kDeclarativeEventPrefix[] = "declarative";
void ConvertBinaryDictionaryValuesToBase64(base::DictionaryValue* dict);
// Encodes |binary| as base64 and returns a new StringValue populated with the
// encoded string.
scoped_ptr<base::StringValue> ConvertBinaryToBase64(base::BinaryValue* binary) {
std::string binary_data = std::string(binary->GetBuffer(), binary->GetSize());
std::string data64;
base::Base64Encode(binary_data, &data64);
return scoped_ptr<base::StringValue>(new base::StringValue(data64));
}
// Parses through |args| replacing any BinaryValues with base64 encoded
// StringValues. Recurses over any nested ListValues, and calls
// ConvertBinaryDictionaryValuesToBase64 for any nested DictionaryValues.
void ConvertBinaryListElementsToBase64(base::ListValue* args) {
size_t index = 0;
for (base::ListValue::iterator iter = args->begin(); iter != args->end();
++iter, ++index) {
if ((*iter)->IsType(base::Value::TYPE_BINARY)) {
base::BinaryValue* binary = NULL;
if (args->GetBinary(index, &binary))
args->Set(index, ConvertBinaryToBase64(binary).release());
} else if ((*iter)->IsType(base::Value::TYPE_LIST)) {
base::ListValue* list;
(*iter)->GetAsList(&list);
ConvertBinaryListElementsToBase64(list);
} else if ((*iter)->IsType(base::Value::TYPE_DICTIONARY)) {
base::DictionaryValue* dict;
(*iter)->GetAsDictionary(&dict);
ConvertBinaryDictionaryValuesToBase64(dict);
}
}
}
// Parses through |dict| replacing any BinaryValues with base64 encoded
// StringValues. Recurses over any nested DictionaryValues, and calls
// ConvertBinaryListElementsToBase64 for any nested ListValues.
void ConvertBinaryDictionaryValuesToBase64(base::DictionaryValue* dict) {
for (base::DictionaryValue::Iterator iter(*dict); !iter.IsAtEnd();
iter.Advance()) {
if (iter.value().IsType(base::Value::TYPE_BINARY)) {
base::BinaryValue* binary = NULL;
if (dict->GetBinary(iter.key(), &binary))
dict->Set(iter.key(), ConvertBinaryToBase64(binary).release());
} else if (iter.value().IsType(base::Value::TYPE_LIST)) {
const base::ListValue* list;
iter.value().GetAsList(&list);
ConvertBinaryListElementsToBase64(const_cast<base::ListValue*>(list));
} else if (iter.value().IsType(base::Value::TYPE_DICTIONARY)) {
const base::DictionaryValue* dict;
iter.value().GetAsDictionary(&dict);
ConvertBinaryDictionaryValuesToBase64(
const_cast<base::DictionaryValue*>(dict));
}
}
}
} // namespace
RulesFunction::RulesFunction()
: rules_registry_(NULL) {
}
RulesFunction::~RulesFunction() {}
bool RulesFunction::HasPermission() {
std::string event_name;
EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &event_name));
int web_view_instance_id = 0;
EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(1, &web_view_instance_id));
// <webview> embedders use the declarativeWebRequest API via
// <webview>.onRequest.
if (web_view_instance_id != 0 &&
extension_->permissions_data()->HasAPIPermission(
extensions::APIPermission::kWebView))
return true;
return ExtensionFunction::HasPermission();
}
bool RulesFunction::RunAsync() {
std::string event_name;
EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &event_name));
int web_view_instance_id = 0;
EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(1, &web_view_instance_id));
int embedder_process_id = render_frame_host()->GetProcess()->GetID();
bool from_web_view = web_view_instance_id != 0;
// If we are not operating on a particular <webview>, then the key is 0.
int rules_registry_id = RulesRegistryService::kDefaultRulesRegistryID;
if (from_web_view) {
// Sample event names:
// webViewInternal.declarativeWebRequest.onRequest.
// webViewInternal.declarativeWebRequest.onMessage.
// The "webViewInternal." prefix is removed from the event name.
std::size_t found = event_name.find(kDeclarativeEventPrefix);
EXTENSION_FUNCTION_VALIDATE(found != std::string::npos);
event_name = event_name.substr(found);
rules_registry_id = WebViewGuest::GetOrGenerateRulesRegistryID(
embedder_process_id, web_view_instance_id);
}
// The following call will return a NULL pointer for apps_shell, but should
// never be called there anyways.
rules_registry_ = RulesRegistryService::Get(browser_context())->
GetRulesRegistry(rules_registry_id, event_name);
DCHECK(rules_registry_.get());
// Raw access to this function is not available to extensions, therefore
// there should never be a request for a nonexisting rules registry.
EXTENSION_FUNCTION_VALIDATE(rules_registry_.get());
if (content::BrowserThread::CurrentlyOn(rules_registry_->owner_thread())) {
bool success = RunAsyncOnCorrectThread();
SendResponse(success);
} else {
scoped_refptr<base::SingleThreadTaskRunner> thread_task_runner =
content::BrowserThread::GetMessageLoopProxyForThread(
rules_registry_->owner_thread());
base::PostTaskAndReplyWithResult(
thread_task_runner.get(), FROM_HERE,
base::Bind(&RulesFunction::RunAsyncOnCorrectThread, this),
base::Bind(&RulesFunction::SendResponse, this));
}
return true;
}
bool EventsEventAddRulesFunction::RunAsyncOnCorrectThread() {
ConvertBinaryListElementsToBase64(args_.get());
scoped_ptr<AddRules::Params> params(AddRules::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
error_ = rules_registry_->AddRules(extension_id(), params->rules);
if (error_.empty())
results_ = AddRules::Results::Create(params->rules);
return error_.empty();
}
bool EventsEventRemoveRulesFunction::RunAsyncOnCorrectThread() {
scoped_ptr<RemoveRules::Params> params(RemoveRules::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
if (params->rule_identifiers.get()) {
error_ = rules_registry_->RemoveRules(extension_id(),
*params->rule_identifiers);
} else {
error_ = rules_registry_->RemoveAllRules(extension_id());
}
return error_.empty();
}
bool EventsEventGetRulesFunction::RunAsyncOnCorrectThread() {
scoped_ptr<GetRules::Params> params(GetRules::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
std::vector<linked_ptr<Rule> > rules;
if (params->rule_identifiers.get()) {
rules_registry_->GetRules(
extension_id(), *params->rule_identifiers, &rules);
} else {
rules_registry_->GetAllRules(extension_id(), &rules);
}
results_ = GetRules::Results::Create(rules);
return true;
}
} // namespace extensions
| 37.64486 | 80 | 0.737339 | [
"vector"
] |
bac2062efdc12fc9c96160de68c0501af4bee60a | 747 | cpp | C++ | Introductory Problems/Gray Code.cpp | razouq/cses | 82534f4ac37a690b5cd72ab094d5276bd01dd64e | [
"MIT"
] | 3 | 2021-03-14T18:47:13.000Z | 2021-03-19T09:59:56.000Z | Introductory Problems/Gray Code.cpp | razouq/cses | 82534f4ac37a690b5cd72ab094d5276bd01dd64e | [
"MIT"
] | null | null | null | Introductory Problems/Gray Code.cpp | razouq/cses | 82534f4ac37a690b5cd72ab094d5276bd01dd64e | [
"MIT"
] | null | null | null | #include "bits/stdc++.h"
#pragma GCC optimize ("O3")
#pragma GCC target ("sse4")
#define ll long long
#define ull unsigned long long
#define F first
#define S second
#define PB push_back
#define POB pop_back
using namespace std;
int main(){
// freopen("input.in", "r", stdin);
// freopen("output.out", "w", stdout);
ios::sync_with_stdio(0);
cin.tie();
int n;
cin>>n;
n--;
vector<string> v;
vector<string> u;
v.PB("0");
u.PB("1");
while(n--) {
for(int i = u.size()-1; i >= 0; i--) {
v.PB(u[i]);
}
u = v;
for(string &item : v) item = "0" + item;
for(string &item : u) item = "1" + item;
}
for(string item : v) cout<<item<<endl;
for(int i = u.size()-1; i >= 0; i--) cout<<u[i]<<endl;
cout<<endl;
return 0;
}
| 16.977273 | 55 | 0.576975 | [
"vector"
] |
bac3d70072926fc8a4baf35e2f3a23062b5da9b6 | 36,015 | hh | C++ | sigrlinn/sigrlinn.hh | raptoravis/sigrlinn | 37fd2f8c73e38e9c266301517f4292e0d6e536ef | [
"MIT"
] | 140 | 2015-01-13T22:40:16.000Z | 2022-01-15T00:53:47.000Z | sigrlinn/sigrlinn.hh | raptoravis/sigrlinn | 37fd2f8c73e38e9c266301517f4292e0d6e536ef | [
"MIT"
] | 17 | 2015-01-23T15:15:14.000Z | 2019-03-16T20:30:52.000Z | sigrlinn/sigrlinn.hh | raptoravis/sigrlinn | 37fd2f8c73e38e9c266301517f4292e0d6e536ef | [
"MIT"
] | 22 | 2015-01-19T13:00:55.000Z | 2021-03-27T09:04:34.000Z | /// The MIT License (MIT)
///
/// Copyright (c) 2015 Kirill Bazhenov
/// Copyright (c) 2015 BitBox, Ltd.
///
/// 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 <stdint.h>
#include <wchar.h>
namespace sgfx
{
template <typename T, int tag>
struct Handle
{
T value = static_cast<T>(0);
inline explicit Handle(const T& newValue) : value(newValue) {}
inline Handle() {}
inline Handle(const Handle& d) : value(d.value) {}
inline Handle& operator=(const Handle& d) { value = d.value; return *this; }
inline Handle& operator=(const T& d) { value = d; return *this; }
inline bool operator==(const Handle& handle) { return value == handle.value; }
inline bool operator!=(const Handle& handle) { return value != handle.value; }
inline static Handle invalidHandle() { return Handle(static_cast<T>(0)); }
inline friend bool operator==(const Handle& h0, const Handle& h1) { return h0.value == h1.value; }
};
typedef Handle<void*, 1> VertexShaderHandle;
typedef Handle<void*, 2> HullShaderHandle;
typedef Handle<void*, 3> DomainShaderHandle;
typedef Handle<void*, 4> GeometryShaderHandle;
typedef Handle<void*, 5> PixelShaderHandle;
typedef Handle<void*, 6> SurfaceShaderHandle; // VS+HS+DS+GS+PS
typedef Handle<void*, 7> ComputeShaderHandle;
typedef Handle<void*, 8> PipelineStateHandle;
typedef Handle<void*, 9> VertexFormatHandle;
typedef Handle<void*, 10> SamplerStateHandle;
// same tag for textures is intended
typedef Handle<void*, 11> TextureHandle;
typedef Handle<void*, 11> Texture1DHandle;
typedef Handle<void*, 11> Texture2DHandle;
typedef Handle<void*, 11> Texture3DHandle;
typedef Handle<void*, 11> CubemapHandle;
// render target
typedef Handle<void*, 12> RenderTargetHandle;
// different tag for buffers is intended
typedef Handle<void*, 13> BufferHandle;
typedef Handle<void*, 14> ConstantBufferHandle;
// draw queue
typedef Handle<void*, 15> DrawQueueHandle;
// compute queue
typedef Handle<void*, 16> ComputeQueueHandle;
// buffers
namespace BufferFlags {
enum : uint32_t {
VertexBuffer = (1U << 0), // can be set as a vertex buffer
IndexBuffer = (1U << 1), // can be set as an index buffer
StructuredBuffer = (1U << 2), // can be set as a structured buffer
CPURead = (1U << 3), // can be mapped to be read by the CPU
CPUWrite = (1U << 4), // can be mapped to be written by the CPU
GPUWrite = (1U << 5), // can be written by the GPU
GPUCounter = (1U << 6), // can be written by the GPU with atomic counter usage
GPUAppend = (1U << 7), // can be appended by the GPU
StreamOutput = (1U << 8), // can be used as a stream output buffer
IndirectArgs = (1U << 9), // can be used as a drawIndirect args buffer
};
}
enum class MapType : size_t
{
Read = 0,
Write = 1,
Count
};
namespace TextureFlags {
enum : uint32_t {
RenderTarget = (1U << 0),
DepthStencil = (1U << 1),
CPURead = (1U << 2),
GPUWrite = (1U << 3),
GPUCounter = (1U << 4)
};
}
// formats
enum class PrimitiveTopology : size_t
{
TriangleList,
TriangleStrip,
PointList,
Count
};
enum class TextureFilter : size_t
{
MinMagMip_Point,
MinMag_Point_Mip_Linear,
Min_Point_Mag_Linear_Mip_Point,
Min_Point_MagMip_Linear,
Min_Linear_MagMip_Point,
Min_Linear_Mag_Point_Mip_Linear,
MinMag_Linear_Mip_Point,
MinMagMip_Linear,
Anisotropic,
Count
};
enum class AddressMode : size_t
{
Wrap,
Mirror,
Clamp,
Border,
Count
};
enum class DataFormat : size_t
{
BC1, // DXT1
BC2, // DXT3
BC3, // DXT5
BC4, // LATC1/ATI1
BC5, // LATC2/ATI2
BC6H, // BC6H
BC7, // BC7
ETC1, // ETC1 RGB8
ETC2, // ETC2 RGB8
ETC2A, // ETC2 RGBA8
ETC2A1, // ETC2 RGB8A1
PTC12, // PVRTC1 RGB 2BPP
PTC14, // PVRTC1 RGB 4BPP
PTC12A, // PVRTC1 RGBA 2BPP
PTC14A, // PVRTC1 RGBA 4BPP
PTC22, // PVRTC2 RGBA 2BPP
PTC24, // PVRTC2 RGBA 4BPP
UnknownCompressed, // compressed formats above
R1,
R8,
R16,
R16F,
R32I,
R32U,
R32F,
RG8,
RG16,
RG16F,
RG32I,
RG32U,
RG32F,
RGB32I,
RGB32U,
RGB32F,
RGBA8,
RGBA16,
RGBA16F,
RGBA32I,
RGBA32U,
RGBA32F,
R11G11B10F,
UnknownDepth, // depth formats below
D16,
D24S8,
D32F,
Count
};
inline bool isCompressedFormat(DataFormat format) { return format < DataFormat::UnknownCompressed; }
inline bool isDepthFormat(DataFormat format) { return format > DataFormat::UnknownDepth; }
// render state
enum class FillMode : size_t
{
Solid,
Wireframe,
Count
};
enum class CullMode : size_t
{
Back,
Front,
None,
Count
};
enum class CounterDirection : size_t
{
CW,
CCW,
Count
};
enum class BlendFactor : size_t
{
Zero,
One,
SrcAlpha,
DstAlpha,
OneMinusSrcAlpha,
OneMinusDstAlpha,
SrcColor,
DstColor,
OneMinusSrcColor,
OneMinusDstColor,
Count
};
enum class BlendOp : size_t
{
Add,
Subtract,
RevSubtract,
Min,
Max,
Count
};
namespace RenderTargetSlot {
enum {
Count = 8
};
}
enum class ColorWriteMask : uint8_t
{
Red = (1U << 0),
Green = (1U << 1),
Blue = (1U << 2),
Alpha = (1U << 3),
All = Red | Green | Blue | Alpha
};
enum class DepthWriteMask : size_t
{
Zero,
All,
Count
};
enum class ComparisonFunc : size_t
{
Always,
Never,
Less,
LessEqual,
Greater,
GreaterEqual,
Equal,
NotEqual,
Count
};
typedef ComparisonFunc DepthFunc;
typedef ComparisonFunc StencilFunc;
typedef ComparisonFunc SamplerFunc;
enum class StencilOp : size_t
{
Keep,
Zero,
Replace,
Increment,
Decrement,
Count
};
struct RasterizerState
{
FillMode fillMode = FillMode::Solid;
CullMode cullMode = CullMode::Back;
CounterDirection counterDirection = CounterDirection::CCW;
};
struct BlendDesc
{
bool blendEnabled = false;
ColorWriteMask writeMask = ColorWriteMask::All;
BlendFactor srcBlend = BlendFactor::One;
BlendFactor dstBlend = BlendFactor::Zero;
BlendOp blendOp = BlendOp::Add;
BlendFactor srcBlendAlpha = BlendFactor::One;
BlendFactor dstBlendAlpha = BlendFactor::Zero;
BlendOp blendOpAlpha = BlendOp::Add;
};
struct BlendState
{
BlendDesc blendDesc;
bool separateBlendEnabled = false;
BlendDesc renderTargetBlendDesc[RenderTargetSlot::Count];
bool alphaToCoverageEnabled = false;
};
struct StencilDesc
{
StencilFunc stencilFunc = StencilFunc::Always;
StencilOp failOp = StencilOp::Keep;
StencilOp depthFailOp = StencilOp::Keep;
StencilOp passOp = StencilOp::Keep;
};
struct DepthStencilState
{
bool depthEnabled = true;
DepthWriteMask writeMask = DepthWriteMask::All;
DepthFunc depthFunc = DepthFunc::Less;
bool stencilEnabled = false;
uint32_t stencilRef;
uint8_t stencilReadMask; // not implemented
uint8_t stencilWriteMask;
StencilDesc frontFaceStencilDesc;
StencilDesc backFaceStencilDesc;
};
struct PipelineStateDescriptor
{
RasterizerState rasterizerState;
BlendState blendState;
DepthStencilState depthStencilState;
SurfaceShaderHandle shader;
VertexFormatHandle vertexFormat;
};
// vertex stage
struct VertexElementDescriptor // TODO: rework to make it more compatible with GL and DX
{
const char* semanticName; // not used on GL
uint32_t semanticIndex; // not used on GL
DataFormat format;
uint32_t slot; // not used on GL
uint64_t offset;
bool perInstanceData;
};
struct SamplerStateDescriptor
{
TextureFilter filter = TextureFilter::MinMagMip_Linear;
AddressMode addressU = AddressMode::Clamp;
AddressMode addressV = AddressMode::Clamp;
AddressMode addressW = AddressMode::Clamp;
float lodBias = 0.0F;
uint32_t maxAnisotropy = 1;
ComparisonFunc comparisonFunc = ComparisonFunc::Never;
uint32_t borderColor = 0xFFFFFFFF;
float minLod = -3.402823466e+38F;
float maxLod = 3.402823466e+38F;
};
struct RenderTargetDescriptor
{
uint32_t numColorTextures = 0;
sgfx::TextureHandle colorTextures[RenderTargetSlot::Count];
sgfx::TextureHandle depthStencilTexture;
};
// caps
namespace GPUCaps {
enum : uint64_t {
// general GPU features
GeometryShader = (1UL << 0),
TessellationShader = (1UL << 1),
ComputeShader = (1UL << 2),
MultipleRenderTargets = (1UL << 3),
TextureArray = (1UL << 4),
CubemapArray = (1UL << 5),
StreamOutput = (1UL << 6),
AlphaToCoverage = (1UL << 7),
SeparateBlend = (1UL << 8),
StructuredBuffer = (1UL << 9),
RWStructuredBuffer = (1UL << 10),
// texture compression support
TextureCompressionDXT = (1UL << 11),
TextureCompressionPVR = (1UL << 12),
TextureCompressionETC = (1UL << 13),
// texture format support
TextureFormatInteger = (1UL << 14),
TextureFormatFloat = (1UL << 15)
};
}
// misc
typedef void(*ErrorReportFunc)(const char*);
//=============================================================================
bool initD3D11(void* d3dDevice, void* d3dContext, void* d3dSwapChain);
bool initD3D12(void* d3dDevice);
bool initOpenGL();
#ifdef NDA_CODE_AMD_MANTLE
// NDACodeStripper v0.17: 1 line removed
#endif
void shutdown();
typedef void* (*AllocFunc)(size_t size);
typedef void (*FreeFunc)(void* ptr);
// memory
void setAllocator(AllocFunc nalloc, FreeFunc nfree);
void* allocate(size_t size);
void deallocate(void* ptr);
uint64_t getGPUCaps();
// shader compiler
enum class ShaderCompileVersion : size_t
{
v4_0,
v5_0
};
enum class ShaderCompileTarget : size_t
{
VS,
HS,
DS,
GS,
PS,
CS
};
struct ShaderCompileMacro
{
const char* name;
const char* value;
};
namespace ShaderCompileFlags {
enum : uint64_t {
Debug = (1UL << 0),
Strict = (1UL << 1),
IEEStrict = (1UL << 2),
Optimize0 = (1UL << 3),
Optimize1 = (1UL << 4),
Optimize2 = (1UL << 5),
Optimize3 = (1UL << 6)
};
}
bool compileShader(
const char* sourceCode,
size_t sourceCodeSize,
ShaderCompileVersion version,
ShaderCompileTarget target,
const ShaderCompileMacro* macros,
size_t macrosSize,
uint64_t flags,
ErrorReportFunc errorFunc,
void*& outData, // use deallocate() to dispose this
size_t& outDataSize
);
// shaders
VertexShaderHandle createVertexShader(const void* data, size_t dataSize);
void releaseVertexShader(VertexShaderHandle handle);
HullShaderHandle createHullShader(const void* data, size_t dataSize);
void releaseHullShader(HullShaderHandle handle);
DomainShaderHandle createDomainShader(const void* data, size_t dataSize);
void releaseDomainShader(DomainShaderHandle handle);
GeometryShaderHandle createGeometryShader(const void* data, size_t dataSize);
void releaseGeometryShader(GeometryShaderHandle handle);
PixelShaderHandle createPixelShader(const void* data, size_t dataSize);
void releasePixelShader(PixelShaderHandle handle);
SurfaceShaderHandle linkSurfaceShader(
VertexShaderHandle vs,
HullShaderHandle hs,
DomainShaderHandle ds,
GeometryShaderHandle gs,
PixelShaderHandle ps
);
void releaseSurfaceShader(SurfaceShaderHandle handle);
// compute shader stuff
ComputeQueueHandle createComputeQueue(ComputeShaderHandle shader);
void releaseComputeQueue(ComputeQueueHandle handle);
void setConstantBuffer(ComputeQueueHandle handle, uint32_t idx, ConstantBufferHandle buffer);
void setResource(ComputeQueueHandle handle, uint32_t idx, BufferHandle resource);
void setResource(ComputeQueueHandle handle, uint32_t idx, TextureHandle resource);
void setResourceRW(ComputeQueueHandle handle, uint32_t idx, BufferHandle resource);
void setResourceRW(ComputeQueueHandle handle, uint32_t idx, TextureHandle resource);
void submit(ComputeQueueHandle handle, uint32_t x, uint32_t y, uint32_t z);
ComputeShaderHandle createComputeShader(const void* data, size_t dataSize);
void releaseComputeShader(ComputeShaderHandle handle);
// pipeline state
VertexFormatHandle createVertexFormat(
VertexElementDescriptor* elements,
size_t size,
void* shaderBytecode, size_t shaderBytecodeSize,
ErrorReportFunc errorReport
);
void releaseVertexFormat(VertexFormatHandle handle);
PipelineStateHandle createPipelineState(const PipelineStateDescriptor& desc);
void releasePipelineState(PipelineStateHandle handle);
// buffers
BufferHandle createBuffer(uint32_t flags, const void* mem, size_t size, size_t stride);
void releaseBuffer(BufferHandle handle);
void* mapBuffer(BufferHandle handle, MapType type);
void unmapBuffer(BufferHandle handle);
void copyBufferData(BufferHandle handle, size_t offset, size_t size, const void* mem);
void clearBufferRW(BufferHandle handle, uint32_t value);
void clearBufferRW(BufferHandle handle, float value);
ConstantBufferHandle createConstantBuffer(const void* mem, size_t size);
void updateConstantBuffer(ConstantBufferHandle handle, const void* mem);
void releaseConstantBuffer(ConstantBufferHandle handle);
// textures
SamplerStateHandle createSamplerState(const SamplerStateDescriptor& desc);
void releaseSamplerState(SamplerStateHandle handle);
Texture1DHandle createTexture1D(uint32_t width, DataFormat format, uint32_t numMipmaps, uint32_t flags);
Texture2DHandle createTexture2D(uint32_t width, uint32_t height, DataFormat format, uint32_t numMipmaps, uint32_t flags);
Texture3DHandle createTexture3D(uint32_t width, uint32_t height, uint32_t depth, DataFormat format, uint32_t numMipmaps, uint32_t flags);
void clearTextureRW(TextureHandle handle, uint32_t value);
void clearTextureRW(TextureHandle handle, float value);
void* mapTexture(TextureHandle handle, MapType type);
void unmapTexture(TextureHandle handle);
void updateTexture(
TextureHandle handle, const void* mem,
uint32_t mip,
size_t offsetX, size_t sizeX,
size_t offsetY, size_t sizeY,
size_t offsetZ, size_t sizeZ,
size_t rowPitch, size_t depthPitch
);
void releaseTexture(TextureHandle handle);
// async buffer copying
void copyResource(TextureHandle src, TextureHandle dst);
void copyResource(BufferHandle src, BufferHandle dst);
void copyResource(ConstantBufferHandle src, ConstantBufferHandle dst);
// render targets
Texture2DHandle getBackBuffer();
RenderTargetHandle createRenderTarget(const RenderTargetDescriptor& desc);
void releaseRenderTarget(RenderTargetHandle handle);
void setViewport(uint32_t width, uint32_t height, float minDepth, float maxDepth);
void setResourceRW(RenderTargetHandle handle, uint32_t slot, BufferHandle resource);
void setResourceRW(RenderTargetHandle handle, uint32_t slot, TextureHandle resource);
void setRenderTarget(RenderTargetHandle handle);
void clearRenderTarget(RenderTargetHandle handle, uint32_t color);
void clearRenderTarget(RenderTargetHandle handle, uint32_t slot, uint32_t color);
void clearDepthStencil(RenderTargetHandle handle, float depth, uint8_t stencil);
void present(uint32_t swapInterval);
// drawing
DrawQueueHandle createDrawQueue(PipelineStateHandle state);
void releaseDrawQueue(DrawQueueHandle handle);
// per queue
void setSamplerState(DrawQueueHandle handle, uint32_t idx, SamplerStateHandle sampler);
// per draw call
void setPrimitiveTopology(DrawQueueHandle qd, PrimitiveTopology topology);
void setVertexBuffer(DrawQueueHandle dq, BufferHandle vb, uint32_t idx = 0);
void setIndexBuffer(DrawQueueHandle dq, BufferHandle ib);
void setConstantBuffer(DrawQueueHandle handle, uint32_t idx, ConstantBufferHandle buffer);
void setResource(DrawQueueHandle handle, uint32_t idx, BufferHandle resource);
void setResource(DrawQueueHandle handle, uint32_t idx, TextureHandle resource);
void draw(DrawQueueHandle dq, uint32_t count, uint32_t startVertex);
void drawIndexed(DrawQueueHandle dq, uint32_t count, uint32_t startIndex, uint32_t startVertex);
void drawInstanced(DrawQueueHandle dq, uint32_t instanceCount, uint32_t count, uint32_t startVertex, uint32_t startInstance);
void drawIndexedInstanced(DrawQueueHandle dq, uint32_t instanceCount, uint32_t count, uint32_t startIndex, uint32_t startVertex, uint32_t startInstance);
void drawInstancedIndirect(DrawQueueHandle dq, BufferHandle indirectArgs, size_t argsOffset);
void drawIndexedInstancedIndirect(DrawQueueHandle dq, BufferHandle indirectArgs, size_t argsOffset);
void submit(DrawQueueHandle handle);
void flush();
// performance markers
void beginPerfEvent(const wchar_t* name);
void endPerfEvent();
// optional interop with D3D11
#ifdef SGFX_D3D11_INTEROP
namespace d3d11
{
ID3D11Buffer* getNativeBuffer(ConstantBufferHandle handle);
ID3D11Resource* getNativeResource(BufferHandle handle);
ID3D11ShaderResourceView* getNativeSRV(BufferHandle handle);
ID3D11UnorderedAccessView* getNativeUAV(BufferHandle handle);
ID3D11Resource* getNativeResource(TextureHandle handle);
ID3D11ShaderResourceView* getNativeSRV(TextureHandle handle);
ID3D11UnorderedAccessView* getNativeUAV(TextureHandle handle);
ID3D11SamplerState* getNativeSamplerState(SamplerStateHandle handle);
ID3D11RenderTargetView* getNativeRTV(RenderTargetHandle handle, size_t idx);
ID3D11DepthStencilView* getNativeDSV(RenderTargetHandle handle);
}
#endif
// internal classes and data
#ifdef SGFX_INTERNAL_IMPLEMENTATION
namespace SGFX_NS_INTERNAL
{
// default array allocator
struct DefaultAllocator
{
static inline uint8_t* Allocate(size_t size) { return reinterpret_cast<uint8_t*>(allocate(size)); }
static inline void Free(uint8_t* ptr) { deallocate(ptr); }
};
///
/// ImmutableArray represents an abstract sequence container that cannot change in size.
///
/// It is guaranteed that all the data in this container uses contiguous storage locations for
/// its elements, which means that the elements can also be accessed using offsets on regular
/// pointers to its elements, and just as efficiently as in C arrays.
///
template <typename T>
class ImmutableArray
{
protected:
size_t capacity = 0;
size_t size = 0;
T* pointer = nullptr;
ImmutableArray() {}
ImmutableArray(const ImmutableArray& other) = delete;
virtual ~ImmutableArray() {}
public:
SGFX_FORCE_INLINE T* GetData() { return pointer; }
SGFX_FORCE_INLINE const T* GetData() const { return pointer; }
SGFX_FORCE_INLINE T& operator[](size_t index) { return pointer[index]; }
SGFX_FORCE_INLINE const T& operator[](size_t index) const { return pointer[index]; }
// range for support
SGFX_FORCE_INLINE T* begin() const { return pointer; }
SGFX_FORCE_INLINE T* end() const { return pointer + size; }
// size and capacity
SGFX_FORCE_INLINE size_t GetSize() const { return size; }
SGFX_FORCE_INLINE size_t GetCapacity() const { return capacity; }
// utils
SGFX_FORCE_INLINE bool IsEmpty() const { return size == 0; }
SGFX_FORCE_INLINE ptrdiff_t Find(const T& e)
{
for (size_t i = 0; i < GetSize(); ++i)
if (pointer[i] == e)
return i;
return -1;
}
template <typename Pred>
SGFX_FORCE_INLINE ptrdiff_t Find(const Pred& pred)
{
for (size_t i = 0; i < GetSize(); ++i)
if (pred(pointer[i]))
return i;
return -1;
}
};
///
/// DynamicArray is a concrete sequence container representing a contiguous array that can change in
/// size.
///
/// Just like ImmutableArray, DynamicArray uses contiguous storage locations for its elements.
/// But unlike immutable arrays, dynamic array size can change dynamically, with its storage being
/// handled automatically by the container.
///
/// Internally, DynamicArray uses a dynamically allocated array to store its elements. This array
/// may need to be reallocated in order to grow in size when new elements are inserted, which
/// implies allocating a new array and moving all elements to it. This is a relatively expensive
/// task in terms of processing time, and thus, dynamic arrays do not reallocate each time an
/// element is added to the container, instead DynamicArray::kGrowAmount is used to control growing
/// size.
///
/// DynamicArray is very efficient with random access pattern, while adding and removing elements
/// is less effective compared to List.
///
template <typename T, size_t I = 32, size_t G = 64, typename A = DefaultAllocator>
class DynamicArray final : public ImmutableArray<T>
{
protected:
using ImmutableArray<T>::capacity;
using ImmutableArray<T>::size;
using ImmutableArray<T>::pointer;
private:
enum
{
kInplaceStorageSize = I,
kGrowAmount = G
};
uint8_t _inplaceStorage[kInplaceStorageSize * sizeof(T)];
SGFX_FORCE_INLINE void DeleteContents()
{
uint8_t* ptr = reinterpret_cast<uint8_t*>(pointer);
if (ptr != _inplaceStorage) {
A::Free(ptr);
pointer = reinterpret_cast<T*>(_inplaceStorage);
}
}
public:
using ImmutableArray<T>::GetData;
using ImmutableArray<T>::IsEmpty;
using ImmutableArray<T>::Find;
SGFX_FORCE_INLINE DynamicArray()
{
capacity = kInplaceStorageSize;
pointer = reinterpret_cast<T*>(_inplaceStorage);
}
SGFX_FORCE_INLINE DynamicArray(const DynamicArray& other)
{
capacity = kInplaceStorageSize;
pointer = reinterpret_cast<T*>(_inplaceStorage);
Resize(other.GetSize());
for (size_t i = 0; i < size; ++i)
::new (&pointer[i]) T(other[i]);
}
SGFX_FORCE_INLINE DynamicArray& operator=(const DynamicArray& other)
{
Resize(other.GetSize());
for (size_t i = 0; i < size; ++i)
::new (&pointer[i]) T(other[i]);
return *this;
}
SGFX_FORCE_INLINE DynamicArray& operator=(const ImmutableArray<T>& other)
{
Resize(other.GetSize());
for (size_t i = 0; i < size; ++i)
::new (&pointer[i]) T(other[i]);
return *this;
}
SGFX_FORCE_INLINE ~DynamicArray()
{
Purge();
}
SGFX_FORCE_INLINE void Clear()
{
for (size_t i = 0; i < size; ++i)
pointer[i].~T();
size = 0;
}
SGFX_FORCE_INLINE void Purge()
{
Clear();
DeleteContents();
size = 0;
capacity = kInplaceStorageSize;
}
SGFX_FORCE_INLINE void Resize(size_t newSize)
{
if (newSize == size) return; // fool protection
if (newSize > capacity) {
Grow(newSize - size);
}
if (newSize < size) {
for (size_t i = newSize; i < size; ++i)
pointer[i].~T();
} else {
for (size_t i = size; i < newSize; ++i)
::new (&pointer[i]) T();
}
size = newSize;
}
SGFX_FORCE_INLINE void Reserve(size_t numElements)
{
if (numElements > capacity)
Grow(numElements - capacity);
}
SGFX_FORCE_INLINE void Grow(size_t numElements)
{
size_t newCapacity = size + numElements;
capacity = newCapacity;
if (newCapacity > kInplaceStorageSize) {
T* ptr = reinterpret_cast<T*>(A::Allocate(newCapacity * sizeof(T)));
for (size_t i = 0; i < size; ++i)
::new (&ptr[i]) T(static_cast<T&&>(pointer[i]));
DeleteContents();
pointer = ptr;
}
}
SGFX_FORCE_INLINE void Merge(const DynamicArray& other)
{
if (!other.IsEmpty()) {
Reserve(GetSize() + other.GetSize());
for (const T& element : other)
Add(element);
}
}
SGFX_FORCE_INLINE void Add(const T& element)
{
if (size >= capacity)
Grow(kGrowAmount);
T* ptr = pointer + size;
::new (ptr)T(element);
size++;
}
template <typename ...Args>
SGFX_FORCE_INLINE void EmplaceAdd(Args&&... args)
{
if (size >= capacity)
Grow(kGrowAmount);
T* ptr = pointer + size;
::new (ptr)T(static_cast<Args&&>(args)...);
size++;
}
SGFX_FORCE_INLINE void Remove(size_t index)
{
if (index < size) {
pointer[index].~T();
T* ptr = pointer + index;
for (size_t i = index + 1; i < size; ++i) {
::new (ptr)T(static_cast<T&&>(pointer[i]));
ptr++;
ptr->~T();
}
size--;
}
}
SGFX_FORCE_INLINE void Remove(const T& element)
{
ptrdiff_t index = Find(element);
if (index != -1)
Remove(index);
}
};
// emulated draw queues for pre-DX12 APIs (DX11 and GL4)
struct ShaderResource final
{
bool isTexture = false;
void* value = nullptr;
inline ShaderResource() {}
inline ShaderResource(bool texture, void* newHandle)
: isTexture(texture), value(newHandle)
{}
};
struct DrawCall final
{
enum Type : uint32_t
{
Draw = 0,
DrawIndexed = 1,
DrawInstanced = 2,
DrawIndexedInstanced = 3,
DrawInstancedIndirect = 4,
DrawIndexedInstancedIndirect = 5
};
enum
{
kMaxConstantBuffers = 8,
kMaxShaderResources = 128,
kMaxVertexBuffers = 16
};
ConstantBufferHandle constantBuffers[kMaxConstantBuffers];
ShaderResource shaderResources[kMaxShaderResources];
BufferHandle vertexBuffers[kMaxVertexBuffers];
BufferHandle indexBuffer;
BufferHandle indirectArgsBuffer;
size_t indirectArgsOffset;
PrimitiveTopology primitiveTopology;
uint32_t instanceCount;
uint32_t count;
uint32_t startVertex;
uint32_t startIndex;
uint32_t startInstance;
Type type;
};
class DrawQueue final
{
public:
typedef DynamicArray<DrawCall, 4096, 4096> DrawCallArray;
private:
PipelineStateHandle state;
DrawCall currentDrawCall;
DrawCallArray drawCalls;
public:
enum
{
kMaxSamplerStates = 8
};
SamplerStateHandle samplerStates[kMaxSamplerStates];
DrawQueue(PipelineStateHandle _state) : state(_state) {}
SGFX_FORCE_INLINE PipelineStateHandle getState() const { return state; }
SGFX_FORCE_INLINE const DrawCallArray& getDrawCalls() const { return drawCalls; }
SGFX_FORCE_INLINE void clear()
{
drawCalls.Clear();
}
SGFX_FORCE_INLINE void setPrimitiveTopology(PrimitiveTopology topology) { currentDrawCall.primitiveTopology = topology; }
SGFX_FORCE_INLINE void setVertexBuffer(uint32_t idx, BufferHandle handle) { currentDrawCall.vertexBuffers[idx] = handle; }
SGFX_FORCE_INLINE void setIndexBuffer(BufferHandle handle) { currentDrawCall.indexBuffer = handle; }
SGFX_FORCE_INLINE void setSamplerState(uint32_t idx, SamplerStateHandle handle)
{
samplerStates[idx] = handle;
}
SGFX_FORCE_INLINE void setConstantBuffer(uint32_t idx, ConstantBufferHandle resource)
{
currentDrawCall.constantBuffers[idx] = resource;
}
SGFX_FORCE_INLINE void setResource(uint32_t idx, BufferHandle resource)
{
currentDrawCall.shaderResources[idx] = ShaderResource(false, resource.value);
}
SGFX_FORCE_INLINE void setResource(uint32_t idx, TextureHandle resource)
{
currentDrawCall.shaderResources[idx] = ShaderResource(true, resource.value);
}
SGFX_FORCE_INLINE void draw(uint32_t count, uint32_t startVertex)
{
currentDrawCall.count = count;
currentDrawCall.startVertex = startVertex;
currentDrawCall.startIndex = 0;
currentDrawCall.type = DrawCall::Draw;
drawCalls.Add(currentDrawCall);
std::memset(¤tDrawCall, 0, sizeof(currentDrawCall));
}
SGFX_FORCE_INLINE void drawIndexed(uint32_t count, uint32_t startIndex, uint32_t startVertex)
{
currentDrawCall.count = count;
currentDrawCall.startVertex = startVertex;
currentDrawCall.startIndex = startIndex;
currentDrawCall.type = DrawCall::DrawIndexed;
drawCalls.Add(currentDrawCall);
std::memset(¤tDrawCall, 0, sizeof(currentDrawCall));
}
SGFX_FORCE_INLINE void drawInstanced(uint32_t instanceCount, uint32_t count, uint32_t startVertex, uint32_t startInstance)
{
currentDrawCall.instanceCount = instanceCount;
currentDrawCall.count = count;
currentDrawCall.startVertex = startVertex;
currentDrawCall.startIndex = 0;
currentDrawCall.startInstance = startInstance;
currentDrawCall.type = DrawCall::DrawInstanced;
drawCalls.Add(currentDrawCall);
std::memset(¤tDrawCall, 0, sizeof(currentDrawCall));
}
SGFX_FORCE_INLINE void drawIndexedInstanced(uint32_t instanceCount, uint32_t count, uint32_t startIndex, uint32_t startVertex, uint32_t startInstance)
{
currentDrawCall.instanceCount = instanceCount;
currentDrawCall.count = count;
currentDrawCall.startVertex = startVertex;
currentDrawCall.startIndex = startIndex;
currentDrawCall.startInstance = startInstance;
currentDrawCall.type = DrawCall::DrawIndexedInstanced;
drawCalls.Add(currentDrawCall);
std::memset(¤tDrawCall, 0, sizeof(currentDrawCall));
}
SGFX_FORCE_INLINE void drawInstancedIndirect(BufferHandle indirectArgs, size_t argsOffset)
{
currentDrawCall.type = DrawCall::DrawInstancedIndirect;
currentDrawCall.indirectArgsBuffer = indirectArgs;
currentDrawCall.indirectArgsOffset = argsOffset;
drawCalls.Add(currentDrawCall);
std::memset(¤tDrawCall, 0, sizeof(currentDrawCall));
}
SGFX_FORCE_INLINE void drawIndexedInstancedIndirect(BufferHandle indirectArgs, size_t argsOffset)
{
currentDrawCall.type = DrawCall::DrawIndexedInstancedIndirect;
currentDrawCall.indirectArgsBuffer = indirectArgs;
currentDrawCall.indirectArgsOffset = argsOffset;
drawCalls.Add(currentDrawCall);
std::memset(¤tDrawCall, 0, sizeof(currentDrawCall));
}
};
struct ComputeQueue final
{
enum
{
kMaxSamplerStates = 8
};
enum
{
kMaxConstantBuffers = 8,
kMaxShaderResources = 128,
kMaxShaderResourcesRW = 8
};
SamplerStateHandle samplerStates[kMaxSamplerStates];
ConstantBufferHandle constantBuffers[kMaxConstantBuffers];
ShaderResource shaderResources[kMaxShaderResources];
ShaderResource shaderResourcesRW[kMaxShaderResourcesRW];
ComputeShaderHandle shader;
SGFX_FORCE_INLINE void setConstantBuffer(uint32_t idx, ConstantBufferHandle resource)
{
constantBuffers[idx] = resource;
}
SGFX_FORCE_INLINE void setResource(uint32_t idx, BufferHandle resource)
{
shaderResources[idx] = ShaderResource(false, resource.value);
}
SGFX_FORCE_INLINE void setResource(uint32_t idx, TextureHandle resource)
{
shaderResources[idx] = ShaderResource(true, resource.value);
}
SGFX_FORCE_INLINE void setResourceRW(uint32_t idx, BufferHandle resource)
{
shaderResourcesRW[idx] = ShaderResource(false, resource.value);
}
SGFX_FORCE_INLINE void setResourceRW(uint32_t idx, TextureHandle resource)
{
shaderResourcesRW[idx] = ShaderResource(true, resource.value);
}
};
}
#endif
}
| 31.047414 | 173 | 0.629127 | [
"render",
"solid"
] |
bac44d96619f7173164e055f8828d9a885994651 | 17,305 | cpp | C++ | Core/Contents/Source/PolyEntity.cpp | Guendeli/Polycode | f458010cb81a4c78874e29ff7738eae4e13b12bb | [
"MIT"
] | 1 | 2020-08-25T06:30:49.000Z | 2020-08-25T06:30:49.000Z | Core/Contents/Source/PolyEntity.cpp | Guendeli/Polycode | f458010cb81a4c78874e29ff7738eae4e13b12bb | [
"MIT"
] | null | null | null | Core/Contents/Source/PolyEntity.cpp | Guendeli/Polycode | f458010cb81a4c78874e29ff7738eae4e13b12bb | [
"MIT"
] | null | null | null | /*
Copyright (C) 2011 by Ivan Safrin
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "PolyEntity.h"
#include "PolyRenderer.h"
using namespace Polycode;
Rotation::Rotation() {
pitch = 0;
yaw = 0;
roll = 0;
}
Entity::Entity() : EventDispatcher() {
userData = NULL;
scale.set(1,1,1);
renderer = NULL;
enabled = true;
depthTest = true;
visible = true;
bBoxRadius = 0;
color.setColor(1.0f,1.0f,1.0f,1.0f);
parentEntity = NULL;
matrixDirty = true;
matrixAdj = 1.0f;
billboardMode = false;
billboardRoll = false;
billboardIgnoreScale = false;
backfaceCulled = true;
depthOnly = false;
depthWrite = true;
ignoreParentMatrix = false;
alphaTest = false;
blendingMode = Renderer::BLEND_MODE_NORMAL;
lockMatrix = false;
renderWireframe = false;
colorAffectsChildren = true;
visibilityAffectsChildren = true;
ownsChildren = false;
enableScissor = false;
editorOnly = false;
}
Entity *Entity::getEntityById(String id, bool recursive) {
for(int i=0;i<children.size();i++) {
if(children[i]->id == id) {
return children[i];
} else {
if(recursive) {
Entity *ret = children[i]->getEntityById(id, recursive);
if(ret) {
return ret;
}
}
}
}
return NULL;
}
Entity *Entity::Clone(bool deepClone, bool ignoreEditorOnly) {
Entity *newEntity = new Entity();
applyClone(newEntity, deepClone, ignoreEditorOnly);
return newEntity;
}
void Entity::applyClone(Entity *clone, bool deepClone, bool ignoreEditorOnly) {
clone->ownsChildren = ownsChildren;
clone->position = position;
clone->rotation = rotation;
clone->scale = scale;
clone->color = color;
clone->custEntityType = custEntityType;
clone->billboardMode = billboardMode;
clone->billboardRoll = billboardRoll;
clone->alphaTest = alphaTest;
clone->backfaceCulled = backfaceCulled;
clone->renderWireframe = renderWireframe;
clone->depthWrite = depthWrite;
clone->depthTest = depthTest;
clone->blendingMode = blendingMode;
clone->colorAffectsChildren;
clone->visibilityAffectsChildren = visibilityAffectsChildren;
clone->depthOnly = depthOnly;
clone->setUserData(getUserData());
clone->entityProps = entityProps;
clone->bBox = bBox;
clone->ignoreParentMatrix = ignoreParentMatrix;
clone->enableScissor = enableScissor;
clone->scissorBox = scissorBox;
clone->editorOnly = editorOnly;
clone->id = id;
for(int i=0; i < tags.size(); i++) {
clone->addTag(tags[i]);
}
clone->setRenderer(renderer);
if(deepClone) {
for(int i=0; i < children.size(); i++) {
if(children[i]->editorOnly && ignoreEditorOnly) {
} else {
Entity *childClone = children[i]->Clone(deepClone, ignoreEditorOnly);
clone->addChild(childClone);
}
}
}
}
std::vector<Entity*> Entity::getEntitiesByTag(String tag, bool recursive) {
std::vector<Entity*> retVector;
for(int i=0;i<children.size();i++) {
if(children[i]->hasTag(tag)) {
retVector.push_back(children[i]);
}
if(recursive) {
std::vector<Entity*> childVector = children[i]->getEntitiesByTag(tag, recursive);
retVector.insert(retVector.end(), childVector.begin(), childVector.end());
}
}
return retVector;
}
void Entity::setUserData(void *userData) {
this->userData = userData;
}
void *Entity::getUserData() {
return userData;
}
Entity *Entity::getParentEntity() const {
return parentEntity;
}
Color Entity::getCombinedColor() const {
if(parentEntity) {
if(parentEntity->colorAffectsChildren)
return color * parentEntity->getCombinedColor();
else
return color;
} else {
return color;
}
}
Matrix4 Entity::getLookAtMatrix(const Vector3 &loc, const Vector3 &upVector) {
rebuildTransformMatrix();
Vector3 D;
if(parentEntity)
D = loc - (parentEntity->getConcatenatedMatrix() *position);
else
D = loc - position;
Vector3 back = D * -1;
back.Normalize();
Vector3 right = back.crossProduct(upVector) ;
right.Normalize();
right = right * -1;
Vector3 up = back.crossProduct(right);
Matrix4 newMatrix(right.x, right.y, right.z, 0,
up.x, up.y, up.z, 0,
back.x, back.y, back.z, 0,
0, 0 , 0, 1);
return newMatrix;
}
void Entity::lookAt(const Vector3 &loc, const Vector3 &upVector) {
Matrix4 newMatrix = getLookAtMatrix(loc, upVector);
rotationQuat.createFromMatrix(newMatrix);
matrixDirty = true;
}
void Entity::lookAtEntity(Entity *entity, const Vector3 &upVector) {
if(entity->getParentEntity())
lookAt(entity->getParentEntity()->getConcatenatedMatrix() * (entity->getPosition()), upVector);
else
lookAt(entity->getPosition(), upVector);
}
void Entity::removeChild(Entity *entityToRemove) {
for(int i=0;i<children.size();i++) {
if(children[i] == entityToRemove) {
children.erase(children.begin()+i);
}
}
}
unsigned int Entity::getNumChildren() {
return children.size();
}
Entity *Entity::getChildAtIndex(unsigned int index) {
if(index < children.size()) {
return children[index];
}
return NULL;
}
void Entity::addChild(Entity *newChild) {
addEntity(newChild);
}
void Entity::setColor(Color color) {
this->color.setColor(&color);
}
void Entity::setColorInt(int r, int g, int b, int a) {
color.setColorRGBA(r,g, b, a);
}
void Entity::setColor(Number r, Number g, Number b, Number a) {
color.setColor(r,g,b,a);
}
void Entity::recalculateBBox() {
}
void Entity::setBlendingMode(int newBlendingMode) {
blendingMode = newBlendingMode;
}
Number Entity::getBBoxRadius() const {
Number compRad;
Number biggest = bBoxRadius;
for(int i=0;i<children.size();i++) {
compRad = children[i]->getCompoundBBoxRadius();
if(compRad > biggest)
biggest = compRad;
}
return biggest;
}
Number Entity::getCompoundBBoxRadius() const {
Number compRad;
Number biggest = bBoxRadius + position.distance(Vector3(0,0,0));
for(int i=0;i<children.size();i++) {
compRad = children[i]->getCompoundBBoxRadius();
if(compRad > biggest)
biggest = compRad;
}
return biggest;
}
void Entity::setBBoxRadius(Number rad) {
bBoxRadius = rad;
}
Entity::~Entity() {
if(ownsChildren) {
for(int i=0; i < children.size(); i++) {
delete children[i];
}
}
}
Vector3 Entity::getChildCenter() const {
return childCenter;
}
Matrix4 Entity::buildPositionMatrix() {
Matrix4 posMatrix;
posMatrix.m[3][0] = position.x*matrixAdj;
posMatrix.m[3][1] = position.y*matrixAdj;
posMatrix.m[3][2] = position.z*matrixAdj;
return posMatrix;
}
void Entity::rebuildTransformMatrix() {
if(lockMatrix)
return;
if(billboardMode){
transformMatrix.identity();
} else {
transformMatrix = rotationQuat.createMatrix();
}
Matrix4 scaleMatrix;
scaleMatrix.m[0][0] *= scale.x;
scaleMatrix.m[1][1] *= scale.y;
scaleMatrix.m[2][2] *= scale.z;
Matrix4 posMatrix = buildPositionMatrix();
transformMatrix = scaleMatrix*transformMatrix*posMatrix;
matrixDirty = false;
}
void Entity::doUpdates() {
Update();
for(int i=0; i < children.size(); i++) {
children[i]->doUpdates();
}
}
void Entity::checkTransformSetters() {
if(_position != position) {
_position = position;
matrixDirty = true;
}
if(_scale != scale) {
_scale = scale;
matrixDirty = true;
}
if(_rotation != rotation) {
_rotation = rotation;
rebuildRotation();
matrixDirty = true;
}
}
void Entity::updateEntityMatrix() {
checkTransformSetters();
if(matrixDirty)
rebuildTransformMatrix();
for(int i=0; i < children.size(); i++) {
children[i]->updateEntityMatrix();
}
}
Vector3 Entity::getCompoundScale() const {
if(parentEntity != NULL) {
Vector3 parentScale = parentEntity->getCompoundScale();
return Vector3(scale.x * parentScale.x, scale.y * parentScale.y,scale.z * parentScale.z);
}
else
return scale;
}
Matrix4 Entity::getConcatenatedRollMatrix() const {
Quaternion q;
q.createFromAxisAngle(0.0f, 0.0f, 1.0f, _rotation.roll*matrixAdj);
Matrix4 transformMatrix = q.createMatrix();
if(parentEntity != NULL)
return transformMatrix * parentEntity->getConcatenatedRollMatrix();
else
return transformMatrix;
}
void Entity::transformAndRender() {
if(!renderer || !enabled)
return;
if(depthOnly) {
renderer->drawToColorBuffer(false);
}
bool isScissorEnabled;
Polycode::Rectangle oldScissorBox;
if(enableScissor) {
isScissorEnabled = renderer->isScissorEnabled();
oldScissorBox = renderer->getScissorBox();
renderer->enableScissor(true);
Polycode::Rectangle finalScrissorBox = scissorBox;
// make sure that our scissor box is constrained to the parent one if it exists
if(isScissorEnabled) {
if(finalScrissorBox.x < oldScissorBox.x)
finalScrissorBox.x = oldScissorBox.x;
if(finalScrissorBox.x > oldScissorBox.x + oldScissorBox.w)
finalScrissorBox.x = oldScissorBox.x + oldScissorBox.w;
if(finalScrissorBox.x+finalScrissorBox.w > oldScissorBox.x + oldScissorBox.w)
finalScrissorBox.w = oldScissorBox.x - finalScrissorBox.x;
if(finalScrissorBox.y < oldScissorBox.y)
finalScrissorBox.y = oldScissorBox.y;
if(finalScrissorBox.y > oldScissorBox.y + oldScissorBox.h)
finalScrissorBox.y = oldScissorBox.y + oldScissorBox.h;
if(finalScrissorBox.y+finalScrissorBox.h > oldScissorBox.y + oldScissorBox.h)
finalScrissorBox.h = oldScissorBox.y - finalScrissorBox.y;
}
renderer->setScissorBox(finalScrissorBox);
}
renderer->pushMatrix();
if(ignoreParentMatrix && parentEntity) {
renderer->multModelviewMatrix(parentEntity->getConcatenatedMatrix().inverse());
// renderer->setCurrentModelMatrix(parentEntity->getConcatenatedMatrix().inverse());
}
renderer->multModelviewMatrix(transformMatrix);
renderer->setCurrentModelMatrix(transformMatrix);
renderer->setVertexColor(color.r,color.g,color.b,color.a);
if(billboardMode) {
if(billboardIgnoreScale) {
renderer->billboardMatrix();
} else {
renderer->billboardMatrixWithScale(getCompoundScale());
}
if(billboardRoll) {
renderer->multModelviewMatrix(getConcatenatedRollMatrix());
}
}
if(!depthWrite)
renderer->enableDepthWrite(false);
else
renderer->enableDepthWrite(true);
if(!depthTest)
renderer->enableDepthTest(false);
else
renderer->enableDepthTest(true);
renderer->enableAlphaTest(alphaTest);
Color combined = getCombinedColor();
renderer->setVertexColor(combined.r,combined.g,combined.b,combined.a);
renderer->setBlendingMode(blendingMode);
renderer->enableBackfaceCulling(backfaceCulled);
int mode = renderer->getRenderMode();
if(renderWireframe)
renderer->setRenderMode(Renderer::RENDER_MODE_WIREFRAME);
else
renderer->setRenderMode(Renderer::RENDER_MODE_NORMAL);
if(visible) {
Render();
}
if(visible || (!visible && !visibilityAffectsChildren)) {
adjustMatrixForChildren();
renderChildren();
}
renderer->setRenderMode(mode);
renderer->popMatrix();
if(!depthWrite)
renderer->enableDepthWrite(true);
if(depthOnly) {
renderer->drawToColorBuffer(true);
}
if(enableScissor) {
renderer->enableScissor(isScissorEnabled);
renderer->setScissorBox(oldScissorBox);
}
}
void Entity::setRenderer(Renderer *renderer) {
this->renderer = renderer;
for(int i=0;i<children.size();i++) {
children[i]->setRenderer(renderer);
}
}
void Entity::addEntity(Entity *newChild) {
newChild->setRenderer(renderer);
newChild->setParentEntity(this);
children.push_back(newChild);
}
void Entity::renderChildren() {
for(int i=0;i<children.size();i++) {
children[i]->transformAndRender();
}
}
void Entity::dirtyMatrix(bool val) {
matrixDirty = val;
}
void Entity::setRotationQuat(Number w, Number x, Number y, Number z) {
rotationQuat.w = w;
rotationQuat.x = x;
rotationQuat.y = y;
rotationQuat.z = z;
matrixDirty = true;
}
Quaternion Entity::getRotationQuat() const {
return rotationQuat;
}
Vector3 Entity::getScale() const {
return scale;
}
Matrix4 Entity::getConcatenatedMatrixRelativeTo(Entity *relativeEntity) {
checkTransformSetters();
if(matrixDirty)
rebuildTransformMatrix();
if(parentEntity != NULL && parentEntity != relativeEntity)
return transformMatrix * parentEntity->getConcatenatedMatrixRelativeTo(relativeEntity);
else
return transformMatrix;
}
Matrix4 Entity::getConcatenatedMatrix() {
checkTransformSetters();
if(matrixDirty)
rebuildTransformMatrix();
if(parentEntity != NULL)
return transformMatrix * parentEntity->getConcatenatedMatrix();
else
return transformMatrix;
}
const Matrix4& Entity::getTransformMatrix() const {
return transformMatrix;
}
void Entity::Pitch(Number pitch) {
rotation.pitch += pitch;
matrixDirty = true;
}
void Entity::Yaw(Number yaw) {
rotation.yaw += yaw;
matrixDirty = true;
}
void Entity::Roll(Number roll) {
rotation.roll += roll;
matrixDirty = true;
}
void Entity::setRoll(Number roll) {
rotation.roll = roll;
matrixDirty = true;
}
void Entity::setPitch(Number pitch) {
rotation.pitch = pitch;
matrixDirty = true;
}
void Entity::setYaw(Number yaw) {
rotation.yaw = yaw;
matrixDirty = true;
}
void Entity::rebuildRotation() {
rotationQuat.fromAxes(_rotation.pitch, _rotation.yaw, _rotation.roll);
}
void Entity::setEntityProp(const String& propName, const String& propValue) {
for(int i=0; i < entityProps.size(); i++) {
if(entityProps[i].propName == propName) {
entityProps[i].propValue = propValue;
return;
}
}
EntityProp entityProp;
entityProp.propName = propName;
entityProp.propValue = propValue;
entityProps.push_back(entityProp);
}
String Entity::getEntityProp(const String& propName) {
for(int i=0; i < entityProps.size(); i++) {
if(entityProps[i].propName == propName) {
return entityProps[i].propValue;
}
}
return "null";
}
Vector3 Entity::getCombinedPosition() const {
if(parentEntity != NULL)
return (parentEntity->getCombinedPosition())+position;
else
return position;
}
void Entity::setParentEntity(Entity *entity) {
parentEntity = entity;
}
Number Entity::getPitch() const {
return rotation.pitch;
}
Number Entity::getYaw() const {
return rotation.yaw;
}
Number Entity::getRoll() const {
return rotation.roll;
}
void Entity::setTransformByMatrixPure(const Matrix4& matrix) {
transformMatrix = matrix;
}
void Entity::setPosition(const Vector3 &posVec) {
position = posVec;
matrixDirty = true;
}
void Entity::setPositionX(Number x) {
position.x = x;
matrixDirty = true;
}
void Entity::setPositionY(Number y) {
position.y = y;
matrixDirty = true;
}
void Entity::setPositionZ(Number z) {
position.z = z;
matrixDirty = true;
}
void Entity::setScaleX(Number x) {
scale.x = x;
matrixDirty = true;
}
void Entity::setScaleY(Number y) {
scale.y = y;
matrixDirty = true;
}
void Entity::setScaleZ(Number z) {
scale.z = z;
matrixDirty = true;
}
void Entity::setScale(const Vector3 &v) {
scale.x = v.x;
scale.y = v.y;
scale.z = v.z;
matrixDirty = true;
}
void Entity::setPosition(Number x, Number y, Number z) {
position.x = x;
position.y = y;
position.z = z;
matrixDirty = true;
}
void Entity::Translate(const Vector3 &tVec) {
position += tVec;
matrixDirty = true;
}
void Entity::Translate(Number x, Number y, Number z) {
position.x += x;
position.y += y;
position.z += z;
matrixDirty = true;
}
void Entity::Scale(Number x, Number y, Number z) {
scale.x *= x;
scale.y *= y;
scale.z *= z;
matrixDirty = true;
}
void Entity::setScale(Number x, Number y, Number z) {
scale.x = x;
scale.y = y;
scale.z = z;
matrixDirty = true;
}
Vector3 Entity::getPosition() const {
return position;
}
Number Entity::getCombinedPitch() const {
if(parentEntity != NULL)
return parentEntity->getCombinedPitch()+rotation.pitch;
else
return rotation.pitch;
}
Number Entity::getCombinedYaw() const {
if(parentEntity != NULL)
return parentEntity->getCombinedYaw()+rotation.yaw;
else
return rotation.yaw;
}
Number Entity::getCombinedRoll() const {
if(parentEntity != NULL)
return parentEntity->getCombinedRoll()+rotation.roll;
else
return rotation.roll;
}
unsigned int Entity::getNumTags() const {
return tags.size();
}
String Entity::getTagAtIndex(unsigned int index) const {
if(index < tags.size())
return tags[index];
return "";
}
bool Entity::hasTag(String tag) const {
for(int i=0; i < tags.size(); i++) {
if(tags[i] == tag)
return true;
}
return false;
}
void Entity::clearTags() {
tags.clear();
}
void Entity::addTag(String tag) {
tags.push_back(tag);
}
| 22.444877 | 99 | 0.711875 | [
"render",
"vector"
] |
bac8439f4b49fe6ed9ddf1f375252852e1042e69 | 1,587 | hpp | C++ | PA4/src/primitives/surface.hpp | dowoncha/COMP575 | 6e48bdd80cb1a3e677c07655640efa941325e59c | [
"MIT"
] | null | null | null | PA4/src/primitives/surface.hpp | dowoncha/COMP575 | 6e48bdd80cb1a3e677c07655640efa941325e59c | [
"MIT"
] | null | null | null | PA4/src/primitives/surface.hpp | dowoncha/COMP575 | 6e48bdd80cb1a3e677c07655640efa941325e59c | [
"MIT"
] | null | null | null | /******************************************************************************
*
* filename: Surfaces.h
* author : Do Won Cha
*
*****************************************************************************/
#pragma once
#ifndef _RAY_SURFACES_
#define _RAY_SURFACES_
#include <Eigen/Core>
#include <string>
namespace raytracer
{
using namespace Eigen;
class Surface;
class Ray;
/**
* Hit data is returned upon call to IntersectSurfaces.
*/
struct HitData
{
Vector3f hit_point, hit_time;
Vector3f normal;
float t, tMax;
Surface* hit_surface;
HitData() :
t(0),
tMax(10000.0f),
hit_surface(nullptr)
{ }
};
/**
* Object's that have a position.
*/
class Node
{
public:
Node() : position_(0.0f) { }
Node(Vector3f position) : position_(position) { }
virtual ~Node() { }
Vector3f position() const { return position_; }
void set_position(Vector3f position) { position_ = position; }
protected:
Vector3f position_;
};
/**
* Abstract class for objects that require a position and a material.
*/
class Surface : public Node
{
public:
Surface(Vector3f position, std::string material_name = "") :
Node(position),
material_name_(material_name)
{ }
virtual ~Surface() { }
virtual bool Intersect(const Ray& ray, HitData& hit) = 0;
virtual Vector3f normal() const;
void set_material(std::string material_name) { material_name_ = material_name; }
std::string material() const { return material_name_; }
protected:
std::string material_name_;
};
} // end of namespace raytracer
#endif // RAY_SURFACES end
| 18.892857 | 82 | 0.613737 | [
"object"
] |
bacaf5e6c12e5676590356f471212134eae4e76f | 623 | cpp | C++ | Algorithms/Complete Search/Generating Subsets/Algorithm1.cpp | NixonZ/Code_Chef | 5bffb7c1f88e2754b31d724158f684dc2c91089b | [
"Apache-2.0"
] | null | null | null | Algorithms/Complete Search/Generating Subsets/Algorithm1.cpp | NixonZ/Code_Chef | 5bffb7c1f88e2754b31d724158f684dc2c91089b | [
"Apache-2.0"
] | null | null | null | Algorithms/Complete Search/Generating Subsets/Algorithm1.cpp | NixonZ/Code_Chef | 5bffb7c1f88e2754b31d724158f684dc2c91089b | [
"Apache-2.0"
] | null | null | null | #include <bits/stdc++.h>
#include <time.h>
using namespace std;
//Method 1- Recursive Search returns all subsets of {0,1,...n-1}
int n;
vector<int> subsets;
void search(int k)
{
if(k==n)
{
if(!subsets.size())
cout<<"empty\n";
else
{
cout<<'[';
for(auto x:subsets)
cout<<x <<',';
cout<<"\b]\n";
}
}
else
{
search(k+1); //this search doesnt get k
subsets.push_back(k);
search(k+1); //this search gets k
subsets.pop_back();
}
}
int main()
{
srand(time(0));
::n=rand()%5;
cout<<"n=" <<::n <<endl;
search(0);
}
//very beautiful O(2^n) algorithm
| 16.837838 | 64 | 0.540931 | [
"vector"
] |
bace23e58cbd0a8eeda711bf0bd365e42aa46f7f | 12,674 | cxx | C++ | ds/adsi/winnt/cuar.cxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | ds/adsi/winnt/cuar.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | ds/adsi/winnt/cuar.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //---------------------------------------------------------------------------
//
// Microsoft Windows
// Copyright (C) Microsoft Corporation, 1992 - 1995
//
// File: cuar.cxx
//
// Contents: Account Restrictions Propset for the User object
//
// History: 11-1-95 krishnag Created.
// 8-5-96 ramv Modified to be consistent with spec
//
//
// PROPERTY_RW(AccountDisabled, boolean, 1) I
// PROPERTY_RW(AccountExpirationDate, DATE, 2) I
// PROPERTY_RO(AccountCanExpire, boolean, 3) I
// PROPERTY_RO(PasswordCanExpire, boolean, 4) I
// PROPERTY_RW(GraceLoginsAllowed, long, 5) NI
// PROPERTY_RW(GraceLoginsRemaining, long, 6) NI
// PROPERTY_RW(IsAccountLocked, boolean, 7) I
// PROPERTY_RW(IsAdmin, boolean, 8) I
// PROPERTY_RW(LoginHours, VARIANT, 9) I
// PROPERTY_RW(LoginWorkstations, VARIANT, 10) I
// PROPERTY_RW(MaxLogins, long, 11) I
// PROPERTY_RW(MaxStorage, long, 12) I
// PROPERTY_RW(PasswordExpirationDate, DATE, 13) I
// PROPERTY_RW(PasswordRequired, boolean, 14) I
// PROPERTY_RW(RequireUniquePassword,boolean, 15) I
//
//
//----------------------------------------------------------------------------
#include "winnt.hxx"
#pragma hdrstop
// Class CWinNTUser
STDMETHODIMP
CWinNTUser::get_AccountDisabled(THIS_ VARIANT_BOOL FAR* retval)
{
HRESULT hr = S_OK;
VARIANT var;
VariantInit(&var);
hr = Get(L"UserFlags", &var);
BAIL_ON_FAILURE(hr);
if (V_I4(&var) & UF_ACCOUNTDISABLE) {
*retval = VARIANT_TRUE;
}else {
*retval = VARIANT_FALSE;
}
error:
RRETURN_EXP_IF_ERR(hr);
}
STDMETHODIMP
CWinNTUser::put_AccountDisabled(THIS_ VARIANT_BOOL fAccountDisabled)
{
HRESULT hr = S_OK;
VARIANT var;
VariantInit(&var);
hr = Get(L"UserFlags", &var);
BAIL_ON_FAILURE(hr);
if (fAccountDisabled == VARIANT_TRUE) {
V_I4(&var) |= UF_ACCOUNTDISABLE;
} else if (fAccountDisabled == VARIANT_FALSE){
V_I4(&var) &= ~UF_ACCOUNTDISABLE;
}else {
BAIL_ON_FAILURE(hr = E_FAIL);
}
hr = Put(L"UserFlags", var);
BAIL_ON_FAILURE(hr);
error:
RRETURN_EXP_IF_ERR(hr);
}
STDMETHODIMP
CWinNTUser::get_AccountExpirationDate(THIS_ DATE FAR* retval)
{
GET_PROPERTY_DATE((IADsUser *)this, AccountExpirationDate);
}
STDMETHODIMP
CWinNTUser::put_AccountExpirationDate(THIS_ DATE daAccountExpirationDate)
{
PUT_PROPERTY_DATE((IADsUser *)this, AccountExpirationDate);
}
STDMETHODIMP
CWinNTUser::get_GraceLoginsAllowed(THIS_ long FAR* retval)
{
GET_PROPERTY_LONG((IADsUser *)this, GraceLoginsAllowed);
}
STDMETHODIMP
CWinNTUser::put_GraceLoginsAllowed(THIS_ long lGraceLoginsAllowed)
{
PUT_PROPERTY_LONG((IADsUser *)this, GraceLoginsAllowed);
}
STDMETHODIMP
CWinNTUser::get_GraceLoginsRemaining(THIS_ long FAR* retval)
{
GET_PROPERTY_LONG((IADsUser *)this, GraceLoginsRemaining);
}
STDMETHODIMP
CWinNTUser::put_GraceLoginsRemaining(THIS_ long lGraceLoginsRemaining)
{
PUT_PROPERTY_LONG((IADsUser *)this, GraceLoginsRemaining);
}
STDMETHODIMP
CWinNTUser::get_IsAccountLocked(THIS_ VARIANT_BOOL FAR* retval)
{
HRESULT hr = S_OK;
DWORD dwUserFlags = 0;
VARIANT var;
if(_fUseCacheForAcctLocked) {
// see comment on _fUseCacheForAcctLocked in cuser.hxx
VariantInit(&var);
hr = Get(L"UserFlags", &var);
BAIL_ON_FAILURE(hr);
if (V_I4(&var) & UF_LOCKOUT) {
*retval = VARIANT_TRUE;
}else {
*retval = VARIANT_FALSE;
}
}
else {
hr = GetUserFlags(&dwUserFlags);
BAIL_ON_FAILURE(hr);
VariantInit(&var);
hr = Get(L"UserFlags", &var);
BAIL_ON_FAILURE(hr);
if (dwUserFlags & UF_LOCKOUT) {
V_I4(&var) |= UF_LOCKOUT;
*retval = VARIANT_TRUE;
}
else {
V_I4(&var) &= ~UF_LOCKOUT;
*retval = VARIANT_FALSE;
}
hr = Put(L"UserFlags", var);
BAIL_ON_FAILURE(hr);
_fUseCacheForAcctLocked = TRUE;
}
error:
RRETURN_EXP_IF_ERR(hr);
}
STDMETHODIMP
CWinNTUser::put_IsAccountLocked(THIS_ VARIANT_BOOL fIsAccountLocked)
{
HRESULT hr = S_OK;
VARIANT var;
VariantInit(&var);
hr = Get(L"UserFlags", &var);
BAIL_ON_FAILURE(hr);
if (fIsAccountLocked == VARIANT_TRUE) {
// only the system can lockout an account. Can't do it using ADSI.
BAIL_ON_FAILURE(hr = E_INVALIDARG);
} else if (fIsAccountLocked == VARIANT_FALSE){
V_I4(&var) &= ~UF_LOCKOUT;
}else {
BAIL_ON_FAILURE(hr = E_FAIL);
}
hr = Put(L"UserFlags", var);
BAIL_ON_FAILURE(hr);
_fUseCacheForAcctLocked = TRUE;
error:
RRETURN_EXP_IF_ERR(hr);
}
STDMETHODIMP
CWinNTUser::get_LoginHours(THIS_ VARIANT FAR* retval)
{
GET_PROPERTY_VARIANT((IADsUser *)this,LoginHours);
}
STDMETHODIMP
CWinNTUser::put_LoginHours(THIS_ VARIANT vLoginHours)
{
PUT_PROPERTY_VARIANT((IADsUser *)this,LoginHours);
}
STDMETHODIMP
CWinNTUser::get_LoginWorkstations(THIS_ VARIANT FAR* retval)
{
GET_PROPERTY_VARIANT((IADsUser *)this,LoginWorkstations);
}
STDMETHODIMP
CWinNTUser::put_LoginWorkstations(THIS_ VARIANT vLoginWorkstations)
{
PUT_PROPERTY_VARIANT((IADsUser *)this,LoginWorkstations);
}
STDMETHODIMP
CWinNTUser::get_MaxLogins(THIS_ long FAR* retval)
{
RRETURN(E_ADS_PROPERTY_NOT_SUPPORTED);
}
STDMETHODIMP
CWinNTUser::put_MaxLogins(THIS_ long lMaxLogins)
{
RRETURN(E_ADS_PROPERTY_NOT_SUPPORTED);
}
STDMETHODIMP
CWinNTUser::get_MaxStorage(THIS_ long FAR* retval)
{
GET_PROPERTY_LONG((IADsUser *)this, MaxStorage);
}
STDMETHODIMP
CWinNTUser::put_MaxStorage(THIS_ long lMaxStorage)
{
PUT_PROPERTY_LONG((IADsUser *)this, MaxStorage);
}
STDMETHODIMP
CWinNTUser::get_PasswordExpirationDate(THIS_ DATE FAR* retval)
{
HRESULT hr = S_OK;
VARIANT var;
SYSTEMTIME SystemTime;
SYSTEMTIME LocalTime;
FILETIME FileTime;
DWORD dwCurrentTime = 0L;
DWORD dwLastMod = 0L;
DWORD dwPasswordAge = 0L;
DWORD dwMaxPasswordAge = 0L;
DWORD dwPasswordExpDate = 0L;
VariantInit(&var);
hr = Get(L"PasswordAge", &var);
BAIL_ON_FAILURE(hr);
dwPasswordAge = V_I4(&var);
VariantInit(&var);
hr = Get(L"MaxPasswordAge", &var);
BAIL_ON_FAILURE(hr);
dwMaxPasswordAge = V_I4(&var);
LARGE_INTEGER Time;
GetSystemTime(&SystemTime);
SystemTimeToFileTime(&SystemTime, &FileTime);
memset(&Time, 0, sizeof(LARGE_INTEGER));
Time.LowPart = FileTime.dwLowDateTime;
Time.HighPart = FileTime.dwHighDateTime
;
RtlTimeToSecondsSince1970 ((PLARGE_INTEGER)&Time, &dwCurrentTime);
dwLastMod = dwCurrentTime - dwPasswordAge;
if (dwMaxPasswordAge == TIMEQ_FOREVER) {
BAIL_ON_FAILURE(hr = E_ADS_PROPERTY_NOT_FOUND);
}else {
dwPasswordExpDate = dwLastMod + dwMaxPasswordAge;
}
hr = ConvertDWORDtoDATE( dwPasswordExpDate, retval);
error:
RRETURN_EXP_IF_ERR(hr);
}
STDMETHODIMP
CWinNTUser::put_PasswordExpirationDate(THIS_ DATE daPasswordExpirationDate)
{
PUT_PROPERTY_DATE((IADsUser *)this, PasswordExpirationDate);
}
STDMETHODIMP
CWinNTUser::get_PasswordRequired(THIS_ VARIANT_BOOL FAR* retval)
{
HRESULT hr = S_OK;
long lnUserFlags = 0L;
VARIANT var;
VariantInit(&var);
hr = Get(L"UserFlags", &var);
BAIL_ON_FAILURE(hr);
if (V_I4(&var) & UF_PASSWD_NOTREQD) {
*retval = VARIANT_FALSE;
}else {
*retval = VARIANT_TRUE;
}
error:
RRETURN_EXP_IF_ERR(hr);
}
STDMETHODIMP
CWinNTUser::put_PasswordRequired(THIS_ VARIANT_BOOL fPasswordRequired)
{
HRESULT hr = S_OK;
VARIANT var;
VariantInit(&var);
hr = Get(L"UserFlags", &var);
BAIL_ON_FAILURE(hr);
if (fPasswordRequired == VARIANT_TRUE) {
V_I4(&var) &= ~UF_PASSWD_NOTREQD;
} else if (fPasswordRequired == VARIANT_FALSE){
V_I4(&var) |= UF_PASSWD_NOTREQD;
}else {
BAIL_ON_FAILURE(hr = E_FAIL);
}
hr = Put(L"UserFlags", var);
BAIL_ON_FAILURE(hr);
error:
RRETURN_EXP_IF_ERR(hr);
}
STDMETHODIMP
CWinNTUser::get_PasswordMinimumLength(THIS_ LONG FAR* retval)
{
HRESULT hr = S_OK;
VARIANT varTemp;
hr = Get(L"MinPasswordLength", &varTemp);
BAIL_ON_FAILURE(hr);
*retval = V_I4(&varTemp);
error:
RRETURN_EXP_IF_ERR(hr);
}
STDMETHODIMP
CWinNTUser::put_PasswordMinimumLength(THIS_ LONG lPasswordMinimumLength)
{
VARIANT varTemp;
HRESULT hr;
VariantInit(&varTemp);
V_VT(&varTemp) = VT_I4;
V_I4(&varTemp) = lPasswordMinimumLength;
hr = Put(L"MinPasswordLength", varTemp);
RRETURN_EXP_IF_ERR(hr);
}
STDMETHODIMP
CWinNTUser::get_RequireUniquePassword(THIS_ VARIANT_BOOL FAR* retval)
{
GET_PROPERTY_VARIANT_BOOL((IADsUser *)this, RequireUniquePassword);
}
STDMETHODIMP
CWinNTUser::put_RequireUniquePassword(THIS_ VARIANT_BOOL fRequireUniquePassword)
{
PUT_PROPERTY_VARIANT_BOOL((IADsUser *)this, RequireUniquePassword);
}
STDMETHODIMP
CWinNTUser::SetPassword(THIS_ BSTR NewPassword)
{
NET_API_STATUS nasStatus;
LPUSER_INFO_2 lpUserInfo2 = NULL;
HRESULT hr;
WCHAR szHostServerName[MAX_PATH];
DWORD dwParmErr = 0;
WCHAR szBuffer[MAX_PATH];
//
// objects associated with invalid SIDs have neither a
// corresponding server nor domain
//
if ((!_DomainName) && (!_ServerName)) {
BAIL_ON_FAILURE(hr = E_ADS_INVALID_USER_OBJECT);
}
if (GetObjectState() == ADS_OBJECT_UNBOUND) {
// We want to set the password in this case
// This is to allow the creation of users when there
// is a restriction such as new user should have passwd.
hr = setPrivatePassword(NewPassword);
RRETURN(hr);
}
if (_ParentType == WINNT_DOMAIN_ID) {
hr = WinNTGetCachedDCName(
_DomainName,
szHostServerName,
_Credentials.GetFlags()
);
BAIL_ON_FAILURE(hr);
}else {
hr = MakeUncName(
_ServerName,
szHostServerName
);
BAIL_ON_FAILURE(hr);
}
nasStatus = NetUserGetInfo(
szHostServerName,
_Name,
2,
(LPBYTE *)&lpUserInfo2
);
hr = HRESULT_FROM_WIN32(nasStatus);
BAIL_ON_FAILURE(hr);
lpUserInfo2->usri2_password = NewPassword;
nasStatus = NetUserSetInfo(
szHostServerName,
_Name,
2,
(LPBYTE)lpUserInfo2,
&dwParmErr
);
hr = HRESULT_FROM_WIN32(nasStatus);
BAIL_ON_FAILURE(hr);
error:
if (lpUserInfo2) {
NetApiBufferFree(lpUserInfo2);
}
RRETURN_EXP_IF_ERR(hr);
}
STDMETHODIMP
CWinNTUser::ChangePassword(THIS_ BSTR bstrOldPassword, BSTR bstrNewPassword)
{
NET_API_STATUS nasStatus;
LPBYTE lpBuffer = NULL;
HRESULT hr;
WCHAR szHostServerName[MAX_PATH];
//
// objects associated with invalid SIDs have neither a
// corresponding server nor domain
//
if ((!_DomainName) && (!_ServerName)) {
BAIL_ON_FAILURE(hr = E_ADS_INVALID_USER_OBJECT);
}
if (_ParentType == WINNT_DOMAIN_ID) {
hr = WinNTGetCachedDCName(
_DomainName,
szHostServerName,
_Credentials.GetFlags()
);
BAIL_ON_FAILURE(hr);
}else {
hr = MakeUncName(
_ServerName,
szHostServerName
);
BAIL_ON_FAILURE(hr);
}
nasStatus = NetUserChangePassword(
szHostServerName,
_Name,
bstrOldPassword,
bstrNewPassword
);
hr = HRESULT_FROM_WIN32(nasStatus);
BAIL_ON_FAILURE(hr);
error:
RRETURN_EXP_IF_ERR(hr);
}
| 23.426987 | 81 | 0.607543 | [
"object"
] |
bad765bbe1ef6098a51b42e5be0e8cca5ada0079 | 21,512 | hpp | C++ | openstudiocore/src/model/StandardGlazing_Impl.hpp | BIMDataHub/OpenStudio-1 | 13ec115b00aa6a2af1426ceb26446f05014c8c8d | [
"blessing"
] | 4 | 2015-05-02T21:04:15.000Z | 2015-10-28T09:47:22.000Z | openstudiocore/src/model/StandardGlazing_Impl.hpp | BIMDataHub/OpenStudio-1 | 13ec115b00aa6a2af1426ceb26446f05014c8c8d | [
"blessing"
] | null | null | null | openstudiocore/src/model/StandardGlazing_Impl.hpp | BIMDataHub/OpenStudio-1 | 13ec115b00aa6a2af1426ceb26446f05014c8c8d | [
"blessing"
] | 1 | 2020-11-12T21:52:36.000Z | 2020-11-12T21:52:36.000Z | /**********************************************************************
* Copyright (c) 2008-2015, Alliance for Sustainable Energy.
* All rights reserved.
*
* 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.1 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**********************************************************************/
#ifndef MODEL_STANDARDGLAZING_IMPL_HPP
#define MODEL_STANDARDGLAZING_IMPL_HPP
#include "ModelAPI.hpp"
#include "Glazing_Impl.hpp"
#include "../utilities/units/Quantity.hpp"
#include "../utilities/units/OSOptionalQuantity.hpp"
namespace openstudio {
namespace model {
namespace detail {
/** StandardGlazing_Impl is a Glazing_Impl that is the implementation class for StandardGlazing.*/
class MODEL_API StandardGlazing_Impl : public Glazing_Impl {
Q_OBJECT;
Q_PROPERTY(std::string opticalDataType READ opticalDataType WRITE setOpticalDataType);
Q_PROPERTY(std::vector<std::string> opticalDataTypeValues READ opticalDataTypeValues);
Q_PROPERTY(boost::optional<std::string> windowGlassSpectralDataSetName READ windowGlassSpectralDataSetName WRITE setWindowGlassSpectralDataSetName RESET resetWindowGlassSpectralDataSetName);
Q_PROPERTY(double solarTransmittance READ solarTransmittance WRITE setSolarTransmittance RESET resetSolarTransmittanceatNormalIncidence);
Q_PROPERTY(double thickness READ thickness WRITE setThickness);
Q_PROPERTY(openstudio::Quantity thickness_SI READ thickness_SI WRITE setThickness);
Q_PROPERTY(openstudio::Quantity thickness_IP READ thickness_IP WRITE setThickness);
Q_PROPERTY(boost::optional<double> solarTransmittanceatNormalIncidence READ solarTransmittanceatNormalIncidence WRITE setSolarTransmittanceatNormalIncidence RESET resetSolarTransmittanceatNormalIncidence);
Q_PROPERTY(openstudio::OSOptionalQuantity solarTransmittanceatNormalIncidence_SI READ solarTransmittanceatNormalIncidence_SI WRITE setSolarTransmittanceatNormalIncidence RESET resetSolarTransmittanceatNormalIncidence);
Q_PROPERTY(openstudio::OSOptionalQuantity solarTransmittanceatNormalIncidence_IP READ solarTransmittanceatNormalIncidence_IP WRITE setSolarTransmittanceatNormalIncidence RESET resetSolarTransmittanceatNormalIncidence);
Q_PROPERTY(boost::optional<double> frontSideSolarReflectanceatNormalIncidence READ frontSideSolarReflectanceatNormalIncidence WRITE setFrontSideSolarReflectanceatNormalIncidence RESET resetFrontSideSolarReflectanceatNormalIncidence);
Q_PROPERTY(openstudio::OSOptionalQuantity frontSideSolarReflectanceatNormalIncidence_SI READ frontSideSolarReflectanceatNormalIncidence_SI WRITE setFrontSideSolarReflectanceatNormalIncidence RESET resetFrontSideSolarReflectanceatNormalIncidence);
Q_PROPERTY(openstudio::OSOptionalQuantity frontSideSolarReflectanceatNormalIncidence_IP READ frontSideSolarReflectanceatNormalIncidence_IP WRITE setFrontSideSolarReflectanceatNormalIncidence RESET resetFrontSideSolarReflectanceatNormalIncidence);
Q_PROPERTY(boost::optional<double> backSideSolarReflectanceatNormalIncidence READ backSideSolarReflectanceatNormalIncidence WRITE setBackSideSolarReflectanceatNormalIncidence RESET resetBackSideSolarReflectanceatNormalIncidence);
Q_PROPERTY(openstudio::OSOptionalQuantity backSideSolarReflectanceatNormalIncidence_SI READ backSideSolarReflectanceatNormalIncidence_SI WRITE setBackSideSolarReflectanceatNormalIncidence RESET resetBackSideSolarReflectanceatNormalIncidence);
Q_PROPERTY(openstudio::OSOptionalQuantity backSideSolarReflectanceatNormalIncidence_IP READ backSideSolarReflectanceatNormalIncidence_IP WRITE setBackSideSolarReflectanceatNormalIncidence RESET resetBackSideSolarReflectanceatNormalIncidence);
Q_PROPERTY(boost::optional<double> visibleTransmittanceatNormalIncidence READ visibleTransmittanceatNormalIncidence WRITE setVisibleTransmittanceatNormalIncidence RESET resetVisibleTransmittanceatNormalIncidence);
Q_PROPERTY(openstudio::OSOptionalQuantity visibleTransmittanceatNormalIncidence_SI READ visibleTransmittanceatNormalIncidence_SI WRITE setVisibleTransmittanceatNormalIncidence RESET resetVisibleTransmittanceatNormalIncidence);
Q_PROPERTY(openstudio::OSOptionalQuantity visibleTransmittanceatNormalIncidence_IP READ visibleTransmittanceatNormalIncidence_IP WRITE setVisibleTransmittanceatNormalIncidence RESET resetVisibleTransmittanceatNormalIncidence);
Q_PROPERTY(boost::optional<double> frontSideVisibleReflectanceatNormalIncidence READ frontSideVisibleReflectanceatNormalIncidence WRITE setFrontSideVisibleReflectanceatNormalIncidence RESET resetFrontSideVisibleReflectanceatNormalIncidence);
Q_PROPERTY(openstudio::OSOptionalQuantity frontSideVisibleReflectanceatNormalIncidence_SI READ frontSideVisibleReflectanceatNormalIncidence_SI WRITE setFrontSideVisibleReflectanceatNormalIncidence RESET resetFrontSideVisibleReflectanceatNormalIncidence);
Q_PROPERTY(openstudio::OSOptionalQuantity frontSideVisibleReflectanceatNormalIncidence_IP READ frontSideVisibleReflectanceatNormalIncidence_IP WRITE setFrontSideVisibleReflectanceatNormalIncidence RESET resetFrontSideVisibleReflectanceatNormalIncidence);
Q_PROPERTY(boost::optional<double> backSideVisibleReflectanceatNormalIncidence READ backSideVisibleReflectanceatNormalIncidence WRITE setBackSideVisibleReflectanceatNormalIncidence RESET resetBackSideVisibleReflectanceatNormalIncidence);
Q_PROPERTY(openstudio::OSOptionalQuantity backSideVisibleReflectanceatNormalIncidence_SI READ backSideVisibleReflectanceatNormalIncidence_SI WRITE setBackSideVisibleReflectanceatNormalIncidence RESET resetBackSideVisibleReflectanceatNormalIncidence);
Q_PROPERTY(openstudio::OSOptionalQuantity backSideVisibleReflectanceatNormalIncidence_IP READ backSideVisibleReflectanceatNormalIncidence_IP WRITE setBackSideVisibleReflectanceatNormalIncidence RESET resetBackSideVisibleReflectanceatNormalIncidence);
Q_PROPERTY(double infraredTransmittanceatNormalIncidence READ infraredTransmittanceatNormalIncidence WRITE setInfraredTransmittanceatNormalIncidence RESET resetInfraredTransmittanceatNormalIncidence);
Q_PROPERTY(openstudio::Quantity infraredTransmittanceatNormalIncidence_SI READ infraredTransmittanceatNormalIncidence_SI WRITE setInfraredTransmittanceatNormalIncidence RESET resetInfraredTransmittanceatNormalIncidence);
Q_PROPERTY(openstudio::Quantity infraredTransmittanceatNormalIncidence_IP READ infraredTransmittanceatNormalIncidence_IP WRITE setInfraredTransmittanceatNormalIncidence RESET resetInfraredTransmittanceatNormalIncidence);
Q_PROPERTY(bool isInfraredTransmittanceatNormalIncidenceDefaulted READ isInfraredTransmittanceatNormalIncidenceDefaulted);
Q_PROPERTY(double frontSideInfraredHemisphericalEmissivity READ frontSideInfraredHemisphericalEmissivity WRITE setFrontSideInfraredHemisphericalEmissivity RESET resetFrontSideInfraredHemisphericalEmissivity);
Q_PROPERTY(openstudio::Quantity frontSideInfraredHemisphericalEmissivity_SI READ frontSideInfraredHemisphericalEmissivity_SI WRITE setFrontSideInfraredHemisphericalEmissivity RESET resetFrontSideInfraredHemisphericalEmissivity);
Q_PROPERTY(openstudio::Quantity frontSideInfraredHemisphericalEmissivity_IP READ frontSideInfraredHemisphericalEmissivity_IP WRITE setFrontSideInfraredHemisphericalEmissivity RESET resetFrontSideInfraredHemisphericalEmissivity);
Q_PROPERTY(bool isFrontSideInfraredHemisphericalEmissivityDefaulted READ isFrontSideInfraredHemisphericalEmissivityDefaulted);
Q_PROPERTY(double backSideInfraredHemisphericalEmissivity READ backSideInfraredHemisphericalEmissivity WRITE setBackSideInfraredHemisphericalEmissivity RESET resetBackSideInfraredHemisphericalEmissivity);
Q_PROPERTY(openstudio::Quantity backSideInfraredHemisphericalEmissivity_SI READ backSideInfraredHemisphericalEmissivity_SI WRITE setBackSideInfraredHemisphericalEmissivity RESET resetBackSideInfraredHemisphericalEmissivity);
Q_PROPERTY(openstudio::Quantity backSideInfraredHemisphericalEmissivity_IP READ backSideInfraredHemisphericalEmissivity_IP WRITE setBackSideInfraredHemisphericalEmissivity RESET resetBackSideInfraredHemisphericalEmissivity);
Q_PROPERTY(bool isBackSideInfraredHemisphericalEmissivityDefaulted READ isBackSideInfraredHemisphericalEmissivityDefaulted);
Q_PROPERTY(double conductivity READ conductivity WRITE setConductivity RESET resetConductivity);
Q_PROPERTY(openstudio::Quantity conductivity_SI READ conductivity_SI WRITE setConductivity RESET resetConductivity);
Q_PROPERTY(openstudio::Quantity conductivity_IP READ conductivity_IP WRITE setConductivity RESET resetConductivity);
Q_PROPERTY(bool isConductivityDefaulted READ isConductivityDefaulted);
Q_PROPERTY(double dirtCorrectionFactorforSolarandVisibleTransmittance READ dirtCorrectionFactorforSolarandVisibleTransmittance WRITE setDirtCorrectionFactorforSolarandVisibleTransmittance RESET resetDirtCorrectionFactorforSolarandVisibleTransmittance);
Q_PROPERTY(openstudio::Quantity dirtCorrectionFactorforSolarandVisibleTransmittance_SI READ dirtCorrectionFactorforSolarandVisibleTransmittance_SI WRITE setDirtCorrectionFactorforSolarandVisibleTransmittance RESET resetDirtCorrectionFactorforSolarandVisibleTransmittance);
Q_PROPERTY(openstudio::Quantity dirtCorrectionFactorforSolarandVisibleTransmittance_IP READ dirtCorrectionFactorforSolarandVisibleTransmittance_IP WRITE setDirtCorrectionFactorforSolarandVisibleTransmittance RESET resetDirtCorrectionFactorforSolarandVisibleTransmittance);
Q_PROPERTY(bool isDirtCorrectionFactorforSolarandVisibleTransmittanceDefaulted READ isDirtCorrectionFactorforSolarandVisibleTransmittanceDefaulted);
Q_PROPERTY(bool solarDiffusing READ solarDiffusing WRITE setSolarDiffusing RESET resetSolarDiffusing);
Q_PROPERTY(bool isSolarDiffusingDefaulted READ isSolarDiffusingDefaulted);
// TODO: Add relationships for objects related to this one, but not pointed to by the underlying data.
// Such relationships can be generated by the GenerateRelationships.rb script.
public:
/** @name Constructors and Destructors */
//@{
StandardGlazing_Impl(const IdfObject& idfObject,
Model_Impl* model,
bool keepHandle);
StandardGlazing_Impl(const openstudio::detail::WorkspaceObject_Impl& other,
Model_Impl* model,
bool keepHandle);
StandardGlazing_Impl(const StandardGlazing_Impl& other,
Model_Impl* model,
bool keepHandle);
virtual ~StandardGlazing_Impl() {}
//@}
/** @name Virtual Methods */
//@{
virtual const std::vector<std::string>& outputVariableNames() const override;
virtual IddObjectType iddObjectType() const override;
//@}
/** @name Getters */
//@{
std::string opticalDataType() const;
boost::optional<std::string> windowGlassSpectralDataSetName() const;
/** Get the thickness of the material. */
virtual double thickness() const override;
double solarTransmittance() const;
Quantity getThickness(bool returnIP=false) const;
boost::optional<double> solarTransmittanceatNormalIncidence() const;
OSOptionalQuantity getSolarTransmittanceatNormalIncidence(bool returnIP=false) const;
boost::optional<double> frontSideSolarReflectanceatNormalIncidence() const;
OSOptionalQuantity getFrontSideSolarReflectanceatNormalIncidence(bool returnIP=false) const;
boost::optional<double> backSideSolarReflectanceatNormalIncidence() const;
OSOptionalQuantity getBackSideSolarReflectanceatNormalIncidence(bool returnIP=false) const;
virtual boost::optional<double> getVisibleTransmittance() const override;
boost::optional<double> visibleTransmittanceatNormalIncidence() const;
OSOptionalQuantity getVisibleTransmittanceatNormalIncidence(bool returnIP=false) const;
boost::optional<double> frontSideVisibleReflectanceatNormalIncidence() const;
OSOptionalQuantity getFrontSideVisibleReflectanceatNormalIncidence(bool returnIP=false) const;
boost::optional<double> backSideVisibleReflectanceatNormalIncidence() const;
OSOptionalQuantity getBackSideVisibleReflectanceatNormalIncidence(bool returnIP=false) const;
double infraredTransmittance() const;
double infraredTransmittanceatNormalIncidence() const;
Quantity getInfraredTransmittanceatNormalIncidence(bool returnIP=false) const;
bool isInfraredTransmittanceatNormalIncidenceDefaulted() const;
double frontSideInfraredHemisphericalEmissivity() const;
Quantity getFrontSideInfraredHemisphericalEmissivity(bool returnIP=false) const;
bool isFrontSideInfraredHemisphericalEmissivityDefaulted() const;
double backSideInfraredHemisphericalEmissivity() const;
Quantity getBackSideInfraredHemisphericalEmissivity(bool returnIP=false) const;
bool isBackSideInfraredHemisphericalEmissivityDefaulted() const;
/** The conductivitiy of the material in W/m*K. */
double thermalConductivity() const;
double conductivity() const;
Quantity getConductivity(bool returnIP=false) const;
bool isConductivityDefaulted() const;
double dirtCorrectionFactorforSolarandVisibleTransmittance() const;
Quantity getDirtCorrectionFactorforSolarandVisibleTransmittance(bool returnIP=false) const;
bool isDirtCorrectionFactorforSolarandVisibleTransmittanceDefaulted() const;
bool solarDiffusing() const;
bool isSolarDiffusingDefaulted() const;
//@}
/** @name Setters */
//@{
bool setOpticalDataType(std::string opticalDataType);
void setWindowGlassSpectralDataSetName(boost::optional<std::string> windowGlassSpectralDataSetName);
void resetWindowGlassSpectralDataSetName();
/** Set thickness to value (m). */
virtual bool setThickness(double value) override;
bool setThickness(const Quantity& thickness);
bool setSolarTransmittance(double value);
bool setSolarTransmittanceatNormalIncidence(boost::optional<double> solarTransmittanceatNormalIncidence);
bool setSolarTransmittanceatNormalIncidence(const OSOptionalQuantity& solarTransmittanceatNormalIncidence);
void resetSolarTransmittanceatNormalIncidence();
bool setFrontSideSolarReflectanceatNormalIncidence(boost::optional<double> frontSideSolarReflectanceatNormalIncidence);
bool setFrontSideSolarReflectanceatNormalIncidence(const OSOptionalQuantity& frontSideSolarReflectanceatNormalIncidence);
void resetFrontSideSolarReflectanceatNormalIncidence();
bool setBackSideSolarReflectanceatNormalIncidence(boost::optional<double> backSideSolarReflectanceatNormalIncidence);
bool setBackSideSolarReflectanceatNormalIncidence(const OSOptionalQuantity& backSideSolarReflectanceatNormalIncidence);
void resetBackSideSolarReflectanceatNormalIncidence();
bool setVisibleTransmittance(double value);
bool setVisibleTransmittanceatNormalIncidence(boost::optional<double> visibleTransmittanceatNormalIncidence);
bool setVisibleTransmittanceatNormalIncidence(const OSOptionalQuantity& visibleTransmittanceatNormalIncidence);
void resetVisibleTransmittanceatNormalIncidence();
bool setFrontSideVisibleReflectanceatNormalIncidence(boost::optional<double> frontSideVisibleReflectanceatNormalIncidence);
bool setFrontSideVisibleReflectanceatNormalIncidence(const OSOptionalQuantity& frontSideVisibleReflectanceatNormalIncidence);
void resetFrontSideVisibleReflectanceatNormalIncidence();
bool setBackSideVisibleReflectanceatNormalIncidence(boost::optional<double> backSideVisibleReflectanceatNormalIncidence);
bool setBackSideVisibleReflectanceatNormalIncidence(const OSOptionalQuantity& backSideVisibleReflectanceatNormalIncidence);
void resetBackSideVisibleReflectanceatNormalIncidence();
bool setInfraredTransmittance(double value);
bool setInfraredTransmittanceatNormalIncidence(double infraredTransmittanceatNormalIncidence);
bool setInfraredTransmittanceatNormalIncidence(const Quantity& infraredTransmittanceatNormalIncidence);
void resetInfraredTransmittanceatNormalIncidence();
bool setFrontSideInfraredHemisphericalEmissivity(double frontSideInfraredHemisphericalEmissivity);
bool setFrontSideInfraredHemisphericalEmissivity(const Quantity& frontSideInfraredHemisphericalEmissivity);
void resetFrontSideInfraredHemisphericalEmissivity();
bool setBackSideInfraredHemisphericalEmissivity(double backSideInfraredHemisphericalEmissivity);
bool setBackSideInfraredHemisphericalEmissivity(const Quantity& backSideInfraredHemisphericalEmissivity);
void resetBackSideInfraredHemisphericalEmissivity();
/** Sets the conductivity of the material in W/m*K, if possible. */
bool setThermalConductivity(double value);
bool setConductivity(double conductivity);
bool setConductivity(const Quantity& conductivity);
void resetConductivity();
bool setDirtCorrectionFactorforSolarandVisibleTransmittance(double dirtCorrectionFactorforSolarandVisibleTransmittance);
bool setDirtCorrectionFactorforSolarandVisibleTransmittance(const Quantity& dirtCorrectionFactorforSolarandVisibleTransmittance);
void resetDirtCorrectionFactorforSolarandVisibleTransmittance();
void setSolarDiffusing(bool solarDiffusing);
void resetSolarDiffusing();
//@}
/** @name Other */
//@{
/** The conductance of the material in W/m^2*K. */
double thermalConductance() const;
/** The resistivity of the material in m*K/W. */
double thermalResistivity() const;
/** The resistance of the material in m^2*K/W. */
double thermalResistance() const;
double interiorVisibleReflectance() const;
double exteriorVisibleReflectance() const;
virtual boost::optional<double> interiorVisibleAbsorptance() const override;
virtual boost::optional<double> exteriorVisibleAbsorptance() const override;
/** Sets the conductance of the material in W/m^2*K, if possible. */
bool setThermalConductance(double value);
/** Sets the resistivity of the material in m*K/W, if possible. */
bool setThermalResistivity(double value);
/** Sets the resistance of the material in m^2*K/W, if possible. */
bool setThermalResistance(double value);
//@}
protected:
private:
REGISTER_LOGGER("openstudio.model.StandardGlazing");
std::vector<std::string> opticalDataTypeValues() const;
openstudio::Quantity thickness_SI() const;
openstudio::Quantity thickness_IP() const;
openstudio::OSOptionalQuantity solarTransmittanceatNormalIncidence_SI() const;
openstudio::OSOptionalQuantity solarTransmittanceatNormalIncidence_IP() const;
openstudio::OSOptionalQuantity frontSideSolarReflectanceatNormalIncidence_SI() const;
openstudio::OSOptionalQuantity frontSideSolarReflectanceatNormalIncidence_IP() const;
openstudio::OSOptionalQuantity backSideSolarReflectanceatNormalIncidence_SI() const;
openstudio::OSOptionalQuantity backSideSolarReflectanceatNormalIncidence_IP() const;
openstudio::OSOptionalQuantity visibleTransmittanceatNormalIncidence_SI() const;
openstudio::OSOptionalQuantity visibleTransmittanceatNormalIncidence_IP() const;
openstudio::OSOptionalQuantity frontSideVisibleReflectanceatNormalIncidence_SI() const;
openstudio::OSOptionalQuantity frontSideVisibleReflectanceatNormalIncidence_IP() const;
openstudio::OSOptionalQuantity backSideVisibleReflectanceatNormalIncidence_SI() const;
openstudio::OSOptionalQuantity backSideVisibleReflectanceatNormalIncidence_IP() const;
openstudio::Quantity infraredTransmittanceatNormalIncidence_SI() const;
openstudio::Quantity infraredTransmittanceatNormalIncidence_IP() const;
openstudio::Quantity frontSideInfraredHemisphericalEmissivity_SI() const;
openstudio::Quantity frontSideInfraredHemisphericalEmissivity_IP() const;
openstudio::Quantity backSideInfraredHemisphericalEmissivity_SI() const;
openstudio::Quantity backSideInfraredHemisphericalEmissivity_IP() const;
openstudio::Quantity conductivity_SI() const;
openstudio::Quantity conductivity_IP() const;
openstudio::Quantity dirtCorrectionFactorforSolarandVisibleTransmittance_SI() const;
openstudio::Quantity dirtCorrectionFactorforSolarandVisibleTransmittance_IP() const;
};
} // detail
} // model
} // openstudio
#endif // MODEL_STANDARDGLAZING_IMPL_HPP
| 57.827957 | 277 | 0.82368 | [
"vector",
"model"
] |
badb4f9a32aa0ad5dcea1bfb9913c592b730dc23 | 3,328 | cpp | C++ | simulation/halsim_gui/src/main/native/cpp/RelaySimGui.cpp | shueja-personal/allwpilib | 4b2f6be29e21986703d9c3ddcd2fe07121b2ff6b | [
"BSD-3-Clause"
] | 707 | 2016-05-11T16:54:13.000Z | 2022-03-30T13:03:15.000Z | simulation/halsim_gui/src/main/native/cpp/RelaySimGui.cpp | shueja-personal/allwpilib | 4b2f6be29e21986703d9c3ddcd2fe07121b2ff6b | [
"BSD-3-Clause"
] | 2,308 | 2016-05-12T00:17:17.000Z | 2022-03-30T20:08:10.000Z | simulation/halsim_gui/src/main/native/cpp/RelaySimGui.cpp | shueja-personal/allwpilib | 4b2f6be29e21986703d9c3ddcd2fe07121b2ff6b | [
"BSD-3-Clause"
] | 539 | 2016-05-11T20:33:26.000Z | 2022-03-28T20:20:25.000Z | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#include "RelaySimGui.h"
#include <glass/hardware/Relay.h>
#include <memory>
#include <vector>
#include <hal/Ports.h>
#include <hal/simulation/RelayData.h>
#include <wpigui.h>
#include "HALDataSource.h"
#include "HALSimGui.h"
using namespace halsimgui;
namespace {
HALSIMGUI_DATASOURCE_BOOLEAN_INDEXED(RelayForward, "RelayFwd");
HALSIMGUI_DATASOURCE_BOOLEAN_INDEXED(RelayReverse, "RelayRev");
class RelaySimModel : public glass::RelayModel {
public:
explicit RelaySimModel(int32_t index)
: m_index{index}, m_forward{index}, m_reverse{index} {}
void Update() override {}
bool Exists() override {
return HALSIM_GetRelayInitializedForward(m_index) ||
HALSIM_GetRelayInitializedReverse(m_index);
}
glass::DataSource* GetForwardData() override {
return HALSIM_GetRelayInitializedForward(m_index) ? &m_forward : nullptr;
}
glass::DataSource* GetReverseData() override {
return HALSIM_GetRelayInitializedReverse(m_index) ? &m_reverse : nullptr;
}
void SetForward(bool val) override { HALSIM_SetRelayForward(m_index, val); }
void SetReverse(bool val) override { HALSIM_SetRelayReverse(m_index, val); }
private:
int32_t m_index;
RelayForwardSource m_forward;
RelayReverseSource m_reverse;
};
class RelaysSimModel : public glass::RelaysModel {
public:
RelaysSimModel() : m_models(HAL_GetNumRelayHeaders()) {}
void Update() override;
bool Exists() override { return true; }
void ForEachRelay(wpi::function_ref<void(glass::RelayModel& model, int index)>
func) override;
private:
// indexed by channel
std::vector<std::unique_ptr<RelaySimModel>> m_models;
};
} // namespace
void RelaysSimModel::Update() {
for (int32_t i = 0, iend = static_cast<int32_t>(m_models.size()); i < iend;
++i) {
auto& model = m_models[i];
if (HALSIM_GetRelayInitializedForward(i) ||
HALSIM_GetRelayInitializedReverse(i)) {
if (!model) {
model = std::make_unique<RelaySimModel>(i);
}
} else {
model.reset();
}
}
}
void RelaysSimModel::ForEachRelay(
wpi::function_ref<void(glass::RelayModel& model, int index)> func) {
for (int32_t i = 0, iend = static_cast<int32_t>(m_models.size()); i < iend;
++i) {
if (auto model = m_models[i].get()) {
func(*model, i);
}
}
}
static bool RelayAnyInitialized() {
static const int32_t num = HAL_GetNumRelayHeaders();
for (int32_t i = 0; i < num; ++i) {
if (HALSIM_GetRelayInitializedForward(i) ||
HALSIM_GetRelayInitializedReverse(i)) {
return true;
}
}
return false;
}
void RelaySimGui::Initialize() {
HALSimGui::halProvider->Register(
"Relays", RelayAnyInitialized,
[] { return std::make_unique<RelaysSimModel>(); },
[](glass::Window* win, glass::Model* model) {
win->SetFlags(ImGuiWindowFlags_AlwaysAutoResize);
win->SetDefaultPos(180, 20);
return glass::MakeFunctionView([=] {
glass::DisplayRelays(static_cast<RelaysSimModel*>(model),
HALSimGui::halProvider->AreOutputsEnabled());
});
});
}
| 27.966387 | 80 | 0.681791 | [
"vector",
"model"
] |
badd1551df1877fd5a442be5561db5d921bfe6b5 | 882 | cpp | C++ | source/Library.Shared/GeometryShaderReader.cpp | ssshammi/real-time-3d-rendering-with-directx-and-hlsl | 05a05c5c26784dafa9a89747276f385252951f2f | [
"MIT"
] | null | null | null | source/Library.Shared/GeometryShaderReader.cpp | ssshammi/real-time-3d-rendering-with-directx-and-hlsl | 05a05c5c26784dafa9a89747276f385252951f2f | [
"MIT"
] | null | null | null | source/Library.Shared/GeometryShaderReader.cpp | ssshammi/real-time-3d-rendering-with-directx-and-hlsl | 05a05c5c26784dafa9a89747276f385252951f2f | [
"MIT"
] | null | null | null | #include "pch.h"
#include "GeometryShaderReader.h"
#include "Game.h"
#include "GameException.h"
#include "Utility.h"
using namespace std;
using namespace DirectX;
using namespace winrt;
namespace Library
{
RTTI_DEFINITIONS(GeometryShaderReader)
GeometryShaderReader::GeometryShaderReader(Game& game) :
ContentTypeReader(game, GeometryShader::TypeIdClass())
{
}
shared_ptr<GeometryShader> GeometryShaderReader::_Read(const wstring& assetName)
{
com_ptr<ID3D11GeometryShader> hullShader;
vector<char> compiledGeometryShader;
Utility::LoadBinaryFile(assetName, compiledGeometryShader);
ThrowIfFailed(mGame->Direct3DDevice()->CreateGeometryShader(&compiledGeometryShader[0], compiledGeometryShader.size(), nullptr, hullShader.put()), "ID3D11Device::CreatedGeometryShader() failed.");
return shared_ptr<GeometryShader>(new GeometryShader(move(hullShader)));
}
} | 30.413793 | 198 | 0.795918 | [
"vector"
] |
bae1011cf7153539809d10da5325a1a2a4425e58 | 84,284 | cc | C++ | Molecule/smiles.cc | rajarshi/Lilly-Medchem-Rules | cb391fd04ba5820a88e31a8957bff68de08959f7 | [
"Apache-2.0"
] | null | null | null | Molecule/smiles.cc | rajarshi/Lilly-Medchem-Rules | cb391fd04ba5820a88e31a8957bff68de08959f7 | [
"Apache-2.0"
] | null | null | null | Molecule/smiles.cc | rajarshi/Lilly-Medchem-Rules | cb391fd04ba5820a88e31a8957bff68de08959f7 | [
"Apache-2.0"
] | null | null | null | #include <stdlib.h>
#include <memory>
#include <random>
#include <algorithm>
#include "assert.h"
#include "misc.h"
#include "iwbits.h"
#include "iwrandom.h"
// Define this to get the molecule private functions defined here
#define COMPILING_MOLECULER_CC
#define COMPILING_SMILES_CC
#define COMPILING_CTB
#include "molecule.h"
#include "path.h"
#include "smiles.h"
#include "aromatic.h"
#include "misc2.h"
#include "iwrnm.h"
#include "iwrcb.h"
static unsigned int random_smiles_default_seed = 3172776704;
/*
We have various classes that guide the atom ordering when building a smiles
Each class must have two methods, next_starting_atom, and next_atom with the
signatures below.
Obviously I could have done this with virtual class heirarchy.
*/
class Atom_Chooser_Default
{
private:
public:
Atom_Chooser_Default() {}
int next_starting_atom(const Molecule & m, const int * zorder, atom_number_t & a, const int * include_atom) const;
int next_atom(const Molecule & m, const int * zorder, const atom_number_t zatom, atom_number_t & b, const int * include_atom) const;
// int next_atom(const Molecule & m, const atom_number_t zatom, Set_of_Atoms & unprocessed_connections, const int * zorder, atom_number_t & b) const;
};
int
Atom_Chooser_Default::next_starting_atom(const Molecule & m, const int * zorder, atom_number_t & a, const int * include_atom) const
{
const int matoms = m.natoms();
const int include_chiral_info = include_chiral_info_in_smiles();
atom_number_t atom_to_return_if_nothing_else_found = INVALID_ATOM_NUMBER;
for (int i = 0; i < matoms; ++i)
{
if (zorder[i] >= 0) // already in smiles
continue;
if (NULL != include_atom && 0 == include_atom[i])
continue;
const Chiral_Centre * c = m.chiral_centre_at_atom(i);
if (c && include_chiral_info)
{
if (INVALID_ATOM_NUMBER == atom_to_return_if_nothing_else_found)
atom_to_return_if_nothing_else_found = i;
}
else
{
a = i;
return 1;
}
}
if (INVALID_ATOM_NUMBER == atom_to_return_if_nothing_else_found)
return 0;
a = atom_to_return_if_nothing_else_found;
return 1;
}
#ifdef NEW_VERSION_MAYBE
int
Atom_Chooser_Default::next_atom(const Molecule & m,
const atom_number_t zatom,
Set_of_Atoms & unprocessed_connections,
const int * zorder,
atom_number_t & b) const
{
const int n = unprocessed_connections.number_elements();
if (0 == n)
return 0;
if (1 == n)
{
b = unprocessed_connections[0];
unprocessed_connections.resize(0);
return 1;
}
for (int i = 0; i < n; ++i)
{
const atom_number_t j = unprocessed_connections[i];
if (zorder[j] >= 0) // we could remove it
continue;
if (1 == m.ncon(j))
{
b = j;
return 1;
}
}
}
#endif
int
Atom_Chooser_Default::next_atom (const Molecule & m, const int * zorder, const atom_number_t zatom, atom_number_t & next_atom, const int * include_atom) const
{
next_atom = INVALID_ATOM_NUMBER;
const Atom * a = m.atomi(zatom);
const int acon = a->ncon();
for (int i = 0; i < acon; ++i)
{
atom_number_t j;
bond_type_t bt;
a->other_and_type(zatom, i, j, bt);
if (zorder[j] >= 0) // atom already classified
continue;
if (NULL != include_atom && 0 == include_atom[j])
continue;
if (1 == m.ncon(j))
{
next_atom = j;
return 1;
}
if (! IS_SINGLE_BOND(bt))
{
next_atom = j;
return 1;
}
if (INVALID_ATOM_NUMBER == next_atom)
next_atom = j;
}
return INVALID_ATOM_NUMBER != next_atom;
}
class Atom_Chooser_Lowest_Rank : public Atom_Chooser_Default
{
private:
const int * _rank;
public:
Atom_Chooser_Lowest_Rank(const int * r) : _rank(r) {}
int next_starting_atom(const Molecule & m, const int * zorder, atom_number_t & a, const int * include_atom) const;
int next_atom(const Molecule & m, const int * zorder, const atom_number_t zatom, atom_number_t & b, const int * include_atom) const;
};
int
Atom_Chooser_Lowest_Rank::next_starting_atom (const Molecule & m,
const int * zorder,
atom_number_t & a,
const int * include_atom) const
{
const int matoms = m.natoms();
int lowest_rank = 0;
a = INVALID_ATOM_NUMBER;
const int include_chiral_info = include_chiral_info_in_smiles();
atom_number_t atom_to_return_if_nothing_else_found = INVALID_ATOM_NUMBER;
int rank_last_resort_atom = 0;
for (int i = 0; i < matoms; ++i)
{
if (zorder[i] >= 0) // already in smiles
continue;
if (NULL != include_atom && 0 == include_atom[i])
continue;
const Chiral_Centre * c = m.chiral_centre_at_atom(i);
if (c && include_chiral_info)
{
if (INVALID_ATOM_NUMBER == atom_to_return_if_nothing_else_found || _rank[i] < rank_last_resort_atom)
{
atom_to_return_if_nothing_else_found = i;
rank_last_resort_atom = _rank[i];
}
}
else if (INVALID_ATOM_NUMBER == a || _rank[i] < lowest_rank)
{
lowest_rank = _rank[i];
a = i;
}
}
if (INVALID_ATOM_NUMBER != a)
return 1;
if (INVALID_ATOM_NUMBER == atom_to_return_if_nothing_else_found)
return 0;
a = atom_to_return_if_nothing_else_found;
return 1;
}
int
Atom_Chooser_Lowest_Rank::next_atom(const Molecule & m, const int * zorder, const atom_number_t zatom, atom_number_t & b, const int * include_atom) const
{
const Atom * a = m.atomi(zatom);
const int acon = a->ncon();
int lowest_score = 0;
atom_number_t atom_with_lowest_score = INVALID_ATOM_NUMBER;
for (int i = 0; i < acon; ++i)
{
const atom_number_t j = a->other(zatom, i);
if (zorder[j] >= 0)
continue;
if (NULL != include_atom && 0 == include_atom[j])
continue;
if (INVALID_ATOM_NUMBER == atom_with_lowest_score || _rank[j] < lowest_score)
{
atom_with_lowest_score = j;
lowest_score = _rank[j];
}
}
if (INVALID_ATOM_NUMBER == atom_with_lowest_score)
return 0;
b = atom_with_lowest_score;
return 1;
}
class Atom_Chooser_Random
{
private:
std::default_random_engine _rng;
public:
Atom_Chooser_Random(const unsigned int s = 0);
int next_starting_atom(const Molecule & m, const int * zorder, atom_number_t & a, const int * include_atom);
int next_atom(const Molecule & m, const int * zorder, const atom_number_t zatom, atom_number_t & b, const int * include_atom);
};
Atom_Chooser_Random::Atom_Chooser_Random(const unsigned int s)
{
if (0 == s)
{
std::random_device rd;
_rng.seed(rd());
}
else
_rng.seed(random_smiles_default_seed);
return;
}
int
Atom_Chooser_Random::next_starting_atom (const Molecule & m,
const int * zorder,
atom_number_t & a,
const int * include_atom)
{
const int matoms = m.natoms();
std::uniform_int_distribution<int> u(0, matoms - 1);
int ndx = u(_rng);
//cerr << " ndx " << ndx << endl;
const int include_chiral_info = include_chiral_info_in_smiles();
atom_number_t atom_to_return_if_nothing_else_found = INVALID_ATOM_NUMBER;
for (int i = 0; i < matoms; ++i, ++ndx)
{
if (ndx == matoms)
ndx = 0;
if (zorder[ndx] >= 0)
continue;
if (NULL != include_atom && 0 == include_atom[ndx])
continue;
const Chiral_Centre * c= m.chiral_centre_at_atom(ndx);
if (INVALID_ATOM_NUMBER == atom_to_return_if_nothing_else_found && include_chiral_info && c)
atom_to_return_if_nothing_else_found = ndx;
else if (include_chiral_info && c)
;
else
{
a = ndx;
return 1;
}
}
if (INVALID_ATOM_NUMBER == atom_to_return_if_nothing_else_found)
return 0;
a = atom_to_return_if_nothing_else_found;
return 1;
}
int
Atom_Chooser_Random::next_atom(const Molecule & m, const int * zorder, const atom_number_t zatom, atom_number_t & next_atom, const int * include_atom)
{
const Atom * a = m.atomi(zatom);
const int acon = a->ncon();
next_atom = INVALID_ATOM_NUMBER;
atom_number_t multiple_bond = INVALID_ATOM_NUMBER;
std::bernoulli_distribution u(0.5);
for (int i = 0; i < acon; i++)
{
atom_number_t j;
bond_type_t bt;
a->other_and_type(zatom, i, j, bt);
if (zorder[j] >= 0)
continue;
if (NULL != include_atom && 0 == include_atom[j])
continue;
if (! IS_SINGLE_BOND(bt))
{
if (INVALID_ATOM_NUMBER == multiple_bond)
multiple_bond = j;
else if (u(_rng))
multiple_bond = j;
}
else if (INVALID_ATOM_NUMBER == next_atom)
next_atom = j;
else if (u(_rng))
next_atom = j;
}
if (INVALID_ATOM_NUMBER != multiple_bond)
{
next_atom = multiple_bond;
return 1;
}
return INVALID_ATOM_NUMBER != next_atom;
}
class Atom_Chooser_Unique
{
private:
const int * _canonical_rank;
public:
Atom_Chooser_Unique(const int * r) : _canonical_rank(r) {}
int next_starting_atom(const Molecule & m, const int * zorder, atom_number_t & a, const int * include_atom) const;
int next_atom(const Molecule & m, const int * zorder, const atom_number_t zatom, atom_number_t & b, const int * include_atom) const;
};
int
Atom_Chooser_Unique::next_starting_atom(const Molecule & m, const int * zorder, atom_number_t & first_atom, const int * include_atom) const
{
int include_chiral_info = include_chiral_info_in_smiles();
const int matoms = m.natoms();
int min_ncon = matoms; // greater than all ncon() values
first_atom = INVALID_ATOM_NUMBER;
int rank_first_atom = 0;
atom_number_t chiral_atom_if_we_need_to = INVALID_ATOM_NUMBER; // in case everything chiral [P@]12[P@]3[P@@]1[P@@]23
int rank_chiral_atom = 0;
for (int i = 0; i < matoms; i++)
{
if (zorder[i] >= 0) // already processed
continue;
// A smiles cannot START at a chiral atom
if (include_chiral_info && m.chiral_centre_at_atom(i))
{
if (chiral_atom_if_we_need_to < 0 || _canonical_rank[i] > rank_chiral_atom)
{
chiral_atom_if_we_need_to = i;
rank_chiral_atom = _canonical_rank[i];
}
continue;
}
const Atom * a = m.atomi(i);
const int ncon = a->ncon();
if (ncon < min_ncon)
{
min_ncon = ncon;
first_atom = i;
rank_first_atom = _canonical_rank[i];
}
else if (ncon == min_ncon && _canonical_rank[i] > rank_first_atom)
{
first_atom = i;
rank_first_atom = _canonical_rank[i];
}
}
if (INVALID_ATOM_NUMBER != first_atom)
return 1;
if (chiral_atom_if_we_need_to >= 0)
{
first_atom = chiral_atom_if_we_need_to;
return 1;
}
return 0;
}
//#define DEBUG_UNIQUE_SMILES_ORDERING
//#define DEBUG_UNIQUE_SMILES_ORDERING
//#define DEBUG_UNIQUE_SMILES_ORDERING
int
Atom_Chooser_Unique::next_atom (const Molecule & m, const int * zorder, const atom_number_t current_atom, atom_number_t & b, const int * include_atom) const
{
// Variables for bond order decisions
atom_number_t zdefault = INVALID_ATOM_NUMBER;
int hbc_save = 0; // initialised to shut gcc up
int highest_bond_count = 0; // definitely initialised to 0
const Atom * a = m.atomi(current_atom);
int acon = a->ncon();
for (int i = 0; i < acon; i++)
{
const Bond * b = a->item(i);
atom_number_t j = b->other(current_atom);
if (zorder[j] >= 0)
continue;
if (NULL != include_atom && 0 == include_atom[j])
continue;
int bcount;
// Note that the counting here is different from in the function number_of_bonds().
// In that function, single and double bonds are counted first, here we want to catch
// aromatic bonds first as contributing one to the bond count
if (b->is_aromatic())
bcount = 1;
else
bcount = b->number_of_bonds();
#ifdef DEBUG_UNIQUE_SMILES_ORDERING
cerr << "Choosing next unique atom, " << j << " (bcount = " << bcount << ", rj = " << canonical_rank(j) << ")\n";
#endif
if (bcount < highest_bond_count) // definitely not
continue;
const int rj = _canonical_rank[j];
if (bcount > highest_bond_count)
{
highest_bond_count = bcount;
zdefault = j;
hbc_save = rj;
}
else if (rj > hbc_save) // bcount == highest_bond_count
{
#ifdef DEBUG_UNIQUE_SMILES_ORDERING
cerr << "Bonds equal, rj = " << rj << " hbc_save = " << hbc_save << endl;
#endif
zdefault = j;
hbc_save = rj;
}
}
if (INVALID_ATOM_NUMBER != zdefault)
{
b = zdefault;
#ifdef DEBUG_UNIQUE_SMILES_ORDERING
cerr << "Next unique atom is atom " << b << endl;
#endif
return 1;
}
return 0;
}
class Atom_Chooser_Specific_Atom : public Atom_Chooser_Default
{
private:
Set_of_Atoms _start_atom;
// private functions
int _first_unselected (const int matoms, const int * zorder, atom_number_t & a, const int * include_atom) const;
public:
Atom_Chooser_Specific_Atom(const atom_number_t a) { _start_atom.add(a);}
Atom_Chooser_Specific_Atom(const Atom_Chooser_Specific_Atom & s) : _start_atom(s._start_atom) {}
int next_starting_atom(const Molecule & m, const int * zorder, atom_number_t & a, const int * include_atom);
int next_atom(const Molecule & m, const int * zorder, const atom_number_t zatom, atom_number_t & b, const int * include_atom) const;
};
int
Atom_Chooser_Specific_Atom::_first_unselected (const int matoms,
const int * zorder,
atom_number_t & a,
const int * include_atom) const
{
for (int i = 0; i < matoms; ++i)
{
if (zorder[i] >= 0)
continue;
if (NULL != include_atom && 0 == include_atom[i])
continue;
a = i;
return 1;
}
return 0;
}
int
Atom_Chooser_Specific_Atom::next_starting_atom(const Molecule & m, const int * zorder, atom_number_t & a, const int * include_atom)
{
const int n = _start_atom.number_elements();
if (0 == n)
return _first_unselected(m.natoms(), zorder, a, include_atom);
atom_number_t atom_to_return_if_nothing_else_found = INVALID_ATOM_NUMBER;
const int include_chiral_info = include_chiral_info_in_smiles();
for (int i = 0; i < n; ++i)
{
const atom_number_t j = _start_atom[i];
if (zorder[j] >= 0) // at this stage we could remove j from the array if we wanted to
continue;
if (NULL != include_atom && 0 == include_atom[j])
{
cerr << "Atom_Chooser_Specific_Atom:warning, selected start atom not included " << m.name() << endl;
continue;
}
if (include_chiral_info && m.chiral_centre_at_atom(j))
atom_to_return_if_nothing_else_found = j;
else
{
a = j;
_start_atom.remove_item(i);
return 1;
}
}
if (INVALID_ATOM_NUMBER != atom_to_return_if_nothing_else_found)
{
a = atom_to_return_if_nothing_else_found;
return 1;
}
// None of the specified atoms available, choose first
return _first_unselected(m.natoms(), zorder, a, include_atom);
}
int
Atom_Chooser_Specific_Atom::next_atom (const Molecule & m, const int * zorder, const atom_number_t zatom, atom_number_t & b, const int * include_atom) const
{
return this->Atom_Chooser_Default::next_atom(m, zorder, zatom, b, include_atom);
}
/*
I need an object to describe how to choose the first atom in a smiles
*/
#define SMILES_FIRST_ATOM_DEFAULT 1
#define SMILES_FIRST_ATOM_UNIQUE 4
/*
Note that if
*/
class Smiles_First_Atom
{
private:
int _how_to_choose; // one of the defined values above
atom_number_t _a;
public:
Smiles_First_Atom();
int smdeflt() const { return SMILES_FIRST_ATOM_DEFAULT == _how_to_choose;}
int unique () const { return SMILES_FIRST_ATOM_UNIQUE == _how_to_choose;}
void set_build_type (int s) { _how_to_choose = s;}
void set_atom_number (atom_number_t a) { _a = a;}
int atom_specified (atom_number_t &) const;
int atom_specified() const { return INVALID_ATOM_NUMBER != _a;}
void unset_first_atom() { _a = INVALID_ATOM_NUMBER; _how_to_choose = SMILES_FIRST_ATOM_DEFAULT;}
};
Smiles_First_Atom::Smiles_First_Atom()
{
_how_to_choose = SMILES_FIRST_ATOM_DEFAULT;
_a = INVALID_ATOM_NUMBER;
return;
}
int
Smiles_First_Atom::atom_specified (atom_number_t & first_atom) const
{
if (INVALID_ATOM_NUMBER == _a)
return 0;
first_atom = _a;
return 1;
}
//#define DEBUG_SMILES_CHOOSE_FIRST_ATOM
#ifdef DEBUG_SMILES_CHOOSE_FIRST_ATOM
static ostream &
operator << (ostream & os, const Smiles_First_Atom & smfa)
{
os << "SMFA: ";
if (smfa.atom_specified())
{
atom_number_t a;
(void) smfa.atom_specified(a);
os << "atom " << a;
}
else if (smfa.smdeflt())
os << "default";
else if (smfa.nice())
os << "nice";
else if (smfa.unique())
os << "unique";
else if (smfa.random())
os << "random";
else
os << " HUH";
return os;
}
#endif
static int _write_aromatic_bonds_as_colons = 0;
void
set_write_smiles_aromatic_bonds_as_colons (int s)
{
_write_aromatic_bonds_as_colons = s;
}
int
write_smiles_aromatic_bonds_as_colons()
{
return _write_aromatic_bonds_as_colons;
}
void
Smiles_Information::_default_values()
{
_smiles_order_type = INVALID_SMILES_ORDER_TYPE;
_smiles_order = NULL;
_smiles_is_smarts = 0;
_create_smarts_embedding = NULL;
_user_specified_atomic_smarts = NULL;
return;
}
Smiles_Information::Smiles_Information (int natoms) : _natoms(natoms)
{
_default_values();
return;
};
Smiles_Information::Smiles_Information() : _natoms(-1)
{
_default_values();
return;
}
Smiles_Information::~Smiles_Information()
{
if (NULL != _smiles_order)
delete [] _smiles_order;
if (NULL != _create_smarts_embedding)
delete [] _create_smarts_embedding;
if (NULL != _user_specified_atomic_smarts)
delete [] _user_specified_atomic_smarts;
return;
}
int
Smiles_Information::debug_print (std::ostream & os) const
{
if (NULL != _smiles_order)
{
if (UNIQUE_SMILES_ORDER_TYPE == _smiles_order_type)
os << "Unique smiles order computed\n";
else if (RANDOM_SMILES_ORDER_TYPE == _smiles_order_type)
os << "Random smiles order computed\n";
else if (DEFAULT_SMILES_ORDER_TYPE == _smiles_order_type)
os << "Default smiles order computed\n";
else if (SUBSET_SMILES_ORDER_TYPE == _smiles_order_type)
os << "Subset smiles order computed\n";
else
os << "Hmmm, smiles order type is " << _smiles_order_type << endl;
}
_ring_closure_bonds.write_bonds(os);
if (_smiles_start_atom.number_elements() > 0)
{
for (int i = 0; i < _smiles_start_atom.number_elements(); i++)
{
os << "smiles in fragment " << i << " starts with atom " << _smiles_start_atom[i] << endl;
}
}
if (_smiles.length())
os << "Smiles is '" << _smiles << "'\n";
return os.good();
}
void
Smiles_Information::make_empty()
{
_smiles = EMPTY_MOLECULE_SMILES;
if (NULL != _smiles_order)
{
delete [] _smiles_order;
_smiles_order = NULL;
}
return;
}
int
Smiles_Information::prepare_to_build_ordering (int matoms)
{
_smiles_order_type = INVALID_SMILES_ORDER_TYPE;
if (NULL == _smiles_order)
_smiles_order = new_int(matoms, -1);
else
set_vector(_smiles_order, matoms, -1);
_natoms = matoms;
if (! _ring_closure_bonds.activate(matoms))
return 0;
_smiles_start_atom.resize_keep_storage(0);
return 1;
}
int
Smiles_Information::prepare_to_build_smiles (int matoms)
{
_smiles.resize_keep_storage(0);
if (_smiles.elements_allocated() < 3 * matoms)
_smiles.resize(3 * matoms);
if (_atom_order_in_smiles.number_elements() > 0)
_atom_order_in_smiles.resize_keep_storage(0);
else
_atom_order_in_smiles.resize(matoms);
_natoms = matoms;
return 1;
}
void
Smiles_Information::invalidate()
{
_natoms = -1; // added IAW Aug 2014
_smiles_order_type = INVALID_SMILES_ORDER_TYPE;
_smiles.resize_keep_storage(0);
if (NULL != _smiles_order)
{
delete [] _smiles_order;
_smiles_order = NULL;
}
return;
}
int
Smiles_Information::create_smarts_embedding (atom_number_t zatom) const
{
if (NULL == _create_smarts_embedding) // should be a fatal error
return 0;
return _create_smarts_embedding[zatom];
}
int
Smiles_Information::set_create_smarts_embedding (int s)
{
assert(_natoms > 0);
if (NULL == _create_smarts_embedding)
_create_smarts_embedding = new_int(_natoms, s);
else
set_vector(_create_smarts_embedding, _natoms, s);
return 1;
}
int
Smiles_Information::set_create_smarts_embedding (atom_number_t zatom,
int s)
{
assert(_natoms > 0 && zatom >= 0 && zatom < _natoms);
if (NULL == _create_smarts_embedding)
_create_smarts_embedding = new_int(_natoms);
_create_smarts_embedding[zatom] = s;
return 1;
}
/*
*/
int
Molecule::_smiles_choose_first_atom (const int * zorder,
Smiles_First_Atom & smfa,
atom_number_t & first_atom,
const int * include_atom)
{
#ifdef DEBUG_SMILES_CHOOSE_FIRST_ATOM
cerr << "INto _smiles_choose_first_atom " << smfa << endl;
for (int i = 0; i < _number_elements; i++)
{
cerr << "Atom " << i << " order " << zorder[i] << endl;
}
#endif
if (smfa.smdeflt())
return _smiles_choose_first_atom(zorder, first_atom, include_atom);
if (smfa.unique())
{
if (NULL == include_atom)
return _smiles_choose_unique_first_atom(zorder, first_atom);
else
return _smiles_choose_unique_first_atom(zorder, first_atom, include_atom);
}
cerr << "Molecule::_smiles_choose_first_atom: no method specified\n";
iwabort();
return 0;
}
/*
Note that this is incorrect, a chiral atom can start a smiles, but
not sure if that works or not...
Mar 2004. Ran into problems with a subset. Every member of the molecule subset
was a chiral centre. Therefore save a possible match in ATOM_TO_RETURN_IF_NOTHING_ELSE_FOUND
*/
int
Molecule::_smiles_choose_first_atom (const int * zorder,
atom_number_t & first_atom,
const int * include_atom)
{
int include_chiral_info = include_chiral_info_in_smiles();
atom_number_t atom_to_return_if_nothing_else_found = INVALID_ATOM_NUMBER;
for (int i = 0; i < _number_elements; i++)
{
if (zorder[i] >= 0) // already done
continue;
if (NULL != include_atom && 0 == include_atom[i])
continue;
// A smiles cannot START at a chiral atom
#ifdef DEBUG_SMILES_CHOOSE_FIRST_ATOM
cerr << "Can the smiles start with atom " << i << endl;
cerr << "include_chiral_info " << include_chiral_info << endl;
cerr << "ncon " << _things[i]->ncon() << endl;
cerr << "chiral " << chiral_centre_at_atom(i) << endl;
if (include_chiral_info && _things[i]->ncon() > 2 && chiral_centre_at_atom(i))
cerr << "Nope, that looks chiral\n";
#endif
if (include_chiral_info && _things[i]->ncon() > 2 && chiral_centre_at_atom(i))
{
atom_to_return_if_nothing_else_found = i;
continue;
}
first_atom = i;
return 1;
}
if (INVALID_ATOM_NUMBER == atom_to_return_if_nothing_else_found)
return 0;
first_atom = atom_to_return_if_nothing_else_found;
return 1;
}
/*
External entry point for setting the random number used for
random smiles generation
*/
void
set_smiles_random_number_seed (random_number_seed_t seed)
{
random_smiles_default_seed = seed;
}
random_number_seed_t
set_smiles_random_number_seed_random()
{
std::random_device rd;
random_smiles_default_seed = rd();
return random_smiles_default_seed;
}
/*
As you can see, this is really not truly random, in that the
first atoms will be favoured.
*/
/*int
Molecule::_smiles_choose_random_first_atom (const int * zorder,
atom_number_t & first_atom,
const int * include_atom)
{
int include_chiral_info = include_chiral_info_in_smiles();
int istart = smiles_random_number_stream.intbtwij(0, _number_elements);
atom_number_t atom_to_return_if_nothing_else_found = INVALID_ATOM_NUMBER;
for (int i = istart; i < _number_elements; i++)
{
if (zorder[i] >= 0) // already done
continue;
if (NULL != include_atom && 0 == include_atom[i])
continue;
// A smiles cannot START at a chiral atom
if (include_chiral_info && chiral_centre_at_atom(i))
{
atom_to_return_if_nothing_else_found = i;
continue;
}
first_atom = i;
return 1;
}
// If we come to here, we did not find a suitable atom in the
// range [istart..matoms). How about (0..istart)
for (int i = 0; i < istart; i++)
{
// cerr << "Checking random start atom " << i << " zorder = " << zorder[i] << endl;
if (zorder[i] >= 0) // already processed
continue;
// A smiles cannot START at a chiral atom
if (include_chiral_info_in_smiles() && chiral_centre_at_atom(i))
{
atom_to_return_if_nothing_else_found = i;
continue;
}
first_atom = i;
return 1;
}
if (INVALID_ATOM_NUMBER != atom_to_return_if_nothing_else_found)
{
first_atom = atom_to_return_if_nothing_else_found;
return 1;
}
//cerr << "No random start atom available\n";
// Nothing possible
return 0;
}*/
/*
For unique smiles, we choose the highest ranked, most lowly connected atom
*/
int
Molecule::_smiles_choose_unique_first_atom (const int * zorder,
atom_number_t & first_atom)
{
const int * canonical_rank = _symmetry_class_and_canonical_rank.canonical_rank();
assert(NULL != canonical_rank);
int include_chiral_info = include_chiral_info_in_smiles();
int min_ncon = _number_elements; // greater than all ncon() values
atom_number_t zdefault = INVALID_ATOM_NUMBER;
int rsave = 0;
atom_number_t chiral_atom_if_we_need_to = INVALID_ATOM_NUMBER; // in case everything chiral [P@]12[P@]3[P@@]1[P@@]23
for (int i = 0; i < _number_elements; i++)
{
if (zorder[i] >= 0) // already processed
continue;
// A smiles cannot START at a chiral atom
if (include_chiral_info && chiral_centre_at_atom(i))
{
if (chiral_atom_if_we_need_to < 0)
chiral_atom_if_we_need_to = i;
continue;
}
const Atom * a = _things[i];
int ncon = a->ncon();
if (ncon < min_ncon)
{
min_ncon = ncon;
zdefault = i;
rsave = canonical_rank[i];
}
else if (ncon == min_ncon && canonical_rank[i] > rsave)
{
zdefault = i;
rsave = canonical_rank[i];
}
}
if (INVALID_ATOM_NUMBER != zdefault)
{
first_atom = zdefault;
return 1;
}
if (chiral_atom_if_we_need_to >= 0)
{
first_atom = chiral_atom_if_we_need_to;
return 1;
}
return 0;
}
/*
When dealing with a subset, we need to take into account only the number
of atoms connected in the subset
*/
int
Molecule::_smiles_choose_unique_first_atom (const int * zorder,
atom_number_t & first_atom,
const int * include_atom)
{
const int * canonical_rank = _symmetry_class_and_canonical_rank.canonical_rank();
assert(NULL != canonical_rank);
assert(NULL != include_atom);
int include_chiral_info = include_chiral_info_in_smiles();
int min_ncon = _number_elements; // greater than all ncon() values
atom_number_t zdefault = INVALID_ATOM_NUMBER;
int rsave = 0;
for (int i = 0; i < _number_elements; i++)
{
if (zorder[i] >= 0) // already processed
continue;
if (0 == include_atom[i])
continue;
// A smiles cannot START at a chiral atom
if (include_chiral_info && chiral_centre_at_atom(i))
continue;
const Atom * a = _things[i];
int ncon = a->ncon(i, include_atom);
if (ncon < min_ncon)
{
min_ncon = ncon;
zdefault = i;
rsave = canonical_rank[i];
}
else if (ncon == min_ncon && canonical_rank[i] > rsave)
{
zdefault = i;
rsave = canonical_rank[i];
}
}
if (INVALID_ATOM_NUMBER != zdefault)
{
first_atom = zdefault;
return 1;
}
return 0;
}
/*
The default (fast) behaviour is to find the first singly connected
and follow that. Otherwise follow the first multiple bond
*/
int
Molecule::_smiles_choose_next_atom (const int * zorder,
atom_number_t current_atom,
atom_number_t & next_atom,
const int * include_atom)
{
atom_number_t zdefault = INVALID_ATOM_NUMBER;
const Atom * a = _things[current_atom];
int acon = a->ncon();
for (int i = 0; i < acon; i++)
{
atom_number_t j;
bond_type_t bt;
a->other_and_type(current_atom, i, j, bt);
if (zorder[j] >= 0) // atom already classified
continue;
if (NULL != include_atom && 0 == include_atom[j])
continue;
if (1 == _things[j]->ncon())
{
next_atom = j;
return 1;
}
if (! IS_SINGLE_BOND(bt))
{
next_atom = j;
return 1;
}
else if (INVALID_ATOM_NUMBER == zdefault)
zdefault = j;
}
if (INVALID_ATOM_NUMBER != zdefault)
{
next_atom = zdefault;
return 1;
}
return 0;
}
/*
The rule for unique order is connection with the highest bond order
first, with ties broken by unique ordering.
*/
//#define DEBUG_BUILD_SMILES_ORDERING
/*
Look for ring closure bonds attached to the atom, then continue
the search.
Turns out we can get slightly quicker run times if we can pass N by value rather than
by reference. But if it is a complex object, then that fails.
*/
#ifdef NEW_VEWRSIONASDLKASD
template <typename N>
int
Molecule::_build_smiles_ordering_fctr (N identify_next_atom,
const atom_number_t previous_atom,
const atom_number_t zatom,
int & icounter,
const int * include_atom,
Smiles_Information & smi_info)
{
int * zorder = smi_info.smiles_order();
assert(zatom >= 0 && zatom < _number_elements && zorder[zatom] < 0);
#ifdef DEBUG_BUILD_SMILES_ORDERING
cerr << "_build_smiles_ordering continues with atom " << zatom << endl;
#endif
zorder[zatom] = icounter;
icounter++;
const Atom * a = _things[zatom];
const int acon = a->ncon();
if (INVALID_ATOM_NUMBER != previous_atom && 1 == acon) // got to a terminal atom
return 0;
Set_of_Atoms unprocessed_connections;
for (int i = 0; i < acon; i++)
{
const Bond * b = a->item(i);
atom_number_t j = b->other(zatom);;
if (previous_atom == j) // the atom from which we came
continue;
#ifdef DEBUG_BUILD_SMILES_ORDERING
cerr << " Atom " << j << " is connected";
if (zorder[j] >= 0)
cerr << ". Ring closure detected";
cerr << endl;
#endif
if (zorder[j] >= 0) // we have found a ring closure
smi_info.add_ring_closure_bond(zatom, j);
else if (NULL != include_atom && 0 == include_atom[j])
;
else
unprocessed_connections.add(j);
}
if (0 == unprocessed_connections.number_elements())
return 0;
if (1 == unprocessed_connections.number_elements())
return 1 + _build_smiles_ordering_fctr(identify_next_atom, zatom, unprocessed_connections[0], icounter, include_atom, smi_info);
atom_number_t b;
int rc = 0;
while (identify_next_atom.next_atom(*this, unprocessed_connections, zorder, zatom, b))
{
rc += _build_smiles_ordering_fctr(identify_next_atom, zatom, b, icounter, include_atom, smi_info);
}
return rc;
}
#endif
template <typename N>
int
Molecule::_build_smiles_ordering_fctr (N identify_next_atom,
atom_number_t previous_atom,
atom_number_t zatom,
int & icounter,
const int * include_atom,
Smiles_Information & smi_info)
{
int * zorder = smi_info.smiles_order();
assert(zatom >= 0 && zatom < _number_elements && zorder[zatom] < 0);
#ifdef DEBUG_BUILD_SMILES_ORDERING
cerr << "_build_smiles_ordering continues with atom " << zatom << endl;
#endif
while (1)
{
zorder[zatom] = icounter;
icounter++;
const Atom * a = _things[zatom];
const int acon = a->ncon();
if (INVALID_ATOM_NUMBER != previous_atom && 1 == acon) // got to a terminal atom
return 0;
atom_number_t next_unprocessed_connection = INVALID_ATOM_NUMBER;
for (int i = 0; i < acon; i++)
{
const atom_number_t j = a->other(zatom, i);;
if (previous_atom == j) // the atom from which we came
continue;
#ifdef DEBUG_BUILD_SMILES_ORDERING
cerr << " Atom " << j << " is connected";
if (zorder[j] >= 0)
cerr << ". Ring closure detected";
cerr << endl;
#endif
if (zorder[j] >= 0) // we have found a ring closure
smi_info.add_ring_closure_bond(zatom, j);
else if (NULL != include_atom && 0 == include_atom[j])
;
else if (INVALID_ATOM_NUMBER == next_unprocessed_connection)
next_unprocessed_connection = j;
else
next_unprocessed_connection = _number_elements; // special value that cannot be an atom number
}
if (INVALID_ATOM_NUMBER == next_unprocessed_connection)
return 0;
if (_number_elements == next_unprocessed_connection) // remember special value used above. More than one path from her
break;
previous_atom = zatom;
zatom = next_unprocessed_connection;
}
//if (_number_elements != next_unprocessed_connection) // remember special value used above
// return 1 + _build_smiles_ordering_fctr(identify_next_atom, zatom, next_unprocessed_connection, icounter, include_atom, smi_info);
atom_number_t b;
int rc = 0;
while (identify_next_atom.next_atom(*this, zorder, zatom, b, include_atom))
{
rc += _build_smiles_ordering_fctr(identify_next_atom, zatom, b, icounter, include_atom, smi_info);
}
return rc;
}
/*
All smiles building comes through here.
*/
template <typename N>
int
Molecule::_build_smiles_ordering_fctr (N next_atom_selector,
const int * include_atom,
Smiles_Information & smi_info)
{
if (! _fragment_information.contains_valid_data())
(void) number_fragments();
//cerr << "Molecule::_build_smiles_ordering:there are " << _fragment_information.number_fragments() << " fragments in full molecule with " << _number_elements << " atoms\n";
smi_info.prepare_to_build_ordering(_number_elements);
int zcounter = 0; // allocated in increasing order
atom_number_t a; // start atom within each fragment
int frag = 0;
while (next_atom_selector.next_starting_atom(*this, smi_info.smiles_order(), a, include_atom))
{
#ifdef DEBUG_BUILD_SMILES_ORDERING
cerr << "Starting fragment with atom " << a << " " << const_smarts_equivalent_for_atom(a) << endl;
#endif
smi_info.add_start_atom(a);
_build_smiles_ordering_fctr(next_atom_selector, INVALID_ATOM_NUMBER, a, zcounter, include_atom, smi_info);
frag++;
}
// If we built a subset, we may have fewer or more fragments detected
if (0 == frag)
{
cerr << "Molecule::_build_smiles_ordering:no atoms selected!\n";
return 0;
}
assert(NULL == include_atom ? frag == _fragment_information.number_fragments() : frag > 0);
#ifdef DEBUG_BUILD_SMILES_ORDERING
cerr << "Smiles order array constructed, " << frag << " fragments\n";
for (int i = 0; i < _number_elements; i++)
{
cerr << "Atom " << i << " order is " << zorder[i];
if (_fragment_information.number_fragments() > 1)
cerr << " fragment " << _fragment_information.fragment_membership(i);
cerr << endl;
}
//if (_ring_closure_bonds.number_elements())
//{
// for (int i = 0; i < _ring_closure_bonds.number_elements(); i++)
// {
// const Bond * b = _ring_closure_bonds[i];
// cerr << "Ring closure bond " << i << " " << *b << endl;
// }
//}
#endif
return 1;
}
/*
In a subset, is a given bond still in a ring
*/
#ifdef SEEMS_NOT_BEING_USED
int
Molecule::_ring_bond_in_subset (const int * include_atom,
atom_number_t a1,
atom_number_t a2)
{
int nr = nrings();
for (int i = 0; i < nr; i++)
{
const Ring * ri = ringi(i);
if (! ri->contains_bond(a1, a2))
continue;
if (ri->all_members_set_in_array(include_atom, 1))
return 1;
}
return 0;
}
#endif
/*
We are processing the connections to ANCHOR, and need to build
a sorted array of the adjacent bonds which need to be processed.
We do an insertion sort, based on the ZORDER value of the atom
at the other end of the bond
*/
static void
insert_bond (atom_number_t anchor,
const int * zorder,
resizable_array<const Bond *> & bonds,
const Bond * b)
{
int nb = bonds.number_elements();
atom_number_t zatom = b->other (anchor);
for (int i = 0; i < nb; i++)
{
atom_number_t ai = bonds[i]->other (anchor);
if (zorder[zatom] < zorder[ai])
{
bonds.insert_before (i, b);
return;
}
}
// If we come out here, either the list is empty, or the new atom at
// the end of the bond is ordered higher than all others
bonds.add(b);
return;
}
/*
We need to put the ring closure bonds into canonical order
*/
static void
sort_ring_closures_found(resizable_array<atom_number_t> & ring_closures_found,
const int * zorder)
{
if (2 == ring_closures_found.number_elements())
{
atom_number_t a0 = ring_closures_found[0];
atom_number_t a1 = ring_closures_found[1];
if (zorder[a0] > zorder[a1])
ring_closures_found.swap_elements(0, 1);
}
else if (3 == ring_closures_found.number_elements()) // poor-man's sort
{
atom_number_t a0 = ring_closures_found[0];
atom_number_t a1 = ring_closures_found[1];
atom_number_t a2 = ring_closures_found[2];
if (zorder[a0] > zorder[a1])
{
std::swap(a0, a1);
ring_closures_found.swap_elements(0, 1);
}
if (zorder[a1] > zorder[a2])
{
std::swap(a1, a2);
ring_closures_found.swap_elements(1, 2);
}
if (zorder[a0] > zorder[a1])
ring_closures_found.swap_elements(0, 1);
}
return;
}
//#define DEBUG_SMILES_FORMATION
/*
Ran into problems with deciding which atoms should be in the smiles
and which should be omitted. For now, if it is in the CT, it will
be processed.
Very strange stuff when dealing with directional bonds.
Consider
2
\
1==3
/ \
0 4
And consider starting with atom 2. The smiles is 2\1(\0)=3\4
BUT, the 0-1 bond will be an / bond.
Similarly, when starting with atom 0, the smiles is 0/1(/2)=3\4
BUT, the 1-2 bond will be a \ bond
When we detect that, we must react appropriately
The implementation is deliberately not recursive. Recursive stops processing larger molecules
*/
int
Molecule::_construct_smiles_for_fragment(Smiles_Formation_Info & sfi,
Smiles_Information & smi_info)
{
int * already_done = sfi.already_done();
IWString & smiles = smi_info.smiles();
atom_number_t previous_atom = sfi.previous_atom();
atom_number_t zatom = sfi.zatom();
const int * include_atom = sfi.include_atom();
#ifdef DOES_NOT_HELP
if (0 == _things[zatom]->ncon() && NULL != include_atom && include_atom[zatom]) // a counterion
{
_process_atom_for_smiles(sfi, smiles);
if (NULL != include_atom)
include_atom[zatom] = 1;
return 1;
}
#endif
resizable_array<atom_number_t> prev, current; // stack of various things to avoid recursion
IWString open_paren, clse_paren, bond_char;
//cerr << "_construct_smiles_for_fragment previous_atom " << previous_atom << endl;
prev.add(previous_atom);
current.add(zatom);
open_paren.add(' ');
clse_paren.add(' ');
bond_char.add(' ');
const int * zorder = smi_info.smiles_order();
resizable_array<const Bond *> ring_opening_bonds;
resizable_array<atom_number_t> ring_closures_found;
resizable_array<const Bond *> process_these_bonds;
while (current.number_elements() > 0)
{
#ifdef DEBUG_SMILES_FORMATION
cerr << "stack";
for (int i = 0; i < current.number_elements(); ++i)
{
if (i > 0)
cerr << '|';
cerr << ' ' << current[i] << ' ' << prev[i] << ' ' << open_paren[i] << ' ' << bond_char[i];
}
cerr << endl;
#endif
// if (current.number_elements() > 1000)
// cerr << "stack " << current.number_elements() << endl;
// cerr << smiles.length() << endl;
// cerr << current.number_elements() << ' ' << prev.number_elements() << ' ' << bond_char.number_elements() << ' ' << open_paren.number_elements() << endl;
zatom = current.pop();
previous_atom = prev.pop();
const char bsymb = bond_char.pop();
const char oparen = open_paren.pop();
if (' ' != oparen)
clse_paren += ')';
sfi.set_prev_and_zatom(previous_atom, zatom);
if (' ' != oparen)
smiles += oparen;
if (' ' != bsymb)
smiles += bsymb;
already_done[zatom] = 1;
smi_info.add_atom(zatom);
const Atom * a = _things[zatom];
int acon = a->ncon();
// If there are no other connections from here, no need to go looking
// for ring openings or prioritising connections
if (acon > 1) // most likely case
;
else if ((1 == acon && INVALID_ATOM_NUMBER != previous_atom) || (0 == acon))
{
_process_atom_for_smiles(sfi, smiles);
if (clse_paren.number_elements() && ' ' != clse_paren.pop())
smiles += ')';
continue;
}
// Build a sorted list of the connections to be processed, identifying
// any ring openings or closings.
// Note that we duplicate a lot of code here to avoid repeatedly testing INCLUDE_ATOM
ring_opening_bonds.resize_keep_storage(0);
ring_closures_found.resize_keep_storage(0);
process_these_bonds.resize_keep_storage(0);
if (NULL == include_atom)
{
for (int i = 0; i < acon; i++)
{
const Bond * b = a->item(i);
atom_number_t j = b->other(zatom);
if (previous_atom == j)
continue;
if (already_done[j]) // closing a ring
ring_closures_found.add(j);
else if (smi_info.contains_ring_closure_bond(zatom, j))
insert_bond(zatom, zorder, ring_opening_bonds, b);
else // just a regular connection
insert_bond(zatom, zorder, process_these_bonds, b);
}
}
else
{
for (int i = 0; i < acon; i++)
{
const Bond * b = a->item(i);
atom_number_t j = b->other(zatom);
if (previous_atom == j)
continue;
if (0 == include_atom[j])
continue;
if (already_done[j]) // closing a ring
ring_closures_found.add(j);
else if (smi_info.contains_ring_closure_bond(zatom, j))
insert_bond(zatom, zorder, ring_opening_bonds, b);
else // just a regular connection
insert_bond(zatom, zorder, process_these_bonds, b);
}
}
#ifdef DEBUG_INSERT_BOND
int npb = process_these_bonds.number_elements();
for (int i = 0; i < npb; i++)
{
const Bond * b = process_these_bonds[i];
cerr << " i = " << i << " bond to " << b->other(zatom) << " order " << zorder[b->other(zatom)] << endl;
}
#endif
const Chiral_Centre * c = NULL;
if (include_chiral_info_in_smiles())
c = chiral_centre_at_atom(zatom); // will be NULL if atom A is not a chiral centre
if (NULL != c && ring_closures_found.number_elements() > 1)
sort_ring_closures_found(ring_closures_found, zorder);
// Now that we have determined any ring openings, we can append the smiles symbol.
// We must wait until ring openings are determined for chiral atoms
(void) _process_atom_for_smiles(sfi, zorder, ring_opening_bonds, ring_closures_found, c, smiles);
Ring_Number_Manager & rnm = sfi.rnm();
assert(rnm.ok());
rnm.append_ring_closing_and_opening_digits(smiles, zatom, ring_closures_found, ring_opening_bonds, c);
// if ('(' == cparen)
// smiles += ')';
#ifdef DEBUG_SMILES_FORMATION
cerr << "After atom " << zatom << " smiles is now '" << smiles << "'\n";
if (ring_closures_found.number_elements())
cerr << "Found " << ring_closures_found.number_elements() << " ring closures\n";
#endif
// Handle the case of no further connections
// If there are no connections, there should not be any ring openings
acon = process_these_bonds.number_elements();
if (0 == acon)
{
if (ring_opening_bonds.number_elements())
cerr << "No connections, but " << ring_opening_bonds.number_elements() << " ring openings\n";
assert( (NULL == include_atom) ? (0 == ring_opening_bonds.number_elements()) : 1);
if (clse_paren.number_elements() && ' ' != clse_paren.pop())
smiles += ')';
continue;
}
const int inc_ctb = include_cis_trans_in_smiles(); // do the call once for efficiency
unsigned int inc_arom; // aromatic bonds or not
if (! sfi.write_smiles())
inc_arom = 1;
else
inc_arom = get_include_aromaticity_in_smiles();
if (write_single_bonds_in_smiles())
inc_arom |= 2;
for (int i = acon - 1; i >= 0; --i)
{
const Bond * b = process_these_bonds[i];
const atom_number_t j = b->other(zatom);
if (inc_ctb && b->is_directional())
_process_directional_bond_for_smiles(bond_char, b, j);
else if (_write_aromatic_bonds_as_colons && b->is_aromatic())
bond_char += ':';
else
b->append_bond_type_space_for_nothing(bond_char, j, inc_arom);
if (i != (acon - 1))
open_paren.add('(');
else
open_paren.add(' ');
prev.add(zatom);
current.add(j);
}
}
while (clse_paren.number_elements())
{
if (' ' != clse_paren.pop())
smiles += ')';
}
return 1;
}
/*
A smiles for a fragment will begin with atom A
We need to identify the bond down which the smiles will start
*/
const Bond *
Molecule::_identify_first_smiles_bond (atom_number_t zatom,
const int * zorder)
{
const Atom * a = _things[zatom];
int acon = a->ncon();
int smallest_zorder = -1;
const Bond * rc = NULL;
for (int i = 0; i < acon; i++)
{
const Bond * b = a->item(i);
atom_number_t j = b->other(zatom);
if (smallest_zorder < 0)
{
smallest_zorder = zorder[j];
rc = b;
}
else if (zorder[j] < smallest_zorder)
{
smallest_zorder = zorder[j];
rc = b;
}
}
return rc;
}
int
Molecule::_construct_smiles(const Fragment_Information & frag_info,
Smiles_Information & smi_info,
const int * include_atom)
{
int * already_done = new_int(_number_elements); std::unique_ptr<int[]> free_already_done(already_done);
smi_info.prepare_to_build_smiles(_number_elements);
const int * zorder = smi_info.smiles_order();
#ifdef DEBUG_SMILES_FORMATION
for (int i = 0; i < _number_elements; i++)
{
cerr << "Atom " << i << " (" << atomic_symbol(i) << ") order is " << zorder[i];
if (NULL != include_atom)
cerr << " include_atom " << include_atom[i];
cerr << endl;
}
#endif
const Set_of_Atoms & smiles_start_atom = smi_info.smiles_start_atom();
int n = smiles_start_atom.number_elements();
assert(n == frag_info.number_fragments()); // must be a smiles start atom in each fragment
int rc = 0;
int need_dot = 0;
#ifdef DEBUG_SMILES_FORMATION
cerr << "Generating smiles for molecule with " << frag_info.number_fragments() << " fragments\n";
for (int i = 0; i < _number_elements; i++)
{
cerr << " atom " << i << " '" << smarts_equivalent_for_atom(i) << " in fragment " << frag_info.fragment_membership(i);
if (NULL != include_atom)
cerr << " include " << include_atom[i];
cerr << endl;
}
#endif
IWString & smiles = smi_info.smiles();
for (int i = 0; i < n; i++)
{
atom_number_t astart = smiles_start_atom[i];
int f = frag_info.fragment_membership(astart);
if (NULL == include_atom) // no need to check anything
;
else if (include_atom[astart]) // great, that atom is being processed
;
else // see if we can find something in fragment F
{
astart = _choose_highest_canonical_order_in_fragment(f, zorder, include_atom);
if (INVALID_ATOM_NUMBER == astart)
continue;
}
if (need_dot)
smiles += '.';
int nr = frag_info.rings_in_fragment(f);
#ifdef DEBUG_SMILES_FORMATION
cerr << "Fragment " << f << " contains " << frag_info.bonds_in_fragment(f) << " bonds and " << frag_info.atoms_in_fragment(f) << " atoms, nr = " << nr << ", start atom " << astart << endl;
#endif
Smiles_Formation_Info sfi(_number_elements, nr);
// cerr << "Doing smarts? " << smi_info.smiles_is_smarts() << endl;
if (NULL != smi_info.user_specified_atomic_smarts())
sfi.set_user_specified_atomic_smarts(smi_info.user_specified_atomic_smarts());
if (smi_info.smiles_is_smarts())
{
sfi.set_make_smarts_embedding(smi_info.create_smarts_embedding());
// cerr << "Adding user specified atomic smarts " << smi_info.user_specified_atomic_smarts() << endl;
}
sfi.set_zatom(astart);
sfi.set_already_done(already_done);
sfi.set_include_atom(include_atom);
if (write_smiles_with_smarts_atoms())
sfi.set_write_smiles(0);
rc += _construct_smiles_for_fragment(sfi, smi_info);
need_dot = 1;
}
return rc;
}
/*
The array _smiles_order can be ordered in a number of ways.
_smiles_order_type must be updated to correspond with the
ordering type
*/
const IWString &
Molecule::smiles()
{
assert(ok());
if (! _smiles_information.contains_smiles()) // need to recompute
;
else if (_smiles_information.smiles_is_smarts())
{
_smiles_information.make_empty();
_smiles_information.set_smiles_is_smarts(0);
}
else
return _smiles_information.smiles();
if (0 == _number_elements)
{
_smiles_information.make_empty();
return _smiles_information.smiles();
}
(void) number_fragments();
if (! _smiles_information.contains_valid_ordering())
{
Atom_Chooser_Default acd;
if (! _build_smiles_ordering_fctr(acd, NULL, _smiles_information))
{
cerr << "Molecule::smiles: cannot construct ordering\n";
_smiles_information.set_error();
return _smiles_information.smiles();
}
_smiles_information.set_smiles_order_type(DEFAULT_SMILES_ORDER_TYPE);
}
_smiles_information.smiles().resize(4 * _number_elements);
_construct_smiles(_fragment_information, _smiles_information, NULL);
return _smiles_information.smiles();
}
const IWString &
Molecule::smiles (Smiles_Information & smi_info,
const int * include_atom)
{
if (0 == _number_elements)
{
smi_info.make_empty();
return smi_info.smiles();
}
Atom_Chooser_Default acd;
if (! _build_smiles_ordering_fctr(acd, include_atom, smi_info))
{
cerr << "Molecule::smiles:cannot build subset smiles info\n";
smi_info.set_error();
return smi_info.smiles();
}
Fragment_Information frag_info;
if (! compute_fragment_information(frag_info, include_atom))
{
cerr << "Molecule::smiles:cannot compute fragment info of subset\n";
smi_info.set_error();
return smi_info.smiles();
}
smi_info.set_smiles_order_type(SUBSET_SMILES_ORDER_TYPE);
_construct_smiles(frag_info, smi_info, include_atom);
return smi_info.smiles();
}
const IWString &
Molecule::random_smiles()
{
if (0 == _number_elements)
{
_smiles_information.make_empty();
return _smiles_information.smiles();
}
invalidate_smiles();
Atom_Chooser_Random acr;
(void) _build_smiles_ordering_fctr(acr, NULL, _smiles_information);
_smiles_information.set_smiles_order_type(RANDOM_SMILES_ORDER_TYPE);
_construct_smiles(_fragment_information, _smiles_information, NULL);
return _smiles_information.smiles();
}
/*
For helping people with text based programmes, we have the ability to
start a smiles with any atom. This is a kludge, because this doesn't
really fit well with how the smiles are built.
*/
const IWString &
Molecule::smiles_starting_with_atom (atom_number_t astart)
{
return smiles_starting_with_atom(astart, _smiles_information, NULL);
}
const IWString &
Molecule::smiles_starting_with_atom (atom_number_t astart,
Smiles_Information & smi_info,
const int * include_atom)
{
if (0 == _number_elements)
{
smi_info.make_empty();
return smi_info.smiles();
}
assert(NULL == include_atom ? 1 : 0 != include_atom[astart]);
smi_info.invalidate();
(void) number_fragments();
Atom_Chooser_Specific_Atom acsa(astart);
(void) _build_smiles_ordering_fctr(acsa, include_atom, smi_info);
#ifdef NOT_SURE_WHY_I_HAD_DONE_THIS
Fragment_Information frag_info;
if (! compute_fragment_information(frag_info, include_atom))
{
cerr << "Molecule::smiles_starting_with_atom:cannot find fragment info for subset\n";
smi_info.set_error();
return smi_info.smiles();
}
#endif
smi_info.set_smiles_order_type(RANDOM_SMILES_ORDER_TYPE);
_construct_smiles(_fragment_information, smi_info, include_atom);
return smi_info.smiles();
}
/*
Someone may need to know the order of the atoms in the smiles
*/
int
Molecule::smiles_atom_order (int * s)
{
(void) smiles(); // will force construction of the array(s)
const int * so = _smiles_information.smiles_order();
copy_vector(s, so, _number_elements);
return 1;
}
//#define DEBUG_UNIQUE_SMILES
const IWString &
Molecule::_unique_smiles (const Fragment_Information & frag_info,
Smiles_Information & smi_info,
Symmetry_Class_and_Canonical_Rank & sccr,
const int * include_atom)
{
//cerr << "Allocated? " << sccr.arrays_allocated() << endl;
if (0 == _number_elements)
{
smi_info.make_empty();
return smi_info.smiles();
}
smi_info.prepare_to_build_ordering(_number_elements);
compute_aromaticity_if_needed();
#ifdef DEBUG_UNIQUE_SMILES
cerr << "Computing unique smiles for " << _number_elements << " atoms\n";
if (! sccr.arrays_allocated())
cerr << "Computing canonical rank\n";
else
cerr << "Canonical rank already computed\n";
#endif
if (! sccr.arrays_allocated())
compute_canonical_ranking(sccr, include_atom);
#ifdef DEBUG_UNIQUE_SMILES
cerr << "Canonical rank computed\n";
const int * c = sccr.canonical_rank();
for (int i = 0; i < _number_elements; i++)
{
cerr << "Atom " << i << " type " << _things[i]->atomic_symbol();
if (NULL != include_atom)
cerr << " include " << include_atom[i];
cerr << " rank " << c[i] << endl;
}
cerr << "Order type " << smi_info.smiles_order_type() << '\n';
#endif
if (include_cis_trans_in_smiles())
_adjust_cis_trans_bonds_to_canonical_form(sccr.canonical_rank());
assert(NULL != _aromaticity); // aromaticity computed in compute_canonical_ranking
Smiles_First_Atom smfa;
smfa.set_build_type(SMILES_FIRST_ATOM_UNIQUE);
Atom_Chooser_Unique acn(canonical_ranks());
(void) _build_smiles_ordering_fctr(acn, include_atom, smi_info);
if (NULL == include_atom)
smi_info.set_smiles_order_type(UNIQUE_SMILES_ORDER_TYPE);
else
smi_info.set_smiles_order_type(SUBSET_SMILES_ORDER_TYPE);
#ifdef DEBUG_UNIQUE_SMILES
cerr << "Smiles unique order is\n";
const int * s = smi_info.smiles_order();
for (int i = 0; i < _number_elements; i++)
{
cerr << " i = " << i << " order = " << s[i] << endl;
}
#endif
_construct_smiles(frag_info, smi_info, include_atom);
return smi_info.smiles();
}
#ifdef VERSION_USING_FUNCTION_POINTER
const IWString &
Molecule::_unique_smiles (const Fragment_Information & frag_info,
Smiles_Information & smi_info,
Symmetry_Class_and_Canonical_Rank & sccr,
const int * include_atom)
{
//cerr << "Allocated? " << sccr.arrays_allocated() << endl;
if (0 == _number_elements)
{
smi_info.make_empty();
return smi_info.smiles();
}
smi_info.prepare_to_build_ordering(_number_elements);
compute_aromaticity_if_needed();
#ifdef DEBUG_UNIQUE_SMILES
cerr << "Computing unique smiles for " << _number_elements << " atoms\n";
if (! sccr.arrays_allocated())
cerr << "Computing canonical rank\n";
else
cerr << "Canonical rank already computed\n";
#endif
if (! sccr.arrays_allocated())
compute_canonical_ranking(sccr, include_atom);
#ifdef DEBUG_UNIQUE_SMILES
cerr << "Canonical rank computed\n";
const int * c = sccr.canonical_rank();
for (int i = 0; i < _number_elements; i++)
{
cerr << "Atom " << i << " type " << _things[i]->atomic_symbol();
if (NULL != include_atom)
cerr << " include " << include_atom[i];
cerr << " rank " << c[i] << endl;
}
cerr << "Order type " << smi_info.smiles_order_type() << '\n';
#endif
if (include_cis_trans_in_smiles())
_adjust_cis_trans_bonds_to_canonical_form(sccr.canonical_rank());
assert(NULL != _aromaticity); // aromaticity computed in compute_canonical_ranking
Smiles_First_Atom smfa;
smfa.set_build_type(SMILES_FIRST_ATOM_UNIQUE);
(void) _build_smiles_ordering(smfa,
&Molecule::_smiles_choose_unique_next_atom,
include_atom,
smi_info);
if (NULL == include_atom)
smi_info.set_smiles_order_type(UNIQUE_SMILES_ORDER_TYPE);
else
smi_info.set_smiles_order_type(SUBSET_SMILES_ORDER_TYPE);
#ifdef DEBUG_UNIQUE_SMILES
cerr << "Smiles unique order is\n";
const int * s = smi_info.smiles_order();
for (int i = 0; i < _number_elements; i++)
{
cerr << " i = " << i << " order = " << s[i] << endl;
}
#endif
_construct_smiles(frag_info, smi_info, include_atom);
return smi_info.smiles();
}
#endif
/*
Be careful using unique_smiles() and non_aromatic_unique_smiles()
If you call unique_smiles() and then non_aromatic_unique_smiles()
you will likely get the same smiles back. To force a recomputation,
call invalidate_smiles() in between...
Jul 2000. Introduce a default aromaticity that is used for all
unique smiles
*/
static int default_unique_smiles_aromaticity = Daylight;
int
set_default_unique_smiles_aromaticity (int a)
{
default_unique_smiles_aromaticity = a;
return 1;
}
/*
We have some common tasks that need to happen when doing unique smiles determinations.
Some things need to be set and then restored.
*/
class Hold_and_Restore_Global_Settings
{
private:
int _aromsave; // save the global aromaticity definition
int _incaromsave; // save the include aromaticity in smiles definition
int _inc_atom_map_save;
public:
Hold_and_Restore_Global_Settings (int incarom);
~Hold_and_Restore_Global_Settings();
int aromaticity_changed() const { return _aromsave != default_unique_smiles_aromaticity;}
};
Hold_and_Restore_Global_Settings::Hold_and_Restore_Global_Settings (int incarom)
{
_aromsave = global_aromaticity_type();
set_global_aromaticity_type(default_unique_smiles_aromaticity);
_incaromsave = get_include_aromaticity_in_smiles();
set_include_aromaticity_in_smiles(incarom);
_inc_atom_map_save = include_atom_map_with_smiles();
set_include_atom_map_with_smiles(0);
return;
}
Hold_and_Restore_Global_Settings::~Hold_and_Restore_Global_Settings()
{
set_global_aromaticity_type(_aromsave);
set_include_aromaticity_in_smiles(_incaromsave);
set_include_atom_map_with_smiles(_inc_atom_map_save);
return;
}
const IWString &
Molecule::unique_smiles()
{
if (UNIQUE_SMILES_ORDER_TYPE == _smiles_information.smiles_order_type())
return _smiles_information.smiles();
Hold_and_Restore_Global_Settings hrgs(1);
if (hrgs.aromaticity_changed()) // we may have Pearlman aromaticity, but need Daylight for unique smiles
compute_aromaticity();
else
compute_aromaticity_if_needed();
_smiles_information.set_smiles_is_smarts(0);
return _unique_smiles(_fragment_information, _smiles_information, _symmetry_class_and_canonical_rank, NULL);
}
const IWString &
Molecule::unique_smiles (Smiles_Information & smi_info,
const int * include_atom)
{
assert(NULL != include_atom);
if (0 == _number_elements)
{
_smiles_information.make_empty();
return _smiles_information.smiles();
}
_smiles_information.set_smiles_is_smarts(0);
//_fragment_information.debug_print(cerr);
Hold_and_Restore_Global_Settings hrgs(1);
if (hrgs.aromaticity_changed())
compute_aromaticity();
Fragment_Information frag_info;
if (! compute_fragment_information(frag_info, include_atom))
{
cerr << "Molecule::unique_smiles:cannot compute fragment info for subset\n";
smi_info.set_error();
return smi_info.smiles();
}
Symmetry_Class_and_Canonical_Rank sccr;
if (! sccr.allocate_arrays(_number_elements))
return smi_info.set_error();
compute_canonical_ranking(sccr, include_atom);
if (include_cis_trans_in_smiles())
_adjust_cis_trans_bonds_to_canonical_form(sccr.canonical_rank());
// _smiles_choose_unique_*_atom need to have the molecule's canonical order fixed. Make
// a copy of any existing data in _symmetry_class_and_canonical_rank and store the
// values from sccr into _symmetry_class_and_canonical_rank
Symmetry_Class_and_Canonical_Rank sccr_save;
sccr_save.store_values_from(_symmetry_class_and_canonical_rank, _number_elements);
_symmetry_class_and_canonical_rank.store_values_from(sccr, _number_elements);
_unique_smiles(frag_info, smi_info, sccr, include_atom);
_symmetry_class_and_canonical_rank.store_values_from(sccr_save, _number_elements);
return smi_info.smiles();
}
const IWString &
Molecule::non_aromatic_unique_smiles()
{
if (0 == _number_elements)
{
_smiles_information.make_empty();
return _smiles_information.smiles();
}
_smiles_information.set_smiles_is_smarts(0);
Hold_and_Restore_Global_Settings hrgs(0);
if (hrgs.aromaticity_changed())
compute_aromaticity();
return _unique_smiles(_fragment_information, _smiles_information, _symmetry_class_and_canonical_rank, NULL);
}
/*
In processing a fused system, it has been discerned that some rings
which had previously been assigned separate fused system identifiers
are in fact part of the same fused system.
We examine rings in RINGS, starting with ring RSTART.
The common fused system identifier is FUSED_SYSTEM_IDENTIFIER.
The fused system identifiers which need to be changed are in FUSED_SYS_IDS_TO_BE_CHANGES
*/
int
Molecule::_merge_fused_system_identifiers (resizable_array<Ring *> & rings,
int rstart,
int fused_system_identifier,
resizable_array<int> & fused_sys_ids_to_be_changed)
{
int rc = 0;
int nr = rings.number_elements();
for (int i = rstart; i < nr; i++)
{
Ring * r = rings[i];
if (! r->is_fused())
continue;
int rfsysid = r->fused_system_identifier();
if (rfsysid == fused_system_identifier)
continue;
if (fused_sys_ids_to_be_changed.contains(rfsysid))
{
r->set_fused_system_identifier(fused_system_identifier);
r->set_is_fused(1);
rc++;
}
}
return rc;
}
int
Molecule::_find_raw_rings(const atom_number_t previous_atom,
const atom_number_t current_atom,
resizable_array<Ring *> & rings,
resizable_array<atom_number_t> & active_rings,
int * already_done)
{
assert(0 == already_done[current_atom]);
assert(rings.number_elements() == active_rings.number_elements());
already_done[current_atom] = 1;
//cerr << "GBORETN: processing atom " << current_atom << ", ncon " << _things[current_atom]->ncon() << endl;
const Atom * c = _things[current_atom];
int acon = c->ncon();
if (0 == acon)
return rings.number_elements();
Set_of_Atoms to_process;
to_process.resize(acon);
for (int i = 0; i < acon; i++)
{
const atom_number_t j = c->other(current_atom, i);
if (previous_atom == j)
continue;
if (already_done[j])
{
// cerr << "From atom " << current_atom << " found new ring to atom " << j << endl;
Ring * tmp = new Ring;
tmp->resize(6);
tmp->add(j);
tmp->add(current_atom);
rings.add(tmp);
tmp->set_fragment_membership(_fragment_information.fragment_membership(current_atom));
active_rings.add(j);
}
else
to_process.add(j);
}
// Recursively call this function for each bond attached to CURRENT_ATOM
acon = to_process.number_elements();
for (int i = 0; i < acon; i++)
{
const atom_number_t j = to_process[i]; // c->other(current_atom, i);
if (already_done[j])
continue;
const int rstart = rings.number_elements();
(void) _find_raw_rings(current_atom, j, rings, active_rings, already_done);
const int nrings_now = rings.number_elements();
// cerr << "Looking from " << current_atom << " to " << j << " now have " << nrings_now << " rings, compare " << rstart << endl;
if (rstart == nrings_now) // no new rings found down this bond
continue;
// Count the number of new rings down this bond, and try to determine
// any existing fusion specifications. Note that we may find different
// fused sys identifiers in the list of new rings. These numbers must
// all be consolidated, as they now are known to belong to the same
// fused system,
int number_new_rings = 0;
int fused_system_identifier = -99;
// cerr << "Current = " << current_atom << " to " << j <<
// " now " << rings.number_elements() << " rings\n";
resizable_array<int> fused_sys_ids_to_be_changed;
for (int k = rstart; k < nrings_now; k++)
{
if (INVALID_ATOM_NUMBER == active_rings[k]) // ring has been processed
continue;
number_new_rings++;
Ring * r = rings[k];
if (! r->is_fused()) // not interested in isolated rings
continue;
int rsysid = r->fused_system_identifier();
if (fused_system_identifier < 0) // first fused ring found here
fused_system_identifier = rsysid;
else if (rsysid == fused_system_identifier) // already has same id, no change
;
else // different systems need to be merged
fused_sys_ids_to_be_changed.add(rsysid);
// if (r->is_fused())
// cerr << "FBLOGD current = " << current_atom << " con = " << i << " atom " << j <<
// " k = " << k << " found fused sys identifier " << r->fused_system_identifier() <<
// " to " << active_rings[k] << endl;
}
if (0 == number_new_rings)
continue;
if (-99 == fused_system_identifier)
fused_system_identifier = current_atom;
else
_merge_fused_system_identifiers(rings, rstart, fused_system_identifier, fused_sys_ids_to_be_changed);
// cerr << "Will assign fused system identifier " << fused_system_identifier << endl;
for (int k = rstart; k < nrings_now; k++)
{
if (INVALID_ATOM_NUMBER == active_rings[k])
continue;
Ring * r = rings[k];
if (number_new_rings > 1)
{
r->set_fused_system_identifier(fused_system_identifier);
r->set_is_fused(1);
}
if (active_rings[k] == current_atom) // ring is complete, terminate it
active_rings[k] = INVALID_ATOM_NUMBER;
else
r->add(current_atom);
}
}
assert(rings.number_elements() == active_rings.number_elements());
return rings.number_elements();
}
//#define DEBUG_FIND_RAW_RINGS_FOR_FRAGMENT
/*
Process the raw rings for atoms with _fragment_membership == id
We need to be careful with systems with spiro fusions to ring systems,
C1CCCC2C1CC(C2)1OC(OC1)1OCCO1 3 spiro
for example. Since the spiro rings are not fused, we can correclty set
their final ring membership.
By default, we set the ring membership of fused systems to IW_RING_MEMBERSHIP_IS_A_RING_ATOM,
but that would overwrite the values correctly found for the spiro rings. So, if we have
the case of spiro rings joined to a ring system, force a complete SSSR
*/
int
Molecule::_find_raw_rings_for_fragment (int id, int * already_done)
{
if (0 == nrings())
return 1;
if (id < 0 || id >= _fragment_information.number_fragments())
{
cerr << "Molecule::_find_raw_rings_for_fragment:finding rings in fragment " << id << " but only " << _fragment_information.number_fragments() << " fragments\n";
debug_print(cerr);
assert(NULL == "This is very bad");
}
if (NULL == _ring_membership)
_initialise_ring_membership();
// Initialise all these atoms as 0 ring membership
int atoms_being_processed = 0;
atom_number_t start_atom = INVALID_ATOM_NUMBER; // first atom in the fragment
const int * fragment_membership = _fragment_information.fragment_membership();
for (int i = 0; i < _number_elements; i++)
{
if (id == fragment_membership[i])
{
_ring_membership[i] = 0;
atoms_being_processed++;
if (INVALID_ATOM_NUMBER == start_atom)
start_atom = i;
}
}
int nr = _fragment_information.rings_in_fragment(id);
assert(nr >= 0);
if (0 == nr) // no rings in this fragment
return 1;
assert(atoms_being_processed > 2);
resizable_array<Ring *> rings;
resizable_array<atom_number_t> active_rings;
active_rings.resize(nrings());
_find_raw_rings(INVALID_ATOM_NUMBER, start_atom, rings, active_rings, already_done);
nr = rings.number_elements();
assert(nr > 0);
#ifdef DEBUG_FIND_RAW_RINGS_FOR_FRAGMENT
cerr << "Found " << nr << " rings for fragment " << id << endl;
for (int i = 0; i < nr; i++)
{
cerr << "Ring " << i << " ";
const Ring * ri = rings[i];
cerr << (*ri) << endl;
if (! ok_ring(ri))
{
cerr << "Very bad news, not a valid ring\n";
iwabort();
}
}
#endif
// Update ring membership with the details
int number_fused_rings = 0;
for (int i = 0; i < nr; i++)
{
Ring * ri = rings[i];
if (ri->is_fused())
number_fused_rings++;
else
{
ri->increment_vector(_ring_membership, 1);
_add_ring_to_sssr(ri);
}
}
if (0 == number_fused_rings)
return _assign_fsid_values_to_isolated_rings();
assert(nr > 1); // can't be just one fused ring
// Accumulate the fused_system_identifiers of the fused systems that need to be processed with their attached spiro rings
resizable_array<int> spiro_between_isolated_and_fused;
if (number_fused_rings < nr) // must be both fused and isolated rings present - check for spiro fusions between them
{
for (int i = 0; i < nr; i++)
{
const Ring * ri = rings[i];
if (! ri->is_fused())
continue;
if (ri->fused_ring_check_for_spiro_fusion(_ring_membership))
spiro_between_isolated_and_fused.add_if_not_already_present(ri->fused_system_identifier());
}
}
#ifdef DEBUG_FIND_RAW_RINGS_FOR_FRAGMENT
cerr << "After examining rings, spiro between isolated and fused = " << spiro_between_isolated_and_fused.number_elements() << ", nr = " << nr << endl;
#endif
// Fused rings that are not bonded to a spiro ring to go raw rings
for (int i = 0; i < nr; i++)
{
Ring * ri = rings[i];
if (! ri->is_fused())
continue;
int fsid = ri->fused_system_identifier();
if (spiro_between_isolated_and_fused.contains(fsid))
continue;
ri->set_vector(_ring_membership, IW_RING_MEMBERSHIP_IS_A_RING_ATOM);
_raw_rings.add(ri);
// _experimental_raw_rings.add(ri);
}
if (spiro_between_isolated_and_fused.number_elements())
{
// cerr << "Spiro fusion to fused system\n";
for (int i = 0; i < spiro_between_isolated_and_fused.number_elements(); i++)
{
int fsid = spiro_between_isolated_and_fused[i];
_handle_spiro_between_isolated_and_fused(rings, fsid, already_done);
}
for (int i = 0; i < nr; i++)
{
Ring * ri = rings[i];
if (! ri->is_fused())
continue;
int fsid = ri->fused_system_identifier();
if (spiro_between_isolated_and_fused.contains(fsid))
delete ri;
}
}
return nr;
}
// Mar 2015. Assign non-negative fsid values to isolated rings
int
Molecule::_assign_fsid_values_to_isolated_rings()
{
int isolated_ring_fsid = _number_elements; // just some number that will be unique
const int nr = _sssr_rings.number_elements();
for (int i = 0; i < nr; ++i)
{
Ring * ri = _sssr_rings[i];
if (ri->fused_system_identifier() >= 0)
continue;
ri->set_fused_system_identifier(isolated_ring_fsid);
ri->set_is_fused(0);
isolated_ring_fsid--;
}
return nr;
}
/*
A new isolated ring has been found. Update the _ring_membership,
but only values greater than 0 - the others are undetermined yet.
Sept 97. Previously this set ring membership to 1 only if the
existing value of _ring_membership was zero. This failed in
the case of spiro fused rings, so now we check for >= 0 values
and always increment.
also tell the bonds about the new ring
*/
#ifdef IS_THIS_BEING_CALLED_NO
int
Molecule::_update_ring_membership (const Ring * r)
{
int ring_size = r->number_elements();
atom_number_t prev_atom = r->last_item();
for (int i = 0; i < ring_size; i++)
{
atom_number_t j = r->item(i);
cerr << "Molecule::_update_ring_membership: atom " << j << " rm = " << _ring_membership[j] << endl;
if (IW_RING_MEMBERSHIP_IS_A_RING_ATOM == _ring_membership[j]) // probably part of a fused system - spiro fusion
_ring_membership[j] = 1;
else if (_ring_membership[j] >= 0)
_ring_membership[j]++;
cerr << "Molecule::_update_ring_membership: atom " << j << " rm = " << _ring_membership[j] << endl;
const Atom * aj = _things[j];
Bond * b = const_cast<Bond *>(aj->bond_to_atom(prev_atom)); // loss of const OK
assert(b);
b->set_nrings(1);
prev_atom = j;
}
return 1;
}
#endif
int
Molecule::_find_raw_rings (int * already_done)
{
int nf = _fragment_information.number_fragments();
//cerr << "Finding raw rings for " << nf << " fragments\n";
for (int i = 0; i < nf; i++)
{
// cerr << "Finding raw rings for fragment " << i << endl;
if (! _find_raw_rings_for_fragment(i, already_done))
{
cerr << "Molecule::_find_raw_rings: Bad news, cannot get raw rings for fragment " << i << endl;
debug_print(cerr);
iwabort();
}
}
return _raw_rings.number_elements();
}
int
Molecule::_find_raw_rings()
{
assert(0 == _raw_rings.number_elements());
(void) number_fragments();
if (0 == nrings())
return 1;
int * tmp = new_int(_number_elements); std::unique_ptr<int[]> free_tmp(tmp);
return _find_raw_rings(tmp);
}
int
smiles_error_message (const char * smiles,
int length_of_smiles,
int characters_processed,
const char * message)
{
if (! display_smiles_interpretation_error_messages())
return 1;
assert(message);
cerr << message << endl;
int smiles_chars_to_print = characters_processed + 10;
if (smiles_chars_to_print > length_of_smiles || smiles_chars_to_print > 80)
smiles_chars_to_print = length_of_smiles;
for (int i = 0; i < smiles_chars_to_print; i++)
{
cerr << smiles[i];
}
cerr << endl;
//cerr << " ";
for (int i = 0; i < characters_processed; i++)
cerr << ' ';
cerr << "^\n";
return 1;
}
void
Molecule::_add_ring_to_sssr (Ring * ri)
{
ri->set_ring_number(_sssr_rings.number_elements());
_sssr_rings.add(ri);
// _experimental_sssr_rings.add(ri);
// Update the bond ring membership
atom_number_t aprev = ri->last_item();
int ring_size = ri->number_elements();
for (int i = 0; i < ring_size; i++)
{
atom_number_t j = ri->item(i);
// _things[j]->in_another_ring();
Bond * b = const_cast<Bond *>(_things[j]->bond_to_atom(aprev));
b->in_another_ring();
aprev = j;
}
return;
}
//#define DEBUG_HANDLE_SPIRO_BETWEEN_ISOLATED_AND_FUSED
/*
Spiro fusions between isolated and fused systems are problematic. We force SSSR
determination of all the fused rings in the fragment
*/
int
Molecule::_handle_spiro_between_isolated_and_fused (const resizable_array<Ring *> & rings,
int fsid,
int * atmp)
{
set_vector(atmp, _number_elements, 0);
int nr = rings.number_elements();
#ifdef DEBUG_HANDLE_SPIRO_BETWEEN_ISOLATED_AND_FUSED
cerr << "Handling " << nr << " rings for possible spiro/fused systems, _sssr_rings.number_elements = " << _sssr_rings.number_elements() << endl;
#endif
for (int i = 0; i < nr; i++)
{
const Ring * ri = rings[i];
if (! ri->is_fused())
continue;
if (fsid != ri->fused_system_identifier())
continue;
ri->set_vector(atmp, 1);
}
return _pearlman_sssr(atmp, 1);
}
int
Molecule::_all_atoms_are_chain_atoms (const int * process_these_atoms)
{
for (int i = 0; i < _number_elements; i++)
{
if (0 == process_these_atoms[i])
continue;
if (is_ring_atom(i))
return 0;
}
return 1;
}
/*int
Molecule::_determine_ring_closure_bonds (const int * zorder,
const int * include_atom)
{
assert(NULL != include_atom);
int * already_done = new_int (_number_elements); std::unique_ptr<int[]> free_already_done (already_done);
int n = _smiles_start_atom.number_elements();
for (int i = 0; i < n; i++)
{
atom_number_t astart = _smiles_start_atom[i];
if (NULL == include_atom)
;
else if (include_atom[astart])
;
else
{
astart = _choose_highest_canonical_order_in_fragment (i, zorder, include_atom);
if (INVALID_ATOM_NUMBER == astart)
continue;
}
_determine_ring_closure_bonds (INVALID_ATOM_NUMBER, astart, zorder, include_atom, already_done);
}
return 1;
}*/
/*
We need to re-determine the ring closure bonds when dealing with a subset
The canonical order is already known
*/
/*int
Molecule::_determine_ring_closure_bonds (atom_number_t aprev,
atom_number_t zatom,
const int * zorder,
const int * include_atom,
int * already_done)
{
assert(NULL != include_atom); // subset only
already_done[zatom] = 1;
const Atom * a = _things[zatom];
int acon = a->ncon();
resizable_array<const Bond *> process_these_bonds;
int rc = 0;
for (int i = 0; i < acon; i++)
{
const Bond * b = a->item (i);
atom_number_t j = b->other (zatom);
if (aprev == j)
continue;
if (0 == include_atom[j])
continue;
if (already_done[j])
{
_ring_closure_bonds.add (zatom, j);
rc++;
}
else
{
insert_bond (zatom, zorder, process_these_bonds, b);
}
}
int n = process_these_bonds.number_elements();
for (int i = 0; i < n; i++)
{
const Bond * b = process_these_bonds[i];
atom_number_t j = b->other (zatom);
if (already_done[j])
continue;
rc += _determine_ring_closure_bonds (zatom, j, zorder, include_atom, already_done);
}
return rc;
}*/
/*
We are doing the smiles for a fragment, but there is a subset, and the molecule's default
_smiles_start_atom was not part of the subset. Find another suitable starting point
*/
atom_number_t
Molecule::_choose_highest_canonical_order_in_fragment (int f,
const int * zorder,
const int * include_atom) const
{
atom_number_t rc = INVALID_ATOM_NUMBER;
int z;
const int * fragment_membership = _fragment_information.fragment_membership();
for (int i = 0; i < _number_elements; i++)
{
if (0 == include_atom[i])
continue;
if (f != fragment_membership[i])
continue;
if (INVALID_ATOM_NUMBER == rc || z > zorder[i])
{
rc = i;
z = zorder[i];
}
}
return rc;
}
int
Smiles_Information::allocate_user_specified_atomic_smarts()
{
assert(NULL == _user_specified_atomic_smarts);
assert(_natoms > 0);
_user_specified_atomic_smarts = new IWString[_natoms];
assert(NULL != _user_specified_atomic_smarts);
return 1;
}
IWString &
Smiles_Information::user_specified_atomic_smarts(atom_number_t zatom)
{
return _user_specified_atomic_smarts[zatom];
}
const IWString &
Smiles_Information::user_specified_atomic_smarts(atom_number_t zatom) const
{
return _user_specified_atomic_smarts[zatom];
}
void
Smiles_Information::set_user_specified_atomic_smarts(atom_number_t zatom,
const IWString & s)
{
if (NULL != _user_specified_atomic_smarts)
;
else if (_natoms <= 0)
{
cerr << "Smiles_Information::set_user_specified_atomic_smarts:atom count unknown\n";
return;
}
else
_user_specified_atomic_smarts = new IWString[_natoms];
_user_specified_atomic_smarts[zatom] = s;
return;
}
IWString
Molecule::isotopically_labelled_smiles()
{
if (0 == _number_elements)
return (".");
int * isave = NULL;
for (int i = 0; i < _number_elements; i++)
{
int iso = _things[i]->isotope();
if (0 == iso)
{
_things[i]->set_isotope(i);
continue;
}
if (NULL == isave)
isave = new_int(_number_elements);
isave[i] = iso;
_things[i]->set_isotope(i);
}
Smiles_Information sminfo;
(void) number_fragments();
Atom_Chooser_Default acd;
if (! _build_smiles_ordering_fctr(acd, NULL, sminfo))
{
cerr << "Molecule::isotopically_labelled_smiles: cannot construct ordering\n";
_smiles_information.set_error();
return sminfo.smiles();
}
sminfo.set_smiles_order_type(DEFAULT_SMILES_ORDER_TYPE);
_construct_smiles(_fragment_information, sminfo, NULL);
if (NULL != isave)
{
for (int i = 0; i < _number_elements; i++)
{
_things[i]->set_isotope(isave[i]);
}
delete [] isave;
}
else
{
for (int i = 0; i < _number_elements; i++)
{
_things[i]->set_isotope(0);
}
}
return (sminfo.smiles());
}
const IWString &
Molecule::smiles_using_order (const int * user_specified_rank)
{
if (0 == _number_elements)
{
_smiles_information.make_empty();
return _smiles_information.smiles();
}
_smiles_information.invalidate();
(void) number_fragments();
_smiles_information.prepare_to_build_ordering(_number_elements);
_smiles_information.set_smiles_order_type(USER_SPECIFIED_SMILES_ORDER);
Atom_Chooser_Lowest_Rank aclr(user_specified_rank);
int rc = _build_smiles_ordering_fctr(aclr, NULL, _smiles_information);
if (0 == rc)
return _smiles_information.smiles();
_smiles_information.set_smiles_order_type(USER_SPECIFIED_SMILES_ORDER);
_construct_smiles(_fragment_information, _smiles_information, NULL);
return _smiles_information.smiles();
}
| 25.402049 | 192 | 0.655308 | [
"object"
] |
bae3f472d88f7965917b6aec9b481f9fa2380b0e | 1,547 | cc | C++ | benchmark/sized_deletes.cc | s-kanev/gperftools | 6af68f4cc7877deeae43dbe3510047d32f031153 | [
"BSD-3-Clause"
] | null | null | null | benchmark/sized_deletes.cc | s-kanev/gperftools | 6af68f4cc7877deeae43dbe3510047d32f031153 | [
"BSD-3-Clause"
] | null | null | null | benchmark/sized_deletes.cc | s-kanev/gperftools | 6af68f4cc7877deeae43dbe3510047d32f031153 | [
"BSD-3-Clause"
] | null | null | null | #include <cstdlib>
#include <cstdint>
#include <random>
#include <vector>
#include "run_benchmark.h"
#include "num_iterations.h"
// Structs of increasing sizes to enable the compiler to invoke sized delete.
struct size4 {
size4() {}
uint32_t elems[1];
};
struct size32 {
size32() {}
uint32_t elems[8];
};
struct size64 {
size64() {}
uint32_t elems[16];
};
struct size96 {
size96() {}
uint32_t elems[24];
};
struct size128 {
size128() {}
uint32_t elems[32];
};
struct size160 {
size160(){}
uint32_t elems[40];
};
struct size192 {
size192() {}
uint32_t elems[48];
};
struct size224 {
size224() {}
uint32_t elems[56];
};
struct size256 {
size256() {}
uint32_t elems[64];
};
static void bench_sized_deletes(long rep, long iterations, uintptr_t param)
{
for (; iterations>0; iterations-=1) {
size32 *p32 = new size32();
if (!p32) abort();
delete p32;
size64 *p64 = new size64();
if (!p64) abort();
delete p64;
size96 *p96 = new size96();
if (!p96) abort();
delete p96;
size128 *p128 = new size128();
if (!p128) abort();
delete p128;
size160 *p160 = new size160();
if (!p160) abort();
delete p160;
size192 *p192 = new size192();
if (!p192) abort();
delete p192;
size224 *p224 = new size224();
if (!p224) abort();
delete p224;
size256 *p256 = new size256();
if (!p256) abort();
delete p256;
}
}
int main(void) {
report_benchmark("bench_sized_deletes", bench_sized_deletes, NULL, 0);
return 0;
}
| 16.114583 | 77 | 0.613445 | [
"vector"
] |
baea1b3f1623375bb0c418136497e4b32fa85248 | 2,412 | cpp | C++ | src/core/src/op/util/fft_base.cpp | ryanloney/openvino-1 | 4e0a740eb3ee31062ba0df88fcf438564f67edb7 | [
"Apache-2.0"
] | 1 | 2022-02-26T17:33:44.000Z | 2022-02-26T17:33:44.000Z | src/core/src/op/util/fft_base.cpp | ryanloney/openvino-1 | 4e0a740eb3ee31062ba0df88fcf438564f67edb7 | [
"Apache-2.0"
] | 18 | 2022-01-21T08:42:58.000Z | 2022-03-28T13:21:31.000Z | src/core/src/op/util/fft_base.cpp | ryanloney/openvino-1 | 4e0a740eb3ee31062ba0df88fcf438564f67edb7 | [
"Apache-2.0"
] | 1 | 2020-12-13T22:16:54.000Z | 2020-12-13T22:16:54.000Z | // Copyright (C) 2018-2022 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "ngraph/op/util/fft_base.hpp"
#include <fft_base_shape_inference.hpp>
#include <ngraph/validation_util.hpp>
#include "itt.hpp"
#include "ngraph/attribute_visitor.hpp"
using namespace std;
BWDCMP_RTTI_DEFINITION(ov::op::util::FFTBase);
ov::op::util::FFTBase::FFTBase(const Output<Node>& data, const Output<Node>& axes) : Op({data, axes}) {}
ov::op::util::FFTBase::FFTBase(const Output<Node>& data, const Output<Node>& axes, const Output<Node>& signal_size)
: Op({data, axes, signal_size}) {}
bool ov::op::util::FFTBase::visit_attributes(AttributeVisitor& visitor) {
NGRAPH_OP_SCOPE(util_FFTBase_visit_attributes);
return true;
}
void ov::op::util::FFTBase::validate_and_infer_types() {
NGRAPH_OP_SCOPE(util_FFTBase_validate_and_infer_types);
size_t num_of_inputs = get_input_size();
NODE_VALIDATION_CHECK(this, num_of_inputs == 2 || num_of_inputs == 3, "FFT op must have 2 or 3 inputs.");
element::Type input_et = get_input_element_type(0);
NODE_VALIDATION_CHECK(this,
input_et == element::f32 || input_et == element::f16 || input_et == element::bf16,
"FFT op input element type must be f32, f16, or bf16");
element::Type axes_et = get_input_element_type(1);
NODE_VALIDATION_CHECK(this,
axes_et == element::i64 || axes_et == element::i32,
"FFT op axes element type must be i32 or i64");
if (num_of_inputs == 3) {
element::Type signal_size_et = get_input_element_type(2);
NODE_VALIDATION_CHECK(this,
signal_size_et == element::i64 || signal_size_et == element::i32,
"FFT op signal_size element type must be i32 or i64");
}
std::vector<ov::PartialShape> output_shapes = {ov::PartialShape()};
std::vector<ov::PartialShape> input_shapes;
const auto& data = get_input_partial_shape(0);
const auto& axes = get_input_partial_shape(1);
if (input_values().size() == 2) {
input_shapes = {data, axes};
} else {
const auto& signal_size = get_input_partial_shape(2);
input_shapes = {data, axes, signal_size};
}
shape_infer(this, input_shapes, output_shapes);
set_output_type(0, get_input_element_type(0), output_shapes[0]);
}
| 37.107692 | 115 | 0.660862 | [
"vector"
] |
baea62f10cbfc23ccabc7834a7584548645d8614 | 1,938 | hpp | C++ | include/seqan3/alphabet/composite/all.hpp | smehringer/seqan3 | 141677c2ca0d24771d53bf2c6bc784c1e10eff90 | [
"CC-BY-4.0",
"CC0-1.0"
] | 283 | 2017-03-14T23:43:33.000Z | 2022-03-28T02:30:02.000Z | include/seqan3/alphabet/composite/all.hpp | eaasna/seqan3 | 02d00cf9ac57b17469db44b52efe7cae25700b98 | [
"CC0-1.0",
"CC-BY-4.0"
] | 2,754 | 2017-03-21T18:39:02.000Z | 2022-03-31T13:26:15.000Z | include/seqan3/alphabet/composite/all.hpp | eaasna/seqan3 | 02d00cf9ac57b17469db44b52efe7cae25700b98 | [
"CC0-1.0",
"CC-BY-4.0"
] | 88 | 2017-03-20T12:43:42.000Z | 2022-03-17T08:56:13.000Z | // -----------------------------------------------------------------------------------------------------
// Copyright (c) 2006-2021, Knut Reinert & Freie Universität Berlin
// Copyright (c) 2016-2021, Knut Reinert & MPI für molekulare Genetik
// This file may be used, modified and/or redistributed under the terms of the 3-clause BSD-License
// shipped with this file and also available at: https://github.com/seqan/seqan3/blob/master/LICENSE.md
// -----------------------------------------------------------------------------------------------------
/*!\file
* \author Marcel Ehrhardt <marcel.ehrhardt AT fu-berlin.de>
* \brief Meta-header for the \link alphabet_composite Alphabet / Composite submodule \endlink.
*/
#pragma once
#include <seqan3/alphabet/composite/alphabet_tuple_base.hpp>
#include <seqan3/alphabet/composite/alphabet_variant.hpp>
#include <seqan3/alphabet/composite/semialphabet_any.hpp>
/*!\defgroup alphabet_composite Composite
* \brief Provides templates for combining existing alphabets into new alphabet types.
* \ingroup alphabet
* \see alphabet
*
* \details
*
* ### Introduction
*
* This module provides various class templates that allow you to combine existing alphabets into new ones. For example,
* you can add new characters to existing alphabets by using seqan3::alphabet_variant or combine alphabets with quality
* information by using seqan3::alphabet_tuple_base.
*
* We have currently three major composite alphabets:
* * seqan3::alphabet_tuple_base which can be used to create a std::tuple like object that still models
* seqan3::alphabet.
* * seqan3::alphabet_variant which roughly corresponds to the Union of the given types. It behaves similar to
* std::variant, but also models seqan3::alphabet.
* * seqan3::semialphabet_any which type erases other alphabets of the same size and allows again transformation to
* alphabets of the same size by copying the rank.
*/
| 49.692308 | 120 | 0.688338 | [
"object"
] |
baef9ab00f0fb2a5a0f481c9a7c620716c7efa59 | 49,502 | cxx | C++ | VolumeRendering/vtkVolumeTextureMapper3D.cxx | garyc618/GitTagBug | 0b1cdbf5a6f6b9b23fa03ff1d9f4a84953831864 | [
"BSD-3-Clause"
] | 1 | 2019-05-31T06:45:40.000Z | 2019-05-31T06:45:40.000Z | VolumeRendering/vtkVolumeTextureMapper3D.cxx | garyc618/GitTagBug | 0b1cdbf5a6f6b9b23fa03ff1d9f4a84953831864 | [
"BSD-3-Clause"
] | null | null | null | VolumeRendering/vtkVolumeTextureMapper3D.cxx | garyc618/GitTagBug | 0b1cdbf5a6f6b9b23fa03ff1d9f4a84953831864 | [
"BSD-3-Clause"
] | null | null | null | /*=========================================================================
Program: Visualization Toolkit
Module: vtkVolumeTextureMapper3D.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkVolumeTextureMapper3D.h"
#include "vtkCamera.h"
#include "vtkColorTransferFunction.h"
#include "vtkDataArray.h"
#include "vtkImageData.h"
#include "vtkMath.h"
#include "vtkMatrix4x4.h"
#include "vtkPiecewiseFunction.h"
#include "vtkPointData.h"
#include "vtkRenderer.h"
#include "vtkVolume.h"
#include "vtkVolumeProperty.h"
#include "vtkVolumeRenderingFactory.h"
vtkCxxRevisionMacro(vtkVolumeTextureMapper3D, "1.13");
//----------------------------------------------------------------------------
// Needed when we don't use the vtkStandardNewMacro.
vtkInstantiatorNewMacro(vtkVolumeTextureMapper3D);
//----------------------------------------------------------------------------
// This method moves the scalars from the input volume into volume1 (and
// possibly volume2) which are the 3D texture maps used for rendering.
//
// In the case where our volume is a power of two, the copy is done
// directly. If we need to resample, then trilinear interpolation is used.
//
// A shift/scale is applied to the input scalar value to produce an 8 bit
// value for the texture volume.
//
// When the input data is one component, the scalar value is placed in the
// second component of the two component volume1. The first component is
// filled in later with the gradient magnitude.
//
// When the input data is two component non-independent, the first component
// of the input data is placed in the first component of volume1, and the
// second component of the input data is placed in the third component of
// volume1. Volume1 has three components - the second is filled in later with
// the gradient magnitude.
//
// When the input data is four component non-independent, the first three
// components of the input data are placed in volume1 (which has three
// components), and the fourth component is placed in the second component
// of volume2. The first component of volume2 is later filled in with the
// gradient magnitude.
template <class T>
void vtkVolumeTextureMapper3DComputeScalars( T *dataPtr,
vtkVolumeTextureMapper3D *me,
float offset, float scale,
unsigned char *volume1,
unsigned char *volume2)
{
T *inPtr;
unsigned char *outPtr, *outPtr2;
int i, j, k;
int idx;
int inputDimensions[3];
double inputSpacing[3];
vtkImageData *input = me->GetInput();
input->GetDimensions( inputDimensions );
input->GetSpacing( inputSpacing );
int outputDimensions[3];
float outputSpacing[3];
me->GetVolumeDimensions( outputDimensions );
me->GetVolumeSpacing( outputSpacing );
int components = input->GetNumberOfScalarComponents();
double wx, wy, wz;
double fx, fy, fz;
int x, y, z;
double sampleRate[3];
sampleRate[0] = outputSpacing[0] / static_cast<double>(inputSpacing[0]);
sampleRate[1] = outputSpacing[1] / static_cast<double>(inputSpacing[1]);
sampleRate[2] = outputSpacing[2] / static_cast<double>(inputSpacing[2]);
// This is the case where no interpolation is needed
if ( inputDimensions[0] == outputDimensions[0] &&
inputDimensions[1] == outputDimensions[1] &&
inputDimensions[2] == outputDimensions[2] )
{
int size = outputDimensions[0] * outputDimensions[1] * outputDimensions[2];
inPtr = dataPtr;
if ( components == 1 )
{
outPtr = volume1;
if ( scale == 1.0 )
{
for ( i = 0; i < size; i++ )
{
idx = static_cast<int>(*(inPtr++) + offset);
*(outPtr++) = 0;
*(outPtr++) = idx;
}
}
else
{
for ( i = 0; i < size; i++ )
{
idx = static_cast<int>((*(inPtr++) + offset) * scale);
*(outPtr++) = 0;
*(outPtr++) = idx;
}
}
}
else if ( components == 2 )
{
outPtr = volume1;
if ( scale == 1.0 )
{
for ( i = 0; i < size; i++ )
{
idx = static_cast<int>(*(inPtr++) + offset);
*(outPtr++) = idx;
*(outPtr++) = 0;
idx = static_cast<int>(*(inPtr++) + offset);
*(outPtr++) = idx;
}
}
else
{
for ( i = 0; i < size; i++ )
{
idx = static_cast<int>((*(inPtr++) + offset) * scale);
*(outPtr++) = idx;
*(outPtr++) = 0;
idx = static_cast<int>((*(inPtr++) + offset) * scale);
*(outPtr++) = idx;
}
}
}
else if ( components == 4 )
{
outPtr = volume1;
outPtr2 = volume2;
if ( scale == 1.0 )
{
for ( i = 0; i < size; i++ )
{
idx = static_cast<int>(*(inPtr++) + offset);
*(outPtr++) = idx;
idx = static_cast<int>(*(inPtr++) + offset);
*(outPtr++) = idx;
idx = static_cast<int>(*(inPtr++) + offset);
*(outPtr++) = idx;
*(outPtr2++) = 0;
idx = static_cast<int>(*(inPtr++) + offset);
*(outPtr2++) = idx;
}
}
else
{
for ( i = 0; i < size; i++ )
{
idx = static_cast<int>((*(inPtr++) + offset) * scale);
*(outPtr++) = idx;
idx = static_cast<int>((*(inPtr++) + offset) * scale);
*(outPtr++) = idx;
idx = static_cast<int>((*(inPtr++) + offset) * scale);
*(outPtr++) = idx;
*(outPtr2++) = 0;
idx = static_cast<int>((*(inPtr++) + offset) * scale);
*(outPtr2++) = idx;
}
}
}
}
// The sizes are different and interpolation is required
else
{
outPtr = volume1;
outPtr2 = volume2;
for ( k = 0; k < outputDimensions[2]; k++ )
{
fz = k * sampleRate[2];
fz = (fz >= inputDimensions[2]-1)?(inputDimensions[2]-1.001):(fz);
z = vtkMath::Floor( fz );
wz = fz - z;
for ( j = 0; j < outputDimensions[1]; j++ )
{
fy = j * sampleRate[1];
fy = (fy >= inputDimensions[1]-1)?(inputDimensions[1]-1.001):(fy);
y = vtkMath::Floor( fy );
wy = fy - y;
for ( i = 0; i < outputDimensions[0]; i++ )
{
fx = i * sampleRate[0];
fx = (fx >= inputDimensions[0]-1)?(inputDimensions[0]-1.001):(fx);
x = vtkMath::Floor( fx );
wx = fx - x;
inPtr =
dataPtr + components * ( z*inputDimensions[0]*inputDimensions[1] +
y*inputDimensions[0] +
x );
if ( components == 1 )
{
float A, B, C, D, E, F, G, H;
A = static_cast<float>(*(inPtr));
B = static_cast<float>(*(inPtr+1));
C = static_cast<float>(*(inPtr+inputDimensions[0]));
D = static_cast<float>(*(inPtr+inputDimensions[0]+1));
E = static_cast<float>(*(inPtr+inputDimensions[0]*inputDimensions[1]));
F = static_cast<float>(*(inPtr+inputDimensions[0]*inputDimensions[1]+1));
G = static_cast<float>(*(inPtr+inputDimensions[0]*inputDimensions[1]+inputDimensions[0]));
H = static_cast<float>(*(inPtr+inputDimensions[0]*inputDimensions[1]+inputDimensions[0]+1));
float val =
(1.0-wx)*(1.0-wy)*(1.0-wz)*A +
( wx)*(1.0-wy)*(1.0-wz)*B +
(1.0-wx)*( wy)*(1.0-wz)*C +
( wx)*( wy)*(1.0-wz)*D +
(1.0-wx)*(1.0-wy)*( wz)*E +
( wx)*(1.0-wy)*( wz)*F +
(1.0-wx)*( wy)*( wz)*G +
( wx)*( wy)*( wz)*H;
idx = static_cast<int>((val + offset)*scale);
*(outPtr++) = 0;
*(outPtr++) = idx;
}
else if ( components == 2 )
{
float A1, B1, C1, D1, E1, F1, G1, H1;
float A2, B2, C2, D2, E2, F2, G2, H2;
A1 = static_cast<float>(*(inPtr));
A2 = static_cast<float>(*(inPtr+1));
B1 = static_cast<float>(*(inPtr+2));
B2 = static_cast<float>(*(inPtr+3));
C1 = static_cast<float>(*(inPtr+2*inputDimensions[0]));
C2 = static_cast<float>(*(inPtr+2*inputDimensions[0]+1));
D1 = static_cast<float>(*(inPtr+2*inputDimensions[0]+2));
D2 = static_cast<float>(*(inPtr+2*inputDimensions[0]+3));
E1 = static_cast<float>(*(inPtr+2*inputDimensions[0]*inputDimensions[1]));
E2 = static_cast<float>(*(inPtr+2*inputDimensions[0]*inputDimensions[1]+1));
F1 = static_cast<float>(*(inPtr+2*inputDimensions[0]*inputDimensions[1]+2));
F2 = static_cast<float>(*(inPtr+2*inputDimensions[0]*inputDimensions[1]+3));
G1 = static_cast<float>(*(inPtr+2*inputDimensions[0]*inputDimensions[1]+2*inputDimensions[0]));
G2 = static_cast<float>(*(inPtr+2*inputDimensions[0]*inputDimensions[1]+2*inputDimensions[0]+1));
H1 = static_cast<float>(*(inPtr+2*inputDimensions[0]*inputDimensions[1]+2*inputDimensions[0]+2));
H2 = static_cast<float>(*(inPtr+2*inputDimensions[0]*inputDimensions[1]+2*inputDimensions[0]+3));
float val1 =
(1.0-wx)*(1.0-wy)*(1.0-wz)*A1 +
( wx)*(1.0-wy)*(1.0-wz)*B1 +
(1.0-wx)*( wy)*(1.0-wz)*C1 +
( wx)*( wy)*(1.0-wz)*D1 +
(1.0-wx)*(1.0-wy)*( wz)*E1 +
( wx)*(1.0-wy)*( wz)*F1 +
(1.0-wx)*( wy)*( wz)*G1 +
( wx)*( wy)*( wz)*H1;
float val2 =
(1.0-wx)*(1.0-wy)*(1.0-wz)*A2 +
( wx)*(1.0-wy)*(1.0-wz)*B2 +
(1.0-wx)*( wy)*(1.0-wz)*C2 +
( wx)*( wy)*(1.0-wz)*D2 +
(1.0-wx)*(1.0-wy)*( wz)*E2 +
( wx)*(1.0-wy)*( wz)*F2 +
(1.0-wx)*( wy)*( wz)*G2 +
( wx)*( wy)*( wz)*H2;
idx = static_cast<int>((val1 + offset) * scale);
*(outPtr++) = idx;
*(outPtr++) = 0;
idx = static_cast<int>((val2 + offset) * scale);
*(outPtr++) = idx;
}
else
{
float Ar, Br, Cr, Dr, Er, Fr, Gr, Hr;
float Ag, Bg, Cg, Dg, Eg, Fg, Gg, Hg;
float Ab, Bb, Cb, Db, Eb, Fb, Gb, Hb;
float Aa, Ba, Ca, Da, Ea, Fa, Ga, Ha;
Ar = static_cast<float>(*(inPtr));
Ag = static_cast<float>(*(inPtr+1));
Ab = static_cast<float>(*(inPtr+2));
Aa = static_cast<float>(*(inPtr+3));
Br = static_cast<float>(*(inPtr+4));
Bg = static_cast<float>(*(inPtr+5));
Bb = static_cast<float>(*(inPtr+6));
Ba = static_cast<float>(*(inPtr+7));
Cr = static_cast<float>(*(inPtr+4*inputDimensions[0]));
Cg = static_cast<float>(*(inPtr+4*inputDimensions[0]+1));
Cb = static_cast<float>(*(inPtr+4*inputDimensions[0]+2));
Ca = static_cast<float>(*(inPtr+4*inputDimensions[0]+3));
Dr = static_cast<float>(*(inPtr+4*inputDimensions[0]+4));
Dg = static_cast<float>(*(inPtr+4*inputDimensions[0]+5));
Db = static_cast<float>(*(inPtr+4*inputDimensions[0]+6));
Da = static_cast<float>(*(inPtr+4*inputDimensions[0]+7));
Er = static_cast<float>(*(inPtr+4*inputDimensions[0]*inputDimensions[1]));
Eg = static_cast<float>(*(inPtr+4*inputDimensions[0]*inputDimensions[1]+1));
Eb = static_cast<float>(*(inPtr+4*inputDimensions[0]*inputDimensions[1]+2));
Ea = static_cast<float>(*(inPtr+4*inputDimensions[0]*inputDimensions[1]+3));
Fr = static_cast<float>(*(inPtr+4*inputDimensions[0]*inputDimensions[1]+4));
Fg = static_cast<float>(*(inPtr+4*inputDimensions[0]*inputDimensions[1]+5));
Fb = static_cast<float>(*(inPtr+4*inputDimensions[0]*inputDimensions[1]+6));
Fa = static_cast<float>(*(inPtr+4*inputDimensions[0]*inputDimensions[1]+7));
Gr = static_cast<float>(*(inPtr+4*inputDimensions[0]*inputDimensions[1]+4*inputDimensions[0]));
Gg = static_cast<float>(*(inPtr+4*inputDimensions[0]*inputDimensions[1]+4*inputDimensions[0]+1));
Gb = static_cast<float>(*(inPtr+4*inputDimensions[0]*inputDimensions[1]+4*inputDimensions[0]+2));
Ga = static_cast<float>(*(inPtr+4*inputDimensions[0]*inputDimensions[1]+4*inputDimensions[0]+3));
Hr = static_cast<float>(*(inPtr+4*inputDimensions[0]*inputDimensions[1]+4*inputDimensions[0]+4));
Hg = static_cast<float>(*(inPtr+4*inputDimensions[0]*inputDimensions[1]+4*inputDimensions[0]+5));
Hb = static_cast<float>(*(inPtr+4*inputDimensions[0]*inputDimensions[1]+4*inputDimensions[0]+6));
Ha = static_cast<float>(*(inPtr+4*inputDimensions[0]*inputDimensions[1]+4*inputDimensions[0]+7));
float valr =
(1.0-wx)*(1.0-wy)*(1.0-wz)*Ar +
( wx)*(1.0-wy)*(1.0-wz)*Br +
(1.0-wx)*( wy)*(1.0-wz)*Cr +
( wx)*( wy)*(1.0-wz)*Dr +
(1.0-wx)*(1.0-wy)*( wz)*Er +
( wx)*(1.0-wy)*( wz)*Fr +
(1.0-wx)*( wy)*( wz)*Gr +
( wx)*( wy)*( wz)*Hr;
float valg =
(1.0-wx)*(1.0-wy)*(1.0-wz)*Ag +
( wx)*(1.0-wy)*(1.0-wz)*Bg +
(1.0-wx)*( wy)*(1.0-wz)*Cg +
( wx)*( wy)*(1.0-wz)*Dg +
(1.0-wx)*(1.0-wy)*( wz)*Eg +
( wx)*(1.0-wy)*( wz)*Fg +
(1.0-wx)*( wy)*( wz)*Gg +
( wx)*( wy)*( wz)*Hg;
float valb =
(1.0-wx)*(1.0-wy)*(1.0-wz)*Ab +
( wx)*(1.0-wy)*(1.0-wz)*Bb +
(1.0-wx)*( wy)*(1.0-wz)*Cb +
( wx)*( wy)*(1.0-wz)*Db +
(1.0-wx)*(1.0-wy)*( wz)*Eb +
( wx)*(1.0-wy)*( wz)*Fb +
(1.0-wx)*( wy)*( wz)*Gb +
( wx)*( wy)*( wz)*Hb;
float vala =
(1.0-wx)*(1.0-wy)*(1.0-wz)*Aa +
( wx)*(1.0-wy)*(1.0-wz)*Ba +
(1.0-wx)*( wy)*(1.0-wz)*Ca +
( wx)*( wy)*(1.0-wz)*Da +
(1.0-wx)*(1.0-wy)*( wz)*Ea +
( wx)*(1.0-wy)*( wz)*Fa +
(1.0-wx)*( wy)*( wz)*Ga +
( wx)*( wy)*( wz)*Ha;
idx = static_cast<int>((valr + offset) * scale);
*(outPtr++) = idx;
idx = static_cast<int>((valg + offset) * scale);
*(outPtr++) = idx;
idx = static_cast<int>((valb + offset) * scale);
*(outPtr++) = idx;
*(outPtr2++) = 0;
idx = static_cast<int>((vala + offset) * scale);
*(outPtr2++) = idx;
}
}
}
}
}
}
//-----------------------------------------------------------------------------
template <class T>
void vtkVolumeTextureMapper3DComputeGradients( T *dataPtr,
vtkVolumeTextureMapper3D *me,
double scalarRange[2],
unsigned char *volume1,
unsigned char *volume2,
unsigned char *volume3)
{
int x, y, z;
int offset, outputOffset;
int x_start, x_limit;
int y_start, y_limit;
int z_start, z_limit;
T *dptr;
double n[3], t;
double gvalue;
double zeroNormalThreshold;
int xlow, xhigh;
double aspect[3];
unsigned char *outPtr1, *outPtr2;
unsigned char *normals, *gradmags;
int gradmagIncrement;
int gradmagOffset;
double floc[3];
int loc[3];
// me->InvokeEvent( vtkEvent::VolumeMapperComputeGradientsStartEvent, NULL );
float outputSpacing[3];
me->GetVolumeSpacing( outputSpacing );
double spacing[3];
vtkImageData *input = me->GetInput();
input->GetSpacing( spacing );
double sampleRate[3];
sampleRate[0] = outputSpacing[0] / static_cast<double>(spacing[0]);
sampleRate[1] = outputSpacing[1] / static_cast<double>(spacing[1]);
sampleRate[2] = outputSpacing[2] / static_cast<double>(spacing[2]);
int components = input->GetNumberOfScalarComponents();
int dim[3];
input->GetDimensions(dim);
int outputDim[3];
me->GetVolumeDimensions( outputDim );
double avgSpacing = (spacing[0] + spacing[1] + spacing[2]) / 3.0;
// adjust the aspect
aspect[0] = spacing[0] * 2.0 / avgSpacing;
aspect[1] = spacing[1] * 2.0 / avgSpacing;
aspect[2] = spacing[2] * 2.0 / avgSpacing;
double scale = 255.0 / (0.25*(scalarRange[1] - scalarRange[0]));
// Get the length at or below which normals are considered to
// be "zero"
zeroNormalThreshold =.001 * (scalarRange[1] - scalarRange[0]);
int thread_id = 0;
int thread_count = 1;
x_start = 0;
x_limit = outputDim[0];
y_start = 0;
y_limit = outputDim[1];
z_start = static_cast<int>(( thread_id / static_cast<float>(thread_count) ) *
outputDim[2] );
z_limit = static_cast<int>(( (thread_id + 1) / static_cast<float>(thread_count) ) *
outputDim[2] );
// Do final error checking on limits - make sure they are all within bounds
// of the scalar input
x_start = (x_start<0)?(0):(x_start);
y_start = (y_start<0)?(0):(y_start);
z_start = (z_start<0)?(0):(z_start);
x_limit = (x_limit>dim[0])?(outputDim[0]):(x_limit);
y_limit = (y_limit>dim[1])?(outputDim[1]):(y_limit);
z_limit = (z_limit>dim[2])?(outputDim[2]):(z_limit);
if ( components == 1 || components == 2 )
{
normals = volume2;
gradmags = volume1;
gradmagIncrement = components+1;
gradmagOffset = components-1;
}
else
{
normals = volume3;
gradmags = volume2;
gradmagIncrement = 2;
gradmagOffset = 0;
}
double wx, wy, wz;
// Loop through all the data and compute the encoded normal and
// gradient magnitude for each scalar location
for ( z = z_start; z < z_limit; z++ )
{
floc[2] = z*sampleRate[2];
floc[2] = (floc[2]>=(dim[2]-1))?(dim[2]-1.001):(floc[2]);
loc[2] = vtkMath::Floor(floc[2]);
wz = floc[2] - loc[2];
for ( y = y_start; y < y_limit; y++ )
{
floc[1] = y*sampleRate[1];
floc[1] = (floc[1]>=(dim[1]-1))?(dim[1]-1.001):(floc[1]);
loc[1] = vtkMath::Floor(floc[1]);
wy = floc[1] - loc[1];
xlow = x_start;
xhigh = x_limit;
outputOffset = z * outputDim[0] * outputDim[1] + y * outputDim[0] + xlow;
// Set some pointers
outPtr1 = gradmags + gradmagIncrement*outputOffset;
outPtr2 = normals + 3*outputOffset;
for ( x = xlow; x < xhigh; x++ )
{
floc[0] = x*sampleRate[0];
floc[0] = (floc[0]>=(dim[0]-1))?(dim[0]-1.001):(floc[0]);
loc[0] = vtkMath::Floor(floc[0]);
wx = floc[0] - loc[0];
offset = loc[2] * dim[0] * dim[1] + loc[1] * dim[0] + loc[0];
dptr = dataPtr + components*offset + components - 1;
// Use a central difference method if possible,
// otherwise use a forward or backward difference if
// we are on the edge
int sampleOffset[6];
sampleOffset[0] = (loc[0]<1) ?(0):(-components);
sampleOffset[1] = (loc[0]>=dim[0]-2)?(0):( components);
sampleOffset[2] = (loc[1]<1) ?(0):(-components*dim[0]);
sampleOffset[3] = (loc[1]>=dim[1]-2)?(0):( components*dim[0]);
sampleOffset[4] = (loc[2]<1) ?(0):(-components*dim[0]*dim[1]);
sampleOffset[5] = (loc[2]>=dim[2]-2)?(0):( components*dim[0]*dim[1]);
float sample[6];
for ( int i = 0; i < 6; i++ )
{
float A, B, C, D, E, F, G, H;
T *samplePtr = dptr + sampleOffset[i];
A = static_cast<float>(*(samplePtr));
B = static_cast<float>(*(samplePtr+components));
C = static_cast<float>(*(samplePtr+components*dim[0]));
D = static_cast<float>(*(samplePtr+components*dim[0]+components));
E = static_cast<float>(*(samplePtr+components*dim[0]*dim[1]));
F = static_cast<float>(*(samplePtr+components*dim[0]*dim[1]+components));
G = static_cast<float>(*(samplePtr+components*dim[0]*dim[1]+components*dim[0]));
H = static_cast<float>(*(samplePtr+components*dim[0]*dim[1]+components*dim[0]+components));
sample[i] =
(1.0-wx)*(1.0-wy)*(1.0-wz)*A +
( wx)*(1.0-wy)*(1.0-wz)*B +
(1.0-wx)*( wy)*(1.0-wz)*C +
( wx)*( wy)*(1.0-wz)*D +
(1.0-wx)*(1.0-wy)*( wz)*E +
( wx)*(1.0-wy)*( wz)*F +
(1.0-wx)*( wy)*( wz)*G +
( wx)*( wy)*( wz)*H;
}
n[0] = ((sampleOffset[0]==0 || sampleOffset[1]==0)?(2.0):(1.0))*(sample[0] -sample[1]);
n[1] = ((sampleOffset[2]==0 || sampleOffset[3]==0)?(2.0):(1.0))*(sample[2] -sample[3]);
n[2] = ((sampleOffset[4]==0 || sampleOffset[5]==0)?(2.0):(1.0))*(sample[4] -sample[5]);
// Take care of the aspect ratio of the data
// Scaling in the vtkVolume is isotropic, so this is the
// only place we have to worry about non-isotropic scaling.
n[0] /= aspect[0];
n[1] /= aspect[1];
n[2] /= aspect[2];
// Compute the gradient magnitude
t = sqrt( n[0]*n[0] + n[1]*n[1] + n[2]*n[2] );
// Encode this into an 4 bit value
gvalue = t * scale;
gvalue = (gvalue<0.0)?(0.0):(gvalue);
gvalue = (gvalue>255.0)?(255.0):(gvalue);
*(outPtr1+gradmagOffset) = static_cast<unsigned char>(gvalue + 0.5);
// Normalize the gradient direction
if ( t > zeroNormalThreshold )
{
n[0] /= t;
n[1] /= t;
n[2] /= t;
}
else
{
n[0] = n[1] = n[2] = 0.0;
}
int nx = static_cast<int>((n[0] / 2.0 + 0.5)*255.0 + 0.5);
int ny = static_cast<int>((n[1] / 2.0 + 0.5)*255.0 + 0.5);
int nz = static_cast<int>((n[2] / 2.0 + 0.5)*255.0 + 0.5);
nx = (nx<0)?(0):(nx);
ny = (ny<0)?(0):(ny);
nz = (nz<0)?(0):(nz);
nx = (nx>255)?(255):(nx);
ny = (ny>255)?(255):(ny);
nz = (nz>255)?(255):(nz);
*(outPtr2 ) = nx;
*(outPtr2+1) = ny;
*(outPtr2+2) = nz;
outPtr1 += gradmagIncrement;
outPtr2 += 3;
}
}
// if ( z%8 == 7 )
// {
// float args[1];
// args[0] =
// static_cast<float>(z - z_start) /
// static_cast<float>(z_limit - z_start - 1);
// me->InvokeEvent( vtkEvent::VolumeMapperComputeGradientsProgressEvent, args );
// }
}
// me->InvokeEvent( vtkEvent::VolumeMapperComputeGradientsEndEvent, NULL );
}
//-----------------------------------------------------------------------------
vtkVolumeTextureMapper3D::vtkVolumeTextureMapper3D()
{
this->PolygonBuffer = NULL;
this->IntersectionBuffer = NULL;
this->NumberOfPolygons = 0;
this->BufferSize = 0;
// The input used when creating the textures
this->SavedTextureInput = NULL;
// The input used when creating the color tables
this->SavedParametersInput = NULL;
this->SavedRGBFunction = NULL;
this->SavedGrayFunction = NULL;
this->SavedScalarOpacityFunction = NULL;
this->SavedGradientOpacityFunction = NULL;
this->SavedColorChannels = 0;
this->SavedSampleDistance = 0;
this->SavedScalarOpacityDistance = 0;
this->Volume1 = NULL;
this->Volume2 = NULL;
this->Volume3 = NULL;
this->VolumeSize = 0;
this->VolumeComponents = 0;
this->VolumeSpacing[0] = this->VolumeSpacing[1] = this->VolumeSpacing[2] = 0;
this->SampleDistance = 1.0;
this->ActualSampleDistance = 1.0;
this->RenderMethod = vtkVolumeTextureMapper3D::NO_METHOD;
this->PreferredRenderMethod = vtkVolumeTextureMapper3D::FRAGMENT_PROGRAM_METHOD;
}
//-----------------------------------------------------------------------------
vtkVolumeTextureMapper3D::~vtkVolumeTextureMapper3D()
{
delete [] this->PolygonBuffer;
delete [] this->IntersectionBuffer;
delete [] this->Volume1;
delete [] this->Volume2;
delete [] this->Volume3;
}
//-----------------------------------------------------------------------------
vtkVolumeTextureMapper3D *vtkVolumeTextureMapper3D::New()
{
// First try to create the object from the vtkObjectFactory
vtkObject* ret =
vtkVolumeRenderingFactory::CreateInstance("vtkVolumeTextureMapper3D");
return static_cast<vtkVolumeTextureMapper3D *>(ret);
}
//-----------------------------------------------------------------------------
void vtkVolumeTextureMapper3D::ComputePolygons( vtkRenderer *ren,
vtkVolume *vol,
double inBounds[6] )
{
// Get the camera position and focal point
double focalPoint[4], position[4];
double plane[4];
vtkCamera *camera = ren->GetActiveCamera();
camera->GetPosition( position );
camera->GetFocalPoint( focalPoint );
position[3] = 1.0;
focalPoint[3] = 1.0;
// Pass the focal point and position through the inverse of the
// volume's matrix to map back into the data coordinates. We
// are going to compute these polygons in the coordinate system
// of the input data - this is easiest since this data must be
// axis aligned. Then we'll use OpenGL to transform these polygons
// into the world coordinate system through the use of the
// volume's matrix.
vtkMatrix4x4 *matrix = vtkMatrix4x4::New();
vol->GetMatrix( matrix );
matrix->Invert();
matrix->MultiplyPoint( position, position );
matrix->MultiplyPoint( focalPoint, focalPoint );
matrix->Delete();
if ( position[3] )
{
position[0] /= position[3];
position[1] /= position[3];
position[2] /= position[3];
}
if ( focalPoint[3] )
{
focalPoint[0] /= focalPoint[3];
focalPoint[1] /= focalPoint[3];
focalPoint[2] /= focalPoint[3];
}
// Create a plane equation using the direction and position of the camera
plane[0] = focalPoint[0] - position[0];
plane[1] = focalPoint[1] - position[1];
plane[2] = focalPoint[2] - position[2];
vtkMath::Normalize( plane );
plane[3] = -(plane[0] * position[0] + plane[1] * position[1] +
plane[2] * position[2]);
// Find the min and max distances of the boundary points of the volume
double minDistance = VTK_DOUBLE_MAX;
double maxDistance = VTK_DOUBLE_MIN;
// The inBounds parameter is the bounds we are using for clipping the
// texture planes against. First we need to clip these against the bounds
// of the volume to make sure they don't exceed it.
double volBounds[6];
this->GetInput()->GetBounds( volBounds );
double bounds[6];
bounds[0] = (inBounds[0]>volBounds[0])?(inBounds[0]):(volBounds[0]);
bounds[1] = (inBounds[1]<volBounds[1])?(inBounds[1]):(volBounds[1]);
bounds[2] = (inBounds[2]>volBounds[2])?(inBounds[2]):(volBounds[2]);
bounds[3] = (inBounds[3]<volBounds[3])?(inBounds[3]):(volBounds[3]);
bounds[4] = (inBounds[4]>volBounds[4])?(inBounds[4]):(volBounds[4]);
bounds[5] = (inBounds[5]<volBounds[5])?(inBounds[5]):(volBounds[5]);
// Create 8 vertices for the bounding box we are rendering
int i, j, k;
double vertices[8][3];
int idx = 0;
for ( k = 0; k < 2; k++ )
{
for ( j = 0; j < 2; j++ )
{
for ( i = 0; i < 2; i++ )
{
vertices[idx][2] = bounds[4+k];
vertices[idx][1] = bounds[2+j];
vertices[idx][0] = bounds[i];
double d =
plane[0] * vertices[idx][0] +
plane[1] * vertices[idx][1] +
plane[2] * vertices[idx][2] +
plane[3];
idx++;
// Keep track of closest and farthest point
minDistance = (d<minDistance)?(d):(minDistance);
maxDistance = (d>maxDistance)?(d):(maxDistance);
}
}
}
int dim[6];
this->GetVolumeDimensions(dim);
float tCoordOffset[3], tCoordScale[3];
tCoordOffset[0] = 0.5 / dim[0];
tCoordOffset[1] = 0.5 / dim[1];
tCoordOffset[2] = 0.5 / dim[2];
tCoordScale[0] = (dim[0]-1) / static_cast<float>(dim[0]);
tCoordScale[1] = (dim[1]-1) / static_cast<float>(dim[1]);
tCoordScale[2] = (dim[2]-1) / static_cast<float>(dim[2]);
float spacing[3];
this->GetVolumeSpacing( spacing );
double offset =
0.333 * 0.5 * (spacing[0] + spacing[1] + spacing[2]);
minDistance += 0.1*offset;
maxDistance -= 0.1*offset;
minDistance = (minDistance < offset)?(offset):(minDistance);
double stepSize = this->ActualSampleDistance;
// Determine the number of polygons
int numPolys = static_cast<int>(
(maxDistance - minDistance)/static_cast<double>(stepSize));
// Check if we have space, free old space only if it is too small
if ( this->BufferSize < numPolys )
{
delete [] this->PolygonBuffer;
delete [] this->IntersectionBuffer;
this->BufferSize = numPolys;
this->PolygonBuffer = new float [36*this->BufferSize];
this->IntersectionBuffer = new float [12*this->BufferSize];
}
this->NumberOfPolygons = numPolys;
// Compute the intersection points for each edge of the volume
int lines[12][2] = { {0,1}, {1,3}, {2,3}, {0,2},
{4,5}, {5,7}, {6,7}, {4,6},
{0,4}, {1,5}, {3,7}, {2,6} };
float *iptr, *pptr;
for ( i = 0; i < 12; i++ )
{
double line[3];
line[0] = vertices[lines[i][1]][0] - vertices[lines[i][0]][0];
line[1] = vertices[lines[i][1]][1] - vertices[lines[i][0]][1];
line[2] = vertices[lines[i][1]][2] - vertices[lines[i][0]][2];
double d = maxDistance;
iptr = this->IntersectionBuffer + i;
double planeDotLineOrigin = vtkMath::Dot( plane, vertices[lines[i][0]] );
double planeDotLine = vtkMath::Dot( plane, line );
double t, increment;
if ( planeDotLine != 0.0 )
{
t = (d - planeDotLineOrigin - plane[3] ) / planeDotLine;
increment = -stepSize / planeDotLine;
}
else
{
t = -1.0;
increment = 0.0;
}
for ( j = 0; j < numPolys; j++ )
{
*iptr = (t > 0.0 && t < 1.0)?(t):(-1.0);
t += increment;
iptr += 12;
}
}
// Compute the polygons by determining which edges were intersected
int neighborLines[12][6] =
{ { 1, 2, 3, 4, 8, 9}, { 0, 2, 3, 5, 9, 10},
{ 0, 1, 3, 6, 10, 11}, { 0, 1, 2, 7, 8, 11},
{ 0, 5, 6, 7, 8, 9}, { 1, 4, 6, 7, 9, 10},
{ 2, 4, 5, 7, 10, 11}, { 3, 4, 5, 6, 8, 11},
{ 0, 3, 4, 7, 9, 11}, { 0, 1, 4, 5, 8, 10},
{ 1, 2, 5, 6, 9, 11}, { 2, 3, 6, 7, 8, 10} };
float tCoord[12][4] =
{{0,0,0,0}, {1,0,0,1}, {0,1,0,0}, {0,0,0,1},
{0,0,1,0}, {1,0,1,1}, {0,1,1,0}, {0,0,1,1},
{0,0,0,2}, {1,0,0,2}, {1,1,0,2}, {0,1,0,2}};
double low[3];
double high[3];
low[0] = (bounds[0] - volBounds[0]) / (volBounds[1] - volBounds[0]);
high[0] = (bounds[1] - volBounds[0]) / (volBounds[1] - volBounds[0]);
low[1] = (bounds[2] - volBounds[2]) / (volBounds[3] - volBounds[2]);
high[1] = (bounds[3] - volBounds[2]) / (volBounds[3] - volBounds[2]);
low[2] = (bounds[4] - volBounds[4]) / (volBounds[5] - volBounds[4]);
high[2] = (bounds[5] - volBounds[4]) / (volBounds[5] - volBounds[4]);
for ( i = 0; i < 12; i++ )
{
tCoord[i][0] = (tCoord[i][0])?(high[0]):(low[0]);
tCoord[i][1] = (tCoord[i][1])?(high[1]):(low[1]);
tCoord[i][2] = (tCoord[i][2])?(high[2]):(low[2]);
}
iptr = this->IntersectionBuffer;
pptr = this->PolygonBuffer;
for ( i = 0; i < numPolys; i++ )
{
// Look for a starting point
int start = 0;
while ( start < 12 && iptr[start] == -1.0 )
{
start++;
}
if ( start == 12 )
{
pptr[0] = -1.0;
}
else
{
int current = start;
int previous = -1;
int errFlag = 0;
idx = 0;
while ( idx < 6 && !errFlag && ( idx == 0 || current != start) )
{
double t = iptr[current];
*(pptr + idx*6) =
tCoord[current][0] * tCoordScale[0] + tCoordOffset[0];
*(pptr + idx*6 + 1) =
tCoord[current][1] * tCoordScale[1] + tCoordOffset[1];
*(pptr + idx*6 + 2) =
tCoord[current][2] * tCoordScale[2] + tCoordOffset[2];
int coord = static_cast<int>(tCoord[current][3]);
*(pptr + idx*6 + coord) =
(low[coord] + t*(high[coord]-low[coord]))*tCoordScale[coord] + tCoordOffset[coord];
*(pptr + idx*6 + 3) = static_cast<float>(
vertices[lines[current][0]][0] +
t*(vertices[lines[current][1]][0] - vertices[lines[current][0]][0]));
*(pptr + idx*6 + 4) = static_cast<float>(
vertices[lines[current][0]][1] +
t*(vertices[lines[current][1]][1] - vertices[lines[current][0]][1]));
*(pptr + idx*6 + 5) = static_cast<float>(
vertices[lines[current][0]][2] +
t*(vertices[lines[current][1]][2] - vertices[lines[current][0]][2]));
idx++;
j = 0;
while ( j < 6 &&
(*(this->IntersectionBuffer + i*12 +
neighborLines[current][j]) < 0 ||
neighborLines[current][j] == previous) )
{
j++;
}
if ( j >= 6 )
{
errFlag = 1;
}
else
{
previous = current;
current = neighborLines[current][j];
}
}
if ( idx < 6 )
{
*(pptr + idx*6) = -1;
}
}
iptr += 12;
pptr += 36;
}
}
//-----------------------------------------------------------------------------
int vtkVolumeTextureMapper3D::UpdateVolumes(vtkVolume *vtkNotUsed(vol))
{
int needToUpdate = 0;
// Get the image data
vtkImageData *input = this->GetInput();
input->Update();
// Has the volume changed in some way?
if ( this->SavedTextureInput != input ||
this->SavedTextureMTime.GetMTime() < input->GetMTime() )
{
needToUpdate = 1;
}
if ( !needToUpdate )
{
return 0;
}
this->SavedTextureInput = input;
this->SavedTextureMTime.Modified();
// How big does the Volume need to be?
int dim[3];
input->GetDimensions(dim);
int powerOfTwoDim[3];
for ( int i = 0; i < 3; i++ )
{
powerOfTwoDim[i] = 32;
while ( powerOfTwoDim[i] < dim[i] )
{
powerOfTwoDim[i] *= 2;
}
}
while ( ! this->IsTextureSizeSupported( powerOfTwoDim ) )
{
if ( powerOfTwoDim[0] >= powerOfTwoDim[1] &&
powerOfTwoDim[0] >= powerOfTwoDim[2] )
{
powerOfTwoDim[0] /= 2;
}
else if ( powerOfTwoDim[1] >= powerOfTwoDim[0] &&
powerOfTwoDim[1] >= powerOfTwoDim[2] )
{
powerOfTwoDim[1] /= 2;
}
else
{
powerOfTwoDim[2] /= 2;
}
}
int neededSize = powerOfTwoDim[0] * powerOfTwoDim[1] * powerOfTwoDim[2];
int components = input->GetNumberOfScalarComponents();
// What is the spacing?
double spacing[3];
input->GetSpacing(spacing);
// Is it the right size? If not, allocate it.
if ( this->VolumeSize != neededSize ||
this->VolumeComponents != components )
{
delete [] this->Volume1;
delete [] this->Volume2;
delete [] this->Volume3;
switch (components)
{
case 1:
this->Volume1 = new unsigned char [2*neededSize];
this->Volume2 = new unsigned char [3*neededSize];
this->Volume3 = NULL;
break;
case 2:
this->Volume1 = new unsigned char [3*neededSize];
this->Volume2 = new unsigned char [3*neededSize];
this->Volume3 = NULL;
break;
case 3:
case 4:
this->Volume1 = new unsigned char [3*neededSize];
this->Volume2 = new unsigned char [2*neededSize];
this->Volume3 = new unsigned char [3*neededSize];
break;
}
this->VolumeSize = neededSize;
this->VolumeComponents = components;
}
// Find the scalar range
double scalarRange[2];
input->GetPointData()->GetScalars()->GetRange(scalarRange, components-1);
// Is the difference between max and min less than 4096? If so, and if
// the data is not of float or double type, use a simple offset mapping.
// If the difference between max and min is 4096 or greater, or the data
// is of type float or double, we must use an offset / scaling mapping.
// In this case, the array size will be 4096 - we need to figure out the
// offset and scale factor.
float offset;
float scale;
int arraySizeNeeded;
int scalarType = input->GetScalarType();
if ( scalarType == VTK_FLOAT ||
scalarType == VTK_DOUBLE ||
scalarRange[1] - scalarRange[0] > 255 )
{
arraySizeNeeded = 256;
offset = -scalarRange[0];
scale = 255.0 / (scalarRange[1] - scalarRange[0]);
}
else
{
arraySizeNeeded = static_cast<int>(scalarRange[1] - scalarRange[0] + 1);
offset = -scalarRange[0];
scale = 1.0;
}
this->ColorTableSize = arraySizeNeeded;
this->ColorTableOffset = offset;
this->ColorTableScale = scale;
// Save the volume size
this->VolumeDimensions[0] = powerOfTwoDim[0];
this->VolumeDimensions[1] = powerOfTwoDim[1];
this->VolumeDimensions[2] = powerOfTwoDim[2];
// Compute the new spacing
this->VolumeSpacing[0] =
(dim[0]-1.01)*spacing[0] / static_cast<double>(this->VolumeDimensions[0]-1);
this->VolumeSpacing[1] =
(dim[1]-1.01)*spacing[1] / static_cast<double>(this->VolumeDimensions[1]-1);
this->VolumeSpacing[2] =
((dim[2])-1.01)*spacing[2] / static_cast<double>(this->VolumeDimensions[2]-1);
// Transfer the input volume to the RGBA volume
void *dataPtr = input->GetScalarPointer();
switch ( scalarType )
{
vtkTemplateMacro(
vtkVolumeTextureMapper3DComputeScalars(
static_cast<VTK_TT *>(dataPtr), this,
offset, scale,
this->Volume1,
this->Volume2));
}
switch ( scalarType )
{
vtkTemplateMacro(
vtkVolumeTextureMapper3DComputeGradients(
static_cast<VTK_TT *>(dataPtr), this,
scalarRange,
this->Volume1,
this->Volume2,
this->Volume3));
}
return 1;
}
//-----------------------------------------------------------------------------
int vtkVolumeTextureMapper3D::UpdateColorLookup( vtkVolume *vol )
{
int needToUpdate = 0;
// Get the image data
vtkImageData *input = this->GetInput();
input->Update();
// Has the volume changed in some way?
if ( this->SavedParametersInput != input ||
this->SavedParametersMTime.GetMTime() < input->GetMTime() )
{
needToUpdate = 1;
}
// What sample distance are we going to use for rendering? If we
// have to render quickly according to our allocated render time,
// don't necessary obey the sample distance requested by the user.
// Instead set the sample distance to the average spacing.
this->ActualSampleDistance = this->SampleDistance;
if ( vol->GetAllocatedRenderTime() < 1.0 )
{
float spacing[3];
this->GetVolumeSpacing(spacing);
this->ActualSampleDistance =
0.333 * (static_cast<double>(spacing[0]) + static_cast<double>(spacing[1]) + static_cast<double>(spacing[2]));
}
// How many components?
int components = input->GetNumberOfScalarComponents();
// Has the sample distance changed?
if ( this->SavedSampleDistance != this->ActualSampleDistance )
{
needToUpdate = 1;
}
vtkColorTransferFunction *rgbFunc = NULL;
vtkPiecewiseFunction *grayFunc = NULL;
// How many color channels for this component?
int colorChannels = vol->GetProperty()->GetColorChannels(0);
if ( components < 3 )
{
// Has the number of color channels changed?
if ( this->SavedColorChannels != colorChannels )
{
needToUpdate = 1;
}
// Has the color transfer function changed in some way,
// and we are using it?
if ( colorChannels == 3 )
{
rgbFunc = vol->GetProperty()->GetRGBTransferFunction(0);
if ( this->SavedRGBFunction != rgbFunc ||
this->SavedParametersMTime.GetMTime() < rgbFunc->GetMTime() )
{
needToUpdate = 1;
}
}
// Has the gray transfer function changed in some way,
// and we are using it?
if ( colorChannels == 1 )
{
grayFunc = vol->GetProperty()->GetGrayTransferFunction(0);
if ( this->SavedGrayFunction != grayFunc ||
this->SavedParametersMTime.GetMTime() < grayFunc->GetMTime() )
{
needToUpdate = 1;
}
}
}
// Has the scalar opacity transfer function changed in some way?
vtkPiecewiseFunction *scalarOpacityFunc =
vol->GetProperty()->GetScalarOpacity(0);
if ( this->SavedScalarOpacityFunction != scalarOpacityFunc ||
this->SavedParametersMTime.GetMTime() <
scalarOpacityFunc->GetMTime() )
{
needToUpdate = 1;
}
// Has the gradient opacity transfer function changed in some way?
vtkPiecewiseFunction *gradientOpacityFunc =
vol->GetProperty()->GetGradientOpacity(0);
if ( this->SavedGradientOpacityFunction != gradientOpacityFunc ||
this->SavedParametersMTime.GetMTime() <
gradientOpacityFunc->GetMTime() )
{
needToUpdate = 1;
}
double scalarOpacityDistance =
vol->GetProperty()->GetScalarOpacityUnitDistance(0);
if ( this->SavedScalarOpacityDistance != scalarOpacityDistance )
{
needToUpdate = 1;
}
// If we have not found any need to update, return now
if ( !needToUpdate )
{
return 0;
}
this->SavedRGBFunction = rgbFunc;
this->SavedGrayFunction = grayFunc;
this->SavedScalarOpacityFunction = scalarOpacityFunc;
this->SavedGradientOpacityFunction = gradientOpacityFunc;
this->SavedColorChannels = colorChannels;
this->SavedSampleDistance = this->ActualSampleDistance;
this->SavedScalarOpacityDistance = scalarOpacityDistance;
this->SavedParametersInput = input;
this->SavedParametersMTime.Modified();
// Find the scalar range
double scalarRange[2];
input->GetPointData()->GetScalars()->GetRange(scalarRange, components-1);
int arraySizeNeeded = this->ColorTableSize;
if ( components < 3 )
{
// Sample the transfer functions between the min and max.
if ( colorChannels == 1 )
{
grayFunc->GetTable( scalarRange[0], scalarRange[1],
arraySizeNeeded, this->TempArray1 );
}
else
{
rgbFunc->GetTable( scalarRange[0], scalarRange[1],
arraySizeNeeded, this->TempArray1 );
}
}
scalarOpacityFunc->GetTable( scalarRange[0], scalarRange[1],
arraySizeNeeded, this->TempArray2 );
float goArray[256];
gradientOpacityFunc->GetTable( 0, (scalarRange[1] - scalarRange[0])*0.25,
256, goArray );
// Correct the opacity array for the spacing between the planes.
int i;
float *fptr2 = this->TempArray2;
double factor = this->ActualSampleDistance / scalarOpacityDistance;
for ( i = 0; i < arraySizeNeeded; i++ )
{
if ( *fptr2 > 0.0001 )
{
*fptr2 = 1.0-pow(static_cast<double>(1.0-(*fptr2)),factor);
}
fptr2++;
}
int goLoop;
unsigned char *ptr, *rgbptr, *aptr;
float *fptr1;
switch (components)
{
case 1:
// Move the two temp float arrays into one RGBA unsigned char array
ptr = this->ColorLookup;
for ( goLoop = 0; goLoop < 256; goLoop++ )
{
fptr1 = this->TempArray1;
fptr2 = this->TempArray2;
if ( colorChannels == 1 )
{
for ( i = 0; i < arraySizeNeeded; i++ )
{
*(ptr++) = static_cast<unsigned char>(*(fptr1)*255.0 + 0.5);
*(ptr++) = static_cast<unsigned char>(*(fptr1)*255.0 + 0.5);
*(ptr++) = static_cast<unsigned char>(*(fptr1++)*255.0 + 0.5);
*(ptr++) = static_cast<unsigned char>(*(fptr2++)*goArray[goLoop]*255.0 + 0.5);
}
}
else
{
for ( i = 0; i < arraySizeNeeded; i++ )
{
*(ptr++) = static_cast<unsigned char>(*(fptr1++)*255.0 + 0.5);
*(ptr++) = static_cast<unsigned char>(*(fptr1++)*255.0 + 0.5);
*(ptr++) = static_cast<unsigned char>(*(fptr1++)*255.0 + 0.5);
*(ptr++) = static_cast<unsigned char>(*(fptr2++)*goArray[goLoop]*255.0 + 0.5);
}
}
for ( ; i < 256; i++ )
{
*(ptr++) = 0;
*(ptr++) = 0;
*(ptr++) = 0;
*(ptr++) = 0;
}
}
break;
case 2:
// Move the two temp float arrays into one RGB unsigned char array and
// one alpha array.
rgbptr = this->ColorLookup;
aptr = this->AlphaLookup;
if ( colorChannels == 1 )
{
for ( i = 0; i < arraySizeNeeded; i++ )
{
fptr1 = this->TempArray1;
fptr2 = this->TempArray2;
for ( goLoop = 0; goLoop < 256; goLoop++ )
{
*(rgbptr++) = static_cast<unsigned char>(*(fptr1)*255.0 + 0.5);
*(rgbptr++) = static_cast<unsigned char>(*(fptr1)*255.0 + 0.5);
*(rgbptr++) = static_cast<unsigned char>(*(fptr1++)*255.0 + 0.5);
*(aptr++) = static_cast<unsigned char>(*(fptr2++)*goArray[goLoop]*255.0 + 0.5);
}
}
}
else
{
fptr1 = this->TempArray1;
fptr2 = this->TempArray2;
for ( i = 0; i < arraySizeNeeded; i++ )
{
for ( goLoop = 0; goLoop < 256; goLoop++ )
{
*(rgbptr++) = static_cast<unsigned char>(*(fptr1)*255.0 + 0.5);
*(rgbptr++) = static_cast<unsigned char>(*(fptr1+1)*255.0 + 0.5);
*(rgbptr++) = static_cast<unsigned char>(*(fptr1+2)*255.0 + 0.5);
*(aptr++) = static_cast<unsigned char>(*(fptr2)*goArray[goLoop]*255.0 + 0.5);
}
fptr1+=3;
fptr2++;
}
}
for ( ; i < 256; i++ )
{
for ( goLoop = 0; goLoop < 256; goLoop++ )
{
*(rgbptr++) = 0;
*(rgbptr++) = 0;
*(rgbptr++) = 0;
*(aptr++) = 0;
}
}
break;
case 3:
case 4:
// Move the two temp float arrays into one alpha array
aptr = this->AlphaLookup;
for ( goLoop = 0; goLoop < 256; goLoop++ )
{
fptr2 = this->TempArray2;
for ( i = 0; i < arraySizeNeeded; i++ )
{
*(aptr++) = static_cast<unsigned char>(*(fptr2++)*goArray[goLoop]*255.0 + 0.5);
}
for ( ; i < 256; i++ )
{
*(aptr++) = 0;
}
}
break;
}
return 1;
}
//-----------------------------------------------------------------------------
// Print the vtkVolumeTextureMapper3D
void vtkVolumeTextureMapper3D::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "Sample Distance: " << this->SampleDistance << endl;
os << indent << "Render Method: " << this->RenderMethod << endl;
os << indent << "Preferred Render Method: " << this->PreferredRenderMethod << endl;
os << indent << "NumberOfPolygons: " << this->NumberOfPolygons << endl;
os << indent << "ActualSampleDistance: "
<< this->ActualSampleDistance << endl;
os << indent << "VolumeDimensions: " << this->VolumeDimensions[0] << " "
<< this->VolumeDimensions[1] << " " << this->VolumeDimensions[2] << endl;
os << indent << "VolumeSpacing: " << this->VolumeSpacing[0] << " "
<< this->VolumeSpacing[1] << " " << this->VolumeSpacing[2] << endl;
}
| 33.379636 | 116 | 0.525938 | [
"render",
"object",
"transform",
"3d"
] |
baf3708c9cb9b4a5e05eea9b56192a0e3433525f | 2,156 | cpp | C++ | saga/impl/engine/context_base.cpp | saga-project/saga-cpp | 7376c0de0529e7d7b80cf08b94ec484c2e56d38e | [
"BSL-1.0"
] | 5 | 2015-09-15T16:24:14.000Z | 2021-08-12T11:05:55.000Z | saga/impl/engine/context_base.cpp | saga-project/saga-cpp | 7376c0de0529e7d7b80cf08b94ec484c2e56d38e | [
"BSL-1.0"
] | null | null | null | saga/impl/engine/context_base.cpp | saga-project/saga-cpp | 7376c0de0529e7d7b80cf08b94ec484c2e56d38e | [
"BSL-1.0"
] | 3 | 2016-11-17T04:38:38.000Z | 2021-04-10T17:23:52.000Z | // Copyright (c) 2005-2009 Hartmut Kaiser
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// job LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <saga/saga/util.hpp>
#include <saga/saga/base.hpp>
#include <saga/saga/adaptors/task.hpp>
#include <saga/saga/adaptors/instance_data.hpp>
#include <saga/saga/adaptors/context_cpi_instance_data.hpp>
#include <saga/impl/context_cpi.hpp>
#include <saga/impl/engine/context_base.hpp>
///////////////////////////////////////////////////////////////////////////////
namespace saga { namespace impl
{
context::context()
: proxy(saga::object::Context, saga::detail::get_the_session())
{
// initialize the instance data
typedef adaptors::v1_0::context_cpi_instance_data
instance_data_type;
typedef adaptors::instance_data <instance_data_type>
context_instance_data;
{
context_instance_data data;
data.init_data(this,
TR1::shared_ptr <instance_data_type>(new instance_data_type));
} // lock goes out of scope
}
context::context(attribute const& rhs_attr)
: saga::impl::proxy(saga::object::Context, saga::detail::get_the_session()),
attribute_base(rhs_attr)
{}
void context::init()
{
try {
// initialize a CPI instance and execute required functions
this->initcpi("context_cpi");
}
catch (saga::exception const& e) {
// map special exceptions
switch (e.get_error()) {
case saga::adaptors::AdaptorDeclined:
case saga::adaptors::NoAdaptor:
case saga::adaptors::NoAdaptorInfo:
case saga::adaptors::Unexpected:
SAGA_THROW_PLAIN(e.get_object(), e.what(), saga::NoSuccess);
// just rethrow otherwise
default:
throw;
}
}
}
// API function
SAGA_CALL_IMPL_IMPL_0(context, context_cpi, set_defaults)
///////////////////////////////////////////////////////////////////////////////
}}
| 32.179104 | 82 | 0.576067 | [
"object"
] |
baf99ffffba31849bfca3cd534df8a7a515dc498 | 2,572 | hpp | C++ | include/mfemopt/reducedfunctional.hpp | stefanozampini/petscopt | 73e4f9d50b1d216ff21d9322b5f83e8ca247ec24 | [
"BSD-2-Clause"
] | 9 | 2019-02-06T14:25:32.000Z | 2022-03-31T19:50:01.000Z | include/mfemopt/reducedfunctional.hpp | stefanozampini/petscopt | 73e4f9d50b1d216ff21d9322b5f83e8ca247ec24 | [
"BSD-2-Clause"
] | null | null | null | include/mfemopt/reducedfunctional.hpp | stefanozampini/petscopt | 73e4f9d50b1d216ff21d9322b5f83e8ca247ec24 | [
"BSD-2-Clause"
] | 1 | 2021-10-19T04:26:48.000Z | 2021-10-19T04:26:48.000Z | #if !defined(_MFEMOPT_REDUCEDFUNCTIONAL_HPP)
#define _MFEMOPT_REDUCEDFUNCTIONAL_HPP
#include <petscoptconf.h>
#if defined(PETSCOPT_HAVE_MFEMOPT)
#include <mfemoptconf.h>
#include <mfem/linalg/vector.hpp>
#include <mfem/linalg/handle.hpp>
#include <mfem/linalg/petsc.hpp>
namespace mfemopt
{
// Abstract class for functions of the type f : R^m -> R to be minimized
class ReducedFunctional : public mfem::Operator
{
private:
mutable bool objgradcalled; // prevent from recursion in default implementations
public:
ReducedFunctional() : objgradcalled(false) {}
/* this method is not pure since we can use ReducedFunctional in a PetscNonlinearSolver */
virtual void ComputeObjective(const mfem::Vector&,double*) const
{ mfem::mfem_error("ReducedFunctional::Compute not overloaded!"); }
virtual void ComputeGradient(const mfem::Vector&,mfem::Vector&) const;
virtual void ComputeObjectiveAndGradient(const mfem::Vector&,double*,mfem::Vector&) const;
virtual mfem::Operator& GetHessian(const mfem::Vector&) const
{
mfem::mfem_error("ReducedFunctional::GetHessian() is not overloaded!");
return const_cast<ReducedFunctional&>(*this);
}
virtual void ComputeGuess(mfem::Vector&) const;
virtual void GetBounds(mfem::Vector&,mfem::Vector&) const;
virtual void Init(const mfem::Vector&) {}
virtual void Update(int,const mfem::Vector&,const mfem::Vector&,const mfem::Vector&,const mfem::Vector&) {}
virtual void PostCheck(const mfem::Vector&,mfem::Vector&,mfem::Vector&,bool &cy,bool &cw) const
{ cy = false; cw = false; }
/* Default interface for mfem::Operator */
virtual void Mult(const mfem::Vector& x, mfem::Vector& y) const
{ ComputeGradient(x,y); }
virtual mfem::Operator& GetGradient(const mfem::Vector& m) const
{ return GetHessian(m); }
/* Testing */
void TestFDGradient(MPI_Comm,const mfem::Vector&,double,bool=true);
void TestFDHessian(MPI_Comm,const mfem::Vector&);
void TestTaylor(MPI_Comm,const mfem::Vector&,bool=false);
void TestTaylor(MPI_Comm,const mfem::Vector&,const mfem::Vector&,bool=false);
virtual ~ReducedFunctional() {}
};
// Abstract class for functions of the type f : R^m -> R to be minimized in an Hilbert space
class HilbertReducedFunctional : public ReducedFunctional
{
public:
virtual void Riesz(const mfem::Vector&, mfem::Vector&) const = 0;
virtual void Inner(const mfem::Vector&, const mfem::Vector&, double*) const = 0;
virtual mfem::Operator& GetOperatorNorm() const = 0;
virtual ~HilbertReducedFunctional() {}
};
}
#endif
#endif
| 36.742857 | 110 | 0.730171 | [
"vector"
] |
bafe749d1166f5316301cbff0fc2fd79ead9a3ec | 15,273 | hxx | C++ | Modules/Numerics/NeuralNetworks/include/itkRBFLayer.hxx | eile/ITK | 2f09e6e2f9e0a4a7269ac83c597f97b04f915dc1 | [
"Apache-2.0"
] | 1 | 2021-12-27T19:14:03.000Z | 2021-12-27T19:14:03.000Z | Modules/Numerics/NeuralNetworks/include/itkRBFLayer.hxx | eile/ITK | 2f09e6e2f9e0a4a7269ac83c597f97b04f915dc1 | [
"Apache-2.0"
] | 1 | 2016-12-03T05:33:13.000Z | 2016-12-03T05:33:13.000Z | Modules/Numerics/NeuralNetworks/include/itkRBFLayer.hxx | eile/ITK | 2f09e6e2f9e0a4a7269ac83c597f97b04f915dc1 | [
"Apache-2.0"
] | null | null | null | /*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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 __itkRBFLayer_hxx
#define __itkRBFLayer_hxx
#include "itkRBFLayer.h"
#include "itkGaussianRadialBasisFunction.h"
namespace itk
{
namespace Statistics
{
template<typename TMeasurementVector, typename TTargetVector>
RBFLayer<TMeasurementVector,TTargetVector>
::RBFLayer()
{
m_Bias = 1;
m_NumClasses = 0;
typedef GaussianRadialBasisFunction<ValueType> GRBFType;
m_RBF=GRBFType::New();
m_DistanceMetric = DistanceMetricType::New();
// TMeasurementVector origin;
// m_DistanceMetric->SetMeasurementVectorSize(origin.Size());
m_RBF_Dim = 0;
//
}
template<typename TMeasurementVector, typename TTargetVector>
RBFLayer<TMeasurementVector,TTargetVector>
::~RBFLayer()
{
}
template<typename TMeasurementVector, typename TTargetVector>
void
RBFLayer<TMeasurementVector,TTargetVector>
::SetRBF(RBFType* f)
{
m_RBF = f;
this->Modified();
}
template<typename TMeasurementVector, typename TTargetVector>
void
RBFLayer<TMeasurementVector,TTargetVector>
::SetRBF_Dim(unsigned int dim)
{
m_RBF_Dim=dim;
m_DistanceMetric->SetMeasurementVectorSize(m_RBF_Dim);
}
template<typename TMeasurementVector, typename TTargetVector>
void
RBFLayer<TMeasurementVector,TTargetVector>
::SetNumberOfNodes(unsigned int c)
{
//TMeasurementVector sampleinputvector;
//m_RBF_Dim= sampleinputvector.Size();
Superclass::SetNumberOfNodes(c);
this->m_NodeInputValues.set_size(m_RBF_Dim); //c);
this->m_NodeOutputValues.set_size(c);
m_InputErrorValues.set_size(c);
m_OutputErrorValues.set_size(c);
if(this->GetLayerTypeCode() != Self::OUTPUTLAYER)
{
//TMeasurementVector temp;
InternalVectorType temp(m_RBF_Dim);
for(unsigned int i=0; i<c; i++)
{
m_Centers.push_back(temp);
}
this->m_NodeOutputValues.set_size(c);
m_Radii.SetSize(c);
m_Radii.fill(1.0);
}
this->Modified();
}
template<typename TMeasurementVector, typename TTargetVector>
void
RBFLayer<TMeasurementVector,TTargetVector>
::SetInputValue(unsigned int i, ValueType value)
{
this->m_NodeInputValues[i] = value;
this->Modified();
}
template<typename TMeasurementVector, typename TTargetVector>
typename RBFLayer<TMeasurementVector,TTargetVector>::ValueType
RBFLayer<TMeasurementVector,TTargetVector>
::GetInputValue(unsigned int i) const
{
return m_NodeInputValues[i];
}
template<typename TMeasurementVector, typename TTargetVector>
void
RBFLayer<TMeasurementVector,TTargetVector>
::SetOutputValue(unsigned int i, ValueType value)
{
m_NodeOutputValues(i) = value;
this->Modified();
}
template<typename TMeasurementVector, typename TTargetVector>
typename RBFLayer<TMeasurementVector,TTargetVector>::ValueType
RBFLayer<TMeasurementVector,TTargetVector>
::GetOutputValue(unsigned int i) const
{
return m_NodeOutputValues(i);
}
template<typename TMeasurementVector, typename TTargetVector>
void
RBFLayer<TMeasurementVector,TTargetVector>
::SetOutputVector(TMeasurementVector value)
{
m_NodeOutputValues = value.GetVnlVector();
this->Modified();
}
template<typename TMeasurementVector, typename TTargetVector>
typename RBFLayer<TMeasurementVector,TTargetVector>::ValueType *
RBFLayer<TMeasurementVector,TTargetVector>
::GetOutputVector()
{
return m_NodeOutputValues.data_block();
}
template<typename TMeasurementVector, typename TTargetVector>
void
RBFLayer<TMeasurementVector,TTargetVector>
::SetRadii(ValueType c,unsigned int i)
{
m_Radii.SetElement(i,c);
this->Modified();
}
template<typename TMeasurementVector, typename TTargetVector>
typename RBFLayer<TMeasurementVector,TTargetVector>::ValueType
RBFLayer<TMeasurementVector,TTargetVector>
::GetRadii(unsigned int i) const
{
return m_Radii.GetElement(i);
}
template<typename TMeasurementVector, typename TTargetVector>
void
RBFLayer<TMeasurementVector,TTargetVector>
::SetCenter(TMeasurementVector c,unsigned int i)
{
InternalVectorType temp(c.Size());
for(unsigned int j=0; j<c.Size(); j++)
{
temp[j]=c[j];
}
m_Centers[i]=temp; //c;
this->Modified();
}
template<typename TMeasurementVector, typename TTargetVector>
typename RBFLayer<TMeasurementVector,TTargetVector>::InternalVectorType
RBFLayer<TMeasurementVector,TTargetVector>
::GetCenter(unsigned int i) const
{
if(m_Centers.size() != 0)
{
return m_Centers[i];
}
else
{
return 0;
}
}
template<typename TMeasurementVector, typename TTargetVector>
typename RBFLayer<TMeasurementVector,TTargetVector>::ValueType
RBFLayer<TMeasurementVector,TTargetVector>
::GetInputErrorValue(unsigned int n) const
{
return m_InputErrorValues[n];
}
template<typename TMeasurementVector, typename TTargetVector>
typename RBFLayer<TMeasurementVector,TTargetVector>::ValueType *
RBFLayer<TMeasurementVector,TTargetVector>
::GetInputErrorVector()
{
return m_InputErrorValues.data_block();
}
template<typename TMeasurementVector, typename TTargetVector>
void
RBFLayer<TMeasurementVector,TTargetVector>
::SetInputErrorValue(ValueType v, unsigned int i)
{
m_InputErrorValues[i] = v;
this->Modified();
}
template<typename TMeasurementVector, typename TTargetVector>
void
RBFLayer<TMeasurementVector,TTargetVector>
::ForwardPropagate()
{
typename WeightSetInterfaceType::Pointer inputweightset;
typename InputFunctionInterfaceType::Pointer inputfunction;
if(this->GetLayerTypeCode() == Self::OUTPUTLAYER)
{
typename TransferFunctionInterfaceType::Pointer transferfunction;
inputfunction = this->GetModifiableNodeInputFunction();
transferfunction = this->GetModifiableActivationFunction();
inputweightset = this->GetModifiableInputWeightSet();
ValueType * inputvalues = inputweightset->GetOutputValues();
const int rows = this->m_NumberOfNodes;
const int cols = this->m_InputWeightSet->GetNumberOfInputNodes();
vnl_matrix<ValueType> inputmatrix;
inputmatrix.set_size(rows, cols);
inputmatrix.copy_in(inputvalues);
inputfunction->SetSize(cols); //include bias
for (int j = 0; j < rows; j++)
{
vnl_vector<ValueType> temp_vnl;
temp_vnl.set_size(inputmatrix.cols());
temp_vnl=inputmatrix.get_row(j);
m_NodeInputValues.put(j, inputfunction->Evaluate(temp_vnl.data_block()));
m_NodeOutputValues.put(j, transferfunction->Evaluate(m_NodeInputValues[j]));
}
}
else
{
inputweightset = this->GetModifiableInputWeightSet();
inputfunction = this->GetModifiableNodeInputFunction();
vnl_vector<ValueType> temp;
ValueType * inputvalues = inputweightset->GetInputValues();
int cols = this->m_InputWeightSet->GetNumberOfInputNodes();
vnl_matrix<ValueType> inputmatrix;
inputmatrix.set_size(1, cols-1);
inputmatrix.copy_in(inputvalues);
inputfunction->SetSize(cols-1); //include bias
m_NodeInputValues = inputmatrix.get_row(0);
ValueType * cdeltavalues = inputweightset->GetTotalDeltaValues();
vnl_matrix<ValueType> center_increment(cdeltavalues,inputweightset->GetNumberOfOutputNodes(),
inputweightset->GetNumberOfInputNodes());
vnl_vector<ValueType> width_increment;
width_increment.set_size(inputweightset->GetNumberOfOutputNodes());
width_increment.fill(0);
width_increment= center_increment.get_column(inputweightset->GetNumberOfInputNodes()-1);
ValueType temp_radius;
InternalVectorType temp_center;
temp_center.SetSize(m_RBF_Dim);
//TMeasurementVector tempvector1;
//TMeasurementVector tempvector2;
//TMeasurementVector tempcenter;
InternalVectorType tempvector1(m_RBF_Dim);
InternalVectorType tempvector2(m_RBF_Dim);
InternalVectorType tempcenter(m_RBF_Dim);
for (unsigned int i = 0; i < m_NumClasses; i++)
{
tempcenter = m_Centers[i];
for(unsigned int j=0;j<m_RBF_Dim;j++)
{
ValueType val =tempcenter[j];
val += center_increment[i][j];
tempcenter[j]=val;
}
m_Centers[i]=tempcenter;
temp_radius = m_Radii.GetElement(i);
temp_radius += width_increment[i];
m_Radii.SetElement(i,temp_radius);
InternalVectorType array1(m_NodeInputValues.size());
array1= m_NodeInputValues;
for(unsigned int j=0; j<tempvector1.size(); j++)
tempvector1[j]=m_NodeInputValues[j];
//tempvector1.Set_vnl_vector(m_NodeInputValues);
tempvector2=m_Centers[i];
tempcenter= m_Centers[i];
//double dt= m_DistanceMetric->Evaluate(tempvector1,tempvector2);
//std::cout<<"Euclidean in layer ="<<dt<<std::endl;
m_RBF->SetRadius(m_Radii.GetElement(i));
InternalVectorType temp_array(m_RBF_Dim);
NodeVectorType temp_vector= m_Centers[i];
for(unsigned int ii=0; ii<m_RBF_Dim; ii++)
temp_array.SetElement(ii,temp_vector[ii]);
m_RBF->SetCenter(temp_array);
m_NodeOutputValues.put(i,m_RBF->Evaluate(m_DistanceMetric->Evaluate(tempvector1,tempvector2)));
}
}
}
template<typename TMeasurementVector, typename TTargetVector>
void
RBFLayer<TMeasurementVector,TTargetVector>
::SetDistanceMetric(DistanceMetricType* f)
{
m_DistanceMetric=f;
this->Modified();
}
template<typename TMeasurementVector, typename TTargetVector>
void
RBFLayer<TMeasurementVector,TTargetVector>
::ForwardPropagate(TMeasurementVector samplevector)
{
typename TransferFunctionInterfaceType::Pointer transferfunction = this->GetModifiableActivationFunction();
for (unsigned int i = 0; i < samplevector.Size(); i++)
{
samplevector[i] = transferfunction->Evaluate(samplevector[i]);
m_NodeOutputValues.put(i, samplevector[i]);
}
}
template<typename TMeasurementVector, typename TTargetVector>
void
RBFLayer<TMeasurementVector,TTargetVector>
::SetOutputErrorValues(TTargetVector errors)
{
for(unsigned int i=0; i<errors.Size(); i++)
m_OutputErrorValues[i] = errors[i];
this->Modified();
}
template<typename TMeasurementVector, typename TTargetVector>
typename RBFLayer<TMeasurementVector,TTargetVector>::ValueType
RBFLayer<TMeasurementVector,TTargetVector>
::GetOutputErrorValue(unsigned int i) const
{
return m_OutputErrorValues[i];
}
template<typename TMeasurementVector, typename TTargetVector>
void
RBFLayer<TMeasurementVector,TTargetVector>
::BackwardPropagate()
{
const unsigned int num_nodes = this->GetNumberOfNodes();
typename Superclass::WeightSetType::Pointer outputweightset = Superclass::GetModifiableOutputWeightSet();
typename Superclass::WeightSetType::Pointer inputweightset = Superclass::GetModifiableInputWeightSet();
vnl_vector<ValueType> OutputLayerInput(outputweightset->GetInputValues(),num_nodes);
ValueType * deltavalues = outputweightset->GetDeltaValues();
ValueType * weightvalues = outputweightset->GetWeightValues();
const unsigned int cols = num_nodes;
const unsigned int rows = outputweightset->GetNumberOfOutputNodes();
vnl_matrix<ValueType> weightmatrix(weightvalues, rows, cols);
vnl_matrix<ValueType> deltamatrix(deltavalues, rows, cols);
vnl_vector<ValueType> deltaww;
deltaww.set_size(cols);
deltaww.fill(0);
/*
TMeasurementVector tempvector1;
TMeasurementVector tempvector2;*/
InternalVectorType tempvector1(m_RBF_Dim);
InternalVectorType tempvector2(m_RBF_Dim);
for(unsigned int c1=0; c1<rows; c1++)
{
for(unsigned int c2=0; c2<cols; c2++)
{
deltamatrix[c1][c2]=deltamatrix[c1][c2]/OutputLayerInput[c2];
}
}
for (unsigned int i = 0; i < cols; i++)
{
deltaww[i] = dot_product(deltamatrix.get_column(i),
weightmatrix.get_column(i));
}
//compute gradient for centers
InternalVectorType array1(m_NodeInputValues.size());
array1= m_NodeInputValues;
vnl_matrix<ValueType> DW_temp(inputweightset->GetNumberOfOutputNodes(),
inputweightset->GetNumberOfInputNodes());
DW_temp.fill(0.0);
for(unsigned int k=0; k<array1.Size(); k++)
tempvector1[k]=array1[k];
for(unsigned int k=0; k<num_nodes; k++)
{
for (unsigned int i = 0; i < m_RBF_Dim; i++)
{
tempvector2=m_Centers[k];
double dist=m_DistanceMetric->Evaluate(tempvector1,tempvector2);
m_RBF->SetRadius(m_Radii.GetElement(k));
NodeVectorType temp_vector= m_Centers[k];
InternalVectorType temp_array(m_RBF_Dim);
for(unsigned int ii=0; ii<m_RBF_Dim; ii++)
temp_array.SetElement(ii,temp_vector[ii]);
m_RBF->SetCenter(temp_array);
DW_temp[k][i]=deltaww[k] * m_RBF->EvaluateDerivative
(dist,array1,'u',i);
}
}
//compute gradient for widths
NodeVectorType width_gradient;
width_gradient.set_size(num_nodes);
width_gradient.fill(0.0);
for (unsigned int i=0;i<num_nodes;i++)
{
tempvector2=m_Centers[i];
double dist=m_DistanceMetric->Evaluate(tempvector1,tempvector2);
width_gradient[i]=deltaww[i] * m_RBF->EvaluateDerivative
(dist,array1,'s');
}
inputweightset->SetDeltaValues(DW_temp.data_block());
inputweightset->SetDeltaBValues(width_gradient.data_block());
}
template<typename TMeasurementVector, typename TTargetVector>
typename RBFLayer<TMeasurementVector,TTargetVector>::ValueType
RBFLayer<TMeasurementVector,TTargetVector>
::Activation(ValueType n)
{
return this->m_ActivationFunction->Evaluate(n);
}
template<typename TMeasurementVector, typename TTargetVector>
typename RBFLayer<TMeasurementVector,TTargetVector>::ValueType
RBFLayer<TMeasurementVector,TTargetVector>
::DActivation(ValueType n)
{
return this->m_ActivationFunction->EvaluateDerivative(n);
}
/** Print the object */
template<typename TMeasurementVector, typename TTargetVector>
void
RBFLayer<TMeasurementVector,TTargetVector>
::PrintSelf( std::ostream& os, Indent indent ) const
{
os << indent << "RBFLayer(" << this << ")" << std::endl;
os << indent << "m_DistanceMetric = " << m_DistanceMetric << std::endl;
os << indent << "m_NodeInputValues = " << m_NodeInputValues << std::endl;
os << indent << "m_NodeOutputValues = " << m_NodeOutputValues << std::endl;
os << indent << "m_InputErrorValues = " << m_InputErrorValues << std::endl;
os << indent << "m_OutputErrorValues = " << m_OutputErrorValues << std::endl;
//os << indent << "m_Centers = " << m_Centers << std::endl;
os << indent << "m_Radii = " << m_Radii << std::endl;
os << indent << "m_Bias = " << m_Bias << std::endl;
os << indent << "m_RBF_Dim = " << m_RBF_Dim << std::endl;
os << indent << "m_RBF = " << m_RBF << std::endl;
Superclass::PrintSelf( os, indent );
}
} // end namespace Statistics
} // end namespace itk
#endif
| 31.105906 | 109 | 0.73463 | [
"object"
] |
bafe940ee55f199092a695cb794454c04a22c8c9 | 2,070 | cc | C++ | GMLib/modules/core/benchmarks/array.cc | MormonJesus69420/Virtual-Reality-Graphics-And-Animation-Project | 5cac3042d83f59ca5041247437ddc69afe3487c4 | [
"WTFPL"
] | 2 | 2019-08-04T09:41:42.000Z | 2022-03-08T02:13:00.000Z | GMLib/modules/core/benchmarks/array.cc | MormonJesus69420/Virtual-Reality-Graphics-And-Animation-Project | 5cac3042d83f59ca5041247437ddc69afe3487c4 | [
"WTFPL"
] | null | null | null | GMLib/modules/core/benchmarks/array.cc | MormonJesus69420/Virtual-Reality-Graphics-And-Animation-Project | 5cac3042d83f59ca5041247437ddc69afe3487c4 | [
"WTFPL"
] | null | null | null | #include <benchmark/benchmark.h>
#include <containers/gmarray.h>
using namespace GMlib;
#include <vector>
#include <limits>
#include <random>
#include <algorithm>
/*!
* \brief BM_ArrayAlwaysInsert
* Testing 'alwaysInsert's into an array of some size
*/
static void BM_Array_insertAlways_increasing(benchmark::State& state)
{
// Setup
Array<int> test_array(0);
// The test loop
while (state.KeepRunning())
for (int i = 0; i < state.range(0); ++i) test_array.insertAlways(i);
}
BENCHMARK(BM_Array_insertAlways_increasing)
->Unit(benchmark::kMillisecond)
->RangeMultiplier(2)
->Ranges({{1, 2 << 15}});
static void BM_Array_insertAlways_random(benchmark::State& state)
{
// Setup
Array<int> test_array(0);
std::default_random_engine generator;
std::uniform_int_distribution<int> distribution(
std::numeric_limits<int>::lowest(), std::numeric_limits<int>::max());
const auto no_values = size_t(state.range(0));
std::vector<int> values(no_values);
for (size_t i = 0; i < no_values; ++i) values.at(i) = distribution(generator);
// The test loop
while (state.KeepRunning())
for (size_t i = 0; i < no_values; ++i)
test_array.insertAlways(values.at(i));
}
BENCHMARK(BM_Array_insertAlways_random)
->Unit(benchmark::kMillisecond)
->RangeMultiplier(2)
->Ranges({{1, 2 << 15}});
static void BM_Array_sort(benchmark::State& state)
{
// Setup
Array<int> test_array(0);
test_array.setSorted(false);
std::default_random_engine generator;
std::uniform_int_distribution<int> distribution(
std::numeric_limits<int>::lowest(), std::numeric_limits<int>::max());
const auto no_values = size_t(state.range(0));
for (size_t i = 0; i < no_values; ++i)
test_array.insertAlways(distribution(generator));
// The test loop
while (state.KeepRunning()) test_array.sort();
}
BENCHMARK(BM_Array_sort)
->Unit(benchmark::kMillisecond)
->RangeMultiplier(2)
->Ranges({{1, 2 << 15}});
BENCHMARK_MAIN()
| 26.202532 | 81 | 0.668116 | [
"vector"
] |
24008e08a69f4e1c63fdc4c906b1586ef6ca144a | 18,135 | cpp | C++ | src/wpds/Tests/unit-tests/Source/AddOns/Domains/binrel/binrel.cpp | ucd-plse/mpi-error-prop | 4367df88bcdc4d82c9a65b181d0e639d04962503 | [
"BSD-3-Clause"
] | 3 | 2020-05-22T04:17:23.000Z | 2020-07-17T04:14:25.000Z | src/wpds/Tests/unit-tests/Source/AddOns/Domains/binrel/binrel.cpp | ucd-plse/mpi-error-prop | 4367df88bcdc4d82c9a65b181d0e639d04962503 | [
"BSD-3-Clause"
] | null | null | null | src/wpds/Tests/unit-tests/Source/AddOns/Domains/binrel/binrel.cpp | ucd-plse/mpi-error-prop | 4367df88bcdc4d82c9a65b181d0e639d04962503 | [
"BSD-3-Clause"
] | null | null | null | #include "gtest/gtest.h"
#include "buddy/bdd.h"
// ::std
#include <iostream>
#include <vector>
#include <utility>
#include <limits>
#include <sstream>
#include <string>
#include <cstdlib>
// ::wali::domains::binrel
#include "wali/domains/binrel/BinRel.hpp"
#include "wali/domains/binrel/ProgramBddContext.hpp"
using namespace std;
using namespace wali;
using namespace wali::domains::binrel;
#include "Common.cpp"
namespace{
TEST(BinRelSelfTest, copyTest){
ProgramBddContext ctx;
ctx.addBoolVar("a");
ProgramBddContext ctx2 = ctx;
}
TEST(BinRelSelfTest, repopulateCacheOnCopy){
ProgramBddContext ctx;
ctx.addBoolVar("a");
ProgramBddContext ctx2 = ctx;
sem_elem_t b = new BinRel(&ctx2, bddtrue);
// This should just not fail an exception is what I'm checking.
b->one()->extend(b);
}
TEST(BinRelSelfTest, repopulateCacheOnAssign){
ProgramBddContext ctx;
ctx.addBoolVar("a");
ProgramBddContext ctx2;
ctx2 = ctx;
sem_elem_t b = new BinRel(&ctx2, bddtrue);
// This should just not fail an exception is what I'm checking.
b->one()->extend(b);
}
TEST(BinRelSelfTest, creationTest){
program_bdd_context_t brm = new ProgramBddContext();
brm->addBoolVar("a");
brm->addBoolVar("b");
brm->addBoolVar("c");
brm->addBoolVar("d");
brm->addIntVar("p",4);
brm->addIntVar("q",4);
brm->addIntVar("r",4);
brm->addIntVar("s",4);
ASSERT_EQ(brm->size(), 8);
bdd a = brm->From("a");
bdd p = brm->From("p");
sem_elem_t se1 = new BinRel(brm.get_ptr(),a,false);
sem_elem_t se2 = new BinRel(brm.get_ptr(),p,false);
stringstream ss;
se1->print(ss << "se1: ") << endl;
se2->print(ss << "se2: ") << endl;
ASSERT_TRUE(compareOutput("BinRelSelfTest","creationTest",ss));
}
TEST(BinRelSelfTest, selfTest){
program_bdd_context_t brm = new ProgramBddContext();
brm->addBoolVar("a");
brm->addBoolVar("b");
brm->addIntVar("p",4);
bdd a = brm->From("a");
a = brm->Assign("b",a);
sem_elem_t se1 = new BinRel(brm.get_ptr(),a,false);
wali::test_semelem_impl(se1);
}
class BinRelTestBool: public ::testing::Test{
protected:
virtual void SetUp(){
brm = new ProgramBddContext();
brm->addBoolVar("a");
brm->addBoolVar("b");
brm->addBoolVar("c");
//ASSERT_EQ(voc.size(), 3);
}
protected:
program_bdd_context_t brm;
};
TEST_F(BinRelTestBool,constantTests){
stringstream ss;
sem_elem_t se = new BinRel(brm.get_ptr(),brm->False(),false);
se->one()->print(ss << "one(): ") << endl;
se->zero()->print(ss << "zero(): ") << endl;
EXPECT_TRUE(compareOutput("BinRelTestBool","constantTests",ss));
}
TEST_F(BinRelTestBool,extendTests){
stringstream ss;
bdd a;
a = brm->Assign("c", brm->And(brm->From("a"),brm->From("b")));
sem_elem_t se1 = new BinRel(brm.get_ptr(),a,false);
a = brm->Assume(brm->From("a"), brm->From("b"));
sem_elem_t se2 = new BinRel(brm.get_ptr(),a,false);
sem_elem_t one = se1->one();
sem_elem_t zero = se1->zero();
EXPECT_TRUE(zero->equal(zero->extend(se1)));
EXPECT_TRUE(se2->equal(se2->extend(one)));
se1->print(ss << "se1: ") << endl;
se2->print(ss << "se2: ") << endl;
se1->extend(se2)->print(ss << "se1->extend(se2): ") << endl;
se2->extend(se1)->print(ss << "se2->extend(se1): ") << endl;
EXPECT_TRUE(compareOutput("BinRelTestBool","extendTests",ss));
binrel_t be1,be2;
be1 = dynamic_cast<BinRel*>(se1.get_ptr());
be2 = dynamic_cast<BinRel*>(se2.get_ptr());
EXPECT_TRUE(se1->extend(se2.get_ptr())->equal((be1 * be2).get_ptr()));
EXPECT_TRUE(se2->extend(se1.get_ptr())->equal((be2 * be1).get_ptr()));
EXPECT_TRUE(compareOutput("BinRelTestBool","extendTests",ss));
}
TEST_F(BinRelTestBool,combineTests){
stringstream ss;
bdd a;
a = brm->Assign("c", brm->And(brm->From("a"),brm->From("b")));
sem_elem_t se1 = new BinRel(brm.get_ptr(),a,false);
a = brm->Assume(brm->From("a"), brm->From("b"));
sem_elem_t se2 = new BinRel(brm.get_ptr(),a,false);
sem_elem_t one = se1->one();
sem_elem_t zero = se1->zero();
EXPECT_TRUE(se1->equal(zero->combine(se1)));
EXPECT_TRUE(one->equal(one->combine(one)));
se1->print(ss << "se1: ") << endl;
se2->print(ss << "se2: ") << endl;
se1->combine(se2)->print(ss << "se1->combine(se2): ") << endl;
se2->combine(se1)->print(ss << "se2->combine(se1): ") << endl;
EXPECT_TRUE(compareOutput("BinRelTestBool","combineTests",ss));
binrel_t be1,be2;
be1 = dynamic_cast<BinRel*>(se1.get_ptr());
be2 = dynamic_cast<BinRel*>(se2.get_ptr());
EXPECT_TRUE(se1->combine(se2.get_ptr())->equal((be1 | be2).get_ptr()));
}
TEST_F(BinRelTestBool, transposeTests){
stringstream ss;
bdd a;
a = brm->Assign("c", brm->And(brm->From("a"),brm->From("b")));
sem_elem_tensor_t se1 = new BinRel(brm.get_ptr(),a,false);
a = brm->Assume(brm->From("a"), brm->From("b"));
sem_elem_tensor_t se2 = new BinRel(brm.get_ptr(),a,false);
se1->print(ss << "se1: ") << endl;
se1->transpose()->print(ss << "se1: ") << endl;
se2->print(ss << "se2: ") << endl;
se2->transpose()->print(ss << "se2: ") << endl;
EXPECT_TRUE(compareOutput("BinRelTestBool","transposeTests",ss));
}
TEST_F(BinRelTestBool, tensorTests){
brm = new ProgramBddContext();
brm->addBoolVar("a");
brm->addBoolVar("b");
//ASSERT_EQ(voc.size(), 2);
stringstream ss;
bdd a;
a = brm->Assume(brm->From("a"), brm->From("b"));
sem_elem_tensor_t se1 = new BinRel(brm.get_ptr(),a,false);
a = brm->Assume(brm->From("a"), brm->Not(brm->From("b")));
sem_elem_tensor_t se2 = new BinRel(brm.get_ptr(),a,false);
sem_elem_tensor_t se3 = se1->tensor(se2.get_ptr());
se1->print(ss << "se1: ") << endl;
se2->print(ss << "se2: ") << endl;
se3->print(ss << "se3: ") << endl;
EXPECT_TRUE(compareOutput("BinRelTestBool","tensorTests",ss));
}
TEST_F(BinRelTestBool, detensorTest){
stringstream ss;
bdd a;
a = brm->Assume(brm->From("a"), brm->From("b"));
sem_elem_tensor_t se1 = new BinRel(brm.get_ptr(),a,false);
a = brm->Assume(brm->From("b"), brm->From("c"));
sem_elem_tensor_t se2 = new BinRel(brm.get_ptr(),a,false);
sem_elem_tensor_t se3 = se1->tensor(se2.get_ptr());
sem_elem_tensor_t se4 = se3->detensor();
sem_elem_tensor_t se5 =
dynamic_cast<SemElemTensor*>(se1->extend(se2.get_ptr()).get_ptr());
se1->print(ss << "se1: ") << endl;
se2->print(ss << "se2: ") << endl;
se3->print(ss << "se3: ") << endl;
se4->print(ss << "se4: ") << endl;
se5->print(ss << "se5: ") << endl;
EXPECT_TRUE(compareOutput("BinRelTestBool","detensorTests",ss));
EXPECT_TRUE(se5->equal(se4.get_ptr()));
}
TEST_F(BinRelTestBool, detensorTransposeTest){
stringstream ss;
bdd a;
a = brm->Assign("a", brm->From("c"));
sem_elem_tensor_t se1 = new BinRel(brm.get_ptr(),a,false);
a = brm->Assume(brm->From("b"), brm->From("c"));
sem_elem_tensor_t se2 = new BinRel(brm.get_ptr(),a,false);
sem_elem_tensor_t se3 = se1->tensor(se2.get_ptr());
sem_elem_tensor_t se4 = se3->detensor();
sem_elem_tensor_t se5 =
dynamic_cast<SemElemTensor*>(se1->extend(se2.get_ptr()).get_ptr());
sem_elem_tensor_t se6 = se2->tensor(se1.get_ptr());
sem_elem_tensor_t se7 = se6->detensorTranspose();
sem_elem_tensor_t se8 =
dynamic_cast<SemElemTensor*>(se2->extend(se1.get_ptr()).get_ptr());
EXPECT_TRUE(se5->equal(se4.get_ptr()));
EXPECT_TRUE(se8->equal(se7.get_ptr()));
}
class BinRelTestInt: public ::testing::Test{
protected:
virtual void SetUp(){
brm = new ProgramBddContext();
brm->addIntVar("a",4);
brm->addIntVar("b",4);
brm->addIntVar("c",4);
//ASSERT_EQ(voc.size(), 3);
}
protected:
sem_elem_tensor_t screenVar(string var, sem_elem_tensor_t wt);
program_bdd_context_t brm;
};
sem_elem_tensor_t BinRelTestInt::screenVar(string var, sem_elem_tensor_t wt){
sem_elem_tensor_t screen = new BinRel(brm.get_ptr(),brm->Assume(brm->From(var),brm->Const(0)), false);
return dynamic_cast<SemElemTensor*>(wt->extend(screen.get_ptr()).get_ptr());
}
TEST_F(BinRelTestInt,testScreen){
stringstream ss;
sem_elem_tensor_t wt = new BinRel(brm.get_ptr(),brm->Const(0), false);
wt = dynamic_cast<SemElemTensor*>(wt->one().get_ptr());
wt->print(ss << "W[1]: ") << endl;
wt = screenVar("a",wt);
wt->print(ss << "W[1 & a==0]: ") << endl;
wt = screenVar("b",wt);
wt->print(ss << "W[1 && a==0 && b==0]: ") << endl;
wt = screenVar("c",wt);
wt->print(ss << "W[1 && a==0 && b==0 && c==0]: ") << endl;
EXPECT_TRUE(compareOutput("BinRelTestInt","testScreen",ss));
}
TEST(BinRelTestRandom, baseDomain){
// //Maybe this should be done in a more repeat-friendly way// //
stringstream ss;
bool failed = false, dump = false;
program_bdd_context_t brm = new ProgramBddContext();
brm->addIntVar( "a", 4);
brm->addBoolVar( "b");
brm->addIntVar( "c", 4);
brm->addBoolVar( "d");
//ASSERT_EQ(voc.size(),4);
srand((unsigned)time(NULL));
for(int h=0;h<20;++h){
bdd r1bdd = brm->tGetRandomTransformer();
bdd r2bdd = brm->tGetRandomTransformer();
bdd r3bdd = brm->tGetRandomTransformer();
sem_elem_t r1 = new BinRel(brm.get_ptr(),r1bdd,false);
sem_elem_t r2 = new BinRel(brm.get_ptr(),r2bdd,false);
sem_elem_t r3 = new BinRel(brm.get_ptr(),r3bdd,false);
sem_elem_t w1,w2,w3,w4,w5;
w1 = r1->combine(r2);
w2 = r2->combine(r1);
if(!w1->equal(w2) || dump){
ss << "#################################\nr1 | r2 <> r2 | r1\n\n";
r1->print(ss << "r1: ") << endl;
r2->print(ss << "r2: ") << endl;
w1->print(ss << "r1 | r2: ") << endl;
w2->print(ss << "r2 | r1: ") << endl;
failed = true;
}
w1 = (r1->extend(r2))->combine(r1->extend(r3));
w2 = r1->extend(r2->combine(r3));;
if(!w1->equal(w2) || dump){
ss << "#################################\nr1 & (r2 | r3) <> r1 & r2 | r1 & r3\n\n";
r1->print(ss << "r1: ") << endl;
r2->print(ss << "r2: ") << endl;
r3->print(ss << "r3: ") << endl;
w1->print(ss << "r1 & (r2 | r3): ") << endl;
w2->print(ss << "r1 & r2 | r1 & r3: ") << endl;
failed = true;
}
w1 = (r1->extend(r3))->combine(r2->extend(r3));
w2 = (r1->combine(r2))->extend(r3);
if(!w1->equal(w2) || dump){
ss << "#################################\n(r1 | r2 ) & r3 <> r1 & r3 | r2 & r3\n\n";
r1->print(ss << "r1: ") << endl;
r2->print(ss << "r2: ") << endl;
r3->print(ss << "r3: ") << endl;
w1->print(ss << "(r1 | r2) & r3: ") << endl;
w2->print(ss << "r1 & r3 | r2 & r3: ") << endl;
failed = true;
}
}
if(failed){
cerr << "\n Differences logged in BinRelTestRandom_baseDomain.output\n";
writeOutput("BinRelTestRandom","baseDomain", ss);
}
ASSERT_FALSE(failed);
}
TEST(BinRelTestRandom, tensorDomain){
// //Maybe this should be done in a more repeat-friendly way// //
stringstream ss;
bool failed = false;
bool dump = false;
program_bdd_context_t brm = new ProgramBddContext();
brm->addIntVar( "a", 4);
brm->addBoolVar( "b");
brm->addIntVar( "c", 4);
brm->addBoolVar( "d");
//ASSERT_EQ(voc.size(),4);
srand((unsigned)time(NULL));
for(int h=0;h<20;++h){
bdd r1bdd = brm->tGetRandomTransformer(true);
bdd r2bdd = brm->tGetRandomTransformer(true);
bdd r3bdd = brm->tGetRandomTransformer(true);
sem_elem_t r1 = new BinRel(brm.get_ptr(),r1bdd,true);
sem_elem_t r2 = new BinRel(brm.get_ptr(),r2bdd,true);
sem_elem_t r3 = new BinRel(brm.get_ptr(),r3bdd,true);
sem_elem_t w1,w2,w3,w4,w5;
w1 = r1->combine(r2);
w2 = r2->combine(r1);
if(!w1->equal(w2) || dump){
ss << "#################################\n[tensor] r1 | r2 <> r2 | r1\n\n";
r1->print(ss << "r1: ") << endl;
r2->print(ss << "r2: ") << endl;
w1->print(ss << "r1 | r2: ") << endl;
w2->print(ss << "r2 | r1: ") << endl;
failed = true;
}
w1 = (r1->extend(r2))->combine(r1->extend(r3));
w2 = r1->extend(r2->combine(r3));;
if(!w1->equal(w2) || dump){
ss << "#################################\n[tensor] r1 & (r2 | r3) <> r1 & r2 | r1 & r3\n\n";
r1->print(ss << "r1: ") << endl;
r2->print(ss << "r2: ") << endl;
r3->print(ss << "r3: ") << endl;
w1->print(ss << "r1 & (r2 | r3): ") << endl;
w2->print(ss << "r1 & r2 | r1 & r3: ") << endl;
failed = true;
}
w1 = (r1->extend(r3))->combine(r2->extend(r3));
w2 = (r1->combine(r2))->extend(r3);
if(!w1->equal(w2) || dump){
ss << "#################################\n[tensor] (r1 | r2 ) & r3 <> r1 & r3 | r2 & r3\n\n";
r1->print(ss << "r1: ") << endl;
r2->print(ss << "r2: ") << endl;
r3->print(ss << "r3: ") << endl;
w1->print(ss << "(r1 | r2) & r3: ") << endl;
w2->print(ss << "r1 & r3 | r2 & r3: ") << endl;
failed = true;
}
}
if(failed){
cerr << "\n Differences logged in BinRelTestRandom_baseDomain.output\n";
writeOutput("BinRelTestRandom","tensorDomain", ss);
}
ASSERT_FALSE(failed);
}
TEST(BinRelTestRandom, baseTensorDomain){
// //Maybe this should be done in a more repeat-friendly way// //
stringstream ss;
bool failed = false;
bool dump = false;
program_bdd_context_t brm = new ProgramBddContext();
brm->addIntVar( "a", 4);
brm->addBoolVar( "b");
brm->addIntVar( "c", 4);
brm->addBoolVar( "d");
srand(time(NULL));
//for debugging
//srand(1);
for(int h=0;h<20;++h){
bdd b1bdd = brm->tGetRandomTransformer(false);
bdd b2bdd = brm->tGetRandomTransformer();
bdd b3bdd = brm->tGetRandomTransformer();
bdd b4bdd = brm->tGetRandomTransformer(false);
bdd t1bdd = brm->tGetRandomTransformer(true);
bdd t2bdd = brm->tGetRandomTransformer(true);
sem_elem_tensor_t b1 = new BinRel(brm.get_ptr(),b1bdd,false);
sem_elem_tensor_t b2 = new BinRel(brm.get_ptr(),b2bdd,false);
sem_elem_tensor_t b3 = new BinRel(brm.get_ptr(),b3bdd,false);
sem_elem_tensor_t b4 = new BinRel(brm.get_ptr(),b4bdd,false);
sem_elem_tensor_t t1 = new BinRel(brm.get_ptr(),t1bdd,true);
sem_elem_tensor_t t2 = new BinRel(brm.get_ptr(),t2bdd,true);
sem_elem_tensor_t w1,w2,w3,w4;
w1 = b1->tensor(b2.get_ptr());
w2 = b3->tensor(b4.get_ptr());
w1 = dynamic_cast<SemElemTensor*>(w1->extend(w2.get_ptr()).get_ptr());
w3 = dynamic_cast<SemElemTensor*>(b1->extend(b3.get_ptr()).get_ptr());
w4 = dynamic_cast<SemElemTensor*>(b2->extend(b4.get_ptr()).get_ptr());
w3 = w3->tensor(w4.get_ptr());
if(!w1->equal(w3) || dump){
ss << "#################################\n(b1,b2) & (b3,b4) <> (b1 & b3,b2 & b4)\n\n";
b1->print(ss << "b1: ") << endl;
b2->print(ss << "b2: ") << endl;
b3->print(ss << "b3: ") << endl;
b4->print(ss << "b4: ") << endl;
w1 = b1->tensor(b2.get_ptr());
w1->print(ss << "(b1,b2): ") << endl;
w2 = b3->tensor(b4.get_ptr());
w2->print(ss << "(b3,b4): ") << endl;
w1 = dynamic_cast<SemElemTensor*>(w1->extend(w2.get_ptr()).get_ptr());
w1->print(ss << "(b1,b2) & (b3,b4): ") << endl;
b1->print(ss << "b1: ") << endl;
b2->print(ss << "b2: ") << endl;
b3->print(ss << "b3: ") << endl;
b4->print(ss << "b4: ") << endl;
w3 = dynamic_cast<SemElemTensor*>(b1->extend(b3.get_ptr()).get_ptr());
w3->print(ss << "b1 & b3: ") << endl;
w4 = dynamic_cast<SemElemTensor*>(b2->extend(b4.get_ptr()).get_ptr());
w4->print(ss << "b2 & b4: ") << endl;
w3 = w3->tensor(w4.get_ptr());
w3->print(ss << "(b1 & b3,b2 & b4): ") << endl;
failed = true;
}
w1 = dynamic_cast<SemElemTensor*>(t1->combine(t2.get_ptr()).get_ptr());
w1 = w1->detensor();
w2 = t1->detensor();
w3 = t2->detensor();
w2 = dynamic_cast<SemElemTensor*>(w2->combine(w3.get_ptr()).get_ptr());
if(!w1->equal(w2) || dump){
ss << "#################################\nD(t1 | t2) <> D(t1) | D(t2)\n\n";
t1->print(ss << "t1: ") << endl;
t2->print(ss << "t2: ") << endl;
w1 = dynamic_cast<SemElemTensor*>(t1->combine(t2.get_ptr()).get_ptr());
w1->print(ss << "t1 | t2: ") << endl;
w1 = w1->detensor();
w1->print(ss << "D(t1 | t2): ") << endl;
w2 = t1->detensor();
w2->print(ss << "D(t1): ") << endl;
w3 = t2->detensor();
w3->print(ss << "D(t2): ") << endl;
w2 = dynamic_cast<SemElemTensor*>(w2->combine(w3.get_ptr()).get_ptr());
w2->print(ss << "D(t1) | D(t2): ") << endl;
failed = true;
}
w1 = b1->tensor(b2.get_ptr());
w1 = w1->detensor();
w2 = dynamic_cast<SemElemTensor*>(b1->extend(b2.get_ptr()).get_ptr());
if(!w1->equal(w2) || dump){
ss << "#################################\nD((b1, b2)) <> b1 & b2\n\n";
b1->print(ss << "b1: ") << endl;
b2->print(ss << "b2: ") << endl;
w1 = b1->tensor(b2.get_ptr());
w1->print(ss << "(b1,r2): ") << endl;
w1 = w1->detensor();
w1->print(ss << "D((b1,r2)): ") << endl;
w2 = dynamic_cast<SemElemTensor*>(b1->extend(b2.get_ptr()).get_ptr());
w2->print(ss << "b1 & b2: ") << endl;
failed = true;
}
}
if(failed){
cerr << "\n Differences logged in BinRelTestRandom_baseDomain.output\n";
writeOutput("BinRelTestRandom","baseTensorDomain", ss);
}
ASSERT_FALSE(failed);
}
} //namespace
| 33.39779 | 106 | 0.556989 | [
"vector"
] |
24031a8b08d56c256e7cd9cbad14a4ddc0fe5f88 | 3,291 | hpp | C++ | Source/VolumeFactory.hpp | gpdaniels/Raymarcher | 5c01f982251914739451ea992d3f59987dc7c537 | [
"MIT"
] | 6 | 2020-01-19T07:57:31.000Z | 2021-09-12T11:18:59.000Z | Source/VolumeFactory.hpp | gpdaniels/Raymarcher | 5c01f982251914739451ea992d3f59987dc7c537 | [
"MIT"
] | null | null | null | Source/VolumeFactory.hpp | gpdaniels/Raymarcher | 5c01f982251914739451ea992d3f59987dc7c537 | [
"MIT"
] | 1 | 2020-12-27T13:06:54.000Z | 2020-12-27T13:06:54.000Z | /*
The MIT License
Copyright (c) 2017 Geoffrey Daniels. http://gpdaniels.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
*/
#pragma once
#ifndef RAYMARCH_VOLUMEFACTORY_HPP
#define RAYMARCH_VOLUMEFACTORY_HPP
#include "Volume.hpp"
namespace Raymarch {
/// @brief VolumeFactory provides a number of factory functions to create volumes.
class VolumeFactory {
private:
/// @brief Deleted destructor.
~VolumeFactory(void) = delete;
/// @brief Deleted constructor.
VolumeFactory(void) = delete;
public:
/// @brief Create a solid cuboid volume of a given voxel type.
/// @param SizeX - Width of the volume.
/// @param SizeY - Height of the volume.
/// @param SizeZ - Depth of the volume.
/// @param Value - The voxel value.
static Volume CreateSolid(std::size_t SizeX, std::size_t SizeY, std::size_t SizeZ, Voxel Value);
/// @brief Create an ellipsoid of a given voxel type.
/// @param SizeX - Width of the volume.
/// @param SizeY - Height of the volume.
/// @param SizeZ - Depth of the volume.
/// @param Value - The voxel value.
static Volume CreateEllipsoid(std::size_t SizeX, std::size_t SizeY, std::size_t SizeZ, Voxel Value);
/// @brief Create a sponge by only setting random positions in a cuboid volume to a given voxel type.
/// @param SizeX - Width of the volume.
/// @param SizeY - Height of the volume.
/// @param SizeZ - Depth of the volume.
/// @param Density - The fill ratio of the sponge between 0.0 and 1.0.
/// @param Value - The voxel value.
static Volume CreateRandomSponge(std::size_t SizeX, std::size_t SizeY, std::size_t SizeZ, double Density, Voxel Value);
/// @brief Create a column volume of a given voxel type.
/// @param SizeX - Width of the volume.
/// @param SizeY - Height of the volume.
/// @param SizeZ - Depth of the volume.
/// @param Radius - The radius of the column radius between 0.0 and 1.0.
/// @param Value - The voxel value.
static Volume CreateColumn(std::size_t SizeX, std::size_t SizeY, std::size_t SizeZ, double Radius, Voxel Value);
};
}
#endif // RAYMARCH_VOLUMEFACTORY_HPP
| 44.472973 | 127 | 0.686418 | [
"solid"
] |
24036cbc6a1361aab00e2b3f7f9234ed4f0b9a71 | 4,216 | hpp | C++ | src/sdglib/mappers/LinkedReadsMapper.hpp | bioinfologics/sdg | b874f5e4de2a5a77320fac2080bae48e12c1fd03 | [
"MIT"
] | 19 | 2019-07-01T22:46:20.000Z | 2021-11-21T17:06:16.000Z | src/sdglib/mappers/LinkedReadsMapper.hpp | bioinfologics/sdg | b874f5e4de2a5a77320fac2080bae48e12c1fd03 | [
"MIT"
] | 58 | 2019-06-20T08:54:11.000Z | 2021-08-04T09:30:28.000Z | src/sdglib/mappers/LinkedReadsMapper.hpp | bioinfologics/bsg | 387f06ef21c494c4370b4c43869f72e27503024d | [
"MIT"
] | 6 | 2017-11-22T16:23:11.000Z | 2019-04-17T17:09:01.000Z | //
// Created by Bernardo Clavijo (EI) on 11/02/2018.
//
#pragma once
#include <set>
#include <unordered_set>
#include <map>
#include <sdglib/types/MappingTypes.hpp>
#include <sdglib/indexers/UniqueKmerIndex.hpp>
#include <sdglib/Version.hpp>
class WorkSpace;
class UniqueKmerIndex;
class Unique63merIndex;
class LinkedReadsDatastore;
using LinkedTag = uint32_t;
class TagNeighbour {
public:
TagNeighbour(){};
TagNeighbour(sgNodeID_t n, float s):node(n),score(s){};
sgNodeID_t node;
float score; //breaking the latte principle
};
/**
* @brief A mapper for linked reads from a LinkedReadsDatastore.
*
* Supports partial remapping of unmapped reads or of a selection list.
*/
class LinkedReadsMapper {
public:
LinkedReadsMapper(WorkSpace &_ws, LinkedReadsDatastore &_datastore);
/**
* @brief Provides an overview of the information in the LinkedReadsMapper
* @param level Base indentation level to use on the result
* @param recursive Whether it should explore or not the rest of the hierarchy
* @return
* A text summary of the information contained in a LinkedReadsMapper
*/
std::string ls(int level=0,bool recursive=true) const;
friend std::ostream& operator<<(std::ostream &os, const LinkedReadsMapper &lirm);
void write(std::ofstream & output_file);
void read(std::ifstream & input_file);
void dump_readpaths(std::ofstream &opf);
void load_readpaths(std::ifstream &ipf);
/**
* Checks that the graph and datastore are the same and if they are assigns reads_in_node and nodes_in_read collections
*
* @param other LinkedReadsMapper to compare with
* @return
*/
LinkedReadsMapper& operator=(const LinkedReadsMapper &other);
/** @brief creates a read path for each read through mapping
*
* @return
*/
void path_reads(uint8_t k=63,int filter=200, bool fill_offsets=false);
/** @brief Prints the count of pairs mapped.
*
* Prints the count of pairs mapped where no end mapped, a single end mapped and both ends mapped and of those how many mapped to a single node.
*/
void print_status() const;
/** @brief Given a nodeID returns a set of all tags mapped to that node.
* If there are no mapped tags returns an empty set
*
* @param n nodeID
* @return set of bsg10xtags
*/
std::set<LinkedTag> get_node_tags(sgNodeID_t n);
/**
* Creates a nieghbours matrix with all nodes where for each node the function finds all nodes that have tags that
* cover min_score of the total tags of each node.
*
* Example:
* - node A has reads with tags 5, 5, 6, 7, 8
* - node B has reads with tags 5, 8, 9, 9, 10
*
* Then B tags cover 3/6=0.5 of A reads, and A tags cover 2/5=0.4 of B reads.
* If min_score=.5 then B is in A's neighbours, but A is not in B's
*
* Results are stored in the tag_neighbours vector
* @param min_size
* @param min_score
* @param min_mapped_reads_per_tag
*/
void compute_all_tag_neighbours(int min_size,float min_score, int min_mapped_reads_per_tag=2);
void write_tag_neighbours(std::string filename);
void read_tag_neighbours(std::string filename);
WorkSpace &ws;
LinkedReadsDatastore &datastore;
/**
* Collection of read mappings
* reads_in_node[nodeID] = [vector of mappings to nodeID... ]
*/
std::vector<std::vector<ReadMapping>> reads_in_node;
/**
* Read to node index
* read_to_node[readID] = nodeID where the read is mapped to
*/
std::vector<sgNodeID_t> read_to_node;//id of the main node if mapped, set to 0 to remap on next process
/**
* Collection of neighbouring nodes
* Completed using compute_all_tag_neighbours()
* tag_neighbours[nodeID] = [collection of 10 determined neighbours (see TagNeighbour) ...]
*/
std::vector<std::vector<TagNeighbour>> tag_neighbours; //not persisted yet!
std::vector<ReadPath> read_paths;
std::vector<std::vector<std::pair<uint32_t,uint32_t>>> read_path_offsets;
std::vector<std::vector<int64_t>> paths_in_node;
static const sdgVersion_t min_compat;
};
| 31.22963 | 148 | 0.685009 | [
"vector"
] |
240439bad8ab4ba914b4ed4e9aff9f94158fc9db | 5,171 | cpp | C++ | jobs/prop_mesher_job_step.cpp | Relintai/props | 2afd6eff45f9a921bdf4090ff3029def86df5cb5 | [
"MIT"
] | 6 | 2020-09-23T18:01:46.000Z | 2022-02-15T13:14:23.000Z | jobs/prop_mesher_job_step.cpp | Relintai/props | 2afd6eff45f9a921bdf4090ff3029def86df5cb5 | [
"MIT"
] | null | null | null | jobs/prop_mesher_job_step.cpp | Relintai/props | 2afd6eff45f9a921bdf4090ff3029def86df5cb5 | [
"MIT"
] | 1 | 2020-09-14T05:09:22.000Z | 2020-09-14T05:09:22.000Z | /*
Copyright (c) 2019-2021 Péter Magyar
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "prop_mesher_job_step.h"
const String PropMesherJobStep::BINDING_STRING_PROP_MESHER_JOB_STEP_TYPE = "Normal,Normal LOD,Drop UV2,Merge Verts,Bake Texture,Simplify Mesh";
PropMesherJobStep::PropMesherJobStepType PropMesherJobStep::get_job_type() const {
return _job_type;
}
void PropMesherJobStep::set_job_type(const PropMesherJobStep::PropMesherJobStepType value) {
_job_type = value;
}
int PropMesherJobStep::get_lod_index() const {
return _lod_index;
}
void PropMesherJobStep::set_lod_index(const int value) {
_lod_index = value;
}
#ifdef MESH_UTILS_PRESENT
Ref<FastQuadraticMeshSimplifier> PropMesherJobStep::get_fqms() {
return _fqms;
}
void PropMesherJobStep::set_fqms(const Ref<FastQuadraticMeshSimplifier> &val) {
_fqms = val;
}
float PropMesherJobStep::get_simplification_step_ratio() const {
return _simplification_step_ratio;
}
void PropMesherJobStep::set_simplification_step_ratio(const float value) {
_simplification_step_ratio = value;
}
int PropMesherJobStep::get_simplification_steps() const {
return _simplification_steps;
}
void PropMesherJobStep::set_simplification_steps(const int value) {
_simplification_steps = value;
}
float PropMesherJobStep::get_simplification_agressiveness() const {
return _simplification_agressiveness;
}
void PropMesherJobStep::set_simplification_agressiveness(const float value) {
_simplification_agressiveness = value;
}
#endif
PropMesherJobStep::PropMesherJobStep() {
_job_type = TYPE_NORMAL;
_lod_index = 0;
#ifdef MESH_UTILS_PRESENT
_simplification_step_ratio = 0.8;
_simplification_steps = 2;
_simplification_agressiveness = 7;
#endif
}
PropMesherJobStep::~PropMesherJobStep() {
#ifdef MESH_UTILS_PRESENT
_fqms.unref();
#endif
}
void PropMesherJobStep::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_job_type"), &PropMesherJobStep::get_job_type);
ClassDB::bind_method(D_METHOD("set_job_type", "value"), &PropMesherJobStep::set_job_type);
ADD_PROPERTY(PropertyInfo(Variant::INT, "job_type", PROPERTY_HINT_ENUM, PropMesherJobStep::BINDING_STRING_PROP_MESHER_JOB_STEP_TYPE), "set_job_type", "get_job_type");
ClassDB::bind_method(D_METHOD("get_lod_index"), &PropMesherJobStep::get_lod_index);
ClassDB::bind_method(D_METHOD("set_lod_index", "value"), &PropMesherJobStep::set_lod_index);
ADD_PROPERTY(PropertyInfo(Variant::INT, "lod_index"), "set_lod_index", "get_lod_index");
#ifdef MESH_UTILS_PRESENT
ClassDB::bind_method(D_METHOD("get_fqms"), &PropMesherJobStep::get_fqms);
ClassDB::bind_method(D_METHOD("set_fqms", "value"), &PropMesherJobStep::set_fqms);
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "fqms", PROPERTY_HINT_RESOURCE_TYPE, "FastQuadraticMeshSimplifier"), "set_fqms", "get_fqms");
ClassDB::bind_method(D_METHOD("get_simplification_step_ratio"), &PropMesherJobStep::get_simplification_step_ratio);
ClassDB::bind_method(D_METHOD("set_simplification_step_ratio", "value"), &PropMesherJobStep::set_simplification_step_ratio);
ADD_PROPERTY(PropertyInfo(Variant::REAL, "simplification_step_ratio"), "set_simplification_step_ratio", "get_simplification_step_ratio");
ClassDB::bind_method(D_METHOD("get_simplification_steps"), &PropMesherJobStep::get_simplification_steps);
ClassDB::bind_method(D_METHOD("set_simplification_steps", "value"), &PropMesherJobStep::set_simplification_steps);
ADD_PROPERTY(PropertyInfo(Variant::INT, "simplification_steps"), "set_simplification_steps", "get_simplification_steps");
ClassDB::bind_method(D_METHOD("get_simplification_agressiveness"), &PropMesherJobStep::get_simplification_agressiveness);
ClassDB::bind_method(D_METHOD("set_simplification_agressiveness", "value"), &PropMesherJobStep::set_simplification_agressiveness);
ADD_PROPERTY(PropertyInfo(Variant::REAL, "simplification_agressiveness"), "set_simplification_agressiveness", "get_simplification_agressiveness");
#endif
BIND_ENUM_CONSTANT(TYPE_NORMAL);
BIND_ENUM_CONSTANT(TYPE_NORMAL_LOD);
BIND_ENUM_CONSTANT(TYPE_DROP_UV2);
BIND_ENUM_CONSTANT(TYPE_MERGE_VERTS);
BIND_ENUM_CONSTANT(TYPE_BAKE_TEXTURE);
BIND_ENUM_CONSTANT(TYPE_SIMPLIFY_MESH);
BIND_ENUM_CONSTANT(TYPE_OTHER);
}
| 41.701613 | 167 | 0.81841 | [
"mesh",
"object"
] |
2405df95cebbef09a44bcb82d178a4c304cd6dbd | 10,654 | cc | C++ | tools/compiler/dr/src/generate/t_gv_generator.cc | mehrdad-shokri/Pebble | 68315f176d9e328a233ace29b7579a829f89879f | [
"BSD-2-Clause"
] | 841 | 2016-11-11T21:44:15.000Z | 2022-03-13T09:00:56.000Z | tools/compiler/dr/src/generate/t_gv_generator.cc | mehrdad-shokri/Pebble | 68315f176d9e328a233ace29b7579a829f89879f | [
"BSD-2-Clause"
] | 21 | 2016-11-17T04:24:06.000Z | 2019-04-11T09:36:52.000Z | tools/compiler/dr/src/generate/t_gv_generator.cc | mehrdad-shokri/Pebble | 68315f176d9e328a233ace29b7579a829f89879f | [
"BSD-2-Clause"
] | 343 | 2016-11-11T11:06:19.000Z | 2022-03-21T09:07:45.000Z | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#include <string>
#include <fstream>
#include <iostream>
#include <vector>
#include <map>
#include <list>
#include <stdlib.h>
#include <sys/stat.h>
#include <sstream>
#include "t_generator.h"
#include "../platform.h"
using std::map;
using std::ofstream;
using std::ostringstream;
using std::pair;
using std::string;
using std::stringstream;
using std::vector;
static const string endl = "\n"; // avoid ostream << std::endl flushes
/**
* Graphviz code generator
*/
class t_gv_generator : public t_generator {
public:
t_gv_generator(
t_program* program,
const std::map<std::string, std::string>& parsed_options,
const std::string& option_string)
: t_generator(program)
{
(void) parsed_options;
(void) option_string;
out_dir_base_ = "gen-gv";
std::map<std::string, std::string>::const_iterator iter;
iter = parsed_options.find("exceptions");
exception_arrows = (iter != parsed_options.end());
}
/**
* Init and end of generator
*/
void init_generator();
void close_generator();
/**
* Program-level generation functions
*/
void generate_typedef (t_typedef* ttypedef);
void generate_enum (t_enum* tenum);
void generate_const (t_const* tconst);
void generate_struct (t_struct* tstruct);
void generate_service (t_service* tservice);
protected:
/**
* Helpers
*/
void print_type(t_type* ttype, string struct_field_ref);
void print_const_value(t_type* type, t_const_value* tvalue);
private:
std::ofstream f_out_;
std::list<string> edges;
bool exception_arrows;
};
/**
* Init generator:
* - Adds some escaping for the Graphviz domain.
* - Create output directory and open file for writting.
* - Write the file header.
*/
void t_gv_generator::init_generator() {
escape_['{'] = "\\{";
escape_['}'] = "\\}";
// Make output directory
MKDIR(get_out_dir().c_str());
string fname = get_out_dir() + program_->get_name() + ".gv";
f_out_.open(fname.c_str());
f_out_ << "digraph \"" << escape_string(program_name_) << "\" {" << endl;
f_out_ << "node [style=filled, shape=record];" << endl;
f_out_ << "edge [arrowsize=0.5];" << endl;
f_out_ << "rankdir=LR" << endl;
}
/**
* Closes generator:
* - Print accumulated nodes connections.
* - Print footnote.
* - Closes file.
*/
void t_gv_generator::close_generator() {
// Print edges
std::list<string>::iterator iter = edges.begin();
for ( ; iter != edges.end(); iter++) {
f_out_ << (*iter) << endl;
}
// Print graph end } and close file
f_out_ << "}" << endl;
f_out_.close();
}
void t_gv_generator::generate_typedef (t_typedef* ttypedef) {
string name = ttypedef->get_name();
f_out_ << "node [fillcolor=azure];" << endl;
f_out_ << name << " [label=\"";
f_out_ << escape_string(name);
f_out_ << " :: ";
print_type(ttypedef->get_type(), name);
f_out_ << "\"];" << endl;
}
void t_gv_generator::generate_enum (t_enum* tenum) {
string name = tenum->get_name();
f_out_ << "node [fillcolor=white];" << endl;
f_out_ << name << " [label=\"enum " << escape_string(name);
vector<t_enum_value*> values = tenum->get_constants();
vector<t_enum_value*>::iterator val_iter;
for (val_iter = values.begin(); val_iter != values.end(); ++val_iter) {
f_out_ << '|' << (*val_iter)->get_name();
f_out_ << " = ";
f_out_ << (*val_iter)->get_value();
}
f_out_ << "\"];" << endl;
}
void t_gv_generator::generate_const (t_const* tconst) {
string name = tconst->get_name();
f_out_ << "node [fillcolor=aliceblue];" << endl;
f_out_ << "const_" << name << " [label=\"";
f_out_ << escape_string(name);
f_out_ << " = ";
print_const_value( tconst->get_type(), tconst->get_value());
f_out_ << " :: ";
print_type(tconst->get_type(), "const_" + name);
f_out_ << "\"];" << endl;
}
void t_gv_generator::generate_struct (t_struct* tstruct) {
string name = tstruct->get_name();
if (tstruct->is_xception()) {
f_out_ << "node [fillcolor=lightpink];" << endl;
f_out_ << name << " [label=\"";
f_out_ << "exception " << escape_string(name);
} else if (tstruct->is_union()) {
f_out_ << "node [fillcolor=lightcyan];" << endl;
f_out_ << name << " [label=\"";
f_out_ << "union " << escape_string(name);
} else {
f_out_ << "node [fillcolor=beige];" << endl;
f_out_ << name << " [label=\"";
f_out_ << "struct " << escape_string(name);
}
vector<t_field*> members = tstruct->get_members();
vector<t_field*>::iterator mem_iter = members.begin();
for ( ; mem_iter != members.end(); mem_iter++) {
string field_name = (*mem_iter)->get_name();
// print port (anchor reference)
f_out_ << "|<field_" << field_name << '>';
// field name :: field type
f_out_ << (*mem_iter)->get_name();
f_out_ << " :: ";
print_type((*mem_iter)->get_type(),
name + ":field_" + field_name);
}
f_out_ << "\"];" << endl;
}
void t_gv_generator::print_type(t_type* ttype, string struct_field_ref) {
if (ttype->is_container()) {
if (ttype->is_list()) {
f_out_ << "list\\<";
print_type(((t_list*)ttype)->get_elem_type(), struct_field_ref);
f_out_ << "\\>";
} else if (ttype->is_set()) {
f_out_ << "set\\<";
print_type(((t_set*)ttype)->get_elem_type(), struct_field_ref);
f_out_ << "\\>";
} else if (ttype->is_map()) {
f_out_ << "map\\<";
print_type(((t_map*)ttype)->get_key_type(), struct_field_ref);
f_out_ << ", ";
print_type(((t_map*)ttype)->get_val_type(), struct_field_ref);
f_out_ << "\\>";
}
} else if (ttype->is_base_type()) {
f_out_ << (((t_base_type*)ttype)->is_binary() ? "binary" : ttype->get_name());
} else {
f_out_ << ttype->get_name();
edges.push_back(struct_field_ref + " -> " + ttype->get_name());
}
}
/**
* Prints out an string representation of the provided constant value
*/
void t_gv_generator::print_const_value(t_type* type, t_const_value* tvalue) {
bool first = true;
switch (tvalue->get_type()) {
case t_const_value::CV_INTEGER:
f_out_ << tvalue->get_integer();
break;
case t_const_value::CV_DOUBLE:
f_out_ << tvalue->get_double();
break;
case t_const_value::CV_STRING:
f_out_ << "\\\"" << get_escaped_string(tvalue) << "\\\"";
break;
case t_const_value::CV_MAP:
{
f_out_ << "\\{ ";
map<t_const_value*, t_const_value*> map_elems = tvalue->get_map();
map<t_const_value*, t_const_value*>::iterator map_iter;
for (map_iter = map_elems.begin(); map_iter != map_elems.end(); map_iter++) {
if (!first) {
f_out_ << ", ";
}
first = false;
print_const_value( ((t_map*)type)->get_key_type(), map_iter->first);
f_out_ << " = ";
print_const_value( ((t_map*)type)->get_val_type(), map_iter->second);
}
f_out_ << " \\}";
}
break;
case t_const_value::CV_LIST:
{
f_out_ << "\\{ ";
vector<t_const_value*> list_elems = tvalue->get_list();;
vector<t_const_value*>::iterator list_iter;
for (list_iter = list_elems.begin(); list_iter != list_elems.end(); list_iter++) {
if (!first) {
f_out_ << ", ";
}
first = false;
if (type->is_list()) {
print_const_value( ((t_list*)type)->get_elem_type(), *list_iter);
} else {
print_const_value( ((t_set*)type)->get_elem_type(), *list_iter);
}
}
f_out_ << " \\}";
}
break;
case t_const_value::CV_IDENTIFIER:
f_out_ << escape_string(type->get_name()) << "." << escape_string(tvalue->get_identifier_name());
break;
default:
f_out_ << "UNKNOWN";
break;
}
}
void t_gv_generator::generate_service (t_service* tservice) {
string service_name = get_service_name(tservice);
f_out_ << "subgraph cluster_" << service_name << " {" << endl;
f_out_ << "node [fillcolor=bisque];" << endl;
f_out_ << "style=dashed;" << endl;
f_out_ << "label = \"" << escape_string(service_name) << " service\";" << endl;
// TODO: service extends
vector<t_function*> functions = tservice->get_functions();
vector<t_function*>::iterator fn_iter = functions.begin();
for ( ; fn_iter != functions.end(); fn_iter++) {
string fn_name = (*fn_iter)->get_name();
f_out_ << "function_" << fn_name;
f_out_ << "[label=\"<return_type>function " << escape_string(fn_name);
f_out_ << " :: ";
print_type((*fn_iter)->get_returntype(), "function_" + fn_name + ":return_type");
vector<t_field*> args = (*fn_iter)->get_arglist()->get_members();
vector<t_field*>::iterator arg_iter = args.begin();
for ( ; arg_iter != args.end(); arg_iter++) {
f_out_ << "|<param_" << (*arg_iter)->get_name() << ">";
f_out_ << (*arg_iter)->get_name();
if ((*arg_iter)->get_value() != NULL) {
f_out_ << " = ";
print_const_value((*arg_iter)->get_type(), (*arg_iter)->get_value());
}
f_out_ << " :: ";
print_type((*arg_iter)->get_type(),
"function_" + fn_name + ":param_" + (*arg_iter)->get_name());
}
// end of node
f_out_ << "\"];" << endl;
// Exception edges
if (exception_arrows) {
vector<t_field*> excepts = (*fn_iter)->get_xceptions()->get_members();
vector<t_field*>::iterator ex_iter = excepts.begin();
for ( ; ex_iter != excepts.end(); ex_iter++) {
edges.push_back("function_" + fn_name + " -> " +
(*ex_iter)->get_type()->get_name() + " [color=red]");
}
}
}
f_out_ << " }" << endl;
}
THRIFT_REGISTER_GENERATOR(gv, "Graphviz",
" exceptions: Whether to draw arrows from functions to exception.\n"
)
| 30.791908 | 103 | 0.605406 | [
"shape",
"vector"
] |
2405f13eaa972e57a70edb8e0b532210d48a6e26 | 4,042 | cpp | C++ | src/runtime_src/core/tools/xbutil2/SubCmdMem.cpp | akhileshbhople/XRT | 7f43226d5a7c8b95871c21d434313b8075192ea7 | [
"Apache-2.0"
] | 1 | 2021-03-20T07:05:42.000Z | 2021-03-20T07:05:42.000Z | src/runtime_src/core/tools/xbutil2/SubCmdMem.cpp | akhileshbhople/XRT | 7f43226d5a7c8b95871c21d434313b8075192ea7 | [
"Apache-2.0"
] | null | null | null | src/runtime_src/core/tools/xbutil2/SubCmdMem.cpp | akhileshbhople/XRT | 7f43226d5a7c8b95871c21d434313b8075192ea7 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (C) 2019 Xilinx, Inc
*
* 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://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.
*/
// ------ I N C L U D E F I L E S -------------------------------------------
// Local - Include Files
#include "SubCmdMem.h"
#include "XBUtilities.h"
namespace XBU = XBUtilities;
// 3rd Party Library - Include Files
#include <boost/program_options.hpp>
namespace po = boost::program_options;
// System - Include Files
#include <iostream>
// ------ L O C A L F U N C T I O N S ---------------------------------------
// ------ F U N C T I O N S ---------------------------------------------------
int subCmdMem(const std::vector<std::string> &_options, bool _help)
// Reference Command: mem --read [-d card] [-a [0x]start_addr] [-i size_bytes] [-o output filename]
// mem --write [-d card] [-a [0x]start_addr] [-i size_bytes] [-e pattern_byte]
// Read 256 bytes from DDR starting at 0x1000 into file read.out\n";
// xbutil mem --read -a 0x1000 -i 256 -o read.out
// - Default values for address is 0x0, size is DDR size and file is memread.out
// Write 256 bytes to DDR starting at 0x1000 with byte 0xaa
// xbutil mem --write -a 0x1000 -i 256 -e 0xaa
// - Default values for address is 0x0, size is DDR size and pattern is 0x0
{
XBU::verbose("SubCommand: mem");
// -- Retrieve and parse the subcommand options -----------------------------
bool bRead = false;
bool bWrite = false;
uint64_t card = 0;
std::string sStartAddr;
std::string sSizeBytes;
std::string sOutputFile;
std::string sPatternBytes;
po::options_description memDesc("mem options");
memDesc.add_options()
("read", boost::program_options::bool_switch(&bRead), "Read operation")
("write", boost::program_options::bool_switch(&bWrite), "Write operation")
(",c", boost::program_options::value<uint64_t>(&card), "Card to be examined")
(",a", boost::program_options::value<std::string>(&sStartAddr), "Start Address")
(",i", boost::program_options::value<std::string>(&sSizeBytes), "Size bytes")
(",o", boost::program_options::value<std::string>(&sOutputFile), "Output File")
(",e", boost::program_options::value<std::string>(&sPatternBytes), "Pattern bytes")
;
// Parse sub-command ...
po::variables_map vm;
try {
po::store(po::command_line_parser(_options).options(memDesc).run(), vm);
po::notify(vm); // Can throw
} catch (po::error& e) {
std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
std::cerr << memDesc << std::endl;
// Re-throw exception
throw;
}
// Check to see if help was requested or no command was found
if (_help == true) {
std::cout << memDesc << std::endl;
return 0;
}
// -- Do some DRC checks here --------------------------------------------
// -- Now process the subcommand --------------------------------------------
XBU::verbose(XBU::format(" Read Operation: %d", bRead));
XBU::verbose(XBU::format("Write Operation: %d", bWrite));
XBU::verbose(XBU::format(" Card: %ld", card));
XBU::verbose(XBU::format(" Start Address: %s", sStartAddr.c_str()));
XBU::verbose(XBU::format(" Size Bytes: %s", sSizeBytes.c_str()));
XBU::verbose(XBU::format(" Output File: %s", sOutputFile.c_str()));
XBU::verbose(XBU::format(" Pattern: %s", sPatternBytes.c_str()));
XBU::error("COMMAND BODY NOT IMPLEMENTED.");
// TODO: Put working code here
return 0;
}
| 37.775701 | 101 | 0.596734 | [
"vector"
] |
24073f1268de31e4c3b1836a4c25fd502bbc1c74 | 6,427 | cpp | C++ | GAG/src/GAGPL/CHEMISTRY/ModificationTable.cpp | hh1985/multi_hs_seq | 9cf4e70fb59283da30339499952c43a0684f7e77 | [
"Apache-2.0"
] | 2 | 2015-04-03T14:44:45.000Z | 2015-04-15T13:38:39.000Z | GAG/src/GAGPL/CHEMISTRY/ModificationTable.cpp | hh1985/multi_hs_seq | 9cf4e70fb59283da30339499952c43a0684f7e77 | [
"Apache-2.0"
] | null | null | null | GAG/src/GAGPL/CHEMISTRY/ModificationTable.cpp | hh1985/multi_hs_seq | 9cf4e70fb59283da30339499952c43a0684f7e77 | [
"Apache-2.0"
] | null | null | null | /********************************************************************
created: 2012/06/27
created: 27:6:2012 15:55
filename: ModificationTable.cpp
file path: GAG\src\GAGPL\CHEMISTRY
file base: ModificationTable
file ext: cpp
author: Han Hu
purpose:
*********************************************************************/
#include <GAGPL/CHEMISTRY/ModificationTable.h>
#include <GAGPL/CHEMISTRY/FunctionalGroupTable.h>
#include <boost/tuple/tuple.hpp>
#include <boost/make_shared.hpp>
#include <iostream>
namespace gag
{
ModificationTable& ModificationTable::Instance()
{
static ModificationTable mt;
return mt;
}
void ModificationTable::load(const std::string& filename)
{
std::cout << "Load modification once!" << std::endl;
FunctionalGroupTable& ftable = FunctionalGroupTable::Instance();
//ftable.load();
using boost::property_tree::ptree;
ptree pt;
read_xml(filename, pt);
BOOST_FOREACH(ptree::value_type &v, pt.get_child("parameters.ModificationSet"))
{
if(v.first == "Modification") {
// Only one name is allowed.
std::string name = v.second.get<std::string>("Name");
// Multiple symbols are allowed.
std::set<std::string> symbols;
std::vector<Reaction> reactions;
std::pair<ptree::assoc_iterator, ptree::assoc_iterator> ei = v.second.equal_range("Symbol");
for(ptree::assoc_iterator iter = ei.first; iter != ei.second; iter++)
{
symbols.insert(iter->second.data());
}
// Iterate over all the reactions.
std::pair<ptree::assoc_iterator, ptree::assoc_iterator> reaction_pair = v.second.equal_range("Reaction");
for(ptree::assoc_iterator iter = reaction_pair.first; iter != reaction_pair.second; iter++)
{
Reaction rt;
if(iter->second.count("Position") > 0)
rt.position = iter->second.get<size_t>("Position");
BOOST_FOREACH(ptree::value_type &s, iter->second.get_child("Target"))
{
if(s.first == "Core") {
if(s.second.count("Minus") > 0) {
std::pair<ptree::assoc_iterator, ptree::assoc_iterator> minus_pair = s.second.equal_range("Minus");
for(ptree::assoc_iterator assoc_iter = minus_pair.first; assoc_iter != minus_pair.second; assoc_iter++)
{
rt.core_operation.push_back(std::make_pair(Removement, assoc_iter->second.data()));
}
}
if(s.second.count("Plus") > 0) {
//size_t position = s.second.get("Plus.<xmlattr>.Site", 0);
std::pair<ptree::assoc_iterator, ptree::assoc_iterator> plus_pair = s.second.equal_range("Plus");
for(ptree::assoc_iterator assoc_iter = plus_pair.first; assoc_iter != plus_pair.second; assoc_iter++)
{
rt.core_operation.push_back(std::make_pair(Addition, assoc_iter->second.data()));
}
}
} else if(s.first == "Subgroup") {
OperationSet oper_set;
if(s.second.count("Minus") > 0) {
size_t fg_position = s.second.get("Minus.<xmlattr>.Site", 0);
std::pair<ptree::assoc_iterator, ptree::assoc_iterator> minus_pair = s.second.equal_range("Minus");
for(ptree::assoc_iterator assoc_iter = minus_pair.first; assoc_iter != minus_pair.second; assoc_iter++)
{
oper_set.push_back(boost::make_tuple(fg_position, Removement, assoc_iter->second.data()));
}
}
if(s.second.count("Plus") > 0) {
size_t fg_position = s.second.get("Plus.<xmlattr>.Site",0);
std::pair<ptree::assoc_iterator, ptree::assoc_iterator> plus_pair = s.second.equal_range("Plus");
for(ptree::assoc_iterator assoc_iter = plus_pair.first; assoc_iter != plus_pair.second; assoc_iter++)
{
oper_set.push_back(boost::make_tuple(fg_position, Addition, assoc_iter->second.data()));
}
}
rt.sub_fg_operation.insert(std::make_pair(s.second.get<std::string>("FunctionalGroup"), oper_set));
}
}
OperationSet oper_set;
if(iter->second.count("Reactant") > 0) {
BOOST_FOREACH(ptree::value_type &s, iter->second.get_child("Reactant"))
{
if(s.first == "FunctionalGroup")
rt.reactant_operation.first = s.second.data();
else if(s.first == "Minus") {
size_t fg_position = s.second.get("<xmlattr>.Site", 0);
oper_set.push_back(boost::make_tuple(fg_position, Removement, s.second.data()));
} else if(s.first == "Plus") {
size_t fg_position = s.second.get("<xmlattr>.Site", 0);
oper_set.push_back(boost::make_tuple(fg_position, Addition, s.second.data()));
}
}
}
rt.reactant_operation.second = oper_set;
reactions.push_back(rt);
}
ModificationRule mr;
// Iterate over all the rules.
std::pair<ptree::assoc_iterator, ptree::assoc_iterator> rule_pair = v.second.equal_range("Rule");
for(ptree::assoc_iterator rule_iter = rule_pair.first; rule_iter != rule_pair.second; rule_iter++)
{
std::string fg_symbol = rule_iter->second.get<std::string>("FunctionalGroup");
std::vector<size_t> sites;
std::pair<ptree::assoc_iterator, ptree::assoc_iterator> site_pair = rule_iter->second.equal_range("Position");
for(ptree::assoc_iterator site_iter = site_pair.first; site_iter != site_pair.second; site_iter++)
{
sites.push_back((size_t)atoi(site_iter->second.data().c_str()));
}
mr.insert(std::make_pair(fg_symbol, sites));
}
// Store the information into mod_table;
ModificationPtr mod_ptr = boost::make_shared<Modification>(name, symbols, reactions, mr);
// mod_table.insert(mod_ptr);
// Update the reference table: mod_by_name and mod_by_shortcut.
mod_by_name.insert(std::make_pair(name, mod_ptr));
for(std::set<std::string>::iterator iter = mod_ptr->getSymbols().begin(); iter!=mod_ptr->getSymbols().end(); iter++)
{
mod_by_symbols.insert(std::make_pair(*iter, mod_ptr));
}
}
}
}
Modification ModificationTable::getModificationBySymbol( const std::string& symbol )
{
std::map<std::string, ModificationPtr>::iterator iter = mod_by_symbols.find(symbol);
return iter != mod_by_symbols.end() ? *(iter->second) : Modification();
}
Modification ModificationTable::getModificationByName( const std::string& name)
{
std::map<std::string, ModificationPtr>::iterator iter = mod_by_name.find(name);
return iter != mod_by_name.end() ? *(iter->second) : Modification();
}
} | 35.905028 | 120 | 0.648358 | [
"vector"
] |
240b741c8a791e2d8dc746a0a4175bbb6231e2ad | 57,776 | cpp | C++ | Plugins/StoryGraphPlugin/Source/StoryGraphPluginRuntime/Private/CustomNodes.cpp | VernamRD/StoryGraph | 7014f55232f2e9981ecd3ae58d031e32d1496127 | [
"MIT"
] | 1 | 2020-08-13T11:54:04.000Z | 2020-08-13T11:54:04.000Z | Plugins/StoryGraphPlugin/Source/StoryGraphPluginRuntime/Private/CustomNodes.cpp | VernamRD/StoryGraph | 7014f55232f2e9981ecd3ae58d031e32d1496127 | [
"MIT"
] | null | null | null | Plugins/StoryGraphPlugin/Source/StoryGraphPluginRuntime/Private/CustomNodes.cpp | VernamRD/StoryGraph | 7014f55232f2e9981ecd3ae58d031e32d1496127 | [
"MIT"
] | 1 | 2022-02-14T16:11:04.000Z | 2022-02-14T16:11:04.000Z | // Copyright 2016 Dmitriy Pavlov
#include "CustomNodes.h"
#include "Engine/Engine.h"
#include "HUD_StoryGraph.h"
#include "LogCategoryRutime.h"
#include "StoryGraph.h"
#include "StoryGraphObject.h"
#include "StoryGraphWidget.h"
#include "OtherActor_StoryGraph.h"
//UCustomNodeBase...........................................................................................
void UCustomNodeBase::GetChildNodes(TArray<UCustomNodeBase*>& ChildNodes, EPinDataTypes OutPinType)
{
ChildNodes.Empty();
for (int i = 0; i < NodePins.Num(); i++)
{
if (NodePins[i].Direction == (int)EEdGraphPinDirection::EGPD_Output && NodePins[i].PinDataType == (int)
OutPinType)
{
for (int j = 0; j < NodePins[i].Links.Num(); j++)
{
if (NodePins[i].Links[j])
{
ChildNodes.Add((UCustomNodeBase*)NodePins[i].Links[j]);
}
}
}
}
}
UCustomNodeBase* UCustomNodeBase::GetFistChildNode()
{
TArray<UCustomNodeBase*> ChildNodes;
GetChildNodes(ChildNodes, EPinDataTypes::PinType_Vertical);
if (ChildNodes.Num() > 0)
{
return ChildNodes[0];
}
GetChildNodes(ChildNodes, EPinDataTypes::PinType_Horizontal);
if (ChildNodes.Num() > 0)
{
return ChildNodes[0];
}
return nullptr;
}
void UCustomNodeBase::GetInputNodes(TArray<UCustomNodeBase*>& InputNodes, EPinDataTypes OutPinType)
{
InputNodes.Empty();
for (int i = 0; i < NodePins.Num(); i++)
{
if (NodePins[i].Direction == (int)EEdGraphPinDirection::EGPD_Input && NodePins[i].PinDataType == (int)OutPinType
)
{
for (int j = 0; j < NodePins[i].Links.Num(); j++)
{
if (NodePins[i].Links[j])
{
InputNodes.Add((UCustomNodeBase*)NodePins[i].Links[j]);
}
}
}
}
}
FString UCustomNodeBase::GetPinDataTypeEnumAsString(EPinDataTypes EnumValue)
{
const UEnum* EnumPtr = FindObject<UEnum>(ANY_PACKAGE, TEXT("EPinDataTypes"), true);
if (!EnumPtr) return FString("Invalid");
return EnumPtr->GetNameStringByIndex((int)EnumValue);
}
EInsertNodeType UCustomNodeBase::GetInsertNodeType(ENodeType NodeType)
{
switch (NodeType)
{
case ENodeType::DialogNode:
case ENodeType::DialogStart:
case ENodeType::DialogEnd:
case ENodeType::DialogExit:
case ENodeType::AddDialogFromDialog:
return EInsertNodeType::DialogGraphStandalone;
case ENodeType::SetDialogTrigger:
case ENodeType::SetInventoryItemState:
return EInsertNodeType::DialogGraphDependent;
case ENodeType::PrintString:
case ENodeType::EndGame:
case ENodeType::AddQuestPhase:
case ENodeType::AddScreenMessage:
case ENodeType::PrintQuestPhaseOnScreen:
case ENodeType::SendMessageToLevelBlueprint:
return EInsertNodeType::StoryGraphStandalone;
case ENodeType::CancelQuest:
case ENodeType::QuestStart:
case ENodeType::GetStoryGraphObjectState:
case ENodeType::AddDialog:
case ENodeType::SetSceneObjectActive:
case ENodeType::SendMessageScene:
case ENodeType::AddTargetObjectToPhase:
case ENodeType::AddMessageBranch:
return EInsertNodeType::StoryGraphDependent;
case ENodeType::MessageStart:
case ENodeType::ActivateTrigger:
case ENodeType::Message:
case ENodeType::MessageExit:
case ENodeType::MessageEnd:
return EInsertNodeType::MessageGraphStandalone;
case ENodeType::SetInventoryItemStateFromMessage:
return EInsertNodeType::MessageGraphDependent;
default:
return EInsertNodeType::NotDefine;
}
}
FString UCustomNodeBase::GetActionNameFromNodeType(ENodeType NodeType)
{
switch (NodeType)
{
case ENodeType::PrintString:
return "Print string";
case ENodeType::DialogNode:
return "Dialog node";
case ENodeType::DialogStart:
return "New dialog brunch";
case ENodeType::DialogEnd:
return "Dialog end";
case ENodeType::DialogExit:
return "Dialog exit";
case ENodeType::SetDialogTrigger:
return "Set dialog trigger";
case ENodeType::AddQuestPhase:
return "Add quest phase";
case ENodeType::GetStoryGraphObjectState:
return "Get object state";
case ENodeType::AddDialog:
return "Activate/deactivate dialog";
case ENodeType::AddDialogFromDialog:
return "Activate/deactivate dialog";
case ENodeType::AddMessageBranch:
return "Activate/deactivate message";
case ENodeType::SetSceneObjectActive:
return "Active/deactive object";
case ENodeType::CancelQuest:
return "Cancel quest";
case ENodeType::QuestStart:
return "Quest start";
case ENodeType::EndGame:
return "Game over";
case ENodeType::SendMessageScene:
return "Send Message";
case ENodeType::AddScreenMessage:
return "Add Screen Message";
case ENodeType::AddTargetObjectToPhase:
return "Add to radar";
case ENodeType::MessageStart:
return "New message brunch";
case ENodeType::Message:
return "Message";
case ENodeType::MessageExit:
return "Message exit";
case ENodeType::MessageEnd:
return "Message end";
case ENodeType::ActivateTrigger:
return "Activate trigger";
case ENodeType::SetInventoryItemState:
return "Set inventory state";
case ENodeType::SetInventoryItemStateFromMessage:
return "Set inventory state";
case ENodeType::PrintQuestPhaseOnScreen:
return "Print quest phase on screen";
case ENodeType::SendMessageToLevelBlueprint:
return "Send message to level blueprint";
default:
return "Not define";
}
}
FString UCustomNodeBase::GetToolTipFromNodeType(ENodeType NodeType)
{
switch (NodeType)
{
case ENodeType::PrintString:
return "Print debug string on screen or log";
case ENodeType::DialogNode:
return "Add Dialog";
case ENodeType::DialogStart:
return "Create new dialog brunch";
case ENodeType::DialogEnd:
return "Set current dialog brunch unactive";
case ENodeType::DialogExit:
return "Exit from dialog screen";
case ENodeType::SetDialogTrigger:
return "Activate/Deactivate dialog trigger";
case ENodeType::AddQuestPhase:
return "Add quest phase";
case ENodeType::GetStoryGraphObjectState:
return "Waiting when object switch in current state";
case ENodeType::AddDialog:
return "Add or Remove dialog brunch for current character";
case ENodeType::AddDialogFromDialog:
return "Add or Remove dialog brunch for current dialog";
case ENodeType::AddMessageBranch:
return "Add or Remove message brunch for current place trigger";
case ENodeType::SetSceneObjectActive:
return "Active or deactive scene object";
case ENodeType::QuestStart:
return "Begin new quest from this node";
case ENodeType::CancelQuest:
return "Cancel quest performance";
case ENodeType::EndGame:
return "Mark current quest phase as last phase in game";
case ENodeType::SendMessageScene:
return "Send message to scene object";
case ENodeType::AddScreenMessage:
return "Add message on screen";
case ENodeType::AddTargetObjectToPhase:
return "Add object to current quest phase for it displayed on radar";
case ENodeType::MessageStart:
return "Create new message branch";
case ENodeType::Message:
return "Create new message node";
case ENodeType::MessageExit:
return "Exit from message screen mode";
case ENodeType::MessageEnd:
return "Set current message brunch unactive";
case ENodeType::ActivateTrigger:
return "Switch trigger in active state";
case ENodeType::SetInventoryItemState:
return "Set current state of inventory item";
case ENodeType::SetInventoryItemStateFromMessage:
return "Set current state of inventory item";
case ENodeType::PrintQuestPhaseOnScreen:
return "Print quest phase on screen";
case ENodeType::SendMessageToLevelBlueprint:
return "Send message to level blueprint";
default:
return "Not define";
}
}
TSubclassOf<UCustomNodeBase> UCustomNodeBase::GetClassFromNodeType(ENodeType NodeType)
{
switch (NodeType)
{
case ENodeType::PrintString:
return UPrintStringNode::StaticClass();
case ENodeType::DialogNode:
return UDialogNode::StaticClass();
case ENodeType::DialogStart:
return UDialogStartNode::StaticClass();
case ENodeType::DialogEnd:
return UDialogEndNode::StaticClass();
case ENodeType::DialogExit:
return UDialogExitNode::StaticClass();
case ENodeType::AddQuestPhase:
return UAddQuestPhaseNode::StaticClass();
case ENodeType::GetStoryGraphObjectState:
return UGetStoryGraphObjectStateNode::StaticClass();
case ENodeType::SetDialogTrigger:
return USetDialogTriggerNode::StaticClass();
case ENodeType::AddDialog:
return UAddDialogNode::StaticClass();
case ENodeType::AddDialogFromDialog:
return UAddDialogFromDialogNode::StaticClass();
case ENodeType::AddMessageBranch:
return UAddMessageBranchNode::StaticClass();
case ENodeType::SetSceneObjectActive:
return USetSceneObjectActiveNode::StaticClass();
case ENodeType::CancelQuest:
return UCancelQuestNode::StaticClass();
case ENodeType::QuestStart:
return UQuestStartNode::StaticClass();
case ENodeType::EndGame:
return UEndGameNode::StaticClass();
case ENodeType::SendMessageScene:
return USendMessageNode::StaticClass();
case ENodeType::AddScreenMessage:
return UAddScreenMessageNode::StaticClass();
case ENodeType::AddTargetObjectToPhase:
return UAddTargetObjectToPhaseNode::StaticClass();
case ENodeType::MessageStart:
return UMessageStartNode::StaticClass();
case ENodeType::Message:
return UMessageNode::StaticClass();
case ENodeType::MessageExit:
return UMessageExitNode::StaticClass();
case ENodeType::MessageEnd:
return UMessageEndNode::StaticClass();
case ENodeType::ActivateTrigger:
return UActivateTriggerNode::StaticClass();
case ENodeType::SetInventoryItemState:
return USetInventoryItemStateNode::StaticClass();
case ENodeType::SetInventoryItemStateFromMessage:
return USetInventoryItemStateFromMessageNode::StaticClass();
case ENodeType::PrintQuestPhaseOnScreen:
return UPrintQuestPhaseOnScreenNode::StaticClass();
case ENodeType::SendMessageToLevelBlueprint:
return USendMessageToLevelBlueprintNode::StaticClass();
default:
return UCustomNodeBase::StaticClass();
}
}
FName UCustomNodeBase::GetIconNameFromNodeType(ENodeType NodeType)
{
switch (NodeType)
{
case ENodeType::AddTargetObjectToPhase:
return FName("CustomNode.Radar");
case ENodeType::QuestStart:
return FName("CustomNode.QuestStart");
default:
return FName("Non");
}
}
FLinearColor UCustomNodeBase::GetColorFromNodeType(ENodeType NodeType, int ColorNumber)
{
switch (NodeType)
{
case ENodeType::AddDialog:
if (ColorNumber == 0) return FLinearColor(0.1f, 0.1f, 0.4f);
if (ColorNumber == 1) return FLinearColor(0.1f, 0.2f, 0.4f);
case ENodeType::AddDialogFromDialog:
return FLinearColor(0.1f, 0.2f, 0.4f);
case ENodeType::AddMessageBranch:
if (ColorNumber == 0) return FLinearColor(0.1f, 0.1f, 0.4f);
if (ColorNumber == 1) return FLinearColor(0.1f, 0.2f, 0.4f);
case ENodeType::AddQuestPhase:
if (ColorNumber == 0) return FLinearColor(0.1f, 0.1f, 0.1f);
if (ColorNumber == 1) return FLinearColor(0.4f, 0.1f, 0.1f);
if (ColorNumber == 2) return FLinearColor(0.1f, 0.2f, 0.4f);
case ENodeType::AddScreenMessage:
return FLinearColor(0.4f, 0.1f, 0.4f);
case ENodeType::AddTargetObjectToPhase:
return FLinearColor(0.1f, 0.4f, 0.1f);
case ENodeType::CancelQuest:
return FLinearColor::Yellow;
case ENodeType::DialogEnd:
return FLinearColor(0.4f, 0.1f, 0.1f);
case ENodeType::DialogExit:
return FLinearColor(0.4f, 0.1f, 0.1f);
case ENodeType::DialogNode:
if (ColorNumber == 0) return FLinearColor(0.1f, 0.1f, 0.1f);
if (ColorNumber == 1) return FLinearColor(0.1f, 0.4f, 0.1f);
if (ColorNumber == 2) return FLinearColor(0.1f, 0.1f, 0.4f);
case ENodeType::DialogStart:
if (ColorNumber == 0) return FLinearColor(0.1f, 0.1f, 0.1f);
if (ColorNumber == 1) return FLinearColor(0.1f, 0.1f, 0.4f);
case ENodeType::EndGame:
return FLinearColor(0.4f, 0.1f, 0.1f);
case ENodeType::GetStoryGraphObjectState:
return FLinearColor(0.4f, 0.2f, 0.0f);
case ENodeType::PrintString:
return FLinearColor::Yellow;
case ENodeType::QuestStart:
if (ColorNumber == 0) return FLinearColor(0.4f, 0.1f, 0.1f);
if (ColorNumber == 1) return FLinearColor(0.1f, 0.2f, 0.4f);
case ENodeType::SendMessageScene:
return FLinearColor(0.1f, 0.4f, 0.1f);
case ENodeType::SetDialogTrigger:
return FLinearColor(0.4f, 0.2f, 0.0f);
case ENodeType::SetSceneObjectActive:
return FLinearColor(0.1f, 0.4f, 0.1f);
case ENodeType::MessageStart:
return FLinearColor(0.1f, 0.1f, 0.4f);
case ENodeType::Message:
if (ColorNumber == 0) return FLinearColor(0.1f, 0.1f, 0.1f);
if (ColorNumber == 1) return FLinearColor(0.1f, 0.4f, 0.1f);
if (ColorNumber == 2) return FLinearColor(0.1f, 0.1f, 0.4f);
case ENodeType::MessageExit:
return FLinearColor(0.4f, 0.1f, 0.1f);
case ENodeType::MessageEnd:
return FLinearColor(0.4f, 0.1f, 0.1f);
case ENodeType::ActivateTrigger:
return FLinearColor(0.4f, 0.2f, 0.0f);
case ENodeType::SetInventoryItemState:
return FLinearColor(0.1f, 0.4f, 0.1f);
case ENodeType::SetInventoryItemStateFromMessage:
return FLinearColor(0.1f, 0.4f, 0.1f);
case ENodeType::PrintQuestPhaseOnScreen:
return FLinearColor(0.1f, 0.4f, 0.1f);
case ENodeType::SendMessageToLevelBlueprint:
return FLinearColor(0.1f, 0.4f, 0.1f);
default:
return FLinearColor(0.1f, 0.1f, 0.1f);
}
}
EPerformNodeResult UCustomNodeBase::PerformNode()
{
return EPerformNodeResult::Successed;
}
FText UCustomNodeBase::GetNodeTitle() const
{
return FText::FromString(GetActionNameFromNodeType(NodeType));
}
#if WITH_EDITORONLY_DATA
void UCustomNodeBase::InitNode(UStoryGraphObject* pGraphObject_)
{
pGraphObject = pGraphObject_;
RefreshColor();
}
void UCustomNodeBase::CreatePin(FStoryGraphPin NewPin)
{
NodePins.Add(NewPin);
CreatePinDelegate.ExecuteIfBound(NewPin);
UpdateGraphNode();
}
void UCustomNodeBase::RemovePin(int32 PinNumber)
{
NodePins.RemoveAt(PinNumber);
RemovePinDelegate.ExecuteIfBound(PinNumber);
UpdateGraphNode();
}
void UCustomNodeBase::UpdateGraphNode()
{
NodeUpdateDelegate.ExecuteIfBound();
pStoryGraph->StoryGraphState = EStoryGraphState::ST_Modify;
}
void UCustomNodeBase::PostEditChangeProperty(struct FPropertyChangedEvent& e)
{
Super::PostEditChangeProperty(e);
UpdateGraphNode();
}
void UCustomNodeBase::GetXMLSavingProperty(std::map<FString, XMLProperty>& Properties)
{
Properties.clear();
Properties.insert(
std::pair<FString, XMLProperty
>("NodeType", XMLProperty(GetEnumValueAsString<ENodeType>("ENodeType", NodeType))));
if (pGraphObject)
{
Properties.insert(std::pair<FString, XMLProperty>("GraphOject", XMLProperty(pGraphObject->XMLID)));
}
else
{
Properties.insert(std::pair<FString, XMLProperty>("GraphOject", XMLProperty("Non")));
}
Properties.insert(std::pair<FString, XMLProperty>("Comment", XMLProperty(Comment)));
//Add links to another nods
Properties.insert(std::pair<FString, XMLProperty>("Arr_Pins", XMLProperty("")));
XMLProperty& PinsPointer = Properties["Arr_Pins"];
for (int i = 0; i < NodePins.Num(); i++)
{
PinsPointer.Properties.insert(
std::pair<FString, XMLProperty>("Arr_Pin" + FString::FromInt(i), XMLProperty("")));
XMLProperty& LinksPointer = PinsPointer.Properties["Arr_Pin" + FString::FromInt(i)];
if (NodePins[i].Direction == (int)EEdGraphPinDirection::EGPD_Output)
{
for (int j = 0; j < NodePins[i].Links.Num(); j++)
{
LinksPointer.Properties.insert(std::pair<FString, XMLProperty>(
"Link" + FString::FromInt(i) + FString::FromInt(j),
XMLProperty(NodePins[i].Links[j]->XMLID)));
}
}
}
}
void UCustomNodeBase::LoadPropertyFromXML(std::map<FString, XMLProperty>& Properties)
{
Comment = Properties["Comment"].Val;
RefreshColor();
}
void UCustomNodeBase::DeleteLinkToNode(UCustomNodeBase* NodeLink)
{
for (int i = 0; i < NodePins.Num(); i++)
{
for (int j = 0; j < NodePins[i].Links.Num(); j++)
{
if (NodePins[i].Links[j] == NodeLink)
{
NodePins[i].Links.RemoveAt(j);
return;
}
}
}
}
#endif //WITH_EDITORONLY_DATA
//UDialogNodeBase...........................................................................................
FText UDialogNodeBase::GetDialogName(FText Dialog)
{
return FText::FromString(Dialog.ToString().Left(18));
}
bool UDialogNodeBase::GetChildNode(const UDialogObject* CurrentDialog, UDialogNodeBase*& NextNode)
{
if (!CurrentDialog)
{
NextNode = (UDialogNodeBase*)GetFistChildNode();
return true;
}
else
{
for (int j = 0; j < NodePins[CurrentDialog->CurrentDialogPin].Links.Num(); j++)
{
if (NodePins[CurrentDialog->CurrentDialogPin].Links[j])
{
NextNode = (UDialogNodeBase*)NodePins[CurrentDialog->CurrentDialogPin].Links[j];
return true;
}
}
}
return false;
}
#if WITH_EDITORONLY_DATA
void UDialogNodeBase::RefreshDialogOwner()
{
TArray<UCustomNodeBase*> InputNodes;
GetInputNodes(InputNodes, EPinDataTypes::PinType_Horizontal);
if (InputNodes.Num() > 0)
{
UDialogNodeBase* AnotherDialogNodeBase = Cast<UDialogNodeBase>(InputNodes[0]);
if (AnotherDialogNodeBase->DialogOwner == ECharDialogOwner::NotDefine)
{
TopDialog = nullptr;
DialogOwner = ECharDialogOwner::NotDefine;
}
else if (AnotherDialogNodeBase->DialogOwner == ECharDialogOwner::Character)
{
TopDialog = AnotherDialogNodeBase->TopDialog;
DialogOwner = ECharDialogOwner::Character;
}
else if (AnotherDialogNodeBase->DialogOwner == ECharDialogOwner::NPC)
{
TopDialog = AnotherDialogNodeBase->TopDialog;
DialogOwner = ECharDialogOwner::NPC;
}
}
else
{
TopDialog = nullptr;
DialogOwner = ECharDialogOwner::NotDefine;
}
UpdateGraphNode();
TArray<UCustomNodeBase*> ChildNodes;
GetChildNodes(ChildNodes, EPinDataTypes::PinType_Horizontal);
for (int j = 0; j < ChildNodes.Num(); j++)
{
((UDialogNodeBase*)ChildNodes[j])->RefreshDialogOwner();
}
}
void UDialogNodeBase::PinConnectionListChanged(FStoryGraphPin* Pin)
{
Super::PinConnectionListChanged(Pin);
if (Pin->Direction == EEdGraphPinDirection::EGPD_Input)
{
RefreshDialogOwner();
}
}
void UDialogNodeBase::AddDialog()
{
UDialogObject* NewDialog = NewObject<UDialogObject>(this, UDialogObject::StaticClass());
NewDialog->DialogNode = this;
NewDialog->Dialog = FText::FromString("New dialog");
NewDialog->CurrentDialogPin = Dialogs.Add(NewDialog) + 1;
CreatePin(FStoryGraphPin(EGPD_Output, EPinDataTypes::PinType_Horizontal));
UpdateGraphNode(); //Update graph node
}
void UDialogNodeBase::GetXMLSavingProperty(std::map<FString, XMLProperty>& Properties)
{
Super::GetXMLSavingProperty(Properties);
Properties.insert(std::pair<FString, XMLProperty>("Arr_Dialogs", XMLProperty("")));
XMLProperty& DialogsPointer = Properties["Arr_Dialogs"];
for (int i = 0; i < Dialogs.Num(); i++)
{
DialogsPointer.Properties.insert(
std::pair<FString, XMLProperty>("Dialog_" + FString::FromInt(i),
XMLProperty(Dialogs[i]->Dialog.ToString())));
}
}
void UDialogNodeBase::LoadPropertyFromXML(std::map<FString, XMLProperty>& Properties)
{
if (Properties["Arr_Dialogs"].Properties.size() > 1)
{
for (int i = 0; i < Properties["Arr_Dialogs"].Properties.size() - 1; i++)
{
AddDialog();
}
}
int i = 0;
for (auto it = Properties["Arr_Dialogs"].Properties.begin(); it != Properties["Arr_Dialogs"].Properties.end(); ++it)
{
Dialogs[i++]->Dialog = FText::FromString(it->second.Val);
}
Super::LoadPropertyFromXML(Properties);
}
#endif //WITH_EDITORONLY_DATA
//UStoryVerticalNodeBase...........................................................................................
void UStoryVerticalNodeBase::ResetUnPerformBrunch()
{
TArray<UCustomNodeBase*> InputNodes;
GetInputNodes(InputNodes, EPinDataTypes::PinType_Vertical);
bPerformNode = true;
for (int i = 0; i < InputNodes.Num(); i++)
{
if (!((UStoryVerticalNodeBase*)InputNodes[i])->bPerformNode)
{
((UStoryVerticalNodeBase*)InputNodes[i])->ResetUnPerformBrunch();
}
}
}
EPerformNodeResult UStoryVerticalNodeBase::PerformNode()
{
Super::PerformNode();
TArray<UCustomNodeBase*> ChildNodes;
GetChildNodes(ChildNodes, EPinDataTypes::PinType_Horizontal);
for (int i = 0; i < ChildNodes.Num(); i++)
{
(ChildNodes[i])->PerformNode();
}
return EPerformNodeResult::Successed;
}
#if WITH_EDITORONLY_DATA
void UStoryVerticalNodeBase::RefreshQuestOwner()
{
TArray<UCustomNodeBase*> InputNodes;
GetInputNodes(InputNodes, EPinDataTypes::PinType_Vertical);
if (InputNodes.Num() > 0)
{
UStoryVerticalNodeBase* AnotherVerticalNodeBase = Cast<UStoryVerticalNodeBase>(InputNodes[0]);
//Refresh quest phase
pQuestPhase = AnotherVerticalNodeBase->pQuestPhase;
//Refresh Quest owner
pQuestOwner = AnotherVerticalNodeBase->pQuestOwner;
}
else
{
pQuestOwner = nullptr;
pQuestPhase = nullptr;
}
RefreshColor();
UpdateGraphNode();
TArray<UCustomNodeBase*> ChildNodes;
GetChildNodes(ChildNodes, EPinDataTypes::PinType_Vertical);
for (int i = 0; i < ChildNodes.Num(); i++)
{
((UStoryVerticalNodeBase*)ChildNodes[i])->RefreshQuestOwner();
}
}
void UStoryVerticalNodeBase::PinConnectionListChanged(FStoryGraphPin* Pin)
{
Super::PinConnectionListChanged(Pin);
if (Pin->Direction == (int)EEdGraphPinDirection::EGPD_Input && Pin->PinDataType == (int)EPinDataTypes::
PinType_Vertical)
{
RefreshQuestOwner();
}
}
#endif //WITH_EDITORONLY_DATA
//UStoryHorizontalNodeBase...........................................................................................
EPerformNodeResult UStoryHorizontalNodeBase::PerformNode()
{
Super::PerformNode();
TArray<UCustomNodeBase*> ChildNodes;
GetChildNodes(ChildNodes, EPinDataTypes::PinType_Horizontal);
for (int i = 0; i < ChildNodes.Num(); i++)
{
(ChildNodes[i])->PerformNode();
}
return EPerformNodeResult::Successed;
}
#if WITH_EDITORONLY_DATA
void UStoryHorizontalNodeBase::RefreshQuestPhase()
{
TArray<UCustomNodeBase*> InputNodes;
GetInputNodes(InputNodes, EPinDataTypes::PinType_Horizontal);
if (InputNodes.Num() > 0) //we have input links
{
UStoryVerticalNodeBase* VerticalNode = Cast<UStoryVerticalNodeBase>(InputNodes[0]);
UStoryHorizontalNodeBase* HorizontalNode = Cast<UStoryHorizontalNodeBase>(InputNodes[0]);
if (VerticalNode)
{
pQuestPhase = VerticalNode->pQuestPhase;
}
else if (HorizontalNode)
{
pQuestPhase = HorizontalNode->pQuestPhase;
}
}
else
{
pQuestPhase = nullptr;
}
//Update out nods
TArray<UCustomNodeBase*> ChildNodes;
GetChildNodes(ChildNodes, EPinDataTypes::PinType_Horizontal);
for (int j = 0; j < ChildNodes.Num(); j++)
{
((UStoryHorizontalNodeBase*)ChildNodes[j])->RefreshQuestPhase();
}
OwnedQuestPhase = pQuestPhase ? UDialogNodeBase::GetDialogName(pQuestPhase->Description).ToString() : "Non";
}
void UStoryHorizontalNodeBase::PinConnectionListChanged(FStoryGraphPin* Pin)
{
Super::PinConnectionListChanged(Pin);
if (Pin->Direction == (int)EEdGraphPinDirection::EGPD_Input && Pin->PinDataType == (int)EPinDataTypes::
PinType_Horizontal)
{
RefreshQuestPhase();
}
}
#endif //WITH_EDITORONLY_DATA
//UAddQuestPhaseNode...........................................................................................
UAddQuestPhaseNode::UAddQuestPhaseNode()
{
NodeType = ENodeType::AddQuestPhase;
NodePins.Add(FStoryGraphPin(EEdGraphPinDirection::EGPD_Input, EPinDataTypes::PinType_Vertical));
NodePins.Add(FStoryGraphPin(EEdGraphPinDirection::EGPD_Output, EPinDataTypes::PinType_Horizontal));
NodePins.Add(FStoryGraphPin(EEdGraphPinDirection::EGPD_Output, EPinDataTypes::PinType_Vertical));
}
EPerformNodeResult UAddQuestPhaseNode::PerformNode()
{
Super::PerformNode();
if (bPerformNode)
{
return EPerformNodeResult::NodeAlreadyPerformed;
}
else
{
if (!IsEmpty)
{
(QuestPhaseToAdd->pOwnedQuest)->AddPhase(QuestPhaseToAdd);
}
bPerformNode = true;
return EPerformNodeResult::Successed;
}
}
FText UAddQuestPhaseNode::GetNodeTitle() const
{
if (IsEmpty)
{
return FText::FromString("Empty phase");
}
return UDialogNodeBase::GetDialogName(QuestPhaseToAdd->Description);
}
#if WITH_EDITORONLY_DATA
void UAddQuestPhaseNode::InitNode(UStoryGraphObject* pGraphObject_)
{
Super::InitNode(pGraphObject_);
QuestPhaseToAdd = NewObject<UQuestPhase>(this, UQuestPhase::StaticClass());
QuestPhaseToAdd->Description = FText::FromString("New Quest Phase");
pQuestPhase = QuestPhaseToAdd;
}
void UAddQuestPhaseNode::SetQuestPhase(FText NewQuestPhase)
{
QuestPhaseToAdd->Description = NewQuestPhase;
UpdateGraphNode();
}
void UAddQuestPhaseNode::RefreshColor()
{
if (pQuestOwner)
{
if (pQuestOwner->MainQuest)
{
NodeColor = UCustomNodeBase::GetColorFromNodeType(ENodeType::AddQuestPhase, 1);
}
else
{
NodeColor = UCustomNodeBase::GetColorFromNodeType(ENodeType::AddQuestPhase, 2);
}
}
else
{
NodeColor = UCustomNodeBase::GetColorFromNodeType(ENodeType::AddQuestPhase, 0);
}
}
void UAddQuestPhaseNode::PinConnectionListChanged(FStoryGraphPin* Pin)
{
Super::PinConnectionListChanged(Pin);
PropertyUpdateDelegate.ExecuteIfBound();
}
void UAddQuestPhaseNode::RefreshQuestOwner()
{
if (IsEmpty)
{
Super::RefreshQuestOwner();
RefreshColor();
UpdateGraphNode();
return;
}
//Refresh quest phase
pQuestPhase = QuestPhaseToAdd;
TArray<UCustomNodeBase*> InputNodes;
GetInputNodes(InputNodes, EPinDataTypes::PinType_Vertical);
if (InputNodes.Num() > 0)
{
UStoryVerticalNodeBase* AnotherVerticalNode = Cast<UStoryVerticalNodeBase>(InputNodes[0]);
//Refresh Quest owner
pQuestOwner = AnotherVerticalNode->pQuestOwner;
}
else
{
pQuestOwner = nullptr;
}
QuestPhaseToAdd->pOwnedQuest = pQuestOwner;
RefreshColor();
UpdateGraphNode();
//Update out nods
TArray<UCustomNodeBase*> ChildNodes;
GetChildNodes(ChildNodes, EPinDataTypes::PinType_Vertical);
for (int i = 0; i < ChildNodes.Num(); i++)
{
((UStoryVerticalNodeBase*)ChildNodes[i])->RefreshQuestOwner();
}
}
void UAddQuestPhaseNode::GetXMLSavingProperty(std::map<FString, XMLProperty>& Properties)
{
Super::GetXMLSavingProperty(Properties);
Properties.insert(
std::pair<FString, XMLProperty>("QuestPhaseToAdd", XMLProperty(QuestPhaseToAdd->Description.ToString())));
Properties.insert(std::pair<FString, XMLProperty>("IsEmpty", XMLProperty(IsEmpty ? "true" : "false")));
}
void UAddQuestPhaseNode::LoadPropertyFromXML(std::map<FString, XMLProperty>& Properties)
{
QuestPhaseToAdd->Description = FText::FromString(Properties["QuestPhaseToAdd"].Val);
IsEmpty = Properties["IsEmpty"].Val == "true";
Super::LoadPropertyFromXML(Properties);
}
#endif //WITH_EDITORONLY_DATA
//UDialogStartNode...........................................................................................
UDialogStartNode::UDialogStartNode()
{
NodeType = ENodeType::DialogStart;
DialogOwner = ECharDialogOwner::Character;
IsActive = true;
NodePins.Add(FStoryGraphPin(EEdGraphPinDirection::EGPD_Output, EPinDataTypes::PinType_Horizontal));
}
#if WITH_EDITORONLY_DATA
void UDialogStartNode::InitNode(UStoryGraphObject* pGraphObject_)
{
Super::InitNode(pGraphObject_);
Dialogs.Add(NewObject<UDialogObject>(this, UDialogObject::StaticClass()));
Dialogs[0]->DialogNode = this;
Dialogs[0]->Dialog = FText::FromString("Enter text");
Dialogs[0]->CurrentDialogPin = 0;
TopDialog = Dialogs[0];
}
void UDialogStartNode::SetNewDialog(FText NewDialog)
{
Dialogs[0]->Dialog = NewDialog;
UpdateGraphNode(); //Refresh node
for (int i = 0; i < pStoryGraph->GraphNodes.Num(); i++)
{
if (pStoryGraph->GraphNodes[i]->NodeType == ENodeType::AddDialog)
{
pStoryGraph->GraphNodes[i]->UpdateGraphNode(); //Refresh all USetQuestStateNode nodes
}
}
}
void UDialogStartNode::RefreshColor()
{
Super::RefreshColor();
NodeColor = IsActive
? UCustomNodeBase::GetColorFromNodeType(ENodeType::DialogStart, 1)
: UCustomNodeBase::GetColorFromNodeType(ENodeType::DialogStart, 0);
UpdateGraphNode();
}
void UDialogStartNode::RefreshDialogOwner()
{
if (!TopDialog)
{
TopDialog = Dialogs[0];
}
Super::RefreshDialogOwner();
}
void UDialogStartNode::GetXMLSavingProperty(std::map<FString, XMLProperty>& Properties)
{
Super::GetXMLSavingProperty(Properties);
Properties.insert(std::pair<FString, XMLProperty>("IsActive", IsActive ? "true" : "false"));
Properties.insert(std::pair<FString, XMLProperty>("DialogPriority", XMLProperty(FString::FromInt(DialogPriority))));
}
void UDialogStartNode::LoadPropertyFromXML(std::map<FString, XMLProperty>& Properties)
{
IsActive = Properties["IsActive"].Val == "true";
DialogPriority = FCString::Atoi(*Properties["DialogPriority"].Val);
Super::LoadPropertyFromXML(Properties);
}
#endif //WITH_EDITORONLY_DATA
//UDialogNode...........................................................................................
UDialogNode::UDialogNode()
{
NodeType = ENodeType::DialogNode;
TopDialog = nullptr;
DialogOwner = ECharDialogOwner::NotDefine;
NodePins.Add(FStoryGraphPin(EEdGraphPinDirection::EGPD_Input, EPinDataTypes::PinType_Horizontal));
NodePins.Add(FStoryGraphPin(EEdGraphPinDirection::EGPD_Output, EPinDataTypes::PinType_Horizontal));
}
#if WITH_EDITORONLY_DATA
void UDialogNode::InitNode(UStoryGraphObject* pGraphObject_)
{
Super::InitNode(pGraphObject_);
Dialogs.Add(NewObject<UDialogObject>(this, UDialogObject::StaticClass()));
Dialogs[0]->DialogNode = this;
Dialogs[0]->Dialog = FText::FromString("Enter text");
Dialogs[0]->CurrentDialogPin = 1;
}
void UDialogNode::RefreshColor()
{
TArray<UCustomNodeBase*> InputNodes;
GetInputNodes(InputNodes, EPinDataTypes::PinType_Horizontal);
if (InputNodes.Num() > 0)
{
UDialogNodeBase* AnotherDialogNodeBase = Cast<UDialogNodeBase>(InputNodes[0]);
if (AnotherDialogNodeBase->DialogOwner == ECharDialogOwner::Character)
{
NodeColor = UCustomNodeBase::GetColorFromNodeType(ENodeType::DialogNode, 1);
}
else if (AnotherDialogNodeBase->DialogOwner == ECharDialogOwner::NPC)
{
NodeColor = UCustomNodeBase::GetColorFromNodeType(ENodeType::DialogNode, 2);
}
}
else
{
NodeColor = UCustomNodeBase::GetColorFromNodeType(ENodeType::DialogNode, 0);
}
}
void UDialogNode::RefreshDialogOwner()
{
TArray<UCustomNodeBase*> InputNodes;
GetInputNodes(InputNodes, EPinDataTypes::PinType_Horizontal);
if (InputNodes.Num() > 0)
{
UDialogNodeBase* AnotherDialogNodeBase = Cast<UDialogNodeBase>(InputNodes[0]);
if (AnotherDialogNodeBase->DialogOwner == ECharDialogOwner::NotDefine)
{
TopDialog = nullptr;
DialogOwner = ECharDialogOwner::NotDefine;
}
else if (AnotherDialogNodeBase->DialogOwner == ECharDialogOwner::Character)
{
TopDialog = AnotherDialogNodeBase->TopDialog;
DialogOwner = ECharDialogOwner::NPC;
}
else if (AnotherDialogNodeBase->DialogOwner == ECharDialogOwner::NPC)
{
TopDialog = AnotherDialogNodeBase->TopDialog;
DialogOwner = ECharDialogOwner::Character;
}
}
else
{
TopDialog = nullptr;
DialogOwner = ECharDialogOwner::NotDefine;
}
PropertyUpdateDelegate.ExecuteIfBound();
//Remove links from hidden pins
UCustomNodeBase* LinkToNode;
if (DialogOwner == ECharDialogOwner::NPC)
{
for (int i = 2; i < NodePins.Num(); i++)
{
LinkToNode = nullptr;
if (NodePins[i].Links.Num() > 0) LinkToNode = NodePins[i].Links[0];
BreakPinDelegate.ExecuteIfBound(i);
if (LinkToNode) ((UDialogNodeBase*)LinkToNode)->RefreshDialogOwner();
}
}
RefreshColor();
UpdateGraphNode();
//Update out nods
TArray<UCustomNodeBase*> ChildNodes;
GetChildNodes(ChildNodes, EPinDataTypes::PinType_Horizontal);
for (int j = 0; j < ChildNodes.Num(); j++)
{
((UDialogNodeBase*)ChildNodes[j])->RefreshDialogOwner();
}
}
#endif //WITH_EDITORONLY_DATA
//UDialogEndNode...................................................................
UDialogEndNode::UDialogEndNode()
{
NodeType = ENodeType::DialogEnd;
NodePins.Add(FStoryGraphPin(EEdGraphPinDirection::EGPD_Input, EPinDataTypes::PinType_Horizontal));
NodePins.Add(FStoryGraphPin(EEdGraphPinDirection::EGPD_Output, EPinDataTypes::PinType_Horizontal));
}
EPerformNodeResult UDialogEndNode::PerformNode()
{
Super::PerformNode();
if (TopDialog)
{
((UDialogStartNode*)TopDialog->DialogNode)->IsActive = false;
}
else
{
UE_LOG(LogCategoryStoryGraphPluginRuntime, Warning, TEXT("Top dialog non"));
}
return EPerformNodeResult::Successed;
}
//UDialogExitNode...................................................................
UDialogExitNode::UDialogExitNode()
{
NodeType = ENodeType::DialogExit;
NodePins.Add(FStoryGraphPin(EEdGraphPinDirection::EGPD_Input, EPinDataTypes::PinType_Horizontal));
}
EPerformNodeResult UDialogExitNode::PerformNode()
{
Super::PerformNode();
if (pStoryGraph && pStoryGraph->OwnedActor)
{
AHUD_StoryGraph* HUD = Cast<AHUD_StoryGraph>(
pStoryGraph->OwnedActor->GetWorld()->GetFirstPlayerController()->GetHUD());
if (HUD)
{
HUD->OpenDialogEvent(false);
}
else
{
UE_LOG(LogCategoryStoryGraphPluginRuntime, Warning, TEXT("Your HUD should inherit AHUD_StoryGraph class"));
}
}
return EPerformNodeResult::Successed;
}
//USetDialogTriggerNode............................................................................
USetDialogTriggerNode::USetDialogTriggerNode()
{
NodeType = ENodeType::SetDialogTrigger;
NodePins.Add(FStoryGraphPin(EEdGraphPinDirection::EGPD_Input, EPinDataTypes::PinType_Horizontal));
NodePins.Add(FStoryGraphPin(EEdGraphPinDirection::EGPD_Output, EPinDataTypes::PinType_Horizontal));
}
EPerformNodeResult USetDialogTriggerNode::PerformNode()
{
Super::PerformNode();
pGraphObject->SetCurrentState((int)TriggerState);
return EPerformNodeResult::Successed;
}
FText USetDialogTriggerNode::GetNodeTitle() const
{
return FText::FromString(GetEnumValueAsString<EDialogTriggerStates>("EDialogTriggerStates", TriggerState));
}
#if WITH_EDITORONLY_DATA
void USetDialogTriggerNode::GetXMLSavingProperty(std::map<FString, XMLProperty>& Properties)
{
Super::GetXMLSavingProperty(Properties);
Properties.insert(
std::pair<FString, XMLProperty>("TriggerState", XMLProperty(FString::FromInt((int)TriggerState))));
}
void USetDialogTriggerNode::LoadPropertyFromXML(std::map<FString, XMLProperty>& Properties)
{
TriggerState = (EDialogTriggerStates)FCString::Atoi(*Properties["TriggerState"].Val);
Super::LoadPropertyFromXML(Properties);
}
#endif //WITH_EDITORONLY_DATA
//USetSceneObjectActiveNode...................................................................
USetSceneObjectActiveNode::USetSceneObjectActiveNode()
{
NodeType = ENodeType::SetSceneObjectActive;
NodePins.Add(FStoryGraphPin(EEdGraphPinDirection::EGPD_Input, EPinDataTypes::PinType_Horizontal));
NodePins.Add(FStoryGraphPin(EEdGraphPinDirection::EGPD_Output, EPinDataTypes::PinType_Horizontal));
}
EPerformNodeResult USetSceneObjectActiveNode::PerformNode()
{
Super::PerformNode();
((UStoryGraphObjectWithSceneObject*)pGraphObject)->SetSceneObjectActive(IsActive);
return EPerformNodeResult::Successed;
}
FText USetSceneObjectActiveNode::GetNodeTitle() const
{
return IsActive ? FText::FromString("Active") : FText::FromString("Unactive");
}
#if WITH_EDITORONLY_DATA
void USetSceneObjectActiveNode::GetXMLSavingProperty(std::map<FString, XMLProperty>& Properties)
{
Super::GetXMLSavingProperty(Properties);
Properties.insert(std::pair<FString, XMLProperty>("IsActive", XMLProperty(IsActive ? "true" : "false")));
}
void USetSceneObjectActiveNode::LoadPropertyFromXML(std::map<FString, XMLProperty>& Properties)
{
IsActive = Properties["IsActive"].Val == "true";
Super::LoadPropertyFromXML(Properties);
}
#endif //WITH_EDITORONLY_DATA
//UGetStoryGraphObjectNode.................................................................
UGetStoryGraphObjectStateNode::UGetStoryGraphObjectStateNode()
{
NodeType = ENodeType::GetStoryGraphObjectState;
WantedObjectState = 0;
NodePins.Add(FStoryGraphPin(EEdGraphPinDirection::EGPD_Input, EPinDataTypes::PinType_Vertical));
NodePins.Add(FStoryGraphPin(EEdGraphPinDirection::EGPD_Output, EPinDataTypes::PinType_Vertical));
}
EPerformNodeResult UGetStoryGraphObjectStateNode::PerformNode()
{
Super::PerformNode();
UStoryGraphInventoryItem* InventoryItem = Cast<UStoryGraphInventoryItem>(pGraphObject);
if (bPerformNode)
{
return EPerformNodeResult::NodeAlreadyPerformed;
}
if (pGraphObject->GetCurrentState() == WantedObjectState)
{
bPerformNode = true;
return EPerformNodeResult::Successed;
}
else
{
return EPerformNodeResult::Fail;
}
}
FText UGetStoryGraphObjectStateNode::GetNodeTitle() const
{
TArray<FString> ObjectStates;
if (pGraphObject)
{
pGraphObject->GetObjectStateAsString(ObjectStates);
if (ObjectStates.Num() > 0) return FText::FromString(ObjectStates[WantedObjectState]);
else return FText::FromString("Non");
}
else
{
return FText::FromString("Non");
}
}
void UGetStoryGraphObjectStateNode::SetWantedObjectState(int WantedState_)
{
WantedObjectState = WantedState_;
#if WITH_EDITORONLY_DATA
UpdateGraphNode();
#endif //WITH_EDITORONLY_DATA
}
#if WITH_EDITORONLY_DATA
void UGetStoryGraphObjectStateNode::GetXMLSavingProperty(std::map<FString, XMLProperty>& Properties)
{
Super::GetXMLSavingProperty(Properties);
Properties.insert(
std::pair<FString, XMLProperty>("WantedObjectState", XMLProperty(FString::FromInt(WantedObjectState))));
}
void UGetStoryGraphObjectStateNode::LoadPropertyFromXML(std::map<FString, XMLProperty>& Properties)
{
WantedObjectState = FCString::Atoi(*Properties["WantedObjectState"].Val);
Super::LoadPropertyFromXML(Properties);
}
#endif //WITH_EDITORONLY_DATA
//UAddDialogNode...........................................................................................
UAddDialogNode::UAddDialogNode()
{
NodeType = ENodeType::AddDialog;
Activate = true;
NodePins.Add(FStoryGraphPin(EEdGraphPinDirection::EGPD_Input, EPinDataTypes::PinType_Horizontal));
NodePins.Add(FStoryGraphPin(EEdGraphPinDirection::EGPD_Output, EPinDataTypes::PinType_Horizontal));
}
EPerformNodeResult UAddDialogNode::PerformNode()
{
Super::PerformNode();
SelectedDialog->IsActive = Activate;
return EPerformNodeResult::Successed;
}
FText UAddDialogNode::GetNodeTitle() const
{
return SelectedDialog && SelectedDialog->Dialogs.Num() > 0
? UDialogNodeBase::GetDialogName(SelectedDialog->Dialogs[0]->Dialog)
: FText::FromString("Not Defined");
}
#if WITH_EDITORONLY_DATA
void UAddDialogNode::SetCurrentDialog(UDialogStartNode* SelectedDialog_)
{
SelectedDialog = SelectedDialog_;
UpdateGraphNode();
}
void UAddDialogNode::RefreshColor()
{
if (Activate)
{
NodeColor = UCustomNodeBase::GetColorFromNodeType(ENodeType::AddDialog, 0);
}
else
{
NodeColor = UCustomNodeBase::GetColorFromNodeType(ENodeType::AddDialog, 1);
}
}
void UAddDialogNode::GetXMLSavingProperty(std::map<FString, XMLProperty>& Properties)
{
Super::GetXMLSavingProperty(Properties);
Properties.insert(std::pair<FString, XMLProperty>("SelectedDialog", XMLProperty(SelectedDialog->XMLID)));
Properties.insert(std::pair<FString, XMLProperty>("Activate", XMLProperty(Activate ? "true" : "false")));
}
void UAddDialogNode::LoadPropertyFromXML(std::map<FString, XMLProperty>& Properties)
{
int32 SignNum = Properties["SelectedDialog"].Val.Find("_");
UStoryGraphObject* CurrentStoryGarphObject = pStoryGraph->GraphObjects[FCString::Atoi(
*Properties["SelectedDialog"].Val.Left(SignNum))];
if (UStoryGraphCharacter* pStoryGraphCharecter = Cast<UStoryGraphCharacter>(CurrentStoryGarphObject))
{
SelectedDialog = (UDialogStartNode*)pStoryGraphCharecter->GraphNodes[FCString::Atoi(
*Properties["SelectedDialog"].Val.RightChop(SignNum + 1))];
}
else if (UStoryGraphPlaceTrigger* pStoryGraphPlaceTrigger = Cast<UStoryGraphPlaceTrigger>(CurrentStoryGarphObject))
{
SelectedDialog = (UDialogStartNode*)pStoryGraphPlaceTrigger->GraphNodes[FCString::Atoi(
*Properties["SelectedDialog"].Val.RightChop(SignNum + 1))];
}
Activate = Properties["Activate"].Val == "true";
Super::LoadPropertyFromXML(Properties);
}
#endif //WITH_EDITORONLY_DATA
//UAddDialogFromDialogNode...........................................................................................
UAddDialogFromDialogNode::UAddDialogFromDialogNode()
{
NodeType = ENodeType::AddDialogFromDialog;
Activate = true;
NodePins.Add(FStoryGraphPin(EEdGraphPinDirection::EGPD_Input, EPinDataTypes::PinType_Horizontal));
NodePins.Add(FStoryGraphPin(EEdGraphPinDirection::EGPD_Output, EPinDataTypes::PinType_Horizontal));
}
EPerformNodeResult UAddDialogFromDialogNode::PerformNode()
{
Super::PerformNode();
SelectedDialog->IsActive = Activate;
return EPerformNodeResult::Successed;
}
FText UAddDialogFromDialogNode::GetNodeTitle() const
{
return SelectedDialog && SelectedDialog->Dialogs.Num() > 0
? UDialogNodeBase::GetDialogName(SelectedDialog->Dialogs[0]->Dialog)
: FText::FromString("Not Defind");
}
void UAddDialogFromDialogNode::SetCurrentDialog(UDialogStartNode* SelectedDialog_)
{
SelectedDialog = SelectedDialog_;
#if WITH_EDITORONLY_DATA
UpdateGraphNode();
#endif //WITH_EDITORONLY_DATA
}
#if WITH_EDITORONLY_DATA
void UAddDialogFromDialogNode::GetXMLSavingProperty(std::map<FString, XMLProperty>& Properties)
{
Super::GetXMLSavingProperty(Properties);
Properties.insert(std::pair<FString, XMLProperty>("SelectedDialog", XMLProperty(SelectedDialog->XMLID)));
Properties.insert(std::pair<FString, XMLProperty>("Activate", XMLProperty(Activate ? "true" : "false")));
}
void UAddDialogFromDialogNode::LoadPropertyFromXML(std::map<FString, XMLProperty>& Properties)
{
int32 SignNum = Properties["SelectedDialog"].Val.Find("_");
UStoryGraphObject* CurrentStoryGarphObject = pStoryGraph->GraphObjects[FCString::Atoi(
*Properties["SelectedDialog"].Val.Left(SignNum))];
if (UStoryGraphCharacter* pStoryGraphCharecter = Cast<UStoryGraphCharacter>(CurrentStoryGarphObject))
{
SelectedDialog = (UDialogStartNode*)pStoryGraphCharecter->GraphNodes[FCString::Atoi(
*Properties["SelectedDialog"].Val.RightChop(SignNum + 1))];
}
else if (UStoryGraphPlaceTrigger* pStoryGraphPlaceTrigger = Cast<UStoryGraphPlaceTrigger>(CurrentStoryGarphObject))
{
SelectedDialog = (UDialogStartNode*)pStoryGraphPlaceTrigger->GraphNodes[FCString::Atoi(
*Properties["SelectedDialog"].Val.RightChop(SignNum + 1))];
}
Activate = Properties["Activate"].Val == "true";
Super::LoadPropertyFromXML(Properties);
}
#endif //WITH_EDITORONLY_DATA
//UCancelQuestNode.............................................................................................
UCancelQuestNode::UCancelQuestNode()
{
NodeType = ENodeType::CancelQuest;
NodePins.Add(FStoryGraphPin(EEdGraphPinDirection::EGPD_Input, EPinDataTypes::PinType_Horizontal));
NodePins.Add(FStoryGraphPin(EEdGraphPinDirection::EGPD_Output, EPinDataTypes::PinType_Horizontal));
}
EPerformNodeResult UCancelQuestNode::PerformNode()
{
Super::PerformNode();
((UStoryGraphQuest*)pGraphObject)->SetCurrentState((int)EQuestStates::Canceled);
return EPerformNodeResult::Successed;
}
//UQuestStartNode.......................................................................................................
UQuestStartNode::UQuestStartNode()
{
NodeType = ENodeType::QuestStart;
NodePins.Add(FStoryGraphPin(EEdGraphPinDirection::EGPD_Output, EPinDataTypes::PinType_Vertical));
NodePins.Add(FStoryGraphPin(EEdGraphPinDirection::EGPD_Output, EPinDataTypes::PinType_Horizontal));
}
FText UQuestStartNode::GetNodeTitle() const
{
return FText::FromString("Start");
}
#if WITH_EDITORONLY_DATA
void UQuestStartNode::InitNode(class UStoryGraphObject* pGraphObject_)
{
Super::InitNode(pGraphObject_);
pQuestOwner = (UStoryGraphQuest*)pGraphObject_;
}
void UQuestStartNode::RefreshColor()
{
UStoryGraphQuest* Quest = Cast<UStoryGraphQuest>(pGraphObject);
if (Quest)
{
NodeColor = Quest->MainQuest
? UCustomNodeBase::GetColorFromNodeType(ENodeType::QuestStart, 0)
: NodeColor = UCustomNodeBase::GetColorFromNodeType(ENodeType::QuestStart, 1);
UpdateGraphNode();
}
}
void UQuestStartNode::RefreshQuestOwner()
{
pQuestOwner = (UStoryGraphQuest*)pGraphObject;
RefreshColor();
UpdateGraphNode();
TArray<UCustomNodeBase*> ChildNodes;
GetChildNodes(ChildNodes, EPinDataTypes::PinType_Vertical);
for (int i = 0; i < ChildNodes.Num(); i++)
{
((UStoryVerticalNodeBase*)ChildNodes[i])->RefreshQuestOwner();
}
}
#endif //WITH_EDITORONLY_DATA
//UEndGameNode..................................................................................................................
UEndGameNode::UEndGameNode()
{
NodeType = ENodeType::EndGame;
NodePins.Add(FStoryGraphPin(EEdGraphPinDirection::EGPD_Input, EPinDataTypes::PinType_Vertical));
}
EPerformNodeResult UEndGameNode::PerformNode()
{
Super::PerformNode();
if (pStoryGraph && pStoryGraph->OwnedActor)
{
if (AHUD_StoryGraph* HUD = Cast<AHUD_StoryGraph>(
pStoryGraph->OwnedActor->GetWorld()->GetFirstPlayerController()->GetHUD()))
{
HUD->EndGame(pQuestPhase->Description);
}
else
{
UE_LOG(LogCategoryStoryGraphPluginRuntime, Warning, TEXT("Your HUD should inherit AHUD_StoryGraph class"));
}
}
return EPerformNodeResult::Successed;
}
#if WITH_EDITORONLY_DATA
void UEndGameNode::RefreshColor()
{
if (pQuestOwner)
{
if (pQuestOwner->MainQuest)
{
NodeColor = UCustomNodeBase::GetColorFromNodeType(ENodeType::AddQuestPhase, 1);
}
else
{
NodeColor = UCustomNodeBase::GetColorFromNodeType(ENodeType::AddQuestPhase, 2);
}
}
else
{
NodeColor = UCustomNodeBase::GetColorFromNodeType(ENodeType::AddQuestPhase, 0);
}
}
#endif //WITH_EDITORONLY_DATA
//USendMessageNode..................................................................................................................
USendMessageNode::USendMessageNode()
{
NodeType = ENodeType::SendMessageScene;
NodePins.Add(FStoryGraphPin(EEdGraphPinDirection::EGPD_Input, EPinDataTypes::PinType_Horizontal));
NodePins.Add(FStoryGraphPin(EEdGraphPinDirection::EGPD_Output, EPinDataTypes::PinType_Horizontal));
}
EPerformNodeResult USendMessageNode::PerformNode()
{
Super::PerformNode();
((UStoryGraphObjectWithSceneObject*)pGraphObject)->SendMessageToSceneObject(Message);
return EPerformNodeResult::Successed;
}
FText USendMessageNode::GetNodeTitle() const
{
return FText::FromString("Msg: " + Message);
}
#if WITH_EDITORONLY_DATA
void USendMessageNode::GetXMLSavingProperty(std::map<FString, XMLProperty>& Properties)
{
Super::GetXMLSavingProperty(Properties);
Properties.insert(std::pair<FString, XMLProperty>("Message", XMLProperty(Message)));
}
void USendMessageNode::LoadPropertyFromXML(std::map<FString, XMLProperty>& Properties)
{
Message = Properties["Message"].Val;
Super::LoadPropertyFromXML(Properties);
}
#endif //WITH_EDITORONLY_DATA
//UPrintStringNode..................................................................................................................
UPrintStringNode::UPrintStringNode()
{
NodeType = ENodeType::PrintString;
InString = "Hello";
PrintToScreen = true;
PrintToLog = true;
Duration = 2.0;
TextColor = FColor::Blue;
NodePins.Add(FStoryGraphPin(EEdGraphPinDirection::EGPD_Input, EPinDataTypes::PinType_Horizontal));
NodePins.Add(FStoryGraphPin(EEdGraphPinDirection::EGPD_Output, EPinDataTypes::PinType_Horizontal));
NodePins.Add(FStoryGraphPin(EEdGraphPinDirection::EGPD_Input, EPinDataTypes::PinType_Vertical));
NodePins.Add(FStoryGraphPin(EEdGraphPinDirection::EGPD_Output, EPinDataTypes::PinType_Vertical));
}
EPerformNodeResult UPrintStringNode::PerformNode()
{
Super::PerformNode();
if (bPerformNode)
{
return EPerformNodeResult::NodeAlreadyPerformed;
}
else
{
if (PrintToScreen) GEngine->AddOnScreenDebugMessage(-1, Duration, TextColor, InString);
if (PrintToLog) UE_LOG(LogCategoryStoryGraphPluginRuntime, Warning, TEXT("%s"), *InString);
bPerformNode = true;
return EPerformNodeResult::Successed;
}
}
FText UPrintStringNode::GetNodeTitle() const
{
return FText::FromString(InString);
}
#if WITH_EDITORONLY_DATA
void UPrintStringNode::GetXMLSavingProperty(std::map<FString, XMLProperty>& Properties)
{
Super::GetXMLSavingProperty(Properties);
Properties.insert(std::pair<FString, XMLProperty>("InString", XMLProperty(InString)));
Properties.insert(std::pair<FString, XMLProperty>("PrintToScreen", XMLProperty(PrintToScreen ? "true" : "false")));
Properties.insert(std::pair<FString, XMLProperty>("PrintToLog", XMLProperty(PrintToLog ? "true" : "false")));
Properties.insert(std::pair<FString, XMLProperty>("Duration", XMLProperty(FString::SanitizeFloat(Duration))));
}
void UPrintStringNode::LoadPropertyFromXML(std::map<FString, XMLProperty>& Properties)
{
InString = Properties["InString"].Val;
PrintToScreen = Properties["PrintToScreen"].Val == "true";
PrintToLog = Properties["PrintToLog"].Val == "true";
Duration = FCString::Atof(*Properties["Duration"].Val);
Super::LoadPropertyFromXML(Properties);
}
#endif //WITH_EDITORONLY_DATA
//UAddScreenMessageNode..................................................................................................................
UAddScreenMessageNode::UAddScreenMessageNode()
{
NodeType = ENodeType::AddScreenMessage;
Message = FText::FromString("Hello");
Duration = 5.0;
NodePins.Add(FStoryGraphPin(EEdGraphPinDirection::EGPD_Input, EPinDataTypes::PinType_Horizontal));
NodePins.Add(FStoryGraphPin(EEdGraphPinDirection::EGPD_Output, EPinDataTypes::PinType_Horizontal));
}
EPerformNodeResult UAddScreenMessageNode::PerformNode()
{
Super::PerformNode();
if (pStoryGraph && pStoryGraph->OwnedActor)
{
if (AHUD_StoryGraph* HUD = Cast<AHUD_StoryGraph>(
pStoryGraph->OwnedActor->GetWorld()->GetFirstPlayerController()->GetHUD()))
{
if (HUD->GameScreen)
{
HUD->GameScreen->AddMessageOnScreen(Message, Duration);
}
}
}
return EPerformNodeResult::Successed;
}
FText UAddScreenMessageNode::GetNodeTitle() const
{
return Message;
}
#if WITH_EDITORONLY_DATA
void UAddScreenMessageNode::GetXMLSavingProperty(std::map<FString, XMLProperty>& Properties)
{
Super::GetXMLSavingProperty(Properties);
Properties.insert(std::pair<FString, XMLProperty>("Message", XMLProperty(Message.ToString())));
Properties.insert(std::pair<FString, XMLProperty>("Duration", XMLProperty(FString::SanitizeFloat(Duration))));
}
void UAddScreenMessageNode::LoadPropertyFromXML(std::map<FString, XMLProperty>& Properties)
{
Message = FText::FromString(Properties["Message"].Val);
Duration = FCString::Atof(*Properties["Duration"].Val);
Super::LoadPropertyFromXML(Properties);
}
#endif //WITH_EDITORONLY_DATA
//UAddTargetObjectToPhaseNode..................................................................................................................
UAddTargetObjectToPhaseNode::UAddTargetObjectToPhaseNode()
{
NodeType = ENodeType::AddTargetObjectToPhase;
NodePins.Add(FStoryGraphPin(EEdGraphPinDirection::EGPD_Input, EPinDataTypes::PinType_Horizontal));
NodePins.Add(FStoryGraphPin(EEdGraphPinDirection::EGPD_Output, EPinDataTypes::PinType_Horizontal));
}
EPerformNodeResult UAddTargetObjectToPhaseNode::PerformNode()
{
Super::PerformNode();
if (pQuestPhase)
{
TArray<AActor*> ScenObjects;
((UStoryGraphObjectWithSceneObject*)pGraphObject)->GetSceneObjects(ScenObjects);
pQuestPhase->PhaseObjects.Append(ScenObjects);
}
return EPerformNodeResult::Successed;
}
FText UAddTargetObjectToPhaseNode::GetNodeTitle() const
{
return FText::FromString("Radar");
}
//UMessageStartNode..................................................................................................
UMessageStartNode::UMessageStartNode()
{
NodeType = ENodeType::MessageStart;
}
//UMessageNode...........................................................................................................
UMessageNode::UMessageNode()
{
NodeType = ENodeType::Message;
}
//UMessageEndNode.....................................................................................................
UMessageEndNode::UMessageEndNode()
{
NodeType = ENodeType::MessageEnd;
}
//UMessageExitNode........................................................................................................
UMessageExitNode::UMessageExitNode()
{
NodeType = ENodeType::MessageExit;
}
//UActivateTriggerNode..................................................................................................................
UActivateTriggerNode::UActivateTriggerNode()
{
NodeType = ENodeType::ActivateTrigger;
NodePins.Add(FStoryGraphPin(EEdGraphPinDirection::EGPD_Input, EPinDataTypes::PinType_Horizontal));
NodePins.Add(FStoryGraphPin(EEdGraphPinDirection::EGPD_Output, EPinDataTypes::PinType_Horizontal));
}
EPerformNodeResult UActivateTriggerNode::PerformNode()
{
Super::PerformNode();
((UStoryGraphPlaceTrigger*)GetOuter())->SetCurrentState((int)EPlaceTriggerStates::Active);
return EPerformNodeResult::Successed;
}
FText UActivateTriggerNode::GetNodeTitle() const
{
return FText::FromString("Activate");
}
//USetInventoryItemStateNode..................................................................................................................
USetInventoryItemStateNode::USetInventoryItemStateNode()
{
NodeType = ENodeType::SetInventoryItemState;
NodePins.Add(FStoryGraphPin(EEdGraphPinDirection::EGPD_Input, EPinDataTypes::PinType_Horizontal));
NodePins.Add(FStoryGraphPin(EEdGraphPinDirection::EGPD_Output, EPinDataTypes::PinType_Horizontal));
}
EPerformNodeResult USetInventoryItemStateNode::PerformNode()
{
Super::PerformNode();
pGraphObject->SetCurrentState(NewCurrentInventoryItemState);
return EPerformNodeResult::Successed;
}
FText USetInventoryItemStateNode::GetNodeTitle() const
{
if (pGraphObject)
{
TArray<FString> ObjectStates;
pGraphObject->GetObjectStateAsString(ObjectStates);
return FText::FromString(ObjectStates[NewCurrentInventoryItemState]);
}
else
{
return FText::FromString("Non");
}
}
void USetInventoryItemStateNode::SetCurrentState(int State)
{
NewCurrentInventoryItemState = State;
#if WITH_EDITORONLY_DATA
UpdateGraphNode();
#endif //WITH_EDITORONLY_DATA
}
#if WITH_EDITORONLY_DATA
void USetInventoryItemStateNode::GetXMLSavingProperty(std::map<FString, XMLProperty>& Properties)
{
Super::GetXMLSavingProperty(Properties);
Properties.insert(std::pair<FString, XMLProperty>("NewCurrentInventoryItemState",
XMLProperty(FString::FromInt(NewCurrentInventoryItemState))));
}
void USetInventoryItemStateNode::LoadPropertyFromXML(std::map<FString, XMLProperty>& Properties)
{
NewCurrentInventoryItemState = FCString::Atoi(*Properties["NewCurrentInventoryItemState"].Val);
Super::LoadPropertyFromXML(Properties);
}
#endif //WITH_EDITORONLY_DATA
//USetInventoryItemStateFromMessageNode......................................................
USetInventoryItemStateFromMessageNode::USetInventoryItemStateFromMessageNode()
{
NodeType = ENodeType::SetInventoryItemStateFromMessage;
}
//UPrintQuestPhaseOnScreenNode..................................................................................................................
UPrintQuestPhaseOnScreenNode::UPrintQuestPhaseOnScreenNode()
{
NodeType = ENodeType::PrintQuestPhaseOnScreen;
NodePins.Add(FStoryGraphPin(EEdGraphPinDirection::EGPD_Input, EPinDataTypes::PinType_Horizontal));
NodePins.Add(FStoryGraphPin(EEdGraphPinDirection::EGPD_Output, EPinDataTypes::PinType_Horizontal));
}
EPerformNodeResult UPrintQuestPhaseOnScreenNode::PerformNode()
{
Super::PerformNode();
if (pStoryGraph && pStoryGraph->OwnedActor)
{
AHUD_StoryGraph* HUD = Cast<AHUD_StoryGraph>(
pStoryGraph->OwnedActor->GetWorld()->GetFirstPlayerController()->GetHUD());
if (HUD)
{
HUD->PrintQuestPhaseOnScreen(pQuestPhase->Description);
}
else
{
UE_LOG(LogCategoryStoryGraphPluginRuntime, Warning, TEXT("Your HUD should inherit AHUD_StoryGraph class"));
}
}
return EPerformNodeResult::Successed;
}
FText UPrintQuestPhaseOnScreenNode::GetNodeTitle() const
{
return FText::FromString("PrintOnScreen");
}
//UAddMessageBranchNode..................................................................................................................
UAddMessageBranchNode::UAddMessageBranchNode()
{
NodeType = ENodeType::AddMessageBranch;
}
//USendMessageToLevelBlueprintNode..................................................................................................................
USendMessageToLevelBlueprintNode::USendMessageToLevelBlueprintNode()
{
NodeType = ENodeType::SendMessageToLevelBlueprint;
NodePins.Add(FStoryGraphPin(EEdGraphPinDirection::EGPD_Input, EPinDataTypes::PinType_Horizontal));
NodePins.Add(FStoryGraphPin(EEdGraphPinDirection::EGPD_Output, EPinDataTypes::PinType_Horizontal));
}
EPerformNodeResult USendMessageToLevelBlueprintNode::PerformNode()
{
Super::PerformNode();
if (pStoryGraph && pStoryGraph->OwnedActor)
{
ALevelScriptActor_StoryGraph* LevelBlueprint = Cast<ALevelScriptActor_StoryGraph>(
pStoryGraph->OwnedActor->GetWorld()->GetLevelScriptActor());
if (LevelBlueprint)
{
LevelBlueprint->GetMessageFromStoryGraph(Message);
}
else
{
UE_LOG(LogCategoryStoryGraphPluginRuntime, Warning, TEXT("Reparen level blueprint"));
}
}
return EPerformNodeResult::Successed;
}
FText USendMessageToLevelBlueprintNode::GetNodeTitle() const
{
return FText::FromString("Msg: " + Message);
}
#if WITH_EDITORONLY_DATA
void USendMessageToLevelBlueprintNode::GetXMLSavingProperty(std::map<FString, XMLProperty>& Properties)
{
Super::GetXMLSavingProperty(Properties);
Properties.insert(std::pair<FString, XMLProperty>("Message", XMLProperty(Message)));
}
void USendMessageToLevelBlueprintNode::LoadPropertyFromXML(std::map<FString, XMLProperty>& Properties)
{
Message = Properties["Message"].Val;
Super::LoadPropertyFromXML(Properties);
}
#endif //WITH_EDITORONLY_DATA
| 25.850559 | 148 | 0.725284 | [
"object"
] |
240e82a987b14f876a8e7f360853602a2aed3cb2 | 2,597 | hpp | C++ | src/metrics/Object.hpp | DataDog/dd-native-metrics-js | 1970b459913faf6415a11386edb7bc9c2a063e8a | [
"Apache-2.0"
] | 1 | 2021-08-19T18:00:11.000Z | 2021-08-19T18:00:11.000Z | src/metrics/Object.hpp | DataDog/dd-native-metrics-js | 1970b459913faf6415a11386edb7bc9c2a063e8a | [
"Apache-2.0"
] | null | null | null | src/metrics/Object.hpp | DataDog/dd-native-metrics-js | 1970b459913faf6415a11386edb7bc9c2a063e8a | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <nan.h>
#include <stdint.h>
#include <string>
#include <uv.h>
#include <vector>
#include "Histogram.hpp"
namespace datadog {
class Object {
public:
Object();
Object(v8::Local<v8::Object> target);
void set(std::string key, std::string value);
void set(std::string key, uint64_t value);
void set(std::string key, v8::Local<v8::Object> value);
void set(std::string key, Object value);
void set(std::string key, std::vector<Object> value);
void set(std::string key, Histogram value);
void set(std::string key, Nan::FunctionCallback value);
v8::Local<v8::Object> to_json();
private:
v8::Local<v8::Object> target_;
};
Object::Object() {
target_ = Nan::New<v8::Object>();
}
Object::Object(v8::Local<v8::Object> target) {
target_ = target;
}
void Object::set(std::string key, std::string value) {
Nan::Set(
target_,
Nan::New(key).ToLocalChecked(),
Nan::New(value).ToLocalChecked()
);
}
void Object::set(std::string key, uint64_t value) {
Nan::Set(
target_,
Nan::New(key).ToLocalChecked(),
Nan::New<v8::Number>(static_cast<double>(value))
);
}
void Object::set(std::string key, v8::Local<v8::Object> value) {
Nan::Set(
target_,
Nan::New(key).ToLocalChecked(),
value
);
}
void Object::set(std::string key, Object value) {
Nan::Set(
target_,
Nan::New(key).ToLocalChecked(),
value.to_json()
);
}
void Object::set(std::string key, std::vector<Object> value) {
v8::Local<v8::Array> array = Nan::New<v8::Array>(value.size());
for (unsigned int i = 0; i < array->Length(); i++) {
Nan::Set(array, i, value.at(i).to_json());
}
Nan::Set(
target_,
Nan::New(key).ToLocalChecked(),
array
);
}
void Object::set(std::string key, Histogram value) {
Object obj;
obj.set("min", value.min());
obj.set("max", value.max());
obj.set("sum", value.sum());
obj.set("avg", value.avg());
obj.set("count", value.count());
obj.set("median", value.percentile(0.50));
obj.set("p95", value.percentile(0.95));
Nan::Set(
target_,
Nan::New(key).ToLocalChecked(),
obj.to_json()
);
}
void Object::set(std::string key, Nan::FunctionCallback value) {
Nan::Set(
target_,
Nan::New(key).ToLocalChecked(),
Nan::GetFunction(Nan::New<v8::FunctionTemplate>(value)).ToLocalChecked()
);
}
v8::Local<v8::Object> Object::to_json() {
return target_;
}
}
| 22.780702 | 78 | 0.585676 | [
"object",
"vector"
] |
241021bca2c9ece5fc864528d605024f7dab5e27 | 8,238 | hxx | C++ | Modules/Core/Mesh/include/itkMeshToMeshFilter.hxx | bradking/ITK | 625d4497512b0fb0108106e680063998b8528e06 | [
"Apache-2.0"
] | 945 | 2015-01-09T00:43:52.000Z | 2022-03-30T08:23:02.000Z | Modules/Core/Mesh/include/itkMeshToMeshFilter.hxx | bradking/ITK | 625d4497512b0fb0108106e680063998b8528e06 | [
"Apache-2.0"
] | 2,354 | 2015-02-04T21:54:21.000Z | 2022-03-31T20:58:21.000Z | Modules/Core/Mesh/include/itkMeshToMeshFilter.hxx | bradking/ITK | 625d4497512b0fb0108106e680063998b8528e06 | [
"Apache-2.0"
] | 566 | 2015-01-04T14:26:57.000Z | 2022-03-18T20:33:18.000Z | /*=========================================================================
*
* Copyright NumFOCUS
*
* 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.txt
*
* 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.
*
*=========================================================================*/
/*=========================================================================
*
* Portions of this file are subject to the VTK Toolkit Version 3 copyright.
*
* Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
*
* For complete copyright, license and disclaimer of warranty information
* please refer to the NOTICE file at the top of the ITK source tree.
*
*=========================================================================*/
#ifndef itkMeshToMeshFilter_hxx
#define itkMeshToMeshFilter_hxx
#include "itkMesh.h"
#include "itkMeshToMeshFilter.h"
namespace itk
{
/**
*
*/
template <typename TInputMesh, typename TOutputMesh>
MeshToMeshFilter<TInputMesh, TOutputMesh>::MeshToMeshFilter()
{
// Modify superclass default values, can be overridden by subclasses
this->SetNumberOfRequiredInputs(1);
}
/**
*
*/
template <typename TInputMesh, typename TOutputMesh>
void
MeshToMeshFilter<TInputMesh, TOutputMesh>::SetInput(const TInputMesh * input)
{
// Process object is not const-correct so the const_cast is required here
this->ProcessObject::SetNthInput(0, const_cast<TInputMesh *>(input));
}
/**
*
*/
template <typename TInputMesh, typename TOutputMesh>
auto
MeshToMeshFilter<TInputMesh, TOutputMesh>::GetInput() const -> const InputMeshType *
{
return itkDynamicCastInDebugMode<const TInputMesh *>(this->GetPrimaryInput());
}
/**
*
*/
template <typename TInputMesh, typename TOutputMesh>
auto
MeshToMeshFilter<TInputMesh, TOutputMesh>::GetInput(unsigned int idx) const -> const InputMeshType *
{
return dynamic_cast<const TInputMesh *>(this->ProcessObject::GetInput(idx));
}
template <typename TInputMesh, typename TOutputMesh>
void
MeshToMeshFilter<TInputMesh, TOutputMesh>::CopyInputMeshToOutputMeshPoints()
{
const InputMeshType * inputMesh = this->GetInput();
OutputMeshPointer outputMesh = this->GetOutput();
using OutputPointsContainer = typename TOutputMesh::PointsContainer;
using InputPointsContainer = typename TInputMesh::PointsContainer;
typename OutputPointsContainer::Pointer outputPoints = OutputPointsContainer::New();
const InputPointsContainer * inputPoints = inputMesh->GetPoints();
if (inputPoints)
{
outputPoints->Reserve(inputPoints->Size());
typename InputPointsContainer::ConstIterator inputItr = inputPoints->Begin();
typename InputPointsContainer::ConstIterator inputEnd = inputPoints->End();
typename OutputPointsContainer::Iterator outputItr = outputPoints->Begin();
while (inputItr != inputEnd)
{
outputItr.Value() = inputItr.Value();
++inputItr;
++outputItr;
}
outputMesh->SetPoints(outputPoints);
}
}
template <typename TInputMesh, typename TOutputMesh>
void
MeshToMeshFilter<TInputMesh, TOutputMesh>::CopyInputMeshToOutputMeshPointData()
{
const InputMeshType * inputMesh = this->GetInput();
OutputMeshPointer outputMesh = this->GetOutput();
using OutputPointDataContainer = typename TOutputMesh::PointDataContainer;
using InputPointDataContainer = typename TInputMesh::PointDataContainer;
typename OutputPointDataContainer::Pointer outputPointData = OutputPointDataContainer::New();
const InputPointDataContainer * inputPointData = inputMesh->GetPointData();
if (inputPointData)
{
outputPointData->Reserve(inputPointData->Size());
typename InputPointDataContainer::ConstIterator inputItr = inputPointData->Begin();
typename InputPointDataContainer::ConstIterator inputEnd = inputPointData->End();
typename OutputPointDataContainer::Iterator outputItr = outputPointData->Begin();
while (inputItr != inputEnd)
{
outputItr.Value() = inputItr.Value();
++inputItr;
++outputItr;
}
outputMesh->SetPointData(outputPointData);
}
}
template <typename TInputMesh, typename TOutputMesh>
void
MeshToMeshFilter<TInputMesh, TOutputMesh>::CopyInputMeshToOutputMeshCellLinks()
{
const InputMeshType * inputMesh = this->GetInput();
OutputMeshPointer outputMesh = this->GetOutput();
using OutputCellLinksContainer = typename TOutputMesh::CellLinksContainer;
using InputCellLinksContainer = typename TInputMesh::CellLinksContainer;
typename OutputCellLinksContainer::Pointer outputCellLinks = OutputCellLinksContainer::New();
const InputCellLinksContainer * inputCellLinks = inputMesh->GetCellLinks();
if (inputCellLinks)
{
outputCellLinks->Reserve(inputCellLinks->Size());
typename InputCellLinksContainer::ConstIterator inputItr = inputCellLinks->Begin();
typename InputCellLinksContainer::ConstIterator inputEnd = inputCellLinks->End();
typename OutputCellLinksContainer::Iterator outputItr = outputCellLinks->Begin();
while (inputItr != inputEnd)
{
outputItr.Value() = inputItr.Value();
++inputItr;
++outputItr;
}
outputMesh->SetCellLinks(outputCellLinks);
}
}
template <typename TInputMesh, typename TOutputMesh>
void
MeshToMeshFilter<TInputMesh, TOutputMesh>::CopyInputMeshToOutputMeshCells()
{
const InputMeshType * inputMesh = this->GetInput();
OutputMeshPointer outputMesh = this->GetOutput();
using OutputCellsContainer = typename TOutputMesh::CellsContainer;
using InputCellsContainer = typename TInputMesh::CellsContainer;
using CellAutoPointer = typename TOutputMesh::CellAutoPointer;
outputMesh->SetCellsAllocationMethod(MeshEnums::MeshClassCellsAllocationMethod::CellsAllocatedDynamicallyCellByCell);
typename OutputCellsContainer::Pointer outputCells = OutputCellsContainer::New();
const InputCellsContainer * inputCells = inputMesh->GetCells();
if (inputCells)
{
outputCells->Reserve(inputCells->Size());
typename InputCellsContainer::ConstIterator inputItr = inputCells->Begin();
typename InputCellsContainer::ConstIterator inputEnd = inputCells->End();
typename OutputCellsContainer::Iterator outputItr = outputCells->Begin();
CellAutoPointer clone;
while (inputItr != inputEnd)
{
// outputItr.Value() = inputItr.Value();
// BUG: FIXME: Here we are copying a pointer, which is a mistake. What we
// should do is to clone the cell.
inputItr.Value()->MakeCopy(clone);
outputItr.Value() = clone.ReleaseOwnership();
++inputItr;
++outputItr;
}
outputMesh->SetCells(outputCells);
}
}
template <typename TInputMesh, typename TOutputMesh>
void
MeshToMeshFilter<TInputMesh, TOutputMesh>::CopyInputMeshToOutputMeshCellData()
{
const InputMeshType * inputMesh = this->GetInput();
OutputMeshPointer outputMesh = this->GetOutput();
using OutputCellDataContainer = typename TOutputMesh::CellDataContainer;
using InputCellDataContainer = typename TInputMesh::CellDataContainer;
typename OutputCellDataContainer::Pointer outputCellData = OutputCellDataContainer::New();
const InputCellDataContainer * inputCellData = inputMesh->GetCellData();
if (inputCellData)
{
outputCellData->Reserve(inputCellData->Size());
typename InputCellDataContainer::ConstIterator inputItr = inputCellData->Begin();
typename InputCellDataContainer::ConstIterator inputEnd = inputCellData->End();
typename OutputCellDataContainer::Iterator outputItr = outputCellData->Begin();
while (inputItr != inputEnd)
{
outputItr.Value() = inputItr.Value();
++inputItr;
++outputItr;
}
outputMesh->SetCellData(outputCellData);
}
}
} // end namespace itk
#endif
| 32.433071 | 119 | 0.717893 | [
"object"
] |
2414c8f4e324835edc94d6a9ef5bca041e0dd4e2 | 29,911 | cc | C++ | soa/service/runner.cc | datacratic/DasDB | 5ccc1fc7c6c69c97e3dae0e02bb4009f95908d3b | [
"Apache-2.0"
] | 3 | 2017-12-06T00:25:52.000Z | 2021-08-24T20:46:54.000Z | soa/service/runner.cc | datacratic/DasDB | 5ccc1fc7c6c69c97e3dae0e02bb4009f95908d3b | [
"Apache-2.0"
] | null | null | null | soa/service/runner.cc | datacratic/DasDB | 5ccc1fc7c6c69c97e3dae0e02bb4009f95908d3b | [
"Apache-2.0"
] | 1 | 2016-11-24T17:14:16.000Z | 2016-11-24T17:14:16.000Z | /* runner.cc -*- C++ -*-
Wolfgang Sourdeau, September 2013
Copyright (c) 2013 Datacratic. All rights reserved.
A command runner class that hides the specifics of the underlying unix
system calls and can intercept input and output.
*/
#include <fcntl.h>
#include <poll.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/epoll.h>
#include <sys/prctl.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/resource.h>
#include <iostream>
#include <utility>
#include "jml/arch/futex.h"
#include "jml/arch/timers.h"
#include "jml/utils/guard.h"
#include "jml/utils/file_functions.h"
#include "logs.h"
#include "message_loop.h"
#include "sink.h"
#include "runner.h"
#include "soa/types/basic_value_descriptions.h"
using namespace std;
using namespace Datacratic;
timevalDescription::
timevalDescription()
{
addField("tv_sec", &timeval::tv_sec, "seconds");
addField("tv_usec", &timeval::tv_usec, "micro seconds");
}
rusageDescription::
rusageDescription()
{
addField("utime", &rusage::ru_utime, "user CPU time used");
addField("stime", &rusage::ru_stime, "system CPU time used");
addField("maxrss", &rusage::ru_maxrss, "maximum resident set size");
addField("ixrss", &rusage::ru_ixrss, "integral shared memory size");
addField("idrss", &rusage::ru_idrss, "integral unshared data size");
addField("isrss", &rusage::ru_isrss, "integral unshared stack size");
addField("minflt", &rusage::ru_minflt, "page reclaims (soft page faults)");
addField("majflt", &rusage::ru_majflt, "page faults (hard page faults)");
addField("nswap", &rusage::ru_nswap, "swaps");
addField("inblock", &rusage::ru_inblock, "block input operations");
addField("oublock", &rusage::ru_oublock, "block output operations");
addField("msgsnd", &rusage::ru_msgsnd, "IPC messages sent");
addField("msgrcv", &rusage::ru_msgrcv, "IPC messages received");
addField("nsignals", &rusage::ru_nsignals, "signals received");
addField("nvcsw", &rusage::ru_nvcsw, "voluntary context switches");
addField("nivcsw", &rusage::ru_nivcsw, "involuntary context switches");
}
namespace {
Logging::Category warnings("Runner::warning");
tuple<int, int>
CreateStdPipe(bool forWriting)
{
int fds[2];
int rc = pipe(fds);
if (rc == -1) {
throw ML::Exception(errno, "CreateStdPipe pipe2");
}
if (forWriting) {
return tuple<int, int>(fds[1], fds[0]);
}
else {
return tuple<int, int>(fds[0], fds[1]);
}
}
} // namespace
namespace Datacratic {
/* ASYNCRUNNER */
Runner::
Runner()
: closeStdin(false), running_(false), childPid_(-1),
wakeup_(EFD_NONBLOCK | EFD_CLOEXEC),
statusRemaining_(sizeof(Task::ChildStatus))
{
Epoller::init(4);
handleEvent = [&] (const struct epoll_event & event) {
return this->handleEpollEvent(event);
};
}
Runner::
~Runner()
{
waitTermination();
}
Epoller::HandleEventResult
Runner::
handleEpollEvent(const struct epoll_event & event)
{
if (event.data.ptr == &task_.statusFd) {
// fprintf(stderr, "parent: handle child status input\n");
handleChildStatus(event);
}
else if (event.data.ptr == &task_.stdOutFd) {
// fprintf(stderr, "parent: handle child output from stdout\n");
handleOutputStatus(event, task_.stdOutFd, stdOutSink_);
}
else if (event.data.ptr == &task_.stdErrFd) {
// fprintf(stderr, "parent: handle child output from stderr\n");
handleOutputStatus(event, task_.stdErrFd, stdErrSink_);
}
else if (event.data.ptr == nullptr) {
// stdInSink cleanup for now...
handleWakeup(event);
}
else {
throw ML::Exception("this should never occur");
}
return Epoller::DONE;
}
void
Runner::
handleChildStatus(const struct epoll_event & event)
{
// cerr << "handleChildStatus\n";
Task::ChildStatus status;
if ((event.events & EPOLLIN) != 0) {
while (1) {
char * current = (statusBuffer_ + sizeof(Task::ChildStatus)
- statusRemaining_);
ssize_t s = ::read(task_.statusFd, current, statusRemaining_);
if (s == -1) {
if (errno == EWOULDBLOCK) {
break;
}
else if (errno == EBADF || errno == EINVAL) {
// cerr << "badf\n";
break;
}
throw ML::Exception(errno, "Runner::handleChildStatus read");
}
else if (s == 0) {
break;
}
statusRemaining_ -= s;
if (statusRemaining_ > 0) {
cerr << "warning: reading status fd in multiple chunks\n";
continue;
}
memcpy(&status, statusBuffer_, sizeof(status));
// Set up for next message
statusRemaining_ = sizeof(statusBuffer_);
#if 0
cerr << "got status " << status.state
<< " " << Task::statusStateAsString(status.state)
<< " " << status.pid << " " << status.childStatus
<< " " << status.launchErrno << " "
<< strerror(status.launchErrno) << " "
<< Task::strLaunchError(status.launchErrorCode)
<< endl;
#endif
task_.statusState = status.state;
task_.runResult.usage = status.usage;
if (status.launchErrno || status.launchErrorCode) {
//cerr << "*** launch error" << endl;
// Error
task_.runResult.updateFromLaunchError
(status.launchErrno,
Task::strLaunchError(status.launchErrorCode));
task_.postTerminate(*this);
childPid_ = -2;
ML::futex_wake(childPid_);
running_ = false;
ML::futex_wake(running_);
break;
}
switch (status.state) {
case Task::LAUNCHING:
childPid_ = status.pid;
// cerr << " childPid_ = status.pid (launching)\n";
break;
case Task::RUNNING:
childPid_ = status.pid;
// cerr << " childPid_ = status.pid (running)\n";
ML::futex_wake(childPid_);
break;
case Task::STOPPED:
childPid_ = -3;
// cerr << " childPid_ = -3 (stopped)\n";
ML::futex_wake(childPid_);
task_.runResult.updateFromStatus(status.childStatus);
task_.statusState = Task::StatusState::DONE;
if (stdInSink_ && stdInSink_->state != OutputSink::CLOSED) {
stdInSink_->requestClose();
}
attemptTaskTermination();
break;
case Task::DONE:
throw ML::Exception("unexpected status DONE");
case Task::ST_UNKNOWN:
throw ML::Exception("unexpected status UNKNOWN");
}
if (status.launchErrno || status.launchErrorCode)
break;
}
}
if ((event.events & EPOLLHUP) != 0) {
//cerr << "*** hangup" << endl;
removeFd(task_.statusFd);
::close(task_.statusFd);
task_.statusFd = -1;
}
else {
restartFdOneShot(task_.statusFd, event.data.ptr);
}
// cerr << "handleChildStatus done\n";
}
void
Runner::
handleOutputStatus(const struct epoll_event & event,
int outputFd, shared_ptr<InputSink> & sink)
{
char buffer[4096];
bool closedFd(false);
string data;
if ((event.events & EPOLLIN) != 0) {
while (1) {
ssize_t len = ::read(outputFd, buffer, sizeof(buffer));
// cerr << "returned len: " << len << endl;
if (len < 0) {
// perror(" len -1");
if (errno == EWOULDBLOCK) {
break;
}
else if (errno == EBADF || errno == EINVAL) {
closedFd = true;
break;
}
else {
throw ML::Exception(errno,
"Runner::handleOutputStatus read");
}
}
else if (len == 0) {
closedFd = true;
break;
}
else if (len > 0) {
data.append(buffer, len);
}
}
if (data.size() > 0) {
// cerr << "sending child output to output handler\n";
sink->notifyReceived(move(data));
}
else {
cerr << "ignoring child output due to size == 0\n";
}
}
if (closedFd || (event.events & EPOLLHUP) != 0) {
sink->notifyClosed();
sink.reset();
attemptTaskTermination();
}
else {
JML_TRACE_EXCEPTIONS(false);
try {
restartFdOneShot(outputFd, event.data.ptr);
}
catch (const ML::Exception & exc) {
cerr << "closing sink due to bad fd\n";
sink->notifyClosed();
sink.reset();
attemptTaskTermination();
}
}
}
void
Runner::
handleWakeup(const struct epoll_event & event)
{
// cerr << "handleWakup\n";
while (!wakeup_.tryRead());
if ((event.events & EPOLLIN) != 0) {
if (stdInSink_) {
if (stdInSink_->connectionState_
== AsyncEventSource::DISCONNECTED) {
attemptTaskTermination();
removeFd(wakeup_.fd());
}
else {
wakeup_.signal();
restartFdOneShot(wakeup_.fd(), event.data.ptr);
}
}
}
}
void
Runner::
attemptTaskTermination()
{
/* for a task to be considered done:
- stdout and stderr must have been closed, provided we redirected them
- the closing child status must have been returned */
if ((!stdInSink_ || stdInSink_->state == OutputSink::CLOSED)
&& !stdOutSink_ && !stdErrSink_ && childPid_ < 0
&& (task_.statusState == Task::StatusState::STOPPED
|| task_.statusState == Task::StatusState::DONE)) {
task_.postTerminate(*this);
if (stdInSink_) {
stdInSink_.reset();
}
// cerr << "terminated task\n";
running_ = false;
ML::futex_wake(running_);
}
#if 0
else {
cerr << "cannot terminate yet because:\n";
if ((stdInSink_ && stdInSink_->state != OutputSink::CLOSED)) {
cerr << "stdin sink active\n";
}
if (stdOutSink_) {
cerr << "stdout sink active\n";
}
if (stdErrSink_) {
cerr << "stderr sink active\n";
}
if (childPid_ >= 0) {
cerr << "childPid_ >= 0\n";
}
if (!(task_.statusState == Task::StatusState::STOPPED
|| task_.statusState == Task::StatusState::DONE)) {
cerr << "task status != stopped/done\n";
}
}
#endif
}
OutputSink &
Runner::
getStdInSink()
{
if (running_)
throw ML::Exception("already running");
if (stdInSink_)
throw ML::Exception("stdin sink already set");
auto onClose = [&] () {
if (task_.stdInFd != -1) {
::close(task_.stdInFd);
task_.stdInFd = -1;
}
parent_->removeSource(stdInSink_.get());
wakeup_.signal();
};
stdInSink_.reset(new AsyncFdOutputSink(onClose, onClose));
return *stdInSink_;
}
void
Runner::
run(const vector<string> & command,
const OnTerminate & onTerminate,
const shared_ptr<InputSink> & stdOutSink,
const shared_ptr<InputSink> & stdErrSink)
{
if (parent_ == nullptr) {
LOG(warnings)
<< ML::format("Runner %p is not connected to any MessageLoop\n", this);
}
if (running_)
throw ML::Exception("already running");
running_ = true;
ML::futex_wake(running_);
task_.statusState = Task::StatusState::ST_UNKNOWN;
task_.onTerminate = onTerminate;
Task::ChildFds childFds;
tie(task_.statusFd, childFds.statusFd) = CreateStdPipe(false);
if (stdInSink_) {
tie(task_.stdInFd, childFds.stdIn) = CreateStdPipe(true);
}
else if (closeStdin) {
childFds.stdIn = -1;
}
if (stdOutSink) {
stdOutSink_ = stdOutSink;
tie(task_.stdOutFd, childFds.stdOut) = CreateStdPipe(false);
}
if (stdErrSink) {
stdErrSink_ = stdErrSink;
tie(task_.stdErrFd, childFds.stdErr) = CreateStdPipe(false);
}
::flockfile(stdout);
::flockfile(stderr);
::fflush_unlocked(NULL);
task_.wrapperPid = fork();
::funlockfile(stderr);
::funlockfile(stdout);
if (task_.wrapperPid == -1) {
throw ML::Exception(errno, "Runner::run fork");
}
else if (task_.wrapperPid == 0) {
task_.runWrapper(command, childFds);
}
else {
task_.statusState = Task::StatusState::LAUNCHING;
ML::set_file_flag(task_.statusFd, O_NONBLOCK);
if (stdInSink_) {
ML::set_file_flag(task_.stdInFd, O_NONBLOCK);
stdInSink_->init(task_.stdInFd);
parent_->addSource("stdInSink", stdInSink_);
addFdOneShot(wakeup_.fd());
}
addFdOneShot(task_.statusFd, &task_.statusFd);
if (stdOutSink) {
ML::set_file_flag(task_.stdOutFd, O_NONBLOCK);
addFdOneShot(task_.stdOutFd, &task_.stdOutFd);
}
if (stdErrSink) {
ML::set_file_flag(task_.stdErrFd, O_NONBLOCK);
addFdOneShot(task_.stdErrFd, &task_.stdErrFd);
}
childFds.close();
}
}
bool
Runner::
kill(int signum, bool mustSucceed) const
{
if (childPid_ <= 0) {
if (mustSucceed)
throw ML::Exception("subprocess not available");
else return false;
}
::kill(-childPid_, signum);
waitTermination();
return true;
}
bool
Runner::
signal(int signum, bool mustSucceed)
{
if (childPid_ <= 0) {
if (mustSucceed)
throw ML::Exception("subprocess not available");
else return false;
}
::kill(childPid_, signum);
return true;
}
bool
Runner::
waitStart(double secondsToWait) const
{
Date deadline = Date::now().plusSeconds(secondsToWait);
while (childPid_ == -1) {
//cerr << "waitStart childPid_ = " << childPid_ << endl;
double timeToWait = Date::now().secondsUntil(deadline);
if (timeToWait < 0)
break;
if (isfinite(timeToWait))
ML::futex_wait(childPid_, -1, timeToWait);
else ML::futex_wait(childPid_, -1);
//cerr << "waitStart childPid_ now = " << childPid_ << endl;
}
return childPid_ > 0;
}
void
Runner::
waitTermination() const
{
while (running_) {
ML::futex_wait(running_, true);
}
}
/* RUNNER::TASK */
Runner::Task::
Task()
: wrapperPid(-1),
stdInFd(-1),
stdOutFd(-1),
stdErrFd(-1),
statusFd(-1),
statusState(ST_UNKNOWN)
{}
std::string
Runner::Task::
strLaunchError(LaunchErrorCode error)
{
switch (error) {
case E_NONE: return "no error";
case E_READ_STATUS_PIPE: return "read() on status pipe";
case E_STATUS_PIPE_WRONG_LENGTH:
return "wrong message size reading launch pipe";
case E_SUBTASK_LAUNCH: return "exec() launching subtask";
case E_SUBTASK_WAITPID: return "waitpid waiting for subtask";
case E_WRONG_CHILD: return "waitpid() returned the wrong child";
}
throw ML::Exception("unknown error launch error code %d",
error);
}
std::string
Runner::Task::
statusStateAsString(StatusState statusState)
{
switch (statusState) {
case ST_UNKNOWN: return "UNKNOWN";
case LAUNCHING: return "LAUNCHING";
case RUNNING: return "RUNNING";
case STOPPED: return "STOPPED";
case DONE: return "DONE";
}
throw ML::Exception("unknown status %d", statusState);
}
void
Runner::Task::
runWrapper(const vector<string> & command, ChildFds & fds)
{
// Undo any SIGCHLD block from the parent process so it can
// properly wait for the signal
::signal(SIGCHLD, SIG_DFL);
::signal(SIGPIPE, SIG_DFL);
fds.dupToStdStreams();
fds.closeRemainingFds();
// Set up the arguments before we fork, as we don't want to call malloc()
// from the fork, and it can be called from c_str() in theory.
size_t len = command.size();
char * argv[len + 1];
for (int i = 0; i < len; i++) {
argv[i] = (char *) command[i].c_str();
}
argv[len] = NULL;
// Create a pipe for the child to accurately report launch errors back
// to the parent. We set the close-on-exit so that when the new
// process has finished launching, the pipe will be completely closed
// and we can use this to know that it has properly started.
int childLaunchStatusFd[2] = { -1, -1 };
// Arrange for them to be closed in the case of an exception.
ML::Call_Guard guard([&] ()
{
if (childLaunchStatusFd[0] != -1)
::close(childLaunchStatusFd[0]);
if (childLaunchStatusFd[1] != -1)
::close(childLaunchStatusFd[1]);
});
int res = ::pipe2(childLaunchStatusFd, O_CLOEXEC);
if (res == -1)
throw ML::Exception(errno, "pipe() for status");
int childPid = fork();
if (childPid == -1) {
throw ML::Exception(errno, "fork() in runWrapper");
}
else if (childPid == 0) {
::close(childLaunchStatusFd[0]);
::setsid();
::signal(SIGQUIT, SIG_DFL);
::signal(SIGTERM, SIG_DFL);
::signal(SIGINT, SIG_DFL);
::prctl(PR_SET_PDEATHSIG, SIGHUP);
if (getppid() == 1) {
cerr << "runner: parent process already dead\n";
::kill(getpid(), SIGHUP);
}
::close(fds.statusFd);
int res = ::execv(command[0].c_str(), argv);
if (res == -1) {
// Report back that we couldn't launch
int err = errno;
int res = ::write(childLaunchStatusFd[1], &err, sizeof(err));
if (res == -1)
_exit(124);
else _exit(125);
}
// No need to close the FDs because this fork won't last long
/* there is no possible way this code could be executed */
throw ML::Exception("The Alpha became the Omega.");
}
else {
::close(childLaunchStatusFd[1]);
childLaunchStatusFd[1] = -1;
// FILE * terminal = ::fopen("/dev/tty", "a");
// ::fprintf(terminal, "wrapper: real child pid: %d\n", childPid);
ChildStatus status;
// Write an update to the current status
auto writeStatus = [&] ()
{
int res = ::write(fds.statusFd, &status, sizeof(status));
if (res == -1)
throw ML::Exception(errno, "runWrapper write status");
else if (res != sizeof(status))
throw ML::Exception("didn't completely write status");
};
// Write that there was an error to the calling process, and then
// exit
auto writeError = [&] (int launchErrno, LaunchErrorCode errorCode,
int exitCode)
{
status.launchErrno = launchErrno;
status.launchErrorCode = errorCode;
//cerr << "sending error " << strerror(launchErrno)
//<< " " << strLaunchError(errorCode) << " and exiting with "
//<< exitCode << endl;
int res = ::write(fds.statusFd, &status, sizeof(status));
if (res == -1)
throw ML::Exception(errno, "runWrapper write status");
else if (res != sizeof(status))
throw ML::Exception("didn't completely write status");
fds.close();
_exit(exitCode);
};
status.state = LAUNCHING;
status.pid = childPid;
writeStatus();
// ::fprintf(terminal, "wrapper: waiting child...\n");
// Read from the launch status pipe to know that the launch has
// finished.
int launchErrno;
int bytes = ::read(childLaunchStatusFd[0], &launchErrno,
sizeof(launchErrno));
if (bytes == 0) {
// Launch happened successfully (pipe was closed on exec)
status.state = RUNNING;
writeStatus();
}
else {
// Error launching
//cerr << "got launch error" << endl;
int childStatus;
// We ignore the error code for this... there is nothing we
// can do if we can't waitpid
while (::waitpid(childPid, &childStatus, 0) == -1 && errno == EINTR) ;
//cerr << "waitpid on " << childPid << " returned "
// << res << " with childStatus "
// << childStatus << endl;
//cerr << "done with an error; first wait for the child to exit"
// << endl;
if (bytes == -1) {
// Problem reading
writeError(errno, E_READ_STATUS_PIPE, 127);
}
else if (bytes != sizeof(launchErrno)) {
// Wrong size of message
writeError(0, E_STATUS_PIPE_WRONG_LENGTH, 127);
}
else {
// Launch was unsuccessful; we have the errno. Return it and
// exit.
writeError(launchErrno, E_SUBTASK_LAUNCH, 126);
}
}
int childStatus;
int res;
while ((res = ::waitpid(childPid, &childStatus, 0)) == -1
&& errno == EINTR);
if (res == -1) {
writeError(errno, E_SUBTASK_WAITPID, 127);
}
else if (res != childPid) {
writeError(0, E_WRONG_CHILD, 127);
}
status.state = STOPPED;
status.childStatus = childStatus;
getrusage(RUSAGE_CHILDREN, &status.usage);
writeStatus();
fds.close();
::_exit(0);
}
}
void
Runner::Task::
postTerminate(Runner & runner)
{
// cerr << "postTerminate\n";
if (wrapperPid <= 0) {
throw ML::Exception("wrapperPid <= 0, has postTerminate been executed before?");
}
// cerr << "waiting for wrapper pid: " << wrapperPid << endl;
int wrapperPidStatus;
while (true) {
int res = ::waitpid(wrapperPid, &wrapperPidStatus, 0);
if (res == wrapperPid) {
break;
}
else if (res == -1) {
if (errno != EINTR) {
throw ML::Exception(errno, "waitpid");
}
}
else {
throw ML::Exception("waitpid has not returned the wrappedPid");
}
}
wrapperPid = -1;
//cerr << "finished waiting for wrapper with status " << wrapperPidStatus
// << endl;
if (stdInFd != -1) {
::close(stdInFd);
stdInFd = -1;
}
auto unregisterFd = [&] (int & fd) {
if (fd > -1) {
JML_TRACE_EXCEPTIONS(false);
try {
runner.removeFd(fd);
}
catch (const ML::Exception & exc) {
}
::close(fd);
fd = -1;
}
};
unregisterFd(stdOutFd);
unregisterFd(stdErrFd);
command.clear();
if (onTerminate) {
onTerminate(runResult);
onTerminate = nullptr;
}
runResult = RunResult();
}
/* CHILD::CHILDFDS */
Runner::Task::ChildFds::
ChildFds()
: stdIn(::fileno(stdin)),
stdOut(::fileno(stdout)),
stdErr(::fileno(stderr)),
statusFd(-1)
{
}
/* child api */
void
Runner::Task::ChildFds::
closeRemainingFds()
{
struct rlimit limits;
::getrlimit(RLIMIT_NOFILE, &limits);
for (int fd = 0; fd < limits.rlim_cur; fd++) {
if ((fd != STDIN_FILENO || stdIn == -1)
&& fd != STDOUT_FILENO && fd != STDERR_FILENO
&& fd != statusFd) {
::close(fd);
}
}
}
void
Runner::Task::ChildFds::
dupToStdStreams()
{
auto dupToStdStream = [&] (int oldFd, int newFd) {
if (oldFd != newFd) {
int rc = ::dup2(oldFd, newFd);
if (rc == -1) {
throw ML::Exception(errno,
"ChildFds::dupToStdStream dup2");
}
}
};
if (stdIn != -1) {
dupToStdStream(stdIn, STDIN_FILENO);
}
dupToStdStream(stdOut, STDOUT_FILENO);
dupToStdStream(stdErr, STDERR_FILENO);
}
/* parent & child api */
void
Runner::Task::ChildFds::
close()
{
auto closeIfNotEqual = [&] (int & fd, int notValue) {
if (fd != notValue) {
::close(fd);
}
};
closeIfNotEqual(stdIn, STDIN_FILENO);
closeIfNotEqual(stdOut, STDOUT_FILENO);
closeIfNotEqual(stdErr, STDERR_FILENO);
closeIfNotEqual(statusFd, -1);
}
/* RUNNER TASK CHILDSTATUS */
Runner::Task::ChildStatus::
ChildStatus()
{
// Doing it this way keeps ValGrind happy
::memset(this, 0, sizeof(*this));
state = ST_UNKNOWN;
pid = -1;
childStatus = -1;
launchErrno = 0;
launchErrorCode = E_NONE;
}
/* RUNRESULT */
RunResult::
RunResult()
: state(UNKNOWN), signum(-1), returnCode(-1), launchErrno(0)
{
::memset(&usage, 0, sizeof(usage));
}
void
RunResult::
updateFromStatus(int status)
{
if (WIFEXITED(status)) {
state = RETURNED;
returnCode = WEXITSTATUS(status);
}
else if (WIFSIGNALED(status)) {
state = SIGNALED;
signum = WTERMSIG(status);
}
}
int
RunResult::
processStatus()
const
{
int status;
if (state == RETURNED)
status = returnCode;
else if (state == SIGNALED)
status = 128 + signum;
else if (state == LAUNCH_ERROR) {
if (launchErrno == EPERM) {
status = 126;
}
else if (launchErrno == ENOENT) {
status = 127;
}
else {
status = 1;
}
}
else
throw ML::Exception("unhandled state");
return status;
}
void
RunResult::
updateFromLaunchError(int launchErrno,
const std::string & launchError)
{
this->state = LAUNCH_ERROR;
this->launchErrno = launchErrno;
if (!launchError.empty()) {
this->launchError = launchError;
if (launchErrno)
this->launchError += std::string(": ")
+ strerror(launchErrno);
}
else {
this->launchError = strerror(launchErrno);
}
}
std::string
to_string(const RunResult::State & state)
{
switch (state) {
case RunResult::UNKNOWN: return "UNKNOWN";
case RunResult::LAUNCH_ERROR: return "LAUNCH_ERROR";
case RunResult::RETURNED: return "RETURNED";
case RunResult::SIGNALED: return "SIGNALED";
}
return ML::format("RunResult::State(%d)", state);
}
std::ostream &
operator << (std::ostream & stream, const RunResult::State & state)
{
return stream << to_string(state);
}
RunResultDescription::
RunResultDescription()
{
addField("state", &RunResult::state, "State of run command");
addField("signum", &RunResult::signum,
"Signal number that it exited with", -1);
addField("returnCode", &RunResult::returnCode,
"Return code of command", -1);
addField("launchErrno", &RunResult::launchErrno,
"Errno for launch error", 0);
addField("launchError", &RunResult::launchError,
"Error message for launch error");
addField("usage", &RunResult::usage,
"Process statistics as returned by getrusage()");
}
RunResultStateDescription::
RunResultStateDescription()
{
addValue("UNKNOWN", RunResult::UNKNOWN,
"State is unknown or uninitialized");
addValue("LAUNCH_ERROR", RunResult::LAUNCH_ERROR,
"Command was unable to be launched");
addValue("RETURNED", RunResult::RETURNED, "Command returned");
addValue("SIGNALED", RunResult::SIGNALED, "Command exited with a signal");
}
/* EXECUTE */
RunResult
execute(MessageLoop & loop,
const vector<string> & command,
const shared_ptr<InputSink> & stdOutSink,
const shared_ptr<InputSink> & stdErrSink,
const string & stdInData,
bool closeStdin)
{
RunResult result;
auto onTerminate = [&](const RunResult & runResult) {
result = runResult;
};
Runner runner;
loop.addSource("runner", runner);
if (stdInData.size() > 0) {
auto & sink = runner.getStdInSink();
runner.run(command, onTerminate, stdOutSink, stdErrSink);
sink.write(stdInData);
sink.requestClose();
}
else {
runner.closeStdin = closeStdin;
runner.run(command, onTerminate, stdOutSink, stdErrSink);
}
runner.waitTermination();
loop.removeSource(&runner);
runner.waitConnectionState(AsyncEventSource::DISCONNECTED);
return result;
}
RunResult
execute(const vector<string> & command,
const shared_ptr<InputSink> & stdOutSink,
const shared_ptr<InputSink> & stdErrSink,
const string & stdInData,
bool closeStdin)
{
MessageLoop loop(1, 0, -1);
loop.start();
RunResult result = execute(loop, command, stdOutSink, stdErrSink,
stdInData, closeStdin);
loop.shutdown();
return result;
}
} // namespace Datacratic
| 27.491728 | 88 | 0.55167 | [
"vector"
] |
241b7e2bf4457a39656b37c09cf74e3ebe52552e | 1,251 | cpp | C++ | examples/google-code-jam/Qwrk/Problem A.cpp | rbenic-fer/progauthfp | d0fd96c31ab0aab1a9acdcb7c75f2b430f51c675 | [
"MIT"
] | null | null | null | examples/google-code-jam/Qwrk/Problem A.cpp | rbenic-fer/progauthfp | d0fd96c31ab0aab1a9acdcb7c75f2b430f51c675 | [
"MIT"
] | null | null | null | examples/google-code-jam/Qwrk/Problem A.cpp | rbenic-fer/progauthfp | d0fd96c31ab0aab1a9acdcb7c75f2b430f51c675 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <algorithm>
typedef std::pair<char, char> PCC;
char decode (char d)
{
if (d == ' ') return ' ';
if (d == 'a') return 'y';
if (d == 'b') return 'h';
if (d == 'c') return 'e';
if (d == 'd') return 's';
if (d == 'e') return 'o';
if (d == 'f') return 'c';
if (d == 'g') return 'v';
if (d == 'h') return 'x';
if (d == 'i') return 'd';
if (d == 'j') return 'u';
if (d == 'k') return 'i';
if (d == 'l') return 'g';
if (d == 'm') return 'l';
if (d == 'n') return 'b';
if (d == 'o') return 'k';
if (d == 'p') return 'r';
if (d == 'q') return 'z';
if (d == 'r') return 't';
if (d == 's') return 'n';
if (d == 't') return 'w';
if (d == 'u') return 'j';
if (d == 'v') return 'p';
if (d == 'w') return 'f';
if (d == 'x') return 'm';
if (d == 'y') return 'a';
if (d == 'z') return 'q';
}
int main()
{
char cl; int T; std::cin >> T; std::cin.ignore (1);
for (int c = 1; c <= T; ++c) {
std::string enc;
std::getline (std::cin, enc);
std::cout << "Case #" << c << ": ";
for (int i = 0; i < enc.length(); ++i) {
std::cout << decode (enc[i]);
}
std::cout << '\n';
}
return 0;
} | 22.339286 | 53 | 0.43805 | [
"vector"
] |
2420404b82458ed62489c7d4d723d5c6c8747c35 | 1,769 | hpp | C++ | query_optimizer/cost_model/CostModel.hpp | spring-operator/quickstep | 3e98776002eb5db7154031fd6ef1a7f000a89d81 | [
"Apache-2.0"
] | 31 | 2016-01-20T05:43:46.000Z | 2022-02-07T09:14:06.000Z | query_optimizer/cost_model/CostModel.hpp | spring-operator/quickstep | 3e98776002eb5db7154031fd6ef1a7f000a89d81 | [
"Apache-2.0"
] | 221 | 2016-01-20T18:25:10.000Z | 2016-06-26T02:58:12.000Z | query_optimizer/cost_model/CostModel.hpp | spring-operator/quickstep | 3e98776002eb5db7154031fd6ef1a7f000a89d81 | [
"Apache-2.0"
] | 17 | 2016-01-20T04:00:21.000Z | 2019-03-12T02:41:25.000Z | /**
* Copyright 2011-2015 Quickstep Technologies LLC.
* Copyright 2015 Pivotal Software, 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.
**/
#ifndef QUERY_OPTIMIZER_COST_MODEL_COST_MODEL_HPP_
#define QUERY_OPTIMIZER_COST_MODEL_COST_MODEL_HPP_
#include <cstddef>
#include "query_optimizer/physical/Physical.hpp"
#include "utility/Macros.hpp"
namespace quickstep {
namespace optimizer {
namespace cost {
/** \addtogroup CostModel
* @{
*/
/**
* @brief Interface to a cost model of physical plans.
*/
class CostModel {
public:
/**
* @brief Destructor.
*/
virtual ~CostModel() {}
/**
* @brief Estimate the cardinality of the output relation of \p physical_plan.
*
* @param physical_plan The physical plan for which the cardinality of the
* output relation is estimated.
* @return The estimated cardinality.
*/
virtual std::size_t estimateCardinality(
const physical::PhysicalPtr &physical_plan) = 0;
protected:
/**
* @brief Constructor.
*/
CostModel() {}
private:
DISALLOW_COPY_AND_ASSIGN(CostModel);
};
/** @} */
} // namespace cost
} // namespace optimizer
} // namespace quickstep
#endif /* QUERY_OPTIMIZER_COST_MODEL_COST_MODEL_HPP_ */
| 24.915493 | 80 | 0.701526 | [
"model"
] |
242faaeb9dc6321173a2981a0c91ee42bdb369e8 | 1,652 | hpp | C++ | src/common/Config.hpp | vivint-smarthome/ceph-mesos | 914f50c55aff4d8bbc9c00149e775ebaa3674a33 | [
"Apache-2.0"
] | 1 | 2017-06-12T22:58:11.000Z | 2017-06-12T22:58:11.000Z | src/common/Config.hpp | vivint-smarthome/ceph-mesos | 914f50c55aff4d8bbc9c00149e775ebaa3674a33 | [
"Apache-2.0"
] | null | null | null | src/common/Config.hpp | vivint-smarthome/ceph-mesos | 914f50c55aff4d8bbc9c00149e775ebaa3674a33 | [
"Apache-2.0"
] | null | null | null | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _CEPHMESOS_COMMON_CONFIG_HPP_
#define _CEPHMESOS_COMMON_CONFIG_HPP_
#include <string>
#include <vector>
const std::string hostConfigFolder = "cephmesos.d";
struct Config
{
std::string id;
std::string role;
std::string master;
std::string zookeeper;
int restport;
int fileport;
std::string fileroot;
std::string mgmtdev;
std::string datadev;
std::vector <std::string> osddevs;
std::vector <std::string> jnldevs;
int jnlparts;
};
Config* get_config(int* argc, char*** argv);
Config* get_config_by_hostname(std::string hostname);
bool is_host_config(const char *filename);
std::string get_file_contents(const char *filename);
std::string get_config_path_by_hostname(std::string hostname);
Config* parse_config_string(std::string input);
Config* merge_config(Config* defaultConfig, Config* hostConfig);
#endif
| 31.169811 | 75 | 0.755448 | [
"vector"
] |
2430c69cff0d7172650c280c315846d57726a09d | 695 | cpp | C++ | b-LeetCode/55-Jump-Game.cpp | ftxj/4th-Semester | 1d5c7e7e028176524bdafc64078775d42b73b51c | [
"MIT"
] | null | null | null | b-LeetCode/55-Jump-Game.cpp | ftxj/4th-Semester | 1d5c7e7e028176524bdafc64078775d42b73b51c | [
"MIT"
] | null | null | null | b-LeetCode/55-Jump-Game.cpp | ftxj/4th-Semester | 1d5c7e7e028176524bdafc64078775d42b73b51c | [
"MIT"
] | null | null | null | class Solution {
public:
bool canJump(vector<int>& nums) {
if(nums.size() == 1) return true;
for(int i = 0; i < nums.size();){
for(int j = i; j <= i + nums[i]; ++j){
if(j + 1 == nums.size())
return true;
if(j >= nums.size())
return false;
if(j + nums[j] > i + nums[i]){
i = j;
break;
}
if(j == i + nums[i]){
i += nums[i];
break;
}
}
if(nums[i] == 0)
return false;
}
return false;
}
}; | 27.8 | 50 | 0.305036 | [
"vector"
] |
24366498a55576e711546c44a94d302712022278 | 3,887 | cpp | C++ | Code/Tools/AWSNativeSDKInit/source/Platform/Android/InitializeCerts_Android.cpp | BreakerOfThings/o3de | f4c59f868c726470ec910623facd836047d059c3 | [
"Apache-2.0",
"MIT"
] | 11 | 2021-07-08T09:58:26.000Z | 2022-03-17T17:59:26.000Z | Code/Tools/AWSNativeSDKInit/source/Platform/Android/InitializeCerts_Android.cpp | RoddieKieley/o3de | e804fd2a4241b039a42d9fa54eaae17dc94a7a92 | [
"Apache-2.0",
"MIT"
] | 29 | 2021-07-06T19:33:52.000Z | 2022-03-22T10:27:49.000Z | Code/Tools/AWSNativeSDKInit/source/Platform/Android/InitializeCerts_Android.cpp | RoddieKieley/o3de | e804fd2a4241b039a42d9fa54eaae17dc94a7a92 | [
"Apache-2.0",
"MIT"
] | 4 | 2021-07-06T19:24:43.000Z | 2022-03-31T12:42:27.000Z | /*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include <AzCore/PlatformDef.h>
// The AWS Native SDK AWSAllocator triggers a warning due to accessing members of std::allocator directly.
// AWSAllocator.h(70): warning C4996: 'std::allocator<T>::pointer': warning STL4010: Various members of std::allocator are deprecated in
// C++17. Use std::allocator_traits instead of accessing these members directly. You can define
// _SILENCE_CXX17_OLD_ALLOCATOR_MEMBERS_DEPRECATION_WARNING or _SILENCE_ALL_CXX17_DEPRECATION_WARNINGS to acknowledge that you have received
// this warning.
AZ_PUSH_DISABLE_WARNING(4251 4996, "-Wunknown-warning-option")
#include <aws/core/utils/memory/stl/AWSString.h>
AZ_POP_DISABLE_WARNING
#include <AzCore/Android/Utils.h>
#include <AzCore/IO/FileIO.h>
#include <AzCore/IO/SystemFile.h>
#include <AzCore/std/containers/vector.h>
namespace AWSNativeSDKInit
{
namespace Platform
{
void CopyCaCertBundle()
{
AZStd::vector<char> contents;
AZStd::string certificatePath = "@products@/certificates/aws/cacert.pem";
AZStd::string publicStoragePath = AZ::Android::Utils::GetAppPublicStoragePath();
publicStoragePath.append("/certificates/aws/cacert.pem");
AZ::IO::FileIOBase* fileBase = AZ::IO::FileIOBase::GetInstance();
if (!fileBase->Exists(certificatePath.c_str()))
{
AZ_Error("AWSNativeSDKInit", false, "Certificate File(%s) does not exist.\n", certificatePath.c_str());
}
AZ::IO::HandleType fileHandle;
AZ::IO::Result fileResult = fileBase->Open(certificatePath.c_str(), AZ::IO::OpenMode::ModeRead, fileHandle);
if (!fileResult)
{
AZ_Error("AWSNativeSDKInit", false, "Failed to open certificate file with result %i\n", fileResult.GetResultCode());
}
AZ::u64 fileSize = 0;
fileBase->Size(fileHandle, fileSize);
if (fileSize == 0)
{
AZ_Error("AWSNativeSDKInit", false, "Given empty file(%s) as the certificate bundle.\n", certificatePath.c_str());
}
contents.resize(fileSize + 1);
fileResult = fileBase->Read(fileHandle, contents.data(), fileSize);
if (!fileResult)
{
AZ_Error(
"AWSNativeSDKInit", false, "Failed to read from the certificate bundle(%s) with result code(%i).\n", certificatePath.c_str(),
fileResult.GetResultCode());
}
AZ_Printf("AWSNativeSDKInit", "Certificate bundle is read successfully from %s", certificatePath.c_str());
AZ::IO::HandleType outFileHandle;
AZ::IO::Result outFileResult = fileBase->Open(publicStoragePath.c_str(), AZ::IO::OpenMode::ModeWrite, outFileHandle);
if (!outFileResult)
{
AZ_Error("AWSNativeSDKInit", false, "Failed to open the certificate bundle with result %i\n", fileResult.GetResultCode());
}
AZ::IO::Result writeFileResult = fileBase->Write(outFileHandle, contents.data(), fileSize);
if (!writeFileResult)
{
AZ_Error("AWSNativeSDKInit", false, "Failed to write the certificate bundle with result %i\n", writeFileResult.GetResultCode());
}
fileBase->Close(fileHandle);
fileBase->Close(outFileHandle);
AZ_Printf("AWSNativeSDKInit", "Certificate bundle successfully copied to %s", publicStoragePath.c_str());
}
} // namespace Platform
}
| 42.714286 | 146 | 0.628763 | [
"vector",
"3d"
] |
2436a413224af8a2a52aa1ff75e208f77825b0d4 | 3,694 | cxx | C++ | Tauola1_1_5/src/eventRecordInterfaces/TauolaHEPEVTEvent.cxx | klendathu2k/StarGenerator | 7dd407c41d4eea059ca96ded80d30bda0bc014a4 | [
"MIT"
] | 2 | 2018-12-24T19:37:00.000Z | 2022-02-28T06:57:20.000Z | Tauola1_1_5/src/eventRecordInterfaces/TauolaHEPEVTEvent.cxx | klendathu2k/StarGenerator | 7dd407c41d4eea059ca96ded80d30bda0bc014a4 | [
"MIT"
] | null | null | null | Tauola1_1_5/src/eventRecordInterfaces/TauolaHEPEVTEvent.cxx | klendathu2k/StarGenerator | 7dd407c41d4eea059ca96ded80d30bda0bc014a4 | [
"MIT"
] | null | null | null | #include "TauolaHEPEVTEvent.h"
#include "Log.h"
namespace Tauolapp
{
TauolaHEPEVTEvent::~TauolaHEPEVTEvent()
{
for(unsigned int i=0;i<particle_list.size();i++) delete particle_list[i];
}
TauolaHEPEVTEvent::TauolaHEPEVTEvent() {}
void TauolaHEPEVTEvent::addParticle(TauolaHEPEVTParticle *p)
{
p->setEvent(this);
p->setBarcode(particle_list.size());
particle_list.push_back(p);
}
TauolaHEPEVTParticle *TauolaHEPEVTEvent::getParticle(int i)
{
if( i<0 || i>=(int)particle_list.size() ) return NULL;
return particle_list[i];
}
int TauolaHEPEVTEvent::getParticleCount()
{
return particle_list.size();
}
// we have conflict in names, looks for -pdg_id also...
std::vector<TauolaParticle*> TauolaHEPEVTEvent::findParticles(int pdg_id){
std::vector<TauolaParticle*> list;
// Loop over all particles in the event looking
// for tau (or other) particle with specified pdg_id and -pdg_id
for(unsigned int i=0; i<particle_list.size(); i++)
{
if( abs(particle_list[i]->getPdgID() ) == pdg_id)
list.push_back(particle_list[i]);
}
return list;
}
// we have conflict in names, should be findStableTaus or have another argument.
std::vector<TauolaParticle*> TauolaHEPEVTEvent::findStableParticles(int pdg_id){
std::vector<TauolaParticle*> tau_list = findParticles(pdg_id);
std::vector<TauolaParticle*> stable_tau_list;
for(int i=0; i<(int) tau_list.size(); i++){
if(!tau_list.at(i)->hasDaughters())
stable_tau_list.push_back(tau_list[i]);
else
{
std::vector<TauolaParticle*> t = tau_list[i]->getDaughters();
//Ignore taus that we won't be decaying anyway
if(t.size()==1) continue;
if(t.size()==2 && (abs(t[0]->getPdgID())==15 || abs(t[1]->getPdgID())==15) ) continue;
Log::Warning()<<"Particle with pdg code "<<tau_list.at(i)->getPdgID()
<<" already has daughters" <<endl;
}
}
return stable_tau_list;
}
void TauolaHEPEVTEvent::print()
{
printf("TauolaHEPEVTEvent\n-----------------\n");
for(unsigned int i=0;i<particle_list.size();i++) particle_list[i]->print();
}
void TauolaHEPEVTEvent::clear()
{
for(unsigned int i=0;i<particle_list.size();i++) delete particle_list[i];
particle_list.clear();
}
#ifdef USE_HEPEVT_INTERFACE
void TauolaHEPEVTEvent::read_event_from_HEPEVT(TauolaHEPEVTEvent *evt)
{
if(evt==NULL) return;
for(int i=0; i<hepevt_.nhep; i++)
{
TauolaHEPEVTParticle *p = new TauolaHEPEVTParticle
(
hepevt_.idhep [i],
hepevt_.isthep[i],
hepevt_.phep [i][0],
hepevt_.phep [i][1],
hepevt_.phep [i][2],
hepevt_.phep [i][3],
hepevt_.phep [i][4],
hepevt_.jmohep[i][0]-1,
hepevt_.jmohep[i][1]-1,
hepevt_.jdahep[i][0]-1,
hepevt_.jdahep[i][1]-1
);
evt->addParticle(p);
}
}
void TauolaHEPEVTEvent::write_event_to_HEPEVT(TauolaHEPEVTEvent *evt)
{
if(evt==NULL) return;
hepevt_.nhep = evt->getParticleCount();
for(int i=0; i<hepevt_.nhep; i++)
{
TauolaHEPEVTParticle *p = evt->getParticle(i);
hepevt_.idhep [i] =p->getPdgID();
hepevt_.isthep[i] =p->getStatus();
hepevt_.phep [i][0]=p->getPx();
hepevt_.phep [i][1]=p->getPy();
hepevt_.phep [i][2]=p->getPz();
hepevt_.phep [i][3]=p->getE();
hepevt_.phep [i][4]=p->getMass();
hepevt_.jmohep[i][0]=p->getFirstMotherIndex() +1;
hepevt_.jmohep[i][1]=p->getSecondMotherIndex() +1;
hepevt_.jdahep[i][0]=p->getDaughterRangeStart()+1;
hepevt_.jdahep[i][1]=p->getDaughterRangeEnd() +1;
hepevt_.vhep [i][0]=0.0;
hepevt_.vhep [i][1]=0.0;
hepevt_.vhep [i][2]=0.0;
hepevt_.vhep [i][3]=0.0;
}
}
#endif
} // namespace Tauolapp
| 25.652778 | 92 | 0.649161 | [
"vector"
] |
0f843193b4b833d62ec573e7bfd971b463b7a958 | 50,319 | cc | C++ | src/connectivity/bluetooth/core/bt-host/fidl/helpers.cc | PlugFox/fuchsia | 39afe5230d41628b3c736a6e384393df954968c8 | [
"BSD-2-Clause"
] | 2 | 2021-12-29T10:11:08.000Z | 2022-01-04T15:37:09.000Z | src/connectivity/bluetooth/core/bt-host/fidl/helpers.cc | PlugFox/fuchsia | 39afe5230d41628b3c736a6e384393df954968c8 | [
"BSD-2-Clause"
] | null | null | null | src/connectivity/bluetooth/core/bt-host/fidl/helpers.cc | PlugFox/fuchsia | 39afe5230d41628b3c736a6e384393df954968c8 | [
"BSD-2-Clause"
] | null | null | null | // Copyright 2017 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "helpers.h"
#include <endian.h>
#include <algorithm>
#include <charconv>
#include <iterator>
#include <unordered_set>
#include "fuchsia/bluetooth/sys/cpp/fidl.h"
#include "src/connectivity/bluetooth/core/bt-host/att/att.h"
#include "src/connectivity/bluetooth/core/bt-host/common/advertising_data.h"
#include "src/connectivity/bluetooth/core/bt-host/common/log.h"
#include "src/connectivity/bluetooth/core/bt-host/gap/discovery_filter.h"
#include "src/connectivity/bluetooth/core/bt-host/gap/gap.h"
#include "src/connectivity/bluetooth/core/bt-host/sco/sco.h"
#include "src/connectivity/bluetooth/core/bt-host/sm/types.h"
#include "src/lib/fxl/strings/string_number_conversions.h"
using fuchsia::bluetooth::Bool;
using fuchsia::bluetooth::Error;
using fuchsia::bluetooth::ErrorCode;
using fuchsia::bluetooth::Int8;
using fuchsia::bluetooth::Status;
namespace fble = fuchsia::bluetooth::le;
namespace fbredr = fuchsia::bluetooth::bredr;
namespace fbt = fuchsia::bluetooth;
namespace fgatt = fuchsia::bluetooth::gatt;
namespace fhost = fuchsia::bluetooth::host;
namespace fsys = fuchsia::bluetooth::sys;
namespace faudio = fuchsia::hardware::audio;
namespace bthost::fidl_helpers {
namespace {
fbt::AddressType AddressTypeToFidl(bt::DeviceAddress::Type type) {
switch (type) {
case bt::DeviceAddress::Type::kBREDR:
[[fallthrough]];
case bt::DeviceAddress::Type::kLEPublic:
return fbt::AddressType::PUBLIC;
case bt::DeviceAddress::Type::kLERandom:
[[fallthrough]];
case bt::DeviceAddress::Type::kLEAnonymous:
return fbt::AddressType::RANDOM;
}
return fbt::AddressType::PUBLIC;
}
fbt::Address AddressToFidl(fbt::AddressType type, const bt::DeviceAddressBytes& value) {
fbt::Address output;
output.type = type;
bt::MutableBufferView value_dst(output.bytes.data(), output.bytes.size());
value_dst.Write(value.bytes());
return output;
}
fbt::Address AddressToFidl(const bt::DeviceAddress& input) {
return AddressToFidl(AddressTypeToFidl(input.type()), input.value());
}
bt::sm::SecurityProperties SecurityPropsFromFidl(const fsys::SecurityProperties& sec_prop) {
auto level = bt::sm::SecurityLevel::kEncrypted;
if (sec_prop.authenticated) {
level = bt::sm::SecurityLevel::kAuthenticated;
}
return bt::sm::SecurityProperties(level, sec_prop.encryption_key_size,
sec_prop.secure_connections);
}
fsys::SecurityProperties SecurityPropsToFidl(const bt::sm::SecurityProperties& sec_prop) {
return fsys::SecurityProperties{
.authenticated = sec_prop.authenticated(),
.secure_connections = sec_prop.secure_connections(),
// TODO(armansito): Declare the key size as uint8_t in bt::sm?
.encryption_key_size = static_cast<uint8_t>(sec_prop.enc_key_size()),
};
}
bt::sm::LTK LtkFromFidl(const fsys::Ltk& ltk) {
return bt::sm::LTK(SecurityPropsFromFidl(ltk.key.security),
bt::hci_spec::LinkKey(ltk.key.data.value, ltk.rand, ltk.ediv));
}
fsys::PeerKey LtkToFidlPeerKey(const bt::sm::LTK& ltk) {
return fsys::PeerKey{
.security = SecurityPropsToFidl(ltk.security()),
.data = fsys::Key{ltk.key().value()},
};
}
fsys::Ltk LtkToFidl(const bt::sm::LTK& ltk) {
return fsys::Ltk{
.key = LtkToFidlPeerKey(ltk),
.ediv = ltk.key().ediv(),
.rand = ltk.key().rand(),
};
}
bt::sm::Key PeerKeyFromFidl(const fsys::PeerKey& key) {
return bt::sm::Key(SecurityPropsFromFidl(key.security), key.data.value);
}
fsys::PeerKey PeerKeyToFidl(const bt::sm::Key& key) {
return fsys::PeerKey{
.security = SecurityPropsToFidl(key.security()),
.data = {key.value()},
};
}
fbt::DeviceClass DeviceClassToFidl(bt::DeviceClass input) {
auto bytes = input.bytes();
fbt::DeviceClass output{static_cast<uint32_t>(bytes[0] | (bytes[1] << 8) | (bytes[2] << 16))};
return output;
}
std::optional<bt::sdp::DataElement> FidlToDataElement(const fbredr::DataElement& fidl) {
bt::sdp::DataElement out;
switch (fidl.Which()) {
case fbredr::DataElement::Tag::kInt8:
return bt::sdp::DataElement(fidl.int8());
case fbredr::DataElement::Tag::kInt16:
return bt::sdp::DataElement(fidl.int16());
case fbredr::DataElement::Tag::kInt32:
return bt::sdp::DataElement(fidl.int32());
case fbredr::DataElement::Tag::kInt64:
return bt::sdp::DataElement(fidl.int64());
case fbredr::DataElement::Tag::kUint8:
return bt::sdp::DataElement(fidl.uint8());
case fbredr::DataElement::Tag::kUint16:
return bt::sdp::DataElement(fidl.uint16());
case fbredr::DataElement::Tag::kUint32:
return bt::sdp::DataElement(fidl.uint32());
case fbredr::DataElement::Tag::kUint64:
return bt::sdp::DataElement(fidl.uint64());
case fbredr::DataElement::Tag::kStr:
return bt::sdp::DataElement(fidl.str());
case fbredr::DataElement::Tag::kUrl:
out.SetUrl(fidl.url());
break;
case fbredr::DataElement::Tag::kB:
return bt::sdp::DataElement(fidl.b());
case fbredr::DataElement::Tag::kUuid:
out.Set(fidl_helpers::UuidFromFidl(fidl.uuid()));
break;
case fbredr::DataElement::Tag::kSequence: {
std::vector<bt::sdp::DataElement> seq;
for (const auto& fidl_elem : fidl.sequence()) {
auto it = FidlToDataElement(*fidl_elem);
if (!it) {
return std::nullopt;
}
seq.emplace_back(std::move(it.value()));
}
out.Set(std::move(seq));
break;
}
case fbredr::DataElement::Tag::kAlternatives: {
std::vector<bt::sdp::DataElement> alts;
for (const auto& fidl_elem : fidl.alternatives()) {
auto elem = FidlToDataElement(*fidl_elem);
if (!elem) {
return std::nullopt;
}
alts.emplace_back(std::move(elem.value()));
}
out.SetAlternative(std::move(alts));
break;
}
default:
// Types not handled: Null datatype (never used)
bt_log(WARN, "fidl", "Encountered FidlToDataElement type not handled.");
return std::nullopt;
}
return out;
}
bool AddProtocolDescriptorList(bt::sdp::ServiceRecord* rec,
bt::sdp::ServiceRecord::ProtocolListId id,
const ::std::vector<fbredr::ProtocolDescriptor>& descriptor_list) {
bt_log(TRACE, "fidl", "ProtocolDescriptorList %d", id);
for (auto& descriptor : descriptor_list) {
bt::sdp::DataElement protocol_params;
if (descriptor.params.size() > 1) {
std::vector<bt::sdp::DataElement> params;
for (auto& fidl_param : descriptor.params) {
auto bt_param = FidlToDataElement(fidl_param);
if (bt_param) {
params.emplace_back(std::move(bt_param.value()));
} else {
return false;
}
}
protocol_params.Set(std::move(params));
} else if (descriptor.params.size() == 1) {
auto param = FidlToDataElement(descriptor.params.front());
if (param) {
protocol_params = std::move(param).value();
} else {
return false;
}
protocol_params = FidlToDataElement(descriptor.params.front()).value();
}
bt_log(TRACE, "fidl", "Adding protocol descriptor: {%d : %s}",
fidl::ToUnderlying(descriptor.protocol), protocol_params.ToString().c_str());
rec->AddProtocolDescriptor(id, bt::UUID(static_cast<uint16_t>(descriptor.protocol)),
std::move(protocol_params));
}
return true;
}
// Returns true if the appearance value (in host byte order) is included in
// fuchsia.bluetooth.Appearance, which is a subset of Bluetooth Assigned Numbers, "Appearance
// Values" (https://www.bluetooth.com/specifications/assigned-numbers/).
//
// TODO(fxbug.dev/66358): Remove this compatibility check with the strict Appearance enum.
[[nodiscard]] bool IsAppearanceValid(uint16_t appearance_raw) {
switch (appearance_raw) {
case 0u: // UNKNOWN
[[fallthrough]];
case 64u: // PHONE
[[fallthrough]];
case 128u: // COMPUTER
[[fallthrough]];
case 192u: // WATCH
[[fallthrough]];
case 193u: // WATCH_SPORTS
[[fallthrough]];
case 256u: // CLOCK
[[fallthrough]];
case 320u: // DISPLAY
[[fallthrough]];
case 384u: // REMOTE_CONTROL
[[fallthrough]];
case 448u: // EYE_GLASSES
[[fallthrough]];
case 512u: // TAG
[[fallthrough]];
case 576u: // KEYRING
[[fallthrough]];
case 640u: // MEDIA_PLAYER
[[fallthrough]];
case 704u: // BARCODE_SCANNER
[[fallthrough]];
case 768u: // THERMOMETER
[[fallthrough]];
case 769u: // THERMOMETER_EAR
[[fallthrough]];
case 832u: // HEART_RATE_SENSOR
[[fallthrough]];
case 833u: // HEART_RATE_SENSOR_BELT
[[fallthrough]];
case 896u: // BLOOD_PRESSURE
[[fallthrough]];
case 897u: // BLOOD_PRESSURE_ARM
[[fallthrough]];
case 898u: // BLOOD_PRESSURE_WRIST
[[fallthrough]];
case 960u: // HID
[[fallthrough]];
case 961u: // HID_KEYBOARD
[[fallthrough]];
case 962u: // HID_MOUSE
[[fallthrough]];
case 963u: // HID_JOYSTICK
[[fallthrough]];
case 964u: // HID_GAMEPAD
[[fallthrough]];
case 965u: // HID_DIGITIZER_TABLET
[[fallthrough]];
case 966u: // HID_CARD_READER
[[fallthrough]];
case 967u: // HID_DIGITAL_PEN
[[fallthrough]];
case 968u: // HID_BARCODE_SCANNER
[[fallthrough]];
case 1024u: // GLUCOSE_METER
[[fallthrough]];
case 1088u: // RUNNING_WALKING_SENSOR
[[fallthrough]];
case 1089u: // RUNNING_WALKING_SENSOR_IN_SHOE
[[fallthrough]];
case 1090u: // RUNNING_WALKING_SENSOR_ON_SHOE
[[fallthrough]];
case 1091u: // RUNNING_WALKING_SENSOR_ON_HIP
[[fallthrough]];
case 1152u: // CYCLING
[[fallthrough]];
case 1153u: // CYCLING_COMPUTER
[[fallthrough]];
case 1154u: // CYCLING_SPEED_SENSOR
[[fallthrough]];
case 1155u: // CYCLING_CADENCE_SENSOR
[[fallthrough]];
case 1156u: // CYCLING_POWER_SENSOR
[[fallthrough]];
case 1157u: // CYCLING_SPEED_AND_CADENCE_SENSOR
[[fallthrough]];
case 3136u: // PULSE_OXIMETER
[[fallthrough]];
case 3137u: // PULSE_OXIMETER_FINGERTIP
[[fallthrough]];
case 3138u: // PULSE_OXIMETER_WRIST
[[fallthrough]];
case 3200u: // WEIGHT_SCALE
[[fallthrough]];
case 3264u: // PERSONAL_MOBILITY
[[fallthrough]];
case 3265u: // PERSONAL_MOBILITY_WHEELCHAIR
[[fallthrough]];
case 3266u: // PERSONAL_MOBILITY_SCOOTER
[[fallthrough]];
case 3328u: // GLUCOSE_MONITOR
[[fallthrough]];
case 5184u: // SPORTS_ACTIVITY
[[fallthrough]];
case 5185u: // SPORTS_ACTIVITY_LOCATION_DISPLAY
[[fallthrough]];
case 5186u: // SPORTS_ACTIVITY_LOCATION_AND_NAV_DISPLAY
[[fallthrough]];
case 5187u: // SPORTS_ACTIVITY_LOCATION_POD
[[fallthrough]];
case 5188u: // SPORTS_ACTIVITY_LOCATION_AND_NAV_POD
return true;
default:
return false;
}
}
[[nodiscard]] std::optional<fbt::Appearance> AppearanceToFidl(uint16_t appearance_raw) {
if (IsAppearanceValid(appearance_raw)) {
return static_cast<fbt::Appearance>(appearance_raw);
}
return std::nullopt;
}
} // namespace
std::optional<bt::PeerId> PeerIdFromString(const std::string& id) {
if (id.empty()) {
return std::nullopt;
}
uint64_t value = 0;
auto [_, error] = std::from_chars(id.data(), id.data() + id.size(), value, /*base=*/16);
if (error != std::errc()) {
return std::nullopt;
}
return bt::PeerId(value);
}
ErrorCode HostErrorToFidlDeprecated(bt::HostError host_error) {
switch (host_error) {
case bt::HostError::kFailed:
return ErrorCode::FAILED;
case bt::HostError::kTimedOut:
return ErrorCode::TIMED_OUT;
case bt::HostError::kInvalidParameters:
return ErrorCode::INVALID_ARGUMENTS;
case bt::HostError::kCanceled:
return ErrorCode::CANCELED;
case bt::HostError::kInProgress:
return ErrorCode::IN_PROGRESS;
case bt::HostError::kNotSupported:
return ErrorCode::NOT_SUPPORTED;
case bt::HostError::kNotFound:
return ErrorCode::NOT_FOUND;
case bt::HostError::kProtocolError:
return ErrorCode::PROTOCOL_ERROR;
default:
break;
}
return ErrorCode::FAILED;
}
Status NewFidlError(ErrorCode error_code, std::string description) {
Status status;
status.error = std::make_unique<Error>();
status.error->error_code = error_code;
status.error->description = description;
return status;
}
fsys::Error HostErrorToFidl(bt::HostError error) {
ZX_DEBUG_ASSERT(error != bt::HostError::kNoError);
switch (error) {
case bt::HostError::kFailed:
return fsys::Error::FAILED;
case bt::HostError::kTimedOut:
return fsys::Error::TIMED_OUT;
case bt::HostError::kInvalidParameters:
return fsys::Error::INVALID_ARGUMENTS;
case bt::HostError::kCanceled:
return fsys::Error::CANCELED;
case bt::HostError::kInProgress:
return fsys::Error::IN_PROGRESS;
case bt::HostError::kNotSupported:
return fsys::Error::NOT_SUPPORTED;
case bt::HostError::kNotFound:
return fsys::Error::PEER_NOT_FOUND;
default:
break;
}
return fsys::Error::FAILED;
}
fuchsia::bluetooth::gatt::Error GattStatusToFidl(bt::Status<bt::att::ErrorCode> status) {
ZX_ASSERT(!status.is_success());
switch (status.error()) {
case bt::HostError::kPacketMalformed:
return fuchsia::bluetooth::gatt::Error::INVALID_RESPONSE;
case bt::HostError::kProtocolError:
switch (status.protocol_error()) {
case bt::att::ErrorCode::kInsufficientAuthorization:
return fuchsia::bluetooth::gatt::Error::INSUFFICIENT_AUTHORIZATION;
case bt::att::ErrorCode::kInsufficientAuthentication:
return fuchsia::bluetooth::gatt::Error::INSUFFICIENT_AUTHENTICATION;
case bt::att::ErrorCode::kInsufficientEncryptionKeySize:
return fuchsia::bluetooth::gatt::Error::INSUFFICIENT_ENCRYPTION_KEY_SIZE;
case bt::att::ErrorCode::kInsufficientEncryption:
return fuchsia::bluetooth::gatt::Error::INSUFFICIENT_ENCRYPTION;
case bt::att::ErrorCode::kReadNotPermitted:
return fuchsia::bluetooth::gatt::Error::READ_NOT_PERMITTED;
default:
return fuchsia::bluetooth::gatt::Error::FAILURE;
}
default:
return fuchsia::bluetooth::gatt::Error::FAILURE;
}
}
fuchsia::bluetooth::gatt2::Error AttStatusToGattFidlError(bt::Status<bt::att::ErrorCode> status) {
ZX_ASSERT(!status.is_success());
switch (status.error()) {
case bt::HostError::kPacketMalformed:
return fuchsia::bluetooth::gatt2::Error::INVALID_PDU;
case bt::HostError::kInvalidParameters:
return fuchsia::bluetooth::gatt2::Error::INVALID_PARAMETERS;
case bt::HostError::kProtocolError:
switch (status.protocol_error()) {
case bt::att::ErrorCode::kInsufficientAuthorization:
return fuchsia::bluetooth::gatt2::Error::INSUFFICIENT_AUTHORIZATION;
case bt::att::ErrorCode::kInsufficientAuthentication:
return fuchsia::bluetooth::gatt2::Error::INSUFFICIENT_AUTHENTICATION;
case bt::att::ErrorCode::kInsufficientEncryptionKeySize:
return fuchsia::bluetooth::gatt2::Error::INSUFFICIENT_ENCRYPTION_KEY_SIZE;
case bt::att::ErrorCode::kInsufficientEncryption:
return fuchsia::bluetooth::gatt2::Error::INSUFFICIENT_ENCRYPTION;
case bt::att::ErrorCode::kReadNotPermitted:
return fuchsia::bluetooth::gatt2::Error::READ_NOT_PERMITTED;
case bt::att::ErrorCode::kInvalidHandle:
return fuchsia::bluetooth::gatt2::Error::INVALID_HANDLE;
default:
return fuchsia::bluetooth::gatt2::Error::UNLIKELY_ERROR;
}
default:
return fuchsia::bluetooth::gatt2::Error::UNLIKELY_ERROR;
}
}
bt::UUID UuidFromFidl(const fuchsia::bluetooth::Uuid& input) {
// Conversion must always succeed given the defined size of |input|.
static_assert(sizeof(input.value) == 16, "FIDL UUID definition malformed!");
return bt::UUID(bt::BufferView(input.value.data(), input.value.size()));
}
fuchsia::bluetooth::Uuid UuidToFidl(const bt::UUID& uuid) {
fuchsia::bluetooth::Uuid output;
// Conversion must always succeed given the defined size of |input|.
static_assert(sizeof(output.value) == 16, "FIDL UUID definition malformed!");
output.value = uuid.value();
return output;
}
bt::sm::IOCapability IoCapabilityFromFidl(fsys::InputCapability input,
fsys::OutputCapability output) {
if (input == fsys::InputCapability::NONE && output == fsys::OutputCapability::NONE) {
return bt::sm::IOCapability::kNoInputNoOutput;
} else if (input == fsys::InputCapability::KEYBOARD &&
output == fsys::OutputCapability::DISPLAY) {
return bt::sm::IOCapability::kKeyboardDisplay;
} else if (input == fsys::InputCapability::KEYBOARD && output == fsys::OutputCapability::NONE) {
return bt::sm::IOCapability::kKeyboardOnly;
} else if (input == fsys::InputCapability::NONE && output == fsys::OutputCapability::DISPLAY) {
return bt::sm::IOCapability::kDisplayOnly;
} else if (input == fsys::InputCapability::CONFIRMATION &&
output == fsys::OutputCapability::DISPLAY) {
return bt::sm::IOCapability::kDisplayYesNo;
}
return bt::sm::IOCapability::kNoInputNoOutput;
}
bt::gap::LeSecurityMode LeSecurityModeFromFidl(const fsys::LeSecurityMode mode) {
switch (mode) {
case fsys::LeSecurityMode::MODE_1:
return bt::gap::LeSecurityMode::Mode1;
case fsys::LeSecurityMode::SECURE_CONNECTIONS_ONLY:
return bt::gap::LeSecurityMode::SecureConnectionsOnly;
}
bt_log(WARN, "fidl", "FIDL security mode not recognized, defaulting to SecureConnectionsOnly");
return bt::gap::LeSecurityMode::SecureConnectionsOnly;
}
std::optional<bt::sm::SecurityLevel> SecurityLevelFromFidl(const fsys::PairingSecurityLevel level) {
switch (level) {
case fsys::PairingSecurityLevel::ENCRYPTED:
return bt::sm::SecurityLevel::kEncrypted;
case fsys::PairingSecurityLevel::AUTHENTICATED:
return bt::sm::SecurityLevel::kAuthenticated;
default:
return std::nullopt;
};
}
fsys::TechnologyType TechnologyTypeToFidl(bt::gap::TechnologyType type) {
switch (type) {
case bt::gap::TechnologyType::kLowEnergy:
return fsys::TechnologyType::LOW_ENERGY;
case bt::gap::TechnologyType::kClassic:
return fsys::TechnologyType::CLASSIC;
case bt::gap::TechnologyType::kDualMode:
return fsys::TechnologyType::DUAL_MODE;
default:
ZX_PANIC("invalid technology type: %u", static_cast<unsigned int>(type));
break;
}
// This should never execute.
return fsys::TechnologyType::DUAL_MODE;
}
fsys::HostInfo HostInfoToFidl(const bt::gap::Adapter& adapter) {
fsys::HostInfo info;
info.set_id(fbt::HostId{adapter.identifier().value()});
info.set_technology(TechnologyTypeToFidl(adapter.state().type()));
info.set_address(AddressToFidl(fbt::AddressType::PUBLIC, adapter.state().controller_address()));
info.set_local_name(adapter.local_name());
info.set_discoverable(adapter.IsDiscoverable());
info.set_discovering(adapter.IsDiscovering());
return info;
}
fsys::Peer PeerToFidl(const bt::gap::Peer& peer) {
fsys::Peer output;
output.set_id(fbt::PeerId{peer.identifier().value()});
output.set_address(AddressToFidl(peer.address()));
output.set_technology(TechnologyTypeToFidl(peer.technology()));
output.set_connected(peer.connected());
output.set_bonded(peer.bonded());
if (peer.name()) {
output.set_name(*peer.name());
}
if (peer.le()) {
const std::optional<bt::AdvertisingData>& adv_data = peer.le()->parsed_advertising_data();
if (adv_data.has_value()) {
if (adv_data->appearance().has_value()) {
if (auto appearance = AppearanceToFidl(adv_data->appearance().value())) {
output.set_appearance(appearance.value());
} else {
bt_log(DEBUG, "fidl", "omitting unencodeable appearance %#.4x of peer %s",
adv_data->appearance().value(), bt_str(peer.identifier()));
}
}
if (adv_data->tx_power()) {
output.set_tx_power(adv_data->tx_power().value());
}
}
}
if (peer.bredr() && peer.bredr()->device_class()) {
output.set_device_class(DeviceClassToFidl(*peer.bredr()->device_class()));
}
if (peer.rssi() != bt::hci_spec::kRSSIInvalid) {
output.set_rssi(peer.rssi());
}
if (peer.bredr()) {
std::transform(peer.bredr()->services().begin(), peer.bredr()->services().end(),
std::back_inserter(*output.mutable_bredr_services()), UuidToFidl);
}
// TODO(fxbug.dev/57344): Populate le_service UUIDs based on GATT results as well as advertising
// and inquiry data.
return output;
}
std::optional<bt::DeviceAddress> AddressFromFidlBondingData(
const fuchsia::bluetooth::sys::BondingData& bond) {
bt::DeviceAddressBytes bytes(bond.address().bytes);
bt::DeviceAddress::Type type;
if (bond.has_bredr_bond()) {
// A random identity address can only be present in a LE-only bond.
if (bond.address().type == fbt::AddressType::RANDOM) {
bt_log(WARN, "fidl", "BR/EDR or Dual-Mode bond cannot have a random identity address!");
return std::nullopt;
}
// TODO(fxbug.dev/2761): We currently assign kBREDR as the address type for dual-mode bonds.
// This makes address management for dual-mode devices a bit confusing as we have two "public"
// address types (i.e. kBREDR and kLEPublic). We should align the stack address types with
// the FIDL address types, such that both kBREDR and kLEPublic are represented as the same
// kind of "PUBLIC".
type = bt::DeviceAddress::Type::kBREDR;
} else {
type = bond.address().type == fbt::AddressType::RANDOM ? bt::DeviceAddress::Type::kLERandom
: bt::DeviceAddress::Type::kLEPublic;
}
bt::DeviceAddress address(type, bytes);
if (!address.IsPublic() && !address.IsStaticRandom()) {
bt_log(ERROR, "fidl", "%s: BondingData address is not public or static random (address: %s)",
__FUNCTION__, bt_str(address));
return std::nullopt;
}
return address;
}
bt::sm::PairingData LePairingDataFromFidl(bt::DeviceAddress peer_address,
const fuchsia::bluetooth::sys::LeBondData& data) {
bt::sm::PairingData result;
if (data.has_peer_ltk()) {
result.peer_ltk = LtkFromFidl(data.peer_ltk());
}
if (data.has_local_ltk()) {
result.local_ltk = LtkFromFidl(data.local_ltk());
}
if (data.has_irk()) {
result.irk = PeerKeyFromFidl(data.irk());
// If there is an IRK, there must also be an identity address. Assume that the identity
// address is the peer address, since the peer address is set to the identity address upon
// bonding.
result.identity_address = peer_address;
}
if (data.has_csrk()) {
result.csrk = PeerKeyFromFidl(data.csrk());
}
return result;
}
std::optional<bt::sm::LTK> BredrKeyFromFidl(const fsys::BredrBondData& data) {
if (!data.has_link_key()) {
return std::nullopt;
}
auto key = PeerKeyFromFidl(data.link_key());
return bt::sm::LTK(key.security(), bt::hci_spec::LinkKey(key.value(), 0, 0));
}
std::vector<bt::UUID> BredrServicesFromFidl(const fuchsia::bluetooth::sys::BredrBondData& data) {
std::vector<bt::UUID> services_out;
if (data.has_services()) {
std::transform(data.services().begin(), data.services().end(), std::back_inserter(services_out),
UuidFromFidl);
}
return services_out;
}
fuchsia::bluetooth::sys::BondingData PeerToFidlBondingData(const bt::gap::Adapter& adapter,
const bt::gap::Peer& peer) {
fsys::BondingData out;
out.set_identifier(fbt::PeerId{peer.identifier().value()});
out.set_local_address(
AddressToFidl(fbt::AddressType::PUBLIC, adapter.state().controller_address()));
out.set_address(AddressToFidl(peer.address()));
if (peer.name()) {
out.set_name(*peer.name());
}
// LE
if (peer.le() && peer.le()->bond_data()) {
fsys::LeBondData out_le;
const bt::sm::PairingData& bond = *peer.le()->bond_data();
// TODO(armansito): Store the peer's preferred connection parameters.
// TODO(fxbug.dev/59645): Store GATT and AD service UUIDs.
if (bond.local_ltk) {
out_le.set_local_ltk(LtkToFidl(*bond.local_ltk));
}
if (bond.peer_ltk) {
out_le.set_peer_ltk(LtkToFidl(*bond.peer_ltk));
}
if (bond.irk) {
out_le.set_irk(PeerKeyToFidl(*bond.irk));
}
if (bond.csrk) {
out_le.set_csrk(PeerKeyToFidl(*bond.csrk));
}
out.set_le_bond(std::move(out_le));
}
// BR/EDR
if (peer.bredr() && peer.bredr()->link_key()) {
fsys::BredrBondData out_bredr;
// TODO(fxbug.dev/1262): Populate with history of role switches.
const auto& services = peer.bredr()->services();
std::transform(services.begin(), services.end(),
std::back_inserter(*out_bredr.mutable_services()), UuidToFidl);
out_bredr.set_link_key(LtkToFidlPeerKey(*peer.bredr()->link_key()));
out.set_bredr_bond(std::move(out_bredr));
}
return out;
}
fble::RemoteDevicePtr NewLERemoteDevice(const bt::gap::Peer& peer) {
bt::AdvertisingData ad;
if (!peer.le()) {
return nullptr;
}
auto fidl_device = std::make_unique<fble::RemoteDevice>();
fidl_device->identifier = peer.identifier().ToString();
fidl_device->connectable = peer.connectable();
// Initialize advertising data only if its non-empty.
const std::optional<bt::AdvertisingData>& adv_data = peer.le()->parsed_advertising_data();
if (adv_data.has_value()) {
auto data = fidl_helpers::AdvertisingDataToFidlDeprecated(adv_data.value());
fidl_device->advertising_data =
std::make_unique<fble::AdvertisingDataDeprecated>(std::move(data));
} else if (peer.le()->advertising_data().size()) {
// If the peer's raw advertising_data has been set (which is the case if the size is non-0),
// but failed to parse, then this conversion failed.
return nullptr;
}
if (peer.rssi() != bt::hci_spec::kRSSIInvalid) {
fidl_device->rssi = std::make_unique<Int8>();
fidl_device->rssi->value = peer.rssi();
}
return fidl_device;
}
bool IsScanFilterValid(const fble::ScanFilter& fidl_filter) {
// |service_uuids| is the only field that can potentially contain invalid
// data, since they are represented as strings.
if (!fidl_filter.service_uuids)
return true;
for (const auto& uuid_str : *fidl_filter.service_uuids) {
if (!bt::IsStringValidUuid(uuid_str))
return false;
}
return true;
}
bool PopulateDiscoveryFilter(const fble::ScanFilter& fidl_filter,
bt::gap::DiscoveryFilter* out_filter) {
ZX_DEBUG_ASSERT(out_filter);
if (fidl_filter.service_uuids) {
std::vector<bt::UUID> uuids;
for (const auto& uuid_str : *fidl_filter.service_uuids) {
bt::UUID uuid;
if (!bt::StringToUuid(uuid_str, &uuid)) {
bt_log(WARN, "fidl", "invalid service UUID given to scan filter: %s", uuid_str.c_str());
return false;
}
uuids.push_back(uuid);
}
if (!uuids.empty())
out_filter->set_service_uuids(uuids);
}
if (fidl_filter.connectable) {
out_filter->set_connectable(fidl_filter.connectable->value);
}
if (fidl_filter.manufacturer_identifier) {
out_filter->set_manufacturer_code(fidl_filter.manufacturer_identifier->value);
}
if (fidl_filter.name_substring && !fidl_filter.name_substring.value_or("").empty()) {
out_filter->set_name_substring(fidl_filter.name_substring.value_or(""));
}
if (fidl_filter.max_path_loss) {
out_filter->set_pathloss(fidl_filter.max_path_loss->value);
}
return true;
}
bt::gap::DiscoveryFilter DiscoveryFilterFromFidl(
const fuchsia::bluetooth::le::Filter& fidl_filter) {
bt::gap::DiscoveryFilter out;
if (fidl_filter.has_service_uuid()) {
out.set_service_uuids({bt::UUID(fidl_filter.service_uuid().value)});
}
// TODO(fxbug.dev/77549): Set service data UUIDs.
if (fidl_filter.has_manufacturer_id()) {
out.set_manufacturer_code(fidl_filter.manufacturer_id());
}
if (fidl_filter.has_connectable()) {
out.set_connectable(fidl_filter.connectable());
}
if (fidl_filter.has_name()) {
out.set_name_substring(fidl_filter.name());
}
if (fidl_filter.has_max_path_loss()) {
out.set_pathloss(fidl_filter.max_path_loss());
}
return out;
}
bt::gap::AdvertisingInterval AdvertisingIntervalFromFidl(fble::AdvertisingModeHint mode_hint) {
switch (mode_hint) {
case fble::AdvertisingModeHint::VERY_FAST:
return bt::gap::AdvertisingInterval::FAST1;
case fble::AdvertisingModeHint::FAST:
return bt::gap::AdvertisingInterval::FAST2;
case fble::AdvertisingModeHint::SLOW:
return bt::gap::AdvertisingInterval::SLOW;
}
return bt::gap::AdvertisingInterval::SLOW;
}
std::optional<bt::AdvertisingData> AdvertisingDataFromFidl(const fble::AdvertisingData& input) {
bt::AdvertisingData output;
if (input.has_name()) {
if (!output.SetLocalName(input.name())) {
return std::nullopt;
}
}
if (input.has_appearance()) {
output.SetAppearance(static_cast<uint16_t>(input.appearance()));
}
if (input.has_tx_power_level()) {
output.SetTxPower(input.tx_power_level());
}
if (input.has_service_uuids()) {
for (const auto& uuid : input.service_uuids()) {
bt::UUID bt_uuid = UuidFromFidl(uuid);
if (!output.AddServiceUuid(bt_uuid)) {
bt_log(WARN, "fidl",
"Received more Service UUIDs than fit in a single AD - truncating UUID %s",
bt_str(bt_uuid));
}
}
}
if (input.has_service_data()) {
for (const auto& entry : input.service_data()) {
if (!output.SetServiceData(UuidFromFidl(entry.uuid), bt::BufferView(entry.data))) {
return std::nullopt;
}
}
}
if (input.has_manufacturer_data()) {
for (const auto& entry : input.manufacturer_data()) {
bt::BufferView data(entry.data);
if (!output.SetManufacturerData(entry.company_id, data)) {
return std::nullopt;
}
}
}
if (input.has_uris()) {
for (const auto& uri : input.uris()) {
if (!output.AddUri(uri)) {
return std::nullopt;
}
}
}
return output;
}
fble::AdvertisingData AdvertisingDataToFidl(const bt::AdvertisingData& input) {
fble::AdvertisingData output;
if (input.local_name()) {
output.set_name(*input.local_name());
}
if (input.appearance()) {
// TODO(fxbug.dev/66358): Remove this to allow for passing arbitrary appearance values to
// clients in a way that's forward-compatible with future BLE revisions.
const uint16_t appearance_raw = input.appearance().value();
if (auto appearance = AppearanceToFidl(appearance_raw)) {
output.set_appearance(appearance.value());
} else {
bt_log(DEBUG, "fidl", "omitting unencodeable appearance %#.4x of peer %s", appearance_raw,
input.local_name().value_or("").c_str());
}
}
if (input.tx_power()) {
output.set_tx_power_level(*input.tx_power());
}
std::unordered_set<bt::UUID> service_uuids = input.service_uuids();
if (!service_uuids.empty()) {
std::vector<fbt::Uuid> uuids;
uuids.reserve(service_uuids.size());
for (const auto& uuid : service_uuids) {
uuids.push_back(fbt::Uuid{uuid.value()});
}
output.set_service_uuids(std::move(uuids));
}
if (!input.service_data_uuids().empty()) {
std::vector<fble::ServiceData> entries;
for (const auto& uuid : input.service_data_uuids()) {
auto data = input.service_data(uuid);
fble::ServiceData entry{fbt::Uuid{uuid.value()}, data.ToVector()};
entries.push_back(std::move(entry));
}
output.set_service_data(std::move(entries));
}
if (!input.manufacturer_data_ids().empty()) {
std::vector<fble::ManufacturerData> entries;
for (const auto& id : input.manufacturer_data_ids()) {
auto data = input.manufacturer_data(id);
fble::ManufacturerData entry{id, data.ToVector()};
entries.push_back(std::move(entry));
}
output.set_manufacturer_data(std::move(entries));
}
if (!input.uris().empty()) {
std::vector<std::string> uris;
for (const auto& uri : input.uris()) {
uris.push_back(uri);
}
output.set_uris(std::move(uris));
}
return output;
}
fble::AdvertisingDataDeprecated AdvertisingDataToFidlDeprecated(const bt::AdvertisingData& input) {
fble::AdvertisingDataDeprecated output;
if (input.local_name()) {
output.name = *input.local_name();
}
if (input.appearance()) {
output.appearance = std::make_unique<fbt::UInt16>();
output.appearance->value = *input.appearance();
}
if (input.tx_power()) {
output.tx_power_level = std::make_unique<fbt::Int8>();
output.tx_power_level->value = *input.tx_power();
}
if (!input.service_uuids().empty()) {
output.service_uuids.emplace();
for (const auto& uuid : input.service_uuids()) {
output.service_uuids->push_back(uuid.ToString());
}
}
if (!input.service_data_uuids().empty()) {
output.service_data.emplace();
for (const auto& uuid : input.service_data_uuids()) {
auto data = input.service_data(uuid);
fble::ServiceDataEntry entry{uuid.ToString(), data.ToVector()};
output.service_data->push_back(std::move(entry));
}
}
if (!input.manufacturer_data_ids().empty()) {
output.manufacturer_specific_data.emplace();
for (const auto& id : input.manufacturer_data_ids()) {
auto data = input.manufacturer_data(id);
fble::ManufacturerSpecificDataEntry entry{id, data.ToVector()};
output.manufacturer_specific_data->push_back(std::move(entry));
}
}
if (!input.uris().empty()) {
output.uris.emplace();
for (const auto& uri : input.uris()) {
output.uris->push_back(uri);
}
}
return output;
}
fuchsia::bluetooth::le::ScanData AdvertisingDataToFidlScanData(const bt::AdvertisingData& input,
zx::time timestamp) {
// Reuse bt::AdvertisingData -> fble::AdvertisingData utility, since most fields are the same as
// fble::ScanData.
fble::AdvertisingData fidl_adv_data = AdvertisingDataToFidl(input);
fble::ScanData out;
if (fidl_adv_data.has_tx_power_level()) {
out.set_tx_power(fidl_adv_data.tx_power_level());
}
if (fidl_adv_data.has_appearance()) {
out.set_appearance(fidl_adv_data.appearance());
}
if (fidl_adv_data.has_service_uuids()) {
out.set_service_uuids(std::move(*fidl_adv_data.mutable_service_uuids()));
}
if (fidl_adv_data.has_service_data()) {
out.set_service_data(std::move(*fidl_adv_data.mutable_service_data()));
}
if (fidl_adv_data.has_manufacturer_data()) {
out.set_manufacturer_data(std::move(*fidl_adv_data.mutable_manufacturer_data()));
}
if (fidl_adv_data.has_uris()) {
out.set_uris(std::move(*fidl_adv_data.mutable_uris()));
}
out.set_timestamp(timestamp.get());
return out;
}
fble::Peer PeerToFidlLe(const bt::gap::Peer& peer) {
ZX_ASSERT(peer.le());
fble::Peer output;
output.set_id(fbt::PeerId{peer.identifier().value()});
output.set_connectable(peer.connectable());
if (peer.rssi() != bt::hci_spec::kRSSIInvalid) {
output.set_rssi(peer.rssi());
}
const std::optional<bt::AdvertisingData>& advertising_data = peer.le()->parsed_advertising_data();
if (advertising_data.has_value()) {
std::optional<zx::time> timestamp = peer.le()->parsed_advertising_data_timestamp();
output.set_advertising_data(AdvertisingDataToFidl(advertising_data.value()));
output.set_data(AdvertisingDataToFidlScanData(advertising_data.value(), timestamp.value()));
}
if (peer.name()) {
output.set_name(peer.name().value());
}
output.set_bonded(peer.bonded());
output.set_last_updated(peer.last_updated().get());
return output;
}
bt::gatt::ReliableMode ReliableModeFromFidl(const fgatt::WriteOptions& write_options) {
return (write_options.has_reliable_mode() &&
write_options.reliable_mode() == fgatt::ReliableMode::ENABLED)
? bt::gatt::ReliableMode::kEnabled
: bt::gatt::ReliableMode::kDisabled;
}
// TODO(fxbug.dev/63438): The 64 bit `fidl_gatt_id` can overflow the 16 bits of a bt:att::Handle
// that underlies CharacteristicHandles when directly casted. Fix this.
bt::gatt::CharacteristicHandle CharacteristicHandleFromFidl(uint64_t fidl_gatt_id) {
if (fidl_gatt_id > std::numeric_limits<bt::att::Handle>::max()) {
bt_log(ERROR, "fidl",
"Casting a 64-bit FIDL GATT ID with `bits[16, 63] != 0` (0x%lX) to 16-bit "
"Characteristic Handle",
fidl_gatt_id);
}
return bt::gatt::CharacteristicHandle(static_cast<bt::att::Handle>(fidl_gatt_id));
}
// TODO(fxbug.dev/63438): The 64 bit `fidl_gatt_id` can overflow the 16 bits of a bt:att::Handle
// that underlies DescriptorHandles when directly casted. Fix this.
bt::gatt::DescriptorHandle DescriptorHandleFromFidl(uint64_t fidl_gatt_id) {
if (fidl_gatt_id > std::numeric_limits<bt::att::Handle>::max()) {
bt_log(ERROR, "fidl",
"Casting a 64-bit FIDL GATT ID with `bits[16, 63] != 0` (0x%lX) to 16-bit Descriptor "
"Handle",
fidl_gatt_id);
}
return bt::gatt::DescriptorHandle(static_cast<bt::att::Handle>(fidl_gatt_id));
}
fpromise::result<bt::sdp::ServiceRecord, fuchsia::bluetooth::ErrorCode>
ServiceDefinitionToServiceRecord(const fuchsia::bluetooth::bredr::ServiceDefinition& definition) {
bt::sdp::ServiceRecord rec;
std::vector<bt::UUID> classes;
if (!definition.has_service_class_uuids()) {
bt_log(WARN, "fidl", "Advertised service contains no Service UUIDs");
return fpromise::error(fuchsia::bluetooth::ErrorCode::INVALID_ARGUMENTS);
}
for (auto& uuid : definition.service_class_uuids()) {
bt::UUID btuuid = fidl_helpers::UuidFromFidl(uuid);
bt_log(TRACE, "fidl", "Setting Service Class UUID %s", bt_str(btuuid));
classes.emplace_back(std::move(btuuid));
}
rec.SetServiceClassUUIDs(classes);
if (definition.has_protocol_descriptor_list()) {
if (!AddProtocolDescriptorList(&rec, bt::sdp::ServiceRecord::kPrimaryProtocolList,
definition.protocol_descriptor_list())) {
bt_log(ERROR, "fidl", "Failed to add protocol descriptor list");
return fpromise::error(fuchsia::bluetooth::ErrorCode::INVALID_ARGUMENTS);
}
}
if (definition.has_additional_protocol_descriptor_lists()) {
// It's safe to iterate through this list with a ProtocolListId as ProtocolListId = uint8_t,
// and std::numeric_limits<uint8_t>::max() == 255 == the MAX_SEQUENCE_LENGTH vector limit from
// fuchsia.bluetooth.bredr/ServiceDefinition.additional_protocol_descriptor_lists.
ZX_ASSERT(definition.additional_protocol_descriptor_lists().size() <=
std::numeric_limits<bt::sdp::ServiceRecord::ProtocolListId>::max());
bt::sdp::ServiceRecord::ProtocolListId protocol_list_id = 1;
for (const auto& descriptor_list : definition.additional_protocol_descriptor_lists()) {
if (!AddProtocolDescriptorList(&rec, protocol_list_id, descriptor_list)) {
bt_log(ERROR, "fidl", "Failed to add additional protocol descriptor list");
return fpromise::error(fuchsia::bluetooth::ErrorCode::INVALID_ARGUMENTS);
}
protocol_list_id++;
}
}
if (definition.has_profile_descriptors()) {
for (const auto& profile : definition.profile_descriptors()) {
bt_log(TRACE, "fidl", "Adding Profile %#hx v%d.%d", profile.profile_id, profile.major_version,
profile.minor_version);
rec.AddProfile(bt::UUID(uint16_t(profile.profile_id)), profile.major_version,
profile.minor_version);
}
}
if (definition.has_information()) {
for (const auto& info : definition.information()) {
if (!info.has_language()) {
return fpromise::error(fuchsia::bluetooth::ErrorCode::INVALID_ARGUMENTS);
}
std::string language = info.language();
std::string name, description, provider;
if (info.has_name()) {
name = info.name();
}
if (info.has_description()) {
description = info.description();
}
if (info.has_provider()) {
provider = info.provider();
}
bt_log(TRACE, "fidl", "Adding Info (%s): (%s, %s, %s)", language.c_str(), name.c_str(),
description.c_str(), provider.c_str());
rec.AddInfo(language, name, description, provider);
}
}
if (definition.has_additional_attributes()) {
for (const auto& attribute : definition.additional_attributes()) {
auto elem = FidlToDataElement(attribute.element);
if (elem) {
bt_log(TRACE, "fidl", "Adding attribute %#x : %s", attribute.id,
elem.value().ToString().c_str());
rec.SetAttribute(attribute.id, std::move(elem.value()));
}
}
}
return fpromise::ok(std::move(rec));
}
bt::gap::BrEdrSecurityRequirements FidlToBrEdrSecurityRequirements(
const fbredr::ChannelParameters& fidl) {
bt::gap::BrEdrSecurityRequirements requirements{.authentication = false,
.secure_connections = false};
if (fidl.has_security_requirements()) {
if (fidl.security_requirements().has_authentication_required()) {
requirements.authentication = fidl.security_requirements().authentication_required();
}
if (fidl.security_requirements().has_secure_connections_required()) {
requirements.secure_connections = fidl.security_requirements().secure_connections_required();
}
}
return requirements;
}
bt::sco::ParameterSet FidlToScoParameterSet(const fbredr::HfpParameterSet param_set) {
switch (param_set) {
case fbredr::HfpParameterSet::MSBC_T1:
return bt::sco::kParameterSetMsbcT1;
case fbredr::HfpParameterSet::MSBC_T2:
return bt::sco::kParameterSetMsbcT2;
case fbredr::HfpParameterSet::CVSD_S1:
return bt::sco::kParameterSetCvsdS1;
case fbredr::HfpParameterSet::CVSD_S2:
return bt::sco::kParameterSetCvsdS2;
case fbredr::HfpParameterSet::CVSD_S3:
return bt::sco::kParameterSetCvsdS3;
case fbredr::HfpParameterSet::CVSD_S4:
return bt::sco::kParameterSetCvsdS4;
case fbredr::HfpParameterSet::CVSD_D0:
return bt::sco::kParameterSetCvsdD0;
case fbredr::HfpParameterSet::CVSD_D1:
return bt::sco::kParameterSetCvsdD1;
}
}
bt::hci_spec::VendorCodingFormat FidlToScoCodingFormat(const fbredr::CodingFormat format) {
bt::hci_spec::VendorCodingFormat out;
// Set to 0 since vendor specific coding formats are not supported.
out.company_id = 0;
out.vendor_codec_id = 0;
switch (format) {
case fbredr::CodingFormat::ALAW:
out.coding_format = bt::hci_spec::CodingFormat::kALaw;
break;
case fbredr::CodingFormat::MULAW:
out.coding_format = bt::hci_spec::CodingFormat::kMuLaw;
break;
case fbredr::CodingFormat::CVSD:
out.coding_format = bt::hci_spec::CodingFormat::kCvsd;
break;
case fbredr::CodingFormat::LINEAR_PCM:
out.coding_format = bt::hci_spec::CodingFormat::kLinearPcm;
break;
case fbredr::CodingFormat::MSBC:
out.coding_format = bt::hci_spec::CodingFormat::kMSbc;
break;
case fbredr::CodingFormat::TRANSPARENT:
out.coding_format = bt::hci_spec::CodingFormat::kTransparent;
break;
}
return out;
}
fpromise::result<bt::hci_spec::PcmDataFormat> FidlToPcmDataFormat(
const faudio::SampleFormat& format) {
switch (format) {
case faudio::SampleFormat::PCM_SIGNED:
return fpromise::ok(bt::hci_spec::PcmDataFormat::k2sComplement);
case faudio::SampleFormat::PCM_UNSIGNED:
return fpromise::ok(bt::hci_spec::PcmDataFormat::kUnsigned);
default:
// Other sample formats are not supported by SCO.
return fpromise::error();
}
}
bt::hci_spec::ScoDataPath FidlToScoDataPath(const fbredr::DataPath& path) {
switch (path) {
case fbredr::DataPath::HOST:
return bt::hci_spec::ScoDataPath::kHci;
case fbredr::DataPath::OFFLOAD: {
// TODO(fxbug.dev/58458): Use path from stack configuration file instead of this hardcoded
// value. "6" is the data path usually used in Broadcom controllers.
return static_cast<bt::hci_spec::ScoDataPath>(6);
}
case fbredr::DataPath::TEST:
return bt::hci_spec::ScoDataPath::kAudioTestMode;
}
}
fpromise::result<bt::hci_spec::SynchronousConnectionParameters> FidlToScoParameters(
const fbredr::ScoConnectionParameters& params) {
bt::hci_spec::SynchronousConnectionParameters out;
if (!params.has_parameter_set()) {
bt_log(WARN, "fidl", "SCO parameters missing parameter_set");
return fpromise::error();
}
auto param_set = FidlToScoParameterSet(params.parameter_set());
out.transmit_bandwidth = param_set.transmit_receive_bandwidth;
out.receive_bandwidth = out.transmit_bandwidth;
if (!params.has_air_coding_format()) {
bt_log(WARN, "fidl", "SCO parameters missing air_coding_format");
return fpromise::error();
}
auto air_coding_format = FidlToScoCodingFormat(params.air_coding_format());
out.transmit_coding_format = air_coding_format;
out.receive_coding_format = out.transmit_coding_format;
if (!params.has_air_frame_size()) {
bt_log(WARN, "fidl", "SCO parameters missing air_frame_size");
return fpromise::error();
}
out.transmit_codec_frame_size_bytes = params.air_frame_size();
out.receive_codec_frame_size_bytes = out.transmit_codec_frame_size_bytes;
if (!params.has_io_bandwidth()) {
bt_log(WARN, "fidl", "SCO parameters missing io_bandwidth");
return fpromise::error();
}
out.input_bandwidth = params.io_bandwidth();
out.output_bandwidth = out.input_bandwidth;
if (!params.has_io_coding_format()) {
bt_log(WARN, "fidl", "SCO parameters missing io_coding_format");
return fpromise::error();
}
out.input_coding_format = FidlToScoCodingFormat(params.io_coding_format());
out.output_coding_format = out.input_coding_format;
if (!params.has_io_frame_size()) {
bt_log(WARN, "fidl", "SCO parameters missing io_frame_size");
return fpromise::error();
}
out.input_coded_data_size_bits = params.io_frame_size();
out.output_coded_data_size_bits = out.input_coded_data_size_bits;
if (params.has_io_pcm_data_format() &&
out.input_coding_format.coding_format == bt::hci_spec::CodingFormat::kLinearPcm) {
auto io_pcm_format = FidlToPcmDataFormat(params.io_pcm_data_format());
if (io_pcm_format.is_error()) {
bt_log(WARN, "fidl", "Unsupported IO PCM data format in SCO parameters");
return fpromise::error();
}
out.input_pcm_data_format = io_pcm_format.value();
out.output_pcm_data_format = out.input_pcm_data_format;
} else if (out.input_coding_format.coding_format == bt::hci_spec::CodingFormat::kLinearPcm) {
bt_log(WARN, "fidl",
"SCO parameters missing io_pcm_data_format (required for linear PCM IO coding format)");
return fpromise::error();
} else {
out.input_pcm_data_format = bt::hci_spec::PcmDataFormat::kNotApplicable;
out.output_pcm_data_format = out.input_pcm_data_format;
}
if (params.has_io_pcm_sample_payload_msb_position() &&
out.input_coding_format.coding_format == bt::hci_spec::CodingFormat::kLinearPcm) {
out.input_pcm_sample_payload_msb_position = params.io_pcm_sample_payload_msb_position();
out.output_pcm_sample_payload_msb_position = out.input_pcm_sample_payload_msb_position;
} else {
out.input_pcm_sample_payload_msb_position = 0u;
out.output_pcm_sample_payload_msb_position = out.input_pcm_sample_payload_msb_position;
}
if (!params.has_path()) {
bt_log(WARN, "fidl", "SCO parameters missing data path");
return fpromise::error();
}
out.input_data_path = FidlToScoDataPath(params.path());
out.output_data_path = out.input_data_path;
// For HCI Host transport the transport unit size should be "0". For PCM transport the unit size
// is vendor specific. A unit size of "0" indicates "not applicable".
// TODO(fxbug.dev/58458): Use unit size from stack configuration file instead of hardcoding "not
// applicable".
out.input_transport_unit_size_bits = 0u;
out.output_transport_unit_size_bits = out.input_transport_unit_size_bits;
out.max_latency_ms = param_set.max_latency_ms;
out.packet_types = param_set.packet_types;
out.retransmission_effort = param_set.retransmission_effort;
return fpromise::ok(out);
}
fpromise::result<std::vector<bt::hci_spec::SynchronousConnectionParameters>>
FidlToScoParametersVector(const std::vector<fbredr::ScoConnectionParameters>& params) {
std::vector<bt::hci_spec::SynchronousConnectionParameters> out;
out.reserve(params.size());
for (const fbredr::ScoConnectionParameters& param : params) {
fpromise::result<bt::hci_spec::SynchronousConnectionParameters> result =
FidlToScoParameters(param);
if (result.is_error()) {
return fpromise::error();
}
out.push_back(result.take_value());
}
return fpromise::ok(std::move(out));
}
bool IsFidlGattHandleValid(fuchsia::bluetooth::gatt2::Handle handle) {
if (handle.value > std::numeric_limits<bt::att::Handle>::max()) {
bt_log(ERROR, "fidl", "Invalid 64-bit FIDL GATT ID with `bits[16, 63] != 0` (0x%lX)",
handle.value);
return false;
}
return true;
}
} // namespace bthost::fidl_helpers
// static
std::vector<uint8_t> fidl::TypeConverter<std::vector<uint8_t>, bt::ByteBuffer>::Convert(
const bt::ByteBuffer& from) {
std::vector<uint8_t> to(from.size());
bt::MutableBufferView view(to.data(), to.size());
view.Write(from);
return to;
}
| 36.019327 | 100 | 0.682088 | [
"vector",
"transform"
] |
0f867fc3a196128d5ead0efb0660de9181b40234 | 13,452 | cpp | C++ | dev/Code/Sandbox/Editor/Objects/VisAreaShapeObject.cpp | crazyskateface/lumberyard | 164512f8d415d6bdf37e195af319ffe5f96a8f0b | [
"AML"
] | 5 | 2018-08-17T21:05:55.000Z | 2021-04-17T10:48:26.000Z | dev/Code/Sandbox/Editor/Objects/VisAreaShapeObject.cpp | JulianoCristian/Lumberyard-3 | dc523dd780f3cd1874251181b7cf6848b8db9959 | [
"AML"
] | null | null | null | dev/Code/Sandbox/Editor/Objects/VisAreaShapeObject.cpp | JulianoCristian/Lumberyard-3 | dc523dd780f3cd1874251181b7cf6848b8db9959 | [
"AML"
] | 5 | 2017-12-05T16:36:00.000Z | 2021-04-27T06:33:54.000Z | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#include "StdAfx.h"
#include "VisAreaShapeObject.h"
#include <I3DEngine.h>
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
C3DEngineAreaObjectBase::C3DEngineAreaObjectBase()
{
m_area = 0;
mv_closed = true;
m_bPerVertexHeight = true;
}
//////////////////////////////////////////////////////////////////////////
XmlNodeRef C3DEngineAreaObjectBase::Export(const QString& levelPath, XmlNodeRef& xmlNode)
{
XmlNodeRef objNode = CBaseObject::Export(levelPath, xmlNode);
// Export Points
if (!m_points.empty())
{
const Matrix34& wtm = GetWorldTM();
XmlNodeRef points = objNode->newChild("Points");
for (int i = 0; i < m_points.size(); i++)
{
XmlNodeRef pnt = points->newChild("Point");
pnt->setAttr("Pos", wtm.TransformPoint(m_points[i]));
}
}
return objNode;
}
//////////////////////////////////////////////////////////////////////////
void C3DEngineAreaObjectBase::Done()
{
if (m_area)
{
// reset the listener vis area in the unlucky case that we are deleting the
// vis area where the listener is currently in
// Audio: do we still need this?
GetIEditor()->Get3DEngine()->DeleteVisArea(m_area);
m_area = 0;
}
CShapeObject::Done();
}
//////////////////////////////////////////////////////////////////////////
bool C3DEngineAreaObjectBase::CreateGameObject()
{
if (!m_area)
{
uint64 visGUID = *((uint64*)&GetId());
m_area = GetIEditor()->Get3DEngine()->CreateVisArea(visGUID);
m_bAreaModified = true;
UpdateGameArea(false);
}
return true;
}
//////////////////////////////////////////////////////////////////////////
// CVisAreaShapeObject
//////////////////////////////////////////////////////////////////////////
CVisAreaShapeObject::CVisAreaShapeObject()
{
mv_height = 5;
m_bDisplayFilledWhenSelected = true;
// Ambient color zeroed out and hidden in Editor, no longer supported in VisAreas/Portals with PBR
mv_vAmbientColor = Vec3(ZERO);
mv_bAffectedBySun = false;
mv_bIgnoreSkyColor = false;
mv_fViewDistRatio = 100.f;
mv_bSkyOnly = false;
mv_bOceanIsVisible = false;
mv_bIgnoreGI = false;
SetColor(QColor(255, 128, 0));
}
//////////////////////////////////////////////////////////////////////////
void CVisAreaShapeObject::InitVariables()
{
AddVariable(mv_height, "Height", functor(*this, &CVisAreaShapeObject::OnShapeChange));
AddVariable(mv_displayFilled, "DisplayFilled");
AddVariable(mv_bAffectedBySun, "AffectedBySun", functor(*this, &CVisAreaShapeObject::OnShapeChange));
AddVariable(mv_bIgnoreSkyColor, "IgnoreSkyColor", functor(*this, &CVisAreaShapeObject::OnShapeChange));
AddVariable(mv_bIgnoreGI, "IgnoreGI", functor(*this, &CVisAreaShapeObject::OnShapeChange));
AddVariable(mv_fViewDistRatio, "ViewDistRatio", functor(*this, &CVisAreaShapeObject::OnShapeChange));
AddVariable(mv_bSkyOnly, "SkyOnly", functor(*this, &CVisAreaShapeObject::OnShapeChange));
AddVariable(mv_bOceanIsVisible, "OceanIsVisible", functor(*this, &CVisAreaShapeObject::OnShapeChange));
}
//////////////////////////////////////////////////////////////////////////
void CVisAreaShapeObject::UpdateGameArea(bool bRemove)
{
if (bRemove)
{
return;
}
if (!m_bAreaModified)
{
return;
}
if (m_area)
{
std::vector<Vec3> points;
if (GetPointCount() > 3)
{
const Matrix34& wtm = GetWorldTM();
points.resize(GetPointCount());
for (int i = 0; i < GetPointCount(); i++)
{
points[i] = wtm.TransformPoint(GetPoint(i));
}
Vec3 vAmbClr = mv_vAmbientColor;
SVisAreaInfo info;
info.fHeight = GetHeight();
info.vAmbientColor = vAmbClr;
info.bAffectedByOutLights = mv_bAffectedBySun;
info.bIgnoreSkyColor = mv_bIgnoreSkyColor;
info.bSkyOnly = mv_bSkyOnly;
info.fViewDistRatio = mv_fViewDistRatio;
info.bDoubleSide = true;
info.bUseDeepness = false;
info.bUseInIndoors = false;
info.bOceanIsVisible = mv_bOceanIsVisible;
info.bIgnoreGI = mv_bIgnoreGI;
info.fPortalBlending = -1;
GetIEditor()->Get3DEngine()->UpdateVisArea(m_area, &points[0], points.size(), GetName().toLatin1().data(), info, true);
}
}
m_bAreaModified = false;
}
//////////////////////////////////////////////////////////////////////////
// CPortalShapeObject
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
CPortalShapeObject::CPortalShapeObject()
{
m_bDisplayFilledWhenSelected = true;
SetColor(QColor(100, 250, 60));
mv_bUseDeepness = true;
mv_bDoubleSide = true;
mv_bPortalBlending = true;
mv_fPortalBlendValue = 0.5f;
}
//////////////////////////////////////////////////////////////////////////
void CPortalShapeObject::InitVariables()
{
CVisAreaShapeObject::InitVariables();
AddVariable(mv_bUseDeepness, "UseDeepness", functor(*this, &CPortalShapeObject::OnShapeChange));
AddVariable(mv_bDoubleSide, "DoubleSide", functor(*this, &CPortalShapeObject::OnShapeChange));
AddVariable(mv_bPortalBlending, "LightBlending", functor(*this, &CPortalShapeObject::OnShapeChange));
AddVariable(mv_fPortalBlendValue, "LightBlendValue", functor(*this, &CPortalShapeObject::OnShapeChange));
mv_fPortalBlendValue.SetLimits(0.0f, 1.0f);
}
//////////////////////////////////////////////////////////////////////////
void CPortalShapeObject::UpdateGameArea(bool bRemove)
{
if (bRemove)
{
return;
}
if (!m_bAreaModified)
{
return;
}
if (m_area)
{
std::vector<Vec3> points;
if (GetPointCount() > 3)
{
const Matrix34& wtm = GetWorldTM();
points.resize(GetPointCount());
for (int i = 0; i < GetPointCount(); i++)
{
points[i] = wtm.TransformPoint(GetPoint(i));
}
QString name = QString("Portal_") + GetName();
Vec3 vAmbClr = mv_vAmbientColor;
SVisAreaInfo info;
info.fHeight = GetHeight();
info.vAmbientColor = vAmbClr;
info.bAffectedByOutLights = mv_bAffectedBySun;
info.bIgnoreSkyColor = mv_bIgnoreSkyColor;
info.bSkyOnly = mv_bSkyOnly;
info.fViewDistRatio = mv_fViewDistRatio;
info.bDoubleSide = true;
info.bUseDeepness = false;
info.bUseInIndoors = false;
info.bOceanIsVisible = mv_bOceanIsVisible;
info.bIgnoreGI = mv_bIgnoreGI;
info.fPortalBlending = -1;
if (mv_bPortalBlending)
{
info.fPortalBlending = mv_fPortalBlendValue;
}
GetIEditor()->Get3DEngine()->UpdateVisArea(m_area, &points[0], points.size(), name.toLatin1().data(), info, true);
}
}
m_bAreaModified = false;
}
//////////////////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
COccluderPlaneObject::COccluderPlaneObject()
{
m_bDisplayFilledWhenSelected = true;
SetColor(QColor(200, 128, 60));
mv_height = 5;
mv_displayFilled = true;
mv_bUseInIndoors = false;
mv_bDoubleSide = true;
mv_fViewDistRatio = 100.f;
}
//////////////////////////////////////////////////////////////////////////
void COccluderPlaneObject::InitVariables()
{
AddVariable(mv_height, "Height", functor(*this, &COccluderPlaneObject::OnShapeChange));
AddVariable(mv_displayFilled, "DisplayFilled");
AddVariable(mv_fViewDistRatio, "CullDistRatio", functor(*this, &COccluderPlaneObject::OnShapeChange));
AddVariable(mv_bUseInIndoors, "UseInIndoors", functor(*this, &COccluderPlaneObject::OnShapeChange));
AddVariable(mv_bDoubleSide, "DoubleSide", functor(*this, &COccluderPlaneObject::OnShapeChange));
}
//////////////////////////////////////////////////////////////////////////
void COccluderPlaneObject::UpdateGameArea(bool bRemove)
{
if (bRemove)
{
return;
}
if (!m_bAreaModified)
{
return;
}
if (m_area)
{
std::vector<Vec3> points;
if (GetPointCount() > 1)
{
const Matrix34& wtm = GetWorldTM();
points.resize(GetPointCount());
for (int i = 0; i < GetPointCount(); i++)
{
points[i] = wtm.TransformPoint(GetPoint(i));
}
if (!m_points[0].IsEquivalent(m_points[1]))
{
QString name = QString("OcclArea_") + GetName();
SVisAreaInfo info;
info.fHeight = GetHeight();
info.vAmbientColor = Vec3(0, 0, 0);
info.bAffectedByOutLights = false;
info.bSkyOnly = false;
info.fViewDistRatio = mv_fViewDistRatio;
info.bDoubleSide = true;
info.bUseDeepness = false;
info.bUseInIndoors = mv_bUseInIndoors;
info.bOceanIsVisible = false;
info.fPortalBlending = -1;
GetIEditor()->Get3DEngine()->UpdateVisArea(m_area, &points[0], points.size(), name.toLatin1().data(), info, false);
}
}
}
m_bAreaModified = false;
}
//////////////////////////////////////////////////////////////////////////
void COccluderPlaneObject::PostLoad(CObjectArchive& ar)
{
C3DEngineAreaObjectBase::PostLoad(ar);
// July 2013: This needs for compatibility with old saved levels. Can be removed later.
if (m_points.size() == 4)
{
GetIEditor()->GetObjectManager()->ConvertToType(this, "OccluderArea");
}
}
//////////////////////////////////////////////////////////////////////////
// COccluderAreaObject
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
COccluderAreaObject::COccluderAreaObject()
{
m_bDisplayFilledWhenSelected = true;
m_bForce2D = true;
m_bNoCulling = true;
SetColor(QColor(200, 128, 60));
mv_displayFilled = true;
mv_bUseInIndoors = false;
mv_fViewDistRatio = 100.f;
}
//////////////////////////////////////////////////////////////////////////
void COccluderAreaObject::InitVariables()
{
AddVariable(mv_displayFilled, "DisplayFilled");
AddVariable(mv_fViewDistRatio, "CullDistRatio", functor(*this, &COccluderAreaObject::OnShapeChange));
AddVariable(mv_bUseInIndoors, "UseInIndoors", functor(*this, &COccluderAreaObject::OnShapeChange));
}
//////////////////////////////////////////////////////////////////////////
void COccluderAreaObject::UpdateGameArea(bool bRemove)
{
if (bRemove)
{
return;
}
if (!m_bAreaModified)
{
return;
}
if (m_area)
{
std::vector<Vec3> points;
if (GetPointCount() > 3)
{
const Matrix34& wtm = GetWorldTM();
points.resize(GetPointCount());
for (int i = 0; i < GetPointCount(); i++)
{
points[i] = wtm.TransformPoint(GetPoint(i));
}
{
QString name = QString("OcclArea_") + GetName();
SVisAreaInfo info;
info.fHeight = 0;
info.vAmbientColor = Vec3(0, 0, 0);
info.bAffectedByOutLights = false;
info.bSkyOnly = false;
info.fViewDistRatio = mv_fViewDistRatio;
info.bDoubleSide = true;
info.bUseDeepness = false;
info.bUseInIndoors = mv_bUseInIndoors;
info.bOceanIsVisible = false;
info.fPortalBlending = -1;
GetIEditor()->Get3DEngine()->UpdateVisArea(m_area, &points[0], points.size(), name.toLatin1().data(), info, false);
}
}
}
m_bAreaModified = false;
}
//////////////////////////////////////////////////////////////////////////
void COccluderAreaObject::PostLoad(CObjectArchive& ar)
{
C3DEngineAreaObjectBase::PostLoad(ar);
// July 2013: This needs for compatibility with old saved levels. Can be removed later.
if (m_points.size() == 2)
{
GetIEditor()->GetObjectManager()->ConvertToType(this, "OccluderPlane");
}
}
#include <Objects/VisAreaShapeObject.moc> | 32.889976 | 131 | 0.534865 | [
"vector"
] |
0f8b13b0927975f31dfb5d7195167a2bb026ec59 | 23,427 | cc | C++ | test/src/unit-capi-query.cc | upj977155/TileDB | 1c96c6a0c030e058930ff9d47409865fbfe2178f | [
"MIT"
] | null | null | null | test/src/unit-capi-query.cc | upj977155/TileDB | 1c96c6a0c030e058930ff9d47409865fbfe2178f | [
"MIT"
] | null | null | null | test/src/unit-capi-query.cc | upj977155/TileDB | 1c96c6a0c030e058930ff9d47409865fbfe2178f | [
"MIT"
] | null | null | null | /**
* @file unit-capi-query.cc
*
* @section LICENSE
*
* The MIT License
*
* @copyright Copyright (c) 2017-2021 TileDB, Inc.
* @copyright Copyright (c) 2016 MIT and Intel Corporation
*
* 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.
*
* @section DESCRIPTION
*
* Tests for the C API tiledb_query_t spec.
*/
#include <tiledb/sm/c_api/tiledb_struct_def.h>
#include <cassert>
#include <cstring>
#include <iostream>
#include <sstream>
#include <thread>
#include "catch.hpp"
#include "test/src/helpers.h"
#include "test/src/vfs_helpers.h"
#ifdef _WIN32
#include "tiledb/sm/filesystem/win.h"
#else
#include "tiledb/sm/filesystem/posix.h"
#endif
#include "tiledb/sm/c_api/tiledb.h"
#include "tiledb/sm/misc/utils.h"
using namespace tiledb::test;
struct QueryFx {
// TileDB context and vfs
tiledb_ctx_t* ctx_;
tiledb_vfs_t* vfs_;
// Vector of supported filsystems
const std::vector<std::unique_ptr<SupportedFs>> fs_vec_;
// Functions
QueryFx();
~QueryFx();
void remove_temp_dir(const std::string& path);
void create_temp_dir(const std::string& path);
void create_array(const std::string& path);
void test_get_buffer_write(const std::string& path);
void test_get_buffer_write_decoupled(const std::string& path);
void test_get_buffer_read(const std::string& path);
void test_get_buffer_read_decoupled(const std::string& path);
static std::string random_name(const std::string& prefix);
};
QueryFx::QueryFx()
: fs_vec_(vfs_test_get_fs_vec()) {
// Initialize vfs test
REQUIRE(vfs_test_init(fs_vec_, &ctx_, &vfs_).ok());
}
QueryFx::~QueryFx() {
// Close vfs test
REQUIRE(vfs_test_close(fs_vec_, ctx_, vfs_).ok());
tiledb_vfs_free(&vfs_);
tiledb_ctx_free(&ctx_);
}
std::string QueryFx::random_name(const std::string& prefix) {
std::stringstream ss;
ss << prefix << "-" << std::this_thread::get_id() << "-"
<< TILEDB_TIMESTAMP_NOW_MS;
return ss.str();
}
void QueryFx::create_temp_dir(const std::string& path) {
remove_temp_dir(path);
REQUIRE(tiledb_vfs_create_dir(ctx_, vfs_, path.c_str()) == TILEDB_OK);
}
void QueryFx::remove_temp_dir(const std::string& path) {
int is_dir = 0;
REQUIRE(tiledb_vfs_is_dir(ctx_, vfs_, path.c_str(), &is_dir) == TILEDB_OK);
if (is_dir)
REQUIRE(tiledb_vfs_remove_dir(ctx_, vfs_, path.c_str()) == TILEDB_OK);
}
void QueryFx::create_array(const std::string& path) {
// Create array schema
tiledb_array_schema_t* array_schema;
int rc = tiledb_array_schema_alloc(ctx_, TILEDB_DENSE, &array_schema);
REQUIRE(rc == TILEDB_OK);
// Set schema members
rc = tiledb_array_schema_set_capacity(ctx_, array_schema, 10000);
REQUIRE(rc == TILEDB_OK);
rc = tiledb_array_schema_set_cell_order(ctx_, array_schema, TILEDB_ROW_MAJOR);
REQUIRE(rc == TILEDB_OK);
rc = tiledb_array_schema_set_tile_order(ctx_, array_schema, TILEDB_ROW_MAJOR);
REQUIRE(rc == TILEDB_OK);
// Create dimensions
tiledb_dimension_t* d1;
uint64_t dim_domain[] = {1, 10, 1, 10};
uint64_t extents[] = {5, 5};
rc = tiledb_dimension_alloc(
ctx_, "dim_1", TILEDB_INT64, &dim_domain[0], &extents[0], &d1);
REQUIRE(rc == TILEDB_OK);
tiledb_dimension_t* d2;
rc = tiledb_dimension_alloc(
ctx_, "dim_2", TILEDB_INT64, &dim_domain[2], &extents[1], &d2);
REQUIRE(rc == TILEDB_OK);
// Set domain
tiledb_domain_t* domain;
rc = tiledb_domain_alloc(ctx_, &domain);
REQUIRE(rc == TILEDB_OK);
rc = tiledb_domain_add_dimension(ctx_, domain, d1);
REQUIRE(rc == TILEDB_OK);
tiledb_datatype_t domain_type;
rc = tiledb_domain_get_type(ctx_, domain, &domain_type);
REQUIRE(rc == TILEDB_OK);
REQUIRE(domain_type == TILEDB_INT64);
rc = tiledb_domain_add_dimension(ctx_, domain, d2);
REQUIRE(rc == TILEDB_OK);
rc = tiledb_array_schema_set_domain(ctx_, array_schema, domain);
REQUIRE(rc == TILEDB_OK);
// Add attributes
tiledb_attribute_t* a1;
rc = tiledb_attribute_alloc(ctx_, "", TILEDB_INT32, &a1);
REQUIRE(rc == TILEDB_OK);
rc = tiledb_array_schema_add_attribute(ctx_, array_schema, a1);
REQUIRE(rc == TILEDB_OK);
tiledb_attribute_t* a2;
rc = tiledb_attribute_alloc(ctx_, "a2", TILEDB_INT32, &a2);
REQUIRE(rc == TILEDB_OK);
rc = tiledb_attribute_set_cell_val_num(ctx_, a2, TILEDB_VAR_NUM);
REQUIRE(rc == TILEDB_OK);
rc = tiledb_array_schema_add_attribute(ctx_, array_schema, a2);
REQUIRE(rc == TILEDB_OK);
// Create array
rc = tiledb_array_create(ctx_, path.c_str(), array_schema);
REQUIRE(rc == TILEDB_OK);
// Clean up
tiledb_array_schema_free(&array_schema);
tiledb_attribute_free(&a1);
tiledb_attribute_free(&a2);
tiledb_dimension_free(&d1);
tiledb_dimension_free(&d2);
tiledb_domain_free(&domain);
}
void QueryFx::test_get_buffer_write(const std::string& path) {
// Open array
tiledb_array_t* array;
int rc = tiledb_array_alloc(ctx_, path.c_str(), &array);
CHECK(rc == TILEDB_OK);
rc = tiledb_array_open(ctx_, array, TILEDB_WRITE);
CHECK(rc == TILEDB_OK);
// Prepare subarray and buffers
uint64_t subarray[] = {1, 2, 1, 2};
int a1[] = {1, 2, 3, 4};
uint64_t a1_size = sizeof(a1);
uint64_t a2_off[] = {0, 4, 8, 12};
uint64_t a2_off_size = sizeof(a2_off);
int a2_val[] = {1, 2, 3, 4};
uint64_t a2_val_size = sizeof(a2_val);
// Prepare query
tiledb_query_t* query;
rc = tiledb_query_alloc(ctx_, array, TILEDB_WRITE, &query);
REQUIRE(rc == TILEDB_OK);
rc = tiledb_query_set_subarray(ctx_, query, subarray);
CHECK(rc == TILEDB_OK);
// Get unset buffers
void* a1_got;
uint64_t* a1_got_size;
uint64_t* a2_off_got;
uint64_t* a2_off_got_size;
void* a2_val_got;
uint64_t* a2_val_got_size;
rc = tiledb_query_get_data_buffer(ctx_, query, "", &a1_got, &a1_got_size);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_get_data_buffer(
ctx_, query, "a2", &a2_val_got, &a2_val_got_size);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_get_offsets_buffer(
ctx_, query, "a2", &a2_off_got, &a2_off_got_size);
CHECK(rc == TILEDB_OK);
CHECK(a1_got == nullptr);
CHECK(a1_got_size == nullptr);
CHECK(a2_off_got == nullptr);
CHECK(a2_off_got_size == nullptr);
CHECK(a2_val_got == nullptr);
CHECK(a2_val_got_size == nullptr);
// Set buffers
rc = tiledb_query_set_data_buffer(ctx_, query, "", a1, &a1_size);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_set_data_buffer(ctx_, query, "a2", a2_val, &a2_val_size);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_set_offsets_buffer(ctx_, query, "a2", a2_off, &a2_off_size);
CHECK(rc == TILEDB_OK);
// Get invalid var-sized buffer
rc = tiledb_query_get_data_buffer(
ctx_, query, "a1", &a2_val_got, &a2_val_got_size);
CHECK(rc == TILEDB_ERR);
rc = tiledb_query_get_offsets_buffer(
ctx_, query, "a1", &a2_off_got, &a2_off_got_size);
CHECK(rc == TILEDB_ERR);
// Test getting the coords buffer
rc = tiledb_query_get_data_buffer(
ctx_, query, "dim_1", &a2_val_got, &a2_val_got_size);
CHECK(rc == TILEDB_OK);
CHECK(a1_got == nullptr);
CHECK(a1_got_size == nullptr);
rc = tiledb_query_get_offsets_buffer(
ctx_, query, "dim_1", &a2_off_got, &a2_off_got_size);
CHECK(rc == TILEDB_ERR);
// Test invalid attribute
rc = tiledb_query_get_data_buffer(ctx_, query, "foo", &a1_got, &a1_got_size);
CHECK(rc == TILEDB_ERR);
rc = tiledb_query_get_data_buffer(
ctx_, query, "foo-var", &a2_val_got, &a2_val_got_size);
CHECK(rc == TILEDB_ERR);
rc = tiledb_query_get_offsets_buffer(
ctx_, query, "foo-var", &a2_off_got, &a2_off_got_size);
CHECK(rc == TILEDB_ERR);
// Test correctly got buffers
rc = tiledb_query_get_data_buffer(ctx_, query, "", &a1_got, &a1_got_size);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_get_data_buffer(
ctx_, query, "a2", &a2_val_got, &a2_val_got_size);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_get_offsets_buffer(
ctx_, query, "a2", &a2_off_got, &a2_off_got_size);
CHECK(rc == TILEDB_OK);
CHECK(a1_got == a1);
CHECK(a1_got_size == &a1_size);
CHECK(a2_off_got == a2_off);
CHECK(a2_off_got_size == &a2_off_size);
CHECK(a2_val_got == a2_val);
CHECK(a2_val_got_size == &a2_val_size);
// Close array
rc = tiledb_array_close(ctx_, array);
CHECK(rc == TILEDB_OK);
// Clean up
tiledb_array_free(&array);
tiledb_query_free(&query);
}
void QueryFx::test_get_buffer_write_decoupled(const std::string& path) {
// Open array
tiledb_array_t* array;
int rc = tiledb_array_alloc(ctx_, path.c_str(), &array);
CHECK(rc == TILEDB_OK);
rc = tiledb_array_open(ctx_, array, TILEDB_WRITE);
CHECK(rc == TILEDB_OK);
// Prepare subarray and buffers
uint64_t subarray[] = {1, 2, 1, 2};
int a1[] = {1, 2, 3, 4};
uint64_t a1_size = sizeof(a1);
uint64_t a2_off[] = {0, 4, 8, 12};
uint64_t a2_off_size = sizeof(a2_off);
int a2_val[] = {1, 2, 3, 4};
uint64_t a2_val_size = sizeof(a2_val);
// Prepare query
tiledb_query_t* query;
rc = tiledb_query_alloc(ctx_, array, TILEDB_WRITE, &query);
REQUIRE(rc == TILEDB_OK);
rc = tiledb_query_set_subarray(ctx_, query, subarray);
CHECK(rc == TILEDB_OK);
// Get unset buffers
void* a1_got;
uint64_t* a1_got_size;
uint64_t* a2_off_got;
uint64_t* a2_off_got_size;
void* a2_val_got;
uint64_t* a2_val_got_size;
rc = tiledb_query_get_data_buffer(ctx_, query, "", &a1_got, &a1_got_size);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_get_data_buffer(
ctx_, query, "a2", &a2_val_got, &a2_val_got_size);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_get_offsets_buffer(
ctx_, query, "a2", &a2_off_got, &a2_off_got_size);
CHECK(rc == TILEDB_OK);
CHECK(a1_got == nullptr);
CHECK(a1_got_size == nullptr);
CHECK(a2_off_got == nullptr);
CHECK(a2_off_got_size == nullptr);
CHECK(a2_val_got == nullptr);
CHECK(a2_val_got_size == nullptr);
// Set buffers
rc = tiledb_query_set_data_buffer(ctx_, query, "", a1, &a1_size);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_set_data_buffer(ctx_, query, "a2", a2_val, &a2_val_size);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_set_offsets_buffer(ctx_, query, "a2", a2_off, &a2_off_size);
CHECK(rc == TILEDB_OK);
// Test getting the coords buffer
rc =
tiledb_query_get_data_buffer(ctx_, query, "dim_1", &a1_got, &a1_got_size);
CHECK(rc == TILEDB_OK);
CHECK(a1_got == nullptr);
CHECK(a1_got_size == nullptr);
rc = tiledb_query_get_offsets_buffer(
ctx_, query, "dim_1", &a2_off_got, &a2_off_got_size);
CHECK(rc == TILEDB_ERR);
// Test invalid attribute
rc = tiledb_query_get_data_buffer(ctx_, query, "foo", &a1_got, &a1_got_size);
CHECK(rc == TILEDB_ERR);
rc = tiledb_query_get_data_buffer(
ctx_, query, "foo-var", &a2_val_got, &a2_val_got_size);
CHECK(rc == TILEDB_ERR);
rc = tiledb_query_get_offsets_buffer(
ctx_, query, "foo-var", &a2_off_got, &a2_off_got_size);
CHECK(rc == TILEDB_ERR);
// Test correctly got buffers
rc = tiledb_query_get_data_buffer(ctx_, query, "", &a1_got, &a1_got_size);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_get_data_buffer(
ctx_, query, "a2", &a2_val_got, &a2_val_got_size);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_get_offsets_buffer(
ctx_, query, "a2", &a2_off_got, &a2_off_got_size);
CHECK(rc == TILEDB_OK);
CHECK(a1_got == a1);
CHECK(a1_got_size == &a1_size);
CHECK(a2_off_got == a2_off);
CHECK(a2_off_got_size == &a2_off_size);
CHECK(a2_val_got == a2_val);
CHECK(a2_val_got_size == &a2_val_size);
// Close array
rc = tiledb_array_close(ctx_, array);
CHECK(rc == TILEDB_OK);
// Clean up
tiledb_array_free(&array);
tiledb_query_free(&query);
}
void QueryFx::test_get_buffer_read(const std::string& path) {
// Open array
tiledb_array_t* array;
int rc = tiledb_array_alloc(ctx_, path.c_str(), &array);
CHECK(rc == TILEDB_OK);
rc = tiledb_array_open(ctx_, array, TILEDB_READ);
CHECK(rc == TILEDB_OK);
// Prepare subarray and buffers
uint64_t subarray[] = {1, 2, 1, 2};
int a1[4];
uint64_t a1_size = sizeof(a1);
uint64_t a2_off[4];
uint64_t a2_off_size = sizeof(a2_off);
int a2_val[4];
uint64_t a2_val_size = sizeof(a2_val);
// Prepare query
tiledb_query_t* query;
rc = tiledb_query_alloc(ctx_, array, TILEDB_READ, &query);
REQUIRE(rc == TILEDB_OK);
rc = tiledb_query_set_subarray(ctx_, query, subarray);
CHECK(rc == TILEDB_OK);
// Get unset buffers
void* a1_got;
uint64_t* a1_got_size;
uint64_t* a2_off_got;
uint64_t* a2_off_got_size;
void* a2_val_got;
uint64_t* a2_val_got_size;
rc = tiledb_query_get_data_buffer(ctx_, query, "", &a1_got, &a1_got_size);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_get_data_buffer(
ctx_, query, "a2", &a2_val_got, &a2_val_got_size);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_get_offsets_buffer(
ctx_, query, "a2", &a2_off_got, &a2_off_got_size);
CHECK(rc == TILEDB_OK);
CHECK(a1_got == nullptr);
CHECK(a1_got_size == nullptr);
CHECK(a2_off_got == nullptr);
CHECK(a2_off_got_size == nullptr);
CHECK(a2_val_got == nullptr);
CHECK(a2_val_got_size == nullptr);
// Set buffers
rc = tiledb_query_set_data_buffer(ctx_, query, "", a1, &a1_size);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_set_data_buffer(ctx_, query, "a2", a2_val, &a2_val_size);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_set_offsets_buffer(ctx_, query, "a2", a2_off, &a2_off_size);
CHECK(rc == TILEDB_OK);
// Get invalid fixed-sized / var-sized buffer
rc = tiledb_query_get_data_buffer(ctx_, query, "a2", &a1_got, &a1_got_size);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_get_data_buffer(
ctx_, query, "a1", &a2_val_got, &a2_val_got_size);
CHECK(rc == TILEDB_ERR);
rc = tiledb_query_get_offsets_buffer(
ctx_, query, "a1", &a2_off_got, &a2_off_got_size);
CHECK(rc == TILEDB_ERR);
// Test getting the coords buffer
rc =
tiledb_query_get_data_buffer(ctx_, query, "dim_1", &a1_got, &a1_got_size);
CHECK(rc == TILEDB_OK);
CHECK(a1_got == nullptr);
CHECK(a1_got_size == nullptr);
rc = tiledb_query_get_data_buffer(
ctx_, query, "dim_1", &a2_val_got, &a2_val_got_size);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_get_offsets_buffer(
ctx_, query, "dim_1", &a2_off_got, &a2_off_got_size);
CHECK(rc == TILEDB_ERR);
// Test invalid attribute
rc = tiledb_query_get_data_buffer(ctx_, query, "foo", &a1_got, &a1_got_size);
CHECK(rc == TILEDB_ERR);
rc = tiledb_query_get_data_buffer(
ctx_, query, "foo-var", &a2_val_got, &a2_val_got_size);
CHECK(rc == TILEDB_ERR);
rc = tiledb_query_get_offsets_buffer(
ctx_, query, "foo-var", &a2_off_got, &a2_off_got_size);
CHECK(rc == TILEDB_ERR);
// Test correctly got buffers
rc = tiledb_query_get_data_buffer(ctx_, query, "", &a1_got, &a1_got_size);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_get_data_buffer(
ctx_, query, "a2", &a2_val_got, &a2_val_got_size);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_get_offsets_buffer(
ctx_, query, "a2", &a2_off_got, &a2_off_got_size);
CHECK(rc == TILEDB_OK);
CHECK(a1_got == a1);
CHECK(a1_got_size == &a1_size);
CHECK(a2_off_got == a2_off);
CHECK(a2_off_got_size == &a2_off_size);
CHECK(a2_val_got == a2_val);
CHECK(a2_val_got_size == &a2_val_size);
// Close array
rc = tiledb_array_close(ctx_, array);
CHECK(rc == TILEDB_OK);
// Clean up
tiledb_array_free(&array);
tiledb_query_free(&query);
}
void QueryFx::test_get_buffer_read_decoupled(const std::string& path) {
// Open array
tiledb_array_t* array;
int rc = tiledb_array_alloc(ctx_, path.c_str(), &array);
CHECK(rc == TILEDB_OK);
rc = tiledb_array_open(ctx_, array, TILEDB_READ);
CHECK(rc == TILEDB_OK);
// Prepare subarray and buffers
uint64_t subarray[] = {1, 2, 1, 2};
int a1[4];
uint64_t a1_size = sizeof(a1);
uint64_t a2_off[4];
uint64_t a2_off_size = sizeof(a2_off);
int a2_val[4];
uint64_t a2_val_size = sizeof(a2_val);
// Prepare query
tiledb_query_t* query;
rc = tiledb_query_alloc(ctx_, array, TILEDB_READ, &query);
REQUIRE(rc == TILEDB_OK);
rc = tiledb_query_set_subarray(ctx_, query, subarray);
CHECK(rc == TILEDB_OK);
// Get unset buffers
void* a1_got;
uint64_t* a1_got_size;
uint64_t* a2_off_got;
uint64_t* a2_off_got_size;
void* a2_val_got;
uint64_t* a2_val_got_size;
rc = tiledb_query_get_data_buffer(ctx_, query, "", &a1_got, &a1_got_size);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_get_data_buffer(
ctx_, query, "a2", &a2_val_got, &a2_val_got_size);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_get_offsets_buffer(
ctx_, query, "a2", &a2_off_got, &a2_off_got_size);
CHECK(rc == TILEDB_OK);
CHECK(a1_got == nullptr);
CHECK(a1_got_size == nullptr);
CHECK(a2_off_got == nullptr);
CHECK(a2_off_got_size == nullptr);
CHECK(a2_val_got == nullptr);
CHECK(a2_val_got_size == nullptr);
// Set buffers
rc = tiledb_query_set_data_buffer(ctx_, query, "", a1, &a1_size);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_set_data_buffer(ctx_, query, "a2", a2_val, &a2_val_size);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_set_offsets_buffer(ctx_, query, "a2", a2_off, &a2_off_size);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_get_data_buffer(
ctx_, query, "a1", &a2_val_got, &a2_val_got_size);
CHECK(rc == TILEDB_ERR);
rc = tiledb_query_get_offsets_buffer(
ctx_, query, "a1", &a2_off_got, &a2_off_got_size);
CHECK(rc == TILEDB_ERR);
// Test getting the coords buffer
rc =
tiledb_query_get_data_buffer(ctx_, query, "dim_1", &a1_got, &a1_got_size);
CHECK(rc == TILEDB_OK);
CHECK(a1_got == nullptr);
CHECK(a1_got_size == nullptr);
// Test invalid attribute
rc = tiledb_query_get_data_buffer(ctx_, query, "foo", &a1_got, &a1_got_size);
CHECK(rc == TILEDB_ERR);
rc = tiledb_query_get_data_buffer(
ctx_, query, "foo-var", &a2_val_got, &a2_val_got_size);
CHECK(rc == TILEDB_ERR);
rc = tiledb_query_get_offsets_buffer(
ctx_, query, "foo-var", &a2_off_got, &a2_off_got_size);
CHECK(rc == TILEDB_ERR);
// Test correctly got buffers
rc = tiledb_query_get_data_buffer(ctx_, query, "", &a1_got, &a1_got_size);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_get_data_buffer(
ctx_, query, "a2", &a2_val_got, &a2_val_got_size);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_get_offsets_buffer(
ctx_, query, "a2", &a2_off_got, &a2_off_got_size);
CHECK(rc == TILEDB_OK);
CHECK(a1_got == a1);
CHECK(a1_got_size == &a1_size);
CHECK(a2_off_got == a2_off);
CHECK(a2_off_got_size == &a2_off_size);
CHECK(a2_val_got == a2_val);
CHECK(a2_val_got_size == &a2_val_size);
// Close array
rc = tiledb_array_close(ctx_, array);
CHECK(rc == TILEDB_OK);
// Clean up
tiledb_array_free(&array);
tiledb_query_free(&query);
}
TEST_CASE_METHOD(
QueryFx,
"C API: Test query get buffer",
"[capi], [query], [query-get-buffer]") {
// TODO: refactor for each supported FS.
SupportedFsLocal local_fs;
std::string temp_dir = local_fs.file_prefix() + local_fs.temp_dir();
std::string array_name = temp_dir + "query_get_buffer";
create_temp_dir(temp_dir);
create_array(array_name);
test_get_buffer_write(array_name);
test_get_buffer_write_decoupled(array_name);
test_get_buffer_read(array_name);
test_get_buffer_read_decoupled(array_name);
remove_temp_dir(temp_dir);
}
TEST_CASE_METHOD(
QueryFx,
"C API: Test query get layout",
"[capi], [query], [query-get-layout]") {
SupportedFsLocal local_fs;
std::string temp_dir = local_fs.file_prefix() + local_fs.temp_dir();
std::string array_name = temp_dir + "query_get_layout";
create_temp_dir(temp_dir);
create_array(array_name);
tiledb_array_t* array;
int rc = tiledb_array_alloc(ctx_, array_name.c_str(), &array);
REQUIRE(rc == TILEDB_OK);
rc = tiledb_array_open(ctx_, array, TILEDB_READ);
REQUIRE(rc == TILEDB_OK);
tiledb_query_t* query;
rc = tiledb_query_alloc(ctx_, array, TILEDB_READ, &query);
REQUIRE(rc == TILEDB_OK);
tiledb_layout_t layout;
rc = tiledb_query_get_layout(ctx_, query, &layout);
REQUIRE(rc == TILEDB_OK);
REQUIRE(layout == TILEDB_ROW_MAJOR);
rc = tiledb_query_set_layout(ctx_, query, TILEDB_COL_MAJOR);
REQUIRE(rc == TILEDB_OK);
rc = tiledb_query_get_layout(ctx_, query, &layout);
REQUIRE(rc == TILEDB_OK);
REQUIRE(layout == TILEDB_COL_MAJOR);
rc = tiledb_query_set_layout(ctx_, query, TILEDB_GLOBAL_ORDER);
REQUIRE(rc == TILEDB_OK);
rc = tiledb_query_get_layout(ctx_, query, &layout);
REQUIRE(rc == TILEDB_OK);
REQUIRE(layout == TILEDB_GLOBAL_ORDER);
rc = tiledb_query_set_layout(ctx_, query, TILEDB_UNORDERED);
REQUIRE(rc == TILEDB_OK);
rc = tiledb_query_get_layout(ctx_, query, &layout);
REQUIRE(rc == TILEDB_OK);
REQUIRE(layout == TILEDB_UNORDERED);
rc = tiledb_array_close(ctx_, array);
REQUIRE(rc == TILEDB_OK);
tiledb_query_free(&query);
tiledb_array_free(&array);
remove_temp_dir(temp_dir);
}
TEST_CASE_METHOD(
QueryFx,
"C API: Test query get array",
"[capi], [query], [query-get-array]") {
SupportedFsLocal local_fs;
std::string temp_dir = local_fs.file_prefix() + local_fs.temp_dir();
std::string array_name = temp_dir + "query_get_array";
create_temp_dir(temp_dir);
create_array(array_name);
tiledb_array_t* array;
int rc = tiledb_array_alloc(ctx_, array_name.c_str(), &array);
REQUIRE(rc == TILEDB_OK);
rc = tiledb_array_open(ctx_, array, TILEDB_READ);
REQUIRE(rc == TILEDB_OK);
tiledb_query_t* query;
rc = tiledb_query_alloc(ctx_, array, TILEDB_READ, &query);
REQUIRE(rc == TILEDB_OK);
tiledb_array_t* rarray;
rc = tiledb_query_get_array(ctx_, query, &rarray);
REQUIRE(rc == TILEDB_OK);
CHECK(rarray->array_ != array->array_);
tiledb_array_schema_t* rschema;
rc = tiledb_array_get_schema(ctx_, rarray, &rschema);
REQUIRE(rc == TILEDB_OK);
// Get schema members
uint64_t rcapacity;
rc = tiledb_array_schema_get_capacity(ctx_, rschema, &rcapacity);
REQUIRE(rc == TILEDB_OK);
REQUIRE(rcapacity == 10000);
tiledb_layout_t layout;
rc = tiledb_array_schema_get_cell_order(ctx_, rschema, &layout);
REQUIRE(rc == TILEDB_OK);
REQUIRE(layout == TILEDB_ROW_MAJOR);
rc = tiledb_array_schema_get_tile_order(ctx_, rschema, &layout);
REQUIRE(rc == TILEDB_OK);
REQUIRE(layout == TILEDB_ROW_MAJOR);
rc = tiledb_array_close(ctx_, array);
REQUIRE(rc == TILEDB_OK);
tiledb_array_schema_free(&rschema);
tiledb_query_free(&query);
tiledb_array_free(&array);
tiledb_array_free(&rarray);
remove_temp_dir(temp_dir);
}
| 32.810924 | 80 | 0.706364 | [
"vector"
] |
0f90aa43dccd0703b7b4b7ff25be765e7a774371 | 1,543 | cpp | C++ | src/Domain/Structure/CreateInitialMesh.cpp | keefemitman/spectre | a8c3e387addc34d8a4544728f405991e6c9e5e38 | [
"MIT"
] | null | null | null | src/Domain/Structure/CreateInitialMesh.cpp | keefemitman/spectre | a8c3e387addc34d8a4544728f405991e6c9e5e38 | [
"MIT"
] | null | null | null | src/Domain/Structure/CreateInitialMesh.cpp | keefemitman/spectre | a8c3e387addc34d8a4544728f405991e6c9e5e38 | [
"MIT"
] | null | null | null | // Distributed under the MIT License.
// See LICENSE.txt for details.
#include "Domain/Structure/CreateInitialMesh.hpp"
#include <array>
#include <cstddef>
#include <vector>
#include "DataStructures/Index.hpp"
#include "Domain/Structure/ElementId.hpp"
#include "Domain/Structure/OrientationMap.hpp"
#include "NumericalAlgorithms/Spectral/Mesh.hpp"
#include "NumericalAlgorithms/Spectral/Spectral.hpp"
#include "Utilities/GenerateInstantiations.hpp"
#include "Utilities/Gsl.hpp"
namespace domain::Initialization {
template <size_t Dim>
Mesh<Dim> create_initial_mesh(
const std::vector<std::array<size_t, Dim>>& initial_extents,
const ElementId<Dim>& element_id,
const OrientationMap<Dim>& orientation) noexcept {
const auto& unoriented_extents = initial_extents[element_id.block_id()];
Index<Dim> extents;
for (size_t i = 0; i < Dim; ++i) {
extents[i] = gsl::at(unoriented_extents, orientation(i));
}
return {extents.indices(), Spectral::Basis::Legendre,
Spectral::Quadrature::GaussLobatto};
}
} // namespace domain::Initialization
/// \cond
#define DIM(data) BOOST_PP_TUPLE_ELEM(0, data)
#define INSTANTIATE(_, data) \
template Mesh<DIM(data)> \
domain::Initialization::create_initial_mesh<DIM(data)>( \
const std::vector<std::array<size_t, DIM(data)>>&, \
const ElementId<DIM(data)>&, const OrientationMap<DIM(data)>&) noexcept;
GENERATE_INSTANTIATIONS(INSTANTIATE, (1, 2, 3))
#undef DIM
#undef INSTANTIATE
/// \endcond
| 32.145833 | 78 | 0.706416 | [
"mesh",
"vector"
] |
0f91d7c8e124f27e15d4af745683573e302ae44e | 579 | cc | C++ | tests/CADMeshTests.cc | josephmckenna/CADMesh | cd867d46af7f6474f70c94f0dfdf2a4fcd3024ff | [
"MIT"
] | 94 | 2015-02-03T18:20:30.000Z | 2022-02-21T17:06:31.000Z | tests/CADMeshTests.cc | josephmckenna/CADMesh | cd867d46af7f6474f70c94f0dfdf2a4fcd3024ff | [
"MIT"
] | 36 | 2015-02-19T12:32:09.000Z | 2021-11-17T13:07:05.000Z | tests/CADMeshTests.cc | josephmckenna/CADMesh | cd867d46af7f6474f70c94f0dfdf2a4fcd3024ff | [
"MIT"
] | 59 | 2015-03-04T10:52:39.000Z | 2022-02-23T12:15:48.000Z | #define CATCH_CONFIG_MAIN
#include "catch2/catch.hpp"
// CADMesh //
#include "CADMesh.hh"
SCENARIO( "Load a PLY file as a tessellated mesh.") {
GIVEN( "the PLY file on disk" ) {
auto mesh = CADMesh::TessellatedMesh::FromPLY("../meshes/sphere.ply");
REQUIRE( mesh->GetFileName() == "../meshes/sphere.ply" );
WHEN( "setting the output verbosity" ) {
mesh->SetVerbose(1);
THEN( "the output verbosity flag changes" ) {
REQUIRE( mesh->GetVerbose() == 1 );
}
}
}
}
| 24.125 | 78 | 0.542314 | [
"mesh"
] |
0f93ac40776ae41f8614da6784c5d5c9ab2acd2b | 4,898 | cpp | C++ | src/conformance/framework/bitmask_generator.cpp | rpavlik/OpenXR-CTS | 5600673d550ddd5692614d11fabe0f9ceae16ed6 | [
"Unlicense",
"BSD-3-Clause",
"Apache-2.0",
"MIT"
] | 35 | 2020-07-07T18:10:11.000Z | 2022-03-13T10:48:45.000Z | src/conformance/framework/bitmask_generator.cpp | rpavlik/OpenXR-CTS | 5600673d550ddd5692614d11fabe0f9ceae16ed6 | [
"Unlicense",
"BSD-3-Clause",
"Apache-2.0",
"MIT"
] | 29 | 2020-09-10T16:36:59.000Z | 2022-03-31T18:17:32.000Z | src/conformance/framework/bitmask_generator.cpp | rpavlik/OpenXR-CTS | 5600673d550ddd5692614d11fabe0f9ceae16ed6 | [
"Unlicense",
"BSD-3-Clause",
"Apache-2.0",
"MIT"
] | 9 | 2020-09-10T16:01:57.000Z | 2022-01-21T18:28:35.000Z | // Copyright (c) 2019-2021, The Khronos Group Inc.
// Copyright (c) 2019 Collabora, Ltd.
//
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/*!
* @file
* @brief Implementation
* @author Ryan Pavlik <ryan.pavlik@collabora.com>
*/
#include "bitmask_generator.h"
#include <vector>
#include <memory>
namespace Conformance
{
namespace
{
/*!
* GeneratorBase implementation for the BitmaskGenerator - implementation details.
*
* @see bitmaskGenerator for the factory function to create one of these.
*
* Uses the binary of an integer index as a selection of
* which supplied bitmasks should be enabled in a given generated output.
* Yes, this is a bitmask that selects bitmasks.
*/
class BitmaskGenerator : public GeneratorBase<BitmaskData const&>
{
public:
~BitmaskGenerator() override = default;
BitmaskGenerator(const BitmaskGenerator&) = delete;
BitmaskGenerator& operator=(const BitmaskGenerator&) = delete;
BitmaskGenerator(BitmaskGenerator&&) = delete;
BitmaskGenerator& operator=(BitmaskGenerator&&) = delete;
static std::unique_ptr<GeneratorBase<BitmaskData const&>> create(bool zeroOk, std::initializer_list<BitmaskData> const& bits)
{
std::unique_ptr<BitmaskGenerator> generator(new BitmaskGenerator(zeroOk, bits));
return generator;
}
BitmaskGenerator(bool zeroOk, std::initializer_list<BitmaskData> const& bits) : bits_(bits), zeroOk_(zeroOk)
{
}
BitmaskData const& get() override
{
return current_;
}
bool next() override
{
// Return the zeroth combination first.
if (zeroOk_ && !gotZeroYet_) {
gotZeroYet_ = true;
return true;
}
// Otherwise, move on to the next index
currentIndex_++;
const auto n = bits_.size();
if (currentIndex_ >= (uint64_t(0x1) << n)) {
// n is highest bit number + 1.
// Thus, the largest mask is 0x1 << n - 1.
// If we exceed that, we've run out of combinations.
return false;
}
BitmaskData accumulate{{}, 0};
// Loop through the bits of our index to determine whether to enable a given bitmask
for (size_t i = 0; i < n; ++i) {
uint64_t indexBit = (uint64_t(0x1) << i);
if ((indexBit & currentIndex_) != 0) {
// Yes, enable this bitmask
accumulate |= bits_[i];
}
}
current_ = accumulate;
return true;
}
private:
std::vector<BitmaskData> bits_;
bool zeroOk_;
bool gotZeroYet_ = false;
uint64_t currentIndex_ = 0;
BitmaskData current_;
};
} // namespace
BitmaskData operator|(BitmaskData const& lhs, BitmaskData const& rhs)
{
if (lhs.empty()) {
return rhs;
}
if (rhs.empty()) {
return lhs;
}
// If we are here, we are combining two non-empty.
BitmaskData ret{lhs};
ret |= rhs;
return ret;
}
BitmaskData& BitmaskData::operator|=(BitmaskData const& other)
{
if (this == &other) {
return *this;
}
if (other.empty()) {
return *this;
}
if (empty()) {
*this = other;
return *this;
}
description += " | ";
description += other.description;
bitmask |= other.bitmask;
return *this;
}
GeneratorWrapper<BitmaskData const&> bitmaskGeneratorIncluding0(std::initializer_list<BitmaskData> const& bits)
{
return {BitmaskGenerator::create(true, bits)};
}
GeneratorWrapper<BitmaskData const&> bitmaskGenerator(std::initializer_list<BitmaskData> const& bits)
{
return {BitmaskGenerator::create(false, bits)};
}
} // namespace Conformance
| 32.872483 | 137 | 0.557575 | [
"vector"
] |
0f9777e74f57b3a39f976c89d6922d5cd92525e6 | 10,353 | cpp | C++ | src/other/ext/openscenegraph/src/osg/AutoTransform.cpp | lf-/brlcad | f91ea585c1a930a2e97c3f5a8274db8805ebbb46 | [
"BSD-4-Clause",
"BSD-3-Clause"
] | null | null | null | src/other/ext/openscenegraph/src/osg/AutoTransform.cpp | lf-/brlcad | f91ea585c1a930a2e97c3f5a8274db8805ebbb46 | [
"BSD-4-Clause",
"BSD-3-Clause"
] | null | null | null | src/other/ext/openscenegraph/src/osg/AutoTransform.cpp | lf-/brlcad | f91ea585c1a930a2e97c3f5a8274db8805ebbb46 | [
"BSD-4-Clause",
"BSD-3-Clause"
] | null | null | null | /* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* 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
* OpenSceneGraph Public License for more details.
*/
#include <osg/AutoTransform>
#include <osg/CullStack>
#include <osg/Notify>
#include <osg/io_utils>
using namespace osg;
AutoTransform::AutoTransform():
_autoUpdateEyeMovementTolerance(0.0),
_autoRotateMode(NO_ROTATION),
_autoScaleToScreen(false),
_scale(1.0,1.0,1.0),
_minimumScale(0.0),
_maximumScale(DBL_MAX),
_autoScaleTransitionWidthRatio(0.25),
_axis(0.0f,0.0f,1.0f),
_normal(0.0f,-1.0f,0.0f),
_cachedMode(NO_ROTATION),
_side(1.0f,0.0,0.0f)
{
// setNumChildrenRequiringUpdateTraversal(1);
}
AutoTransform::AutoTransform(const AutoTransform& pat,const CopyOp& copyop):
Transform(pat,copyop),
_position(pat._position),
_pivotPoint(pat._pivotPoint),
_autoUpdateEyeMovementTolerance(pat._autoUpdateEyeMovementTolerance),
_autoRotateMode(pat._autoRotateMode),
_autoScaleToScreen(pat._autoScaleToScreen),
_rotation(pat._rotation),
_scale(pat._scale),
_minimumScale(pat._minimumScale),
_maximumScale(pat._maximumScale),
_autoScaleTransitionWidthRatio(pat._autoScaleTransitionWidthRatio),
_axis(pat._axis),
_normal(pat._normal),
_cachedMode(pat._cachedMode),
_side(pat._side)
{
// setNumChildrenRequiringUpdateTraversal(getNumChildrenRequiringUpdateTraversal()+1);
}
void AutoTransform::setAutoScaleToScreen(bool autoScaleToScreen)
{
_autoScaleToScreen = autoScaleToScreen;
if (_autoScaleToScreen) setCullingActive(false);
}
void AutoTransform::setAutoRotateMode(AutoRotateMode mode)
{
_autoRotateMode = mode;
_cachedMode = CACHE_DIRTY;
updateCache();
}
void AutoTransform::setAxis(const Vec3& axis)
{
_axis = axis;
_axis.normalize();
updateCache();
}
void AutoTransform::setNormal(const Vec3& normal)
{
_normal = normal;
_normal.normalize();
updateCache();
}
void AutoTransform::updateCache()
{
if (_autoRotateMode==ROTATE_TO_AXIS)
{
if (_axis==Vec3(1.0f,0.0,0.0f) && _normal==Vec3(0.0f,-1.0,0.0f)) _cachedMode = AXIAL_ROT_X_AXIS;
else if (_axis==Vec3(0.0f,1.0,0.0f) && _normal==Vec3(1.0f, 0.0,0.0f)) _cachedMode = AXIAL_ROT_Y_AXIS;
else if (_axis==Vec3(0.0f,0.0,1.0f) && _normal==Vec3(0.0f,-1.0,0.0f)) _cachedMode = AXIAL_ROT_Z_AXIS;
else _cachedMode = ROTATE_TO_AXIS;
}
else _cachedMode = _autoRotateMode;
_side = _axis^_normal;
_side.normalize();
}
void AutoTransform::setScale(const Vec3d& scale)
{
_scale = scale;
if (_scale.x()<_minimumScale) _scale.x() = _minimumScale;
if (_scale.y()<_minimumScale) _scale.y() = _minimumScale;
if (_scale.z()<_minimumScale) _scale.z() = _minimumScale;
if (_scale.x()>_maximumScale) _scale.x() = _maximumScale;
if (_scale.y()>_maximumScale) _scale.y() = _maximumScale;
if (_scale.z()>_maximumScale) _scale.z() = _maximumScale;
dirtyBound();
}
bool AutoTransform::computeLocalToWorldMatrix(Matrix& matrix,NodeVisitor* nv) const
{
if (_referenceFrame==RELATIVE_RF)
{
matrix.preMult(computeMatrix(nv));
}
else // absolute
{
matrix = computeMatrix(nv);
}
return true;
}
bool AutoTransform::computeWorldToLocalMatrix(Matrix& matrix,NodeVisitor* nv) const
{
if (_referenceFrame==RELATIVE_RF)
{
matrix.postMult(osg::Matrix::inverse(computeMatrix(nv)));
}
else // absolute
{
matrix = osg::Matrix::inverse(computeMatrix(nv));
}
return true;
}
osg::Matrixd AutoTransform::computeMatrix(const osg::NodeVisitor* nv) const
{
Quat rotation = _rotation;
osg::Vec3d scale = _scale;
const CullStack* cs = nv ? nv->asCullStack() : 0;
if (cs)
{
osg::Vec3d eyePoint = cs->getEyeLocal();
osg::Vec3d localUp = cs->getUpLocal();
if (getAutoScaleToScreen())
{
double size = 1.0/cs->pixelSize(getPosition(),0.48f);
if (_autoScaleTransitionWidthRatio>0.0)
{
if (_minimumScale>0.0)
{
double j = _minimumScale;
double i = (_maximumScale<DBL_MAX) ?
_minimumScale+(_maximumScale-_minimumScale)*_autoScaleTransitionWidthRatio :
_minimumScale*(1.0+_autoScaleTransitionWidthRatio);
double c = 1.0/(4.0*(i-j));
double b = 1.0 - 2.0*c*i;
double a = j + b*b / (4.0*c);
double k = -b / (2.0*c);
if (size<k) size = _minimumScale;
else if (size<i) size = a + b*size + c*(size*size);
}
if (_maximumScale<DBL_MAX)
{
double n = _maximumScale;
double m = (_minimumScale>0.0) ?
_maximumScale+(_minimumScale-_maximumScale)*_autoScaleTransitionWidthRatio :
_maximumScale*(1.0-_autoScaleTransitionWidthRatio);
double c = 1.0 / (4.0*(m-n));
double b = 1.0 - 2.0*c*m;
double a = n + b*b/(4.0*c);
double p = -b / (2.0*c);
if (size>p) size = _maximumScale;
else if (size>m) size = a + b*size + c*(size*size);
}
}
else
{
if (_minimumScale>0.0 && size<_minimumScale)
{
size = _minimumScale;
}
if (_maximumScale<DBL_MAX && size>_maximumScale)
{
size = _maximumScale;
}
}
// TODO setScale(size);
scale.set(size, size, size);
}
if (_autoRotateMode==ROTATE_TO_SCREEN)
{
osg::Vec3d mv_translation;
osg::Vec3d mv_scale;
osg::Quat mv_rotation;
osg::Quat mv_so;
cs->getModelViewMatrix()->decompose( mv_translation, mv_rotation, mv_scale, mv_so );
// TODO setRotation(rotation.inverse());
rotation = mv_rotation.inverse();
}
else if (_autoRotateMode==ROTATE_TO_CAMERA)
{
osg::Vec3d PosToEye = _position - eyePoint;
osg::Matrix lookto = osg::Matrix::lookAt(
osg::Vec3d(0,0,0), PosToEye, localUp);
Quat q;
q.set(osg::Matrix::inverse(lookto));
// TODO setRotation(q);
rotation = q;
}
else if (_autoRotateMode==ROTATE_TO_AXIS)
{
Matrix matrix;
Vec3 ev(eyePoint - _position);
switch(_cachedMode)
{
case(AXIAL_ROT_Z_AXIS):
{
ev.z() = 0.0f;
float ev_length = ev.length();
if (ev_length>0.0f)
{
//float rotation_zrotation_z = atan2f(ev.x(),ev.y());
//mat.makeRotate(inRadians(rotation_z),0.0f,0.0f,1.0f);
float inv = 1.0f/ev_length;
float s = ev.x()*inv;
float c = -ev.y()*inv;
matrix(0,0) = c;
matrix(1,0) = -s;
matrix(0,1) = s;
matrix(1,1) = c;
}
break;
}
case(AXIAL_ROT_Y_AXIS):
{
ev.y() = 0.0f;
float ev_length = ev.length();
if (ev_length>0.0f)
{
//float rotation_zrotation_z = atan2f(ev.x(),ev.y());
//mat.makeRotate(inRadians(rotation_z),0.0f,0.0f,1.0f);
float inv = 1.0f/ev_length;
float s = -ev.z()*inv;
float c = ev.x()*inv;
matrix(0,0) = c;
matrix(2,0) = s;
matrix(0,2) = -s;
matrix(2,2) = c;
}
break;
}
case(AXIAL_ROT_X_AXIS):
{
ev.x() = 0.0f;
float ev_length = ev.length();
if (ev_length>0.0f)
{
//float rotation_zrotation_z = atan2f(ev.x(),ev.y());
//mat.makeRotate(inRadians(rotation_z),0.0f,0.0f,1.0f);
float inv = 1.0f/ev_length;
float s = -ev.z()*inv;
float c = -ev.y()*inv;
matrix(1,1) = c;
matrix(2,1) = -s;
matrix(1,2) = s;
matrix(2,2) = c;
}
break;
}
case(ROTATE_TO_AXIS): // need to implement
{
float ev_side = ev*_side;
float ev_normal = ev*_normal;
float angle = atan2f(ev_side,ev_normal);
matrix.makeRotate(angle,_axis);
break;
}
}
Quat q;
q.set(matrix);
// TODO setRotation(q);
rotation = q;
}
}
_rotation = rotation;
_scale = scale;
// setRotation(rotation);
// setScale(scale);
osg::Matrixd matrix;
matrix.makeRotate(rotation);
matrix.postMultTranslate(_position);
matrix.preMultScale(scale);
matrix.preMultTranslate(-_pivotPoint);
return matrix;
}
| 32.659306 | 109 | 0.521781 | [
"transform"
] |
0f985575a724684b17581fbc94c41e18f61e0104 | 2,172 | hpp | C++ | openstudiocore/src/openstudio_lib/RunTabController.hpp | ORNL-BTRIC/OpenStudio | 878f94bebf6f025445d1373e8b2304ececac16d8 | [
"blessing"
] | null | null | null | openstudiocore/src/openstudio_lib/RunTabController.hpp | ORNL-BTRIC/OpenStudio | 878f94bebf6f025445d1373e8b2304ececac16d8 | [
"blessing"
] | null | null | null | openstudiocore/src/openstudio_lib/RunTabController.hpp | ORNL-BTRIC/OpenStudio | 878f94bebf6f025445d1373e8b2304ececac16d8 | [
"blessing"
] | null | null | null | /**********************************************************************
* Copyright (c) 2008-2014, Alliance for Sustainable Energy.
* All rights reserved.
*
* 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.1 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**********************************************************************/
#ifndef OPENSTUDIO_RUNTABCONTROLLER_H
#define OPENSTUDIO_RUNTABCONTROLLER_H
#include <openstudio_lib/MainTabController.hpp>
#include <utilities/core/Path.hpp>
namespace openstudio {
namespace runmanager {
class RunManager;
class JobStatusWidget;
}
namespace model {
class Model;
}
class RunView;
class RunTabController : public MainTabController
{
Q_OBJECT
public:
RunTabController(const model::Model & model, const openstudio::path &t_modelPath,
const openstudio::path &t_tempFolder, openstudio::runmanager::RunManager t_runManager);
virtual ~RunTabController() {}
openstudio::RunView * runView();
runmanager::RunManager runManager();
enum TabID
{
OUTPUT,
TREE
};
signals:
void resultsGenerated(const openstudio::path &t_sqlFile, const openstudio::path &t_radianceOutputFile);
void toolsUpdated();
void useRadianceStateChanged(bool);
public slots:
void updateToolsWarnings();
private:
RunView * m_runView;
openstudio::runmanager::JobStatusWidget * m_status;
};
} // openstudio
#endif // OPENSTUDIO_RUNTABCONTROLLER_H
| 27.493671 | 108 | 0.667587 | [
"model"
] |
0f99ae747491dfa92d2d8cce311aee723b00ef69 | 492 | cpp | C++ | src/Pathfinding-Visualizer/Search.cpp | joshuainovero/Pathfinding-Visualizer | da94f026d2a1c26cb5241500e8013d1e9d906543 | [
"MIT"
] | 4 | 2021-10-15T03:40:48.000Z | 2022-01-19T18:48:01.000Z | src/Pathfinding-Visualizer/Search.cpp | joshuainovero/Pathfinding-Visualizer | da94f026d2a1c26cb5241500e8013d1e9d906543 | [
"MIT"
] | null | null | null | src/Pathfinding-Visualizer/Search.cpp | joshuainovero/Pathfinding-Visualizer | da94f026d2a1c26cb5241500e8013d1e9d906543 | [
"MIT"
] | 2 | 2021-10-15T03:40:52.000Z | 2022-01-05T10:07:42.000Z | #include "Search.hpp"
Search_::Search_(std::vector<Node*>* tiles_, uint32_t total_rows_, Node* start, Node* end)
: Algorithm_(tiles_, total_rows_){
start_node = start;
end_node = end;
}
Search_::~Search_() {}
void Search_::reconstruct_path(Node* current){
while (current != start_node){
path_nodes.push_back(current);
current = previous_node[current];
}
std::reverse(path_nodes.begin(), path_nodes.end());
path_nodes.pop_back();
} | 23.428571 | 90 | 0.650407 | [
"vector"
] |
0f9a32a4b0db516b0c88b292aad36702c4654b24 | 3,412 | cpp | C++ | velox/tpch/gen/DBGenIterator.cpp | laithsakka/velox | 41c01f63276205f6afd7e1db49c9d09430dcfbcc | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | velox/tpch/gen/DBGenIterator.cpp | laithsakka/velox | 41c01f63276205f6afd7e1db49c9d09430dcfbcc | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | velox/tpch/gen/DBGenIterator.cpp | laithsakka/velox | 41c01f63276205f6afd7e1db49c9d09430dcfbcc | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "velox/tpch/gen/DBGenIterator.h"
#include <folly/Singleton.h>
#include "velox/common/base/Exceptions.h"
#include "velox/external/duckdb/tpch/dbgen/include/dbgen/dbgen_gunk.hpp"
namespace facebook::velox::tpch {
namespace {
// DBGenLease is a singleton that controls access to the DBGEN C functions. It
// handles initialization and cleanup of dbgen gunk structures, and set/unset of
// global variables used by DBGEN.
//
// Only acquire instances of this class using folly::Singleton.
class DBGenLease {
public:
DBGenLease() {
// load_dists()/cleanup_dists() need to be called to ensure the global
// variables required by dbgen are populated.
load_dists();
}
~DBGenLease() {
cleanup_dists();
}
// Get a lease, or a permission to safely call internal dbgen functions.
std::unique_lock<std::mutex> getLease(size_t scaleFactor) {
auto lock = std::unique_lock<std::mutex>{mutex_};
// DBGEN takes the scale factor through this global variable.
scale = scaleFactor;
// This is tricky: dbgen code initializes seeds using hard-coded literals in
// the C codebase, which are updated every time a record is generated. In
// order to make these functions reproducible, before we make the first
// invocation we need to make a copy (a backup) of the initial state of
// these seeds. For subsequent leases, we restore that backed up state to
// ensure results are reproducible.
if (firstCall_) {
// Store the initial random seed.
memcpy(seedBackup_, seed_, sizeof(seed_t) * MAX_STREAM + 1);
firstCall_ = false;
} else {
// Restore random seeds from backup.
memcpy(seed_, seedBackup_, sizeof(seed_t) * MAX_STREAM + 1);
}
return lock;
}
private:
std::mutex mutex_;
seed_t* seed_{DBGenGlobals::Seed};
seed_t seedBackup_[MAX_STREAM + 1];
bool firstCall_{true};
};
// Make the object above a singleton.
static folly::Singleton<DBGenLease> DBGenLeaseSingleton;
} // namespace
DBGenIterator DBGenIterator::create(size_t scaleFactor) {
auto dbGenLease = DBGenLeaseSingleton.try_get();
VELOX_CHECK_NOT_NULL(dbGenLease);
return DBGenIterator(dbGenLease->getLease(scaleFactor));
}
void DBGenIterator::genNation(size_t index, code_t& code) {
row_start(NATION);
mk_nation(index, &code);
row_stop_h(NATION);
}
void DBGenIterator::genOrder(size_t index, order_t& order) {
row_start(ORDER);
mk_order(index, &order, /*update-num=*/0);
row_stop_h(ORDER);
}
void DBGenIterator::genSupplier(size_t index, supplier_t& supplier) {
row_start(SUPP);
mk_supp(index, &supplier);
row_stop_h(SUPP);
}
void DBGenIterator::genPart(size_t index, part_t& part) {
row_start(PART);
mk_part(index, &part);
row_stop_h(PART);
}
} // namespace facebook::velox::tpch
| 30.738739 | 80 | 0.720692 | [
"object"
] |
0f9d39758a45fdedd802b2bd02eebeaf08d1932e | 2,477 | cpp | C++ | formresult.cpp | horsicq/StaticScan | 8688d135e8a51f32398b099e255d56bca3c46da9 | [
"MIT"
] | 7 | 2018-05-10T14:03:07.000Z | 2020-08-02T05:48:26.000Z | formresult.cpp | horsicq/StaticScan | 8688d135e8a51f32398b099e255d56bca3c46da9 | [
"MIT"
] | null | null | null | formresult.cpp | horsicq/StaticScan | 8688d135e8a51f32398b099e255d56bca3c46da9 | [
"MIT"
] | 6 | 2017-06-03T17:58:36.000Z | 2021-09-14T07:12:46.000Z | // copyright (c) 2017-2021 hors<horsicq@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.
//
#include "formresult.h"
#include "ui_formresult.h"
FormResult::FormResult(QWidget *pParent) :
QWidget(pParent),
ui(new Ui::FormResult)
{
ui->setupUi(this);
g_pModel=nullptr;
g_scanResult={0};
}
FormResult::~FormResult()
{
delete ui;
}
void FormResult::setData(SpecAbstract::SCAN_RESULT scanResult, QString sSaveFileName)
{
this->g_scanResult=scanResult;
this->g_sSaveFileName=sSaveFileName;
ui->labelElapsedTime->clear();
QAbstractItemModel *pOldModel=ui->treeViewResult->model();
g_pModel=new StaticScanItemModel(&(this->g_scanResult.listRecords),this,1);
ui->treeViewResult->setModel(g_pModel);
ui->treeViewResult->expandAll();
delete pOldModel;
ui->labelElapsedTime->setText(QString("%1 %2").arg(QString::number(g_scanResult.nScanTime),tr("msec")));
}
void FormResult::on_pushButtonClear_clicked()
{
QAbstractItemModel *pOldModel=ui->treeViewResult->model();
ui->treeViewResult->setModel(nullptr);
delete pOldModel;
ui->labelElapsedTime->clear();
}
void FormResult::on_pushButtonSave_clicked()
{
QAbstractItemModel *pModel=ui->treeViewResult->model();
if(pModel)
{
DialogStaticScanProcess::saveResult(this,(StaticScanItemModel *)pModel,g_sSaveFileName);
}
}
| 32.168831 | 109 | 0.716996 | [
"model"
] |
0f9e7c030437e334a38f6b91eccfa694185053f7 | 11,162 | cpp | C++ | ovr_sdk_mobile/VrAppFramework/Src/App_Android.cpp | ejeinc/Meganekko | c62d82e8a5d2eb67af056282f4ff7c90cbd73494 | [
"Apache-2.0"
] | 25 | 2015-10-08T09:35:35.000Z | 2018-09-14T06:53:39.000Z | ovr_sdk_mobile/VrAppFramework/Src/App_Android.cpp | ejeinc/Meganekko | c62d82e8a5d2eb67af056282f4ff7c90cbd73494 | [
"Apache-2.0"
] | 16 | 2015-09-28T07:21:55.000Z | 2017-04-25T02:31:57.000Z | ovr_sdk_mobile/VrAppFramework/Src/App_Android.cpp | ejeinc/Meganekko | c62d82e8a5d2eb67af056282f4ff7c90cbd73494 | [
"Apache-2.0"
] | 11 | 2016-03-17T02:34:17.000Z | 2022-01-19T08:10:35.000Z | /************************************************************************************
Filename : App_Android.cpp
Content : Native counterpart to VrActivity and VrApp
Created : September 30, 2013
Authors : John Carmack
Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved.
*************************************************************************************/
#include "App.h"
#include "AppLocal.h"
#if defined( OVR_OS_ANDROID )
#include "Android/JniUtils.h"
#include "VrApi.h"
#include "VrApi_Helpers.h"
#include <android/native_window_jni.h> // for native window JNI
#include "OVR_Input.h"
// do not queue input events if less than this number of slots are available in the
// message queue. This prevents input from overflowing the queue if the message
// queue is not be serviced by VrThreadFunction.
static const int MIN_SLOTS_AVAILABLE_FOR_INPUT = 12;
void ComposeIntentMessage( char const * packageName, char const * uri, char const * jsonText,
char * out, size_t outSize );
extern "C"
{
// The JNIEXPORT macro prevents the functions from ever being stripped out of the library.
void Java_com_oculus_vrappframework_VrApp_nativeOnCreate( JNIEnv *jni, jclass clazz, jobject activity )
{
ovrJava java;
jni->GetJavaVM( &java.Vm );
java.Env = jni;
java.ActivityObject = activity;
const ovrInitParms initParms = vrapi_DefaultInitParms( &java );
int32_t initResult = vrapi_Initialize( &initParms );
if ( initResult != VRAPI_INITIALIZE_SUCCESS )
{
LOG( "vrapi_Initialize failed" );
// If intialization failed, vrapi_* function calls will not be available.
exit( 0 );
}
}
void Java_com_oculus_vrappframework_VrApp_nativeOnPause( JNIEnv *jni, jclass clazz,
jlong appPtr )
{
LOG( "%p nativePause", (void *)appPtr );
OVR::AppLocal * appLocal = (OVR::AppLocal *)appPtr;
appLocal->GetMessageQueue().SendPrintf( "pause " );
}
void Java_com_oculus_vrappframework_VrApp_nativeOnResume( JNIEnv *jni, jclass clazz,
jlong appPtr )
{
LOG( "%p nativeResume", (void *)appPtr );
OVR::AppLocal * appLocal = (OVR::AppLocal *)appPtr;
appLocal->GetMessageQueue().SendPrintf( "resume " );
}
void Java_com_oculus_vrappframework_VrApp_nativeOnDestroy( JNIEnv *jni, jclass clazz,
jlong appPtr )
{
LOG( "%p nativeDestroy", (void *)appPtr );
OVR::AppLocal * appLocal = (OVR::AppLocal *)appPtr;
const bool exitOnDestroy = appLocal->ExitOnDestroy;
appLocal->StopVrThread();
appLocal->SetActivity( jni, NULL );
delete appLocal;
vrapi_Shutdown();
if ( exitOnDestroy )
{
LOG( "ExitOnDestroy is true, exiting" );
exit( 0 ); // FIXME: is this still needed?
}
else
{
LOG( "ExitOnDestroy was false, returning normally." );
}
}
void Java_com_oculus_vrappframework_VrApp_nativeSurfaceCreated( JNIEnv *jni, jclass clazz,
jlong appPtr, jobject surface )
{
LOG( "%p nativeSurfaceCreated( %p )", (void *)appPtr, surface );
OVR::AppLocal * appLocal = (OVR::AppLocal *)appPtr;
ANativeWindow * newNativeWindow = ANativeWindow_fromSurface( jni, surface );
if ( ANativeWindow_getWidth( newNativeWindow ) < ANativeWindow_getHeight( newNativeWindow ) )
{
// An app that is relaunched after pressing the home button gets an initial surface with
// the wrong orientation even though android:screenOrientation="landscape" is set in the
// manifest. The choreographer callback will also never be called for this surface because
// the surface is immediately replaced with a new surface with the correct orientation.
WARN( " Surface not in landscape mode!" );
}
LOG( " pendingNativeWindow = ANativeWindow_fromSurface( jni, surface )" );
appLocal->pendingNativeWindow = newNativeWindow;
appLocal->GetMessageQueue().SendPrintf( "surfaceCreated " );
}
void Java_com_oculus_vrappframework_VrApp_nativeSurfaceChanged( JNIEnv *jni, jclass clazz,
jlong appPtr, jobject surface )
{
LOG( "%p nativeSurfaceChanged( %p )", (void *)appPtr, surface );
OVR::AppLocal * appLocal = (OVR::AppLocal *)appPtr;
ANativeWindow * newNativeWindow = ANativeWindow_fromSurface( jni, surface );
if ( ANativeWindow_getWidth( newNativeWindow ) < ANativeWindow_getHeight( newNativeWindow ) )
{
// An app that is relaunched after pressing the home button gets an initial surface with
// the wrong orientation even though android:screenOrientation="landscape" is set in the
// manifest. The choreographer callback will also never be called for this surface because
// the surface is immediately replaced with a new surface with the correct orientation.
WARN( " Surface not in landscape mode!" );
}
if ( newNativeWindow != appLocal->pendingNativeWindow )
{
if ( appLocal->pendingNativeWindow != NULL )
{
appLocal->GetMessageQueue().SendPrintf( "surfaceDestroyed " );
LOG( " ANativeWindow_release( pendingNativeWindow )" );
ANativeWindow_release( appLocal->pendingNativeWindow );
appLocal->pendingNativeWindow = NULL;
}
if ( newNativeWindow != NULL )
{
LOG( " pendingNativeWindow = ANativeWindow_fromSurface( jni, surface )" );
appLocal->pendingNativeWindow = newNativeWindow;
appLocal->GetMessageQueue().SendPrintf( "surfaceCreated " );
}
}
else if ( newNativeWindow != NULL )
{
ANativeWindow_release( newNativeWindow );
}
}
void Java_com_oculus_vrappframework_VrApp_nativeSurfaceDestroyed( JNIEnv *jni, jclass clazz,
jlong appPtr, jobject surface )
{
LOG( "%p nativeSurfaceDestroyed()", (void *)appPtr );
OVR::AppLocal * appLocal = (OVR::AppLocal *)appPtr;
appLocal->GetMessageQueue().SendPrintf( "surfaceDestroyed " );
LOG( " ANativeWindow_release( %p )", appLocal->pendingNativeWindow );
ANativeWindow_release( appLocal->pendingNativeWindow );
appLocal->pendingNativeWindow = NULL;
}
void Java_com_oculus_vrappframework_VrActivity_nativeJoypadAxis( JNIEnv *jni, jclass clazz,
jlong appPtr, jfloat lx, jfloat ly, jfloat rx, jfloat ry )
{
OVR::AppLocal * appLocal = (OVR::AppLocal *)appPtr;
// Suspend input until EnteredVrMode( INTENT_LAUNCH ) has finished to avoid overflowing the message queue on long loads.
if ( appLocal->IntentType != OVR::INTENT_LAUNCH )
{
appLocal->GetMessageQueue().PostPrintfIfSpaceAvailable( MIN_SLOTS_AVAILABLE_FOR_INPUT, "joy %f %f %f %f", lx, ly, rx, ry );
}
}
void Java_com_oculus_vrappframework_VrActivity_nativeTouch( JNIEnv *jni, jclass clazz,
jlong appPtr, jint action, jfloat x, jfloat y )
{
OVR::AppLocal * appLocal = (OVR::AppLocal *)appPtr;
// Suspend input until EnteredVrMode( INTENT_LAUNCH ) has finished to avoid overflowing the message queue on long loads.
if ( appLocal->IntentType != OVR::INTENT_LAUNCH )
{
appLocal->GetMessageQueue().PostPrintfIfSpaceAvailable( MIN_SLOTS_AVAILABLE_FOR_INPUT, "touch %i %f %f", action, x, y );
}
}
void Java_com_oculus_vrappframework_VrActivity_nativeKeyEvent( JNIEnv *jni, jclass clazz,
jlong appPtr, jint key, jboolean down, jint repeatCount )
{
OVR::AppLocal * appLocal = (OVR::AppLocal *)appPtr;
// Suspend input until EnteredVrMode( INTENT_LAUNCH ) has finished to avoid overflowing the message queue on long loads.
if ( appLocal->IntentType != OVR::INTENT_LAUNCH )
{
OVR::ovrKeyCode keyCode = OVR::OSKeyToKeyCode( key );
//LOG( "nativeKeyEvent: key = %i, keyCode = %i, down = %s, repeatCount = %i", key, keyCode, down ? "true" : "false", repeatCount );
appLocal->GetMessageQueue().PostPrintfIfSpaceAvailable( MIN_SLOTS_AVAILABLE_FOR_INPUT, "key %i %i %i", keyCode, down, repeatCount );
}
}
void Java_com_oculus_vrappframework_VrActivity_nativeNewIntent( JNIEnv *jni, jclass clazz,
jlong appPtr, jstring fromPackageName, jstring command, jstring uriString )
{
LOG( "%p nativeNewIntent", (void *)appPtr );
JavaUTFChars utfPackageName( jni, fromPackageName );
JavaUTFChars utfUri( jni, uriString );
JavaUTFChars utfJson( jni, command );
char intentMessage[4096];
ComposeIntentMessage( utfPackageName.ToStr(), utfUri.ToStr(), utfJson.ToStr(),
intentMessage, sizeof( intentMessage ) );
LOG( "nativeNewIntent: %s", intentMessage );
OVR::AppLocal * appLocal = (OVR::AppLocal *)appPtr;
appLocal->GetMessageQueue().PostString( intentMessage );
}
} // extern "C"
namespace OVR
{
//=======================================================================================
// VrAppInterface
//=======================================================================================
jlong VrAppInterface::SetActivity( JNIEnv * jni, jclass clazz, jobject activity, jstring javaFromPackageNameString,
jstring javaCommandString, jstring javaUriString )
{
// Make a permanent global reference for the class
if ( ActivityClass != NULL )
{
jni->DeleteGlobalRef( ActivityClass );
}
ActivityClass = (jclass)jni->NewGlobalRef( clazz );
JavaUTFChars utfFromPackageString( jni, javaFromPackageNameString );
JavaUTFChars utfJsonString( jni, javaCommandString );
JavaUTFChars utfUriString( jni, javaUriString );
LOG( "VrAppInterface::SetActivity: %s %s %s", utfFromPackageString.ToStr(), utfJsonString.ToStr(), utfUriString.ToStr() );
AppLocal * appLocal = static_cast< AppLocal * >( app );
if ( appLocal == NULL )
{ // First time initialization
// This will set the VrAppInterface app pointer directly,
// so it is set when OneTimeInit is called.
LOG( "new AppLocal( %p %p %p )", jni, activity, this );
appLocal = new AppLocal( *jni, activity, *this );
app = appLocal;
// Start the VrThread and wait for it to have initialized.
appLocal->StartVrThread();
}
else
{ // Just update the activity object.
LOG( "Update AppLocal( %p %p %p )", jni, activity, this );
appLocal->SetActivity( jni, activity );
}
// Send the launch intent.
char intentMessage[4096];
ComposeIntentMessage( utfFromPackageString.ToStr(), utfUriString.ToStr(), utfJsonString.ToStr(), intentMessage, sizeof( intentMessage ) );
appLocal->GetMessageQueue().PostString( intentMessage );
return (jlong)app;
}
//=======================================================================================
// AppLocal
//=======================================================================================
void AppLocal::SetActivity( JNIEnv * jni, jobject activity )
{
if ( Java.ActivityObject != NULL )
{
jni->DeleteGlobalRef( Java.ActivityObject );
Java.ActivityObject = NULL;
VrSettings.ModeParms.Java.ActivityObject = NULL;
}
if ( activity != NULL )
{
Java.ActivityObject = jni->NewGlobalRef( activity );
VrSettings.ModeParms.Java.ActivityObject = Java.ActivityObject;
}
}
void AppLocal::HandleVrModeChanges()
{
if ( Resumed != false && nativeWindow != NULL )
{
if ( OvrMobile == NULL )
{
Configure();
EnterVrMode();
}
}
else
{
if ( OvrMobile != NULL )
{
LeaveVrMode();
}
}
}
// This callback happens from the java thread, after a string has been
// pulled off the message queue
void AppLocal::TtjCommand( JNIEnv & jni, const char * commandString )
{
if ( MatchesHead( "finish ", commandString ) )
{
jni.CallVoidMethod( Java.ActivityObject, finishActivityMethodId );
}
}
} // namespace OVR
#else // OVR_OS_ANDROID
// add a single symbol to avoid LNK4221 when there are no symbols defined
namespace { char App_Android_EmptyFile; }
#endif
| 34.134557 | 139 | 0.698889 | [
"object"
] |
0fa4df1c5629039d3aa2f1f5aed0da934c422dbe | 1,090 | cpp | C++ | codes/CodeForces/Round #259/cf453C.cpp | JeraKrs/ACM | edcd61ec6764b8cd804bf1538dfde53d0ff572b5 | [
"Apache-2.0"
] | null | null | null | codes/CodeForces/Round #259/cf453C.cpp | JeraKrs/ACM | edcd61ec6764b8cd804bf1538dfde53d0ff572b5 | [
"Apache-2.0"
] | null | null | null | codes/CodeForces/Round #259/cf453C.cpp | JeraKrs/ACM | edcd61ec6764b8cd804bf1538dfde53d0ff572b5 | [
"Apache-2.0"
] | null | null | null | #include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
const int maxn = 1e5+5;
int N, M, a, b, s;
int ans, rec[maxn*4];
int c[maxn], v[maxn];
vector<int> g[maxn];
void init () {
ans = s = 0;
scanf("%d%d", &N, &M);
memset(v, 0, sizeof(v));
for (int i = 0; i < M; i++) {
scanf("%d%d", &a, &b);
g[a].push_back(b);
g[b].push_back(a);
}
for (int i = 1; i <= N; i++) {
scanf("%d", &c[i]);
if (c[i])
s = i;
}
}
inline void set (int u) {
c[u] ^= 1;
rec[ans++] = u;
}
void dfs (int u) {
set(u);
v[u] = 1;
for (int i = 0; i < g[u].size(); i++) {
if (v[g[u][i]])
continue;
dfs(g[u][i]);
set(u);
if (c[g[u][i]]) {
set(g[u][i]);
set(u);
}
}
}
bool judge () {
for (int i = 1; i <= N; i++)
if (c[i])
return false;
return true;
}
int main () {
init();
dfs(s);
if (c[s]) {
c[s] = 0;
ans--;
}
if (judge ()) {
printf("%d\n", ans);
if (ans) {
printf("%d", rec[0]);
for (int i = 1; i < ans; i++)
printf(" %d", rec[i]);
printf("\n");
}
} else
printf("-1\n");
return 0;
}
| 13.13253 | 40 | 0.457798 | [
"vector"
] |
0fa765a5d53650a9e15fe367820103c6c0e6b621 | 12,053 | cpp | C++ | src/IB/IBFEPostProcessor.cpp | syam-s/IBAMR | b6502f2f818835961d103fd2a2827d9336e68640 | [
"BSD-3-Clause"
] | 2 | 2020-03-03T12:29:36.000Z | 2021-02-15T06:54:20.000Z | src/IB/IBFEPostProcessor.cpp | syam-s/IBAMR | b6502f2f818835961d103fd2a2827d9336e68640 | [
"BSD-3-Clause"
] | null | null | null | src/IB/IBFEPostProcessor.cpp | syam-s/IBAMR | b6502f2f818835961d103fd2a2827d9336e68640 | [
"BSD-3-Clause"
] | null | null | null | // ---------------------------------------------------------------------
//
// Copyright (c) 2014 - 2019 by the IBAMR developers
// All rights reserved.
//
// This file is part of IBAMR.
//
// IBAMR is free software and is distributed under the 3-clause BSD
// license. The full text of the license can be found in the file
// COPYRIGHT at the top level directory of IBAMR.
//
// ---------------------------------------------------------------------
/////////////////////////////// INCLUDES /////////////////////////////////////
#include "ibamr/IBFEPostProcessor.h"
#include "ibamr/namespaces.h" // IWYU pragma: keep
#include "ibtk/FEDataManager.h"
#include "ibtk/LEInteractor.h"
#include "ibtk/libmesh_utilities.h"
#include "IntVector.h"
#include "PatchHierarchy.h"
#include "PatchLevel.h"
#include "RefineAlgorithm.h"
#include "RefineOperator.h"
#include "RefineSchedule.h"
#include "Variable.h"
#include "VariableContext.h"
#include "VariableDatabase.h"
#include "tbox/Pointer.h"
#include "tbox/RestartManager.h"
#include "tbox/Utilities.h"
#include "libmesh/enum_fe_family.h"
#include "libmesh/enum_order.h"
#include "libmesh/equation_systems.h"
#include "libmesh/system.h"
#include <memory>
#include <ostream>
#include <set>
#include <string>
#include <utility>
#include <vector>
namespace libMesh
{
template <typename T>
class NumericVector;
} // namespace libMesh
using namespace libMesh;
/////////////////////////////// NAMESPACE ////////////////////////////////////
namespace IBAMR
{
/////////////////////////////// STATIC ///////////////////////////////////////
/////////////////////////////// PUBLIC ///////////////////////////////////////
IBFEPostProcessor::IBFEPostProcessor(std::string name, FEDataManager* fe_data_manager)
: d_name(std::move(name)),
d_mesh(&fe_data_manager->getEquationSystems()->get_mesh()),
d_fe_data_manager(fe_data_manager)
{
// intentionally blank
return;
} // IBFEPostProcessor
void
IBFEPostProcessor::registerScalarVariable(const std::string& name,
libMesh::FEFamily fe_family,
libMesh::Order fe_order,
ScalarMeshFcnPtr fcn,
const std::vector<SystemData>& system_data,
void* fcn_ctx)
{
EquationSystems* equation_systems = d_fe_data_manager->getEquationSystems();
auto& system = equation_systems->add_system<System>(name + " reconstruction system");
RestartManager* restart_manager = RestartManager::getManager();
const bool is_from_restart = restart_manager->isFromRestart();
if (!is_from_restart) system.add_variable(name, fe_order, fe_family);
d_scalar_var_systems.push_back(&system);
d_scalar_var_fcns.push_back(fcn);
d_scalar_var_system_data.push_back(system_data);
d_scalar_var_fcn_ctxs.push_back(fcn_ctx);
d_var_systems.push_back(&system);
return;
} // registerScalarVariable
void
IBFEPostProcessor::registerVectorVariable(const std::string& name,
libMesh::FEFamily fe_family,
libMesh::Order fe_order,
VectorMeshFcnPtr fcn,
const std::vector<SystemData>& system_data,
void* fcn_ctx,
unsigned int dim)
{
EquationSystems* equation_systems = d_fe_data_manager->getEquationSystems();
auto& system = equation_systems->add_system<System>(name + " reconstruction system");
RestartManager* restart_manager = RestartManager::getManager();
const bool is_from_restart = restart_manager->isFromRestart();
for (unsigned int i = 0; i < dim; ++i)
{
if (!is_from_restart) system.add_variable(name + "_" + std::to_string(i), fe_order, fe_family);
}
d_vector_var_systems.push_back(&system);
d_vector_var_fcns.push_back(fcn);
d_vector_var_system_data.push_back(system_data);
d_vector_var_fcn_ctxs.push_back(fcn_ctx);
d_vector_var_dims.push_back(dim);
d_var_systems.push_back(&system);
return;
} // registerVectorVariable
void
IBFEPostProcessor::registerTensorVariable(const std::string& var_name,
libMesh::FEFamily var_fe_family,
libMesh::Order var_fe_order,
TensorMeshFcnPtr var_fcn,
const std::vector<SystemData>& system_data,
void* var_fcn_ctx,
unsigned int var_dim)
{
EquationSystems* equation_systems = d_fe_data_manager->getEquationSystems();
auto& system = equation_systems->add_system<System>(var_name + " reconstruction system");
RestartManager* restart_manager = RestartManager::getManager();
const bool is_from_restart = restart_manager->isFromRestart();
for (unsigned int i = 0; i < var_dim; ++i)
{
for (unsigned int j = 0; j < var_dim; ++j)
{
if (!is_from_restart)
system.add_variable(
var_name + "_" + std::to_string(i) + std::to_string(j), var_fe_order, var_fe_family);
}
}
d_tensor_var_systems.push_back(&system);
d_tensor_var_fcns.push_back(var_fcn);
d_tensor_var_system_data.push_back(system_data);
d_tensor_var_fcn_ctxs.push_back(var_fcn_ctx);
d_tensor_var_dims.push_back(var_dim);
d_var_systems.push_back(&system);
return;
} // registerTensorVariable
void
IBFEPostProcessor::registerInterpolatedScalarEulerianVariable(
const std::string& var_name,
libMesh::FEFamily var_fe_family,
libMesh::Order var_fe_order,
Pointer<hier::Variable<NDIM> > var,
Pointer<VariableContext> ctx,
const HierarchyGhostCellInterpolation::InterpolationTransactionComponent& ghost_fill_transaction)
{
registerInterpolatedScalarEulerianVariable(var_name,
var_fe_family,
var_fe_order,
var,
ctx,
ghost_fill_transaction,
d_fe_data_manager->getDefaultInterpSpec());
return;
} // registerInterpolatedScalarEulerianVariable
void
IBFEPostProcessor::registerInterpolatedScalarEulerianVariable(
const std::string& var_name,
libMesh::FEFamily var_fe_family,
libMesh::Order var_fe_order,
Pointer<hier::Variable<NDIM> > var,
Pointer<VariableContext> ctx,
const HierarchyGhostCellInterpolation::InterpolationTransactionComponent& ghost_fill_transaction,
const FEDataManager::InterpSpec& interp_spec)
{
EquationSystems* equation_systems = d_fe_data_manager->getEquationSystems();
auto& system = equation_systems->add_system<System>(var_name + " interpolation system");
RestartManager* restart_manager = RestartManager::getManager();
const bool is_from_restart = restart_manager->isFromRestart();
if (!is_from_restart) system.add_variable(var_name, var_fe_order, var_fe_family);
d_scalar_interp_var_systems.push_back(&system);
d_scalar_interp_vars.push_back(var);
d_scalar_interp_ctxs.push_back(ctx);
d_scalar_interp_data_idxs.push_back(-1); // These must be set up just before they are used.
d_scalar_interp_scratch_idxs.push_back(-1);
d_scalar_interp_fill_transactions.push_back(ghost_fill_transaction);
d_scalar_interp_specs.push_back(interp_spec);
d_var_systems.push_back(&system);
} // registerInterpolatedEulerianScalarVariable
void
IBFEPostProcessor::initializeFEData()
{
if (d_fe_data_initialized) return;
for (const auto& var_system : d_var_systems)
{
System& system = *var_system;
system.assemble_before_solve = false;
system.assemble();
}
d_fe_data_initialized = true;
return;
} // initializeFEData
void
IBFEPostProcessor::postProcessData(const double data_time)
{
// First interpolate variables from the Eulerian grid, then reconstruct
// variables on the Lagrangian mesh.
interpolateVariables(data_time);
reconstructVariables(data_time);
return;
} // postProcessData
/////////////////////////////// PROTECTED ////////////////////////////////////
void
IBFEPostProcessor::interpolateVariables(const double data_time)
{
Pointer<PatchHierarchy<NDIM> > hierarchy = d_fe_data_manager->getPatchHierarchy();
const std::pair<int, int> patch_level_range = d_fe_data_manager->getPatchLevels();
const int coarsest_ln = patch_level_range.first;
const int finest_ln = patch_level_range.second - 1;
const size_t num_eulerian_vars = d_scalar_interp_var_systems.size();
// Set up Eulerian scratch space and fill ghost cell values.
std::set<int> scratch_idxs;
for (unsigned int k = 0; k < num_eulerian_vars; ++k)
{
int& data_idx = d_scalar_interp_data_idxs[k];
int& scratch_idx = d_scalar_interp_scratch_idxs[k];
if (data_idx < 0 || scratch_idx < 0)
{
TBOX_ASSERT(data_idx < 0 || scratch_idx < 0);
VariableDatabase<NDIM>* var_db = VariableDatabase<NDIM>::getDatabase();
Pointer<hier::Variable<NDIM> > data_var = d_scalar_interp_vars[k];
Pointer<VariableContext> data_ctx = d_scalar_interp_ctxs[k];
data_idx = var_db->mapVariableAndContextToIndex(data_var, data_ctx);
TBOX_ASSERT(data_idx >= 0);
Pointer<VariableContext> scratch_ctx = var_db->getContext(d_name + "::SCRATCH");
const FEDataManager::InterpSpec& interp_spec = d_scalar_interp_specs[k];
const int ghost_width = LEInteractor::getMinimumGhostWidth(interp_spec.kernel_fcn) + 1;
scratch_idx = var_db->registerVariableAndContext(data_var, scratch_ctx, ghost_width);
scratch_idxs.insert(scratch_idx);
d_scalar_interp_fill_transactions[k].d_src_data_idx = data_idx;
d_scalar_interp_fill_transactions[k].d_dst_data_idx = scratch_idx;
}
}
for (int ln = coarsest_ln; ln <= finest_ln; ++ln)
{
Pointer<PatchLevel<NDIM> > level = hierarchy->getPatchLevel(ln);
for (unsigned int k = 0; k < num_eulerian_vars; ++k)
{
const int scratch_idx = d_scalar_interp_scratch_idxs[k];
if (!level->checkAllocated(scratch_idx)) level->allocatePatchData(scratch_idx, data_time);
}
}
HierarchyGhostCellInterpolation ghost_fill_op;
ghost_fill_op.initializeOperatorState(d_scalar_interp_fill_transactions, hierarchy);
ghost_fill_op.fillData(data_time);
// Interpolate variables.
NumericVector<double>* X_ghost_vec = d_fe_data_manager->buildGhostedCoordsVector(/*localize_data*/ true);
for (unsigned int k = 0; k < num_eulerian_vars; ++k)
{
System* system = d_scalar_interp_var_systems[k];
const std::string& system_name = system->name();
const int scratch_idx = d_scalar_interp_scratch_idxs[k];
d_fe_data_manager->interp(scratch_idx, *system->solution, *X_ghost_vec, system_name, d_scalar_interp_specs[k]);
}
// Deallocate Eulerian scratch space.
for (int ln = coarsest_ln; ln <= finest_ln; ++ln)
{
Pointer<PatchLevel<NDIM> > level = hierarchy->getPatchLevel(ln);
for (unsigned int k = 0; k < num_eulerian_vars; ++k)
{
const int scratch_idx = d_scalar_interp_scratch_idxs[k];
level->deallocatePatchData(scratch_idx);
}
}
return;
} // interpolateVariables
/////////////////////////////// PRIVATE //////////////////////////////////////
/////////////////////////////// NAMESPACE ////////////////////////////////////
} // namespace IBAMR
//////////////////////////////////////////////////////////////////////////////
| 40.446309 | 119 | 0.628308 | [
"mesh",
"vector"
] |
0fa81ec3a4e33c3b1ad1ed485a7d58f00bb8d0a0 | 1,438 | cpp | C++ | Chapter01/lambda_capturing_by_value/lambda_capturing_by_value.cpp | Vaibhav-Kashyap/-Learning-CPP-Functional-Programming-packt | 3c7ef5fcfb161870b644595c69fdb3a3522d8411 | [
"MIT"
] | 41 | 2017-08-25T07:13:57.000Z | 2022-01-06T12:28:33.000Z | Chapter01/lambda_capturing_by_value/lambda_capturing_by_value.cpp | Vaibhav-Kashyap/-Learning-CPP-Functional-Programming-packt | 3c7ef5fcfb161870b644595c69fdb3a3522d8411 | [
"MIT"
] | null | null | null | Chapter01/lambda_capturing_by_value/lambda_capturing_by_value.cpp | Vaibhav-Kashyap/-Learning-CPP-Functional-Programming-packt | 3c7ef5fcfb161870b644595c69fdb3a3522d8411 | [
"MIT"
] | 26 | 2017-08-10T21:12:25.000Z | 2021-11-17T07:25:04.000Z | /* lambda_capturing_by_value.cpp */
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
auto main() -> int
{
cout << "[lambda_capturing_by_value.cpp]" << endl;
// Initializing a vector containing integer element
vector<int> vect;
for (int i = 0; i < 10; ++i)
vect.push_back(i);
// Displaying the elements of vect
cout << "Original Data:" << endl;
for_each(
begin(vect),
end(vect),
[](int n){
cout << n << " ";
});
cout << endl;
// Initializing two variables
int a = 2;
int b = 8;
// Capturing value explicitly from the two variables
cout << "Printing elements between " << a;
cout << " and " << b << " explicitly [a,b]:" << endl;
for_each(
begin(vect),
end(vect),
[a,b](int n){
if (n >= a && n <= b)
cout << n << " ";
});
cout << endl;
// Modifying variable a and b
a = 3;
b = 7;
// Capturing value implicitly from the two variables
cout << "printing elements between " << a;
cout << " and " << b << " implicitly[=]:" << endl;
for_each(
begin(vect),
end(vect),
[=](int n){
if (n >= a && n <= b)
cout << n << " ";
});
cout << endl;
return 0;
}
| 23.57377 | 57 | 0.456885 | [
"vector"
] |
0fadda7fa420f51f251014cbfb942522cbab9ebf | 12,099 | cc | C++ | chrome/renderer/spellchecker/spellcheck.cc | GnorTech/chromium | e1c7731d5bd099ca5544fcf8eda3867d4ce5bab5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2018-03-10T13:08:49.000Z | 2018-03-10T13:08:49.000Z | chrome/renderer/spellchecker/spellcheck.cc | GnorTech/chromium | e1c7731d5bd099ca5544fcf8eda3867d4ce5bab5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/renderer/spellchecker/spellcheck.cc | GnorTech/chromium | e1c7731d5bd099ca5544fcf8eda3867d4ce5bab5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2020-11-04T07:19:31.000Z | 2020-11-04T07:19:31.000Z | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/renderer/spellchecker/spellcheck.h"
#include "base/bind.h"
#include "base/message_loop_proxy.h"
#include "base/utf_string_conversions.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/spellcheck_common.h"
#include "chrome/common/spellcheck_messages.h"
#include "chrome/common/spellcheck_result.h"
#include "chrome/renderer/spellchecker/spellcheck_language.h"
#include "chrome/renderer/spellchecker/spellcheck_provider.h"
#include "content/public/renderer/render_view.h"
#include "content/public/renderer/render_view_visitor.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebTextCheckingCompletion.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebTextCheckingResult.h"
using WebKit::WebVector;
using WebKit::WebTextCheckingResult;
using WebKit::WebTextCheckingType;
namespace {
class UpdateSpellcheckEnabled : public content::RenderViewVisitor {
public:
explicit UpdateSpellcheckEnabled(bool enabled) : enabled_(enabled) {}
virtual bool Visit(content::RenderView* render_view) OVERRIDE;
private:
bool enabled_; // New spellcheck-enabled state.
DISALLOW_COPY_AND_ASSIGN(UpdateSpellcheckEnabled);
};
bool UpdateSpellcheckEnabled::Visit(content::RenderView* render_view) {
SpellCheckProvider* provider = SpellCheckProvider::Get(render_view);
DCHECK(provider);
provider->EnableSpellcheck(enabled_);
return true;
}
} // namespace
class SpellCheck::SpellcheckRequest {
public:
SpellcheckRequest(const string16& text,
int offset,
WebKit::WebTextCheckingCompletion* completion)
: text_(text), offset_(offset), completion_(completion) {
DCHECK(completion);
}
~SpellcheckRequest() {}
string16 text() { return text_; }
int offset() { return offset_; }
WebKit::WebTextCheckingCompletion* completion() { return completion_; }
private:
string16 text_; // Text to be checked in this task.
int offset_; // The text offset from the beginning.
// The interface to send the misspelled ranges to WebKit.
WebKit::WebTextCheckingCompletion* completion_;
DISALLOW_COPY_AND_ASSIGN(SpellcheckRequest);
};
// Initializes SpellCheck object.
// spellcheck_enabled_ currently MUST be set to true, due to peculiarities of
// the initialization sequence.
// Since it defaults to true, newly created SpellCheckProviders will enable
// spellchecking. After the first word is typed, the provider requests a check,
// which in turn triggers the delayed initialization sequence in SpellCheck.
// This does send a message to the browser side, which triggers the creation
// of the SpellcheckService. That does create the observer for the preference
// responsible for enabling/disabling checking, which allows subsequent changes
// to that preference to be sent to all SpellCheckProviders.
// Setting |spellcheck_enabled_| to false by default prevents that mechanism,
// and as such the SpellCheckProviders will never be notified of different
// values.
// TODO(groby): Simplify this.
SpellCheck::SpellCheck()
: auto_spell_correct_turned_on_(false),
spellcheck_enabled_(true) {
}
SpellCheck::~SpellCheck() {
}
bool SpellCheck::OnControlMessageReceived(const IPC::Message& message) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(SpellCheck, message)
IPC_MESSAGE_HANDLER(SpellCheckMsg_Init, OnInit)
IPC_MESSAGE_HANDLER(SpellCheckMsg_CustomDictionaryChanged,
OnCustomDictionaryChanged)
IPC_MESSAGE_HANDLER(SpellCheckMsg_EnableAutoSpellCorrect,
OnEnableAutoSpellCorrect)
IPC_MESSAGE_HANDLER(SpellCheckMsg_EnableSpellCheck, OnEnableSpellCheck)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
void SpellCheck::OnInit(IPC::PlatformFileForTransit bdict_file,
const std::vector<std::string>& custom_words,
const std::string& language,
bool auto_spell_correct) {
Init(IPC::PlatformFileForTransitToPlatformFile(bdict_file),
custom_words, language);
auto_spell_correct_turned_on_ = auto_spell_correct;
#if !defined(OS_MACOSX)
PostDelayedSpellCheckTask(pending_request_param_.release());
#endif
}
void SpellCheck::OnCustomDictionaryChanged(
const std::vector<std::string>& words_added,
const std::vector<std::string>& words_removed) {
custom_dictionary_.OnCustomDictionaryChanged(words_added, words_removed);
}
void SpellCheck::OnEnableAutoSpellCorrect(bool enable) {
auto_spell_correct_turned_on_ = enable;
}
void SpellCheck::OnEnableSpellCheck(bool enable) {
spellcheck_enabled_ = enable;
UpdateSpellcheckEnabled updater(enable);
content::RenderView::ForEach(&updater);
}
// TODO(groby): Make sure we always have a spelling engine, even before Init()
// is called.
void SpellCheck::Init(base::PlatformFile file,
const std::vector<std::string>& custom_words,
const std::string& language) {
spellcheck_.Init(file, language);
custom_dictionary_.Init(custom_words);
}
bool SpellCheck::SpellCheckWord(
const char16* in_word,
int in_word_len,
int tag,
int* misspelling_start,
int* misspelling_len,
std::vector<string16>* optional_suggestions) {
DCHECK(in_word_len >= 0);
DCHECK(misspelling_start && misspelling_len) << "Out vars must be given.";
// Do nothing if we need to delay initialization. (Rather than blocking,
// report the word as correctly spelled.)
if (InitializeIfNeeded())
return true;
return spellcheck_.SpellCheckWord(in_word, in_word_len,
tag,
misspelling_start, misspelling_len,
optional_suggestions);
}
bool SpellCheck::SpellCheckParagraph(
const string16& text,
WebVector<WebTextCheckingResult>* results) {
#if !defined(OS_MACOSX)
// Mac has its own spell checker, so this method will not be used.
DCHECK(results);
std::vector<WebTextCheckingResult> textcheck_results;
size_t length = text.length();
size_t offset = 0;
// Spellcheck::SpellCheckWord() automatically breaks text into words and
// checks the spellings of the extracted words. This function sets the
// position and length of the first misspelled word and returns false when
// the text includes misspelled words. Therefore, we just repeat calling the
// function until it returns true to check the whole text.
int misspelling_start = 0;
int misspelling_length = 0;
while (offset <= length) {
if (SpellCheckWord(&text[offset],
length - offset,
0,
&misspelling_start,
&misspelling_length,
NULL)) {
results->assign(textcheck_results);
return true;
}
if (!custom_dictionary_.SpellCheckWord(
&text[offset], misspelling_start, misspelling_length)) {
string16 replacement;
textcheck_results.push_back(WebTextCheckingResult(
WebKit::WebTextCheckingTypeSpelling,
misspelling_start + offset,
misspelling_length,
replacement));
}
offset += misspelling_start + misspelling_length;
}
results->assign(textcheck_results);
return false;
#else
return true;
#endif
}
string16 SpellCheck::GetAutoCorrectionWord(const string16& word, int tag) {
string16 autocorrect_word;
if (!auto_spell_correct_turned_on_)
return autocorrect_word; // Return the empty string.
int word_length = static_cast<int>(word.size());
if (word_length < 2 ||
word_length > chrome::spellcheck_common::kMaxAutoCorrectWordSize)
return autocorrect_word;
if (InitializeIfNeeded())
return autocorrect_word;
char16 misspelled_word[
chrome::spellcheck_common::kMaxAutoCorrectWordSize + 1];
const char16* word_char = word.c_str();
for (int i = 0; i <= chrome::spellcheck_common::kMaxAutoCorrectWordSize;
++i) {
if (i >= word_length)
misspelled_word[i] = 0;
else
misspelled_word[i] = word_char[i];
}
// Swap adjacent characters and spellcheck.
int misspelling_start, misspelling_len;
for (int i = 0; i < word_length - 1; i++) {
// Swap.
std::swap(misspelled_word[i], misspelled_word[i + 1]);
// Check spelling.
misspelling_start = misspelling_len = 0;
SpellCheckWord(misspelled_word, word_length, tag, &misspelling_start,
&misspelling_len, NULL);
// Make decision: if only one swap produced a valid word, then we want to
// return it. If we found two or more, we don't do autocorrection.
if (misspelling_len == 0) {
if (autocorrect_word.empty()) {
autocorrect_word.assign(misspelled_word);
} else {
autocorrect_word.clear();
break;
}
}
// Restore the swapped characters.
std::swap(misspelled_word[i], misspelled_word[i + 1]);
}
return autocorrect_word;
}
#if !defined(OS_MACOSX) // OSX uses its own spell checker
void SpellCheck::RequestTextChecking(
const string16& text,
int offset,
WebKit::WebTextCheckingCompletion* completion) {
// Clean up the previous request before starting a new request.
if (pending_request_param_.get())
pending_request_param_->completion()->didCancelCheckingText();
pending_request_param_.reset(new SpellcheckRequest(
text, offset, completion));
// We will check this text after we finish loading the hunspell dictionary.
if (InitializeIfNeeded())
return;
PostDelayedSpellCheckTask(pending_request_param_.release());
}
#endif
bool SpellCheck::InitializeIfNeeded() {
return spellcheck_.InitializeIfNeeded();
}
#if !defined(OS_MACOSX) // OSX doesn't have |pending_request_param_|
void SpellCheck::PostDelayedSpellCheckTask(SpellcheckRequest* request) {
if (!request)
return;
base::MessageLoopProxy::current()->PostTask(FROM_HERE,
base::Bind(&SpellCheck::PerformSpellCheck,
AsWeakPtr(),
base::Owned(request)));
}
#endif
#if !defined(OS_MACOSX) // Mac uses its native engine instead.
void SpellCheck::PerformSpellCheck(SpellcheckRequest* param) {
DCHECK(param);
if (!spellcheck_.IsEnabled()) {
param->completion()->didCancelCheckingText();
} else {
WebVector<WebKit::WebTextCheckingResult> results;
SpellCheckParagraph(param->text(), &results);
param->completion()->didFinishCheckingText(results);
}
}
#endif
void SpellCheck::CreateTextCheckingResults(
ResultFilter filter,
int line_offset,
const string16& line_text,
const std::vector<SpellCheckResult>& spellcheck_results,
WebVector<WebTextCheckingResult>* textcheck_results) {
// Double-check misspelled words with our spellchecker and attach grammar
// markers to them if our spellchecker tells they are correct words, i.e. they
// are probably contextually-misspelled words.
const char16* text = line_text.c_str();
std::vector<WebTextCheckingResult> list;
for (size_t i = 0; i < spellcheck_results.size(); ++i) {
WebTextCheckingType type =
static_cast<WebTextCheckingType>(spellcheck_results[i].type);
int word_location = spellcheck_results[i].location;
int word_length = spellcheck_results[i].length;
int misspelling_start = 0;
int misspelling_length = 0;
if (type == WebKit::WebTextCheckingTypeSpelling &&
filter == USE_NATIVE_CHECKER) {
if (SpellCheckWord(text + word_location, word_length, 0,
&misspelling_start, &misspelling_length, NULL)) {
type = WebKit::WebTextCheckingTypeGrammar;
}
}
if (!custom_dictionary_.SpellCheckWord(text, word_location, word_length)) {
list.push_back(WebTextCheckingResult(
type,
word_location + line_offset,
word_length,
spellcheck_results[i].replacement));
}
}
textcheck_results->assign(list);
}
| 34.767241 | 87 | 0.716175 | [
"object",
"vector"
] |
0fadf5a26724ace632a0e10e8a67caf756d740df | 6,550 | cpp | C++ | test/lcp-client-lib/tests/DateTimeTest.cpp | isabelleknott/readium-lcp-client | 764b28f5f4d879f771be7e727cf4a79ac0d62d9f | [
"BSD-3-Clause"
] | 11 | 2017-02-24T10:58:19.000Z | 2021-12-28T11:24:45.000Z | test/lcp-client-lib/tests/DateTimeTest.cpp | isabelleknott/readium-lcp-client | 764b28f5f4d879f771be7e727cf4a79ac0d62d9f | [
"BSD-3-Clause"
] | 19 | 2017-03-10T09:16:04.000Z | 2020-01-31T09:20:59.000Z | test/lcp-client-lib/tests/DateTimeTest.cpp | isabelleknott/readium-lcp-client | 764b28f5f4d879f771be7e727cf4a79ac0d62d9f | [
"BSD-3-Clause"
] | 10 | 2017-06-14T08:06:42.000Z | 2022-01-25T16:49:43.000Z | // Copyright (c) 2016 Mantano
// Licensed to the Readium Foundation under one or more contributor license agreements.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
// 3. Neither the name of the organization nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <gtest/gtest.h>
#include "DateTime.h"
namespace lcptest
{
TEST(DateTimeTest, JointUtcToNormalIso)
{
std::string joint = "20151111T222137Z";
lcp::DateTime object(joint);
ASSERT_EQ("2015-11-11T22:21:37Z", object.ToString());
}
TEST(DateTimeTest, JointTimeZoneToNormalIso)
{
std::string joint = "20151111T222137+0100";
lcp::DateTime object(joint);
ASSERT_EQ("2015-11-11T22:21:37+01:00", object.ToString());
}
TEST(DateTimeTest, JointIso_Utc_WrongFormatThrow)
{
std::string joint1 = "20151111T222137Z-";
ASSERT_THROW(lcp::DateTime object(joint1), std::invalid_argument);
std::string joint2 = "20151111T22A137Z";
ASSERT_THROW(lcp::DateTime object(joint2), std::invalid_argument);
std::string joint3 = "20151111222137Z";
ASSERT_THROW(lcp::DateTime object(joint3), std::invalid_argument);
}
TEST(DateTimeTest, JointIsoFormat_TimeZone_WrongFormatThrow)
{
std::string joint1 = "20151111T222137+0100-";
ASSERT_THROW(lcp::DateTime object(joint1), std::invalid_argument);
std::string joint2 = "201y1111T222137+0100";
ASSERT_THROW(lcp::DateTime object(joint2), std::invalid_argument);
std::string joint3 = "20151111T2A2137+0100";
ASSERT_THROW(lcp::DateTime object(joint3), std::invalid_argument);
}
TEST(DateTimeTest, NormalIso_Utc_WrongFormatThrow)
{
std::string joint1 = "2015-11-11T22:21:37X";
ASSERT_THROW(lcp::DateTime object(joint1), std::invalid_argument);
std::string joint2 = "2015-11-11T22 21 37Z";
ASSERT_THROW(lcp::DateTime object(joint2), std::invalid_argument);
std::string joint3 = "2015-11-11T22-21-37Z";
ASSERT_THROW(lcp::DateTime object(joint3), std::invalid_argument);
std::string joint4 = "2015-AA-11T22:21:37Z";
ASSERT_THROW(lcp::DateTime object(joint4), std::invalid_argument);
}
TEST(DateTimeTest, NormalIsoFormat_TimeZone_WrongFormatThrow)
{
std::string joint1 = "2015-11-11T22:21:37+";
ASSERT_THROW(lcp::DateTime object(joint1), std::invalid_argument);
std::string joint2 = "2015-11-11T22 21 37Z+01:00";
ASSERT_THROW(lcp::DateTime object(joint2), std::invalid_argument);
std::string joint3 = "2015-11-11T22-21-37Z+01:00";
ASSERT_THROW(lcp::DateTime object(joint3), std::invalid_argument);
std::string joint4 = "2015-AA-11T22:21:37Z+01:00";
ASSERT_THROW(lcp::DateTime object(joint4), std::invalid_argument);
}
TEST(DateTimeTest, NormalIsoTimeToTime_t_Utc)
{
std::string timeStr = "2015-11-11T22:21:37Z";
lcp::DateTime object(timeStr);
ASSERT_EQ(object.ToTime(), 1447273297);
}
TEST(DateTimeTest, NormalIsoTimeToTime_t_TimeZoneZero)
{
std::string timeStr = "2015-11-11T22:21:37+00:00";
lcp::DateTime object(timeStr);
ASSERT_EQ(object.ToTime(), 1447273297);
}
TEST(DateTimeTest, NormalIsoTimeToTime_t_TimeZonePlusTwo)
{
std::string timeStr = "2015-11-11T22:21:37+02:00";
lcp::DateTime object(timeStr);
ASSERT_EQ(object.ToTime(), 1447280497);
}
TEST(DateTimeTest, NormalIsoTimeToTime_t_TimeZoneMinusTwo)
{
std::string timeStr = "2015-11-11T22:21:37-02:00";
lcp::DateTime object(timeStr);
ASSERT_EQ(object.ToTime(), 1447266097);
}
TEST(DateTimeTest, CompareSmaller)
{
lcp::DateTime left("2015-11-11T22:21:37Z");
lcp::DateTime right("2015-11-11T22:21:37+02:00");
ASSERT_TRUE(left < right);
}
TEST(DateTimeTest, CompareBigger)
{
lcp::DateTime left("2015-11-11T22:21:37+02:00");
lcp::DateTime right("2015-11-11T22:21:37Z");
ASSERT_TRUE(left > right);
}
TEST(DateTimeTest, Equality)
{
lcp::DateTime left("2015-11-11T22:21:37+00:00");
lcp::DateTime right("2015-11-11T22:21:37Z");
ASSERT_TRUE(left == right);
}
TEST(DateTimeTest, NotEqual)
{
lcp::DateTime left("2015-11-11T22:21:37+05:00");
lcp::DateTime right("2015-11-11T22:21:37Z");
ASSERT_TRUE(left != right);
}
TEST(DateTimeTest, DateWithFractionalSecondsPart)
{
std::string timeStr = "2015-11-11T22:21:37.984546-02:00";
lcp::DateTime object(timeStr);
ASSERT_EQ(object.ToTime(), 1447266097);
ASSERT_STREQ("2015-11-11T22:21:37.984546-02:00", object.ToString().c_str());
}
TEST(DateTimeTest, 2038YearBugIn32BitSystemsTest)
{
std::string timeStr = "2045-11-11T22:21:37-02:00";
lcp::DateTime object(timeStr);
ASSERT_EQ(object.ToTime(), 2394037297);
ASSERT_STREQ("2045-11-11T22:21:37-02:00", object.ToString().c_str());
}
TEST(DateTimeTest, DateTimeNow)
{
lcp::DateTime now = lcp::DateTime::Now();
}
} | 37.00565 | 87 | 0.676031 | [
"object"
] |
0faea998bf93a0c519df8b5aa5fde816ab0fce40 | 18,554 | cpp | C++ | src/Adanaxis/AdanaxisGame.cpp | mushware/adanaxis-core-app | 679ac3e8a122e059bb208e84c73efc19753e87dd | [
"MIT"
] | 9 | 2020-11-02T17:20:40.000Z | 2021-12-25T15:35:36.000Z | src/Adanaxis/AdanaxisGame.cpp | mushware/adanaxis-core-app | 679ac3e8a122e059bb208e84c73efc19753e87dd | [
"MIT"
] | 2 | 2020-06-27T23:14:13.000Z | 2020-11-02T17:28:32.000Z | src/Adanaxis/AdanaxisGame.cpp | mushware/adanaxis-core-app | 679ac3e8a122e059bb208e84c73efc19753e87dd | [
"MIT"
] | 1 | 2021-05-12T23:05:42.000Z | 2021-05-12T23:05:42.000Z | //%Header {
/*****************************************************************************
*
* File: src/Adanaxis/AdanaxisGame.cpp
*
* Copyright: Andy Southgate 2002-2007, 2020
*
* 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.
*
****************************************************************************/
//%Header } M6cHGgl/7upPIjU0r5Rn/Q
/*
* $Id: AdanaxisGame.cpp,v 1.72 2007/06/13 14:08:47 southa Exp $
* $Log: AdanaxisGame.cpp,v $
* Revision 1.72 2007/06/13 14:08:47 southa
* Level 29
*
* Revision 1.71 2007/06/11 20:06:14 southa
* Compatibility fixes and level 27
*
* Revision 1.70 2007/06/07 13:23:02 southa
* Level 24
*
* Revision 1.69 2007/06/02 15:56:58 southa
* Shader fix and prerelease work
*
* Revision 1.68 2007/05/10 14:06:26 southa
* Level 16 and retina spin
*
* Revision 1.67 2007/04/21 09:41:06 southa
* Level work
*
* Revision 1.66 2007/04/18 09:22:00 southa
* Header and level fixes
*
* Revision 1.65 2007/04/16 18:50:59 southa
* Voice work
*
* Revision 1.64 2007/04/16 08:41:07 southa
* Level and header mods
*
* Revision 1.63 2007/03/20 17:31:23 southa
* Difficulty and GL options
*
* Revision 1.62 2007/03/09 19:50:11 southa
* Resident textures
*
* Revision 1.61 2007/03/07 16:59:43 southa
* Khazi spawning and level ends
*
* Revision 1.60 2007/02/08 17:55:14 southa
* Common routines in space generation
*
* Revision 1.59 2006/12/18 15:39:35 southa
* Palette changes
*
* Revision 1.58 2006/12/14 15:59:23 southa
* Fire and cutscene fixes
*
* Revision 1.57 2006/12/14 00:33:44 southa
* Control fix and audio pacing
*
* Revision 1.56 2006/11/25 21:26:31 southa
* Display mode definitions
*
* Revision 1.55 2006/11/09 23:53:59 southa
* Explosion and texture loading
*
* Revision 1.54 2006/11/03 18:46:33 southa
* Damage effectors
*
* Revision 1.53 2006/10/17 15:28:01 southa
* Player collisions
*
* Revision 1.52 2006/09/07 10:02:36 southa
* Shader interface
*
* Revision 1.51 2006/08/01 23:21:52 southa
* Rendering demo content
*
* Revision 1.50 2006/08/01 17:21:23 southa
* River demo
*
* Revision 1.49 2006/07/31 11:01:36 southa
* Music and dialogues
*
* Revision 1.48 2006/07/28 16:52:18 southa
* Options work
*
* Revision 1.47 2006/07/28 11:14:27 southa
* Records for multiple spaces
*
* Revision 1.46 2006/07/27 13:51:33 southa
* Menu and control fixes
*
* Revision 1.45 2006/07/26 16:37:20 southa
* Options menu
*
* Revision 1.44 2006/07/20 12:22:20 southa
* Precache display
*
* Revision 1.43 2006/07/19 14:34:50 southa
* Flare effects
*
* Revision 1.42 2006/07/18 16:58:36 southa
* Texture fixes
*
* Revision 1.41 2006/07/12 11:22:40 southa
* Advanced control menu
*
* Revision 1.40 2006/07/11 19:49:03 southa
* Control menu
*
* Revision 1.39 2006/07/07 18:13:57 southa
* Menu start and stop
*
* Revision 1.38 2006/07/04 16:55:26 southa
* Ruby key handling
*
* Revision 1.37 2006/07/02 21:08:53 southa
* Ruby menu work
*
* Revision 1.36 2006/06/30 17:26:09 southa
* Render prelude
*
* Revision 1.35 2006/06/30 15:05:31 southa
* Texture and buffer purge
*
* Revision 1.34 2006/06/21 16:52:28 southa
* Deco objects
*
* Revision 1.33 2006/06/21 12:17:54 southa
* Ruby object generation
*
* Revision 1.32 2006/06/20 19:06:51 southa
* Object creation
*
* Revision 1.31 2006/06/14 18:45:45 southa
* Ruby mesh generation
*
* Revision 1.30 2006/06/12 16:01:21 southa
* Ruby mesh generation
*
* Revision 1.29 2006/06/07 12:15:18 southa
* Grid and test textures
*
* Revision 1.28 2006/06/06 17:58:31 southa
* Ruby texture definition
*
* Revision 1.27 2006/06/05 16:54:43 southa
* Ruby textures
*
* Revision 1.26 2006/05/01 17:39:00 southa
* Texture generation
*
* Revision 1.25 2006/04/20 00:22:45 southa
* Added ruby executive
*
* Revision 1.24 2006/04/19 20:14:10 southa
* Added Ruby framework
*
* Revision 1.23 2005/09/05 12:54:29 southa
* Solid rendering work
*
* Revision 1.22 2005/08/05 10:33:33 southa
* win32 build fixes
*
* Revision 1.21 2005/08/02 14:37:44 southa
* Adanaxis control demo work
*
* Revision 1.20 2005/08/02 11:11:47 southa
* Adanaxis control demo work
*
* Revision 1.19 2005/08/01 20:24:15 southa
* Backdrop and build fixes
*
* Revision 1.18 2005/07/18 13:13:35 southa
* Extrude to point and projectile mesh
*
* Revision 1.17 2005/07/11 16:37:46 southa
* Uplink control work
*
* Revision 1.16 2005/07/07 16:54:17 southa
* Control tweaks
*
* Revision 1.15 2005/07/06 19:08:26 southa
* Adanaxis control work
*
* Revision 1.14 2005/07/04 15:59:00 southa
* Adanaxis work
*
* Revision 1.13 2005/07/02 00:42:36 southa
* Conditioning tweaks
*
* Revision 1.12 2005/07/01 16:42:54 southa
* Render work
*
* Revision 1.11 2005/06/30 16:29:24 southa
* Adanaxis work
*
* Revision 1.10 2005/06/29 11:11:15 southa
* Camera and rendering work
*
* Revision 1.9 2005/06/23 13:56:56 southa
* MushGame link work
*
* Revision 1.8 2005/06/23 11:58:27 southa
* MushGame link work
*
* Revision 1.7 2005/06/21 15:57:46 southa
* MushGame work
*
* Revision 1.6 2005/06/21 13:10:50 southa
* MushGame work
*
* Revision 1.5 2005/06/20 14:30:33 southa
* Adanaxis work
*
* Revision 1.4 2005/06/16 17:25:37 southa
* Client/server work
*
* Revision 1.3 2005/06/14 20:39:40 southa
* Adanaxis work
*
* Revision 1.2 2005/06/14 13:25:33 southa
* Adanaxis work
*
* Revision 1.1 2005/06/13 17:34:54 southa
* Adanaxis creation
*
*/
#include "AdanaxisGame.h"
#include "AdanaxisAppHandler.h"
#include "AdanaxisClient.h"
#include "AdanaxisIntern.h"
#include "AdanaxisMeshLibrary.h"
#include "AdanaxisRecords.h"
#include "AdanaxisRender.h"
#include "AdanaxisRuby.h"
#include "AdanaxisSaveData.h"
#include "AdanaxisServer.h"
#include "AdanaxisUtil.h"
#include "API/mushPlatform.h"
#include "API/mushMedia.h"
#include "API/mushMushGL.h"
#include "API/mushMushGame.h"
#include "API/mushMushMesh.h"
#include "API/mushMushMeshLibrary.h"
#include "API/mushMushRuby.h"
using namespace Mushware;
using namespace std;
AdanaxisGame::AdanaxisGame(const std::string& inName) :
m_inited(false),
m_name(inName),
m_startDialogueShown(false)
{
}
AdanaxisGame::~AdanaxisGame()
{}
void
AdanaxisGame::Process(MushGameAppHandler& inAppHandler)
{
#ifdef MUSHCORE_DEBUG
if (inAppHandler.LatchedKeyStateTake('.'))
{
MushGLUtil::BufferPurge();
}
if (inAppHandler.LatchedKeyStateTake('/'))
{
MushGLUtil::TexturePurge();
}
if (inAppHandler.LatchedKeyStateTake(','))
{
MushGLUtil::Purge();
MushGLV::Sgl().Purge();
MushGLV::Sgl().Acquaint();
}
#endif
VolatileData().ShowFpsSet(m_config.ShowFps());
Logic().PerFrameProcessing();
Logic().MainSequence();
// Start the clock once we're going
if (!Logic().IsPrecacheMode() && !SaveData().ClockStarted())
{
if (Logic().IsGameMode())
{
// TimingSequence will have run at least once, so GameMsec is valid
Logic().StartTimeSet(Logic().GameMsec());
SaveData().ClockStartedSet(true);
}
else if (Logic().IsMenuMode() && !m_startDialogueShown)
{
m_startDialogueShown = true;
MushGameDialogueUtils::NamedDialoguesAdd(SaveData().DialoguesWRef(), "^menuonce");
}
}
GLUtils::PostRedisplay();
}
const GLModeDef&
AdanaxisGame::DisplayModeDef(void) const
{
return m_config.ModeDef();
}
void
AdanaxisGame::PreviousModeDef(void)
{
m_config.ModeDefSet(PlatformVideoUtils::Sgl().PreviousModeDef(m_config.ModeDef()));
}
void
AdanaxisGame::NextModeDef(void)
{
m_config.ModeDefSet(PlatformVideoUtils::Sgl().NextModeDef(m_config.ModeDef()));
}
void
AdanaxisGame::BrightnessSet(Mushware::tVal inValue)
{
VolatileData().BrightnessSet(inValue);
}
void
AdanaxisGame::Display(MushGameAppHandler& inAppHandler)
{
}
void
AdanaxisGame::ScriptFunction(const std::string& inName, MushGameAppHandler& inAppHandler) const
{}
void
AdanaxisGame::LocalGameCreate(MushGameAppHandler& inAppHandler)
{
MushGameUtil::LocalGameCreate("adanaxis", "Adanaxis");
ClientRefWRef().NameSet(m_name);
ServerRefWRef().NameSet(m_name);
SaveDataRefWRef().NameSet(m_name);
VolatileDataRefWRef().NameSet(m_name);
LogicRefWRef().NameSet(m_name);
AdanaxisRuby::LogicNameSet(m_name);
MushGameUtil::LocalGameJobsCreate(Logic());
}
void
AdanaxisGame::Init(MushGameAppHandler& inAppHandler)
{
MushMeshLibraryBase::SingletonMutate(new AdanaxisMeshLibrary);
MushMesh4Maker::SingletonMutate(new MushMeshLibraryMaker);
std::srand(time(NULL));
LocalGameCreate(inAppHandler);
MushGameConfigUtils::ConfigAcquire(&m_config);
AdanaxisRecords::Sgl().Load();
if (AdanaxisUtil::AppHandler().FirstGame() && m_config.SafeMode())
{
m_config.ModeDefSet(GLModeDef(640, 480, false));
m_config.TextureDetailSet(0);
m_config.UseGLCompressionSet(0);
m_config.UseGLShaderSet(0);
MushGameDialogueUtils::NamedDialoguesAdd(SaveData().DialoguesWRef(), "^safemode");
}
Logic().InitialDataCreate();
UpdateFromConfig();
SaveData().GameDifficultySet(AdanaxisUtil::Config().ConfigDifficulty());
try
{
VolatileData().RubyGameSet(MushRubyExec::Sgl().Eval("$currentGame"));
VolatileData().RubyGame().Call(AdanaxisIntern::Sgl().mLoad());
}
catch (MushRubyFail& e)
{
MushcoreLog::Sgl().ErrorLog() << "Game failed to initialise: " << e.what() << endl;
#ifdef MUSHCORE_DEBUG
throw;
#else
MushRubyExec::Sgl().Call(VolatileData().RubyGame(), AdanaxisIntern::Sgl().mSpaceNameSet(), MushRubyValue("menu1"));
VolatileData().RubyGame().Call(AdanaxisIntern::Sgl().mLoad());
MushGameDialogueUtils::NamedDialoguesAdd(SaveData().DialoguesWRef(), "^levelfailed");
#endif
}
VolatileData().RubyLogicSet(MushRubyExec::Sgl().Eval("$currentLogic"));
VolatileData().RubySpaceSet(MushRubyExec::Sgl().Call("$currentGame.mSpace"));
MushRubyExec::Sgl().Call(VolatileData().RubySpace(), "mInitialPiecesCreate");
VolatileData().IsMenuBackdropSet(MushRubyExec::Sgl().Call(VolatileData().RubySpace(), "mIsMenuBackdrop").Bool());
SaveData().SpaceNameSet(MushRubyExec::Sgl().Call("$currentGame.mSpaceName").String());
SaveData().PrimaryTypeSet(MushRubyExec::Sgl().Call(VolatileData().RubySpace(), "mPrimary").U32());
SaveData().RetinaSpinSet(MushRubyExec::Sgl().Call(VolatileData().RubySpace(), "mRetinaSpin").Val());
SaveData().PermanentSpinSet(MushRubyExec::Sgl().Call(VolatileData().RubySpace(), "mPermanentSpin").Bool());
SaveData().PermanentThrustSet(MushRubyExec::Sgl().Call(VolatileData().RubySpace(), "mPermanentThrust").Bool());
SaveData().SpeedAugmentationSet(MushRubyExec::Sgl().Call(VolatileData().RubySpace(), "mSpeedAugmentation").Bool());
AdanaxisUtil::MissingSkinsCreate(Logic());
//AdanaxisUtil::MeshPurge(Logic());
MediaAudio::Sgl().AudioVolumeSet(m_config.AudioVolume() / 100.0);
MediaAudio::Sgl().MusicVolumeSet(m_config.MusicVolume() / 100.0);
MediaAudio::Sgl().VoiceVolumeSet(m_config.VoiceVolume() / 100.0);
MediaAudio::Sgl().MusicFadeOut(1000); // Level starts music once it loads
Logic().RecordTimeSet(AdanaxisRecords::Sgl().RecordTime(SaveData().GameDifficulty(), SaveData().SpaceName()));
Logic().MenuModeEnter();
Logic().StartTimeSet(0);
Logic().EndTimeSet(0);
inAppHandler.MouseSensitivitySet(m_config.MouseSensitivity());
VolatileData().BrightnessSet(m_config.Brightness());
VolatileData().ShowFpsSet(m_config.ShowFps());
VolatileData().ScannerOnSet(false);
m_inited = true;
SaveData().ClockStartedSet(false);
AdanaxisUtil::AppHandler().FirstGameSet(false);
}
void
AdanaxisGame::ControlsToDefaultSet(MushGameAppHandler& inHandler)
{
MushGameBase::ControlsToDefaultSet(inHandler);
m_config.AxesToDefaultSet();
m_config.KeysToDefaultSet();
UpdateFromConfig();
}
void
AdanaxisGame::UpdateFromConfig(void)
{
AdanaxisAppHandler& appHandler = AdanaxisUtil::AppHandler();
for (U32 i=0; i < m_config.AxisDefs().size(); ++i)
{
appHandler.AxisDefSet(m_config.AxisDefs(i), i);
appHandler.AxisDefWRef(i).Reset();
}
for (U32 i=0; i < m_config.KeyDefs().size(); ++i)
{
appHandler.KeyDefSet(m_config.KeyDefs(i), i);
appHandler.KeyDefWRef(i).Reset();
}
}
void
AdanaxisGame::UpdateToConfig(void)
{
AdanaxisAppHandler& appHandler = AdanaxisUtil::AppHandler();
for (U32 i=0; i < m_config.AxisDefs().size(); ++i)
{
m_config.AxisDefSet(appHandler.AxisDef(i), i);
m_config.AxisDefWRef(i).Reset();
}
for (U32 i=0; i < m_config.KeyDefs().size(); ++i)
{
m_config.KeyDefSet(appHandler.KeyDef(i), i);
m_config.KeyDefWRef(i).Reset();
}
}
void
AdanaxisGame::ConfigSave(void)
{
const MushcoreScalar *pScalar;
if (MushcoreEnv::Sgl().VariableGetIfExists(pScalar, "CONFIG_FILENAME"))
{
UpdateToConfig();
m_config.AutoFileSave(pScalar->StringGet());
}
}
void
AdanaxisGame::SwapIn(MushGameAppHandler& inAppHandler)
{
MushGameBase::SwapIn(inAppHandler);
AdanaxisAppHandler& appHandler = AdanaxisUtil::AppHandler();
appHandler.LastAxesValidSet(false);
if (!m_inited)
{
Init(inAppHandler);
}
try
{
const GLModeDef& modeDefRef = m_config.ModeDef();
if (!inAppHandler.ScreenEntered() || modeDefRef != inAppHandler.CurrentModeDefGet())
{
if (MushGLV::Sgl().ContextValid())
{
// Purge all textures
MushGLUtil::Purge();
MushGLV::Sgl().Purge();
}
inAppHandler.EnterScreen(modeDefRef);
MushGLV::Sgl().Acquaint();
if (MushcoreEnv::Sgl().VariableExists("MUSHGL_DUMP_MUSHGLV"))
{
MushcoreLog::Sgl().ErrorLog() << MushGLV::Sgl() << endl;
}
if (MushGLV::Sgl().HasS3TC())
{
m_config.UseGLCompressionSet(m_config.UseGLCompression() % 2);
}
else
{
m_config.UseGLCompressionSet(2);
}
MushGLV::Sgl().UseS3TCSet(m_config.UseGLCompression() == 1);
if (MushGLV::Sgl().HasShader())
{
m_config.UseGLShaderSet(m_config.UseGLShader() % 2);
try
{
MushGLUtil::ShaderTest();
}
catch (std::exception &e)
{
MushcoreLog::Sgl().WarningLog() << "GL Shader test failed - disabling : " << e.what() << endl;
m_config.UseGLShaderSet(2);
}
}
else
{
m_config.UseGLShaderSet(2);
}
MushGLV::Sgl().UseShaderSet(m_config.UseGLShader() == 1);
}
else
{
// Screen alread valid - just purge the level-specific textures
MushGLV::Sgl().Acquaint();
MushGLUtil::PurgeNonResident();
}
}
catch (...)
{
m_config.ModeDefSet(GLModeDef(640, 480, false));
ConfigSave();
throw;
}
GLUtils::CheckGLError();
Logic().PrecacheModeEnter();
dynamic_cast<AdanaxisRender&>(SaveData().RenderRef().WRef()).RenderPreludeSet();
}
void
AdanaxisGame::SwapOut(MushGameAppHandler& inAppHandler)
{
MushGameBase::SwapOut(inAppHandler);
ConfigSave();
}
//%outOfLineFunctions {
const char *AdanaxisGame::AutoName(void) const
{
return "AdanaxisGame";
}
MushcoreVirtualObject *AdanaxisGame::AutoClone(void) const
{
return new AdanaxisGame(*this);
}
MushcoreVirtualObject *AdanaxisGame::AutoCreate(void) const
{
return new AdanaxisGame;
}
MushcoreVirtualObject *AdanaxisGame::AutoVirtualFactory(void)
{
return new AdanaxisGame;
}
namespace
{
void AutoInstall(void)
{
MushcoreFactory::Sgl().FactoryAdd("AdanaxisGame", AdanaxisGame::AutoVirtualFactory);
}
MushcoreInstaller AutoInstaller(AutoInstall);
} // end anonymous namespace
void
AdanaxisGame::AutoPrint(std::ostream& ioOut) const
{
ioOut << "[";
ioOut << "name=" << m_name << ", ";
ioOut << "config=" << m_config << ", ";
ioOut << "startDialogueShown=" << m_startDialogueShown;
ioOut << "]";
}
bool
AdanaxisGame::AutoXMLDataProcess(MushcoreXMLIStream& ioIn, const std::string& inTagStr)
{
if (inTagStr == "obj")
{
AutoInputPrologue(ioIn);
ioIn >> *this;
AutoInputEpilogue(ioIn);
}
else if (inTagStr == "name")
{
ioIn >> m_name;
}
else if (inTagStr == "config")
{
ioIn >> m_config;
}
else if (inTagStr == "startDialogueShown")
{
ioIn >> m_startDialogueShown;
}
else
{
return false;
}
return true;
}
void
AdanaxisGame::AutoXMLPrint(MushcoreXMLOStream& ioOut) const
{
ioOut.TagSet("name");
ioOut << m_name;
ioOut.TagSet("config");
ioOut << m_config;
ioOut.TagSet("startDialogueShown");
ioOut << m_startDialogueShown;
}
//%outOfLineFunctions } 7rvmWEETrQ1yRz+b8SzWWA
| 27.733931 | 123 | 0.649887 | [
"mesh",
"render",
"object",
"solid"
] |
0fb43d1b22debfdcc56b759220839f5f1d1eede8 | 32,058 | hpp | C++ | SFML-UILoader/TGUI-0.8/include/TGUI/Container.hpp | ChrisAcornley/SFML-UILoader | ac84cc5502e1d5d7a8d680e0ac342dd1e97f6587 | [
"MIT"
] | null | null | null | SFML-UILoader/TGUI-0.8/include/TGUI/Container.hpp | ChrisAcornley/SFML-UILoader | ac84cc5502e1d5d7a8d680e0ac342dd1e97f6587 | [
"MIT"
] | null | null | null | SFML-UILoader/TGUI-0.8/include/TGUI/Container.hpp | ChrisAcornley/SFML-UILoader | ac84cc5502e1d5d7a8d680e0ac342dd1e97f6587 | [
"MIT"
] | null | null | null | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// TGUI - Texus' Graphical User Interface
// Copyright (C) 2012-2019 Bruno Van de Velde (vdv_b@tgui.eu)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#ifndef TGUI_CONTAINER_HPP
#define TGUI_CONTAINER_HPP
#include <list>
#include <TGUI/Widget.hpp>
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
namespace tgui
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Container widget
///
/// Parent class for widgets that contain child widgets.
///
/// Signals:
/// - Inherited signals from Widget
///
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class TGUI_API Container : public Widget
{
public:
typedef std::shared_ptr<Container> Ptr; ///< Shared widget pointer
typedef std::shared_ptr<const Container> ConstPtr; ///< Shared constant widget pointer
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Default constructor
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Container();
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Copy constructor
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Container(const Container& copy);
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Move constructor
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Container(Container&& copy);
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Destructor
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
~Container();
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Overload of copy assignment operator
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Container& operator= (const Container& right);
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Overload of move assignment operator
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Container& operator= (Container&& right);
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Changes the size of the container
/// @param size The new size of the container
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void setSize(const Layout2d& size) override;
using Widget::setSize;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Returns a list of all the widgets in this container
///
/// @return Vector of all widget pointers
///
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
const std::vector<Widget::Ptr>& getWidgets() const
{
return m_widgets;
}
#ifndef TGUI_REMOVE_DEPRECATED_CODE
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Returns a list of the names of all the widgets in this container
///
/// @return Vector of all widget names
///
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TGUI_DEPRECATED("Use getWidgets() and Widget::getWidgetName instead") const std::vector<sf::String> getWidgetNames() const
{
std::vector<sf::String> m_widgetNames;
m_widgetNames.reserve(m_widgets.size());
for (std::size_t i = 0; i < m_widgets.size(); ++i)
m_widgetNames.emplace_back(m_widgets[i]->getWidgetName());
return m_widgetNames;
}
#endif
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Adds a widget to the container
///
/// @param widgetPtr Pointer to the widget you would like to add
/// @param widgetName You can give the widget a unique name to retrieve it from the container later
///
/// @warning The widget name should not contain whitespace
///
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
virtual void add(const Widget::Ptr& widgetPtr, const sf::String& widgetName = "");
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Returns a pointer to a widget that was added earlier
///
/// @param widgetName The name that was given to the widget when it was added to the container
///
/// The container will first search for widgets that are direct children of it, but when none of the child widgets match
/// the given name, a recursive search will be performed.
///
/// @return Pointer to the earlier added widget
///
/// @warning This function will return nullptr when an unknown widget name was passed
///
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Widget::Ptr get(const sf::String& widgetName) const;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Returns a pointer to a widget that was added earlier
///
/// @param widgetName The name that was given to the widget when it was added to the container
///
/// @return Pointer to the earlier added widget.
/// The pointer will already be casted to the desired type
///
/// The container will first search for widgets that are direct children of it, but when none of the child widgets match
/// the given name, a recursive search will be performed.
///
/// @warning This function will return nullptr when an unknown widget name was passed
///
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <class T>
typename T::Ptr get(const sf::String& widgetName) const
{
return std::dynamic_pointer_cast<T>(get(widgetName));
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Removes a single widget that was added to the container
///
/// @param widget Pointer to the widget to remove
///
/// @return True when widget is removed, false when widget was not found
///
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
virtual bool remove(const Widget::Ptr& widget);
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Removes all widgets that were added to the container
///
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
virtual void removeAllWidgets();
#ifndef TGUI_REMOVE_DEPRECATED_CODE
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Changes the name of a widget
///
/// @param widget Widget of which the name should be changed
/// @param name New name for the widget
///
/// @return True when the name was changed, false when the widget wasn't part of this container.
///
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TGUI_DEPRECATED("Use Widget::setWidgetName instead") bool setWidgetName(const Widget::Ptr& widget, const std::string& name);
using Widget::setWidgetName;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Returns the name of a widget
///
/// @param widget Widget of which the name should be retrieved
///
/// @return Name of the widget or an empty string when the widget wasn't part of this container or wasn't given a name
///
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TGUI_DEPRECATED("Use Widget::getWidgetName instead") std::string getWidgetName(const Widget::ConstPtr& widget) const;
#endif
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Unchecks all the radio buttons
///
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void uncheckRadioButtons();
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Returns the space available for widgets inside the container
/// @return Size of the container
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
virtual Vector2f getInnerSize() const;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Returns the distance between the position of the container and a widget that would be drawn inside
/// this container on relative position (0,0)
///
/// @return Offset of the widgets in the container
///
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
virtual Vector2f getChildWidgetsOffset() const
{
return Vector2f{0, 0};
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Changes the character size of all existing and future child widgets
///
/// @param size The new text size
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void setTextSize(unsigned int size) override;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Loads the child widgets from a text file
///
/// @param filename Filename of the widget file
/// @param replaceExisting Remove existing widgets first if there are any
///
/// @throw Exception when file could not be opened or parsing failed
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void loadWidgetsFromFile(const std::string& filename, bool replaceExisting = true);
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Saves the child widgets to a text file
/// @param filename Filename of the widget file
/// @throw Exception when file could not be opened for writing
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void saveWidgetsToFile(const std::string& filename);
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Loads the child widgets from a string stream
///
/// @param stream stringstream that contains the widget file
/// @param replaceExisting Remove existing widgets first if there are any
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void loadWidgetsFromStream(std::stringstream& stream, bool replaceExisting = true);
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Loads the child widgets from a string stream
///
/// @param stream stringstream that contains the widget file
/// @param replaceExisting Remove existing widgets first if there are any
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void loadWidgetsFromStream(std::stringstream&& stream, bool replaceExisting = true);
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Saves the child widgets to a text file
///
/// @param stream stringstream to which the widget file will be added
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void saveWidgetsToStream(std::stringstream& stream) const;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Places a widget before all other widgets
///
/// @param widget The widget that should be moved to the front
///
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void moveWidgetToFront(const Widget::Ptr& widget);
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Places a widget behind all other widgets
///
/// @param widget The widget that should be moved to the back
///
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void moveWidgetToBack(const Widget::Ptr& widget);
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Focuses the next widget in this container
/// @return Whether a new widget was focused
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool focusNextWidget();
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Focuses the previous widget in this container
/// @return Whether a new widget was focused
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool focusPreviousWidget();
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Focus or unfocus the widget
/// @param focused Is the widget focused?
///
/// When a widget is focused, the previously focused widget will be unfocused.
///
/// @warning This function only works properly when the widget was already added to its parent (e.g. the Gui).
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void setFocused(bool focused) override;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @internal
/// Called when one of the child widgets of this container gains focus.
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void childWidgetFocused(const Widget::Ptr& child);
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @internal
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void leftMousePressed(Vector2f pos) override;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @internal
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void leftMouseReleased(Vector2f pos) override;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @internal
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void rightMousePressed(Vector2f pos) override;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @internal
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void rightMouseReleased(Vector2f pos) override;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @internal
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void mouseMoved(Vector2f pos) override;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @internal
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void keyPressed(const sf::Event::KeyEvent& event) override;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @internal
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void textEntered(std::uint32_t key) override;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @internal
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool mouseWheelScrolled(float delta, Vector2f pos) override;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @internal
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void mouseNoLongerOnWidget() override;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @internal
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void leftMouseButtonNoLongerDown() override;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @internal
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void rightMouseButtonNoLongerDown() override;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @internal
// Shows the tool tip when the widget is located below the mouse.
// Returns its tool tip or the tool tip from a child widget if the mouse is on top of the widget.
// A nullptr is returned when the mouse is not on top of the widget or when the tool tip is empty.
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Widget::Ptr askToolTip(Vector2f mousePos) override;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @internal
// This function is called every frame with the time passed since the last frame.
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void update(sf::Time elapsedTime) override;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @internal
// The function returns true when the event is consumed and false when the event was ignored by all widgets.
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool handleEvent(sf::Event& event);
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
protected:
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Function called when one of the properties of the renderer is changed
///
/// @param property Lowercase name of the property that was changed
///
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void rendererChanged(const std::string& property) override;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Saves the widget as a tree node in order to save it to a file
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::unique_ptr<DataIO::Node> save(SavingRenderersMap& renderers) const override;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Loads the widget from a tree of nodes
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void load(const std::unique_ptr<DataIO::Node>& node, const LoadingRenderersMap& renderers) override;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Checks above which widget the mouse is standing.
// If there is no widget below the mouse then this function will return a null pointer.
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Widget::Ptr mouseOnWhichWidget(Vector2f mousePos);
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// This function will call the draw function from all the widgets.
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
virtual void drawWidgetContainer(sf::RenderTarget* target, const sf::RenderStates& states = sf::RenderStates::Default) const;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Find out what the index of the focused widget is. Returns 0 when no widget is focused and index+1 otherwise.
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::size_t getFocusedWidgetIndex() const;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Try to focus the given child widget
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool tryFocusWidget(const tgui::Widget::Ptr &widget, bool reverseWidgetOrder);
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
protected:
std::vector<Widget::Ptr> m_widgets;
Widget::Ptr m_widgetBelowMouse;
Widget::Ptr m_focusedWidget;
Vector2f m_prevInnerSize;
// Did we enter handleEvent directly or because we got a MouseReleased event?
bool m_handingMouseReleased = false;
// Does focusing the next widget always keep a widget from this container focused (e.g. in a ChildWindow)?
bool m_isolatedFocus = false;
friend class SubwidgetContainer; // Needs access to save and load functions
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
};
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @internal
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class TGUI_API GuiContainer : public Container
{
public:
typedef std::shared_ptr<GuiContainer> Ptr; ///< Shared widget pointer
typedef std::shared_ptr<const GuiContainer> ConstPtr; ///< Shared constant widget pointer
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Default constructor
///
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
GuiContainer();
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Doesn't has any effect
///
/// @param size Ignored
///
/// The window size cannot be changed by a widget.
///
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void setSize(const Layout2d& size) override;
using Widget::setSize;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Focus or unfocus the widget
/// @param focused Is the widget focused?
///
/// The gui container can't be unfocused.
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void setFocused(bool focused) override;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Returns whether the mouse position (which is relative to the parent widget) lies on top of the widget
///
/// @return Is the mouse on top of the widget?
///
/// This function always returns true.
///
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool mouseOnWidget(Vector2f pos) const override;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
private:
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// This function does nothing.
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void draw(sf::RenderTarget& target, sf::RenderStates states) const override;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Returns a nullptr.
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Widget::Ptr clone() const override
{
return nullptr;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
protected:
friend class Gui; // Required to let Gui access protected members from container and Widget
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
};
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#endif // TGUI_CONTAINER_HPP
| 54.8 | 133 | 0.296494 | [
"vector"
] |
0fc10bdb62cf7566fbcd0f9e115a107babcb1010 | 70,996 | cpp | C++ | velox/dwio/dwrf/writer/ColumnWriter.cpp | ZJie1/velox | 7ac665ad5ed6b973dcf5daef98045adc72a768d8 | [
"Apache-2.0"
] | null | null | null | velox/dwio/dwrf/writer/ColumnWriter.cpp | ZJie1/velox | 7ac665ad5ed6b973dcf5daef98045adc72a768d8 | [
"Apache-2.0"
] | null | null | null | velox/dwio/dwrf/writer/ColumnWriter.cpp | ZJie1/velox | 7ac665ad5ed6b973dcf5daef98045adc72a768d8 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "velox/dwio/dwrf/writer/ColumnWriter.h"
#include "velox/dwio/common/ChainedBuffer.h"
#include "velox/dwio/dwrf/writer/DictionaryEncodingUtils.h"
#include "velox/dwio/dwrf/writer/EntropyEncodingSelector.h"
#include "velox/dwio/dwrf/writer/FlatMapColumnWriter.h"
#include "velox/dwio/dwrf/writer/IntegerDictionaryEncoder.h"
#include "velox/dwio/dwrf/writer/StatisticsBuilderUtils.h"
#include "velox/vector/ComplexVector.h"
#include "velox/vector/DecodedVector.h"
#include "velox/vector/FlatVector.h"
using namespace facebook::velox::dwio::common;
using namespace facebook::velox::memory;
namespace facebook::velox::dwrf {
namespace {
FOLLY_ALWAYS_INLINE void initializeSelectivityVector(
const Ranges& ranges,
SelectivityVector& selectivityVector) {
selectivityVector.clearAll();
for (auto& range : ranges.getRanges()) {
selectivityVector.setValidRange(
std::get<0>(range), std::get<1>(range), true);
}
selectivityVector.updateBounds();
}
auto& decode(
WriterContext& context,
WriterContext::LocalDecodedVector& decoded,
const VectorPtr& slice,
const Ranges& ranges) {
auto localSv = context.getLocalSelectivityVector(slice->size());
initializeSelectivityVector(ranges, localSv.get());
decoded.get().decode(*slice, localSv.get());
return decoded.get();
}
template <typename T>
class ByteRleColumnWriter : public ColumnWriter {
public:
ByteRleColumnWriter(
WriterContext& context,
const TypeWithId& type,
const uint32_t sequence,
std::function<std::unique_ptr<ByteRleEncoder>(
std::unique_ptr<BufferedOutputStream>)> factory,
std::function<void(IndexBuilder&)> onRecordPosition)
: ColumnWriter{context, type, sequence, onRecordPosition},
data_{factory(newStream(StreamKind::StreamKind_DATA))} {
reset();
}
uint64_t write(const VectorPtr& slice, const Ranges& ranges) override;
void flush(
std::function<proto::ColumnEncoding&(uint32_t)> encodingFactory,
std::function<void(proto::ColumnEncoding&)> encodingOverride) override {
ColumnWriter::flush(encodingFactory, encodingOverride);
data_->flush();
}
void recordPosition() override {
ColumnWriter::recordPosition();
data_->recordPosition(*indexBuilder_);
}
private:
std::unique_ptr<ByteRleEncoder> data_;
};
template <>
uint64_t ByteRleColumnWriter<int8_t>::write(
const VectorPtr& slice,
const Ranges& ranges) {
static_assert(sizeof(int8_t) == sizeof(char), "unexpected type width");
static_assert(NULL_SIZE == 1, "unexpected raw data size");
if (slice->encoding() == VectorEncoding::Simple::FLAT) {
// Optimized path for flat vectors
auto flatVector = slice->as<FlatVector<int8_t>>();
DWIO_ENSURE(flatVector, "unexpected vector type");
ColumnWriter::write(slice, ranges);
const auto* nulls = slice->rawNulls();
const auto* vals = flatVector->template rawValues<char>();
data_->add(vals, ranges, nulls);
StatisticsBuilderUtils::addValues<int8_t>(
dynamic_cast<IntegerStatisticsBuilder&>(*indexStatsBuilder_),
slice,
ranges);
} else {
// The path for non-flat vectors
auto localDv = context_.getLocalDecodedVector();
auto& decodedVector = decode(context_, localDv, slice, ranges);
ColumnWriter::write(decodedVector, ranges);
std::function<bool(vector_size_t)> isNullAt = nullptr;
if (decodedVector.mayHaveNulls()) {
isNullAt = [&decodedVector](vector_size_t index) {
return decodedVector.isNullAt(index);
};
}
data_->add(
[&decodedVector](vector_size_t index) {
return decodedVector.valueAt<int8_t>(index);
},
ranges,
isNullAt);
// Updating status builder with individual boolean stream values
// The logic is equivalent to addValues which has been used for
// the flat version before.
StatisticsBuilderUtils::addValues<int8_t>(
dynamic_cast<IntegerStatisticsBuilder&>(*indexStatsBuilder_),
decodedVector,
ranges);
}
indexStatsBuilder_->increaseRawSize(ranges.size());
return ranges.size();
}
template <>
uint64_t ByteRleColumnWriter<bool>::write(
const VectorPtr& slice,
const Ranges& ranges) {
static_assert(sizeof(bool) == sizeof(char), "unexpected type width");
static_assert(NULL_SIZE == 1, "unexpected raw data size");
if (slice->encoding() == VectorEncoding::Simple::FLAT) {
// Optimized path for flat vectors
auto flatVector = slice->as<FlatVector<bool>>();
DWIO_ENSURE(flatVector, "unexpected vector type");
ColumnWriter::write(slice, ranges);
const auto* nulls = slice->rawNulls();
const auto* vals = flatVector->template rawValues<uint64_t>();
data_->addBits(vals, ranges, nulls, false);
StatisticsBuilderUtils::addValues(
dynamic_cast<BooleanStatisticsBuilder&>(*indexStatsBuilder_),
slice,
ranges);
} else {
auto localDv = context_.getLocalDecodedVector();
auto& decodedVector = decode(context_, localDv, slice, ranges);
ColumnWriter::write(decodedVector, ranges);
std::function<bool(vector_size_t)> isNullAt = nullptr;
if (decodedVector.mayHaveNulls()) {
isNullAt = [&decodedVector](vector_size_t index) {
return decodedVector.isNullAt(index);
};
}
data_->addBits(
[&decodedVector](vector_size_t index) {
return decodedVector.valueAt<bool>(index);
},
ranges,
isNullAt,
false);
// Updating status builder with individual boolean stream values
// The logic is equivalent to addValues which has been used for
// the flat version before.
StatisticsBuilderUtils::addValues(
dynamic_cast<BooleanStatisticsBuilder&>(*indexStatsBuilder_),
decodedVector,
ranges);
}
indexStatsBuilder_->increaseRawSize(ranges.size());
return ranges.size();
}
// The integer writer class that tries to use dictionary encoding to write
// the given integer values. If dictionary encoding is determined to be
// inefficient for the column, we would write the column with direct encoding
// instead.
template <typename T>
class IntegerColumnWriter : public ColumnWriter {
public:
IntegerColumnWriter(
WriterContext& context,
const TypeWithId& type,
const uint32_t sequence,
std::function<void(IndexBuilder&)> onRecordPosition)
: ColumnWriter{context, type, sequence, onRecordPosition},
data_{nullptr},
dataDirect_{nullptr},
inDictionary_{nullptr},
dictEncoder_{context.getIntDictionaryEncoder<T>(
EncodingKey{
type.id,
context.shareFlatMapDictionaries ? 0 : sequence},
getMemoryPool(MemoryUsageCategory::DICTIONARY),
getMemoryPool(MemoryUsageCategory::GENERAL))},
rows_{getMemoryPool(MemoryUsageCategory::GENERAL)},
dictionaryKeySizeThreshold_{
getConfig(Config::DICTIONARY_NUMERIC_KEY_SIZE_THRESHOLD)},
sort_{getConfig(Config::DICTIONARY_SORT_KEYS)},
useDictionaryEncoding_{useDictionaryEncoding()},
strideOffsets_{getMemoryPool(MemoryUsageCategory::GENERAL)} {
DWIO_ENSURE_GE(dictionaryKeySizeThreshold_, 0.0);
DWIO_ENSURE_LE(dictionaryKeySizeThreshold_, 1.0);
DWIO_ENSURE(firstStripe_);
if (!useDictionaryEncoding_) {
// Suppress the stream used to initialize dictionary encoder.
// TODO: passing factory method into the dict encoder also works
// around this problem but has messier code organization.
context_.suppressStream(StreamIdentifier{
id_,
context_.shareFlatMapDictionaries ? 0 : sequence_,
0,
StreamKind::StreamKind_DICTIONARY_DATA});
initStreamWriters(useDictionaryEncoding_);
}
reset();
}
uint64_t write(const VectorPtr& slice, const Ranges& ranges) override;
void reset() override {
// Lots of decisions regarding the presence of streams are made at flush
// time. We would defer recording all stream positions till then, and
// only record position for PRESENT stream upon construction.
ColumnWriter::recordPosition();
// Record starting position only for direct encoding because we don't know
// until the next flush whether we need to write the IN_DICTIONARY stream.
if (useDictionaryEncoding_) {
// explicitly initialize first entry
strideOffsets_.resize(0);
strideOffsets_.append(0);
} else {
strideOffsets_.clear();
recordDirectEncodingStreamPositions();
}
}
void flush(
std::function<proto::ColumnEncoding&(uint32_t)> encodingFactory,
std::function<void(proto::ColumnEncoding&)> encodingOverride) override {
// Determine whether dictionary is the right encoding to use when writing
// the first stripe. We will continue using the same decision for all
// subsequent stripes.
// When we have already determined not to use dictionary encoding prior to
// flush, we would skip this block.
if (UNLIKELY(firstStripe_) && useDictionaryEncoding_) {
// Determine whether dictionary is the right encoding.
useDictionaryEncoding_ = shouldKeepDictionary();
initStreamWriters(useDictionaryEncoding_);
if (!useDictionaryEncoding_) {
// Suppress the stream used to initialize dictionary encoder.
// TODO: passing factory method into the dict encoder also works
// around this problem but has messier code organization.
context_.suppressStream(StreamIdentifier{
id_,
context_.shareFlatMapDictionaries ? 0 : sequence_,
0,
StreamKind::StreamKind_DICTIONARY_DATA});
// Record direct encoding stream starting position.
recordDirectEncodingStreamPositions(0);
convertToDirectEncoding();
}
}
if (useDictionaryEncoding_) {
finalDictionarySize_ = dictEncoder_.flush();
populateDictionaryEncodingStreams();
}
// NOTE: Flushes index. All index entries need to have been backfilled.
ColumnWriter::flush(encodingFactory, encodingOverride);
size_t dictEncoderSize = dictEncoder_.size();
dictEncoder_.clear();
rows_.clear();
ensureValidStreamWriters(useDictionaryEncoding_);
// Flush in the order of the spec: IN_DICT, DICT_DATA, DATA
if (useDictionaryEncoding_) {
// Suppress IN_DICTIONARY stream if all values are kept in dict.
// TODO: It would be nice if the suppression could be pushed down to
// the index builder as well so we don't have to micromanage when and
// whether to write specific streams.
if (UNLIKELY(finalDictionarySize_ == dictEncoderSize)) {
suppressStream(StreamKind::StreamKind_IN_DICTIONARY);
} else {
inDictionary_->flush();
}
data_->flush();
} else {
dataDirect_->flush();
}
// Start the new stripe.
firstStripe_ = false;
}
// FIXME: call base class set encoding first to deal with sequence and
// whatnot.
void setEncoding(proto::ColumnEncoding& encoding) const override {
ColumnWriter::setEncoding(encoding);
if (useDictionaryEncoding_) {
encoding.set_kind(
proto::ColumnEncoding_Kind::ColumnEncoding_Kind_DICTIONARY);
encoding.set_dictionarysize(finalDictionarySize_);
}
}
void createIndexEntry() override {
hasNull_ = hasNull_ || indexStatsBuilder_->hasNull().value();
fileStatsBuilder_->merge(*indexStatsBuilder_);
// Add entry with stats for either case.
indexBuilder_->addEntry(*indexStatsBuilder_);
indexStatsBuilder_->reset();
ColumnWriter::recordPosition();
// TODO: the only way useDictionaryEncoding_ right now is
// through abandonDictionary, so we already have the stream initialization
// handled. Might want to rethink stream initialization in the future when
// we support starting with low memory mode and switching encoding after
// first stripe.
if (useDictionaryEncoding_) {
// Record the stride boundaries so that we can backfill the stream
// positions when actually writing the streams.
strideOffsets_.append(rows_.size());
} else {
recordDirectEncodingStreamPositions();
}
}
void recordDirectEncodingStreamPositions(int32_t strideOffset = -1) {
dataDirect_->recordPosition(*indexBuilder_, strideOffset);
}
void recordDictionaryEncodingStreamPositions(
bool writeInDictionaryStream,
int32_t strideOffset) {
if (writeInDictionaryStream) {
inDictionary_->recordPosition(*indexBuilder_, strideOffset);
}
data_->recordPosition(*indexBuilder_, strideOffset);
}
// This incurs additional memory usage. A good long term adjustment but not
// viable mitigation to memory pressure.
void abandonDictionaries() override {
if (!useDictionaryEncoding_) {
return;
}
useDictionaryEncoding_ = false;
// TODO: hopefully not required in the future, but need to solve the problem
// of replacing/deleting streams.
DWIO_ENSURE(firstStripe_);
initStreamWriters(useDictionaryEncoding_);
// Record direct encoding stream starting position.
recordDirectEncodingStreamPositions(0);
convertToDirectEncoding();
dictEncoder_.clear();
rows_.clear();
strideOffsets_.clear();
}
private:
uint64_t writeDict(DecodedVector& decodedVector, const Ranges& ranges);
uint64_t writeDirect(const VectorPtr& slice, const Ranges& ranges);
void ensureValidStreamWriters(bool dictEncoding) {
// Ensure we have valid streams for exactly one encoding.
DWIO_ENSURE(
(dictEncoding && data_ && inDictionary_ && !dataDirect_) ||
(!dictEncoding && !data_ && !inDictionary_ && dataDirect_));
}
void initStreamWriters(bool dictEncoding) {
if (!data_ && !dataDirect_) {
if (dictEncoding) {
data_ = IntEncoder</* isSigned = */ false>::createRle(
RleVersion_1,
newStream(StreamKind::StreamKind_DATA),
getConfig(Config::USE_VINTS),
sizeof(T));
inDictionary_ = createBooleanRleEncoder(
newStream(StreamKind::StreamKind_IN_DICTIONARY));
} else {
dataDirect_ = IntEncoder</* isSigned = */ true>::createDirect(
newStream(StreamKind::StreamKind_DATA),
getConfig(Config::USE_VINTS),
sizeof(T));
}
}
ensureValidStreamWriters(dictEncoding);
}
// NOTE: This should be called *before* clearing the rows_ buffer.
bool shouldKeepDictionary() const {
// TODO(T91508412): Move the dictionary efficiency based decision into
// dictionary encoder.
auto totalElementCount = dictEncoder_.getTotalCount();
return totalElementCount != 0 &&
// TODO: wonder if this should be final dictionary size instead. In that
// case, might be better off passing in the dict size and row size
// directly in order to prevent from being called before getting the
// actual final dict size.
(static_cast<float>(dictEncoder_.size()) / totalElementCount) <=
dictionaryKeySizeThreshold_;
}
// Should be called only once per stripe for both flushing and abandoning
// dictionary encoding.
void populateStrides(
std::function<void(size_t, size_t)> populateData,
std::function<void(size_t)> populateIndex) {
size_t numStrides = strideOffsets_.size() - 1;
// Populate data and stream positions for completed strides.
for (size_t i = 1; i <= numStrides; ++i) {
const auto& start = strideOffsets_[i - 1];
const auto& end = strideOffsets_[i];
DWIO_ENSURE_GE(end, start);
if (end > start) {
populateData(start, end);
}
// Set up for next stride.
if (isIndexEnabled()) {
// Backing filling stream positions for the stride index entry.
// Stats are already captured when creating the entry.
populateIndex(i);
}
}
size_t endOfLastStride = strideOffsets_[numStrides];
// Populate data only for the current stride.
// Happens only when abandoning dictionary in the incomplete (current)
// stride.
if (endOfLastStride < rows_.size()) {
populateData(endOfLastStride, rows_.size());
}
}
void populateDictionaryEncodingStreams();
void convertToDirectEncoding();
// Could be RLE encoded raw data or dictionary encoded values.
std::unique_ptr<IntEncoder<false>> data_;
// Direct-encoded data in case dictionary encoding is not optimal.
std::unique_ptr<IntEncoder<true>> dataDirect_;
// Whether data at offset is in the stripe dictionary. If not, it's either
// written as raw value or in the stride dictionary.
std::unique_ptr<ByteRleEncoder> inDictionary_;
IntegerDictionaryEncoder<T>& dictEncoder_;
// write dict writes to an in-memory vector too so that we can later write
// the sorted order after compiling a lookup table.
ChainedBuffer<uint32_t> rows_;
size_t finalDictionarySize_;
const float dictionaryKeySizeThreshold_;
const bool sort_;
// This value could change if we are writing with low memory mode or if we
// determine with the first stripe that the data is not fit for dictionary
// encoding.
bool useDictionaryEncoding_;
bool firstStripe_{true};
DataBuffer<size_t> strideOffsets_;
};
template <typename T>
uint64_t IntegerColumnWriter<T>::write(
const VectorPtr& slice,
const Ranges& ranges) {
if (useDictionaryEncoding_) {
// Decode and then write
auto localDv = context_.getLocalDecodedVector();
auto& decodedVector = decode(context_, localDv, slice, ranges);
return writeDict(decodedVector, ranges);
} else {
// If the input is not a flat vector we make a complete copy and convert
// it to flat vector
if (slice->encoding() != VectorEncoding::Simple::FLAT) {
auto newBase = BaseVector::create(
CppToType<T>::create(),
slice->size(),
&getMemoryPool(MemoryUsageCategory::GENERAL));
auto newVector = std::dynamic_pointer_cast<FlatVector<T>>(newBase);
newVector->copy(slice.get(), 0, 0, slice->size());
return writeDirect(newVector, ranges);
} else {
// Directly write the flat vector
return writeDirect(slice, ranges);
}
}
}
template <typename T>
uint64_t IntegerColumnWriter<T>::writeDict(
DecodedVector& decodedVector,
const Ranges& ranges) {
auto& statsBuilder =
dynamic_cast<IntegerStatisticsBuilder&>(*indexStatsBuilder_);
ColumnWriter::write(decodedVector, ranges);
// make sure we have enough space
rows_.reserve(rows_.size() + ranges.size());
auto processRow = [&](vector_size_t pos) {
T value = decodedVector.valueAt<T>(pos);
rows_.unsafeAppend(dictEncoder_.addKey(value));
statsBuilder.addValues(value);
};
uint64_t nullCount = 0;
if (decodedVector.mayHaveNulls()) {
for (auto& pos : ranges) {
if (decodedVector.isNullAt(pos)) {
++nullCount;
} else {
processRow(pos);
}
}
} else {
for (auto& pos : ranges) {
processRow(pos);
}
}
uint64_t rawSize = (ranges.size() - nullCount) * sizeof(T);
if (nullCount > 0) {
statsBuilder.setHasNull();
rawSize += nullCount * NULL_SIZE;
}
statsBuilder.increaseRawSize(rawSize);
return rawSize;
}
template <typename T>
uint64_t IntegerColumnWriter<T>::writeDirect(
const VectorPtr& slice,
const Ranges& ranges) {
ensureValidStreamWriters(false);
auto flatVector = slice->asFlatVector<T>();
DWIO_ENSURE(flatVector, "unexpected vector type");
ColumnWriter::write(slice, ranges);
auto nulls = slice->rawNulls();
auto vals = flatVector->rawValues();
auto count = dataDirect_->add(vals, ranges, nulls);
StatisticsBuilderUtils::addValues<T>(
dynamic_cast<IntegerStatisticsBuilder&>(*indexStatsBuilder_),
slice,
ranges);
auto rawSize = count * sizeof(T) + (ranges.size() - count) * NULL_SIZE;
indexStatsBuilder_->increaseRawSize(rawSize);
return rawSize;
}
// TODO: T45220726 Reduce memory usage in this method by
// allocating fewer buffers.
// One way to do so is via passing a getData function into writer instead of
// writing to intermediate buffers.
template <typename T>
void IntegerColumnWriter<T>::populateDictionaryEncodingStreams() {
ensureValidStreamWriters(true);
MemoryPool& pool{getMemoryPool(MemoryUsageCategory::GENERAL)};
// Allocate fixed size buffer for batch write
DataBuffer<char> writeBuffer{pool};
writeBuffer.reserve(64 * 1024);
// Lookup table may contain unsigned dictionary offsets [0 - 2^31) or signed
// raw values. So the type used by it need to cover both ranges.
using LookupType = typename std::conditional<sizeof(T) < 4, int32_t, T>::type;
// When all the Keys are in Dictionary, inDictionaryStream is omitted.
bool writeInDictionaryStream = finalDictionarySize_ != dictEncoder_.size();
// Record starting positions of the dictionary encoding streams.
recordDictionaryEncodingStreamPositions(writeInDictionaryStream, 0);
// Add and populate index entry for rows_[start:end).
// TODO: T45260340 Unfortunately standard usage of the index
// builder would need to segment the writes in the data buffer again. Should
// we manually call add on index builder and still batch the entire write?
auto populateDictionaryStreams = [&, this](size_t start, size_t end) {
// Do this once per stride as opposed to per row to reduce branching
// cost.
if (writeInDictionaryStream) {
bufferedWrite<char>(
writeBuffer,
start,
end,
[&](auto index) { return dictEncoder_.getInDict()[rows_[index]]; },
[&](auto buf, auto size) {
inDictionary_->add(buf, Ranges::of(0, size), nullptr);
});
}
// lookupTable represents the data as signed, but each value needs to be
// interpretted by combining the corresponding offset in the indctionary
// data. if inDictionary is true, lookupTable contains offset into
// dictionary(unsigned) if inDictionary is false, lookupTable contains the
// actual value(signed).
bufferedWrite<LookupType>(
writeBuffer,
start,
end,
[&](auto index) { return dictEncoder_.getLookupTable()[rows_[index]]; },
[&](auto buf, auto size) {
data_->add(buf, Ranges::of(0, size), nullptr);
});
};
// The writer always calls createIndexEntry before flush.
size_t lastIndexStrideOffset = strideOffsets_[strideOffsets_.size() - 1];
DWIO_ENSURE_EQ(lastIndexStrideOffset, rows_.size());
populateStrides(
populateDictionaryStreams,
std::bind(
&IntegerColumnWriter<T>::recordDictionaryEncodingStreamPositions,
this,
writeInDictionaryStream,
std::placeholders::_1));
}
template <typename T>
void IntegerColumnWriter<T>::convertToDirectEncoding() {
ensureValidStreamWriters(false);
auto populateDirectStream = [&, this](size_t start, size_t end) {
bufferedWrite<T>(
getMemoryPool(MemoryUsageCategory::GENERAL),
64 * 1024,
start,
end,
[&](auto index) { return dictEncoder_.getKey(rows_[index]); },
[&](auto buf, auto size) {
dataDirect_->add(buf, Ranges::of(0, size), nullptr);
});
};
populateStrides(
populateDirectStream,
std::bind(
&IntegerColumnWriter<T>::recordDirectEncodingStreamPositions,
this,
std::placeholders::_1));
}
class TimestampColumnWriter : public ColumnWriter {
public:
TimestampColumnWriter(
WriterContext& context,
const TypeWithId& type,
const uint32_t sequence,
std::function<void(IndexBuilder&)> onRecordPosition)
: ColumnWriter{context, type, sequence, onRecordPosition},
seconds_{IntEncoder</* isSigned = */ true>::createRle(
RleVersion_1,
newStream(StreamKind::StreamKind_DATA),
context.getConfig(Config::USE_VINTS),
LONG_BYTE_SIZE)},
nanos_{IntEncoder</* isSigned = */ false>::createRle(
RleVersion_1,
newStream(StreamKind::StreamKind_NANO_DATA),
context.getConfig(Config::USE_VINTS),
LONG_BYTE_SIZE)} {
reset();
}
uint64_t write(const VectorPtr& slice, const Ranges& ranges) override;
void flush(
std::function<proto::ColumnEncoding&(uint32_t)> encodingFactory,
std::function<void(proto::ColumnEncoding&)> encodingOverride) override {
ColumnWriter::flush(encodingFactory, encodingOverride);
seconds_->flush();
nanos_->flush();
}
void recordPosition() override {
ColumnWriter::recordPosition();
seconds_->recordPosition(*indexBuilder_);
nanos_->recordPosition(*indexBuilder_);
}
private:
std::unique_ptr<IntEncoder<true>> seconds_;
std::unique_ptr<IntEncoder<false>> nanos_;
};
namespace {
FOLLY_ALWAYS_INLINE int64_t formatTime(int64_t seconds, uint64_t nanos) {
DWIO_ENSURE(seconds >= MIN_SECONDS);
if (seconds < 0 && nanos != 0) {
// Adding 1 for neagive seconds is there to imitate the Java ORC writer.
// Consider the case where -1500 milliseconds need to be represented.
// In java world, due to a bug (-1500/1000 will result in -1 or rounding up)
// Due to this Java represented -1500 millis as -1 for seconds and 5*10^8
// for nanos (Note, Epoch is ignored for simplicity sake).
// In CPP world, it will be represented as -2 seconds and 5*10^8 nanos
// and nanos can never be negative in CPP. (CPP has right
// representation).
// PS: Due to this bug, the second before UTC epoch with non zero nanos will
// always be converted to second after UTC epoch with same nanos.
seconds += 1;
}
return seconds - EPOCH_OFFSET;
}
FOLLY_ALWAYS_INLINE int64_t formatNanos(uint64_t nanos) {
if (nanos == 0) {
return 0;
}
DWIO_ENSURE(nanos <= MAX_NANOS);
if (nanos % 100 != 0) {
return nanos << 3;
} else {
nanos /= 100;
int32_t trailingZeros = 1;
while (nanos % 10 == 0 && trailingZeros < 7) {
nanos /= 10;
trailingZeros += 1;
}
return (nanos << 3) | trailingZeros;
}
}
} // namespace
uint64_t TimestampColumnWriter::write(
const VectorPtr& slice,
const Ranges& ranges) {
// Timestamp is not frequently used, always decode so we have less branches to
// deal with.
auto localDv = context_.getLocalDecodedVector();
auto& decodedVector = decode(context_, localDv, slice, ranges);
ColumnWriter::write(decodedVector, ranges);
size_t count = 0;
if (decodedVector.mayHaveNulls()) {
for (auto& pos : ranges) {
if (!decodedVector.isNullAt(pos)) {
auto ts = decodedVector.valueAt<Timestamp>(pos);
seconds_->writeValue(formatTime(ts.getSeconds(), ts.getNanos()));
nanos_->writeValue(formatNanos(ts.getNanos()));
++count;
}
}
} else {
for (auto& pos : ranges) {
auto ts = decodedVector.valueAt<Timestamp>(pos);
seconds_->writeValue(formatTime(ts.getSeconds(), ts.getNanos()));
nanos_->writeValue(formatNanos(ts.getNanos()));
++count;
}
}
indexStatsBuilder_->increaseValueCount(count);
if (count != ranges.size()) {
indexStatsBuilder_->setHasNull();
}
// Seconds is Long, Nanos is int.
constexpr uint32_t TimeStampSize = LONG_BYTE_SIZE + INT_BYTE_SIZE;
auto rawSize = count * TimeStampSize + (ranges.size() - count) * NULL_SIZE;
indexStatsBuilder_->increaseRawSize(rawSize);
return rawSize;
}
// The string writer class that tries to use dictionary encoding to write
// the given string values. If dictionary encoding is determined to be
// inefficient for the column, we would write the column with direct encoding
// instead.
class StringColumnWriter : public ColumnWriter {
public:
StringColumnWriter(
WriterContext& context,
const TypeWithId& type,
const uint32_t sequence,
std::function<void(IndexBuilder&)> onRecordPosition)
: ColumnWriter{context, type, sequence, onRecordPosition},
data_{nullptr},
dataDirect_{nullptr},
dataDirectLength_{nullptr},
dictionaryData_{nullptr},
dictionaryDataLength_{nullptr},
inDictionary_{nullptr},
strideDictionaryData_{nullptr},
strideDictionaryDataLength_{nullptr},
dictEncoder_{
getMemoryPool(MemoryUsageCategory::DICTIONARY),
getMemoryPool(MemoryUsageCategory::GENERAL)},
rows_{getMemoryPool(MemoryUsageCategory::GENERAL)},
encodingSelector_{
getMemoryPool(MemoryUsageCategory::GENERAL),
getConfig(Config::DICTIONARY_STRING_KEY_SIZE_THRESHOLD),
getConfig(Config::ENTROPY_KEY_STRING_SIZE_THRESHOLD),
getConfig(Config::ENTROPY_STRING_MIN_SAMPLES),
getConfig(Config::ENTROPY_STRING_DICT_SAMPLE_FRACTION),
getConfig(Config::ENTROPY_STRING_THRESHOLD)},
sort_{getConfig(Config::DICTIONARY_SORT_KEYS)},
useDictionaryEncoding_{useDictionaryEncoding()},
strideOffsets_{getMemoryPool(MemoryUsageCategory::GENERAL)} {
DWIO_ENSURE(firstStripe_);
if (!useDictionaryEncoding_) {
initStreamWriters(useDictionaryEncoding_);
}
reset();
}
uint64_t write(const VectorPtr& slice, const Ranges& ranges) override;
void reset() override {
// Lots of decisions regarding the presence of streams are made at flush
// time. We would defer recording all stream positions till then, and
// only record position for PRESENT stream upon construction.
ColumnWriter::recordPosition();
// Record starting position only for direct encoding because we don't know
// until the next flush whether we need to write the IN_DICTIONARY stream.
if (useDictionaryEncoding_) {
// explicitly initialize first entry
strideOffsets_.resize(0);
strideOffsets_.append(0);
} else {
strideOffsets_.clear();
recordDirectEncodingStreamPositions();
}
}
void flush(
std::function<proto::ColumnEncoding&(uint32_t)> encodingFactory,
std::function<void(proto::ColumnEncoding&)> encodingOverride) override {
// Determine whether dictionary is the right encoding to use when writing
// the first stripe. We will continue using the same decision for all
// subsequent stripes.
if (UNLIKELY(firstStripe_) && useDictionaryEncoding_) {
// Determine whether dictionary is the right encoding.
useDictionaryEncoding_ = shouldKeepDictionary();
initStreamWriters(useDictionaryEncoding_);
if (!useDictionaryEncoding_) {
// Record direct encoding stream starting position.
recordDirectEncodingStreamPositions(0);
convertToDirectEncoding();
}
}
if (useDictionaryEncoding_) {
populateDictionaryEncodingStreams();
}
// NOTE: Flushes index. All index entries need to have been backfilled.
ColumnWriter::flush(encodingFactory, encodingOverride);
size_t dictEncoderSize = dictEncoder_.size();
dictEncoder_.clear();
rows_.clear();
ensureValidStreamWriters(useDictionaryEncoding_);
// Flush in the order of the spec:
// STRIDE_DICT, STRIDE_DICT_LENGTH, IN_DICT, DICT, DICT_LENGTH, DATA
if (useDictionaryEncoding_) {
// Suppress IN_DICTIONARY stream if all values are kept in dict.
// TODO: T46365785 It would be nice if the suppression
// could be pushed down to the index builder as well so we don't have to
// micromanage when and whether to write specific streams.
if (UNLIKELY(finalDictionarySize_ == dictEncoderSize)) {
suppressStream(StreamKind::StreamKind_STRIDE_DICTIONARY);
suppressStream(StreamKind::StreamKind_STRIDE_DICTIONARY_LENGTH);
suppressStream(StreamKind::StreamKind_IN_DICTIONARY);
} else {
strideDictionaryData_->flush();
strideDictionaryDataLength_->flush();
inDictionary_->flush();
}
dictionaryData_->flush();
dictionaryDataLength_->flush();
data_->flush();
} else {
dataDirect_->flush();
dataDirectLength_->flush();
}
// Start the new stripe.
firstStripe_ = false;
}
// FIXME: call base class set encoding first to deal with sequence and
// whatnot.
void setEncoding(proto::ColumnEncoding& encoding) const override {
ColumnWriter::setEncoding(encoding);
if (useDictionaryEncoding_) {
encoding.set_kind(
proto::ColumnEncoding_Kind::ColumnEncoding_Kind_DICTIONARY);
encoding.set_dictionarysize(finalDictionarySize_);
}
}
void createIndexEntry() override {
hasNull_ = hasNull_ || indexStatsBuilder_->hasNull().value();
fileStatsBuilder_->merge(*indexStatsBuilder_);
// Add entry with stats for either case.
indexBuilder_->addEntry(*indexStatsBuilder_);
indexStatsBuilder_->reset();
ColumnWriter::recordPosition();
// TODO: the only way useDictionaryEncoding_ right now is
// through abandonDictionary, so we already have the stream initialization
// handled. Might want to rethink stream initialization in the future when
// we support starting with low memory mode and switching encoding after
// first stripe.
if (useDictionaryEncoding_) {
// Record the stride boundaries so that we can backfill the stream
// positions when actually writing the streams.
strideOffsets_.append(rows_.size());
} else {
recordDirectEncodingStreamPositions();
}
}
void recordDirectEncodingStreamPositions(int32_t strideOffset = -1) {
dataDirect_->recordPosition(*indexBuilder_, strideOffset);
dataDirectLength_->recordPosition(*indexBuilder_, strideOffset);
}
void recordDictionaryEncodingStreamPositions(
bool writeInDictionaryStream,
int32_t strideOffset,
const DataBuffer<uint32_t>& strideDictCounts) {
if (writeInDictionaryStream) {
strideDictionaryData_->recordPosition(*indexBuilder_, strideOffset);
strideDictionaryDataLength_->recordPosition(*indexBuilder_, strideOffset);
indexBuilder_->add(strideDictCounts[strideOffset], strideOffset);
data_->recordPosition(*indexBuilder_, strideOffset);
inDictionary_->recordPosition(*indexBuilder_, strideOffset);
} else {
data_->recordPosition(*indexBuilder_, strideOffset);
}
}
void abandonDictionaries() override {
if (!useDictionaryEncoding_) {
return;
}
useDictionaryEncoding_ = false;
// TODO: hopefully not required in the future, but need to solve the problem
// of replacing/deleting streams.
DWIO_ENSURE(firstStripe_);
initStreamWriters(useDictionaryEncoding_);
// Record direct encoding stream starting position.
recordDirectEncodingStreamPositions(0);
convertToDirectEncoding();
dictEncoder_.clear();
rows_.clear();
strideOffsets_.clear();
}
protected:
bool useDictionaryEncoding() const override {
return (sequence_ == 0 ||
!context_.getConfig(
Config::MAP_FLAT_DISABLE_DICT_ENCODING_STRING)) &&
!context_.isLowMemoryMode();
}
private:
uint64_t writeDict(DecodedVector& decodedVector, const Ranges& ranges);
uint64_t writeDirect(DecodedVector& decodedVector, const Ranges& ranges);
void ensureValidStreamWriters(bool dictEncoding) {
// Ensure we have exactly one valid data stream.
DWIO_ENSURE(
(dictEncoding && data_ && dictionaryData_ && dictionaryDataLength_ &&
strideDictionaryData_ && strideDictionaryDataLength_ &&
inDictionary_ && !dataDirect_ && !dataDirectLength_) ||
(!dictEncoding && !data_ && !dictionaryData_ &&
!dictionaryDataLength_ && !strideDictionaryData_ &&
!strideDictionaryDataLength_ && !inDictionary_ && dataDirect_ &&
dataDirectLength_));
}
void initStreamWriters(bool dictEncoding) {
if (!data_ && !dataDirect_) {
if (dictEncoding) {
data_ = IntEncoder</* isSigned = */ false>::createRle(
RleVersion_1,
newStream(StreamKind::StreamKind_DATA),
getConfig(Config::USE_VINTS),
sizeof(uint32_t));
dictionaryData_ = std::make_unique<AppendOnlyBufferedStream>(
newStream(StreamKind::StreamKind_DICTIONARY_DATA));
dictionaryDataLength_ = IntEncoder</* isSigned = */ false>::createRle(
RleVersion_1,
newStream(StreamKind::StreamKind_LENGTH),
getConfig(Config::USE_VINTS),
sizeof(uint32_t));
inDictionary_ = createBooleanRleEncoder(
newStream(StreamKind::StreamKind_IN_DICTIONARY));
strideDictionaryData_ = std::make_unique<AppendOnlyBufferedStream>(
newStream(StreamKind::StreamKind_STRIDE_DICTIONARY));
strideDictionaryDataLength_ =
IntEncoder</* isSigned = */ false>::createRle(
RleVersion_1,
newStream(StreamKind::StreamKind_STRIDE_DICTIONARY_LENGTH),
getConfig(Config::USE_VINTS),
sizeof(uint32_t));
} else {
dataDirect_ = std::make_unique<AppendOnlyBufferedStream>(
newStream(StreamKind::StreamKind_DATA));
dataDirectLength_ = IntEncoder</* isSigned = */ false>::createRle(
RleVersion_1,
newStream(StreamKind::StreamKind_LENGTH),
getConfig(Config::USE_VINTS),
sizeof(uint32_t));
}
}
ensureValidStreamWriters(dictEncoding);
}
// NOTE: This should be called *before* clearing the rows_ buffer.
bool shouldKeepDictionary() const {
return rows_.size() != 0 &&
encodingSelector_.useDictionary(dictEncoder_, rows_.size());
}
// Should be called only once per stripe for both flushing and abandoning
// dictionary encoding.
void populateStrides(
std::function<void(size_t, size_t, size_t)> populateData,
std::function<void(size_t)> populateIndex) {
size_t numStrides = strideOffsets_.size() - 1;
// Populate data and stream positions for completed strides.
for (size_t i = 1; i <= numStrides; ++i) {
const auto& start = strideOffsets_[i - 1];
const auto& end = strideOffsets_[i];
DWIO_ENSURE_GE(end, start);
if (end > start) {
populateData(start, end, i - 1);
}
// Set up for next stride.
if (isIndexEnabled()) {
// Backing filling stream positions for the stride index entry.
// Stats are already captured when creating the entry.
populateIndex(i);
}
}
size_t endOfLastStride = strideOffsets_[numStrides];
// Populate data only for the current stride.
// Happens only when abandoning dictionary in the incomplete (current)
// stride.
if (endOfLastStride < rows_.size()) {
populateData(endOfLastStride, rows_.size(), numStrides);
}
}
void populateDictionaryEncodingStreams();
void convertToDirectEncoding();
// Could be RLE encoded raw data or dictionary encoded values.
std::unique_ptr<IntEncoder<false>> data_;
// Direct-encoded data in case dictionary encoding is not optimal.
std::unique_ptr<AppendOnlyBufferedStream> dataDirect_;
std::unique_ptr<IntEncoder<false>> dataDirectLength_;
// Keys in stripe dictionary
std::unique_ptr<AppendOnlyBufferedStream> dictionaryData_;
std::unique_ptr<IntEncoder<false>> dictionaryDataLength_;
// Whether data at offset is in the stripe dictionary. If not, it's either
// written as raw value or in the stride dictionary.
std::unique_ptr<ByteRleEncoder> inDictionary_;
// Keys in stride dictionary
std::unique_ptr<AppendOnlyBufferedStream> strideDictionaryData_;
std::unique_ptr<IntEncoder<false>> strideDictionaryDataLength_;
StringDictionaryEncoder dictEncoder_;
// write dict writes to an in-memory vector so that we can later write
// the sorted order after compiling a lookup table.
ChainedBuffer<uint32_t> rows_;
size_t finalDictionarySize_;
EntropyEncodingSelector encodingSelector_;
const bool sort_;
// This value could change if we are writing with low memory mode or if we
// determine with the first stripe that the data is not fit for dictionary
// encoding.
bool useDictionaryEncoding_;
bool firstStripe_{true};
DataBuffer<size_t> strideOffsets_;
};
uint64_t StringColumnWriter::write(
const VectorPtr& slice,
const Ranges& ranges) {
auto localDv = context_.getLocalDecodedVector();
auto& decodedVector = decode(context_, localDv, slice, ranges);
if (useDictionaryEncoding_) {
return writeDict(decodedVector, ranges);
} else {
return writeDirect(decodedVector, ranges);
}
}
uint64_t StringColumnWriter::writeDict(
DecodedVector& decodedVector,
const Ranges& ranges) {
auto& statsBuilder =
dynamic_cast<StringStatisticsBuilder&>(*indexStatsBuilder_);
ColumnWriter::write(decodedVector, ranges);
// make sure we have enough space
rows_.reserve(rows_.size() + ranges.size());
size_t strideIndex = strideOffsets_.size() - 1;
uint64_t rawSize = 0;
auto processRow = [&](size_t pos) {
auto sp = decodedVector.valueAt<StringView>(pos);
rows_.unsafeAppend(dictEncoder_.addKey(sp, strideIndex));
statsBuilder.addValues(sp);
rawSize += sp.size();
};
uint64_t nullCount = 0;
if (decodedVector.mayHaveNulls()) {
for (auto& pos : ranges) {
if (decodedVector.isNullAt(pos)) {
++nullCount;
} else {
processRow(pos);
}
}
} else {
for (auto& pos : ranges) {
processRow(pos);
}
}
if (nullCount > 0) {
statsBuilder.setHasNull();
rawSize += nullCount * NULL_SIZE;
}
statsBuilder.increaseRawSize(rawSize);
return rawSize;
}
uint64_t StringColumnWriter::writeDirect(
DecodedVector& decodedVector,
const Ranges& ranges) {
auto& statsBuilder =
dynamic_cast<StringStatisticsBuilder&>(*indexStatsBuilder_);
ColumnWriter::write(decodedVector, ranges);
// make sure we have enough space
rows_.reserve(rows_.size() + ranges.size());
// TODO Optimize to avoid copy
DataBuffer<int64_t> lengths{getMemoryPool(MemoryUsageCategory::GENERAL)};
lengths.reserve(ranges.size());
uint64_t rawSize = 0;
auto processRow = [&](size_t pos) {
auto sp = decodedVector.valueAt<StringView>(pos);
auto size = sp.size();
dataDirect_->write(sp.data(), size);
statsBuilder.addValues(sp);
rawSize += size;
lengths.unsafeAppend(size);
};
uint64_t nullCount = 0;
if (decodedVector.mayHaveNulls()) {
for (auto& pos : ranges) {
if (decodedVector.isNullAt(pos)) {
++nullCount;
} else {
processRow(pos);
}
}
} else {
for (auto& pos : ranges) {
processRow(pos);
}
}
if (lengths.size() > 0) {
dataDirectLength_->add(
lengths.data(), Ranges::of(0, lengths.size()), nullptr);
}
if (nullCount > 0) {
statsBuilder.setHasNull();
rawSize += nullCount * NULL_SIZE;
}
statsBuilder.increaseRawSize(rawSize);
return rawSize;
}
// TODO: T45220726 Reduce memory usage in this method by
// allocating fewer buffers.
// One way to do so is via passing a getData function into writer instead of
// writing to intermediate buffers.
void StringColumnWriter::populateDictionaryEncodingStreams() {
ensureValidStreamWriters(true);
MemoryPool& pool{getMemoryPool(MemoryUsageCategory::GENERAL)};
DataBuffer<uint32_t> lookupTable{pool};
DataBuffer<bool> inDict{pool};
// All elements are initialized as 0.
DataBuffer<uint32_t> strideDictCounts{
pool,
strideOffsets_.size(),
};
finalDictionarySize_ = DictionaryEncodingUtils::getSortedIndexLookupTable(
dictEncoder_,
pool,
sort_,
DictionaryEncodingUtils::frequencyOrdering,
true,
lookupTable,
inDict,
strideDictCounts,
[&](auto buf, auto size) { dictionaryData_->write(buf, size); },
[&](auto buf, auto size) {
dictionaryDataLength_->add(buf, Ranges::of(0, size), nullptr);
});
// When all the Keys are in Dictionary, inDictionaryStream is omitted.
bool writeInDictionaryStream = finalDictionarySize_ != dictEncoder_.size();
// Record starting positions of the dictionary encoding streams.
recordDictionaryEncodingStreamPositions(
writeInDictionaryStream, 0, strideDictCounts);
// Add and populate index entry for rows_[start:end).
// TODO: T45260340 Unfortunately standard usage of the index
// builder would need to segment the writes in the data buffer again. Should
// we manually call add on index builder and still batch the entire write?
auto populateDictionaryStreams =
[&, this](size_t start, size_t end, size_t strideIndex) {
// Do this once per stride as opposed to per row to reduce branching
// cost.
if (writeInDictionaryStream) {
auto strideDictKeyCount = strideDictCounts[strideIndex];
DataBuffer<uint32_t> sortedStrideDictKeyIndexBuffer{pool};
sortedStrideDictKeyIndexBuffer.reserve(strideDictKeyCount);
{
auto inDictWriter = createBufferedWriter<char>(
getMemoryPool(MemoryUsageCategory::GENERAL),
64 * 1024,
[&](auto buf, auto size) {
inDictionary_->add(buf, Ranges::of(0, size), nullptr);
});
uint32_t strideDictSize = 0;
for (size_t i = start; i != end; ++i) {
auto origIndex = rows_[i];
bool valInDict = inDict[origIndex];
inDictWriter.add(valInDict ? 1 : 0);
// TODO: optimize this branching either through restoring visitor
// pattern, or through separating the index backfill.
if (!valInDict) {
auto strideDictIndex = lookupTable[origIndex];
sortedStrideDictKeyIndexBuffer[strideDictIndex] = origIndex;
++strideDictSize;
}
}
DWIO_ENSURE_EQ(strideDictSize, strideDictKeyCount);
}
// StrideDictKey can be empty, when all keys for stride are in
// dictionary.
if (strideDictKeyCount > 0) {
auto strideLengthWriter = createBufferedWriter<uint32_t>(
getMemoryPool(MemoryUsageCategory::GENERAL),
64 * 1024,
[&](auto buf, auto size) {
strideDictionaryDataLength_->add(
buf, Ranges::of(0, size), nullptr);
});
for (size_t i = 0; i < strideDictKeyCount; ++i) {
auto val = dictEncoder_.getKey(sortedStrideDictKeyIndexBuffer[i]);
strideDictionaryData_->write(val.data(), val.size());
strideLengthWriter.add(val.size());
}
}
}
bufferedWrite<uint32_t>(
pool,
64 * 1024,
start,
end,
[&](auto index) { return lookupTable[rows_[index]]; },
[&](auto buf, auto size) {
data_->add(buf, Ranges::of(0, size), nullptr);
});
};
// The writer always calls createIndexEntry before flush.
size_t lastIndexStrideOffset = strideOffsets_[strideOffsets_.size() - 1];
DWIO_ENSURE_EQ(lastIndexStrideOffset, rows_.size());
populateStrides(
populateDictionaryStreams,
std::bind(
&StringColumnWriter::recordDictionaryEncodingStreamPositions,
this,
writeInDictionaryStream,
std::placeholders::_1,
std::cref(strideDictCounts)));
}
void StringColumnWriter::convertToDirectEncoding() {
ensureValidStreamWriters(false);
auto populateDirectStream =
[&, this](size_t start, size_t end, size_t /* unused */) {
auto lengthWriter = createBufferedWriter<uint32_t>(
getMemoryPool(MemoryUsageCategory::GENERAL),
64 * 1024,
[&](auto buf, auto size) {
dataDirectLength_->add(buf, Ranges::of(0, size), nullptr);
});
for (size_t i = start; i != end; ++i) {
auto key = dictEncoder_.getKey(rows_[i]);
dataDirect_->write(key.data(), key.size());
lengthWriter.add(key.size());
}
};
populateStrides(
populateDirectStream,
std::bind(
&StringColumnWriter::recordDirectEncodingStreamPositions,
this,
std::placeholders::_1));
}
template <typename T>
class FloatColumnWriter : public ColumnWriter {
public:
FloatColumnWriter(
WriterContext& context,
const TypeWithId& type,
const uint32_t sequence,
std::function<void(IndexBuilder&)> onRecordPosition)
: ColumnWriter{context, type, sequence, onRecordPosition},
data_{newStream(StreamKind::StreamKind_DATA)} {
reset();
}
uint64_t write(const VectorPtr& slice, const Ranges& ranges) override;
void flush(
std::function<proto::ColumnEncoding&(uint32_t)> encodingFactory,
std::function<void(proto::ColumnEncoding&)> encodingOverride) override {
ColumnWriter::flush(encodingFactory, encodingOverride);
data_.flush();
}
void recordPosition() override {
ColumnWriter::recordPosition();
data_.recordPosition(*indexBuilder_);
}
private:
AppendOnlyBufferedStream data_;
};
template <typename T>
uint64_t FloatColumnWriter<T>::write(
const VectorPtr& slice,
const Ranges& ranges) {
static_assert(folly::kIsLittleEndian, "not supported");
auto& statsBuilder =
dynamic_cast<DoubleStatisticsBuilder&>(*indexStatsBuilder_);
uint64_t nullCount = 0;
if (slice->encoding() == VectorEncoding::Simple::FLAT) {
auto flatVector = slice->asFlatVector<T>();
DWIO_ENSURE(flatVector, "unexpected vector type");
ColumnWriter::write(slice, ranges);
auto nulls = slice->rawNulls();
auto data = flatVector->rawValues();
if (slice->mayHaveNulls()) {
// higher throughput is achieved through this local buffer
auto writer = createBufferedWriter<T>(
getMemoryPool(MemoryUsageCategory::GENERAL),
1024,
[&](auto buf, auto size) {
data_.write(reinterpret_cast<const char*>(buf), size * sizeof(T));
});
auto processRow = [&](size_t pos) {
auto val = data[pos];
writer.add(val);
statsBuilder.addValues(val);
};
for (auto& pos : ranges) {
if (bits::isBitNull(nulls, pos)) {
++nullCount;
} else {
processRow(pos);
}
}
} else {
for (auto& pos : ranges) {
statsBuilder.addValues(data[pos]);
}
for (const auto& [start, end] : ranges.getRanges()) {
const char* srcPtr = reinterpret_cast<const char*>(data + start);
size_t sz = end - start;
data_.write(srcPtr, sz * sizeof(T));
}
}
} else {
auto localDv = context_.getLocalDecodedVector();
auto& decodedVector = decode(context_, localDv, slice, ranges);
ColumnWriter::write(decodedVector, ranges);
// higher throughput is achieved through this local buffer
auto writer = createBufferedWriter<T>(
getMemoryPool(MemoryUsageCategory::GENERAL),
1024,
[&](auto buf, auto size) {
data_.write(reinterpret_cast<const char*>(buf), size * sizeof(T));
});
auto processRow = [&](size_t pos) {
auto val = decodedVector.template valueAt<T>(pos);
writer.add(val);
statsBuilder.addValues(val);
};
if (decodedVector.mayHaveNulls()) {
for (auto& pos : ranges) {
if (decodedVector.isNullAt(pos)) {
++nullCount;
} else {
processRow(pos);
}
}
} else {
for (auto& pos : ranges) {
processRow(pos);
}
}
}
uint64_t rawSize = (ranges.size() - nullCount) * sizeof(T);
if (nullCount > 0) {
statsBuilder.setHasNull();
rawSize += nullCount * NULL_SIZE;
}
statsBuilder.increaseRawSize(rawSize);
return rawSize;
}
class BinaryColumnWriter : public ColumnWriter {
public:
BinaryColumnWriter(
WriterContext& context,
const TypeWithId& type,
const uint32_t sequence,
std::function<void(IndexBuilder&)> onRecordPosition)
: ColumnWriter{context, type, sequence, onRecordPosition},
data_{newStream(StreamKind::StreamKind_DATA)},
lengths_{IntEncoder<false>::createRle(
RleVersion_1,
newStream(StreamKind::StreamKind_LENGTH),
context.getConfig(Config::USE_VINTS),
INT_BYTE_SIZE)} {
reset();
}
uint64_t write(const VectorPtr& slice, const Ranges& ranges) override;
void flush(
std::function<proto::ColumnEncoding&(uint32_t)> encodingFactory,
std::function<void(proto::ColumnEncoding&)> encodingOverride) override {
ColumnWriter::flush(encodingFactory, encodingOverride);
data_.flush();
lengths_->flush();
}
void recordPosition() override {
ColumnWriter::recordPosition();
data_.recordPosition(*indexBuilder_);
lengths_->recordPosition(*indexBuilder_);
}
private:
AppendOnlyBufferedStream data_;
std::unique_ptr<IntEncoder<false>> lengths_;
};
uint64_t BinaryColumnWriter::write(
const VectorPtr& slice,
const Ranges& ranges) {
auto binarySlice = slice->asFlatVector<StringView>();
DWIO_ENSURE(binarySlice, "unexpected vector type");
ColumnWriter::write(slice, ranges);
auto nulls = slice->rawNulls();
auto data = binarySlice->rawValues();
// TODO Optimize to avoid copy
DataBuffer<int64_t> lengths{getMemoryPool(MemoryUsageCategory::GENERAL)};
lengths.reserve(ranges.size());
uint64_t rawSize = 0;
auto& statsBuilder =
dynamic_cast<BinaryStatisticsBuilder&>(*indexStatsBuilder_);
auto processRow = [&](size_t pos) {
auto size = data[pos].size();
lengths.unsafeAppend(size);
data_.write(data[pos].data(), size);
statsBuilder.addValues(size);
rawSize += size;
};
uint64_t nullCount = 0;
if (slice->mayHaveNulls()) {
for (auto& pos : ranges) {
if (bits::isBitNull(nulls, pos)) {
++nullCount;
} else {
processRow(pos);
}
}
} else {
for (auto& pos : ranges) {
processRow(pos);
}
}
if (lengths.size() > 0) {
lengths_->add(lengths.data(), Ranges::of(0, lengths.size()), nullptr);
}
if (nullCount > 0) {
statsBuilder.setHasNull();
rawSize += nullCount * NULL_SIZE;
}
statsBuilder.increaseRawSize(rawSize);
return rawSize;
}
class StructColumnWriter : public ColumnWriter {
public:
StructColumnWriter(
WriterContext& context,
const TypeWithId& type,
const uint32_t sequence,
std::function<void(IndexBuilder&)> onRecordPosition)
: ColumnWriter{context, type, sequence, onRecordPosition} {
reset();
}
uint64_t write(const VectorPtr& slice, const Ranges& ranges) override;
void flush(
std::function<proto::ColumnEncoding&(uint32_t)> encodingFactory,
std::function<void(proto::ColumnEncoding&)> encodingOverride) override {
ColumnWriter::flush(encodingFactory, encodingOverride);
for (auto& c : children_) {
c->flush(encodingFactory);
}
}
private:
uint64_t writeChildrenAndStats(
const RowVector* rowSlice,
const Ranges& ranges,
uint64_t nullCount);
};
uint64_t StructColumnWriter::writeChildrenAndStats(
const RowVector* rowSlice,
const Ranges& ranges,
uint64_t nullCount) {
uint64_t rawSize = 0;
if (ranges.size() > 0) {
for (size_t i = 0; i < children_.size(); ++i) {
rawSize += children_.at(i)->write(rowSlice->childAt(i), ranges);
}
}
if (nullCount) {
indexStatsBuilder_->setHasNull();
rawSize += nullCount * NULL_SIZE;
}
indexStatsBuilder_->increaseValueCount(ranges.size());
indexStatsBuilder_->increaseRawSize(rawSize);
return rawSize;
}
uint64_t StructColumnWriter::write(
const VectorPtr& slice,
const Ranges& ranges) {
// Special case for writing the root. Root writer accepts rows, so all are
// not null.
if (isRoot()) {
Ranges childRanges;
const RowVector* rowSlice;
const Ranges* childRangesPtr;
if (slice->encoding() != VectorEncoding::Simple::ROW) {
auto localDv = context_.getLocalDecodedVector();
auto& decodedVector = decode(context_, localDv, slice, ranges);
rowSlice = decodedVector.base()->as<RowVector>();
DWIO_ENSURE(rowSlice, "unexpected vector type");
childRangesPtr = &childRanges;
// For every index in wrapped indices we will add a 1-entry size range.
for (auto& pos : ranges) {
childRanges.add(decodedVector.index(pos), decodedVector.index(pos) + 1);
}
} else {
rowSlice = slice->as<RowVector>();
DWIO_ENSURE(rowSlice, "unexpected vector type");
childRangesPtr = &ranges;
}
auto rawSize = writeChildrenAndStats(rowSlice, *childRangesPtr, 0);
context_.incRowCount(ranges.size());
return rawSize;
}
// General case for writing row (struct)
uint64_t nullCount = 0;
Ranges childRanges;
const RowVector* rowSlice;
const Ranges* childRangesPtr;
if (slice->encoding() != VectorEncoding::Simple::ROW) {
auto localDv = context_.getLocalDecodedVector();
auto& decodedVector = decode(context_, localDv, slice, ranges);
rowSlice = decodedVector.base()->as<RowVector>();
DWIO_ENSURE(rowSlice, "unexpected vector type");
childRangesPtr = &childRanges;
ColumnWriter::write(decodedVector, ranges);
if (decodedVector.mayHaveNulls()) {
// Compute range of slice that child writer need to write.
// For every index in wrapped indices we will add a 1-entry size range.
for (auto& pos : ranges) {
if (decodedVector.isNullAt(pos)) {
nullCount++;
} else {
childRanges.add(
decodedVector.index(pos), decodedVector.index(pos) + 1);
}
}
} else {
for (auto& pos : ranges) {
childRanges.add(decodedVector.index(pos), decodedVector.index(pos) + 1);
}
}
} else {
rowSlice = slice->as<RowVector>();
DWIO_ENSURE(rowSlice, "unexpected vector type");
childRangesPtr = &ranges;
ColumnWriter::write(slice, ranges);
auto nulls = slice->rawNulls();
if (slice->mayHaveNulls()) {
// Compute range of slice that child writer need to write.
// If null count not present, err on the side of caution and assume nulls
// exist.
if (!rowSlice->getNullCount().has_value() ||
rowSlice->getNullCount().value() > 0) {
childRanges = ranges.filter(
[&nulls](auto i) { return !bits::isBitNull(nulls, i); });
childRangesPtr = &childRanges;
nullCount = ranges.size() - childRanges.size();
}
}
}
return writeChildrenAndStats(rowSlice, *childRangesPtr, nullCount);
}
class ListColumnWriter : public ColumnWriter {
public:
ListColumnWriter(
WriterContext& context,
const TypeWithId& type,
const uint32_t sequence,
std::function<void(IndexBuilder&)> onRecordPosition)
: ColumnWriter{context, type, sequence, onRecordPosition},
lengths_{IntEncoder</* isSigned = */ false>::createRle(
RleVersion_1,
newStream(StreamKind::StreamKind_LENGTH),
context.getConfig(Config::USE_VINTS),
INT_BYTE_SIZE)} {
reset();
}
uint64_t write(const VectorPtr& slice, const Ranges& ranges) override;
void flush(
std::function<proto::ColumnEncoding&(uint32_t)> encodingFactory,
std::function<void(proto::ColumnEncoding&)> encodingOverride) override {
ColumnWriter::flush(encodingFactory, encodingOverride);
lengths_->flush();
children_.at(0)->flush(encodingFactory);
}
void recordPosition() override {
ColumnWriter::recordPosition();
lengths_->recordPosition(*indexBuilder_);
}
private:
std::unique_ptr<IntEncoder</* isSigned = */ false>> lengths_;
};
uint64_t ListColumnWriter::write(const VectorPtr& slice, const Ranges& ranges) {
DataBuffer<vector_size_t> nonNullLengths{
getMemoryPool(MemoryUsageCategory::GENERAL)};
nonNullLengths.reserve(ranges.size());
Ranges childRanges;
uint64_t nullCount = 0;
const ArrayVector* arraySlice;
const vector_size_t* offsets;
const vector_size_t* lengths;
auto processRow = [&](size_t pos) {
// only add if length > 0
auto begin = offsets[pos];
auto end = begin + lengths[pos];
if (end > begin) {
childRanges.add(begin, end);
}
nonNullLengths.unsafeAppend(end - begin);
};
if (slice->encoding() != VectorEncoding::Simple::ARRAY) {
auto localDv = context_.getLocalDecodedVector();
auto& decodedVector = decode(context_, localDv, slice, ranges);
arraySlice = decodedVector.base()->as<ArrayVector>();
DWIO_ENSURE(arraySlice, "unexpected vector type");
ColumnWriter::write(decodedVector, ranges);
offsets = arraySlice->rawOffsets();
lengths = arraySlice->rawSizes();
if (decodedVector.mayHaveNulls()) {
for (auto& pos : ranges) {
if (decodedVector.isNullAt(pos)) {
++nullCount;
} else {
processRow(decodedVector.index(pos));
}
}
} else {
for (auto& pos : ranges) {
processRow(decodedVector.index(pos));
}
}
} else {
arraySlice = slice->as<ArrayVector>();
DWIO_ENSURE(arraySlice, "unexpected vector type");
ColumnWriter::write(slice, ranges);
auto nulls = slice->rawNulls();
// Retargeting array and its offsets and lengths to be used
// by the processRow lambda.
offsets = arraySlice->rawOffsets();
lengths = arraySlice->rawSizes();
if (slice->mayHaveNulls()) {
for (auto& pos : ranges) {
if (bits::isBitNull(nulls, pos)) {
++nullCount;
} else {
processRow(pos);
}
}
} else {
for (auto& pos : ranges) {
processRow(pos);
}
}
}
if (nonNullLengths.size()) {
lengths_->add(
nonNullLengths.data(), Ranges::of(0, nonNullLengths.size()), nullptr);
}
uint64_t rawSize = 0;
if (childRanges.size()) {
rawSize += children_.at(0)->write(arraySlice->elements(), childRanges);
}
if (nullCount > 0) {
indexStatsBuilder_->setHasNull();
rawSize += nullCount * NULL_SIZE;
}
indexStatsBuilder_->increaseValueCount(ranges.size() - nullCount);
indexStatsBuilder_->increaseRawSize(rawSize);
return rawSize;
}
class MapColumnWriter : public ColumnWriter {
public:
MapColumnWriter(
WriterContext& context,
const TypeWithId& type,
const uint32_t sequence,
std::function<void(IndexBuilder&)> onRecordPosition)
: ColumnWriter{context, type, sequence, onRecordPosition},
lengths_{IntEncoder</* isSigned = */ false>::createRle(
RleVersion_1,
newStream(StreamKind::StreamKind_LENGTH),
context.getConfig(Config::USE_VINTS),
INT_BYTE_SIZE)} {
reset();
}
uint64_t write(const VectorPtr& slice, const Ranges& ranges) override;
void flush(
std::function<proto::ColumnEncoding&(uint32_t)> encodingFactory,
std::function<void(proto::ColumnEncoding&)> encodingOverride) override {
ColumnWriter::flush(encodingFactory, encodingOverride);
lengths_->flush();
children_.at(0)->flush(encodingFactory);
children_.at(1)->flush(encodingFactory);
}
void recordPosition() override {
ColumnWriter::recordPosition();
lengths_->recordPosition(*indexBuilder_);
}
private:
std::unique_ptr<IntEncoder<false>> lengths_;
};
uint64_t MapColumnWriter::write(const VectorPtr& slice, const Ranges& ranges) {
DataBuffer<vector_size_t> nonNullLengths{
getMemoryPool(MemoryUsageCategory::GENERAL)};
nonNullLengths.reserve(ranges.size());
Ranges childRanges;
uint64_t nullCount = 0;
const MapVector* mapSlice;
const vector_size_t* offsets;
const vector_size_t* lengths;
auto processRow = [&](size_t pos) {
// Only add if length > 0.
auto begin = offsets[pos];
auto end = begin + lengths[pos];
if (end > begin) {
childRanges.add(begin, end);
}
nonNullLengths.unsafeAppend(end - begin);
};
if (slice->encoding() != VectorEncoding::Simple::MAP) {
auto localDv = context_.getLocalDecodedVector();
auto& decodedVector = decode(context_, localDv, slice, ranges);
mapSlice = decodedVector.base()->as<MapVector>();
DWIO_ENSURE(mapSlice, "unexpected vector type");
ColumnWriter::write(decodedVector, ranges);
offsets = mapSlice->rawOffsets();
lengths = mapSlice->rawSizes();
if (decodedVector.mayHaveNulls()) {
for (auto& pos : ranges) {
if (decodedVector.isNullAt(pos)) {
++nullCount;
} else {
processRow(decodedVector.index(pos));
}
}
} else {
for (auto& pos : ranges) {
processRow(decodedVector.index(pos));
}
}
} else {
mapSlice = slice->as<MapVector>();
DWIO_ENSURE(mapSlice, "unexpected vector type");
ColumnWriter::write(slice, ranges);
auto nulls = slice->rawNulls();
offsets = mapSlice->rawOffsets();
lengths = mapSlice->rawSizes();
if (slice->mayHaveNulls()) {
for (auto& pos : ranges) {
if (bits::isBitNull(nulls, pos)) {
++nullCount;
} else {
processRow(pos);
}
}
} else {
for (auto& pos : ranges) {
processRow(pos);
}
}
}
if (nonNullLengths.size()) {
lengths_->add(
nonNullLengths.data(), Ranges::of(0, nonNullLengths.size()), nullptr);
}
uint64_t rawSize = 0;
if (childRanges.size()) {
DWIO_ENSURE_EQ(mapSlice->mapKeys()->size(), mapSlice->mapValues()->size());
rawSize += children_.at(0)->write(mapSlice->mapKeys(), childRanges);
rawSize += children_.at(1)->write(mapSlice->mapValues(), childRanges);
}
if (nullCount > 0) {
indexStatsBuilder_->setHasNull();
rawSize += nullCount * NULL_SIZE;
}
indexStatsBuilder_->increaseValueCount(ranges.size() - nullCount);
indexStatsBuilder_->increaseRawSize(rawSize);
return rawSize;
}
} // namespace
std::unique_ptr<ColumnWriter> ColumnWriter::create(
WriterContext& context,
const TypeWithId& type,
const uint32_t sequence,
std::function<void(IndexBuilder&)> onRecordPosition) {
const auto flatMapEnabled = context.getConfig(Config::FLATTEN_MAP);
const auto& flatMapCols = context.getConfig(Config::MAP_FLAT_COLS);
// When flat map is enabled, all columns provided in the MAP_FLAT_COLS config,
// must be of MAP type. We only check top level columns (columns which are
// direct children of the root node).
if (flatMapEnabled && type.parent != nullptr && type.parent->id == 0 &&
type.type->kind() != TypeKind::MAP &&
std::find(flatMapCols.begin(), flatMapCols.end(), type.column) !=
flatMapCols.end()) {
DWIO_RAISE(fmt::format(
"MAP_FLAT_COLS contains column {}, but the root type of this column is {}."
" Column root types must be of type MAP",
type.column,
mapTypeKindToName(type.type->kind())));
}
switch (type.type->kind()) {
case TypeKind::BOOLEAN:
return std::make_unique<ByteRleColumnWriter<bool>>(
context, type, sequence, &createBooleanRleEncoder, onRecordPosition);
case TypeKind::TINYINT:
return std::make_unique<ByteRleColumnWriter<int8_t>>(
context, type, sequence, &createByteRleEncoder, onRecordPosition);
case TypeKind::SMALLINT:
return std::make_unique<IntegerColumnWriter<int16_t>>(
context, type, sequence, onRecordPosition);
case TypeKind::INTEGER:
return std::make_unique<IntegerColumnWriter<int32_t>>(
context, type, sequence, onRecordPosition);
case TypeKind::BIGINT:
return std::make_unique<IntegerColumnWriter<int64_t>>(
context, type, sequence, onRecordPosition);
case TypeKind::REAL:
return std::make_unique<FloatColumnWriter<float>>(
context, type, sequence, onRecordPosition);
case TypeKind::DOUBLE:
return std::make_unique<FloatColumnWriter<double>>(
context, type, sequence, onRecordPosition);
case TypeKind::VARCHAR:
return std::make_unique<StringColumnWriter>(
context, type, sequence, onRecordPosition);
case TypeKind::VARBINARY:
return std::make_unique<BinaryColumnWriter>(
context, type, sequence, onRecordPosition);
case TypeKind::TIMESTAMP:
return std::make_unique<TimestampColumnWriter>(
context, type, sequence, onRecordPosition);
case TypeKind::ROW: {
auto ret = std::make_unique<StructColumnWriter>(
context, type, sequence, onRecordPosition);
ret->children_.reserve(type.size());
for (int32_t i = 0; i < type.size(); ++i) {
ret->children_.push_back(create(context, *type.childAt(i), sequence));
}
return ret;
}
case TypeKind::MAP: {
DWIO_ENSURE_EQ(type.size(), 2, "Map should have exactly two children");
// We only flatten maps which are direct children of the root node.
// All other (nested) maps are treated as regular maps.
if (type.parent != nullptr && type.parent->id == 0 &&
context.getConfig(Config::FLATTEN_MAP) &&
std::find(flatMapCols.begin(), flatMapCols.end(), type.column) !=
flatMapCols.end()) {
DWIO_ENSURE(!onRecordPosition, "unexpected flat map nesting");
return FlatMapColumnWriter<TypeKind::INVALID>::create(
context, type, sequence);
}
auto ret = std::make_unique<MapColumnWriter>(
context, type, sequence, onRecordPosition);
ret->children_.push_back(create(context, *type.childAt(0), sequence));
ret->children_.push_back(create(context, *type.childAt(1), sequence));
return ret;
}
case TypeKind::ARRAY: {
DWIO_ENSURE_EQ(type.size(), 1, "Array should have exactly one child");
auto ret = std::make_unique<ListColumnWriter>(
context, type, sequence, onRecordPosition);
ret->children_.push_back(create(context, *type.childAt(0), sequence));
return ret;
}
default:
DWIO_RAISE("not supported yet ", mapTypeKindToName(type.type->kind()));
}
}
} // namespace facebook::velox::dwrf
| 35.163943 | 83 | 0.674292 | [
"vector"
] |
0fc1cb532aeedf22b19b7d91dda8e7c98378d694 | 1,331 | cpp | C++ | Shader/ShaderAttribute.cpp | SatoshiMabuchi/Crystal | 91b2d72e5544cf86183587d2cfea48ca7f390dd4 | [
"MIT"
] | null | null | null | Shader/ShaderAttribute.cpp | SatoshiMabuchi/Crystal | 91b2d72e5544cf86183587d2cfea48ca7f390dd4 | [
"MIT"
] | null | null | null | Shader/ShaderAttribute.cpp | SatoshiMabuchi/Crystal | 91b2d72e5544cf86183587d2cfea48ca7f390dd4 | [
"MIT"
] | null | null | null | #include "ShaderAttribute.h"
#include "ShaderObject.h"
using namespace Crystal::Shader;
std::string IShaderAttribute::getTypeName() const
{
return type.toString();
}
void ShaderAttribute1f::render(ShaderObject& shader)
{
glVertexAttribPointer(shader.getAttribLocation(getName()), 1, GL_FLOAT, GL_FALSE, 0, &value);
}
void ShaderAttribute2f::render(ShaderObject& shader)
{
glVertexAttribPointer(shader.getAttribLocation(getName()), 2, GL_FLOAT, GL_FALSE, 0, &value);
}
void ShaderAttribute3f::render(ShaderObject& shader)
{
glVertexAttribPointer(shader.getAttribLocation(getName()), 3, GL_FLOAT, GL_FALSE, 0, value.data());
}
void ShaderAttribute4f::render(ShaderObject& shader)
{
glVertexAttribPointer(shader.getAttribLocation(getName()), 4, GL_FLOAT, GL_FALSE, 0, value.data());
}
void ShaderAttributeMatrix2d::render(ShaderObject& shader)
{
glVertexAttribPointer(shader.getAttribLocation(getName()), 4, GL_FLOAT, GL_FALSE, 0, value.data());
}
void ShaderAttributeMatrix3d::render(ShaderObject& shader)
{
glVertexAttribPointer(shader.getAttribLocation(getName()), 9, GL_FLOAT, GL_FALSE, 0, value.data());
}
void ShaderAttributeMatrix4d::render(ShaderObject& shader)
{
glVertexAttribPointer(shader.getAttribLocation(getName()), 16, GL_FLOAT, GL_FALSE, 0, value.data());
} | 30.25 | 102 | 0.752066 | [
"render"
] |
0fc27c30e3cc61e1b0cd1eed5219a138907c3d6c | 4,089 | cpp | C++ | cpp_feature/test/test_parser.cpp | eozd/SIU-2018 | 81df1760be6a26c48d4140511ab194ffc8d700d7 | [
"Apache-2.0"
] | 1 | 2019-06-27T04:07:56.000Z | 2019-06-27T04:07:56.000Z | cpp_feature/test/test_parser.cpp | eozd/SIU-2018 | 81df1760be6a26c48d4140511ab194ffc8d700d7 | [
"Apache-2.0"
] | null | null | null | cpp_feature/test/test_parser.cpp | eozd/SIU-2018 | 81df1760be6a26c48d4140511ab194ffc8d700d7 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2018 Esref Ozdemir
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <catch/catch.hpp>
#include <feature/constants.hpp>
#include <feature/player.hpp>
#include <feature/row.hpp>
#include <parser.hpp>
using namespace feature;
using namespace feature::details;
TEST_CASE("Test parser::parse_line", "[parser::parse_line]") {
SECTION("Parse a regular line") {
std::string line =
"116001217 78392209 2 58 27 "
"4955,0,3,52.94,19.45 5264,1,14,80.03,47.38 5844,1,6,76.54,33.21 "
"4886,1,18,56.07,16.18 6116,6,0,91.82,68.8 4933,1,9,49.06,34.72 "
"6080,1,11,55.06,56.11 6117,7,0,48,0.52 4934,0,37,49.27,31.62 "
"6081,0,19,52.94,55.03 6118,1,-1,104.79,41.69 "
"6079,0,89,72.26,43.93 5241,1,35,85.37,38.82 5827,3,1,10.94,34.52 "
"6047,1,26,85.21,24.03 6089,1,17,74.45,44.34 5469,2,0,65.47,42.17 "
"6012,0,7,75.38,26.2 5433,1,19,78.81,54.66 5757,0,39,88.01,30.63 "
"5722,0,33,48.78,40.87 5990,0,8,61.65,32.3 5876,1,25,79.99,19.66 "
"5840,0,28,83.62,41.41 6100,0,17,72.82,50.32 ";
std::vector<Player> players{Player(4955, 0, 3, 52.94, 19.45),
Player(5264, 1, 14, 80.03, 47.38),
Player(5844, 1, 6, 76.54, 33.21),
Player(4886, 1, 18, 56.07, 16.18),
Player(6116, 6, 0, 91.82, 68.8),
Player(4933, 1, 9, 49.06, 34.72),
Player(6080, 1, 11, 55.06, 56.11),
Player(6117, 7, 0, 48, 0.52),
Player(4934, 0, 37, 49.27, 31.62),
Player(6081, 0, 19, 52.94, 55.03),
Player(6118, 1, -1, 104.79, 41.69),
Player(6079, 0, 89, 72.26, 43.93),
Player(5241, 1, 35, 85.37, 38.82),
Player(5827, 3, 1, 10.94, 34.52),
Player(6047, 1, 26, 85.21, 24.03),
Player(6089, 1, 17, 74.45, 44.34),
Player(5469, 2, 0, 65.47, 42.17),
Player(6012, 0, 7, 75.38, 26.2),
Player(5433, 1, 19, 78.81, 54.66),
Player(5757, 0, 39, 88.01, 30.63),
Player(5722, 0, 33, 48.78, 40.87),
Player(5990, 0, 8, 61.65, 32.3),
Player(5876, 1, 25, 79.99, 19.66),
Player(5840, 0, 28, 83.62, 41.41),
Player(6100, 0, 17, 72.82, 50.32)};
Row row = parse_line(line);
REQUIRE(row.match_id == 116001217);
REQUIRE(row.timestamp == 78392209);
REQUIRE(row.half == 2);
REQUIRE(row.minute == 58);
REQUIRE(row.second == 27);
REQUIRE(row.players == players);
}
SECTION("Parse a line with no player data") {
std::string line =
"116001217 78392209 2 58 27 ";
Row row = parse_line(line);
REQUIRE(row.match_id == 116001217);
REQUIRE(row.timestamp == 78392209);
REQUIRE(row.half == 2);
REQUIRE(row.minute == 58);
REQUIRE(row.second == 27);
REQUIRE(row.players == std::vector<Player>());
}
}
| 46.465909 | 79 | 0.480558 | [
"vector"
] |
0fc421ccdb5747cf0aa8238ed9d72db7da06a776 | 361 | cpp | C++ | cpp/example/src/BestTime2BuyAndSellStock/bestTime2BuyAndSellStock.cpp | zcemycl/algoTest | 9518fb2b60fd83c85aeb2ab809ff647aaf643f0a | [
"MIT"
] | 1 | 2022-01-26T16:33:45.000Z | 2022-01-26T16:33:45.000Z | cpp/example/src/BestTime2BuyAndSellStock/bestTime2BuyAndSellStock.cpp | zcemycl/algoTest | 9518fb2b60fd83c85aeb2ab809ff647aaf643f0a | [
"MIT"
] | null | null | null | cpp/example/src/BestTime2BuyAndSellStock/bestTime2BuyAndSellStock.cpp | zcemycl/algoTest | 9518fb2b60fd83c85aeb2ab809ff647aaf643f0a | [
"MIT"
] | 1 | 2022-01-26T16:35:44.000Z | 2022-01-26T16:35:44.000Z | #include "bestTime2BuyAndSellStock.h"
int bestTime2BuyAndSellStock::naive(vector<int>& prices){
int minVal = prices[0];
int maxReturn = 0;
for (int i=1;i<prices.size();i++){
if (prices[i]-minVal>maxReturn)
maxReturn = prices[i]-minVal;
if (prices[i]<minVal)
minVal = prices[i];
}
return maxReturn;
}
| 25.785714 | 57 | 0.601108 | [
"vector"
] |
0fc57c641c5d2066f6b481a357fd95deda811062 | 2,237 | hpp | C++ | components/SNPSummaryComponent/include/components/SNPSummaryComponent/ConsensusCaller.hpp | CreRecombinase/qctool | 6dad3a15c461177bf6940ba7b991337402ca5c41 | [
"BSL-1.0"
] | 3 | 2021-04-21T05:42:24.000Z | 2022-01-26T14:59:43.000Z | components/SNPSummaryComponent/include/components/SNPSummaryComponent/ConsensusCaller.hpp | CreRecombinase/qctool | 6dad3a15c461177bf6940ba7b991337402ca5c41 | [
"BSL-1.0"
] | 2 | 2020-04-09T16:11:04.000Z | 2020-11-10T11:18:56.000Z | components/SNPSummaryComponent/include/components/SNPSummaryComponent/ConsensusCaller.hpp | gavinband/qctool | 8d8adb45151c91f953fe4a9af00498073b1132ba | [
"BSL-1.0"
] | null | null | null |
// Copyright Gavin Band 2008 - 2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef QCTOOL_CALLCOMPARERCOMPONENT_CONSENSUS_CALLER_HPP
#define QCTOOL_CALLCOMPARERCOMPONENT_CONSENSUS_CALLER_HPP
#include <boost/signals2/signal.hpp>
#include "genfile/SNPDataSourceProcessor.hpp"
#include "genfile/VariantIdentifyingData.hpp"
#include "genfile/VariantDataReader.hpp"
#include "genfile/VCFFormatSNPDataSink.hpp"
#include "PairwiseCallComparerManager.hpp"
// Given a set of calls passed in by processed_snp
// The consensus caller outputs a
struct ConsensusCaller: public PairwiseCallComparerManager::MergeClient
{
public:
typedef std::auto_ptr< ConsensusCaller > UniquePtr ;
typedef boost::shared_ptr< ConsensusCaller > SharedPtr ;
static UniquePtr create( std::string const& model ) ;
static SharedPtr create_shared( std::string const& model ) ;
public:
ConsensusCaller() ;
virtual ~ConsensusCaller() ;
public:
typedef boost::signals2::signal<
void (
genfile::VariantIdentifyingData const&,
Eigen::MatrixXd const&,
std::map< std::string, std::vector< genfile::VariantEntry > > const&
)
> ResultSignal ;
void send_results_to( ResultSignal::slot_type ) ;
void send_results(
genfile::VariantIdentifyingData const& snp,
Eigen::MatrixXd const& genotypes,
std::map< std::string, std::vector< genfile::VariantEntry > > const& info
) ;
void begin_processing_snps( std::size_t number_of_samples ) ;
void begin_comparisons( genfile::VariantIdentifyingData const& snp ) ;
virtual void set_result(
std::string const& comparison,
std::string const& accepted_calls,
PairwiseCallComparerManager::Calls const& calls
) = 0 ;
void end_comparisons() ;
std::size_t get_number_of_samples() const { return m_number_of_samples ; }
genfile::VariantIdentifyingData const& get_snp() const { return m_snp ; }
std::vector< std::string > const& get_consensus_call_names() const { return m_call_names ; }
private:
std::vector< std::string > m_call_names ;
ResultSignal m_result_signal ;
genfile::VariantIdentifyingData m_snp ;
std::size_t m_number_of_samples ;
} ;
#endif
| 32.897059 | 93 | 0.762181 | [
"vector",
"model"
] |
0fc6ea7be0d35b98d08d5213a8c67d02da7dde7a | 1,831 | cpp | C++ | test_deprecated/testUtil/example_tc_lock.cpp | SuckShit/TarsCpp | 3f42f4e7a7bf43026a782c5d4b033155c27ed0c4 | [
"BSD-3-Clause"
] | 1 | 2019-09-05T07:25:51.000Z | 2019-09-05T07:25:51.000Z | test_deprecated/testUtil/example_tc_lock.cpp | SuckShit/TarsCpp | 3f42f4e7a7bf43026a782c5d4b033155c27ed0c4 | [
"BSD-3-Clause"
] | null | null | null | test_deprecated/testUtil/example_tc_lock.cpp | SuckShit/TarsCpp | 3f42f4e7a7bf43026a782c5d4b033155c27ed0c4 | [
"BSD-3-Clause"
] | 1 | 2021-05-21T09:59:06.000Z | 2021-05-21T09:59:06.000Z | /**
* Tencent is pleased to support the open source community by making Tars available.
*
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the 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
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
#include "util/tc_thread.h"
#include <unistd.h>
#include <iostream>
#include <vector>
using namespace std;
using namespace tars;
class MyThread : public TC_Thread, public TC_ThreadLock
{
public:
MyThread()
{
bTerminate = false;
}
/**
* 结束线程
*/
void terminate()
{
//先加锁, 然后设置结束状态, 然后通知其他线程醒过来
Lock sync(*this);
bTerminate = true;
notifyAll();
}
void doSomething()
{
cout << "doSomething" << endl;
}
/**
* 运行
*/
protected:
virtual void run()
{
while (!bTerminate)
{
{
Lock sync(*this);
timedWait(10000);
}
if (bTerminate)
{
return;
}
doSomething();
}
}
protected:
bool bTerminate;
};
int main(int argc, char *argv[])
{
try
{
MyThread mt;
mt.start();
mt.terminate();
mt.getThreadControl().join();
}
catch (exception& ex)
{
cout << ex.what() << endl;
}
return 0;
}
| 20.120879 | 92 | 0.575096 | [
"vector"
] |
0fc8c5e3cf1db6258b8c5902b5af96d976e6bb9b | 4,417 | cpp | C++ | dev/Code/Sandbox/Editor/SettingsBlock.cpp | crazyskateface/lumberyard | 164512f8d415d6bdf37e195af319ffe5f96a8f0b | [
"AML"
] | 5 | 2018-08-17T21:05:55.000Z | 2021-04-17T10:48:26.000Z | dev/Code/Sandbox/Editor/SettingsBlock.cpp | JulianoCristian/Lumberyard-3 | dc523dd780f3cd1874251181b7cf6848b8db9959 | [
"AML"
] | null | null | null | dev/Code/Sandbox/Editor/SettingsBlock.cpp | JulianoCristian/Lumberyard-3 | dc523dd780f3cd1874251181b7cf6848b8db9959 | [
"AML"
] | 5 | 2017-12-05T16:36:00.000Z | 2021-04-27T06:33:54.000Z | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#include "StdAfx.h"
#include "SettingsBlock.h"
#include "Serialization.h"
#include <Serialization/ITextInputArchive.h>
#include <Serialization/ITextOutputArchive.h>
using std::vector;
SProjectSettingsBlock* SProjectSettingsBlock::s_pLastBlock;
SProjectSettingsBlock::SProjectSettingsBlock(const char* name, const char* label)
: m_name(name)
, m_label(label)
{
m_pPrevious = s_pLastBlock;
s_pLastBlock = this;
}
struct SAllSettingsSerializer
{
void Serialize(Serialization::IArchive& ar)
{
SProjectSettingsBlock* pCurrent = SProjectSettingsBlock::s_pLastBlock;
while (pCurrent != 0)
{
ar(*pCurrent, pCurrent->GetName(), pCurrent->GetLabel());
pCurrent = pCurrent->m_pPrevious;
}
}
} static gAllSettingsSerializer;
void SProjectSettingsBlock::GetAllSettingsSerializer(Serialization::SStruct* pSerializer)
{
*pSerializer = Serialization::SStruct(gAllSettingsSerializer);
}
SProjectSettingsBlock* SProjectSettingsBlock::Find(const char* blockName)
{
SProjectSettingsBlock* pCurrent = SProjectSettingsBlock::s_pLastBlock;
while (pCurrent != 0)
{
if (_stricmp(pCurrent->GetName(), blockName) == 0)
{
return pCurrent;
}
}
return 0;
}
static bool ReadFileContent(vector<char>* pBuffer, const char* filename)
{
AZ::IO::HandleType fileHandle = gEnv->pCryPak->FOpen(filename, "rb");
if (fileHandle == AZ::IO::InvalidHandle)
{
return false;
}
size_t size = gEnv->pCryPak->FGetSize(fileHandle);
pBuffer->resize(size);
bool result = true;
if (gEnv->pCryPak->FRead(&(*pBuffer)[0], size, fileHandle) != size)
{
result = false;
}
gEnv->pCryPak->FClose(fileHandle);
return result;
}
static bool SaveFileContent(const char* filename, const char* pBuffer, size_t length)
{
string fullpath = Path::GamePathToFullPath(filename).toLatin1().data();
AZ::IO::HandleType fileHandle = AZ::IO::InvalidHandle;
if (!gEnv->pFileIO->Open(fullpath.c_str(), AZ::IO::GetOpenModeFromStringMode("wb"), fileHandle))
{
return false;
}
bool result = true;
if (!gEnv->pFileIO->Write(fileHandle, pBuffer, length))
{
result = false;
}
gEnv->pFileIO->Close(fileHandle);
return result;
}
static bool SaveFileContentIfDiffers(const char* filename, const char* pBuffer, size_t length)
{
vector<char> content;
ReadFileContent(&content, filename);
bool needToWrite = true;
if (!content.empty() && content.size() == length)
{
needToWrite = memcmp(&content[0], pBuffer, length) != 0;
}
if (needToWrite)
{
return SaveFileContent(filename, pBuffer, length);
}
else
{
return true;
}
}
bool SProjectSettingsBlock::Load()
{
const char* filename = GetFilename();
vector<char> content;
if (!ReadFileContent(&content, filename))
{
return false;
}
auto pArchive(Serialization::CreateTextInputArchive());
if (!pArchive)
{
return false;
}
if (!pArchive->AttachMemory(&content[0], content.size()))
{
return false;
}
Serialization::SStruct serializer;
GetAllSettingsSerializer(&serializer);
serializer(*pArchive);
return true;
}
bool SProjectSettingsBlock::Save()
{
const char* filename = GetFilename();
auto pArchive(Serialization::CreateTextOutputArchive());
if (!pArchive)
{
return false;
}
Serialization::SStruct serializer;
GetAllSettingsSerializer(&serializer);
serializer(*pArchive);
return SaveFileContentIfDiffers(filename, pArchive->GetBuffer(), pArchive->GetBufferLength());
}
const char* SProjectSettingsBlock::GetFilename()
{
return "SandboxSettings.json";
}
| 25.531792 | 100 | 0.676251 | [
"vector"
] |
0fc8db2a5a14be52ba83ab09873d43e4ba3d5a2d | 15,947 | cpp | C++ | lib/extern/gmatutil/util/LeapSecsFileReader.cpp | ryanketzner/sphericalpolygon | de7ab321382d192b86e7ad9527f025a143f3f3f7 | [
"Apache-2.0"
] | 4 | 2021-12-23T16:49:06.000Z | 2022-02-09T21:36:31.000Z | lib/extern/gmatutil/util/LeapSecsFileReader.cpp | ryanketzner/sphericalpolygon | de7ab321382d192b86e7ad9527f025a143f3f3f7 | [
"Apache-2.0"
] | 15 | 2022-01-14T17:28:14.000Z | 2022-02-11T02:39:25.000Z | lib/extern/gmatutil/util/LeapSecsFileReader.cpp | ryanketzner/sphericalpolygon | de7ab321382d192b86e7ad9527f025a143f3f3f7 | [
"Apache-2.0"
] | 1 | 2022-02-03T15:44:16.000Z | 2022-02-03T15:44:16.000Z | //$Id: LeapSecsFileReader.cpp 10525 2012-05-24 14:42:59Z wendys-dev $
//------------------------------------------------------------------------------
// LeapSecsFileReader
//------------------------------------------------------------------------------
// GMAT: General Mission Analysis Tool.
//
// Copyright (c) 2002 - 2020 United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration.
// All Other 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.
//
// Author: Allison R. Greene
// Created: 2005/01/26
//
/**
* Reads time coefficent file, creates a table of coefficients and converts
* to the utc.
*
* File found at : ftp://maia.usno.navy.mil/ser7/tai-utc.dat
*
* @note The MJD-JD offset used is GmatTimeConstants::JD_NOV_17_1858
*/
//------------------------------------------------------------------------------
#include "LeapSecsFileReader.hpp"
#include "MessageInterface.hpp"
#include "GmatConstants.hpp"
#include "RealUtilities.hpp"
#include "StringUtil.hpp"
#include "UtilityException.hpp"
#include <fstream>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <cstdlib> // Required for GCC 4.3
//#define DEBUG_READ_LEAP_SECS_FILE
//#define DEBUG_IN_LEAP_SECOND
//#define DEBUG_DUMP_DATA
//---------------------------------
// static data
//---------------------------------
// hard coded for now - need to allow user to set later
//std::string LeapSecsFileReader::withFileName = "tai-utc.dat";
//------------------------------------------------------------------------------
// public
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// LeapSecsFileReader()
//------------------------------------------------------------------------------
/**
* Constructor.
*/
//------------------------------------------------------------------------------
LeapSecsFileReader::LeapSecsFileReader(const std::string &fileName) :
withFileName (fileName)
{
isInitialized = false;
}
//------------------------------------------------------------------------------
// ~LeapSecsFileReader()
//------------------------------------------------------------------------------
/**
* Destructor.
*/
//------------------------------------------------------------------------------
LeapSecsFileReader::~LeapSecsFileReader()
{
}
//------------------------------------------------------------------------------
// bool Initialize()
//------------------------------------------------------------------------------
bool LeapSecsFileReader::Initialize()
{
std::ifstream instream;
try
{
if (!isInitialized)
{
instream.open(withFileName.c_str());
//if (instream == NULL)
if (!instream.is_open())
{
std::string errMsg = "Unable to locate leap second file "
+ withFileName + "\n";
throw UtilityException(errMsg);
}
bool isOK = true;
Integer numLinesParsed = 0;
while (!instream.eof())
{
std::string line;
getline(instream,line);
if (!GmatStringUtil::IsBlank(line, true))
{
if (!(isOK = Parse(line))) break;
numLinesParsed++;
}
}
// Why personalization data written to this file?
// Try closing before throwing an exception (LOJ: 2014.06.18)
// Moved from below
#ifdef DEBUG_LEAP_SECOND_FILE
MessageInterface::ShowMessage
("LeapSecsFileReader::Initialize() 1 Closing leap second file\n");
#endif
instream.close();
if (!isOK)
{
std::string errMsg = "Unable to read leap second file "
+ withFileName + " - file is malformed\n";
throw UtilityException(errMsg);
}
if (numLinesParsed == 0)
{
std::string errMsg = "Unable to read leap second file "
+ withFileName + " - file contains no data\n";
throw UtilityException(errMsg);
}
//instream.close();
}
}
catch (...)
{
if (instream.is_open())
{
#ifdef DEBUG_LEAP_SECOND_FILE
MessageInterface::ShowMessage
("LeapSecsFileReader::Initialize() 2 Closing leap second file\n");
#endif
instream.close();
}
//MessageInterface::PopupMessage(Gmat::WARNING_,
// "Unknown Error in LeapSecondFileReader");
// re-throw the exception
throw;
}
isInitialized = true;
return isInitialized;
}
//------------------------------------------------------------------------------
// Real NumberOfLeapSecondsFrom(UtcMjd utcMjd)
//------------------------------------------------------------------------------
/**
* Converts utcmjd to utcjd and then looks it up from the table. If file is not
* read, 0 is returned.
*
* @return number of leap seconds
* @note Assumes that JD from table is utcjd.
*/
//------------------------------------------------------------------------------
Real LeapSecsFileReader::NumberOfLeapSecondsFrom(UtcMjd utcMjd)
{
if (isInitialized)
{
Real jd = utcMjd + GmatTimeConstants::JD_MJD_OFFSET;
// look up each entry in the table to see if value is greater then the
// julian date
std::vector<LeapSecondInformation>::iterator info;
for (std::vector<LeapSecondInformation>::iterator i = lookUpTable.end();
i > lookUpTable.begin(); i--)
{
info = i-1;
if (jd >= info->julianDate)
{
return (info->offset1 + ((utcMjd - info->offset2) * info->offset3));
}
}
return 0.0;
}
else
return 0.0;
}
//------------------------------------------------------------------------------
// Real GetFirstLeapSecondMJD(Real fromUtcMjd, Real toUtcMjd)
//------------------------------------------------------------------------------
/**
* Returns UTCMJD of first leap seconds occurred between fromUtcMjd and toUtcMjd.
* If file is not read or fromUtcMjd is greater than toUtcMjd, or no leap seconds
* occurred between input dates, -1 is returned.
*
* @return First date of leap seconds occurred between two input dates
* @note Assumes that JD from table is utcjd.
*/
//------------------------------------------------------------------------------
Real LeapSecsFileReader::GetFirstLeapSecondMJD(Real fromUtcMjd, Real toUtcMjd)
{
#ifdef DEBUG_LEAP_SECOND
MessageInterface::ShowMessage
("LeapSecsFileReader::GetFirstLeapSecondMJD() entered, fromUtcMjd=%.12f, "
"toUtcMjd=%.12f, isInitialized=%d\n", fromUtcMjd, toUtcMjd, isInitialized);
#endif
Real firstMjd = -1.0;
if (isInitialized && (toUtcMjd >= fromUtcMjd))
{
Real fromJd = fromUtcMjd + GmatTimeConstants::JD_MJD_OFFSET;
Real toJd = toUtcMjd + GmatTimeConstants::JD_MJD_OFFSET;
Real currJd = 0.0;
RealArray utcMjdArray;
// look up each entry in the table to see if value is greater then the
// julian date
std::vector<LeapSecondInformation>::iterator info;
for (std::vector<LeapSecondInformation>::iterator i = lookUpTable.end();
i > lookUpTable.begin(); i--)
{
info = i-1;
currJd = info->julianDate;
if ((currJd >= fromJd) && (currJd <= toJd))
{
utcMjdArray.push_back(currJd);
}
else if (currJd < fromJd)
{
break;
}
}
// Compute MJD of first JD in the array
if (utcMjdArray.empty())
{
firstMjd = -1.0;
}
else
{
//Since iterator goes backward in the above for loop, larger jd is moved to front
firstMjd = utcMjdArray.back() - GmatTimeConstants::JD_MJD_OFFSET;
}
}
#ifdef DEBUG_LEAP_SECOND
MessageInterface::ShowMessage
("LeapSecsFileReader::GetFirstLeapSecondMJD() returning %.12f\n", firstMjd);
#endif
return firstMjd;
}
//------------------------------------------------------------------------------
// bool IsInLeapSecond(Real theTaiMjd)
// theTaiMjd is referenced to GmatTimeConstants::JD_NOV_17_1858
//------------------------------------------------------------------------------
bool LeapSecsFileReader::IsInLeapSecond(Real theTaiMjd)
{
bool isLeap = false;
// Find rhe nearest leap second to the input tai mjd time
Real nearestLeapSecond = 0.0;
// Is the time before or after the lookup table?
Integer sz = lookUpTable.size();
Real tai0 = lookUpTable.at(0).taiMJD;
Real taif = lookUpTable.at(sz-1).taiMJD;
#ifdef DEBUG_IN_LEAP_SECOND
MessageInterface::ShowMessage("In IsInLS, theTaiMjd = %12.10f\n", theTaiMjd);
MessageInterface::ShowMessage(" tai0 = %12.10f\n", tai0);
MessageInterface::ShowMessage(" taif = %12.10f\n", taif);
MessageInterface::ShowMessage(" one sec = %12.10f\n", 1.0 /GmatTimeConstants::SECS_PER_DAY);
#endif
// is this correct? or should it be 0.0 before the earliest time on the file?
if (theTaiMjd <= tai0)
nearestLeapSecond = tai0;
else if (theTaiMjd >= taif)
nearestLeapSecond = taif;
else
{
Real diff = GmatRealConstants::REAL_MAX;
Real currDiff = 0.0;
Real currTai = 0.0;
Real previousTai = taif;
Integer lookupSize = lookUpTable.size();
for (Integer ii = lookupSize - 1; ii >= 0; ii--)
{
currTai = lookUpTable.at(ii).taiMJD;
currDiff = GmatMathUtil::Abs(currTai - theTaiMjd);
// added '=' because if it's exactly in-between, we want the later one
// - is that correct?
if (currDiff >= diff)
{
nearestLeapSecond = previousTai;
break;
}
else // currDiff < diff so save it as the smallest diff so far
{
diff = currDiff;
previousTai = currTai;
if (ii == 0) // we've reached the end (beginning!) of the table
{
nearestLeapSecond = currTai;
}
}
}
}
if (nearestLeapSecond == 0.0) // something went wrong
{
std::string errMsg = "ERROR finding nearest leap second\n";
throw UtilityException(errMsg);
}
Real nearestMinusOne = nearestLeapSecond - (1.0/GmatTimeConstants::SECS_PER_DAY);
// Determine if the input time is within the leap second
if ((theTaiMjd >= nearestMinusOne) && (theTaiMjd < nearestLeapSecond))
isLeap = true;
#ifdef DEBUG_IN_LEAP_SECOND
MessageInterface::ShowMessage("---------- nearestLeapSecond = %12.10f\n", nearestLeapSecond);
MessageInterface::ShowMessage("---------- nearestMinusOne = %12.10f\n", nearestMinusOne);
MessageInterface::ShowMessage("---------- isLeap = %s\n", (isLeap? " true" : "false"));
#endif
return isLeap;
}
//------------------------------------------------------------------------------
// private methods
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// bool Parse()
//------------------------------------------------------------------------------
/**
* Parses each line to add leap second information to the table
*
* Format of the line is:
* YYYY MMM D =JD jDate TAI-UTC= off1 S + (MJD - off2) X off3 S
* @return true if the file parses successfully
*/
//------------------------------------------------------------------------------
bool LeapSecsFileReader::Parse(std::string line)
{
#ifdef DEBUG_READ_LEAP_SECS_FILE
MessageInterface::ShowMessage("Entering LeapSecsFileReader::Parse with line = %s\n", line.c_str());
#endif
Real jDate, off1, off2, off3;
// ignore blank lines
if (GmatStringUtil::IsBlank(line, true)) return true;
std::istringstream ss(line);
Integer year, day;
std::string month, equalsJD, tai_utc, S, plus, mjd, minus, closeParen, X, S2;
// clear error flags
ss.clear();
try
{
ss >> year >> month >> day >> equalsJD >> jDate >> tai_utc >> off1 >> S >> plus >> mjd >> minus >> off2 >> closeParen >> X >> off3 >> S2;
#ifdef DEBUG_READ_LEAP_SECS_FILE
MessageInterface::ShowMessage("Entering LeapSecsFileReader::Parse - data read from line are: \n");
MessageInterface::ShowMessage(" year = %d\n", year);
MessageInterface::ShowMessage(" month = %s\n", month.c_str());
MessageInterface::ShowMessage(" day = %d\n", day);
MessageInterface::ShowMessage(" equalsJD = %s\n", equalsJD.c_str());
MessageInterface::ShowMessage(" >>>jDate = %12.10f\n", jDate);
MessageInterface::ShowMessage(" tai_utc = %s\n", tai_utc.c_str());
MessageInterface::ShowMessage(" >>>off1 = %12.10f\n", off1);
MessageInterface::ShowMessage(" S = %s\n", S.c_str());
MessageInterface::ShowMessage(" plus = %s\n", plus.c_str());
MessageInterface::ShowMessage(" mjd = %s\n", mjd.c_str());
MessageInterface::ShowMessage(" minus = %s\n", minus.c_str());
MessageInterface::ShowMessage(" >>>off2 = %12.10f\n", off2);
MessageInterface::ShowMessage(" closeParen = %s\n", closeParen.c_str());
MessageInterface::ShowMessage(" X = %s\n", X.c_str());
MessageInterface::ShowMessage(" >>>off3 = %12.10f\n", off3);
MessageInterface::ShowMessage(" S2 = %s\n", S2.c_str());
if (ss.fail()) MessageInterface::ShowMessage(" ------ fail is true ------\n");
if (ss.bad()) MessageInterface::ShowMessage(" ------ bad is true ------\n");
if (ss.eof()) MessageInterface::ShowMessage(" ------ eof is true ------\n");
#endif
// if there was an error reading all of the items from the stream, return false
// don't check for eof here, as it will return true when it gets to the end of the line
if (ss.bad() || ss.fail()) return false;
// Convert to TAI time (MJD) here and store that as well
Real numLeapSeconds = off1 + ((jDate - off2) * off3);
Real taiDate = jDate - GmatTimeConstants::JD_MJD_OFFSET +
(numLeapSeconds/GmatTimeConstants::SECS_PER_DAY);
#ifdef DEBUG_DUMP_DATA
MessageInterface::ShowMessage(" LookUpTable(%d)::\n", (Integer) lookUpTable.size());
MessageInterface::ShowMessage(" jDate =============== %12.10f\n", jDate);
MessageInterface::ShowMessage(" taiDate =============== %12.10f\n", taiDate);
MessageInterface::ShowMessage(" off1 =============== %12.10f\n", off1);
MessageInterface::ShowMessage(" off2 =============== %12.10f\n", off2);
MessageInterface::ShowMessage(" off3 =============== %12.10f\n", off3);
#endif
LeapSecondInformation leapSecInfo = {jDate, taiDate, off1, off2, off3};
lookUpTable.push_back(leapSecInfo);
return true;
}
catch (BaseException &be)
{
return false;
}
}
| 37.434272 | 143 | 0.523045 | [
"vector"
] |
0fc99724c4f1e303661e2723057553fb20f15a6c | 87,883 | cpp | C++ | king/rplot.cpp | statgen/topmed_variant_calling | cfd0242eada5a0c6ddd73695af22fa47af20f010 | [
"Apache-2.0"
] | 14 | 2018-09-06T18:04:33.000Z | 2021-09-17T16:27:27.000Z | king/rplot.cpp | statgen/topmed_variant_calling | cfd0242eada5a0c6ddd73695af22fa47af20f010 | [
"Apache-2.0"
] | 6 | 2018-10-03T21:37:46.000Z | 2022-01-17T08:43:53.000Z | king/rplot.cpp | statgen/topmed_variant_calling | cfd0242eada5a0c6ddd73695af22fa47af20f010 | [
"Apache-2.0"
] | 5 | 2019-05-14T18:30:22.000Z | 2021-12-13T22:06:09.000Z | //////////////////////////////////////////////////////////////////////
// rplot.cpp
// (c) 2010-2019 Wei-Min Chen
//
// This file is distributed as part of the KING source code package
// and may not be redistributed in any form, without prior written
// permission from the author. Permission is granted for you to
// modify this file for your own personal use, but modified versions
// must retain this copyright notice and must not be distributed.
//
// Permission is granted for you to use this file to compile KING.
//
// All computer programs have bugs. Use this file at your own risk.
//
// March 28, 2019
#include "rplot.h"
#include "MathMatrix.h"
#include "StringArray.h"
int CheckRout(const char *scriptfile);
void plotIBD1vsIBD2(const char *prefix, FILE *fp);
void plotMIerror(const char *prefix)
{
String scriptfile=prefix;
scriptfile.Add("_MIerrorplot.R");
FILE *fp = fopen(scriptfile, "wt");
if(fp == NULL) error("Cannot open %s to write.", (const char*)scriptfile);
fprintf(fp, "## %s for KING MI error plot, by Wei-Min Chen and Zhennan Zhu\n", (const char*)scriptfile);
fprintf(fp, "library(kinship2)\n");
fprintf(fp, "library(igraph)\n");
fprintf(fp, "ped <- read.table(file=\"%ssplitped.txt\", stringsAsFactors=FALSE)[,c(1,2,5,6,7,8,9)]\n", (const char*)prefix);
fprintf(fp, "ped$V8[ped$V8==-9 | ped$V8==0 | ped$V8==1] <- 0\n");
fprintf(fp, "ped$V8[ped$V8==2] <- 1\n");
fprintf(fp, "colnames(ped) <- c(\"FID\", \"ID\", \"FA\", \"MO\", \"Sex\", \"Affected\", \"Status\")\n");
fprintf(fp, "data <- read.table(\"%s.kin\",header = TRUE, stringsAsFactors = FALSE)\n", (const char*)prefix);
fprintf(fp, "mi.err <- data[data[, \"Error\"]==1, \"FID\" ]\n");
fprintf(fp, "Inf.color <- c(\"purple\", \"red\", \"green\", \"blue\", \"yellow\")\n");
fprintf(fp, "Inf.type <- c(\"Dup/MZ\", \"PO\", \"FS\", \"2nd\", \"3rd\")\n");
fprintf(fp, "data.fam <- merge(data, ped, by.x = c(\"FID\", \"ID1\"), by.y = c(\"FID\", \"ID\"))\n");
fprintf(fp, "data.all <- merge(data.fam, ped, by.x = c(\"FID\", \"ID2\"), by.y = c(\"FID\", \"ID\"))[, c(\"FID\", \"ID1\", \"ID2\", \"Sex.x\", \"Sex.y\", \"InfType\")]\n");
fprintf(fp, "data.all <- data.all[data.all[, \"InfType\"] %%in%% Inf.type, ]\n");
fprintf(fp, "for (i in 1:5) data.all[data.all$InfType == Inf.type[i], 6] <- i\n");
fprintf(fp, "postscript(\"%s_MIerrorplot.ps\", paper=\"letter\", horizontal=T, fonts=c(\"serif\", \"Palatino\"))\n", (const char*)prefix);
fprintf(fp, "par(mfrow=c(1, 2))\n");
fprintf(fp, "for (famid in unique(mi.err)){\n");
fprintf(fp, " fam <- ped[ped[, \"FID\"]==famid,]\n");
fprintf(fp, "if (all(fam[, c(\"FA\", \"MO\")]==0)){\n");
fprintf(fp, " g.empty <- make_empty_graph(n = nrow(fam), directed = FALSE)\n");
fprintf(fp, " plot(g.empty, vertex.size=27, vertex.color=NA, vertex.label.cex=.5, vertex.label.dist=1.6,\n");
fprintf(fp, " vertex.label.degree= pi/2, vertex.label.color=\"black\", vertex.label= fam[,\"ID\"],\n");
fprintf(fp, " edge.color=NA, layout=layout_with_fr(g.empty, grid=\"nogrid\"), asp=0,\n");
fprintf(fp, " vertex.shape=c(\"none\", \"square\", \"circle\")[1+fam[,\"Sex\"]])}else{\n");
fprintf(fp, " pedplot <- pedigree(id = fam$ID, dadid = fam$FA, momid = fam$MO, sex = as.numeric(fam$Sex),\n");
fprintf(fp, " affected = as.numeric(fam$Affected), status = as.numeric(fam$Status), famid = fam$FID, missid = 0)\n");
fprintf(fp, " plot(pedplot[toString(famid)], cex = 0.5, symbolsize = 2.8)}\n");
fprintf(fp, " fam.sub <- data.all[data.all$FID==famid,][, 2:6]\n");
fprintf(fp, " id <- unique(mapply(c, fam.sub[,c(1,3)], fam.sub[,c(2, 4)]))\n");
fprintf(fp, " g <- graph_from_data_frame(d=fam.sub, vertices=id[, 1], directed=FALSE)\n");
fprintf(fp, " plot(g, edge.width=1.5, vertex.size=27, vertex.color=NA, vertex.label.cex=0.5,\n");
fprintf(fp, " edge.color=Inf.color[as.numeric(fam.sub$InfType)], layout=layout_with_fr(g, grid=\"nogrid\"), asp=0,\n");
fprintf(fp, " vertex.shape=c(\"none\", \"square\", \"circle\")[1+as.numeric(id[, 2])], margin=0.3)\n");
fprintf(fp, " legend(\"bottomright\", Inf.type, lty=1, col=Inf.color, text.col=Inf.color, cex=0.7, bty=\"n\")\n");
fprintf(fp, " mtext(paste(\"Documented versus Inferred Family\", famid, \"in %s\"), side = 3, line = -2, outer = TRUE)}\n", (const char*)prefix);
fprintf(fp, "dev.off()\n");
fclose(fp);
char command[256];
sprintf(command, "R CMD BATCH %s", (const char*)scriptfile);
system(command);
int error = CheckRout(scriptfile);
switch(error){
case 3: printf("R plot failed for missing R libraries kinship2/igraph .\n");
printf(" Please rerun R code %s (or KING) after kinship2/igraph is installed.\n", (const char*)scriptfile);
break;
case 2: printf("R code %s failed.\n", (const char*)scriptfile);
break;
case 1: printf("R code %s failed.\n", (const char*)scriptfile);
printf(" Please check %sout for details.\n", (const char*)scriptfile);
break;
case 0: sprintf(command, "ps2pdf %s_MIerrorplot.ps", (const char*)prefix);
system(command);
printf("MI error plots are generated in %s_MIerrorplot.pdf\n", (const char*)prefix);
break;
default: printf("Unexpected error. Please contact KING authors.\n");
}
}
void plotUniqueFamily(const char *prefix, int degree, const char *analysis)
{
if(analysis != "related" && analysis != "ibdseg") return;
String inputfile = prefix;
if(analysis == "related") inputfile.Add(".kin0");
else inputfile.Add(".seg");
String scriptfile=prefix;
scriptfile.Add("_uniqfamplot.R");
FILE *fp = fopen(scriptfile, "wt");
if(fp == NULL) error("Cannot open %s to write.", (const char*)scriptfile);
fprintf(fp, "## %s for KING --%s, by Wei-Min Chen and Zhennan Zhu\n", (const char*)scriptfile, (const char*)analysis);
fprintf(fp, "library(igraph)\n");
fprintf(fp, "data <- read.table(file=\"%s\", header=TRUE, stringsAsFactors=FALSE)[,c(\"ID1\", \"ID2\", \"InfType\")]\n", (const char*)inputfile);
fprintf(fp, "Inf.color <- c(\"purple\", \"red\", \"green\", \"blue\")\n");
fprintf(fp, "Inf.type <- c(\"Dup/MZ\", \"PO\", \"FS\", \"2nd\")\n");
fprintf(fp, "relatives <- data[data$InfType %%in%% Inf.type, ]\n");
fprintf(fp, "for (i in 1:length(Inf.type)) relatives[relatives$InfType == Inf.type[i], \"InfType\"] <- i\n");
fprintf(fp, "colnames(relatives)[3] <- \"color\"\n");
fprintf(fp, "BuildPed <- function(v){\n");
fprintf(fp, " buildType <- \"\"\n");
fprintf(fp, " if(v[1]==3 && v[2]==3 && v[4]==2 && v[6]==1) buildType <- \"2_GG/HalfSibs\"\n");
fprintf(fp, " else if(v[1]==3 && v[2]==3 && v[3]==1 && v[4]==2) buildType <- \"2_MZtwins+1_Parent/Child\"\n");
fprintf(fp, " else if(v[1]==4 && v[2]==5 && v[3]==1 && v[4]==4) buildType <- \"2_Parents+2_MZtwins\"\n");
fprintf(fp, " if(v[5]>0){\n");
fprintf(fp, " s <- floor(sqrt(v[5]*2))+1\n");
fprintf(fp, " if(s*(s-1)/2==v[5]){\n");
fprintf(fp, " if(v[2]==v[5] && v[4]==0) buildType <- paste(s, \"_FullSiblings\", sep=\"\")\n");
fprintf(fp, " else if(v[2]==v[5]+s && v[4]==s) buildType <- paste(\"1_Parent+\", s, \"_FullSiblings\", sep=\"\")\n");
fprintf(fp, " else if(v[2]==v[5]+s*2 && v[4]==s*2) buildType <- paste(\"2_Parents+\", s, \"_FullSiblings\", sep=\"\")\n");
fprintf(fp, " else buildType <- paste(s, \"_FullSiblings+\", v[1]-s, \"_Relatives\", sep=\"\")\n");
fprintf(fp, " }else if(v[3]==0 && v[4]==0 && v[6]==0) buildType <- \"Undetermined_FS_Only\"\n");
fprintf(fp, " else buildType <- \"Undetermined_FS\"\n");
fprintf(fp, " }else if(v[4]==0 && v[6]==0){\n");
fprintf(fp, " buildType <- ifelse(v[3]==1, \"2_MZtwins\", \"Undetermined_MZ_Only\")\n");
fprintf(fp, " }else if(v[3]==0 && v[4]==0){\n");
fprintf(fp, " buildType <- ifelse(v[6]==1, \"2_Second-Degree_Relatives\", \"Undetermined_2nd_Only\")\n");
fprintf(fp, " }else if(v[3]==0 && v[6]==0){\n");
fprintf(fp, " if(v[4]==1) buildType <- \"1_Parent+1_Child\"\n");
fprintf(fp, " else if(v[4]==2) buildType <- \"2_Parents+1_Child(Trio)\"\n");
fprintf(fp, " else buildType <- \"Undetermined_PO_Only\"}\n");
fprintf(fp, "if(buildType==\"\"){\n");
fprintf(fp, " if(v[3]>0) buildType <- \"Undetermined_MZ\"\n");
fprintf(fp, " else if(v[4]>0) buildType <- \"Undetermined_PO\"}\n");
fprintf(fp, " return(buildType)\n");
fprintf(fp, "}\n");
fprintf(fp, "g <- graph_from_data_frame(d = relatives, vertices = unique(c(relatives$ID1, relatives$ID2)), directed = FALSE)\n");
fprintf(fp, "imc <- cluster_infomap(g)\n");
fprintf(fp, "imc.membership <- membership(imc)\n");
fprintf(fp, "community.info <- cbind(imc$membership,imc$names)\n");
fprintf(fp, "colnames(community.info) <- c(\"membership\", \"ID\")\n");
fprintf(fp, "community.rel <- merge(relatives, community.info, by.x = c(\"ID1\"), by.y = c(\"ID\"))\n");
fprintf(fp, "community.rel$membership <- as.numeric(as.character(community.rel$membership))\n");
fprintf(fp, "color_counts <- function(i) {\n");
fprintf(fp, " sub.colors <- community.rel[community.rel[, \"membership\"]==i, \"color\"]\n");
fprintf(fp, " return(sapply(1:4, function(y) sum(sub.colors==y)))}\n");
fprintf(fp, "colors <- t(sapply(1:length(imc), color_counts))\n");
fprintf(fp, "fam.info <- cbind(community.index=1:length(imc), sizes.node = sizes(imc), edge.colors=apply(colors, 1, sum), colors)\n");
fprintf(fp, "fam.info <- as.data.frame(fam.info)\n");
fprintf(fp, "all.counts <- aggregate(cbind(fam.info[0],counts=1),fam.info[,-1], length)\n");
fprintf(fp, "fam.info.counts <- merge(fam.info, all.counts, by= c(\"sizes.node\",\"edge.colors\",\"V4\",\"V5\",\"V6\",\"V7\"))\n");
fprintf(fp, "uniq.fam.info <- fam.info.counts[!duplicated(fam.info.counts[, c(1:6,8)]), ][,c(7, 1:6, 8)]\n");
fprintf(fp, "uniq.fam.info <- uniq.fam.info[order(uniq.fam.info$counts,decreasing=TRUE),]\n");
fprintf(fp, "all.counts <- uniq.fam.info[,\"counts\"]\n");
fprintf(fp, "uniq.cluster <- induced_subgraph(g, (1:length(V(g)))[imc.membership %%in%% uniq.fam.info[, \"community.index\"]])\n");
fprintf(fp, "all.names <- sapply(V(uniq.cluster)$name, function(x) membership(imc)[names(imc.membership)%%in%%x])\n");
fprintf(fp, "all.builds <- apply((uniq.fam.info[, -1]),1,BuildPed)\n");
fprintf(fp, "lo <- layout_(uniq.cluster, with_fr(), normalize())\n");
fprintf(fp, "LocationForACluster<-function(x){\n");
fprintf(fp, " lo.local <- lo[all.names==x,]\n");
fprintf(fp, " return(c(min(as.numeric(lo.local[,1])), max(as.numeric(lo.local[,1])), max(as.numeric(lo.local[,2]))))}\n");
fprintf(fp, "locations <- sapply(uniq.fam.info[, 1], LocationForACluster)\n");
fprintf(fp, "postscript(\"%s_uniqfamplot.ps\", paper=\"letter\", horizontal=T)\n", prefix);
fprintf(fp, "plot(uniq.cluster, vertex.color=NA, vertex.size=1, vertex.label=NA, layout=lo, asp=0,\n");
fprintf(fp, " edge.color=Inf.color[as.numeric(E(uniq.cluster)$color)], main=\"All Unique Family Configurations in %s\")\n", prefix);
fprintf(fp, "text((locations[1,]+locations[2,])/2, locations[3,]+0.04, all.counts)\n");
fprintf(fp, "legend(\"bottomright\", Inf.type, lty = 1, col = Inf.color, text.col = Inf.color, cex = 0.7, bty = \"n\")\n");
if(degree>1){
fprintf(fp, "par(mfrow=c(2,3))\n");
fprintf(fp, "is.built <- all.builds!=\"\"\n");
fprintf(fp, "for(i in uniq.fam.info[, 1][is.built]){\n");
fprintf(fp, " index <- (1:length(uniq.fam.info[, 1]))[uniq.fam.info[, 1]==i]\n");
fprintf(fp, " g1 <- induced_subgraph(g, (1:length(V(g)))[imc.membership == i])\n");
fprintf(fp, " if(substr(all.builds[index],1,12)!=\"Undetermined\"&&all.counts[index]>1||all.counts[index]>10)\n");
fprintf(fp, " plot(g1, vertex.color=NA, vertex.size=3, vertex.label=NA, layout=layout_with_fr, asp=0,\n");
fprintf(fp, " edge.color=Inf.color[as.numeric(edge.attributes(g1)$color)], main=paste(all.counts[index], all.builds[index], \"Families\"))}\n");
}
fprintf(fp, "dev.off()\n");
fclose(fp);
char command[256];
sprintf(command, "R CMD BATCH %s", (const char*)scriptfile);
system(command);
if(!CheckRout(scriptfile)){
sprintf(command, "ps2pdf %s_uniqfamplot.ps", prefix);
system(command);
printf("Unique family plot is generated in %s_uniqfamplot.pdf\n\n", prefix);
}
}
void plotDuplicate(const char *prefix)
{
String scriptfile=prefix;
scriptfile.Add("_duplicateplot.R");
FILE *fp = fopen(scriptfile, "wt");
if(fp == NULL) error("Cannot open %s to write.", (const char*)scriptfile);
fprintf(fp, "## %s for KING --duplicate, by Wei-Min Chen and Zhennan Zhu\n", (const char*)scriptfile);
fprintf(fp, "library(igraph)\n");
fprintf(fp, "data <- read.table(file=\"%s.con\", header=TRUE, stringsAsFactors=FALSE)[,c(2,4)]\n", prefix);
fprintf(fp, "if(dim(data)[1]==0) q()\n");
fprintf(fp, "postscript(\"%s_duplicateplot.ps\", paper=\"letter\", horizontal=T, fonts=c(\"serif\", \"Palatino\"))\n", prefix);
fprintf(fp, "if(substr(data[1,1],1,4)==\"QRY_\"||substr(data[1,1],1,4)==\"REF_\"||substr(data[1,2],1,4)==\"QRY_\"||substr(data[1,2],1,4)==\"REF_\"){\n");
fprintf(fp, " ordered <- rbind(data[substr(data[,1],1,3)==\"QRY\" & substr(data[,2],1,3)==\"REF\", c(1,2)],\n");
fprintf(fp, " data[substr(data[,1],1,3)==\"REF\" & substr(data[,2],1,3)==\"QRY\", c(2,1)])\n");
fprintf(fp, " ordered <- cbind(substr(ordered[,1],5,1000),substr(ordered[,2],5,1000))\n");
fprintf(fp, " mismatched <- ordered[ordered[,1]!=ordered[,2],]\n");
fprintf(fp, " if(dim(mismatched)[1]==0) q()\n");
fprintf(fp, " g <- graph_from_data_frame(d=mismatched, vertices=unique(c(mismatched[,1],mismatched[,2])), directed=TRUE)\n");
fprintf(fp, " plot(g, vertex.shape=\"none\", vertex.label.cex=0.5, edge.arrow.size=0.3,\n");
fprintf(fp, " layout=layout_with_fr, asp=0, main=paste(dim(mismatched)[1], \"Pairs Are Matched (QUERY<-REF) in %s\"))\n", prefix);
fprintf(fp, "}else{\n");
fprintf(fp, "g <- graph_from_data_frame(d=data, vertices=unique(c(data$ID1,data$ID2)), directed=FALSE)\n");
fprintf(fp, "if(dim(data)[1]<500) {plot(g, vertex.shape=\"none\", vertex.label.cex=0.5,\n");
fprintf(fp, " layout=layout_with_fr, asp=0, main=paste(dim(data)[1], \"Duplicate Pairs in %s\"))\n", prefix);
fprintf(fp, "}else{g2 <- induced_subgraph(g, c((1:length(V(g)))[degree(g)>1],(1:length(V(g)))[degree(g)==1])[1:200])\n");
fprintf(fp, "plot(g2, vertex.shape=\"none\", vertex.label.cex=0.5, layout=layout_with_fr, asp=0, main=paste(\"200 Duplicates in %s\"))}}\n", prefix);
fprintf(fp, "dev.off()\n");
fclose(fp);
char command[256];
sprintf(command, "R CMD BATCH %s", (const char*)scriptfile);
system(command);
int error = CheckRout(scriptfile);
switch(error){
case 3: printf("--duplicate is done but R plot failed for missing R library igraph.\n");
printf(" Please intall igraph and run R code %s (or KING) again.\n\n", (const char*)scriptfile);
break;
case 2: printf("--duplicate is done but R code %s failed.\n\n", (const char*)scriptfile);
break;
case 1: printf("--duplicate is done but R code %s failed.\n", (const char*)scriptfile);
printf(" Please check %sout for details.\n\n", (const char*)scriptfile);
break;
case 0: sprintf(command, "ps2pdf %s_duplicateplot.ps", prefix);
system(command);
printf("Duplicate plot is generated in %s_duplicateplot.pdf\n\n", prefix);
break;
default: printf("Unexpected error. Please contact KING authors.\n");
}
}
void plotCluster(const char *prefix)
{
String scriptfile=prefix;
scriptfile.Add("_clusterplot.R");
FILE *fp = fopen(scriptfile, "wt");
if(fp == NULL) error("Cannot open %s to write.", (const char*)scriptfile);
fprintf(fp, "## %s for KING --cluster, by Wei-Min Chen and Zhennan Zhu\n", (const char*)scriptfile);
fprintf(fp, "library(igraph)\n");
fprintf(fp, "data <- read.table(file=\"%scluster.kin\", header=TRUE, stringsAsFactors=FALSE)\n", (const char*)prefix);
fprintf(fp, "postscript(\"%s_clusterplot.ps\", paper=\"letter\", horizontal=T, fonts=c(\"serif\", \"Palatino\"))\n", (const char*)prefix);
fprintf(fp, "Inf.color <- c(\"purple\", \"red\", \"green\", \"blue\", \"yellow\")\n");
fprintf(fp, "Inf.type <- c(\"Dup/MZ\", \"PO\", \"FS\", \"2nd\", \"3rd\")\n");
fprintf(fp, "for(famid in unique(data$FID)){\n");
fprintf(fp, " fam <- data[data$FID==famid & data$InfType %%in%% Inf.type,][,c(2,3,4,5,15)]\n");
fprintf(fp, " id <- unique(mapply(c, fam[,c(1,3)], fam[,c(2,4)]))\n");
fprintf(fp, " for(i in 1:5) fam[fam$InfType==Inf.type[i],5] <- i\n");
fprintf(fp, " g <- graph_from_data_frame(d=fam, vertices=id[,1], directed=FALSE)\n");
fprintf(fp, " plot(g, edge.width=1.5, vertex.size=4, vertex.color=NA, vertex.label.cex=0.5,\n");
fprintf(fp, " edge.color=Inf.color[as.numeric(fam$InfType)], layout=layout_with_fr(g,grid=\"nogrid\"), asp=0,\n");
fprintf(fp, " vertex.shape=c(\"none\",\"square\",\"circle\")[1+as.numeric(id[,2])])\n");
fprintf(fp, " legend(\"bottomright\", Inf.type, lty=1, col=Inf.color, text.col=Inf.color, pt.cex=2, cex=0.8, bty=\"n\")\n");
fprintf(fp, "}\n");
fprintf(fp, "dev.off()\n");
fclose(fp);
char command[256];
sprintf(command, "R CMD BATCH %s", (const char*)scriptfile);
system(command);
int error = CheckRout(scriptfile);
switch(error){
case 3: printf("--cluster is done but R plot failed for missing R library igraph.\n");
printf(" Please intall igraph and run R code %s (or KING) again.\n\n", (const char*)scriptfile);
break;
case 2: printf("--cluster is done but R code %s failed.\n\n", (const char*)scriptfile);
break;
case 1: printf("--cluster is done but R code %s failed.\n", (const char*)scriptfile);
printf(" Please check %sout for details.\n\n", (const char*)scriptfile);
break;
case 0: sprintf(command, "ps2pdf %s_clusterplot.ps", (const char*)prefix);
system(command);
printf("Plots of newly clustered families are generated in %s_clusterplot.pdf\n\n", (const char*)prefix);
break;
default: printf("Unexpected error. Please contact KING authors.\n");
}
}
void plotSplitped(const char *prefix)
{
String scriptfile=prefix;
scriptfile.Add("_pedplot.R");
FILE *fp = fopen(scriptfile, "wt");
if(fp == NULL) error("Cannot open %s to write.", (const char*)scriptfile);
fprintf(fp, "## %s for KING pedigree plot, by Wei-Min Chen and Zhennan Zhu\n", (const char*)scriptfile);
fprintf(fp, "library(kinship2)\n");
fprintf(fp, "ped <- read.table(file=\"%ssplitped.txt\", stringsAsFactors=FALSE)[,3:9]\n", (const char*)prefix);
fprintf(fp, "postscript(\"%s_pedplot.ps\", paper=\"letter\", horizontal=T)\n",(const char*)prefix);
// fprintf(fp, "ped$V8[ped$V8==-9 | ped$V8==0] <- NA\n");
// fprintf(fp, "ped$V8[ped$V8==1] <- 0\n");
fprintf(fp, "ped$V8[ped$V8==-9 | ped$V8==0 | ped$V8==1] <- 0\n");
fprintf(fp, "ped$V8[ped$V8==2] <- 1\n");
fprintf(fp, "pedAll <- pedigree(id = ped$V4, dadid = ped$V5, momid = ped$V6, sex = as.numeric(ped$V7), affected = as.numeric(ped$V8), status = as.numeric(ped$V9), famid = ped$V3, missid = 0)\n");
fprintf(fp, "for(f in unique(ped$V3))\n");
fprintf(fp, " if(any(ped$V5[ped$V3 == f] != 0 | ped$V6[ped$V3 == f] != 0))\n");
fprintf(fp, " plot(pedAll[toString(f)], cex=0.5, symbolsize = 2.8)\n");
fprintf(fp, "dev.off()\n");
fclose(fp);
char command[256];
sprintf(command, "R CMD BATCH %s", (const char*)scriptfile);
system(command);
int error = CheckRout(scriptfile);
switch(error){
case 3: printf("R plot failed for missing R library kinship2.\n");
printf(" Please rerun R code %s (or KING) after kinship2 is installed.\n\n", (const char*)scriptfile);
break;
case 2: printf("R code %s failed.\n\n", (const char*)scriptfile);
break;
case 1: printf("R code %s failed.\n", (const char*)scriptfile);
printf(" Please check %sout for details.\n\n", (const char*)scriptfile);
break;
case 0: sprintf(command, "ps2pdf %s_pedplot.ps", (const char*)prefix);
system(command);
printf("Pedigree plots are generated in %s_pedplot.pdf\n\n", (const char*)prefix);
break;
default: printf("Unexpected error. Please contact KING authors.\n");
}
}
void plotBuild(const char *prefix)
{
String scriptfile=prefix;
scriptfile.Add("_buildplot.R");
FILE *fp = fopen(scriptfile, "wt");
if(fp == NULL) error("Cannot open %s to write.", (const char*)scriptfile);
fprintf(fp, "## %s for KING --build, by Wei-Min Chen and Zhennan Zhu\n", (const char*)scriptfile);
fprintf(fp, "library(kinship2)\n");
fprintf(fp, "ped <- read.table(file=\"%supdateparents.txt\", stringsAsFactors=FALSE)\n", (const char*)prefix);
fprintf(fp, "ped$V6[ped$V6==-9 | ped$V6==0 | ped$V6==1] <- 0\n");
fprintf(fp, "ped$V6[ped$V6==2] <- 1\n");
fprintf(fp, "pedAll <- pedigree(id = ped$V2, dadid = ped$V3, momid = ped$V4, sex = as.numeric(ped$V5), affected = as.numeric(ped$V6), status = as.numeric(ped$V7), famid = ped$V1, missid = 0)\n");
fprintf(fp, "postscript(\"%s_buildplot.ps\", paper=\"letter\", horizontal=T)\n",(const char*)prefix);
fprintf(fp, "for(f in unique(ped$V1))\n");
fprintf(fp, " if(any(ped$V3[ped$V1 == f] != 0 | ped$V4[ped$V1 == f] != 0))\n");
fprintf(fp, " plot(pedAll[toString(f)], cex=0.5)\n");
fprintf(fp, "dev.off()\n");
fclose(fp);
char command[256];
sprintf(command, "R CMD BATCH %s", (const char*)scriptfile);
system(command);
int error = CheckRout(scriptfile);
switch(error){
case 3: printf("--build is done but R plot failed for missing R library kinship2.\n");
printf(" Please install kinship2 and run R code %s (or KING) again.\n\n", (const char*)scriptfile);
break;
case 2: printf("--build is done but R code %s failed.\n\n", (const char*)scriptfile);
break;
case 1: printf("--build is done but R code %s failed.\n", (const char*)scriptfile);
printf(" Please check %sout for details.\n\n", (const char*)scriptfile);
break;
case 0: sprintf(command, "ps2pdf %s_buildplot.ps", (const char*)prefix);
system(command);
printf("Plots of newly reconstruction pedigrees are generated in %s_buildplot.pdf\n\n", (const char*)prefix);
break;
default: printf("Unexpected error. Please contact KING authors.\n");
}
}
void plotHEreg(const char *prefix, int SEXCHR)
{
String scriptfile=prefix;
scriptfile.Add("_herplot.R");
FILE *fp = fopen(scriptfile, "wt");
if(fp == NULL) error("Cannot open %s to write.", (const char*)scriptfile);
fprintf(fp, "## %s for KING --hereg, by Wei-Min Chen\n", (const char*)scriptfile);
fprintf(fp, "postscript(\"%s_herplot.ps\", paper=\"letter\", horizontal=T)\n",(const char*)prefix);
fprintf(fp, "data<-c()\n");
fprintf(fp, "if(file.exists(\"%s.her\")) data <- read.table(file=\"%s.her\", header=T)\n",
(const char*)prefix,(const char*)prefix);
fprintf(fp, "if(length(data$LOD)>0){\n");
fprintf(fp, "alltraits <- as.character(data$Trait)\n");
fprintf(fp, "uniqtraits <- unique(alltraits)\n");
fprintf(fp, "for(trait in uniqtraits){\n");
fprintf(fp, "localdata <- data[alltraits==trait,]\n");
fprintf(fp, "Pos <- localdata$Pos\n");
fprintf(fp, "baseStop <- c()\n");
fprintf(fp, "base <- 0\n");
fprintf(fp, "for(i in 1:%d){\n", SEXCHR-1);
fprintf(fp, " Pos[localdata$Chr==i] <- localdata$Pos[localdata$Chr==i] + base\n");
fprintf(fp, " base <- base + max(0, localdata$Pos[localdata$Chr==i])\n");
fprintf(fp, " baseStop <- c(baseStop, base)\n");
fprintf(fp, "}\n");
fprintf(fp, "baseStart <- c(0, baseStop[-%d])\n", SEXCHR-1);
fprintf(fp, "baseMiddle <- (baseStart + baseStop)/2\n");
fprintf(fp, "LOD=localdata$LOD\n");
fprintf(fp, "plot(Pos, LOD, type=\"l\", xlab=\"Chromosome\", ylab = \"LOD Score\", xaxt = 'n',\n");
fprintf(fp, " cex = 1.5, cex.axis=1.5, cex.main=1.5, cex.lab = 1.5, cex.sub = 1.5,\n");
fprintf(fp, " ylim=c(0, min(max(LOD),10)),\n");
fprintf(fp, " lwd = 1.5, main = paste(\"Haseman-Elston Regression for Trait\" , trait))\n", (const char*)prefix);
fprintf(fp, "base <- 0\n");
fprintf(fp, "oldlocaldata <- localdata\n");
fprintf(fp, "for(i in 1:%d){\n", SEXCHR-1);
fprintf(fp, "localdata <- oldlocaldata[oldlocaldata$Chr==i,]\n");
fprintf(fp, "repeat{\n");
fprintf(fp, "maxLOD <- max(0,localdata$LOD)\n");
fprintf(fp, "if(maxLOD >= 2.2){\n");
fprintf(fp, "localpos.max <- median(localdata$Pos[localdata$LOD==maxLOD])\n");
fprintf(fp, "text(base+localpos.max, min(maxLOD,10)-0.1, paste(i, \":\", localpos.max, sep=\"\"), col=\"red\")\n");
fprintf(fp, "}\n");
fprintf(fp, "if(maxLOD >= 2.2) localdata$LOD[localdata$Pos > localpos.max - 10 & localdata$Pos < localpos.max + 10] <- 0;\n");
fprintf(fp, "if(maxLOD < 2.2) break\n");
fprintf(fp, "}\n");
fprintf(fp, " base <- base + max(0, localdata$Pos)\n");
fprintf(fp, "}\n");
fprintf(fp, "axis(1, labels=FALSE, line = 0, at = c(0,baseStop))\n");
fprintf(fp, "axis(1, labels=c(1:%d), line = -0.5, lty=\"blank\", at = baseMiddle)\n", SEXCHR-1);
fprintf(fp, "abline(h = 3.6, lty = 2, col=\"red\")\n");
fprintf(fp, "abline(h = 2.2, lty = 3, col=\"green\")\n");
fprintf(fp, "}\n");
fprintf(fp, "dev.off()\n");
fprintf(fp, "}\n");
fclose(fp);
char command[256];
sprintf(command, "R CMD BATCH %s", (const char*)scriptfile);
system(command);
int error = CheckRout(scriptfile);
if(error == 2)
printf("--hereg is done but R code %s failed.\n\n", (const char*)scriptfile);
else if(error){
printf("--hereg is done but R code %s failed.\n", (const char*)scriptfile);
printf(" Please check %sout for details.\n\n", (const char*)scriptfile);
}else{
sprintf(command, "ps2pdf %s_herplot.ps", (const char*)prefix);
system(command);
printf("Haseman-Elston regression plots are generated in %s_herplot.pdf\n", (const char*)prefix);
}
}
void plotPopROH(const char *prefix, int SEXCHR)
{
String scriptfile=prefix;
scriptfile.Add("_poprohplot.R");
FILE *fp = fopen(scriptfile, "wt");
if(fp == NULL) error("Cannot open %s to write.", (const char*)scriptfile);
fprintf(fp, "## %s for KING --poproh, by Wei-Min Chen\n", (const char*)scriptfile);
fprintf(fp, "postscript(\"%s_poprohplot.ps\", paper=\"letter\", horizontal=T)\n",
(const char*)prefix);
fprintf(fp, "data<-c()\n");
fprintf(fp, "if(file.exists(\"%s.rohdiff\")) data <- read.table(file=\"%s.rohdiff\", header=T)\n",
(const char*)prefix,(const char*)prefix);
fprintf(fp, "if(length(data$LOD)>0){\n");
fprintf(fp, "N <- max(data$Pop_Pos)\n");
fprintf(fp, "label.pop <- 1:N\n");
fprintf(fp, "for(p1 in 1:(N-1)){\n");
fprintf(fp, " for(p2 in (p1+1):N){\n");
fprintf(fp, "localdata <- data[data$Pop_Neg == p1 & data$Pop_Pos == p2,]\n");
fprintf(fp, "Pos <- localdata$Pos\n");
fprintf(fp, "baseStop <- c()\n");
fprintf(fp, "base <- 0\n");
fprintf(fp, "for(i in 1:%d){\n", SEXCHR-1);
fprintf(fp, " Pos[localdata$Chr==i] <- localdata$Pos[localdata$Chr==i] + base\n");
fprintf(fp, " base <- base + max(0, localdata$Pos[localdata$Chr==i])\n");
fprintf(fp, " baseStop <- c(baseStop, base)\n");
fprintf(fp, "}\n");
fprintf(fp, "baseStart <- c(0, baseStop[-%d])\n", SEXCHR-1);
fprintf(fp, "baseMiddle <- (baseStart + baseStop)/2\n");
fprintf(fp, "LOD=localdata$LOD\n");
fprintf(fp, "plot(Pos, LOD, type=\"l\", xlab=\"Chromosome\", ylab = \"LOD Score\", xaxt = 'n',\n");
fprintf(fp, " cex = 1.5, cex.axis=1.5, cex.main=1.5, cex.lab = 1.5, cex.sub = 1.5, lwd = 1.5,\n");
fprintf(fp, " main = paste(\"ROH difference in \", label.pop[p1], \" (-) and \", label.pop[p2], \" (+)\", sep=\"\"),\n");
fprintf(fp, " ylim=c(max(min(LOD),-10), min(max(LOD),10)))\n");
fprintf(fp, "base <- 0\n");
fprintf(fp, "for(i in 1:%d){\n", SEXCHR-1);
fprintf(fp, "maxLOD <- max(0,localdata$LOD[localdata$Chr==i])\n");
fprintf(fp, "if(maxLOD >= 3.6){\n");
fprintf(fp, "localpos <- median(localdata$Pos[localdata$Chr==i][localdata$LOD[localdata$Chr==i]==maxLOD])\n");
fprintf(fp, "text(base+localpos, min(maxLOD,10)-0.1, paste(i, \":\", localpos, sep=\"\"), col=\"red\")\n");
fprintf(fp, "}\n");
fprintf(fp, "minLOD <- min(0,localdata$LOD[localdata$Chr==i])\n");
fprintf(fp, "if(minLOD <= -3.6){\n");
fprintf(fp, "localpos <- median(localdata$Pos[localdata$Chr==i][localdata$LOD[localdata$Chr==i]==minLOD])\n");
fprintf(fp, "text(base+localpos, max(minLOD,-10)+0.1, paste(i, \":\", localpos, sep=\"\"), col=\"red\")\n");
fprintf(fp, "}\n");
fprintf(fp, " base <- base + max(0, localdata$Pos[localdata$Chr==i])\n");
fprintf(fp, "}\n");
fprintf(fp, "axis(1, labels=FALSE, line = 0, at = c(0,baseStop))\n");
fprintf(fp, "axis(1, labels=c(1:%d), line = -0.5, lty=\"blank\", at = baseMiddle)\n", SEXCHR-1);
fprintf(fp, "abline(h = 3.6, lty = 2, col=\"red\")\n");
fprintf(fp, "abline(h = -3.6, lty = 2, col=\"red\")\n");
fprintf(fp, "}\n");
fprintf(fp, "}\n");
fprintf(fp, "dev.off()\n");
fprintf(fp, "}\n");
fclose(fp);
char command[256];
sprintf(command, "R CMD BATCH %s", (const char*)scriptfile);
system(command);
int error = CheckRout(scriptfile);
if(error == 2)
printf("--poproh is done but R code %s failed.\n\n", (const char*)scriptfile);
else if(error){
printf("--poproh is done but R code %s failed.\n", (const char*)scriptfile);
printf(" Please check %sout for details.\n\n", (const char*)scriptfile);
}else{
sprintf(command, "ps2pdf %s_poprohplot.ps", (const char*)prefix);
system(command);
printf("ROH difference between populations is generated in %s_poprohplot.pdf\n", (const char*)prefix);
}
}
void plotROHforQT(const char *prefix, int SEXCHR)
{
String scriptfile=prefix;
scriptfile.Add("_mthomoplot.R");
FILE *fp = fopen(scriptfile, "wt");
if(fp == NULL) error("Cannot open %s to write.", (const char*)scriptfile);
fprintf(fp, "## %s for KING --mthomo, by Wei-Min Chen\n", (const char*)scriptfile);
fprintf(fp, "postscript(\"%s_mthomoplot.ps\", paper=\"letter\", horizontal=T)\n",
(const char*)prefix);
fprintf(fp, "data<-c()\n");
fprintf(fp, "if(file.exists(\"%s.mthomo\")) data <- read.table(file=\"%s.mthomo\", header=T)\n",
(const char*)prefix,(const char*)prefix);
fprintf(fp, "if(length(data$LOD)>0){\n");
fprintf(fp, "alltraits <- as.character(data$Trait)\n");
fprintf(fp, "uniqtraits <- unique(alltraits)\n");
fprintf(fp, "for(trait in uniqtraits){\n");
fprintf(fp, "localdata <- data[alltraits==trait,]\n");
fprintf(fp, "Pos <- localdata$Pos\n");
fprintf(fp, "baseStop <- c()\n");
fprintf(fp, "base <- 0\n");
fprintf(fp, "for(i in 1:%d){\n", SEXCHR-1);
fprintf(fp, " Pos[localdata$Chr==i] <- localdata$Pos[localdata$Chr==i] + base\n");
fprintf(fp, " base <- base + max(0, localdata$Pos[localdata$Chr==i])\n");
fprintf(fp, " baseStop <- c(baseStop, base)\n");
fprintf(fp, "}\n");
fprintf(fp, "baseStart <- c(0, baseStop[-%d])\n", SEXCHR-1);
fprintf(fp, "baseMiddle <- (baseStart + baseStop)/2\n");
fprintf(fp, "LOD=localdata$LOD\n");
fprintf(fp, "plot(Pos, LOD, type=\"l\", xlab=\"Chromosome\", ylab = \"LOD Score\", xaxt = 'n',\n");
fprintf(fp, " cex = 1.5, cex.axis=1.5, cex.main=1.5, cex.lab = 1.5, cex.sub = 1.5,\n");
fprintf(fp, " ylim=c(max(min(LOD),-10), min(max(LOD),10)),\n");
fprintf(fp, " lwd = 1.5, main = paste(\"Homozygosity Mapping of\" , trait))\n", (const char*)prefix);
fprintf(fp, "base <- 0\n");
fprintf(fp, "oldlocaldata <- localdata\n");
fprintf(fp, "for(i in 1:%d){\n", SEXCHR-1);
fprintf(fp, "localdata <- oldlocaldata[oldlocaldata$Chr==i,]\n");
fprintf(fp, "repeat{\n");
fprintf(fp, "maxLOD <- max(0,localdata$LOD)\n");
fprintf(fp, "if(maxLOD >= 2.2){\n");
fprintf(fp, "localpos.max <- median(localdata$Pos[localdata$LOD==maxLOD])\n");
fprintf(fp, "text(base+localpos.max, min(maxLOD,10)-0.1, paste(i, \":\", localpos.max, sep=\"\"), col=\"red\")\n");
fprintf(fp, "}\n");
fprintf(fp, "minLOD <- min(0,localdata$LOD)\n");
fprintf(fp, "if(minLOD <= -2.2){\n");
fprintf(fp, "localpos.min <- median(localdata$Pos[localdata$LOD==minLOD])\n");
fprintf(fp, "text(base+localpos.min, max(minLOD,-10)+0.1, paste(i, \":\", localpos.min, sep=\"\"), col=\"red\")\n");
fprintf(fp, "}\n");
fprintf(fp, "if(maxLOD >= 2.2) localdata$LOD[localdata$Pos > localpos.max - 10 & localdata$Pos < localpos.max + 10] <- 0;\n");
fprintf(fp, "if(minLOD <= -2.2) localdata$LOD[localdata$Pos > localpos.min - 10 & localdata$Pos < localpos.min + 10] <- 0;\n");
fprintf(fp, "if(maxLOD < 2.2 && minLOD > -2.2) break\n");
fprintf(fp, "}\n");
fprintf(fp, " base <- base + max(0, localdata$Pos)\n");
fprintf(fp, "}\n");
fprintf(fp, "axis(1, labels=FALSE, line = 0, at = c(0,baseStop))\n");
fprintf(fp, "axis(1, labels=c(1:%d), line = -0.5, lty=\"blank\", at = baseMiddle)\n", SEXCHR-1);
fprintf(fp, "abline(h = 3.6, lty = 2, col=\"red\")\n");
fprintf(fp, "abline(h = 2.2, lty = 3, col=\"green\")\n");
fprintf(fp, "abline(h = -3.6, lty = 2, col=\"red\")\n");
fprintf(fp, "abline(h = -2.2, lty = 3, col=\"green\")\n");
fprintf(fp, "}\n");
fprintf(fp, "dev.off()\n");
fprintf(fp, "}\n");
fclose(fp);
char command[256];
sprintf(command, "R CMD BATCH %s", (const char*)scriptfile);
system(command);
int error = CheckRout(scriptfile);
if(error == 2)
printf("--mthomo is done but R code %s failed.\n\n", (const char*)scriptfile);
else if(error){
printf("--mthomo is done but R code %s failed.\n", (const char*)scriptfile);
printf(" Please check %sout for details.\n\n", (const char*)scriptfile);
}else{
sprintf(command, "ps2pdf %s_mthomoplot.ps", (const char*)prefix);
system(command);
printf("Homozygosity mapping plots are generated in %s_mthomoplot.pdf\n", (const char*)prefix);
}
}
void plotROHmapping(const char *prefix, const char *stratName, int SEXCHR)
{
String postfix = stratName[0]=='\0'? "homomap": "homomapMH";
String scriptfile=prefix;
scriptfile.Add("_");
scriptfile.Add(postfix);
scriptfile.Add("plot.R");
FILE *fp = fopen(scriptfile, "wt");
if(fp == NULL) error("Cannot open %s to write.", (const char*)scriptfile);
fprintf(fp, "## %s for KING --homomap, by Wei-Min Chen\n", (const char*)scriptfile);
fprintf(fp, "postscript(\"%s_%splot.ps\", paper=\"letter\", horizontal=T)\n",
(const char*)prefix, (const char*)postfix);
fprintf(fp, "data<-c()\n");
fprintf(fp, "if(file.exists(\"%s.%s\")) data <- read.table(file=\"%s.%s\", header=T)\n",
(const char*)prefix, (const char*)postfix,
(const char*)prefix, (const char*)postfix);
fprintf(fp, "if(length(data$LOD)>0){\n");
fprintf(fp, "Pos <- data$Pos\n");
fprintf(fp, "baseStop <- c()\n");
fprintf(fp, "base <- 0\n");
fprintf(fp, "for(i in 1:%d){\n", SEXCHR-1);
fprintf(fp, " Pos[data$Chr==i] <- data$Pos[data$Chr==i] + base\n");
fprintf(fp, " base <- base + max(0, data$Pos[data$Chr==i])\n");
fprintf(fp, " baseStop <- c(baseStop, base)\n");
fprintf(fp, "}\n");
fprintf(fp, "baseStart <- c(0, baseStop[-%d])\n", SEXCHR-1);
fprintf(fp, "baseMiddle <- (baseStart + baseStop)/2\n");
fprintf(fp, "plot(Pos, data$LOD, type=\"l\", xlab=\"Chromosome\", ylab = \"LOD Score\", xaxt = 'n',\n");
fprintf(fp, " cex = 1.5, cex.axis=1.5, cex.main=1.5, cex.lab = 1.5, cex.sub = 1.5,\n");
fprintf(fp, " ylim=c(max(min(data$LOD),-5), min(max(data$LOD),10)),\n");
fprintf(fp, " lwd = 1.5, main = \"Homozygosity Mapping in %s\")\n", (const char*)prefix);
fprintf(fp, "base <- 0\n");
fprintf(fp, "for(i in 1:%d){\n", SEXCHR-1);
fprintf(fp, "localdata <- data[data$Chr==i,]\n");
fprintf(fp, "repeat{\n");
fprintf(fp, "maxLOD <- max(0,localdata$LOD)\n");
fprintf(fp, "if(maxLOD >= 3.6){\n");
fprintf(fp, "localpos.max <- median(localdata$Pos[localdata$LOD==maxLOD])\n");
fprintf(fp, "text(base+localpos.max, min(maxLOD,10)-0.1, paste(i, \":\", localpos.max, sep=\"\"), col=\"red\")\n");
fprintf(fp, "}\n");
fprintf(fp, "minLOD <- min(0,localdata$LOD)\n");
fprintf(fp, "if(minLOD <= -3.6){\n");
fprintf(fp, "localpos.min <- median(localdata$Pos[localdata$LOD==minLOD])\n");
fprintf(fp, "text(base+localpos.min, max(minLOD,-5)+0.1, paste(i, \":\", localpos.min, sep=\"\"), col=\"red\")\n");
fprintf(fp, "}\n");
fprintf(fp, "if(maxLOD >= 3.6) localdata$LOD[localdata$Pos > localpos.max - 10 & localdata$Pos < localpos.max + 10] <- 0;\n");
fprintf(fp, "if(minLOD <= -3.6) localdata$LOD[localdata$Pos > localpos.min - 10 & localdata$Pos < localpos.min + 10] <- 0;\n");
fprintf(fp, "if(maxLOD < 3.6 && minLOD > -3.6) break\n");
fprintf(fp, "}\n");
fprintf(fp, " base <- base + max(0, localdata$Pos)\n");
fprintf(fp, "}\n");
fprintf(fp, "axis(1, labels=FALSE, line = 0, at = c(0,baseStop))\n");
fprintf(fp, "axis(1, labels=c(1:%d), line = -0.5, lty=\"blank\", at = baseMiddle)\n", SEXCHR-1);
fprintf(fp, "abline(h = 3.6, lty = 2, col=\"red\")\n");
fprintf(fp, "abline(h = 2.2, lty = 3, col=\"green\")\n");
fprintf(fp, "abline(h = -3.6, lty = 2, col=\"red\")\n");
fprintf(fp, "dev.off()\n");
fprintf(fp, "}\n");
fclose(fp);
char command[256];
sprintf(command, "R CMD BATCH %s", (const char*)scriptfile);
system(command);
int error = CheckRout(scriptfile);
if(error == 2)
printf("--homomap is done but R code %s failed.\n\n", (const char*)scriptfile);
else if(error){
printf("--homomap is done but R code %s failed.\n", (const char*)scriptfile);
printf(" Please check %sout for details.\n\n", (const char*)scriptfile);
}else{
sprintf(command, "ps2pdf %s_%splot.ps",
(const char*)prefix, (const char*)postfix);
system(command);
printf("Homozygosity mapping plot is generated in %s_%splot.pdf\n",
(const char*)prefix, (const char*)postfix);
}
}
void plotPopDist(const char *prefix)
{
String scriptfile=prefix;
scriptfile.Add("_popdistplot.R");
FILE *fp = fopen(scriptfile, "wt");
if(fp == NULL) error("Cannot open %s to write.", (const char*)scriptfile);
fprintf(fp, "## %s for KING --popdist, by Wei-Min Chen\n", (const char*)scriptfile);
fprintf(fp, "postscript(\"%s_popdistplot.ps\", paper=\"letter\", horizontal=T)\n",
(const char*)prefix);
fprintf(fp, "data<-c()\n");
fprintf(fp, "if(file.exists(\"%s.dst\")) data <- read.table(file=\"%s.dst\", header=T)\n",
(const char*)prefix,(const char*)prefix);
fprintf(fp, "if(length(data$DistIBD)>0){\n");
fprintf(fp, "N <- sqrt(2*length(data$DistIBD)+0.25)-0.5\n");
fprintf(fp, "M <- matrix(0,N,N)\n");
fprintf(fp, "M[upper.tri(M, diag=TRUE)] <- data$DistIBD\n");
fprintf(fp, "M[lower.tri(M, diag=TRUE)] <- data$DistIBD\n");
fprintf(fp, "plot(hclust(as.dist(M)),main=\"Clustering of %s Populations By Average IBD\",xlab=\"\",ylab=\"1 - IBD Proportion\")\n",
(const char*)prefix);
fprintf(fp, "mds <- cmdscale(M)\n");
fprintf(fp, "plot(mds[,1],mds[,2],type=\"n\",xlab=\"\",ylab=\"\", axes=FALSE,main=\"MDS of %s Populations Using Average IBD\")\n",
(const char*)prefix);
fprintf(fp, "text(mds[,1],mds[,2],1:N)\n");
fprintf(fp, "dev.off()\n");
fprintf(fp, "}\n");
fclose(fp);
char command[256];
sprintf(command, "R CMD BATCH %s", (const char*)scriptfile);
system(command);
int error = CheckRout(scriptfile);
if(error == 2)
printf("--popdist is done but R code %s failed.\n\n", (const char*)scriptfile);
else if(error){
printf("--popdist is done but R code %s failed.\n", (const char*)scriptfile);
printf(" Please check %sout for details.\n\n", (const char*)scriptfile);
}else{
sprintf(command, "ps2pdf %s_popdistplot.ps", (const char*)prefix);
system(command);
printf("Population distance plot is generated in %s_popdistplot.pdf\n", (const char*)prefix);
}
}
void plotIBDmapping(const char *prefix, int SEXCHR)
{
String scriptfile=prefix;
scriptfile.Add("_ibdmapplot.R");
FILE *fp = fopen(scriptfile, "wt");
if(fp == NULL) error("Cannot open %s to write.", (const char*)scriptfile);
fprintf(fp, "## %s for KING --ibdmap, by Wei-Min Chen\n", (const char*)scriptfile);
fprintf(fp, "postscript(\"%s_ibdmapplot.ps\", paper=\"letter\", horizontal=T)\n",
(const char*)prefix);
fprintf(fp, "data<-c()\n");
fprintf(fp, "if(file.exists(\"%s.ibdmap\")) data <- read.table(file=\"%s.ibdmap\", header=T)\n",
(const char*)prefix,(const char*)prefix);
fprintf(fp, "if(length(data$P)>0){\n");
fprintf(fp, "Pos <- data$PosMb\n");
fprintf(fp, "baseStop <- c()\n");
fprintf(fp, "base <- 0\n");
fprintf(fp, "for(i in 1:%d){\n", SEXCHR-1);
fprintf(fp, " Pos[data$Chr==i] <- data$PosMb[data$Chr==i] + base\n");
fprintf(fp, " base <- base + max(0, data$PosMb[data$Chr==i])\n");
fprintf(fp, " baseStop <- c(baseStop, base)\n");
fprintf(fp, "}\n");
fprintf(fp, "baseStart <- c(0, baseStop[-%d])\n", SEXCHR-1);
fprintf(fp, "baseMiddle <- (baseStart + baseStop)/2\n");
fprintf(fp, "logP <- rep(10, length(data$P))\n");
fprintf(fp, "logP[data$P>0] <- -log(data$P[data$P>0])/log(10)\n");
fprintf(fp, "plot(Pos, logP, type=\"l\", xlab=\"Chromosome\", ylab = expression(paste(\"-\", log[10],\"P\",sep=\"\")), xaxt = 'n',\n");
fprintf(fp, " cex = 1.2, cex.axis=1.2, cex.main=1.5, cex.lab = 1.2, cex.sub = 1.2, ylim=c(0,max(c(logP[logP<10]),4)),\n");
fprintf(fp, " lwd = 1.2, main = \"Permutation P Values of IBD Mapping in %s\")\n", (const char*)prefix);
fprintf(fp, "base <- 0\n");
fprintf(fp, "for(i in 1:%d){\n", SEXCHR-1);
fprintf(fp, "minP <- min(1,data$P[data$Chr==i])\n");
fprintf(fp, "if(minP < 0.0001){\n");
fprintf(fp, "localpos <- median(data$Pos[data$Chr==i][data$P[data$Chr==i]==minP])\n");
fprintf(fp, "text(base+localpos, -log(minP, 10)-0.1, paste(i, \":\", localpos, sep=\"\"), col=\"red\")\n");
fprintf(fp, "}\n");
fprintf(fp, " base <- base + max(0, data$Pos[data$Chr==i])\n");
fprintf(fp, "}\n");
fprintf(fp, "axis(1, labels=FALSE, line = 0, at = c(0,baseStop))\n");
fprintf(fp, "axis(1, labels=c(1:%d), line = -0.5, lty=\"blank\", at = baseMiddle)\n", SEXCHR-1);
fprintf(fp, "abline(h = 4, lty = 2, col=\"red\")\n");
fprintf(fp, "dev.off()\n");
fprintf(fp, "}\n");
fclose(fp);
char command[256];
sprintf(command, "R CMD BATCH %s", (const char*)scriptfile);
system(command);
int error = CheckRout(scriptfile);
if(error == 2)
printf("--ibdmap is done but R code %s failed.\n\n", (const char*)scriptfile);
else if(error){
printf("--ibdmap is done but R code %s failed.\n", (const char*)scriptfile);
printf(" Please check %sout for details.\n\n", (const char*)scriptfile);
}else{
sprintf(command, "ps2pdf %s_ibdmapplot.ps", (const char*)prefix);
system(command);
printf("IBD mapping plot is generated in %s_ibdmapplot.pdf\n", (const char*)prefix);
}
}
void plotAncestry(const char *prefix)
{
String scriptfile=prefix;
scriptfile.Add("_ancestryplot.R");
FILE *fp = fopen(scriptfile, "wt");
if(fp == NULL) error("Cannot open %s to write.", (const char*)scriptfile);
fprintf(fp, "## %s for KING --ancestry, by Wei-Min Chen\n", (const char*)scriptfile);
fprintf(fp, "postscript(\"%s_ancestryplot.ps\", paper=\"letter\", horizontal=T)\n",
(const char*)prefix);
fprintf(fp, "data<-c()\n");
fprintf(fp, "if(file.exists(\"%s.anc\")) data <- read.table(file=\"%s.anc\", header=T)\n",
(const char*)prefix,(const char*)prefix);
fprintf(fp, "if(length(data$Admix)>0){\n");
fprintf(fp, " plot(data$Admix, data$Ancestry, xlab=\"Admixed Proportion\", ylab = \"Ancestry\",\n");
fprintf(fp, " cex = 1.5, cex.axis=1.5, cex.main=1.5, cex.lab = 1.5, cex.sub = 1.5,\n");
fprintf(fp, " lwd = 1.5, main = \"Ancestry in %s\")\n", (const char*)prefix);
fprintf(fp, " abline(a=0, b=0.5, col=\"red\")\n");
fprintf(fp, " abline(a=1, b=-0.5, col=\"red\")\n");
fprintf(fp, " y <- seq(0,1,0.001)\n");
fprintf(fp, " x <- y*(1-y)*2\n");
fprintf(fp, " lines(x, y, col=\"red\")\n");
fprintf(fp, " plot(data$Anc_P1, data$Anc_P2, xlab=\"Ancestry of Parent 1\", ylab = \"Ancestry of Parent 2\",\n");
fprintf(fp, " cex = 1.5, cex.axis=1.5, cex.main=1.5, cex.lab = 1.5, cex.sub = 1.5,\n");
fprintf(fp, " lwd = 1.5, main = \"Parental Ancestry in %s\")\n", (const char*)prefix);
fprintf(fp, "}\n");
fclose(fp);
char command[256];
sprintf(command, "R CMD BATCH %s", (const char*)scriptfile);
system(command);
int error = CheckRout(scriptfile);
if(error == 2)
printf("--ancestry is done but R code %s failed.\n\n", (const char*)scriptfile);
else if(error){
printf("--ancestry is done but R code %s failed.\n", (const char*)scriptfile);
printf(" Please check %sout for details.\n\n", (const char*)scriptfile);
}else{
sprintf(command, "ps2pdf %s_ancestryplot.ps", (const char*)prefix);
system(command);
printf("Ancestry plot is generated in %s_ancestryplot.pdf\n", (const char*)prefix);
}
}
void plotNPL(const char *prefix, int SEXCHR)
{
String scriptfile=prefix;
scriptfile.Add("_nplplot.R");
FILE *fp = fopen(scriptfile, "wt");
if(fp == NULL) error("Cannot open %s to write.", (const char*)scriptfile);
fprintf(fp, "## %s for KING --npl, by Wei-Min Chen\n", (const char*)scriptfile);
fprintf(fp, "postscript(\"%s_nplplot.ps\", paper=\"letter\", horizontal=T)\n",
(const char*)prefix);
fprintf(fp, "data<-c()\n");
fprintf(fp, "if(file.exists(\"%s.npl\")) data <- read.table(file=\"%s.npl\", header=T)\n",
(const char*)prefix,(const char*)prefix);
fprintf(fp, "if(length(data$LODwDSP)>0){\n");
fprintf(fp, "Pos <- data$Pos\n");
fprintf(fp, "baseStop <- c()\n");
fprintf(fp, "base <- 0\n");
fprintf(fp, "for(i in 1:%d){\n", SEXCHR-1);
fprintf(fp, " Pos[data$Chr==i] <- data$Pos[data$Chr==i] + base\n");
fprintf(fp, " base <- base + max(0,data$Pos[data$Chr==i])\n");
fprintf(fp, " baseStop <- c(baseStop, base)\n");
fprintf(fp, "}\n");
fprintf(fp, "baseStart <- c(0, baseStop[-%d])\n", SEXCHR-1);
fprintf(fp, "baseMiddle <- (baseStart + baseStop)/2\n");
fprintf(fp, "plot(Pos, data$LODwDSP, type=\"l\", xlab=\"Chromosome\", ylab = \"LOD Score\", xaxt = 'n',\n");
fprintf(fp, " cex = 1.5, cex.axis=1.5, cex.main=1.5, cex.lab = 1.5, cex.sub = 1.5,\n");
fprintf(fp, " lwd = 1.5, main = \"ASP/DSP NPL Scan in %s\", ylim=c(0,min(max(data$LODwDSP),10)))\n", (const char*)prefix);
fprintf(fp, "base <- 0\n");
fprintf(fp, "for(i in 1:%d){\n", SEXCHR-1);
fprintf(fp, "maxLOD <- max(0,data$LODwDSP[data$Chr==i])\n");
fprintf(fp, "if(maxLOD >= 3.6){\n");
fprintf(fp, "localpos <- median(data$Pos[data$Chr==i][data$LODwDSP[data$Chr==i]==maxLOD])\n");
fprintf(fp, "text(base+localpos, min(maxLOD,10)-0.1, paste(i, \":\", localpos, sep=\"\"), col=\"red\")\n");
fprintf(fp, "}\n");
fprintf(fp, " base <- base + max(0, data$Pos[data$Chr==i])\n");
fprintf(fp, "}\n");
fprintf(fp, "axis(1, labels=FALSE, line = 0, at = c(0,baseStop))\n");
fprintf(fp, "axis(1, labels=c(1:%d), line = -0.5, lty=\"blank\", at = baseMiddle)\n", SEXCHR-1);
fprintf(fp, "abline(h = 3.6, lty = 2, col=\"red\")\n");
fprintf(fp, "abline(h = 2.2, lty = 3, col=\"green\")\n");
fprintf(fp, "}\n");
fprintf(fp, "Pos <- data$Pos\n");
fprintf(fp, "baseStop <- c()\n");
fprintf(fp, "base <- 0\n");
fprintf(fp, "for(i in 1:%d){\n", SEXCHR-1);
fprintf(fp, " Pos[data$Chr==i] <- data$Pos[data$Chr==i] + base\n");
fprintf(fp, " base <- base + max(0,data$Pos[data$Chr==i])\n");
fprintf(fp, " baseStop <- c(baseStop, base)\n");
fprintf(fp, "}\n");
fprintf(fp, "baseStart <- c(0, baseStop[-%d])\n", SEXCHR-1);
fprintf(fp, "baseMiddle <- (baseStart + baseStop)/2\n");
fprintf(fp, "plot(Pos, data$LOD_ASP, type=\"l\", xlab=\"Chromosome\", ylab = \"LOD Score\", xaxt = 'n',\n");
fprintf(fp, " cex = 1.5, cex.axis=1.5, cex.main=1.5, cex.lab = 1.5, cex.sub = 1.5,\n");
fprintf(fp, " lwd = 1.5, main = \"ASP NPL Scan in %s\", ylim=c(0,min(max(data$LOD_ASP),10)))\n", (const char*)prefix);
fprintf(fp, "base <- 0\n");
fprintf(fp, "for(i in 1:%d){\n", SEXCHR-1);
fprintf(fp, "maxLOD <- max(0,data$LOD_ASP[data$Chr==i])\n");
fprintf(fp, "if(maxLOD >= 3.6){\n");
fprintf(fp, "localpos <- median(data$Pos[data$Chr==i][data$LOD_ASP[data$Chr==i]==maxLOD])\n");
fprintf(fp, "text(base+localpos, min(maxLOD,10)-0.1, paste(i, \":\", localpos, sep=\"\"), col=\"red\")\n");
fprintf(fp, "}\n");
fprintf(fp, " base <- base + max(0, data$Pos[data$Chr==i])\n");
fprintf(fp, "}\n");
fprintf(fp, "axis(1, labels=FALSE, line = 0, at = c(0,baseStop))\n");
fprintf(fp, "axis(1, labels=c(1:%d), line = -0.5, lty=\"blank\", at = baseMiddle)\n", SEXCHR-1);
fprintf(fp, "abline(h = 3.6, lty = 2, col=\"red\")\n");
fprintf(fp, "abline(h = 2.2, lty = 3, col=\"green\")\n");
fclose(fp);
char command[256];
sprintf(command, "R CMD BATCH %s", (const char*)scriptfile);
system(command);
int error = CheckRout(scriptfile);
if(error == 2)
printf("--npl is done but R code %s failed.\n\n", (const char*)scriptfile);
else if(error){
printf("--npl is done but R code %s failed.\n", (const char*)scriptfile);
printf(" Please check %sout for details.\n\n", (const char*)scriptfile);
}else{
sprintf(command, "ps2pdf %s_nplplot.ps", (const char*)prefix);
system(command);
printf("ASP NPL plot is generated in %s_nplplot.pdf\n", (const char*)prefix);
}
}
void plotAUCmapping(const char *prefix, int SEXCHR)
{
String scriptfile=prefix;
scriptfile.Add("_aucmapplot.R");
FILE *fp = fopen(scriptfile, "wt");
if(fp == NULL) error("Cannot open %s to write.", (const char*)scriptfile);
fprintf(fp, "## %s for KING --aucmap, by Wei-Min Chen\n", (const char*)scriptfile);
fprintf(fp, "postscript(\"%s_aucmapplot.ps\", paper=\"letter\", horizontal=T)\n",(const char*)prefix);
fprintf(fp, "data<-c()\n");
fprintf(fp, "if(file.exists(\"%s.aucmap\")) data <- read.table(file=\"%s.aucmap\", header=T)\n",
(const char*)prefix,(const char*)prefix);
fprintf(fp, "if(length(data$AUC)>0){\n");
fprintf(fp, "Pos <- data$Pos\n");
fprintf(fp, "baseStop <- c()\n");
fprintf(fp, "base <- 0\n");
fprintf(fp, "for(i in 1:%d){\n", SEXCHR-1);
fprintf(fp, " Pos[data$Chr==i] <- data$Pos[data$Chr==i] + base\n");
fprintf(fp, " base <- base + max(data$Pos[data$Chr==i])\n");
fprintf(fp, " baseStop <- c(baseStop, base)\n");
fprintf(fp, "}\n");
fprintf(fp, "baseStart <- c(0, baseStop[-%d])\n", SEXCHR-1);
fprintf(fp, "baseMiddle <- (baseStart + baseStop)/2\n");
fprintf(fp, "plot(Pos[data$Success>0.9], data$AUC[data$Success>0.9], type=\"l\", xlab=\"Chromosome\", ylab = \"AUC\", xaxt = 'n',\n");
fprintf(fp, " cex = 1.5, cex.axis=1.5, cex.main=1.5, cex.lab = 1.5, cex.sub = 1.5, ylim=c(0.5,max(data$AUC[data$Success>0.9])),\n");
fprintf(fp, " lwd = 1.5, main = \"Risk Prediction Using Position-Specific IBD Relatives in %s\")\n",
(const char*)prefix);
fprintf(fp, "base <- 0\n");
fprintf(fp, "for(i in 1:%d){\n", SEXCHR-1);
fprintf(fp, "maxAUC <- max(0,data$AUC[data$Chr==i])\n");
fprintf(fp, "if(maxAUC > 0.6){\n");
fprintf(fp, "localpos <- median(data$Pos[data$Chr==i][data$AUC[data$Chr==i]==maxAUC])\n");
fprintf(fp, "text(base+localpos, maxAUC-0.01, paste(i, \":\", localpos, sep=\"\"), col=\"red\")\n");
fprintf(fp, "}\n");
fprintf(fp, " base <- base + max(0, data$Pos[data$Chr==i])\n");
fprintf(fp, "}\n");
fprintf(fp, "axis(1, labels=FALSE, line = 0, at = c(0,baseStop))\n");
fprintf(fp, "axis(1, labels=c(1:%d), line = -0.5, lty=\"blank\", at = baseMiddle)\n", SEXCHR-1);
fprintf(fp, "abline(h = 0.6, lty = 2, col=\"red\")\n");
fprintf(fp, "dev.off()\n");
fprintf(fp, "}\n");
fclose(fp);
char command[256];
sprintf(command, "R CMD BATCH %s", (const char*)scriptfile);
system(command);
int error = CheckRout(scriptfile);
if(error == 2)
printf("--aucmap is done but R code %s failed.\n\n", (const char*)scriptfile);
else if(error){
printf("--aucmap is done but R code %s failed.\n", (const char*)scriptfile);
printf(" Please check %sout for details.\n\n", (const char*)scriptfile);
}else{
sprintf(command, "ps2pdf %s_aucmapplot.ps", (const char*)prefix);
system(command);
printf("AUC mapping plot is generated in %s_aucmapplot.pdf\n", (const char*)prefix);
}
}
void plotRelationship(const char *prefix)
{
String scriptfile=prefix;
scriptfile.Add("_relplot.R");
FILE *fp = fopen(scriptfile, "wt");
if(fp == NULL) error("Cannot open %s to write.", (const char*)scriptfile);
fprintf(fp, "## %s for KING --related, by Wei-Min Chen\n", (const char*)scriptfile);
fprintf(fp, "postscript(\"%s_relplot.ps\", paper=\"letter\", horizontal=T)\n",
(const char*)prefix);
fprintf(fp, "data<-c()\n");
fprintf(fp, "if(file.exists(\"%s.kin\")) data <- read.table(file=\"%s.kin\", header=T)\n",
(const char*)prefix,(const char*)prefix);
fprintf(fp, "allcolors <- c(\"purple\", \"red\", \"green\", \"blue\", \"magenta\", \"gold\", \"black\")\n");
fprintf(fp, "allrelatives <- c(\"MZ Twin\", \"Parent-Offspring\", \"Full Siblings\", \"2nd-Degree\", \"3rd-Degree\", \"More Distant\", \"Unrelated\")\n");
fprintf(fp, "if(length(data$IBD1Seg)>0 & length(data$IBD2Seg)>0){\n");
// Page 1 plot: IBD1 vs IBD2
fprintf(fp, "allpair <- data$PropIBD>0 | data$Kinship>0.04419\n");
fprintf(fp, "d0 <- data$Phi==0.5\n");
fprintf(fp, "d1.PO <- data$Phi==0.25 & data$Z0==0\n");
fprintf(fp, "d1.FS <- data$Phi==0.25 & data$Z0>0\n");
fprintf(fp, "d2 <- data$Phi>0.08839 & data$Phi<=0.17678\n");
fprintf(fp, "d3 <- data$Phi>0.04419 & data$Phi<=0.08839\n");
fprintf(fp, "dO <- data$Phi>0 & data$Phi<=0.04419\n");
fprintf(fp, "dU <- data$Phi==0 & allpair\n");
fprintf(fp, "plot(data$IBD1Seg[dU], data$IBD2Seg[dU], type=\"p\", col = \"black\", cex.lab=1.2,\n");
fprintf(fp, "xlim=c(min(data$IBD1Seg[allpair]), max(data$IBD1Seg[allpair])),\n");
fprintf(fp, "ylim=c(min(data$IBD2Seg[allpair]), max(data$IBD2Seg[allpair])),\n");
fprintf(fp, "main = \"IBD Segments In %s Families\",\n", (const char*)prefix);
fprintf(fp, "xlab=expression(paste(\"Length Proportion of IBD1 Segments (\", pi[1], \")\", sep=\"\")),\n");
fprintf(fp, "ylab=expression(paste(\"Length Proportion of IBD2 Segments (\", pi[2], \")\", sep=\"\")))\n");
fprintf(fp, "points(data$IBD1Seg[d0], data$IBD2Seg[d0], col=\"purple\")\n");
fprintf(fp, "points(data$IBD1Seg[d1.PO], data$IBD2Seg[d1.PO], col=\"red\")\n");
fprintf(fp, "points(data$IBD1Seg[d1.FS], data$IBD2Seg[d1.FS], col=\"green\")\n");
fprintf(fp, "points(data$IBD1Seg[d2], data$IBD2Seg[d2], col=\"blue\")\n");
fprintf(fp, "points(data$IBD1Seg[d3], data$IBD2Seg[d3], col=\"magenta\")\n");
fprintf(fp, "points(data$IBD1Seg[dO], data$IBD2Seg[dO], col=\"gold\")\n");
fprintf(fp, "points(data$IBD1Seg[dU & data$PropIBD>0.08838835], data$IBD2Seg[dU & data$PropIBD>0.08838835], col=\"black\")\n");
fprintf(fp, "points(data$IBD1Seg[d1.FS & data$IBD2Seg<0.08], data$IBD2Seg[d1.FS & data$IBD2Seg<0.08], col=\"green\")\n");
fprintf(fp, "points(data$IBD1Seg[d1.PO & data$IBD1Seg+data$IBD2Seg<0.9], data$IBD2Seg[d1.PO & data$IBD1Seg+data$IBD2Seg<0.9], col=\"red\")\n");
fprintf(fp, "abline(h = 0.08, col = \"green\", lty = 3, lwd = 2)\n"); // FS && MZ
fprintf(fp, "abline(a = 0.96, b = -1, col = \"red\", lty = 3, lwd = 2)\n"); // PO
fprintf(fp, "abline(a = 0.3535534, b = -0.5, col = \"green\", lty = 3, lwd = 2)\n");// FS
fprintf(fp, "abline(a = 0.1767767, b = -0.5, col = \"blue\", lty = 3, lwd = 2)\n");// 2nd/3rd
fprintf(fp, "abline(a = 0.08838835, b = -0.5, col = \"magenta\", lty = 3, lwd = 2)\n");// 3rd/4th
fprintf(fp, "abline(a = 0.04419, b = -0.5, col = \"gold\", lty = 3, lwd = 2)\n");// 4th/UN
fprintf(fp, "legend(\"topright\", allrelatives, col=allcolors, text.col=allcolors, pch=19, cex=1.2)\n");
// Page 2 plot: Kinship vs. PropIBD
fprintf(fp, "allpair <- data$PropIBD>0 | data$Kinship>0.04419\n");
fprintf(fp, "d0 <- data$Phi==0.5\n");
fprintf(fp, "d1.PO <- data$Phi==0.25 & data$Z0==0\n");
fprintf(fp, "d1.FS <- data$Phi==0.25 & data$Z0>0\n");
fprintf(fp, "d2 <- data$Phi>0.08839 & data$Phi<=0.17678\n");
fprintf(fp, "d3 <- data$Phi>0.04419 & data$Phi<=0.08839\n");
fprintf(fp, "dO <- data$Phi>0 & data$Phi<=0.04419\n");
fprintf(fp, "dU <- data$Phi==0 & allpair\n");
fprintf(fp, "plot(data$PropIBD[dU], data$Kinship[dU], type=\"p\", col = \"black\", cex.lab=1.2,\n");
fprintf(fp, "xlim=c(min(data$PropIBD[allpair]), max(data$PropIBD[allpair])),\n");
fprintf(fp, "ylim=c(min(data$Kinship[allpair]), max(data$Kinship[allpair])),\n");
fprintf(fp, "main = paste(\"Kinship vs Proportion IBD (Corr=\", round(cor(data$Kinship[data$PropIBD>0], data$PropIBD[data$PropIBD>0]),digit=3),\") in %s Families\",sep=\"\"),\n",
(const char*)prefix);
fprintf(fp, "xlab=expression(paste(\"Proportion of Genomes IBD (\", pi,\"=\",pi[2]+pi[1]/2,\")\",sep=\"\")),\n");
fprintf(fp, "ylab = expression(paste(\"Estimated Kinship Coefficient (\", phi, \")\", sep=\"\")))\n");
fprintf(fp, "points(data$PropIBD[d0], data$Kinship[d0], col=\"purple\")\n");
fprintf(fp, "points(data$PropIBD[d1.FS], data$Kinship[d1.FS], col=\"green\")\n");
fprintf(fp, "points(data$PropIBD[d1.PO], data$Kinship[d1.PO], col=\"red\")\n");
fprintf(fp, "points(data$PropIBD[d2], data$Kinship[d2], col=\"blue\")\n");
fprintf(fp, "points(data$PropIBD[d3], data$Kinship[d3], col=\"magenta\")\n");
fprintf(fp, "points(data$PropIBD[dO], data$Kinship[dO], col=\"gold\")\n");
fprintf(fp, "points(data$PropIBD[dU & data$Kinship>0.088], data$Kinship[dU & data$Kinship>0.088], col=\"black\")\n");
fprintf(fp, "abline(h = 0.35355, col = \"purple\", lty = 3)\n");
fprintf(fp, "abline(h = 0.17678, col = \"green\", lty = 3)\n");
fprintf(fp, "abline(h = 0.08838, col = \"blue\", lty = 3)\n");
fprintf(fp, "abline(h = 0.04419, col = \"magenta\", lty = 3)\n");
fprintf(fp, "abline(h = 0.02210, col = \"gold\", lty = 3)\n");
fprintf(fp, "abline(a = 0, b = 0.5, lty = 1)\n");
fprintf(fp, "abline(a = 0, b = 0.7071068, lty = 3)\n");
fprintf(fp, "abline(a = 0, b = 0.3535534, lty = 3)\n");
fprintf(fp, "abline(v = 0.70711, col = \"purple\", lty = 3)\n");
fprintf(fp, "abline(v = 0.35355, col = \"green\", lty = 3)\n");
fprintf(fp, "abline(v = 0.17678, col = \"blue\", lty = 3)\n");
fprintf(fp, "abline(v = 0.08838, col = \"magenta\", lty = 3)\n");
fprintf(fp, "abline(v = 0.04419, col = \"gold\", lty = 3)\n");
fprintf(fp, "text(x=0.35355, y=0.35355, \"1st\", adj=c(0,1), col=\"green\")\n");
fprintf(fp, "text(x=0.17678, y=0.17678, \"2nd\", adj=c(0,1), col=\"blue\")\n");
fprintf(fp, "text(x=0.08839, y=0.08839, \"3rd\", adj=c(0,1), col=\"magenta\")\n");
fprintf(fp, "text(x=0.04419, y=0.04419, \"4th\", adj=c(0,1), col=\"gold\")\n");
fprintf(fp, "legend(\"bottomright\", allrelatives, col=allcolors, text.col=allcolors, pch=19, cex=1.2)\n");
fprintf(fp, "}else if(length(data$Kinship)>0){\n");
// In absence of IBDSeg, plot 1: Kinship vs HomIBS0
fprintf(fp, "d0 <- data$Phi==0.5\n");
fprintf(fp, "d1.PO <- data$Phi==0.25 & data$Z0==0\n");
fprintf(fp, "d1.FS <- data$Phi==0.25 & data$Z0>0\n");
fprintf(fp, "d2 <- data$Phi==0.125\n");
fprintf(fp, "dU <- data$Phi==0\n");
fprintf(fp, "dO <- !d0 & !d1.PO & !d1.FS & !d2 & !dU\n");
fprintf(fp, "plot(data$HomIBS0[dU], data$Kinship[dU], type=\"p\", col = \"black\", cex.lab=1.3,\n");
fprintf(fp, "xlim=c(min(data$HomIBS0), max(data$HomIBS0)),\n");
fprintf(fp, "ylim=c(min(data$Kinship), max(data$Kinship)),\n");
fprintf(fp, "main = \"Kinship vs IBS0 in %s Families\",\n", (const char*)prefix);
fprintf(fp, "xlab=\"Proportion of Zero IBS In Minor Homozygote Pairs\", ylab = \"Estimated Kinship Coefficient\")\n");
fprintf(fp, "points(data$HomIBS0[d0], data$Kinship[d0], col=\"purple\")\n");
fprintf(fp, "points(data$HomIBS0[d1.PO], data$Kinship[d1.PO], col=\"red\")\n");
fprintf(fp, "points(data$HomIBS0[d1.FS], data$Kinship[d1.FS], col=\"green\")\n");
fprintf(fp, "points(data$HomIBS0[d2], data$Kinship[d2], col=\"blue\")\n");
fprintf(fp, "points(data$HomIBS0[dO], data$Kinship[dO], col=\"gold\")\n");
fprintf(fp, "points(data$HomIBS0[dU & data$Kinship>0.088], data$Kinship[dU & data$Kinship>0.088], col=\"black\")\n");
fprintf(fp, "abline(h = 0.3536, col = \"red\", lty = 3)\n");
fprintf(fp, "abline(h = 0.1768, col = \"green\", lty = 3)\n");
fprintf(fp, "abline(h = 0.0884, col = \"blue\", lty = 3)\n");
fprintf(fp, "abline(h = 0.0442, col = \"black\", lty = 3)\n");
fprintf(fp, "legend(\"topright\", allrelatives, col=allcolors, text.col=allcolors, pch=19, cex=1.2)\n");
// in absence of IBDSeg, plot 2: Kinship vs. HetConc
fprintf(fp, "plot(data$HetConc[dU], data$Kinship[dU], type=\"p\",\n");
fprintf(fp, "col = \"black\", cex.lab=1.3,\n");
fprintf(fp, "xlim = c(min(data$HetConc), max(data$HetConc[data$HetConc<0.8])),\n");
fprintf(fp, "ylim = c(min(data$Kinship), max(data$Kinship[data$HetConc<0.8])),\n");
fprintf(fp, "main = \"Kinship vs Heterozygote Concordance In %s Families\",\n", (const char*)prefix);
fprintf(fp, "xlab=\"Heterozygote Concordance Rate\", ylab = \"Estimated Kinship Coefficient\")\n");
fprintf(fp, "points(data$HetConc[d1.PO], data$Kinship[d1.PO], col=\"red\")\n");
fprintf(fp, "points(data$HetConc[d1.FS], data$Kinship[d1.FS], col=\"green\")\n");
fprintf(fp, "points(data$HetConc[d2], data$Kinship[d2], col=\"blue\")\n");
fprintf(fp, "points(data$HetConc[dO], data$Kinship[dO], col=\"gold\")\n");
fprintf(fp, "points(data$HetConc[dU & data$Kinship>0.088], data$Kinship[dU & data$Kinship>0.088], col=\"black\")\n");
fprintf(fp, "abline(h = 0.3536, col = \"red\", lty = 3)\n");
fprintf(fp, "abline(h = 0.1768, col = \"green\", lty = 3)\n");
fprintf(fp, "abline(h = 0.0884, col = \"blue\", lty = 3)\n");
fprintf(fp, "abline(h = 0.0442, col = \"black\", lty = 3)\n");
fprintf(fp, "legend(\"bottomright\", allrelatives, col=allcolors, text.col=allcolors, pch=19, cex=1.2)\n");
fprintf(fp, "if(sum(d1.FS)>20){\n");
fprintf(fp, "y.cut <- 2^-2.5\n");
fprintf(fp, "x.FS <- quantile(data$HetConc[d1.FS], probs=c(0.1, 0.9))\n");
fprintf(fp, "y.FS <- quantile(data$Kinship[d1.FS], probs=c(0.1, 0.9))\n");
fprintf(fp, "slope.FS <- (y.FS[2]-y.FS[1]) / (x.FS[2]-x.FS[1])\n");
fprintf(fp, "a.FS <- y.FS[1]-x.FS[1]*slope.FS\n");
fprintf(fp, "abline(a=a.FS, b=slope.FS, col=\"green\")\n");
fprintf(fp, "x.cut.FS <- (y.cut - a.FS)/slope.FS\n");
fprintf(fp, "}\n");
fprintf(fp, "if(sum(d2)>20){\n");
fprintf(fp, "x.d2 <- quantile(data$HetConc[d2], probs=c(0.9, 0.1))\n");
fprintf(fp, "y.d2 <- quantile(data$Kinship[d2], probs=c(0.9, 0.1))\n");
fprintf(fp, "slope.d2 <- (y.d2[2]-y.d2[1]) / (x.d2[2]-x.d2[1])\n");
fprintf(fp, "a.d2 <- y.d2[1]-x.d2[1]*slope.d2\n");
fprintf(fp, "abline(a=a.d2, b=slope.d2, col=\"blue\")\n");
fprintf(fp, "x.cut.d2 <- (y.cut - a.d2)/slope.d2\n");
fprintf(fp, "x.cut <- sqrt(x.cut.d2 * x.cut.FS)\n");
fprintf(fp, "}\n");
fprintf(fp, "if(sum(d1.FS)>20 & sum(d2)>20){\n");
fprintf(fp, "print(c(x.cut.d2, x.cut.FS, x.cut))\n");
fprintf(fp, "abline(v=x.cut, col=\"purple\", lty=3)\n");
fprintf(fp, "text(x=x.cut, y=0.3, labels=round(x.cut,digit=3),col=\"purple\")\n");
fprintf(fp, "points(data$HetConc[d1.FS & data$HetConc < x.cut], data$Kinship[d1.FS & data$HetConc < x.cut], col=\"green\")\n");
fprintf(fp, "}\n");
fprintf(fp, "}\n");
fprintf(fp, "\nif(!file.exists(\"%s.kin0\")) quit()\n", (const char*)prefix);
fprintf(fp, "data <- read.table(file = \"%s.kin0\", header=T)\n", (const char*)prefix);
plotIBD1vsIBD2(prefix, fp);
// Page 2 plot: Kinship vs. PropIBD
fprintf(fp, "if(length(data$IBD1Seg)>0 & length(data$IBD2Seg)>0){\n");
fprintf(fp, "d0 <- data$IBD2Seg>0.7\n");
fprintf(fp, "d1.PO <- (!d0) & data$IBD1Seg+data$IBD2Seg>0.96 | (data$IBD1Seg+data$IBD2Seg>0.9 & data$IBD2Seg<0.08)\n");
fprintf(fp, "d1.FS <- (!d0) & (!d1.PO) & data$PropIBD>0.35355 & data$IBD2Seg>=0.08\n");
fprintf(fp, "d2 <- data$PropIBD>0.17678 & data$IBD1Seg+data$IBD2Seg<=0.9 & (!d1.FS)\n");
fprintf(fp, "d3 <- data$PropIBD>0.08839 & data$PropIBD<=0.17678\n");
fprintf(fp, "d4 <- data$PropIBD>0.04419 & data$PropIBD<=0.08839\n");
fprintf(fp, "dU <- data$PropIBD<=0.04419\n");
fprintf(fp, "plot(data$PropIBD[d1.FS], data$Kinship[d1.FS], type=\"p\", col=\"green\", cex.lab=1.2,\n");
fprintf(fp, "xlim=c(min(data$PropIBD), max(data$PropIBD)),\n");
fprintf(fp, "ylim=c(min(data$Kinship), max(data$Kinship)),\n");
fprintf(fp, "main = paste(\"Kinship vs Proportion IBD (Corr=\", round(cor(data$Kinship[data$PropIBD>0], data$PropIBD[data$PropIBD>0]),digit=3),\") in Inferred %s Relatives\",sep=\"\"),\n",
(const char*)prefix);
fprintf(fp, "xlab=expression(paste(\"Proportion of Genomes IBD (\", pi,\"=\",pi[2]+pi[1]/2,\")\",sep=\"\")), \n");
fprintf(fp, "ylab = expression(paste(\"Estimated Kinship Coefficient (\", phi, \")\", sep=\"\")))\n");
fprintf(fp, "points(data$PropIBD[d1.PO], data$Kinship[d1.PO], col=\"red\")\n");
fprintf(fp, "points(data$PropIBD[d0], data$Kinship[d0], col=\"purple\")\n");
fprintf(fp, "points(data$PropIBD[d2], data$Kinship[d2], col=\"blue\")\n");
fprintf(fp, "points(data$PropIBD[d3], data$Kinship[d3], col=\"magenta\")\n");
fprintf(fp, "points(data$PropIBD[d4], data$Kinship[d4], col=\"gold\")\n");
fprintf(fp, "points(data$PropIBD[dU], data$Kinship[dU], col=\"black\")\n");
fprintf(fp, "abline(h = 0.35355, col = \"purple\", lty = 3)\n");
fprintf(fp, "abline(h = 0.17678, col = \"green\", lty = 3)\n");
fprintf(fp, "abline(h = 0.08839, col = \"blue\", lty = 3)\n");
fprintf(fp, "abline(h = 0.04419, col = \"magenta\", lty = 3)\n");
fprintf(fp, "abline(h = 0.02210, col = \"gold\", lty = 3)\n");
fprintf(fp, "abline(a = 0, b = 0.5, lty = 1)\n");
fprintf(fp, "abline(a = 0, b = 0.7071068, lty = 3)\n");
fprintf(fp, "abline(a = 0, b = 0.3535534, lty = 3)\n");
fprintf(fp, "abline(v = 0.70711, col = \"purple\", lty = 3)\n");
fprintf(fp, "abline(v = 0.35355, col = \"green\", lty = 3)\n");
fprintf(fp, "abline(v = 0.17678, col = \"blue\", lty = 3)\n");
fprintf(fp, "abline(v = 0.08839, col = \"magenta\", lty = 3)\n");
fprintf(fp, "abline(v = 0.04419, col = \"gold\", lty = 3)\n");
fprintf(fp, "text(x=0.35355, y=0.35355, \"1st\", adj=c(0,1), col=\"green\")\n");
fprintf(fp, "text(x=0.17678, y=0.17678, \"2nd\", adj=c(0,1), col=\"blue\")\n");
fprintf(fp, "text(x=0.08839, y=0.08839, \"3rd\", adj=c(0,1), col=\"magenta\")\n");
fprintf(fp, "text(x=0.04419, y=0.04419, \"4th\", adj=c(0,1), col=\"gold\")\n");
fprintf(fp, "legend(\"bottomright\", c(\"Inferred MZ\", \"Inferred PO\", \"Inferred FS\", \"Inferred 2nd\", \"Inferred 3rd\", \"Inferred 4th\", \"Inferred UN\"),\n");
fprintf(fp, "col=allcolors, text.col = allcolors, pch = 19, cex = 1.2)\n");
fprintf(fp, "}\n");
fprintf(fp, "dev.off()\n");
fclose(fp);
char command[256];
sprintf(command, "R CMD BATCH %s", (const char*)scriptfile);
system(command);
int error = CheckRout(scriptfile);
if(error == 2)
printf("--related is done but R code %s failed.\n\n", (const char*)scriptfile);
else if(error){
printf("--related is done but R code %s failed.\n", (const char*)scriptfile);
printf(" Please check %sout for details.\n\n", (const char*)scriptfile);
}else{
sprintf(command, "ps2pdf %s_relplot.ps", (const char*)prefix);
system(command);
printf("Relationship plot is generated in %s_relplot.pdf\n", (const char*)prefix);
}
}
void plotIBDSeg(const char *prefix)
{
String scriptfile=prefix;
scriptfile.Add("_ibd1vsibd2.R");
FILE *fp = fopen(scriptfile, "wt");
if(fp == NULL) error("Cannot open %s to write.", (const char*)scriptfile);
fprintf(fp, "## %s for KING --ibdseg, by Wei-Min Chen\n", (const char*)scriptfile);
fprintf(fp, "postscript(\"%s_ibd1vsibd2.ps\", paper=\"letter\", horizontal=T)\n",
(const char*)prefix);
fprintf(fp, "data<-c()\n");
fprintf(fp, "if(file.exists(\"%s.seg\")) data <- read.table(file=\"%s.seg\", header=T)\n",
(const char*)prefix,(const char*)prefix);
plotIBD1vsIBD2(prefix, fp);
fprintf(fp, "dev.off()\n");
fclose(fp);
char command[256];
sprintf(command, "R CMD BATCH %s", (const char*)scriptfile);
system(command);
int error = CheckRout(scriptfile);
if(error == 2)
printf("--ibdseg is done but R code %s failed.\n\n", (const char*)scriptfile);
else if(error){
printf("--ibdseg is done but R code %s failed.\n", (const char*)scriptfile);
printf(" Please check %sout for details.\n\n", (const char*)scriptfile);
}else{
sprintf(command, "ps2pdf %s_ibd1vsibd2.ps", (const char*)prefix);
system(command);
printf("IBD1 vs IBD2 plot is generated in %s_ibd1vsibd2.pdf\n", (const char*)prefix);
}
}
void plotGenderError(const char *prefix, IntArray & plotx, Vector & ploty, IntArray & plotz, double xHeterozygosity, int gendererrorCount)
{
String genderplotdata=prefix;
genderplotdata.Add("_gender_autodata.txt");
FILE *fp = fopen(genderplotdata, "wt");
if(fp == NULL) error("Cannot open %s to write.", (const char*)genderplotdata);
fprintf(fp, "YCount\txHeterozygosity\tSEX\n");
for(int i = 0; i < plotx.Length(); i++)
fprintf(fp, "%d\t%.5lf\t%d\n", plotx[i], ploty[i], plotz[i]);
fclose(fp);
String genderplot=prefix;
genderplot.Add("_gender_autoplot.ps");
String scriptfile=prefix;
scriptfile.Add("_gender_autoplot.R");
fp = fopen(scriptfile, "wt");
if(fp == NULL) error("Cannot open %s to write.", (const char*)scriptfile);
fprintf(fp, "## %s for KING --autoQC, by Wei-Min Chen\n", (const char*)scriptfile);
fprintf(fp, "data <- read.table(file=\"%s\", header=T)\n", (const char*)genderplotdata);
fprintf(fp, "postscript(\"%s\", paper=\"letter\", horizontal=T)\n", (const char*)genderplot);
fprintf(fp, "isFemale<-data$SEX==2\n");
fprintf(fp, "isMale<-data$SEX==1\n");
fprintf(fp, "isUnknown<-data$SEX==0\n");
fprintf(fp, "cutoff<-max(data$YCount)/2\n");
fprintf(fp, "plot(data$YCount[isFemale],data$xHeterozygosity[isFemale], type=\"p\",\n");
fprintf(fp, " col=\"red\", xlim=c(0,max(data$YCount)), ylim=c(0,max(data$xHeterozygosity)),\n");
if(gendererrorCount){
fprintf(fp, " main=\"Gender Checking in %s Samples (%d Samples Mislabeled)\", \n",
(const char*)prefix, gendererrorCount);
fprintf(fp, " xlab=\"# Y-Chr SNPs\", ylab=\"X-Chr Heterozygosity\")\n");
}else{
fprintf(fp, " main=\"Gender Checking in %s Samples\", \n", (const char*)prefix);
fprintf(fp, " xlab=\"# Y-Chr SNPs\", ylab=\"X-Chr Heterozygosity\")\n");
}
fprintf(fp, "points(data$YCount[isMale], data$xHeterozygosity[isMale], col=\"blue\")\n");
fprintf(fp, "points(data$YCount[isUnknown], data$xHeterozygosity[isUnknown], col=\"black\")\n");
fprintf(fp, "points(data$YCount[isFemale&data$YCount>cutoff], data$xHeterozygosity[isFemale&data$YCount>cutoff], col=\"red\")\n");
fprintf(fp, "points(data$YCount[isMale&data$YCount<cutoff], data$xHeterozygosity[isMale&data$YCount<cutoff], col=\"blue\")\n");
fprintf(fp, "abline(v=cutoff, col=\"purple\", lty=2)\n");
fprintf(fp, "abline(v=cutoff*2/3, col=\"purple\")\n");
fprintf(fp, "abline(v=cutoff*4/3, col=\"purple\")\n");
fprintf(fp, "abline(h=%.4lf, col=\"purple\")\n", xHeterozygosity);
fprintf(fp, "legend(\"topright\", c(\"Female\", \"Male\", \"Unknown\"), col=c(\"red\", \"blue\", \"black\"),\n");
fprintf(fp, " text.col = c(\"red\", \"blue\", \"black\"), pch = 19, cex = 1.2)\n");
fprintf(fp, "dev.off()\n");
fclose(fp);
char command[256];
sprintf(command, "R CMD BATCH %s", (const char*)scriptfile);
system(command);
int error = CheckRout(scriptfile);
if(error == 2)
printf("--autoQC is done but R code %s failed.\n\n", (const char*)scriptfile);
else if(error){
printf("--autoQC is done but R code %s failed.\n", (const char*)scriptfile);
printf(" Please check %sout for details.\n\n", (const char*)scriptfile);
}else{
sprintf(command, "ps2pdf %s", (const char*)genderplot);
system(command);
printf("Gender plot are generated in %s_gender_autoplot.pdf\n", (const char*)prefix);
}
}
void plotPopStructure(const char *prefix, int projectFlag)
{
String scriptfile=prefix;
scriptfile.Add("_pcplot.R");
FILE *fp = fopen(scriptfile, "wt");
if(fp == NULL) error("Cannot open %s to write.", (const char*)scriptfile);
fprintf(fp, "## %s for KING --mds or --pca, by Wei-Min Chen\n", (const char*)scriptfile);
fprintf(fp, "postscript(\"%s_pcplot.ps\", paper=\"letter\", horizontal=T)\n",(const char*)prefix);
fprintf(fp, "data <- read.table(file=\"%spc.txt\", header=T)\n", (const char*)prefix);
fprintf(fp, "plot(data$PC1, data$PC2, type=\"p\", xlab=\"PC1\", ylab=\"PC2\", main = \"Population Structure in %s\")\n",(const char*)prefix);
if(projectFlag){
fprintf(fp, "points(data[data[,6]==2,7], data[data[,6]==2,8], col = \"red\")\n");
fprintf(fp, "legend(\"topright\", c(\"Reference Sample to Generate PCs\", \"Study Sample Projected to Reference PC Space\"),\n");
fprintf(fp, "col=c(\"black\",\"red\"),text.col = c(\"black\", \"red\"), pch = 19, cex = 1.2)\n");
}else
fprintf(fp, "plot(data$PC3, data$PC4, type=\"p\", xlab=\"PC3\", ylab=\"PC4\", main = \"Population Structure in %s\")\n",(const char*)prefix);
fprintf(fp, "dev.off()\n");
fclose(fp);
char command[256];
sprintf(command, "R CMD BATCH %s", (const char*)scriptfile);
system(command);
int error = CheckRout(scriptfile);
if(error == 2)
printf("--mds or --pca is done but R code %s failed.\n\n", (const char*)scriptfile);
else if(error){
printf("--ibdmap or --pca is done but R code %s failed.\n", (const char*)scriptfile);
printf(" Please check %sout for details.\n\n", (const char*)scriptfile);
}else{
sprintf(command, "ps2pdf %s_pcplot.ps", (const char*)prefix);
system(command);
printf("Population structure plot is generated in %s_pcplot.pdf\n", (const char*)prefix);
}
}
int CheckRout(const char *scriptfile)
{
String outfile=scriptfile;
outfile.Add("out");
int errorFlag = 1;
char buff[256]; // define the buffer and allocate the length
FILE *fp = fopen((const char*)outfile, "rb");
if(fp != NULL){
fseek(fp, -17, SEEK_END);// set pointer to the end of file minus the length you need. Presumably there can be more than one new line caracter
fread(buff, 16, 1, fp); // read the contents of the file starting from where fseek() positioned us
buff[16] = '\0'; // close the string
String lastline=buff;
if(lastline.Find("Execution halted")==-1) errorFlag = 0;
else{
fseek(fp, -100, SEEK_END); // set pointer to the end of file minus the length you need. Presumably there can be more than one new line caracter
fread(buff, 80, 1, fp); // read the contents of the file starting from where fseek() positioned us
buff[80] = '\0'; // close the string
lastline=buff;
if(lastline.Find("Error in library")>-1) errorFlag = 3;
}
fclose(fp); // close the file
}else errorFlag = 2; // unable to open .Rout file
return errorFlag;
}
void plotIBD1vsIBD2(const char *prefix, FILE *fp)
{
fprintf(fp, "if(length(data$IBD1Seg)>0 & length(data$IBD2Seg)>0){\n");
fprintf(fp, "d0 <- data$IBD2Seg>0.7\n");
fprintf(fp, "d1.PO <- (!d0) & data$IBD1Seg+data$IBD2Seg>0.96 | (data$IBD1Seg+data$IBD2Seg>0.9 & data$IBD2Seg<0.08)\n");
fprintf(fp, "d1.FS <- (!d0) & (!d1.PO) & data$PropIBD>0.35355 & data$IBD2Seg>=0.08\n");
fprintf(fp, "d2 <- data$PropIBD>0.17678 & data$IBD1Seg+data$IBD2Seg<=0.9 & (!d1.FS)\n");
fprintf(fp, "d3 <- data$PropIBD>0.08839 & data$PropIBD<=0.17678\n");
fprintf(fp, "d4 <- data$PropIBD>0.04419 & data$PropIBD<=0.08839\n");
fprintf(fp, "dU <- data$PropIBD>0 & data$PropIBD<=0.04419\n");
fprintf(fp, "plot(data$IBD1Seg[dU], data$IBD2Seg[dU], type=\"p\", col = \"black\", cex.lab=1.2,\n");
fprintf(fp, "xlim=c(min(data$IBD1Seg), max(data$IBD1Seg)),\n");
fprintf(fp, "ylim=c(min(data$IBD2Seg), max(data$IBD2Seg)),\n");
fprintf(fp, "main = \"IBD Segments In Inferred %s Relatives\",\n", (const char*)prefix);
fprintf(fp, "xlab=expression(paste(\"Length Proportion of IBD1 Segments (\", pi[1], \")\", sep=\"\")),\n");
fprintf(fp, "ylab=expression(paste(\"Length Proportion of IBD2 Segments (\", pi[2], \")\", sep=\"\")))\n");
fprintf(fp, "points(data$IBD1Seg[d0], data$IBD2Seg[d0], col=\"purple\")\n");
fprintf(fp, "points(data$IBD1Seg[d1.PO], data$IBD2Seg[d1.PO], col=\"red\")\n");
fprintf(fp, "points(data$IBD1Seg[d1.FS], data$IBD2Seg[d1.FS], col=\"green\")\n");
fprintf(fp, "points(data$IBD1Seg[d2], data$IBD2Seg[d2], col=\"blue\")\n");
fprintf(fp, "points(data$IBD1Seg[d3], data$IBD2Seg[d3], col=\"magenta\")\n");
fprintf(fp, "points(data$IBD1Seg[d4], data$IBD2Seg[d4], col=\"gold\")\n");
fprintf(fp, "abline(h = 0.08, col = \"green\", lty = 3, lwd = 2)\n"); // FS && MZ
fprintf(fp, "abline(a = 0.96, b = -1, col = \"red\", lty = 3, lwd = 2)\n"); // PO
fprintf(fp, "abline(a = 0.3535534, b = -0.5, col = \"green\", lty = 3, lwd = 2)\n");// FS
fprintf(fp, "abline(a = 0.1767767, b = -0.5, col = \"blue\", lty = 3, lwd = 2)\n");// 2nd/3rd
fprintf(fp, "abline(a = 0.08838835, b = -0.5, col = \"magenta\", lty = 3, lwd = 2)\n");// 3rd/4th
fprintf(fp, "abline(a = 0.04419, b = -0.5, col = \"gold\", lty = 3, lwd = 2)\n");// 4th/UN
fprintf(fp, "allcolors <- c(\"purple\", \"red\", \"green\", \"blue\", \"magenta\", \"gold\", \"black\")\n");
fprintf(fp, "legend(\"topright\", c(\"Inferred MZ\", \"Inferred PO\", \"Inferred FS\", \"Inferred 2nd\", \"Inferred 3rd\", \"Inferred 4th\", \"Inferred UN\"),\n");
fprintf(fp, " col=allcolors, text.col = allcolors, pch = 19, cex = 1.2)\n");
fprintf(fp, "}\n");
}
/*
void plotHetConcvsIBD2(const char *prefix)
{
String scriptfile=prefix;
scriptfile.Add("_ibd2plot.R");
FILE *fp = fopen(scriptfile, "wt");
if(fp == NULL) error("Cannot open %s to write.", (const char*)scriptfile);
fprintf(fp, "#%s for KING, by Wei-Min Chen\n", (const char*)scriptfile);
fprintf(fp, "postscript(\"%s_ibd2plot.ps\", paper=\"letter\", horizontal=T)\n",
(const char*)prefix);
fprintf(fp, "data <- read.table(file=\"%s.seg2\", header=T)\n", (const char*)prefix);
fprintf(fp, "valid <- data$Pr_IBD2>0.005\n");
fprintf(fp, "if(sum(valid)>0){\n");
fprintf(fp, "plot(data$Pr_IBD2[valid], data$HetConc[valid], type=\"p\",\n");
fprintf(fp, "col = \"black\", cex.lab=1.3,\n");
fprintf(fp, "main = \"Relationships In %s Families\",\n", (const char*)prefix);
fprintf(fp, "xlab=\"Proportion of IBD2 Segments\", ylab = \"Heterozygote Concordance Rate\")\n");
fprintf(fp, "}\n");
fprintf(fp, "dev.off()\n");
fclose(fp);
char command[256];
sprintf(command, "R CMD BATCH %s", (const char*)scriptfile);
system(command);
int error = CheckRout(scriptfile);
if(error == 2)
printf("R code %s cannot be run.\n", (const char*)scriptfile);
else if(error)
printf("Errors found in R code %s. Please check %sout for details.\n\n", (const char*)scriptfile, (const char*)scriptfile);
else{
sprintf(command, "ps2pdf %s_ibd2plot.ps", (const char*)prefix);
system(command);
printf(" Relationship plot is generated in %s_ibd2plot.pdf\n", (const char*)prefix);
}
}
void plotIBD2(const char *prefix)
{
String scriptfile=prefix;
scriptfile.Add("_ibd2plot.R");
FILE *fp = fopen(scriptfile, "wt");
if(fp == NULL) error("Cannot open %s to write.", (const char*)scriptfile);
fprintf(fp, "postscript(\"%s_ibd2plot.ps\", paper=\"letter\", horizontal=T)\n",
(const char*)prefix);
fprintf(fp, "data <- read.table(file=\"%s.ibs\", header=T)\n", (const char*)prefix);
fprintf(fp, "if(dim(data)[1]>0){\n");
fprintf(fp, "d0 <- data$Phi==0.5\n");
fprintf(fp, "d1.PO <- data$Phi==0.25 & data$Z0==0\n");
fprintf(fp, "d1.FS <- data$Phi==0.25 & data$Z0>0\n");
fprintf(fp, "d2 <- data$Phi==0.125\n");
fprintf(fp, "dU <- data$Phi==0\n");
fprintf(fp, "dO <- !d0 & !d1.PO & !d1.FS & !d2 & !dU\n");
fprintf(fp, "plot(data$Pr_IBD2[dU], data$Kinship[dU], type=\"p\",\n");
fprintf(fp, "col = \"black\", cex.lab=1.3,\n");
fprintf(fp, "xlim = c(min(data$Pr_IBD2), max(data$Pr_IBD2)),\n");
fprintf(fp, "ylim = c(min(data$Kinship), max(data$Kinship)),\n");
fprintf(fp, "main = \"Relationships In %s Families\",\n", (const char*)prefix);
fprintf(fp, "xlab=\"Proportion of IBD2 Segments\", ylab = \"Estimated Kinship Coefficient\")\n");
fprintf(fp, "points(data$Pr_IBD2[d0], data$Kinship[d0], col=\"purple\")\n");
fprintf(fp, "points(data$Pr_IBD2[d1.PO], data$Kinship[d1.PO], col=\"red\")\n");
fprintf(fp, "points(data$Pr_IBD2[d1.FS], data$Kinship[d1.FS], col=\"green\")\n");
fprintf(fp, "points(data$Pr_IBD2[d2], data$Kinship[d2], col=\"blue\")\n");
fprintf(fp, "points(data$Pr_IBD2[dO], data$Kinship[dO], col=\"gold\")\n");
fprintf(fp, "points(data$Pr_IBD2[dU & data$Kinship>0.088], data$Kinship[dU & data$Kinship>0.088], col=\"black\")\n");
fprintf(fp, "points(data$Pr_IBD2[d1.FS & data$Pr_IBD2<0.05], data$Kinship[d1.FS & data$Pr_IBD2<0.05], col=\"green\")\n");
fprintf(fp, "abline(h = 0.3536, col = \"red\", lty = 3)\n");
fprintf(fp, "abline(h = 0.1768, col = \"green\", lty = 3)\n");
fprintf(fp, "abline(h = 0.0884, col = \"blue\", lty = 3)\n");
fprintf(fp, "abline(h = 0.0442, col = \"black\", lty = 3)\n");
fprintf(fp, "legend(\"bottomright\", c(\"MZ Twin\", \"Parent-Offspring\", \"Full Siblings\", \"2nd-Degree\", \"More Distant\", \"Unrelated\"),\n");
fprintf(fp, "col=c(\"purple\", \"red\", \"green\", \"blue\", \"gold\", \"black\"),\n");
fprintf(fp, "text.col = c(\"purple\", \"red\", \"green\", \"blue\", \"gold\", \"black\"), pch = 19, cex = 1.2)\n");
fprintf(fp, "}\n");
fprintf(fp, "dev.off()\n");
fclose(fp);
char command[256];
sprintf(command, "R CMD BATCH %s", (const char*)scriptfile);
system(command);
int error = CheckRout(scriptfile);
if(error == 2)
printf("R code %s cannot be run.\n", (const char*)scriptfile);
else if(error)
printf("Errors found in R code %s. Please check %sout for details.\n\n", (const char*)scriptfile, (const char*)scriptfile);
else{
sprintf(command, "ps2pdf %s_ibd2plot.ps", (const char*)prefix);
system(command);
printf(" Relationship plot is generated in %s_ibd2plot.pdf\n", (const char*)prefix);
}
}
*/
/*
fprintf(fp, "data <- read.table(file=\"%s\", nrows=2000, header=TRUE, stringsAsFactors=FALSE)[,c(\"ID1\", \"ID2\", \"InfType\")]\n", (const char*)inputfile);
fprintf(fp, "postscript(\"%s_relativeplot.ps\", paper=\"letter\", horizontal=T)\n", prefix);
if(degree == 1){
fprintf(fp, "Inf.color <- c(\"purple\", \"red\", \"green\")\n");
fprintf(fp, "Inf.type <- c(\"DUP/MZ\", \"PO\", \"FS\")\n");
}else if(degree == 2){
fprintf(fp, "Inf.color <- c(\"purple\", \"red\", \"green\", \"blue\")\n");
fprintf(fp, "Inf.type <- c(\"DUP/MZ\", \"PO\", \"FS\", \"2nd\")\n");
}else{
fprintf(fp, "Inf.color <- c(\"purple\", \"red\", \"green\", \"blue\", \"yellow\")\n");
fprintf(fp, "Inf.type <- c(\"DUP/MZ\", \"PO\", \"FS\", \"2nd\", \"3rd\")\n");
}
fprintf(fp, "relatives <- data[data$InfType %%in%% Inf.type,]\n");
fprintf(fp, "count.rp <- min(dim(relatives)[1],1000)\n");
fprintf(fp, "relatives <- relatives[1:count.rp,]\n");
fprintf(fp, "for(i in 1:length(Inf.type)) relatives[relatives$InfType==Inf.type[i],\"InfType\"] <- i\n");
fprintf(fp, "g <- graph_from_data_frame(d=relatives, vertices=unique(c(relatives$ID1,relatives$ID2)), directed=FALSE)\n");
fprintf(fp, "plot(g, vertex.color=NA, vertex.size=1, vertex.label=NA, layout=layout_with_fr, asp=0,\n");
fprintf(fp, "edge.color=Inf.color[as.numeric(relatives$InfType)], main=paste(count.rp, \"Relative Pairs in %s\"))\n", prefix);
fprintf(fp, "legend(\"bottomright\", Inf.type, lty=1, col=Inf.color, text.col=Inf.color, pt.cex=2, cex=0.8, bty=\"n\")\n");
*/
/*
fprintf(fp, " }else if(v[1]==4){\n");
fprintf(fp, " if(v[2]==5 && v[4]==4 && v[5]==1) buildType <- \"2_Parents+2_FullSiblings\"\n");
fprintf(fp, " else if(v[2]==6 && v[4]==3 && v[5]==3) buildType <- \"1_Parent+3_FullSiblings\"\n");
fprintf(fp, " else if(v[2]==6 && v[5]==6) buildType <- \"4_FullSiblings\"\n");
fprintf(fp, " }else if(v[1]==5){\n");
fprintf(fp, " if(v[2]==9 && v[4]==6 && v[5]==3) buildType <- \"2_Parents+3_FullSiblings\"\n");
fprintf(fp, " else if(v[2]==10 && v[4]==4 && v[5]==6) buildType <- \"1_Parents+4_FullSiblings\"\n");
fprintf(fp, " else if(v[2]==10 && v[5]==10) buildType <- \"5_FullSiblings\"\n");
fprintf(fp, " }else if(v[1]==6){\n");
fprintf(fp, " if(v[2]==14 && v[4]==8 && v[5]==6) buildType <- \"2_Parents+4_FullSiblings\"\n");
fprintf(fp, " else if(v[2]==15 && v[4]==5 && v[5]==10) buildType <- \"1_Parent+5_FullSiblings\"\n");
fprintf(fp, " else if(v[2]==15 && v[5]==15) buildType <- \"6_FullSiblings\"\n");
fprintf(fp, " }else if(v[1]==7){\n");
fprintf(fp, " if(v[2]==20 && v[4]==10 && v[5]==10) buildType <- \"2_Parents+5_FullSiblings\"\n");
fprintf(fp, " else if(v[2]==21 && v[4]==6 && v[5]==15) buildType <- \"1_Parent+6_FullSiblings\"\n");
fprintf(fp, " else if(v[2]==21 && v[5]==21) buildType <- \"7_FullSiblings\"\n");
fprintf(fp, " }\n");
*/
| 59.420554 | 199 | 0.591138 | [
"shape",
"vector"
] |
0fc9dc89adffe8b4ab2a694a176a43f43ecc3fe8 | 14,348 | cpp | C++ | src/jablotron/JablotronDeviceManager.cpp | jalowiczor/gateway | 612a08d6154e8768dfd30f1e1f00de1bfcad090f | [
"BSD-3-Clause"
] | null | null | null | src/jablotron/JablotronDeviceManager.cpp | jalowiczor/gateway | 612a08d6154e8768dfd30f1e1f00de1bfcad090f | [
"BSD-3-Clause"
] | null | null | null | src/jablotron/JablotronDeviceManager.cpp | jalowiczor/gateway | 612a08d6154e8768dfd30f1e1f00de1bfcad090f | [
"BSD-3-Clause"
] | null | null | null | #include <Poco/RegularExpression.h>
#include <Poco/Thread.h>
#include <Poco/StringTokenizer.h>
#include "commands/NewDeviceCommand.h"
#include "core/CommandDispatcher.h"
#include "di/Injectable.h"
#include "io/AutoClose.h"
#include "jablotron/JablotronDeviceAC88.h"
#include "jablotron/JablotronDeviceManager.h"
#include "hotplug/HotplugEvent.h"
#include "util/LambdaTimerTask.h"
BEEEON_OBJECT_BEGIN(BeeeOn, JablotronDeviceManager)
BEEEON_OBJECT_CASTABLE(CommandHandler)
BEEEON_OBJECT_CASTABLE(StoppableRunnable)
BEEEON_OBJECT_CASTABLE(HotplugListener)
BEEEON_OBJECT_PROPERTY("distributor", &JablotronDeviceManager::setDistributor)
BEEEON_OBJECT_PROPERTY("commandDispatcher", &JablotronDeviceManager::setCommandDispatcher)
BEEEON_OBJECT_PROPERTY("attemptsCount", &JablotronDeviceManager::setAttemptsCount)
BEEEON_OBJECT_PROPERTY("retryTimeout", &JablotronDeviceManager::setRetryTimeout)
BEEEON_OBJECT_END(BeeeOn, JablotronDeviceManager)
using namespace BeeeOn;
using namespace Poco;
using namespace std;
static const string JABLOTRON_VENDOR_ID = "0403";
static const string JABLOTRON_PRODUCT_ID = "6015";
static const string VENDOR_NAME = "Jablotron";
static const int BAUD_RATE = 57600;
static const int MAX_DEVICES_IN_JABLOTRON = 32;
static const int NUMBER_OF_RETRIES = 3;
static const int MAX_NUMBER_FAILED_REPEATS = 10;
static const int RESPONSE_WAIT_MSEC = 5000;
static const int DEFAULT_PG_VALUE = 0;
static const Timespan READ_TIMEOUT = 1 * Timespan::SECONDS;
static const Timespan SLEEP_AFTER_FAILED = 1 * Timespan::SECONDS;
static const Timespan DELAY_AFTER_SET_SWITCH = 1 * Timespan::SECONDS;
static const Timespan DELAY_BEETWEEN_CYCLES = 300 * Timespan::MILLISECONDS;
static const DeviceID DEFAULT_DEVICE_ID(DevicePrefix::PREFIX_JABLOTRON, 0);
JablotronDeviceManager::JablotronDeviceManager():
DongleDeviceManager(DevicePrefix::PREFIX_JABLOTRON),
m_lastResponse(NONE),
m_isListen(false),
m_pgx(DEFAULT_DEVICE_ID, DEFAULT_PG_VALUE),
m_pgy(DEFAULT_DEVICE_ID, DEFAULT_PG_VALUE)
{
}
void JablotronDeviceManager::initJablotronDongle()
{
m_serial.setBaudRate(BAUD_RATE);
m_serial.setStopBits(SerialPort::StopBits::STOPBITS_1);
m_serial.setParity(SerialPort::Parity::PARITY_NONE);
m_serial.setDataBits(SerialPort::DataBits::DATABITS_8);
m_serial.setNonBlocking(true);
m_serial.setDevicePath(dongleName());
m_serial.open();
m_serial.flush();
}
void JablotronDeviceManager::dongleVersion()
{
string message;
m_serial.write("\x1BWHO AM I?\n");
if (nextMessage(message) != MessageType::DATA) {
logger().warning(
"unexpected response: " + message,
__FILE__, __LINE__);
return;
}
if (wasTurrisDongleVersion(message)) {
logger().information(
"Jablotron Dongle version: "
+ message,
__FILE__, __LINE__);
}
else {
logger().warning(
"unknown dongle version: " + message,
__FILE__, __LINE__);
}
}
void JablotronDeviceManager::dongleAvailable()
{
AutoClose<SerialPort> serial(m_serial);
m_devices.clear();
initJablotronDongle();
dongleVersion();
jablotronProcess();
}
void JablotronDeviceManager::stop()
{
DongleDeviceManager::stop();
m_listenTimer.cancel(true);
answerQueue().dispose();
}
void JablotronDeviceManager::jablotronProcess()
{
string message;
setupDongleDevices();
loadDeviceList();
while (!m_stop) {
MessageType response = nextMessage(message);
if (isResponse(response)) {
m_lastResponse = response;
m_responseRcv.set();
continue;
}
if (response != MessageType::DATA) {
logger().warning(
"unexpected response: " + message,
__FILE__, __LINE__);
continue;
}
DeviceID id = JablotronDevice::buildID(extractSerialNumber(message));
Mutex::ScopedLock guard(m_lock);
auto it = m_devices.find(id);
if (it != m_devices.end() && !it->second.isNull() && it->second->paired()) {
shipMessage(message, it->second);
}
else if (it != m_devices.end() && m_isListen) {
doNewDevice(id, it);
}
else {
logger().debug(
"device " + id.toString()
+ " is not paired",
__FILE__, __LINE__);
}
}
}
bool JablotronDeviceManager::accept(const Command::Ptr cmd)
{
if (cmd->is<DeviceSetValueCommand>())
return cmd->cast<DeviceSetValueCommand>().deviceID().prefix() == m_prefix;
else if (cmd->is<GatewayListenCommand>())
return true;
else if (cmd->is<DeviceUnpairCommand>()) {
auto it = m_devices.find(cmd->cast<DeviceUnpairCommand>().deviceID());
return it != m_devices.end();
}
else if (cmd->is<DeviceAcceptCommand>()) {
return cmd->cast<DeviceAcceptCommand>().deviceID().prefix() == m_prefix;
}
return false;
}
void JablotronDeviceManager::handle(Command::Ptr cmd, Answer::Ptr answer)
{
if (cmd->is<DeviceSetValueCommand>())
doSetValue(cmd.cast<DeviceSetValueCommand>(), answer);
else if (cmd->is<GatewayListenCommand>())
doListenCommand(cmd.cast<GatewayListenCommand>(), answer);
else if (cmd->is<DeviceUnpairCommand>())
doUnpairCommand(cmd.cast<DeviceUnpairCommand>(), answer);
else if (cmd->is<DeviceAcceptCommand>())
doDeviceAcceptCommand(cmd.cast<DeviceAcceptCommand>(), answer);
else
throw IllegalStateException("received unaccepted command");
}
void JablotronDeviceManager::doDeviceAcceptCommand(
const DeviceAcceptCommand::Ptr cmd, const Answer::Ptr answer)
{
Mutex::ScopedLock guard(m_lock);
Result::Ptr result = new Result(answer);
auto it = m_devices.find(cmd->deviceID());
if (it == m_devices.end()) {
logger().error(
"unknown " + cmd->deviceID().toString()
+ " device", __FILE__, __LINE__);
result->setStatus(Result::Status::FAILED);
} else {
it->second->setPaired(true);
result->setStatus(Result::Status::SUCCESS);
}
}
void JablotronDeviceManager::doUnpairCommand(
const DeviceUnpairCommand::Ptr cmd, const Answer::Ptr answer)
{
Result::Ptr result = new Result(answer);
Mutex::ScopedLock guard(m_lock);
auto it = m_devices.find(cmd->deviceID());
if (it != m_devices.end()) {
it->second = nullptr;
}
else {
logger().warning(
"attempt to unpair unknown device: "
+ cmd->deviceID().toString());
}
result->setStatus(Result::Status::SUCCESS);
}
void JablotronDeviceManager::doListenCommand(
const GatewayListenCommand::Ptr cmd, const Answer::Ptr answer)
{
Result::Ptr result = new Result(answer);
result->setStatus(Result::Status::SUCCESS);
if (m_isListen)
return;
m_isListen = true;
LambdaTimerTask::Ptr task(new LambdaTimerTask([=]()
{
logger().debug("listen is done", __FILE__, __LINE__);
m_isListen = false;
Mutex::ScopedLock guard(m_lock);
for (auto &device : m_devices) {
if (device.second.isNull())
continue;
if (!device.second->paired())
device.second = nullptr;
}
}));
m_listenTimer.schedule(
task,
Timestamp() + cmd->duration());
}
void JablotronDeviceManager::doNewDevice(const DeviceID &deviceID,
map<DeviceID, JablotronDevice::Ptr>::iterator &it)
{
if (it->second.isNull()) {
try {
it->second = JablotronDevice::create(deviceID.ident());
}
catch (const InvalidArgumentException &ex) {
logger().log(ex, __FILE__, __LINE__);
return;
}
it->second->setPaired(false);
}
NewDeviceCommand::Ptr cmd =
new NewDeviceCommand(
it->second->deviceID(),
VENDOR_NAME,
it->second->name(),
it->second->moduleTypes(),
it->second->refreshTime()
);
dispatch(cmd);
}
void JablotronDeviceManager::loadDeviceList()
{
set<DeviceID> deviceIDs = deviceList(-1);
Mutex::ScopedLock guard(m_lock);
for (auto &id : deviceIDs) {
auto it = m_devices.find(id);
if (it != m_devices.end()) {
try {
it->second = JablotronDevice::create(id.ident());
}
catch (const InvalidArgumentException &ex) {
logger().log(ex, __FILE__, __LINE__);
continue;
}
it->second->setPaired(true);
}
}
obtainLastValue();
}
JablotronDeviceManager::MessageType JablotronDeviceManager::nextMessage(
string &message)
{
// find message between newline
// message example: \nAC-88 RELAY:1\n
const RegularExpression re("(?!\\n)[^\\n]*(?=\\n)");
while (!re.extract(m_buffer, message) && !m_stop) {
try {
m_buffer += m_serial.read(READ_TIMEOUT);
}
catch (const TimeoutException &ex) {
// avoid frozen state, allow to test m_stop time after time
continue;
}
}
// erase matched message from buffer + 2x newline
m_buffer.erase(0, message.size() + 2);
logger().trace("received data: " + message, __FILE__, __LINE__);
return messageType(message);
}
JablotronDeviceManager::MessageType JablotronDeviceManager::messageType(
const string &data)
{
if (data == "OK")
return MessageType::OK;
else if (data == "ERROR")
return MessageType::ERROR;
return MessageType::DATA;
}
bool JablotronDeviceManager::wasTurrisDongleVersion(
const string &message) const
{
const RegularExpression re("TURRIS DONGLE V[0-9].[0-9]*");
return re.match(message);
}
void JablotronDeviceManager::setupDongleDevices()
{
string buffer;
for (int i = 0; i < MAX_DEVICES_IN_JABLOTRON; i++) {
Mutex::ScopedLock guard(m_lock);
// we need 2-digits long value (zero-prefixed when needed)
m_serial.write("\x1BGET SLOT:" + NumberFormatter::format0(i, 2) + "\n");
if (nextMessage(buffer) != MessageType::DATA) {
logger().error(
"unknown message: " + buffer,
__FILE__, __LINE__
);
continue;
}
// finding empty slot: SLOT:XX [--------]
RegularExpression re(".*[--------].*");
if (re.match(buffer)) {
logger().trace("empty slot", __FILE__, __LINE__);
continue;
}
try {
uint32_t serialNumber = extractSerialNumber(buffer);
DeviceID deviceID = JablotronDevice::buildID(serialNumber);
// create empty JablotronDevice
// after the obtain server device list, create JablotronDevice for paired devices
m_devices.emplace(deviceID, nullptr);
logger().debug(
"created device: " + to_string(serialNumber)
+ " from dongle", __FILE__, __LINE__);
if (JablotronDevice::create(serialNumber).cast<JablotronDeviceAC88>().isNull())
continue;
if (m_pgx.first == DEFAULT_DEVICE_ID)
m_pgx.first = deviceID;
else
m_pgy.first = deviceID;
}
catch (const InvalidArgumentException &ex) {
logger().log(ex, __FILE__, __LINE__);
}
catch (const SyntaxException &ex) {
logger().log(ex, __FILE__, __LINE__);
}
}
}
uint32_t JablotronDeviceManager::extractSerialNumber(const string &message)
{
RegularExpression re("\\[([0-9]+)\\]");
vector<string> tmp;
if (re.split(message, tmp) == 2)
return NumberParser::parseUnsigned(tmp[1]);
throw InvalidArgumentException(
"invalid serial number string: " + message);
}
void JablotronDeviceManager::shipMessage(
const string &message, JablotronDevice::Ptr jablotronDevice)
{
try {
ship(jablotronDevice->extractSensorData(message));
}
catch (const RangeException &ex) {
logger().error(
"unexpected token index in message: " + message,
__FILE__, __LINE__
);
}
catch (const Exception &ex) {
logger().log(ex, __FILE__, __LINE__);
};
}
string JablotronDeviceManager::dongleMatch(const HotplugEvent &e)
{
const string &productID = e.properties()
->getString("tty.ID_MODEL_ID", "");
const string &vendorID = e.properties()
->getString("tty.ID_VENDOR_ID", "");
if (e.subsystem() == "tty") {
if (vendorID == JABLOTRON_VENDOR_ID
&& productID == JABLOTRON_PRODUCT_ID)
return e.node();
}
return "";
}
/* Retransmission packet status is recommended to be done 3 times with
* a minimum gap 200ms and 500ms maximum space (for an answer) - times
* in the space, it is recommended to choose random.
*/
bool JablotronDeviceManager::transmitMessage(const string &msg, bool autoResult)
{
string message;
for (int i = 0; i < NUMBER_OF_RETRIES; i++) {
if (!m_serial.write(msg)) {
Thread::sleep(SLEEP_AFTER_FAILED.totalMilliseconds());
continue;
}
if (!autoResult) {
int i = 0;
while(!getResponse() && i < NUMBER_OF_RETRIES)
i++;
}
if (m_responseRcv.tryWait(RESPONSE_WAIT_MSEC)) {
if (m_lastResponse == ERROR) {
Thread::sleep(DELAY_BEETWEEN_CYCLES.totalMilliseconds());
continue;
}
Thread::sleep(DELAY_AFTER_SET_SWITCH.totalMilliseconds());
return true;
}
else {
poco_error(logger(), "no response received");
return false;
}
}
Thread::sleep(DELAY_AFTER_SET_SWITCH.totalMilliseconds());
return false;
}
bool JablotronDeviceManager::getResponse()
{
string message;
MessageType response = nextMessage(message);
if (isResponse(response)) {
m_lastResponse = response;
m_responseRcv.set();
return true;
}
return false;
}
bool JablotronDeviceManager::isResponse(MessageType type)
{
return type == OK || type == ERROR;
}
bool JablotronDeviceManager::modifyValue(
const DeviceID &deviceID, int value, bool autoResult)
{
Mutex::ScopedLock guard(m_lock);
auto it = m_devices.find(deviceID);
if (it == m_devices.end()) {
throw NotFoundException(
"device " + deviceID.toString()
+ " not found");
}
if (it->second.cast<JablotronDeviceAC88>().isNull()) {
throw InvalidArgumentException(
"device " + it->first.toString()
+ " is not Jablotron AC-88");
}
if (!it->second->paired()) {
InvalidArgumentException(
"device " + it->first.toString()
+ " is not paired");
}
if (m_pgx.first == deviceID)
m_pgx.second = value;
else
m_pgy.second = value;
string modifyString = "\x1BTX ENROLL:0 PGX:" + to_string(m_pgx.second) +
" PGY:" + to_string(m_pgy.second) + " ALARM:0 BEEP:FAST\n";
return transmitMessage(modifyString, autoResult);
}
void JablotronDeviceManager::obtainLastValue()
{
int value;
for (auto &device : m_devices) {
if (device.second.cast<JablotronDeviceAC88>().isNull())
continue;
if (!device.second->paired())
continue;
try {
value = lastValue(device.first, 0);
}
catch (const Exception &ex) {
logger().log(ex, __FILE__, __LINE__);
continue;
}
if (!modifyValue(device.first, value, false)) {
logger().warning(
"last value on device: " + device.first.toString()
+ " is not set",
__FILE__, __LINE__);
}
}
}
void JablotronDeviceManager::doSetValue(
DeviceSetValueCommand::Ptr cmd, Answer::Ptr answer)
{
Result::Ptr result = new Result(answer);
bool ret = false;
try {
ret = modifyValue(cmd->deviceID(), cmd->value());
}
catch (const Exception &ex) {
logger().log(ex, __FILE__, __LINE__);
}
if (ret)
result->setStatus(Result::Status::SUCCESS);
else
result->setStatus(Result::Status::FAILED);
}
| 24.652921 | 90 | 0.709855 | [
"vector"
] |
0fcd0c56a49813011b63690692b4a8e1b75738be | 27,160 | cpp | C++ | lib/Parser/rust-api.cpp | matinzd/hermes | 14eec7ffd8889c1dceb7886b3fee86becdfed452 | [
"MIT"
] | 2 | 2021-09-28T13:22:37.000Z | 2021-12-20T12:05:19.000Z | lib/Parser/rust-api.cpp | matinzd/hermes | 14eec7ffd8889c1dceb7886b3fee86becdfed452 | [
"MIT"
] | null | null | null | lib/Parser/rust-api.cpp | matinzd/hermes | 14eec7ffd8889c1dceb7886b3fee86becdfed452 | [
"MIT"
] | 1 | 2021-12-24T11:25:24.000Z | 2021-12-24T11:25:24.000Z | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/*
* This file exposes a C API for use by Rust. It cannot actually be used from C
* as is, because the function declarations themselves require C++ types.
* Addressing that would require non-trivial effort, which for now we have
* chosen not to do, given that we don't have a use case for C, just Rust. For
* that reason we are not exposing a header file - there is no possible
* consumer for that file.
*/
#include "hermes/Parser/JSParser.h"
#include "hermes/Support/SimpleDiagHandler.h"
// As explained above, we don't have a header with prototypes for this file.
#if defined(__GNUC__) && defined(__clang__)
#pragma clang diagnostic ignored "-Wmissing-prototypes"
#elif defined(__GNUC__)
#pragma GCC diagnostic ignored "-Wmissing-prototypes"
#endif
using llvh::cast;
using llvh::dyn_cast;
using llvh::isa;
using namespace hermes;
using namespace hermes::ESTree;
// While we return almost all attributes unmodified by value, that doesn't work
// for NodeList (since it is the head of a circular list) and we need to return
// a pointer to it.
// So some templating to adjust the return type of the getter depending on the
// type of the AST attribute.
namespace {
template <class T>
struct ReturnType {
using Type = T;
static inline Type get(T x) {
return x;
}
};
template <>
struct ReturnType<NodeList> {
using Type = const NodeList *;
static inline Type get(const NodeList &x) {
return &x;
}
};
} // namespace
#define ESTREE_FIRST(NAME, ...)
#define ESTREE_NODE_0_ARGS(NAME, ...)
// NOTE: -fomit-frame-pointer helps here
#define ESTREE_NODE_1_ARGS(NAME, BASE, ARG0TY, ARG0NM, ARG0OPT) \
extern "C" ReturnType<ARG0TY>::Type hermes_get_##NAME##_##ARG0NM( \
const NAME##Node *node) { \
return ReturnType<ARG0TY>::get(node->_##ARG0NM); \
}
#define ESTREE_NODE_2_ARGS( \
NAME, BASE, ARG0TY, ARG0NM, ARG0OPT, ARG1TY, ARG1NM, ARG1OPT) \
extern "C" ReturnType<ARG0TY>::Type hermes_get_##NAME##_##ARG0NM( \
const NAME##Node *node) { \
return ReturnType<ARG0TY>::get(node->_##ARG0NM); \
} \
extern "C" ReturnType<ARG1TY>::Type hermes_get_##NAME##_##ARG1NM( \
const NAME##Node *node) { \
return ReturnType<ARG1TY>::get(node->_##ARG1NM); \
}
#define ESTREE_NODE_3_ARGS( \
NAME, \
BASE, \
ARG0TY, \
ARG0NM, \
ARG0OPT, \
ARG1TY, \
ARG1NM, \
ARG1OPT, \
ARG2TY, \
ARG2NM, \
ARG2OPT) \
extern "C" ReturnType<ARG0TY>::Type hermes_get_##NAME##_##ARG0NM( \
const NAME##Node *node) { \
return ReturnType<ARG0TY>::get(node->_##ARG0NM); \
} \
extern "C" ReturnType<ARG1TY>::Type hermes_get_##NAME##_##ARG1NM( \
const NAME##Node *node) { \
return ReturnType<ARG1TY>::get(node->_##ARG1NM); \
} \
extern "C" ReturnType<ARG2TY>::Type hermes_get_##NAME##_##ARG2NM( \
const NAME##Node *node) { \
return ReturnType<ARG2TY>::get(node->_##ARG2NM); \
}
#define ESTREE_NODE_4_ARGS( \
NAME, \
BASE, \
ARG0TY, \
ARG0NM, \
ARG0OPT, \
ARG1TY, \
ARG1NM, \
ARG1OPT, \
ARG2TY, \
ARG2NM, \
ARG2OPT, \
ARG3TY, \
ARG3NM, \
ARG3OPT) \
extern "C" ReturnType<ARG0TY>::Type hermes_get_##NAME##_##ARG0NM( \
const NAME##Node *node) { \
return ReturnType<ARG0TY>::get(node->_##ARG0NM); \
} \
extern "C" ReturnType<ARG1TY>::Type hermes_get_##NAME##_##ARG1NM( \
const NAME##Node *node) { \
return ReturnType<ARG1TY>::get(node->_##ARG1NM); \
} \
extern "C" ReturnType<ARG2TY>::Type hermes_get_##NAME##_##ARG2NM( \
const NAME##Node *node) { \
return ReturnType<ARG2TY>::get(node->_##ARG2NM); \
} \
extern "C" ReturnType<ARG3TY>::Type hermes_get_##NAME##_##ARG3NM( \
const NAME##Node *node) { \
return ReturnType<ARG3TY>::get(node->_##ARG3NM); \
}
#define ESTREE_NODE_5_ARGS( \
NAME, \
BASE, \
ARG0TY, \
ARG0NM, \
ARG0OPT, \
ARG1TY, \
ARG1NM, \
ARG1OPT, \
ARG2TY, \
ARG2NM, \
ARG2OPT, \
ARG3TY, \
ARG3NM, \
ARG3OPT, \
ARG4TY, \
ARG4NM, \
ARG4OPT) \
extern "C" ReturnType<ARG0TY>::Type hermes_get_##NAME##_##ARG0NM( \
const NAME##Node *node) { \
return ReturnType<ARG0TY>::get(node->_##ARG0NM); \
} \
extern "C" ReturnType<ARG1TY>::Type hermes_get_##NAME##_##ARG1NM( \
const NAME##Node *node) { \
return ReturnType<ARG1TY>::get(node->_##ARG1NM); \
} \
extern "C" ReturnType<ARG2TY>::Type hermes_get_##NAME##_##ARG2NM( \
const NAME##Node *node) { \
return ReturnType<ARG2TY>::get(node->_##ARG2NM); \
} \
extern "C" ReturnType<ARG3TY>::Type hermes_get_##NAME##_##ARG3NM( \
const NAME##Node *node) { \
return ReturnType<ARG3TY>::get(node->_##ARG3NM); \
} \
extern "C" ReturnType<ARG4TY>::Type hermes_get_##NAME##_##ARG4NM( \
const NAME##Node *node) { \
return ReturnType<ARG4TY>::get(node->_##ARG4NM); \
}
#define ESTREE_NODE_6_ARGS( \
NAME, \
BASE, \
ARG0TY, \
ARG0NM, \
ARG0OPT, \
ARG1TY, \
ARG1NM, \
ARG1OPT, \
ARG2TY, \
ARG2NM, \
ARG2OPT, \
ARG3TY, \
ARG3NM, \
ARG3OPT, \
ARG4TY, \
ARG4NM, \
ARG4OPT, \
ARG5TY, \
ARG5NM, \
ARG5OPT) \
extern "C" ReturnType<ARG0TY>::Type hermes_get_##NAME##_##ARG0NM( \
const NAME##Node *node) { \
return ReturnType<ARG0TY>::get(node->_##ARG0NM); \
} \
extern "C" ReturnType<ARG1TY>::Type hermes_get_##NAME##_##ARG1NM( \
const NAME##Node *node) { \
return ReturnType<ARG1TY>::get(node->_##ARG1NM); \
} \
extern "C" ReturnType<ARG2TY>::Type hermes_get_##NAME##_##ARG2NM( \
const NAME##Node *node) { \
return ReturnType<ARG2TY>::get(node->_##ARG2NM); \
} \
extern "C" ReturnType<ARG3TY>::Type hermes_get_##NAME##_##ARG3NM( \
const NAME##Node *node) { \
return ReturnType<ARG3TY>::get(node->_##ARG3NM); \
} \
extern "C" ReturnType<ARG4TY>::Type hermes_get_##NAME##_##ARG4NM( \
const NAME##Node *node) { \
return ReturnType<ARG4TY>::get(node->_##ARG4NM); \
} \
extern "C" ReturnType<ARG5TY>::Type hermes_get_##NAME##_##ARG5NM( \
const NAME##Node *node) { \
return ReturnType<ARG5TY>::get(node->_##ARG5NM); \
}
#define ESTREE_NODE_7_ARGS( \
NAME, \
BASE, \
ARG0TY, \
ARG0NM, \
ARG0OPT, \
ARG1TY, \
ARG1NM, \
ARG1OPT, \
ARG2TY, \
ARG2NM, \
ARG2OPT, \
ARG3TY, \
ARG3NM, \
ARG3OPT, \
ARG4TY, \
ARG4NM, \
ARG4OPT, \
ARG5TY, \
ARG5NM, \
ARG5OPT, \
ARG6TY, \
ARG6NM, \
ARG6OPT) \
extern "C" ReturnType<ARG0TY>::Type hermes_get_##NAME##_##ARG0NM( \
const NAME##Node *node) { \
return ReturnType<ARG0TY>::get(node->_##ARG0NM); \
} \
extern "C" ReturnType<ARG1TY>::Type hermes_get_##NAME##_##ARG1NM( \
const NAME##Node *node) { \
return ReturnType<ARG1TY>::get(node->_##ARG1NM); \
} \
extern "C" ReturnType<ARG2TY>::Type hermes_get_##NAME##_##ARG2NM( \
const NAME##Node *node) { \
return ReturnType<ARG2TY>::get(node->_##ARG2NM); \
} \
extern "C" ReturnType<ARG3TY>::Type hermes_get_##NAME##_##ARG3NM( \
const NAME##Node *node) { \
return ReturnType<ARG3TY>::get(node->_##ARG3NM); \
} \
extern "C" ReturnType<ARG4TY>::Type hermes_get_##NAME##_##ARG4NM( \
const NAME##Node *node) { \
return ReturnType<ARG4TY>::get(node->_##ARG4NM); \
} \
extern "C" ReturnType<ARG5TY>::Type hermes_get_##NAME##_##ARG5NM( \
const NAME##Node *node) { \
return ReturnType<ARG5TY>::get(node->_##ARG5NM); \
} \
extern "C" ReturnType<ARG6TY>::Type hermes_get_##NAME##_##ARG6NM( \
const NAME##Node *node) { \
return ReturnType<ARG6TY>::get(node->_##ARG6NM); \
}
#define ESTREE_NODE_8_ARGS( \
NAME, \
BASE, \
ARG0TY, \
ARG0NM, \
ARG0OPT, \
ARG1TY, \
ARG1NM, \
ARG1OPT, \
ARG2TY, \
ARG2NM, \
ARG2OPT, \
ARG3TY, \
ARG3NM, \
ARG3OPT, \
ARG4TY, \
ARG4NM, \
ARG4OPT, \
ARG5TY, \
ARG5NM, \
ARG5OPT, \
ARG6TY, \
ARG6NM, \
ARG6OPT, \
ARG7TY, \
ARG7NM, \
ARG7OPT) \
extern "C" ReturnType<ARG0TY>::Type hermes_get_##NAME##_##ARG0NM( \
const NAME##Node *node) { \
return ReturnType<ARG0TY>::get(node->_##ARG0NM); \
} \
extern "C" ReturnType<ARG1TY>::Type hermes_get_##NAME##_##ARG1NM( \
const NAME##Node *node) { \
return ReturnType<ARG1TY>::get(node->_##ARG1NM); \
} \
extern "C" ReturnType<ARG2TY>::Type hermes_get_##NAME##_##ARG2NM( \
const NAME##Node *node) { \
return ReturnType<ARG2TY>::get(node->_##ARG2NM); \
} \
extern "C" ReturnType<ARG3TY>::Type hermes_get_##NAME##_##ARG3NM( \
const NAME##Node *node) { \
return ReturnType<ARG3TY>::get(node->_##ARG3NM); \
} \
extern "C" ReturnType<ARG4TY>::Type hermes_get_##NAME##_##ARG4NM( \
const NAME##Node *node) { \
return ReturnType<ARG4TY>::get(node->_##ARG4NM); \
} \
extern "C" ReturnType<ARG5TY>::Type hermes_get_##NAME##_##ARG5NM( \
const NAME##Node *node) { \
return ReturnType<ARG5TY>::get(node->_##ARG5NM); \
} \
extern "C" ReturnType<ARG6TY>::Type hermes_get_##NAME##_##ARG6NM( \
const NAME##Node *node) { \
return ReturnType<ARG6TY>::get(node->_##ARG6NM); \
} \
extern "C" ReturnType<ARG7TY>::Type hermes_get_##NAME##_##ARG7NM( \
const NAME##Node *node) { \
return ReturnType<ARG7TY>::get(node->_##ARG7NM); \
}
#include "hermes/AST/ESTree.def"
namespace {
enum class ParserDialect : uint8_t {
/// Good old JS.
JavaScript,
/// Parse all Flow type syntax.
Flow,
/// Parse all unambiguous Flow type syntax. Syntax that can be intepreted as
/// either Flow types or standard JavaScript is parsed as if it were standard
/// JavaScript.
///
/// For example, `foo<T>(x)` is parsed as if it were standard JavaScript
/// containing two comparisons, even though it could otherwise be interpreted
/// as a call expression with Flow type arguments.
FlowUnambiguous,
/// Parse TypeScript.
TypeScript,
};
/// Flags controlling the behavior of the parser.
struct ParserFlags {
/// Start parsing in strict mode.
bool strictMode = false;
/// Enable JSX parsing.
bool enableJSX = false;
/// Dialect control.
ParserDialect dialect = ParserDialect::JavaScript;
};
enum class DiagKind : uint32_t {
Error,
Warning,
Remark,
Note,
};
DiagKind toDiagKind(llvh::SourceMgr::DiagKind k) {
switch (k) {
default:
assert(false);
case llvh::SourceMgr::DK_Error:
return DiagKind::Error;
case llvh::SourceMgr::DK_Warning:
return DiagKind::Warning;
case llvh::SourceMgr::DK_Remark:
return DiagKind::Remark;
case llvh::SourceMgr::DK_Note:
return DiagKind::Note;
}
}
struct Coord {
/// 1-based.
int line = -1;
/// 1-based.
int column = -1;
Coord() = default;
Coord(int lineNo, int columnNo) : line(lineNo), column(columnNo) {}
};
/// A temporary struct describing an error message, returned to Rust.
struct DiagMessage {
/// Location.
SMLoc loc{};
/// Source coordinate.
Coord coord{};
/// What kind of message.
DiagKind diagKind = DiagKind::Error;
/// Error message.
llvh::StringRef message{};
/// Contents of the error line.
llvh::StringRef lineContents{};
DiagMessage() = default;
DiagMessage(const llvh::SMDiagnostic &diag)
: loc(diag.getLoc()),
coord(diag.getLineNo(), diag.getColumnNo()),
diagKind(toDiagKind(diag.getKind())),
message(diag.getMessage()),
lineContents(diag.getLineContents()) {}
};
enum class MagicCommentKind : uint32_t {
SourceUrl = 0,
SourceMappingUrl = 1,
};
struct DataRef {
const void *data;
size_t length;
};
template <typename T>
inline DataRef toDataRef(const T &ref) {
return {ref.data(), ref.size()};
}
/// This object contains the entire parser state.
struct ParserContext {
/// Parser context with allocators, string table, etc.
Context context_{};
/// Source buffer id, generated by SourceErrorManager.
unsigned bufId_ = ~0u;
/// Original error messages. We need them because they provide storage for
/// the strings.
std::deque<llvh::SMDiagnostic> ourMessages_{};
/// Messages converted to the external layout.
std::vector<DiagMessage> convertedMessages_{};
/// Index of the first error.
llvh::Optional<size_t> firstError_;
/// AST.
ESTree::ProgramNode *ast_ = nullptr;
explicit ParserContext() {
context_.getSourceErrorManager().setDiagHandler(
[](const llvh::SMDiagnostic &diag, void *ctx) {
static_cast<ParserContext *>(ctx)->addMessage(diag);
},
this);
}
void setInputBuffer(llvh::StringRef str) {
assert(!haveBufferId() && "input buffer has already been set");
assert(str.back() == 0 && "input source must be 0-terminated");
bufId_ = context_.getSourceErrorManager().addNewSourceBuffer(
llvh::MemoryBuffer::getMemBuffer(str.drop_back(), "JavaScript", true));
}
bool haveBufferId() const {
return bufId_ != ~0u;
}
unsigned getBufferId() const {
assert(haveBufferId() && "input buffer has not been set");
return bufId_;
}
void addMessage(const llvh::SMDiagnostic &diag) {
if (diag.getKind() <= llvh::SourceMgr::DK_Error && !firstError_)
firstError_ = ourMessages_.size();
ourMessages_.push_back(diag);
convertedMessages_.push_back(ourMessages_.back());
}
void addError(const char *msg) {
context_.getSourceErrorManager().error(
SMLoc{}, "Input is not zero terminated");
}
};
} // namespace
/// source is the zero terminated input. source[len-1] must be \0.
extern "C" ParserContext *
hermes_parser_parse(ParserFlags flags, const char *source, size_t len) {
std::unique_ptr<ParserContext> parserCtx(new ParserContext());
parserCtx->context_.setStrictMode(flags.strictMode);
parserCtx->context_.setParseJSX(flags.enableJSX);
parserCtx->context_.setParseTS(false);
parserCtx->context_.setParseFlow(hermes::ParseFlowSetting::NONE);
switch (flags.dialect) {
case ParserDialect::JavaScript:
break;
case ParserDialect::Flow:
parserCtx->context_.setParseFlow(hermes::ParseFlowSetting::ALL);
break;
case ParserDialect::FlowUnambiguous:
parserCtx->context_.setParseFlow(hermes::ParseFlowSetting::UNAMBIGUOUS);
break;
case ParserDialect::TypeScript:
parserCtx->context_.setParseTS(true);
break;
}
if (len == 0 || source[len - 1] != 0) {
parserCtx->addError("Input is not zero terminated");
return parserCtx.release();
}
parserCtx->setInputBuffer(StringRef(source, len));
parser::JSParser parser(
parserCtx->context_, parserCtx->bufId_, hermes::parser::FullParse);
auto ast = parser.parse();
if (!parserCtx->firstError_) {
if (!ast) {
// Just in case.
parserCtx->addError("Internal error");
} else {
parserCtx->ast_ = *ast;
}
}
return parserCtx.release();
}
extern "C" void hermes_parser_free(ParserContext *parserCtx) {
delete parserCtx;
}
/// \return the index of the first error or -1 if no errors.
extern "C" ssize_t hermes_parser_get_first_error(
const ParserContext *parserCtx) {
return parserCtx->firstError_ ? (int)*parserCtx->firstError_ : -1;
}
extern "C" DataRef hermes_parser_get_messages(const ParserContext *parserCtx) {
return toDataRef(parserCtx->convertedMessages_);
}
extern "C" ESTree::ProgramNode *hermes_parser_get_ast(
const ParserContext *parserCtx) {
return parserCtx->ast_;
}
extern "C" bool
hermes_parser_find_location(ParserContext *parserCtx, SMLoc loc, Coord *res) {
SourceErrorManager::SourceCoords coords;
if (!parserCtx->context_.getSourceErrorManager().findBufferLineAndLoc(
loc, coords)) {
res->line = res->column = -1;
return false;
}
res->line = coords.line;
res->column = coords.col;
return true;
}
/// Note that we guarantee that the result is valid UTF-8 because we only
/// return it if there were no parse errors.
extern "C" DataRef hermes_parser_get_magic_comment(
ParserContext *parserCtx,
MagicCommentKind kind) {
// Make sure that we have successfully parsed the input. (The magic comments
// could be set even if we didn't, but in that case are not guaranteed to be
// value utf-8).
if (!parserCtx->haveBufferId() || !parserCtx->ast_)
return {nullptr, 0};
StringRef res{};
switch (kind) {
case MagicCommentKind::SourceUrl:
res = parserCtx->context_.getSourceErrorManager().getSourceUrl(
parserCtx->getBufferId());
break;
case MagicCommentKind::SourceMappingUrl:
res = parserCtx->context_.getSourceErrorManager().getSourceMappingUrl(
parserCtx->getBufferId());
break;
}
return toDataRef(res);
}
extern "C" DataRef hermes_get_node_name(ESTree::Node *n) {
return toDataRef(n->getNodeName());
}
| 45.41806 | 79 | 0.405339 | [
"object",
"vector"
] |
0fd13b9f745d8974c5f0fcff5a67e61224f568f0 | 5,786 | cc | C++ | tensorflow/compiler/xrt/client/xrt_client_test.cc | slavslav/tensorflow | e29e704c9c8d68113fc407243b75a09325c86d08 | [
"Apache-2.0"
] | null | null | null | tensorflow/compiler/xrt/client/xrt_client_test.cc | slavslav/tensorflow | e29e704c9c8d68113fc407243b75a09325c86d08 | [
"Apache-2.0"
] | null | null | null | tensorflow/compiler/xrt/client/xrt_client_test.cc | slavslav/tensorflow | e29e704c9c8d68113fc407243b75a09325c86d08 | [
"Apache-2.0"
] | null | null | null | /* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <memory>
#include "tensorflow/compiler/xla/status_macros.h"
#include "tensorflow/compiler/xla/tests/literal_test_util.h"
#include "tensorflow/compiler/xrt/client/xrt_grpc_eager_client.h"
#include "tensorflow/compiler/xrt/client/xrt_tf_client.h"
#include "tensorflow/core/distributed_runtime/rpc/grpc_channel.h"
#include "tensorflow/core/distributed_runtime/rpc/grpc_session.h"
#include "tensorflow/core/distributed_runtime/rpc/grpc_testlib.h"
#include "tensorflow/core/framework/tensor.pb.h"
#include "tensorflow/core/framework/tensor_shape.pb.h"
#include "tensorflow/core/framework/types.pb.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/lib/random/random.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/protobuf/cluster.pb.h"
#include "tensorflow/core/protobuf/eager_service.pb.h"
#include "tensorflow/core/protobuf/tensorflow_server.pb.h"
#include "tensorflow/core/util/device_name_utils.h"
namespace tensorflow {
class XrtClientTest : public ::testing::Test {
protected:
XrtClientTest() {
string binary_path =
absl::StrCat(testing::TensorFlowSrcRoot(),
"/compiler/xrt/client/xrt_testlib_server");
TF_CHECK_OK(test::TestCluster::MakeTestCluster(
binary_path, SessionOptions(), /*n=*/1, &cluster_));
CHECK_EQ(cluster_->targets().size(), 1);
JobDef* job = cluster_def_.add_job();
job->set_name("localhost");
(*job->mutable_tasks())[0] = cluster_->targets()[0];
}
std::unique_ptr<test::TestCluster> cluster_;
ClusterDef cluster_def_;
};
// Test some connection basics using XrtGrpcEagerClient directly.
TEST_F(XrtClientTest, XrtGrpcEagerClientWorks) {
ChannelCreationFunction channel_func =
ConvertToChannelCreationFunction(NewHostPortGrpcChannel);
TF_ASSERT_OK_AND_ASSIGN(std::shared_ptr<GrpcChannelCache> channel_cache,
GetGrpcChannelCache(cluster_def_, channel_func));
XrtGrpcEagerClientCache client_cache(channel_cache);
TF_ASSERT_OK_AND_ASSIGN(
XrtGrpcEagerClient * client,
client_cache.GetClient("/job:localhost/task:0/replica:0"));
// Create and destroy a context to verify we can make RPCs.
eager::CreateContextRequest request;
ServerDef* server_def = request.mutable_server_def();
*server_def->mutable_cluster() = cluster_def_;
server_def->set_job_name("localhost");
server_def->set_protocol("grpc");
request.set_keep_alive_secs(60);
request.set_rendezvous_id(random::New64());
eager::CreateContextResponse create_response;
TF_ASSERT_OK(client->SyncCall(&XrtGrpcEagerClient::CreateContextAsync,
&request, &create_response));
eager::CloseContextRequest close_request;
close_request.set_context_id(create_response.context_id());
eager::CloseContextResponse close_response;
TF_ASSERT_OK(client->SyncCall(&XrtGrpcEagerClient::CloseContextAsync,
&close_request, &close_response));
}
// Tests that we can connect to a server using the higher-level XrtTfClient API,
// transfer tensors to the device, run an Add operator, and retrieve the result.
TEST_F(XrtClientTest, XrtTfClientWorks) {
ChannelCreationFunction channel_func =
ConvertToChannelCreationFunction(NewHostPortGrpcChannel);
TF_ASSERT_OK_AND_ASSIGN(std::shared_ptr<GrpcChannelCache> channel_cache,
GetGrpcChannelCache(cluster_def_, channel_func));
auto client = std::make_shared<XrtTfClient>(cluster_def_, channel_cache);
TF_ASSERT_OK_AND_ASSIGN(
std::shared_ptr<XrtTfContext> context,
XrtTfContext::Create(XrtTfContext::Options(), client, /*job=*/"localhost",
/*task=*/0));
auto a_proto = absl::make_unique<TensorProto>();
a_proto->set_dtype(DT_INT32);
a_proto->add_int_val(47);
XrtTensorHandle a =
context->SendTensor(std::move(a_proto), context->cpu_device_id());
auto b_proto = absl::make_unique<TensorProto>();
b_proto->set_dtype(DT_INT32);
b_proto->mutable_tensor_shape()->add_dim()->set_size(2);
b_proto->add_int_val(-101);
b_proto->add_int_val(3);
XrtTensorHandle b =
context->SendTensor(std::move(b_proto), context->cpu_device_id());
protobuf::Map<string, AttrValue> attrs;
attrs["T"] = MakeAttrValue(DT_INT32);
std::vector<XrtTensorHandle> add_outputs = context->EnqueueOp(
"Add", {&a, &b}, /*output_arity=*/1, attrs, context->cpu_device_id());
ASSERT_EQ(add_outputs.size(), 1);
std::shared_ptr<XrtRecvTensorFuture> future =
context->RecvTensor(add_outputs[0], DT_INT32, /*host_memory=*/false);
TF_ASSERT_OK_AND_ASSIGN(RecvTensorResponse * response, future->Get());
const TensorProto& out_proto = response->tensor();
EXPECT_EQ(out_proto.dtype(), DT_INT32);
ASSERT_EQ(out_proto.tensor_content().size(), sizeof(int32) * 2);
std::vector<int32> out(2);
out_proto.tensor_content().CopyToArray(reinterpret_cast<char*>(out.data()));
// TODO(phawkins): handle endian conversion.
EXPECT_EQ(out[0], -54);
EXPECT_EQ(out[1], 50);
}
} // namespace tensorflow
| 41.328571 | 80 | 0.734013 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.