text string | size int64 | token_count int64 |
|---|---|---|
/*
* Copyright 2019 Google
*
* 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 "Firestore/core/src/firebase/firestore/remote/grpc_nanopb.h"
#include <vector>
#include "Firestore/core/include/firebase/firestore/firestore_errors.h"
#include "Firestore/core/src/firebase/firestore/nanopb/writer.h"
#include "Firestore/core/src/firebase/firestore/remote/grpc_util.h"
#include "Firestore/core/src/firebase/firestore/util/status.h"
#include "grpcpp/support/status.h"
namespace firebase {
namespace firestore {
namespace remote {
using nanopb::ByteString;
using nanopb::ByteStringWriter;
using util::Status;
ByteBufferReader::ByteBufferReader(const grpc::ByteBuffer& buffer) {
std::vector<grpc::Slice> slices;
grpc::Status status = buffer.Dump(&slices);
// Conversion may fail if compression is used and gRPC tries to decompress an
// ill-formed buffer.
if (!status.ok()) {
Status error{Error::kInternal,
"Trying to convert an invalid grpc::ByteBuffer"};
error.CausedBy(ConvertStatus(status));
set_status(error);
return;
}
ByteStringWriter writer;
writer.Reserve(buffer.Length());
for (const auto& slice : slices) {
writer.Append(slice.begin(), slice.size());
}
bytes_ = writer.Release();
stream_ = pb_istream_from_buffer(bytes_.data(), bytes_.size());
}
void ByteBufferReader::Read(const pb_field_t* fields, void* dest_struct) {
if (!ok()) return;
if (!pb_decode(&stream_, fields, dest_struct)) {
Fail(PB_GET_ERROR(&stream_));
}
}
namespace {
bool AppendToGrpcBuffer(pb_ostream_t* stream,
const pb_byte_t* buf,
size_t count) {
auto buffer = static_cast<std::vector<grpc::Slice>*>(stream->state);
buffer->emplace_back(buf, count);
return true;
}
} // namespace
ByteBufferWriter::ByteBufferWriter() {
stream_.callback = AppendToGrpcBuffer;
stream_.state = &buffer_;
stream_.max_size = SIZE_MAX;
}
grpc::ByteBuffer ByteBufferWriter::Release() {
grpc::ByteBuffer result{buffer_.data(), buffer_.size()};
buffer_.clear();
return result;
}
} // namespace remote
} // namespace firestore
} // namespace firebase
| 2,676 | 862 |
/*
* BSD License
*
* Copyright (c) Lydia Zoghbi 2019
*
* Permission is hereby granted, free of charge, to any person or organization
* obtaining a copy of the software and accompanying documentation covered by
* this license (the "Software") to use, reproduce, display, distribute,
* execute, and transmit the Software, and to prepare derivative works of the
* Software, and to permit third-parties to whom the Software is furnished to
* do so, all subject to the following:
*
* The copyright notices in the Software and this entire statement
* must be included in all copies of the Software, in whole or in part, and
* all derivative works of the Software, unless such copies or derivative
* works are solely in the form of machine-executable object code generated by
* a source language processor.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file listener.cpp
* @author Lydia Zoghbi
* @copyright Copyright BSD License
* @date 11/02/2019
* @version 1.0
*
* @brief Listener file for the ENPM808X ROS Assignment
*
*/
#include "ros/ros.h"
#include "std_msgs/String.h"
#include "beginner_tutorials/string_modifier.h"
/**
* @brief Callback function for the function outputting the string
*
* @param A constant string
*
* @return Nothing
*/
void chatterCallback(const std_msgs::String::ConstPtr& msg) {
ROS_INFO("I am receiving: [%s]", msg->data.c_str());
}
/**
* @brief Main loop for the listener
*
* @param ROS argument count
* @param ROS argument vector
*
* @return 0 exit status
*/
int main(int argc, char **argv) {
// Initiates the listener node
ros::init(argc, argv, "listener");
// Creates the nodehandle object, initiates the node, and closes it off at the end
ros::NodeHandle n;
// Creates the subscriber object
auto sub = n.subscribe("chatter", 1000, chatterCallback);
// Will enter a loop, exits only when Ctrl-C is pressed or node shutdown by Master
ros::spin();
return 0;
}
| 2,771 | 965 |
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
// Description : Dynamic node for Track Event logic
#include "StdAfx.h"
#include "FlowTrackEventNode.h"
CFlowTrackEventNode::CFlowTrackEventNode(SActivationInfo* pActInfo)
: m_refs(0)
, m_pSequence(NULL)
, m_nOutputs(1)
{
m_outputs = new SOutputPortConfig[1];
m_outputs[0] = SOutputPortConfig();
}
CFlowTrackEventNode::~CFlowTrackEventNode()
{
SAFE_DELETE_ARRAY(m_outputs);
if (NULL != m_pSequence && false == gEnv->IsEditor())
{
m_pSequence->RemoveTrackEventListener(this);
m_pSequence = NULL;
}
}
CFlowTrackEventNode::CFlowTrackEventNode(CFlowTrackEventNode const& obj)
: m_refs(0)
, m_pSequence(NULL)
, m_outputs(NULL)
{
*this = obj;
}
CFlowTrackEventNode& CFlowTrackEventNode::operator =(CFlowTrackEventNode const& obj)
{
if (this != &obj)
{
m_refs = 0; // New reference count
m_pSequence = obj.m_pSequence;
// Copy outputs
m_nOutputs = obj.m_nOutputs;
SAFE_DELETE_ARRAY(m_outputs);
m_outputs = new SOutputPortConfig[m_nOutputs];
for (int i = 0; i < m_nOutputs; ++i)
{
m_outputs[i] = obj.m_outputs[i];
}
m_outputStrings = obj.m_outputStrings;
}
return *this;
}
void CFlowTrackEventNode::AddRef()
{
++m_refs;
}
void CFlowTrackEventNode::Release()
{
if (0 == --m_refs)
{
delete this;
}
}
IFlowNodePtr CFlowTrackEventNode::Clone(SActivationInfo* pActInfo)
{
CFlowTrackEventNode* pClone = new CFlowTrackEventNode(*this);
return pClone;
}
void CFlowTrackEventNode::GetConfiguration(SFlowNodeConfig& config)
{
static const SInputPortConfig inputs[] = {
// Note: Must be first!
InputPortConfig<string>("seq_Sequence", "", _HELP("Working animation sequence"), _HELP("Sequence"), 0),
InputPortConfig<int>("seqid_SequenceId", 0, _HELP("Working animation sequence"), _HELP("SequenceId"), 0),
{0}
};
config.pInputPorts = inputs;
config.pOutputPorts = m_outputs;
config.SetCategory(EFLN_APPROVED);
config.nFlags |= EFLN_DYNAMIC_OUTPUT;
config.nFlags |= EFLN_HIDE_UI;
}
void CFlowTrackEventNode::ProcessEvent(EFlowEvent event, SActivationInfo* pActInfo)
{
if (event == eFE_Initialize && false == gEnv->IsEditor())
{
AddListener(pActInfo);
}
}
bool CFlowTrackEventNode::SerializeXML(SActivationInfo* pActInfo, const XmlNodeRef& root, bool reading)
{
if (true == reading)
{
int count = root->getChildCount();
// Resize
if (m_outputs)
{
SAFE_DELETE_ARRAY(m_outputs);
}
m_outputs = new SOutputPortConfig[count + 1];
m_nOutputs = count + 1;
for (int i = 0; i < count; ++i)
{
XmlNodeRef child = root->getChild(i);
m_outputStrings.push_back(child->getAttr("Name"));
m_outputs[i] = OutputPortConfig<string>(m_outputStrings[i]);
}
m_outputs[count] = SOutputPortConfig();
}
return true;
}
void CFlowTrackEventNode::Serialize(SActivationInfo* pActInfo, TSerialize ser)
{
if (ser.IsReading() && false == gEnv->IsEditor())
{
AddListener(pActInfo);
}
}
void CFlowTrackEventNode::AddListener(SActivationInfo* pActInfo)
{
CRY_ASSERT(pActInfo);
m_actInfo = *pActInfo;
// Remove from old
if (NULL != m_pSequence)
{
m_pSequence->RemoveTrackEventListener(this);
m_pSequence = NULL;
}
// Look up sequence
const int kSequenceName = 0;
const int kSequenceId = 1;
m_pSequence = gEnv->pMovieSystem->FindSequenceById((uint32)GetPortInt(pActInfo, kSequenceId));
if (NULL == m_pSequence)
{
string name = GetPortString(pActInfo, kSequenceName);
m_pSequence = gEnv->pMovieSystem->FindLegacySequenceByName(name.c_str());
}
if (NULL != m_pSequence)
{
m_pSequence->AddTrackEventListener(this);
}
}
void CFlowTrackEventNode::OnTrackEvent(IAnimSequence* pSequence, int reason, const char* event, void* pUserData)
{
if (reason != ITrackEventListener::eTrackEventReason_Triggered)
{
return;
}
// Find output port and call it
for (int i = 0; i < m_nOutputs; ++i)
{
if (m_outputs[i].name && strcmp(m_outputs[i].name, event) == 0)
{
// Call it
TFlowInputData value;
const char* param = (const char*)pUserData;
value.Set(string(param));
ActivateOutput(&m_actInfo, i, value);
return;
}
}
}
| 5,163 | 1,768 |
#include "plane.hh"
namespace geometry {
bool Plane::intersect(const Line& line, Out<Vec3> point) const {
constexpr double EPS = 1e-7;
if (line.direction.cross(normal).norm() < EPS) {
// Parallel
return false;
}
const double d = (origin - line.point).dot(normal) / (line.direction.dot(normal));
*point = line.point + (d * line.direction);
return true;
}
bool Plane::intersect(const Ray& ray, Out<Vec3> point) const {
constexpr double EPS = 1e-7;
if (ray.direction.cross(normal).norm() < EPS) {
// Parallel
return false;
}
const double d = (origin - ray.origin).dot(normal) / (ray.direction.dot(normal));
*point = ray.origin + (d * ray.direction);
if (d < 0.0) {
// Pointing in the wrong direction
return false;
} else {
return true;
}
}
} // namespace geometry | 826 | 297 |
// This file has been generated by Py++.
#ifndef RecordCameraPathHandler_hpp__pyplusplus_wrapper
#define RecordCameraPathHandler_hpp__pyplusplus_wrapper
void register_RecordCameraPathHandler_class();
#endif//RecordCameraPathHandler_hpp__pyplusplus_wrapper
| 259 | 74 |
#include "radio.hpp"
namespace radio {
DEFINE_FLOAT64(kRadioParamModule, timeout, 0.25,
"Timeout after which radio will assume a robot is disconnected. Seconds.");
Radio::Radio()
: Node{"radio", rclcpp::NodeOptions{}
.automatically_declare_parameters_from_overrides(true)
.allow_undeclared_parameters(true)},
param_provider_(this, kRadioParamModule) {
team_color_sub_ = create_subscription<rj_msgs::msg::TeamColor>(
referee::topics::kTeamColorPub, rclcpp::QoS(1).transient_local(),
[this](rj_msgs::msg::TeamColor::SharedPtr color) { // NOLINT
switch_team(color->is_blue);
});
for (int i = 0; i < kNumShells; i++) {
robot_status_pubs_.at(i) = create_publisher<rj_msgs::msg::RobotStatus>(
topics::robot_status_pub(i), rclcpp::QoS(1));
manipulator_subs_.at(i) = create_subscription<rj_msgs::msg::ManipulatorSetpoint>(
control::topics::manipulator_setpoint_pub(i), rclcpp::QoS(1),
[this, i](rj_msgs::msg::ManipulatorSetpoint::SharedPtr manipulator) { // NOLINT
manipulators_cached_.at(i) = *manipulator;
});
motion_subs_.at(i) = create_subscription<rj_msgs::msg::MotionSetpoint>(
control::topics::motion_setpoint_pub(i), rclcpp::QoS(1),
[this, i](rj_msgs::msg::MotionSetpoint::SharedPtr motion) { // NOLINT
last_updates_.at(i) = RJ::now();
send(i, *motion, manipulators_cached_.at(i));
});
}
tick_timer_ = create_wall_timer(std::chrono::milliseconds(16), [this]() { tick(); });
}
void Radio::publish(int robot_id, const rj_msgs::msg::RobotStatus& robot_status) {
robot_status_pubs_.at(robot_id)->publish(robot_status);
}
void Radio::tick() {
receive();
RJ::Time update_time = RJ::now();
for (int i = 0; i < kNumShells; i++) {
if (last_updates_.at(i) + RJ::Seconds(PARAM_timeout) < update_time) {
using rj_msgs::msg::ManipulatorSetpoint;
using rj_msgs::msg::MotionSetpoint;
// Send a NOP packet if we haven't got any updates.
const auto motion = rj_msgs::build<MotionSetpoint>()
.velocity_x_mps(0)
.velocity_y_mps(0)
.velocity_z_radps(0);
const auto manipulator = rj_msgs::build<ManipulatorSetpoint>()
.shoot_mode(ManipulatorSetpoint::SHOOT_MODE_KICK)
.trigger_mode(ManipulatorSetpoint::TRIGGER_MODE_STAND_DOWN)
.kick_speed(0)
.dribbler_speed(0);
last_updates_.at(i) = RJ::now();
send(i, motion, manipulator);
}
}
}
} // namespace radio
| 2,918 | 963 |
/**********************************************************************
* 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
**********************************************************************/
#include <model/YearDescription.hpp>
#include <model/YearDescription_Impl.hpp>
#include <model/RunPeriod.hpp>
#include <model/RunPeriod_Impl.hpp>
#include <model/RunPeriodControlDaylightSavingTime.hpp>
#include <model/RunPeriodControlDaylightSavingTime_Impl.hpp>
#include <model/RunPeriodControlSpecialDays.hpp>
#include <model/RunPeriodControlSpecialDays_Impl.hpp>
#include <model/SizingPeriod.hpp>
#include <model/SizingPeriod_Impl.hpp>
#include <model/ScheduleBase.hpp>
#include <model/ScheduleBase_Impl.hpp>
#include <model/ScheduleRule.hpp>
#include <model/ScheduleRule_Impl.hpp>
#include <model/LightingDesignDay.hpp>
#include <model/LightingDesignDay_Impl.hpp>
#include <model/Model.hpp>
#include <model/Model_Impl.hpp>
#include <utilities/idd/IddFactory.hxx>
#include <utilities/idd/OS_YearDescription_FieldEnums.hxx>
#include <utilities/time/Date.hpp>
#include <utilities/core/Assert.hpp>
namespace openstudio {
namespace model {
namespace detail {
YearDescription_Impl::YearDescription_Impl(const IdfObject& idfObject, Model_Impl* model, bool keepHandle)
: ParentObject_Impl(idfObject,model,keepHandle)
{
OS_ASSERT(idfObject.iddObject().type() == YearDescription::iddObjectType());
}
YearDescription_Impl::YearDescription_Impl(const openstudio::detail::WorkspaceObject_Impl& other,
Model_Impl* model,
bool keepHandle)
: ParentObject_Impl(other,model,keepHandle)
{
OS_ASSERT(other.iddObject().type() == YearDescription::iddObjectType());
}
YearDescription_Impl::YearDescription_Impl(const YearDescription_Impl& other,
Model_Impl* model,
bool keepHandle)
: ParentObject_Impl(other,model,keepHandle)
{}
const std::vector<std::string>& YearDescription_Impl::outputVariableNames() const
{
static std::vector<std::string> result;
if (result.empty()){
}
return result;
}
IddObjectType YearDescription_Impl::iddObjectType() const {
return YearDescription::iddObjectType();
}
std::vector<ModelObject> YearDescription_Impl::children() const
{
std::vector<ModelObject> result;
Model model = this->model();
boost::optional<RunPeriodControlDaylightSavingTime> dst = model.getOptionalUniqueModelObject<RunPeriodControlDaylightSavingTime>();
if (dst){
result.push_back(*dst);
}
BOOST_FOREACH(RunPeriodControlSpecialDays day, model.getConcreteModelObjects<RunPeriodControlSpecialDays>()){
result.push_back(day);
}
return result;
}
std::vector<IddObjectType> YearDescription_Impl::allowableChildTypes() const
{
IddObjectTypeVector result;
result.push_back(RunPeriodControlDaylightSavingTime::iddObjectType());
result.push_back(RunPeriodControlSpecialDays::iddObjectType());
return result;
}
boost::optional<int> YearDescription_Impl::calendarYear() const {
return getInt(OS_YearDescriptionFields::CalendarYear,true);
}
std::string YearDescription_Impl::dayofWeekforStartDay() const {
boost::optional<int> calendarYear = this->calendarYear();
if (calendarYear){
openstudio::Date jan1(MonthOfYear::Jan, 1, *calendarYear);
std::string result = jan1.dayOfWeek().valueName();
return result;
}
boost::optional<std::string> value = getString(OS_YearDescriptionFields::DayofWeekforStartDay,true);
OS_ASSERT(value);
return value.get();
}
bool YearDescription_Impl::isDayofWeekforStartDayDefaulted() const {
return isEmpty(OS_YearDescriptionFields::DayofWeekforStartDay);
}
bool YearDescription_Impl::isLeapYear() const {
boost::optional<int> calendarYear = this->calendarYear();
if (calendarYear){
openstudio::Date jan1(MonthOfYear::Jan, 1, *calendarYear);
bool result = jan1.isLeapYear();
return result;
}
boost::optional<std::string> value = getString(OS_YearDescriptionFields::IsLeapYear,true);
OS_ASSERT(value);
return openstudio::istringEqual(value.get(), "Yes");
}
bool YearDescription_Impl::isIsLeapYearDefaulted() const {
return isEmpty(OS_YearDescriptionFields::IsLeapYear);
}
void YearDescription_Impl::setCalendarYear(boost::optional<int> calendarYear) {
bool wasLeapYear = this->isLeapYear();
bool result = false;
if (calendarYear) {
result = setInt(OS_YearDescriptionFields::CalendarYear, calendarYear.get());
this->resetDayofWeekforStartDay();
this->resetIsLeapYear();
} else {
result = setString(OS_YearDescriptionFields::CalendarYear, "");
}
OS_ASSERT(result);
bool isLeapYear = this->isLeapYear();
updateModelLeapYear(wasLeapYear, isLeapYear);
}
void YearDescription_Impl::resetCalendarYear() {
bool wasLeapYear = this->isLeapYear();
bool result = setString(OS_YearDescriptionFields::CalendarYear, "");
OS_ASSERT(result);
bool isLeapYear = this->isLeapYear();
updateModelLeapYear(wasLeapYear, isLeapYear);
}
bool YearDescription_Impl::setDayofWeekforStartDay(std::string dayofWeekforStartDay) {
bool result = false;
if (!this->calendarYear()){
result = setString(OS_YearDescriptionFields::DayofWeekforStartDay, dayofWeekforStartDay);
}
return result;
}
void YearDescription_Impl::resetDayofWeekforStartDay() {
bool result = setString(OS_YearDescriptionFields::DayofWeekforStartDay, "");
OS_ASSERT(result);
}
bool YearDescription_Impl::setIsLeapYear(bool isLeapYear) {
bool result = false;
bool wasLeapYear = this->isLeapYear();
if (!this->calendarYear()){
if (isLeapYear) {
result = setString(OS_YearDescriptionFields::IsLeapYear, "Yes");
} else {
result = setString(OS_YearDescriptionFields::IsLeapYear, "No");
}
}
if (result){
updateModelLeapYear(wasLeapYear, isLeapYear);
}
return result;
}
void YearDescription_Impl::resetIsLeapYear() {
bool wasLeapYear = this->isLeapYear();
bool result = setString(OS_YearDescriptionFields::IsLeapYear, "");
OS_ASSERT(result);
bool isLeapYear = this->isLeapYear();
updateModelLeapYear(wasLeapYear, isLeapYear);
}
int YearDescription_Impl::assumedYear() const
{
boost::optional<int> calendarYear = this->calendarYear();
if (calendarYear){
return *calendarYear;
}
openstudio::YearDescription yd;
yd.isLeapYear = this->isLeapYear();
std::string dayofWeekforStartDay = this->dayofWeekforStartDay();
if (!dayofWeekforStartDay.empty()){
try{
openstudio::DayOfWeek dow(dayofWeekforStartDay);
yd.yearStartsOnDayOfWeek = dow;
}catch(const std::exception& ){
LOG(Error, "'" << dayofWeekforStartDay << "' is not yet a supported option for YearDescription");
}
}
return yd.assumedYear();
}
openstudio::Date YearDescription_Impl::makeDate(openstudio::MonthOfYear monthOfYear, unsigned dayOfMonth)
{
boost::optional<int> calendarYear = this->calendarYear();
if (calendarYear){
return openstudio::Date(monthOfYear, dayOfMonth, *calendarYear);
}
openstudio::YearDescription yd;
yd.isLeapYear = this->isLeapYear();
std::string dayofWeekforStartDay = this->dayofWeekforStartDay();
if (!dayofWeekforStartDay.empty()){
if (istringEqual(dayofWeekforStartDay, "UseWeatherFile")){
LOG(Info, "'UseWeatherFile' is not yet a supported option for YearDescription");
}else{
openstudio::DayOfWeek dow(dayofWeekforStartDay);
yd.yearStartsOnDayOfWeek = dow;
}
}
return openstudio::Date(monthOfYear, dayOfMonth, yd);
}
openstudio::Date YearDescription_Impl::makeDate(unsigned monthOfYear, unsigned dayOfMonth)
{
return makeDate(openstudio::MonthOfYear(monthOfYear), dayOfMonth);
}
openstudio::Date YearDescription_Impl::makeDate(openstudio::NthDayOfWeekInMonth n, openstudio::DayOfWeek dayOfWeek, openstudio::MonthOfYear monthOfYear)
{
boost::optional<int> year = this->calendarYear();
if (!year){
year = this->assumedYear();
}
return openstudio::Date::fromNthDayOfMonth(n, dayOfWeek, monthOfYear, *year);
}
openstudio::Date YearDescription_Impl::makeDate(unsigned dayOfYear)
{
boost::optional<int> year = this->calendarYear();
if (!year){
year = this->assumedYear();
}
return openstudio::Date::fromDayOfYear(dayOfYear, *year);
}
void YearDescription_Impl::updateModelLeapYear(bool wasLeapYear, bool isLeapYear)
{
if (wasLeapYear == isLeapYear){
return;
}
if (!wasLeapYear && isLeapYear){
return;
}
model::Model model = this->model();
if (wasLeapYear && !isLeapYear){
BOOST_FOREACH(RunPeriod runPeriod, model.getModelObjects<RunPeriod>()){
runPeriod.ensureNoLeapDays();
}
BOOST_FOREACH(RunPeriodControlDaylightSavingTime runPeriodControlDaylightSavingTime, model.getModelObjects<RunPeriodControlDaylightSavingTime>()){
runPeriodControlDaylightSavingTime.ensureNoLeapDays();
}
BOOST_FOREACH(RunPeriodControlSpecialDays runPeriodControlSpecialDays, model.getModelObjects<RunPeriodControlSpecialDays>()){
runPeriodControlSpecialDays.ensureNoLeapDays();
}
BOOST_FOREACH(SizingPeriod sizingPeriod, model.getModelObjects<SizingPeriod>()){
sizingPeriod.ensureNoLeapDays();
}
BOOST_FOREACH(ScheduleBase scheduleBase, model.getModelObjects<ScheduleBase>()){
scheduleBase.ensureNoLeapDays();
}
BOOST_FOREACH(ScheduleRule scheduleRule, model.getModelObjects<ScheduleRule>()){
scheduleRule.ensureNoLeapDays();
}
BOOST_FOREACH(LightingDesignDay lightingDesignDay, model.getModelObjects<LightingDesignDay>()){
lightingDesignDay.ensureNoLeapDays();
}
}
}
} // detail
IddObjectType YearDescription::iddObjectType() {
IddObjectType result(IddObjectType::OS_YearDescription);
return result;
}
std::vector<std::string> YearDescription::validDayofWeekforStartDayValues() {
return getIddKeyNames(IddFactory::instance().getObject(iddObjectType()).get(),
OS_YearDescriptionFields::DayofWeekforStartDay);
}
boost::optional<int> YearDescription::calendarYear() const {
return getImpl<detail::YearDescription_Impl>()->calendarYear();
}
std::string YearDescription::dayofWeekforStartDay() const {
return getImpl<detail::YearDescription_Impl>()->dayofWeekforStartDay();
}
bool YearDescription::isDayofWeekforStartDayDefaulted() const {
return getImpl<detail::YearDescription_Impl>()->isDayofWeekforStartDayDefaulted();
}
bool YearDescription::isLeapYear() const {
return getImpl<detail::YearDescription_Impl>()->isLeapYear();
}
bool YearDescription::isIsLeapYearDefaulted() const {
return getImpl<detail::YearDescription_Impl>()->isIsLeapYearDefaulted();
}
void YearDescription::setCalendarYear(int calendarYear) {
getImpl<detail::YearDescription_Impl>()->setCalendarYear(calendarYear);
}
void YearDescription::resetCalendarYear() {
getImpl<detail::YearDescription_Impl>()->resetCalendarYear();
}
bool YearDescription::setDayofWeekforStartDay(std::string dayofWeekforStartDay) {
return getImpl<detail::YearDescription_Impl>()->setDayofWeekforStartDay(dayofWeekforStartDay);
}
void YearDescription::resetDayofWeekforStartDay() {
getImpl<detail::YearDescription_Impl>()->resetDayofWeekforStartDay();
}
bool YearDescription::setIsLeapYear(bool isLeapYear) {
return getImpl<detail::YearDescription_Impl>()->setIsLeapYear(isLeapYear);
}
void YearDescription::resetIsLeapYear() {
getImpl<detail::YearDescription_Impl>()->resetIsLeapYear();
}
int YearDescription::assumedYear() const {
return getImpl<detail::YearDescription_Impl>()->assumedYear();
}
openstudio::Date YearDescription::makeDate(openstudio::MonthOfYear monthOfYear, unsigned dayOfMonth)
{
return getImpl<detail::YearDescription_Impl>()->makeDate(monthOfYear, dayOfMonth);
}
openstudio::Date YearDescription::makeDate(unsigned monthOfYear, unsigned dayOfMonth)
{
return getImpl<detail::YearDescription_Impl>()->makeDate(monthOfYear, dayOfMonth);
}
openstudio::Date YearDescription::makeDate(openstudio::NthDayOfWeekInMonth n, openstudio::DayOfWeek dayOfWeek, openstudio::MonthOfYear monthOfYear)
{
return getImpl<detail::YearDescription_Impl>()->makeDate(n, dayOfWeek, monthOfYear);
}
openstudio::Date YearDescription::makeDate(unsigned dayOfYear)
{
return getImpl<detail::YearDescription_Impl>()->makeDate(dayOfYear);
}
/// @cond
YearDescription::YearDescription(boost::shared_ptr<detail::YearDescription_Impl> impl)
: ParentObject(impl)
{}
YearDescription::YearDescription(Model& model)
: ParentObject(YearDescription::iddObjectType(),model)
{}
/// @endcond
} // model
} // openstudio
| 14,278 | 4,387 |
// File Automatically generated by eLiSe
#include "StdAfx.h"
#include "cEqAppui_NoDist__PProjInc_M2CFour11x2.h"
cEqAppui_NoDist__PProjInc_M2CFour11x2::cEqAppui_NoDist__PProjInc_M2CFour11x2():
cElCompiledFonc(2)
{
AddIntRef (cIncIntervale("Intr",0,16));
AddIntRef (cIncIntervale("Orient",16,22));
AddIntRef (cIncIntervale("Tmp_PTer",22,25));
Close(false);
}
void cEqAppui_NoDist__PProjInc_M2CFour11x2::ComputeVal()
{
double tmp0_ = mCompCoord[16];
double tmp1_ = mCompCoord[17];
double tmp2_ = cos(tmp1_);
double tmp3_ = mCompCoord[22];
double tmp4_ = mCompCoord[23];
double tmp5_ = mCompCoord[24];
double tmp6_ = sin(tmp0_);
double tmp7_ = cos(tmp0_);
double tmp8_ = sin(tmp1_);
double tmp9_ = mCompCoord[18];
double tmp10_ = mLocProjI_x*tmp3_;
double tmp11_ = mLocProjP0_x+tmp10_;
double tmp12_ = mLocProjJ_x*tmp4_;
double tmp13_ = tmp11_+tmp12_;
double tmp14_ = mLocProjK_x*tmp5_;
double tmp15_ = tmp13_+tmp14_;
double tmp16_ = mCompCoord[19];
double tmp17_ = (tmp15_)-tmp16_;
double tmp18_ = sin(tmp9_);
double tmp19_ = -(tmp18_);
double tmp20_ = -(tmp8_);
double tmp21_ = cos(tmp9_);
double tmp22_ = mLocProjI_y*tmp3_;
double tmp23_ = mLocProjP0_y+tmp22_;
double tmp24_ = mLocProjJ_y*tmp4_;
double tmp25_ = tmp23_+tmp24_;
double tmp26_ = mLocProjK_y*tmp5_;
double tmp27_ = tmp25_+tmp26_;
double tmp28_ = mCompCoord[20];
double tmp29_ = (tmp27_)-tmp28_;
double tmp30_ = mLocProjI_z*tmp3_;
double tmp31_ = mLocProjP0_z+tmp30_;
double tmp32_ = mLocProjJ_z*tmp4_;
double tmp33_ = tmp31_+tmp32_;
double tmp34_ = mLocProjK_z*tmp5_;
double tmp35_ = tmp33_+tmp34_;
double tmp36_ = mCompCoord[21];
double tmp37_ = (tmp35_)-tmp36_;
double tmp38_ = -(tmp6_);
double tmp39_ = tmp7_*tmp20_;
double tmp40_ = tmp6_*tmp20_;
double tmp41_ = tmp38_*tmp19_;
double tmp42_ = tmp39_*tmp21_;
double tmp43_ = tmp41_+tmp42_;
double tmp44_ = (tmp43_)*(tmp17_);
double tmp45_ = tmp7_*tmp19_;
double tmp46_ = tmp40_*tmp21_;
double tmp47_ = tmp45_+tmp46_;
double tmp48_ = (tmp47_)*(tmp29_);
double tmp49_ = tmp44_+tmp48_;
double tmp50_ = tmp2_*tmp21_;
double tmp51_ = tmp50_*(tmp37_);
double tmp52_ = tmp49_+tmp51_;
double tmp53_ = tmp7_*tmp2_;
double tmp54_ = tmp53_*(tmp17_);
double tmp55_ = tmp6_*tmp2_;
double tmp56_ = tmp55_*(tmp29_);
double tmp57_ = tmp54_+tmp56_;
double tmp58_ = tmp8_*(tmp37_);
double tmp59_ = tmp57_+tmp58_;
double tmp60_ = (tmp59_)/(tmp52_);
double tmp61_ = tmp38_*tmp21_;
double tmp62_ = tmp39_*tmp18_;
double tmp63_ = tmp61_+tmp62_;
double tmp64_ = (tmp63_)*(tmp17_);
double tmp65_ = tmp7_*tmp21_;
double tmp66_ = tmp40_*tmp18_;
double tmp67_ = tmp65_+tmp66_;
double tmp68_ = (tmp67_)*(tmp29_);
double tmp69_ = tmp64_+tmp68_;
double tmp70_ = tmp2_*tmp18_;
double tmp71_ = tmp70_*(tmp37_);
double tmp72_ = tmp69_+tmp71_;
double tmp73_ = (tmp72_)/(tmp52_);
mVal[0] = ((mLocNDP0_x+mLocNDdx_x*(tmp60_)+mLocNDdy_x*(tmp73_))-mLocXIm)*mLocScNorm;
mVal[1] = ((mLocNDP0_y+mLocNDdx_y*(tmp60_)+mLocNDdy_y*(tmp73_))-mLocYIm)*mLocScNorm;
}
void cEqAppui_NoDist__PProjInc_M2CFour11x2::ComputeValDeriv()
{
double tmp0_ = mCompCoord[16];
double tmp1_ = mCompCoord[17];
double tmp2_ = cos(tmp1_);
double tmp3_ = mCompCoord[22];
double tmp4_ = mCompCoord[23];
double tmp5_ = mCompCoord[24];
double tmp6_ = sin(tmp0_);
double tmp7_ = cos(tmp0_);
double tmp8_ = sin(tmp1_);
double tmp9_ = mCompCoord[18];
double tmp10_ = mLocProjI_x*tmp3_;
double tmp11_ = mLocProjP0_x+tmp10_;
double tmp12_ = mLocProjJ_x*tmp4_;
double tmp13_ = tmp11_+tmp12_;
double tmp14_ = mLocProjK_x*tmp5_;
double tmp15_ = tmp13_+tmp14_;
double tmp16_ = mCompCoord[19];
double tmp17_ = (tmp15_)-tmp16_;
double tmp18_ = sin(tmp9_);
double tmp19_ = -(tmp18_);
double tmp20_ = -(tmp8_);
double tmp21_ = cos(tmp9_);
double tmp22_ = mLocProjI_y*tmp3_;
double tmp23_ = mLocProjP0_y+tmp22_;
double tmp24_ = mLocProjJ_y*tmp4_;
double tmp25_ = tmp23_+tmp24_;
double tmp26_ = mLocProjK_y*tmp5_;
double tmp27_ = tmp25_+tmp26_;
double tmp28_ = mCompCoord[20];
double tmp29_ = (tmp27_)-tmp28_;
double tmp30_ = mLocProjI_z*tmp3_;
double tmp31_ = mLocProjP0_z+tmp30_;
double tmp32_ = mLocProjJ_z*tmp4_;
double tmp33_ = tmp31_+tmp32_;
double tmp34_ = mLocProjK_z*tmp5_;
double tmp35_ = tmp33_+tmp34_;
double tmp36_ = mCompCoord[21];
double tmp37_ = (tmp35_)-tmp36_;
double tmp38_ = -(tmp6_);
double tmp39_ = tmp7_*tmp20_;
double tmp40_ = tmp6_*tmp20_;
double tmp41_ = tmp38_*tmp19_;
double tmp42_ = tmp39_*tmp21_;
double tmp43_ = tmp41_+tmp42_;
double tmp44_ = (tmp43_)*(tmp17_);
double tmp45_ = tmp7_*tmp19_;
double tmp46_ = tmp40_*tmp21_;
double tmp47_ = tmp45_+tmp46_;
double tmp48_ = (tmp47_)*(tmp29_);
double tmp49_ = tmp44_+tmp48_;
double tmp50_ = tmp2_*tmp21_;
double tmp51_ = tmp50_*(tmp37_);
double tmp52_ = tmp49_+tmp51_;
double tmp53_ = tmp7_*tmp2_;
double tmp54_ = tmp53_*(tmp17_);
double tmp55_ = tmp6_*tmp2_;
double tmp56_ = tmp55_*(tmp29_);
double tmp57_ = tmp54_+tmp56_;
double tmp58_ = tmp8_*(tmp37_);
double tmp59_ = tmp57_+tmp58_;
double tmp60_ = -(1);
double tmp61_ = tmp60_*tmp6_;
double tmp62_ = -(tmp7_);
double tmp63_ = tmp61_*tmp20_;
double tmp64_ = tmp39_*tmp18_;
double tmp65_ = tmp38_*tmp21_;
double tmp66_ = tmp65_+tmp64_;
double tmp67_ = (tmp66_)*(tmp17_);
double tmp68_ = tmp7_*tmp21_;
double tmp69_ = tmp40_*tmp18_;
double tmp70_ = tmp68_+tmp69_;
double tmp71_ = (tmp70_)*(tmp29_);
double tmp72_ = tmp67_+tmp71_;
double tmp73_ = tmp2_*tmp18_;
double tmp74_ = tmp73_*(tmp37_);
double tmp75_ = tmp72_+tmp74_;
double tmp76_ = tmp62_*tmp19_;
double tmp77_ = tmp63_*tmp21_;
double tmp78_ = tmp76_+tmp77_;
double tmp79_ = (tmp78_)*(tmp17_);
double tmp80_ = tmp61_*tmp19_;
double tmp81_ = tmp80_+tmp42_;
double tmp82_ = (tmp81_)*(tmp29_);
double tmp83_ = tmp79_+tmp82_;
double tmp84_ = ElSquare(tmp52_);
double tmp85_ = tmp60_*tmp8_;
double tmp86_ = -(tmp2_);
double tmp87_ = tmp86_*tmp7_;
double tmp88_ = tmp86_*tmp6_;
double tmp89_ = tmp87_*tmp21_;
double tmp90_ = tmp89_*(tmp17_);
double tmp91_ = tmp88_*tmp21_;
double tmp92_ = tmp91_*(tmp29_);
double tmp93_ = tmp90_+tmp92_;
double tmp94_ = tmp85_*tmp21_;
double tmp95_ = tmp94_*(tmp37_);
double tmp96_ = tmp93_+tmp95_;
double tmp97_ = -(tmp21_);
double tmp98_ = tmp60_*tmp18_;
double tmp99_ = tmp97_*tmp38_;
double tmp100_ = tmp98_*tmp39_;
double tmp101_ = tmp99_+tmp100_;
double tmp102_ = (tmp101_)*(tmp17_);
double tmp103_ = tmp97_*tmp7_;
double tmp104_ = tmp98_*tmp40_;
double tmp105_ = tmp103_+tmp104_;
double tmp106_ = (tmp105_)*(tmp29_);
double tmp107_ = tmp102_+tmp106_;
double tmp108_ = tmp98_*tmp2_;
double tmp109_ = tmp108_*(tmp37_);
double tmp110_ = tmp107_+tmp109_;
double tmp111_ = tmp60_*(tmp43_);
double tmp112_ = tmp60_*(tmp47_);
double tmp113_ = tmp60_*tmp50_;
double tmp114_ = mLocProjI_x*(tmp43_);
double tmp115_ = mLocProjI_y*(tmp47_);
double tmp116_ = tmp114_+tmp115_;
double tmp117_ = mLocProjI_z*tmp50_;
double tmp118_ = tmp116_+tmp117_;
double tmp119_ = mLocProjJ_x*(tmp43_);
double tmp120_ = mLocProjJ_y*(tmp47_);
double tmp121_ = tmp119_+tmp120_;
double tmp122_ = mLocProjJ_z*tmp50_;
double tmp123_ = tmp121_+tmp122_;
double tmp124_ = mLocProjK_x*(tmp43_);
double tmp125_ = mLocProjK_y*(tmp47_);
double tmp126_ = tmp124_+tmp125_;
double tmp127_ = mLocProjK_z*tmp50_;
double tmp128_ = tmp126_+tmp127_;
double tmp129_ = (tmp59_)/(tmp52_);
double tmp130_ = (tmp75_)/(tmp52_);
double tmp131_ = tmp61_*tmp2_;
double tmp132_ = tmp131_*(tmp17_);
double tmp133_ = tmp53_*(tmp29_);
double tmp134_ = tmp132_+tmp133_;
double tmp135_ = (tmp134_)*(tmp52_);
double tmp136_ = (tmp59_)*(tmp83_);
double tmp137_ = tmp135_-tmp136_;
double tmp138_ = (tmp137_)/tmp84_;
double tmp139_ = tmp62_*tmp21_;
double tmp140_ = tmp63_*tmp18_;
double tmp141_ = tmp139_+tmp140_;
double tmp142_ = (tmp141_)*(tmp17_);
double tmp143_ = tmp61_*tmp21_;
double tmp144_ = tmp143_+tmp64_;
double tmp145_ = (tmp144_)*(tmp29_);
double tmp146_ = tmp142_+tmp145_;
double tmp147_ = (tmp146_)*(tmp52_);
double tmp148_ = (tmp75_)*(tmp83_);
double tmp149_ = tmp147_-tmp148_;
double tmp150_ = (tmp149_)/tmp84_;
double tmp151_ = tmp85_*tmp7_;
double tmp152_ = tmp151_*(tmp17_);
double tmp153_ = tmp85_*tmp6_;
double tmp154_ = tmp153_*(tmp29_);
double tmp155_ = tmp152_+tmp154_;
double tmp156_ = tmp2_*(tmp37_);
double tmp157_ = tmp155_+tmp156_;
double tmp158_ = (tmp157_)*(tmp52_);
double tmp159_ = (tmp59_)*(tmp96_);
double tmp160_ = tmp158_-tmp159_;
double tmp161_ = (tmp160_)/tmp84_;
double tmp162_ = tmp87_*tmp18_;
double tmp163_ = tmp162_*(tmp17_);
double tmp164_ = tmp88_*tmp18_;
double tmp165_ = tmp164_*(tmp29_);
double tmp166_ = tmp163_+tmp165_;
double tmp167_ = tmp85_*tmp18_;
double tmp168_ = tmp167_*(tmp37_);
double tmp169_ = tmp166_+tmp168_;
double tmp170_ = (tmp169_)*(tmp52_);
double tmp171_ = (tmp75_)*(tmp96_);
double tmp172_ = tmp170_-tmp171_;
double tmp173_ = (tmp172_)/tmp84_;
double tmp174_ = (tmp59_)*(tmp110_);
double tmp175_ = -(tmp174_);
double tmp176_ = tmp175_/tmp84_;
double tmp177_ = tmp98_*tmp38_;
double tmp178_ = tmp21_*tmp39_;
double tmp179_ = tmp177_+tmp178_;
double tmp180_ = (tmp179_)*(tmp17_);
double tmp181_ = tmp98_*tmp7_;
double tmp182_ = tmp21_*tmp40_;
double tmp183_ = tmp181_+tmp182_;
double tmp184_ = (tmp183_)*(tmp29_);
double tmp185_ = tmp180_+tmp184_;
double tmp186_ = tmp21_*tmp2_;
double tmp187_ = tmp186_*(tmp37_);
double tmp188_ = tmp185_+tmp187_;
double tmp189_ = (tmp188_)*(tmp52_);
double tmp190_ = (tmp75_)*(tmp110_);
double tmp191_ = tmp189_-tmp190_;
double tmp192_ = (tmp191_)/tmp84_;
double tmp193_ = tmp60_*tmp53_;
double tmp194_ = tmp193_*(tmp52_);
double tmp195_ = (tmp59_)*tmp111_;
double tmp196_ = tmp194_-tmp195_;
double tmp197_ = (tmp196_)/tmp84_;
double tmp198_ = tmp60_*(tmp66_);
double tmp199_ = tmp198_*(tmp52_);
double tmp200_ = (tmp75_)*tmp111_;
double tmp201_ = tmp199_-tmp200_;
double tmp202_ = (tmp201_)/tmp84_;
double tmp203_ = tmp60_*tmp55_;
double tmp204_ = tmp203_*(tmp52_);
double tmp205_ = (tmp59_)*tmp112_;
double tmp206_ = tmp204_-tmp205_;
double tmp207_ = (tmp206_)/tmp84_;
double tmp208_ = tmp60_*(tmp70_);
double tmp209_ = tmp208_*(tmp52_);
double tmp210_ = (tmp75_)*tmp112_;
double tmp211_ = tmp209_-tmp210_;
double tmp212_ = (tmp211_)/tmp84_;
double tmp213_ = tmp85_*(tmp52_);
double tmp214_ = (tmp59_)*tmp113_;
double tmp215_ = tmp213_-tmp214_;
double tmp216_ = (tmp215_)/tmp84_;
double tmp217_ = tmp60_*tmp73_;
double tmp218_ = tmp217_*(tmp52_);
double tmp219_ = (tmp75_)*tmp113_;
double tmp220_ = tmp218_-tmp219_;
double tmp221_ = (tmp220_)/tmp84_;
double tmp222_ = mLocProjI_x*tmp53_;
double tmp223_ = mLocProjI_y*tmp55_;
double tmp224_ = tmp222_+tmp223_;
double tmp225_ = mLocProjI_z*tmp8_;
double tmp226_ = tmp224_+tmp225_;
double tmp227_ = (tmp226_)*(tmp52_);
double tmp228_ = (tmp59_)*(tmp118_);
double tmp229_ = tmp227_-tmp228_;
double tmp230_ = (tmp229_)/tmp84_;
double tmp231_ = mLocProjI_x*(tmp66_);
double tmp232_ = mLocProjI_y*(tmp70_);
double tmp233_ = tmp231_+tmp232_;
double tmp234_ = mLocProjI_z*tmp73_;
double tmp235_ = tmp233_+tmp234_;
double tmp236_ = (tmp235_)*(tmp52_);
double tmp237_ = (tmp75_)*(tmp118_);
double tmp238_ = tmp236_-tmp237_;
double tmp239_ = (tmp238_)/tmp84_;
double tmp240_ = mLocProjJ_x*tmp53_;
double tmp241_ = mLocProjJ_y*tmp55_;
double tmp242_ = tmp240_+tmp241_;
double tmp243_ = mLocProjJ_z*tmp8_;
double tmp244_ = tmp242_+tmp243_;
double tmp245_ = (tmp244_)*(tmp52_);
double tmp246_ = (tmp59_)*(tmp123_);
double tmp247_ = tmp245_-tmp246_;
double tmp248_ = (tmp247_)/tmp84_;
double tmp249_ = mLocProjJ_x*(tmp66_);
double tmp250_ = mLocProjJ_y*(tmp70_);
double tmp251_ = tmp249_+tmp250_;
double tmp252_ = mLocProjJ_z*tmp73_;
double tmp253_ = tmp251_+tmp252_;
double tmp254_ = (tmp253_)*(tmp52_);
double tmp255_ = (tmp75_)*(tmp123_);
double tmp256_ = tmp254_-tmp255_;
double tmp257_ = (tmp256_)/tmp84_;
double tmp258_ = mLocProjK_x*tmp53_;
double tmp259_ = mLocProjK_y*tmp55_;
double tmp260_ = tmp258_+tmp259_;
double tmp261_ = mLocProjK_z*tmp8_;
double tmp262_ = tmp260_+tmp261_;
double tmp263_ = (tmp262_)*(tmp52_);
double tmp264_ = (tmp59_)*(tmp128_);
double tmp265_ = tmp263_-tmp264_;
double tmp266_ = (tmp265_)/tmp84_;
double tmp267_ = mLocProjK_x*(tmp66_);
double tmp268_ = mLocProjK_y*(tmp70_);
double tmp269_ = tmp267_+tmp268_;
double tmp270_ = mLocProjK_z*tmp73_;
double tmp271_ = tmp269_+tmp270_;
double tmp272_ = (tmp271_)*(tmp52_);
double tmp273_ = (tmp75_)*(tmp128_);
double tmp274_ = tmp272_-tmp273_;
double tmp275_ = (tmp274_)/tmp84_;
mVal[0] = ((mLocNDP0_x+mLocNDdx_x*(tmp129_)+mLocNDdy_x*(tmp130_))-mLocXIm)*mLocScNorm;
mCompDer[0][0] = 0;
mCompDer[0][1] = 0;
mCompDer[0][2] = 0;
mCompDer[0][3] = 0;
mCompDer[0][4] = 0;
mCompDer[0][5] = 0;
mCompDer[0][6] = 0;
mCompDer[0][7] = 0;
mCompDer[0][8] = 0;
mCompDer[0][9] = 0;
mCompDer[0][10] = 0;
mCompDer[0][11] = 0;
mCompDer[0][12] = 0;
mCompDer[0][13] = 0;
mCompDer[0][14] = 0;
mCompDer[0][15] = 0;
mCompDer[0][16] = ((tmp138_)*mLocNDdx_x+(tmp150_)*mLocNDdy_x)*mLocScNorm;
mCompDer[0][17] = ((tmp161_)*mLocNDdx_x+(tmp173_)*mLocNDdy_x)*mLocScNorm;
mCompDer[0][18] = ((tmp176_)*mLocNDdx_x+(tmp192_)*mLocNDdy_x)*mLocScNorm;
mCompDer[0][19] = ((tmp197_)*mLocNDdx_x+(tmp202_)*mLocNDdy_x)*mLocScNorm;
mCompDer[0][20] = ((tmp207_)*mLocNDdx_x+(tmp212_)*mLocNDdy_x)*mLocScNorm;
mCompDer[0][21] = ((tmp216_)*mLocNDdx_x+(tmp221_)*mLocNDdy_x)*mLocScNorm;
mCompDer[0][22] = ((tmp230_)*mLocNDdx_x+(tmp239_)*mLocNDdy_x)*mLocScNorm;
mCompDer[0][23] = ((tmp248_)*mLocNDdx_x+(tmp257_)*mLocNDdy_x)*mLocScNorm;
mCompDer[0][24] = ((tmp266_)*mLocNDdx_x+(tmp275_)*mLocNDdy_x)*mLocScNorm;
mVal[1] = ((mLocNDP0_y+mLocNDdx_y*(tmp129_)+mLocNDdy_y*(tmp130_))-mLocYIm)*mLocScNorm;
mCompDer[1][0] = 0;
mCompDer[1][1] = 0;
mCompDer[1][2] = 0;
mCompDer[1][3] = 0;
mCompDer[1][4] = 0;
mCompDer[1][5] = 0;
mCompDer[1][6] = 0;
mCompDer[1][7] = 0;
mCompDer[1][8] = 0;
mCompDer[1][9] = 0;
mCompDer[1][10] = 0;
mCompDer[1][11] = 0;
mCompDer[1][12] = 0;
mCompDer[1][13] = 0;
mCompDer[1][14] = 0;
mCompDer[1][15] = 0;
mCompDer[1][16] = ((tmp138_)*mLocNDdx_y+(tmp150_)*mLocNDdy_y)*mLocScNorm;
mCompDer[1][17] = ((tmp161_)*mLocNDdx_y+(tmp173_)*mLocNDdy_y)*mLocScNorm;
mCompDer[1][18] = ((tmp176_)*mLocNDdx_y+(tmp192_)*mLocNDdy_y)*mLocScNorm;
mCompDer[1][19] = ((tmp197_)*mLocNDdx_y+(tmp202_)*mLocNDdy_y)*mLocScNorm;
mCompDer[1][20] = ((tmp207_)*mLocNDdx_y+(tmp212_)*mLocNDdy_y)*mLocScNorm;
mCompDer[1][21] = ((tmp216_)*mLocNDdx_y+(tmp221_)*mLocNDdy_y)*mLocScNorm;
mCompDer[1][22] = ((tmp230_)*mLocNDdx_y+(tmp239_)*mLocNDdy_y)*mLocScNorm;
mCompDer[1][23] = ((tmp248_)*mLocNDdx_y+(tmp257_)*mLocNDdy_y)*mLocScNorm;
mCompDer[1][24] = ((tmp266_)*mLocNDdx_y+(tmp275_)*mLocNDdy_y)*mLocScNorm;
}
void cEqAppui_NoDist__PProjInc_M2CFour11x2::ComputeValDerivHessian()
{
ELISE_ASSERT(false,"Foncteur cEqAppui_NoDist__PProjInc_M2CFour11x2 Has no Der Sec");
}
void cEqAppui_NoDist__PProjInc_M2CFour11x2::SetNDP0_x(double aVal){ mLocNDP0_x = aVal;}
void cEqAppui_NoDist__PProjInc_M2CFour11x2::SetNDP0_y(double aVal){ mLocNDP0_y = aVal;}
void cEqAppui_NoDist__PProjInc_M2CFour11x2::SetNDdx_x(double aVal){ mLocNDdx_x = aVal;}
void cEqAppui_NoDist__PProjInc_M2CFour11x2::SetNDdx_y(double aVal){ mLocNDdx_y = aVal;}
void cEqAppui_NoDist__PProjInc_M2CFour11x2::SetNDdy_x(double aVal){ mLocNDdy_x = aVal;}
void cEqAppui_NoDist__PProjInc_M2CFour11x2::SetNDdy_y(double aVal){ mLocNDdy_y = aVal;}
void cEqAppui_NoDist__PProjInc_M2CFour11x2::SetProjI_x(double aVal){ mLocProjI_x = aVal;}
void cEqAppui_NoDist__PProjInc_M2CFour11x2::SetProjI_y(double aVal){ mLocProjI_y = aVal;}
void cEqAppui_NoDist__PProjInc_M2CFour11x2::SetProjI_z(double aVal){ mLocProjI_z = aVal;}
void cEqAppui_NoDist__PProjInc_M2CFour11x2::SetProjJ_x(double aVal){ mLocProjJ_x = aVal;}
void cEqAppui_NoDist__PProjInc_M2CFour11x2::SetProjJ_y(double aVal){ mLocProjJ_y = aVal;}
void cEqAppui_NoDist__PProjInc_M2CFour11x2::SetProjJ_z(double aVal){ mLocProjJ_z = aVal;}
void cEqAppui_NoDist__PProjInc_M2CFour11x2::SetProjK_x(double aVal){ mLocProjK_x = aVal;}
void cEqAppui_NoDist__PProjInc_M2CFour11x2::SetProjK_y(double aVal){ mLocProjK_y = aVal;}
void cEqAppui_NoDist__PProjInc_M2CFour11x2::SetProjK_z(double aVal){ mLocProjK_z = aVal;}
void cEqAppui_NoDist__PProjInc_M2CFour11x2::SetProjP0_x(double aVal){ mLocProjP0_x = aVal;}
void cEqAppui_NoDist__PProjInc_M2CFour11x2::SetProjP0_y(double aVal){ mLocProjP0_y = aVal;}
void cEqAppui_NoDist__PProjInc_M2CFour11x2::SetProjP0_z(double aVal){ mLocProjP0_z = aVal;}
void cEqAppui_NoDist__PProjInc_M2CFour11x2::SetScNorm(double aVal){ mLocScNorm = aVal;}
void cEqAppui_NoDist__PProjInc_M2CFour11x2::SetXIm(double aVal){ mLocXIm = aVal;}
void cEqAppui_NoDist__PProjInc_M2CFour11x2::SetYIm(double aVal){ mLocYIm = aVal;}
double * cEqAppui_NoDist__PProjInc_M2CFour11x2::AdrVarLocFromString(const std::string & aName)
{
if (aName == "NDP0_x") return & mLocNDP0_x;
if (aName == "NDP0_y") return & mLocNDP0_y;
if (aName == "NDdx_x") return & mLocNDdx_x;
if (aName == "NDdx_y") return & mLocNDdx_y;
if (aName == "NDdy_x") return & mLocNDdy_x;
if (aName == "NDdy_y") return & mLocNDdy_y;
if (aName == "ProjI_x") return & mLocProjI_x;
if (aName == "ProjI_y") return & mLocProjI_y;
if (aName == "ProjI_z") return & mLocProjI_z;
if (aName == "ProjJ_x") return & mLocProjJ_x;
if (aName == "ProjJ_y") return & mLocProjJ_y;
if (aName == "ProjJ_z") return & mLocProjJ_z;
if (aName == "ProjK_x") return & mLocProjK_x;
if (aName == "ProjK_y") return & mLocProjK_y;
if (aName == "ProjK_z") return & mLocProjK_z;
if (aName == "ProjP0_x") return & mLocProjP0_x;
if (aName == "ProjP0_y") return & mLocProjP0_y;
if (aName == "ProjP0_z") return & mLocProjP0_z;
if (aName == "ScNorm") return & mLocScNorm;
if (aName == "XIm") return & mLocXIm;
if (aName == "YIm") return & mLocYIm;
return 0;
}
cElCompiledFonc::cAutoAddEntry cEqAppui_NoDist__PProjInc_M2CFour11x2::mTheAuto("cEqAppui_NoDist__PProjInc_M2CFour11x2",cEqAppui_NoDist__PProjInc_M2CFour11x2::Alloc);
cElCompiledFonc * cEqAppui_NoDist__PProjInc_M2CFour11x2::Alloc()
{ return new cEqAppui_NoDist__PProjInc_M2CFour11x2();
}
| 19,068 | 9,851 |
////////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "Config/GeneratorConfiguration.h"
#include "Items/StructSpecificCode.h"
#include "Items/StructDescription.h"
#include "Generator/StructHelperGenerator.h"
using namespace std;
using namespace dxcodegen::Config;
using namespace dxcodegen::Items;
using namespace dxcodegen::Generator;
////////////////////////////////////////////////////////////////////////////////
StructHelperGenerator::StructHelperGenerator(GeneratorConfiguration& config, const std::vector<StructDescriptionPtr>& structures, const string& outputPath) :
m_config(config),
m_outputPath(outputPath),
m_className("DXStructHelper"),
IGenerator("class DXStructHelper")
{
m_structures = structures;
}
////////////////////////////////////////////////////////////////////////////////
StructHelperGenerator::~StructHelperGenerator()
{
}
////////////////////////////////////////////////////////////////////////////////
void StructHelperGenerator::GenerateCode()
{
GenerateHpp();
GenerateCpp();
}
////////////////////////////////////////////////////////////////////////////////
void StructHelperGenerator::GenerateHpp()
{
string filename = m_className + ".h";
ofstream* sortida = CreateFilename(m_outputPath + filename);
if (sortida && sortida->is_open())
{
cout << "Creating '" << filename << "'" << endl;
GenerateDefinition(*sortida);
}
CloseFilename(sortida);
}
////////////////////////////////////////////////////////////////////////////////
void StructHelperGenerator::GenerateCpp()
{
string filename = m_className + ".cpp";
ofstream* sortida = CreateFilename(m_outputPath + filename);
if (sortida && sortida->is_open())
{
cout << "Creating '" << filename << "'" << endl;
GenerateImplementation(*sortida);
}
CloseFilename(sortida);
}
////////////////////////////////////////////////////////////////////////////////
void StructHelperGenerator::GenerateDefinition(ofstream& sortida)
{
sortida << "#pragma once" << endl;
sortida << endl;
sortida << "namespace dxtraceman" << endl;
sortida << "{" << endl;
sortida << " class " << m_className << endl;
sortida << " {" << endl;
GenerateDefinitionMethods(sortida);
sortida << " };" << endl;
sortida << "}" << endl;
}
////////////////////////////////////////////////////////////////////////////////
void StructHelperGenerator::GenerateDefinitionMethods(ofstream& sortida)
{
sortida << " public:" << endl;
sortida << endl;
for (vector<StructDescriptionPtr>::iterator it = m_structures.begin(); it != m_structures.end(); it++)
{
sortida << " static int " << (*it)->GetName() << "_ToString(char* buffer, unsigned int size, " << (*it)->GetName() << "* value);" << endl;
}
sortida << endl;
}
////////////////////////////////////////////////////////////////////////////////
void StructHelperGenerator::GenerateImplementation(ofstream& sortida)
{
sortida << "#include \"stdafx.h\"" << endl;
sortida << "#include \"arraystream.h\"" << endl;
sortida << "#include \"DXTypeHelper.h\"" << endl;
sortida << "#include \"" << m_className << ".h\"" << endl;
sortida << endl;
sortida << "using namespace dxtraceman;" << endl;
sortida << endl;
for (vector<StructDescriptionPtr>::iterator it = m_structures.begin(); it != m_structures.end(); it++)
{
GenerateImplementationMethod(sortida, *it);
}
}
////////////////////////////////////////////////////////////////////////////////
void StructHelperGenerator::GenerateImplementationMethod(ofstream& sortida, StructDescriptionPtr structure)
{
StructSpecificCodePtr structSC = m_config.GetStructSpecificCode(structure->GetName());
// Begin generate method body
sortida << "int " << m_className << "::" << structure->GetName() << "_ToString(char* buffer, unsigned int size, " << structure->GetName() << "* value)" << endl;
sortida << "{" << endl;
sortida << " char local_buffer[256];" << endl;
sortida << " arraystream buf(buffer, size);" << endl;
sortida << " std::ostream out(&buf);" << endl;
sortida << endl;
sortida << " out << \"# struct " << structure->GetName() << "\" << std::endl;" << endl;
sortida << " out << \"# {\" << std::endl;" << endl;
for (unsigned int i=0; i < structure->GetFieldCount(); i++)
{
string fieldType = structure->GetField(i)->GetType();
string fieldName = structure->GetField(i)->GetName();
if (structSC)
{
StructFieldSpecificCodePtr fieldSC = structSC->GetField(fieldName);
if ((bool) fieldSC && (bool) fieldSC->GetPolicy(StructFieldSpecificCode::ChangeSaveType))
{
StructFieldSpecificCode::StructFieldChangeSaveTypePolicy* fieldPolicy = (StructFieldSpecificCode::StructFieldChangeSaveTypePolicy*) (void*) fieldSC->GetPolicy(StructFieldSpecificCode::ChangeSaveType);
fieldType = fieldPolicy->GetSaveType();
}
}
sortida << " DXTypeHelper::ToString(local_buffer, sizeof(local_buffer), (void*) &(value->" << fieldName << "), DXTypeHelper::TT_" << fieldType << ");" << endl;
sortida << " out << \"# " << fieldName << " = \" << local_buffer << std::endl;" << endl;
}
sortida << " out << \"# }\";" << endl;
sortida << endl;
sortida << " buf.finalize();" << endl;
sortida << " return buf.tellp();" << endl;
// End generate method body
sortida << "}" << endl;
sortida << endl;
}
////////////////////////////////////////////////////////////////////////////////
| 5,488 | 1,533 |
/*
In recreational number theory, a narcissistic number is also known
as a pluperfect digital invariant (PPDI), an Armstrong number or a
plus perfect number is a number that is the sum of its digits
each raised to the power of the number of digits.
*/
#include <bits/stdc++.h>
using namespace std;
// Function to check whether the Number is Armstrong Number or Not.
bool is_armstrong(int n)
{
if (n < 0)
{
return false;
}
int sum = 0;
int var = n;
int number_of_digits = floor(log10(n) + 1);
while (var > 0)
{
int rem = var % 10;
sum = sum + pow(rem, number_of_digits);
var = var / 10;
}
return n == sum;
}
int main()
{
cout << "Enter the Number to check whether it is Armstrong Number or Not:" << endl;
int n;
cin >> n;
if (is_armstrong(n))
cout << n << " is Armstrong Number." << endl;
else
cout << n << " is Not Armstrong Number." << endl;
return 0;
}
/*
Input:
Enter the Number to check whether it is Armstrong Number or Not:
153
Output:
153 is Armstrong Number.
Input:
Enter the Number to check whether it is Armstrong Number or Not:
12
Output:
12 is Not Armstrong Number.
Time Complexity: O(log(n))
Space Complexity: O(1)
*/
| 1,165 | 423 |
//
// file: package.cpp
// author: Michael Brockus
// gmail: <michaelbrockus@gmail.com>
//
#include "hackazon/package.hpp"
//
// Should return a greeting message as it’s initial value
//
// Param list:
// -> There is none to speak of at this time.
//
const char *hak::greet(void)
{
return "Hello, C++ Developer.";
} // end of functions greet
| 347 | 122 |
/**
* @file binaryBuffer.hpp
* @data 21 september, 2017
*
* \class BinaryBuffer
*
* \brief Buffer between sensor and SPI SD write
*
* This class holds a finite amount of data and acts
* as a FiFo.
*/
#pragma once
#include <vector>
#include "SystemVariables.hpp"
#include "esp_log.h"
class BinaryBuffer{
public:
/*!
* \brief BinaryBuffer constructor
*
* Clear the buffer and set state to write only.
*/
BinaryBuffer();
/*!
* \brief readOnly method
*
* This method sets the buffer to read only mode.
*/
void readOnly();
/*!
* \brief writeOnly method
*
* This method set the buffer to write only mode.
*/
void writeOnly();
/*!
* \brief clear method
*
* This method clears the BinaryBuffer.
*/
void clear();
/*!
* \brief add method
* \param in SampleData structure
* \return bool returns flase if state is read only
*
* This method adds a SampleData strcture
* to the buffer.
*/
bool add( SampleData in );
/*!
* \brief get method
* \return SampleData buffer pointer
*
* This method returns a pointer to the
* first sample of the buffer.
*/
const std::vector<SampleData>& get(); // should perhaps be a pointer, copy could be too slow on large scale operations?
/*!
* \brief isFull method
* \return bool (true) if the buffer is full
*
* Returns true if the buffer is full
*/
bool isFull();
/*!
* \brief BinaryBuffer deconstructor
*
* Empty, not implemented.
*/
~BinaryBuffer();
private:
bool readState();
bool state;
std::vector<SampleData> buffer;
const int BufferSize = BINARY_BUFFER_SIZE;
};
| 1,680 | 594 |
#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include "../src/Graph.h"
#include "../src/Person.h"
using namespace std;
using testing::Eq;
void createNetwork(Graph<Person> & net1)
{
Person p1("Ana",19);
Person p2("Carlos",33);
Person p3("Filipe", 20);
Person p4("Ines", 18);
Person p5("Maria", 24);
Person p6("Rui",21);
Person p7("Vasco",28);
net1.addVertex(p1); net1.addVertex(p2);
net1.addVertex(p3); net1.addVertex(p4);
net1.addVertex(p5); net1.addVertex(p6); net1.addVertex(p7);
net1.addEdge(p1,p2,0);
net1.addEdge(p1,p3,0);
net1.addEdge(p1,p4,0);
net1.addEdge(p2,p5,0);
net1.addEdge(p5,p6,0);
net1.addEdge(p5,p1,0);
net1.addEdge(p3,p6,0);
net1.addEdge(p3,p7,0);
net1.addEdge(p6,p2,0);
}
TEST(CAL_FP04, test_addVertex) {
Graph<Person> net1;
Person p1("Ana",19);
Person p2("Carlos",33);
Person p3("Filipe", 20);
Person p4("Ines", 18);
net1.addVertex(p1); net1.addVertex(p2);
net1.addVertex(p3); net1.addVertex(p4);
EXPECT_EQ(false, net1.addVertex(p2));
EXPECT_EQ(4, net1.getNumVertex());
}
TEST(CAL_FP04, test_removeVertex) {
Graph<Person> net1;
Person p1("Ana",19);
Person p2("Carlos",33);
Person p3("Filipe", 20);
Person p4("Ines", 18);
net1.addVertex(p1); net1.addVertex(p2);
net1.addVertex(p3); net1.addVertex(p4);
EXPECT_EQ(true, net1.removeVertex(p2));
EXPECT_EQ(false, net1.removeVertex(p2));
EXPECT_EQ(3, net1.getNumVertex());
}
TEST(CAL_FP04, test_addEdge) {
Graph<Person> net1;
Person p1("Ana",19);
Person p2("Carlos",33);
Person p3("Filipe", 20);
Person p4("Ines", 18);
Person p5("Maria", 24);
net1.addVertex(p1); net1.addVertex(p2);
net1.addVertex(p3); net1.addVertex(p4);
EXPECT_EQ(true, net1.addEdge(p1,p2,0));
EXPECT_EQ(true, net1.addEdge(p1,p3,0));
EXPECT_EQ(true, net1.addEdge(p1,p4,0));
EXPECT_EQ(false, net1.addEdge(p2,p5,0));
}
TEST(CAL_FP04, test_removeEdge) {
Graph<Person> net1;
Person p1("Ana",19);
Person p2("Carlos",33);
Person p3("Filipe", 20);
Person p4("Ines", 18);
Person p5("Maria", 24);
net1.addVertex(p1); net1.addVertex(p2);
net1.addVertex(p3); net1.addVertex(p4);
EXPECT_EQ(true, net1.addEdge(p1,p2,0));
EXPECT_EQ(true, net1.addEdge(p1,p3,0));
EXPECT_EQ(true, net1.addEdge(p1,p4,0));
EXPECT_EQ(true, net1.addEdge(p2,p4,0));
EXPECT_EQ(true, net1.removeEdge(p1,p3));
EXPECT_EQ(false, net1.removeEdge(p1,p5));
EXPECT_EQ(false, net1.removeEdge(p2,p3));
}
TEST(CAL_FP04, test_dfs) {
Graph<Person> net1;
createNetwork(net1);
vector<Person> v1 = net1.dfs();
string names[] = {"Ana", "Carlos", "Maria", "Rui", "Filipe", "Vasco", "Ines"};
for (unsigned i = 0; i < 7; i++)
if (i < v1.size())
EXPECT_EQ(names[i], v1[i].getName());
else
EXPECT_EQ(names[i], "(null)");
}
TEST(CAL_FP04, test_bfs) {
Graph<Person> net1;
createNetwork(net1);
vector<Person> v1 = net1.bfs(Person("Ana",19));
string names[] = {"Ana", "Carlos", "Filipe", "Ines", "Maria", "Rui", "Vasco"};
for (unsigned i = 0; i < 7; i++)
if (i < v1.size())
EXPECT_EQ(names[i], v1[i].getName());
else
EXPECT_EQ(names[i], "(null)");
}
TEST(CAL_FP04, test_removeVertex_Again) {
Graph<Person> net1;
createNetwork(net1);
Person p2("Carlos",33);
EXPECT_EQ(true, net1.removeVertex(p2));
vector<Person> v1=net1.dfs();
string names[] = {"Ana", "Filipe", "Rui", "Vasco", "Ines", "Maria"};
for (unsigned i = 0; i < 6; i++)
EXPECT_EQ(names[i], v1[i].getName());
}
TEST(CAL_FP04, test_removeEdge_Again) {
/* //uncomment test body below!
Graph<Person> net1;
createNetwork(net1);
Person p5("Maria", 24);
Person p6("Rui",21);
EXPECT_EQ(true, net1.removeEdge(p5,p6));
vector<Person> v1=net1.dfs();
string names[] = {"Ana", "Carlos", "Maria", "Filipe", "Rui", "Vasco", "Ines"};
for (unsigned i = 0; i < 7; i++)
EXPECT_EQ(names[i], v1[i].getName());
*/
}
TEST(CAL_FP04, test_maxNewChildren) {
Graph<Person> net1;
Person p1("Ana",19);
Person p2("Carlos",33);
Person p3("Filipe", 20);
Person p4("Ines", 18);
Person p5("Maria", 24);
Person p6("Rui",21);
Person p7("Vasco",28);
net1.addVertex(p1); net1.addVertex(p2);
net1.addVertex(p3); net1.addVertex(p4);
net1.addVertex(p5); net1.addVertex(p6); net1.addVertex(p7);
net1.addEdge(p1,p2,0);
net1.addEdge(p1,p3,0);
net1.addEdge(p2,p5,0);
net1.addEdge(p3,p4,0);
net1.addEdge(p5,p6,0);
net1.addEdge(p5,p1,0);
net1.addEdge(p3,p6,0);
net1.addEdge(p3,p7,0);
net1.addEdge(p3,p2,0);
Person pt;
EXPECT_EQ(3, net1.maxNewChildren(Person("Ana",19), pt));
EXPECT_EQ("Filipe", pt.getName());
}
TEST(CAL_FP04, test_isDAG) {
Graph<int> myGraph;
myGraph.addVertex(0);myGraph.addVertex(1); myGraph.addVertex(2);
myGraph.addVertex(3); myGraph.addVertex(4); myGraph.addVertex(5);
myGraph.addEdge(1, 2, 0);
myGraph.addEdge(2, 5, 0);
myGraph.addEdge(5, 4, 0);
myGraph.addEdge(4, 1, 0);
myGraph.addEdge(5, 1, 0);
myGraph.addEdge(2, 3, 0);
myGraph.addEdge(3, 1, 0);
myGraph.addEdge(0, 4, 0);
EXPECT_EQ(false, myGraph.isDAG());
myGraph.removeEdge(4, 1);
myGraph.removeEdge(5, 1);
myGraph.removeEdge(2, 3);
EXPECT_EQ(true, myGraph.isDAG());
myGraph.addEdge(1, 4, 0);
EXPECT_EQ(true, myGraph.isDAG());
}
TEST(CAL_FP04, test_topsort) {
Graph<int> myGraph;
myGraph.addVertex(1); myGraph.addVertex(2); myGraph.addVertex(3); myGraph.addVertex(4);
myGraph.addVertex(5); myGraph.addVertex(6); myGraph.addVertex(7);
myGraph.addEdge(1, 2, 0);
myGraph.addEdge(1, 4, 0);
myGraph.addEdge(1, 3, 0);
myGraph.addEdge(2, 5, 0);
myGraph.addEdge(2, 4, 0);
myGraph.addEdge(3, 6, 0);
myGraph.addEdge(4, 3, 0);
myGraph.addEdge(4, 6, 0);
myGraph.addEdge(4, 7, 0);
myGraph.addEdge(5, 4, 0);
myGraph.addEdge(5, 7, 0);
myGraph.addEdge(7, 6, 0);
vector<int> topOrder;
topOrder = myGraph.topsort();
stringstream ss;
for( unsigned int i = 0; i < topOrder.size(); i++)
ss << topOrder[i] << " ";
EXPECT_EQ("1 2 5 4 3 7 6 ", ss.str());
//para testar a inclusao de um ciclo no grafo!
myGraph.addEdge(3, 1, 0);
topOrder = myGraph.topsort();
ss.str("");
for( unsigned int i = 0; i < topOrder.size(); i++)
ss << topOrder[i] << " ";
EXPECT_EQ("", ss.str());
}
| 6,589 | 3,049 |
#include "ionspaymentprocessor.h"
#include <QString>
#include <iostream>
IONSPaymentProcessor::IONSPaymentProcessor(BitcoinGUI * gui, QObject * parent)
: QObject(parent), gui(gui)
{
}
void IONSPaymentProcessor::pay(QString address, QString fee)
{
QString uri("chameleon:" + address + "?amount=" + fee);
gui->handleURI(uri);
}
void IONSPaymentProcessor::myUsernames()
{
gui->ionsMyUsernamesClicked();
}
void IONSPaymentProcessor::Register()
{
gui->ionsRegisterClicked();
}
| 496 | 182 |
//=========================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
//
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//=========================================================================
#include "pqCMBColorMapWidget.h"
#include "pqApplicationCore.h"
#include "pqDataRepresentation.h"
#include "pqProxyWidget.h"
#include "vtkCommand.h"
#include "vtkSMPVRepresentationProxy.h"
#include "vtkSMProperty.h"
#include "vtkSMPropertyHelper.h"
#include "vtkSMTransferFunctionProxy.h"
#include "vtkWeakPointer.h"
#include <QPointer>
#include <QVBoxLayout>
class pqCMBColorMapWidget::pqInternals
{
public:
QPointer<pqProxyWidget> ProxyWidget;
QPointer<pqDataRepresentation> ActiveRepresentation;
unsigned long ObserverId;
pqInternals(pqCMBColorMapWidget* vtkNotUsed(self))
: ObserverId(0)
{
}
~pqInternals() {}
};
pqCMBColorMapWidget::pqCMBColorMapWidget(QWidget* parentObject)
: Superclass(parentObject)
, Internals(new pqCMBColorMapWidget::pqInternals(this))
{
// pqActiveObjects *activeObjects = &pqActiveObjects::instance();
// this->connect(activeObjects, SIGNAL(representationChanged(pqDataRepresentation*)),
// this, SLOT(updateActive()));
new QVBoxLayout(this);
this->layout()->setMargin(0);
this->updateRepresentation();
}
pqCMBColorMapWidget::~pqCMBColorMapWidget()
{
delete this->Internals;
this->Internals = NULL;
}
void pqCMBColorMapWidget::updatePanel()
{
if (this->Internals->ProxyWidget)
{
this->Internals->ProxyWidget->filterWidgets(true);
}
}
void pqCMBColorMapWidget::updateRepresentation()
{
// pqDataRepresentation* repr =
// pqActiveObjects::instance().activeRepresentation();
pqDataRepresentation* repr = this->Internals->ActiveRepresentation;
// Set the current LUT proxy to edit.
if (repr && vtkSMPVRepresentationProxy::GetUsingScalarColoring(repr->getProxy()))
{
this->setColorTransferFunction(
vtkSMPropertyHelper(repr->getProxy(), "LookupTable", true).GetAsProxy());
}
else
{
this->setColorTransferFunction(NULL);
}
}
void pqCMBColorMapWidget::setDataRepresentation(pqDataRepresentation* repr)
{
// this method sets up hooks to ensure that when the repr's properties are
// modified, the editor shows the correct LUT.
if (this->Internals->ActiveRepresentation == repr)
{
return;
}
if (this->Internals->ActiveRepresentation)
{
// disconnect signals.
if (this->Internals->ObserverId)
{
this->Internals->ActiveRepresentation->getProxy()->RemoveObserver(
this->Internals->ObserverId);
}
}
this->Internals->ObserverId = 0;
this->Internals->ActiveRepresentation = repr;
if (repr && repr->getProxy())
{
this->Internals->ObserverId = repr->getProxy()->AddObserver(
vtkCommand::PropertyModifiedEvent, this, &pqCMBColorMapWidget::updateRepresentation);
}
this->updateRepresentation();
}
void pqCMBColorMapWidget::setColorTransferFunction(vtkSMProxy* ctf)
{
if (this->Internals->ProxyWidget == NULL && ctf == NULL)
{
return;
}
if (this->Internals->ProxyWidget && ctf && this->Internals->ProxyWidget->proxy() == ctf)
{
return;
}
if ((ctf == NULL && this->Internals->ProxyWidget) ||
(this->Internals->ProxyWidget && ctf && this->Internals->ProxyWidget->proxy() != ctf))
{
this->layout()->removeWidget(this->Internals->ProxyWidget);
delete this->Internals->ProxyWidget;
}
if (!ctf)
{
return;
}
pqProxyWidget* widget = new pqProxyWidget(ctf, this);
widget->setObjectName("Properties");
widget->setApplyChangesImmediately(true);
widget->filterWidgets();
this->layout()->addWidget(widget);
this->Internals->ProxyWidget = widget;
this->updatePanel();
QObject::connect(widget, SIGNAL(changeFinished()), this, SLOT(renderViews()));
}
void pqCMBColorMapWidget::renderViews()
{
if (this->Internals->ActiveRepresentation)
{
this->Internals->ActiveRepresentation->renderViewEventually();
}
}
| 4,209 | 1,391 |
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <set>
using namespace std;
class Class
{
public:
virtual int func1()
{
return 0;
}
virtual int func2()
{
return 1;
}
int var1;
float var2;
};
class Der : public Class
{
public:
int func1()
{
return 2;
}
};
int main()
{
Class* obj = new Der;
cout << Class << endl;
return 0;
}
#if 0
typedef long double ld;
ld poly[101];
ld newPoly[101];
ld newton(ld x)
{
int cnt = 0;
while (true)
{
ld fx = poly[0];
ld dfx = 0.0;
for(int i=1;i<=100;i++)
{
dfx += i*poly[i]*pow(x,i-1);
fx += poly[i]*pow(x,i);
}
x = x - fx/dfx;
cnt ++ ;
if(cnt > 100000) return 0xdeadbeef;
ld res = poly[0];
for(int i=1;i<=100;i++)
if(poly[i])
res += poly[i]*pow(x,i);
if(res < 1e-5) break;
}
cout << x << endl;
return x;
}
void divide(ld divisor)
{
memset(newPoly,0,sizeof(newPoly));
ld next = poly[100];
for (int i=99;i>=0;i--)
{
newPoly[i] = next;
next = next*divisor + poly[i];
}
memcpy(poly,newPoly,sizeof(poly));
}
int main()
{
int n;
cin >> n;
int co,po;
int tm = 0;
for(int i=0;i!=n;i++)
{
cin >> co >> po;
poly[po] = co;
if(!tm) tm = po;
}
set<ld> ans;
for(int i=0;i!=tm;i++)
{
ld root = newton(1227);
if(root==0xdeadbeef)
break;
ans.insert((ld)((((long long)(root))*100000)/100000));
divide(root);
}
if(ans.size()==0)
{
cout << "NO REAL ROOTS" << endl;
} else {
for(set<ld>::iterator it = ans.begin();it!=ans.end();it++)
cout << *it << endl;
}
return 0;
}
#endif | 1,567 | 833 |
// Copyright (c) 2018 Microsoft Corporation
// Licensed under the MIT license.
// Author: Paul Koch <code@koch.ninja>
#ifndef TREE_SWEEP_HPP
#define TREE_SWEEP_HPP
#include <type_traits> // std::is_standard_layout
#include <stddef.h> // size_t, ptrdiff_t
#include "ebm_native.h"
#include "logging.h"
#include "zones.h"
#include "ebm_internal.hpp"
#include "HistogramTargetEntry.hpp"
namespace DEFINED_ZONE_NAME {
#ifndef DEFINED_ZONE_NAME
#error DEFINED_ZONE_NAME must be defined
#endif // DEFINED_ZONE_NAME
template<bool bClassification>
struct HistogramBucket;
template<bool bClassification>
struct TreeSweep final {
private:
size_t m_cBestSamplesLeft;
FloatEbmType m_bestWeightLeft;
const HistogramBucket<bClassification> * m_pBestHistogramBucketEntry;
// use the "struct hack" since Flexible array member method is not available in C++
// m_aBestHistogramTargetEntry must be the last item in this struct
// AND this class must be "is_standard_layout" since otherwise we can't guarantee that this item is placed at the bottom
// standard layout classes have some additional odd restrictions like all the member data must be in a single class
// (either the parent or child) if the class is derrived
HistogramTargetEntry<bClassification> m_aBestHistogramTargetEntry[1];
public:
TreeSweep() = default; // preserve our POD status
~TreeSweep() = default; // preserve our POD status
void * operator new(std::size_t) = delete; // we only use malloc/free in this library
void operator delete (void *) = delete; // we only use malloc/free in this library
INLINE_ALWAYS size_t GetCountBestSamplesLeft() const {
return m_cBestSamplesLeft;
}
INLINE_ALWAYS void SetCountBestSamplesLeft(const size_t cBestSamplesLeft) {
m_cBestSamplesLeft = cBestSamplesLeft;
}
INLINE_ALWAYS FloatEbmType GetBestWeightLeft() const {
return m_bestWeightLeft;
}
INLINE_ALWAYS void SetBestWeightLeft(const FloatEbmType bestWeightLeft) {
m_bestWeightLeft = bestWeightLeft;
}
INLINE_ALWAYS const HistogramBucket<bClassification> * GetBestHistogramBucketEntry() const {
return m_pBestHistogramBucketEntry;
}
INLINE_ALWAYS void SetBestHistogramBucketEntry(const HistogramBucket<bClassification> * pBestHistogramBucketEntry) {
m_pBestHistogramBucketEntry = pBestHistogramBucketEntry;
}
INLINE_ALWAYS HistogramTargetEntry<bClassification> * GetBestHistogramTargetEntry() {
return ArrayToPointer(m_aBestHistogramTargetEntry);
}
};
static_assert(std::is_standard_layout<TreeSweep<true>>::value && std::is_standard_layout<TreeSweep<false>>::value,
"We use the struct hack in several places, so disallow non-standard_layout types in general");
static_assert(std::is_trivial<TreeSweep<true>>::value && std::is_trivial<TreeSweep<false>>::value,
"We use memcpy in several places, so disallow non-trivial types in general");
static_assert(std::is_pod<TreeSweep<true>>::value && std::is_pod<TreeSweep<false>>::value,
"We use a lot of C constructs, so disallow non-POD types in general");
INLINE_ALWAYS bool GetTreeSweepSizeOverflow(const bool bClassification, const size_t cVectorLength) {
const size_t cBytesHistogramTargetEntry = bClassification ?
sizeof(HistogramTargetEntry<true>) :
sizeof(HistogramTargetEntry<false>);
if(UNLIKELY(IsMultiplyError(cBytesHistogramTargetEntry, cVectorLength))) {
return true;
}
const size_t cBytesTreeSweepComponent = bClassification ?
(sizeof(TreeSweep<true>) - sizeof(HistogramTargetEntry<true>)) :
(sizeof(TreeSweep<false>) - sizeof(HistogramTargetEntry<false>));
if(UNLIKELY(IsAddError(cBytesTreeSweepComponent, cBytesHistogramTargetEntry * cVectorLength))) {
return true;
}
return false;
}
INLINE_ALWAYS size_t GetTreeSweepSize(bool bClassification, const size_t cVectorLength) {
const size_t cBytesTreeSweepComponent = bClassification ?
sizeof(TreeSweep<true>) - sizeof(HistogramTargetEntry<true>) :
sizeof(TreeSweep<false>) - sizeof(HistogramTargetEntry<false>);
const size_t cBytesHistogramTargetEntry = bClassification ?
sizeof(HistogramTargetEntry<true>) :
sizeof(HistogramTargetEntry<false>);
return cBytesTreeSweepComponent + cBytesHistogramTargetEntry * cVectorLength;
}
template<bool bClassification>
INLINE_ALWAYS TreeSweep<bClassification> * AddBytesTreeSweep(TreeSweep<bClassification> * const pTreeSweep, const size_t cBytesAdd) {
return reinterpret_cast<TreeSweep<bClassification> *>(reinterpret_cast<char *>(pTreeSweep) + cBytesAdd);
}
template<bool bClassification>
INLINE_ALWAYS size_t CountTreeSweep(
const TreeSweep<bClassification> * const pTreeSweepStart,
const TreeSweep<bClassification> * const pTreeSweepCur,
const size_t cBytesPerTreeSweep
) {
EBM_ASSERT(reinterpret_cast<const char *>(pTreeSweepStart) <= reinterpret_cast<const char *>(pTreeSweepCur));
const size_t cBytesDiff = reinterpret_cast<const char *>(pTreeSweepCur) - reinterpret_cast<const char *>(pTreeSweepStart);
EBM_ASSERT(0 == cBytesDiff % cBytesPerTreeSweep);
return cBytesDiff / cBytesPerTreeSweep;
}
} // DEFINED_ZONE_NAME
#endif // TREE_SWEEP_HPP
| 5,215 | 1,773 |
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <proxygen/lib/http/codec/compress/HPACKEncoderBase.h>
namespace proxygen {
uint32_t HPACKEncoderBase::handlePendingContextUpdate(HPACKEncodeBuffer& buf,
uint32_t tableCapacity) {
CHECK_EQ(HPACK::TABLE_SIZE_UPDATE.code, HPACK::Q_TABLE_SIZE_UPDATE.code)
<< "Code assumes these are equal";
uint32_t encoded = 0;
if (pendingContextUpdate_) {
VLOG(5) << "Encoding table size update size=" << tableCapacity;
encoded = buf.encodeInteger(tableCapacity, HPACK::TABLE_SIZE_UPDATE);
pendingContextUpdate_ = false;
}
return encoded;
}
} // namespace proxygen
| 863 | 272 |
#include "modules/twinkle.h"
// Background color for 'unlit' pixels
// Can be set to CRGB::Black if desired.
CRGB gBackgroundColor = CRGB::Black;
// Example of dim incandescent fairy light background color
// CRGB gBackgroundColor = CRGB(CRGB::FairyLight).nscale8_video(16);
// Add or remove palette names from this list to control which color
// palettes are used, and in what order.
const TProgmemRGBPalette16* ActivePaletteList[] = {
//&RetroC9_p,
//&BlueWhite_p,
//&RainbowColors_p,
&HeatColors_p,
//&LavaColors_p,
&FairyLight_p,
&RedGreenWhite_p,
&ForestColors_p,
&PartyColors_p,
&RedWhite_p,
&OceanColors_p,
//&Snow_p,
//&Holly_p,
//&Ice_p
};
CRGBPalette16 gCurrentPalette;
CRGBPalette16 gTargetPalette;
void twinkle_init() {
delay( 1000 ); //safety startup delay
chooseNextColorPalette(gTargetPalette);
}
void twinkle_update(CRGBSet& user_leds)
{
EVERY_N_SECONDS( SECONDS_PER_PALETTE ) {
chooseNextColorPalette( gTargetPalette );
}
EVERY_N_MILLISECONDS( 10 ) {
nblendPaletteTowardPalette( gCurrentPalette, gTargetPalette, 12);
}
drawTwinkles( user_leds);
}
void drawTwinkles( CRGBSet& L)
{
// "PRNG16" is the pseudorandom number generator
// It MUST be reset to the same starting value each time
// this function is called, so that the sequence of 'random'
// numbers that it generates is (paradoxically) stable.
uint16_t PRNG16 = 11337;
uint32_t clock32 = millis();
// Set up the background color, "bg".
// if AUTO_SELECT_BACKGROUND_COLOR == 1, and the first two colors of
// the current palette are identical, then a deeply faded version of
// that color is used for the background color
CRGB bg;
if( (AUTO_SELECT_BACKGROUND_COLOR == 1) &&
(gCurrentPalette[0] == gCurrentPalette[1] )) {
bg = gCurrentPalette[0];
uint8_t bglight = bg.getAverageLight();
if( bglight > 64) {
bg.nscale8_video( 16); // very bright, so scale to 1/16th
} else if( bglight > 16) {
bg.nscale8_video( 64); // not that bright, so scale to 1/4th
} else {
bg.nscale8_video( 86); // dim, scale to 1/3rd.
}
} else {
bg = gBackgroundColor; // just use the explicitly defined background color
}
uint8_t backgroundBrightness = bg.getAverageLight();
for( CRGB& pixel: L) {
PRNG16 = (uint16_t)(PRNG16 * 2053) + 1384; // next 'random' number
uint16_t myclockoffset16= PRNG16; // use that number as clock offset
PRNG16 = (uint16_t)(PRNG16 * 2053) + 1384; // next 'random' number
// use that number as clock speed adjustment factor (in 8ths, from 8/8ths to 23/8ths)
uint8_t myspeedmultiplierQ5_3 = ((((PRNG16 & 0xFF)>>4) + (PRNG16 & 0x0F)) & 0x0F) + 0x08;
uint32_t myclock30 = (uint32_t)((clock32 * myspeedmultiplierQ5_3) >> 3) + myclockoffset16;
uint8_t myunique8 = PRNG16 >> 8; // get 'salt' value for this pixel
// We now have the adjusted 'clock' for this pixel, now we call
// the function that computes what color the pixel should be based
// on the "brightness = f( time )" idea.
CRGB c = computeOneTwinkle( myclock30, myunique8);
uint8_t cbright = c.getAverageLight();
int16_t deltabright = cbright - backgroundBrightness;
if( deltabright >= 32 || (!bg)) {
// If the new pixel is significantly brighter than the background color,
// use the new color.
pixel = c;
} else if( deltabright > 0 ) {
// If the new pixel is just slightly brighter than the background color,
// mix a blend of the new color and the background color
pixel = blend( bg, c, deltabright * 8);
} else {
// if the new pixel is not at all brighter than the background color,
// just use the background color.
pixel = bg;
}
}
}
CRGB computeOneTwinkle( uint32_t ms, uint8_t salt)
{
uint16_t ticks = ms >> (8-TWINKLE_SPEED);
uint8_t fastcycle8 = ticks;
uint16_t slowcycle16 = (ticks >> 8) + salt;
slowcycle16 += sin8( slowcycle16);
slowcycle16 = (slowcycle16 * 2053) + 1384;
uint8_t slowcycle8 = (slowcycle16 & 0xFF) + (slowcycle16 >> 8);
uint8_t bright = 0;
if( ((slowcycle8 & 0x0E)/2) < TWINKLE_DENSITY) {
bright = attackDecayWave8( fastcycle8);
}
uint8_t hue = slowcycle8 - salt;
CRGB c;
if( bright > 0) {
c = ColorFromPalette( gCurrentPalette, hue, bright, NOBLEND);
if( COOL_LIKE_INCANDESCENT == 1 ) {
coolLikeIncandescent( c, fastcycle8);
}
} else {
c = CRGB::Black;
}
return c;
}
uint8_t attackDecayWave8( uint8_t i)
{
if( i < 86) {
return i * 3;
} else {
i -= 86;
return 255 - (i + (i/2));
}
}
void coolLikeIncandescent( CRGB& c, uint8_t phase)
{
if( phase < 128) return;
uint8_t cooling = (phase - 128) >> 4;
c.g = qsub8( c.g, cooling);
c.b = qsub8( c.b, cooling * 2);
}
void chooseNextColorPalette( CRGBPalette16& pal)
{
const uint8_t numberOfPalettes = sizeof(ActivePaletteList) / sizeof(ActivePaletteList[0]);
static uint8_t whichPalette = -1;
whichPalette = addmod8( whichPalette, 1, numberOfPalettes);
pal = *(ActivePaletteList[whichPalette]);
}
| 5,104 | 2,072 |
#include "browser.hpp"
#include <cstdlib>
#include <string>
#include "../util/range.hpp"
#include "config/config.hpp"
#ifdef ELONA_OS_WINDOWS
#include <windows.h>
#endif
using namespace std::literals::string_literals;
namespace
{
bool _is_trusted_url(const char* url)
{
const char* trusted_urls[] = {
"http://ylvania.org/jp",
"http://ylvania.org/en",
"https://elonafoobar.com",
};
return range::find(trusted_urls, url) != std::end(trusted_urls);
}
} // namespace
namespace elona
{
void open_browser(const char* url)
{
if (Config::instance().is_test)
{
return;
}
if (!_is_trusted_url(url))
{
throw std::runtime_error{"Try to open unknown URL!"};
}
#if defined(ELONA_OS_WINDOWS)
HWND parent = NULL;
LPCWSTR operation = NULL;
// `url` must be ascii only.
const auto len = std::strlen(url);
std::basic_string<WCHAR> url_(len, L'\0');
for (size_t i = 0; i < len; ++i)
{
url_[i] = url[i];
}
LPCWSTR extra_parameter = NULL;
LPCWSTR default_dir = NULL;
INT show_command = SW_SHOWNORMAL;
::ShellExecute(
parent,
operation,
url_.c_str(),
extra_parameter,
default_dir,
show_command);
#elif defined(ELONA_OS_MACOS)
std::system(("open "s + url).c_str());
#elif defined(ELONA_OS_LINUX)
std::system(("xdg-open "s + url).c_str());
#elif defined(ELONA_OS_ANDROID)
// TODO: implement for android.
(void)url;
return;
#else
#error "Unsupported OS"
#endif
}
} // namespace elona
| 1,574 | 597 |
#include "irods/rsDataObjLseek.hpp"
#include "irods/dataObjLseek.h"
#include "irods/rodsLog.h"
#include "irods/rsGlobalExtern.hpp"
#include "irods/rcGlobalExtern.h"
#include "irods/subStructFileLseek.h"
#include "irods/objMetaOpr.hpp"
#include "irods/subStructFileUnlink.h"
#include "irods/rsSubStructFileLseek.hpp"
#include "irods/rsFileLseek.hpp"
#include "irods/irods_resource_backport.hpp"
#include <cstring>
int rsDataObjLseek(rsComm_t* rsComm,
openedDataObjInp_t* dataObjLseekInp,
fileLseekOut_t** dataObjLseekOut)
{
const int l1descInx = dataObjLseekInp->l1descInx;
if (l1descInx <= 2 || l1descInx >= NUM_L1_DESC) {
rodsLog(LOG_ERROR, "%s: l1descInx %d out of range", __func__, l1descInx);
return SYS_FILE_DESC_OUT_OF_RANGE;
}
auto& l1desc = L1desc[l1descInx];
if (l1desc.inuseFlag != FD_INUSE) {
return BAD_INPUT_DESC_INDEX;
}
if (l1desc.remoteZoneHost) {
// Cross zone operation.
dataObjLseekInp->l1descInx = l1desc.remoteL1descInx;
const auto ec = rcDataObjLseek(l1desc.remoteZoneHost->conn, dataObjLseekInp, dataObjLseekOut);
dataObjLseekInp->l1descInx = l1descInx;
return ec;
}
const int l3descInx = l1desc.l3descInx;
if (l3descInx <= 2) {
rodsLog(LOG_ERROR, "%s: l3descInx %d out of range", __func__, l3descInx);
return SYS_FILE_DESC_OUT_OF_RANGE;
}
auto* dataObjInfo = l1desc.dataObjInfo;
// Extract the host location from the resource hierarchy.
std::string location;
if (const auto ret = irods::get_loc_for_hier_string(dataObjInfo->rescHier, location); !ret.ok()) {
irods::log(PASSMSG("rsDataObjLseek: failed in get_loc_for_hier_string", ret));
return ret.code();
}
if (getStructFileType(dataObjInfo->specColl) >= 0) {
subStructFileLseekInp_t subStructFileLseekInp{};
subStructFileLseekInp.type = dataObjInfo->specColl->type;
subStructFileLseekInp.fd = l1desc.l3descInx;
subStructFileLseekInp.offset = dataObjLseekInp->offset;
subStructFileLseekInp.whence = dataObjLseekInp->whence;
rstrcpy(subStructFileLseekInp.addr.hostAddr, location.c_str(), NAME_LEN);
rstrcpy(subStructFileLseekInp.resc_hier, dataObjInfo->rescHier, NAME_LEN);
return rsSubStructFileLseek(rsComm, &subStructFileLseekInp, dataObjLseekOut);
}
// If the replica was opened in read-only mode, then don't allow the client
// to seek past the data size in the catalog. This is necessary because the
// size of the replica in storage could be larger than the data size in the
// catalog.
//
// For all other modes, let the seek operation do what it normally does.
//
// This code does not apply to objects that are related to special collections.
const auto offset = (O_RDONLY == (l1desc.dataObjInp->openFlags & O_ACCMODE))
? std::min(dataObjLseekInp->offset, dataObjInfo->dataSize)
: dataObjLseekInp->offset;
*dataObjLseekOut = static_cast<fileLseekOut_t*>(malloc(sizeof(fileLseekOut_t)));
std::memset(*dataObjLseekOut, 0, sizeof(fileLseekOut_t));
(*dataObjLseekOut)->offset = _l3Lseek(rsComm, l3descInx, offset, dataObjLseekInp->whence);
if ((*dataObjLseekOut)->offset >= 0) {
return 0;
}
return (*dataObjLseekOut)->offset;
}
rodsLong_t _l3Lseek(rsComm_t* rsComm, int l3descInx, rodsLong_t offset, int whence)
{
fileLseekInp_t fileLseekInp{};
fileLseekInp.fileInx = l3descInx;
fileLseekInp.offset = offset;
fileLseekInp.whence = whence;
fileLseekOut_t* fileLseekOut = nullptr;
if (const auto ec = rsFileLseek(rsComm, &fileLseekInp, &fileLseekOut); ec < 0) {
return ec;
}
const auto off = fileLseekOut->offset;
std::free(fileLseekOut);
return off;
}
| 3,856 | 1,500 |
/*++
Copyright (C) Microsoft Corporation, 1991 - 1999
Module Name:
secclnt.hxx
Abstract:
This file contains an abstraction to the security support for clients
and that which is common to both servers and clients.
Author:
Michael Montague (mikemon) 10-Apr-1992
Revision History:
--*/
#ifndef __SECCLNT_HXX__
#define __SECCLNT_HXX__
typedef SecBufferDesc SECURITY_BUFFER_DESCRIPTOR;
typedef SecBuffer SECURITY_BUFFER;
#define MAXIMUM_SECURITY_BLOCK_SIZE 16
enum PACKAGE_LEG_COUNT
{
LegsUnknown,
ThreeLegs,
EvenNumberOfLegs
};
typedef struct
{
#ifdef UNICODE
SecPkgInfoW PackageInfo;
#else
SecPkgInfoA PackageInfo;
#endif
SECURITY_CREDENTIALS *ServerSecurityCredentials;
PACKAGE_LEG_COUNT LegCount;
} SECURITY_PACKAGE_INFO;
typedef struct
{
unsigned long Count;
SECURITY_PACKAGE_INFO * SecurityPackages;
PSecurityFunctionTable RpcSecurityInterface;
void * ProviderDll;
RPC_CHAR *ProviderDllName;
} SECURITY_PROVIDER_INFO;
extern SECURITY_PROVIDER_INFO PAPI * ProviderList;
extern unsigned long NumberOfProviders;
extern unsigned long LoadedProviders;
extern unsigned long AvailableProviders;
extern int SecuritySupportLoaded;
extern int FailedToLoad;
extern PSecurityFunctionTable RpcSecurityInterface;
extern SecPkgInfo PAPI * SecurityPackages;
extern unsigned long NumberOfSecurityPackages;
extern MUTEX * SecurityCritSect;
extern RPC_STATUS
InsureSecuritySupportLoaded (
);
extern RPC_STATUS
IsAuthenticationServiceSupported (
IN unsigned long AuthenticationService
);
extern RPC_STATUS
FindServerCredentials (
IN RPC_AUTH_KEY_RETRIEVAL_FN GetKeyFn,
IN void __RPC_FAR * Arg,
IN unsigned long AuthenticationService,
IN unsigned long AuthenticationLevel,
IN RPC_CHAR __RPC_FAR * Principal,
IN OUT SECURITY_CREDENTIALS ** SecurityCredentials
);
extern RPC_STATUS
RemoveCredentialsFromCache (
IN unsigned long AuthenticationService
);
extern PACKAGE_LEG_COUNT
GetPackageLegCount(
DWORD id
);
extern BOOL
ReadPackageLegInfo();
extern DWORD * FourLeggedPackages;
class SECURITY_CREDENTIALS
/*++
Class Description:
This class is an abstraction of the credential handle provided by
the Security APIs.
Fields:
PackageIndex - Contains the index for this package in the array of
packages pointed to by SecurityPackages.
Credentials - Contains the credential handle used by the security
package.
--*/
{
friend RPC_STATUS
FindServerCredentials (
IN RPC_AUTH_KEY_RETRIEVAL_FN GetKeyFn,
IN void __RPC_FAR * Arg,
IN unsigned long AuthenticationService,
IN unsigned long AuthenticationLevel,
IN RPC_CHAR __RPC_FAR * Principal,
IN OUT SECURITY_CREDENTIALS ** SecurityCredentials
);
public:
unsigned AuthenticationService;
private:
BOOL Valid;
unsigned int ProviderIndex;
unsigned int PackageIndex;
CredHandle CredentialsHandle;
unsigned int ReferenceCount;
MUTEX CredentialsMutex;
SEC_CHAR __SEC_FAR * DefaultPrincName;
public:
SECURITY_CREDENTIALS (
IN OUT RPC_STATUS PAPI * Status
);
~SECURITY_CREDENTIALS ();
RPC_STATUS
AcquireCredentialsForServer (
IN RPC_AUTH_KEY_RETRIEVAL_FN GetKeyFn,
IN void __RPC_FAR * Arg,
IN unsigned long AuthenticationService,
IN unsigned long AuthenticationLevel,
IN RPC_CHAR __RPC_FAR * Principal
);
RPC_STATUS
AcquireCredentialsForClient (
IN RPC_AUTH_IDENTITY_HANDLE AuthIdentity,
IN unsigned long AuthenticationService,
IN unsigned long AuthenticationLevel
);
RPC_STATUS
InquireDefaultPrincName (
OUT SEC_CHAR __SEC_FAR **MyDefaultPrincName
);
void
FreeCredentials (
);
unsigned int
MaximumTokenLength (
);
PCredHandle
InquireCredHandle (
);
void
ReferenceCredentials(
void
);
void
DereferenceCredentials(
void
);
PSecurityFunctionTable
InquireProviderFunctionTable (
);
int
CompareCredentials(
SECURITY_CREDENTIALS PAPI * Creds
);
};
inline
int
SECURITY_CREDENTIALS::CompareCredentials(
SECURITY_CREDENTIALS PAPI * Creds
)
{
CredHandle * Cookie = Creds->InquireCredHandle();
if ( (CredentialsHandle.dwLower == Cookie->dwLower)
&&(CredentialsHandle.dwUpper == Cookie->dwUpper) )
{
return 0;
}
return 1;
}
inline unsigned int
SECURITY_CREDENTIALS::MaximumTokenLength (
)
/*++
Return Value:
The maximum size, in bytes, of the tokens passed around at security
context initialization time.
--*/
{
return(ProviderList[ProviderIndex].SecurityPackages[PackageIndex].PackageInfo.cbMaxToken);
}
inline PSecurityFunctionTable
SECURITY_CREDENTIALS::InquireProviderFunctionTable(
)
/*++
Return Value:
--*/
{
return(ProviderList[ProviderIndex].RpcSecurityInterface);
}
inline PCredHandle
SECURITY_CREDENTIALS::InquireCredHandle (
)
/*++
Return Value:
The credential handle for this object will be returned.
--*/
{
return(&CredentialsHandle);
}
class SECURITY_CONTEXT : public CLIENT_AUTH_INFO
/*++
Class Description:
This is an abstraction of a security context. It allows you to use
it to generate signatures and then verify them, as well as, sealing
and unsealing messages.
Fields:
DontForgetToDelete - Contains a flag indicating whether or not there
is a valid security context which needs to be deleted. A value
of non-zero indicates there is a valid security context.
SecurityContext - Contains a handle to the security context maintained
by the security package on our behalf.
MaxHeaderLength - Contains the maximum size of a header for this
security context.
MaxSignatureLength - Contains the maximum size of a signature for
this security context.
--*/
{
public:
unsigned AuthContextId;
unsigned Flags;
unsigned long ContextAttributes;
PACKAGE_LEG_COUNT Legs;
SECURITY_CONTEXT (
CLIENT_AUTH_INFO *myAuthInfo,
unsigned myAuthContextId,
BOOL fUseDatagram,
RPC_STATUS __RPC_FAR * pStatus
);
inline ~SECURITY_CONTEXT (
void
)
{
DeleteSecurityContext();
}
RPC_STATUS
SetMaximumLengths (
);
unsigned int
MaximumHeaderLength (
);
unsigned int
MaximumSignatureLength (
);
unsigned int
BlockSize (
);
RPC_STATUS
CompleteSecurityToken (
IN OUT SECURITY_BUFFER_DESCRIPTOR PAPI * BufferDescriptor
);
RPC_STATUS
SignOrSeal (
IN unsigned long Sequence,
IN unsigned int SignNotSealFlag,
IN OUT SECURITY_BUFFER_DESCRIPTOR PAPI * BufferDescriptor
);
RPC_STATUS
VerifyOrUnseal (
IN unsigned long Sequence,
IN unsigned int VerifyNotUnsealFlag,
IN OUT SECURITY_BUFFER_DESCRIPTOR PAPI * BufferDescriptor
);
BOOL
FullyConstructed()
{
return fFullyConstructed;
}
// client-side calls
RPC_STATUS
InitializeFirstTime(
IN SECURITY_CREDENTIALS * Credentials,
IN RPC_CHAR * ServerPrincipal,
IN unsigned long AuthenticationLevel,
IN OUT SECURITY_BUFFER_DESCRIPTOR * BufferDescriptor,
IN OUT unsigned char *NewAuthType = NULL
);
RPC_STATUS
InitializeThirdLeg(
IN SECURITY_CREDENTIALS * Credentials,
IN unsigned long DataRep,
IN SECURITY_BUFFER_DESCRIPTOR * In,
IN OUT SECURITY_BUFFER_DESCRIPTOR * Out
);
RPC_STATUS
GetWireIdForSnego(
OUT unsigned char *WireId
);
RPC_STATUS
InqMarshalledTargetInfo (
OUT unsigned long *MarshalledTargetInfoLength,
OUT unsigned char **MarshalledTargetInfo
);
// server-side calls
void
DeletePac (
void PAPI * Pac
);
RPC_STATUS
AcceptFirstTime (
IN SECURITY_CREDENTIALS * Credentials,
IN SECURITY_BUFFER_DESCRIPTOR PAPI * InputBufferDescriptor,
IN OUT SECURITY_BUFFER_DESCRIPTOR PAPI * OutputBufferDescriptor,
IN unsigned long AuthenticationLevel,
IN unsigned long DataRepresentation,
IN unsigned long NewContextNeededFlag
);
RPC_STATUS
AcceptThirdLeg (
IN unsigned long DataRepresentation,
IN SECURITY_BUFFER_DESCRIPTOR PAPI * BufferDescriptor,
OUT SECURITY_BUFFER_DESCRIPTOR PAPI * OutBufferDescriptor
);
unsigned long
InquireAuthorizationService (
);
RPC_AUTHZ_HANDLE
InquirePrivileges (
);
RPC_STATUS
ImpersonateClient (
);
void
RevertToSelf (
);
RPC_STATUS
GetAccessToken (
OUT HANDLE *ImpersonationToken,
OUT BOOL *fNeedToCloseToken
);
inline AUTHZ_CLIENT_CONTEXT_HANDLE
GetAuthzContext (
void
)
{
return AuthzClientContext;
}
inline PAUTHZ_CLIENT_CONTEXT_HANDLE
GetAuthzContextAddress (
void
)
{
return &AuthzClientContext;
}
RPC_STATUS
GetDceInfo (
RPC_AUTHZ_HANDLE __RPC_FAR * PacHandle,
unsigned long __RPC_FAR * AuthzSvc
);
void
DeleteSecurityContext (
void
);
RPC_STATUS
CheckForFailedThirdLeg (
void
);
protected:
unsigned char fFullyConstructed;
unsigned char DontForgetToDelete;
unsigned char fDatagram;
CtxtHandle SecurityContext;
unsigned int MaxHeaderLength;
unsigned int MaxSignatureLength;
unsigned int cbBlockSize;
PSecurityFunctionTable RpcSecurityInterface;
int FailedContext;
ExtendedErrorInfo *FailedContextEEInfo;
AUTHZ_CLIENT_CONTEXT_HANDLE AuthzClientContext;
DWORD VerifyCertificate();
public:
CtxtHandle *
InqSecurityContext ()
{
return &SecurityContext;
}
};
typedef SECURITY_CONTEXT * PSECURITY_CONTEXT;
inline unsigned int
SECURITY_CONTEXT::MaximumHeaderLength (
)
/*++
Return Value:
The maximum size of the header used by SECURITY_CONTEXT::SealMessage
will be returned. This is in bytes.
--*/
{
return(MaxHeaderLength);
}
inline unsigned int
SECURITY_CONTEXT::BlockSize (
)
/*++
Return Value:
For best effect, buffers to be signed or sealed should be a multiple
of this length.
--*/
{
return(cbBlockSize);
}
inline unsigned int
SECURITY_CONTEXT::MaximumSignatureLength (
)
/*++
Return Value:
The maximum size, in bytes, of the signature used by
SECURITY_CONTEXT::MakeSignature will be returned.
--*/
{
return(MaxSignatureLength);
}
#endif // __SECCLNT_HXX__
| 11,439 | 3,822 |
/*
* Copyright (C) 2015 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* 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 "config.h"
#include "HTMLSlotElement.h"
#include "Event.h"
#include "EventNames.h"
#include "HTMLNames.h"
#include "MutationObserver.h"
#include "ShadowRoot.h"
#include "Text.h"
#include <wtf/IsoMallocInlines.h>
namespace WebCore {
WTF_MAKE_ISO_ALLOCATED_IMPL(HTMLSlotElement);
using namespace HTMLNames;
Ref<HTMLSlotElement> HTMLSlotElement::create(const QualifiedName& tagName, Document& document)
{
return adoptRef(*new HTMLSlotElement(tagName, document));
}
HTMLSlotElement::HTMLSlotElement(const QualifiedName& tagName, Document& document)
: HTMLElement(tagName, document)
{
ASSERT(hasTagName(slotTag));
}
HTMLSlotElement::InsertedIntoAncestorResult HTMLSlotElement::insertedIntoAncestor(InsertionType insertionType, ContainerNode& parentOfInsertedTree)
{
auto insertionResult = HTMLElement::insertedIntoAncestor(insertionType, parentOfInsertedTree);
ASSERT_UNUSED(insertionResult, insertionResult == InsertedIntoAncestorResult::Done);
if (insertionType.treeScopeChanged && isInShadowTree()) {
if (auto* shadowRoot = containingShadowRoot())
shadowRoot->addSlotElementByName(attributeWithoutSynchronization(nameAttr), *this);
}
return InsertedIntoAncestorResult::Done;
}
void HTMLSlotElement::removedFromAncestor(RemovalType removalType, ContainerNode& oldParentOfRemovedTree)
{
if (removalType.treeScopeChanged && oldParentOfRemovedTree.isInShadowTree()) {
auto* oldShadowRoot = oldParentOfRemovedTree.containingShadowRoot();
ASSERT(oldShadowRoot);
oldShadowRoot->removeSlotElementByName(attributeWithoutSynchronization(nameAttr), *this, oldParentOfRemovedTree);
}
HTMLElement::removedFromAncestor(removalType, oldParentOfRemovedTree);
}
void HTMLSlotElement::childrenChanged(const ChildChange& childChange)
{
HTMLElement::childrenChanged(childChange);
if (isInShadowTree()) {
if (auto* shadowRoot = containingShadowRoot())
shadowRoot->slotFallbackDidChange(*this);
}
}
void HTMLSlotElement::attributeChanged(const QualifiedName& name, const AtomString& oldValue, const AtomString& newValue, AttributeModificationReason reason)
{
HTMLElement::attributeChanged(name, oldValue, newValue, reason);
if (isInShadowTree() && name == nameAttr) {
if (auto shadowRoot = makeRefPtr(containingShadowRoot()))
shadowRoot->renameSlotElement(*this, oldValue, newValue);
}
}
const Vector<Node*>* HTMLSlotElement::assignedNodes() const
{
auto shadowRoot = makeRefPtr(containingShadowRoot());
if (!shadowRoot)
return nullptr;
return shadowRoot->assignedNodesForSlot(*this);
}
static void flattenAssignedNodes(Vector<Ref<Node>>& nodes, const HTMLSlotElement& slot)
{
if (!slot.containingShadowRoot())
return;
auto* assignedNodes = slot.assignedNodes();
if (!assignedNodes) {
for (RefPtr<Node> child = slot.firstChild(); child; child = child->nextSibling()) {
if (is<HTMLSlotElement>(*child))
flattenAssignedNodes(nodes, downcast<HTMLSlotElement>(*child));
else if (is<Text>(*child) || is<Element>(*child))
nodes.append(*child);
}
return;
}
for (const RefPtr<Node>& node : *assignedNodes) {
if (is<HTMLSlotElement>(*node) && downcast<HTMLSlotElement>(*node).containingShadowRoot())
flattenAssignedNodes(nodes, downcast<HTMLSlotElement>(*node));
else
nodes.append(*node);
}
}
Vector<Ref<Node>> HTMLSlotElement::assignedNodes(const AssignedNodesOptions& options) const
{
if (options.flatten) {
if (!isInShadowTree())
return { };
Vector<Ref<Node>> nodes;
flattenAssignedNodes(nodes, *this);
return nodes;
}
auto* assignedNodes = this->assignedNodes();
if (!assignedNodes)
return { };
return assignedNodes->map([] (Node* node) { return makeRef(*node); });
}
Vector<Ref<Element>> HTMLSlotElement::assignedElements(const AssignedNodesOptions& options) const
{
auto nodes = assignedNodes(options);
Vector<Ref<Element>> elements;
elements.reserveCapacity(nodes.size());
for (auto& node : nodes) {
if (is<Element>(node))
elements.uncheckedAppend(static_reference_cast<Element>(WTFMove(node)));
}
return elements;
}
void HTMLSlotElement::enqueueSlotChangeEvent()
{
// https://dom.spec.whatwg.org/#signal-a-slot-change
if (m_inSignalSlotList)
return;
m_inSignalSlotList = true;
MutationObserver::enqueueSlotChangeEvent(*this);
}
void HTMLSlotElement::dispatchSlotChangeEvent()
{
m_inSignalSlotList = false;
Ref<Event> event = Event::create(eventNames().slotchangeEvent, Event::CanBubble::Yes, Event::IsCancelable::No);
event->setTarget(this);
dispatchEvent(event);
}
}
| 6,192 | 2,006 |
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "lite/kernels/arm/concat_compute.h"
#include <string>
#include <vector>
#include "lite/backends/arm/math/funcs.h"
#include "lite/core/op_registry.h"
#include "lite/core/tensor.h"
#include "lite/core/type_system.h"
namespace paddle {
namespace lite {
namespace kernels {
namespace arm {
std::vector<size_t> stride_numel(const DDim& ddim) {
std::vector<size_t> strides(ddim.size());
strides[ddim.size() - 1] = ddim[ddim.size() - 1];
for (int i = ddim.size() - 2; i >= 0; --i) {
strides[i] = strides[i + 1] * ddim[i];
}
return strides;
}
template <typename T>
void ConcatFunc(const std::vector<lite::Tensor*> inputs,
int axis,
lite::Tensor* out) {
// Sometimes direct copies will be faster, this maybe need deeply analysis.
if (axis == 0 && inputs.size() < 10) {
size_t output_offset = 0;
for (auto* in : inputs) {
auto in_stride = stride_numel(in->dims());
auto out_stride = stride_numel(out->dims());
void* dst = out->mutable_data<T>() + output_offset;
const void* src = in->data<T>();
// src and dst tensor should have the same dims size.
CHECK(in_stride.size() == out_stride.size());
std::memcpy(dst, src, sizeof(T) * in_stride[0]);
output_offset += in_stride[0];
}
} else {
std::vector<lite::Tensor*> inputs_concat(inputs.size());
for (int j = 0; j < inputs.size(); ++j) {
inputs_concat[j] = inputs[j];
}
lite::arm::math::concat_func<T>(inputs_concat, axis, out);
}
}
void ConcatCompute::Run() {
auto& param = Param<operators::ConcatParam>();
std::vector<lite::Tensor*> inputs = param.x;
CHECK_GE(inputs.size(), 1);
auto* out = param.output;
int axis = param.axis;
auto* axis_tensor = param.axis_tensor;
if (axis_tensor != nullptr) {
auto* axis_tensor_data = axis_tensor->data<int>();
axis = axis_tensor_data[0];
}
switch (inputs.front()->precision()) {
case PRECISION(kFloat):
ConcatFunc<float>(inputs, axis, out);
break;
case PRECISION(kInt32):
ConcatFunc<int32_t>(inputs, axis, out);
break;
case PRECISION(kInt64):
ConcatFunc<int64_t>(inputs, axis, out);
break;
default:
LOG(FATAL) << "Concat does not implement for the "
<< "input type:"
<< static_cast<int>(inputs.front()->precision());
}
}
} // namespace arm
} // namespace kernels
} // namespace lite
} // namespace paddle
REGISTER_LITE_KERNEL(
concat, kARM, kAny, kNCHW, paddle::lite::kernels::arm::ConcatCompute, def)
.BindInput("X", {LiteType::GetTensorTy(TARGET(kARM), PRECISION(kAny))})
.BindInput("AxisTensor",
{LiteType::GetTensorTy(TARGET(kARM), PRECISION(kInt32))})
.BindOutput("Out", {LiteType::GetTensorTy(TARGET(kARM), PRECISION(kAny))})
.Finalize();
| 3,457 | 1,263 |
// Font generated by stb_font_inl_generator.c (4/1 bpp)
//
// Following instructions show how to use the only included font, whatever it is, in
// a generic way so you can replace it with any other font by changing the include.
// To use multiple fonts, replace STB_SOMEFONT_* below with STB_FONT_consolas_bold_35_usascii_*,
// and separately install each font. Note that the CREATE function call has a
// totally different name; it's just 'stb_font_consolas_bold_35_usascii'.
//
/* // Example usage:
static stb_fontchar fontdata[STB_SOMEFONT_NUM_CHARS];
static void init(void)
{
// optionally replace both STB_SOMEFONT_BITMAP_HEIGHT with STB_SOMEFONT_BITMAP_HEIGHT_POW2
static unsigned char fontpixels[STB_SOMEFONT_BITMAP_HEIGHT][STB_SOMEFONT_BITMAP_WIDTH];
STB_SOMEFONT_CREATE(fontdata, fontpixels, STB_SOMEFONT_BITMAP_HEIGHT);
... create texture ...
// for best results rendering 1:1 pixels texels, use nearest-neighbor sampling
// if allowed to scale up, use bilerp
}
// This function positions characters on integer coordinates, and assumes 1:1 texels to pixels
// Appropriate if nearest-neighbor sampling is used
static void draw_string_integer(int x, int y, char *str) // draw with top-left point x,y
{
... use texture ...
... turn on alpha blending and gamma-correct alpha blending ...
glBegin(GL_QUADS);
while (*str) {
int char_codepoint = *str++;
stb_fontchar *cd = &fontdata[char_codepoint - STB_SOMEFONT_FIRST_CHAR];
glTexCoord2f(cd->s0, cd->t0); glVertex2i(x + cd->x0, y + cd->y0);
glTexCoord2f(cd->s1, cd->t0); glVertex2i(x + cd->x1, y + cd->y0);
glTexCoord2f(cd->s1, cd->t1); glVertex2i(x + cd->x1, y + cd->y1);
glTexCoord2f(cd->s0, cd->t1); glVertex2i(x + cd->x0, y + cd->y1);
// if bilerping, in D3D9 you'll need a half-pixel offset here for 1:1 to behave correct
x += cd->advance_int;
}
glEnd();
}
// This function positions characters on float coordinates, and doesn't require 1:1 texels to pixels
// Appropriate if bilinear filtering is used
static void draw_string_float(float x, float y, char *str) // draw with top-left point x,y
{
... use texture ...
... turn on alpha blending and gamma-correct alpha blending ...
glBegin(GL_QUADS);
while (*str) {
int char_codepoint = *str++;
stb_fontchar *cd = &fontdata[char_codepoint - STB_SOMEFONT_FIRST_CHAR];
glTexCoord2f(cd->s0f, cd->t0f); glVertex2f(x + cd->x0f, y + cd->y0f);
glTexCoord2f(cd->s1f, cd->t0f); glVertex2f(x + cd->x1f, y + cd->y0f);
glTexCoord2f(cd->s1f, cd->t1f); glVertex2f(x + cd->x1f, y + cd->y1f);
glTexCoord2f(cd->s0f, cd->t1f); glVertex2f(x + cd->x0f, y + cd->y1f);
// if bilerping, in D3D9 you'll need a half-pixel offset here for 1:1 to behave correct
x += cd->advance;
}
glEnd();
}
*/
#ifndef STB_FONTCHAR__TYPEDEF
#define STB_FONTCHAR__TYPEDEF
typedef struct
{
// coordinates if using integer positioning
float s0,t0,s1,t1;
signed short x0,y0,x1,y1;
int advance_int;
// coordinates if using floating positioning
float s0f,t0f,s1f,t1f;
float x0f,y0f,x1f,y1f;
float advance;
} stb_fontchar;
#endif
#define STB_FONT_consolas_bold_35_usascii_BITMAP_WIDTH 256
#define STB_FONT_consolas_bold_35_usascii_BITMAP_HEIGHT 160
#define STB_FONT_consolas_bold_35_usascii_BITMAP_HEIGHT_POW2 256
#define STB_FONT_consolas_bold_35_usascii_FIRST_CHAR 32
#define STB_FONT_consolas_bold_35_usascii_NUM_CHARS 95
#define STB_FONT_consolas_bold_35_usascii_LINE_SPACING 23
static unsigned int stb__consolas_bold_35_usascii_pixels[]={
0x0309fff3,0x00022000,0x300037ae,0x30000375,0x3ee7fdb9,0x3fffffff,
0xfffffffb,0x337be63f,0x3ba00002,0x99730005,0x10000035,0x0cccc333,
0x55553000,0x0aaaa600,0x884ccc00,0x88000999,0xfff99999,0x00017e44,
0xc8003ba2,0xb800ffff,0x05ffffff,0xfffff900,0x3ffffee7,0xfffb3fff,
0x263fffff,0x00dfffff,0x037fc400,0x3ffffee0,0x00001fff,0x7ecffff1,
0xf30002ff,0xfd005fff,0xf30009ff,0x3fff2dff,0xfffc8003,0x324fff9e,
0x10002fff,0x2001dffd,0x202fffff,0xffffffe8,0x7e4005ff,0xf73fffff,
0x7fffffff,0x3ffffff6,0xffff31ff,0xa8000dff,0xfb1005ff,0xffffffff,
0xf700007f,0x7ffcc7ff,0x3ffa0005,0x7ffcc05f,0xff98000f,0x07fff96f,
0x3dfff900,0x7fe49fff,0x744002ff,0x3a006fff,0xf102ffff,0xfd99dfff,
0x3e600dff,0x309adfff,0xfff95555,0x2abfff67,0x32a60aaa,0x0003ffff,
0x2009ff91,0xfffffffe,0x003fffff,0x207fffc0,0x0001fffe,0x401ffff7,
0x0005fffc,0x3f2dfff3,0xfb8003ff,0x4fff9dff,0x00ffffe4,0x01dfffb0,
0x037ffdc0,0xf707fffb,0xff9005ff,0x7fd4009f,0x00fffb3f,0x006fffa8,
0x3fffff6a,0xff504eff,0xf7315bff,0x4000ffff,0xfa84fffa,0xf10004ff,
0x7fc07fff,0xf30002ff,0x3fff2dff,0xfffb8003,0xd84fff9d,0xf7006fff,
0x30001dff,0x7ffdc079,0x017ff602,0x8003fff6,0xffb3fffa,0xfffd000f,
0xffffd300,0x0fffffff,0x5417fffa,0x0003ffff,0x3e03fffd,0x90000fff,
0x3ea0dfff,0x260007ff,0xfff96fff,0xfff50007,0x209fff39,0x4c04fffe,
0x0001ffff,0x09fff100,0x400fff98,0x54007ffe,0xfffb3fff,0x1fffb000,
0x7ffffc40,0x7fffffff,0x407fffb8,0x8006fffd,0x3206fff9,0x30003fff,
0xfb01ffff,0x4c0009ff,0xfff96fff,0xfff50007,0x209fff39,0x201ffffa,
0x5104fffe,0x55555555,0xfff70555,0x07fff001,0x4006fff8,0xffb3fffa,
0xfff9000f,0x7ffff401,0xdbafffbd,0x04fffd86,0x007fffd4,0x80bfff20,
0x0006fff8,0xf10ffffa,0x31003fff,0xfff99995,0x98ffff2d,0xf980abcb,
0x4fff9bff,0x417fff60,0x2a06fffa,0xffffffff,0x7fc0ffff,0x9110c43f,
0xfff809ff,0x7ffd4006,0x000fffb3,0x2201fff9,0xff33ffff,0x5fffd00b,
0x1ffff880,0x1fffe200,0x00bfff60,0x237ffdc0,0xa806fffa,0xffffffff,
0x7fff96ff,0xdfffffd1,0x9bfff981,0x3e204fff,0xffd80fff,0x3ffea02f,
0xffffffff,0x43ffea0f,0xcfefffe9,0x7fc05ffb,0x7fd4006f,0x00fffb3f,
0x201fff90,0xf50ffffa,0xffff009f,0x5ffff003,0x1fffdc00,0x02fffcc0,
0x1ffff880,0x880ffff6,0xfffffffd,0xff96ffff,0xfffffd9f,0x55443fff,
0x04fff98a,0x221fffec,0x75407fff,0xfeeeeeee,0x3ff20fff,0xffffff35,
0x80dff57f,0x54006fff,0xfffb3fff,0x3fff7000,0x4bfffe60,0x7c403ffb,
0xff800fff,0x3fa003ff,0xffd000ff,0x3f60001f,0xffff14ff,0x7fffec01,
0xffffdcdf,0xffffff96,0xbfffffdf,0x04fff980,0x2e37ffd4,0x40004fff,
0x3a0ffff8,0xffffd3ff,0xfff57fff,0x02fffc40,0x6cfffea0,0xfb8007ff,
0xfff104ff,0x05ffb9ff,0x00ffff98,0x004fffe8,0x400bfff5,0x0004fffb,
0x3eeffff3,0x3fea04ff,0xfff984ff,0xbfffff96,0x07fffec3,0x809fff30,
0x360ffff8,0x40002fff,0xf10ffff8,0x7fff53ff,0xff35fff1,0x1fffe40f,
0x4fffea00,0x98007ffd,0xfb00efff,0x3fffffff,0x0ffffa80,0x03fffe80,
0x003fffb0,0x000ffff8,0xfd5fffd0,0x7ffc03ff,0xdfff305f,0x41bffff2,
0x2603ffff,0xfd804fff,0x3fffa1ff,0x7fc40000,0x1fff50ff,0x3fe6dff9,
0x227ff99f,0x0ffffdba,0x9fffd400,0xb0007ffd,0x437bffff,0xffffffe8,
0xff301cff,0xfff003ff,0xfff3005f,0xfff9000d,0x3fee0007,0x206fffef,
0x301ffff9,0x3ff2dfff,0xfffb00ef,0x27ffcc0b,0xf17ffe40,0x10000fff,
0x3ee1ffff,0x2a9ffd6f,0x7ff98fff,0x3bffffea,0xfffa8001,0x000fffb3,
0x27ffff54,0x3fffff62,0x440dffff,0xf801ffff,0xfc801fff,0xf88002ff,
0xf10006ff,0x07ffffff,0x303fffd4,0x3ff2dfff,0x3ffee03f,0x13ffe606,
0x44ffff20,0x80006fff,0xf90ffff8,0x54fffebf,0x4dff57ff,0x00dffffa,
0x27fff500,0x20007ffd,0x04ffffda,0xffffffb5,0xfff81dff,0x7ffc403f,
0x7ffc400f,0x3ff60007,0xffb0001f,0x5c01ffff,0x3e606fff,0x7fff96ff,
0x03fffdc0,0x7009fff3,0x3fe69fff,0xf880005f,0x9ff90fff,0x3ee5fff1,
0x54dff57f,0x04fffffe,0xb3fffa80,0x2e000fff,0x03efffff,0x7fffffdc,
0x7fff46ff,0x3fffdc05,0x027ffdc0,0x0bfff500,0x3fffea00,0x7ffe404f,
0x5bffe605,0x2a03fffc,0x3e606fff,0xffb804ff,0x0dfff34f,0xffff1000,
0x3e33ff61,0x2dff92ff,0xeb885ffb,0x54002fff,0xfffb3fff,0xffff1000,
0x67fe4003,0x21fffffc,0x200ffffb,0xe803fffe,0x40000fff,0x0000fffe,
0x801ffffd,0x2605fffc,0xfff96fff,0x2fffdc07,0x009fff30,0x3e27fff7,
0x880007ff,0xffb0ffff,0x323fff17,0x09ff95ff,0x0027ffdc,0x7ecfffea,
0xffa8007f,0x7fec003f,0x47ffff51,0x80effff8,0x400ffffd,0x0005fffa,
0x004fffb8,0x00bffff0,0x540dfff7,0xfff96fff,0x27ffec07,0x009fff30,
0x7fc5fff9,0xf880007f,0x7ffb0fff,0x3fa5fff1,0x405ffd5f,0x4005fff8,
0xffb3fffa,0xfff7000f,0x0ffe8003,0xfb0ffffe,0xd97bdfff,0xb009ffff,
0x00003fff,0x000ffff1,0x003ffff7,0x101ffff5,0x3f2dfffd,0xfff103ff,
0x7ffcc05f,0x1fffd804,0x0007fffe,0x21ffff10,0x7fff4ffd,0xff3bfff7,
0x0dfff00f,0xb3fffa80,0xf9000fff,0xff8001ff,0x217fffc7,0xffffffe8,
0x805fffff,0x0006fff8,0x00bfff20,0x04ffffa8,0x07ffff10,0x32dffffd,
0xffb03fff,0x7fcc01ff,0x7ffc404f,0x0ffff60f,0xffff1000,0x7f57ff21,
0xffffffff,0xfff805ff,0x7ffd4006,0x000fffb3,0x2a01fff9,0x45bfe21b,
0x880ffffd,0xfffffffe,0xff9005ff,0x4c00007f,0x2aa06fff,0x06ffffda,
0x5ffffec0,0xffffffb9,0x41bfff96,0x03ffffd9,0x2027ffcc,0x7dc5fffa,
0x440006ff,0xff70ffff,0x3bfffeed,0x00effffd,0x4006fff8,0xffb3fffa,
0xfff9000f,0x3bffee01,0xfffdeffd,0x7f5404ff,0x002dffff,0x001ffff1,
0x1fffd800,0xfffffff0,0xff98001f,0xffffffff,0xfff96ffe,0xffffffff,
0xfff300bf,0x2fffd809,0x00ffffc4,0x1ffff100,0xffc9ffea,0x0dffe88e,
0x00dfff00,0xfb3fffa8,0xff9000ff,0x3ffee01f,0xffffffff,0x3ee005ff,
0x7dc004ff,0x800004ff,0xff05fffa,0x001bffff,0x3ffffee0,0x6ffd9fff,
0xfffffff9,0x0019ffff,0x4409fff3,0xffb06fff,0x7c40009f,0x3ffe67ff,
0x00020221,0x5001bffe,0x3ff67fff,0xfffc8007,0xfffff700,0x7fffffff,
0x6fff9800,0x3fffa010,0xfd000000,0xdfff01ff,0xd500005b,0x361bffff,
0xffb736ff,0x03bfffff,0x027ffcc0,0x2a07fffb,0x0001ffff,0xff8ffff5,
0xd000004f,0xfa800fff,0x0fffb3ff,0x01fffb00,0x3ffb2ea2,0x0002cdff,
0x13dffff1,0xfff30d93,0x5c00000b,0x09883fff,0x35100000,0x33310001,
0x3fe60001,0xdfff504f,0x37ffec01,0x5fffd800,0x0007ffe4,0x07ffec00,
0x27fff500,0xe8007ffd,0x7f4007ff,0xf900000f,0xffffffff,0x02fffd89,
0x3fe20000,0x0000007f,0x00000000,0x213ffe60,0x401ffff8,0x183ffff8,
0x13fffe20,0x300dfff3,0x5fffb800,0x4fffea00,0x5c007ffd,0x7c006fff,
0x7400007f,0xffffffff,0x0dfff10f,0xff900000,0x4ccccc5f,0x99999999,
0x10999999,0x11111111,0x00000011,0x444fff98,0x5004fffe,0xef85ffff,
0xffeb99ab,0xfffe80ff,0x0375c41d,0x3bfffe20,0x555531ac,0x3f67fff9,
0x0aaaaaff,0xffffb751,0x37fc4005,0x3ee20000,0x20dfffff,0x0002ccc9,
0x3ccc8800,0x3ffffffe,0xffffffff,0xff91ffff,0xdfffffff,0x98000000,
0x7ff44fff,0x7fe4006f,0x3fffe2ff,0x2fffffff,0xfffffd10,0x00dffffd,
0xffffff70,0x3ffffee7,0xfffb3fff,0x263fffff,0x06ffffff,0x002ffd40,
0x9aa98800,0x00000000,0xfffff800,0xffffffff,0x91ffffff,0xffffffff,
0x000000df,0x364fff98,0x8000efff,0xff1ffffd,0xffffffff,0xfffe8807,
0x05ffffff,0xfffff700,0x3ffffee7,0xfffb3fff,0x263fffff,0x00cfffff,
0x0004cc40,0x00000000,0x3e000000,0xffffffff,0xffffffff,0xffff91ff,
0x00dfffff,0xff980000,0x03bfea4f,0x24ffd800,0xefffffdb,0x3b2e000c,
0x001cefff,0x976e5440,0xeeeeeeea,0xddddd92e,0x37a61ddd,0x000001bc,
0x00000000,0x00000000,0x77500000,0x77777777,0x98000000,0x07544fff,
0x2026c000,0x11000008,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x013ffe60,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x7fcc0000,0x0000004f,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x20000000,0x00000009,
0x00d54400,0x54c01998,0xaaaabccc,0x0cccc42a,0x200eed40,0x80009998,
0x99999999,0x26600001,0x5cc01aaa,0x00999882,0x65d4c000,0x533a89ac,
0xabdca855,0x016e6000,0xaccb9880,0xefff9801,0x64c000bc,0x4003defe,
0x01effffb,0x6c41bff2,0xffffffff,0x3f60ffff,0x7fd407ff,0x3ff200ff,
0xfff8003f,0x01ffffff,0x7fff5400,0xff907fff,0x5fffb8df,0xfff50000,
0xdfffffff,0x7f4dfff2,0x400effff,0x0007fff9,0xfffffff7,0x7ffcc03f,
0x800bffff,0xfffffffc,0xfffb801e,0xf980ffff,0xfff880ff,0xffffffff,
0x3ff60fff,0x7ffec07f,0x3fff203f,0xffff8003,0x001fffff,0x3fffff60,
0xff987fff,0x3fee3fff,0x6c40005f,0xffffffff,0xfff96fff,0xfffffff5,
0x7fd403ff,0x7ec4007f,0xffffffff,0xffff303f,0x403fffff,0xfffffffc,
0x7fc00eff,0x83ffeabf,0xffd03ffe,0xfff935bf,0x7ec199bf,0x7fec07ff,
0x3ff203ff,0xfff8003f,0x01ffffff,0xfffff700,0xf50fffdf,0x7dc9ffff,
0x6c0005ff,0xdcdfffff,0xff96ffff,0xffdfffff,0x7d40bfff,0x7f4007ff,
0xffffffff,0xee883fff,0xefffffff,0xbffff980,0x04ffffb9,0xffa9bfe6,
0x9837fdc5,0xff986fff,0xffff906f,0x0ffff980,0x00ffff20,0x0ffffc00,
0x7fffc400,0x7cc0c40d,0x3ee3ffff,0x2a0005ff,0xf984ffff,0xffff96ff,
0x7ffec3bf,0xffff500f,0x7fffdc00,0xfffc98ad,0xffd7007f,0xfff70bff,
0x05fffa87,0xff993fea,0x407ffe66,0xfd02fffa,0xfff901ff,0x0177300d,
0x003fffc8,0x03ffff00,0x1ffff300,0x6fffd800,0x002fffdc,0x20bfffd0,
0xff96fff9,0x3ffe0dff,0xf955553f,0x55555fff,0x7fffc435,0x7ffff504,
0x3fffa200,0x07ffec0f,0xf5037ffc,0xd2ffd4bf,0x7fdc07ff,0x3fff902f,
0x00dfff90,0x3fffc800,0xffff0000,0xfff50003,0x0f2a000b,0x0017ffee,
0x80ffffcc,0xff96fff9,0x3ff601df,0xffffff5f,0xffffffff,0x3fffdcbf,
0x01bfff60,0x41ffffa8,0x7cc1fffd,0x3fe605ff,0x2e9ff90f,0x7fd406ff,
0x0fffd04f,0x551bfff2,0x15555555,0x51fffe40,0x7c0059b9,0xc8001fff,
0x00004fff,0x105fffb8,0x7d455555,0x3fe607ff,0x07fff96f,0xffb7ffdc,
0xffffffff,0x365fffff,0x7d404fff,0xf1000fff,0xffb87fff,0x1fffec4f,
0x3fbfffa0,0x1fff88ff,0x0ffffc40,0x5c1bffee,0x7ffc5fff,0x01ffffff,
0x3a6bfff2,0x00efffff,0x001ffff8,0x004fffc8,0x5fffb800,0x1ffffe88,
0x981bffee,0xfff96fff,0xbfffdc07,0xfffeeeed,0x4eeeeeef,0x100bfffa,
0x2003ffff,0x4c1ffff9,0xfd89ffff,0xff9806ff,0xffb3ffff,0x3fff2009,
0xffffecef,0x8bfff701,0xffffffff,0x3fff201f,0xfffffffc,0xffff806f,
0xfffc8001,0xfb800004,0xfffd85ff,0x2fffe42f,0x32dfff30,0x3ea03fff,
0xfff506ff,0x3fffe00f,0x2ffff801,0x1ffffb00,0xffdfffb0,0x22001dff,
0xff71deed,0x7ffd400d,0x3fffffff,0xb17ffee0,0xffffdddd,0x7fffe403,
0xffffffff,0x7fffc02f,0x77775c01,0xeeefffff,0x70002eee,0xffc8bfff,
0xfffc83ff,0x5bffe605,0x2e03fffc,0xff505fff,0xfff100ff,0xffff001f,
0xfd755307,0x3e209fff,0x0dffffff,0xfff88000,0xdfff1001,0x019fffff,
0x805fffa8,0x3201ffff,0x31dfffff,0xf809fffd,0x7e401fff,0xffffffff,
0x03ffffff,0x3fee02a2,0x3fffea5f,0x0dfff704,0xfcb7ffd4,0x3ff603ff,
0xffff504f,0x1ffff300,0x09fffd00,0xfffffffb,0x7ffec01d,0x200002ff,
0x32004ffd,0x000627ff,0xf009fff5,0x7e403fff,0xffc86fff,0x7fffc05f,
0x7fffe401,0xffffffff,0xff703fff,0x5fffb87f,0x409ffff3,0x880ffffa,
0xff96fffe,0x3ffe207f,0xffff502f,0x1ffff300,0x07fffd00,0xbffffffb,
0x3fffa201,0x66642fff,0x1bfea003,0x00fffd00,0x04fffa80,0x201ffff8,
0xa80efffc,0x7fc06fff,0x554c01ff,0xadfffdaa,0x880aaaaa,0x2e2fffff,
0xfff8dfff,0x7ffc405f,0xffffe83f,0x207fff96,0x500ffffd,0xf300ffff,
0xff003fff,0xfff905ff,0xffd8037d,0x10ffffff,0x2200bfff,0x6c001fff,
0x9aabefff,0xfffa8019,0x1ffff804,0x40ffff20,0x7c06fff9,0xc8001fff,
0x4c004fff,0x2e5fffff,0xfffedfff,0xffffb006,0xfffff737,0x37fff2df,
0x3ffff660,0x1fffea03,0x07fffe20,0x207fffe0,0xb801fffc,0xffe8efff,
0x4fff88ef,0x269ffb00,0xf703effe,0xffffffff,0x3e605dff,0xfff803ff,
0x3fff201f,0x0dfff303,0x001ffff8,0x004fffc8,0x3fffffc4,0xfffffff7,
0x3fe6001f,0xffffffff,0xfff96fff,0xffffffff,0xfffa80bf,0x7ffff007,
0x0ffff880,0x801fffb8,0xff11ffff,0x7fff5bff,0x51fff500,0x09ffffff,
0x3ffffff2,0x85ffffff,0xf803fff9,0x3f201fff,0xfff303ff,0x1ffff80d,
0x4fffc800,0xffffa800,0x3fbffee7,0x2e005fff,0xffffffff,0xff96fffa,
0xffffffff,0xffa8019f,0xfffd007f,0x7fffb80b,0x801fff70,0x7d46fff9,
0x2fffefff,0x457ffc40,0xfffddfff,0x77fff4c1,0xfffffeee,0x1fffcc3f,
0x00ffffc0,0x2607fff9,0x7fc06fff,0xfc8001ff,0xf90004ff,0x7ffdcdff,
0x03ffffad,0x3ffffaa0,0x96fff88d,0xffffffff,0x3e6003bf,0xfb800fff,
0x3fa00fff,0x500004ff,0xff70bfff,0xb00dffff,0x97feabff,0x3fa23ffd,
0xffd302ff,0xff0000df,0x7fe403ff,0xdfff303f,0x01ffff80,0x04fffc80,
0x49fff500,0xff95fffb,0xa88005ff,0x5bffe609,0x999bfffc,0xfff88000,
0xfff8802f,0xfffd80ef,0xf500000f,0x3ff60dff,0x7d403fff,0x47ff70ff,
0x3fee4ffb,0x7ffd405f,0xfff80007,0x3fff201f,0x0dfff303,0x001ffff8,
0x004fffc8,0x5c5fff90,0x3ffa5fff,0x980000ff,0xfff96fff,0x3fe00007,
0x0660aeff,0x79dffff9,0x07ffffd9,0x2006ff54,0xd01ffff8,0x4403ffff,
0x3ff22fff,0xfc93fea3,0x7fdc05ff,0x06f6445f,0x00ffffc0,0x2607fff9,
0x7fc06fff,0xfc8001ff,0x5c4004ff,0x7fdc4fff,0x3fffe65f,0x7cc0000e,
0x7fff96ff,0x3ff60000,0x5fffffff,0x7fffff44,0x0effffff,0x0dffff10,
0x15fffff0,0x3fffff26,0x717ff206,0x1ffe4bff,0x207ffff7,0x6c3ffffa,
0x26626fff,0xaffff999,0x3ff21999,0xdfff303f,0x3e666662,0x1999afff,
0x04fffc80,0xffffee88,0x2fffdc0e,0x017fffee,0x2dfff300,0x0003fffc,
0xffffff10,0xfb10bfff,0xffffffff,0xffffa809,0x7ffd400f,0xffffffff,
0xf984ffff,0x7ffcc0ff,0x220fffbc,0xeeffffff,0x84fffffe,0xf71fffff,
0xffffffff,0x323fffff,0xff303fff,0x3fffeedf,0xffffffff,0x7fe401ff,
0xfff8804f,0xfff703ff,0x7ffffb0b,0x7ffcc000,0x007fff96,0x7ffe4400,
0x2e04ffff,0x2efffffe,0x7ffff980,0xfffff900,0xffbfffff,0x2ffe87ff,
0xffffffb0,0xfffff309,0x9fffffff,0x43ffffa0,0xfffffffb,0x1fffffff,
0x2607fff9,0xfff76fff,0xffffffff,0xfc803fff,0xdf8804ff,0x3fee00bc,
0xfffe885f,0xff30002f,0x0ffff2df,0x54cc0000,0x0d4c001a,0x17ffe400,
0xffffb300,0x3ff219ff,0x0bff92ff,0x03ffffc8,0x3ffff6a2,0x2a00beff,
0x3fee3fff,0xffffffff,0xff91ffff,0x3ffe607f,0xffffff76,0xffffffff,
0x4fffc803,0xffb80000,0xffff305f,0xdd30003f,0x0bbbaebd,0x00000000,
0x054c0000,0x01553000,0x03300000,0x20006200,0x000000a8,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x10000000,
0x35999975,0x3732a601,0x55400abc,0xaaaaaaaa,0x310002aa,0x95300555,
0x00015799,0x2b332ea2,0x00d554c1,0xaa86aaa2,0xaaaaaaaa,0x953000aa,
0x4c003799,0x4c01accb,0x53002aaa,0x55554555,0x55551002,0x002aaa21,
0x5551aaa8,0x55555555,0xffc88155,0x5fffffff,0xfffffff8,0xff00cfff,
0xffffffff,0x32200fff,0x07ffffff,0x3fffff66,0x7000cfff,0xffffffff,
0x3ffee7ff,0x2fffdc05,0xfffffffd,0x4c07ffff,0xfffffffe,0x3fee00ff,
0x00efffff,0x003ffff5,0x7ec9fffd,0xff7007ff,0x0fffd4ff,0x3a9ffd00,
0xffffffff,0x3ea2ffff,0xffffffff,0xffff85ff,0x6fffffff,0xfffffff0,
0x80ffffff,0xffffffd8,0xfff307ff,0xffffffff,0xfffe880b,0xffffffff,
0x80bfff74,0x3fa5fffb,0xffffffff,0xfff703ff,0xffffffff,0x3ffff201,
0x02ffffff,0xa80bfffd,0x3ee0ffff,0xfd801fff,0x3ffea5ff,0x53ffe002,
0xfffffffe,0xf12fffff,0xffffffff,0xfff0bfff,0xfffffddf,0xfffff09f,
0xffffffff,0x7ffff440,0x887fffff,0xdcdfffff,0x503fffff,0xffffffff,
0x2e9fffff,0x7dc05fff,0x3fffa5ff,0xffffffff,0xfffffd83,0x0fffffff,
0xdfffffd8,0x81ffffff,0x200ffffa,0x7c44fffe,0xff804fff,0x3ffe62ff,
0x4fffe002,0xfffffffe,0xf92fffff,0x73019fff,0xa8815909,0xff87ffff,
0xccccccff,0xfff104cc,0x33357dff,0x0dfff703,0x741bfff2,0x89beffff,
0xf74fda98,0xffb80bff,0x2666625f,0x3fffe999,0x67ffffd4,0x0fdb988a,
0x21ffffcc,0xd05ffffa,0x3ea09fff,0xffe80fff,0x7ffd406f,0x0bffe60f,
0xfd3fff80,0x333337ff,0x3ffa1333,0x7000004f,0xff81ffff,0x3f20007f,
0x64002fff,0xff103fff,0xffff70ff,0x7fdc200b,0x7ffdc05f,0x3fffa005,
0x17ffff43,0x3fff6020,0x1ffff704,0x01ffff50,0x2e09fffd,0x3200ffff,
0x7fc45fff,0x3ffe003f,0x005fffd3,0x001ffffc,0xffff8800,0x003fffc0,
0x02ffff88,0x02fffd80,0xf88dfff1,0xb8005fff,0x7dc05fff,0x3fa005ff,
0x3ffee3ff,0xff98002f,0x3ff600ff,0x9fffd04f,0x00ffffa8,0x405ffff3,
0x7c43fffe,0xff1003ff,0x0bfffa5f,0x0effff80,0xff980000,0x07fff85f,
0x0bfff700,0x3bfff200,0x44fffb80,0x001ffffb,0x405fffb8,0x2005fffb,
0x3fa3fffe,0xf70006ff,0x7f4c0bff,0xfff506ff,0x27fff41f,0x413fffe0,
0xf80ffff8,0x066543ff,0x3fa5fff1,0x3f6002ff,0x0002efff,0x41fffec0,
0xb0007fff,0x20007fff,0x21effff9,0x640ffffa,0x70005fff,0xfb80bfff,
0x3fa005ff,0x3fffe3ff,0xfff90003,0x3fffee05,0x3fffa07f,0x01ffff53,
0x707fffc8,0x3fe0dfff,0x117ff43f,0x3ffa3fff,0x3fee002f,0x00bfffff,
0x3ae66660,0xff80dfff,0x1cceeeff,0x557fffc0,0x00bceeec,0x37fffff2,
0xe82ffffd,0x70004fff,0xfb80bfff,0x3fa005ff,0xffff33ff,0x3ff60003,
0x7ffec42f,0x3ea07fff,0x7fffb7ff,0x3ffff500,0x209fffb0,0x3fe64fff,
0x47ffe25f,0x4002fffe,0xfffffffd,0xfff801df,0x203fffff,0xffffffff,
0xff883eff,0xffffffff,0x3f203fff,0xffffffff,0x87ffff02,0xfffffff9,
0x80bfff74,0x2005fffb,0xff53fffe,0x3a0001ff,0x3fea1fff,0x0fffffff,
0x3f3fffa0,0xff000fff,0xffff07ff,0xb93ffa03,0x3fe67fff,0x9bfffd0f,
0x07999999,0xfffffff9,0x7fc01bff,0x2cffffff,0xfffffff0,0x987fffff,
0xffffffff,0x03ffffff,0x3fffffee,0xfff880df,0x7fffcc2f,0xfff74fff,
0x5fffb80b,0x4ffffa00,0x0007fffb,0x7e43fffe,0xffe8efff,0x3ffea01f,
0x2003ffff,0x7cc5fffd,0x3ffa07ff,0x47ffffa4,0xffd0fff9,0xffffffff,
0x3ff660df,0x0effffff,0xfffffff0,0x9990bfff,0xffffb999,0x7ffcc5ff,
0xfeccdfff,0xfa80ffff,0xffffffff,0x7fffc41f,0x7ffffcc2,0xbfff74ff,
0x05fffb80,0x5cffffa0,0x0000ffff,0xffd5ffff,0x7fffc9ff,0x7ffff401,
0x3ea000ff,0x3ff20fff,0x53ff604f,0x34fffff8,0x7fff4fff,0xffffffff,
0x7ff5c406,0x9804ffff,0x4ffffeb9,0x3ffee200,0x3fffe64f,0x7ffff703,
0xbdffffa8,0x41ffffff,0x6443ffff,0x74fffdcc,0xfb80bfff,0x3fa005ff,
0xffff53ff,0x3ffa0001,0x42ffffff,0x5c00ffff,0x003fffff,0xd17fffc4,
0x7ec05fff,0xffdff75f,0xfe9ffead,0xeeeeeeff,0x3aa005ee,0x000fffff,
0x007fffec,0x99bfff20,0x3600ffff,0x3fe65fff,0x3ff623ff,0x7fff46ff,
0xa7ffdc03,0x5c05fffb,0x3a005fff,0xfff33fff,0x3f60003f,0x40dfffff,
0xd007fff8,0x2000ffff,0xff14fffe,0x5ffd80ff,0x3fff5ffb,0x7ff4fff5,
0xd800002f,0x4001ffff,0x001ffff8,0x887fffd4,0x2e01ffff,0x3ff66fff,
0xffff904f,0x02fffec3,0x7dd3ffee,0x7fdc05ff,0x3ffa004f,0x7ffff13f,
0x3fff2000,0xfff303ff,0x3fff200d,0xfff70005,0x017ffead,0xdff1dff9,
0x3feafffa,0x00bfffa6,0x3ffea000,0xfff8002f,0x7fd4002f,0x17fffc7f,
0x7cdfff70,0x3fe00fff,0x3fff22ff,0x3ffee00f,0x80dfff54,0x2003fffc,
0x3fe2ffff,0xf90007ff,0x7e403fff,0xff9005ff,0x3e6000bf,0xfffd9fff,
0x577fe403,0x7dff94ff,0x7fff4dff,0xf9800002,0x4c000fff,0x4000ffff,
0x7f46fffc,0x3ff205ff,0x0ffff34f,0x262fffd8,0x2e04ffff,0xfff34fff,
0x2fffd80f,0x3ffff100,0x01ffffec,0x0ffffcc0,0x005ffff0,0x0017fff2,
0xffbfffe8,0x7fdc00ff,0xff31ffce,0x7f4bff9f,0x153002ff,0x0ffffb00,
0x7fffe880,0x7fffd400,0x0ffffdc4,0x897fffcc,0x3e03ffff,0x7fe41fff,
0xfff705ff,0x0ffffe29,0x707fffcc,0x07fffe40,0x09fffff1,0x3ff605c4,
0xdfff906f,0x2fffe400,0xdfff9000,0xf700dfff,0xff8fffff,0x3fa5ffef,
0xff5002ff,0xf955579d,0x5d49ffff,0xfca9999a,0x3263ffff,0xfda9999a,
0xff80efff,0xfb99bfff,0x3fa0efff,0x3661bfff,0xff887fff,0xbabdefff,
0x3f64fffe,0xb989cfff,0x7fc4ffff,0xfffd999c,0xffffc85f,0xfecbcdff,
0x7fffcc0f,0xfffc98ad,0x3ff2002f,0x3e60005f,0x03ffffff,0x4fffffa8,
0x2fffffe4,0x2005fffd,0xfffffffa,0x46ffffff,0xfffffffc,0x545fffff,
0xffffffff,0xf701ffff,0xffffffff,0xffa83fff,0xffffffff,0xff702fff,
0xffffffff,0x7fc49fff,0xffffffff,0x7ffc0eff,0xffffffff,0xffffe880,
0xffffffff,0xfffffd80,0x05ffffff,0x02fffe40,0x3ffffe00,0xffa801ff,
0x7fd42fff,0x3ffa4fff,0xfff5002f,0xffffffff,0xfffc81df,0xffffffff,
0xfffffa84,0x01dfffff,0x7fffffdc,0xf902ffff,0xffffffff,0xfe9807ff,
0xffffffff,0x7ffd44ff,0xefffffff,0xffffff81,0x5c02ffff,0xffffffff,
0xff900fff,0x7fffffff,0xbfff9000,0xfffd8000,0xff5007ff,0x3ffe0fff,
0x3fffa4ff,0xffdb3002,0x3bffffff,0x3fffff20,0x500befff,0xffffffff,
0x7ecc003b,0x00cfffff,0x7ffffecc,0x32000cff,0xfffffffe,0xffc880ad,
0x203fffff,0xffffffda,0xfd93000c,0x059fffff,0xfffffea8,0xff90002d,
0xfa8000bf,0x3004ffff,0x360bffff,0x3fa3ffff,0x988002ff,0x30009aa9,
0x00135533,0x001aa998,0x00135100,0x0026a660,0x066aa200,0x01353100,
0x00099980,0x00099880,0x00001530,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x88355300,0xaaa882aa,0x5554c01a,0x5555540a,0xaaaaaaaa,
0x555530aa,0x55555555,0x2aa25555,0x555402aa,0x80d55542,0x260aaaa9,
0x54001aaa,0x2aa01aaa,0x2aaaa2aa,0x00019aaa,0x01599751,0x20155544,
0x5531aaa9,0x00135555,0x55555555,0x26355555,0x09aaaaaa,0x4ffd8000,
0xff83ffd4,0x7ff406ff,0xffffe86f,0xffffffff,0xffff92ff,0xffffffff,
0x3feadfff,0x3fe00fff,0x3fffe25f,0x5ffffb06,0x0027ffe4,0x540ffff6,
0x3f64ffff,0xffffffff,0xffea802e,0x80cfffff,0x6406fffa,0xfffb4fff,
0x7dffffff,0x3fffffa0,0x4fffffff,0xfffffff7,0x00019dff,0xffb87ffd,
0x7ffff506,0x0bfffee0,0x3ffffffa,0xffffffff,0xffffff92,0xffffffff,
0x3fffeadf,0x97ffe04f,0x80fffff9,0x323fffff,0x6c004fff,0xff883fff,
0x7ffec6ff,0xffffffff,0xfffc880e,0xefffffff,0x037ffd40,0x7ed3fff2,
0xffffffff,0x7ff42fff,0xffffffff,0xffff74ff,0xffffffff,0x3ffe8007,
0xfd02ffe4,0x3ffa0fff,0xffffd06f,0xffffffff,0x3fff25ff,0xffffffff,
0xff56ffff,0x3e01ffff,0x3ffe65ff,0x7ffd43ff,0x3fff23ff,0x7ffec004,
0x1ffffd83,0x7fffffec,0x86ffffff,0xfffffffc,0x544fffff,0x7e406fff,
0xffffb4ff,0xffffffff,0x7ffff43f,0xffffffff,0xffffff74,0xdfffffff,
0x217ffc00,0x3ea04ffd,0x7fdc3fff,0x555501ff,0xff755555,0x26621fff,
0xefffc999,0xf5099999,0x207fffff,0x3fea5fff,0x7fe45fff,0x3ff23fff,
0x7fec004f,0x7fffd43f,0x9bfffd83,0xfffffdb9,0x567ff442,0xfffffa88,
0x01bffea0,0x3f69fff9,0xea999cff,0xfd0effff,0x333337ff,0x3fee1333,
0xfcba99df,0x8803ffff,0x7ff41fff,0x3fffec03,0x0017fffe,0x05ffffb0,
0x80bfff70,0x7ffffffa,0x7d4bfff0,0x3e0fffff,0x324fffff,0x6c004fff,
0x3fe23fff,0xfffb05ff,0x9ffff505,0x3ea03d30,0x3fea1fff,0x7ffe406f,
0x207fffb4,0xfd2ffffc,0x7dc005ff,0xfff504ff,0xfff501ff,0xffffffff,
0x307fffff,0x3ee7ffff,0x20001fff,0x005ffffa,0xa80bfff7,0x2fffffff,
0x3ea5fff8,0xf32ffeef,0x649ffbdf,0x6c004fff,0x3ff23fff,0xfffb00ff,
0x17fffa05,0x1ffffc00,0xc80dfff5,0xfffb4fff,0xa7fff407,0x2002fffe,
0x2a04fffb,0xfa84ffff,0xffffffff,0x3fffffff,0xf1ffff90,0x40009fff,
0x00fffff8,0x80bfff70,0xfffdfffa,0x2e5fff86,0x95ffcdff,0x4bffb7ff,
0x4004fffc,0xff53fffd,0x7fec05ff,0xbfff902f,0x3fffe000,0x01bffea3,
0x3f69fff9,0x3ff603ff,0x05fffd5f,0x027ffdc0,0x2a1bfffa,0xffffffff,
0xffffffff,0xdffff103,0x0001ffff,0x017fffe4,0x80bfff70,0xffebfffa,
0x72fffc2f,0x2fff3bff,0x5ffd9ffe,0x0013fff2,0xfd17fffb,0xffd80bff,
0x9fffd02f,0xffff1000,0x037ffd45,0x7ed3fff2,0x3ff603ff,0x05fffd5f,
0x027ffdc0,0x221fffee,0x99effc99,0x999fffa9,0x3ffff200,0x20004fff,
0x004ffffa,0x202fffdc,0xffabfffa,0x92fffc5f,0x2bffebff,0x4bff96ff,
0x4004fffc,0xffcbfffd,0x7fec00ef,0xffffc82f,0xfffb8001,0x3bffea0f,
0xdaaaaaaa,0xfffb4fff,0x9ffff407,0x999bfffe,0x3ee19999,0x7fd404ff,
0x2ffe407f,0x8801ffea,0x0fffffff,0xffff1000,0xffb8001d,0x7ffd405f,
0x7c3ffff3,0x57ff25ff,0x94ffeffd,0x7ffe4dff,0x7ffec004,0x801ffffd,
0xdccdfffd,0x003fffff,0x44fffe88,0xfffffffa,0xffffffff,0x207fffb4,
0xfd2ffffa,0xffffffff,0x3fee1fff,0x7ffcc04f,0x13ff601f,0xc800fff5,
0x004fffff,0x07ffff20,0x17ffee00,0x2e7fff50,0x3ffe5fff,0x7d57ff25,
0xff91ffff,0x027ffe4d,0x3fffff60,0xffb006ff,0xffffffff,0x3f60005d,
0x7fd40fff,0xffffffff,0xfb4fffff,0xfff507ff,0x7ffff4df,0xffffffff,
0x809fff70,0x201ffff9,0x7fdc3ffe,0x7fff4006,0xf50006ff,0x20009fff,
0x5405fffb,0xfff13fff,0xd97ffe1f,0xffff14ff,0xf93ffe4d,0xfd8009ff,
0x3ffffdff,0xfffffd80,0x0003ffff,0x20ffffee,0xfffffffa,0xffffffff,
0x99dfffb4,0x3fffffdb,0x7ffffff4,0x70ffffff,0xf9809fff,0x3fa01fff,
0x02ffe43f,0xffffff70,0xff88009f,0x2e0006ff,0x7d405fff,0x3fff23ff,
0x7ecbfff4,0x93fffa4f,0x3ff27ffb,0x7fec004f,0x0ffffdbf,0x777ffec0,
0x003fffff,0x04ffffb8,0x333dfff5,0xfff93333,0x3fffff69,0x3fffffff,
0x4cdffff4,0x2e199999,0x7d404fff,0x7ffcc7ff,0xffffffff,0x204fffff,
0xfffffff8,0x3f2000ff,0x20001fff,0x5405fffb,0x3fe23fff,0x25fff8ff,
0x3fee4ffe,0xc9ffee1f,0x6c004fff,0xfff8bfff,0x7ffec05f,0x3ffffb12,
0x7fffd400,0x1bffea05,0x369fff90,0xffffffff,0xffe80dff,0x3fee002f,
0x7ffdc04f,0x7ffffcc7,0xffffffff,0x3f204fff,0xffff9fff,0xffff5005,
0xffb80009,0x7ffd405f,0x7dfffec3,0x93ffa5ff,0x7fdc7ff9,0x09fff90f,
0x73fffd80,0x6c07ffff,0x3fa22fff,0xff5006ff,0xffa80bff,0x7ffe406f,
0xdddfffb4,0x7f40359b,0x3ee002ff,0x7fec04ff,0x7fffcc5f,0xffffffff,
0xf304ffff,0x3ff29fff,0x7f4401ff,0xb80006ff,0x7d405fff,0x7ffcc3ff,
0x3fa5fffe,0x2e0d543f,0xfff90fff,0xfffd8009,0x03ffffa3,0x2a17ffec,
0x5401ffff,0xa805ffff,0x7e406fff,0x7fffb4ff,0x5fffd000,0x27ffdc00,
0x07ffff30,0x33fff733,0x337fff33,0x3ffff601,0x0dffff10,0x01ffffc8,
0x5fffb800,0x41fffd40,0x5ffffffe,0x5400fffe,0xfff90fff,0xfffd8009,
0x1bfffe63,0x7417ffec,0x3ea05fff,0xf5004fff,0xffc80dff,0x07fffb4f,
0x05fffd00,0x027ffdc0,0x401ffffb,0x7fc46ffa,0x7ffd401f,0x7fffe43f,
0x7ffff503,0x3fee0000,0x7ffd405f,0xfffffa83,0x00fffe5f,0xfc8fffd4,
0x7ec004ff,0x7ffe43ff,0x2fffd83f,0x81ffffb8,0x004ffffa,0x901bffea,
0x3ff69fff,0xffe8003f,0x3fee002f,0xfffe884f,0x37fdc03f,0xd003ffe6,
0xf881ffff,0x7440ffff,0xeeeeffff,0x02eeeeee,0x202fffdc,0xff03fffa,
0x7fcbffff,0xfff5003f,0x33bfff23,0x4ccccccc,0xf10ffff6,0xfd83ffff,
0xfff882ff,0x7fffd45f,0xeeeeeeef,0xdfff51ee,0xb4fffc80,0xd0007fff,
0x9999bfff,0x3ee59999,0xfedcceff,0xc806ffff,0x3ffd45ff,0x0ffffee0,
0x227fffe4,0xfffffff9,0xffffffff,0x2fffdc03,0x40fffea0,0x15fffffb,
0x2a005fff,0xfff92fff,0xffffffff,0x1fffecff,0x237fffd4,0xf902fffd,
0x7fec3fff,0xffffffff,0xff52ffff,0xfffc80df,0x007fffb4,0xffffffd0,
0x29ffffff,0xfffffffb,0x00dfffff,0x7dc4ffd8,0x3ffe206f,0x3ffe207f,
0x3ffe61ff,0xffffffff,0x5c03ffff,0x7d405fff,0xfff103ff,0x3ffe2bff,
0x5fff5002,0x3ffffff2,0x27ffffff,0xfb03fffd,0x7fec9fff,0xffff302f,
0x7ffffec9,0xffffffff,0x0dfff52f,0xfb4fffc8,0xfd0007ff,0xffffffff,
0x3fee9fff,0xffffffff,0x3ffa002f,0x9037fdc3,0xb807ffff,0x3e65ffff,
0xffffffff,0x03ffffff,0x202fffdc,0x3203fffa,0xff35ffff,0x3fe6005f,
0xfffff92f,0xffffffff,0x881fffec,0xfb1fffff,0x7fec05ff,0xffffb0ff,
0xffffffff,0x3ffea5ff,0xa7ffe406,0x8003fffd,0xfffffffe,0xf74fffff,
0x79dfffff,0x00000015,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x55544000,0xaaaaaaaa,0xaa8801aa,
0x2aaaa01a,0x0009aaaa,0x35555510,0x2aa60000,0x555102aa,0x55555555,
0x4c015555,0x000accca,0x00000000,0x4de6dd44,0x32ea2000,0x800abccd,
0x801bccb9,0x5554c2b9,0x05555101,0xabccba88,0x7ffffdc0,0xffffffff,
0x3fff2204,0x3fff604f,0xdfffffff,0x3fff2001,0x880006ff,0x80ffffff,
0xfffffff8,0xffffffff,0xffffe982,0x80004fff,0x0009705a,0xffffff90,
0xfc8805ff,0xffffffff,0x3fffe602,0xf901efff,0x7ffe4dff,0x0dfff303,
0x3fffffa6,0x3fee2fff,0xffffffff,0xfc884fff,0x204fffff,0xfffffffd,
0x003fffff,0x1ffffffd,0xfffd8000,0xff880fff,0xffffffff,0x5c2fffff,
0xffffffff,0x70000eff,0x5ffb8bff,0xfffd3000,0xbfffffff,0x3ffffa20,
0x02ffffff,0xfffffff7,0xff987fff,0xfff93fff,0x1bffe607,0x3ffffff2,
0x3ee2ffff,0xffffffff,0x2e24ffff,0xffffffff,0x3ffff604,0xffffffff,
0x7ffc402f,0x0002ffff,0x3fffffea,0xffff880f,0xffffffff,0x3fe62fff,
0xfffeffff,0xfd8005ff,0xfff54fff,0xfe8001df,0xffffffff,0xffe82fff,
0xdcaabdff,0xffffa82f,0xffffebbe,0x3ffffea1,0x207fff94,0x7e46fff9,
0xffffffff,0x7fdc02ff,0x7fff405f,0x04ffffff,0x930bfff6,0xb80bffff,
0x4fffffff,0x3fffa000,0xc880ffff,0xcccccccc,0x11ffffec,0x443dffff,
0x001ffffd,0x1dffffb1,0x0f7fffe4,0xcffffb80,0x1bfffea0,0x807ffff1,
0x82fffe80,0x3e65fffd,0xff93ffff,0x3ffe607f,0x3ffffe66,0x00b6a60b,
0xb80bfff7,0xffdaefff,0x3fff604f,0x0ffff902,0xffcfffd8,0xff90007f,
0x01fffd9f,0x5fffe800,0x403fffea,0x9805fffe,0x705ffffe,0x805fffff,
0x304ffff8,0x7cc7ffff,0x5c001fff,0xff106fff,0x7ffec1ff,0x40ffff26,
0x3fa6fff9,0x40000fff,0x4405fffb,0x3fff63ff,0x0bfff604,0x203fffd4,
0xfff8ffff,0x7fcc001f,0x01fffd6f,0x7fffd400,0x817ffee1,0x4c07fffb,
0x403fffff,0x03fffffa,0x803fffea,0x3e24fffd,0x2002efff,0x3a02fffd,
0x1e541fff,0x4c0ffff2,0xfff36fff,0xf700007f,0x81500bff,0x3604fffd,
0xff702fff,0x7ffd40df,0x009fffb5,0xfd2fffd8,0x740001ff,0x7fec5fff,
0x3ffe204f,0xffff700f,0x3fa6005f,0xff704fff,0xfffb80bf,0x7fffff45,
0x7ff401ce,0xcccccccf,0x9002fffe,0x3e607fff,0xffff56ff,0x3fee0000,
0xffb0005f,0x7ffec09f,0x07fffd02,0xfb97ffe4,0x3ea006ff,0x3fffa5ff,
0xfff30000,0x6fffc85f,0x07fffe20,0x07bffff2,0xffffb100,0x4fffc81b,
0x237ffd40,0xfffffff9,0xfff80bef,0xffffffff,0x9003ffff,0x3e607fff,
0xdfff76ff,0x3fee0000,0xffb0005f,0x7ffec09f,0x3fffaa62,0x3fffa00e,
0x01ffff30,0x41ffff10,0x0000fffe,0xf70dfffb,0x7fc03fff,0x3ff622ff,
0x20000dff,0x20effffc,0x5404fffd,0xfe887fff,0xefffffff,0x3ffffe61,
0xffffffff,0xff9003ff,0x3ffe607f,0x00bfffb6,0x17ffee00,0x27ffec00,
0xffffffb0,0x01bfffff,0x3e37ffcc,0xfc803fff,0x7fff43ff,0xfff98000,
0xffff982f,0x3ff660ae,0x3fffa2ff,0xf900005f,0x3f23ffff,0x7fdc05ff,
0x3fae606f,0x10ffffff,0x5555ffff,0x15555555,0x0ffff200,0xfcb7ffcc,
0x700007ff,0x2000bfff,0x3604fffd,0xffffffff,0x2e01cfff,0x7fe44fff,
0x7ffcc05f,0x00fffe86,0x06fffd80,0x3ffffffa,0xfffffffe,0x3ffffea2,
0x7fcc0003,0x3fee3fff,0x7ffe406f,0xfff93004,0x7fffc7ff,0xfc800000,
0xfff503ff,0x03fffead,0x3ffee000,0xfffb0005,0x7fffec09,0xffffffff,
0x3fffb02f,0x407fffa8,0xfe81fffe,0x7cc000ff,0x3e202fff,0xffffffff,
0x4c1fffff,0x004ffffe,0x5fffff50,0x01ffffa8,0x000ffffe,0x749ffff3,
0x20002fff,0x3ff20cdb,0xffff884f,0x09ffff36,0xbfff7000,0x3fff6000,
0x2ffff604,0xfffc9999,0x7ffc40ff,0x2ffff887,0x209fff70,0x4000fffe,
0x8806fffd,0xfffffffc,0x880ffffd,0x00dffffe,0x3fffff20,0x5ffff881,
0x01ffff90,0x47ffff00,0x000ffffc,0x70ffffd8,0xfe88dfff,0x3ffe6fff,
0x002203ff,0x000bfff7,0xd813fff6,0xff502fff,0xfffa89ff,0x09fffd05,
0x333ffff1,0x3fffd333,0xff980133,0x2a2003ff,0xff98abcb,0x3ff600ff,
0xfd800eff,0x2e00efff,0xa9beffff,0x543ffffd,0xffc881be,0x3ffe21ff,
0x5d440bff,0x3ffffe62,0x3bffff53,0xdffffff7,0x77ffffd4,0x02fdbaac,
0x002fffdc,0x204fffd8,0x3a02fffd,0x7fe46fff,0xfeeeeeff,0xffa86fff,
0xffffffff,0x3fffffff,0x03fffec0,0xdfff7000,0xfffff700,0x3fffa205,
0xfffd005f,0xffffffff,0xfffff50d,0xdffffffd,0xffffff50,0x49ffffff,
0x24fffffa,0xffffffff,0x6c6ffeff,0xffffffff,0x7dc02fff,0xfb0005ff,
0x7fec09ff,0x3fff202f,0x7fffffc6,0xffffffff,0x7fffd41f,0xffffffff,
0x203fffff,0x003ffff8,0x0ffff600,0x7ffffd40,0x7ffffcc3,0x3ffa6004,
0xdfffffff,0xfffffa80,0x0effffff,0xffffff70,0x449fffff,0x2a2fffff,
0xffffffff,0x6446ffd9,0xffffffff,0x7fdc02ff,0xffb0005f,0x7ffec09f,
0x93fffa02,0xfffffff9,0xffffffff,0x7ffffd43,0xffffffff,0x3203ffff,
0x00007fff,0x003fffee,0x4fffff98,0x05fffff5,0x3fffae00,0x3a602eff,
0xffffffff,0x7ec400be,0xdfffffff,0x42fffdc2,0x0dfffffa,0x3660dffb,
0xcefffffe,0x2fffdc00,0x4fffd800,0x40bfff60,0x2e3ffffc,0xccccdfff,
0x5fffeccc,0x55555544,0xffffaaaa,0xff101aab,0x100007ff,0x009ffff9,
0x23fffd10,0x001fffe8,0x001a9880,0x09aaa998,0x35531000,0x401a8801,
0x800009a9,0x55100999,0x5dfffb55,0x77543555,0xeffffeee,0xffb2eeee,
0xfd97559f,0x7f41ffff,0x7fdc01ff,0xff0000ff,0xff9001ff,0x326001ff,
0xfffeeccc,0x6c0006ff,0x0077441f,0x00000000,0x00000000,0x00000000,
0xffffffb8,0x4fffffff,0x3fffffea,0xffffffff,0xffffffb3,0x3fffffff,
0x403fffc4,0x002ffff8,0x801ffff0,0x004ffff8,0x3fffffee,0x000effff,
0x00110080,0x00000000,0x00000000,0x00000000,0x7fffffdc,0x4fffffff,
0x3fffffea,0xffffffff,0xffffffb3,0x85dfffff,0xd004fffa,0x20009fff,
0x6400ffff,0x2000ffff,0xfffffffb,0x000003ff,0x00000000,0x00000000,
0x00000000,0xfffb8000,0xffffffff,0x3ffea4ff,0xffffffff,0xfffb3fff,
0x39bdffff,0x00bfff60,0x003fffe4,0x200ffff8,0x004ffff8,0x6f7fffdc,
0x0000009b,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x654c0000,0xa80abcdc,0x372e22aa,0x2e2aa82b,0x2f2e20bc,0x2a1554c0,
0xaa982cdc,0x5553002a,0x2ccc8805,0x55555440,0xaaaaaaaa,0x00aaaaa1,
0x2a155551,0x54c002aa,0x0999802a,0x00054c00,0xa9801555,0xaaaaaaaa,
0x2662aaaa,0x26666099,0x06666620,0xfffff900,0xf89fffff,0xffff76ff,
0x8fff89ff,0xe88ffffd,0x3f21ffff,0xffffd37f,0x7ffcc1df,0xfffe802f,
0x27ffcc04,0x3ffffe60,0xffffffff,0x13fffee4,0x365fffe8,0x36001fff,
0x7fc407ff,0x3ff2002f,0xfffc802f,0x7fffec04,0xffffffff,0x5ffff17f,
0x70bfffe2,0x400bffff,0xfffffffd,0x3fe4ffff,0xfffffbff,0x3ffe4fff,
0xdbfffffc,0x325fffff,0xffffafff,0x7f46ffff,0x7fcc05ff,0x7fcc00ff,
0x7ffcc04f,0xffffffff,0x7ffec4ff,0xffffb81f,0x00bfff20,0xf806ffe8,
0xff3001ff,0x7c401fff,0x3601ffff,0xffffffff,0x3e7fffff,0x3ffe1fff,
0xffff981f,0x9bffb005,0xfffff957,0x3fffffe3,0xfffffeff,0xddfffff0,
0xffbfffff,0x7fffe4ff,0xffffffff,0x3fffee2f,0x17fff200,0x013ffe60,
0xfffffff3,0x87ffffff,0x4c6ffff8,0x7dc2ffff,0x3fe003ff,0x3fe24c5f,
0x7dc0ea0f,0x3604ffff,0x206fffff,0xfffffffd,0x27ffffff,0x3fe0ffff,
0xffb101ff,0x403700bf,0xff4fffe8,0x2219ffff,0xfff3ffff,0x3fffe6bf,
0x321fff73,0x31dfffff,0x7c49fffd,0x3fe03fff,0xff9802ff,0x9999804f,
0xffffa999,0x9ffff506,0x542ffff4,0xf1004fff,0x1efd87ff,0xffb11ffd,
0xfffff301,0x27ffea0b,0x00003fff,0xe83fffa0,0x7e400fff,0xb80005ff,
0xffff5fff,0x9fff909f,0x7c47fffe,0x3ffea7ff,0x0dffff91,0xfc8bfff9,
0xfff506ff,0x3ffe600f,0x3fa20004,0x3f200fff,0xfffb9fff,0x5fff880f,
0xff30e664,0x7fffd45f,0xffe9ffdb,0xffff904f,0x5cbffa0d,0x00000fff,
0xfe8fffd0,0x5553007f,0xffa80003,0x0bffff6f,0x7fd3ffee,0x8fffe25f,
0xff91fffa,0xfff501df,0x0ffff98d,0x004fffd8,0x0009fff3,0x00ffffec,
0x7ffffff4,0x3ffe02ff,0x993ffe66,0x3f221fff,0xffffffff,0x3fa01dff,
0x6ffb84ff,0x00027ff4,0x6c7ffd80,0x000007ff,0x6e665544,0xffff6fff,
0x46aaa205,0x3fe24fff,0x47ffea2f,0xf303fffc,0xfffd0dff,0x1ffff887,
0x7fffffe4,0xffffffff,0x7ffdc07f,0xfff3003f,0xe809ffff,0x3fff27ff,
0x203ffea7,0xffffffb8,0xffc800cf,0x0fffc43f,0x9707ffea,0x99999999,
0x7ec99999,0x03ffec7f,0xffd98000,0xffffffff,0x005ffff6,0x3e24fff8,
0x3ffea2ff,0x207fff91,0xfb86fff9,0x7ffd46ff,0xfffffc86,0xffffffff,
0x3fe607ff,0x7dc005ff,0xd806ffff,0xfffd0fff,0x81ffee5f,0xdfffffb8,
0x1fffd000,0xfd05ffd8,0xffffd8df,0xffffffff,0x91bff27f,0x00000dff,
0xfffffff7,0x3edfffff,0x7c002fff,0x3ffe24ff,0x647ffea2,0xff303fff,
0xffff10df,0x41fffec3,0xfffffffc,0xffffffff,0xdffff107,0xfff88001,
0xffc804ff,0xfffff99f,0x910dff95,0xffffffff,0x3f2203bf,0x7ffcc3ff,
0x47fff301,0xfffffffd,0x27ffffff,0x554c2aa9,0x7d400002,0xaaabefff,
0xfff6fffc,0xfff8005f,0xa8bffe24,0xfff91fff,0x1bffe607,0xf8a7ffec,
0xaa980fff,0xdfffcaaa,0xd02aaaaa,0x0003ffff,0x5ffffffd,0xcafffb80,
0xd8ffffff,0x7ffd45ff,0xffdffeef,0xffdd54ff,0x9ffd0bff,0x70fffd80,
0x99999999,0x00999999,0xfb000000,0x3fea0bff,0x05ffff6f,0x224fff80,
0x3fea2fff,0x07fff91f,0x4c1bffe6,0xfff77fff,0xfff98009,0x3fff2004,
0xffc8003f,0x00ffffff,0x3fafffea,0xfeafffbf,0xa7ffc44f,0x5fff77fd,
0x0bbfffea,0x10033326,0x00005999,0x20000cc0,0x3ffe0098,0xdfff502f,
0x000bfffe,0x7fc49fff,0x47ffea2f,0xf303fffc,0x7ff40dff,0x01fffeaf,
0x027ffcc0,0x04ffffa8,0xbffffa80,0x2205ffff,0xd7ffdfff,0x07fffbff,
0x87ff45f7,0x337aa5e9,0x00000002,0x7ffe4000,0x8266604f,0xff04fffb,
0xfff507ff,0x0bfffedf,0x449fff00,0x3fea2fff,0x07fff91f,0xb81bffe6,
0x6fffefff,0x4fff9800,0x6ffff880,0xffff8800,0x07ffff74,0xaffffffc,
0x1ffffffb,0x41fff810,0x00000000,0xffd00000,0x881dffff,0xfff52fff,
0xfffd07ff,0x3ffee23d,0x5ffff6ff,0x24fff800,0x3ea2fff8,0x7fff91ff,
0x81bffe60,0xfffffff8,0xfff98003,0x7fff4404,0xccccccdf,0xefffd82c,
0x07ffffa0,0x97fffff4,0x0ffffff8,0x003fff00,0x00000000,0xffff5000,
0x541dffff,0xfff91fff,0xfff90bff,0xffffffff,0x3fffedff,0x27ffc002,
0x7d45fff1,0x7fff91ff,0x01bffe60,0x1ffffffb,0x9fff3000,0xfffffb80,
0xffffffff,0x17fffe45,0x41bfffe2,0x20fffffd,0x007ffffe,0x00007332,
0x00000000,0x2effffa0,0xd9afffff,0xfff90fff,0xfff10bff,0xd5ffffff,
0x3fffedff,0x27ffc002,0x7d45fff1,0x7fff91ff,0x01bffe60,0x0bfffff5,
0x13ffe600,0xffffff70,0xbfffffff,0x827fffcc,0xc84ffffb,0x7dc5ffff,
0x00006fff,0x00000000,0x3ffe0000,0x3ffffa24,0x3ea5ffff,0xb103ffff,
0x21bfffff,0xffff6ffd,0x4fff8005,0xfa8bffe2,0x7fff91ff,0x01bffe60,
0x007ffffa,0x7fdc0000,0xffffffff,0xfff15fff,0xfffd80df,0x7fffdc2f,
0x2ffffc42,0x00000000,0x80000000,0x7443fff8,0x1fffffff,0x402fffe4,
0x00009a98,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x80999800,0x1fffffc8,0x00001510,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00003751,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,
};
static signed short stb__consolas_bold_35_usascii_x[95]={ 0,6,3,0,1,0,0,7,4,3,2,1,3,4,
6,1,0,1,2,2,0,2,1,1,1,1,6,3,1,2,3,4,0,0,2,1,1,3,3,0,1,2,2,2,
3,0,1,0,2,0,2,1,1,1,0,0,0,0,1,5,2,4,1,0,0,1,2,2,1,1,0,1,2,2,
2,2,2,1,2,1,2,1,3,2,1,2,0,0,0,0,2,2,7,3,0, };
static signed short stb__consolas_bold_35_usascii_y[95]={ 25,0,0,2,-1,0,0,0,-1,-1,0,7,18,13,
18,0,2,2,2,2,2,2,2,2,2,2,7,7,5,10,5,0,0,2,2,2,2,2,2,2,2,2,2,2,
2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,0,0,2,28,0,7,0,7,0,7,0,7,0,0,
0,0,0,7,7,7,7,7,7,7,2,7,7,7,7,7,7,0,-3,0,11, };
static unsigned short stb__consolas_bold_35_usascii_w[95]={ 0,7,13,19,17,20,20,5,12,12,15,17,10,11,
7,17,19,17,16,16,19,16,17,17,17,17,7,11,15,15,15,13,20,20,16,17,18,14,14,18,17,15,14,17,
15,19,17,19,16,20,17,17,17,17,20,19,20,20,17,10,17,10,17,20,12,16,16,15,16,17,18,18,15,16,
14,17,16,18,15,18,16,16,15,15,16,15,19,20,19,19,15,14,5,14,19, };
static unsigned short stb__consolas_bold_35_usascii_h[95]={ 0,26,10,23,31,26,26,10,34,34,16,18,14,5,
8,29,24,23,23,24,23,24,24,23,24,23,19,25,21,11,21,26,33,23,23,24,23,23,23,24,23,23,24,23,
23,23,23,24,23,30,23,24,23,24,23,23,23,23,23,32,29,32,12,5,8,19,26,19,26,19,25,26,25,25,
33,25,25,18,18,19,25,25,18,19,24,19,18,18,18,26,18,32,36,32,9, };
static unsigned short stb__consolas_bold_35_usascii_s[95]={ 250,76,225,1,121,36,15,250,20,7,164,
89,180,217,245,160,159,17,168,19,73,36,53,93,71,111,214,153,129,209,145,
1,48,52,35,141,235,220,241,89,185,1,126,132,116,96,78,234,203,139,150,
1,60,108,200,221,21,179,42,95,178,84,191,196,239,1,233,238,216,196,134,
57,101,84,33,165,117,34,53,161,200,183,18,180,217,222,69,143,123,196,107,
69,1,106,225, };
static unsigned short stb__consolas_bold_35_usascii_t[95]={ 12,38,138,90,1,38,38,1,1,1,138,
138,138,28,149,1,65,114,90,65,114,65,65,114,65,114,114,38,114,138,114,
38,1,114,114,65,90,90,65,65,90,114,65,90,90,90,90,38,90,1,90,
65,90,65,65,65,90,65,90,1,1,1,138,28,138,138,1,114,1,114,38,
38,38,38,1,38,38,138,138,114,38,38,138,114,38,114,138,138,138,1,138,
1,1,1,149, };
static unsigned short stb__consolas_bold_35_usascii_a[95]={ 308,308,308,308,308,308,308,308,
308,308,308,308,308,308,308,308,308,308,308,308,308,308,308,308,
308,308,308,308,308,308,308,308,308,308,308,308,308,308,308,308,
308,308,308,308,308,308,308,308,308,308,308,308,308,308,308,308,
308,308,308,308,308,308,308,308,308,308,308,308,308,308,308,308,
308,308,308,308,308,308,308,308,308,308,308,308,308,308,308,308,
308,308,308,308,308,308,308, };
// Call this function with
// font: NULL or array length
// data: NULL or specified size
// height: STB_FONT_consolas_bold_35_usascii_BITMAP_HEIGHT or STB_FONT_consolas_bold_35_usascii_BITMAP_HEIGHT_POW2
// return value: spacing between lines
static void stb_font_consolas_bold_35_usascii(stb_fontchar font[STB_FONT_consolas_bold_35_usascii_NUM_CHARS],
unsigned char data[STB_FONT_consolas_bold_35_usascii_BITMAP_HEIGHT][STB_FONT_consolas_bold_35_usascii_BITMAP_WIDTH],
int height)
{
int i,j;
if (data != 0) {
unsigned int *bits = stb__consolas_bold_35_usascii_pixels;
unsigned int bitpack = *bits++, numbits = 32;
for (i=0; i < STB_FONT_consolas_bold_35_usascii_BITMAP_WIDTH*height; ++i)
data[0][i] = 0; // zero entire bitmap
for (j=1; j < STB_FONT_consolas_bold_35_usascii_BITMAP_HEIGHT-1; ++j) {
for (i=1; i < STB_FONT_consolas_bold_35_usascii_BITMAP_WIDTH-1; ++i) {
unsigned int value;
if (numbits==0) bitpack = *bits++, numbits=32;
value = bitpack & 1;
bitpack >>= 1, --numbits;
if (value) {
if (numbits < 3) bitpack = *bits++, numbits = 32;
data[j][i] = (bitpack & 7) * 0x20 + 0x1f;
bitpack >>= 3, numbits -= 3;
} else {
data[j][i] = 0;
}
}
}
}
// build font description
if (font != 0) {
float recip_width = 1.0f / STB_FONT_consolas_bold_35_usascii_BITMAP_WIDTH;
float recip_height = 1.0f / height;
for (i=0; i < STB_FONT_consolas_bold_35_usascii_NUM_CHARS; ++i) {
// pad characters so they bilerp from empty space around each character
font[i].s0 = (stb__consolas_bold_35_usascii_s[i]) * recip_width;
font[i].t0 = (stb__consolas_bold_35_usascii_t[i]) * recip_height;
font[i].s1 = (stb__consolas_bold_35_usascii_s[i] + stb__consolas_bold_35_usascii_w[i]) * recip_width;
font[i].t1 = (stb__consolas_bold_35_usascii_t[i] + stb__consolas_bold_35_usascii_h[i]) * recip_height;
font[i].x0 = stb__consolas_bold_35_usascii_x[i];
font[i].y0 = stb__consolas_bold_35_usascii_y[i];
font[i].x1 = stb__consolas_bold_35_usascii_x[i] + stb__consolas_bold_35_usascii_w[i];
font[i].y1 = stb__consolas_bold_35_usascii_y[i] + stb__consolas_bold_35_usascii_h[i];
font[i].advance_int = (stb__consolas_bold_35_usascii_a[i]+8)>>4;
font[i].s0f = (stb__consolas_bold_35_usascii_s[i] - 0.5f) * recip_width;
font[i].t0f = (stb__consolas_bold_35_usascii_t[i] - 0.5f) * recip_height;
font[i].s1f = (stb__consolas_bold_35_usascii_s[i] + stb__consolas_bold_35_usascii_w[i] + 0.5f) * recip_width;
font[i].t1f = (stb__consolas_bold_35_usascii_t[i] + stb__consolas_bold_35_usascii_h[i] + 0.5f) * recip_height;
font[i].x0f = stb__consolas_bold_35_usascii_x[i] - 0.5f;
font[i].y0f = stb__consolas_bold_35_usascii_y[i] - 0.5f;
font[i].x1f = stb__consolas_bold_35_usascii_x[i] + stb__consolas_bold_35_usascii_w[i] + 0.5f;
font[i].y1f = stb__consolas_bold_35_usascii_y[i] + stb__consolas_bold_35_usascii_h[i] + 0.5f;
font[i].advance = stb__consolas_bold_35_usascii_a[i]/16.0f;
}
}
}
#ifndef STB_SOMEFONT_CREATE
#define STB_SOMEFONT_CREATE stb_font_consolas_bold_35_usascii
#define STB_SOMEFONT_BITMAP_WIDTH STB_FONT_consolas_bold_35_usascii_BITMAP_WIDTH
#define STB_SOMEFONT_BITMAP_HEIGHT STB_FONT_consolas_bold_35_usascii_BITMAP_HEIGHT
#define STB_SOMEFONT_BITMAP_HEIGHT_POW2 STB_FONT_consolas_bold_35_usascii_BITMAP_HEIGHT_POW2
#define STB_SOMEFONT_FIRST_CHAR STB_FONT_consolas_bold_35_usascii_FIRST_CHAR
#define STB_SOMEFONT_NUM_CHARS STB_FONT_consolas_bold_35_usascii_NUM_CHARS
#define STB_SOMEFONT_LINE_SPACING STB_FONT_consolas_bold_35_usascii_LINE_SPACING
#endif
| 47,529 | 32,492 |
#pragma once
//------------------------------------------------------------------------------
//
// Copyright 2018-2019 Fetch.AI Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//------------------------------------------------------------------------------
#include "core/random.hpp"
#include "core/serializers/group_definitions.hpp"
#include "ml/dataloaders/dataloader.hpp"
#include "ml/exceptions/exceptions.hpp"
#include "ml/meta/ml_type_traits.hpp"
#include <stdexcept>
#include <utility>
namespace fetch {
namespace ml {
namespace dataloaders {
template <typename LabelType, typename InputType>
class TensorDataLoader : public DataLoader<LabelType, InputType>
{
using TensorType = InputType;
using DataType = typename TensorType::Type;
using SizeType = fetch::math::SizeType;
using SizeVector = fetch::math::SizeVector;
using ReturnType = std::pair<LabelType, std::vector<TensorType>>;
using IteratorType = typename TensorType::IteratorType;
public:
TensorDataLoader() = default;
TensorDataLoader(SizeVector label_shape, std::vector<SizeVector> data_shapes);
~TensorDataLoader() override = default;
ReturnType GetNext() override;
bool AddData(std::vector<InputType> const &data, LabelType const &labels) override;
SizeType Size() const override;
bool IsDone() const override;
void Reset() override;
bool IsModeAvailable(DataLoaderMode mode) override;
void SetTestRatio(float new_test_ratio) override;
void SetValidationRatio(float new_validation_ratio) override;
template <typename X, typename D>
friend struct fetch::serializers::MapSerializer;
LoaderType LoaderCode() override
{
return LoaderType::TENSOR;
}
protected:
std::shared_ptr<SizeType> train_cursor_ = std::make_shared<SizeType>(0);
std::shared_ptr<SizeType> test_cursor_ = std::make_shared<SizeType>(0);
std::shared_ptr<SizeType> validation_cursor_ = std::make_shared<SizeType>(0);
SizeType test_offset_ = 0;
SizeType validation_offset_ = 0;
SizeType n_samples_ = 0; // number of all samples
SizeType n_test_samples_ = 0; // number of test samples
SizeType n_validation_samples_ = 0; // number of validation samples
SizeType n_train_samples_ = 0; // number of train samples
std::vector<TensorType> data_;
TensorType labels_;
SizeVector label_shape_;
SizeVector one_sample_label_shape_;
std::vector<SizeVector> data_shapes_;
std::vector<SizeVector> one_sample_data_shapes_;
float test_to_train_ratio_ = 0.0;
float validation_to_train_ratio_ = 0.0;
SizeType batch_label_dim_ = fetch::math::numeric_max<SizeType>();
SizeType batch_data_dim_ = fetch::math::numeric_max<SizeType>();
random::Random rand;
SizeType count_ = 0;
void UpdateRanges();
void UpdateCursor() override;
};
template <typename LabelType, typename InputType>
TensorDataLoader<LabelType, InputType>::TensorDataLoader(SizeVector label_shape,
std::vector<SizeVector> data_shapes)
: DataLoader<LabelType, TensorType>()
, label_shape_(std::move(label_shape))
, data_shapes_(std::move(data_shapes))
{
UpdateCursor();
}
template <typename LabelType, typename InputType>
typename TensorDataLoader<LabelType, InputType>::ReturnType
TensorDataLoader<LabelType, InputType>::GetNext()
{
std::vector<InputType> ret_data;
LabelType ret_labels = labels_.View(*this->current_cursor_).Copy(one_sample_label_shape_);
for (SizeType i{0}; i < data_.size(); i++)
{
ret_data.emplace_back(
data_.at(i).View(*this->current_cursor_).Copy(one_sample_data_shapes_.at(i)));
}
if (this->random_mode_)
{
*this->current_cursor_ =
this->current_min_ +
(static_cast<SizeType>(decltype(rand)::generator()) % this->current_size_);
++count_;
}
else
{
(*this->current_cursor_)++;
}
return ReturnType(ret_labels, ret_data);
}
template <typename LabelType, typename InputType>
bool TensorDataLoader<LabelType, InputType>::AddData(std::vector<InputType> const &data,
LabelType const & labels)
{
one_sample_label_shape_ = labels.shape();
one_sample_label_shape_.at(one_sample_label_shape_.size() - 1) = 1;
labels_ = labels.Copy();
// Resize data vector
if (data_.size() < data.size())
{
data_.resize(data.size());
one_sample_data_shapes_.resize(data.size());
}
// Add data to data vector
for (SizeType i{0}; i < data.size(); i++)
{
data_.at(i) = data.at(i).Copy();
one_sample_data_shapes_.at(i) = data.at(i).shape();
one_sample_data_shapes_.at(i).at(one_sample_data_shapes_.at(i).size() - 1) = 1;
}
n_samples_ = data_.at(0).shape().at(data_.at(0).shape().size() - 1);
UpdateRanges();
return true;
}
template <typename LabelType, typename InputType>
typename TensorDataLoader<LabelType, InputType>::SizeType
TensorDataLoader<LabelType, InputType>::Size() const
{
return this->current_size_;
}
template <typename LabelType, typename InputType>
bool TensorDataLoader<LabelType, InputType>::IsDone() const
{
if (this->random_mode_)
{
return (count_ > (this->current_max_ - this->current_min_));
}
return *(this->current_cursor_) >= this->current_max_;
}
template <typename LabelType, typename InputType>
void TensorDataLoader<LabelType, InputType>::Reset()
{
count_ = 0;
*(this->current_cursor_) = this->current_min_;
}
template <typename LabelType, typename InputType>
void TensorDataLoader<LabelType, InputType>::SetTestRatio(float new_test_ratio)
{
test_to_train_ratio_ = new_test_ratio;
UpdateRanges();
}
template <typename LabelType, typename InputType>
void TensorDataLoader<LabelType, InputType>::SetValidationRatio(float new_validation_ratio)
{
validation_to_train_ratio_ = new_validation_ratio;
UpdateRanges();
}
template <typename LabelType, typename InputType>
void TensorDataLoader<LabelType, InputType>::UpdateRanges()
{
float test_percentage = 1.0f - test_to_train_ratio_ - validation_to_train_ratio_;
float validation_percentage = test_percentage + test_to_train_ratio_;
// Define where test set starts
test_offset_ = static_cast<uint32_t>(test_percentage * static_cast<float>(n_samples_));
if (test_offset_ == static_cast<SizeType>(0))
{
test_offset_ = static_cast<SizeType>(1);
}
// Define where validation set starts
validation_offset_ =
static_cast<uint32_t>(validation_percentage * static_cast<float>(n_samples_));
if (validation_offset_ <= test_offset_)
{
validation_offset_ = test_offset_ + 1;
}
// boundary check and fix
if (validation_offset_ > n_samples_)
{
validation_offset_ = n_samples_;
}
if (test_offset_ > n_samples_)
{
test_offset_ = n_samples_;
}
n_validation_samples_ = n_samples_ - validation_offset_;
n_test_samples_ = validation_offset_ - test_offset_;
n_train_samples_ = test_offset_;
*train_cursor_ = 0;
*test_cursor_ = test_offset_;
*validation_cursor_ = validation_offset_;
UpdateCursor();
}
template <typename LabelType, typename InputType>
void TensorDataLoader<LabelType, InputType>::UpdateCursor()
{
switch (this->mode_)
{
case DataLoaderMode::TRAIN:
{
this->current_cursor_ = train_cursor_;
this->current_min_ = 0;
this->current_max_ = test_offset_;
this->current_size_ = n_train_samples_;
break;
}
case DataLoaderMode::TEST:
{
if (test_to_train_ratio_ == 0)
{
throw exceptions::InvalidMode("Dataloader has no test set.");
}
this->current_cursor_ = test_cursor_;
this->current_min_ = test_offset_;
this->current_max_ = validation_offset_;
this->current_size_ = n_test_samples_;
break;
}
case DataLoaderMode::VALIDATE:
{
if (validation_to_train_ratio_ == 0)
{
throw exceptions::InvalidMode("Dataloader has no validation set.");
}
this->current_cursor_ = validation_cursor_;
this->current_min_ = validation_offset_;
this->current_max_ = n_samples_;
this->current_size_ = n_validation_samples_;
break;
}
default:
{
throw exceptions::InvalidMode("Unsupported dataloader mode.");
}
}
}
template <typename LabelType, typename InputType>
bool TensorDataLoader<LabelType, InputType>::IsModeAvailable(DataLoaderMode mode)
{
switch (mode)
{
case DataLoaderMode::TRAIN:
{
return test_offset_ > 0;
}
case DataLoaderMode::TEST:
{
return test_offset_ < validation_offset_;
}
case DataLoaderMode::VALIDATE:
{
return validation_offset_ < n_samples_;
}
default:
{
throw exceptions::InvalidMode("Unsupported dataloader mode.");
}
}
}
} // namespace dataloaders
} // namespace ml
namespace serializers {
/**
* serializer for tensor dataloader
* @tparam TensorType
*/
template <typename LabelType, typename InputType, typename D>
struct MapSerializer<fetch::ml::dataloaders::TensorDataLoader<LabelType, InputType>, D>
{
using Type = fetch::ml::dataloaders::TensorDataLoader<LabelType, InputType>;
using DriverType = D;
static uint8_t const BASE_DATA_LOADER = 1;
static uint8_t const TRAIN_CURSOR = 2;
static uint8_t const TEST_CURSOR = 3;
static uint8_t const VALIDATION_CURSOR = 4;
static uint8_t const TEST_OFFSET = 5;
static uint8_t const VALIDATION_OFFSET = 6;
static uint8_t const TEST_TO_TRAIN_RATIO = 7;
static uint8_t const VALIDATION_TO_TRAIN_RATIO = 8;
static uint8_t const N_SAMPLES = 9;
static uint8_t const N_TRAIN_SAMPLES = 10;
static uint8_t const N_TEST_SAMPLES = 11;
static uint8_t const N_VALIDATION_SAMPLES = 12;
static uint8_t const DATA = 13;
static uint8_t const LABELS = 14;
static uint8_t const LABEL_SHAPE = 15;
static uint8_t const ONE_SAMPLE_LABEL_SHAPE = 16;
static uint8_t const DATA_SHAPES = 17;
static uint8_t const ONE_SAMPLE_DATA_SHAPES = 18;
static uint8_t const BATCH_LABEL_DIM = 19;
static uint8_t const BATCH_DATA_DIM = 20;
template <typename Constructor>
static void Serialize(Constructor &map_constructor, Type const &sp)
{
auto map = map_constructor(20);
// serialize parent class first
auto dl_pointer = static_cast<ml::dataloaders::DataLoader<LabelType, InputType> const *>(&sp);
map.Append(BASE_DATA_LOADER, *(dl_pointer));
map.Append(TRAIN_CURSOR, *sp.train_cursor_);
map.Append(TEST_CURSOR, *sp.test_cursor_);
map.Append(VALIDATION_CURSOR, *sp.validation_cursor_);
map.Append(TEST_OFFSET, sp.test_offset_);
map.Append(VALIDATION_OFFSET, sp.validation_offset_);
map.Append(TEST_TO_TRAIN_RATIO, sp.test_to_train_ratio_);
map.Append(VALIDATION_TO_TRAIN_RATIO, sp.validation_to_train_ratio_);
map.Append(N_SAMPLES, sp.n_samples_);
map.Append(N_TRAIN_SAMPLES, sp.n_train_samples_);
map.Append(N_TEST_SAMPLES, sp.n_test_samples_);
map.Append(N_VALIDATION_SAMPLES, sp.n_validation_samples_);
map.Append(DATA, sp.data_);
map.Append(LABELS, sp.labels_);
map.Append(LABEL_SHAPE, sp.label_shape_);
map.Append(ONE_SAMPLE_LABEL_SHAPE, sp.one_sample_label_shape_);
map.Append(DATA_SHAPES, sp.data_shapes_);
map.Append(ONE_SAMPLE_DATA_SHAPES, sp.one_sample_data_shapes_);
map.Append(BATCH_LABEL_DIM, sp.batch_label_dim_);
map.Append(BATCH_DATA_DIM, sp.batch_data_dim_);
}
template <typename MapDeserializer>
static void Deserialize(MapDeserializer &map, Type &sp)
{
auto dl_pointer = static_cast<ml::dataloaders::DataLoader<LabelType, InputType> *>(&sp);
map.ExpectKeyGetValue(BASE_DATA_LOADER, (*dl_pointer));
map.ExpectKeyGetValue(TRAIN_CURSOR, *sp.train_cursor_);
map.ExpectKeyGetValue(TEST_CURSOR, *sp.test_cursor_);
map.ExpectKeyGetValue(VALIDATION_CURSOR, *sp.validation_cursor_);
map.ExpectKeyGetValue(TEST_OFFSET, sp.test_offset_);
map.ExpectKeyGetValue(VALIDATION_OFFSET, sp.validation_offset_);
map.ExpectKeyGetValue(TEST_TO_TRAIN_RATIO, sp.test_to_train_ratio_);
map.ExpectKeyGetValue(VALIDATION_TO_TRAIN_RATIO, sp.validation_to_train_ratio_);
map.ExpectKeyGetValue(N_SAMPLES, sp.n_samples_);
map.ExpectKeyGetValue(N_TRAIN_SAMPLES, sp.n_train_samples_);
map.ExpectKeyGetValue(N_TEST_SAMPLES, sp.n_test_samples_);
map.ExpectKeyGetValue(N_VALIDATION_SAMPLES, sp.n_validation_samples_);
map.ExpectKeyGetValue(DATA, sp.data_);
map.ExpectKeyGetValue(LABELS, sp.labels_);
map.ExpectKeyGetValue(LABEL_SHAPE, sp.label_shape_);
map.ExpectKeyGetValue(ONE_SAMPLE_LABEL_SHAPE, sp.one_sample_label_shape_);
map.ExpectKeyGetValue(DATA_SHAPES, sp.data_shapes_);
map.ExpectKeyGetValue(ONE_SAMPLE_DATA_SHAPES, sp.one_sample_data_shapes_);
map.ExpectKeyGetValue(BATCH_LABEL_DIM, sp.batch_label_dim_);
map.ExpectKeyGetValue(BATCH_DATA_DIM, sp.batch_data_dim_);
sp.UpdateRanges();
sp.UpdateCursor();
}
};
} // namespace serializers
} // namespace fetch
| 13,988 | 4,787 |
/**********************************************************
Author: Qt君
微信公众号: Qt君(首发)
QQ群: 732271126
Email: 2088201923@qq.com
LICENSE: MIT
**********************************************************/
#include "Keyboard.h"
#include <QApplication>
#include <QLineEdit>
using namespace AeaQt;
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QWidget window;
Keyboard keyboard;
QLineEdit textInput;
QVBoxLayout *v = new QVBoxLayout;
v->addWidget(&textInput);
v->addWidget(&keyboard);
window.setLayout(v);
window.show();
return a.exec();
}
| 597 | 220 |
/*
* Copyright (c) 2015 Cryptonomex, Inc., and contributors.
*
* The MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <graphene/chain/gravity_evaluator.hpp>
#include <graphene/chain/gravity_transfer_object.hpp>
#include <graphene/chain/exceptions.hpp>
#include <graphene/chain/hardfork.hpp>
#include <graphene/chain/is_authorized_asset.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/uuid/string_generator.hpp>
namespace graphene { namespace chain {
//**********************************************************************************************************************************************//
void_result gravity_transfer_evaluator::do_evaluate( const gravity_transfer_operation& op )
{ try {
const database& d = db();
const account_object& from_account = op.from(d);
const account_object& to_account = op.to(d);
const account_object& fee_payer = op.fee_payer_account(d);
const asset_object& asset_type = op.amount.asset_id(d);
try {
GRAPHENE_ASSERT(
is_authorized_asset( d, from_account, asset_type ),
transfer_from_account_not_whitelisted,
"'from' account ${from} is not whitelisted for asset ${asset}",
("from",op.from)
("asset",op.amount.asset_id)
);
GRAPHENE_ASSERT(
is_authorized_asset( d, to_account, asset_type ),
transfer_to_account_not_whitelisted,
"'to' account ${to} is not whitelisted for asset ${asset}",
("to",op.to)
("asset",op.amount.asset_id)
);
if( asset_type.is_transfer_restricted() )
{
GRAPHENE_ASSERT(
from_account.id == asset_type.issuer || to_account.id == asset_type.issuer,
transfer_restricted_transfer_asset,
"Asset {asset} has transfer_restricted flag enabled",
("asset", op.amount.asset_id)
);
}
FC_ASSERT( ( from_account.id != fee_payer.id || to_account.id != fee_payer.id ), "wrong fee_payer account" );
bool insufficient_balance = d.get_balance( from_account, asset_type ).amount >= op.amount.amount;
FC_ASSERT( insufficient_balance,
"Insufficient Balance: ${balance}, unable to transfer '${total_transfer}' from account '${a}' to '${t}'",
("a",from_account.name)("t",to_account.name)("total_transfer",d.to_pretty_string(op.amount))("balance",d.to_pretty_string(d.get_balance(from_account, asset_type))) );
return void_result();
} FC_RETHROW_EXCEPTIONS( error, "Unable to transfer ${a} from ${f} to ${t}", ("a",d.to_pretty_string(op.amount))("f",op.from(d).name)("t",op.to(d).name) );
} FC_CAPTURE_AND_RETHROW( (op) ) }
void_result gravity_transfer_evaluator::do_apply( const gravity_transfer_operation& o )
{ try {
const auto& gto = db( ).create<gravity_transfer_object>( [&]( gravity_transfer_object& obj )
{
std::string time_str = boost::posix_time::to_iso_string( boost::posix_time::from_time_t( db( ).head_block_time( ).sec_since_epoch( ) ) );
std::string id = fc::to_string( obj.id.space( ) ) + "." + fc::to_string( obj.id.type( ) ) + "." + fc::to_string( obj.id.instance( ) );
boost::uuids::string_generator gen;
boost::uuids::uuid u1 = gen( id + time_str + time_str );
obj.uuid = to_string( u1 );
obj.fee = o.fee;
obj.from = o.from;
obj.to = o.to;
obj.amount = o.amount;
obj.fee_payer = o.fee_payer_account;
obj.memo = o.memo;
});
return void_result();
} FC_CAPTURE_AND_RETHROW( (o) ) }
//**********************************************************************************************************************************************//
void_result gravity_transfer_approve_evaluator::do_evaluate( const gravity_transfer_approve_operation& op )
{
return void_result();
}
void_result gravity_transfer_approve_evaluator::do_apply( const gravity_transfer_approve_operation& o )
{ try {
bool gravity_transfer_founded = false;
auto& e = db( ).get_index_type<gravity_transfer_index>( ).indices( ).get<by_transfer_by_uuid>( );
for( auto itr = e.begin( ); itr != e.end( ); itr++ )
{
if( ( *itr ).uuid.compare( o.uuid ) == 0 )
{
if( ( *itr ).to != o.approver )
FC_ASSERT( 0, "wrong receiver!" );
db().adjust_balance( ( *itr ).from, -( *itr ).amount );
db().adjust_balance( ( *itr ).to, ( *itr ).amount );
auto c = db().get_core_asset();
const auto& a = ( *itr ).amount.asset_id( (database&)db() );
db( ).remove( *itr );
gravity_transfer_founded = true;
break;
}
}
FC_ASSERT( gravity_transfer_founded, "gravity transfer not founed!" );
return void_result();
} FC_CAPTURE_AND_RETHROW( (o) ) }
//**********************************************************************************************************************************************//
void_result gravity_transfer_reject_evaluator::do_evaluate( const gravity_transfer_reject_operation& op )
{
return void_result();
}
void_result gravity_transfer_reject_evaluator::do_apply( const gravity_transfer_reject_operation& o )
{ try {
bool gravity_transfer_founded = false;
auto& e = db( ).get_index_type<gravity_transfer_index>( ).indices( ).get<by_transfer_by_uuid>( );
for( auto itr = e.begin( ); itr != e.end( ); itr++ )
{
if( ( *itr ).uuid.compare( o.uuid ) == 0 )
{
if( ( *itr ).to != o.approver )
FC_ASSERT( 0, "wrong receiver!" );
db( ).remove( *itr );
gravity_transfer_founded = true;
break;
}
}
FC_ASSERT( gravity_transfer_founded, "gravity transfer not founed!" );
return void_result();
} FC_CAPTURE_AND_RETHROW( (o) ) }
//**********************************************************************************************************************************************//
} } // graphene::chain
| 7,100 | 2,326 |
//==============================================================================
// Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II
// Copyright 2009 - 2012 LRI UMR 8623 CNRS/Univ Paris Sud XI
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef NT2_LINALG_FUNCTIONS_GALLERY_KMS_HPP_INCLUDED
#define NT2_LINALG_FUNCTIONS_GALLERY_KMS_HPP_INCLUDED
#include <nt2/linalg/functions/kms.hpp>
#include <nt2/include/functions/pow.hpp>
#include <nt2/include/functions/cif.hpp>
#include <nt2/include/functions/rif.hpp>
#include <nt2/include/functions/abs.hpp>
#include <nt2/include/functions/whereij.hpp>
#include <nt2/include/functions/is_less.hpp>
#include <nt2/core/container/dsl.hpp>
#include <nt2/core/utility/box.hpp>
#include <nt2/sdk/complex/meta/is_complex.hpp>
namespace nt2 { namespace ext
{
NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::kms_, tag::cpu_,
(A0)(A1),
(scalar_<integer_<A0> >)
(scalar_<floating_<A1> >)
)
{
BOOST_DISPATCH_RETURNS(2, (A0 const& n, A1 const& rho),
(boost::proto::
make_expr<nt2::tag::kms_, container::domain>
( rho
, boxify(nt2::of_size(size_t(n), size_t(n)))
)
)
)
};
NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::kms_, tag::cpu_,
(A0)(A1)(T),
(scalar_<integer_<A0> >)
(scalar_<unspecified_<A1> >)
(target_< scalar_< unspecified_<T> > >)
)
{
typedef typename T::type value_t;
BOOST_DISPATCH_RETURNS(3, (A0 const& n, A1 const& rho, T const& t),
(boost::proto::
make_expr<nt2::tag::kms_, container::domain>
( value_t(rho)
, boxify(nt2::of_size(size_t(n), size_t(n)))
)
)
)
};
NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::run_assign_, tag::cpu_
, (A0)(A1)(N)
, ((ast_<A0, nt2::container::domain>))
((node_<A1,nt2::tag::kms_,N,nt2::container::domain>))
)
{
typedef A0& result_type;
typedef typename boost::proto::result_of::child_c<A1&,0>::type tmp_type;
typedef typename meta::strip<tmp_type>::type tmp1_type;
typedef typename tmp1_type::value_type value_t;
typedef typename meta::is_complex<value_t>::type iscplx_t;
result_type operator()(A0& out, const A1& in) const
{
BOOST_AUTO_TPL(siz,boost::proto::value( boost::proto::child_c<1>(in)));
value_t rho = boost::proto::child_c<0>(in);
size_t n = siz[0];
out.resize(siz);
finalize(out, n, rho, iscplx_t());
return out;
}
private :
static BOOST_FORCEINLINE void finalize(A0& out, const size_t & n, const value_t & rho, const boost::mpl::false_ &)
{
out = nt2::pow(rho, nt2::abs(nt2::rif(n, meta::as_<value_t>())-cif(n, meta::as_<value_t>())));
}
static BOOST_FORCEINLINE void finalize(A0& out, const size_t & n, const value_t & rho, const boost::mpl::true_ &)
{
out = pow(rho, nt2::abs(nt2::rif(n, meta::as_<value_t>())-nt2::cif(n, meta::as_<value_t>())));
out = whereij(nt2::functor<nt2::tag::is_less_>(), nt2::conj(out), out); //nt2::conj(nt2::tril(out,-1)) + nt2::triu(out);
}
};
} }
#endif
| 4,009 | 1,416 |
//
// Windows Server (Printing) Driver Development Kit Samples.
//
//
// Copyright (c) 1990 - 2005 Microsoft Corporation.
// All Rights Reserved.
//
//
// This source code is intended only as a supplement to Microsoft
// Development Tools and/or on-line documentation. See these other
// materials for detailed information regarding Microsoft code samples.
//
// THIS CODE AND INFORMATION ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
#include "precomp.h"
#pragma hdrstop
_Analysis_mode_(_Analysis_code_type_user_driver_)
#include "acallback.hpp"
#include "notifydata.hpp"
//
// MarshalSchema is used to marshal an EOEMDataSchema enum value into a byte array
// in a platform-independent fashion (to avoid endianness and size issues on other platforms).
// This allows the client and server to run on independent architectures without issue.
// To marshal more complex data structures than a simple enum value, it is recommended that
// the RPC Serialization Services be used. See the MSDN documentation at:
// http://msdn2.microsoft.com/en-us/library/aa378670.aspx for details on their use.
//
void
MarshalSchema(
_In_ EOEMDataSchema const &in,
_Out_ BYTE (&out)[4]
)
{
out[0] = (BYTE)(in);
out[1] = (BYTE)(in >> 8);
out[2] = (BYTE)(in >> 16);
out[3] = (BYTE)(in >> 24);
}
VOID
SendAsyncNotification(
_In_ LPWSTR pPrinterName,
EOEMDataSchema action
)
{
IPrintAsyncNotifyChannel *pIAsynchNotification = NULL;
CPrintOEMAsyncNotifyCallback *pIAsynchCallback = new CPrintOEMAsyncNotifyCallback;
if (pIAsynchCallback)
{
RouterCreatePrintAsyncNotificationChannel(pPrinterName,
const_cast<GUID*>(&SAMPLE_NOTIFICATION_UI),
kPerUser,
kBiDirectional,
pIAsynchCallback,
&pIAsynchNotification);
pIAsynchCallback->Release();
}
if (pIAsynchNotification)
{
BYTE data[4] = { 0 };
MarshalSchema(action, data);
CPrintOEMAsyncNotifyDataObject *pClientNotification = new CPrintOEMAsyncNotifyDataObject(data,
sizeof(data),
const_cast<GUID*>(&SAMPLE_NOTIFICATION_UI));
if (pClientNotification)
{
pIAsynchNotification->SendNotification(pClientNotification);
pClientNotification->Release();
}
pIAsynchNotification->Release();
}
}
VOID
SendAsyncUINotification(
_In_ LPWSTR pPrinterName
)
{
WCHAR pszMsg[] = L"<?xml version=\"1.0\" ?>" \
L"<asyncPrintUIRequest xmlns=\"http://schemas.microsoft.com/2003/print/asyncui/v1/request\">" \
L"<v1><requestOpen><balloonUI><title>AsyncUI sample</title><body>This text is a sample.</body>" \
L"</balloonUI></requestOpen></v1></asyncPrintUIRequest>";
IPrintAsyncNotifyChannel *pIAsynchNotification = NULL;
CPrintOEMAsyncNotifyCallback *pIAsynchCallback = new CPrintOEMAsyncNotifyCallback;
if (pIAsynchCallback)
{
RouterCreatePrintAsyncNotificationChannel(pPrinterName,
const_cast<GUID*>(&MS_ASYNCNOTIFY_UI),
kPerUser,
kBiDirectional,
pIAsynchCallback,
&pIAsynchNotification);
pIAsynchCallback->Release();
}
if (pIAsynchNotification)
{
CPrintOEMAsyncNotifyDataObject *pClientNotification = new CPrintOEMAsyncNotifyDataObject(reinterpret_cast<BYTE*>(pszMsg),
sizeof(pszMsg),
const_cast<GUID*>(&MS_ASYNCNOTIFY_UI));
if (pClientNotification)
{
pIAsynchNotification->SendNotification(pClientNotification);
pClientNotification->Release();
}
pIAsynchNotification->Release();
}
}
| 4,625 | 1,323 |
// This file is distributed under the BSD 3-Clause License. See LICENSE for details.
#pragma once
#include "fmt/format.h"
#include "lnast_ntype.hpp"
#include "upass_core.hpp"
struct uPass_verifier : public upass::uPass {
public:
using uPass::uPass;
// Assignment
// void process_assign() override { check_binary(); }
// Operators
// - Bitwidth
void process_bit_and() override { check_binary(); }
void process_bit_or() override { check_binary(); }
// void process_bit_not() override { check_binary(); }
void process_bit_xor() override { check_binary(); }
// - Bitwidth Insensitive Reduce
// void process_reduce_or() override { check_binary(); }
// - Logical
void process_logical_and() override { check_binary(); }
void process_logical_or() override { check_binary(); }
// void process_logical_not() override { check_binary(); }
// - Arithmetic
void process_plus() override { check_binary(); }
void process_minus() override { check_binary(); }
void process_mult() override { check_binary(); }
void process_div() override { check_binary(); }
void process_mod() override { check_binary(); }
// - Shift
void process_shl() override { check_binary(); }
void process_sra() override { check_binary(); }
// - Bit Manipulation
// void process_sext() override { check_binary(); }
// void process_set_mask() override { check_binary(); }
// void process_get_mask() override { check_binary(); }
// void process_mask_and() override { check_binary(); }
// void process_mask_popcount() override { check_binary(); }
// void process_mask_xor() override { check_binary(); }
// - Comparison
void process_ne() override { check_binary(); }
void process_eq() override { check_binary(); }
void process_lt() override { check_binary(); }
void process_le() override { check_binary(); }
void process_gt() override { check_binary(); }
void process_ge() override { check_binary(); }
private:
void check_binary() {
move_to_child();
check_type(Lnast_ntype::Lnast_ntype_ref);
move_to_sibling();
check_type(Lnast_ntype::Lnast_ntype_ref, Lnast_ntype::Lnast_ntype_const);
move_to_sibling();
check_type(Lnast_ntype::Lnast_ntype_ref, Lnast_ntype::Lnast_ntype_const);
end_of_siblings();
move_to_parent();
}
void end_of_siblings() const {
if (!is_last_child()) {
upass::error("");
}
}
template <class... Lnast_ntype_int>
void check_type(Lnast_ntype_int... ty) const {
if (is_invalid()) {
upass::error("invalid\n");
return;
}
// print_types(ty...);
auto n = get_raw_ntype();
// print_types(n);
if (((n == ty) || ...) || false) {
return;
}
upass::error("failed\n");
}
template <class T, class... Targs>
void print_types(T ty, Targs... tys) const {
std::cout << Lnast_ntype::debug_name(ty) << " ";
print_types(tys...);
}
void print_types() const {}
};
static upass::uPass_plugin verifier("verifier", upass::uPass_wrapper<uPass_verifier>::get_upass);
| 3,020 | 1,034 |
#include "RegisterServer.h"
RegisterServer::RegisterServer(int port)
{
int sockFd= CreateServerSocket(port);
CreateEpollSocket(sockFd);
watchEvent = &SocketWatcher::StartServerWatcher;
printf("Register Server\n");
}
RegisterServer::RegisterServer(char* ipAddr,int port)
{
int sockFd = CreateClientSocket(ipAddr,port);
// CreateEpollSocket(sockFd,1);
CreateEpollSocket(sockFd,DEFAULT_SERVER_EVENTS|EPOLLET,new SocketInfo(sockFd,64));
watchEvent = &SocketWatcher::StartClientWatcher;
//MUXER.AddSubscriberSocket(sockFd);
printf("Register Client\n");
}
void RegisterServer::EventErrorHandler(struct epoll_event &event)
{
printf("RegisterServer::EventErrorHandler();\n");
SocketInfo* dh = (SocketInfo*)event.data.ptr;
//MUXER.RemoveSubscriberSocket(dh->m_socketDescriptor);
close (dh->m_socketDescriptor);
delete dh;
}
void RegisterServer::AcceptNewClientConnection(struct epoll_event &event)
{
printf("RegisterServer()::AcceptNewClientConnection()\n");
struct sockaddr in_addr;
socklen_t in_len;
int infd;
in_len = sizeof in_addr;
infd = accept(m_socketDescriptor,&in_addr,&in_len);
if (infd == -1) //error or Exception
return;
if(SetSocketFlags(infd,O_NONBLOCK) < 0)
{
perror ("Flag Error:");
return;// exit()
}
event.data.ptr = new SocketInfo(infd,64);
#ifdef EDGETRIGGERED
event.events = EPOLLIN | EPOLLET | EPOLLERR | EPOLLRDHUP | EPOLLHUP;
#else
event.events = EPOLLIN | EPOLLERR | EPOLLRDHUP | EPOLLHUP;
#endif
if(epoll_ctl(m_epollDescriptor,EPOLL_CTL_ADD,infd,&event))
{
perror ("epoll_ctl");
return; // exit()
}
//MUXER.AddSubscriberSocket(infd);
}
void RegisterServer::ProcessClientEvent(struct epoll_event &event)
{
printf("RegisterServer::ProcessClientEvent();\n");
int done = 0;
SocketInfo* dh = (SocketInfo*)event.data.ptr;
#ifdef EDGETRIGGERED
while(1)
{
#endif
dh->ReadFromSocket(dh->m_socketDescriptor,done);
if(done == 1) // socket read Error
{
EventErrorHandler(event);
return;
}
#ifdef EDGETRIGGERED
else if(done == 2) //EAGAIN
{
return;
}
}
#endif
}
| 2,268 | 813 |
/*
移行 Note:
map を各 GraphicsResource から CommandBuffer へ移動する。
※ ネイティブの map (transfar) は RenderPass の外側でなければ使えないので、順序制御するため CommandBuffer に統合したい
CommandBuffer と RenderPass は全て pool からインスタンスを得る。インスタンスを外側で保持し続けてはならない。
*/
#include "Internal.hpp"
#include <LuminoEngine/Graphics/Texture.hpp>
#include <LuminoEngine/Graphics/DepthBuffer.hpp>
#include <LuminoEngine/Graphics/RenderPass.hpp>
#include "GraphicsManager.hpp"
#include "GraphicsProfiler.hpp"
#include "RHIs/GraphicsDeviceContext.hpp"
namespace ln {
//==============================================================================
// RenderPass
RenderPass::RenderPass()
: m_manager(nullptr)
, m_rhiObject()
, m_renderTargets{}
, m_depthBuffer()
, m_clearFlags(ClearFlags::None)
, m_clearColor(0, 0, 0, 0)
, m_clearDepth(1.0f)
, m_clearStencil(0x00)
, m_dirty(true)
, m_active(false)
{
detail::GraphicsResourceInternal::initializeHelper_GraphicsResource(this, &m_manager);
detail::GraphicsResourceInternal::manager(this)->profiler()->addRenderPass(this);
}
RenderPass::~RenderPass()
{
detail::GraphicsResourceInternal::manager(this)->profiler()->removeRenderPass(this);
detail::GraphicsResourceInternal::finalizeHelper_GraphicsResource(this, &m_manager);
}
void RenderPass::init()
{
Object::init();
}
void RenderPass::init(RenderTargetTexture* renderTarget, DepthBuffer* depthBuffer)
{
init();
setRenderTarget(0, renderTarget);
setDepthBuffer(depthBuffer);
}
void RenderPass::onDispose(bool explicitDisposing)
{
releaseRHI();
Object::onDispose(explicitDisposing);
}
void RenderPass::setRenderTarget(int index, RenderTargetTexture* value)
{
if (LN_REQUIRE(!m_active)) return;
if (LN_REQUIRE_RANGE(index, 0, GraphicsContext::MaxMultiRenderTargets)) return;
if (m_renderTargets[index] != value) {
m_renderTargets[index] = value;
m_dirty = true;
}
}
RenderTargetTexture* RenderPass::renderTarget(int index) const
{
if (LN_REQUIRE_RANGE(index, 0, GraphicsContext::MaxMultiRenderTargets)) return nullptr;
return m_renderTargets[index];
}
void RenderPass::setDepthBuffer(DepthBuffer* value)
{
if (LN_REQUIRE(!m_active)) return;
if (m_depthBuffer != value) {
m_depthBuffer = value;
m_dirty = true;
}
}
void RenderPass::setClearFlags(ClearFlags value)
{
if (LN_REQUIRE(!m_active)) return;
if (m_clearFlags != value) {
m_clearFlags = value;
m_dirty = true;
}
}
void RenderPass::setClearColor(const Color& value)
{
if (LN_REQUIRE(!m_active)) return;
if (m_clearColor != value) {
m_clearColor = value;
m_dirty = true;
}
}
void RenderPass::setClearDepth(float value)
{
if (LN_REQUIRE(!m_active)) return;
if (m_clearDepth != value) {
m_clearDepth = value;
m_dirty = true;
}
}
void RenderPass::setClearStencil(uint8_t value)
{
if (LN_REQUIRE(!m_active)) return;
if (m_clearStencil != value) {
m_clearStencil = value;
m_dirty = true;
}
}
void RenderPass::setClearValues(ClearFlags flags, const Color& color, float depth, uint8_t stencil)
{
if (LN_REQUIRE(!m_active)) return;
setClearFlags(flags);
setClearColor(color);
setClearDepth(depth);
setClearStencil(stencil);
}
DepthBuffer* RenderPass::depthBuffer() const
{
return m_depthBuffer;
}
void RenderPass::onChangeDevice(detail::IGraphicsDevice* device)
{
if (LN_REQUIRE(!m_active)) return;
if (!device) {
releaseRHI();
}
else {
m_dirty = true; // create with next resolveRHIObject
}
}
detail::IRenderPass* RenderPass::resolveRHIObject(GraphicsContext* context, bool* outModified)
{
if (m_dirty) {
releaseRHI();
m_dirty = false;
const RenderTargetTexture* primaryTarget = m_renderTargets[0];
if (LN_REQUIRE(primaryTarget, "RenderPass: [0] Invalid render target.")) return nullptr;
const Size primarySize(primaryTarget->width(), primaryTarget->height());
detail::NativeRenderPassCache::FindKey key;
for (auto i = 0; i < m_renderTargets.size(); i++) {
RenderTargetTexture* rt = m_renderTargets[i];
if (rt) {
if (LN_REQUIRE(rt->width() == primarySize.width && rt->height() == primarySize.height, u"RenderPass: Invalid render target dimensions.")) return nullptr;
}
key.renderTargets[i] = detail::GraphicsResourceInternal::resolveRHIObject<detail::RHIResource>(context, rt, nullptr);
}
key.depthBuffer = detail::GraphicsResourceInternal::resolveRHIObject<detail::IDepthBuffer>(context, m_depthBuffer, nullptr);
key.clearFlags = m_clearFlags;
key.clearColor = m_clearColor;
key.clearDepth = m_clearDepth;
key.clearStencil = m_clearStencil;
if (!m_renderTargets[0]->m_cleared && !testFlag(key.clearFlags, ClearFlags::Color)) {
key.clearFlags = Flags<ClearFlags>(key.clearFlags) | ClearFlags::Color;
m_dirty = true;
}
m_renderTargets[0]->m_cleared = true;
if (m_depthBuffer) {
if (LN_REQUIRE(m_depthBuffer->width() == primarySize.width && m_depthBuffer->height() == primarySize.height, u"RenderPass: Invalid depth buffer dimensions.")) return nullptr;
if (!m_depthBuffer->m_cleared && !testFlag(key.clearFlags, Flags<ClearFlags>(ClearFlags::Depth | ClearFlags::Stencil).get())) {
key.clearFlags = Flags<ClearFlags>(key.clearFlags) | ClearFlags::Depth | ClearFlags::Stencil;
m_dirty = true;
}
m_depthBuffer->m_cleared = true;
}
auto device = detail::GraphicsResourceInternal::manager(this)->deviceContext();
m_rhiObject = device->renderPassCache()->findOrCreate(key);
key.clearFlags = ClearFlags::None;
key.clearColor = Color(0, 0, 0, 0);
key.clearDepth = 1.0f;
key.clearStencil = 0x00;
m_rhiObjectNoClear = device->renderPassCache()->findOrCreate(key);
}
return m_rhiObject;
}
// [2019/10/5]
// GraphicsContext はデータ転送を遅延実行するため、各種 resolve (vkCmdCopyBuffer()) が呼ばれるタイミングが RenderPass の内側に入ってしまう。
//
// 多分グラフィックスAPIとして正しいであろう対策は、GraphicsContext に map, unmap, setData 等を実装して、resolve の遅延実行をやめること。
// ただ、dynamic なリソース更新するところすべてで GraphicsContext が必要になるので、描画に制限が多くなるし、GraphicsContext の取り回しを考えないとならない。
// 制限として厄介なのは DebugRendering. 各 onUpdate() の時点で何か描きたいときは GraphicsContext が確定していないのでいろいろ制約を考える必要がある。
// 特に、onUpdate 1度に対して複数 SwapChain から world を覗きたいときとか。
//
// もうひとつ、泥臭いけど今のところあまり時間掛けないで回避できるのが、この方法。
detail::IRenderPass* RenderPass::resolveRHIObjectNoClear(GraphicsContext* context, bool* outModified)
{
resolveRHIObject(context, outModified);
return m_rhiObjectNoClear;
}
void RenderPass::releaseRHI()
{
if (m_rhiObject) {
//auto device = detail::GraphicsResourceInternal::manager(this)->deviceContext();
//device->renderPassCache()->release(m_rhiObject);
m_rhiObject = nullptr;
}
}
////==============================================================================
//// RenderPassPool
//namespace detail {
//
//RenderPassPool::RenderPassPool(GraphicsManager* manager)
//{
//}
//
//RenderPass* RenderPassPool::findOrCreate(const FindKey& key)
//{
// uint64_t hash = computeHash(key);
// auto itr = m_hashMap.find(hash);
// if (itr != m_hashMap.end()) {
// return itr->second;
// }
// else {
// // TODO: Pool を使い切ったら、使っていないものを消す
//
// auto pipeline = m_device->createPipeline(key.renderPass, key.state);
// if (!pipeline) {
// return nullptr;
// }
//
// m_hashMap.insert({ hash, pipeline });
// return pipeline;
// }
//}
//
//uint64_t RenderPassPool::computeHash(const FindKey& key)
//{
//}
//
//} // namespace detail
} // namespace ln
| 7,388 | 2,945 |
// Date : 2019-03-26
// Author : Rahul Sharma
// Problem : http://codeforces.com/contest/6/problem/B
#include <iostream>
#include <string>
int main() {
using namespace std;
ios_base::sync_with_stdio(false);
cin.tie(0);
int n, m;
cin >> n >> m;
char p;
cin >> p;
char d[128] = {};
auto check = [&](const string& s) {
if (m > 1) {
if (s[0] == p)
d[s[1]] = 1;
if (s[m - 1] == p)
d[s[m - 2]] = 1;
}
for (int j = 1; j < m - 1; j++)
if (s[j] == p)
d[s[j - 1]] = d[s[j + 1]] = 1;
};
string s[2];
cin >> s[0];
check(s[0]);
for (int i = 1; i < n; i++) {
auto& top = s[1 - (i & 1)];
auto& bot = s[i & 1];
cin >> bot;
check(bot);
for (int j = 0; j < m; j++)
if (top[j] == p)
d[bot[j]] = 1;
else if (bot[j] == p)
d[top[j]] = 1;
}
int c = 0;
for (int i = 'A'; i <= 'Z'; i++)
if (i != p && d[i])
c++;
cout << c;
}
| 1,108 | 470 |
//
// Copyright 2017 Animal Logic
//
// 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 "AL/maya/utils/NodeHelper.h"
#include "AL/maya/utils/MayaHelperMacros.h"
#include "AL/maya/utils/DebugCodes.h"
#include "maya/MDataBlock.h"
#include "maya/MEulerRotation.h"
#include "maya/MFnCompoundAttribute.h"
#include "maya/MFnDependencyNode.h"
#include "maya/MFnEnumAttribute.h"
#include "maya/MFnMatrixAttribute.h"
#include "maya/MFnMessageAttribute.h"
#include "maya/MFnPluginData.h"
#include "maya/MFnStringData.h"
#include "maya/MFnTypedAttribute.h"
#include "maya/MFnUnitAttribute.h"
#include "maya/MGlobal.h"
#include "maya/MMatrix.h"
#include "maya/MPxNode.h"
#include "maya/MTime.h"
#include <cassert>
#include <iostream>
#include <sstream>
#include <cctype>
namespace AL {
namespace maya {
namespace utils {
//----------------------------------------------------------------------------------------------------------------------
// takes an attribute name such as "thisIsAnAttribute" and turns it into "This Is An Attribute". Just used to make the
// attributes a little bit more readable in the Attribute Editor GUI.
//----------------------------------------------------------------------------------------------------------------------
std::string beautifyAttrName(std::string attrName)
{
if(std::islower(attrName[0]))
{
attrName[0] = std::toupper(attrName[0]);
}
for(size_t i = 1; i < attrName.size(); ++i)
{
if(std::isupper(attrName[i]))
{
attrName.insert(i++, 1, ' ');
}
}
return attrName;
}
//----------------------------------------------------------------------------------------------------------------------
/// \brief A little code generator that outputs the custom AE gui needed to handle file path attributes.
/// \param nodeName type name of the node
/// \param attrName the name of the file path attribute
/// \param fileFilter a filter string of the form: "USD Files (*.usd*) (*.usd*);;Alembic Files (*.abc)"
//----------------------------------------------------------------------------------------------------------------------
void constructFilePathUi(
std::ostringstream& oss,
const std::string& nodeName,
const std::string& attrName,
const std::string& fileFilter,
const NodeHelper::FileMode mode)
{
// generate code to create a file attribute GUI (with button to click to load the file)
oss << "global proc AE" << nodeName << "Template_" << attrName << "New(string $anAttr) {\n";
oss << " setUITemplate -pushTemplate attributeEditorTemplate;\n";
oss << " rowLayout -numberOfColumns 3;\n";
oss << " text -label \"" << beautifyAttrName(attrName) << "\";\n";
oss << " textField " << attrName << "FilePathField;\n";
oss << " symbolButton -image \"navButtonBrowse.xpm\" " << attrName << "FileBrowserButton;\n";
oss << " setParent ..;\n";
oss << " AE" << nodeName << "Template_" << attrName << "Replace($anAttr);\n";
oss << " setUITemplate -popTemplate;\n";
oss << "}\n";
// generate the method that will replace the value in the control when another node of the same type is selected
oss << "global proc AE" << nodeName << "Template_" << attrName << "Replace(string $anAttr) {\n";
oss << " evalDeferred (\"connectControl " << attrName << "FilePathField \" + $anAttr);\n";
oss << " button -edit -command (\"AE" << nodeName << "Template_" << attrName << "FileBrowser \" + $anAttr) " << attrName << "FileBrowserButton;\n";
oss << "}\n";
// generate the button callback that will actually create the file dialog for our attribute.
// Depending on the fileMode used, we may end up having more than one filename, which will be munged
// together with a semi-colon as the seperator. It's arguably a little wasteful to retain the code that
// munges together multiple paths when using a single file select mode. Meh. :)
oss << "global proc AE" << nodeName << "Template_" << attrName << "FileBrowser(string $anAttr) {\n";
oss << " string $fileNames[] = `fileDialog2 -caption \"Specify " << beautifyAttrName(attrName) << "\"";
if(!fileFilter.empty())
{
oss << " -fileFilter \"" << fileFilter << "\"";
}
oss << " -fileMode " << mode << "`;\n";
oss << " if (size($fileNames) > 0) {\n";
oss << " string $concatonated = $fileNames[0];\n";
oss << " for($ii=1; $ii < size($fileNames); ++$ii) $concatonated += (\";\" + $fileNames[$ii]);\n";
oss << " evalEcho (\"setAttr -type \\\"string\\\" \" + $anAttr + \" \\\"\" + $concatonated + \"\\\"\");\n";
oss << " }\n";
oss << "}\n";
}
//----------------------------------------------------------------------------------------------------------------------
NodeHelper::InternalData* NodeHelper::m_internal = 0;
//----------------------------------------------------------------------------------------------------------------------
void NodeHelper::setNodeType(const MString& typeName)
{
if(!m_internal)
{
m_internal = new InternalData;
}
m_internal->m_typeBeingRegistered = typeName.asChar();
}
//----------------------------------------------------------------------------------------------------------------------
void NodeHelper::addFrame(const char* frameTitle)
{
if(!m_internal)
m_internal = new InternalData;
m_internal->m_frames.push_front(Frame(frameTitle));
}
//----------------------------------------------------------------------------------------------------------------------
void NodeHelper::addInheritedAttr(const char* longName)
{
if(m_internal)
{
Frame& frame = *m_internal->m_frames.begin();
frame.m_attributes.push_back(longName);
frame.m_attributeTypes.push_back(Frame::kNormal);
}
}
//----------------------------------------------------------------------------------------------------------------------
MObject NodeHelper::addEnumAttr(const char* longName, const char* shortName, uint32_t flags, const char* const * strings, const int16_t* values)
{
if(m_internal)
{
Frame& frame = *m_internal->m_frames.begin();
if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode))
{
frame.m_attributes.push_back(longName);
frame.m_attributeTypes.push_back(Frame::kNormal);
}
}
MFnEnumAttribute fn;
MObject attribute = fn.create(longName, shortName, MFnData::kString);
while(*strings)
{
fn.addField(*strings, *values);
++values;
++strings;
}
fn.setDefault(0);
MStatus status = applyAttributeFlags(fn, flags);
if(!status)
throw status;
return attribute;
}
//----------------------------------------------------------------------------------------------------------------------
MObject NodeHelper::addMeshAttr(const char* longName, const char* shortName, uint32_t flags)
{
MFnTypedAttribute fn;
MStatus status;
MObject attr = fn.create(longName, shortName, MFnData::kMesh, MObject::kNullObj, &status);
if(!status)
throw status;
status = applyAttributeFlags(fn, flags);
if(!status)
throw status;
return attr;
}
//----------------------------------------------------------------------------------------------------------------------
MObject NodeHelper::addStringAttr(const char* longName, const char* shortName, uint32_t flags, bool forceShow)
{
return addStringAttr(longName, shortName, "", flags, forceShow);
}
//----------------------------------------------------------------------------------------------------------------------
MObject NodeHelper::addStringAttr(const char* longName, const char* shortName, const char* defaultValue, uint32_t flags, bool forceShow)
{
if(m_internal)
{
Frame& frame = *m_internal->m_frames.begin();
if(forceShow || ((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode)))
{
frame.m_attributes.push_back(longName);
frame.m_attributeTypes.push_back(Frame::kNormal);
}
}
MFnTypedAttribute fn;
MFnStringData stringData;
MStatus stat;
MObject attribute = fn.create(longName, shortName, MFnData::kString, stringData.create(MString(defaultValue), &stat));
MStatus status = applyAttributeFlags(fn, flags);
if(!status)
throw status;
return attribute;
}
//----------------------------------------------------------------------------------------------------------------------
MObject NodeHelper::addFilePathAttr(const char* longName, const char* shortName, uint32_t flags, FileMode fileMode, const char* fileFilter)
{
if(m_internal)
{
Frame& frame = *m_internal->m_frames.begin();
if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode))
{
frame.m_attributes.push_back(longName);
frame.m_fileFilters.push_back(fileFilter);
frame.m_attributeTypes.push_back((Frame::AttributeUiType)fileMode);
}
}
MFnTypedAttribute fn;
MObject attribute = fn.create(longName, shortName, MFnData::kString);
MStatus status = applyAttributeFlags(fn, flags);
if(!status)
throw status;
return attribute;
}
//----------------------------------------------------------------------------------------------------------------------
MObject NodeHelper::addInt8Attr(const char* longName, const char* shortName, int8_t defaultValue, uint32_t flags)
{
if(m_internal)
{
Frame& frame = *m_internal->m_frames.begin();
if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode))
{
frame.m_attributes.push_back(longName);
frame.m_attributeTypes.push_back(Frame::kNormal);
}
}
MFnNumericAttribute fn;
MObject attribute = fn.create(longName, shortName, MFnNumericData::kChar, defaultValue);
MStatus status = applyAttributeFlags(fn, flags);
if(!status)
throw status;
return attribute;
}
//----------------------------------------------------------------------------------------------------------------------
MObject NodeHelper::addInt16Attr(const char* longName, const char* shortName, int16_t defaultValue, uint32_t flags)
{
if(m_internal)
{
Frame& frame = *m_internal->m_frames.begin();
if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode))
{
frame.m_attributes.push_back(longName);
frame.m_attributeTypes.push_back(Frame::kNormal);
}
}
MFnNumericAttribute fn;
MObject attribute = fn.create(longName, shortName, MFnNumericData::kShort, defaultValue);
MStatus status = applyAttributeFlags(fn, flags);
if(!status)
throw status;
return attribute;
}
//----------------------------------------------------------------------------------------------------------------------
MObject NodeHelper::addInt32Attr(const char* longName, const char* shortName, int32_t defaultValue, uint32_t flags)
{
if(m_internal)
{
Frame& frame = *m_internal->m_frames.begin();
if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode))
{
frame.m_attributes.push_back(longName);
frame.m_attributeTypes.push_back(Frame::kNormal);
}
}
MFnNumericAttribute fn;
MObject attribute = fn.create(longName, shortName, MFnNumericData::kInt, defaultValue);
MStatus status = applyAttributeFlags(fn, flags);
if(!status)
throw status;
return attribute;
}
//----------------------------------------------------------------------------------------------------------------------
MObject NodeHelper::addInt64Attr(const char* longName, const char* shortName, int64_t defaultValue, uint32_t flags)
{
if(m_internal)
{
Frame& frame = *m_internal->m_frames.begin();
if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode))
{
frame.m_attributes.push_back(longName);
frame.m_attributeTypes.push_back(Frame::kNormal);
}
}
MFnNumericAttribute fn;
MObject attribute = fn.create(longName, shortName, MFnNumericData::kInt64, defaultValue);
MStatus status = applyAttributeFlags(fn, flags);
if(!status)
throw status;
return attribute;
}
//----------------------------------------------------------------------------------------------------------------------
MObject NodeHelper::addFloatAttr(const char* longName, const char* shortName, float defaultValue, uint32_t flags)
{
if(m_internal)
{
Frame& frame = *m_internal->m_frames.begin();
if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode))
{
frame.m_attributes.push_back(longName);
frame.m_attributeTypes.push_back(Frame::kNormal);
}
}
MFnNumericAttribute fn;
MObject attribute = fn.create(longName, shortName, MFnNumericData::kFloat, defaultValue);
MStatus status = applyAttributeFlags(fn, flags);
if(!status)
throw status;
return attribute;
}
//----------------------------------------------------------------------------------------------------------------------
MObject NodeHelper::addTimeAttr(const char* longName, const char* shortName, const MTime& defaultValue, uint32_t flags)
{
if(m_internal)
{
Frame& frame = *m_internal->m_frames.begin();
if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode))
{
frame.m_attributes.push_back(longName);
frame.m_attributeTypes.push_back(Frame::kNormal);
}
}
MFnUnitAttribute fn;
MObject attribute = fn.create(longName, shortName, defaultValue);
MStatus status = applyAttributeFlags(fn, flags);
if(!status)
throw status;
return attribute;
}
//----------------------------------------------------------------------------------------------------------------------
MObject NodeHelper::addDistanceAttr(const char* longName, const char* shortName, const MDistance& defaultValue, uint32_t flags)
{
if(m_internal)
{
Frame& frame = *m_internal->m_frames.begin();
if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode))
{
frame.m_attributes.push_back(longName);
frame.m_attributeTypes.push_back(Frame::kNormal);
}
}
MFnUnitAttribute fn;
MObject attribute = fn.create(longName, shortName, defaultValue);
MStatus status = applyAttributeFlags(fn, flags);
if(!status)
throw status;
return attribute;
}
//----------------------------------------------------------------------------------------------------------------------
MObject NodeHelper::addAngleAttr(const char* longName, const char* shortName, const MAngle& defaultValue, uint32_t flags)
{
if(m_internal)
{
Frame& frame = *m_internal->m_frames.begin();
if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode))
{
frame.m_attributes.push_back(longName);
frame.m_attributeTypes.push_back(Frame::kNormal);
}
}
MFnUnitAttribute fn;
MObject attribute = fn.create(longName, shortName, defaultValue);
MStatus status = applyAttributeFlags(fn, flags);
if(!status)
throw status;
return attribute;
}
//----------------------------------------------------------------------------------------------------------------------
MObject NodeHelper::addFloatArrayAttr(const MObject& node, const char* longName, const char* shortName, uint32_t flags)
{
if(m_internal)
{
Frame& frame = *m_internal->m_frames.begin();
if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode))
{
frame.m_attributes.push_back(longName);
frame.m_attributeTypes.push_back(Frame::kNormal);
}
}
MStatus status;
MFnTypedAttribute fnAttr;
MString ln (longName);
MString sn (shortName);
MObject attribute = fnAttr.create(ln, sn, MFnData::kFloatArray, MObject::kNullObj, &status);
if(status != MS::kSuccess)
{
MGlobal::displayWarning("addFloatArrayAttr:Failed to create attribute");
}
applyAttributeFlags(fnAttr, flags);
MFnDependencyNode fn(node, &status);
if(!status)
{
throw status;
}
status = fn.addAttribute(attribute);
if(status != MS::kSuccess)
MGlobal::displayWarning(MString("addFloatArrayAttr::addAttribute: ") + MString(status.errorString()));
return attribute;
}
//----------------------------------------------------------------------------------------------------------------------
MObject NodeHelper::addDoubleAttr(const char* longName, const char* shortName, double defaultValue, uint32_t flags)
{
if(m_internal)
{
Frame& frame = *m_internal->m_frames.begin();
if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode))
{
frame.m_attributes.push_back(longName);
frame.m_attributeTypes.push_back(Frame::kNormal);
}
}
MFnNumericAttribute fn;
MObject attribute = fn.create(longName, shortName, MFnNumericData::kDouble, defaultValue);
MStatus status = applyAttributeFlags(fn, flags);
if(!status)
throw status;
return attribute;
}
//----------------------------------------------------------------------------------------------------------------------
MObject NodeHelper::addBoolAttr(const char* longName, const char* shortName, bool defaultValue, uint32_t flags)
{
if(m_internal)
{
Frame& frame = *m_internal->m_frames.begin();
if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode))
{
frame.m_attributes.push_back(longName);
frame.m_attributeTypes.push_back(Frame::kNormal);
}
}
MFnNumericAttribute fn;
MObject attribute = fn.create(longName, shortName, MFnNumericData::kBoolean, defaultValue);
MStatus status = applyAttributeFlags(fn, flags);
if(!status)
throw status;
return attribute;
}
//----------------------------------------------------------------------------------------------------------------------
MObject NodeHelper::addFloat3Attr(const char* longName, const char* shortName, float defaultX, float defaultY, float defaultZ, uint32_t flags)
{
if(m_internal)
{
Frame& frame = *m_internal->m_frames.begin();
if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode))
{
frame.m_attributes.push_back(longName);
frame.m_attributeTypes.push_back(Frame::kNormal);
}
}
MFnNumericAttribute fn;
MObject attribute;
if(flags & kColour)
{
attribute = fn.createColor(longName, shortName);
fn.setDefault(defaultX, defaultY, defaultZ);
}
else
{
MString ln(longName);
MString sn(shortName);
MObject x = fn.create(ln + "X", sn + "x", MFnNumericData::kFloat, defaultX);
MObject y = fn.create(ln + "Y", sn + "y", MFnNumericData::kFloat, defaultY);
MObject z = fn.create(ln + "Z", sn + "z", MFnNumericData::kFloat, defaultZ);
attribute = fn.create(ln, sn, x, y, z);
}
MStatus status = applyAttributeFlags(fn, flags);
if(!status)
throw status;
return attribute;
}
//----------------------------------------------------------------------------------------------------------------------
MObject NodeHelper::addPointAttr(const char* longName, const char* shortName, const MPoint& defaultValue, uint32_t flags)
{
if(m_internal)
{
Frame& frame = *m_internal->m_frames.begin();
if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode))
{
frame.m_attributes.push_back(longName);
frame.m_attributeTypes.push_back(Frame::kNormal);
}
}
MFnNumericAttribute fn;
MObject attribute;
attribute = fn.createPoint(longName, shortName);
fn.setDefault(defaultValue.x, defaultValue.y, defaultValue.z);
MStatus status = applyAttributeFlags(fn, flags);
if(!status)
throw status;
return attribute;
}
//----------------------------------------------------------------------------------------------------------------------
MObject NodeHelper::addVectorAttr(const char* longName, const char* shortName, const MVector& defaultValue, uint32_t flags)
{
if(m_internal)
{
Frame& frame = *m_internal->m_frames.begin();
if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode))
{
frame.m_attributes.push_back(longName);
frame.m_attributeTypes.push_back(Frame::kNormal);
}
}
MFnNumericAttribute fn;
MObject attribute;
MString ln(longName);
MString sn(shortName);
MObject x = fn.create(ln + "X", sn + "x", MFnNumericData::kDouble, defaultValue.x);
MObject y = fn.create(ln + "Y", sn + "y", MFnNumericData::kDouble, defaultValue.y);
MObject z = fn.create(ln + "Z", sn + "z", MFnNumericData::kDouble, defaultValue.z);
attribute = fn.create(ln, sn, x, y, z);
MStatus status = applyAttributeFlags(fn, flags);
if(!status)
throw status;
return attribute;
}
//----------------------------------------------------------------------------------------------------------------------
MObject NodeHelper::addAngle3Attr(const char* longName, const char* shortName, float defaultX, float defaultY, float defaultZ, uint32_t flags)
{
if(m_internal)
{
Frame& frame = *m_internal->m_frames.begin();
if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode))
{
frame.m_attributes.push_back(longName);
frame.m_attributeTypes.push_back(Frame::kNormal);
}
}
MFnUnitAttribute fnu;
MFnNumericAttribute fn;
MObject attribute;
MString ln(longName);
MString sn(shortName);
MObject x = fnu.create(ln + "X", sn + "x", MFnUnitAttribute::kAngle, defaultX);
MObject y = fnu.create(ln + "Y", sn + "y", MFnUnitAttribute::kAngle, defaultY);
MObject z = fnu.create(ln + "Z", sn + "z", MFnUnitAttribute::kAngle, defaultZ);
attribute = fn.create(ln, sn, x, y, z);
MStatus status = applyAttributeFlags(fn, flags);
if(!status)
throw status;
return attribute;
}
//----------------------------------------------------------------------------------------------------------------------
MObject NodeHelper::addDistance3Attr(const char* longName, const char* shortName, float defaultX, float defaultY, float defaultZ, uint32_t flags)
{
if(m_internal)
{
Frame& frame = *m_internal->m_frames.begin();
if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode))
{
frame.m_attributes.push_back(longName);
frame.m_attributeTypes.push_back(Frame::kNormal);
}
}
MFnUnitAttribute fnu;
MFnNumericAttribute fn;
MObject attribute;
MString ln(longName);
MString sn(shortName);
MObject x = fnu.create(ln + "X", sn + "x", MFnUnitAttribute::kDistance, defaultX);
MObject y = fnu.create(ln + "Y", sn + "y", MFnUnitAttribute::kDistance, defaultY);
MObject z = fnu.create(ln + "Z", sn + "z", MFnUnitAttribute::kDistance, defaultZ);
attribute = fn.create(ln, sn, x, y, z);
MStatus status = applyAttributeFlags(fn, flags);
if(!status)
throw status;
return attribute;
}
//----------------------------------------------------------------------------------------------------------------------
MObject NodeHelper::addMatrixAttr(const char* longName, const char* shortName, const MMatrix& defaultValue, uint32_t flags)
{
if(m_internal)
{
Frame& frame = *m_internal->m_frames.begin();
if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode))
{
frame.m_attributes.push_back(longName);
frame.m_attributeTypes.push_back(Frame::kNormal);
}
}
MFnMatrixAttribute fn;
MObject attribute;
attribute = fn.create(longName, shortName, MFnMatrixAttribute::kDouble);
fn.setDefault(defaultValue);
MStatus status = applyAttributeFlags(fn, flags);
if(!status)
throw status;
return attribute;
}
//----------------------------------------------------------------------------------------------------------------------
MObject NodeHelper::addMatrix3x3Attr(const char* longName, const char* shortName, const float defaultValue[3][3], uint32_t flags)
{
if(m_internal)
{
Frame& frame = *m_internal->m_frames.begin();
if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode))
{
frame.m_attributes.push_back(longName);
frame.m_attributeTypes.push_back(Frame::kNormal);
}
}
MFnNumericAttribute fn;
MFnCompoundAttribute fnc;
MString ln(longName);
MString sn(shortName);
MObject xx = fn.create(ln + "XX", sn + "xx", MFnNumericData::kFloat, defaultValue[0][0]);
MObject xy = fn.create(ln + "XY", sn + "xy", MFnNumericData::kFloat, defaultValue[0][1]);
MObject xz = fn.create(ln + "XZ", sn + "xz", MFnNumericData::kFloat, defaultValue[0][2]);
MObject yx = fn.create(ln + "YX", sn + "yx", MFnNumericData::kFloat, defaultValue[1][0]);
MObject yy = fn.create(ln + "YY", sn + "yy", MFnNumericData::kFloat, defaultValue[1][1]);
MObject yz = fn.create(ln + "YZ", sn + "yz", MFnNumericData::kFloat, defaultValue[1][2]);
MObject zx = fn.create(ln + "ZX", sn + "zx", MFnNumericData::kFloat, defaultValue[2][0]);
MObject zy = fn.create(ln + "ZY", sn + "zy", MFnNumericData::kFloat, defaultValue[2][1]);
MObject zz = fn.create(ln + "ZZ", sn + "zz", MFnNumericData::kFloat, defaultValue[2][2]);
MObject x = fnc.create(ln + "X", sn + "x");
fnc.addChild(xx);
fnc.addChild(xy);
fnc.addChild(xz);
MObject y = fnc.create(ln + "Y", sn + "y");
fnc.addChild(yx);
fnc.addChild(yy);
fnc.addChild(yz);
MObject z = fnc.create(ln + "Z", sn + "z");
fnc.addChild(zx);
fnc.addChild(zy);
fnc.addChild(zz);
MObject attribute = fnc.create(ln, sn);
fnc.addChild(x);
fnc.addChild(y);
fnc.addChild(z);
MStatus status = applyAttributeFlags(fnc, flags);
if(!status)
throw status;
return attribute;
}
//----------------------------------------------------------------------------------------------------------------------
MObject NodeHelper::addMatrix2x2Attr(const char* longName, const char* shortName, const float defaultValue[2][2], uint32_t flags)
{
if(m_internal)
{
Frame& frame = *m_internal->m_frames.begin();
if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode))
{
frame.m_attributes.push_back(longName);
frame.m_attributeTypes.push_back(Frame::kNormal);
}
}
MFnNumericAttribute fn;
MFnCompoundAttribute fnc;
MString ln(longName);
MString sn(shortName);
MObject xx = fn.create(ln + "XX", sn + "xx", MFnNumericData::kFloat, defaultValue[0][0]);
MObject xy = fn.create(ln + "XY", sn + "xy", MFnNumericData::kFloat, defaultValue[0][1]);
MObject yx = fn.create(ln + "YX", sn + "yx", MFnNumericData::kFloat, defaultValue[1][0]);
MObject yy = fn.create(ln + "YY", sn + "yy", MFnNumericData::kFloat, defaultValue[1][1]);
MObject x = fnc.create(ln + "X", sn + "x");
fnc.addChild(xx);
fnc.addChild(xy);
MObject y = fnc.create(ln + "Y", sn + "y");
fnc.addChild(yx);
fnc.addChild(yy);
MObject attribute = fnc.create(ln, sn);
fnc.addChild(x);
fnc.addChild(y);
MStatus status = applyAttributeFlags(fnc, flags);
if(!status)
throw status;
return attribute;
}
//----------------------------------------------------------------------------------------------------------------------
MObject NodeHelper::addDataAttr(const char* longName, const char* shortName, MFnData::Type type, uint32_t flags, MFnAttribute::DisconnectBehavior behaviour)
{
MFnTypedAttribute fn;
MObject attribute = fn.create(longName, shortName, type);
fn.setDisconnectBehavior(behaviour);
MStatus status = applyAttributeFlags(fn, flags | kHidden);
if(!status)
throw status;
return attribute;
}
//----------------------------------------------------------------------------------------------------------------------
MObject NodeHelper::addDataAttr(const char* longName, const char* shortName, const MTypeId& type, uint32_t flags, MFnAttribute::DisconnectBehavior behaviour)
{
MFnTypedAttribute fn;
MObject attribute = fn.create(longName, shortName, type);
fn.setDisconnectBehavior(behaviour);
MStatus status = applyAttributeFlags(fn, flags | kHidden);
if(!status)
throw status;
return attribute;
}
//----------------------------------------------------------------------------------------------------------------------
MObject NodeHelper::addMessageAttr(const char* longName, const char* shortName, uint32_t flags)
{
MFnMessageAttribute fn;
MStatus status;
MObject attribute = fn.create(longName, shortName, &status);
status = applyAttributeFlags(fn, flags | kHidden);
if(!status)
throw status;
return attribute;
}
//----------------------------------------------------------------------------------------------------------------------
MObject NodeHelper::addVec2fAttr(const char* longName, const char* shortName, uint32_t flags)
{
if(m_internal)
{
Frame& frame = *m_internal->m_frames.begin();
if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode))
{
frame.m_attributes.push_back(longName);
frame.m_attributeTypes.push_back(Frame::kNormal);
}
}
MFnNumericAttribute fn;
MObject attribute;
MString ln(longName);
MString sn(shortName);
MObject x = fn.create(ln + "X", sn + "x", MFnNumericData::kFloat, 0);
MObject y = fn.create(ln + "Y", sn + "y", MFnNumericData::kFloat, 0);
attribute = fn.create(ln, sn, x, y);
MStatus status = applyAttributeFlags(fn, flags);
if(!status)
throw status;
return attribute;
}
//----------------------------------------------------------------------------------------------------------------------
MObject NodeHelper::addVec2iAttr(const char* longName, const char* shortName, uint32_t flags)
{
if(m_internal)
{
Frame& frame = *m_internal->m_frames.begin();
if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode))
{
frame.m_attributes.push_back(longName);
frame.m_attributeTypes.push_back(Frame::kNormal);
}
}
MFnNumericAttribute fn;
MObject attribute;
MString ln(longName);
MString sn(shortName);
MObject x = fn.create(ln + "X", sn + "x", MFnNumericData::kLong, 0);
MObject y = fn.create(ln + "Y", sn + "y", MFnNumericData::kLong, 0);
attribute = fn.create(ln, sn, x, y);
MStatus status = applyAttributeFlags(fn, flags);
if(!status)
throw status;
return attribute;
}
//----------------------------------------------------------------------------------------------------------------------
MObject NodeHelper::addVec2dAttr(const char* longName, const char* shortName, uint32_t flags)
{
if(m_internal)
{
Frame& frame = *m_internal->m_frames.begin();
if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode))
{
frame.m_attributes.push_back(longName);
frame.m_attributeTypes.push_back(Frame::kNormal);
}
}
MFnNumericAttribute fn;
MObject attribute;
MString ln(longName);
MString sn(shortName);
MObject x = fn.create(ln + "X", sn + "x", MFnNumericData::kDouble, 0);
MObject y = fn.create(ln + "Y", sn + "y", MFnNumericData::kDouble, 0);
attribute = fn.create(ln, sn, x, y);
MStatus status = applyAttributeFlags(fn, flags);
if(!status)
throw status;
return attribute;
}
//----------------------------------------------------------------------------------------------------------------------
MObject NodeHelper::addDoubleArrayAttr(const MObject& node, const char* longName, const char* shortName, uint32_t flags)
{
if(m_internal)
{
Frame& frame = *m_internal->m_frames.begin();
if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode))
{
frame.m_attributes.push_back(longName);
frame.m_attributeTypes.push_back(Frame::kNormal);
}
}
MStatus status;
MFnTypedAttribute fnAttr;
MString ln (longName);
MString sn (shortName);
MObject attribute = fnAttr.create(ln, sn, MFnData::kDoubleArray, MObject::kNullObj, &status);
if(status != MS::kSuccess)
{
MGlobal::displayWarning("addDoubleArrayAttr:Failed to create attribute");
}
applyAttributeFlags(fnAttr, flags);
MFnDependencyNode fn(node, &status);
if(!status)
{
throw status;
}
status = fn.addAttribute(attribute);
if(status != MS::kSuccess)
MGlobal::displayWarning(MString("addDoubleArrayAttr::addAttribute: ") + MString(status.errorString()));
return attribute;
}
//----------------------------------------------------------------------------------------------------------------------
MObject NodeHelper::addVec3fAttr(const char* longName, const char* shortName, uint32_t flags)
{
if(m_internal)
{
Frame& frame = *m_internal->m_frames.begin();
if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode))
{
frame.m_attributes.push_back(longName);
frame.m_attributeTypes.push_back(Frame::kNormal);
}
}
MFnNumericAttribute fn;
MObject attribute;
MString ln(longName);
MString sn(shortName);
MObject x = fn.create(ln + "X", sn + "x", MFnNumericData::kFloat, 0);
MObject y = fn.create(ln + "Y", sn + "y", MFnNumericData::kFloat, 0);
MObject z = fn.create(ln + "Z", sn + "z", MFnNumericData::kFloat, 0);
attribute = fn.create(ln, sn, x, y, z);
MStatus status = applyAttributeFlags(fn, flags);
if(!status)
throw status;
return attribute;
}
//----------------------------------------------------------------------------------------------------------------------
MObject NodeHelper::addVec3iAttr(const char* longName, const char* shortName, uint32_t flags)
{
if(m_internal)
{
Frame& frame = *m_internal->m_frames.begin();
if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode))
{
frame.m_attributes.push_back(longName);
frame.m_attributeTypes.push_back(Frame::kNormal);
}
}
MFnNumericAttribute fn;
MObject attribute;
MString ln(longName);
MString sn(shortName);
MObject x = fn.create(ln + "X", sn + "x", MFnNumericData::kInt, 0);
MObject y = fn.create(ln + "Y", sn + "y", MFnNumericData::kInt, 0);
MObject z = fn.create(ln + "Z", sn + "z", MFnNumericData::kInt, 0);
attribute = fn.create(ln, sn, x, y, z);
MStatus status = applyAttributeFlags(fn, flags);
if(!status)
throw status;
return attribute;
}
//----------------------------------------------------------------------------------------------------------------------
MObject NodeHelper::addVec3dAttr(const char* longName, const char* shortName, uint32_t flags)
{
if(m_internal)
{
Frame& frame = *m_internal->m_frames.begin();
if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode))
{
frame.m_attributes.push_back(longName);
frame.m_attributeTypes.push_back(Frame::kNormal);
}
}
MFnNumericAttribute fn;
MObject attribute;
MString ln(longName);
MString sn(shortName);
MObject x = fn.create(ln + "X", sn + "x", MFnNumericData::kDouble, 0);
MObject y = fn.create(ln + "Y", sn + "y", MFnNumericData::kDouble, 0);
MObject z = fn.create(ln + "Z", sn + "z", MFnNumericData::kDouble, 0);
attribute = fn.create(ln, sn, x, y, z);
MStatus status = applyAttributeFlags(fn, flags);
if(!status)
throw status;
return attribute;
}
//----------------------------------------------------------------------------------------------------------------------
MObject NodeHelper::addVec4fAttr(const char* longName, const char* shortName, uint32_t flags)
{
if(m_internal)
{
Frame& frame = *m_internal->m_frames.begin();
if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode))
{
frame.m_attributes.push_back(longName);
frame.m_attributeTypes.push_back(Frame::kNormal);
}
}
MFnNumericAttribute fn;
MFnCompoundAttribute fnc;
MObject attribute;
MString ln(longName);
MString sn(shortName);
MObject x = fn.create(ln + "X", sn + "x", MFnNumericData::kFloat, 0);
MObject y = fn.create(ln + "Y", sn + "y", MFnNumericData::kFloat, 0);
MObject z = fn.create(ln + "Z", sn + "z", MFnNumericData::kFloat, 0);
MObject w = fn.create(ln + "W", sn + "w", MFnNumericData::kFloat, 0);
attribute = fnc.create(ln, sn);
AL_MAYA_CHECK_ERROR2(fnc.addChild(x), "could not add x");
AL_MAYA_CHECK_ERROR2(fnc.addChild(y), "could not add y");
AL_MAYA_CHECK_ERROR2(fnc.addChild(z), "could not add z");
AL_MAYA_CHECK_ERROR2(fnc.addChild(w), "could not add w");
MStatus status = applyAttributeFlags(fnc, flags);
if(!status)
throw status;
return attribute;
}
//----------------------------------------------------------------------------------------------------------------------
MObject NodeHelper::addVec4iAttr(const char* longName, const char* shortName, uint32_t flags)
{
if(m_internal)
{
Frame& frame = *m_internal->m_frames.begin();
if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode))
{
frame.m_attributes.push_back(longName);
frame.m_attributeTypes.push_back(Frame::kNormal);
}
}
MFnNumericAttribute fn;
MFnCompoundAttribute fnc;
MObject attribute;
MString ln(longName);
MString sn(shortName);
MObject x = fn.create(ln + "X", sn + "x", MFnNumericData::kLong, 0);
MObject y = fn.create(ln + "Y", sn + "y", MFnNumericData::kLong, 0);
MObject z = fn.create(ln + "Z", sn + "z", MFnNumericData::kLong, 0);
MObject w = fn.create(ln + "W", sn + "w", MFnNumericData::kLong, 0);
attribute = fnc.create(ln, sn);
AL_MAYA_CHECK_ERROR2(fnc.addChild(x), "could not add x");
AL_MAYA_CHECK_ERROR2(fnc.addChild(y), "could not add y");
AL_MAYA_CHECK_ERROR2(fnc.addChild(z), "could not add z");
AL_MAYA_CHECK_ERROR2(fnc.addChild(w), "could not add w");
MStatus status = applyAttributeFlags(fnc, flags);
if(!status)
throw status;
return attribute;
}
//----------------------------------------------------------------------------------------------------------------------
MObject NodeHelper::addVec4dAttr(const char* longName, const char* shortName, uint32_t flags)
{
if(m_internal)
{
Frame& frame = *m_internal->m_frames.begin();
if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode))
{
frame.m_attributes.push_back(longName);
frame.m_attributeTypes.push_back(Frame::kNormal);
}
}
MFnNumericAttribute fn;
MFnCompoundAttribute fnc;
MObject attribute;
MString ln(longName);
MString sn(shortName);
MObject x = fn.create(ln + "X", sn + "x", MFnNumericData::kDouble, 0);
MObject y = fn.create(ln + "Y", sn + "y", MFnNumericData::kDouble, 0);
MObject z = fn.create(ln + "Z", sn + "z", MFnNumericData::kDouble, 0);
MObject w = fn.create(ln + "W", sn + "w", MFnNumericData::kDouble, 0);
attribute = fnc.create(ln, sn);
AL_MAYA_CHECK_ERROR2(fnc.addChild(x), "could not add x");
AL_MAYA_CHECK_ERROR2(fnc.addChild(y), "could not add y");
AL_MAYA_CHECK_ERROR2(fnc.addChild(z), "could not add z");
AL_MAYA_CHECK_ERROR2(fnc.addChild(w), "could not add w");
MStatus status = applyAttributeFlags(fnc, flags);
if(!status)
throw status;
return attribute;
}
//----------------------------------------------------------------------------------------------------------------------
MObject NodeHelper::addCompoundAttr(const char* longName, const char* shortName, uint32_t flags, std::initializer_list<MObject> objs)
{
if(m_internal)
{
Frame& frame = *m_internal->m_frames.begin();
if((flags & kWritable) && !(flags & kHidden) && !(flags & kDontAddToNode))
{
frame.m_attributes.push_back(longName);
frame.m_attributeTypes.push_back(Frame::kNormal);
}
}
MFnCompoundAttribute fn;
MObject obj = fn.create(longName, shortName);
for(auto it : objs)
{
MStatus status = fn.addChild(it);
if(!status)
throw status;
}
MStatus status = applyAttributeFlags(fn, flags);
if(!status)
throw status;
return obj;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus NodeHelper::applyAttributeFlags(MFnAttribute& fn, uint32_t flags)
{
const char* const errorString = "NodeHelper::applyAttributeFlags";
AL_MAYA_CHECK_ERROR(fn.setCached((flags & kCached) != 0), errorString);
AL_MAYA_CHECK_ERROR(fn.setReadable((flags & kReadable) != 0), errorString);
AL_MAYA_CHECK_ERROR(fn.setStorable((flags & kStorable) != 0), errorString);
AL_MAYA_CHECK_ERROR(fn.setWritable((flags & kWritable) != 0), errorString);
AL_MAYA_CHECK_ERROR(fn.setAffectsAppearance((flags & kAffectsAppearance) != 0), errorString);
AL_MAYA_CHECK_ERROR(fn.setKeyable((flags & kKeyable) != 0), errorString);
AL_MAYA_CHECK_ERROR(fn.setConnectable((flags & kConnectable) != 0), errorString);
AL_MAYA_CHECK_ERROR(fn.setArray((flags & kArray) != 0), errorString);
AL_MAYA_CHECK_ERROR(fn.setUsedAsColor((flags & kColour) != 0), errorString);
AL_MAYA_CHECK_ERROR(fn.setHidden((flags & kHidden) != 0), errorString);
AL_MAYA_CHECK_ERROR(fn.setInternal((flags & kInternal) != 0), errorString);
AL_MAYA_CHECK_ERROR(fn.setAffectsWorldSpace((flags & kAffectsWorldSpace) != 0), errorString);
AL_MAYA_CHECK_ERROR(fn.setUsesArrayDataBuilder((flags & kUsesArrayDataBuilder) != 0), errorString);
if(!(flags & (kDynamic | kDontAddToNode)))
{
MStatus status = MPxNode::addAttribute(fn.object());
if(!status)
throw status;
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
void NodeHelper::generateAETemplate()
{
assert(m_internal);
// first hunt down all of the call custom attributes and generate the custom AE templates. This needs to be done before
// we generate the main template procedure (these are all global methods).
std::ostringstream oss;
auto it = m_internal->m_frames.rbegin();
auto end = m_internal->m_frames.rend();
for(; it != end; ++it)
{
size_t fileIndex = 0;
for(size_t i = 0; i < it->m_attributes.size(); ++i)
{
switch(it->m_attributeTypes[i])
{
case Frame::kLoadFilePath:
case Frame::kSaveFilePath:
case Frame::kDirPathWithFiles:
case Frame::kDirPath:
case Frame::kMultiLoadFilePath:
constructFilePathUi(oss, m_internal->m_typeBeingRegistered, it->m_attributes[i], it->m_fileFilters[fileIndex++], (FileMode)it->m_attributeTypes[i]);
break;
default:
break;
}
}
}
// start generating our AE template, and ensure it's wrapped in a scroll layout.
oss << "global proc AE" << m_internal->m_typeBeingRegistered << "Template(string $nodeName) {\n";
oss << " editorTemplate -beginScrollLayout;\n";
// loop through each collapsible frame
it = m_internal->m_frames.rbegin();
for(; it != end; ++it)
{
// frame layout begin!
oss << " editorTemplate -beginLayout \"" << it->m_title << "\" -collapse 0;\n";
for(size_t i = 0; i < it->m_attributes.size(); ++i)
{
switch(it->m_attributeTypes[i])
{
// If we have a file path attribute, use the custom callbacks
case Frame::kLoadFilePath:
case Frame::kSaveFilePath:
case Frame::kDirPathWithFiles:
case Frame::kDirPath:
case Frame::kMultiLoadFilePath:
oss << " editorTemplate -callCustom \"AE" << m_internal->m_typeBeingRegistered << "Template_" << it->m_attributes[i] << "New\" "
<< "\"AE" << m_internal->m_typeBeingRegistered << "Template_" << it->m_attributes[i] << "Replace\" \"" << it->m_attributes[i] << "\";\n";
break;
// for all other attributes, just add a normal control
default:
oss << " editorTemplate -addControl \"" << it->m_attributes[i] << "\";\n";
break;
}
}
oss << " editorTemplate -endLayout;\n";
}
// add all of our base templates that have been added
for(size_t i = 0; i < m_internal->m_baseTemplates.size(); ++i)
{
oss << " " << m_internal->m_baseTemplates[i] << " $nodeName;\n";
}
// finish off the call by adding in the custom attributes section
oss << " editorTemplate -addExtraControls;\n";
oss << " editorTemplate -endScrollLayout;\n";
oss << "}\n";
if (AL_MAYAUTILS_DEBUG)
{
std::cout << oss.str() + "\n" << std::endl;
}
// run our script (AE template command will now exist in memory)
MGlobal::executeCommand(MString(oss.str().c_str(), oss.str().size()));
// get rid of our internal rubbish.
delete m_internal;
m_internal = 0;
}
#define report_get_error(attribute, type, status) \
{ \
MFnAttribute fn(attribute); \
std::cerr << "Unable to get attribute \"" << fn.name().asChar() << "\" of type " << #type << std::endl; \
std::cerr << " - " << status.errorString().asChar() << std::endl; \
}
//----------------------------------------------------------------------------------------------------------------------
bool NodeHelper::inputBoolValue(MDataBlock& dataBlock, const MObject& attribute)
{
MStatus status;
MDataHandle inDataHandle = dataBlock.inputValue(attribute, &status);
if(status)
{
return inDataHandle.asBool();
}
report_get_error(attribute, bool, status);
return false;
}
//----------------------------------------------------------------------------------------------------------------------
int8_t NodeHelper::inputInt8Value(MDataBlock& dataBlock, const MObject& attribute)
{
MStatus status;
MDataHandle inDataHandle = dataBlock.inputValue(attribute, &status);
if(status)
{
return inDataHandle.asChar();
}
report_get_error(attribute, int8_t, status);
return 0;
}
//----------------------------------------------------------------------------------------------------------------------
int16_t NodeHelper::inputInt16Value(MDataBlock& dataBlock, const MObject& attribute)
{
MStatus status;
MDataHandle inDataHandle = dataBlock.inputValue(attribute, &status);
if(status)
{
return inDataHandle.asShort();
}
report_get_error(attribute, int16_t, status);
return 0;
}
//----------------------------------------------------------------------------------------------------------------------
int32_t NodeHelper::inputInt32Value(MDataBlock& dataBlock, const MObject& attribute)
{
MStatus status;
MDataHandle inDataHandle = dataBlock.inputValue(attribute, &status);
if(status)
{
return inDataHandle.asInt();
}
report_get_error(attribute, int32_t, status);
return 0;
}
//----------------------------------------------------------------------------------------------------------------------
int64_t NodeHelper::inputInt64Value(MDataBlock& dataBlock, const MObject& attribute)
{
MStatus status;
MDataHandle inDataHandle = dataBlock.inputValue(attribute, &status);
if(status)
{
return inDataHandle.asInt64();
}
report_get_error(attribute, int64_t, status);
return 0;
}
//----------------------------------------------------------------------------------------------------------------------
float NodeHelper::inputFloatValue(MDataBlock& dataBlock, const MObject& attribute)
{
MStatus status;
MDataHandle inDataHandle = dataBlock.inputValue(attribute, &status);
if(status)
{
return inDataHandle.asFloat();
}
report_get_error(attribute, float, status);
return 0;
}
//----------------------------------------------------------------------------------------------------------------------
double NodeHelper::inputDoubleValue(MDataBlock& dataBlock, const MObject& attribute)
{
MStatus status;
MDataHandle inDataHandle = dataBlock.inputValue(attribute, &status);
if(status)
{
return inDataHandle.asDouble();
}
report_get_error(attribute, double, status);
return 0;
}
//----------------------------------------------------------------------------------------------------------------------
MTime NodeHelper::inputTimeValue(MDataBlock& dataBlock, const MObject& attribute)
{
MStatus status;
MDataHandle inDataHandle = dataBlock.inputValue(attribute, &status);
if(status)
{
return inDataHandle.asTime();
}
report_get_error(attribute, MTime, status);
return MTime();
}
//----------------------------------------------------------------------------------------------------------------------
MMatrix NodeHelper::inputMatrixValue(MDataBlock& dataBlock, const MObject& attribute)
{
MStatus status;
MDataHandle inDataHandle = dataBlock.inputValue(attribute, &status);
if(status)
{
return inDataHandle.asMatrix();
}
report_get_error(attribute, MMatrix, status);
return MMatrix();
}
//----------------------------------------------------------------------------------------------------------------------
MPoint NodeHelper::inputPointValue(MDataBlock& dataBlock, const MObject& attribute)
{
MStatus status;
MDataHandle inDataHandle = dataBlock.inputValue(attribute, &status);
if(status)
{
const double3& v = inDataHandle.asDouble3();
return MPoint(v[0], v[1], v[2]);
}
report_get_error(attribute, MPoint, status);
return MPoint();
}
//----------------------------------------------------------------------------------------------------------------------
MFloatPoint NodeHelper::inputFloatPointValue(MDataBlock& dataBlock, const MObject& attribute)
{
MStatus status;
MDataHandle inDataHandle = dataBlock.inputValue(attribute, &status);
if(status)
{
const float3& v = inDataHandle.asFloat3();
return MFloatPoint(v[0], v[1], v[2]);
}
report_get_error(attribute, MFloatPoint, status);
return MFloatPoint();
}
//----------------------------------------------------------------------------------------------------------------------
MVector NodeHelper::inputVectorValue(MDataBlock& dataBlock, const MObject& attribute)
{
MStatus status;
MDataHandle inDataHandle = dataBlock.inputValue(attribute, &status);
if(status)
{
const double3& v = inDataHandle.asDouble3();
return MVector(v[0], v[1], v[2]);
}
report_get_error(attribute, MVector, status);
return MVector();
}
//----------------------------------------------------------------------------------------------------------------------
MFloatVector NodeHelper::inputFloatVectorValue(MDataBlock& dataBlock, const MObject& attribute)
{
MStatus status;
MDataHandle inDataHandle = dataBlock.inputValue(attribute, &status);
if(status)
{
const float3& v = inDataHandle.asFloat3();
return MFloatVector(v[0], v[1], v[2]);
}
report_get_error(attribute, MFloatVector, status);
return MFloatVector();
}
//----------------------------------------------------------------------------------------------------------------------
MString NodeHelper::inputStringValue(MDataBlock& dataBlock, const MObject& attribute)
{
MStatus status;
MDataHandle inDataHandle = dataBlock.inputValue(attribute, &status);
if(status)
{
return inDataHandle.asString();
}
report_get_error(attribute, MString, status);
return MString();
}
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
MColor NodeHelper::inputColourValue(MDataBlock& dataBlock, const MObject& attribute)
{
MStatus status;
MDataHandle inDataHandle = dataBlock.inputValue(attribute, &status);
if(status)
{
const float3& v = inDataHandle.asFloat3();
return MColor(v[0], v[1], v[2]);
}
report_get_error(attribute, MColor, status);
return MColor();
}
//----------------------------------------------------------------------------------------------------------------------
MPxData* NodeHelper::inputDataValue(MDataBlock& dataBlock, const MObject& attribute)
{
MStatus status;
MDataHandle inDataHandle = dataBlock.inputValue(attribute, &status);
if(status)
{
return inDataHandle.asPluginData();
}
report_get_error(attribute, MPxData, status);
return 0;
}
#define report_set_error(attribute, type, status) \
{ \
MFnAttribute fn(attribute); \
std::cerr << "Unable to set attribute \"" << fn.name().asChar() << "\" of type " << #type << std::endl; \
std::cerr << " - " << status.errorString().asChar() << std::endl; \
}
//----------------------------------------------------------------------------------------------------------------------
MStatus NodeHelper::outputBoolValue(MDataBlock& dataBlock, const MObject& attribute, const bool value)
{
MStatus status;
MDataHandle outDataHandle = dataBlock.outputValue(attribute, &status);
if(status)
{
outDataHandle.setBool(value);
outDataHandle.setClean();
}
else
{
report_set_error(attribute, bool, status);
}
return status;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus NodeHelper::outputInt8Value(MDataBlock& dataBlock, const MObject& attribute, const int8_t value)
{
MStatus status;
MDataHandle outDataHandle = dataBlock.outputValue(attribute, &status);
if(status)
{
outDataHandle.setChar(value);
outDataHandle.setClean();
}
else
{
report_set_error(attribute, int8_t, status);
}
return status;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus NodeHelper::outputInt16Value(MDataBlock& dataBlock, const MObject& attribute, const int16_t value)
{
MStatus status;
MDataHandle outDataHandle = dataBlock.outputValue(attribute, &status);
if(status)
{
outDataHandle.setShort(value);
outDataHandle.setClean();
}
else
{
report_set_error(attribute, int16_t, status);
}
return status;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus NodeHelper::outputInt32Value(MDataBlock& dataBlock, const MObject& attribute, const int32_t value)
{
MStatus status;
MDataHandle outDataHandle = dataBlock.outputValue(attribute, &status);
if(status)
{
outDataHandle.setInt(value);
outDataHandle.setClean();
}
else
{
report_set_error(attribute, int32_t, status);
}
return status;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus NodeHelper::outputInt64Value(MDataBlock& dataBlock, const MObject& attribute, const int64_t value)
{
MStatus status;
MDataHandle outDataHandle = dataBlock.outputValue(attribute, &status);
if(status)
{
outDataHandle.setInt64(value);
outDataHandle.setClean();
}
else
{
report_set_error(attribute, int64_t, status);
}
return status;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus NodeHelper::outputFloatValue(MDataBlock& dataBlock, const MObject& attribute, const float value)
{
MStatus status;
MDataHandle outDataHandle = dataBlock.outputValue(attribute, &status);
if(status)
{
outDataHandle.setFloat(value);
outDataHandle.setClean();
}
else
{
report_set_error(attribute, float, status);
}
return status;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus NodeHelper::outputDoubleValue(MDataBlock& dataBlock, const MObject& attribute, const double value)
{
MStatus status;
MDataHandle outDataHandle = dataBlock.outputValue(attribute, &status);
if(status)
{
outDataHandle.setDouble(value);
outDataHandle.setClean();
}
else
{
report_set_error(attribute, double, status);
}
return status;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus NodeHelper::outputMatrixValue(MDataBlock& dataBlock, const MObject& attribute, const MMatrix& value)
{
MStatus status;
MDataHandle outDataHandle = dataBlock.outputValue(attribute, &status);
if(status)
{
outDataHandle.setMMatrix(value);
outDataHandle.setClean();
}
else
{
report_set_error(attribute, MMatrix, status);
}
return status;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus NodeHelper::outputPointValue(MDataBlock& dataBlock, const MObject& attribute, const MPoint& value)
{
MStatus status;
MDataHandle outDataHandle = dataBlock.outputValue(attribute, &status);
if(status)
{
outDataHandle.set(value.x, value.y, value.z);
outDataHandle.setClean();
}
else
{
report_set_error(attribute, MPoint, status);
}
return status;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus NodeHelper::outputFloatPointValue(MDataBlock& dataBlock, const MObject& attribute, const MFloatPoint& value)
{
MStatus status;
MDataHandle outDataHandle = dataBlock.outputValue(attribute, &status);
if(status)
{
outDataHandle.set(value.x, value.y, value.z);
outDataHandle.setClean();
}
else
{
report_set_error(attribute, MFloatPoint, status);
}
return status;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus NodeHelper::outputVectorValue(MDataBlock& dataBlock, const MObject& attribute, const MVector& value)
{
MStatus status;
MDataHandle outDataHandle = dataBlock.outputValue(attribute, &status);
if(status)
{
outDataHandle.set(value.x, value.y, value.z);
outDataHandle.setClean();
}
else
{
report_set_error(attribute, MVector, status);
}
return status;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus NodeHelper::outputEulerValue(MDataBlock& dataBlock, const MObject& attribute, const MEulerRotation& value)
{
MStatus status;
MDataHandle outDataHandle = dataBlock.outputValue(attribute, &status);
if(status)
{
outDataHandle.set(value.x, value.y, value.z);
outDataHandle.setClean();
}
else
{
report_set_error(attribute, MEulerRotation, status);
}
return status;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus NodeHelper::outputFloatVectorValue(MDataBlock& dataBlock, const MObject& attribute, const MFloatVector& value)
{
MStatus status;
MDataHandle outDataHandle = dataBlock.outputValue(attribute, &status);
if(status)
{
outDataHandle.set(value.x, value.y, value.z);
outDataHandle.setClean();
}
else
{
report_set_error(attribute, MFloatVector, status);
}
return status;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus NodeHelper::outputColourValue(MDataBlock& dataBlock, const MObject& attribute, const MColor& value)
{
MStatus status;
MDataHandle outDataHandle = dataBlock.outputValue(attribute, &status);
if(status)
{
outDataHandle.set(value.r, value.g, value.b);
outDataHandle.setClean();
}
else
{
report_set_error(attribute, MColor, status);
}
return status;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus NodeHelper::outputStringValue(MDataBlock& dataBlock, const MObject& attribute, const MString& value)
{
MStatus status;
MDataHandle outDataHandle = dataBlock.outputValue(attribute, &status);
if(status)
{
outDataHandle.setString(value);
outDataHandle.setClean();
}
else
{
report_set_error(attribute, MString, status);
}
return status;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus NodeHelper::outputTimeValue(MDataBlock& dataBlock, const MObject& attribute, const MTime& value)
{
MStatus status;
MDataHandle outDataHandle = dataBlock.outputValue(attribute, &status);
if(status)
{
outDataHandle.set(value);
outDataHandle.setClean();
}
else
{
report_set_error(attribute, MTime, status);
}
return status;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus NodeHelper::outputDataValue(MDataBlock& dataBlock, const MObject& attribute, MPxData* value)
{
MStatus status;
MDataHandle outDataHandle = dataBlock.outputValue(attribute, &status);
if(status)
{
outDataHandle.set(value);
outDataHandle.setClean();
}
else
{
report_set_error(attribute, MPxData, status);
}
return status;
}
//----------------------------------------------------------------------------------------------------------------------
MPxData* NodeHelper::outputDataValue(MDataBlock& dataBlock, const MObject& attribute)
{
MStatus status;
MDataHandle outDataHandle = dataBlock.outputValue(attribute, &status);
if(status)
{
return outDataHandle.asPluginData();
}
report_get_error(attribute, MPxData, status);
return 0;
}
//----------------------------------------------------------------------------------------------------------------------
MPxData* NodeHelper::createData(const MTypeId& dataTypeId, MObject& data)
{
MStatus status;
MFnPluginData pluginDataFactory;
data = pluginDataFactory.create(dataTypeId, &status);
if(!status)
{
std::cerr << "Unable to create data object of type id: " << dataTypeId.id() << ":" << dataTypeId.className() << std::endl;
return 0;
}
return pluginDataFactory.data();
}
//----------------------------------------------------------------------------------------------------------------------
MStatus NodeHelper::addStringAttr(const MObject& node, const char* longName, const char* shortName, uint32_t flags, bool forceShow, MObject* attribute)
{
try
{
MStatus status;
MFnDependencyNode fn(node, &status);
if(!status)
{
throw status;
}
MObject attr = addStringAttr(longName, shortName, flags | kDynamic, forceShow);
status = fn.addAttribute(attr);
if(!status)
{
MGlobal::displayError(MString("Unable to add string attribute ") + longName + " to node " + fn.name());
throw status;
}
if(attribute) *attribute = attr;
}
catch(MStatus status)
{
return status;
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus NodeHelper::addFilePathAttr(const MObject& node, const char* longName, const char* shortName, uint32_t flags, FileMode forSaving, const char* fileFilter, MObject* attribute)
{
try
{
MStatus status;
MFnDependencyNode fn(node, &status);
if(!status)
{
throw status;
}
MObject attr = addFilePathAttr(longName, shortName, flags | kDynamic, forSaving, fileFilter);
status = fn.addAttribute(attr);
if(!status)
{
MGlobal::displayError(MString("Unable to add filename attribute ") + longName + " to node " + fn.name());
throw status;
}
if(attribute) *attribute = attr;
}
catch(MStatus status)
{
return status;
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus NodeHelper::addInt8Attr(const MObject& node, const char* longName, const char* shortName, int8_t defaultValue, uint32_t flags, MObject* attribute)
{
try
{
MStatus status;
MFnDependencyNode fn(node, &status);
if(!status)
{
throw status;
}
MObject attr = addInt8Attr(longName, shortName, defaultValue, flags | kDynamic);
status = fn.addAttribute(attr);
if(!status)
{
MGlobal::displayError(MString("Unable to add int attribute ") + longName + " to node " + fn.name());
throw status;
}
if(attribute) *attribute = attr;
}
catch(MStatus status)
{
return status;
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus NodeHelper::addInt16Attr(const MObject& node, const char* longName, const char* shortName, int16_t defaultValue, uint32_t flags, MObject* attribute)
{
try
{
MStatus status;
MFnDependencyNode fn(node, &status);
if(!status)
{
throw status;
}
MObject attr = addInt16Attr(longName, shortName, defaultValue, flags | kDynamic);
status = fn.addAttribute(attr);
if(!status)
{
MGlobal::displayError(MString("Unable to add int attribute ") + longName + " to node " + fn.name());
throw status;
}
if(attribute) *attribute = attr;
}
catch(MStatus status)
{
return status;
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus NodeHelper::addInt32Attr(const MObject& node, const char* longName, const char* shortName, int32_t defaultValue, uint32_t flags, MObject* attribute)
{
try
{
MStatus status;
MFnDependencyNode fn(node, &status);
if(!status)
{
throw status;
}
MObject attr = addInt32Attr(longName, shortName, defaultValue, flags | kDynamic);
status = fn.addAttribute(attr);
if(!status)
{
MGlobal::displayError(MString("Unable to add int attribute ") + longName + " to node " + fn.name());
throw status;
}
if(attribute) *attribute = attr;
}
catch(MStatus status)
{
return status;
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus NodeHelper::addInt64Attr(const MObject& node, const char* longName, const char* shortName, int64_t defaultValue, uint32_t flags, MObject* attribute)
{
try
{
MStatus status;
MFnDependencyNode fn(node, &status);
if(!status)
{
throw status;
}
MObject attr = addInt64Attr(longName, shortName, defaultValue, flags | kDynamic);
status = fn.addAttribute(attr);
if(!status)
{
MGlobal::displayError(MString("Unable to add int attribute ") + longName + " to node " + fn.name());
throw status;
}
if(attribute) *attribute = attr;
}
catch(MStatus status)
{
return status;
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus NodeHelper::addFloatAttr(const MObject& node, const char* longName, const char* shortName, float defaultValue, uint32_t flags, MObject* attribute)
{
try
{
MStatus status;
MFnDependencyNode fn(node, &status);
if(!status)
{
throw status;
}
MObject attr = addFloatAttr(longName, shortName, defaultValue, flags | kDynamic);
status = fn.addAttribute(attr);
if(!status)
{
MGlobal::displayError(MString("Unable to add float attribute ") + longName + " to node " + fn.name());
throw status;
}
if(attribute) *attribute = attr;
}
catch(MStatus status)
{
return status;
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus NodeHelper::addDoubleAttr(const MObject& node, const char* longName, const char* shortName, double defaultValue, uint32_t flags, MObject* attribute)
{
try
{
MStatus status;
MFnDependencyNode fn(node, &status);
if(!status)
{
throw status;
}
MObject attr = addDoubleAttr(longName, shortName, defaultValue, flags | kDynamic);
status = fn.addAttribute(attr);
if(!status)
{
MGlobal::displayError(MString("Unable to add double attribute ") + longName + " to node " + fn.name());
throw status;
}
if(attribute) *attribute = attr;
}
catch(MStatus status)
{
return status;
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus NodeHelper::addTimeAttr(const MObject& node, const char* longName, const char* shortName, const MTime& defaultValue, uint32_t flags, MObject* attribute)
{
try
{
MStatus status;
MFnDependencyNode fn(node, &status);
if(!status)
{
throw status;
}
MObject attr = addTimeAttr(longName, shortName, defaultValue, flags | kDynamic);
status = fn.addAttribute(attr);
if(!status)
{
MGlobal::displayError(MString("Unable to add time attribute ") + longName + " to node " + fn.name());
throw status;
}
if(attribute) *attribute = attr;
}
catch(MStatus status)
{
return status;
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus NodeHelper::addDistanceAttr(const MObject& node, const char* longName, const char* shortName, const MDistance& defaultValue, uint32_t flags, MObject* attribute)
{
try
{
MStatus status;
MFnDependencyNode fn(node, &status);
if(!status)
{
throw status;
}
MObject attr = addDistanceAttr(longName, shortName, defaultValue, flags | kDynamic);
status = fn.addAttribute(attr);
if(!status)
{
MGlobal::displayError(MString("Unable to add distance attribute ") + longName + " to node " + fn.name());
throw status;
}
if(attribute) *attribute = attr;
}
catch(MStatus status)
{
return status;
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus NodeHelper::addAngleAttr(const MObject& node, const char* longName, const char* shortName, const MAngle& defaultValue, uint32_t flags, MObject* attribute)
{
try
{
MStatus status;
MFnDependencyNode fn(node, &status);
if(!status)
{
throw status;
}
MObject attr = addAngleAttr(longName, shortName, defaultValue, flags | kDynamic);
status = fn.addAttribute(attr);
if(!status)
{
MGlobal::displayError(MString("Unable to add angle attribute ") + longName + " to node " + fn.name());
throw status;
}
if(attribute) *attribute = attr;
}
catch(MStatus status)
{
return status;
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus NodeHelper::addBoolAttr(const MObject& node, const char* longName, const char* shortName, bool defaultValue, uint32_t flags, MObject* attribute)
{
try
{
MStatus status;
MFnDependencyNode fn(node, &status);
if(!status)
{
throw status;
}
MObject attr = addBoolAttr(longName, shortName, defaultValue, flags | kDynamic);
status = fn.addAttribute(attr);
if(!status)
{
MGlobal::displayError(MString("Unable to add bool attribute ") + longName + " to node " + fn.name());
throw status;
}
if(attribute) *attribute = attr;
}
catch(MStatus status)
{
return status;
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus NodeHelper::addFloat3Attr(const MObject& node, const char* longName, const char* shortName, float defaultX, float defaultY, float defaultZ, uint32_t flags, MObject* attribute)
{
try
{
MStatus status;
MFnDependencyNode fn(node, &status);
if(!status)
{
throw status;
}
MObject attr = addFloat3Attr(longName, shortName, defaultX, defaultY, defaultZ, flags | kDynamic);
status = fn.addAttribute(attr);
if(!status)
{
MGlobal::displayError(MString("Unable to add float3 attribute ") + longName + " to node " + fn.name());
throw status;
}
if(attribute) *attribute = attr;
}
catch(MStatus status)
{
return status;
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus NodeHelper::addAngle3Attr(const MObject& node, const char* longName, const char* shortName, float defaultX, float defaultY, float defaultZ, uint32_t flags, MObject* attribute)
{
try
{
MStatus status;
MFnDependencyNode fn(node, &status);
if(!status)
{
throw status;
}
MObject attr = addAngle3Attr(longName, shortName, defaultX, defaultY, defaultZ, flags | kDynamic);
status = fn.addAttribute(attr);
if(!status)
{
MGlobal::displayError(MString("Unable to add angle3 attribute ") + longName + " to node " + fn.name());
throw status;
}
if(attribute) *attribute = attr;
}
catch(MStatus status)
{
return status;
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus NodeHelper::addPointAttr(const MObject& node, const char* longName, const char* shortName, const MPoint& defaultValue, uint32_t flags, MObject* attribute)
{
try
{
MStatus status;
MFnDependencyNode fn(node, &status);
if(!status)
{
throw status;
}
MObject attr = addPointAttr(longName, shortName, defaultValue, flags | kDynamic);
status = fn.addAttribute(attr);
if(!status)
{
MGlobal::displayError(MString("Unable to add point attribute ") + longName + " to node " + fn.name());
throw status;
}
if(attribute) *attribute = attr;
}
catch(MStatus status)
{
return status;
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus NodeHelper::addVectorAttr(const MObject& node, const char* longName, const char* shortName, const MVector& defaultValue, uint32_t flags, MObject* attribute)
{
try
{
MStatus status;
MFnDependencyNode fn(node, &status);
if(!status)
{
throw status;
}
MObject attr = addVectorAttr(longName, shortName, defaultValue, flags | kDynamic);
status = fn.addAttribute(attr);
if(!status)
{
MGlobal::displayError(MString("Unable to add vector attribute ") + longName + " to node " + fn.name());
throw status;
}
if(attribute) *attribute = attr;
}
catch(MStatus status)
{
return status;
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus NodeHelper::addMatrixAttr(const MObject& node, const char* longName, const char* shortName, const MMatrix& defaultValue, uint32_t flags, MObject* attribute)
{
try
{
MStatus status;
MFnDependencyNode fn(node, &status);
if(!status)
{
throw status;
}
MObject attr = addMatrixAttr(longName, shortName, defaultValue, flags | kDynamic);
status = fn.addAttribute(attr);
if(!status)
{
MGlobal::displayError(MString("Unable to add matrix attribute ") + longName + " to node " + fn.name());
throw status;
}
if(attribute) *attribute = attr;
}
catch(MStatus status)
{
return status;
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus NodeHelper::addMatrix2x2Attr(const MObject& node, const char* longName, const char* shortName, const float defaultValue[2][2], uint32_t flags, MObject* attribute)
{
try
{
MStatus status;
MFnDependencyNode fn(node, &status);
if(!status)
{
throw status;
}
MObject attr = addMatrix2x2Attr(longName, shortName, defaultValue, flags | kDynamic);
status = fn.addAttribute(attr);
if(!status)
{
MGlobal::displayError(MString("Unable to add matrix2x2 attribute ") + longName + " to node " + fn.name());
throw status;
}
if(attribute) *attribute = attr;
}
catch(MStatus status)
{
return status;
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus NodeHelper::addMatrix3x3Attr(const MObject& node, const char* longName, const char* shortName, const float defaultValue[3][3], uint32_t flags, MObject* attribute)
{
try
{
MStatus status;
MFnDependencyNode fn(node, &status);
if(!status)
{
throw status;
}
MObject attr = addMatrix3x3Attr(longName, shortName, defaultValue, flags | kDynamic);
status = fn.addAttribute(attr);
if(!status)
{
MGlobal::displayError(MString("Unable to add matrix3x3 attribute ") + longName + " to node " + fn.name());
throw status;
}
if(attribute) *attribute = attr;
}
catch(MStatus status)
{
return status;
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus NodeHelper::addDataAttr(const MObject& node, const char* longName, const char* shortName, MFnData::Type type, uint32_t flags, MFnAttribute::DisconnectBehavior behaviour, MObject* attribute)
{
try
{
MStatus status;
MFnDependencyNode fn(node, &status);
if(!status)
{
throw status;
}
MObject attr = addDataAttr(longName, shortName, type, flags | kDynamic, behaviour);
status = fn.addAttribute(attr);
if(!status)
{
MGlobal::displayError(MString("Unable to add data attribute ") + longName + " to node " + fn.name());
throw status;
}
if(attribute) *attribute = attr;
}
catch(MStatus status)
{
return status;
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus NodeHelper::addDataAttr(const MObject& node, const char* longName, const char* shortName, const MTypeId& type, uint32_t flags, MFnAttribute::DisconnectBehavior behaviour, MObject* attribute)
{
try
{
MStatus status;
MFnDependencyNode fn(node, &status);
if(!status)
{
throw status;
}
MObject attr = addDataAttr(longName, shortName, type, flags | kDynamic, behaviour);
status = fn.addAttribute(attr);
if(!status)
{
MGlobal::displayError(MString("Unable to add data attribute ") + longName + " to node " + fn.name());
throw status;
}
if(attribute) *attribute = attr;
}
catch(MStatus status)
{
return status;
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus NodeHelper::addMessageAttr(const MObject& node, const char* longName, const char* shortName, uint32_t flags, MObject* attribute)
{
try
{
MStatus status;
MFnDependencyNode fn(node, &status);
if(!status)
{
throw status;
}
MObject attr = addMessageAttr(longName, shortName, flags | kDynamic);
status = fn.addAttribute(attr);
if(!status)
{
MGlobal::displayError(MString("Unable to add message attribute ") + longName + " to node " + fn.name());
throw status;
}
if(attribute) *attribute = attr;
}
catch(MStatus status)
{
return status;
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus NodeHelper::addVec2fAttr(const MObject& node, const char* longName, const char* shortName, uint32_t flags, MObject* attribute)
{
try
{
MStatus status;
MFnDependencyNode fn(node, &status);
if(!status)
{
throw status;
}
MObject attr = addVec2fAttr(longName, shortName, flags | kDynamic);
status = fn.addAttribute(attr);
if(!status)
{
MGlobal::displayError(MString("Unable to add vec2 attribute ") + longName + " to node " + fn.name());
throw status;
}
if(attribute) *attribute = attr;
}
catch(MStatus status)
{
return status;
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus NodeHelper::addVec2iAttr(const MObject& node, const char* longName, const char* shortName, uint32_t flags, MObject* attribute)
{
try
{
MStatus status;
MFnDependencyNode fn(node, &status);
if(!status)
{
throw status;
}
MObject attr = addVec2iAttr(longName, shortName, flags | kDynamic);
status = fn.addAttribute(attr);
if(!status)
{
MGlobal::displayError(MString("Unable to add vec2 attribute ") + longName + " to node " + fn.name());
throw status;
}
if(attribute) *attribute = attr;
}
catch(MStatus status)
{
return status;
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus NodeHelper::addVec2dAttr(const MObject& node, const char* longName, const char* shortName, uint32_t flags, MObject* attribute)
{
try
{
MStatus status;
MFnDependencyNode fn(node, &status);
if(!status)
{
throw status;
}
MObject attr = addVec2dAttr(longName, shortName, flags | kDynamic);
status = fn.addAttribute(attr);
if(!status)
{
MGlobal::displayError(MString("Unable to add vec2 attribute ") + longName + " to node " + fn.name());
throw status;
}
if(attribute) *attribute = attr;
}
catch(MStatus status)
{
return status;
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus NodeHelper::addVec3fAttr(const MObject& node, const char* longName, const char* shortName, uint32_t flags, MObject* attribute)
{
try
{
MStatus status;
MFnDependencyNode fn(node, &status);
if(!status)
{
throw status;
}
MObject attr = addVec3fAttr(longName, shortName, flags | kDynamic);
status = fn.addAttribute(attr);
if(!status)
{
MGlobal::displayError(MString("Unable to add vec3 attribute ") + longName + " to node " + fn.name());
throw status;
}
if(attribute) *attribute = attr;
}
catch(MStatus status)
{
return status;
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus NodeHelper::addVec3iAttr(const MObject& node, const char* longName, const char* shortName, uint32_t flags, MObject* attribute)
{
try
{
MStatus status;
MFnDependencyNode fn(node, &status);
if(!status)
{
throw status;
}
MObject attr = addVec3iAttr(longName, shortName, flags | kDynamic);
status = fn.addAttribute(attr);
if(!status)
{
MGlobal::displayError(MString("Unable to add vec3 attribute ") + longName + " to node " + fn.name());
throw status;
}
if(attribute) *attribute = attr;
}
catch(MStatus status)
{
return status;
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus NodeHelper::addVec3dAttr(const MObject& node, const char* longName, const char* shortName, uint32_t flags, MObject* attribute)
{
try
{
MStatus status;
MFnDependencyNode fn(node, &status);
if(!status)
{
throw status;
}
MObject attr = addVec3dAttr(longName, shortName, flags | kDynamic);
status = fn.addAttribute(attr);
if(!status)
{
MGlobal::displayError(MString("Unable to add vec3 attribute ") + longName + " to node " + fn.name());
throw status;
}
if(attribute) *attribute = attr;
}
catch(MStatus status)
{
return status;
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus NodeHelper::addVec4fAttr(const MObject& node, const char* longName, const char* shortName, uint32_t flags, MObject* attribute)
{
try
{
MStatus status;
MFnDependencyNode fn(node, &status);
if(!status)
{
throw status;
}
MObject attr = addVec4fAttr(longName, shortName, flags | kDynamic);
status = fn.addAttribute(attr);
if(!status)
{
MGlobal::displayError(MString("Unable to add vec4 attribute ") + longName + " to node " + fn.name());
throw status;
}
if(attribute) *attribute = attr;
}
catch(MStatus status)
{
return status;
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus NodeHelper::addVec4iAttr(const MObject& node, const char* longName, const char* shortName, uint32_t flags, MObject* attribute)
{
try
{
MStatus status;
MFnDependencyNode fn(node, &status);
if(!status)
{
throw status;
}
MObject attr = addVec4iAttr(longName, shortName, flags | kDynamic);
status = fn.addAttribute(attr);
if(!status)
{
MGlobal::displayError(MString("Unable to add vec4 attribute ") + longName + " to node " + fn.name());
throw status;
}
if(attribute) *attribute = attr;
}
catch(MStatus status)
{
return status;
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus NodeHelper::addVec4dAttr(const MObject& node, const char* longName, const char* shortName, uint32_t flags, MObject* attribute)
{
try
{
MStatus status;
MFnDependencyNode fn(node, &status);
if(!status)
{
throw status;
}
MObject attr = addVec4dAttr(longName, shortName, flags | kDynamic);
status = fn.addAttribute(attr);
if(!status)
{
MGlobal::displayError(MString("Unable to add vec4 attribute ") + longName + " to node " + fn.name());
throw status;
}
if(attribute) *attribute = attr;
}
catch(MStatus status)
{
return status;
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
} // utils
} // maya
} // AL
//----------------------------------------------------------------------------------------------------------------------
| 86,244 | 26,107 |
// #ifndef __NDTDLWORKER_H__
// #define __NDTDLWORKER_H__
// #include <omp.h>
// #include <cmath>
// #include <string>
// #include <vector>
// #include <rts/core/pt.hpp>
// #include <rts/op/exp.hpp>
// #include "ndt_kernel.hpp"
// #include "sched_log.hpp"
// #include "sched_core.hpp"
// #include "sched_deadline.hpp"
// #include "spdlog/spdlog.h"
// #include "spdlog/async.h"
// #include "spdlog/sinks/basic_file_sink.h"
// class NDTWorker {
// public:
// std::string name;
// std::shared_ptr<spdlog::logger> thr_log;
// std::vector<int> omp_thr_ids;
// rts::Pt pt;
// SchedLog sl;
// NDTWorker(rts::Pt _pt, rts::Exp _exp);
// void apply_rt();
// void msec_work(int msec);
// void work();
// };
// #endif
| 744 | 320 |
//https://codeforces.com/problemset/problem/339/A
#include<bits/stdc++.h>
using namespace std ;
#define aakriti string
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
aakriti s ;
int a ;
cin >> s ;
sort(s.begin(), s.end());
vector<char>v;
for(int i = 0; i < s.size(); i++)
{
if(s[i] != '+')
{
v.push_back(s[i]);
}
}
a = v.size();
for(int i = 0; i < a-1; i++)
{
cout << v[i] << "+";
}
cout << v[a-1];
}
| 532 | 236 |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#include "std.hxx"
#include "_bt.hxx"
#include "_dump.hxx"
#include "_space.hxx"
#include "stat.hxx"
LOCAL ERR ErrDBUTLDumpTables( DBCCINFO *pdbccinfo, PFNTABLE pfntable, VOID* pvCtx = NULL );
#if !defined( MINIMAL_FUNCTIONALITY ) || defined( DEBUGGER_EXTENSION )
VOID DBUTLSprintHex(
__out_bcount(cbDest) CHAR * const szDest,
const INT cbDest,
const BYTE * const rgbSrc,
const INT cbSrc,
const INT cbWidth,
const INT cbChunk,
const INT cbAddress,
const INT cbStart)
{
static const CHAR rgchConvert[] = { '0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f' };
const BYTE * const pbMax = rgbSrc + cbSrc;
const INT cchHexWidth = ( cbWidth * 2 ) + ( cbWidth / cbChunk );
const BYTE * pb = rgbSrc;
CHAR * szDestCurrent = szDest;
Assert( cbDest >= sizeof(CHAR) );
if ( cbDest < sizeof(CHAR) )
{
return;
}
Assert( cchHexWidth );
if ( 0 == cchHexWidth )
{
return;
}
CHAR * const szDestMax = szDestCurrent + cbDest - 1;
while( pbMax != pb && szDestCurrent < szDestMax )
{
if ( cbAddress )
{
StringCbPrintfA( szDestCurrent, szDestMax - szDestCurrent + 1, "%*.*lx ", cbAddress, cbAddress, (INT)(pb - rgbSrc + cbStart) );
(*szDestMax) = 0;
szDestCurrent += strlen(szDestCurrent);
if ( szDestMax <= szDestCurrent )
break;
}
CHAR * szCurrentRightSide = szDestCurrent + cchHexWidth;
if ( szDestMax <= ( szCurrentRightSide + 2 ) )
break;
*szCurrentRightSide++ = '\\';
*szCurrentRightSide++ = ' ';
memset( szDestCurrent, ' ', cchHexWidth );
do
{
Assert( szDestCurrent < szCurrentRightSide );
for( INT cb = 0; cbChunk > cb && pbMax != pb && szCurrentRightSide <= szDestMax && szDestCurrent < szDestMax; ++cb, ++pb )
{
*szDestCurrent++ = rgchConvert[ *pb >> 4 ];
*szDestCurrent++ = rgchConvert[ *pb & 0x0F ];
*szCurrentRightSide++ = isprint( *pb ) ? *pb : '.';
}
szDestCurrent++;
} while( ( ( pb - rgbSrc ) % cbWidth ) && pbMax > pb && szCurrentRightSide < szDestMax);
if ( szCurrentRightSide < szDestMax )
{
*szCurrentRightSide++ = '\n';
*szCurrentRightSide = '\0';
}
szDestCurrent = szCurrentRightSide;
}
Assert( szDestCurrent<= szDestMax ) ;
(*szDestMax) = 0;
}
#pragma prefast(push)
#pragma prefast(disable:6262, "This function uses a lot of stack (33k) because of szBuff[g_cbPageMax].")
VOID DBUTLDumpRec( const LONG cbPage, const FUCB * const pfucbTable, const VOID * const pv, const INT cb, CPRINTF * pcprintf, const INT cbWidth )
{
CHAR szBuf[g_cbPageMax];
TDB* const ptdb = ( pfucbTable != pfucbNil ? pfucbTable->u.pfcb->Ptdb() : ptdbNil );
TDB* const ptdbTemplate = ( ptdb != ptdbNil && ptdb->PfcbTemplateTable() != pfcbNil ?
ptdb->PfcbTemplateTable()->Ptdb() :
ptdbNil );
const REC * const prec = reinterpret_cast<const REC *>( pv );
const CHAR * szColNameSeparator = " - ";
const CHAR * szNullValue = "<NULL>";
const CHAR * szTemplate = " (template)";
const CHAR * szDerived = " (derived)";
#define SzTableColType( ptdbTemplateIn, fTemplateColumnIn ) ( ( ptdbTemplateIn == NULL ) ? "" : ( fTemplateColumnIn ? szTemplate : szDerived ) )
FID fid;
const FID fidFixedFirst = fidFixedLeast;
const FID fidFixedLast = prec->FidFixedLastInRec();
const INT cColumnsFixed = max( 0, fidFixedLast - fidFixedFirst + 1 );
(*pcprintf)( " Fixed Columns: %d\n", cColumnsFixed );
(*pcprintf)( "=================\n" );
for( fid = fidFixedFirst; fid <= fidFixedLast; ++fid )
{
const UINT ifid = fid - fidFixedLeast;
const BYTE * const prgbitNullity = prec->PbFixedNullBitMap() + ifid/8;
const BOOL fTemplateColumn = ptdbTemplate == ptdbNil ? fFalse : fid <= ptdbTemplate->FidFixedLast() ? fTrue : fFalse;
const COLUMNID columnid = ColumnidOfFid( fid, fTemplateColumn );
const FIELD * const pfield = ( ptdb != ptdbNil ) ? ptdb->Pfield( columnid ) : NULL;
BOOL fDeleted = fFalse;
const CHAR * szType = "UnknownColType";
const CHAR * szColumn = "UnknownColName ";
if ( pfield )
{
fDeleted = ( 0 == pfield->itagFieldName );
szType = ( fDeleted ? "<deleted>" : SzColumnType( pfield->coltyp ) );
szColumn = ( fDeleted ? "<deleted>" : ( fTemplateColumn ? ptdbTemplate : ptdb )->SzFieldName( pfield->itagFieldName, ptdbTemplate != NULL && !fTemplateColumn ) );
}
const CHAR * const szHddlSrc = SzTableColType( ptdbTemplate, fTemplateColumn );
(*pcprintf)( "%u (0x%x): [%-16hs] %hs%hs", columnid, columnid, szType, szColumn, szHddlSrc );
if ( FFixedNullBit( prgbitNullity, ifid ) )
{
(*pcprintf)( "%hs%hs\n", szColNameSeparator, szNullValue );
}
else
{
(*pcprintf)( "\n" );
if ( pfucbTable )
{
DATA dataRec;
dataRec.SetPv( (void*)prec );
dataRec.SetCb( cb );
DATA dataCol;
const ERR errRet = ErrRECRetrieveNonTaggedColumn(
pfucbTable->u.pfcb,
columnid,
dataRec,
&dataCol,
pfieldNil );
if ( errRet >= JET_errSuccess )
{
Expected( dataCol.Cb() < 257 );
szBuf[0] = 0;
DBUTLSprintHex( szBuf, sizeof(szBuf), (BYTE*)dataCol.Pv(), dataCol.Cb(), cbWidth );
(*pcprintf)( "%s", szBuf );
}
else
{
(*pcprintf)( "<ERR: got %d trying retrieve column value>\n", errRet );
}
}
else
{
(*pcprintf)( "<ERR: need at least copy of FCB to dump fixed cols>\n" );
}
}
}
(*pcprintf)( "\n" );
const FID fidVariableFirst = fidVarLeast ;
const FID fidVariableLast = prec->FidVarLastInRec();
const INT cColumnsVariable = max( 0, fidVariableLast - fidVariableFirst + 1 );
(*pcprintf)( "Variable Columns: %d\n", cColumnsVariable );
(*pcprintf)( "=================\n" );
const UnalignedLittleEndian<REC::VAROFFSET> * const pibVarOffs = ( const UnalignedLittleEndian<REC::VAROFFSET> * const )prec->PibVarOffsets();
for( fid = fidVariableFirst; fid <= fidVariableLast; ++fid )
{
const UINT ifid = fid - fidVarLeast;
const REC::VAROFFSET ibStartOfColumn = prec->IbVarOffsetStart( fid );
const REC::VAROFFSET ibEndOfColumn = IbVarOffset( pibVarOffs[ifid] );
const BOOL fTemplateColumn = ptdbTemplate == ptdbNil ? fFalse : fid <= ptdbTemplate->FidVarLast() ? fTrue : fFalse;
const COLUMNID columnid = ColumnidOfFid( fid, fTemplateColumn );
const FIELD * const pfield = ( ptdb != ptdbNil ) ? ptdb->Pfield( columnid ) : NULL;
BOOL fDeleted = fFalse;
const CHAR * szType = "UnknownColType";
const CHAR * szColumn = "UnknownColName ";
if ( pfield )
{
fDeleted = ( 0 == pfield->itagFieldName );
szType = ( fDeleted ? "<deleted>" : SzColumnType( pfield->coltyp ) );
szColumn = ( fDeleted ? "<deleted>" : ( fTemplateColumn ? ptdbTemplate : ptdb )->SzFieldName( pfield->itagFieldName, ptdbTemplate != NULL && !fTemplateColumn ) );
}
const CHAR * const szHddlSrc = SzTableColType( ptdbTemplate, fTemplateColumn );
(*pcprintf)( "%u (0x%x): [%-16hs] %hs%hs", columnid, columnid, szType, szColumn, szHddlSrc );
if ( FVarNullBit( pibVarOffs[ifid] ) )
{
(*pcprintf)( "%hs%hs\n", szColNameSeparator, szNullValue );
}
else
{
const VOID * const pvColumn = prec->PbVarData() + ibStartOfColumn;
const INT cbColumn = ibEndOfColumn - ibStartOfColumn;
(*pcprintf)( "%hs%d bytes\n", szColNameSeparator, cbColumn );
DBUTLSprintHex( szBuf, sizeof(szBuf), (BYTE *)pvColumn, cbColumn, cbWidth );
(*pcprintf)( "%s\n", szBuf );
}
}
(*pcprintf)( "\n" );
(*pcprintf)( " Tagged Columns:\n" );
(*pcprintf)( "=================\n" );
DATA dataRec;
dataRec.SetPv( (VOID *)pv );
dataRec.SetCb( cb );
if ( !TAGFIELDS::FIsValidTagfields( cbPage, dataRec, pcprintf ) )
{
(*pcprintf)( "Tagged column corruption detected.\n" );
}
(*pcprintf)( "TAGFIELDS array begins at offset 0x%x from start of record.\n\n", prec->PbTaggedData() - (BYTE *)prec );
TAGFIELDS_ITERATOR ti( dataRec );
ti.MoveBeforeFirst();
while( JET_errSuccess == ti.ErrMoveNext() )
{
const CHAR * szComma = " ";
const BOOL fTemplateColumn = ptdbTemplate == ptdbNil ? fFalse : ti.Fid() <= ptdbTemplate->FidTaggedLast() ? fTrue : fFalse;
const COLUMNID columnid = ColumnidOfFid( ti.Fid(), fTemplateColumn );
const FIELD * const pfield = ( ptdb != ptdbNil ) ? ptdb->Pfield( columnid ) : NULL;
BOOL fDeleted = fFalse;
const CHAR * szType = "UnknownColType";
const CHAR * szColumn = "UnknownColName ";
if ( pfield )
{
fDeleted = ( 0 == pfield->itagFieldName );
szType = ( fDeleted ? "<deleted>" : SzColumnType( pfield->coltyp ) );
szColumn = ( fDeleted ? "<deleted>" : ( fTemplateColumn ? ptdbTemplate : ptdb )->SzFieldName( pfield->itagFieldName, ptdbTemplate != NULL && !fTemplateColumn ) );
Assert( !!ti.FLV() == ( ( pfield->coltyp == JET_coltypLongText ) || ( pfield->coltyp == JET_coltypLongBinary ) ) );
}
const CHAR * const szHddlSrc = SzTableColType( ptdbTemplate, !ti.FDerived() );
(*pcprintf)( "%u (0x%x): [%-16hs] %hs%hs", ti.Fid(), ti.Fid(), szType, szColumn, szHddlSrc );
if( ti.FNull() )
{
(*pcprintf)( "%hs%hs", szColNameSeparator, szNullValue );
szComma = ", ";
}
(*pcprintf)( "\r\n" );
ti.TagfldIterator().MoveBeforeFirst();
INT itag = 1;
while( JET_errSuccess == ti.TagfldIterator().ErrMoveNext() )
{
const BOOL fSeparated = ti.TagfldIterator().FSeparated();
const BOOL fCompressed = ti.TagfldIterator().FCompressed();
const BOOL fEncrypted = ti.TagfldIterator().FEncrypted();
(*pcprintf)( ">> itag %d: %d bytes (offset 0x%x): ", itag, ti.TagfldIterator().CbData(), ti.TagfldIterator().PbData() - (BYTE *)prec );
if ( fSeparated )
{
(*pcprintf)( "separated" );
}
if ( fCompressed )
{
(*pcprintf)( " compressed" );
}
if ( fEncrypted )
{
(*pcprintf)( " encrypted" );
}
(*pcprintf)( "\r\n" );
const INT cbPrintMax = 512;
if( fCompressed && !fEncrypted && !fSeparated )
{
szBuf[0] = 0;
DBUTLSprintHex(
szBuf,
sizeof(szBuf),
ti.TagfldIterator().PbData(),
min( ti.TagfldIterator().CbData(), 64 ),
cbWidth );
(*pcprintf)( "%s%s\r\n", szBuf, ( ti.TagfldIterator().CbData() > 64 ? "...\r\n" : "" ) );
BYTE rgbDecompressed[cbPrintMax];
DATA dataCompressed;
dataCompressed.SetPv( (void *)ti.TagfldIterator().PbData() );
dataCompressed.SetCb( ti.TagfldIterator().CbData() );
INT cbDecompressed;
CallSx( ErrPKDecompressData(
dataCompressed,
NULL,
rgbDecompressed,
sizeof(rgbDecompressed),
&cbDecompressed ),
JET_wrnBufferTruncated );
size_t cbToPrint = min( sizeof(rgbDecompressed ), cbDecompressed );
(*pcprintf)( ">> %d bytes uncompressed:\r\n", cbDecompressed );
szBuf[0] = 0;
DBUTLSprintHex(
szBuf,
sizeof(szBuf),
rgbDecompressed,
min( cbToPrint, cbPrintMax ),
cbWidth );
(*pcprintf)( "%s%s\r\n", szBuf, ( cbDecompressed > cbPrintMax ? "...\r\n" : "" ) );
}
else
{
szBuf[0] = 0;
DBUTLSprintHex(
szBuf,
sizeof(szBuf),
ti.TagfldIterator().PbData(),
min( ti.TagfldIterator().CbData(), cbPrintMax ),
cbWidth );
(*pcprintf)( "%s%s\r\n", szBuf, ( ti.TagfldIterator().CbData() > cbPrintMax ? "...\r\n" : "" ) );
}
++itag;
}
}
(*pcprintf)( "\n" );
}
#pragma prefast(push)
#endif
#ifdef MINIMAL_FUNCTIONALITY
#else
const JET_COLUMNDEF rgcolumndefPageInfoTable[] =
{
{sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed | JET_bitColumnTTKey},
{sizeof(JET_COLUMNDEF), 0, JET_coltypBit, 0, 0, 0, 0, 0, JET_bitColumnFixed | JET_bitColumnNotNULL},
{sizeof(JET_COLUMNDEF), 0, JET_coltypBit, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed},
{sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed },
{sizeof(JET_COLUMNDEF), 0, JET_coltypLong, 0, 0, 0, 0, 0, JET_bitColumnFixed }
};
const INT icolumnidPageInfoPgno = 0;
const INT icolumnidPageInfoFChecked = 1;
const INT icolumnidPageInfoFAvail = 2;
const INT icolumnidPageInfoFreeSpace = 3;
const INT icolumnidPageInfoPgnoLeft = 4;
const INT icolumnidPageInfoPgnoRight = 5;
const INT ccolumndefPageInfoTable = ( sizeof ( rgcolumndefPageInfoTable ) / sizeof(JET_COLUMNDEF) );
LOCAL JET_COLUMNID g_rgcolumnidPageInfoTable[ccolumndefPageInfoTable];
typedef ERR(*PFNDUMP)( PIB *ppib, FUCB *pfucbCatalog, VOID *pfnCallback, VOID *pvCallback );
#endif
LOCAL ERR ErrDBUTLDump( JET_SESID sesid, const JET_DBUTIL_W *pdbutil );
LOCAL VOID DBUTLPrintfIntN( INT iValue, INT ichMax )
{
CHAR rgchT[17];
INT ichT;
_itoa_s( iValue, rgchT, _countof(rgchT), 10 );
for ( ichT = 0; ichT < sizeof(rgchT) && rgchT[ichT] != '\0' ; ichT++ )
;
if ( ichT > ichMax )
{
for ( ichT = 0; ichT < ichMax; ichT++ )
printf( "#" );
}
else
{
for ( ichT = ichMax - ichT; ichT > 0; ichT-- )
printf( " " );
for ( ichT = 0; rgchT[ichT] != '\0'; ichT++ )
printf( "%c", rgchT[ichT] );
}
return;
}
#ifdef MINIMAL_FUNCTIONALITY
#else
LOCAL_BROKEN VOID DBUTLPrintfStringN(
__in_bcount(ichMax) const CHAR *sz,
INT ichMax )
{
INT ich;
for ( ich = 0; ich < ichMax && sz[ich] != '\0' ; ich++ )
printf( "%c", sz[ich] );
for ( ; ich < ichMax; ich++ )
printf( " " );
printf( " " );
return;
}
LOCAL_BROKEN ERR ErrDBUTLRegExt( DBCCINFO *pdbccinfo, PGNO pgnoFirst, CPG cpg, BOOL fAvailT )
{
ERR err = JET_errSuccess;
PGNO pgnoLast = (PGNO)( pgnoFirst + cpg - 1 );
PGNO pgno;
PIB *ppib = pdbccinfo->ppib;
JET_SESID sesid = (JET_SESID) pdbccinfo->ppib;
JET_TABLEID tableid = pdbccinfo->tableidPageInfo;
BYTE fAvail = (BYTE) fAvailT;
Assert( tableid != JET_tableidNil );
if ( pgnoFirst > pgnoLast )
{
return ErrERRCheck( JET_errInvalidParameter );
}
for ( pgno = pgnoFirst; pgno <= pgnoLast; pgno++ )
{
BOOL fFound;
BYTE fChecked = fFalse;
CallR( ErrIsamBeginTransaction( (JET_SESID) ppib, 41189, NO_GRBIT ) );
CallS( ErrDispMakeKey( sesid, tableid, (BYTE *)&pgno, sizeof(pgno), JET_bitNewKey ) );
err = ErrDispSeek( sesid, tableid, JET_bitSeekEQ );
if ( err < 0 && err != JET_errRecordNotFound )
{
Assert( fFalse );
Call( err );
}
fFound = ( err == JET_errRecordNotFound ) ? fFalse : fTrue;
if ( fFound )
{
ULONG cbActual;
BYTE fAvailT2;
Call( ErrDispRetrieveColumn( sesid,
tableid,
g_rgcolumnidPageInfoTable[icolumnidPageInfoFAvail],
(BYTE *)&fAvailT2,
sizeof(fAvailT2),
&cbActual,
0,
NULL ) );
Assert( err == JET_wrnColumnNull || cbActual == sizeof(fAvailT2) );
if ( err != JET_wrnColumnNull )
{
Assert( !fAvail || fAvailT2 );
}
if ( !fAvail )
goto Commit;
Call( ErrDispRetrieveColumn( sesid,
tableid,
g_rgcolumnidPageInfoTable[icolumnidPageInfoFChecked],
(BYTE *)&fChecked,
sizeof(fChecked),
&cbActual,
0,
NULL ) );
Assert( cbActual == sizeof(fChecked) );
Call( ErrDispPrepareUpdate( sesid, tableid, JET_prepReplaceNoLock ) );
}
else
{
Call( ErrDispPrepareUpdate( sesid, tableid, JET_prepInsert ) );
Call( ErrDispSetColumn( sesid,
tableid,
g_rgcolumnidPageInfoTable[icolumnidPageInfoPgno],
(BYTE *) &pgno,
sizeof(pgno),
0,
NULL ) );
}
Call( ErrDispSetColumn( sesid,
tableid,
g_rgcolumnidPageInfoTable[icolumnidPageInfoFChecked],
(BYTE *)&fChecked,
sizeof(fChecked),
0,
NULL ) );
if ( fAvail )
{
Call( ErrDispSetColumn( sesid,
tableid,
g_rgcolumnidPageInfoTable[icolumnidPageInfoFAvail],
(BYTE *) &fAvail,
sizeof(fAvail),
0,
NULL ) );
}
Call( ErrDispUpdate( sesid, tableid, NULL, 0, NULL, 0 ) );
Commit:
Assert( ppib->Level() == 1 );
Call( ErrIsamCommitTransaction( ( JET_SESID ) ppib, 0 ) );
}
return JET_errSuccess;
HandleError:
CallS( ErrIsamRollback( (JET_SESID) ppib, JET_bitRollbackAll ) );
return err;
}
LOCAL_BROKEN ERR ErrDBUTLPrintPageDump( DBCCINFO *pdbccinfo )
{
ERR err;
const JET_SESID sesid = (JET_SESID) pdbccinfo->ppib;
const JET_TABLEID tableid = pdbccinfo->tableidPageInfo;
ULONG cbT;
FUCBSetSequential( reinterpret_cast<FUCB *>( tableid ) );
Assert( pdbccinfo->grbitOptions & JET_bitDBUtilOptionPageDump );
err = ErrDispMove( sesid, tableid, JET_MoveFirst, 0 );
if ( JET_errNoCurrentRecord != err )
{
err = JET_errSuccess;
goto HandleError;
}
Call( err );
printf( "\n\n ***************** PAGE DUMP *******************\n\n" );
printf( "PGNO\tAVAIL\tCHECK\tLEFT\tRIGHT\tFREESPACE\n" );
for( ;
JET_errSuccess == err;
err = ErrDispMove( sesid, tableid, JET_MoveNext, 0 ) )
{
PGNO pgnoThis = pgnoNull;
PGNO pgnoLeft = pgnoNull;
PGNO pgnoRight = pgnoNull;
BYTE fChecked = fFalse;
BYTE fAvail = fFalse;
ULONG cbFreeSpace = 0;
Call( ErrDispRetrieveColumn( sesid,
tableid,
g_rgcolumnidPageInfoTable[icolumnidPageInfoPgno],
(BYTE *) &pgnoThis,
sizeof(pgnoThis),
&cbT,
0,
NULL ) );
Assert( sizeof(pgnoThis) == cbT );
Call( ErrDispRetrieveColumn( sesid,
tableid,
g_rgcolumnidPageInfoTable[icolumnidPageInfoFAvail],
(BYTE *) &fAvail,
sizeof(fAvail),
&cbT,
0,
NULL ) );
Assert( sizeof(fAvail) == cbT || JET_wrnColumnNull == err );
Call( ErrDispRetrieveColumn( sesid,
tableid,
g_rgcolumnidPageInfoTable[icolumnidPageInfoFChecked],
(BYTE *)&fChecked,
sizeof(fChecked),
&cbT,
0,
NULL ) );
Assert( cbT == sizeof(fChecked) );
Assert( fChecked || fAvail );
Call( ErrDispRetrieveColumn( sesid,
tableid,
g_rgcolumnidPageInfoTable[icolumnidPageInfoPgnoLeft],
(BYTE *)&pgnoLeft,
sizeof(pgnoLeft),
&cbT,
0,
NULL ) );
Assert( cbT == sizeof(pgnoLeft) );
Call( ErrDispRetrieveColumn( sesid,
tableid,
g_rgcolumnidPageInfoTable[icolumnidPageInfoPgnoRight],
(BYTE *) &pgnoRight,
sizeof(pgnoRight),
&cbT,
0,
NULL ) );
Assert( cbT == sizeof(pgnoRight) );
Call( ErrDispRetrieveColumn( sesid,
tableid,
g_rgcolumnidPageInfoTable[icolumnidPageInfoFreeSpace],
(BYTE *) &cbFreeSpace,
sizeof(cbFreeSpace),
&cbT,
0,
NULL ) );
Assert( cbT == sizeof(cbFreeSpace) );
printf( "%u\t%s\t%s", pgnoThis, fAvail ? "FAvail" : "", fChecked ? "FCheck" : "" );
if( fChecked )
{
printf( "\t%u\t%u\t%u", pgnoLeft, pgnoRight, cbFreeSpace );
}
printf( "\n" );
}
if ( JET_errNoCurrentRecord == err )
err = JET_errSuccess;
HandleError:
return err;
}
#ifdef DEBUG
LOCAL ERR ErrDBUTLISzToData( const CHAR * const sz, DATA * const pdata )
{
DATA& data = *pdata;
const LONG cch = (LONG)strlen( sz );
if( cch % 2 == 1
|| cch <= 0 )
{
return ErrERRCheck( JET_errInvalidParameter );
}
const LONG cbInsert = cch / 2;
BYTE * pbInsert = (BYTE *)PvOSMemoryHeapAlloc( cbInsert );
if( NULL == pbInsert )
{
return ErrERRCheck( JET_errOutOfMemory );
}
for( INT ibInsert = 0; ibInsert < cbInsert; ++ibInsert )
{
CHAR szConvert[3];
szConvert[0] = sz[ibInsert * 2 ];
szConvert[1] = sz[ibInsert * 2 + 1];
szConvert[2] = 0;
CHAR * pchEnd;
const ULONG lConvert = strtoul( szConvert, &pchEnd, 16 );
if( lConvert > 0xff
|| 0 != *pchEnd )
{
OSMemoryHeapFree( pbInsert );
return ErrERRCheck( JET_errInvalidParameter );
}
pbInsert[ibInsert] = (BYTE)lConvert;
}
data.SetCb( cbInsert );
data.SetPv( pbInsert );
return JET_errSuccess;
}
LOCAL ERR ErrDBUTLIInsertNode(
PIB * const ppib,
const IFMP ifmp,
const PGNO pgno,
const LONG iline,
const DATA& data,
CPRINTF * const pcprintf )
{
ERR err = JET_errSuccess;
CPAGE cpage;
CallR( cpage.ErrGetReadPage( ppib, ifmp, pgno, bflfNoTouch ) );
Call( cpage.ErrUpgradeReadLatchToWriteLatch() );
cpage.Dirty( bfdfFilthy );
(*pcprintf)( "inserting data at %d:%d\r\n", pgno, iline );
cpage.Insert( iline, &data, 1, 0 );
HandleError:
cpage.ReleaseWriteLatch( fTrue );
return err;
}
LOCAL ERR ErrDBUTLIReplaceNode(
PIB * const ppib,
const IFMP ifmp,
const PGNO pgno,
const LONG iline,
const DATA& data,
CPRINTF * const pcprintf )
{
ERR err = JET_errSuccess;
CPAGE cpage;
CallR( cpage.ErrGetReadPage( ppib, ifmp, pgno, bflfNoTouch ) );
Call( cpage.ErrUpgradeReadLatchToWriteLatch() );
cpage.Dirty( bfdfFilthy );
(*pcprintf)( "replacing data at %lu:%d\r\n", pgno, iline );
cpage.Replace( iline, &data, 1, 0 );
HandleError:
cpage.ReleaseWriteLatch( fTrue );
return err;
}
LOCAL ERR ErrDBUTLISetNodeFlags(
PIB * const ppib,
const IFMP ifmp,
const PGNO pgno,
const LONG iline,
const INT fFlags,
CPRINTF * const pcprintf )
{
ERR err = JET_errSuccess;
CPAGE cpage;
CallR( cpage.ErrGetReadPage( ppib, ifmp, pgno, bflfNoTouch ) );
Call( cpage.ErrUpgradeReadLatchToWriteLatch() );
cpage.Dirty( bfdfFilthy );
(*pcprintf)( "settings flags at %lu:%d to 0x%x\r\n", pgno, iline, fFlags );
cpage.ReplaceFlags( iline, fFlags );
HandleError:
cpage.ReleaseWriteLatch( fTrue );
return err;
}
LOCAL ERR ErrDBUTLIDeleteNode(
PIB * const ppib,
const IFMP ifmp,
const PGNO pgno,
const LONG iline,
CPRINTF * const pcprintf )
{
ERR err = JET_errSuccess;
CPAGE cpage;
CallR( cpage.ErrGetReadPage( ppib, ifmp, pgno, bflfNoTouch ) );
Call( cpage.ErrUpgradeReadLatchToWriteLatch() );
cpage.Dirty( bfdfFilthy );
(*pcprintf)( "deleting %lu:%d\r\n", pgno, iline );
cpage.Delete( iline );
HandleError:
cpage.ReleaseWriteLatch( fTrue );
return err;
}
LOCAL ERR ErrDBUTLISetExternalHeader(
PIB * const ppib,
const IFMP ifmp,
const PGNO pgno,
const DATA& data,
CPRINTF * const pcprintf )
{
ERR err = JET_errSuccess;
CPAGE cpage;
CallR( cpage.ErrGetReadPage( ppib, ifmp, pgno, bflfNoTouch ) );
Call( cpage.ErrUpgradeReadLatchToWriteLatch() );
cpage.Dirty( bfdfFilthy );
(*pcprintf)( "setting external header of %lu\r\n", pgno );
cpage.SetExternalHeader( &data, 1, 0 );
HandleError:
cpage.ReleaseWriteLatch( fTrue );
return err;
}
LOCAL ERR ErrDBUTLISetPgnoNext(
PIB * const ppib,
const IFMP ifmp,
const PGNO pgno,
const PGNO pgnoNext,
CPRINTF * const pcprintf )
{
ERR err = JET_errSuccess;
CPAGE cpage;
CallR( cpage.ErrGetReadPage( ppib, ifmp, pgno, bflfNoTouch ) );
Call( cpage.ErrUpgradeReadLatchToWriteLatch() );
cpage.Dirty( bfdfFilthy );
(*pcprintf)( "setting pgnoNext of %lu to %lu (was %lu)\r\n", pgno, pgnoNext, cpage.PgnoNext() );
cpage.SetPgnoNext( pgnoNext );
HandleError:
cpage.ReleaseWriteLatch( fTrue );
return err;
}
LOCAL ERR ErrDBUTLISetPgnoPrev(
PIB * const ppib,
const IFMP ifmp,
const PGNO pgno,
const PGNO pgnoPrev,
CPRINTF * const pcprintf )
{
ERR err = JET_errSuccess;
CPAGE cpage;
CallR( cpage.ErrGetReadPage( ppib, ifmp, pgno, bflfNoTouch ) );
Call( cpage.ErrUpgradeReadLatchToWriteLatch() );
cpage.Dirty( bfdfFilthy );
(*pcprintf)( "setting pgnoPrev of %lu to %lu (was %lu)\r\n", pgno, pgnoPrev, cpage.PgnoPrev() );
cpage.SetPgnoPrev( pgnoPrev );
HandleError:
cpage.ReleaseWriteLatch( fTrue );
return err;
}
LOCAL ERR ErrDBUTLISetPageFlags(
PIB * const ppib,
const IFMP ifmp,
const PGNO pgno,
const ULONG fFlags,
CPRINTF * const pcprintf )
{
ERR err = JET_errSuccess;
CPAGE cpage;
CallR( cpage.ErrGetReadPage( ppib, ifmp, pgno, bflfNoTouch ) );
Call( cpage.ErrUpgradeReadLatchToWriteLatch() );
cpage.Dirty( bfdfFilthy );
(*pcprintf)( "setting flags of %lu to 0x%x (was 0x%x)\r\n", pgno, fFlags, cpage.FFlags() );
cpage.SetFlags( fFlags );
HandleError:
cpage.ReleaseWriteLatch( fTrue );
return err;
}
LOCAL_BROKEN ERR ErrDBUTLMungeDatabase(
PIB * const ppib,
const IFMP ifmp,
const CHAR * const rgszCommand[],
const INT cszCommand,
CPRINTF * const pcprintf )
{
ERR err = JET_errSuccess;
if( 3 == cszCommand
&& _stricmp( rgszCommand[0], "insert" ) == 0 )
{
PGNO pgno;
LONG iline;
DATA data;
if( 2 != sscanf_s( rgszCommand[1], "%lu:%d", &pgno, &iline ) )
{
return ErrERRCheck( JET_errInvalidParameter );
}
CallR( ErrDBUTLISzToData( rgszCommand[2], &data ) );
err = ErrDBUTLIInsertNode( ppib, ifmp, pgno, iline, data, pcprintf );
OSMemoryHeapFree( data.Pv() );
return err;
}
if( 3 == cszCommand
&& _stricmp( rgszCommand[0], "replace" ) == 0 )
{
PGNO pgno;
LONG iline;
DATA data;
if( 2 != sscanf_s( rgszCommand[1], "%lu:%d", &pgno, &iline ) )
{
return ErrERRCheck( JET_errInvalidParameter );
}
CallR( ErrDBUTLISzToData( rgszCommand[2], &data ) );
err = ErrDBUTLIReplaceNode( ppib, ifmp, pgno, iline, data, pcprintf );
OSMemoryHeapFree( data.Pv() );
return err;
}
if( 3 == cszCommand
&& _stricmp( rgszCommand[0], "setflags" ) == 0 )
{
PGNO pgno;
LONG iline;
if( 2 != sscanf_s( rgszCommand[1], "%lu:%d", &pgno, &iline ) )
{
return ErrERRCheck( JET_errInvalidParameter );
}
const ULONG fFlags = strtoul( rgszCommand[2], NULL, 0 );
err = ErrDBUTLISetNodeFlags( ppib, ifmp, pgno, iline, fFlags, pcprintf );
return err;
}
else if( 2 == cszCommand
&& _stricmp( rgszCommand[0], "delete" ) == 0 )
{
PGNO pgno;
LONG iline;
if( 2 != sscanf_s( rgszCommand[1], "%lu:%d", &pgno, &iline ) )
{
return ErrERRCheck( JET_errInvalidParameter );
}
err = ErrDBUTLIDeleteNode( ppib, ifmp, pgno, iline, pcprintf );
return err;
}
if( 3 == cszCommand
&& _stricmp( rgszCommand[0], "exthdr" ) == 0 )
{
char * pchEnd;
const PGNO pgno = strtoul( rgszCommand[1], &pchEnd, 0 );
if( pgnoNull == pgno
|| 0 != *pchEnd )
{
return ErrERRCheck( JET_errInvalidParameter );
}
DATA data;
CallR( ErrDBUTLISzToData( rgszCommand[2], &data ) );
err = ErrDBUTLISetExternalHeader( ppib, ifmp, pgno, data, pcprintf );
OSMemoryHeapFree( data.Pv() );
return err;
}
if( 3 == cszCommand
&& _stricmp( rgszCommand[0], "pgnonext" ) == 0 )
{
char * pchEnd;
const PGNO pgno = strtoul( rgszCommand[1], &pchEnd, 0 );
if( pgnoNull == pgno
|| 0 != *pchEnd )
{
return ErrERRCheck( JET_errInvalidParameter );
}
const PGNO pgnoNext = strtoul( rgszCommand[2], NULL, 0 );
if( 0 != *pchEnd )
{
return ErrERRCheck( JET_errInvalidParameter );
}
err = ErrDBUTLISetPgnoNext( ppib, ifmp, pgno, pgnoNext, pcprintf );
return err;
}
if( 3 == cszCommand
&& _stricmp( rgszCommand[0], "pgnoprev" ) == 0 )
{
char * pchEnd;
const PGNO pgno = strtoul( rgszCommand[1], &pchEnd, 0 );
if( pgnoNull == pgno
|| 0 != *pchEnd )
{
return ErrERRCheck( JET_errInvalidParameter );
}
const PGNO pgnoPrev = strtoul( rgszCommand[2], NULL, 0 );
if( 0 != *pchEnd )
{
return ErrERRCheck( JET_errInvalidParameter );
}
err = ErrDBUTLISetPgnoPrev( ppib, ifmp, pgno, pgnoPrev, pcprintf );
return err;
}
if( 3 == cszCommand
&& _stricmp( rgszCommand[0], "pageflags" ) == 0 )
{
char * pchEnd;
const PGNO pgno = strtoul( rgszCommand[1], &pchEnd, 0 );
if( pgnoNull == pgno
|| 0 != *pchEnd )
{
return ErrERRCheck( JET_errInvalidParameter );
}
const ULONG fFlags = strtoul( rgszCommand[2], NULL, 0 );
if( 0 != *pchEnd )
{
return ErrERRCheck( JET_errInvalidParameter );
}
err = ErrDBUTLISetPageFlags( ppib, ifmp, pgno, fFlags, pcprintf );
return err;
}
if( 1 == cszCommand
&& _stricmp( rgszCommand[0], "help" ) == 0 )
{
(*pcprintf)( "insert <pgno>:<iline> <data> - insert a node\r\n" );
(*pcprintf)( "replace <pgno>:<iline> <data> - replace a node\r\n" );
(*pcprintf)( "delete <pgno>:<iline> - delete a node\r\n" );
(*pcprintf)( "setflags <pgno>:<iline> <flags> - set flags on a node\r\n" );
(*pcprintf)( "exthdr <pgno> <data> - set external header\r\n" );
(*pcprintf)( "pgnonext <pgno> <pgnonext> - set pgnonext on a page\r\n" );
(*pcprintf)( "pgnoprev <pgno> <pgnoprev> - set pgnoprev on a page\r\n" );
(*pcprintf)( "pageflags <pgno> <flags> - set flags on a page\r\n" );
}
else
{
(*pcprintf)( "unknown command \"%s\"\r\n", rgszCommand[0] );
return ErrERRCheck( JET_errInvalidParameter );
}
return err;
}
#endif
LOCAL ERR ErrDBUTLDumpOneColumn( PIB * ppib, FUCB * pfucbCatalog, VOID * pfnCallback, VOID * pvCallback )
{
JET_RETRIEVECOLUMN rgretrievecolumn[10];
COLUMNDEF columndef;
ERR err = JET_errSuccess;
INT iretrievecolumn = 0;
memset( rgretrievecolumn, 0, sizeof( rgretrievecolumn ) );
memset( &columndef, 0, sizeof( columndef ) );
rgretrievecolumn[iretrievecolumn].columnid = fidMSO_Name;
rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)columndef.szName;
rgretrievecolumn[iretrievecolumn].cbData = sizeof( columndef.szName );
rgretrievecolumn[iretrievecolumn].itagSequence = 1;
++iretrievecolumn;
rgretrievecolumn[iretrievecolumn].columnid = fidMSO_Id;
rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)&( columndef.columnid );
rgretrievecolumn[iretrievecolumn].cbData = sizeof( columndef.columnid );
rgretrievecolumn[iretrievecolumn].itagSequence = 1;
++iretrievecolumn;
rgretrievecolumn[iretrievecolumn].columnid = fidMSO_Coltyp;
rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)&( columndef.coltyp );
rgretrievecolumn[iretrievecolumn].cbData = sizeof( columndef.coltyp );
rgretrievecolumn[iretrievecolumn].itagSequence = 1;
++iretrievecolumn;
rgretrievecolumn[iretrievecolumn].columnid = fidMSO_Localization;
rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)&( columndef.cp );
rgretrievecolumn[iretrievecolumn].cbData = sizeof( columndef.cp );
rgretrievecolumn[iretrievecolumn].itagSequence = 1;
++iretrievecolumn;
rgretrievecolumn[iretrievecolumn].columnid = fidMSO_Flags;
rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)&( columndef.fFlags );
rgretrievecolumn[iretrievecolumn].cbData = sizeof( columndef.fFlags );
rgretrievecolumn[iretrievecolumn].itagSequence = 1;
++iretrievecolumn;
rgretrievecolumn[iretrievecolumn].columnid = fidMSO_SpaceUsage;
rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)&( columndef.cbLength );
rgretrievecolumn[iretrievecolumn].cbData = sizeof( columndef.cbLength );
rgretrievecolumn[iretrievecolumn].itagSequence = 1;
++iretrievecolumn;
rgretrievecolumn[iretrievecolumn].columnid = fidMSO_RecordOffset;
rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)&( columndef.ibRecordOffset );
rgretrievecolumn[iretrievecolumn].cbData = sizeof( columndef.ibRecordOffset );
rgretrievecolumn[iretrievecolumn].itagSequence = 1;
++iretrievecolumn;
rgretrievecolumn[iretrievecolumn].columnid = fidMSO_Callback;
rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)&( columndef.szCallback );
rgretrievecolumn[iretrievecolumn].cbData = sizeof( columndef.szCallback );
rgretrievecolumn[iretrievecolumn].itagSequence = 1;
++iretrievecolumn;
rgretrievecolumn[iretrievecolumn].columnid = fidMSO_CallbackData;
rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)&( columndef.rgbCallbackData );
rgretrievecolumn[iretrievecolumn].cbData = sizeof( columndef.rgbCallbackData );
rgretrievecolumn[iretrievecolumn].itagSequence = 1;
++iretrievecolumn;
rgretrievecolumn[iretrievecolumn].columnid = fidMSO_DefaultValue;
rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)columndef.rgbDefaultValue;
rgretrievecolumn[iretrievecolumn].cbData = sizeof( columndef.rgbDefaultValue );
rgretrievecolumn[iretrievecolumn].itagSequence = 1;
++iretrievecolumn;
CallR( ErrIsamRetrieveColumns(
(JET_SESID)ppib,
(JET_TABLEID)pfucbCatalog,
rgretrievecolumn,
iretrievecolumn ) );
columndef.cbDefaultValue = rgretrievecolumn[iretrievecolumn-1].cbActual;
columndef.cbCallbackData = rgretrievecolumn[iretrievecolumn-2].cbActual;
columndef.fFixed = !!FFixedFid( FidOfColumnid( columndef.columnid ) );
columndef.fVariable = !!FVarFid( FidOfColumnid( columndef.columnid ) );
columndef.fTagged = !!FTaggedFid( FidOfColumnid( columndef.columnid ) );
const FIELDFLAG ffield = FIELDFLAG( columndef.fFlags );
columndef.fVersion = !!FFIELDVersion( ffield );
columndef.fNotNull = !!FFIELDNotNull( ffield );
columndef.fMultiValue = !!FFIELDMultivalued( ffield );
columndef.fAutoIncrement = !!FFIELDAutoincrement( ffield );
columndef.fDefaultValue = !!FFIELDDefault( ffield );
columndef.fEscrowUpdate = !!FFIELDEscrowUpdate( ffield );
columndef.fVersioned = !!FFIELDVersioned( ffield );
columndef.fDeleted = !!FFIELDDeleted( ffield );
columndef.fFinalize = !!FFIELDFinalize( ffield );
columndef.fDeleteOnZero = !!FFIELDDeleteOnZero( ffield );
columndef.fUserDefinedDefault = !!FFIELDUserDefinedDefault( ffield );
columndef.fTemplateColumnESE98 = !!FFIELDTemplateColumnESE98( ffield );
columndef.fPrimaryIndexPlaceholder = !!FFIELDPrimaryIndexPlaceholder( ffield );
columndef.fCompressed = !!FFIELDCompressed( ffield );
columndef.fEncrypted = !!FFIELDEncrypted( ffield );
PFNCOLUMN const pfncolumn = (PFNCOLUMN)pfnCallback;
return (*pfncolumn)( &columndef, pvCallback );
}
LOCAL ERR ErrDBUTLDumpOneCallback( PIB * ppib, FUCB * pfucbCatalog, VOID * pfnCallback, VOID * pvCallback )
{
JET_RETRIEVECOLUMN rgretrievecolumn[3];
CALLBACKDEF callbackdef;
ERR err = JET_errSuccess;
INT iretrievecolumn = 0;
memset( rgretrievecolumn, 0, sizeof( rgretrievecolumn ) );
memset( &callbackdef, 0, sizeof( callbackdef ) );
rgretrievecolumn[iretrievecolumn].columnid = fidMSO_Name;
rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)callbackdef.szName;
rgretrievecolumn[iretrievecolumn].cbData = sizeof( callbackdef.szName );
rgretrievecolumn[iretrievecolumn].itagSequence = 1;
++iretrievecolumn;
rgretrievecolumn[iretrievecolumn].columnid = fidMSO_Flags;
rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)&( callbackdef.cbtyp );
rgretrievecolumn[iretrievecolumn].cbData = sizeof( callbackdef.cbtyp );
rgretrievecolumn[iretrievecolumn].itagSequence = 1;
++iretrievecolumn;
rgretrievecolumn[iretrievecolumn].columnid = fidMSO_Callback;
rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)callbackdef.szCallback;
rgretrievecolumn[iretrievecolumn].cbData = sizeof( callbackdef.szCallback );
rgretrievecolumn[iretrievecolumn].itagSequence = 1;
++iretrievecolumn;
CallR( ErrIsamRetrieveColumns(
(JET_SESID)ppib,
(JET_TABLEID)pfucbCatalog,
rgretrievecolumn,
iretrievecolumn ) );
PFNCALLBACKFN const pfncallback = (PFNCALLBACKFN)pfnCallback;
return (*pfncallback)( &callbackdef, pvCallback );
}
LOCAL ERR ErrDBUTLDumpPage( PIB * ppib, IFMP ifmp, PGNO pgno, PFNPAGE pfnpage, VOID * pvCallback )
{
ERR err = JET_errSuccess;
CSR csr;
Call( csr.ErrGetReadPage( ppib, ifmp, pgno, bflfNoTouch ) );
PAGEDEF pagedef;
pagedef.dbtime = csr.Cpage().Dbtime();
pagedef.pgno = pgno;
pagedef.objidFDP = csr.Cpage().ObjidFDP();
pagedef.pgnoNext = csr.Cpage().PgnoNext();
pagedef.pgnoPrev = csr.Cpage().PgnoPrev();
pagedef.pbRawPage = reinterpret_cast<BYTE *>( csr.Cpage().PvBuffer() );
pagedef.cbFree = csr.Cpage().CbPageFree();
pagedef.cbUncommittedFree = csr.Cpage().CbUncommittedFree();
pagedef.clines = SHORT( csr.Cpage().Clines() );
pagedef.fFlags = csr.Cpage().FFlags();
pagedef.fLeafPage = !!csr.Cpage().FLeafPage();
pagedef.fInvisibleSons = !!csr.Cpage().FInvisibleSons();
pagedef.fRootPage = !!csr.Cpage().FRootPage();
pagedef.fPrimaryPage = !!csr.Cpage().FPrimaryPage();
pagedef.fParentOfLeaf = !!csr.Cpage().FParentOfLeaf();
if( pagedef.fInvisibleSons )
{
Assert( !pagedef.fLeafPage );
INT iline;
for( iline = 0; iline < pagedef.clines; iline++ )
{
KEYDATAFLAGS kdf;
csr.SetILine( iline );
NDIGetKeydataflags( csr.Cpage(), csr.ILine(), &kdf );
Assert( kdf.data.Cb() == sizeof( PGNO ) );
pagedef.rgpgnoChildren[iline] = *((UnalignedLittleEndian< PGNO > *)kdf.data.Pv() );
}
pagedef.rgpgnoChildren[pagedef.clines] = pgnoNull;
}
else
{
Assert( pagedef.fLeafPage );
}
Call( (*pfnpage)( &pagedef, pvCallback ) );
HandleError:
csr.ReleasePage();
return err;
}
LOCAL INT PrintCallback( const CALLBACKDEF * pcallbackdef, void * )
{
PFNCALLBACKFN pfncallback = PrintCallback;
Unused( pfncallback );
char szCbtyp[255];
szCbtyp[0] = 0;
if( JET_cbtypNull == pcallbackdef->cbtyp )
{
OSStrCbAppendA( szCbtyp, sizeof(szCbtyp), "NULL" );
}
if( pcallbackdef->cbtyp & JET_cbtypFinalize )
{
OSStrCbAppendA( szCbtyp, sizeof(szCbtyp), "Finalize|" );
}
if( pcallbackdef->cbtyp & JET_cbtypBeforeInsert )
{
OSStrCbAppendA( szCbtyp, sizeof(szCbtyp), "BeforeInsert|" );
}
if( pcallbackdef->cbtyp & JET_cbtypAfterInsert )
{
OSStrCbAppendA( szCbtyp, sizeof(szCbtyp), "AfterInsert|" );
}
if( pcallbackdef->cbtyp & JET_cbtypBeforeReplace )
{
OSStrCbAppendA( szCbtyp, sizeof(szCbtyp), "BeforeReplace|" );
}
if( pcallbackdef->cbtyp & JET_cbtypAfterReplace )
{
OSStrCbAppendA( szCbtyp, sizeof(szCbtyp), "AfterReplace|" );
}
if( pcallbackdef->cbtyp & JET_cbtypBeforeDelete )
{
OSStrCbAppendA( szCbtyp, sizeof(szCbtyp), "BeforeDelete|" );
}
if( pcallbackdef->cbtyp & JET_cbtypAfterDelete )
{
OSStrCbAppendA( szCbtyp, sizeof(szCbtyp), "AfterDelete|" );
}
szCbtyp[strlen( szCbtyp ) - 1] = 0;
printf( " %2.2d (%s) %s\n", pcallbackdef->cbtyp, szCbtyp, pcallbackdef->szCallback );
return 0;
}
LOCAL VOID PrintSpaceHintMetaData(
__in const CHAR * const szIndent,
__in const CHAR * const szObjectType,
__in const JET_SPACEHINTS * const pSpaceHints )
{
printf( "%s%s Space Hints: cbStruct: %d, grbit=0x%x\n", szIndent, szObjectType,
pSpaceHints->cbStruct, pSpaceHints->grbit );
printf( "%s Densities: Initial=%u%%, Maintenance=%u%%\n", szIndent,
pSpaceHints->ulInitialDensity , pSpaceHints->ulMaintDensity );
printf( "%s Growth Hints: cbInitial=%u, ulGrowth=%u%%, cbMinExtent=%u, cbMaxExtent=%u\n", szIndent,
pSpaceHints->cbInitial, pSpaceHints->ulGrowth,
pSpaceHints->cbMinExtent, pSpaceHints->cbMaxExtent );
}
LOCAL INT PrintIndexMetaData( const INDEXDEF * pindexdef, void * )
{
PFNINDEX pfnindex = PrintIndexMetaData;
Unused( pfnindex );
Assert( pindexdef );
printf( " %-15.15s ", pindexdef->szName );
DBUTLPrintfIntN( pindexdef->pgnoFDP, 8 );
printf( " " );
DBUTLPrintfIntN( pindexdef->objidFDP, 8 );
printf( " " );
DBUTLPrintfIntN( pindexdef->density, 6 );
printf( "%%\n" );
if ( pindexdef->fUnique )
printf( " Unique=yes\n" );
if ( pindexdef->fPrimary )
printf( " Primary=yes\n" );
if ( pindexdef->fTemplateIndex )
printf( " Template=yes\n" );
if ( pindexdef->fDerivedIndex )
printf( " Derived=yes\n" );
if ( pindexdef->fNoNullSeg )
printf( " Disallow Null=yes\n" );
if ( pindexdef->fAllowAllNulls )
printf( " Allow All Nulls=yes\n" );
if ( pindexdef->fAllowFirstNull )
printf( " Allow First Null=yes\n" );
if ( pindexdef->fAllowSomeNulls )
printf( " Allow Some Nulls=yes\n" );
if ( pindexdef->fSortNullsHigh )
printf( " Sort Nulls High=yes\n" );
if ( pindexdef->fMultivalued )
printf( " Multivalued=yes\n" );
if ( pindexdef->fTuples )
{
printf( " Tuples=yes\n" );
printf( " LengthMin=%d\n", (ULONG) pindexdef->le_tuplelimits.le_chLengthMin );
printf( " LengthMax=%d\n", (ULONG) pindexdef->le_tuplelimits.le_chLengthMax );
printf( " ToIndexMax=%d\n", (ULONG) pindexdef->le_tuplelimits.le_chToIndexMax );
printf( " CchIncrement=%d\n", (ULONG) pindexdef->le_tuplelimits.le_cchIncrement );
printf( " IchStart=%d\n", (ULONG) pindexdef->le_tuplelimits.le_ichStart );
}
if ( pindexdef->fLocalizedText )
{
WCHAR wszLocaleName[NORM_LOCALE_NAME_MAX_LENGTH];
QWORD qwCurrSortVersion;
SORTID sortID;
printf( " Localized Text=yes\n" );
printf( " Locale Id=%d\n", pindexdef->lcid );
printf( " Locale Name=%ws\n", pindexdef->wszLocaleName );
printf( " LCMap flags=0x%08x\n", pindexdef->dwMapFlags );
if ( ( ( 0 != pindexdef->lcid ) &&
JET_errSuccess == ErrNORMLcidToLocale( pindexdef->lcid, wszLocaleName, _countof( wszLocaleName ) ) &&
JET_errSuccess == ErrNORMGetSortVersion( wszLocaleName, &qwCurrSortVersion, &sortID ) ) ||
( JET_errSuccess == ErrNORMGetSortVersion( pindexdef->wszLocaleName, &qwCurrSortVersion, &sortID ) ) )
{
WCHAR wszSortID[ PERSISTED_SORTID_MAX_LENGTH ] = L"";
WCHAR wszIndexDefSortID[ PERSISTED_SORTID_MAX_LENGTH ] = L"";
WszCATFormatSortID( pindexdef->sortID, wszIndexDefSortID, _countof( wszIndexDefSortID ) );
WszCATFormatSortID( sortID, wszSortID, _countof( wszSortID ) );
printf( " NLSVersion=%d (current OS: %d)\n", pindexdef->dwNLSVersion, DWORD( ( qwCurrSortVersion >> 32 ) & 0xFFFFFFFF ) );
printf( " DefinedVersion=%d (current OS: %d)\n", pindexdef->dwDefinedVersion, DWORD( qwCurrSortVersion & 0xFFFFFFFF ) );
printf( " SortID=%ws (current OS: %ws)\n", wszIndexDefSortID, wszSortID );
}
else
{
WCHAR wszIndexDefSortID[ PERSISTED_SORTID_MAX_LENGTH ] = L"";
WszCATFormatSortID( pindexdef->sortID, wszIndexDefSortID, _countof( wszIndexDefSortID ) );
printf( " NLSVersion=%d (current OS: <unknown>)\n", pindexdef->dwNLSVersion );
printf( " DefinedVersion=%d (current OS: <unknown>)\n", pindexdef->dwDefinedVersion );
printf( " SortID=%ws (current OS: <unknown>)\n", wszIndexDefSortID );
}
}
if ( pindexdef->fExtendedColumns )
printf( " Extended Columns=yes\n" );
printf( " Flags=0x%08x\n", pindexdef->fFlags );
if ( pindexdef->cbVarSegMac )
{
printf( " Index Key Segment Length Specified=yes\n" );
printf( " Maximum Key Segment Length=0x%08x\n", pindexdef->cbVarSegMac );
}
if ( pindexdef->cbKeyMost )
{
printf( " Index Key Length Specified=yes\n" );
printf( " Maximum Key Length=0x%08x\n", pindexdef->cbKeyMost );
}
PrintSpaceHintMetaData( " ", "Index", &(pindexdef->spacehints) );
UINT isz;
Assert( pindexdef->ccolumnidDef > 0 );
if ( pindexdef->fExtendedColumns )
{
printf( " Key Segments (%d)\n", pindexdef->ccolumnidDef );
printf( " -----------------\n" );
}
else
{
printf( " Key Segments (%d - ESE97 format)\n", pindexdef->ccolumnidDef );
printf( " --------------------------------\n" );
}
for( isz = 0; isz < (ULONG)pindexdef->ccolumnidDef; isz++ )
{
printf( " %-15.15s (0x%08x)\n", pindexdef->rgszIndexDef[isz], pindexdef->rgidxsegDef[isz].Columnid() );
}
if( pindexdef->ccolumnidConditional > 0 )
{
if ( pindexdef->fExtendedColumns )
{
printf( " Conditional Columns (%d)\n", pindexdef->ccolumnidConditional );
printf( " ------------------------\n" );
}
else
{
printf( " Conditional Columns (%d - ESE97 format)\n", pindexdef->ccolumnidConditional );
printf( " ---------------------------------------\n" );
}
for( isz = 0; isz < (ULONG)pindexdef->ccolumnidConditional; isz++ )
{
printf( " %-15.15s (0x%08x,%s)\n",
( pindexdef->rgszIndexConditional[isz] ) + 1,
pindexdef->rgidxsegConditional[isz].Columnid(),
( pindexdef->rgidxsegConditional[isz] ).FMustBeNull() ? "JET_bitIndexColumnMustBeNull" : "JET_bitIndexColumnMustBeNonNull" );
}
}
return 0;
}
LOCAL INT PrintColumn( const COLUMNDEF * pcolumndef, void * )
{
PFNCOLUMN pfncolumn = PrintColumn;
Unused( pfncolumn );
Assert( pcolumndef );
printf( " %-15.15s ", pcolumndef->szName );
DBUTLPrintfIntN( pcolumndef->columnid, 9 );
const CHAR * szType;
const CHAR * szFVT;
CHAR szUnknown[50];
if( pcolumndef->fFixed )
{
szFVT = "(F)";
}
else if( pcolumndef->fTagged )
{
szFVT = "(T)";
}
else if( pcolumndef->fVariable )
{
szFVT = "(V)";
}
else
{
AssertSz( fFalse, "Unknown column type is not fixed, tagged, or variable." );
szFVT = "(?)";
}
switch ( pcolumndef->coltyp )
{
case JET_coltypBit:
szType = "Bit";
break;
case JET_coltypUnsignedByte:
szType = "UnsignedByte";
break;
case JET_coltypShort:
szType = "Short";
break;
case JET_coltypUnsignedShort:
szType = "UnsignedShort";
break;
case JET_coltypLong:
szType = "Long";
break;
case JET_coltypUnsignedLong:
szType = "UnsignedLong";
break;
case JET_coltypLongLong:
szType = "LongLong";
break;
case JET_coltypUnsignedLongLong:
szType = "UnsignedLongLong";
break;
case JET_coltypCurrency:
szType = "Currency";
break;
case JET_coltypIEEESingle:
szType = "IEEESingle";
break;
case JET_coltypIEEEDouble:
szType = "IEEEDouble";
break;
case JET_coltypDateTime:
szType = "DateTime";
break;
case JET_coltypGUID:
szType = "GUID";
break;
case JET_coltypBinary:
szType = "Binary";
break;
case JET_coltypText:
szType = "Text";
break;
case JET_coltypLongBinary:
szType = "LongBinary";
break;
case JET_coltypLongText:
szType = "LongText";
break;
case JET_coltypNil:
szType = "Deleted";
break;
default:
OSStrCbFormatA( szUnknown, sizeof(szUnknown), "???(%d)", pcolumndef->coltyp );
szType = szUnknown;
break;
}
printf(" %-12.12s%3.3s ", szType, szFVT );
if ( pcolumndef->cbLength > 9999999 )
{
DBUTLPrintfIntN( pcolumndef->cbLength / ( 1024 * 1024 ), 5 );
printf("MB");
}
else
{
DBUTLPrintfIntN( pcolumndef->cbLength, 7 );
}
if ( 0 != pcolumndef->cbDefaultValue )
{
printf( " Yes" );
}
printf( "\n" );
if ( pcolumndef->fFixed )
printf( " Offset=%d (0x%x)\n", pcolumndef->ibRecordOffset, pcolumndef->ibRecordOffset );
if ( FRECTextColumn( pcolumndef->coltyp ) )
{
printf( " Code Page=%d (0x%x)\n", pcolumndef->cp, pcolumndef->cp );
}
if ( pcolumndef->fVersion )
printf( " Version=yes\n" );
if ( pcolumndef->fNotNull )
printf( " Disallow Null=yes\n" );
if ( pcolumndef->fMultiValue )
printf( " Multi-value=yes\n" );
if ( pcolumndef->fAutoIncrement )
printf( " Auto-increment=yes\n" );
if ( pcolumndef->fEscrowUpdate )
printf( " EscrowUpdate=yes\n" );
if ( pcolumndef->fFinalize )
printf( " Finalize=yes\n" );
if ( pcolumndef->fDeleteOnZero )
printf( " DeleteOnZero=yes\n" );
if ( pcolumndef->fDefaultValue )
{
printf( " DefaultValue=yes\n" );
printf( " Length=%d bytes\n", pcolumndef->cbDefaultValue );
}
if ( pcolumndef->fUserDefinedDefault )
{
printf( " User-defined Default=yes\n" );
printf( " Callback=%s\n", pcolumndef->szCallback );
printf( " CallbackData=%d bytes\n", pcolumndef->cbCallbackData );
}
if ( pcolumndef->fTemplateColumnESE98 )
printf( " TemplateColumnESE98=yes\n" );
if ( pcolumndef->fPrimaryIndexPlaceholder )
printf( " PrimaryIndexPlaceholder=yes\n" );
if ( pcolumndef->fCompressed )
printf( " Compressed=yes\n" );
if ( pcolumndef->fEncrypted )
printf( " Encrypted=yes\n" );
printf( " Flags=0x%x\n", pcolumndef->fFlags );
return 0;
}
LOCAL INT PrintTableMetaData( const TABLEDEF * ptabledef, void * pv )
{
PFNTABLE pfntable = PrintTableMetaData;
Unused( pfntable );
Assert( ptabledef );
JET_DBUTIL_A * pdbutil = (JET_DBUTIL_A *)pv;
printf( "Table Name PgnoFDP ObjidFDP PgnoLV ObjidLV Pages Density\n"
"==========================================================================\n"
"%hs\n", ptabledef->szName );
printf( " " );
DBUTLPrintfIntN( ptabledef->pgnoFDP, 8 );
printf( " " );
DBUTLPrintfIntN( ptabledef->objidFDP, 8 );
printf( " " );
DBUTLPrintfIntN( ptabledef->pgnoFDPLongValues, 8 );
printf( " " );
DBUTLPrintfIntN( ptabledef->objidFDPLongValues, 8 );
printf( " " );
DBUTLPrintfIntN( ptabledef->pages, 8 );
printf( " " );
DBUTLPrintfIntN( ptabledef->density, 6 );
printf( "%%\n" );
printf( " LV ChunkSize=%d\n", ptabledef->cbLVChunkMax );
if ( ptabledef->fFlags & JET_bitObjectSystem )
printf( " System Table=yes\n" );
if ( ptabledef->fFlags & JET_bitObjectTableFixedDDL )
printf( " FixedDDL=yes\n" );
if ( ptabledef->fFlags & JET_bitObjectTableTemplate )
printf( " Template=yes\n" );
if ( NULL != ptabledef->szTemplateTable
&& '\0' != ptabledef->szTemplateTable[0] )
{
Assert( ptabledef->fFlags & JET_bitObjectTableDerived );
printf( " Derived From: %5s\n", ptabledef->szTemplateTable );
}
else
{
Assert( !( ptabledef->fFlags & JET_bitObjectTableDerived ) );
}
PrintSpaceHintMetaData( " ", "Table", &(ptabledef->spacehints) );
if ( ptabledef->spacehintsDeferredLV.cbStruct == sizeof(ptabledef->spacehintsDeferredLV) )
{
PrintSpaceHintMetaData( " ", "Deferred LV", &(ptabledef->spacehintsDeferredLV) );
}
JET_DBUTIL_W dbutil;
ERR err = JET_errSuccess;
printf( " Column Name Column Id Column Type Length Default\n"
" -----------------------------------------------------------\n" );
memset( &dbutil, 0, sizeof( dbutil ) );
dbutil.cbStruct = sizeof( dbutil );
dbutil.op = opDBUTILEDBDump;
dbutil.sesid = pdbutil->sesid;
dbutil.dbid = pdbutil->dbid;
dbutil.pgno = ptabledef->objidFDP;
dbutil.pfnCallback = (void *)PrintColumn;
dbutil.pvCallback = &dbutil;
dbutil.edbdump = opEDBDumpColumns;
err = ErrDBUTLDump( pdbutil->sesid, &dbutil );
printf( " Index Name PgnoFDP ObjidFDP Density\n"
" --------------------------------------------\n" );
memset( &dbutil, 0, sizeof( dbutil ) );
dbutil.cbStruct = sizeof( dbutil );
dbutil.op = opDBUTILEDBDump;
dbutil.sesid = pdbutil->sesid;
dbutil.dbid = pdbutil->dbid;
dbutil.pgno = ptabledef->objidFDP;
dbutil.pfnCallback = (void *)PrintIndexMetaData;
dbutil.pvCallback = &dbutil;
dbutil.edbdump = opEDBDumpIndexes;
err = ErrDBUTLDump( pdbutil->sesid, &dbutil );
printf( " Callback Type Callback\n"
" --------------------------------------------\n" );
memset( &dbutil, 0, sizeof( dbutil ) );
dbutil.cbStruct = sizeof( dbutil );
dbutil.op = opDBUTILEDBDump;
dbutil.sesid = pdbutil->sesid;
dbutil.dbid = pdbutil->dbid;
dbutil.pgno = ptabledef->objidFDP;
dbutil.pfnCallback = (void *)PrintCallback;
dbutil.pvCallback = &dbutil;
dbutil.edbdump = opEDBDumpCallbacks;
err = ErrDBUTLDump( pdbutil->sesid, &dbutil );
return err;
}
ERR ErrDBUTLGetIfmpFucbOfPage(
_Inout_ JET_SESID sesid,
PCWSTR wszDatabase,
_In_ const CPAGE& cpage,
_Out_ IFMP * pifmp,
_Out_ FUCB ** ppfucb,
_Out_writes_bytes_opt_(cbObjName) WCHAR * wszObjName = NULL,
_In_ ULONG cbObjName = 0 );
#define cbDbutlObjNameMost ( JET_cbNameMost + 40 + 1 )
ERR ErrDBUTLGetIfmpFucbOfPage( _Inout_ JET_SESID sesid, PCWSTR wszDatabase, _In_ const CPAGE& cpage, _Out_ IFMP * pifmp, _Out_ FUCB ** ppfucbObj, _Out_writes_bytes_opt_(cbObjName) WCHAR * wszObjName, _In_ ULONG cbObjName )
{
ERR err = JET_errSuccess;
JET_DBID jdbid = JET_dbidNil;
*pifmp = ifmpNil;
*ppfucbObj = pfucbNil;
TRY
{
(void)SetParam( reinterpret_cast<PIB*>( sesid )->m_pinst, NULL, JET_paramEnableIndexChecking, JET_IndexCheckingOff, NULL );
Call( ErrIsamAttachDatabase( sesid, wszDatabase, fFalse, NULL, 0, JET_bitDbReadOnly ) );
err = ErrIsamOpenDatabase( sesid, wszDatabase, NULL, &jdbid, JET_bitDbReadOnly );
if ( err < JET_errSuccess )
{
CallS( ErrIsamDetachDatabase( sesid, NULL, wszDatabase ) );
Assert( jdbid == JET_dbidNil );
jdbid = JET_dbidNil;
}
Call( err );
Expected( reinterpret_cast<PIB*>( sesid )->Level() == 0 );
PGNO pgnoFDP = pgnoNull;
CHAR szObjName[JET_cbNameMost+1];
Call( ErrCATSeekTableByObjid(
reinterpret_cast<PIB*>( sesid ),
(IFMP)jdbid,
cpage.ObjidFDP(),
szObjName,
sizeof( szObjName ),
&pgnoFDP ) );
Call( ErrFILEOpenTable( reinterpret_cast<PIB*>( sesid ), (IFMP)jdbid, ppfucbObj, szObjName ) );
Assert( (*ppfucbObj)->u.pfcb->FTypeTable() );
if ( wszObjName )
{
Assert( ( cbDbutlObjNameMost - JET_cbNameMost ) > ( wcslen( L"::LV::[Space Tree]" ) * 2 ) );
OSStrCbFormatW( wszObjName, cbObjName, L"%hs", szObjName );
if ( (*ppfucbObj)->u.pfcb->FTypeLV() )
{
OSStrCbAppendW( wszObjName, cbObjName, L"::LV" );
}
if ( cpage.FFlags() & CPAGE::fPageSpaceTree )
{
OSStrCbAppendW( wszObjName, cbObjName, L"::[Space Tree]" );
}
}
}
EXCEPT( efaExecuteHandler )
{
wprintf( L"WARNING: Hit exception or AV trying to attach database or lookup object or table, continuing without detailed info/strings.\n" );
*pifmp = ifmpNil;
*ppfucbObj = pfucbNil;
err = ErrERRCheck( JET_errDiskIO );
}
Call( err );
*pifmp = (IFMP)jdbid;
jdbid = JET_dbidNil;
Assert( *pifmp != ifmpNil );
Assert( *ppfucbObj != pfucbNil );
return JET_errSuccess;
HandleError:
wprintf( L"WARNING: Hit error %d trying to attach, open or lookup object or table, continuing without detailed info/strings.\n", err );
Assert( *pifmp == ifmpNil );
Assert( *ppfucbObj == pfucbNil );
if ( jdbid != JET_dbidNil )
{
CallS( ErrIsamCloseDatabase( sesid, jdbid, NO_GRBIT ) );
CallS( ErrIsamDetachDatabase( sesid, NULL, wszDatabase ) );
}
return err;
}
void DBUTLCloseIfmpFucb( _Inout_ JET_SESID sesid, PCWSTR wszDatabase, _In_ IFMP ifmp, _Inout_ FUCB * pfucbObj )
{
if ( pfucbObj != pfucbNil )
{
Assert( pfucbObj->u.pfcb->FTypeTable() );
CallS( ErrFILECloseTable( reinterpret_cast<PIB*>( sesid ), pfucbObj ) );
}
if ( ifmp != ifmpNil )
{
CallS( ErrIsamCloseDatabase( sesid, ifmp, NO_GRBIT ) );
CallS( ErrIsamDetachDatabase( sesid, NULL, wszDatabase ) );
}
}
LOCAL ERR ErrDBUTLDumpNode( JET_SESID sesid, IFileSystemAPI *const pfsapi, const WCHAR * const wszFile, const PGNO pgno, const INT iline, const JET_GRBIT grbit )
{
ERR err = JET_errSuccess;
KEYDATAFLAGS kdf;
CPAGE cpage;
IFileAPI* pfapi = NULL;
QWORD ibOffset = OffsetOfPgno( pgno );
VOID* pvPage = NULL;
CHAR* szBuf = NULL;
const INT cbWidth = UtilCprintfStdoutWidth() >= 116 ? 32 : 16;
INT ilineCurrent;
TraceContextScope tcUtil ( iorpDirectAccessUtil );
IFMP ifmp = ifmpNil;
FUCB * pfucbTable = pfucbNil;
pvPage = PvOSMemoryPageAlloc( g_cbPage, NULL );
if( NULL == pvPage )
{
Call( ErrERRCheck( JET_errOutOfMemory ) );
}
err = CIOFilePerf::ErrFileOpen( pfsapi,
reinterpret_cast<PIB*>( sesid )->m_pinst,
wszFile,
IFileAPI::fmfReadOnly,
iofileDbAttached,
qwDumpingFileID,
&pfapi );
if ( err < 0 )
{
wprintf( L"Cannot open file %ws.\n\n", wszFile );
Call( err );
}
Call( pfapi->ErrIORead( *tcUtil, ibOffset, g_cbPage, (BYTE* const)pvPage, qosIONormal ) );
cpage.LoadPage( 1, pgno, pvPage, g_cbPage );
if ( iline < -1 || iline >= cpage.Clines() )
{
printf( "Invalid iline: %d\n\n", iline );
Call( ErrERRCheck( cpage.FPageIsInitialized() ? JET_errInvalidParameter : JET_errPageNotInitialized ) );
}
if ( !cpage.FNewRecordFormat()
&& cpage.FPrimaryPage()
&& !cpage.FRepairedPage()
&& cpage.FLeafPage()
&& !cpage.FSpaceTree()
&& !cpage.FLongValuePage() )
{
if ( iline == -1 )
{
printf( "Cannot dump all nodes on old format page\n\n" );
Call( ErrERRCheck( JET_errInvalidParameter ) );
}
VOID * pvBuf = PvOSMemoryPageAlloc( g_cbPage, NULL );
if( NULL == pvBuf )
{
Call( ErrERRCheck( JET_errOutOfMemory ) );
}
err = ErrUPGRADEConvertNode( &cpage, iline, pvBuf );
OSMemoryPageFree( pvBuf );
Call( err );
}
szBuf = (CHAR *)PvOSMemoryPageAlloc( g_cbPage * 8, NULL );
if( NULL == szBuf )
{
Call( ErrERRCheck( JET_errOutOfMemory ) );
}
ilineCurrent = ( iline == -1 ) ? 0 : iline;
do
{
if ( ilineCurrent >= cpage.Clines() )
{
Assert( ilineCurrent == 0 );
printf( "ERROR: This page doesn't even have one valid iline. Q: Blank? A: %hs\n", cpage.FPageIsInitialized() ? "No" : "Yes" );
Call( ErrERRCheck( cpage.FPageIsInitialized() ? JET_errInvalidParameter : JET_errPageNotInitialized ) );
}
NDIGetKeydataflags( cpage, ilineCurrent, &kdf );
printf( " Node: %d:%d\n\n", pgno, ilineCurrent );
printf( " Flags: 0x%4.4x\n", kdf.fFlags );
printf( "===========\n" );
if( FNDVersion( kdf ) )
{
printf( " Versioned\n" );
}
if( FNDDeleted( kdf ) )
{
printf( " Deleted\n" );
}
if( FNDCompressed( kdf ) )
{
printf( " Compressed\n" );
}
printf( "\n" );
printf( "Key Prefix: %4d bytes\n", kdf.key.prefix.Cb() );
printf( "===========\n" );
szBuf[0] = 0;
DBUTLSprintHex( szBuf, g_cbPage * 8, reinterpret_cast<BYTE *>( kdf.key.prefix.Pv() ), kdf.key.prefix.Cb(), cbWidth );
printf( "%s\n", szBuf );
printf( "Key Suffix: %4d bytes\n", kdf.key.suffix.Cb() );
printf( "===========\n" );
szBuf[0] = 0;
DBUTLSprintHex( szBuf, g_cbPage * 8, reinterpret_cast<BYTE *>( kdf.key.suffix.Pv() ), kdf.key.suffix.Cb(), cbWidth );
printf( "%s\n", szBuf );
printf( " Data: %4d bytes\n", kdf.data.Cb() );
printf( "===========\n" );
szBuf[0] = 0;
DBUTLSprintHex( szBuf, g_cbPage * 8, reinterpret_cast<BYTE *>( kdf.data.Pv() ), kdf.data.Cb(), cbWidth );
printf( "%s\n", szBuf );
printf( "\n\n" );
if( !cpage.FLeafPage() )
{
if( sizeof( PGNO ) == kdf.data.Cb() )
{
const PGNO pgnoChild = *(reinterpret_cast<UnalignedLittleEndian< PGNO > *>( kdf.data.Pv() ) );
printf( "pgnoChild = %lu (0x%x)\n", pgnoChild, pgnoChild );
}
}
else if( cpage.FSpaceTree() )
{
PGNO pgnoLast;
CPG cpg;
SpacePool sppPool;
Call( ErrSPIGetExtentInfo( &kdf, &pgnoLast, &cpg, &sppPool ) );
printf( "%d (0x%x) pages ending at %lu (0x%x) in pool %lu (%ws)\n", cpg, cpg, pgnoLast, pgnoLast, (ULONG)sppPool, WszPoolName( sppPool ) );
}
else if( cpage.FPrimaryPage() )
{
if( cpage.FLongValuePage() )
{
}
else
{
if ( ifmp == ifmpNil && pfucbTable == pfucbNil )
{
tcUtil->iorReason.SetIorp( iorpNone );
OnDebug( ERR errT = )ErrDBUTLGetIfmpFucbOfPage( sesid, wszFile, cpage, &ifmp, &pfucbTable );
tcUtil->iorReason.SetIorp( iorpDirectAccessUtil );
Assert( errT < JET_errSuccess || ifmp != ifmpNil );
Assert( errT < JET_errSuccess || pfucbTable != pfucbNil );
Assert( errT >= JET_errSuccess || ifmp == ifmpNil );
Assert( errT >= JET_errSuccess || pfucbTable == pfucbNil );
}
DBUTLDumpRec( cpage.CbPage(), pfucbTable, kdf.data.Pv(), kdf.data.Cb(), CPRINTFSTDOUT::PcprintfInstance(), cbWidth );
}
}
ilineCurrent++;
}
while ( iline == -1 && ilineCurrent < cpage.Clines() );
HandleError:
DBUTLCloseIfmpFucb( sesid, wszFile, ifmp, pfucbTable );
if ( cpage.FLoadedPage() )
{
cpage.UnloadPage();
}
OSMemoryPageFree( szBuf );
OSMemoryPageFree( pvPage );
delete pfapi;
return err;
}
LOCAL BOOL FDBUTLConvertHexDigit_(
const CHAR cHexDigit,
__out_bcount_full(1) CHAR * const pcHexValue )
{
if ( cHexDigit >= '0' && cHexDigit <= '9' )
{
*pcHexValue = cHexDigit - '0';
return fTrue;
}
else if ( cHexDigit >= 'A' && cHexDigit <= 'F' )
{
*pcHexValue = cHexDigit - 'A' + 0xa;
return fTrue;
}
else if ( cHexDigit >= 'a' && cHexDigit <= 'f' )
{
*pcHexValue = cHexDigit - 'a' + 0xa;
return fTrue;
}
else
{
return fFalse;
}
}
LOCAL BOOL FDBUTLPrintedKeyToRealKey(
__in_bcount(2 * cbKey) const CHAR * const szPrintedKey,
__out_bcount_full(cbKey) CHAR * const szKey,
const ULONG cbKey )
{
for ( ULONG i = 0; i < cbKey; i++ )
{
const ULONG j = i * 2;
CHAR cHighNibble;
CHAR cLowNibble;
if ( 0 == i )
{
printf( "%c%c", szPrintedKey[j], szPrintedKey[j+1] );
}
else
{
printf( " %c%c", szPrintedKey[j], szPrintedKey[j+1] );
}
if ( !FDBUTLConvertHexDigit_( szPrintedKey[j], &cHighNibble )
|| !FDBUTLConvertHexDigit_( szPrintedKey[j+1], &cLowNibble ) )
{
return fFalse;
}
szKey[i] = ( cHighNibble << 4 ) + cLowNibble;
}
return fTrue;
}
LOCAL ERR ErrDBUTLSeekToKey_(
IFileAPI * pfapi,
PGNO pgnoRoot,
CPAGE& cpage,
VOID * const pvPageBuf,
const CHAR * const szPrintedKey,
const CHAR * const szPrintedData )
{
ERR err;
CHAR szKey[cbKeyAlloc];
CHAR szData[cbKeyAlloc];
const ULONG cbPrintedKey = (ULONG)strlen( szPrintedKey );
const ULONG cbPrintedData = ( NULL != szPrintedData ? (ULONG)strlen( szPrintedData ) : 0 );
BOOKMARK bm;
INT compare;
INT iline;
PGNO pgnoCurr = pgnoRoot;
if ( cbPrintedKey % 2 != 0
|| cbPrintedKey > ( cbKeyAlloc * 2 )
|| cbPrintedData % 2 != 0
|| cbPrintedData > ( cbKeyAlloc * 2 ) )
{
return ErrERRCheck( JET_errInvalidBookmark );
}
printf( " Seek bookmark: \"" );
bm.Nullify();
bm.key.suffix.SetPv( szKey );
bm.key.suffix.SetCb( cbPrintedKey / 2 );
if ( cpage.FNonUniqueKeys() && 0 != cbPrintedData )
{
bm.data.SetPv( szData );
bm.data.SetCb( cbPrintedData / 2 );
}
const INT cbSuffix = bm.key.suffix.Cb();
AssertPREFIX( sizeof( szKey ) >= cbSuffix );
if ( !FDBUTLPrintedKeyToRealKey(
szPrintedKey,
szKey,
cbSuffix ) )
{
printf( "...\"\n\n" );
return ErrERRCheck( JET_errInvalidBookmark );
}
const INT cbData = bm.data.Cb();
if ( cbData > 0 )
{
printf( " | " );
AssertPREFIX( sizeof( szData ) >= cbData );
if ( !FDBUTLPrintedKeyToRealKey(
szPrintedData,
szData,
cbData ) )
{
printf( "...\"\n\n" );
return ErrERRCheck( JET_errInvalidBookmark );
}
}
printf( "\"\n" );
while ( !cpage.FLeafPage() )
{
iline = IlineNDISeekGEQInternal( cpage, bm, &compare );
if ( 0 == compare )
{
iline++;
}
printf( " pgno/iline: %lu-%d (", pgnoCurr, iline );
if ( cpage.FRootPage() )
printf( "root," );
if ( cpage.FParentOfLeaf() )
printf( "parent-of-leaf" );
else
printf( "internal" );
printf( ")\n" );
KEYDATAFLAGS kdf;
NDIGetKeydataflags( cpage, iline, &kdf );
if ( sizeof(PGNO) != kdf.data.Cb() )
{
printf( "\n" );
return ErrERRCheck( JET_errBadPageLink );
}
const PGNO pgnoChild = *(UnalignedLittleEndian< PGNO > *)kdf.data.Pv();
cpage.UnloadPage();
err = pfapi->ErrIORead( *TraceContextScope( iorpDirectAccessUtil ), OffsetOfPgno( pgnoChild ), g_cbPage, (BYTE* const)pvPageBuf, qosIONormal );
if ( err < 0 )
{
printf( "\n" );
return err;
}
cpage.LoadPage( 1, pgnoChild, pvPageBuf, g_cbPage );
pgnoCurr = pgnoChild;
}
iline = IlineNDISeekGEQ( cpage, bm, !cpage.FNonUniqueKeys(), &compare );
Assert( iline < cpage.Clines( ) );
if ( iline < 0 )
{
iline = cpage.Clines( ) - 1;
}
printf( " pgno/iline: %lu-%d (%sleaf)\n\n", pgnoCurr, iline, ( cpage.FRootPage() ? "root," : "" ) );
return JET_errSuccess;
}
LOCAL ERR ErrDBUTLDumpPage(
INST * const pinst,
const WCHAR * wszFile,
const PGNO pgno,
const WCHAR * const wszPrintedKeyToSeek,
const WCHAR * const wszPrintedDataToSeek,
const JET_GRBIT grbit )
{
ERR err = JET_errSuccess;
IFileSystemAPI * const pfsapi = pinst->m_pfsapi;
IFileAPI * pfapi = NULL;
CPAGE cpage;
TraceContextScope tcUtil ( iorpDirectAccessUtil );
VOID * const pvPage = PvOSMemoryPageAlloc( g_cbPage, NULL );
if( NULL == pvPage )
{
CallR( ErrERRCheck( JET_errOutOfMemory ) );
}
err = CIOFilePerf::ErrFileOpen( pfsapi,
pinst,
wszFile,
IFileAPI::fmfReadOnly,
iofileDbAttached,
qwDumpingFileID,
&pfapi );
if ( err < 0 )
{
printf( "Cannot open file %ws.\n\n", wszFile );
Call( err );
}
Call( pfapi->ErrIORead( *tcUtil, OffsetOfPgno( pgno ), g_cbPage, (BYTE* const)pvPage, qosIONormal ) );
cpage.LoadPage( 1, pgno, pvPage, g_cbPage );
if ( cpage.Clines() == -1 )
{
AssertSz( cpage.ObjidFDP() == 0 || cpage.FPreInitPage(), "Odd page (%d):0 TAG page should be all 0s\r\n", cpage.PgnoThis() );
}
else
{
Call( cpage.ErrCheckPage( CPRINTFSTDOUT::PcprintfInstance() ) );
}
if ( NULL != wszPrintedKeyToSeek && 0 != cpage.Clines() )
{
CAutoSZ szPrintedKeyToSeek;
CAutoSZ szPrintedDataToSeek;
Call( szPrintedKeyToSeek.ErrSet( wszPrintedKeyToSeek ) );
Call( szPrintedDataToSeek.ErrSet( wszPrintedDataToSeek ) );
Call( ErrDBUTLSeekToKey_( pfapi, pgno, cpage, pvPage, (CHAR*)szPrintedKeyToSeek, (CHAR*)szPrintedDataToSeek ) );
}
#ifdef DEBUGGER_EXTENSION
(VOID)cpage.DumpHeader( CPRINTFSTDOUT::PcprintfInstance() );
printf( "\n" );
(VOID)cpage.DumpTags( CPRINTFSTDOUT::PcprintfInstance() );
printf( "\n" );
#endif
if( grbit & JET_bitDBUtilOptionDumpVerbose )
{
(VOID)cpage.DumpAllocMap( CPRINTFSTDOUT::PcprintfInstance() );
printf( "\n" );
const INT cbWidth = UtilCprintfStdoutWidth() >= 116 ? 32 : 16;
CHAR * szBuf = new CHAR[g_cbPage * 8];
if( NULL == szBuf )
{
Call( ErrERRCheck( JET_errOutOfMemory ) );
}
printf( "Raw dump (cbPage = %d / cbBuffer = %d) in big-endian quartets of bytes (not little endian DWORDs):\n", g_cbPage, g_cbPage );
DBUTLSprintHex( szBuf, g_cbPage * 8, reinterpret_cast<BYTE *>( pvPage ), g_cbPage, cbWidth );
printf( "%s\n", szBuf );
delete [] szBuf;
}
HandleError:
if ( cpage.FLoadedPage() )
{
cpage.UnloadPage();
}
delete pfapi;
OSMemoryPageFree( pvPage );
return err;
}
class CDBUTLIRunCalculator {
CStats * m_pStats;
ULONG * m_pcForwardScans;
ULONG m_cpgCurrRun;
PGNO m_pgnoPrevious;
public:
CDBUTLIRunCalculator( CStats * pStat, ULONG * pcHaltedForwardProgress ) :
m_pStats( pStat ),
m_pcForwardScans( pcHaltedForwardProgress )
{
m_cpgCurrRun = 0;
m_pgnoPrevious = 0x0;
Assert( m_pStats );
Assert( m_pcForwardScans );
Assert( *m_pcForwardScans == 0 );
}
~CDBUTLIRunCalculator( )
{
Assert( m_pgnoPrevious == pgnoDoneSentinel );
Assert( m_cpgCurrRun == 0 );
m_pStats = NULL;
m_pcForwardScans = NULL;
}
ERR ErrBreak( void )
{
ERR err = JET_errSuccess;
if ( m_cpgCurrRun != 0 )
{
if ( m_pStats->ErrAddSample( m_cpgCurrRun ) == CStats::ERR::errOutOfMemory )
{
return ErrERRCheck( JET_errOutOfMemory );
}
m_cpgCurrRun = 0;
}
return err;
}
static const PGNO pgnoDoneSentinel = 0xFFFFFFFF;
ERR ErrProcessPage( PGNO pgno )
{
ERR err = JET_errSuccess;
Assert( pgno != 0x0 );
if ( m_pgnoPrevious == pgnoDoneSentinel )
{
Assert( m_pgnoPrevious != pgnoDoneSentinel );
return JET_errSuccess;
}
if ( pgnoDoneSentinel == pgno )
{
Call( ErrBreak() );
if ( m_pStats->C() )
{
(*m_pcForwardScans)++;
}
}
else
{
if ( pgno < m_pgnoPrevious )
{
(*m_pcForwardScans)++;
}
if ( m_pgnoPrevious != 0x0 )
{
if ( m_pgnoPrevious + 1 != pgno )
{
Call( ErrBreak() );
}
}
m_cpgCurrRun++;
}
m_pgnoPrevious = pgno;
return JET_errSuccess;
HandleError:
Assert( err == JET_errOutOfMemory );
return err;
}
};
class CBTreeStatsManager {
private:
BTREE_STATS_BASIC_CATALOG m_btsBasicCatalog;
BTREE_STATS_SPACE_TREES m_btsSpaceTrees;
BTREE_STATS_PARENT_OF_LEAF m_btsParentOfLeaf;
BTREE_STATS_PAGE_SPACE m_btsInternalPageSpace;
BTREE_STATS_PAGE_SPACE m_btsFullWalk;
BTREE_STATS_LV m_btsLvData;
CPerfectHistogramStats m_rgHistos[20];
BTREE_STATS m_bts;
public:
CBTreeStatsManager( JET_GRBIT grbit, BTREE_STATS * pbtsParent )
{
memset( &m_btsBasicCatalog, 0, sizeof(m_btsBasicCatalog) );
m_btsBasicCatalog.cbStruct = sizeof(m_btsBasicCatalog);
memset( &m_btsSpaceTrees, 0, sizeof(m_btsSpaceTrees) );
m_btsSpaceTrees.cbStruct = sizeof(m_btsSpaceTrees);
memset( &m_btsParentOfLeaf, 0, sizeof(m_btsParentOfLeaf) );
m_btsParentOfLeaf.cbStruct = sizeof(m_btsParentOfLeaf);
memset( &m_btsInternalPageSpace, 0, sizeof(m_btsInternalPageSpace) );
m_btsInternalPageSpace.cbStruct = sizeof(m_btsInternalPageSpace);
memset( &m_btsFullWalk, 0, sizeof(m_btsFullWalk) );
m_btsFullWalk.cbStruct = sizeof(m_btsFullWalk);
memset( &m_btsLvData, 0, sizeof(m_btsLvData) );
m_btsLvData.cbStruct = sizeof(m_btsLvData);
m_btsParentOfLeaf.phistoIOContiguousRuns = (JET_HISTO*)&m_rgHistos[0];
m_btsFullWalk.phistoFreeBytes = (JET_HISTO*)&m_rgHistos[1];
m_btsFullWalk.phistoNodeCounts = (JET_HISTO*)&m_rgHistos[2];
m_btsFullWalk.phistoKeySizes = (JET_HISTO*)&m_rgHistos[3];
m_btsFullWalk.phistoDataSizes = (JET_HISTO*)&m_rgHistos[4];
m_btsFullWalk.phistoKeyCompression = (JET_HISTO*)&m_rgHistos[5];
m_btsFullWalk.phistoUnreclaimedBytes = (JET_HISTO*)&m_rgHistos[6];
m_btsFullWalk.cVersionedNodes = 0;
m_btsInternalPageSpace.phistoFreeBytes = (JET_HISTO*)&m_rgHistos[7];
m_btsInternalPageSpace.phistoNodeCounts = (JET_HISTO*)&m_rgHistos[8];
m_btsInternalPageSpace.phistoKeySizes = (JET_HISTO*)&m_rgHistos[9];
m_btsInternalPageSpace.phistoDataSizes = (JET_HISTO*)&m_rgHistos[10];
m_btsInternalPageSpace.phistoKeyCompression = (JET_HISTO*)&m_rgHistos[11];
m_btsInternalPageSpace.phistoUnreclaimedBytes = (JET_HISTO*)&m_rgHistos[12];
m_btsLvData.phistoLVSize = (JET_HISTO*)&m_rgHistos[13];
m_btsLvData.phistoLVComp = (JET_HISTO*)&m_rgHistos[14];
m_btsLvData.phistoLVRatio = (JET_HISTO*)&m_rgHistos[15];
m_btsLvData.phistoLVSeeks = (JET_HISTO*)&m_rgHistos[16];
m_btsLvData.phistoLVBytes = (JET_HISTO*)&m_rgHistos[17];
m_btsLvData.phistoLVExtraSeeks = (JET_HISTO*)&m_rgHistos[18];
m_btsLvData.phistoLVExtraBytes = (JET_HISTO*)&m_rgHistos[19];
memset( &m_bts, 0, sizeof(m_bts) );
m_bts.cbStruct = sizeof(m_bts);
m_bts.grbitData = grbit;
m_bts.pParent = pbtsParent;
m_bts.pBasicCatalog = ( m_bts.grbitData & JET_bitDBUtilSpaceInfoBasicCatalog ) ?
&m_btsBasicCatalog : NULL;
m_bts.pSpaceTrees = ( m_bts.grbitData & JET_bitDBUtilSpaceInfoSpaceTrees ) ?
&m_btsSpaceTrees : NULL;
m_bts.pParentOfLeaf = ( m_bts.grbitData & JET_bitDBUtilSpaceInfoParentOfLeaf ) ?
&m_btsParentOfLeaf : NULL;
if ( m_bts.pParentOfLeaf )
{
m_bts.pParentOfLeaf->pInternalPageStats = &m_btsInternalPageSpace;
}
m_bts.pFullWalk = ( m_bts.grbitData & JET_bitDBUtilSpaceInfoFullWalk ) ?
&m_btsFullWalk : NULL;
m_bts.pLvData = ( m_bts.grbitData & JET_bitDBUtilSpaceInfoBasicCatalog &&
m_bts.grbitData & JET_bitDBUtilSpaceInfoFullWalk ) ?
&m_btsLvData : NULL;
}
static void ResetParentOfLeaf( BTREE_STATS_PARENT_OF_LEAF * pPOL )
{
Assert( pPOL );
Assert( pPOL->cbStruct == sizeof(*pPOL) );
Assert( pPOL->phistoIOContiguousRuns );
pPOL->fEmpty = fFalse;
pPOL->cpgInternal = 0;
pPOL->cpgData = 0;
pPOL->cDepth = 0;
Assert( pPOL->phistoIOContiguousRuns );
CStatsFromPv(pPOL->phistoIOContiguousRuns)->Zero();
pPOL->cForwardScans = 0;
Assert( pPOL->pInternalPageStats );
Assert( pPOL->pInternalPageStats->phistoFreeBytes );
CStatsFromPv(pPOL->pInternalPageStats->phistoFreeBytes)->Zero();
CStatsFromPv(pPOL->pInternalPageStats->phistoNodeCounts)->Zero();
CStatsFromPv(pPOL->pInternalPageStats->phistoKeySizes)->Zero();
CStatsFromPv(pPOL->pInternalPageStats->phistoDataSizes)->Zero();
CStatsFromPv(pPOL->pInternalPageStats->phistoKeyCompression)->Zero();
CStatsFromPv(pPOL->pInternalPageStats->phistoUnreclaimedBytes)->Zero();
}
static void ResetFullWalk( BTREE_STATS_PAGE_SPACE * pFW )
{
Assert( pFW );
Assert( pFW->cbStruct == sizeof(*pFW) );
Assert( pFW->phistoFreeBytes );
CStatsFromPv(pFW->phistoFreeBytes)->Zero();
Assert( pFW->phistoNodeCounts );
CStatsFromPv(pFW->phistoNodeCounts)->Zero();
Assert( pFW->phistoKeySizes );
CStatsFromPv(pFW->phistoKeySizes)->Zero();
Assert( pFW->phistoDataSizes );
CStatsFromPv(pFW->phistoDataSizes)->Zero();
Assert( pFW->phistoKeyCompression );
CStatsFromPv(pFW->phistoKeyCompression)->Zero();
Assert( pFW->phistoUnreclaimedBytes );
CStatsFromPv(pFW->phistoUnreclaimedBytes)->Zero();
pFW->cVersionedNodes = 0;
}
static void ResetSpaceTreeInfo( BTREE_STATS_SPACE_TREES * pbtsST )
{
Assert( pbtsST );
if ( pbtsST->prgOwnedExtents )
{
delete [] pbtsST->prgOwnedExtents;
pbtsST->prgOwnedExtents = NULL;
}
if ( pbtsST->prgAvailExtents )
{
delete [] pbtsST->prgAvailExtents;
pbtsST->prgAvailExtents = NULL;
}
Assert( pbtsST->prgOwnedExtents == NULL );
Assert( pbtsST->prgAvailExtents == NULL );
memset( pbtsST, 0, sizeof(*pbtsST) );
pbtsST->cbStruct = sizeof(*pbtsST);
}
static void ResetLvData( BTREE_STATS_LV * pLvData )
{
if ( pLvData )
{
Assert( pLvData->cbStruct == sizeof(*pLvData) );
pLvData->cLVRefs = 0;
pLvData->cCorruptLVs = 0;
pLvData->cSeparatedRootChunks = 0;
pLvData->cPartiallyDeletedLVs = 0;
pLvData->lidMax = 0;
CStatsFromPv( pLvData->phistoLVSize )->Zero();
CStatsFromPv( pLvData->phistoLVComp )->Zero();
CStatsFromPv( pLvData->phistoLVRatio )->Zero();
CStatsFromPv( pLvData->phistoLVSeeks )->Zero();
CStatsFromPv( pLvData->phistoLVBytes )->Zero();
CStatsFromPv( pLvData->phistoLVExtraSeeks )->Zero();
CStatsFromPv( pLvData->phistoLVExtraBytes )->Zero();
}
}
~CBTreeStatsManager ()
{
if ( m_bts.pParentOfLeaf )
{
ResetParentOfLeaf( m_bts.pParentOfLeaf );
}
if ( m_bts.pFullWalk )
{
ResetFullWalk( m_bts.pFullWalk );
}
if ( m_bts.pSpaceTrees )
{
ResetSpaceTreeInfo( m_bts.pSpaceTrees );
}
if ( m_bts.pLvData )
{
ResetLvData( m_bts.pLvData );
}
}
BTREE_STATS * Pbts( void )
{
return &m_bts;
}
};
LOCAL ERR ErrEnumDataNodes(
PIB * ppib,
const IFMP ifmp,
const PGNO pgnoFDP,
PFNVISITPAGE pfnErrVisitPage,
void * pvVisitPageCtx,
CPAGE::PFNVISITNODE pfnErrVisitNode,
void * pvVisitNodeCtx
)
{
ERR err;
FUCB *pfucb = pfucbNil;
BOOL fForceInit = fFalse;
DIB dib;
PGNO pgnoLastSeen = pgnoNull;
CPG cpgSeen = 0;
CallR( ErrBTOpen( ppib, pgnoFDP, ifmp, &pfucb ) );
Assert( pfucbNil != pfucb );
Assert( pfcbNil != pfucb->u.pfcb );
if ( !pfucb->u.pfcb->FInitialized() )
{
Assert( pgnoSystemRoot != pgnoFDP );
Assert( pgnoFDPMSO != pgnoFDP );
Assert( pgnoFDPMSO_NameIndex != pgnoFDP );
Assert( pgnoFDPMSO_RootObjectIndex != pgnoFDP );
Assert( pfucb->u.pfcb->WRefCount() == 1 );
pfucb->u.pfcb->Lock();
pfucb->u.pfcb->CreateComplete();
pfucb->u.pfcb->Unlock();
fForceInit = fTrue;
}
else if ( pgnoSystemRoot == pgnoFDP
|| pgnoFDPMSO == pgnoFDP
|| pgnoFDPMSO_NameIndex == pgnoFDP
|| pgnoFDPMSO_RootObjectIndex == pgnoFDP )
{
}
BTUp( pfucb );
if ( pfucb->u.pfcb->FPrimaryIndex() ||
pfucb->u.pfcb->FTypeLV() ||
FFUCBSpace( pfucb ) )
{
FUCBSetSequential( pfucb );
FUCBSetPrereadForward( pfucb, cpgPrereadSequential );
}
dib.dirflag = fDIRNull;
dib.pos = posFirst;
err = ErrBTDown( pfucb, &dib, latchReadNoTouch );
if ( err != JET_errRecordNotFound )
{
Call( err );
forever
{
if( pgnoLastSeen != Pcsr( pfucb )->Pgno() )
{
pgnoLastSeen = Pcsr( pfucb )->Pgno();
++cpgSeen;
if ( pfnErrVisitPage )
{
Call( pfnErrVisitPage( pgnoLastSeen, 0xFFFFFFFF ,
&(Pcsr( pfucb )->Cpage()), pvVisitPageCtx ) );
}
if ( pfnErrVisitNode )
{
Call( Pcsr( pfucb )->Cpage().ErrEnumTags( pfnErrVisitNode, pvVisitNodeCtx ) );
}
}
err = ErrBTNext( pfucb, fDIRNull );
if ( err < 0 )
{
if ( err != JET_errNoCurrentRecord )
{
goto HandleError;
}
break;
}
}
}
err = JET_errSuccess;
HandleError:
Assert( pfucbNil != pfucb );
if ( fForceInit )
{
Assert( pfucb->u.pfcb->WRefCount() == 1 );
pfucb->u.pfcb->Lock();
pfucb->u.pfcb->CreateCompleteErr( errFCBUnusable );
pfucb->u.pfcb->Unlock();
}
BTClose( pfucb );
return err;
}
ERR ErrAccumulatePageStats(
const CPAGE::PGHDR * const ppghdr,
INT itag,
DWORD fNodeFlags,
const KEYDATAFLAGS * const pkdf,
void * pvCtx
);
LOCAL ERR ErrDBUTLGetDataPageStats(
PIB * ppib,
IFMP ifmp,
const PGNO pgnoFDP,
BTREE_STATS_PAGE_SPACE * pFullWalk,
BTREE_STATS_LV * pLvData
)
{
ERR err = JET_errSuccess;
CBTreeStatsManager::ResetFullWalk( pFullWalk );
Assert( pFullWalk->phistoFreeBytes );
CBTreeStatsManager::ResetLvData( pLvData );
if ( fFalse )
{
err = ErrEnumDataNodes( ppib,
ifmp, pgnoFDP,
NULL, NULL,
ErrAccumulatePageStats, pFullWalk );
}
else
{
if ( pLvData )
{
EVAL_LV_PAGE_CTX ctx = { 0 };
ctx.cpgAccumMax = 0;
ctx.rgpgnoAccum = NULL;
ctx.pLvData = pLvData;
CPAGE::PFNVISITNODE rgpfnzErrVisitNode[3] = { ErrAccumulatePageStats, ErrAccumulateLvNodeData, NULL };
void * rgpvzVisitNodeCtx[3] = { pFullWalk, &ctx, NULL };
err = ErrBTUTLAcross( ifmp, pgnoFDP,
CPAGE::fPageLeaf,
ErrAccumulateLvPageData, &ctx,
rgpfnzErrVisitNode, rgpvzVisitNodeCtx );
if ( ctx.rgpgnoAccum != NULL )
{
delete[] ctx.rgpgnoAccum;
ctx.cpgAccumMax = 0;
ctx.rgpgnoAccum = NULL;
}
}
else
{
err = ErrBTUTLAcross( ifmp, pgnoFDP,
CPAGE::fPageLeaf,
NULL, NULL,
ErrAccumulatePageStats, pFullWalk );
}
}
return err;
}
LOCAL ERR ErrDBUTLGetSpaceTreeInfo(
PIB *ppib,
const IFMP ifmp,
const OBJID objidFDP,
const PGNO pgnoFDP,
BTREE_STATS_SPACE_TREES * pbtsSpaceTree,
CPRINTF * const pcprintf )
{
ERR err;
FUCB *pfucb = pfucbNil;
BOOL fForceInit = fFalse;
CPG rgcpgExtent[4];
CallR( ErrBTOpen( ppib, pgnoFDP, ifmp, &pfucb ) );
Assert( pfucbNil != pfucb );
Assert( pfcbNil != pfucb->u.pfcb );
CBTreeStatsManager::ResetSpaceTreeInfo( pbtsSpaceTree );
if ( !pfucb->u.pfcb->FInitialized() )
{
Assert( pgnoSystemRoot != pgnoFDP );
Assert( pgnoFDPMSO != pgnoFDP );
Assert( pgnoFDPMSO_NameIndex != pgnoFDP );
Assert( pgnoFDPMSO_RootObjectIndex != pgnoFDP );
Assert( pfucb->u.pfcb->WRefCount() == 1 );
pfucb->u.pfcb->Lock();
pfucb->u.pfcb->CreateComplete();
pfucb->u.pfcb->Unlock();
fForceInit = fTrue;
}
else if ( pgnoSystemRoot == pgnoFDP
|| pgnoFDPMSO == pgnoFDP
|| pgnoFDPMSO_NameIndex == pgnoFDP
|| pgnoFDPMSO_RootObjectIndex == pgnoFDP )
{
}
Call( ErrBTIGotoRoot( pfucb, latchReadNoTouch ) );
NDGetExternalHeader ( pfucb, noderfIsamAutoInc );
if ( pfucb->kdfCurr.data.Cb() != 0 && pfucb->kdfCurr.data.Pv() != NULL )
{
pbtsSpaceTree->fAutoIncPresents = fTrue;
const QWORD qwAutoInc = *(QWORD*)pfucb->kdfCurr.data.Pv();
pbtsSpaceTree->qwAutoInc = qwAutoInc;
}
else
{
Assert( pfucb->kdfCurr.data.Cb() == 0 );
Assert( pfucb->kdfCurr.data.Pv() == NULL );
pbtsSpaceTree->fAutoIncPresents = fFalse;
}
NDGetExternalHeader ( pfucb, noderfSpaceHeader );
Assert( sizeof( SPACE_HEADER ) == pfucb->kdfCurr.data.Cb() );
const SPACE_HEADER * const psph = reinterpret_cast <SPACE_HEADER *> ( pfucb->kdfCurr.data.Pv() );
if ( psph->Fv1() )
{
pbtsSpaceTree->cpgPrimary = psph->CpgPrimary();
pbtsSpaceTree->cpgLastAlloc = 0;
}
else
{
Assert( psph->Fv2() );
pbtsSpaceTree->cpgPrimary = 0;
pbtsSpaceTree->cpgLastAlloc = psph->CpgLastAlloc();
}
pbtsSpaceTree->fMultiExtent = psph->FMultipleExtent();
if ( pbtsSpaceTree->fMultiExtent )
{
pbtsSpaceTree->pgnoOE = psph->PgnoOE();
pbtsSpaceTree->pgnoAE = psph->PgnoAE();
Assert( ( pbtsSpaceTree->pgnoOE + 1 ) == pbtsSpaceTree->pgnoAE );
}
else
{
pbtsSpaceTree->pgnoOE = pgnoNull;
pbtsSpaceTree->pgnoAE = pgnoNull;
}
BTUp( pfucb );
Call( ErrSPGetInfo(
ppib,
ifmp,
pfucb,
(BYTE *)rgcpgExtent,
sizeof(rgcpgExtent),
fSPOwnedExtent | fSPAvailExtent | fSPReservedExtent | fSPShelvedExtent,
pcprintf ) );
pbtsSpaceTree->cpgOwned = rgcpgExtent[0];
pbtsSpaceTree->cpgAvailable = rgcpgExtent[1];
pbtsSpaceTree->cpgReserved = rgcpgExtent[2];
pbtsSpaceTree->cpgShelved = rgcpgExtent[3];
Call( ErrSPGetExtentInfo(
ppib,
ifmp,
pfucb,
fSPOwnedExtent,
&( pbtsSpaceTree->cOwnedExtents ),
&( pbtsSpaceTree->prgOwnedExtents ) ) );
Call( ErrSPGetExtentInfo(
ppib,
ifmp,
pfucb,
fSPAvailExtent,
&( pbtsSpaceTree->cAvailExtents ),
&( pbtsSpaceTree->prgAvailExtents ) ) );
HandleError:
Assert( pfucbNil != pfucb );
if ( fForceInit )
{
Assert( pfucb->u.pfcb->WRefCount() == 1 );
pfucb->u.pfcb->Lock();
pfucb->u.pfcb->CreateCompleteErr( errFCBUnusable );
pfucb->u.pfcb->Unlock();
}
BTClose( pfucb );
return err;
}
typedef struct
{
CDBUTLIRunCalculator * pRC;
BTREE_STATS_PARENT_OF_LEAF * pPOL;
} EVAL_INT_PAGE_CTX;
ERR EvalInternalPages(
const PGNO pgno, const ULONG iLevel, const CPAGE * pcpage, void * pvCtx
)
{
EVAL_INT_PAGE_CTX * pEval = (EVAL_INT_PAGE_CTX*)pvCtx;
Assert( pEval );
if ( pcpage->FLeafPage() )
{
Assert( pcpage->FRootPage() );
Assert( pEval->pPOL->cpgInternal == 0 );
pEval->pPOL->cpgData++;
if ( pEval->pRC )
{
pEval->pRC->ErrProcessPage(pgno);
}
}
else
{
pEval->pPOL->cpgInternal++;
#ifdef SPACE_DUMP_ACOUNT_FOR_RUNS_BROKEN_BY_INTERNAL_PAGES
if ( pEval->pRC )
{
pEval->pRC->ErrBreak();
}
#endif
}
if ( pEval->pPOL->cDepth == 0 &&
( pcpage->FParentOfLeaf() || pcpage->FLeafPage() ) )
{
pEval->pPOL->cDepth = 1 + ( pcpage->FLeafPage() ? 0 : ( iLevel + 1 ) );
}
return JET_errSuccess;
}
ERR EvalInternalPageNodes(
const CPAGE::PGHDR * const ppghdr,
INT itag,
DWORD fNodeFlags,
const KEYDATAFLAGS * const pkdf,
void * pvCtx
)
{
ERR err = JET_errSuccess;
EVAL_INT_PAGE_CTX * pEval = (EVAL_INT_PAGE_CTX*)pvCtx;
Assert( pEval );
if( !( ppghdr->fFlags & CPAGE::fPageLeaf ) )
{
if ( pEval->pPOL->pInternalPageStats )
{
CallR( ErrAccumulatePageStats(
ppghdr,
itag,
fNodeFlags,
pkdf,
pEval->pPOL->pInternalPageStats ) );
}
}
if ( pkdf == NULL )
{
Assert( itag == 0 );
return JET_errSuccess;
}
if ( pEval->pPOL->fEmpty )
{
pEval->pPOL->fEmpty = fFalse;
}
if( ppghdr->fFlags & CPAGE::fPageParentOfLeaf )
{
PGNO pgnoLeaf = *((UnalignedLittleEndian<ULONG>*)pkdf->data.Pv());
pEval->pPOL->cpgData++;
if ( pEval->pRC )
{
pEval->pRC->ErrProcessPage(pgnoLeaf);
}
}
return err;
}
ERR ErrDBUTLGetParentOfLeaf(
__in const IFMP ifmp,
__in const PGNO pgnoFDP,
__out BTREE_STATS_PARENT_OF_LEAF * pParentOfLeaf
)
{
ERR err = JET_errSuccess;
CBTreeStatsManager::ResetParentOfLeaf( pParentOfLeaf );
Assert( pParentOfLeaf->phistoIOContiguousRuns );
pParentOfLeaf->fEmpty = fTrue;
CDBUTLIRunCalculator RC( (CStats*)(pParentOfLeaf->phistoIOContiguousRuns), &(pParentOfLeaf->cForwardScans) );
EVAL_INT_PAGE_CTX ctx = { &RC, pParentOfLeaf };
Call( ErrBTUTLAcross( ifmp, pgnoFDP,
CPAGE::fPageParentOfLeaf,
EvalInternalPages, &ctx,
EvalInternalPageNodes, &ctx ) );
RC.ErrProcessPage(CDBUTLIRunCalculator::pgnoDoneSentinel);
Assert( pParentOfLeaf->cDepth );
Assert( !pParentOfLeaf->fEmpty || ( pParentOfLeaf->cDepth == 1 ) );
Assert( ( pParentOfLeaf->cpgInternal == 1 ) || ( pParentOfLeaf->cDepth != 2 ) );
Assert( pParentOfLeaf->fEmpty || pParentOfLeaf->cForwardScans );
HandleError:
return err;
}
ERR ErrDBUTLGetAdditionalSpaceData(
PIB * ppib,
const IFMP ifmp,
const OBJID objidFDP,
const PGNO pgnoFDP,
BTREE_STATS * const pbts,
CPRINTF * const pcprintf )
{
ERR err = JET_errSuccess;
if( pbts->pSpaceTrees )
{
Call( ErrDBUTLGetSpaceTreeInfo(
ppib,
ifmp,
objidFDP,
pgnoFDP,
pbts->pSpaceTrees,
pcprintf ) );
}
if ( pbts->pParentOfLeaf )
{
Call( ErrDBUTLGetParentOfLeaf( ifmp, pgnoFDP, pbts->pParentOfLeaf ) );
}
if ( pbts->pFullWalk )
{
Expected( pbts->pBasicCatalog->eType != eBTreeTypeInternalLongValue ||
pbts->pLvData != NULL );
Call( ErrDBUTLGetDataPageStats(
ppib,
ifmp,
pgnoFDP,
pbts->pFullWalk,
pbts->pBasicCatalog->eType == eBTreeTypeInternalLongValue ? pbts->pLvData : NULL ) );
}
HandleError:
return err;
}
typedef struct
{
JET_SESID ppib;
IFMP ifmp;
JET_GRBIT grbitDbUtilOptions;
WCHAR * wszSelectedTable;
BTREE_STATS * pbts;
OBJID objidCurrentTable;
JET_PFNSPACEDATA pfnBTreeStatsAnalysisFunc;
JET_API_PTR pvBTreeStatsAnalysisFuncCtx;
} DBUTIL_ENUM_SPACE_CTX;
ERR ErrDBUTLEnumSingleSpaceTree(
PIB * ppib,
const IFMP ifmp,
const JET_BTREETYPE eBTType,
BTREE_STATS * const pbts,
JET_PFNSPACEDATA pfnBTreeStatsAnalysisFunc,
JET_API_PTR pvBTreeStatsAnalysisFuncCtx )
{
ERR err = JET_errSuccess;
Assert( pbts );
Assert( pbts->pParent );
Assert( pbts->pSpaceTrees );
Assert( pbts->pParent->pSpaceTrees->fMultiExtent );
Assert( eBTType == eBTreeTypeInternalSpaceOE ||
eBTType == eBTreeTypeInternalSpaceAE );
memset( pbts->pSpaceTrees, 0, sizeof(*(pbts->pSpaceTrees)) );
pbts->pSpaceTrees->cbStruct = sizeof(*(pbts->pSpaceTrees));
pbts->pSpaceTrees->pgnoOE = pbts->pParent->pSpaceTrees->pgnoOE;
pbts->pSpaceTrees->pgnoAE = pbts->pParent->pSpaceTrees->pgnoAE;
PGNO pgnoFDP = ( eBTType == eBTreeTypeInternalSpaceOE ) ?
pbts->pSpaceTrees->pgnoOE :
pbts->pSpaceTrees->pgnoAE;
if ( pbts->pBasicCatalog )
{
pbts->pBasicCatalog->eType = eBTType;
pbts->pBasicCatalog->pgnoFDP = pgnoFDP;
Assert( pbts->pBasicCatalog->objidFDP );
Assert( pbts->pParent->pBasicCatalog->objidFDP == pbts->pBasicCatalog->objidFDP );
if ( pbts->pBasicCatalog->eType == eBTreeTypeInternalSpaceOE )
{
OSStrCbCopyW( pbts->pBasicCatalog->rgName, sizeof(pbts->pBasicCatalog->rgName), L"[Owned Extents]" );
}
else
{
Assert( pbts->pBasicCatalog->eType == eBTreeTypeInternalSpaceAE );
OSStrCbCopyW( pbts->pBasicCatalog->rgName, sizeof(pbts->pBasicCatalog->rgName), L"[Avail Extents]" );
}
pbts->pBasicCatalog->pSpaceHints = NULL;
}
if ( pbts->pSpaceTrees )
{
Assert( pbts->pSpaceTrees->cbStruct == sizeof(*(pbts->pSpaceTrees)) );
pbts->pSpaceTrees->cpgPrimary = 1;
Assert( ( pbts->pSpaceTrees->pgnoOE + 1 ) == pbts->pSpaceTrees->pgnoAE );
pbts->pSpaceTrees->cpgAvailable = 0;
BTREE_STATS_PARENT_OF_LEAF btsSpaceTree = { 0 };
EVAL_INT_PAGE_CTX ctx = { NULL, &btsSpaceTree };
Call( ErrBTUTLAcross( ifmp,
pgnoFDP,
CPAGE::fPageParentOfLeaf,
EvalInternalPages, &ctx,
EvalInternalPageNodes, &ctx ) );
pbts->pSpaceTrees->cpgOwned = btsSpaceTree.cpgInternal + btsSpaceTree.cpgData;
pbts->pSpaceTrees->fMultiExtent = (btsSpaceTree.cpgInternal != 0);
}
if ( pbts->pParentOfLeaf )
{
Call( ErrDBUTLGetParentOfLeaf( ifmp, pgnoFDP, pbts->pParentOfLeaf ) );
}
if ( pbts->pFullWalk )
{
Call( ErrDBUTLGetDataPageStats(
ppib,
ifmp,
pgnoFDP,
pbts->pFullWalk,
NULL ) );
}
Call( pfnBTreeStatsAnalysisFunc( pbts, pvBTreeStatsAnalysisFuncCtx ) );
HandleError:
return err;
}
ERR ErrDBUTLEnumSpaceTrees(
PIB * ppib,
const IFMP ifmp,
const OBJID objidParent,
BTREE_STATS * const pbts,
JET_PFNSPACEDATA pfnBTreeStatsAnalysisFunc,
JET_API_PTR pvBTreeStatsAnalysisFuncCtx )
{
ERR err = JET_errSuccess;
Assert( pbts );
Assert( pbts->pParent );
Assert( pbts->pSpaceTrees );
Assert( pbts->pParent->pSpaceTrees->fMultiExtent );
if ( pbts->pBasicCatalog )
{
memset( pbts->pBasicCatalog, 0, sizeof(*(pbts->pBasicCatalog)) );
pbts->pBasicCatalog->cbStruct = sizeof(*(pbts->pBasicCatalog));
pbts->pBasicCatalog->objidFDP = pbts->pParent->pBasicCatalog->objidFDP;
Assert( pbts->pParent->pBasicCatalog->objidFDP == objidParent );
Assert( pbts->pBasicCatalog->objidFDP == objidParent );
pbts->pBasicCatalog->pSpaceHints = NULL;
}
Call( ErrDBUTLEnumSingleSpaceTree(
ppib,
ifmp,
eBTreeTypeInternalSpaceOE,
pbts,
pfnBTreeStatsAnalysisFunc,
pvBTreeStatsAnalysisFuncCtx ) );
Call( ErrDBUTLEnumSingleSpaceTree(
ppib,
ifmp,
eBTreeTypeInternalSpaceAE,
pbts,
pfnBTreeStatsAnalysisFunc,
pvBTreeStatsAnalysisFuncCtx ) );
HandleError:
return err;
}
ERR ErrDBUTLEnumIndexSpace( const INDEXDEF * pindexdef, void * pv )
{
PFNINDEX pfnindex = ErrDBUTLEnumIndexSpace;
ERR err = JET_errSuccess;
DBUTIL_ENUM_SPACE_CTX *pdbues = (DBUTIL_ENUM_SPACE_CTX *)pv;
PIB *ppib = (PIB*)pdbues->ppib;
const IFMP ifmp = pdbues->ifmp;
BTREE_STATS * pbts = pdbues->pbts;
Unused( pfnindex );
Assert( pbts );
Assert( pbts->pParent );
Assert( pindexdef );
if ( pindexdef->fPrimary )
{
return JET_errSuccess;
}
if ( pbts->pBasicCatalog )
{
BTREE_STATS_BASIC_CATALOG * pbtsBasicCatalog = pbts->pBasicCatalog;
pbtsBasicCatalog->cbStruct = sizeof(*pbtsBasicCatalog);
pbtsBasicCatalog->eType = eBTreeTypeUserSecondaryIndex;
CAutoWSZDDL cwszDDL;
CallR( cwszDDL.ErrSet(pindexdef->szName) );
OSStrCbCopyW( pbtsBasicCatalog->rgName, sizeof(pbtsBasicCatalog->rgName), cwszDDL.Pv() );
pbtsBasicCatalog->objidFDP = pindexdef->objidFDP;
pbtsBasicCatalog->pgnoFDP = pindexdef->pgnoFDP;
pbts->pBasicCatalog->pSpaceHints = (JET_SPACEHINTS*) &(pindexdef->spacehints);
}
CPRINTF * const pcprintf = ( pdbues->grbitDbUtilOptions & JET_bitDBUtilOptionDumpVerbose ) ?
CPRINTFSTDOUT::PcprintfInstance() : NULL;
CallR( ErrDBUTLGetAdditionalSpaceData(
ppib,
ifmp,
pindexdef->objidFDP,
pindexdef->pgnoFDP,
pbts,
pcprintf ) );
Call( pdbues->pfnBTreeStatsAnalysisFunc( pbts, pdbues->pvBTreeStatsAnalysisFuncCtx ) );
if ( pbts->pSpaceTrees && pbts->pSpaceTrees->fMultiExtent )
{
CBTreeStatsManager btsIdxSpaceTreesManager( pdbues->grbitDbUtilOptions, pbts );
Call( ErrDBUTLEnumSpaceTrees(
ppib,
ifmp,
pindexdef->objidFDP,
btsIdxSpaceTreesManager.Pbts(),
pdbues->pfnBTreeStatsAnalysisFunc,
pdbues->pvBTreeStatsAnalysisFuncCtx ) );
}
HandleError:
return err;
}
ERR ErrDBUTLEnumTableSpace( const TABLEDEF * ptabledef, void * pv )
{
PFNTABLE pfntable = ErrDBUTLEnumTableSpace;
ERR err;
DBUTIL_ENUM_SPACE_CTX *pdbues = (DBUTIL_ENUM_SPACE_CTX *)pv;
PIB *ppib = (PIB *)pdbues->ppib;
const IFMP ifmp = (IFMP)pdbues->ifmp;
BTREE_STATS * pbts = pdbues->pbts;
CBTreeStatsManager btsTableChildrenManager( pdbues->grbitDbUtilOptions, pbts );
Unused( pfntable );
Assert( ptabledef );
Assert( pbts );
Assert( pbts->pParent );
if ( pbts->pBasicCatalog )
{
BTREE_STATS_BASIC_CATALOG * pbtsBasicCatalog = pbts->pBasicCatalog;
pbtsBasicCatalog->cbStruct = sizeof(*pbtsBasicCatalog);
pbtsBasicCatalog->eType = eBTreeTypeUserClusteredIndex;
CAutoWSZDDL cwszDDL;
CallR( cwszDDL.ErrSet( ptabledef->szName ) );
OSStrCbCopyW( pbtsBasicCatalog->rgName, sizeof(pbtsBasicCatalog->rgName), cwszDDL.Pv() );
pbtsBasicCatalog->objidFDP = ptabledef->objidFDP;
pbtsBasicCatalog->pgnoFDP = ptabledef->pgnoFDP;
pbts->pBasicCatalog->pSpaceHints = (JET_SPACEHINTS*) &(ptabledef->spacehints);
}
if ( pgnoNull != ptabledef->pgnoFDPLongValues )
{
(void)ErrBFPrereadPage( ifmp, ptabledef->pgnoFDPLongValues, bfprfDefault, ppib->BfpriPriority( ifmp ), TcCurr() );
}
CPRINTF * const pcprintf = ( pdbues->grbitDbUtilOptions & JET_bitDBUtilOptionDumpVerbose ) ?
CPRINTFSTDOUT::PcprintfInstance() : NULL;
Call( ErrDBUTLGetAdditionalSpaceData(
ppib,
ifmp,
ptabledef->objidFDP,
ptabledef->pgnoFDP,
pbts,
pcprintf ) );
Call( pdbues->pfnBTreeStatsAnalysisFunc( pbts, pdbues->pvBTreeStatsAnalysisFuncCtx ) );
pbts = btsTableChildrenManager.Pbts();
if ( pbts->pSpaceTrees && pbts->pParent->pSpaceTrees->fMultiExtent )
{
Call( ErrDBUTLEnumSpaceTrees(
ppib,
ifmp,
ptabledef->objidFDP,
pbts,
pdbues->pfnBTreeStatsAnalysisFunc,
pdbues->pvBTreeStatsAnalysisFuncCtx ) );
}
if ( pgnoNull != ptabledef->pgnoFDPLongValues )
{
if ( pbts->pBasicCatalog )
{
BTREE_STATS_BASIC_CATALOG * pbtsBasicCatalog = pbts->pBasicCatalog;
pbtsBasicCatalog->cbStruct = sizeof(*pbtsBasicCatalog);
pbtsBasicCatalog->eType = eBTreeTypeInternalLongValue;
OSStrCbCopyW( pbtsBasicCatalog->rgName, sizeof(pbtsBasicCatalog->rgName), L"[Long Values]" );
pbtsBasicCatalog->objidFDP = ptabledef->objidFDPLongValues;
pbtsBasicCatalog->pgnoFDP = ptabledef->pgnoFDPLongValues;
pbtsBasicCatalog->pSpaceHints = (JET_SPACEHINTS*) &(ptabledef->spacehintsLV);
}
if ( pbts->pLvData )
{
pbts->pLvData->cbLVChunkMax = ptabledef->cbLVChunkMax;
}
Call( ErrDBUTLGetAdditionalSpaceData(
ppib,
ifmp,
ptabledef->objidFDPLongValues,
ptabledef->pgnoFDPLongValues,
pbts,
pcprintf ) );
Call( pdbues->pfnBTreeStatsAnalysisFunc( pbts, pdbues->pvBTreeStatsAnalysisFuncCtx ) );
CBTreeStatsManager btsLVSpaceTreesManager( pdbues->grbitDbUtilOptions, pbts );
if ( pbts->pSpaceTrees && pbts->pSpaceTrees->fMultiExtent )
{
Call( ErrDBUTLEnumSpaceTrees(
ppib,
ifmp,
ptabledef->objidFDPLongValues,
btsLVSpaceTreesManager.Pbts(),
pdbues->pfnBTreeStatsAnalysisFunc,
pdbues->pvBTreeStatsAnalysisFuncCtx ) );
}
}
DBUTIL_ENUM_SPACE_CTX dbuesIdx;
memcpy( &dbuesIdx, pdbues, sizeof(dbuesIdx) );
dbuesIdx.pbts = btsTableChildrenManager.Pbts();
JET_DBUTIL_W dbutil;
memset( &dbutil, 0, sizeof( dbutil ) );
dbutil.cbStruct = sizeof( dbutil );
dbutil.op = opDBUTILEDBDump;
dbutil.sesid = pdbues->ppib;
dbutil.dbid = (JET_DBID)pdbues->ifmp;
dbutil.pgno = ptabledef->objidFDP;
dbutil.pfnCallback = (void *)ErrDBUTLEnumIndexSpace;
dbutil.pvCallback = &dbuesIdx;
dbutil.edbdump = opEDBDumpIndexes;
dbutil.grbitOptions = pdbues->grbitDbUtilOptions;
pdbues->objidCurrentTable = ptabledef->objidFDP;
err = ErrDBUTLDump( pdbues->ppib, &dbutil );
HandleError:
return err;
}
LOCAL INT PrintIndexBareMetaData( const INDEXDEF * pindexdef, void * pv )
{
PFNINDEX pfnindex = PrintIndexBareMetaData;
Unused( pfnindex );
Assert( pindexdef );
printf( " %-49.49s %s ", pindexdef->szName, ( pindexdef->fPrimary ? "Pri" : "Idx" ) );
DBUTLPrintfIntN( pindexdef->objidFDP, 10 );
printf( " " );
DBUTLPrintfIntN( pindexdef->pgnoFDP, 10 );
printf( "\n" );
return JET_errSuccess;
}
LOCAL INT PrintTableBareMetaData( const TABLEDEF * ptabledef, void * pv )
{
PFNTABLE pfntable = PrintTableBareMetaData;
ERR err;
JET_DBUTIL_A *pdbutil = (JET_DBUTIL_A *)pv;
Unused( pfntable );
Assert( ptabledef );
printf( "%-51.51s Tbl ", ptabledef->szName );
DBUTLPrintfIntN( ptabledef->objidFDP, 10 );
printf( " " );
DBUTLPrintfIntN( ptabledef->pgnoFDP, 10 );
printf( "\n" );
if ( pgnoNull != ptabledef->pgnoFDPLongValues )
{
printf( " %-49.49s LV ", "<Long Values>" );
DBUTLPrintfIntN( ptabledef->objidFDPLongValues, 10 );
printf( " " );
DBUTLPrintfIntN( ptabledef->pgnoFDPLongValues, 10 );
printf( "\n" );
}
JET_DBUTIL_W dbutil;
memset( &dbutil, 0, sizeof( dbutil ) );
dbutil.cbStruct = sizeof( dbutil );
dbutil.op = opDBUTILEDBDump;
dbutil.sesid = pdbutil->sesid;
dbutil.dbid = pdbutil->dbid;
dbutil.pgno = ptabledef->objidFDP;
dbutil.pfnCallback = (void *)PrintIndexBareMetaData;
dbutil.pvCallback = &dbutil;
dbutil.edbdump = opEDBDumpIndexes;
dbutil.grbitOptions = pdbutil->grbitOptions;
err = ErrDBUTLDump( pdbutil->sesid, &dbutil );
return err;
}
LOCAL VOID DBUTLDumpDefaultSpaceHints( __inout JET_SPACEHINTS * const pSpacehints, __in const CPG cpgInitial, __in const BOOL fTable )
{
if ( 0 == pSpacehints->cbInitial )
{
pSpacehints->cbInitial = g_cbPage * cpgInitial;
}
if ( 0 == pSpacehints->ulMaintDensity )
{
pSpacehints->ulMaintDensity = ulFILEDefaultDensity;
}
if ( 0 == pSpacehints->cbMinExtent )
{
if ( fTable || ( 0 == ( pSpacehints->grbit & JET_bitSpaceHintsUtilizeParentSpace ) ) )
{
pSpacehints->cbMinExtent = cpgSmallGrow * g_cbPage;
}
else
{
pSpacehints->cbMinExtent = g_cbPage;
}
}
if ( 0 == pSpacehints->cbMaxExtent )
{
if ( fTable || ( 0 == ( pSpacehints->grbit & JET_bitSpaceHintsUtilizeParentSpace ) ) )
{
pSpacehints->cbMaxExtent = cpageSEDefault * g_cbPage;
}
else
{
pSpacehints->cbMaxExtent = g_cbPage;
}
}
if ( 0 == pSpacehints->ulGrowth )
{
pSpacehints->ulGrowth = 100;
}
}
ERR ErrCATIUnmarshallExtendedSpaceHints(
__in INST * const pinst,
__in const SYSOBJ sysobj,
__in const BOOL fDeferredLongValueHints,
__in const BYTE * const pBuffer,
__in const ULONG cbBuffer,
__in const LONG cbPageSize,
__out JET_SPACEHINTS * pSpacehints
);
LOCAL ERR ErrDBUTLDumpOneIndex( PIB * ppib, FUCB * pfucbCatalog, VOID * pfnCallback, VOID * pvCallback )
{
JET_RETRIEVECOLUMN rgretrievecolumn[17];
BYTE pbufidxseg[JET_ccolKeyMost*sizeof(IDXSEG)];
BYTE pbufidxsegConditional[JET_ccolKeyMost*sizeof(IDXSEG)];
BYTE pbExtendedSpaceHints[cbExtendedSpaceHints];
INDEXDEF indexdef;
ERR err = JET_errSuccess;
INT iretrievecolumn = 0;
OBJID objidTable;
USHORT cbVarSegMac = 0;
USHORT cbKeyMost = 0;
QWORD qwSortVersion = 0;
memset( &indexdef, 0, sizeof( indexdef ) );
memset( rgretrievecolumn, 0, sizeof( rgretrievecolumn ) );
rgretrievecolumn[iretrievecolumn].columnid = fidMSO_ObjidTable;
rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)&objidTable;
rgretrievecolumn[iretrievecolumn].cbData = sizeof(objidTable);
rgretrievecolumn[iretrievecolumn].itagSequence = 1;
++iretrievecolumn;
rgretrievecolumn[iretrievecolumn].columnid = fidMSO_PgnoFDP;
rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)&indexdef.pgnoFDP;
rgretrievecolumn[iretrievecolumn].cbData = sizeof(indexdef.pgnoFDP);
rgretrievecolumn[iretrievecolumn].itagSequence = 1;
++iretrievecolumn;
rgretrievecolumn[iretrievecolumn].columnid = fidMSO_Id;
rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)&indexdef.objidFDP;
rgretrievecolumn[iretrievecolumn].cbData = sizeof(indexdef.objidFDP);
rgretrievecolumn[iretrievecolumn].itagSequence = 1;
++iretrievecolumn;
rgretrievecolumn[iretrievecolumn].columnid = fidMSO_Name;
rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)indexdef.szName;
rgretrievecolumn[iretrievecolumn].cbData = sizeof(indexdef.szName);
rgretrievecolumn[iretrievecolumn].itagSequence = 1;
++iretrievecolumn;
rgretrievecolumn[iretrievecolumn].columnid = fidMSO_SpaceUsage;
rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)&indexdef.density;
rgretrievecolumn[iretrievecolumn].cbData = sizeof(indexdef.density);
rgretrievecolumn[iretrievecolumn].itagSequence = 1;
++iretrievecolumn;
rgretrievecolumn[iretrievecolumn].columnid = fidMSO_Localization;
rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)&indexdef.lcid;
rgretrievecolumn[iretrievecolumn].cbData = sizeof(indexdef.lcid);
rgretrievecolumn[iretrievecolumn].itagSequence = 1;
++iretrievecolumn;
rgretrievecolumn[iretrievecolumn].columnid = fidMSO_LocaleName;
rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)&indexdef.wszLocaleName;
rgretrievecolumn[iretrievecolumn].cbData = sizeof(indexdef.wszLocaleName);
rgretrievecolumn[iretrievecolumn].itagSequence = 1;
++iretrievecolumn;
rgretrievecolumn[iretrievecolumn].columnid = fidMSO_SortID;
rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)&indexdef.sortID;
rgretrievecolumn[iretrievecolumn].cbData = sizeof(indexdef.sortID);
rgretrievecolumn[iretrievecolumn].itagSequence = 1;
++iretrievecolumn;
rgretrievecolumn[iretrievecolumn].columnid = fidMSO_LCMapFlags;
rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)&indexdef.dwMapFlags;
rgretrievecolumn[iretrievecolumn].cbData = sizeof(indexdef.dwMapFlags);
rgretrievecolumn[iretrievecolumn].itagSequence = 1;
++iretrievecolumn;
rgretrievecolumn[iretrievecolumn].columnid = fidMSO_Flags;
rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)&indexdef.fFlags;
rgretrievecolumn[iretrievecolumn].cbData = sizeof(indexdef.fFlags);
rgretrievecolumn[iretrievecolumn].itagSequence = 1;
++iretrievecolumn;
const INT iretcolTupleLimits = iretrievecolumn;
rgretrievecolumn[iretrievecolumn].columnid = fidMSO_TupleLimits;
rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)&indexdef.le_tuplelimits;
rgretrievecolumn[iretrievecolumn].cbData = sizeof(indexdef.le_tuplelimits);
rgretrievecolumn[iretrievecolumn].itagSequence = 1;
++iretrievecolumn;
const INT iretcolIdxsegConditional = iretrievecolumn;
rgretrievecolumn[iretrievecolumn].columnid = fidMSO_ConditionalColumns;
rgretrievecolumn[iretrievecolumn].pvData = pbufidxsegConditional;
rgretrievecolumn[iretrievecolumn].cbData = sizeof(pbufidxsegConditional);
rgretrievecolumn[iretrievecolumn].itagSequence = 1;
++iretrievecolumn;
const INT iretcolIdxseg = iretrievecolumn;
rgretrievecolumn[iretrievecolumn].columnid = fidMSO_KeyFldIDs;
rgretrievecolumn[iretrievecolumn].pvData = pbufidxseg;
rgretrievecolumn[iretrievecolumn].cbData = sizeof(pbufidxseg);
rgretrievecolumn[iretrievecolumn].itagSequence = 1;
++iretrievecolumn;
rgretrievecolumn[iretrievecolumn].columnid = fidMSO_VarSegMac;
rgretrievecolumn[iretrievecolumn].pvData = &cbVarSegMac;
rgretrievecolumn[iretrievecolumn].cbData = sizeof(cbVarSegMac);
rgretrievecolumn[iretrievecolumn].itagSequence = 1;
++iretrievecolumn;
rgretrievecolumn[iretrievecolumn].columnid = fidMSO_KeyMost;
rgretrievecolumn[iretrievecolumn].pvData = &cbKeyMost;
rgretrievecolumn[iretrievecolumn].cbData = sizeof(cbKeyMost);
rgretrievecolumn[iretrievecolumn].itagSequence = 1;
++iretrievecolumn;
rgretrievecolumn[iretrievecolumn].columnid = fidMSO_Version;
rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)&qwSortVersion;
rgretrievecolumn[iretrievecolumn].cbData = sizeof(qwSortVersion);
rgretrievecolumn[iretrievecolumn].itagSequence = 1;
++iretrievecolumn;
const INT iretcolExtSpaceHints = iretrievecolumn;
rgretrievecolumn[iretrievecolumn].columnid = fidMSO_SpaceHints;
rgretrievecolumn[iretrievecolumn].pvData = pbExtendedSpaceHints;
rgretrievecolumn[iretrievecolumn].cbData = sizeof(pbExtendedSpaceHints);
rgretrievecolumn[iretrievecolumn].itagSequence = 1;
++iretrievecolumn;
Assert( iretrievecolumn <= sizeof( rgretrievecolumn ) / sizeof( rgretrievecolumn[0] ) );
CallR( ErrIsamRetrieveColumns(
(JET_SESID)ppib,
(JET_TABLEID)pfucbCatalog,
rgretrievecolumn,
iretrievecolumn ) );
const IDBFLAG idbflag = (IDBFLAG)indexdef.fFlags;
const IDXFLAG idxflag = (IDXFLAG)( indexdef.fFlags >> sizeof(IDBFLAG) * 8 );
indexdef.fUnique = !!FIDBUnique( idbflag );
indexdef.fPrimary = !!FIDBPrimary( idbflag );
indexdef.fAllowAllNulls = !!FIDBAllowAllNulls( idbflag );
indexdef.fAllowFirstNull = !!FIDBAllowFirstNull( idbflag );
indexdef.fAllowSomeNulls = !!FIDBAllowSomeNulls( idbflag );
indexdef.fNoNullSeg = !!FIDBNoNullSeg( idbflag );
indexdef.fSortNullsHigh = !!FIDBSortNullsHigh( idbflag );
indexdef.fMultivalued = !!FIDBMultivalued( idbflag );
indexdef.fTuples = ( JET_wrnColumnNull == rgretrievecolumn[iretcolTupleLimits].err ? fFalse : fTrue );
indexdef.fLocaleSet = !!FIDBLocaleSet( idbflag );
indexdef.fLocalizedText = !!FIDBLocalizedText( idbflag );
indexdef.fTemplateIndex = !!FIDBTemplateIndex( idbflag );
indexdef.fDerivedIndex = !!FIDBDerivedIndex( idbflag );
indexdef.fExtendedColumns = !!FIDXExtendedColumns( idxflag );
indexdef.cbVarSegMac = cbVarSegMac;
indexdef.cbKeyMost = cbKeyMost;
indexdef.dwDefinedVersion = (DWORD)( ( qwSortVersion >> 32 ) & 0xFFFFFFFF );
indexdef.dwNLSVersion = (DWORD)( qwSortVersion & 0xFFFFFFFF );
if ( !indexdef.fPrimary && indexdef.fDerivedIndex )
{
const INT cchTableName = JET_cbNameMost + 1;
CHAR szTableName[cchTableName];
FUCB * pfucbDerivedTable;
FCB * pfcbDerivedIndex;
CallR( ErrCATSeekTableByObjid(
ppib,
pfucbCatalog->ifmp,
objidTable,
szTableName,
cchTableName,
NULL ) );
CallR( ErrFILEOpenTable(
ppib,
pfucbCatalog->u.pfcb->Ifmp(),
&pfucbDerivedTable,
szTableName,
JET_bitTableReadOnly ) );
const TDB * ptdbDerivedTable = pfucbDerivedTable->u.pfcb->Ptdb();
for ( pfcbDerivedIndex = pfucbDerivedTable->u.pfcb;
NULL != pfcbDerivedIndex;
pfcbDerivedIndex = pfcbDerivedIndex->PfcbNextIndex() )
{
if ( NULL != pfcbDerivedIndex->Pidb() && ( UtilCmpName( indexdef.szName, ptdbDerivedTable->SzIndexName( pfcbDerivedIndex->Pidb()->ItagIndexName(), pfcbDerivedIndex->FDerivedIndex() ) ) == 0 ) )
{
break;
}
}
Assert( pfcbDerivedIndex );
if ( NULL == pfcbDerivedIndex )
{
CallR( JET_errCatalogCorrupted );
}
pfcbDerivedIndex->GetAPISpaceHints( &indexdef.spacehints );
CallS( ErrFILECloseTable( ppib, pfucbDerivedTable ) );
}
else
{
indexdef.spacehints.cbStruct = sizeof(indexdef.spacehints);
indexdef.spacehints.ulInitialDensity = indexdef.density;
if( rgretrievecolumn[iretcolExtSpaceHints].cbActual )
{
CallR( ErrCATIUnmarshallExtendedSpaceHints( PinstFromPfucb( pfucbCatalog ), sysobjIndex, fFalse, pbExtendedSpaceHints,
rgretrievecolumn[iretcolExtSpaceHints].cbActual, g_rgfmp[ pfucbCatalog->ifmp ].CbPage(), &indexdef.spacehints ) );
}
}
DBUTLDumpDefaultSpaceHints( &indexdef.spacehints, cpgInitialTreeDefault, fFalse );
Assert( rgretrievecolumn[iretcolIdxseg].cbActual > 0 );
if ( indexdef.fExtendedColumns )
{
INT iidxseg;
Assert( sizeof(IDXSEG) == sizeof(JET_COLUMNID) );
Assert( rgretrievecolumn[iretcolIdxseg].cbActual <= sizeof(JET_COLUMNID) * JET_ccolKeyMost );
Assert( rgretrievecolumn[iretcolIdxseg].cbActual % sizeof(JET_COLUMNID) == 0 );
Assert( rgretrievecolumn[iretcolIdxseg].cbActual / sizeof(JET_COLUMNID) <= JET_ccolKeyMost );
indexdef.ccolumnidDef = rgretrievecolumn[iretcolIdxseg].cbActual / sizeof(JET_COLUMNID);
for ( iidxseg = 0; iidxseg < indexdef.ccolumnidDef; iidxseg++ )
{
const LE_IDXSEG * const ple_idxseg = (LE_IDXSEG *)pbufidxseg + iidxseg;
indexdef.rgidxsegDef[iidxseg] = *ple_idxseg;
Assert( FCOLUMNIDValid( indexdef.rgidxsegDef[iidxseg].Columnid() ) );
}
Assert( rgretrievecolumn[iretcolIdxsegConditional].cbActual <= sizeof(JET_COLUMNID) * JET_ccolKeyMost );
Assert( rgretrievecolumn[iretcolIdxsegConditional].cbActual % sizeof(JET_COLUMNID) == 0 );
Assert( rgretrievecolumn[iretcolIdxsegConditional].cbActual / sizeof(JET_COLUMNID) <= JET_ccolKeyMost );
indexdef.ccolumnidConditional = rgretrievecolumn[iretcolIdxsegConditional].cbActual / sizeof(JET_COLUMNID);
for ( iidxseg = 0; iidxseg < indexdef.ccolumnidConditional; iidxseg++ )
{
const LE_IDXSEG * const ple_idxsegConditional = (LE_IDXSEG *)pbufidxsegConditional + iidxseg;
indexdef.rgidxsegConditional[iidxseg] = *ple_idxsegConditional;
Assert( FCOLUMNIDValid( indexdef.rgidxsegConditional[iidxseg].Columnid() ) );
}
}
else
{
Assert( sizeof(IDXSEG_OLD) == sizeof(FID) );
Assert( rgretrievecolumn[iretcolIdxseg].cbActual <= sizeof(FID) * JET_ccolKeyMost );
Assert( rgretrievecolumn[iretcolIdxseg].cbActual % sizeof(FID) == 0);
Assert( rgretrievecolumn[iretcolIdxseg].cbActual / sizeof(FID) <= JET_ccolKeyMost );
indexdef.ccolumnidDef = rgretrievecolumn[iretcolIdxseg].cbActual / sizeof( FID );
SetIdxSegFromOldFormat(
(UnalignedLittleEndian< IDXSEG_OLD > *)pbufidxseg,
indexdef.rgidxsegDef,
indexdef.ccolumnidDef,
fFalse,
fFalse,
NULL );
Assert( rgretrievecolumn[iretcolIdxsegConditional].cbActual <= sizeof(FID) * JET_ccolKeyMost );
Assert( rgretrievecolumn[iretcolIdxsegConditional].cbActual % sizeof(FID) == 0);
Assert( rgretrievecolumn[iretcolIdxsegConditional].cbActual / sizeof(FID) <= JET_ccolKeyMost );
indexdef.ccolumnidConditional = rgretrievecolumn[iretcolIdxsegConditional].cbActual / sizeof( FID );
SetIdxSegFromOldFormat(
(UnalignedLittleEndian< IDXSEG_OLD > *)pbufidxsegConditional,
indexdef.rgidxsegConditional,
indexdef.ccolumnidConditional,
fTrue,
fFalse,
NULL );
}
CallR( ErrCATGetIndexSegments(
ppib,
pfucbCatalog->u.pfcb->Ifmp(),
objidTable,
indexdef.rgidxsegDef,
indexdef.ccolumnidDef,
fFalse,
!indexdef.fExtendedColumns,
indexdef.rgszIndexDef ) );
CallR( ErrCATGetIndexSegments(
ppib,
pfucbCatalog->u.pfcb->Ifmp(),
objidTable,
indexdef.rgidxsegConditional,
indexdef.ccolumnidConditional,
fTrue,
!indexdef.fExtendedColumns,
indexdef.rgszIndexConditional ) );
PFNINDEX const pfnindex = (PFNINDEX)pfnCallback;
return (*pfnindex)( &indexdef, pvCallback );
}
LOCAL ERR ErrGetSpaceHintsForLV( PIB * ppib, const IFMP ifmp, const OBJID objidTable, JET_SPACEHINTS * const pSpacehints )
{
ERR err = JET_errSuccess;
FUCB * pfucbTable = pfucbNil;
FUCB * pfucbLV = pfucbNil;
PGNO pgnoFDP;
CHAR szTableName[JET_cbNameMost+1];
Call( ErrCATSeekTableByObjid(
ppib,
ifmp,
objidTable,
szTableName,
sizeof( szTableName ),
&pgnoFDP ) );
CallR( ErrFILEOpenTable( ppib, ifmp, &pfucbTable, szTableName ) );
Call( ErrFILEOpenLVRoot( pfucbTable, &pfucbLV, fFalse ) );
if( pfucbLV != pfucbNil )
{
pfucbLV->u.pfcb->GetAPISpaceHints( pSpacehints );
}
HandleError:
if( pfucbNil != pfucbTable )
{
if( pfucbNil != pfucbLV )
{
DIRClose( pfucbLV );
pfucbLV = pfucbNil;
}
ErrFILECloseTable( ppib, pfucbTable );
pfucbTable = pfucbNil;
}
return err;
}
LOCAL ERR ErrDBUTLDumpOneTable( PIB * ppib, FUCB * pfucbCatalog, PFNTABLE pfntable, VOID * pvCallback )
{
JET_RETRIEVECOLUMN rgretrievecolumn[11];
BYTE pbExtendedSpaceHints[cbExtendedSpaceHints];
BYTE pbExtendedSpaceHintsDeferredLV[cbExtendedSpaceHints];
TABLEDEF tabledef;
ERR err = JET_errSuccess;
INT iretrievecolumn = 0;
memset( &tabledef, 0, sizeof( tabledef ) );
memset( rgretrievecolumn, 0, sizeof( rgretrievecolumn ) );
rgretrievecolumn[iretrievecolumn].columnid = fidMSO_Name;
rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)tabledef.szName;
rgretrievecolumn[iretrievecolumn].cbData = sizeof( tabledef.szName );
rgretrievecolumn[iretrievecolumn].itagSequence = 1;
++iretrievecolumn;
rgretrievecolumn[iretrievecolumn].columnid = fidMSO_TemplateTable;
rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)tabledef.szTemplateTable;
rgretrievecolumn[iretrievecolumn].cbData = sizeof( tabledef.szTemplateTable );
rgretrievecolumn[iretrievecolumn].itagSequence = 1;
++iretrievecolumn;
rgretrievecolumn[iretrievecolumn].columnid = fidMSO_PgnoFDP;
rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)&( tabledef.pgnoFDP );
rgretrievecolumn[iretrievecolumn].cbData = sizeof( tabledef.pgnoFDP );
rgretrievecolumn[iretrievecolumn].itagSequence = 1;
++iretrievecolumn;
rgretrievecolumn[iretrievecolumn].columnid = fidMSO_Id;
rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)&( tabledef.objidFDP );
rgretrievecolumn[iretrievecolumn].cbData = sizeof( tabledef.objidFDP );
rgretrievecolumn[iretrievecolumn].itagSequence = 1;
++iretrievecolumn;
rgretrievecolumn[iretrievecolumn].columnid = fidMSO_Pages;
rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)&( tabledef.pages );
rgretrievecolumn[iretrievecolumn].cbData = sizeof( tabledef.pages );
rgretrievecolumn[iretrievecolumn].itagSequence = 1;
++iretrievecolumn;
rgretrievecolumn[iretrievecolumn].columnid = fidMSO_SpaceUsage;
rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)&( tabledef.density );
rgretrievecolumn[iretrievecolumn].cbData = sizeof( tabledef.density );
rgretrievecolumn[iretrievecolumn].itagSequence = 1;
++iretrievecolumn;
rgretrievecolumn[iretrievecolumn].columnid = fidMSO_Flags;
rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)&( tabledef.fFlags );
rgretrievecolumn[iretrievecolumn].cbData = sizeof( tabledef.fFlags );
rgretrievecolumn[iretrievecolumn].itagSequence = 1;
++iretrievecolumn;
const INT iretcolExtSpaceHints = iretrievecolumn;
rgretrievecolumn[iretrievecolumn].columnid = fidMSO_SpaceHints;
rgretrievecolumn[iretrievecolumn].pvData = pbExtendedSpaceHints;
rgretrievecolumn[iretrievecolumn].cbData = sizeof(pbExtendedSpaceHints);
rgretrievecolumn[iretrievecolumn].itagSequence = 1;
++iretrievecolumn;
const INT iretcolExtSpaceHintsDeferredLV = iretrievecolumn;
rgretrievecolumn[iretrievecolumn].columnid = fidMSO_SpaceLVDeferredHints;
rgretrievecolumn[iretrievecolumn].pvData = pbExtendedSpaceHintsDeferredLV;
rgretrievecolumn[iretrievecolumn].cbData = sizeof(pbExtendedSpaceHintsDeferredLV);
rgretrievecolumn[iretrievecolumn].itagSequence = 1;
++iretrievecolumn;
rgretrievecolumn[iretrievecolumn].columnid = fidMSO_LVChunkMax;
rgretrievecolumn[iretrievecolumn].pvData = (BYTE *)&( tabledef.cbLVChunkMax );
rgretrievecolumn[iretrievecolumn].cbData = sizeof( tabledef.cbLVChunkMax );
rgretrievecolumn[iretrievecolumn].itagSequence = 1;
++iretrievecolumn;
Call( ErrIsamRetrieveColumns(
(JET_SESID)ppib,
(JET_TABLEID)pfucbCatalog,
rgretrievecolumn,
iretrievecolumn ) );
if ( tabledef.cbLVChunkMax == 0 )
{
tabledef.cbLVChunkMax = (LONG)UlParam( JET_paramLVChunkSizeMost );
}
if ( ( tabledef.fFlags & JET_bitObjectTableDerived ) && ( 0 == rgretrievecolumn[iretcolExtSpaceHints].cbActual ) )
{
FUCB *pfucbTemplateTable;
Assert( ( NULL != tabledef.szTemplateTable ) && ( '\0' != tabledef.szTemplateTable[0] ) );
CallR( ErrFILEOpenTable(
ppib,
pfucbCatalog->u.pfcb->Ifmp(),
&pfucbTemplateTable,
tabledef.szTemplateTable,
JET_bitTableReadOnly ) );
Assert( pfcbNil != pfucbTemplateTable->u.pfcb );
Assert( pfucbTemplateTable->u.pfcb->FTemplateTable() );
Expected( pfucbTemplateTable->u.pfcb->FFixedDDL() );
pfucbTemplateTable->u.pfcb->GetAPISpaceHints( &tabledef.spacehints );
CallS( ErrFILECloseTable( ppib, pfucbTemplateTable ) );
}
else
{
tabledef.spacehints.cbStruct = sizeof(tabledef.spacehints);
tabledef.spacehints.ulInitialDensity = tabledef.density;
if( rgretrievecolumn[iretcolExtSpaceHints].cbActual )
{
Call( ErrCATIUnmarshallExtendedSpaceHints( PinstFromPfucb( pfucbCatalog ), sysobjTable, fFalse, pbExtendedSpaceHints,
rgretrievecolumn[iretcolExtSpaceHints].cbActual, g_rgfmp[ pfucbCatalog->ifmp ].CbPage(), &tabledef.spacehints ) );
}
if( rgretrievecolumn[iretcolExtSpaceHintsDeferredLV].cbActual )
{
memset( &tabledef.spacehintsDeferredLV, 0, sizeof(tabledef.spacehintsDeferredLV) );
tabledef.spacehintsDeferredLV.cbStruct = sizeof(tabledef.spacehints);
tabledef.spacehintsDeferredLV.ulInitialDensity = tabledef.density;
Call( ErrCATIUnmarshallExtendedSpaceHints( PinstFromPfucb( pfucbCatalog ), sysobjTable, fTrue, pbExtendedSpaceHintsDeferredLV,
rgretrievecolumn[iretcolExtSpaceHintsDeferredLV].cbActual, g_rgfmp[ pfucbCatalog->ifmp ].CbPage(), &tabledef.spacehintsDeferredLV ) );
}
}
DBUTLDumpDefaultSpaceHints( &tabledef.spacehints, tabledef.pages, fTrue );
Call( ErrCATAccessTableLV(
ppib,
pfucbCatalog->u.pfcb->Ifmp(),
tabledef.objidFDP,
&tabledef.pgnoFDPLongValues,
&tabledef.objidFDPLongValues ) );
err = ErrGetSpaceHintsForLV( ppib, pfucbCatalog->u.pfcb->Ifmp(), tabledef.objidFDP, &tabledef.spacehintsLV );
if ( err >= JET_errSuccess )
{
DBUTLDumpDefaultSpaceHints( &tabledef.spacehintsLV, 0, fFalse );
}
else
{
err = JET_errSuccess;
}
Call( (*pfntable)( &tabledef, pvCallback ) );
HandleError:
return err;
}
LOCAL ERR ErrDBUTLDumpTables( PIB * ppib, IFMP ifmp, __in PCWSTR wszTableName, PFNTABLE pfntable, VOID * pvCallback )
{
ERR err;
FUCB *pfucbCatalog = pfucbNil;
CallR( ErrCATOpen( ppib, ifmp, &pfucbCatalog ) );
Assert( pfucbNil != pfucbCatalog );
Call( ErrIsamSetCurrentIndex( ppib, pfucbCatalog, szMSORootObjectsIndex ) );
if ( NULL != wszTableName )
{
const BYTE bTrue = 0xff;
CAutoSZDDL szTableName;
Call( szTableName.ErrSet( wszTableName ) );
Call( ErrIsamMakeKey(
ppib,
pfucbCatalog,
&bTrue,
sizeof(bTrue),
JET_bitNewKey ) );
Call( ErrIsamMakeKey(
ppib,
pfucbCatalog,
(CHAR*)szTableName,
(ULONG)strlen((CHAR*)szTableName),
NO_GRBIT ) );
err = ErrIsamSeek( ppib, pfucbCatalog, JET_bitSeekEQ );
if ( JET_errRecordNotFound == err )
err = ErrERRCheck( JET_errObjectNotFound );
Call( err );
CallS( err );
Call( ErrDBUTLDumpOneTable( ppib, pfucbCatalog, pfntable, pvCallback ) );
}
else
{
err = ErrIsamMove( ppib, pfucbCatalog, JET_MoveFirst, NO_GRBIT );
while ( JET_errNoCurrentRecord != err )
{
Call( err );
Call( ErrDBUTLDumpOneTable( ppib, pfucbCatalog, pfntable, pvCallback ) );
err = ErrIsamMove( ppib, pfucbCatalog, JET_MoveNext, NO_GRBIT );
}
}
err = JET_errSuccess;
HandleError:
CallS( ErrCATClose( ppib, pfucbCatalog ) );
return err;
}
LOCAL ERR ErrDBUTLDumpTableObjects(
PIB *ppib,
const IFMP ifmp,
const OBJID objidFDP,
const SYSOBJ sysobj,
PFNDUMP pfnDump,
VOID *pfnCallback,
VOID *pvCallback )
{
ERR err;
FUCB *pfucbCatalog = pfucbNil;
CallR( ErrCATOpen( ppib, ifmp, &pfucbCatalog ) );
Assert( pfucbNil != pfucbCatalog );
FUCBSetSequential( pfucbCatalog );
Call( ErrIsamSetCurrentIndex( ppib, pfucbCatalog, szMSONameIndex ) );
Call( ErrIsamMakeKey(
ppib,
pfucbCatalog,
(BYTE *)&objidFDP,
sizeof(objidFDP),
JET_bitNewKey ) );
Call( ErrIsamMakeKey(
ppib,
pfucbCatalog,
(BYTE *)&sysobj,
sizeof(sysobj),
NO_GRBIT ) );
err = ErrIsamSeek( ppib, pfucbCatalog, JET_bitSeekGT );
if ( err < 0 )
{
if ( JET_errRecordNotFound != err )
goto HandleError;
}
else
{
CallS( err );
Call( ErrIsamMakeKey(
ppib,
pfucbCatalog,
(BYTE *)&objidFDP,
sizeof(objidFDP),
JET_bitNewKey ) );
Call( ErrIsamMakeKey(
ppib,
pfucbCatalog,
(BYTE *)&sysobj,
sizeof(sysobj),
JET_bitStrLimit ) );
err = ErrIsamSetIndexRange( ppib, pfucbCatalog, JET_bitRangeUpperLimit );
Assert( err <= 0 );
while ( JET_errNoCurrentRecord != err )
{
Call( err );
Call( (*pfnDump)( ppib, pfucbCatalog, pfnCallback, pvCallback ) );
err = ErrIsamMove( ppib, pfucbCatalog, JET_MoveNext, NO_GRBIT );
}
}
err = JET_errSuccess;
HandleError:
CallS( ErrCATClose( ppib, pfucbCatalog ) );
return err;
}
#endif
LOCAL ERR ErrDBUTLDumpPageUsage( JET_SESID sesid, const JET_DBUTIL_W * pdbutil )
{
ERR err;
PIB * ppib = (PIB *)sesid;
const FUCB * pfucb = (FUCB *)pdbutil->tableid;
PGNO pgnoFDP;
CallR( ErrPIBCheck( ppib ) );
if ( JET_tableidNil == pdbutil->tableid || pfucbNil == pfucb )
{
CallR( ErrERRCheck( JET_errInvalidTableId ) );
}
CheckTable( ppib, pfucb );
CheckSecondary( pfucb );
if ( pdbutil->grbitOptions & JET_bitDBUtilOptionDumpLVPageUsage )
{
Call( ErrCATAccessTableLV( ppib, pfucb->ifmp, pfucb->u.pfcb->ObjidFDP(), &pgnoFDP ) );
}
else
{
if ( pfucbNil != pfucb->pfucbCurIndex )
pfucb = pfucb->pfucbCurIndex;
pgnoFDP = pfucb->u.pfcb->PgnoFDP();
}
Call( ErrBTDumpPageUsage( ppib, pfucb->ifmp, pgnoFDP ) );
HandleError:
return err;
}
#ifdef MINIMAL_FUNCTIONALITY
#else
LOCAL ERR ErrDBUTLDump( JET_SESID sesid, const JET_DBUTIL_W *pdbutil )
{
ERR err;
switch( pdbutil->edbdump )
{
case opEDBDumpTables:
{
PFNTABLE const pfntable = (PFNTABLE)( pdbutil->pfnCallback );
err = ErrDBUTLDumpTables(
(PIB *)sesid,
IFMP( pdbutil->dbid ),
pdbutil->szTable,
pfntable,
pdbutil->pvCallback );
}
break;
case opEDBDumpIndexes:
err = ErrDBUTLDumpTableObjects(
(PIB *)sesid,
IFMP( pdbutil->dbid ),
(OBJID)pdbutil->pgno,
sysobjIndex,
&ErrDBUTLDumpOneIndex,
pdbutil->pfnCallback,
pdbutil->pvCallback );
break;
case opEDBDumpColumns:
err = ErrDBUTLDumpTableObjects(
(PIB *)sesid,
IFMP( pdbutil->dbid ),
OBJID( pdbutil->pgno ),
sysobjColumn,
&ErrDBUTLDumpOneColumn,
pdbutil->pfnCallback,
pdbutil->pvCallback );
break;
case opEDBDumpCallbacks:
err = ErrDBUTLDumpTableObjects(
(PIB *)sesid,
IFMP( pdbutil->dbid ),
OBJID( pdbutil->pgno ),
sysobjCallback,
&ErrDBUTLDumpOneCallback,
pdbutil->pfnCallback,
pdbutil->pvCallback );
break;
case opEDBDumpPage:
{
PFNPAGE const pfnpage = (PFNPAGE)( pdbutil->pfnCallback );
err = ErrDBUTLDumpPage( (PIB *)sesid, (IFMP) pdbutil->dbid, pdbutil->pgno, pfnpage, pdbutil->pvCallback );
}
break;
default:
Assert( fFalse );
err = ErrERRCheck( JET_errFeatureNotAvailable );
break;
}
return err;
}
LOCAL ERR ErrDBUTLDumpTables( DBCCINFO *pdbccinfo, PFNTABLE pfntable, VOID * pvCtx )
{
JET_SESID sesid = (JET_SESID)pdbccinfo->ppib;
JET_DBID dbid = (JET_DBID)pdbccinfo->ifmp;
JET_DBUTIL_W dbutil;
memset( &dbutil, 0, sizeof( dbutil ) );
dbutil.cbStruct = sizeof( dbutil );
dbutil.op = opDBUTILEDBDump;
dbutil.sesid = sesid;
dbutil.dbid = dbid;
dbutil.pfnCallback = (void *)pfntable;
dbutil.pvCallback = pvCtx ? pvCtx : &dbutil;
dbutil.edbdump = opEDBDumpTables;
dbutil.grbitOptions = pdbccinfo->grbitOptions;
dbutil.szTable = ( NULL == pdbccinfo->wszTable || L'\0' == pdbccinfo->wszTable[0] ?
NULL :
pdbccinfo->wszTable );
return ErrDBUTLDump( sesid, &dbutil );
}
#endif
LOCAL ERR ErrDBUTLDumpFlushMap( INST* const pinst, const WCHAR* const wszFlushMapFilePath, const FMPGNO fmpgno, const JET_GRBIT grbit )
{
if ( grbit & JET_bitDBUtilOptionVerify )
{
return CFlushMapForDump::ErrChecksumFlushMapFile( pinst, wszFlushMapFilePath );
}
else
{
return CFlushMapForDump::ErrDumpFlushMapPage( pinst, wszFlushMapFilePath, fmpgno, grbit & JET_bitDBUtilOptionDumpVerbose );
}
}
LOCAL ERR ErrDBUTLDumpSpaceCat( JET_SESID sesid, JET_DBUTIL_W *pdbutil )
{
ERR err = JET_errSuccess;
JET_DBID dbid = JET_dbidNil;
BOOL fDbAttached = fFalse;
BOOL fDbOpen = fFalse;
if ( ( pdbutil->spcatOptions.pgnoFirst < 1 ) ||
( ( pdbutil->spcatOptions.pgnoLast != pgnoMax ) && ( pdbutil->spcatOptions.pgnoFirst > pdbutil->spcatOptions.pgnoLast ) ) )
{
Error( ErrERRCheck( JET_errInvalidParameter ) );
}
Call( ErrIsamAttachDatabase(
sesid,
pdbutil->spcatOptions.szDatabase,
fFalse,
NULL,
0,
JET_bitDbReadOnly ) );
fDbAttached = fTrue;
Call( ErrIsamOpenDatabase(
sesid,
pdbutil->spcatOptions.szDatabase,
NULL,
&dbid,
JET_bitDbExclusive | JET_bitDbReadOnly ) );
fDbOpen = fTrue;
if ( pdbutil->spcatOptions.pgnoLast == pgnoMax )
{
Call( g_rgfmp[ (IFMP)dbid ].ErrPgnoLastFileSystem( &( pdbutil->spcatOptions.pgnoLast ) ) );
}
pdbutil->spcatOptions.pgnoFirst = UlFunctionalMin( pdbutil->spcatOptions.pgnoFirst, pdbutil->spcatOptions.pgnoLast );
Assert( pdbutil->spcatOptions.pgnoFirst >= 1 );
Assert( pdbutil->spcatOptions.pgnoLast >= 1 );
Assert( pdbutil->spcatOptions.pgnoFirst <= pdbutil->spcatOptions.pgnoLast );
Call( ErrSPGetSpaceCategoryRange(
(PIB*)sesid,
(IFMP)dbid,
pdbutil->spcatOptions.pgnoFirst,
pdbutil->spcatOptions.pgnoLast,
!!( pdbutil->grbitOptions & JET_bitDBUtilFullCategorization ),
(JET_SPCATCALLBACK)pdbutil->spcatOptions.pfnSpaceCatCallback,
pdbutil->spcatOptions.pvContext ) );
err = JET_errSuccess;
HandleError:
if ( fDbOpen )
{
(void)ErrIsamCloseDatabase( sesid, dbid, NO_GRBIT );
fDbOpen = fFalse;
}
if ( fDbAttached )
{
(void)ErrIsamDetachDatabase( sesid, NULL, pdbutil->spcatOptions.szDatabase );
fDbAttached = fFalse;
}
return err;
}
LOCAL ERR ErrDBUTLDumpCachedFileHeader( const WCHAR* const wszFilePath, const JET_GRBIT grbit )
{
ERR err = JET_errSuccess;
Call( ErrOSBCDumpCachedFileHeader( wszFilePath, grbit, CPRINTFSTDOUT::PcprintfInstance() ) );
HandleError:
return err;
}
LOCAL ERR ErrDBUTLDumpCacheFile( const WCHAR* const wszFilePath, const JET_GRBIT grbit )
{
ERR err = JET_errSuccess;
Call( ErrOSBCDumpCacheFile( wszFilePath, grbit, CPRINTFSTDOUT::PcprintfInstance() ) );
HandleError:
return err;
}
BOOL g_fDisableDumpPrintF = fFalse;
ERR ISAMAPI ErrIsamDBUtilities( JET_SESID sesid, JET_DBUTIL_W *pdbutil )
{
ERR err = JET_errSuccess;
INST *pinst = PinstFromPpib( (PIB*)sesid );
PIBTraceContextScope tcScope = ( (PIB*)sesid )->InitTraceContextScope();
tcScope->nParentObjectClass = tceNone;
Assert( pdbutil );
Assert( pdbutil->cbStruct == sizeof( JET_DBUTIL_W ) );
if ( opDBUTILEDBDump != pdbutil->op &&
opDBUTILDumpPageUsage != pdbutil->op &&
opDBUTILChecksumLogFromMemory != pdbutil->op &&
opDBUTILDumpSpaceCategory != pdbutil->op &&
opDBUTILDumpRBSPages != pdbutil->op )
{
if ( NULL == pdbutil->szDatabase || L'\0' == pdbutil->szDatabase[0] )
{
return ErrERRCheck( JET_errDatabaseInvalidName );
}
}
if ( opDBUTILDumpRBSPages == pdbutil->op )
{
if ( NULL == pdbutil->rbsOptions.szDatabase || L'\0' == pdbutil->rbsOptions.szDatabase[0] )
{
return ErrERRCheck( JET_errDatabaseInvalidName );
}
}
if ( opDBUTILChecksumLogFromMemory == pdbutil->op )
{
if ( pinst->m_plog->FLGFileOpened() || !pinst->FComputeLogDisabled() )
{
return ErrERRCheck( JET_errInvalidParameter );
}
}
if ( ( pdbutil->grbitOptions & JET_bitDBUtilOptionSuppressConsoleOutput ) != 0 )
{
g_fDisableDumpPrintF = fTrue;
}
switch ( pdbutil->op )
{
#ifdef MINIMAL_FUNCTIONALITY
#else
case opDBUTILChecksumLogFromMemory:
return ErrDUMPLogFromMemory( pinst,
pdbutil->checksumlogfrommemory.szLog,
pdbutil->checksumlogfrommemory.pvBuffer,
pdbutil->checksumlogfrommemory.cbBuffer );
case opDBUTILDumpLogfile:
return ErrDUMPLog( pinst, pdbutil->szDatabase, pdbutil->lGeneration, pdbutil->isec, pdbutil->grbitOptions, pdbutil->szIntegPrefix );
case opDBUTILDumpFlushMapFile:
return ErrDBUTLDumpFlushMap( pinst, pdbutil->szDatabase, pdbutil->pgno, pdbutil->grbitOptions );
case opDBUTILDumpLogfileTrackNode:
return JET_errSuccess;
case opDBUTILEDBDump:
return ErrDBUTLDump( sesid, pdbutil );
case opDBUTILDumpNode:
return ErrDBUTLDumpNode( sesid, pinst->m_pfsapi, pdbutil->szDatabase, pdbutil->pgno, pdbutil->iline, pdbutil->grbitOptions );
#ifdef DEBUG
case opDBUTILSetHeaderState:
return ErrDUMPFixupHeader( pinst, pdbutil->szDatabase, pdbutil->grbitOptions & JET_bitDBUtilOptionDumpVerbose );
#endif
case opDBUTILDumpPage:
return ErrDBUTLDumpPage( pinst, pdbutil->szDatabase, pdbutil->pgno, pdbutil->szIndex, pdbutil->szTable, pdbutil->grbitOptions );
case opDBUTILDumpHeader:
return ErrDUMPHeader( pinst, pdbutil->szDatabase, pdbutil->grbitOptions & JET_bitDBUtilOptionDumpVerbose );
case opDBUTILDumpCheckpoint:
return ErrDUMPCheckpoint( pinst, pdbutil->szDatabase );
case opDBUTILDumpCachedFileHeader:
return ErrDBUTLDumpCachedFileHeader( pdbutil->szDatabase, pdbutil->grbitOptions );
case opDBUTILDumpCacheFile:
return ErrDBUTLDumpCacheFile( pdbutil->szDatabase, pdbutil->grbitOptions );
#endif
case opDBUTILEDBRepair:
return ErrDBUTLRepair( sesid, pdbutil, CPRINTFSTDOUT::PcprintfInstance() );
#ifdef MINIMAL_FUNCTIONALITY
#else
case opDBUTILEDBScrub:
return ErrDBUTLScrub( sesid, pdbutil );
case opDBUTILDumpData:
return ErrESEDUMPData( sesid, pdbutil );
case opDBUTILDumpPageUsage:
return ErrDBUTLDumpPageUsage( sesid, pdbutil );
#endif
case opDBUTILDBDefragment:
{
ERR errDetach;
if ( (ULONG)UlParam( pinst, JET_paramEngineFormatVersion ) == JET_efvUsePersistedFormat )
{
DBFILEHDR * pdbfilehdr = NULL;
JET_ENGINEFORMATVERSION efvSourceDb = JET_efvExchange55Rtm;
AllocR( pdbfilehdr = (DBFILEHDR * )PvOSMemoryPageAlloc( g_cbPage, NULL ) );
memset( pdbfilehdr, 0, g_cbPage );
IFileAPI * pfapi = NULL;
if ( CIOFilePerf::ErrFileOpen(
pinst->m_pfsapi,
pinst,
pdbutil->szDatabase,
( IFileAPI::fmfReadOnly |
( BoolParam( JET_paramEnableFileCache ) ?
IFileAPI::fmfCached :
IFileAPI::fmfNone ) ),
iofileDbAttached,
qwDefragFileID,
&pfapi ) >= JET_errSuccess )
{
err = ErrUtilReadShadowedHeader( pinst,
pinst->m_pfsapi,
pfapi,
(BYTE*)pdbfilehdr,
g_cbPage,
OffsetOf( DBFILEHDR, le_cbPageSize ),
urhfReadOnly );
if ( err >= JET_errSuccess )
{
const FormatVersions * pfmtvers = NULL;
err = ErrDBFindHighestMatchingDbMajors( pdbfilehdr->Dbv(), &pfmtvers, fTrue );
if ( err >= JET_errSuccess )
{
efvSourceDb = pfmtvers->efv;
}
}
delete pfapi;
}
CallR( err );
Assert( efvSourceDb != JET_efvUsePersistedFormat );
Assert( efvSourceDb != JET_efvExchange55Rtm );
err = SetParam( pinst, NULL, JET_paramEngineFormatVersion, efvSourceDb, NULL );
}
Assert( JET_efvUsePersistedFormat != UlParam( pinst, JET_paramEngineFormatVersion ) );
err = ErrIsamAttachDatabase( sesid,
pdbutil->szDatabase,
fFalse,
NULL,
0,
JET_bitDbReadOnly );
if ( JET_errSuccess != err )
{
return err;
}
err = ErrIsamCompact( sesid,
pdbutil->szDatabase,
pinst->m_pfsapi,
pdbutil->szTable,
JET_PFNSTATUS( pdbutil->pfnCallback ),
NULL,
pdbutil->grbitOptions );
errDetach = ErrIsamDetachDatabase( sesid, NULL, pdbutil->szDatabase );
if ( err >= JET_errSuccess && errDetach < JET_errSuccess )
{
err = errDetach;
}
return err;
}
case opDBUTILDBTrim:
{
ERR errDetach;
err = ErrIsamAttachDatabase( sesid,
pdbutil->szDatabase,
fFalse,
NULL,
0,
JET_bitDbExclusive );
if ( JET_errSuccess != err )
{
return err;
}
err = ErrIsamTrimDatabase( sesid,
pdbutil->szDatabase,
pinst->m_pfsapi,
CPRINTFSTDOUT::PcprintfInstance(),
pdbutil->grbitOptions );
errDetach = ErrIsamDetachDatabase( sesid, NULL, pdbutil->szDatabase );
if ( err >= JET_errSuccess && errDetach < JET_errSuccess )
{
err = errDetach;
}
return err;
}
case opDBUTILDumpSpaceCategory:
return ErrDBUTLDumpSpaceCat( sesid, pdbutil );
case opDBUTILDumpRBSPages:
return ErrDUMPRBSPage( pinst, pdbutil->rbsOptions.szDatabase, pdbutil->rbsOptions.pgnoFirst, pdbutil->rbsOptions.pgnoLast, pdbutil->grbitOptions & JET_bitDBUtilOptionDumpVerbose );
case opDBUTILDumpRBSHeader:
return ErrDUMPRBSHeader( pinst, pdbutil->szDatabase, pdbutil->grbitOptions & JET_bitDBUtilOptionDumpVerbose );
}
#ifdef MINIMAL_FUNCTIONALITY
#else
DBCCINFO dbccinfo;
JET_DBID dbid = JET_dbidNil;
JET_GRBIT grbitAttach;
memset( &dbccinfo, 0, sizeof(DBCCINFO) );
dbccinfo.tableidPageInfo = JET_tableidNil;
dbccinfo.tableidSpaceInfo = JET_tableidNil;
dbccinfo.op = opDBUTILConsistency;
switch ( pdbutil->op )
{
#ifdef DEBUG
case opDBUTILMunge:
#endif
case opDBUTILDumpMetaData:
case opDBUTILDumpSpace:
dbccinfo.op = pdbutil->op;
break;
}
Assert( NULL != pdbutil->szDatabase );
OSStrCbCopyW( dbccinfo.wszDatabase, sizeof(dbccinfo.wszDatabase), pdbutil->szDatabase );
if ( NULL != pdbutil->szTable )
{
OSStrCbCopyW( dbccinfo.wszTable, sizeof(dbccinfo.wszTable), pdbutil->szTable );
}
if ( NULL != pdbutil->szIndex )
{
OSStrCbCopyW( dbccinfo.wszIndex, sizeof(dbccinfo.wszIndex), pdbutil->szIndex );
}
if ( pdbutil->grbitOptions & JET_bitDBUtilOptionStats )
{
dbccinfo.grbitOptions |= JET_bitDBUtilOptionStats;
}
if ( pdbutil->grbitOptions & JET_bitDBUtilOptionDumpVerbose )
{
dbccinfo.grbitOptions |= JET_bitDBUtilOptionDumpVerbose;
}
grbitAttach = ( opDBUTILMunge == dbccinfo.op ) ? 0 : JET_bitDbReadOnly;
CallR( ErrIsamAttachDatabase( sesid,
dbccinfo.wszDatabase,
fFalse,
NULL,
0,
grbitAttach ) );
Assert( JET_wrnDatabaseAttached != err );
Call( ErrIsamOpenDatabase( sesid,
dbccinfo.wszDatabase,
NULL,
&dbid,
grbitAttach ) );
dbccinfo.ppib = (PIB*)sesid;
dbccinfo.ifmp = dbid;
switch ( dbccinfo.op )
{
case opDBUTILConsistency:
Call( ErrERRCheck( JET_errFeatureNotAvailable ) );
break;
case opDBUTILDumpSpace:
{
if ( NULL == pdbutil->pfnCallback )
{
Call( ErrERRCheck( JET_errFeatureNotAvailable ) );
}
Call( ErrOLDDumpMSysDefrag( dbccinfo.ppib, dbccinfo.ifmp ) );
Call( ErrSCANDumpMSysScan( dbccinfo.ppib, dbccinfo.ifmp ) );
Call( MSysDBM::ErrDumpTable( dbccinfo.ifmp ) );
CBTreeStatsManager btsDbRootManager( pdbutil->grbitOptions, NULL );
BTREE_STATS * pbts = btsDbRootManager.Pbts();
if ( pbts->pBasicCatalog )
{
BTREE_STATS_BASIC_CATALOG * pbtsBasicCatalog = pbts->pBasicCatalog;
memset( pbtsBasicCatalog, 0, sizeof(*pbtsBasicCatalog) );
pbtsBasicCatalog->cbStruct = sizeof(*pbtsBasicCatalog);
pbtsBasicCatalog->eType = eBTreeTypeInternalDbRootSpace;
(void)ErrOSStrCbCopyW( pbtsBasicCatalog->rgName, sizeof(pbtsBasicCatalog->rgName), dbccinfo.wszDatabase );
pbtsBasicCatalog->objidFDP = objidSystemRoot;
pbtsBasicCatalog->pgnoFDP = pgnoSystemRoot;
}
if ( pbts->pSpaceTrees )
{
CPRINTF * const pcprintf = ( pdbutil->grbitOptions & JET_bitDBUtilOptionDumpVerbose ) ?
CPRINTFSTDOUT::PcprintfInstance() :
NULL;
CallR( ErrDBUTLGetSpaceTreeInfo(
dbccinfo.ppib,
dbccinfo.ifmp,
objidSystemRoot,
pgnoSystemRoot,
pbts->pSpaceTrees,
pcprintf ) );
}
if ( pbts->pParentOfLeaf )
{
pbts->pParentOfLeaf->cpgData = 1;
}
Call( ((JET_PFNSPACEDATA)pdbutil->pfnCallback)( pbts, (JET_API_PTR)pdbutil->pvCallback ) );
CBTreeStatsManager btsTableManager( pdbutil->grbitOptions, pbts );
if( pbts->pSpaceTrees )
{
Call( ErrDBUTLEnumSpaceTrees(
dbccinfo.ppib,
dbccinfo.ifmp,
objidSystemRoot,
btsTableManager.Pbts(),
(JET_PFNSPACEDATA)pdbutil->pfnCallback,
(JET_API_PTR)pdbutil->pvCallback ) );
}
DBUTIL_ENUM_SPACE_CTX dbues = { 0 };
dbues.ppib = (JET_SESID)dbccinfo.ppib;
dbues.ifmp = dbccinfo.ifmp;
dbues.grbitDbUtilOptions = pdbutil->grbitOptions;
dbues.wszSelectedTable = ( NULL == dbccinfo.wszTable || L'\0' == dbccinfo.wszTable[0] ?
NULL :
dbccinfo.wszTable );
dbues.pbts = btsTableManager.Pbts();
dbues.pfnBTreeStatsAnalysisFunc = (JET_PFNSPACEDATA)pdbutil->pfnCallback;
dbues.pvBTreeStatsAnalysisFuncCtx = (JET_API_PTR) pdbutil->pvCallback;
Call( ErrDBUTLDumpTables( &dbccinfo, ErrDBUTLEnumTableSpace, (VOID*)&dbues ) );
}
break;
case opDBUTILDumpMetaData:
if ( dbccinfo.grbitOptions & JET_bitDBUtilOptionDumpVerbose )
{
printf( "******************************* MSysLocales **********************************\n" );
err = ErrCATDumpMSLocales( NULL, dbccinfo.ifmp );
if ( err != JET_errSuccess )
{
printf( "Failed to dump %hs table with: %d (continuing on ...).\n", szMSLocales, err );
}
printf( "******************************************************************************\n" );
}
printf( "******************************* META-DATA DUMP *******************************\n" );
if ( dbccinfo.grbitOptions & JET_bitDBUtilOptionDumpVerbose )
{
Call( ErrDBUTLDumpTables( &dbccinfo, PrintTableMetaData ) );
}
else
{
printf( "Name Type ObjidFDP PgnoFDP\n" );
printf( "==============================================================================\n" );
printf( "%-51.5ws Db ", dbccinfo.wszDatabase );
DBUTLPrintfIntN( objidSystemRoot, 10 );
printf( " " );
DBUTLPrintfIntN( pgnoSystemRoot, 10 );
printf( "\n\n" );
Call( ErrDBUTLDumpTables( &dbccinfo, PrintTableBareMetaData ) );
}
printf( "******************************************************************************\n" );
break;
default:
err = ErrERRCheck( JET_errFeatureNotAvailable );
Call( err );
break;
}
HandleError:
if ( JET_tableidNil != dbccinfo.tableidPageInfo )
{
Assert( dbccinfo.grbitOptions & JET_bitDBUtilOptionPageDump );
CallS( ErrDispCloseTable( (JET_SESID)dbccinfo.ppib, dbccinfo.tableidPageInfo ) );
dbccinfo.tableidPageInfo = JET_tableidNil;
}
if ( JET_dbidNil != dbid )
{
(VOID)ErrIsamCloseDatabase( sesid, dbid, 0 );
}
(VOID)ErrIsamDetachDatabase( sesid, NULL, dbccinfo.wszDatabase );
fflush( stdout );
#endif
return err;
}
| 165,042 | 58,169 |
/*
* File: collision.cpp
* Author: Nick (original version), ahnonay (SFML2 compatibility)
*/
#include <SFML/Graphics.hpp>
#include "collision.hpp"
namespace Collision
{
sf::Vector2f GetSpriteCenter(const sf::Sprite & Object)
{
sf::FloatRect AABB = Object.getGlobalBounds();
return sf::Vector2f(AABB.left + AABB.width / 2.f, AABB.top + AABB.height / 2.f);
}
sf::Vector2f GetSpriteSize(const sf::Sprite & Object)
{
sf::IntRect OriginalSize = Object.getTextureRect();
sf::Vector2f Scale = Object.getScale();
return sf::Vector2f(OriginalSize.width * Scale.x, OriginalSize.height * Scale.y);
}
bool CircleTest(const sf::Sprite & Object1, const sf::Sprite & Object2) {
sf::Vector2f Obj1Size = GetSpriteSize(Object1);
sf::Vector2f Obj2Size = GetSpriteSize(Object2);
float Radius1 = (Obj1Size.x + Obj1Size.y) / 4;
float Radius2 = (Obj2Size.x + Obj2Size.y) / 4;
sf::Vector2f Distance = GetSpriteCenter(Object1) - GetSpriteCenter(Object2);
return (Distance.x * Distance.x + Distance.y * Distance.y <= (Radius1 + Radius2) * (Radius1 + Radius2));
}
class OrientedBoundingBox // Used in the BoundingBoxTest
{
public:
OrientedBoundingBox(const sf::Sprite& Object) // Calculate the four points of the OBB from a transformed (scaled, rotated...) sprite
{
sf::Transform trans = Object.getTransform();
sf::IntRect local = Object.getTextureRect();
Points[0] = trans.transformPoint(0.f, 0.f);
Points[1] = trans.transformPoint(local.width, 0.f);
Points[2] = trans.transformPoint(local.width, local.height);
Points[3] = trans.transformPoint(0.f, local.height);
}
sf::Vector2f Points[4];
void ProjectOntoAxis(const sf::Vector2f& Axis, float& Min, float& Max) // Project all four points of the OBB onto the given axis and return the dotproducts of the two outermost points
{
Min = (Points[0].x * Axis.x + Points[0].y * Axis.y);
Max = Min;
for (int j = 1; j < 4; j++)
{
float Projection = (Points[j].x * Axis.x + Points[j].y * Axis.y);
if (Projection < Min)
Min = Projection;
if (Projection > Max)
Max = Projection;
}
}
};
bool BoundingBoxTest(const sf::Sprite & Object1, const sf::Sprite & Object2) {
OrientedBoundingBox OBB1(Object1);
OrientedBoundingBox OBB2(Object2);
// Create the four distinct axes that are perpendicular to the edges of the two rectangles
sf::Vector2f Axes[4] = {
sf::Vector2f(OBB1.Points[1].x - OBB1.Points[0].x,
OBB1.Points[1].y - OBB1.Points[0].y),
sf::Vector2f(OBB1.Points[1].x - OBB1.Points[2].x,
OBB1.Points[1].y - OBB1.Points[2].y),
sf::Vector2f(OBB2.Points[0].x - OBB2.Points[3].x,
OBB2.Points[0].y - OBB2.Points[3].y),
sf::Vector2f(OBB2.Points[0].x - OBB2.Points[1].x,
OBB2.Points[0].y - OBB2.Points[1].y)
};
for (int i = 0; i < 4; i++) // For each axis...
{
float MinOBB1, MaxOBB1, MinOBB2, MaxOBB2;
// ... project the points of both OBBs onto the axis ...
OBB1.ProjectOntoAxis(Axes[i], MinOBB1, MaxOBB1);
OBB2.ProjectOntoAxis(Axes[i], MinOBB2, MaxOBB2);
// ... and check whether the outermost projected points of both OBBs overlap.
// If this is not the case, the Separating Axis Theorem states that there can be no collision between the rectangles
if (!((MinOBB2 <= MaxOBB1) && (MaxOBB2 >= MinOBB1)))
return false;
}
return true;
}
}
| 3,338 | 1,408 |
/*
* 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.
*/
#include <stdlib.h>
// Caricature of folly::basic_fbstring without the union between small
// and medium/large data representations, and with an explicit field
// for category_ instead of bitmasking part of the data value.
// ref:
// https://github.com/facebook/folly/blob/72850c2ebfb94d87bea74d89fcf79f3aaa91a627/folly/FBString.h
enum category {
small = 0, // ignore small strings for now
medium = 1,
large = 2,
};
void* checkedMalloc(size_t size) {
void* ptr = malloc(size);
if (ptr == nullptr) {
exit(1);
}
return ptr;
}
struct LikeFBString {
int category_;
char* buffer_;
size_t size_;
unsigned int* refcount_;
LikeFBString() {}
LikeFBString(const LikeFBString& src) {
category_ = src.category();
switch (src.category_) {
case medium:
copyMedium(src);
break;
case large:
copyLarge(src);
break;
default:
exit(2);
}
}
~LikeFBString() {
if (category() == medium) {
free(buffer_);
} else {
decr_ref_count();
}
}
void copySmall(const LikeFBString& src) {}
void copyMedium(const LikeFBString& src) {
buffer_ = (char*)checkedMalloc(src.size_);
size_ = src.size_;
}
void copyLarge(const LikeFBString& src) {
buffer_ = src.buffer_;
size_ = src.size_;
refcount_ = src.refcount_;
*refcount_ = *refcount_ + 1;
}
int category() const { return category_; }
void decr_ref_count() {
if (*refcount_ <= 0) {
exit(1);
}
*refcount_ = *refcount_ - 1;
if (*refcount_ == 0) {
free(buffer_);
}
}
};
void copy_fbstring(LikeFBString& s) {
// this might alias the underlying buffers if the string is large in
// that case the destruction of t does not de-allocate its buffer
// but pulse might think it does if it fails to remember which
// category t belongs to and follows impossibly control flow
LikeFBString t = s;
}
void pass_to_copy_ok() {
LikeFBString s;
copy_fbstring(s);
}
| 2,177 | 759 |
/*
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.
*/
/* ECDH/ECIES/ECDSA Functions - see main program below */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include "ecdh_NIST256.h"
using namespace B256_28;
using namespace NIST256;
/* Calculate a public/private EC GF(p) key pair. W=S.G mod EC(p),
* where S is the secret key and W is the public key
* and G is fixed generator.
* If RNG is NULL then the private key is provided externally in S
* otherwise it is generated randomly internally */
int NIST256::ECP_KEY_PAIR_GENERATE(csprng *RNG,octet* S,octet *W)
{
BIG r,gx,gy,s;
ECP G;
int res=0;
ECP_generator(&G);
BIG_rcopy(r,CURVE_Order);
if (RNG!=NULL)
{
BIG_randomnum(s,r,RNG);
}
else
{
BIG_fromBytes(s,S->val);
BIG_mod(s,r);
}
#ifdef AES_S
BIG_mod2m(s,2*AES_S);
// BIG_toBytes(S->val,s);
#endif
S->len=EGS_NIST256;
BIG_toBytes(S->val,s);
ECP_mul(&G,s);
ECP_toOctet(W,&G,false); // To use point compression on public keys, change to true
/*
#if CURVETYPE_NIST256!=MONTGOMERY
ECP_get(gx,gy,&G);
#else
ECP_get(gx,&G);
#endif
#if CURVETYPE_NIST256!=MONTGOMERY
W->len=2*EFS_NIST256+1;
W->val[0]=4;
BIG_toBytes(&(W->val[1]),gx);
BIG_toBytes(&(W->val[EFS_NIST256+1]),gy);
#else
W->len=EFS_NIST256+1;
W->val[0]=2;
BIG_toBytes(&(W->val[1]),gx);
#endif
*/
return res;
}
/* Validate public key */
int NIST256::ECP_PUBLIC_KEY_VALIDATE(octet *W)
{
BIG q,r,wx,k;
ECP WP;
int valid,nb;
int res=0;
BIG_rcopy(q,Modulus);
BIG_rcopy(r,CURVE_Order);
valid=ECP_fromOctet(&WP,W);
if (!valid) res=ECDH_INVALID_PUBLIC_KEY;
/*
BIG_fromBytes(wx,&(W->val[1]));
if (BIG_comp(wx,q)>=0) res=ECDH_INVALID_PUBLIC_KEY;
#if CURVETYPE_NIST256!=MONTGOMERY
BIG wy;
BIG_fromBytes(wy,&(W->val[EFS_NIST256+1]));
if (BIG_comp(wy,q)>=0) res=ECDH_INVALID_PUBLIC_KEY;
#endif
*/
if (res==0)
{
//#if CURVETYPE_NIST256!=MONTGOMERY
// valid=ECP_set(&WP,wx,wy);
//#else
// valid=ECP_set(&WP,wx);
//#endif
// if (!valid || ECP_isinf(&WP)) res=ECDH_INVALID_PUBLIC_KEY;
// if (res==0 )
// {/* Check point is not in wrong group */
nb=BIG_nbits(q);
BIG_one(k);
BIG_shl(k,(nb+4)/2);
BIG_add(k,q,k);
BIG_sdiv(k,r); /* get co-factor */
while (BIG_parity(k)==0)
{
ECP_dbl(&WP);
BIG_fshr(k,1);
}
if (!BIG_isunity(k)) ECP_mul(&WP,k);
if (ECP_isinf(&WP)) res=ECDH_INVALID_PUBLIC_KEY;
// }
}
return res;
}
/* IEEE-1363 Diffie-Hellman online calculation Z=S.WD */
int NIST256::ECP_SVDP_DH(octet *S,octet *WD,octet *Z)
{
BIG r,s,wx;
int valid;
ECP W;
int res=0;
BIG_fromBytes(s,S->val);
valid=ECP_fromOctet(&W,WD);
/*
BIG_fromBytes(wx,&(WD->val[1]));
#if CURVETYPE_NIST256!=MONTGOMERY
BIG wy;
BIG_fromBytes(wy,&(WD->val[EFS_NIST256+1]));
valid=ECP_set(&W,wx,wy);
#else
valid=ECP_set(&W,wx);
#endif
*/
if (!valid) res=ECDH_ERROR;
if (res==0)
{
BIG_rcopy(r,CURVE_Order);
BIG_mod(s,r);
ECP_mul(&W,s);
if (ECP_isinf(&W)) res=ECDH_ERROR;
else
{
#if CURVETYPE_NIST256!=MONTGOMERY
ECP_get(wx,wx,&W);
#else
ECP_get(wx,&W);
#endif
Z->len=MODBYTES_B256_28;
BIG_toBytes(Z->val,wx);
}
}
return res;
}
#if CURVETYPE_NIST256!=MONTGOMERY
/* IEEE ECDSA Signature, C and D are signature on F using private key S */
int NIST256::ECP_SP_DSA(int sha,csprng *RNG,octet *K,octet *S,octet *F,octet *C,octet *D)
{
char h[128];
octet H= {0,sizeof(h),h};
BIG r,s,f,c,d,u,vx,w;
ECP G,V;
ehashit(sha,F,-1,NULL,&H,sha);
ECP_generator(&G);
BIG_rcopy(r,CURVE_Order);
BIG_fromBytes(s,S->val);
int hlen=H.len;
if (H.len>MODBYTES_B256_28) hlen=MODBYTES_B256_28;
BIG_fromBytesLen(f,H.val,hlen);
if (RNG!=NULL)
{
do
{
BIG_randomnum(u,r,RNG);
BIG_randomnum(w,r,RNG); /* side channel masking */
#ifdef AES_S
BIG_mod2m(u,2*AES_S);
#endif
ECP_copy(&V,&G);
ECP_mul(&V,u);
ECP_get(vx,vx,&V);
BIG_copy(c,vx);
BIG_mod(c,r);
if (BIG_iszilch(c)) continue;
BIG_modmul(u,u,w,r);
BIG_invmodp(u,u,r);
BIG_modmul(d,s,c,r);
BIG_add(d,f,d);
BIG_modmul(d,d,w,r);
BIG_modmul(d,u,d,r);
}
while (BIG_iszilch(d));
}
else
{
BIG_fromBytes(u,K->val);
BIG_mod(u,r);
#ifdef AES_S
BIG_mod2m(u,2*AES_S);
#endif
ECP_copy(&V,&G);
ECP_mul(&V,u);
ECP_get(vx,vx,&V);
BIG_copy(c,vx);
BIG_mod(c,r);
if (BIG_iszilch(c)) return ECDH_ERROR;
BIG_invmodp(u,u,r);
BIG_modmul(d,s,c,r);
BIG_add(d,f,d);
BIG_modmul(d,u,d,r);
if (BIG_iszilch(d)) return ECDH_ERROR;
}
C->len=D->len=EGS_NIST256;
BIG_toBytes(C->val,c);
BIG_toBytes(D->val,d);
return 0;
}
/* IEEE1363 ECDSA Signature Verification. Signature C and D on F is verified using public key W */
int NIST256::ECP_VP_DSA(int sha,octet *W,octet *F, octet *C,octet *D)
{
char h[128];
octet H= {0,sizeof(h),h};
BIG r,wx,wy,f,c,d,h2;
int res=0;
ECP G,WP;
int valid;
ehashit(sha,F,-1,NULL,&H,sha);
ECP_generator(&G);
BIG_rcopy(r,CURVE_Order);
OCT_shl(C,C->len-MODBYTES_B256_28);
OCT_shl(D,D->len-MODBYTES_B256_28);
BIG_fromBytes(c,C->val);
BIG_fromBytes(d,D->val);
int hlen=H.len;
if (hlen>MODBYTES_B256_28) hlen=MODBYTES_B256_28;
BIG_fromBytesLen(f,H.val,hlen);
//BIG_fromBytes(f,H.val);
if (BIG_iszilch(c) || BIG_comp(c,r)>=0 || BIG_iszilch(d) || BIG_comp(d,r)>=0)
res=ECDH_INVALID;
if (res==0)
{
BIG_invmodp(d,d,r);
BIG_modmul(f,f,d,r);
BIG_modmul(h2,c,d,r);
valid=ECP_fromOctet(&WP,W);
/*
BIG_fromBytes(wx,&(W->val[1]));
BIG_fromBytes(wy,&(W->val[EFS_NIST256+1]));
valid=ECP_set(&WP,wx,wy);
*/
if (!valid) res=ECDH_ERROR;
else
{
ECP_mul2(&WP,&G,h2,f);
if (ECP_isinf(&WP)) res=ECDH_INVALID;
else
{
ECP_get(d,d,&WP);
BIG_mod(d,r);
if (BIG_comp(d,c)!=0) res=ECDH_INVALID;
}
}
}
return res;
}
/* IEEE1363 ECIES encryption. Encryption of plaintext M uses public key W and produces ciphertext V,C,T */
void NIST256::ECP_ECIES_ENCRYPT(int sha,octet *P1,octet *P2,csprng *RNG,octet *W,octet *M,int tlen,octet *V,octet *C,octet *T)
{
int i,len;
char z[EFS_NIST256],vz[3*EFS_NIST256+1],k[2*AESKEY_NIST256],k1[AESKEY_NIST256],k2[AESKEY_NIST256],l2[8],u[EFS_NIST256];
octet Z= {0,sizeof(z),z};
octet VZ= {0,sizeof(vz),vz};
octet K= {0,sizeof(k),k};
octet K1= {0,sizeof(k1),k1};
octet K2= {0,sizeof(k2),k2};
octet L2= {0,sizeof(l2),l2};
octet U= {0,sizeof(u),u};
if (ECP_KEY_PAIR_GENERATE(RNG,&U,V)!=0) return;
if (ECP_SVDP_DH(&U,W,&Z)!=0) return;
OCT_copy(&VZ,V);
OCT_joctet(&VZ,&Z);
KDF2(sha,&VZ,P1,2*AESKEY_NIST256,&K);
K1.len=K2.len=AESKEY_NIST256;
for (i=0; i<AESKEY_NIST256; i++)
{
K1.val[i]=K.val[i];
K2.val[i]=K.val[AESKEY_NIST256+i];
}
AES_CBC_IV0_ENCRYPT(&K1,M,C);
OCT_jint(&L2,P2->len,8);
len=C->len;
OCT_joctet(C,P2);
OCT_joctet(C,&L2);
HMAC(sha,C,&K2,tlen,T);
C->len=len;
}
/* IEEE1363 ECIES decryption. Decryption of ciphertext V,C,T using private key U outputs plaintext M */
int NIST256::ECP_ECIES_DECRYPT(int sha,octet *P1,octet *P2,octet *V,octet *C,octet *T,octet *U,octet *M)
{
int i,len;
char z[EFS_NIST256],vz[3*EFS_NIST256+1],k[2*AESKEY_NIST256],k1[AESKEY_NIST256],k2[AESKEY_NIST256],l2[8],tag[32];
octet Z= {0,sizeof(z),z};
octet VZ= {0,sizeof(vz),vz};
octet K= {0,sizeof(k),k};
octet K1= {0,sizeof(k1),k1};
octet K2= {0,sizeof(k2),k2};
octet L2= {0,sizeof(l2),l2};
octet TAG= {0,sizeof(tag),tag};
if (ECP_SVDP_DH(U,V,&Z)!=0) return 0;
OCT_copy(&VZ,V);
OCT_joctet(&VZ,&Z);
KDF2(sha,&VZ,P1,2*AESKEY_NIST256,&K);
K1.len=K2.len=AESKEY_NIST256;
for (i=0; i<AESKEY_NIST256; i++)
{
K1.val[i]=K.val[i];
K2.val[i]=K.val[AESKEY_NIST256+i];
}
if (!AES_CBC_IV0_DECRYPT(&K1,C,M)) return 0;
OCT_jint(&L2,P2->len,8);
len=C->len;
OCT_joctet(C,P2);
OCT_joctet(C,&L2);
HMAC(sha,C,&K2,T->len,&TAG);
C->len=len;
if (!OCT_ncomp(T,&TAG,T->len)) return 0;
return 1;
}
#endif
| 9,300 | 4,747 |
// Copyright (c) 2010 The Chromium Embedded Framework 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 "include/wrapper/cef_zip_archive.h"
#include <algorithm>
#include "include/base/cef_logging.h"
#include "include/base/cef_macros.h"
#include "include/base/cef_scoped_ptr.h"
#include "include/cef_stream.h"
#include "include/cef_zip_reader.h"
#include "include/wrapper/cef_byte_read_handler.h"
#if defined(OS_LINUX)
#include <wctype.h>
#endif
namespace {
// Convert |str| to lowercase in a Unicode-friendly manner.
CefString ToLower(const CefString& str) {
std::wstring wstr = str;
std::transform(wstr.begin(), wstr.end(), wstr.begin(), towlower);
return wstr;
}
class CefZipFile : public CefZipArchive::File {
public:
CefZipFile() : data_size_(0) {}
bool Initialize(size_t data_size) {
data_.reset(new unsigned char[data_size]);
if (data_) {
data_size_ = data_size;
return true;
} else {
DLOG(ERROR) << "Failed to allocate " << data_size << " bytes of memory";
data_size_ = 0;
return false;
}
}
virtual const unsigned char* GetData() const OVERRIDE { return data_.get(); }
virtual size_t GetDataSize() const OVERRIDE { return data_size_; }
virtual CefRefPtr<CefStreamReader> GetStreamReader() const OVERRIDE {
CefRefPtr<CefReadHandler> handler(
new CefByteReadHandler(data_.get(), data_size_,
const_cast<CefZipFile*>(this)));
return CefStreamReader::CreateForHandler(handler);
}
unsigned char* data() { return data_.get(); }
private:
size_t data_size_;
SCOPED_PTR(unsigned char[]) data_;
IMPLEMENT_REFCOUNTING(CefZipFile);
DISALLOW_COPY_AND_ASSIGN(CefZipFile);
};
} // namespace
// CefZipArchive implementation
CefZipArchive::CefZipArchive() {
}
CefZipArchive::~CefZipArchive() {
}
size_t CefZipArchive::Load(CefRefPtr<CefStreamReader> stream,
const CefString& password,
bool overwriteExisting) {
base::AutoLock lock_scope(lock_);
CefRefPtr<CefZipReader> reader(CefZipReader::Create(stream));
if (!reader.get())
return 0;
if (!reader->MoveToFirstFile())
return 0;
FileMap::iterator it;
size_t count = 0;
do {
const size_t size = static_cast<size_t>(reader->GetFileSize());
if (size == 0) {
// Skip directories and empty files.
continue;
}
if (!reader->OpenFile(password))
break;
const CefString& name = ToLower(reader->GetFileName());
it = contents_.find(name);
if (it != contents_.end()) {
if (overwriteExisting)
contents_.erase(it);
else // Skip files that already exist.
continue;
}
CefRefPtr<CefZipFile> contents = new CefZipFile();
if (!contents->Initialize(size))
continue;
unsigned char* data = contents->data();
size_t offset = 0;
// Read the file contents.
do {
offset += reader->ReadFile(data + offset, size - offset);
} while (offset < size && !reader->Eof());
DCHECK(offset == size);
reader->CloseFile();
count++;
// Add the file to the map.
contents_.insert(std::make_pair(name, contents.get()));
} while (reader->MoveToNextFile());
return count;
}
void CefZipArchive::Clear() {
base::AutoLock lock_scope(lock_);
contents_.clear();
}
size_t CefZipArchive::GetFileCount() const {
base::AutoLock lock_scope(lock_);
return contents_.size();
}
bool CefZipArchive::HasFile(const CefString& fileName) const {
base::AutoLock lock_scope(lock_);
FileMap::const_iterator it = contents_.find(ToLower(fileName));
return (it != contents_.end());
}
CefRefPtr<CefZipArchive::File> CefZipArchive::GetFile(
const CefString& fileName) const {
base::AutoLock lock_scope(lock_);
FileMap::const_iterator it = contents_.find(ToLower(fileName));
if (it != contents_.end())
return it->second;
return NULL;
}
bool CefZipArchive::RemoveFile(const CefString& fileName) {
base::AutoLock lock_scope(lock_);
FileMap::iterator it = contents_.find(ToLower(fileName));
if (it != contents_.end()) {
contents_.erase(it);
return true;
}
return false;
}
size_t CefZipArchive::GetFiles(FileMap& map) const {
base::AutoLock lock_scope(lock_);
map = contents_;
return contents_.size();
}
| 4,393 | 1,501 |
#pragma once
#include <QIcon>
#include <QColor>
QIcon loadSvgIconReplacingColor(const char * file, QColor newColor);
QIcon loadSvgIconReplacingColor(const char * file, const char * newColor);
| 194 | 68 |
/*
* UltrasonicFactory.cpp
*
* Created on: Feb 10, 2018
* Author: team302
*/
#include <factories/UltrasonicFactory.h>
#include <subsys/components/DragonUltrasonic.h>
UltrasonicFactory* UltrasonicFactory::m_ultrasonicFactory = nullptr;
DragonUltrasonic* UltrasonicFactory::m_ultrasonic = nullptr;
UltrasonicFactory* UltrasonicFactory::GetUltrasonicFactory()
{
if ( UltrasonicFactory::m_ultrasonicFactory == nullptr )
{
UltrasonicFactory::m_ultrasonicFactory = new UltrasonicFactory();
}
return UltrasonicFactory::m_ultrasonicFactory;
}
DragonUltrasonic* UltrasonicFactory::GetDragonUltrasonic
(
DragonUltrasonic::ULTRASONIC_USAGE usage
)
{
DragonUltrasonic* ultra = nullptr;
if ( usage == DragonUltrasonic::LEFT_SIDE_DISTANCE )
{
ultra = m_left;
}
else if ( usage == DragonUltrasonic::RIGHT_SIDE_DISTANCE )
{
ultra = m_right;
}
else
{
printf( "UltrasonicFactory::GetDragonUltrasonic invalid usage %d \n", usage );
}
return ultra;
}
//=======================================================================================
// Method: CreateUltrasonic
// Description: Create an ultrasonic from the inputs
// Returns: DragonUltrasonic*
//=======================================================================================
DragonUltrasonic* UltrasonicFactory::CreateUltrasonic
(
DragonUltrasonic::ULTRASONIC_USAGE usage,
int analogInChannel
)
{
DragonUltrasonic* ultra = nullptr;
if ( usage == DragonUltrasonic::LEFT_SIDE_DISTANCE )
{
ultra = new DragonUltrasonic( usage, analogInChannel );;
}
else if ( usage == DragonUltrasonic::RIGHT_SIDE_DISTANCE )
{
ultra = new DragonUltrasonic( usage, analogInChannel );;
}
else
{
printf( "UltrasonicFactory::GetDragonUltrasonic invalid usage %d \n", usage );
}
return ultra;
}
UltrasonicFactory::UltrasonicFactory() : m_left( nullptr ),
m_right( nullptr )
{
}
| 2,118 | 771 |
/****
*
* VertexBuffer maintains a vertex data array with locations, normals,
* colors and texcoords.
*
****/
#include "vertex_buffer.h"
#include <sstream>
#include "glm/gtc/matrix_inverse.hpp"
#define NO_LOGGING
#include "util/sxr_log.h"
namespace sxr {
VertexBuffer::VertexBuffer(const char* layout_desc, int vertexCount)
: DataDescriptor(layout_desc),
mVertexCount(0),
mVertexData(NULL)
{
mVertexData = NULL;
setVertexCount(vertexCount);
removePunctuations(layout_desc);
}
VertexBuffer::~VertexBuffer()
{
if (mVertexData != NULL)
{
free(mVertexData);
mVertexData = NULL;
}
mVertexCount = 0;
}
void VertexBuffer::getBoundingVolume(BoundingVolume& bv) const
{
const float* verts = getVertexData();
int stride = getVertexSize();
bv.reset();
for (int i = 0; i < mVertexCount; ++i)
{
glm::vec3 v;
const float* src = verts + i * stride;
v.x = *src++;
v.y = *src++;
v.z = *src;
bv.expand(v);
}
}
const void* VertexBuffer::getData(int index, int& size) const
{
if ((index < 0) || (index > mLayout.size()))
{
return NULL;
}
std::lock_guard<std::mutex> lock(mLock);
const DataEntry& e = mLayout[index];
const float* p = getVertexData();
size = e.Size;
if (p)
{
return p + (e.Offset / sizeof(float));
}
return nullptr;
}
const void* VertexBuffer::getData(const char* attributeName, int& size) const
{
std::lock_guard<std::mutex> lock(mLock);
const DataEntry* e = find(attributeName);
if ((e == NULL) || !e->IsSet)
{
return NULL;
}
const float* p = getVertexData();
size = e->Size;
if (p)
{
return p + (e->Offset / sizeof(float));
}
return nullptr;
}
/**
* Update a float vertex attribute from memory data.
* @param attributeName name of attribute to update
* @param src pointer to source array of float data
* @param srcSize total number of floats in source array
* @param srcStride number of floats in a single entry of source array.
* this is provided to allow copies from source vertex
* formats that are not closely packed.
* If it is zero, it is assumed the source array is
* closely packed and the stride is the size of the attribute.
* @return true if attribute was updated, false on error
*/
int VertexBuffer::setFloatVec(const char* attributeName, const float* src, int srcSize,
int srcStride)
{
std::lock_guard<std::mutex> lock(mLock);
DataEntry* attr = find(attributeName);
const float* srcend;
float* dest;
int dstStride;
int nverts = mVertexCount;
int attrStride;
LOGD("VertexBuffer::setFloatVec %s %d", attributeName, srcSize);
if (attr == NULL)
{
LOGE("VertexBuffer: ERROR attribute %s not found in vertex buffer", attributeName);
return 0;
}
if (src == NULL)
{
LOGE("VertexBuffer: cannot set attribute %s, source array not found", attributeName);
return 0;
}
attrStride = attr->Size / sizeof(float); // # of floats in vertex attribute
if (srcStride == 0)
{
srcStride = attrStride;
nverts = srcSize / srcStride; // # of vertices in input array
int rc = setVertexCount(nverts);
if (rc <= 0)
{
LOGE("VertexBuffer: cannot enlarge vertex array %s, vertex count mismatch", attributeName);
return rc;
}
}
else if (attrStride > srcStride) // stride too small for this attribute?
{
LOGE("VertexBuffer: cannot copy to vertex array %s, stride is %d should be >= %d", attributeName, srcStride, attrStride);
return 0;
}
nverts = srcSize / srcStride; // # of vertices in input array
if (mVertexCount > nverts)
{
LOGE("VertexBuffer: cannot copy to vertex array %s, not enough vertices in source", attributeName);
return false;
}
else if (mVertexCount == 0)
{
int rc = setVertexCount(nverts);
if (rc <= 0)
{
return rc;
}
}
dest = reinterpret_cast<float*>(mVertexData) + attr->Offset / sizeof(float);
dstStride = getTotalSize() / sizeof(float);
srcend = src + srcSize;
markDirty();
for (int i = 0; i < mVertexCount; ++i)
{
for (int j = 0; j < attrStride; ++j)
{
dest[j] = src[j];
}
dest += dstStride;
if (src >= srcend)
{
LOGE("VertexBuffer: error copying to vertex array %s, not enough vertices in source array", attributeName);
break;
}
src += srcStride;
}
markDirty();
attr->IsSet = true;
return 1;
}
bool VertexBuffer::getFloatVec(const char* attributeName, float* dest, int destSize, int destStride) const
{
std::lock_guard<std::mutex> lock(mLock);
const DataEntry* attr = find(attributeName);
const float* dstend;
const float* src = reinterpret_cast<float*>(mVertexData);
int attrSize = attr->Size / sizeof(float);
int srcStride = getVertexSize();
if ((attr == NULL) || !attr->IsSet)
{
LOGE("VertexBuffer: ERROR attribute %s not found in vertex buffer", attributeName);
return false;
}
if (src == NULL)
{
LOGD("VertexBuffer: cannot set attribute %s", attributeName);
return false;
}
src += attr->Offset / sizeof(float);
dstend = dest + destSize;
if (destStride == 0)
{
destStride = attrSize;
}
for (int i = 0; i < mVertexCount; ++i)
{
for (int j = 0; j < attrSize; ++j)
{
dest[j] = src[j];
}
src += srcStride;
dest += destStride;
if (dest > dstend)
{
LOGE("VertexBuffer: error reading from vertex array %s, not enough room in destination array", attributeName);
return false;
}
}
return true;
}
/**
* Update an integer vertex attribute from memory data.
* @param attributeName name of attribute to update
* @param src pointer to source array of int data
* @param srcSize total number of ints in source array
* @param srcStride number of ints in a single entry of source array.
* this is provided to allow copies from source vertex
* formats that are not closely packed.
* If it is zero, it is assumed the source array is
* closely packed and the stride is the size of the attribute.
* @return true if attribute was updated, false on error
*/
int VertexBuffer::setIntVec(const char* attributeName, const int* src, int srcSize,
int srcStride)
{
std::lock_guard<std::mutex> lock(mLock);
DataEntry* attr = find(attributeName);
const int* srcend;
int* dest;
int dstStride;
int nverts = mVertexCount;
int attrStride;
LOGV("VertexBuffer::setIntVec %s %d", attributeName, srcSize);
if (attr == NULL)
{
LOGE("VertexBuffer: ERROR attribute %s not found in vertex buffer", attributeName);
return 0;
}
if (src == NULL)
{
LOGE("VertexBuffer: cannot set attribute %s, source array not found", attributeName);
return 0;
}
attrStride = attr->Size / sizeof(int);
if (srcStride == 0)
{
srcStride = attrStride;
nverts = srcSize / srcStride; // # of vertices in input array
int rc = setVertexCount(nverts);
if (rc <= 0)
{
LOGE("VertexBuffer: cannot enlarge vertex array %s, vertex count mismatch", attributeName);
return rc;
}
}
else if (attrStride > srcStride) // stride too small for this attribute?
{
LOGE("VertexBuffer: cannot copy to vertex array %s, stride is %d should be >= %d", attributeName, srcStride, attrStride);
return 0;
}
nverts = srcSize / srcStride; // # of vertices in input array
if (mVertexCount > nverts)
{
LOGE("VertexBuffer: cannot copy to vertex array %s, not enough vertices in source", attributeName);
return false;
}
else if (mVertexCount == 0)
{
int rc = setVertexCount(nverts);
if (rc <= 0)
{
LOGE("VertexBuffer: cannot enlarge vertex array %s, vertex count mismatch", attributeName);
return rc;
}
}
markDirty();
dest = reinterpret_cast<int*>(mVertexData) + attr->Offset / sizeof(int);
dstStride = getTotalSize() / sizeof(int);
srcend = src + srcSize;
for (int i = 0; i < mVertexCount; ++i)
{
for (int j = 0; j < attrStride; ++j)
{
dest[j] = src[j];
}
dest += dstStride;
if (src >= srcend)
{
LOGE("VertexBuffer: error copying to vertex array %s, not enough vertices in source array", attributeName);
break;
}
src += srcStride;
}
markDirty();
attr->IsSet = true;
return 1;
}
bool VertexBuffer::getIntVec(const char* attributeName, int* dest, int destSize, int destStride) const
{
std::lock_guard<std::mutex> lock(mLock);
const DataEntry* attr = find(attributeName);
const int* dstend;
const int* src = reinterpret_cast<int*>(mVertexData);
int attrSize = attr->Size / sizeof(int);
int srcStride = getTotalSize() / sizeof(int);
if ((attr == NULL) || !attr->IsSet)
{
LOGE("VertexBuffer: ERROR attribute %s not found in vertex buffer", attributeName);
return false;
}
if (src == NULL)
{
LOGE("VertexBuffer: cannot set attribute %s", attributeName);
return false;
}
src += attr->Offset / sizeof(int);
dstend = dest + destSize;
if (destStride == 0)
{
destStride = attrSize;
}
for (int i = 0; i < mVertexCount; ++i)
{
for (int j = 0; j < attrSize; ++j)
{
dest[j] = src[j];
}
src += srcStride;
if (dest > dstend)
{
LOGE("VertexBuffer: error reading from vertex array %s, not enough room in destination array", attributeName);
return false;
}
dest += destStride;
}
return true;
}
bool VertexBuffer::getInfo(const char* attributeName, int& index, int& offset, int& size) const
{
std::lock_guard<std::mutex> lock(mLock);
const DataEntry* attr = find(attributeName);
if ((attr == NULL) || !attr->IsSet)
return false;
offset = attr->Offset;
index = attr->Index;
size = attr->Size;
return true;
}
int VertexBuffer::setVertexCount(int count)
{
if ((mVertexCount != 0) && (mVertexCount != count))
{
LOGE("VertexBuffer: cannot change size of vertex buffer from %d vertices to %d", mVertexCount, count);
return 0;
}
if (mVertexCount == count)
{
return true;
}
if (count > 0)
{
int vsize = getTotalSize();
int datasize = vsize * count;
LOGV("VertexBuffer: allocating vertex buffer of %d bytes with %d vertices\n", datasize, count);
mVertexData = (char*) malloc(datasize);
if (mVertexData)
{
mVertexCount = count;
return 1;
}
LOGE("VertexBuffer: out of memory cannot allocate room for %d vertices\n", count);
return -1;
}
LOGE("VertexBuffer: ERROR: no vertex buffer allocated\n");
return 0;
}
void VertexBuffer::transform(glm::mat4& mtx, bool doNormals)
{
const DataEntry* normEntry = find("a_normal");
float* data = reinterpret_cast<float*>(mVertexData);
int stride = getVertexSize();
if (data == NULL)
{
return;
}
markDirty();
if (doNormals && normEntry)
{
std::lock_guard<std::mutex> lock(mLock);
glm::mat4 invTranspose = glm::transpose(glm::inverse(mtx));
int normOfs = normEntry->Offset / sizeof(float);
for (int i = 0; i < mVertexCount; ++i)
{
glm::vec4 p(data[0], data[1], data[2], 1);
glm::vec4 n(data[normOfs], data[normOfs + 1], data[normOfs + 2], 1);
p = p * mtx;
data[0] = p.x;
data[1] = p.y;
data[2] = p.z;
n = n * invTranspose;
data[normOfs] = n.x;
data[normOfs + 1] = n.y;
data[normOfs + 2] = n.z;
data += stride;
}
}
else
{
for (int i = 0; i < mVertexCount; ++i)
{
std::lock_guard<std::mutex> lock(mLock);
glm::vec4 p(data[0], data[1], data[2], 1);
p = p * mtx;
data[0] = p.x;
data[1] = p.y;
data[2] = p.z;
data += stride;
}
}
}
bool VertexBuffer::forAllVertices(std::function<void(int iter, const float* vertex)> func) const
{
std::lock_guard<std::mutex> lock(mLock);
const float* data = reinterpret_cast<const float*>(mVertexData);
int stride = getVertexSize();
if (data == NULL)
{
return false;
}
for (int i = 0; i < mVertexCount; ++i)
{
func(i, data);
data += stride;
}
return true;
}
bool VertexBuffer::forAllVertices(const char* attrName, std::function<void (int iter, const float* vertex)> func) const
{
std::lock_guard<std::mutex> lock(mLock);
const DataEntry* attr = find(attrName);
const float* data = reinterpret_cast<float*>(mVertexData);
int stride = getVertexSize();
int ofs;
if ((attr == NULL) || !attr->IsSet)
{
LOGE("VertexBuffer: ERROR attribute %s not found in vertex buffer", attrName);
return false;
}
if (data == NULL)
{
LOGD("VertexBuffer: cannot find attribute %s", attrName);
return false;
}
ofs = attr->Offset / sizeof(float);
for (int i = 0; i < mVertexCount; ++i)
{
func(i, data + ofs);
data += stride;
}
return true;
}
void VertexBuffer::dump() const
{
int vsize = getVertexSize();
forAllVertices([vsize](int iter, const float* vertex)
{
const float* v = vertex;
std::ostringstream os;
os.precision(3);
for (int i = 0; i < vsize; ++i)
{
float f = *v++;
os << std::fixed << f << " ";
}
LOGV("%s", os.str().c_str());
});
}
void VertexBuffer::dump(const char* attrName) const
{
int vsize = getVertexSize();
const DataEntry* attr = find(attrName);
if (attr == NULL)
{
LOGE("Attribute %s not found", attrName);
return;
}
forAllVertices(attrName, [attr](int iter, const float* vertex)
{
std::ostringstream os;
os.precision(3);
int asize = attr->Size / sizeof(float);
if (attr->IsInt)
{
const int* iv = (const int*) vertex;
for (int i = 0; i < asize; ++i)
{
os << *iv++ << " ";
}
}
else
{
const float* v = vertex;
for (int i = 0; i < asize; ++i)
{
float f = *v++;
os << std::fixed << f << " ";
}
}
LOGV("%s", os.str().c_str());
});
}
} // end sxrsdk
| 17,578 | 4,963 |
#include <fstream>
#include <stack>
#include <vector>
int main() {
std::ifstream in_file("input.txt");
int N;
in_file >> N;
std::vector<int> a(N);
for(int i = 0; i < N; ++i) {
in_file >> a[i];
}
in_file.close();
std::stack<int> stack;
std::vector<int> nums_global_end(N);
std::vector<int> radii(N);
for(int i = 0; i < N; ++i) {
nums_global_end[i] = -1;
radii[i] = 0;
}
for(int i = 0; i < N; ++i) {
while (!stack.empty() && a[stack.top()] < a[i]) {
int j = stack.top();
stack.pop();
if (nums_global_end[j] == -1 || i - j < j - nums_global_end[j]) {
nums_global_end[j] = i;
radii[j] = i - j;
}
}
if (stack.empty()) {
nums_global_end[i] = -1;
radii[i] = 0;
} else {
if (a[i] != a[stack.top()]) {
nums_global_end[i] = stack.top();
radii[i] = i - stack.top();
} else {
nums_global_end[i] = nums_global_end[stack.top()];
if (nums_global_end[i] != -1) {
radii[i] = i - nums_global_end[stack.top()];
} else {
radii[i] = 0;
}
}
}
stack.push(i);
}
std::ofstream out_file("output.txt");
for(int i = 0; i < N; ++i) {
out_file << radii[i] << ' ';
}
out_file.close();
}
| 1,486 | 565 |
/*
* Copyright (C) 2018
* Course: CO2003
* Author: Rang Nguyen
* Ho Chi Minh City University of Technology
*/
#include"Node.h"
#include <cstring> // ! Fix memmove()
#include <cmath> // ! Fix ceil()
Node::Node(int capacity) {
maxElements = capacity;
elements = new int[capacity]; // ! Allocated dynamic
numElements = 0;
prev = next = NULL;
}
Node::~Node() {
if (elements != NULL)
delete[] elements;
}
int Node::getHalfNodeSize() {
return (int)ceil(maxElements/2.0);
}
bool Node::isUnderHalfFull() {
return numElements < getHalfNodeSize();
}
bool Node::isFull() {
return numElements >= maxElements;
}
bool Node::isOverflow() {
return numElements > maxElements;
}
bool Node::isEmpty() {
return numElements == 0;
}
void Node::add(int val) {
if (isFull())
throw "NodeOverflowExeception";
else
{
elements[numElements] = val;
numElements++;
}
}
void Node::insertAt(int pos, int val) {
if (isFull()) throw "NodeOverflowExeception";
else if (pos < 0 || pos > numElements) throw "IndexOutOfBoundsException";
else {
memmove(elements + pos + 1, elements + pos, (numElements - pos)*sizeof(int));
elements[pos] = val;
numElements++;
}
}
void Node::removeAt(int pos) {
if (pos < 0 || pos >= numElements) throw "IndexOutOfBoundsException";
else {
memmove(elements + pos, elements + pos + 1, (numElements - pos - 1)*sizeof(int));
numElements--;
}
}
void Node::reverse() {
for(int i = 0; i<numElements/2;i++)
std::swap(elements[i], elements[numElements - 1 - i]);
}
void Node::print() {
for (int i = 0; i < numElements; i++)
printf("%d ", elements[i]);
}
void Node::printDetail() {
printf("| prev(%p) |", prev); // ! %d -> %p
for (int i = 0; i < numElements; i++)
printf(" %d |", elements[i]);
for (int i = numElements; i < maxElements; i++)
printf(" X |");
printf(" next(%p) |\n", next);// ! $d -> %p
} | 1,943 | 744 |
// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/extensions/api/atom_extensions_api_client.h"
#include <memory>
#include <string>
#include "atom/browser/extensions/atom_extension_web_contents_observer.h"
#include "atom/browser/extensions/tab_helper.h"
#include "base/memory/ptr_util.h"
#include "brave/browser/guest_view/brave_guest_view_manager_delegate.h"
#include "chrome/browser/extensions/api/messaging/chrome_messaging_delegate.h"
#include "content/public/browser/resource_request_info.h"
#include "extensions/browser/api/management/management_api_delegate.h"
#include "extensions/browser/api/storage/local_value_store_cache.h"
#include "extensions/browser/api/storage/settings_observer.h"
#include "extensions/browser/api/web_request/web_request_event_details.h"
#include "extensions/browser/api/web_request/web_request_event_router_delegate.h"
#include "extensions/browser/disable_reason.h"
#include "extensions/browser/requirements_checker.h"
#include "extensions/browser/value_store/value_store_factory.h"
#include "extensions/common/manifest_handlers/icons_handler.h"
namespace extensions {
class AtomExtensionWebRequestEventRouterDelegate :
public WebRequestEventRouterDelegate {
public:
AtomExtensionWebRequestEventRouterDelegate() {}
~AtomExtensionWebRequestEventRouterDelegate() override {}
void NotifyWebRequestWithheld(int render_process_id,
int render_frame_id,
const std::string& extension_id) override {
// TODO(bridiver) - will this ever be called?
}
private:
DISALLOW_COPY_AND_ASSIGN(AtomExtensionWebRequestEventRouterDelegate);
};
class AtomManagementAPIDelegate : public ManagementAPIDelegate {
public:
AtomManagementAPIDelegate() {}
~AtomManagementAPIDelegate() override {}
void LaunchAppFunctionDelegate(
const Extension* extension,
content::BrowserContext* context) const override { }
bool IsNewBookmarkAppsEnabled() const override { return false; }
bool CanHostedAppsOpenInWindows() const override { return false; }
GURL GetFullLaunchURL(const Extension* extension) const override {
NOTIMPLEMENTED();
return GURL();
}
LaunchType GetLaunchType(const ExtensionPrefs* prefs,
const Extension* extension) const override {
NOTIMPLEMENTED();
return LaunchType::LAUNCH_TYPE_INVALID;
}
void GetPermissionWarningsByManifestFunctionDelegate(
ManagementGetPermissionWarningsByManifestFunction* function,
const std::string& manifest_str) const override {
NOTIMPLEMENTED();
}
std::unique_ptr<InstallPromptDelegate> SetEnabledFunctionDelegate(
content::WebContents* web_contents,
content::BrowserContext* browser_context,
const Extension* extension,
const base::Callback<void(bool)>& callback) const override {
NOTIMPLEMENTED();
return base::WrapUnique(install_prompt_delegate_);
}
// Enables the extension identified by |extension_id|.
void EnableExtension(content::BrowserContext* context,
const std::string& extension_id) const override {
NOTIMPLEMENTED();
}
// Disables the extension identified by |extension_id|.
void DisableExtension(
content::BrowserContext* context,
const Extension* source_extension,
const std::string& extension_id,
disable_reason::DisableReason disable_reason) const override {
NOTIMPLEMENTED();
}
// Used to show a confirmation dialog when uninstalling |target_extension|.
std::unique_ptr<UninstallDialogDelegate> UninstallFunctionDelegate(
ManagementUninstallFunctionBase* function,
const Extension* target_extension,
bool show_programmatic_uninstall_ui) const override {
NOTIMPLEMENTED();
return base::WrapUnique(uninstall_dialog_delegate_);
}
// Uninstalls the extension.
bool UninstallExtension(content::BrowserContext* context,
const std::string& transient_extension_id,
UninstallReason reason,
base::string16* error) const override {
NOTIMPLEMENTED();
return false;
}
// Creates an app shortcut.
bool CreateAppShortcutFunctionDelegate(
ManagementCreateAppShortcutFunction* function,
const Extension* extension,
std::string* error) const override {
NOTIMPLEMENTED();
return false;
}
// Forwards the call to launch_util::SetLaunchType in chrome.
void SetLaunchType(content::BrowserContext* context,
const std::string& extension_id,
LaunchType launch_type) const override {
NOTIMPLEMENTED();
}
// Creates a bookmark app for |launch_url|.
std::unique_ptr<AppForLinkDelegate> GenerateAppForLinkFunctionDelegate(
ManagementGenerateAppForLinkFunction* function,
content::BrowserContext* context,
const std::string& title,
const GURL& launch_url) const override {
NOTIMPLEMENTED();
return base::WrapUnique(app_for_link_delegate_);
}
GURL GetIconURL(
const extensions::Extension* extension,
int icon_size,
ExtensionIconSet::MatchType match,
bool grayscale) const override {
GURL icon_url(base::StringPrintf("%s%s/%d/%d%s",
"chrome://extension-icon/",
extension->id().c_str(),
icon_size,
match,
grayscale ? "?grayscale=true" : ""));
CHECK(icon_url.is_valid());
return icon_url;
}
private:
InstallPromptDelegate* install_prompt_delegate_;
UninstallDialogDelegate* uninstall_dialog_delegate_;
AppForLinkDelegate* app_for_link_delegate_;
DISALLOW_COPY_AND_ASSIGN(AtomManagementAPIDelegate);
};
AtomExtensionsAPIClient::AtomExtensionsAPIClient() {
}
void AtomExtensionsAPIClient::AddAdditionalValueStoreCaches(
content::BrowserContext* context,
const scoped_refptr<ValueStoreFactory>& factory,
const scoped_refptr<base::ObserverListThreadSafe<SettingsObserver>>&
observers,
std::map<settings_namespace::Namespace, ValueStoreCache*>* caches) {
// Add temporary (fake) support for chrome.storage.sync.
(*caches)[settings_namespace::SYNC] =
new LocalValueStoreCache(factory);
}
std::unique_ptr<guest_view::GuestViewManagerDelegate>
AtomExtensionsAPIClient::CreateGuestViewManagerDelegate(
content::BrowserContext* context) const {
return std::make_unique<brave::BraveGuestViewManagerDelegate>(context);
}
void AtomExtensionsAPIClient::AttachWebContentsHelpers(
content::WebContents* web_contents) const {
AtomExtensionWebContentsObserver::CreateForWebContents(web_contents);
}
MessagingDelegate* AtomExtensionsAPIClient::GetMessagingDelegate() {
if (!messaging_delegate_)
messaging_delegate_ = std::make_unique<ChromeMessagingDelegate>();
return messaging_delegate_.get();
}
std::unique_ptr<WebRequestEventRouterDelegate>
AtomExtensionsAPIClient::CreateWebRequestEventRouterDelegate() const {
return base::WrapUnique(
new extensions::AtomExtensionWebRequestEventRouterDelegate());
}
ManagementAPIDelegate* AtomExtensionsAPIClient::CreateManagementAPIDelegate()
const {
return new AtomManagementAPIDelegate();
}
} // namespace extensions
| 7,466 | 2,106 |
// 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 "arrow/util/base64.h"
#include "parquet/encryption/encryption_internal.h"
#include "parquet/encryption/key_toolkit_internal.h"
namespace parquet {
namespace encryption {
namespace internal {
// Acceptable key lengths in number of bits, used to validate the data key lengths
// configured by users and the master key lengths fetched from KMS server.
static constexpr const int32_t kAcceptableDataKeyLengths[] = {128, 192, 256};
std::string EncryptKeyLocally(const std::string& key_bytes, const std::string& master_key,
const std::string& aad) {
AesEncryptor key_encryptor(ParquetCipher::AES_GCM_V1,
static_cast<int>(master_key.size()), false,
false /*write_length*/);
int encrypted_key_len =
static_cast<int>(key_bytes.size()) + key_encryptor.CiphertextSizeDelta();
std::string encrypted_key(encrypted_key_len, '\0');
encrypted_key_len = key_encryptor.Encrypt(
reinterpret_cast<const uint8_t*>(key_bytes.data()),
static_cast<int>(key_bytes.size()),
reinterpret_cast<const uint8_t*>(master_key.data()),
static_cast<int>(master_key.size()), reinterpret_cast<const uint8_t*>(aad.data()),
static_cast<int>(aad.size()), reinterpret_cast<uint8_t*>(&encrypted_key[0]));
return ::arrow::util::base64_encode(
::arrow::util::string_view(encrypted_key.data(), encrypted_key_len));
}
std::string DecryptKeyLocally(const std::string& encoded_encrypted_key,
const std::string& master_key, const std::string& aad) {
std::string encrypted_key = ::arrow::util::base64_decode(encoded_encrypted_key);
AesDecryptor key_decryptor(ParquetCipher::AES_GCM_V1,
static_cast<int>(master_key.size()), false,
false /*contains_length*/);
int decrypted_key_len =
static_cast<int>(encrypted_key.size()) - key_decryptor.CiphertextSizeDelta();
std::string decrypted_key(decrypted_key_len, '\0');
decrypted_key_len = key_decryptor.Decrypt(
reinterpret_cast<const uint8_t*>(encrypted_key.data()),
static_cast<int>(encrypted_key.size()),
reinterpret_cast<const uint8_t*>(master_key.data()),
static_cast<int>(master_key.size()), reinterpret_cast<const uint8_t*>(aad.data()),
static_cast<int>(aad.size()), reinterpret_cast<uint8_t*>(&decrypted_key[0]));
return decrypted_key;
}
bool ValidateKeyLength(int32_t key_length_bits) {
int32_t* found_key_length = std::find(
const_cast<int32_t*>(kAcceptableDataKeyLengths),
const_cast<int32_t*>(std::end(kAcceptableDataKeyLengths)), key_length_bits);
return found_key_length != std::end(kAcceptableDataKeyLengths);
}
} // namespace internal
} // namespace encryption
} // namespace parquet
| 3,611 | 1,156 |
// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
#include "perf_precomp.hpp"
namespace opencv_test {
#define TYPICAL_MAT_TYPES_MORPH CV_8UC1, CV_8UC4
#define TYPICAL_MATS_MORPH testing::Combine(SZ_ALL_GA, testing::Values(TYPICAL_MAT_TYPES_MORPH))
PERF_TEST_P(Size_MatType, erode, TYPICAL_MATS_MORPH)
{
Size sz = get<0>(GetParam());
int type = get<1>(GetParam());
Mat src(sz, type);
Mat dst(sz, type);
declare.in(src, WARMUP_RNG).out(dst);
int runs = (sz.width <= 320) ? 15 : 1;
TEST_CYCLE_MULTIRUN(runs) erode(src, dst, noArray());
SANITY_CHECK(dst);
}
PERF_TEST_P(Size_MatType, dilate, TYPICAL_MATS_MORPH)
{
Size sz = get<0>(GetParam());
int type = get<1>(GetParam());
Mat src(sz, type);
Mat dst(sz, type);
declare.in(src, WARMUP_RNG).out(dst);
TEST_CYCLE() dilate(src, dst, noArray());
SANITY_CHECK(dst);
}
} // namespace
| 1,049 | 455 |
--- src/net.cpp.orig 2015-11-30 23:06:15 UTC
+++ src/net.cpp
@@ -58,7 +58,7 @@ static bool vfLimited[NET_MAX] = {};
static CNode* pnodeLocalHost = NULL;
CAddress addrSeenByPeer(CService("0.0.0.0", 0), nLocalServices);
uint64 nLocalHostNonce = 0;
-array<int, THREAD_MAX> vnThreadsRunning;
+boost::array<int, THREAD_MAX> vnThreadsRunning;
static std::vector<SOCKET> vhListenSocket;
CAddrMan addrman;
@@ -1124,10 +1124,14 @@ void ThreadMapPort2(void* parg)
#ifndef UPNPDISCOVER_SUCCESS
/* miniupnpc 1.5 */
devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0);
-#else
+#elif MINIUPNPC_API_VERSION < 14
/* miniupnpc 1.6 */
int error = 0;
devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &error);
+#else
+ /* miniupnpc 1.9.20150730 */
+ int error = 0;
+ devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, 2, &error);
#endif
struct UPNPUrls urls;
| 952 | 440 |
#include <iostream>
struct str{
int a[2];
double d;
};
double fun(int i) {
str s;
s.a[i] = 1073741824;
s.d = 3.14;
return s.d;
}
int main() {
std::cout << fun(0) << '\n';
std::cout << fun(1) << '\n';
std::cout << fun(2) << '\n';
std::cout << fun(3) << '\n';
std::cout << fun(4) << '\n';
std::cout << fun(6) << '\n';
return 0;
} | 404 | 190 |
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr);
int n;cin>>n;
int before;
long long sum = 0;
for (int i = 0; i < n; i++) {
int a;
cin >> a;
if(i==0) {
before = a;
} else {
if(before > a) sum += (before - a);
else before = a;
}
}
cout << sum;
} | 427 | 159 |
// Copyright (c) 2013-2015 mogemimi.
// Distributed under the MIT license. See LICENSE.md file for details.
#ifndef POMDOG_PREREQUISITESDIRECT3D_373FDC61_HPP
#define POMDOG_PREREQUISITESDIRECT3D_373FDC61_HPP
#if defined(_XBOX_ONE) && defined(_TITLE)
#include <d3dcompiler_x.h>
#else
#include <d3dcompiler.h>
#include <d3dcommon.h>
#endif
#endif // POMDOG_PREREQUISITESDIRECT3D_373FDC61_HPP
| 393 | 198 |
/*
* MIT License
*
* Copyright (c) 2017 Twitter
*
* 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 "vireo/base_cpp.h"
#include "vireo/common/security.h"
#include "vireo/encode/h264.h"
#include "vireo/error/error.h"
extern "C" {
#include "x264.h"
}
#define X264_CSP X264_CSP_I420
#define X264_LOG_LEVEL X264_LOG_WARNING
#define X264_NALU_LENGTH_SIZE 4
#define X264_PROFILE "main"
#define X264_TUNE "ssim"
static vireo::encode::VideoProfileType GetDefaultProfile(const int width, const int height) {
auto min_dimension = min(width, height);
if (min_dimension <= 480) {
return vireo::encode::VideoProfileType::Baseline;
} else if (min_dimension <= 720) {
return vireo::encode::VideoProfileType::Main;
} else {
return vireo::encode::VideoProfileType::High;
}
}
namespace vireo {
using common::Data16;
namespace encode {
struct _H264 {
unique_ptr<x264_t, decltype(&x264_encoder_close)> encoder = { NULL, [](x264_t* encoder) { if (encoder) x264_encoder_close(encoder); } };
functional::Video<frame::Frame> frames;
uint32_t num_cached_frames = 0;
uint32_t num_threads = 0;
uint32_t max_delay = 0;
static inline const char* const GetProfile(VideoProfileType profile) {
THROW_IF(profile != VideoProfileType::Baseline && profile != VideoProfileType::Main && profile != VideoProfileType::High, Unsupported, "unsupported profile type");
switch (profile) {
case VideoProfileType::Baseline:
return "baseline";
case VideoProfileType::Main:
return "main";
case VideoProfileType::High:
return "high";
default:
return "baseline";
}
}
};
H264::H264(const functional::Video<frame::Frame>& frames, float crf, uint32_t optimization, float fps, uint32_t max_bitrate, uint32_t thread_count)
: H264(frames, H264Params(H264Params::ComputationalParams(optimization, thread_count), H264Params::RateControlParams(RCMethod::CRF, crf, max_bitrate), H264Params::GopParams(0), GetDefaultProfile(frames.settings().width, frames.settings().height), fps)) {};
H264::H264(const functional::Video<frame::Frame>& frames, const H264Params& params)
: functional::DirectVideo<H264, Sample>(frames.a(), frames.b()), _this(new _H264()) {
THROW_IF(frames.count() >= security::kMaxSampleCount, Unsafe);
THROW_IF(params.computation.optimization < kH264MinOptimization || params.computation.optimization > kH264MaxOptimization, InvalidArguments);
THROW_IF(params.fps < 0.0f, InvalidArguments);
THROW_IF(params.rc.max_bitrate < 0.0f, InvalidArguments);
THROW_IF(params.computation.thread_count < kH264MinThreadCount || params.computation.thread_count > kH264MaxThreadCount, InvalidArguments);
THROW_IF(!security::valid_dimensions(frames.settings().width, frames.settings().height), Unsafe);
THROW_IF(frames.settings().par_width != frames.settings().par_height, InvalidArguments);
x264_param_t param;
{ // Params
x264_param_default_preset(¶m, x264_preset_names[params.computation.optimization], X264_TUNE);
param.i_threads = params.computation.thread_count ? params.computation.thread_count : 1;
param.i_log_level = X264_LOG_LEVEL;
param.i_width = (int)((frames.settings().width + 1) / 2) * 2;
param.i_height = (int)((frames.settings().height + 1) / 2) * 2;
param.i_fps_num = (int)(params.fps * 1000.0f + 0.5f);
param.i_fps_den = params.fps > 0.0f ? 1000 : 0.0;
param.i_csp = X264_CSP;
param.b_annexb = 0;
param.b_repeat_headers = 0;
param.b_vfr_input = 0;
if (params.gop.num_bframes >= 0) { // if num_bframes < 0, use default settings
param.i_bframe = params.gop.num_bframes;
param.i_bframe_pyramid = params.gop.pyramid_mode;
}
if (param.i_bframe == 0) { // set these zerolatency settings in case number of b frames is 0, otherwise use default settings
param.rc.i_lookahead = 0;
param.i_sync_lookahead = 0;
param.rc.b_mb_tree = 0;
param.b_sliced_threads = 1;
}
if (!params.rc.stats_log_path.empty()) {
if (!params.rc.is_second_pass) {
param.rc.b_stat_write = true;
param.rc.psz_stat_out = (char*)params.rc.stats_log_path.c_str();
} else {
param.rc.b_stat_read = true;
param.rc.psz_stat_in = (char*)params.rc.stats_log_path.c_str();
}
param.rc.b_mb_tree = params.rc.enable_mb_tree;
param.rc.i_lookahead = params.rc.look_ahead;
param.rc.i_aq_mode = params.rc.aq_mode;
param.rc.i_qp_min = params.rc.qp_min;
param.i_frame_reference = params.gop.frame_references;
param.analyse.b_mixed_references = params.rc.mixed_refs;
param.analyse.i_trellis = params.rc.trellis;
param.analyse.i_me_method = params.rc.me_method;
param.analyse.i_me_range = 16;
param.analyse.i_subpel_refine = params.rc.subpel_refine;
param.i_keyint_max = params.gop.keyint_max;
param.i_keyint_min = params.gop.keyint_min;
param.b_sliced_threads = 0;
param.i_lookahead_threads = 1;
}
switch (params.rc.rc_method) {
case RCMethod::CRF:
param.rc.i_rc_method = X264_RC_CRF;
THROW_IF(params.rc.crf < kH264MinCRF || params.rc.crf > kH264MaxCRF, InvalidArguments);
param.rc.f_rf_constant = params.rc.crf;
if (params.rc.max_bitrate != 0.0) {
param.rc.i_vbv_max_bitrate = params.rc.max_bitrate;
param.rc.i_vbv_buffer_size = params.rc.max_bitrate;
}
break;
case RCMethod::CBR:
CHECK(params.rc.bitrate == params.rc.max_bitrate);
param.rc.i_rc_method = X264_RC_ABR;
param.rc.i_bitrate = params.rc.bitrate;
param.rc.i_vbv_max_bitrate = params.rc.bitrate;
param.rc.i_vbv_buffer_size = params.rc.buffer_size;
param.rc.f_vbv_buffer_init = params.rc.buffer_init;
break;
case RCMethod::ABR:
param.rc.i_rc_method = X264_RC_ABR;
param.rc.i_bitrate = params.rc.bitrate;
break;
default: // USE CRF as default mode
param.rc.i_rc_method = X264_RC_CRF;
param.rc.f_rf_constant = 28.0f;
break;
}
THROW_IF(x264_param_apply_profile(¶m, _H264::GetProfile(params.profile)) < 0, InvalidArguments);
}
_this->frames = frames;
_this->num_threads = params.computation.thread_count;
_this->max_delay = params.computation.thread_count + params.rc.look_ahead + params.gop.num_bframes;
{ // Encoder
_this->encoder.reset(x264_encoder_open(¶m));
CHECK(_this->encoder);
}
_settings = frames.settings();
_settings.codec = settings::Video::Codec::H264;
{
x264_nal_t* nals;
int count;
THROW_IF(x264_encoder_headers(_this->encoder.get(), &nals, &count) < 0, InvalidArguments);
CHECK(count >= 3);
_settings.sps_pps = (header::SPS_PPS){
Data16(nals[0].p_payload + X264_NALU_LENGTH_SIZE, nals[0].i_payload - X264_NALU_LENGTH_SIZE, NULL),
Data16(nals[1].p_payload + X264_NALU_LENGTH_SIZE, nals[1].i_payload - X264_NALU_LENGTH_SIZE, NULL),
X264_NALU_LENGTH_SIZE
};
}
}
H264::H264(const H264& h264)
: functional::DirectVideo<H264, Sample>(h264.a(), h264.b(), h264.settings()), _this(h264._this) {
}
auto H264::operator()(uint32_t index) const -> Sample {
THROW_IF(index >= count(), OutOfRange);
THROW_IF(index >= _this->frames.count(), OutOfRange);
x264_nal_t* nals = nullptr;
int i_nals;
x264_picture_t out_picture;
int video_size = 0;
auto has_more_frames_to_encode = [_this = _this, &index]() -> bool {
return index + _this->num_cached_frames < _this->frames.count();
};
if (has_more_frames_to_encode()) {
while (video_size == 0 && has_more_frames_to_encode()) {
const frame::Frame frame = _this->frames(index + _this->num_cached_frames);
const uint64_t pts = frame.pts;
const frame::YUV yuv = frame.yuv();
x264_picture_t in_picture;
x264_picture_init(&in_picture);
in_picture.i_pts = pts;
in_picture.img.i_csp = X264_CSP;
in_picture.img.i_plane = 3;
in_picture.img.plane[0] = (uint8_t*)yuv.plane(frame::Y).bytes().data();
in_picture.img.plane[1] = (uint8_t*)yuv.plane(frame::U).bytes().data();
in_picture.img.plane[2] = (uint8_t*)yuv.plane(frame::V).bytes().data();
in_picture.img.i_stride[0] = (int)yuv.plane(frame::Y).row();
in_picture.img.i_stride[1] = (int)yuv.plane(frame::U).row();
in_picture.img.i_stride[2] = (int)yuv.plane(frame::V).row();
video_size = x264_encoder_encode(_this->encoder.get(), &nals, &i_nals, &in_picture, &out_picture);
_this->num_cached_frames += (video_size == 0);
THROW_IF(_this->num_cached_frames > _this->max_delay, Unsupported);
}
}
if (!has_more_frames_to_encode()) {
CHECK(_this->num_cached_frames > 0);
uint32_t thread = 0;
while (video_size == 0 && (_this->num_threads == 0 || thread < _this->num_threads)) {
CHECK(thread < kH264MaxThreadCount);
video_size = x264_encoder_encode(_this->encoder.get(), &nals, &i_nals, nullptr, &out_picture); // flush out cached frames
thread++;
}
_this->num_cached_frames--;
}
CHECK(video_size > 0);
CHECK(nals);
CHECK(i_nals != 0);
CHECK(out_picture.i_pts >= 0);
const auto video_nal = common::Data32(nals[0].p_payload, video_size, NULL);
if (out_picture.b_keyframe) {
common::Data16 sps_pps_data = _settings.sps_pps.as_extradata(header::SPS_PPS::ExtraDataType::avcc);
uint32_t sps_pps_size = sps_pps_data.count();
uint32_t video_sample_data_size = sps_pps_size + video_size;
common::Data32 video_sample_data = common::Data32(new uint8_t[video_sample_data_size], video_sample_data_size, [](uint8_t* p) { delete[] p; });
video_sample_data.copy(common::Data32(sps_pps_data.data(), sps_pps_size, nullptr));
video_sample_data.set_bounds(video_sample_data.a() + sps_pps_size, video_sample_data_size);
video_sample_data.copy(video_nal);
video_sample_data.set_bounds(0, video_sample_data_size);
return Sample(out_picture.i_pts, out_picture.i_dts, (bool)out_picture.b_keyframe, SampleType::Video, video_sample_data);
} else {
return Sample(out_picture.i_pts, out_picture.i_dts, (bool)out_picture.b_keyframe, SampleType::Video, video_nal);
}
}
}} | 11,227 | 4,389 |
#include "Graphics\Include\Render2D.h"
#include "Graphics\Include\DrawBsp.h"
#include "stdhdr.h"
#include "entity.h"
#include "PilotInputs.h"
#include "simveh.h"
#include "sms.h"
#include "airframe.h"
#include "object.h"
#include "fsound.h"
#include "soundfx.h"
#include "simdrive.h"
#include "mfd.h"
#include "radar.h"
#include "classtbl.h"
#include "playerop.h"
#include "navsystem.h"
#include "commands.h"
#include "hud.h"
#include "fcc.h"
#include "fault.h"
#include "fack.h"
#include "aircrft.h"
#include "smsdraw.h"
#include "airunit.h"
#include "handoff.h"
#include "otwdrive.h" //MI
#include "radardoppler.h" //MI
#include "missile.h" //MI
#include "misslist.h" //MLR
#include "getsimobjectdata.h" // MLR
#include "bomb.h" // MLR
#include "bombfunc.h" // MLR
#include "profiler.h"
#include "harmpod.h" // RV - I-Hawk
extern bool g_bUseRC135;
extern bool g_bEnableColorMfd;
extern bool g_bRealisticAvionics;
extern bool g_bEnableFCCSubNavCycle; // ASSOCIATOR 04/12/03: Enables you to cycle the Nav steerpoint modes modes with the FCC submodes key
extern bool g_bWeaponStepToGun; // MLR 3/13/2004 - optionally turns off weapon stepping to guns
extern bool g_bGreyMFD;
extern bool g_bGreyScaleMFD;
extern bool bNVGmode;
const int FireControlComputer::DATALINK_CYCLE = 20;//JPO = 20 seconds
const float FireControlComputer::MAXJSTARRANGESQ = 200*200;//JPO = 200 nm
const float FireControlComputer::EMITTERRANGE = 60;//JPO = 40 km
const float FireControlComputer::CursorRate = 0.15f; //MI added
FireControlComputer::FireControlComputer (SimVehicleClass* vehicle, int numHardpoints)
{
// sfr: smartpointer
//fccWeaponPtr = NULL; // MLR 3/16/2004 - simulated weapon
fccWeaponId = 0;
//rocketPointer = NULL; // MLR 3/5/2004 - For impact prediction
rocketWeaponId = 0;
platform = vehicle;
airGroundDelayTime = 0.0F;
airGroundRange = 10.0F * NM_TO_FT;
missileMaxTof = -1.0f;
missileActiveTime = -1.0f;
lastmissileActiveTime = -1.0f;
bombPickle = FALSE;
postDrop = FALSE;
preDesignate = TRUE;
tossAnticipationCue = NoCue;
laddAnticipationCue = NoLADDCue; //MI
lastMasterMode = Nav;
// ASSOCIATOR
lastNavMasterMode = Nav;
lastAgMasterMode = (FCCMasterMode)-1; // AirGroundBomb; // MLR 2/8/2004 - EnterAGMasterMode() will see this, and determine the default weapon
// MLR 3/13/2004 - back to using hp ids
lastAirAirHp = -1;
lastAirGroundHp = -1;
lastDogfightHp = -1;
lastMissileOverrideHp = -1;
lastAirAirGunSubMode = EEGS; // MLR 2/7/2004 -
lastAirGroundGunSubMode = STRAF; // MLR 2/7/2004 -
lastAirGroundLaserSubMode = SLAVE; // MLR 4/11/2004 -
inAAGunMode = 0; // MLR 3/14/2004 -
inAGGunMode = 0; // MLR 3/14/2004 -
lastSubMode = ETE;
//lastAirGroundSubMode = CCRP;//me123
lastDogfightGunSubMode = EEGS; //MI
lastAirAirSubMode = Aim9; // ASSOCIATOR
strcpy (subModeString, "");
playerFCC = FALSE;
targetList = NULL;
releaseConsent = FALSE;
designateCmd = FALSE;
dropTrackCmd = FALSE;
targetPtr = NULL;
missileCageCmd = FALSE;
missileTDBPCmd = FALSE;
missileSpotScanCmd = FALSE;
missileSlaveCmd = FALSE;
cursorXCmd = 0;
cursorYCmd = 0;
waypointStepCmd = 127; // Force an intial update (GM radar, at least, needs this)
HSDRangeStepCmd = 0;
HSDRange = 15.0F;
HsdRangeIndex = 0; // JPO
groundPipperAz = groundPipperEl = 0.0F;
masterMode = Nav;
subMode = ETE;
dgftSubMode = Aim9; // JPO dogfight specific
mrmSubMode = Aim120; // ASSOCIATOR 04/12/03: for remembering MRM mode missiles
autoTarget = FALSE;
missileWEZDisplayRange = 20.0F * NM_TO_FT;
mSavedWayNumber = 0;
mpSavedWaypoint = NULL;
mStptMode = FCCWaypoint;
mNewStptMode = mStptMode;
bombReleaseOverride = FALSE;
lastMissileShootRng = -1;
missileLaunched = 0;
lastMissileShootHeight = 0;
lastMissileShootEnergy = 0;
nextMissileImpactTime = -1.0F;
lastMissileImpactTime = -1.0f;
Height = 0;//me123
targetspeed = 0;//me123
hsdstates = 0; // JPO
MissileImpactTimeFlash = 0; // JPO
grndlist = NULL;
BuildPrePlanned(); // JPO
//MI
LaserArm = FALSE;
LaserFire = FALSE;
ManualFire = FALSE;
LaserWasFired = FALSE;
CheckForLaserFire = FALSE;
InhibitFire = FALSE;
Timer = 0.0F;
ImpactTime = 0.0F;
LaserRange = 0.0F;
SafetyDistance = 1 * NM_TO_FT;
pitch = 0.0F;
roll = 0.0F;
yaw = 0.0F;
time = 0;
//MI SOI and HSD
IsSOI = FALSE;
CouldBeSOI = FALSE;
HSDZoom = 0;
HSDXPos = 0; //Wombat778 11-10-2003
HSDYPos = 0; //Wombat778 11-10-2003
HSDCursorXCmd = 0;
HSDCursorYCmd = 0;
xPos = 0; //position of the curson on the scope
yPos = 0;
HSDDesignate = 0;
curCursorRate = CursorRate;
DispX = 0;
DispY = 0;
missileSeekerAz = missileSeekerEl = 0;
}
FireControlComputer::~FireControlComputer (void)
{
ClearCurrentTarget();
ClearPlanned(); // JPO
}
void FireControlComputer::SetPlayerFCC (int flag)
{
WayPointClass* tmpWaypoint;
playerFCC = flag;
Sms->SetPlayerSMS(flag);
tmpWaypoint = platform->waypoint;
TheHud->waypointNum = 0;
while (tmpWaypoint && tmpWaypoint != platform->curWaypoint)
{
tmpWaypoint = tmpWaypoint->GetNextWP();
TheHud->waypointNum ++;
}
}
// JPO - just note it is launched.
void FireControlComputer::MissileLaunch()
{
if(subMode == Aim120)
{
missileLaunched = 1;
lastMissileShootTime = SimLibElapsedTime;
}
if(!Sms->GetCurrentWeapon())
{
switch(masterMode) // MLR 4/12/2004 - Even though this function only appears to be called in AA modes
{
case Missile:
case MissileOverride:
if(!Sms->FindWeaponType (wtAim120))
Sms->FindWeaponType (wtAim9);
SetMasterMode(masterMode);
break;
case Dogfight:
if(!Sms->FindWeaponType (wtAim9))
Sms->FindWeaponType (wtAim120);
SetMasterMode(masterMode);
break;
}
}
UpdateLastData();
// UpdateWeaponPtr();
}
SimObjectType* FireControlComputer::Exec (SimObjectType* curTarget, SimObjectType* newList,
PilotInputs* theInputs)
{
#ifdef Prof_ENABLED
Prof(FireControlComputer_Exec);
#endif
//me123 overtake needs to be calgulated the same way in MissileClass::GetTOF
static const float MISSILE_ALTITUDE_BONUS = 23.0f; //me123 addet here and in // JB 010215 changed from 24 to 23
static const float MISSILE_SPEED = 1500.0f; // JB 010215 changed from 1300 to 1500
if (playerFCC &&
((AircraftClass*)platform)->mFaults->GetFault(FaultClass::fcc_fault))
{
SetTarget (NULL);
}
else
{
if (SimDriver.MotionOn())
{
if (!targetPtr)
{
MissileImpactTimeFlash = 0; // cancel flashing
lastMissileImpactTime = 0;
lastmissileActiveTime = 0;
}
if (targetPtr && missileLaunched)
{
lastMissileShootRng = targetPtr->localData->range;
lastMissileImpactTime = nextMissileImpactTime;
lastMissileShootHeight = Height;
lastMissileShootEnergy = (platform->GetVt() * FTPSEC_TO_KNOTS - 150.0f)/2 ; // JB 010215 changed from 250 to 150
}
missileLaunched = 0;
if (lastMissileImpactTime > 0.0F && targetPtr )
{ //me123 addet this stuff
//this is the missiles approximate overtake
//missilespeed + altitude bonus + target closure
float overtake = lastMissileShootEnergy + MISSILE_SPEED +(lastMissileShootHeight/1000.0f * MISSILE_ALTITUDE_BONUS) + targetspeed * (float)cos(targetPtr->localData->ataFrom);
//this is the predicted range from the missile to the target
lastMissileShootRng = lastMissileShootRng - (overtake / SimLibMajorFrameRate);
lastMissileImpactTime = max (0.0F, lastMissileShootRng/overtake); // this is TOF. Counting on silent failure of divid by 0.0 here...
lastMissileImpactTime += -5.0f * (float) sin(.07f * lastMissileImpactTime); // JB 010215
if (lastMissileImpactTime == 0.0f)
{ // JPO - trigger flashing X
// 8 seconds steady, 5 seconds flash
MissileImpactTimeFlash = SimLibElapsedTime + (5+8) * CampaignSeconds;
lastMissileShootRng = -1.0f; // reset for next
}
else
MissileImpactTimeFlash = 0;
}
}
SetTarget(curTarget);
targetList = newList;
NavMode();
switch (masterMode)
{
case AGGun:
//if (GetSubMode() == STRAF) {
AirGroundMode();
break;
case ILS:
case Nav:
break;
case Dogfight:
case MissileOverride:
case Missile:
AirAirMode();
lastCage = missileCageCmd;
break;
case AirGroundBomb:
AirGroundMode();
break;
case AirGroundRocket:
AirGroundMode();
break;
case AirGroundMissile:
case AirGroundHARM:
AirGroundMissileMode();
break;
case AirGroundLaser:
//if(!playerFCC)
TargetingPodMode();
break;
}
// always run targeting pod for player
// FRB - always run targeting pod for All
//TargetingPodMode();
//if(playerFCC) TargetingPodMode();
// COBRA - RED - CCIP HUD FIX - make the Time To target equal to 0, targeting Pod mode is assigning a time to target
// messing up the CCIP pipper in HudClas::DrawCCIP call
//if(subMode==CCIP) airGroundDelayTime=0.0F;
lastDesignate = designateCmd;
}
return (targetPtr);
}
void FireControlComputer::SetSubMode (FCCSubMode newSubMode)
{
if (newSubMode == CCRP &&
Sms &&
Sms->Ownship() &&
Sms->Ownship()->IsAirplane() && // MLR not always owned by a/c
((AircraftClass *)(Sms->Ownship()))->af &&
(!((AircraftClass *)Sms->Ownship())->af->IsSet(AirframeClass::IsDigital) ||
(!(((AircraftClass *)(Sms->Ownship()))->AutopilotType() == AircraftClass::CombatAP))) &&
platform && RadarDataTable[platform->GetRadarType()].NominalRange == 0.0) // JB 011018
{
newSubMode = CCIP;
}
// It has been stated (by Leon R) that changing modes while releasing weapons is bad, so...
if (bombPickle)
{
return;
}
if (masterMode != Dogfight &&
masterMode != MissileOverride)
{
lastSubMode = subMode;
}
if (lastSubMode == BSGT ||
lastSubMode == SLAVE ||
lastSubMode == HARM ||
lastSubMode == HTS )
{
platform->SOIManager (SimVehicleClass::SOI_RADAR);
}
subMode = newSubMode;
// COBRA - RED - Default to immediate release Pickle Time
PICKLE(DEFAULT_PICKLE);
switch (subMode)
{
case SAM:
strcpy (subModeString, "SAM");
Sms->SetWeaponType (wtNone);
Sms->FindWeaponClass (wcSamWpn);
break;
case Aim9:
strcpy (subModeString, "SRM");
if(Sms && Sms->Ownship() && ((AircraftClass *)Sms->Ownship())->AutopilotType() == AircraftClass::CombatAP )
{
if(Sms->GetCoolState() == SMSClass::WARM && Sms->MasterArm() == SMSClass::Arm)
{ // JPO aim9 cooling
Sms->SetCoolState(SMSClass::COOLING);
}
}
platform->SOIManager (SimVehicleClass::SOI_RADAR);
break;
case Aim120:
strcpy (subModeString, "MRM");
platform->SOIManager (SimVehicleClass::SOI_RADAR);
// COBRA - RED - 1 Second Pickle for AIM 120
PICKLE(SEC_1_PICKLE);
break;
case EEGS:
strcpy (subModeString, "EEGS");
platform->SOIManager (SimVehicleClass::SOI_RADAR);
break;
// ASSOCIATOR 03/12/03: Added the combined SnapShot LCOS Gunmode SSLC
case SSLC:
strcpy (subModeString, "SSLC");
platform->SOIManager (SimVehicleClass::SOI_RADAR);
break;
case LCOS:
strcpy (subModeString, "LCOS");
platform->SOIManager (SimVehicleClass::SOI_RADAR);
break;
case Snapshot:
strcpy (subModeString, "SNAP");
platform->SOIManager (SimVehicleClass::SOI_RADAR);
break;
case CCIP:
// MLR 4/1/2004 - rewrite based on Mirv's info.
preDesignate = TRUE;
strcpy (subModeString, "CCIP");
platform->SOIManager (SimVehicleClass::SOI_RADAR);
break;
case CCRP:
// MLR 4/1/2004 - rewrite based on Mirv's info.
preDesignate = FALSE;
strcpy (subModeString, "CCRP");//me123 moved so we don't write this with no bombs
platform->SOIManager (SimVehicleClass::SOI_RADAR);
// 2001-04-18 ADDED BY S.G. I'LL SET MY RANDOM NUMBER FOR CCRP BOMBING INNACURACY NOW
// Since autoTarget is a byte :-( I'm limiting to just use the same value for both x and y offset :-(
// autoTarget = (rand() & 0x3f) - 32; // In RP5, I'm limited to the variables I can use
xBombAccuracy = (rand() & 0x3f) - 32;
yBombAccuracy = (rand() & 0x3f) - 32;
// COBRA - RED - 1 Second Pickle for CCRP
PICKLE(SEC_1_PICKLE);
break;
case DTOSS:
preDesignate = TRUE;
groundPipperAz = 0.0F;
groundPipperEl = 0.0F;
platform->SOIManager (SimVehicleClass::SOI_HUD);
// MLR 4/1/2004 - rewrite based on Mirv's info.
strcpy (subModeString, "DTOS");
// COBRA - RED - 1 Second Pickle for DTOSS
PICKLE(SEC_1_PICKLE);
break;
case LADD:
preDesignate = FALSE;
groundPipperAz = 0.0F;
groundPipperEl = 0.0F;
platform->SOIManager (SimVehicleClass::SOI_RADAR);
// MLR 4/1/2004 - rewrite based on Mirv's info.
strcpy (subModeString, "LADD");
break;
case MAN: // JPO
preDesignate = TRUE;
strcpy (subModeString, "MAN");
platform->SOIManager (SimVehicleClass::SOI_RADAR);
// COBRA - RED - 1 Second Pickle for MAN
PICKLE(SEC_1_PICKLE);
break;
case OBSOLETERCKT:
preDesignate = TRUE;
strcpy (subModeString, "RCKT");
platform->SOIManager (SimVehicleClass::SOI_RADAR);
break;
case STRAF:
preDesignate = TRUE;
strcpy (subModeString, "STRF");
platform->SOIManager (SimVehicleClass::SOI_RADAR);
break;
case BSGT:
preDesignate = TRUE;
groundPipperAz = 0.0F;
groundPipperEl = 0.0F;
strcpy (subModeString, "BSGT");
platform->SOIManager (SimVehicleClass::SOI_HUD);
break;
case SLAVE:
preDesignate = TRUE;
groundPipperAz = 0.0F;
groundPipperEl = 0.0F;
strcpy (subModeString, "SLAV");
platform->SOIManager (SimVehicleClass::SOI_RADAR);
// COBRA - RED - 1 Second Pickle for SLAVE
PICKLE(SEC_1_PICKLE);
break;
case HARM:
case HTS:
preDesignate = TRUE;
groundPipperAz = 0.0F;
groundPipperEl = 0.0F;
// RV - I-Hawk - on HUD it should read "HTS" for HTS and "HARM" for the HARM WPN mode usage
if ( subMode == HTS )
{
strcpy (subModeString, "HTS");
}
else
{
strcpy (subModeString, "HARM");
}
if (Sms->GetCurrentWeaponHardpoint() >= 0 && // JPO CTD fix
Sms->CurHardpoint() >= 0 && // JB 010805 Possible CTD check curhardpoint
Sms->hardPoint[Sms->CurHardpoint()] != NULL) // Cobra - Sms->GetCurrentWeaponHardpoint() was causing a CTD (returned with a very large number)
{
Sms->SetWeaponType(Sms->hardPoint[Sms->CurHardpoint()]->GetWeaponType());
// RV - I-Hawk - Don't auto pass SOI to HARM if we are using the advanced HARM systems
HarmTargetingPod* harmPod = (HarmTargetingPod*)FindSensor(platform, SensorClass::HTS);
if ( harmPod && (harmPod->GetSubMode() == HarmTargetingPod::HAS ||
harmPod->GetSubMode() == HarmTargetingPod::HAD) )
{
platform->SOIManager (SimVehicleClass::SOI_RADAR);
}
else
{
platform->SOIManager (SimVehicleClass::SOI_WEAPON);
}
}
else
Sms->SetWeaponType (wtNone);
// COBRA - RED - 1 Second Pickle for HTS
PICKLE(SEC_1_PICKLE);
break;
case TargetingPod:
preDesignate = TRUE;
groundPipperAz = 0.0F;
groundPipperEl = 0.0F;
strcpy (subModeString, "GBU");
if (Sms->GetCurrentWeaponHardpoint() >= 0 && // JPO CTD fix
Sms->CurHardpoint() >= 0 && // JB 010805 Possible CTD check curhardpoint
Sms->hardPoint[Sms->GetCurrentWeaponHardpoint()] != NULL &&
Sms->hardPoint[Sms->GetCurrentWeaponHardpoint()]->weaponPointer)
Sms->SetWeaponType(Sms->hardPoint[Sms->CurHardpoint()]->GetWeaponType());
else
Sms->SetWeaponType (wtNone);
platform->SOIManager (SimVehicleClass::SOI_RADAR);
// COBRA - RED - 1 Second Pickle for TGP
PICKLE(SEC_1_PICKLE);
break;
case TimeToGo:
case ETE:
case ETA:
platform->SOIManager (SimVehicleClass::SOI_RADAR);
break;
}
// Make sure string is correct in override modes
switch (masterMode)
{
case Dogfight:
//strcpy (subModeString, "DGFT"); //JPG 29 Apr 04 - This is no longer displayed in new software tapes
break;
case MissileOverride:
if (Sms->curWeaponType == Aim9)
{
strcpy (subModeString, "SRM");
}
if (Sms->curWeaponType == Aim120)
{
strcpy (subModeString, "MRM");
}
break;
}
// MLR 4/1/2004 - Memorize SubMode
switch(masterMode)
{
case ILS:
case Nav:
break;
case Dogfight:
lastDogfightGunSubMode = subMode;
break;
case MissileOverride:
lastMissileOverrideSubMode = subMode;
break;
case AAGun:
lastAirAirGunSubMode = subMode;
break;
case Missile:
lastAirAirSubMode = subMode;
break;
case AGGun:
lastAirGroundGunSubMode = subMode;
break;
case AirGroundBomb:
Sms->SetAGBSubMode(subMode);
{
if (playerFCC && SimDriver.GetPlayerAircraft()->AutopilotType() != AircraftClass::CombatAP)
{
RadarDopplerClass* pradar = (RadarDopplerClass*) FindSensor (platform, SensorClass::Radar);
if(g_bRealisticAvionics && pradar)
{
if(subMode == CCRP || subMode == MAN)
{
pradar->SelectLastAGMode();
}
else
{
pradar->DefaultAGMode();
}
pradar->SetScanDir(1.0F);
}
}
else
{
RadarClass* pradar = (RadarClass*) FindSensor (platform, SensorClass::Radar);
pradar->DefaultAGMode();
}
}
break;
case AirGroundMissile:
//lastAirGroundMissileSubMode = subMode;
break;
case AirGroundHARM:
//lastAirGroundHARMSubMode = subMode;
break;
case AirGroundLaser:
lastAirGroundLaserSubMode = subMode;
break;
case AirGroundCamera:
//lastAirGroundCameraSubMode = subMode;
break;
}
}
void FireControlComputer::ClearOverrideMode (void)
{
if ((GetMasterMode() == Dogfight) ||
(GetMasterMode() == MissileOverride))
{
masterMode = lastMasterMode; // MLR - little kludge so I can get the MM
MASTERMODES mmm = GetMainMasterMode();
masterMode = ClearOveride;//me123 to allow leaving an overide mode
switch(mmm)
{
case MM_AA:
EnterAAMasterMode();
break;
case MM_AG:
EnterAGMasterMode();
break;
default:
SetMasterMode (lastMasterMode);
break;
}
}
}
void FireControlComputer::NextSubMode (void)
{
// MLR 4/3/2004 - Added calls to SetSubMode instead of doing 'stuff' for ourselves.
//MI
RadarDopplerClass* pradar = (RadarDopplerClass*) FindSensor (platform, SensorClass::Radar);
switch (masterMode)
{
// ASSOCIATOR 02/12/03: Now we can use the Cycle FCC Submodes key when in Dogfight Mode
// ASSOCIATOR 03/12/03: Added the combined SnapShot LCOS Gunmode SSLC
case Dogfight:
switch (subMode)
{
case EEGS:
if (PlayerOptions.GetAvionicsType() != ATEasy)
{
SetSubMode (SSLC);
}
break;
case SSLC:
SetSubMode (LCOS);
break;
case LCOS:
SetSubMode (Snapshot);
break;
case Snapshot:
SetSubMode (EEGS);
break;
}
break;
// ASSOCIATOR 02/12/03: Now we can use the Cycle FCC Submodes key when in MissileOverride
// ASSOCIATOR 03/12/03: Added the combined SnapShot LCOS Gunmode SSLC
case AAGun:
switch (subMode)
{
case EEGS:
if (PlayerOptions.GetAvionicsType() != ATEasy)
{
SetSubMode (SSLC);
}
break;
case SSLC:
SetSubMode (LCOS);
break;
case LCOS:
SetSubMode (Snapshot);
break;
case Snapshot:
SetSubMode (EEGS);
break;
}
break;
case Nav:
// MD -- 20031203: removed this since sources seem to indicate that there is no such function in the real jet.
// ASSOCIATOR Added g_bEnableFCCSubNavCycle as an option and !g_bRealisticAvionics to not break the other modes
if( g_bEnableFCCSubNavCycle | !g_bRealisticAvionics )
{
switch (subMode)
{
case ETE:
if (PlayerOptions.GetAvionicsType() != ATEasy)
{
SetSubMode (TimeToGo);
}
break;
case TimeToGo:
SetSubMode (ETA);
break;
case ETA:
SetSubMode (ETE);
break;
}
break;
}
else
break;
case AirGroundBomb:
switch (subMode)
{
case CCIP:
if (PlayerOptions.GetAvionicsType() != ATEasy)
{
SetSubMode (DTOSS);
}
break;
case CCRP:
SetSubMode (CCIP);
break;
case DTOSS:
SetSubMode (CCRP);
break;
default: // catch LADD MAN etc
SetSubMode(CCRP);
break;
}
break;
case AirGroundLaser:
if(g_bRealisticAvionics)
{
SetSubMode(lastAirGroundLaserSubMode);
SetSubMode(SLAVE);
break;
}
// intentionally fall thru
case AirGroundMissile:
switch (subMode)
{
case SLAVE:
if (PlayerOptions.GetAvionicsType() != ATEasy)
{
SetSubMode (BSGT);
}
break;
case BSGT:
SetSubMode (SLAVE);
break;
}
break;
}
}
void FireControlComputer::WeaponStep(void)
{
RadarDopplerClass* pradar = (RadarDopplerClass*) FindSensor (platform, SensorClass::Radar);
BombClass *TheBomb=GetTheBomb();
switch (masterMode)
{
case Dogfight:
case MissileOverride:
case Missile:
case AirGroundMissile:
case AirGroundHARM:
Sms->WeaponStep();
if(pradar && (masterMode == AirGroundMissile || masterMode == AirGroundHARM)) //MI fix
{
pradar->SetScanDir(1.0F);
pradar->SelectLastAGMode();
}
break;
case AGGun:
if(lastAgMasterMode==AirGroundBomb)
{
ToggleAGGunMode();
SetSubMode(CCRP);
}
break;
case AirGroundBomb:
// COBRA - RED - FIXING POSSIBLE CTDs
// CCIP -> DTOS -> STRAF -> CCRP
/*if ((Sms->GetCurrentHardpoint() > 0) && (Sms->hardPoint[Sms->GetCurrentHardpoint()]->GetWeaponType()==wtGPS || // Cobra - no rippling GPS
(((BombClass*)Sms->hardPoint[Sms->GetCurrentHardpoint()]->weaponPointer) &&
((BombClass*)Sms->hardPoint[Sms->GetCurrentHardpoint()]->weaponPointer)->IsSetBombFlag(BombClass::IsJSOW))))*/
{
if( TheBomb && ( TheBomb->IsSetBombFlag(BombClass::IsGPS) || TheBomb->IsSetBombFlag(BombClass::IsJSOW)))
Sms->WeaponStep();
break;
}
switch (subMode)
{
case CCIP:
SetSubMode (DTOSS);
break;
case DTOSS:
//Cobra TJL 11/17/04 Aircraft w/o guns get stuck in DTOSS
//with missile step
//ToggleAGGunMode();
if( Sms->FindWeaponClass(wcGunWpn, TRUE) )
ToggleAGGunMode();
else
SetSubMode(CCRP);
break;
case CCRP:
SetSubMode (CCIP);
break;
default: // catch LADD MAN etc
SetSubMode(CCRP);
break;
}
break;
}
}
SimObjectType* FireControlComputer::TargetStep (SimObjectType* startObject, int checkFeature)
{
VuEntity* testObject = NULL;
VuEntity* groundTarget = NULL;
SimObjectType* curObject = NULL;
SimObjectType* retObject = NULL;
float angOff;
// Starting in the object list
if (startObject == NULL || startObject != targetPtr){
// Start at next and go on
if (startObject){
curObject = startObject->next;
while (curObject){
if (curObject->localData->ata < 60.0F * DTR){
retObject = curObject;
break;
}
curObject = curObject->next;
}
}
// Did we go off the End of the objects?
if (!retObject && checkFeature){
// Check features
{
VuListIterator featureWalker(SimDriver.featureList);
testObject = featureWalker.GetFirst();
while (testObject)
{
angOff = (float)atan2 (testObject->YPos() - platform->YPos(),
testObject->XPos() - platform->XPos()) - platform->Yaw();
if (fabs(angOff) < 60.0F * DTR)
{
break;
}
testObject = featureWalker.GetNext();
}
}
if (testObject)
{
groundTarget = testObject;
// KCK NOTE: Uh.. why are we doing this?
//if (retObject)
//{
//Tpoint pos;
//targetPtr->BaseData()->drawPointer->GetPosition (&pos);
//targetPtr->BaseData()->SetPosition (pos.x, pos.y, pos.z);
//}
groundDesignateX = testObject->XPos();
groundDesignateY = testObject->YPos();
groundDesignateZ = testObject->ZPos();
}
}
// Did we go off the end of the Features?
if (!retObject && !groundTarget){
// Check the head of the object list
curObject = targetList;
if (curObject){
if (curObject->localData->ata < 60.0F * DTR){
retObject = curObject;
}
else {
while (curObject != startObject){
curObject = curObject->next;
if (curObject && curObject->localData->ata < 60.0F * DTR){
retObject = curObject;
break;
}
}
}
}
}
}
else if (startObject == targetPtr)
{
// Find the current object
if (checkFeature)
{
{
VuListIterator featureWalker(SimDriver.featureList);
testObject = featureWalker.GetFirst();
// Iterate up to our position in the list.
while (testObject && testObject != targetPtr->BaseData())
testObject = featureWalker.GetNext();
// And then get the next object
if (testObject)
testObject = featureWalker.GetNext();
// Is there anything after the current object?
while (testObject)
{
angOff = (float)atan2 (testObject->YPos() - platform->YPos(),
testObject->XPos() - platform->XPos()) - platform->Yaw();
if (fabs(angOff) < 60.0F * DTR)
{
break;
}
testObject = featureWalker.GetNext();
}
}
// Found one, so use it
if (testObject)
{
groundTarget = testObject;
// KCK: Why are we doing this?
// Tpoint pos;
// targetPtr->BaseData()->drawPointer->GetPosition (&pos);
// targetPtr->BaseData()->SetPosition (pos.x, pos.y, pos.z);
groundDesignateX = testObject->XPos();
groundDesignateY = testObject->YPos();
groundDesignateZ = testObject->ZPos();
}
}
// Off the end of the feature list?
if (!retObject && !groundTarget)
{
// Check the head of the object list
curObject = targetList;
while (curObject)
{
if (curObject->localData->ata < 60.0F * DTR)
{
retObject = curObject;
break;
}
curObject = curObject->next;
}
}
// Of the End of the object list ?
if (!retObject && checkFeature && !groundTarget){
// Check features
VuListIterator featureWalker(SimDriver.featureList);
testObject = featureWalker.GetFirst();
while (testObject && testObject != targetPtr->BaseData()){
angOff = (float)atan2 (testObject->YPos() - platform->YPos(),
testObject->XPos() - platform->XPos()) - platform->Yaw();
if (fabs(angOff) < 60.0F * DTR){
break;
}
testObject = featureWalker.GetNext();
}
if (testObject)
{
groundTarget = testObject;
groundDesignateX = testObject->XPos();
groundDesignateY = testObject->YPos();
groundDesignateZ = testObject->ZPos();
}
}
}
if (groundTarget){
// We're targeting a feature thing - make a new SimObjectType
#ifdef DEBUG
//retObject = new SimObjectType(OBJ_TAG, platform, (SimBaseClass*)groundTarget);
#else
retObject = new SimObjectType((SimBaseClass*)groundTarget);
#endif
retObject->localData->ataFrom = 180.0F * DTR;
}
SetTarget(retObject);
return retObject;
}
void FireControlComputer::ClearCurrentTarget (void)
{
if (targetPtr)
targetPtr->Release( );
targetPtr = NULL;
}
void FireControlComputer::SetTarget (SimObjectType* newTarget)
{
if (newTarget == targetPtr)
return;
/* MLR debugging stuff
MonoPrint(" FCC::SetTarget - prev:%08x/%08x, new: %08x/%08x\n",
targetPtr,(targetPtr?targetPtr->BaseData():0),
newTarget,(newTarget?newTarget->BaseData():0));
if(!newTarget)
int stop=0;
*/
ClearCurrentTarget();
if (newTarget)
{
ShiAssert( newTarget->BaseData() != (FalconEntity*)0xDDDDDDDD );
newTarget->Reference( );
}
targetPtr = newTarget;
}
void FireControlComputer::DisplayInit (ImageBuffer* image)
{
DisplayExit();
privateDisplay = new Render2D;
((Render2D*)privateDisplay)->Setup (image);
if ((g_bGreyMFD) && (!bNVGmode))
privateDisplay->SetColor(GetMfdColor(MFD_WHITE));
else
privateDisplay->SetColor (0xff00ff00);
}
void FireControlComputer::Display (VirtualDisplay* newDisplay)
{
display = newDisplay;
// JPO intercept for now FCC power...
if (!((AircraftClass*)platform)->HasPower(AircraftClass::FCCPower)) {
BottomRow();
display->TextCenter(0.0f, 0.2f, "FCC");
int ofont = display->CurFont();
display->SetFont(2);
display->TextCenterVertical (0.0f, 0.0f, "OFF");
display->SetFont(3);
return;
}
NavDisplay();
}
void FireControlComputer::PushButton(int whichButton, int whichMFD)
{
AircraftClass *playerAC = SimDriver.GetPlayerAircraft();
ShiAssert(whichButton < 20);
ShiAssert(whichMFD < 4);
if (IsHsdState(HSDCNTL))
{
if (hsdcntlcfg[whichButton].mode != HSDNONE)
{
ToggleHsdState(hsdcntlcfg[whichButton].mode);
return;
}
}
//MI
if(g_bRealisticAvionics)
{
if(playerAC)
{
if(IsSOI && (whichButton >=11 && whichButton <= 13))
platform->StepSOI(2);
}
}
switch (whichButton)
{
case 0: // DEP - JPO
if (g_bRealisticAvionics) {
ToggleHsdState (HSDCEN);
}
break;
case 1: // DCPL - JPO
if (g_bRealisticAvionics) {
ToggleHsdState (HSDCPL);
}
break;
//MI
case 2:
if(g_bRealisticAvionics)
ToggleHSDZoom();
break;
case 4: // CTRL
if (g_bRealisticAvionics) {
ToggleHsdState (HSDCNTL);
}
break;
case 6: // FRZ - JPO
if (g_bRealisticAvionics) {
frz_x = platform->XPos();
frz_y = platform->YPos();
frz_dir = platform->Yaw();
ToggleHsdState(HSDFRZ);
}
break;
case 10:
if (g_bRealisticAvionics) {
MfdDrawable::PushButton(whichButton, whichMFD);
}
break;
case 11: // SMS
if (g_bRealisticAvionics)
MfdDrawable::PushButton(whichButton, whichMFD);
else
MfdDisplay[whichMFD]->SetNewMode(MFDClass::SMSMode);
break;
case 12: // jpo
if (g_bRealisticAvionics)
MfdDrawable::PushButton(whichButton, whichMFD);
break;
case 13: // HSD
if (g_bRealisticAvionics)
MfdDrawable::PushButton(whichButton, whichMFD);
else
MfdDisplay[whichMFD]->SetNewMode(MFDClass::MfdMenu);
break;
case 14: // SWAP
if (g_bRealisticAvionics)
MfdDrawable::PushButton(whichButton, whichMFD);
else
MFDSwapDisplays();
break;
case 18: // Down
if(!g_bRealisticAvionics)
SimHSDRangeStepDown (0, KEY_DOWN, NULL);
else
{
//MI
if(HSDZoom == 0)
SimHSDRangeStepDown (0, KEY_DOWN, NULL);
}
break;
case 19: // UP
if(!g_bRealisticAvionics)
SimHSDRangeStepUp (0, KEY_DOWN, NULL);
else
{
//MI
if(HSDZoom == 0)
SimHSDRangeStepUp (0, KEY_DOWN, NULL);
}
break;
}
}
// STUFF Copied from Harm - now merged. JPO
// JPO
// This routine builds the initial list of preplanned targets.
// this will remain unchanged if there is no dlink/jstar access
void FireControlComputer::BuildPrePlanned()
{
FlightClass* theFlight = (FlightClass*)(platform->GetCampaignObject());
FalconPrivateList* knownEmmitters = NULL;
GroundListElement* tmpElement;
GroundListElement* curElement = NULL;
FalconEntity* eHeader;
// this is all based around waypoints.
if (SimDriver.RunningCampaignOrTactical() && theFlight)
knownEmmitters = theFlight->GetKnownEmitters();
if (knownEmmitters)
{
{
VuListIterator elementWalker (knownEmmitters);
eHeader = (FalconEntity*)elementWalker.GetFirst();
while (eHeader)
{
tmpElement = new GroundListElement (eHeader);
if (grndlist == NULL)
grndlist = tmpElement;
else
curElement->next = tmpElement;
curElement = tmpElement;
eHeader = (FalconEntity*)elementWalker.GetNext();
}
}
knownEmmitters->Unregister();
delete knownEmmitters;
}
nextDlUpdate = SimLibElapsedTime + CampaignSeconds * DATALINK_CYCLE;
}
// update - every so often from a JSTAR platform if available.
void FireControlComputer::UpdatePlanned()
{
if (nextDlUpdate > SimLibElapsedTime)
return;
//Cobra This function was killing SAMs and threat rings on HSD
//without it, everything is appearing as normal on the HSD.
nextDlUpdate = SimLibElapsedTime + 5000/*CampaignSeconds * DATALINK_CYCLE*/;
/*if (((AircraftClass*)platform)->mFaults->GetFault(FaultClass::dlnk_fault) ||
!((AircraftClass*)platform)->HasPower(AircraftClass::DLPower))
return;*/
// RV version
// nextDlUpdate = SimLibElapsedTime + CampaignSeconds * DATALINK_CYCLE;
//if (((AircraftClass*)platform)->mFaults->GetFault(FaultClass::dlnk_fault) || !((AircraftClass*)platform)->HasPower(AircraftClass::DLPower))
// return;
FlightClass* theFlight = (FlightClass*)(platform->GetCampaignObject());
if (!theFlight)
return;
CampEntity e;
VuListIterator myit(EmitterList);
// see if we have a jstar.
Flight jstar = theFlight->GetJSTARFlight();
Team us = theFlight->GetTeam();
// If we didn't find JSTAR do other search
if (!jstar) {
Unit nu, cf;
VuListIterator new_myit(AllAirList);
nu = (Unit) new_myit.GetFirst();
while (nu && !jstar) {
cf = nu;
nu = (Unit) new_myit.GetNext();
if (!cf->IsFlight() || cf->IsDead())
continue;
if (cf->GetUnitMission() == AMIS_JSTAR && cf->GetTeam() == us && cf->GetUnitTOT()+5*CampaignMinutes < Camp_GetCurrentTime() && cf->GetUnitTOT()+95*CampaignMinutes > Camp_GetCurrentTime()) {
// Check if JSTAR is in range for communication
if (Distance(platform->XPos(), platform->YPos(), cf->XPos(), cf->YPos()) * FT_TO_NM <= 250.0f) {
jstar = (Flight)cf;
}
}
}
}
if ((!jstar)||(!g_bUseRC135))
{
// completely new list please
//cobra added here
float myx = platform->XPos();
float myy = platform->YPos();
ClearPlanned();
GroundListElement* tmpElement;
GroundListElement* curElement = NULL;
for (e = (CampEntity) myit.GetFirst(); e; e = (Unit) myit.GetNext())
{
if (e->GetTeam() != us /*&& e->GetSpotted(us) &&
(!e->IsUnit() || !((Unit)e)->Moving()) && e->GetElectronicDetectionRange(Air)*/)
{
float ex = e -> XPos();
float ey = e -> YPos();
if (Distance(ex,ey,myx,myy) * FT_TO_NM < 150/*EMITTERRANGE*/)
{
tmpElement = new GroundListElement(e);
tmpElement->SetFlag(GroundListElement::DataLink);//Cobra nothing is using this...
tmpElement->SetFlag(GroundListElement::RangeRing);//Cobra set the ring???
if (grndlist == NULL){
grndlist = tmpElement;
}
else {
curElement->next = tmpElement;
}
curElement = tmpElement;
}
}
}
return;
}
//cobra added here
int jstarDetectionChance = 0;
if (jstar) {
// This is a ELINT flight (e.g. RC-135)
if (jstar->class_data->Role == ROLE_ELINT)
jstarDetectionChance = 75;
else
// FRB - Give JSTAR SAM finder capabilities
if (!g_bUseRC135)
jstarDetectionChance = 75;
else
jstarDetectionChance = 25;
}
//CampEntity e;
// VuListIterator myit(EmitterList);
for (e = (CampEntity) myit.GetFirst(); e; e = (CampEntity) myit.GetNext())
{
if (e->IsUnit() && e->IsBattalion() && rand()%100 > jstarDetectionChance)
continue;
if (e->IsGroundVehicle()) {
GroundListElement* tmpElement = GetFirstGroundElement();
while (tmpElement) {
if (tmpElement->BaseObject() == e)
break;
tmpElement = tmpElement->GetNext();
}
if (!tmpElement) {
tmpElement = new GroundListElement(e);
AddGroundElement(tmpElement);
}
}
}
}
// every so often - remove dead targets
void FireControlComputer::PruneList()
{
GroundListElement **gpp;
for (gpp = &grndlist; *gpp; ) {
if ((*gpp)->BaseObject() == NULL) { // delete this one
GroundListElement *gp = *gpp;
*gpp = gp -> next;
delete gp;
}
else gpp = &(*gpp)->next;
}
}
GroundListElement::GroundListElement(FalconEntity* newEntity)
{
F4Assert (newEntity);
baseObject = newEntity;
VuReferenceEntity(newEntity);
symbol = RadarDataTable[newEntity->GetRadarType()].RWRsymbol;
if (newEntity->IsCampaign())
range = (float)((CampBaseClass*)newEntity)->GetAproxWeaponRange(Air);
else range = 0;
flags = RangeRing;
next = NULL;
lastHit = SimLibElapsedTime;
}
GroundListElement::~GroundListElement()
{
VuDeReferenceEntity(baseObject);
}
void GroundListElement::HandoffBaseObject()
{
FalconEntity *newBase;
if (baseObject == NULL) return;
newBase = SimCampHandoff( baseObject, HANDOFF_RADAR);
if (newBase != baseObject) {
VuDeReferenceEntity(baseObject);
baseObject = newBase;
if (baseObject) {
VuReferenceEntity(baseObject);
}
}
}
void FireControlComputer::ClearPlanned()
{
GroundListElement* tmpElement;
while (grndlist)
{
tmpElement = grndlist;
grndlist = tmpElement->next;
delete tmpElement;
}
}
MASTERMODES FireControlComputer::GetMainMasterMode()
{
switch (masterMode) {
case AAGun:
case Missile:
return MM_AA;
case ILS:
case Nav:
default:
return MM_NAV;
case AirGroundBomb:
case AirGroundRocket:
case AirGroundMissile:
case AirGroundHARM:
case AirGroundLaser:
case AirGroundCamera:
case AGGun:
return MM_AG;
//case Gun:
//if (subMode == STRAF)
// return MM_AG;
//else return MM_AA;
case Dogfight:
return MM_DGFT;
case MissileOverride:
return MM_MSL;
}
}
int FireControlComputer::LastMissileWillMiss(float range)
{
/* if (lastMissileImpactTime >0 && range > missileRMax )
{
return 1;
}
else return 0;
*/ //me123 if the predicted total TOF is over xx seconds the missile is considered out of energy
if (lastMissileImpactTime >0 && //me123 let's make sure there is a missile in the air
lastMissileImpactTime - ((lastMissileShootTime - SimLibElapsedTime) /1000) >= 80)
return 1;
return 0;
}
float FireControlComputer::Aim120ASECRadius(float range)
{
float asecradius = 0.6f;
static const float bestmaxrange = 0.8f; // upper bound
if (!g_bRealisticAvionics) return asecradius;
if (range > bestmaxrange*missileRMax)
{ // above best range
float dr = (range - bestmaxrange*missileRMax) / (0.2f*missileRMax);
dr = 1.0f - dr;
asecradius *= dr;
}
else if (range < (missileRneMax - missileRneMin)/2.0f)
{
float dr = (range - missileRMin);
dr /= (missileRneMax - missileRneMin)/2.0f - missileRMin;
asecradius *= dr;
}
//MI make the size dependant on missile mode
if(Sms && Sms->curWeapon && ((MissileClass*)Sms->GetCurrentWeapon())->isSlave)
asecradius = max(min(0.3f, asecradius), 0.1f);
else
asecradius = max(min(0.6f, asecradius), 0.1f);
return asecradius;
}
// MLR - SetMasterMode() no longer finds matching weapons if the currently
// selected weapon doesn't match the mastermode.
// However - SMM() will change HPs when Master Modes change.
void FireControlComputer::SetMasterMode (FCCMasterMode newMode)
{
RadarClass* theRadar = (RadarClass*) FindSensor (platform, SensorClass::Radar);
FCCMasterMode oldMode;
HarmTargetingPod* harmPod = (HarmTargetingPod*) FindSensor (platform, SensorClass::HTS);
/* appears to not be needed anymore
if( playerFCC &&
(masterMode == Dogfight || masterMode == MissileOverride) &&
newMode != MissileOverride &&
newMode != Dogfight &&
(Sms->curWeaponType == wtAim9 || Sms->curWeaponType == wtAim120 )) // MLR 1/19/2004 - put these two in parenthesis
{
if ( masterMode == MissileOverride )
weaponMisOvrdMode = Sms->curWeaponType;
else
if ( masterMode == Dogfight )
weaponDogOvrdMode = Sms->curWeaponType;
else
weaponNoOvrdMode = Sms->curWeaponType;
}
*/
// Nav only if Amux and Bmux failed, no change if FCC fail
if(playerFCC &&
(
(
((AircraftClass*)platform)->mFaults->GetFault(FaultClass::fcc_fault)
)
||
(
((AircraftClass*)platform)->mFaults->GetFault(FaultClass::amux_fault) &&
((AircraftClass*)platform)->mFaults->GetFault(FaultClass::bmux_fault) &&
newMode != Nav
)
)
)
return;
// It has been stated (by Leon R) that changing modes while releasing weapons is bad, so...
if (bombPickle)
{
return;
}
switch (masterMode)
{
case ClearOveride:
if (theRadar)
theRadar->ClearOverride();
break;
// Clear any holdouts from previous modes
case AirGroundHARM:
((AircraftClass*)platform)->SetTarget (NULL);
break;
}
oldMode = masterMode;
if (masterMode != Dogfight && masterMode != MissileOverride) masterMode = newMode;//me123
int isAI = !playerFCC ||
( playerFCC && ((AircraftClass *)Sms->Ownship())->AutopilotType() == AircraftClass::CombatAP) ;
switch (masterMode)
{
case Dogfight:
// Clear out any non-air-to-air targets we had locked.
if (oldMode != Dogfight && oldMode != Missile && oldMode != MissileOverride)
ClearCurrentTarget();
//if (oldMode != Dogfight)// MLR 4/11/2004 - I'ld like to remove these, but the AI still calls SMM() directly
//Sms->SetCurrentHpByWeaponId(lastDogfightWId);
// Sms->SetCurrentHardPoint(lastDogfightHp);
postDrop = FALSE;
//MI changed so it remembers last gun submode too
if(!g_bRealisticAvionics)
SetSubMode (EEGS);
else
SetSubMode(lastDogfightGunSubMode);
if(isAI && !WeaponClassMatchesMaster(Sms->curWeaponClass))
if(!Sms->FindWeaponType (wtAim9))
Sms->FindWeaponType(wtAim120);
switch(Sms->curWeaponType)
{
case wtAim9:
SetDgftSubMode(Aim9);
break;
case wtAim120:
SetDgftSubMode(Aim120);
break;
}
if (theRadar && oldMode != Dogfight)
{
theRadar->SetSRMOverride();
}
if (TheHud && playerFCC)
{
TheHud->headingPos = HudClass::Low;
}
break;
case MissileOverride://me123 multi changes here
//strcpy (subModeString, "MSL"); // JPG 20 Jan 04
// Clear out any non-air-to-air targets we had locked.
if (oldMode != Dogfight && oldMode != Missile && oldMode != MissileOverride)
ClearCurrentTarget();
postDrop = FALSE;
//if (oldMode != MissileOverride)// MLR 4/11/2004 - I'ld like to remove these, but the AI still calls SMM() directly
// Sms->SetCurrentHardPoint(lastMissileOverrideHp);
// Sms->SetCurrentHpByWeaponId(lastMissileOverrideWId);
if(isAI && !WeaponClassMatchesMaster(Sms->curWeaponClass))
if(!Sms->FindWeaponType (wtAim120))
Sms->FindWeaponType (wtAim9);
switch(Sms->curWeaponType)
{
case wtAim9:
SetSubMode(Aim9);
SetMrmSubMode(Aim9);
break;
case wtAim120:
SetSubMode(Aim120);
SetMrmSubMode(Aim120);
break;
}
if (theRadar )
{
theRadar->SetMRMOverride();
}
if (TheHud && playerFCC)
TheHud->headingPos = HudClass::Low;
break;
case Missile:
// Clear out any non-air-to-air targets we had locked.
if (oldMode != Dogfight && oldMode != MissileOverride)
ClearCurrentTarget();
postDrop = FALSE;
//if(oldMode != masterMode) // MLR 4/11/2004 - I'ld like to remove these, but the AI still calls SMM() directly
// Sms->SetCurrentHardPoint(lastAirAirHp);
//MonoPrint("FCC:SetMasterMode - 1. CurrentWeaponType=%d\n",Sms->GetCurrentWeaponType());
// make sure the AI get a proper weapon
if(isAI && !WeaponClassMatchesMaster(Sms->curWeaponClass))
if(!Sms->FindWeaponType (wtAim120))
Sms->FindWeaponType (wtAim9);
switch(Sms->GetCurrentWeaponType())
{
case wtAim120:
SetSubMode(Aim120);
break;
case wtAim9:
SetSubMode(Aim9);
break;
}
if (TheHud && playerFCC)
TheHud->headingPos = HudClass::Low;
break;
case ILS:
// Clear out any previous targets we had locked.
ClearCurrentTarget();
Sms->SetWeaponType (wtNone);
Sms->FindWeaponClass (wcNoWpn);
if (TheHud && playerFCC)
TheHud->headingPos = HudClass::High;
platform->SOIManager (SimVehicleClass::SOI_RADAR);
break;
case Nav:
// Clear out any previous targets we had locked.
strcpy (subModeString, "NAV");
ClearCurrentTarget();
Sms->SetWeaponType (wtNone);
Sms->FindWeaponClass (wcNoWpn);
SetSubMode (ETE);
releaseConsent = FALSE;
postDrop = FALSE;
preDesignate = TRUE;
postDrop = FALSE;
bombPickle = FALSE;
// Find currentwaypoint
if (TheHud && playerFCC)
{
TheHud->headingPos = HudClass::Low;
}
// SOI is RADAR in NAV
//Cobra test Double here since ETE above sets SOI_RADAR
//platform->SOIManager (SimVehicleClass::SOI_RADAR);
break;
case AirGroundBomb:
// Clear out any previous targets we had locked.
ClearCurrentTarget();
preDesignate = TRUE;
postDrop = FALSE;
inRange = TRUE;
if(isAI && !WeaponClassMatchesMaster(Sms->curWeaponClass))
Sms->FindWeaponClass (wcBombWpn);
if(g_bRealisticAvionics)
{
SetSubMode(Sms->GetAGBSubMode());
}
else
{
SetSubMode(CCIP);
}
//if(playerFCC)
//{
// Sms->drawable->SetDisplayMode(SmsDrawable::Wpn);
///}
if (TheHud && playerFCC)
TheHud->headingPos = HudClass::High;
break;
case AirGroundRocket:
// Clear out any previous targets we had locked.
ClearCurrentTarget();
preDesignate = TRUE;
postDrop = FALSE;
inRange = TRUE;
if(isAI && !WeaponClassMatchesMaster(Sms->curWeaponClass))
Sms->FindWeaponClass (wcRocketWpn);
SetSubMode (OBSOLETERCKT);
/*
if(!playerFCC)
{
SetSubMode (OBSOLETERCKT);
}
else
{
if(g_bRealisticAvionics)
{
SetSubMode (Sms->GetAGBSubMode());
}
else
{
SetSubMode (OBSOLETERCKT);
}
}
*/
if (TheHud && playerFCC)
TheHud->headingPos = HudClass::High;
break;
case AirGroundMissile:
// Clear out any previous targets we had locked.
ClearCurrentTarget();
preDesignate = TRUE;
postDrop = FALSE;
inRange = TRUE;
missileTarget = FALSE;
if(isAI && !WeaponClassMatchesMaster(Sms->curWeaponClass))
Sms->FindWeaponType (wtAgm65);
if(WeaponClassMatchesMaster(Sms->curWeaponClass))
{
if(playerFCC)
{
this->
Sms->StepMavSubMode(TRUE); // TRUE means initial step
}
/*
if (PlayerOptions.GetAvionicsType() == ATRealistic ||
PlayerOptions.GetAvionicsType() == ATRealisticAV)
SetSubMode (BSGT);
else
SetSubMode (SLAVE);
*/
}
else
{
if(playerFCC)
{
Sms->drawable->SetDisplayMode(SmsDrawable::Wpn);
}
}
/*
if (Sms->curWeaponClass != wcAgmWpn)
{
if (Sms->FindWeaponClass (wcAgmWpn) && Sms->CurHardpoint() >= 0) // JB 010805 Possible CTD check curhardpoint
{
Sms->SetWeaponType(Sms->hardPoint[Sms->CurHardpoint()]->GetWeaponType());
switch (Sms->curWeaponType)
{
case wtAgm65:
// M.N. added full realism mode
if (PlayerOptions.GetAvionicsType() == ATRealistic || PlayerOptions.GetAvionicsType() == ATRealisticAV)
SetSubMode (BSGT);
else
SetSubMode (SLAVE);
break;
}
}
else
{
Sms->SetWeaponType (wtNone);
if( playerFCC )
{
Sms->GetNextWeapon(wdGround);
Sms->drawable->SetDisplayMode(SmsDrawable::Wpn);
}
}
}
*/
if (TheHud && playerFCC)
TheHud->headingPos = HudClass::High;
break;
case AirGroundHARM:
// Clear out any previous targets we had locked.
ClearCurrentTarget();
preDesignate = TRUE;
postDrop = FALSE;
// RV - I-Hawk - Get into the right HARM modes
if( isAI && !WeaponClassMatchesMaster(Sms->curWeaponClass) )
{
Sms->FindWeaponType (wtAgm88);
}
if ( isAI )
{
harmPod->SetSubMode ( HarmTargetingPod::HAS );
harmPod->SetHandedoff ( true ); // AI doesn't need any target hadnoff delay
}
else
{
harmPod->SetSubMode( HarmTargetingPod::HarmModeChooser );
}
/*
if (Sms->curWeaponClass != wcHARMWpn)
{
if (Sms->FindWeaponClass (wcHARMWpn, FALSE) && Sms->CurHardpoint() >= 0) // JB 010805 Possible CTD check curhardpoint
{
Sms->SetWeaponType(Sms->hardPoint[Sms->CurHardpoint()]->GetWeaponType());
switch (Sms->curWeaponType)
{
case wtAgm88:
SetSubMode (HTS);
break;
}
}
else
{
Sms->SetWeaponType (wtNone);
if( playerFCC )
{
Sms->GetNextWeapon(wdGround);
Sms->drawable->SetDisplayMode(SmsDrawable::Wpn);
}
}
}
*/
if (TheHud && playerFCC)
{
TheHud->headingPos = HudClass::High;
}
break;
case AirGroundLaser:
// Clear out any previous targets we had locked.
ClearCurrentTarget();
preDesignate = TRUE;
postDrop = FALSE;
if(isAI && !WeaponClassMatchesMaster(Sms->curWeaponClass))
Sms->FindWeaponType (wtGBU);
if(WeaponClassMatchesMaster(Sms->curWeaponClass))
{
if(!g_bRealisticAvionics)
{
//Mi this isn't true... doc states you start off in SLAVE
if (PlayerOptions.GetAvionicsType() == ATRealistic)
SetSubMode (BSGT);
else
SetSubMode (SLAVE);
}
else
{
InhibitFire = FALSE;
// M.N. added full realism mode
if( PlayerOptions.GetAvionicsType() != ATRealistic &&
PlayerOptions.GetAvionicsType() != ATRealisticAV)
SetSubMode (BSGT);
else
SetSubMode (SLAVE);
}
}
else
{
if( playerFCC )
{
Sms->drawable->SetDisplayMode(SmsDrawable::Wpn);
}
}
/*
if (Sms->curWeaponClass != wcGbuWpn)
{
if (Sms->FindWeaponClass (wcGbuWpn, FALSE) && Sms->CurHardpoint() >= 0) // JB 010805 Possible CTD check curhardpoint
{
Sms->SetWeaponType(Sms->hardPoint[Sms->CurHardpoint()]->GetWeaponType());
switch (Sms->curWeaponType)
{
case wtGBU:
//Mi this isn't true... doc states you start off in SLAVE
if(!g_bRealisticAvionics)
{
if (PlayerOptions.GetAvionicsType() == ATRealistic)
SetSubMode (BSGT);
else
SetSubMode (SLAVE);
}
else
{
InhibitFire = FALSE;
// M.N. added full realism mode
if(PlayerOptions.GetAvionicsType() != ATRealistic && PlayerOptions.GetAvionicsType() != ATRealisticAV)
SetSubMode (BSGT);
else
SetSubMode (SLAVE);
}
break;
}
}
else
{
Sms->SetWeaponType (wtNone);
if( playerFCC )
{
Sms->GetNextWeapon(wdGround);
Sms->drawable->SetDisplayMode(SmsDrawable::Wpn);
}
}
}
*/
if (TheHud && playerFCC)
TheHud->headingPos = HudClass::High;
break;
case AirGroundCamera:
// Clear out any previous targets we had locked.
ClearCurrentTarget();
preDesignate = TRUE;
postDrop = FALSE;
if(isAI && !WeaponClassMatchesMaster(Sms->curWeaponClass))
Sms->FindWeaponClass (wcCamera);
if(WeaponClassMatchesMaster(Sms->curWeaponClass))
{
SetSubMode(PRE); // MLR 2/14/2004 - who knows if this it correct
}
else
{
Sms->drawable->SetDisplayMode(SmsDrawable::Wpn);
}
/*
if (Sms->curWeaponClass != wcCamera)
{
if (Sms->FindWeaponClass (wcCamera, FALSE) && Sms->CurHardpoint() >= 0) // JB 010805 Possible CTD check curhardpoint
{
Sms->SetWeaponType(Sms->hardPoint[Sms->CurHardpoint()]->GetWeaponType());
}
else
{
Sms->SetWeaponType (wtNone);
if( playerFCC )
{
Sms->GetNextWeapon(wdGround);
Sms->drawable->SetDisplayMode(SmsDrawable::Wpn);
}
}
}
*/
if (TheHud && playerFCC)
TheHud->headingPos = HudClass::High;
strcpy (subModeString, "RPOD");
platform->SOIManager (SimVehicleClass::SOI_RADAR);
break;
}
// MLR 2/1/2004 - we check this last, because sometimes we fall back to gun mode in the switch above
if(masterMode==AAGun)
{
if(g_bRealisticAvionics)
SetSubMode(lastAirAirGunSubMode);
else
SetSubMode(EEGS);
if(!WeaponClassMatchesMaster(Sms->curWeaponClass))
Sms->FindWeaponType (wtGuns);
// we only want to store this as the previous weapon if g_bWeaponStepToGun is TRUE
//if(g_bWeaponStepToGun)
// lastAirAirHp = Sms->GetCurrentWeaponHardpoint();
//lastAirAirWId=Sms->GetCurrentWeaponId();
if (TheHud && playerFCC)
TheHud->headingPos = HudClass::Low;
}
if(masterMode==AGGun)
{
{
SetSubMode(STRAF);
}
if(!WeaponClassMatchesMaster(Sms->curWeaponClass))
Sms->FindWeaponType (wtGuns);
// we only want to store this as the previous weapon if g_bWeaponStepToGun is TRUE
//if(g_bWeaponStepToGun)
// lastAirGroundHp = Sms->GetCurrentWeaponHardpoint();
//lastAirGroundWId=Sms->GetCurrentWeaponId(); //>GetCurrentWeaponHardpoint();
if (TheHud && playerFCC)
TheHud->headingPos = HudClass::High;
}
// store master mode, used when leaving DF or MO.
switch(masterMode)
{
case Dogfight:
case MissileOverride:
break;
default:
lastMasterMode = masterMode;
}
UpdateWeaponPtr();
UpdateLastData();
}
void FireControlComputer::UpdateLastData(void)
{
switch(masterMode)
{
case ILS:
case Nav:
lastNavMasterMode = masterMode;
break;
case Dogfight:
lastDogfightHp = Sms->GetCurrentWeaponHardpoint();
break;
case MissileOverride:
lastMissileOverrideHp = Sms->GetCurrentWeaponHardpoint();
break;
case AAGun:
break;
//if(!g_bWeaponStepToGun)
//{
// break;
//}
// intentionally fall thru
case Missile:
//lastAaMasterMode = masterMode;
lastAirAirHp = Sms->GetCurrentWeaponHardpoint();
break;
case AGGun:
break;
//if(!g_bWeaponStepToGun)
//{
// break;
//}
// intentionally fall thru
case AirGroundBomb:
case AirGroundRocket:
case AirGroundMissile:
case AirGroundHARM:
case AirGroundLaser:
case AirGroundCamera:
lastAgMasterMode = masterMode;
lastAirGroundHp = Sms->GetCurrentWeaponHardpoint();
break;
}
}
int FireControlComputer::WeaponClassMatchesMaster(WeaponClass wc)
{
switch(masterMode)
{
case Missile:
if(wc==wcAimWpn || wc==wcGunWpn)
return 1;
return 0;
case Dogfight:
case MissileOverride:
if(wc==wcAimWpn )
return 1;
return 0;
case AAGun:
case AGGun:
if(wc==wcGunWpn)
return 1;
return 0;
case AirGroundMissile:
if(wc==wcAgmWpn)
return 1;
return 0;
break;
case AirGroundBomb:
if(wc==wcBombWpn)// || wc==wcRocketWpn)
return 1;
return 0;
break;
case AirGroundRocket:
if(wc==wcRocketWpn)// || wc==wcRocketWpn)
return 1;
return 0;
break;
case AirGroundHARM:
if(wc==wcHARMWpn)
return 1;
return 0;
break;
case AirGroundLaser:
if(wc==wcGbuWpn)
return 1;
return 0;
break;
case AirGroundCamera:
if(wc==wcCamera)
return 1;
return 0;
break;
/*
case ClearOveride:
if(wc==)
return 1;
return 0;
break;
*/
}
return 0;
}
int FireControlComputer::CanStepToWeaponClass(WeaponClass wc)
{
switch(masterMode)
{
case AAGun:
if( ( wc==wcAimWpn && g_bWeaponStepToGun) ||
wc==wcGunWpn )
return 1;
return 0;
case Missile:
if( wc==wcAimWpn ||
(wc==wcGunWpn && g_bWeaponStepToGun) )
return 1;
return 0;
case MissileOverride:
case Dogfight:
if(wc==wcAimWpn )
return 1;
return 0;
case AGGun:
if( ( ( wc==wcAgmWpn || wc==wcBombWpn ||
wc==wcRocketWpn || wc==wcHARMWpn ||
wc==wcGbuWpn || wc==wcCamera ) && g_bWeaponStepToGun) ||
wc==wcGunWpn )
return 1;
return 0;
case AirGroundBomb:
case AirGroundRocket:
case AirGroundMissile:
case AirGroundHARM:
case AirGroundLaser:
case AirGroundCamera:
if( wc==wcAgmWpn || wc==wcBombWpn ||
wc==wcRocketWpn || wc==wcHARMWpn ||
wc==wcGbuWpn || wc==wcCamera ||
( wc==wcGunWpn && g_bWeaponStepToGun ) )
return 1;
return 0;
}
return 0;
/*
switch(GetMainMasterMode())
{
case MM_AA:
if(g_bWeaponStepToGun)
{
if( wc==wcAimWpn || wc==wcGunWpn )
return 1;
}
else
{
}
return 0;
case MM_DGFT:
case MM_MSL:
if(wc==wcAimWpn )
return 1;
return 0;
case MM_AG:
if( wc==wcAgmWpn || wc==wcBombWpn ||
wc==wcRocketWpn || wc==wcHARMWpn ||
wc==wcGbuWpn || wc==wcCamera ||
( wc==wcGunWpn && g_bWeaponStepToGun ) )
return 1;
return 0;
}
return 0;
*/
}
void FireControlComputer::SetAAMasterModeForCurrentWeapon(void)
{
//UpdateWeaponPtr();
FCCMasterMode newmode = masterMode;
if(Sms->GetCurrentWeaponHardpoint() == -1)
{ // maybe we've jetted the weapons, and the Sms curHardpoint is -1
// anyhow, find what we were using before
Sms->SetCurrentHardPoint(lastAirAirHp,1);
}
inAAGunMode = 0;
switch(Sms->curWeaponClass)
{
case wcAimWpn:
newmode = Missile;
break;
case wcGunWpn:
inAAGunMode = 1;
newmode = AAGun;
break;
}
SetMasterMode(newmode);
}
void FireControlComputer::SetAGMasterModeForCurrentWeapon(void)
{
if(Sms->GetCurrentWeaponHardpoint() == -1)
{ // maybe we've jetted the weapons, and the Sms curHardpoint is -1
// anyhow, find what we were using before
Sms->SetCurrentHardPoint(lastAirGroundHp,1);
}
//UpdateWeaponPtr();
if( Sms->CurHardpoint()<0 )
{ // whoops
return;
}
else
if(!Sms->hardPoint[Sms->CurHardpoint()])
return;
FCCMasterMode newmode = masterMode;
inAGGunMode = 0;
switch(Sms->hardPoint[Sms->CurHardpoint()]->GetWeaponClass())
{
case wcRocketWpn:
newmode = AirGroundRocket;
break;
case wcBombWpn:
newmode = AirGroundBomb;
break;
case wcGunWpn:
inAGGunMode = 1;
newmode = AGGun;
break;
case wcAgmWpn:
newmode = AirGroundMissile;
break;
case wcHARMWpn:
newmode = AirGroundHARM;
break;
case wcGbuWpn:
newmode = AirGroundLaser;
break;
case wcCamera:
newmode = AirGroundCamera;
break;
default:
newmode = AirGroundBomb;
/*
case wcSamWpn:
break;
case wcNoWpn:
break;
case wcECM:
break;
case wcTank:
break;
*/
}
SetMasterMode(newmode);
}
int FireControlComputer::IsInAAMasterMode(void)
{
return(GetMainMasterMode()==MM_AA);
}
int FireControlComputer::IsInAGMasterMode(void)
{
return(GetMainMasterMode()==MM_AG);
}
void FireControlComputer::EnterAAMasterMode(void)
{
if(inAAGunMode)
{ // go to gun mode
if( Sms->FindWeaponClass(wcGunWpn, TRUE) )
SetMasterMode(AAGun);
}
else
{
Sms->SetCurrentHardPoint(lastAirAirHp);
//SetMasterMode(lastAaMasterMode);
SetMasterMode(Missile);
}
}
void FireControlComputer::EnterAGMasterMode(void)
{
if(inAGGunMode)
{ // go to gun mode
if( Sms->FindWeaponClass(wcGunWpn, TRUE) )
SetMasterMode(AGGun);
}
else
{
Sms->SetCurrentHardPoint(lastAirGroundHp);
SetMasterMode(lastAgMasterMode);
}
}
void FireControlComputer::EnterMissileOverrideMode(void)
{
Sms->SetCurrentHardPoint(lastMissileOverrideHp);
SetMasterMode(MissileOverride);
}
void FireControlComputer::EnterDogfightMode(void)
{
Sms->SetCurrentHardPoint(lastDogfightHp);
SetMasterMode(Dogfight);
}
void FireControlComputer::ToggleAAGunMode(void)
{
inAAGunMode = !inAAGunMode;
EnterAAMasterMode();
}
void FireControlComputer::ToggleAGGunMode(void)
{
inAGGunMode = !inAGGunMode;
EnterAGMasterMode();
}
void FireControlComputer::UpdateWeaponPtr(void)
{
// the fccWeaponPointer is ONLY used to access weapon data, impact prediction etc, it is NEVER fired.
int wid;
wid = Sms->GetCurrentWeaponId();
if(wid != fccWeaponId)
{
fccWeaponPtr.reset();
fccWeaponId = wid;
if(fccWeaponId)
{
Falcon4EntityClassType *classPtr = GetWeaponF4CT(fccWeaponId);
if(classPtr)
{
if (
classPtr->vuClassData.classInfo_[VU_TYPE] == TYPE_MISSILE ||
classPtr->vuClassData.classInfo_[VU_TYPE] == TYPE_ROCKET
){
fccWeaponPtr.reset(InitAMissile(Sms->Ownship(), fccWeaponId, 0));
}
else {
if (
classPtr->vuClassData.classInfo_[VU_TYPE] == TYPE_BOMB ||
(
classPtr->vuClassData.classInfo_[VU_TYPE] == TYPE_ELECTRONICS &&
classPtr->vuClassData.classInfo_[VU_CLASS] == CLASS_VEHICLE
) ||
(
classPtr->vuClassData.classInfo_[VU_TYPE] == TYPE_FUEL_TANK &&
classPtr->vuClassData.classInfo_[VU_STYPE] == STYPE_FUEL_TANK
) ||
(
classPtr->vuClassData.classInfo_[VU_TYPE] == TYPE_RECON &&
classPtr->vuClassData.classInfo_[VU_STYPE] == STYPE_CAMERA
) ||
(
classPtr->vuClassData.classInfo_[VU_TYPE] == TYPE_LAUNCHER &&
classPtr->vuClassData.classInfo_[VU_STYPE] == STYPE_ROCKET
)
){
fccWeaponPtr.reset(InitABomb(Sms->Ownship(), fccWeaponId, 0));
}
}
}
if (fccWeaponPtr && fccWeaponPtr->IsLauncher()){
wid = ((BombClass *)fccWeaponPtr.get())->LauGetWeaponId();
if(wid != rocketWeaponId){
if(wid){
rocketPointer.reset((MissileClass *)InitAMissile(Sms->Ownship(), wid, 0));
}
else{
rocketPointer.reset(0);
}
rocketWeaponId = wid;
}
}
}
}
}
void FireControlComputer::SetSms(SMSClass *SMS)
{
Sms = SMS;
// setup default HPs for MMs
// dogfight
if(!Sms->FindWeaponType (wtAim9))
Sms->FindWeaponType(wtAim120);
lastDogfightHp = Sms->CurHardpoint();
// missile override & aamm
if(!Sms->FindWeaponType (wtAim120))
Sms->FindWeaponType(wtAim9);
lastMissileOverrideHp = Sms->CurHardpoint();
lastAirAirHp = Sms->CurHardpoint();
// agmm
/*if(!Sms->FindWeaponType (wtAgm88))
if(!Sms->FindWeaponType (wtAgm65))
if(!Sms->FindWeaponType (wtGBU))
if(!Sms->FindWeaponType (wtGPS))
if(!Sms->FindWeaponType (wtMk84))
if(!Sms->FindWeaponType (wtMk82))
Sms->FindWeaponClass (wcRocketWpn); // used to be: Sms->FindWeaponType (wtLAU); but jammers are marks as wtLAU :rolleyes:*/
//Cobra
if(!Sms->FindWeaponType (wtAgm88))
if(!Sms->FindWeaponType (wtAgm65))
if(!Sms->FindWeaponType (wtGBU))
if(!Sms->FindWeaponType (wtGPS))
if(!Sms->FindWeaponType (wtMk84))
if(!Sms->FindWeaponType (wtMk82))
if(!Sms->FindWeaponClass (wcRocketWpn))
Sms->FindWeaponClass (wcGunWpn);
//end
if(Sms->CurHardpoint() > 0)
{
switch(Sms->hardPoint[Sms->CurHardpoint()]->GetWeaponClass())
{
case wcRocketWpn:
lastAgMasterMode = AirGroundRocket;
break;
case wcBombWpn:
lastAgMasterMode = AirGroundBomb;
break;
case wcAgmWpn:
lastAgMasterMode = AirGroundMissile;
break;
case wcHARMWpn:
lastAgMasterMode = AirGroundHARM;
break;
case wcGbuWpn:
lastAgMasterMode = AirGroundLaser;
break;
case wcCamera:
lastAgMasterMode = AirGroundCamera;
break;
default:
lastAgMasterMode = AirGroundBomb;
}
}
lastAirGroundHp = Sms->CurHardpoint();
// Set us up in Gun mode if we have no AA or AG stores
if(lastAirAirHp == -1)
{
inAAGunMode = 1;
}
//Cobra change to HP 0 for Gun from -1
if(lastAirGroundHp == 0)
{
inAGGunMode = 1;
}
}
// RV - I-Hawk - Added function
bool FireControlComputer::AllowMaddog()
{
if ( Sms && Sms->GetCurrentWeaponType() == wtAim120 )
{
MissileClass* currMissile = (MissileClass*)Sms->GetCurrentWeapon();
if ( !targetPtr && currMissile && currMissile->isSlave )
{
return false;
}
}
return true;
}
| 62,756 | 28,330 |
class Solution {
public:
void subsets(vector<int> nums, set<vector<int>> &s, int i, vector<int> r)
{
if(i == nums.size())
{
sort(r.begin(), r.end());
s.insert(r);
return;
}
else
{
subsets(nums, s, i+1, r);
r.push_back(nums[i]);
subsets(nums, s, i+1, r);
}
}
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
//OM GAN GANAPATHAYE NAMO NAMAH
//JAI SHRI RAM
//JAI BAJRANGBALI
//AMME NARAYANA, DEVI NARAYANA, LAKSHMI NARAYANA, BHADRE NARAYANA
set<vector<int>> s;
vector<int> r;
subsets(nums, s, 0, r);
vector<vector<int>> res;
for(auto it = s.begin(); it != s.end(); it++)
res.push_back(*it);
return res;
}
};
| 847 | 324 |
#include <sstream>
#include <iostream>
#include <ydk/entity_util.hpp>
#include "bundle_info.hpp"
#include "generated_entity_lookup.hpp"
#include "Cisco_IOS_XE_eem.hpp"
using namespace ydk;
namespace cisco_ios_xe {
namespace Cisco_IOS_XE_eem {
const Enum::YLeaf OperatorType::eq {0, "eq"};
const Enum::YLeaf OperatorType::ge {1, "ge"};
const Enum::YLeaf OperatorType::gt {2, "gt"};
const Enum::YLeaf OperatorType::le {3, "le"};
const Enum::YLeaf OperatorType::lt {4, "lt"};
const Enum::YLeaf OperatorType::ne {5, "ne"};
}
}
| 530 | 229 |
/**
* @file main.cc
* @author Stavros Avramidis (@purpl3F0x)
* @date 16/12/2019
* @copyright 2019 Stavros Avramidis under Apache 2.0 License
*/
#include <filesystem>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include "mqa_identifier.h"
namespace fs = std::filesystem;
auto getSampleRateString(const uint32_t fs) {
std::stringstream ss;
if (fs <= 768000)
ss << fs / 1000. << "K";
else if (fs % 44100 == 0)
ss << "DSD" << fs / 44100;
else
ss << "DSD" << fs / 48000 << "x48";
return ss.str();
}
/**
* @short Recursively scan a directory for .flac files
* @param curDir directory to scan
* @param files vector to add the file paths
*/
void recursiveScan(const fs::directory_entry &curDir, std::vector<std::string> &files) {
for (const auto &entry : fs::directory_iterator(curDir)) {
if (fs::is_regular_file(entry) && (fs::path(entry).extension() == ".flac"))
files.push_back(entry.path().string());
else if (fs::is_directory(entry))
recursiveScan(entry, files);
}
}
int main(int argc, char *argv[]) {
std::vector<std::string> files;
if (argc == 1) {
std::cout << "HINT: To use the tool provide files and/or directories as program arguments\n\n";
}
for (auto argn = 1; argn < argc; argn++) {
if (fs::is_directory(argv[argn]))
recursiveScan(fs::directory_entry(argv[argn]), files);
else if (fs::is_regular_file(argv[argn])) {
if (fs::path(argv[argn]).extension() == ".flac")
files.emplace_back(argv[argn]);
else
std::cerr << argv[argn] << " not .flac file\n";
}
}
// Flush error buffer (just to make sure our print is pretty and no error line get in between)
std::cerr << std::flush;
// Let's do some printing
std::cout << "**************************************************\n";
std::cout << "*********** MQA flac identifier tool ***********\n";
std::cout << "******** Stavros Avramidis (@purpl3F0x) ********\n";
std::cout << "** https://github.com/purpl3F0x/MQA_identifier **\n";
std::cout << "**************************************************\n";
std::cout << "Found " << files.size() << " file for scanning...\n\n";
// Start parsing the files
size_t count = 0;
size_t mqa_files = 0;
std::cout << " #\tEncoding\t\tName\n";
for (const auto &file : files) {
std::cout << std::setw(3) << ++count << "\t";
auto id = MQA_identifier(file);
if (id.detect()) {
std::cout << "MQA " << (id.isMQAStudio() ? "Studio " : "")
<< getSampleRateString(id.originalSampleRate()) << " \t"
<< fs::path(file).filename().string() << "\n";
mqa_files++;
} else
std::cout << "NOT MQA \t" << fs::path(file).filename().string() << "\n";
}
std::cout << "\n**************************************************\n";
std::cout << "Scanned " << files.size() << " files\n";
std::cout << "Found " << mqa_files << " MQA files\n";
}
| 3,198 | 1,096 |
/*
* BLueIOMPU9250.h
*
* Created on: Jul 25, 2018
* Author: hoan
*/
#include "app_util_platform.h"
#include "app_scheduler.h"
#include "istddef.h"
#include "ble_app.h"
#include "ble_service.h"
#include "device_intrf.h"
#include "coredev/spi.h"
#include "coredev/timer.h"
#include "sensors/agm_mpu9250.h"
#include "imu/imu_mpu9250.h"
#include "idelay.h"
#include "board.h"
#include "BlueIOThingy.h"
#include "BlueIOMPU9250.h"
static const ACCELSENSOR_CFG s_AccelCfg = {
.DevAddr = 0,
.OpMode = SENSOR_OPMODE_CONTINUOUS,
.Freq = 50000,
.Scale = 2,
.FltrFreq = 0,
.bInter = true,
.IntPol = DEVINTR_POL_LOW,
};
static const GYROSENSOR_CFG s_GyroCfg = {
.DevAddr = 0,
.OpMode = SENSOR_OPMODE_CONTINUOUS,
.Freq = 50000,
.Sensitivity = 10,
.FltrFreq = 200,
};
static const MAGSENSOR_CFG s_MagCfg = {
.DevAddr = 0,
.OpMode = SENSOR_OPMODE_CONTINUOUS,//SENSOR_OPMODE_SINGLE,
.Freq = 50000,
.Precision = MAGSENSOR_PRECISION_HIGH,
};
AgmMpu9250 g_Mpu9250;
static void ImuEvtHandler(Device * const pDev, DEV_EVT Evt);
static const IMU_CFG s_ImuCfg = {
.EvtHandler = ImuEvtHandler
};
static ImuMpu9250 s_Imu;
static Timer * s_pTimer;
static uint32_t s_MotionFeature = 0;
int8_t g_AlignMatrix[9] = {
0, 1, 0,
-1, 0, 0,
0, 0, -1
};
#if 0
/**@brief Acclerometer rotation matrix.
*
* @note Accellerometer inverted to get positive readings when axis is aligned with g (down).
*/
static struct platform_data_s s_accel_pdata =
{
.orientation = { 0, 1, 0,
-1, 0, 0,
0, 0, -1}
};
/* The sensors can be mounted onto the board in any orientation. The mounting
* matrix seen below tells the MPL how to rotate the raw data from the
* driver(s).
* TODO: The following matrices refer to the configuration on internal test
* boards at Invensense. If needed, please modify the matrices to match the
* chip-to-body matrix for your particular set up.
*/
#if 1
static struct platform_data_s gyro_pdata = {
.orientation = { 0, 1, 0,
-1, 0, 0,
0, 0, -1}
};
#else
// BLUEIO-TAG-EVIM
static struct platform_data_s gyro_pdata = {
.orientation = { 0, 1, 0,
1, 0, 0,
0, 0, 1}
};
#endif
#if defined MPU9150 || defined MPU9250
static struct platform_data_s compass_pdata = {
#if 1
.orientation = { 1, 0, 0,
0, 1, 0,
0, 0, -1}
#else
.orientation = { 1, 0, 0,
0, -1, 0,
0, 0, -1}
#endif
};
#define COMPASS_ENABLED 1
#elif defined AK8975_SECONDARY
static struct platform_data_s compass_pdata = {
.orientation = {-1, 0, 0,
0, 1, 0,
0, 0,-1}
};
#define COMPASS_ENABLED 1
#elif defined AK8963_SECONDARY
static struct platform_data_s compass_pdata = {
.orientation = {-1, 0, 0,
0,-1, 0,
0, 0, 1}
};
#define COMPASS_ENABLED 1
#endif
#endif
void ImuRawDataSend(ACCELSENSOR_DATA &AccData, GYROSENSOR_DATA GyroData, MAGSENSOR_DATA &MagData);
void ImuQuatDataSend(long Quat[4]);
static void ImuDataChedHandler(void * p_event_data, uint16_t event_size)
{
ACCELSENSOR_DATA accdata;
GYROSENSOR_DATA gyrodata;
MAGSENSOR_DATA magdata;
IMU_QUAT quat;
long q[4];
s_Imu.Read(accdata);
s_Imu.Read(gyrodata);
s_Imu.Read(magdata);
ImuRawDataSend(accdata, gyrodata, magdata);
s_Imu.Read(quat);
//q[0] = ((float)quat.Q[0] / 32768.0) * (float)(1<<30);
//q[1] = ((float)quat.Q[1] / 32768.0) * (float)(1<<30);
//q[2] = ((float)quat.Q[2] / 32768.0) * (float)(1<<30);
//q[3] = ((float)quat.Q[3] / 32768.0) * (float)(1<<30);
//q[0] = quat.Q[0] << 15;
//q[1] = quat.Q[1] << 15;
//q[2] = quat.Q[2] << 15;
//q[3] = quat.Q[3] << 15;
q[0] = quat.Q[0] * (1 << 30);
q[1] = quat.Q[1] * (1 << 30);
q[2] = quat.Q[2] * (1 << 30);
q[3] = quat.Q[3] * (1 << 30);
//printf("Quat %d: %d %d %d %d\r\n", quat.Timestamp, q[0], q[1], q[2], q[3]);
ImuQuatDataSend(q);
}
static void ImuEvtHandler(Device * const pDev, DEV_EVT Evt)
{
switch (Evt)
{
case DEV_EVT_DATA_RDY:
app_sched_event_put(NULL, 0, ImuDataChedHandler);
//ImuDataChedHandler(NULL, 0);
//g_MotSensor.Read(accdata);
break;
}
}
void MPU9250IntHandler(int IntNo)
{
s_Imu.IntHandler();
return;
}
void mpulib_data_handler_cb()
{
}
void MPU9250EnableFeature(uint32_t Feature)
{
s_MotionFeature |= Feature;
}
static void mpulib_tap_cb(unsigned char direction, unsigned char count)
{
// ble_tms_tap_t tap;
// tap.dir = direction;
// tap.cnt = count;
// BleSrvcCharNotify(GetImuSrvcInstance(), 2, (uint8_t*)&tap, sizeof(ble_tms_tap_t));
/* if (m_motion.features & DRV_MOTION_FEATURE_MASK_TAP)
{
drv_motion_evt_t evt = DRV_MOTION_EVT_TAP;
uint8_t data[2] = {direction, count};
m_motion.evt_handler(&evt, data, sizeof(data));
}
*/
#ifdef MOTION_DEBUG
switch (direction)
{
case TAP_X_UP:
NRF_LOG_DEBUG("drv_motion: tap x+ ");
break;
case TAP_X_DOWN:
NRF_LOG_DEBUG("drv_motion: tap x- ");
break;
case TAP_Y_UP:
NRF_LOG_DEBUG("drv_motion: tap y+ ");
break;
case TAP_Y_DOWN:
NRF_LOG_DEBUG("drv_motion: tap y- ");
break;
case TAP_Z_UP:
NRF_LOG_DEBUG("drv_motion: tap z+ ");
break;
case TAP_Z_DOWN:
NRF_LOG_DEBUG("drv_motion: tap z- ");
break;
default:
return;
}
NRF_LOG_DEBUG("x%d\r\n", count);
#endif
}
static void mpulib_orient_cb(unsigned char orientation)
{
BleSrvcCharNotify(GetImuSrvcInstance(), 2, &orientation, 1);
/* if (m_motion.features & DRV_MOTION_FEATURE_MASK_ORIENTATION)
{
drv_motion_evt_t evt = DRV_MOTION_EVT_ORIENTATION;
m_motion.evt_handler(&evt, &orientation, 1);
}
*/
#ifdef MOTION_DEBUG
switch (orientation)
{
case ANDROID_ORIENT_PORTRAIT:
NRF_LOG_DEBUG("Portrait\r\n");
break;
case ANDROID_ORIENT_LANDSCAPE:
NRF_LOG_DEBUG("Landscape\r\n");
break;
case ANDROID_ORIENT_REVERSE_PORTRAIT:
NRF_LOG_DEBUG("Reverse Portrait\r\n");
break;
case ANDROID_ORIENT_REVERSE_LANDSCAPE:
NRF_LOG_DEBUG("Reverse Landscape\r\n");
break;
default:
return;
}
#endif
}
SPI *g_pSpi = NULL;
bool MPU9250Init(DeviceIntrf * const pIntrF, Timer * const pTimer)
{
g_pSpi = (SPI*)pIntrF;
s_pTimer = pTimer;
bool res = g_Mpu9250.Init(s_AccelCfg, pIntrF, pTimer);
if (res == false)
return res;
g_Mpu9250.Init(s_GyroCfg, NULL);
g_Mpu9250.Init(s_MagCfg, NULL);
IOPinConfig(BLUEIO_TAG_EVIM_IMU_INT_PORT, BLUEIO_TAG_EVIM_IMU_INT_PIN, BLUEIO_TAG_EVIM_IMU_INT_PINOP,
IOPINDIR_INPUT, IOPINRES_PULLUP, IOPINTYPE_NORMAL);
IOPinEnableInterrupt(BLUEIO_TAG_EVIM_IMU_INT_NO, 6, BLUEIO_TAG_EVIM_IMU_INT_PORT,
BLUEIO_TAG_EVIM_IMU_INT_PIN, IOPINSENSE_LOW_TRANSITION,
MPU9250IntHandler);
// g_Mpu9250.Enable();
#if 0
while (1)
{
long l[3];
g_Mpu9250.UpdateData();
ACCELSENSOR_DATA accdata;
g_Mpu9250.Read(accdata);
l[0] = accdata.X;
l[1] = accdata.Y;
l[2] = accdata.Z;
inv_build_accel(l, 0, accdata.Timestamp);
}
#endif
s_Imu.Init(s_ImuCfg, &g_Mpu9250, &g_Mpu9250, &g_Mpu9250);
s_Imu.SetAxisAlignmentMatrix(g_AlignMatrix);
s_Imu.Quaternion(true, 6);
//s_Imu.Compass(true);
return true;
}
int Mpu9250AuxRead(uint8_t DevAddr, uint8_t *pCmdAddr, int CmdAddrLen, uint8_t *pBuff, int BuffLen)
{
int retval = 0;
uint8_t regaddr;
uint8_t d[8];
d[0] = MPU9250_AG_I2C_SLV0_ADDR;
d[1] = DevAddr | MPU9250_AG_I2C_SLV0_ADDR_I2C_SLVO_RD;
d[2] = *pCmdAddr;
while (BuffLen > 0)
{
int cnt = min(15, BuffLen);
d[3] = MPU9250_AG_I2C_SLV0_CTRL_I2C_SLV0_EN |cnt;
g_pSpi->Write(0, d, 4, NULL, 0);
// Delay require for transfer to complete
usDelay(300 + (cnt << 4));
regaddr = MPU9250_AG_EXT_SENS_DATA_00;
cnt = g_pSpi->Read(0, ®addr, 1, pBuff, cnt);
if (cnt <=0)
break;
pBuff += cnt;
BuffLen -= cnt;
retval += cnt;
}
return retval;
}
int Mpu9250AuxWrite(uint8_t DevAddr, uint8_t *pCmdAddr, int CmdAddrLen, uint8_t *pData, int DataLen)
{
int retval = 0;
uint8_t regaddr;
uint8_t d[8];
d[0] = MPU9250_AG_I2C_SLV0_ADDR;
d[1] = DevAddr;
d[2] = *pCmdAddr;
d[3] = MPU9250_AG_I2C_SLV0_CTRL_I2C_SLV0_EN;
while (DataLen > 0)
{
regaddr = MPU9250_AG_I2C_SLV0_DO;
g_pSpi->Write(0, ®addr, 1, pData, 1);
g_pSpi->Write(0, d, 4, NULL, 0);
d[2]++;
pData++;
DataLen--;
retval++;
}
return retval;
}
/**@brief Function for writing to a MPU-9250 register.
*
* @param[in] slave_addr Slave address on the TWI bus.
* @param[in] reg_addr Register address to write.
* @param[in] length Length of the data to write.
* @param[in] p_data Pointer to the data to write.
*
* @retval 0 if success. Else -1.
*/
int drv_mpu9250_write(unsigned char slave_addr, unsigned char reg_addr, unsigned char length, unsigned char const * p_data)
{
if (slave_addr != MPU9250_I2C_DEV_ADDR0 && slave_addr != MPU9250_I2C_DEV_ADDR1)
{
return Mpu9250AuxWrite(slave_addr, ®_addr, 1, (uint8_t*)p_data, length) <= 0;
}
/* else
{
reg_addr &= 0x7F;
return g_pSpi->Write(0, ®_addr, 1, (uint8_t*)p_data, length) <= 0;
}*/
return g_Mpu9250.Write(®_addr, 1, (uint8_t*)p_data, length) <= 0;
}
/**@brief Function for reading a MPU-9250 register.
*
* @param[in] slave_addr Slave address on the TWI bus.
* @param[in] reg_addr Register address to read.
* @param[in] length Length of the data to read.
* @param[out] p_data Pointer to where the data should be stored.
*
* @retval 0 if success. Else -1.
*/
int drv_mpu9250_read(unsigned char slave_addr, unsigned char reg_addr, unsigned char length, unsigned char * p_data)
{
if (slave_addr != MPU9250_I2C_DEV_ADDR0 && slave_addr != MPU9250_I2C_DEV_ADDR1)
{
return Mpu9250AuxRead(slave_addr, ®_addr, 1, (uint8_t*)p_data, length) <= 0;
}
/* else
{
reg_addr |= 0x80;
return g_pSpi->Read(0, ®_addr, 1, p_data, length) <= 0;
}*/
return g_Mpu9250.Read(®_addr, 1, p_data, length) <= 0;
}
/**@brief Function for getting a timestamp in milliseconds.
*
* @param[out] p_count Pointer to the timestamp.
*
* @retval 0 if success. Else -1.
*/
int drv_mpu9250_ms_get(unsigned long * p_count)
{
*p_count = s_pTimer->uSecond() / 1000;
return 0;
}
/**@brief Function for enabling and registering the MPU-9250 interrupt callback.
*
* @param[in] p_int_param Pointer to the interrupt parameter structure.
*
* @retval 0 if success. Else -1.
*/
int drv_mpu9250_int_register(struct int_param_s * p_int_param)
{
printf("drv_mpu9250_int_register\r\n");
IOPinConfig(BLUEIO_TAG_EVIM_IMU_INT_PORT, BLUEIO_TAG_EVIM_IMU_INT_PIN, BLUEIO_TAG_EVIM_IMU_INT_PINOP,
IOPINDIR_INPUT, IOPINRES_PULLDOWN, IOPINTYPE_NORMAL);
IOPinEnableInterrupt(BLUEIO_TAG_EVIM_IMU_INT_NO, 6, BLUEIO_TAG_EVIM_IMU_INT_PORT,
BLUEIO_TAG_EVIM_IMU_INT_PIN, IOPINSENSE_LOW_TRANSITION,
MPU9250IntHandler);
return 0;
}
| 11,359 | 5,337 |
/**
* 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 "Encoder.hh"
#include "Zigzag.hh"
#include <boost/array.hpp>
#include <boost/make_shared.hpp>
namespace avro {
using boost::make_shared;
using boost::shared_ptr;
class BinaryEncoder : public Encoder {
StreamWriter out_;
void init(OutputStream& os);
void flush();
void encodeNull();
void encodeBool(bool b);
void encodeInt(int32_t i);
void encodeLong(int64_t l);
void encodeFloat(float f);
void encodeDouble(double d);
void encodeString(const std::string& s);
void encodeBytes(const uint8_t *bytes, size_t len);
void encodeFixed(const uint8_t *bytes, size_t len);
void encodeEnum(size_t e);
void arrayStart();
void arrayEnd();
void mapStart();
void mapEnd();
void setItemCount(size_t count);
void startItem();
void encodeUnionIndex(size_t e);
void doEncodeLong(int64_t l);
};
EncoderPtr binaryEncoder()
{
return make_shared<BinaryEncoder>();
}
void BinaryEncoder::init(OutputStream& os)
{
out_.reset(os);
}
void BinaryEncoder::flush()
{
out_.flush();
}
void BinaryEncoder::encodeNull()
{
}
void BinaryEncoder::encodeBool(bool b)
{
out_.write(b ? 1 : 0);
}
void BinaryEncoder::encodeInt(int32_t i)
{
doEncodeLong(i);
}
void BinaryEncoder::encodeLong(int64_t l)
{
doEncodeLong(l);
}
void BinaryEncoder::encodeFloat(float f)
{
const uint8_t* p = reinterpret_cast<const uint8_t*>(&f);
out_.writeBytes(p, sizeof(float));
}
void BinaryEncoder::encodeDouble(double d)
{
const uint8_t* p = reinterpret_cast<const uint8_t*>(&d);
out_.writeBytes(p, sizeof(double));
}
void BinaryEncoder::encodeString(const std::string& s)
{
doEncodeLong(s.size());
out_.writeBytes(reinterpret_cast<const uint8_t*>(s.c_str()), s.size());
}
void BinaryEncoder::encodeBytes(const uint8_t *bytes, size_t len)
{
doEncodeLong(len);
out_.writeBytes(bytes, len);
}
void BinaryEncoder::encodeFixed(const uint8_t *bytes, size_t len)
{
out_.writeBytes(bytes, len);
}
void BinaryEncoder::encodeEnum(size_t e)
{
doEncodeLong(e);
}
void BinaryEncoder::arrayStart()
{
}
void BinaryEncoder::arrayEnd()
{
doEncodeLong(0);
}
void BinaryEncoder::mapStart()
{
}
void BinaryEncoder::mapEnd()
{
doEncodeLong(0);
}
void BinaryEncoder::setItemCount(size_t count)
{
if (count == 0) {
throw Exception("Count cannot be zero");
}
doEncodeLong(count);
}
void BinaryEncoder::startItem()
{
}
void BinaryEncoder::encodeUnionIndex(size_t e)
{
doEncodeLong(e);
}
void BinaryEncoder::doEncodeLong(int64_t l)
{
boost::array<uint8_t, 10> bytes;
size_t size = encodeInt64(l, bytes);
out_.writeBytes(bytes.data(), size);
}
} // namespace avro
| 3,514 | 1,210 |
/*
Copyright 2016 Mitchell Young
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#pragma once
#include <array>
#include <iosfwd>
#include <vector>
#include "util/global_config.hpp"
#include "util/pugifwd.hpp"
#include "util/rng_lcg.hpp"
#include "core/core_mesh.hpp"
#include "core/geometry/geom.hpp"
#include "core/xs_mesh.hpp"
#include "particle.hpp"
namespace mocc {
namespace mc {
/**
* A FissionBank stores a sequence of fission sites. Nothing fancy
*/
class FissionBank {
public:
FissionBank(const CoreMesh &mesh);
/**
* \brief Construct a FissionBank by uniformly sampling fission sites.
*
* \param input XML node containing bounds of a 3-D box within which to
* sample initial fission sites
* \param n the number of initial sites to sample
* \param mesh the \ref CoreMesh to use for initial sampling
* \param xs_mesh the \ref XSMesh to use for initial sampling
* \param rng a reference to the random number generator to be used for
* sampling initial fission sites.
*
* This constructor initializes a \ref FissionBank using input specified in
* an XML node.
*/
FissionBank(const pugi::xml_node &input, int n, const CoreMesh &mesh,
const XSMesh &xs_mesh, RNG_LCG &rng);
auto begin()
{
return sites_.begin();
}
const auto begin() const
{
return sites_.cbegin();
}
auto end()
{
return sites_.end();
}
const auto end() const
{
return sites_.cend();
}
int size() const
{
return sites_.size();
}
/**
* \brief Add a new fission site to the \ref FissionBank
*
* \param p a \ref Point3 for the location of the fission site
*
* This method adds a new fission site to the fission bank, and makes a
* contribution to the total number of neutrons that were generated into
* the bank.
*/
void push_back(Particle &p)
{
#pragma omp critical
{
sites_.push_back(p);
total_fission_ += p.weight;
}
return;
}
/**
* \brief Return the Shannon entropy of the fission bank.
*
* This is used to estimate the change in the spatial distribution of
* fission sites from generation to generation. Observing little
* variation in this metric throughout the active cycles lends some
* confidence that the fission source distribution was well converged
* before beginning active cycles.
*/
real_t shannon_entropy() const;
/**
* \brief Swap contents with another \ref FissionBank
*
* \param other the other \ref FissionBank to swap with
*/
void swap(FissionBank &other);
const auto &operator[](unsigned i) const
{
return sites_[i];
}
/**
* \brief Clear the \ref FissionBank of all fission sites
*/
void clear()
{
#pragma omp single
{
sites_.clear();
total_fission_ = 0.0;
}
}
void resize(unsigned int n, RNG_LCG &rng);
real_t total_fission() const
{
return total_fission_;
}
friend std::ostream &operator<<(std::ostream &os, const FissionBank &bank);
private:
const CoreMesh &mesh_;
std::vector<Particle> sites_;
real_t total_fission_;
};
} // namespace mc
} // namespace mocc
| 3,881 | 1,179 |
#if defined _WIN32 || defined _WIN64
#include <Windows.h>
#define DLLEXPORT __declspec(dllexport)
#else
#include <stdio.h>
#endif
#ifndef DLLEXPORT
#define DLLEXPORT
#endif
DLLEXPORT void ExampleLibraryFunction()
{
#if defined _WIN32 || defined _WIN64
MessageBox(NULL, TEXT("Hello world!"), NULL, MB_OK);
#else
printf("Hello World");
#endif
} | 366 | 141 |
#include <iostream>
int main()
{
float x;
int n;
std::cout << "Podaj x i n: ";
std::cin >> x >> n;
switch (n)
{
case 1:
std::cout << "y = " << sqrt(2 * x);
break;
case 2:
std::cout << "y = " << (x * x) - 5;
break;
case 3:
std::cout << "y = " << cos(x) + 1;
break;
default:
std::cout << "y = " << 1;
}
return 0;
} | 369 | 176 |
/*
* libreoj2245
*
* LCT 维护最大值。
* 首先把边按 a 权值排序,从小到大加入,那么所需的 a 就是当前边的 a 。
* 然后用 LCT 维护从 1 到 n 的路径的 b 权值的最大值。
* 由于维护的是边权,我们要给边特别地开点,然后把本来应该相连的点连到两边。
* 动态维护一棵最小生成树,每次加入一条从 u 到 v 的路径的时候就把原来的
* u, v 之间的路径拉出来查询一下路径上的最大值,如果比当前的边要大,
* 就把代表这条边的点从路径里拿出来,再把新边放进去。
* */
#include <cstdio>
#include <algorithm>
#include <iostream>
const size_t Size = 5e4 + 5;
const int Inf = -1u >> 1;
template<class T> T max(const T &a, const T &b) {
return a > b? a : b;
}
template<class T> T min(const T &a, const T &b) {
return a < b? a : b;
}
template<class T> bool chkmin(T &a, const T &b) {
return a > b? a = b, 1 : 0;
}
template<class T> bool chkmax(T &a, const T &b) {
return a <b? a = b, 1 : 0;
}
struct IM { template<class T> IM& operator>>(T &a) {
a = 0; char c = getchar(); bool n = false;
for(;!isdigit(c); c = getchar()) if(c == '-') n = 1;
for(; isdigit(c); c = getchar()) a = a * 10 - 48 + c;
if(n) a = -a;
return *this;
} } getInt;
struct UnionFindSet {
int fa[Size * 4];
void init(int x) {
for(int i = 1; i <= x; ++i) fa[i] = i;
}
int find(int x) {
return x == fa[x]? x : fa[x] = find(fa[x]);
}
int& operator[](const int &x) {
return fa[x];
}
} set;
struct Edge {
int u, v, a, b;
} e[Size * 2];
bool operator<(const Edge &a, const Edge &b) {
return a.a < b.a;
}
struct Node {
int val, id;
Node *fa, *ch[2], *mx;
bool rev;
bool isroot() {
return fa? (fa->ch[0] != this && fa->ch[1] != this) : true;
}
void pushup() {
mx = this;
if(ch[0] && ch[0]->mx->val > mx->val) mx = ch[0]->mx;
if(ch[1] && ch[1]->mx->val > mx->val) mx = ch[1]->mx;
}
void reverse() {
rev ^= 1;
std::swap(ch[0], ch[1]);
}
void pushdown() {
if(rev) {
if(ch[0]) ch[0]->reverse();
if(ch[1]) ch[1]->reverse();
rev = 0;
}
}
bool operator!() {
return fa->ch[1] == this;
}
} nd[Size * 4];
void rotate(Node *x) {
Node *y = x->fa;
bool d = !*x; // must take care here, !*x IS NOT !x
if(!y->isroot())
y->fa->ch[!*y] = x;
x->fa = y->fa;
y->fa = x;
y->ch[d] = x->ch[!d];
x->ch[!d] = y;
if(y->ch[d])
y->ch[d]->fa = y;
y->pushup();
x->pushup();
}
void push(Node *x) {
if(!x->isroot()) push(x->fa);
x->pushdown();
}
void splay(Node *x) {
push(x);
for(Node *y = x->fa; !x->isroot(); y = x->fa) {
if(!y->isroot()) rotate(!*x == !*y? y : x);
rotate(x);
}
}
void access(Node *x) {
for(Node *y = NULL; x; x = (y = x)->fa) {
splay(x);
x->ch[1] = y;
x->pushup();
}
}
void makeroot(Node *x) {
access(x);
splay(x);
x->reverse();
}
Node* findroot(Node *x) {
access(x);
splay(x);
while(x->ch[0]) x = x->ch[0];
return x;
}
void link(Node *x, Node *y) {
makeroot(x);
if(findroot(y) != x) x->fa = y;
}
void cut(Node *x, Node *y) {
makeroot(x);
if(findroot(y) == x && x->fa == y && x->ch[1] == NULL) {
x->fa = y->ch[0] = NULL;
y->pushup();
}
}
void split(Node *x, Node *y) {
makeroot(x);
access(y);
splay(y);
}
int query(int x, int y) {
split(&nd[x], &nd[y]);
return nd[y].mx->val;
}
int n, m;
int ans = Inf;
int main() {
getInt >> n >> m;
set.init(n);
for(int i = 1; i <= m; ++i) {
getInt >> e[i].u >> e[i].v >> e[i].a >> e[i].b;
}
std::sort(e + 1, e + 1 + m);
for(int i = 1, u, v, a, b; i <= m; ++i) {
u = e[i].u, v = e[i].v, a = e[i].a, b = e[i].b;
if(set.find(u) == set.find(v)) {
split(&nd[u], &nd[v]);
Node *x = nd[v].mx;
if(x->val > b) {
cut(x, &nd[e[x->id].u]);
cut(x, &nd[e[x->id].v]);
} else {
// if(set.find(1) == set.find(n)) chkmin(ans, a + query(1, n));
continue;
}
} else {
set[set[u]] = set[v];
}
nd[n + i].val = b;
nd[n + i].mx = &nd[n + 1];
nd[n + i].id = i;
link(&nd[u], &nd[n + i]);
link(&nd[v], &nd[n + i]);
if(set.find(1) == set.find(n)) chkmin(ans, a + query(1, n));
}
std::printf("%d\n", ans == Inf? -1 : ans);
return 0;
}
| 4,355 | 2,109 |
#include "geoclaw.h"
#include "H20utilities/h20utilities.h"
//*********************************************************************************
// GeoClaw starts here
//*********************************************************************************
geoclaw::geoclaw(int flag, QStringList data)
{
// If needed to reach the topo information
if(flag == 1)
{
QString topofilepath = data[0];
QString destination = data[1];
readtopo();
}
// Get total number of timesteps
if(flag == 2)
{
// data[0] - file path to working directory
int totaltimesteps = gclawtotaltime(data[0]);
}
}
//*********************************************************************************
// Read the Geoclaw file
//*********************************************************************************
void geoclaw::readtopo()
{
}
//*********************************************************************************
// Get total timesteps in the Geoclaw file
//*********************************************************************************
int geoclaw::gclawtotaltime(QString filepath)
{
// Local temporary variables
int ii = 1;
int checkt = 0;
int checkq = 0;
do {
// Get filepaths for t-files
QString tfilename = getfilename(filepath,ii,1);
// Get filepaths for q-files
QString qfilename = getfilename(filepath,ii,2);
// Check for existence of files
H20Utilities utility;
checkt = utility.fileexistance(tfilename.toStdString());
checkq = utility.fileexistance(qfilename.toStdString());
// If both files exist, use up to that time step
// Else produce an error accordingly
if ((checkt == 0) && (checkq == 0)) ii = ii + 1;
else ii = ii - 1;
} while((checkt == 0) && (checkq == 0));
// Return the flag
int totaltimesteps =ii;
return totaltimesteps;
}
//*********************************************************************************
// Get filename of the GeoClaw file
//*********************************************************************************
QString geoclaw::getfilename(QString path, int timestep, int flag)
{
QString fullpath;
if(flag == 1) //For t-files
{
if((timestep >= 0) && (timestep < 10)) fullpath = path + "/fort.t000" + QString::number(timestep);
else if((timestep > 9) && (timestep < 100)) fullpath = path + "/fort.t00" + QString::number(timestep);
else if((timestep > 99) && (timestep < 1000)) fullpath = path + "/fort.t0" + QString::number(timestep);
else if((timestep > 999) && (timestep < 10000)) fullpath = path + "/fort.t" + QString::number(timestep);
}
else if(flag == 2)
{
if((timestep >= 0) && (timestep < 10)) fullpath = path + "/fort.q000" + QString::number(timestep);
else if((timestep > 9) && (timestep < 100)) fullpath = path + "/fort.q00" + QString::number(timestep);
else if((timestep > 99) && (timestep < 1000)) fullpath = path + "/fort.q0" + QString::number(timestep);
else if((timestep > 999) && (timestep < 10000)) fullpath = path + "/fort.q" + QString::number(timestep);
}
return fullpath;
}
| 3,224 | 1,005 |
// ==========================================================================
// SeqAn - The Library for Sequence Analysis
// ==========================================================================
// Copyright (c) 2006-2016, Knut Reinert, FU Berlin
// Copyright (c) 2013 NVIDIA Corporation
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of Knut Reinert or the FU Berlin 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 KNUT REINERT OR THE FU BERLIN BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
//
// ==========================================================================
// Author: Enrico Siragusa <enrico.siragusa@fu-berlin.de>
// ==========================================================================
#include <seqan/basic.h>
#include <seqan/reduced_aminoacid.h>
#include <seqan/index.h>
#include "test_index_helpers.h"
using namespace seqan;
// ==========================================================================
// Metafunctions
// ==========================================================================
// ----------------------------------------------------------------------------
// Metafunction Size
// ----------------------------------------------------------------------------
//namespace seqan {
//template <typename TValue>
//struct Size<RankDictionary<TValue, Levels<unsigned> > >
//{
// typedef unsigned Type;
//};
//}
// ==========================================================================
// Types
// ==========================================================================
// --------------------------------------------------------------------------
// RankDictionary Types
// --------------------------------------------------------------------------
typedef SimpleType<unsigned char, ReducedAminoAcid_<Murphy10> > ReducedMurphy10;
typedef Levels<void, LevelsPrefixRDConfig<uint32_t, Alloc<>, 1, 1> > Prefix1Level;
typedef Levels<void, LevelsPrefixRDConfig<uint32_t, Alloc<>, 2, 2> > Prefix2Level;
typedef Levels<void, LevelsPrefixRDConfig<uint32_t, Alloc<>, 3, 3> > Prefix3Level;
typedef Levels<void, LevelsRDConfig<uint32_t, Alloc<>, 1, 1> > Default1Level;
typedef Levels<void, LevelsRDConfig<uint32_t, Alloc<>, 2, 2> > Default2Level;
typedef Levels<void, LevelsRDConfig<uint32_t, Alloc<>, 3, 3> > Default3Level;
typedef
TagList<RankDictionary<bool, Prefix1Level>,
TagList<RankDictionary<Dna, Prefix1Level>,
TagList<RankDictionary<Dna5Q, Prefix1Level>,
TagList<RankDictionary<ReducedMurphy10, Prefix1Level>,
TagList<RankDictionary<AminoAcid, Prefix1Level>,
TagList<RankDictionary<bool, Prefix2Level>,
TagList<RankDictionary<Dna, Prefix2Level>,
TagList<RankDictionary<Dna5Q, Prefix2Level>,
TagList<RankDictionary<ReducedMurphy10, Prefix2Level>,
TagList<RankDictionary<AminoAcid, Prefix2Level>,
TagList<RankDictionary<bool, Prefix3Level>,
TagList<RankDictionary<Dna, Prefix3Level>,
TagList<RankDictionary<Dna5Q, Prefix3Level>,
TagList<RankDictionary<ReducedMurphy10, Prefix3Level>,
TagList<RankDictionary<AminoAcid, Prefix3Level>,
TagList<RankDictionary<bool, WaveletTree<> >,
TagList<RankDictionary<Dna, WaveletTree<> >,
TagList<RankDictionary<Dna5Q, WaveletTree<> >,
TagList<RankDictionary<AminoAcid, WaveletTree<> >
> > > > > > > > > > > > > > > > > > >
RankDictionaryPrefixSumTypes;
typedef
TagList<RankDictionary<bool, Naive<> >,
TagList<RankDictionary<bool, Default1Level>,
TagList<RankDictionary<Dna, Default1Level>,
TagList<RankDictionary<Dna5Q, Default1Level>,
TagList<RankDictionary<ReducedMurphy10, Default1Level>,
TagList<RankDictionary<AminoAcid, Default1Level>,
TagList<RankDictionary<bool, Default2Level>,
TagList<RankDictionary<Dna, Default2Level>,
TagList<RankDictionary<Dna5Q, Default2Level>,
TagList<RankDictionary<ReducedMurphy10, Default2Level>,
TagList<RankDictionary<AminoAcid, Default2Level>,
TagList<RankDictionary<bool, Default3Level>,
TagList<RankDictionary<Dna, Default3Level>,
TagList<RankDictionary<Dna5Q, Default3Level>,
TagList<RankDictionary<ReducedMurphy10, Default3Level>,
TagList<RankDictionary<AminoAcid, Default3Level>,
RankDictionaryPrefixSumTypes
> > > > > > > > > > > > > > > >
RankDictionaryAllTypes;
// ==========================================================================
// Test Classes
// ==========================================================================
// --------------------------------------------------------------------------
// Class RankDictionaryTest
// --------------------------------------------------------------------------
template <typename TRankDictionary>
class RankDictionaryTest : public Test
{
public:
typedef TRankDictionary TRankDict;
typedef typename Value<TRankDict>::Type TValue;
typedef typename Size<TValue>::Type TValueSize;
typedef String<TValue> TText;
typedef typename Iterator<TText, Standard>::Type TTextIterator;
TValueSize alphabetSize;
TText text;
TTextIterator textBegin;
TTextIterator textEnd;
RankDictionaryTest() :
alphabetSize(ValueSize<TValue>::VALUE), text(), textBegin(), textEnd()
{}
void setUp()
{
generateText(text, 3947);
textBegin = begin(text, Standard());
textEnd = end(text, Standard());
}
};
template <typename TRankDictionary>
class RankDictionaryPrefixTest : public RankDictionaryTest<TRankDictionary> {};
SEQAN_TYPED_TEST_CASE(RankDictionaryTest, RankDictionaryAllTypes);
SEQAN_TYPED_TEST_CASE(RankDictionaryPrefixTest, RankDictionaryPrefixSumTypes);
// ==========================================================================
// Tests
// ==========================================================================
// ----------------------------------------------------------------------------
// Test RankDictionary()
// ----------------------------------------------------------------------------
SEQAN_TYPED_TEST(RankDictionaryTest, Constructor)
{
typename TestFixture::TRankDict dict(this->text);
}
// ----------------------------------------------------------------------------
// Test createRankDictionary()
// ----------------------------------------------------------------------------
SEQAN_TYPED_TEST(RankDictionaryTest, CreateRankDictionary)
{
typename TestFixture::TRankDict dict;
createRankDictionary(dict, this->text);
}
// ----------------------------------------------------------------------------
// Test clear() and empty()
// ----------------------------------------------------------------------------
SEQAN_TYPED_TEST(RankDictionaryTest, ClearEmpty)
{
typename TestFixture::TRankDict dict;
SEQAN_ASSERT(empty(dict));
createRankDictionary(dict, this->text);
SEQAN_ASSERT_NOT(empty(dict));
clear(dict);
SEQAN_ASSERT(empty(dict));
}
// ----------------------------------------------------------------------------
// Test getValue()
// ----------------------------------------------------------------------------
SEQAN_TYPED_TEST(RankDictionaryTest, GetValue)
{
typedef typename TestFixture::TTextIterator TTextIterator;
typename TestFixture::TRankDict dict(this->text);
for (TTextIterator textIt = this->textBegin; textIt != this->textEnd; ++textIt)
SEQAN_ASSERT_EQ(getValue(dict, (unsigned long)(textIt - this->textBegin)), value(textIt));
}
// ----------------------------------------------------------------------------
// Test getRank()
// ----------------------------------------------------------------------------
SEQAN_TYPED_TEST(RankDictionaryTest, GetRank)
{
typedef typename TestFixture::TValueSize TValueSize;
typedef typename TestFixture::TText TText;
typedef typename TestFixture::TTextIterator TTextIterator;
typedef typename Size<TText>::Type TTextSize;
typedef String<TTextSize> TPrefixSum;
typename TestFixture::TRankDict dict(this->text);
// The prefix sum is built while scanning the text.
TPrefixSum prefixSum;
resize(prefixSum, this->alphabetSize, 0);
// Scan the text.
for (TTextIterator textIt = this->textBegin; textIt != this->textEnd; ++textIt)
{
// Update the prefix sum.
prefixSum[ordValue(value(textIt))]++;
// Check the rank for all alphabet symbols.
for (TValueSize c = 0; c < this->alphabetSize; ++c)
SEQAN_ASSERT_EQ(getRank(dict, (unsigned long)(textIt - this->textBegin), c), prefixSum[c]);
}
}
SEQAN_TYPED_TEST(RankDictionaryPrefixTest, GetPrefixRank)
{
typedef typename TestFixture::TValueSize TValueSize;
typedef typename TestFixture::TText TText;
typedef typename TestFixture::TTextIterator TTextIterator;
typedef typename Size<TText>::Type TTextSize;
typedef String<TTextSize> TPrefixSum;
typename TestFixture::TRankDict dict(this->text);
// The prefix sum is built while scanning the text.
TPrefixSum prefixSum;
resize(prefixSum, this->alphabetSize, 0);
// Scan the text.
for (TTextIterator textIt = this->textBegin; textIt != this->textEnd; ++textIt)
{
// Update the prefix sum.
prefixSum[ordValue(value(textIt))]++;
// Check the rank for all alphabet symbols.
unsigned long smallerNaive = 0;
for (TValueSize c = 0; c < this->alphabetSize; ++c)
{
unsigned long smaller;
SEQAN_ASSERT_EQ(getRank(dict, (unsigned long)(textIt - this->textBegin), c, smaller), prefixSum[c]);
SEQAN_ASSERT_EQ(smaller, smallerNaive);
smallerNaive += prefixSum[c];
}
}
}
// ----------------------------------------------------------------------------
// Test setValue()
// ----------------------------------------------------------------------------
// NOTE(esiragusa): rename it as assignValue()
// ----------------------------------------------------------------------------
// Test length()
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// Test resize()
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// Test reserve()
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// Test open() and save()
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// Test Size<>
// ----------------------------------------------------------------------------
//SEQAN_DEFINE_TEST(test_rss_sizeof)
//{
// typedef Dna TAlphabet;
// typedef Alloc<unsigned> TTextSpec;
// typedef String<TAlphabet, TTextSpec> TText;
//
// typedef Levels<TAlphabet, unsigned> TRankDictionarySpec;
// typedef RankDictionary<TRankDictionarySpec> TRankDictionary;
//
// TRankSupport rs;
//
// std::cout << "sizeof(Block): " << sizeof(rs.block) << std::endl;
//
// std::cout << "bits(Block): " << BitsPerValue<TRankSupport::TBlock>::VALUE << std::endl;
// std::cout << "length(Block): " << length(rs.block) << std::endl;
// std::cout << "capacity(Block): " << capacity(rs.block) << std::endl;
// std::cout << std::endl;
//
// std::cout << "sizeof(SuperBlock): " << sizeof(rs.sblock) << std::endl;
// std::cout << "bits(SuperBlock): " << BitsPerValue<TRankSupport::TSuperBlock>::VALUE << std::endl;
// std::cout << "length(SuperBlock): " << length(rs.sblock) << std::endl;
// std::cout << "capacity(SuperBlock): " << capacity(rs.sblock) << std::endl;
// std::cout << std::endl;
//
// std::cout << "sizeof(RankSupport): " << sizeof(rs) << std::endl;
// std::cout << "bits(RankSupport): " << BitsPerValue<TRankSupport>::VALUE << std::endl;
// std::cout << std::endl;
//}
//SEQAN_DEFINE_TEST(test_rss_resize)
//{
// typedef Dna TAlphabet;
// typedef Alloc<unsigned> TTextSpec;
// typedef String<TAlphabet, TTextSpec> TText;
//
// typedef Levels<TAlphabet, unsigned> TRankDictionarySpec;
// typedef RankDictionary<TRankDictionarySpec> TRankDictionary;
//
//// TText text = "ACGTNACGTNACGTNACGTNA";
// TText text = "ACGTACGTACGTACGTACGTACGTACGTACGT";
//// TText text = "ACGTACGTACGTACGTACGTACGTACGTACGTCCCCCCCCCCCCCCC";
//
// TRankDictionary dict(text);
//// createRankDictionary(dict, text);
//
// std::cout << "Text: " << text << std::endl;
//// std::cout << "Block: " << rs.block << std::endl;
//
// for (unsigned i = 0; i < 10; i++)
// for (unsigned char c = 0; c < 4; c++)
// std::cout << "getRank(" << Dna(c) << ", " << i << "): " << getRank(dict, i, Dna(c)) << std::endl;
//
// std::cout << std::endl;
//}
// ==========================================================================
// Functions
// ==========================================================================
int main(int argc, char const ** argv)
{
TestSystem::init(argc, argv);
return TestSystem::runAll();
}
| 15,217 | 4,307 |
#pragma once
#include "AppConfig.hpp"
#include "EventEx.hpp"
#include "ScanGroups.hpp"
using namespace EventEx;
/** Defines all of the events in the application */
namespace events {
struct CapActive : public Event {
CapActive() : CapActive(0, 0, 0) {}
CapActive(uint16_t _baseline, uint16_t _measurement, uint8_t _settings) :
baseline(_baseline),
measurement(_measurement),
settings(_settings) {}
uint16_t baseline; // Initial zero level
uint16_t measurement; // Final voltage value
uint8_t settings; // Metadata about the sample; bit 0 indicates low gain.
};
struct CapOffsetCalibrationRequest : public Event {};
struct CapScan : public Event {
const uint16_t *measurements; // Size is N_HV507 * 64
};
struct CapGroups : public Event {
std::array<uint16_t, AppConfig::N_CAP_GROUPS> measurements;
ScanGroups<AppConfig::N_PINS, AppConfig::N_CAP_GROUPS> scanGroups;
};
struct ElectrodesUpdated : public Event {};
struct GpioControl : public Event {
uint8_t pin;
bool value;
bool outputEnable;
bool write;
std::function<void(uint8_t pin, bool value)> callback;
};
struct SetGain : public Event {
SetGain() : data{0} {}
uint8_t data[(AppConfig::N_PINS + 3) / 4];
uint8_t get_channel(uint8_t channel) {
uint32_t offset = channel / 4;
uint32_t shift = (channel % 4) * 2;
return (data[offset] >> shift) & 0x3;
}
void set_channel(uint8_t channel, uint8_t value) {
uint32_t offset = channel / 4;
uint32_t shift = (channel % 4) * 2;
if(offset < sizeof(data)/sizeof(data[0])) {
data[offset] &= ~(0x3 << shift);
data[offset] |= (value & 0x3) << shift;
}
}
};
struct SetElectrodes : public Event {
uint8_t groupID;
uint8_t setting;
uint8_t values[AppConfig::N_BYTES];
};
struct SetDutyCycle : public Event {
bool updateA;
bool updateB;
uint8_t dutyCycleA;
uint8_t dutyCycleB;
};
struct DutyCycleUpdated : public Event {
uint8_t dutyCycleA;
uint8_t dutyCycleB;
};
struct FeedbackCommand : public Event {
float target;
uint8_t mode;
uint8_t measureGroupsPMask;
uint8_t measureGroupsNMask;
uint8_t baseline;
};
struct HvRegulatorUpdate : public Event {
float voltage;
uint16_t vTargetOut;
};
struct SetParameter : public Event {
uint32_t paramIdx;
ConfigOptionValue paramValue;
// If set, this message is setting a param. If clear, this is requesting the current value.
uint8_t writeFlag;
std::function<void(const uint32_t &idx, const ConfigOptionValue ¶mValue)> callback;
};
struct SetPwm : public Event {
uint8_t channel;
uint16_t duty_cycle;
};
struct TemperatureMeasurement : public Event {
uint16_t measurements[AppConfig::N_TEMP_SENSOR];
};
// Partial update of the electrode calibration data
// Calibrations are sent via DataBlob messages, in chunks.
struct UpdateElectrodeCalibration : public Event {
uint16_t offset; // Offset of first byte to update
uint16_t length; // Number of bytes to copy
const uint8_t *data; // Source data to copy
};
} //namespace events | 3,176 | 1,081 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
// vim:cindent:ts=2:et:sw=2:
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "nsStyleConsts.h"
#include "nsPresContext.h"
#include "nsIImage.h"
#include "nsIFrame.h"
#include "nsPoint.h"
#include "nsRect.h"
#include "nsIViewManager.h"
#include "nsIPresShell.h"
#include "nsFrameManager.h"
#include "nsStyleContext.h"
#include "nsIScrollableView.h"
#include "nsLayoutAtoms.h"
#include "nsIDrawingSurface.h"
#include "nsTransform2D.h"
#include "nsIDeviceContext.h"
#include "nsIContent.h"
#include "nsHTMLAtoms.h"
#include "nsIDocument.h"
#include "nsIScrollableFrame.h"
#include "imgIRequest.h"
#include "imgIContainer.h"
#include "gfxIImageFrame.h"
#include "nsCSSRendering.h"
#include "nsCSSColorUtils.h"
#include "nsITheme.h"
#include "nsThemeConstants.h"
#include "nsIServiceManager.h"
#include "nsIDOMHTMLBodyElement.h"
#include "nsIDOMHTMLDocument.h"
#include "nsLayoutUtils.h"
#include "nsINameSpaceManager.h"
#define BORDER_FULL 0 //entire side
#define BORDER_INSIDE 1 //inside half
#define BORDER_OUTSIDE 2 //outside half
//thickness of dashed line relative to dotted line
#define DOT_LENGTH 1 //square
#define DASH_LENGTH 3 //3 times longer than dot
/** The following classes are used by CSSRendering for the rounded rect implementation */
#define MAXPATHSIZE 12
#define MAXPOLYPATHSIZE 1000
enum ePathTypes{
eOutside =0,
eInside,
eCalc,
eCalcRev
};
// To avoid storing this data on nsInlineFrame (bloat) and to avoid
// recalculating this for each frame in a continuation (perf), hold
// a cache of various coordinate information that we need in order
// to paint inline backgrounds.
struct InlineBackgroundData
{
InlineBackgroundData()
: mFrame(nsnull)
{
}
~InlineBackgroundData()
{
}
void Reset()
{
mBoundingBox.SetRect(0,0,0,0);
mContinuationPoint = mUnbrokenWidth = 0;
mFrame = nsnull;
}
nsRect GetContinuousRect(nsIFrame* aFrame)
{
SetFrame(aFrame);
// Assume background-origin: border and return a rect with offsets
// relative to (0,0). If we have a different background-origin,
// then our rect should be deflated appropriately by our caller.
return nsRect(-mContinuationPoint, 0, mUnbrokenWidth, mFrame->GetSize().height);
}
nsRect GetBoundingRect(nsIFrame* aFrame)
{
SetFrame(aFrame);
// Move the offsets relative to (0,0) which puts the bounding box into
// our coordinate system rather than our parent's. We do this by
// moving it the back distance from us to the bounding box.
// This also assumes background-origin: border, so our caller will
// need to deflate us if needed.
nsRect boundingBox(mBoundingBox);
nsPoint point = mFrame->GetPosition();
boundingBox.MoveBy(-point.x, -point.y);
return boundingBox;
}
protected:
nsIFrame* mFrame;
nscoord mContinuationPoint;
nscoord mUnbrokenWidth;
nsRect mBoundingBox;
void SetFrame(nsIFrame* aFrame)
{
NS_PRECONDITION(aFrame, "Need a frame");
nsIFrame *prevInFlow = aFrame->GetPrevInFlow();
if (!prevInFlow || mFrame != prevInFlow) {
// Ok, we've got the wrong frame. We have to start from scratch.
Reset();
Init(aFrame);
return;
}
// Get our last frame's size and add its width to our continuation
// point before we cache the new frame.
mContinuationPoint += mFrame->GetSize().width;
mFrame = aFrame;
}
void Init(nsIFrame* aFrame)
{
// Start with the previous flow frame as our continuation point
// is the total of the widths of the previous frames.
nsIFrame* inlineFrame = aFrame->GetPrevInFlow();
while (inlineFrame) {
nsRect rect = inlineFrame->GetRect();
mContinuationPoint += rect.width;
mUnbrokenWidth += rect.width;
mBoundingBox.UnionRect(mBoundingBox, rect);
inlineFrame = inlineFrame->GetPrevInFlow();
}
// Next add this frame and subsequent frames to the bounding box and
// unbroken width.
inlineFrame = aFrame;
while (inlineFrame) {
nsRect rect = inlineFrame->GetRect();
mUnbrokenWidth += rect.width;
mBoundingBox.UnionRect(mBoundingBox, rect);
inlineFrame = inlineFrame->GetNextInFlow();
}
mFrame = aFrame;
}
};
static InlineBackgroundData gInlineBGData;
static void GetPath(nsFloatPoint aPoints[],nsPoint aPolyPath[],PRInt32 *aCurIndex,ePathTypes aPathType,PRInt32 &aC1Index,float aFrac=0);
// FillRect or InvertRect depending on the renderingaInvert parameter
static void FillOrInvertRect(nsIRenderingContext& aRC,nscoord aX, nscoord aY, nscoord aWidth, nscoord aHeight, PRBool aInvert);
static void FillOrInvertRect(nsIRenderingContext& aRC,const nsRect& aRect, PRBool aInvert);
// Draw a line, skipping that portion which crosses aGap. aGap defines a rectangle gap
// This services fieldset legends and only works for coords defining horizontal lines.
void nsCSSRendering::DrawLine (nsIRenderingContext& aContext,
nscoord aX1, nscoord aY1, nscoord aX2, nscoord aY2,
nsRect* aGap)
{
if (nsnull == aGap) {
aContext.DrawLine(aX1, aY1, aX2, aY2);
} else {
nscoord x1 = (aX1 < aX2) ? aX1 : aX2;
nscoord x2 = (aX1 < aX2) ? aX2 : aX1;
nsPoint gapUpperRight(aGap->x + aGap->width, aGap->y);
nsPoint gapLowerRight(aGap->x + aGap->width, aGap->y + aGap->height);
if ((aGap->y <= aY1) && (gapLowerRight.y >= aY2)) {
if ((aGap->x > x1) && (aGap->x < x2)) {
aContext.DrawLine(x1, aY1, aGap->x, aY1);
}
if ((gapLowerRight.x > x1) && (gapLowerRight.x < x2)) {
aContext.DrawLine(gapUpperRight.x, aY2, x2, aY2);
}
} else {
aContext.DrawLine(aX1, aY1, aX2, aY2);
}
}
}
// Fill a polygon, skipping that portion which crosses aGap. aGap defines a rectangle gap
// This services fieldset legends and only works for points defining a horizontal rectangle
void nsCSSRendering::FillPolygon (nsIRenderingContext& aContext,
const nsPoint aPoints[],
PRInt32 aNumPoints,
nsRect* aGap)
{
#ifdef DEBUG
nsPenMode penMode;
if (NS_SUCCEEDED(aContext.GetPenMode(penMode)) &&
penMode == nsPenMode_kInvert) {
NS_WARNING( "Invert mode ignored in FillPolygon" );
}
#endif
if (nsnull == aGap) {
aContext.FillPolygon(aPoints, aNumPoints);
} else if (4 == aNumPoints) {
nsPoint gapUpperRight(aGap->x + aGap->width, aGap->y);
nsPoint gapLowerRight(aGap->x + aGap->width, aGap->y + aGap->height);
// sort the 4 points by x
nsPoint points[4];
for (PRInt32 pX = 0; pX < 4; pX++) {
points[pX] = aPoints[pX];
}
for (PRInt32 i = 0; i < 3; i++) {
for (PRInt32 j = i+1; j < 4; j++) {
if (points[j].x < points[i].x) {
nsPoint swap = points[i];
points[i] = points[j];
points[j] = swap;
}
}
}
nsPoint upperLeft = (points[0].y <= points[1].y) ? points[0] : points[1];
nsPoint lowerLeft = (points[0].y <= points[1].y) ? points[1] : points[0];
nsPoint upperRight = (points[2].y <= points[3].y) ? points[2] : points[3];
nsPoint lowerRight = (points[2].y <= points[3].y) ? points[3] : points[2];
if ((aGap->y <= upperLeft.y) && (gapLowerRight.y >= lowerRight.y)) {
if ((aGap->x > upperLeft.x) && (aGap->x < upperRight.x)) {
nsPoint leftRect[4];
leftRect[0] = upperLeft;
leftRect[1] = nsPoint(aGap->x, upperLeft.y);
leftRect[2] = nsPoint(aGap->x, lowerLeft.y);
leftRect[3] = lowerLeft;
aContext.FillPolygon(leftRect, 4);
}
if ((gapUpperRight.x > upperLeft.x) && (gapUpperRight.x < upperRight.x)) {
nsPoint rightRect[4];
rightRect[0] = nsPoint(gapUpperRight.x, upperRight.y);
rightRect[1] = upperRight;
rightRect[2] = lowerRight;
rightRect[3] = nsPoint(gapLowerRight.x, lowerRight.y);
aContext.FillPolygon(rightRect, 4);
}
} else {
aContext.FillPolygon(aPoints, aNumPoints);
}
}
}
/**
* Make a bevel color
*/
nscolor nsCSSRendering::MakeBevelColor(PRIntn whichSide, PRUint8 style,
nscolor aBackgroundColor,
nscolor aBorderColor,
PRBool aSpecialCase)
{
nscolor colors[2];
nscolor theColor;
// Given a background color and a border color
// calculate the color used for the shading
if(aSpecialCase)
NS_GetSpecial3DColors(colors, aBackgroundColor, aBorderColor);
else
NS_Get3DColors(colors, aBackgroundColor);
if ((style == NS_STYLE_BORDER_STYLE_BG_OUTSET) ||
(style == NS_STYLE_BORDER_STYLE_OUTSET) ||
(style == NS_STYLE_BORDER_STYLE_RIDGE)) {
// Flip colors for these three border styles
switch (whichSide) {
case NS_SIDE_BOTTOM: whichSide = NS_SIDE_TOP; break;
case NS_SIDE_RIGHT: whichSide = NS_SIDE_LEFT; break;
case NS_SIDE_TOP: whichSide = NS_SIDE_BOTTOM; break;
case NS_SIDE_LEFT: whichSide = NS_SIDE_RIGHT; break;
}
}
switch (whichSide) {
case NS_SIDE_BOTTOM:
theColor = colors[1];
break;
case NS_SIDE_RIGHT:
theColor = colors[1];
break;
case NS_SIDE_TOP:
theColor = colors[0];
break;
case NS_SIDE_LEFT:
default:
theColor = colors[0];
break;
}
return theColor;
}
// Maximum poly points in any of the polygons we generate below
#define MAX_POLY_POINTS 4
// a nifty helper function to create a polygon representing a
// particular side of a border. This helps localize code for figuring
// mitered edges. It is mainly used by the solid, inset, and outset
// styles.
//
// If the side can be represented as a line segment (because the thickness
// is one pixel), then a line with two endpoints is returned
PRIntn nsCSSRendering::MakeSide(nsPoint aPoints[],
nsIRenderingContext& aContext,
PRIntn whichSide,
const nsRect& outside, const nsRect& inside,
PRIntn aSkipSides,
PRIntn borderPart, float borderFrac,
nscoord twipsPerPixel)
{
float borderRest = 1.0f - borderFrac;
PRIntn np = 0;
nscoord thickness, outsideEdge, insideEdge, outsideTL, insideTL, outsideBR,
insideBR;
// Initialize the following six nscoord's:
// outsideEdge, insideEdge, outsideTL, insideTL, outsideBR, insideBR
// so that outsideEdge is the x or y of the outside edge, etc., and
// outsideTR is the y or x at the top or right end, etc., e.g.:
//
// outsideEdge --- ----------------------------------------
// \ /
// \ /
// \ /
// insideEdge ------- ----------------------------------
// | | | |
// outsideTL insideTL insideBR outsideBR
//
// if we don't want the bevel, we'll get rid of it later by setting
// outsideXX to insideXX
switch (whichSide) {
case NS_SIDE_TOP:
// the TL points are the left end; the BR points are the right end
outsideEdge = outside.y;
insideEdge = inside.y;
outsideTL = outside.x;
insideTL = inside.x;
insideBR = inside.XMost();
outsideBR = outside.XMost();
break;
case NS_SIDE_BOTTOM:
// the TL points are the left end; the BR points are the right end
outsideEdge = outside.YMost();
insideEdge = inside.YMost();
outsideTL = outside.x;
insideTL = inside.x;
insideBR = inside.XMost();
outsideBR = outside.XMost();
break;
case NS_SIDE_LEFT:
// the TL points are the top end; the BR points are the bottom end
outsideEdge = outside.x;
insideEdge = inside.x;
outsideTL = outside.y;
insideTL = inside.y;
insideBR = inside.YMost();
outsideBR = outside.YMost();
break;
default:
NS_ASSERTION(whichSide == NS_SIDE_RIGHT, "whichSide is not a valid side");
// the TL points are the top end; the BR points are the bottom end
outsideEdge = outside.XMost();
insideEdge = inside.XMost();
outsideTL = outside.y;
insideTL = inside.y;
insideBR = inside.YMost();
outsideBR = outside.YMost();
break;
}
// Don't draw the bevels if an adjacent side is skipped
if ( (whichSide == NS_SIDE_TOP) || (whichSide == NS_SIDE_BOTTOM) ) {
// a top or bottom side
if ((1<<NS_SIDE_LEFT) & aSkipSides) {
insideTL = outsideTL;
}
if ((1<<NS_SIDE_RIGHT) & aSkipSides) {
insideBR = outsideBR;
}
} else {
// a right or left side
if ((1<<NS_SIDE_TOP) & aSkipSides) {
insideTL = outsideTL;
}
if ((1<<NS_SIDE_BOTTOM) & aSkipSides) {
insideBR = outsideBR;
}
}
// move things around when only drawing part of the border
if (borderPart == BORDER_INSIDE) {
outsideEdge = nscoord(outsideEdge * borderFrac + insideEdge * borderRest);
outsideTL = nscoord(outsideTL * borderFrac + insideTL * borderRest);
outsideBR = nscoord(outsideBR * borderFrac + insideBR * borderRest);
} else if (borderPart == BORDER_OUTSIDE ) {
insideEdge = nscoord(insideEdge * borderFrac + outsideEdge * borderRest);
insideTL = nscoord(insideTL * borderFrac + outsideTL * borderRest);
insideBR = nscoord(insideBR * borderFrac + outsideBR * borderRest);
}
// Base our thickness check on the segment being less than a pixel and 1/2
twipsPerPixel += twipsPerPixel >> 2;
// find the thickness of the piece being drawn
if ((whichSide == NS_SIDE_TOP) || (whichSide == NS_SIDE_LEFT)) {
thickness = insideEdge - outsideEdge;
} else {
thickness = outsideEdge - insideEdge;
}
// if returning a line, do it along inside edge for bottom or right borders
// so that it's in the same place as it would be with polygons (why?)
// XXX The previous version of the code shortened the right border too.
if ( !((thickness >= twipsPerPixel) || (borderPart != BORDER_FULL)) &&
((whichSide == NS_SIDE_BOTTOM) || (whichSide == NS_SIDE_RIGHT))) {
outsideEdge = insideEdge;
}
// return the appropriate line or trapezoid
if ((whichSide == NS_SIDE_TOP) || (whichSide == NS_SIDE_BOTTOM)) {
// top and bottom borders
aPoints[np++].MoveTo(outsideTL,outsideEdge);
aPoints[np++].MoveTo(outsideBR,outsideEdge);
// XXX Making this condition only (thickness >= twipsPerPixel) will
// improve double borders and some cases of groove/ridge,
// but will cause problems with table borders. See last and third
// from last tests in test4.htm
// Doing it this way emulates the old behavior. It might be worth
// fixing.
if ((thickness >= twipsPerPixel) || (borderPart != BORDER_FULL) ) {
aPoints[np++].MoveTo(insideBR,insideEdge);
aPoints[np++].MoveTo(insideTL,insideEdge);
}
} else {
// right and left borders
// XXX Ditto above
if ((thickness >= twipsPerPixel) || (borderPart != BORDER_FULL) ) {
aPoints[np++].MoveTo(insideEdge,insideBR);
aPoints[np++].MoveTo(insideEdge,insideTL);
}
aPoints[np++].MoveTo(outsideEdge,outsideTL);
aPoints[np++].MoveTo(outsideEdge,outsideBR);
}
return np;
}
void nsCSSRendering::DrawSide(nsIRenderingContext& aContext,
PRIntn whichSide,
const PRUint8 borderStyle,
const nscolor borderColor,
const nscolor aBackgroundColor,
const nsRect& borderOutside,
const nsRect& borderInside,
PRIntn aSkipSides,
nscoord twipsPerPixel,
nsRect* aGap)
{
nsPoint theSide[MAX_POLY_POINTS];
nscolor theColor = borderColor;
PRUint8 theStyle = borderStyle;
PRInt32 np;
switch (theStyle) {
case NS_STYLE_BORDER_STYLE_NONE:
case NS_STYLE_BORDER_STYLE_HIDDEN:
return;
case NS_STYLE_BORDER_STYLE_DOTTED: //handled a special case elsewhere
case NS_STYLE_BORDER_STYLE_DASHED: //handled a special case elsewhere
break; // That was easy...
case NS_STYLE_BORDER_STYLE_GROOVE:
case NS_STYLE_BORDER_STYLE_RIDGE:
np = MakeSide (theSide, aContext, whichSide, borderOutside, borderInside, aSkipSides,
BORDER_INSIDE, 0.5f, twipsPerPixel);
aContext.SetColor ( MakeBevelColor (whichSide,
((theStyle == NS_STYLE_BORDER_STYLE_RIDGE) ?
NS_STYLE_BORDER_STYLE_GROOVE :
NS_STYLE_BORDER_STYLE_RIDGE),
aBackgroundColor, theColor,
PR_TRUE));
if (2 == np) {
//aContext.DrawLine (theSide[0].x, theSide[0].y, theSide[1].x, theSide[1].y);
DrawLine (aContext, theSide[0].x, theSide[0].y, theSide[1].x, theSide[1].y, aGap);
} else {
//aContext.FillPolygon (theSide, np);
FillPolygon (aContext, theSide, np, aGap);
}
np = MakeSide (theSide, aContext, whichSide, borderOutside, borderInside,aSkipSides,
BORDER_OUTSIDE, 0.5f, twipsPerPixel);
aContext.SetColor ( MakeBevelColor (whichSide, theStyle, aBackgroundColor,
theColor, PR_TRUE));
if (2 == np) {
//aContext.DrawLine (theSide[0].x, theSide[0].y, theSide[1].x, theSide[1].y);
DrawLine (aContext, theSide[0].x, theSide[0].y, theSide[1].x, theSide[1].y, aGap);
} else {
//aContext.FillPolygon (theSide, np);
FillPolygon (aContext, theSide, np, aGap);
}
break;
case NS_STYLE_BORDER_STYLE_AUTO:
case NS_STYLE_BORDER_STYLE_SOLID:
np = MakeSide (theSide, aContext, whichSide, borderOutside, borderInside,aSkipSides,
BORDER_FULL, 1.0f, twipsPerPixel);
aContext.SetColor (borderColor);
if (2 == np) {
//aContext.DrawLine (theSide[0].x, theSide[0].y, theSide[1].x, theSide[1].y);
DrawLine (aContext, theSide[0].x, theSide[0].y, theSide[1].x, theSide[1].y, aGap);
} else {
//aContext.FillPolygon (theSide, np);
FillPolygon (aContext, theSide, np, aGap);
}
break;
case NS_STYLE_BORDER_STYLE_BG_SOLID:
np = MakeSide (theSide, aContext, whichSide, borderOutside, borderInside, aSkipSides,
BORDER_FULL, 1.0f, twipsPerPixel);
nscolor colors[2];
NS_Get3DColors(colors, aBackgroundColor);
aContext.SetColor (colors[0]);
if (2 == np) {
DrawLine (aContext, theSide[0].x, theSide[0].y, theSide[1].x, theSide[1].y, aGap);
} else {
FillPolygon (aContext, theSide, np, aGap);
}
break;
case NS_STYLE_BORDER_STYLE_DOUBLE:
np = MakeSide (theSide, aContext, whichSide, borderOutside, borderInside,aSkipSides,
BORDER_INSIDE, 0.333333f, twipsPerPixel);
aContext.SetColor (borderColor);
if (2 == np) {
//aContext.DrawLine (theSide[0].x, theSide[0].y, theSide[1].x, theSide[1].y);
DrawLine (aContext, theSide[0].x, theSide[0].y, theSide[1].x, theSide[1].y, aGap);
} else {
//aContext.FillPolygon (theSide, np);
FillPolygon (aContext, theSide, np, aGap);
}
np = MakeSide (theSide, aContext, whichSide, borderOutside, borderInside,aSkipSides,
BORDER_OUTSIDE, 0.333333f, twipsPerPixel);
if (2 == np) {
//aContext.DrawLine (theSide[0].x, theSide[0].y, theSide[1].x, theSide[1].y);
DrawLine (aContext, theSide[0].x, theSide[0].y, theSide[1].x, theSide[1].y, aGap);
} else {
//aContext.FillPolygon (theSide, np);
FillPolygon (aContext, theSide, np, aGap);
}
break;
case NS_STYLE_BORDER_STYLE_BG_OUTSET:
case NS_STYLE_BORDER_STYLE_BG_INSET:
np = MakeSide (theSide, aContext, whichSide, borderOutside, borderInside,aSkipSides,
BORDER_FULL, 1.0f, twipsPerPixel);
aContext.SetColor ( MakeBevelColor (whichSide, theStyle, aBackgroundColor,
theColor, PR_FALSE));
if (2 == np) {
//aContext.DrawLine (theSide[0].x, theSide[0].y, theSide[1].x, theSide[1].y);
DrawLine (aContext, theSide[0].x, theSide[0].y, theSide[1].x, theSide[1].y, aGap);
} else {
//aContext.FillPolygon (theSide, np);
FillPolygon (aContext, theSide, np, aGap);
}
break;
case NS_STYLE_BORDER_STYLE_OUTSET:
case NS_STYLE_BORDER_STYLE_INSET:
np = MakeSide (theSide, aContext, whichSide, borderOutside, borderInside,aSkipSides,
BORDER_FULL, 1.0f, twipsPerPixel);
aContext.SetColor ( MakeBevelColor (whichSide, theStyle, aBackgroundColor,
theColor, PR_TRUE));
if (2 == np) {
//aContext.DrawLine (theSide[0].x, theSide[0].y, theSide[1].x, theSide[1].y);
DrawLine (aContext, theSide[0].x, theSide[0].y, theSide[1].x, theSide[1].y, aGap);
} else {
//aContext.FillPolygon (theSide, np);
FillPolygon (aContext, theSide, np, aGap);
}
break;
}
}
/**
* Draw a dotted/dashed sides of a box
*/
//XXX dashes which span more than two edges are not handled properly MMP
void nsCSSRendering::DrawDashedSides(PRIntn startSide,
nsIRenderingContext& aContext,
/* XXX unused */ const nsRect& aDirtyRect,
const PRUint8 borderStyles[],
const nscolor borderColors[],
const nsRect& borderOutside,
const nsRect& borderInside,
PRIntn aSkipSides,
/* XXX unused */ nsRect* aGap)
{
PRIntn dashLength;
nsRect dashRect, firstRect, currRect;
PRBool bSolid = PR_TRUE;
float over = 0.0f;
PRUint8 style = borderStyles[startSide];
PRBool skippedSide = PR_FALSE;
for (PRIntn whichSide = startSide; whichSide < 4; whichSide++) {
PRUint8 prevStyle = style;
style = borderStyles[whichSide];
if ((1<<whichSide) & aSkipSides) {
// Skipped side
skippedSide = PR_TRUE;
continue;
}
if ((style == NS_STYLE_BORDER_STYLE_DASHED) ||
(style == NS_STYLE_BORDER_STYLE_DOTTED))
{
if ((style != prevStyle) || skippedSide) {
//style discontinuity
over = 0.0f;
bSolid = PR_TRUE;
}
// XXX units for dash & dot?
if (style == NS_STYLE_BORDER_STYLE_DASHED) {
dashLength = DASH_LENGTH;
} else {
dashLength = DOT_LENGTH;
}
aContext.SetColor(borderColors[whichSide]);
switch (whichSide) {
case NS_SIDE_LEFT:
//XXX need to properly handle wrap around from last edge to first edge
//(this is the first edge) MMP
dashRect.width = borderInside.x - borderOutside.x;
dashRect.height = nscoord(dashRect.width * dashLength);
dashRect.x = borderOutside.x;
dashRect.y = borderInside.YMost() - dashRect.height;
if (over > 0.0f) {
firstRect.x = dashRect.x;
firstRect.width = dashRect.width;
firstRect.height = nscoord(dashRect.height * over);
firstRect.y = dashRect.y + (dashRect.height - firstRect.height);
over = 0.0f;
currRect = firstRect;
} else {
currRect = dashRect;
}
while (currRect.YMost() > borderInside.y) {
//clip if necessary
if (currRect.y < borderInside.y) {
over = float(borderInside.y - dashRect.y) /
float(dashRect.height);
currRect.height = currRect.height - (borderInside.y - currRect.y);
currRect.y = borderInside.y;
}
//draw if necessary
if (bSolid) {
aContext.FillRect(currRect);
}
//setup for next iteration
if (over == 0.0f) {
bSolid = PRBool(!bSolid);
}
dashRect.y = dashRect.y - currRect.height;
currRect = dashRect;
}
break;
case NS_SIDE_TOP:
//if we are continuing a solid rect, fill in the corner first
if (bSolid) {
aContext.FillRect(borderOutside.x, borderOutside.y,
borderInside.x - borderOutside.x,
borderInside.y - borderOutside.y);
}
dashRect.height = borderInside.y - borderOutside.y;
dashRect.width = dashRect.height * dashLength;
dashRect.x = borderInside.x;
dashRect.y = borderOutside.y;
if (over > 0.0f) {
firstRect.x = dashRect.x;
firstRect.y = dashRect.y;
firstRect.width = nscoord(dashRect.width * over);
firstRect.height = dashRect.height;
over = 0.0f;
currRect = firstRect;
} else {
currRect = dashRect;
}
while (currRect.x < borderInside.XMost()) {
//clip if necessary
if (currRect.XMost() > borderInside.XMost()) {
over = float(dashRect.XMost() - borderInside.XMost()) /
float(dashRect.width);
currRect.width = currRect.width -
(currRect.XMost() - borderInside.XMost());
}
//draw if necessary
if (bSolid) {
aContext.FillRect(currRect);
}
//setup for next iteration
if (over == 0.0f) {
bSolid = PRBool(!bSolid);
}
dashRect.x = dashRect.x + currRect.width;
currRect = dashRect;
}
break;
case NS_SIDE_RIGHT:
//if we are continuing a solid rect, fill in the corner first
if (bSolid) {
aContext.FillRect(borderInside.XMost(), borderOutside.y,
borderOutside.XMost() - borderInside.XMost(),
borderInside.y - borderOutside.y);
}
dashRect.width = borderOutside.XMost() - borderInside.XMost();
dashRect.height = nscoord(dashRect.width * dashLength);
dashRect.x = borderInside.XMost();
dashRect.y = borderInside.y;
if (over > 0.0f) {
firstRect.x = dashRect.x;
firstRect.y = dashRect.y;
firstRect.width = dashRect.width;
firstRect.height = nscoord(dashRect.height * over);
over = 0.0f;
currRect = firstRect;
} else {
currRect = dashRect;
}
while (currRect.y < borderInside.YMost()) {
//clip if necessary
if (currRect.YMost() > borderInside.YMost()) {
over = float(dashRect.YMost() - borderInside.YMost()) /
float(dashRect.height);
currRect.height = currRect.height -
(currRect.YMost() - borderInside.YMost());
}
//draw if necessary
if (bSolid) {
aContext.FillRect(currRect);
}
//setup for next iteration
if (over == 0.0f) {
bSolid = PRBool(!bSolid);
}
dashRect.y = dashRect.y + currRect.height;
currRect = dashRect;
}
break;
case NS_SIDE_BOTTOM:
//if we are continuing a solid rect, fill in the corner first
if (bSolid) {
aContext.FillRect(borderInside.XMost(), borderInside.YMost(),
borderOutside.XMost() - borderInside.XMost(),
borderOutside.YMost() - borderInside.YMost());
}
dashRect.height = borderOutside.YMost() - borderInside.YMost();
dashRect.width = nscoord(dashRect.height * dashLength);
dashRect.x = borderInside.XMost() - dashRect.width;
dashRect.y = borderInside.YMost();
if (over > 0.0f) {
firstRect.y = dashRect.y;
firstRect.width = nscoord(dashRect.width * over);
firstRect.height = dashRect.height;
firstRect.x = dashRect.x + (dashRect.width - firstRect.width);
over = 0.0f;
currRect = firstRect;
} else {
currRect = dashRect;
}
while (currRect.XMost() > borderInside.x) {
//clip if necessary
if (currRect.x < borderInside.x) {
over = float(borderInside.x - dashRect.x) / float(dashRect.width);
currRect.width = currRect.width - (borderInside.x - currRect.x);
currRect.x = borderInside.x;
}
//draw if necessary
if (bSolid) {
aContext.FillRect(currRect);
}
//setup for next iteration
if (over == 0.0f) {
bSolid = PRBool(!bSolid);
}
dashRect.x = dashRect.x - currRect.width;
currRect = dashRect;
}
break;
}
}
skippedSide = PR_FALSE;
}
}
/** ---------------------------------------------------
* See documentation in nsCSSRendering.h
* @update 10/22/99 dwc
*/
void nsCSSRendering::DrawDashedSides(PRIntn startSide,
nsIRenderingContext& aContext,
const nsRect& aDirtyRect,
const nsStyleColor* aColorStyle,
const nsStyleBorder* aBorderStyle,
const nsStyleOutline* aOutlineStyle,
PRBool aDoOutline,
const nsRect& borderOutside,
const nsRect& borderInside,
PRIntn aSkipSides,
/* XXX unused */ nsRect* aGap)
{
PRIntn dashLength;
nsRect dashRect, currRect;
nscoord temp, temp1, adjust;
PRBool bSolid = PR_TRUE;
float over = 0.0f;
PRBool skippedSide = PR_FALSE;
const nscolor kBlackColor = NS_RGB(0,0,0);
NS_ASSERTION((aDoOutline && aOutlineStyle) || (!aDoOutline && aBorderStyle), "null params not allowed");
PRUint8 style = aDoOutline
? aOutlineStyle->GetOutlineStyle()
: aBorderStyle->GetBorderStyle(startSide);
// find the x and y width
nscoord xwidth = aDirtyRect.XMost();
nscoord ywidth = aDirtyRect.YMost();
for (PRIntn whichSide = startSide; whichSide < 4; whichSide++) {
PRUint8 prevStyle = style;
style = aDoOutline
? aOutlineStyle->GetOutlineStyle()
: aBorderStyle->GetBorderStyle(whichSide);
if ((1<<whichSide) & aSkipSides) {
// Skipped side
skippedSide = PR_TRUE;
continue;
}
if ((style == NS_STYLE_BORDER_STYLE_DASHED) ||
(style == NS_STYLE_BORDER_STYLE_DOTTED))
{
if ((style != prevStyle) || skippedSide) {
//style discontinuity
over = 0.0f;
bSolid = PR_TRUE;
}
if (style == NS_STYLE_BORDER_STYLE_DASHED) {
dashLength = DASH_LENGTH;
} else {
dashLength = DOT_LENGTH;
}
nscolor sideColor(kBlackColor); // default to black in case color cannot be resolved
// (because invert is not supported on cur platform)
PRBool isInvert=PR_FALSE;
if (aDoOutline) {
// see if the outline color is 'invert'
if (aOutlineStyle->GetOutlineInvert()) {
isInvert = PR_TRUE;
} else {
aOutlineStyle->GetOutlineColor(sideColor);
}
} else {
PRBool transparent;
PRBool foreground;
aBorderStyle->GetBorderColor(whichSide, sideColor, transparent, foreground);
if (foreground)
sideColor = aColorStyle->mColor;
if (transparent)
continue; // side is transparent
}
aContext.SetColor(sideColor);
switch (whichSide) {
case NS_SIDE_RIGHT:
case NS_SIDE_LEFT:
bSolid = PR_FALSE;
// This is our dot or dash..
if(whichSide==NS_SIDE_LEFT){
dashRect.width = borderInside.x - borderOutside.x;
} else {
dashRect.width = borderOutside.XMost() - borderInside.XMost();
}
if( dashRect.width >0 ) {
dashRect.height = dashRect.width * dashLength;
dashRect.y = borderOutside.y;
if(whichSide == NS_SIDE_RIGHT){
dashRect.x = borderInside.XMost();
} else {
dashRect.x = borderOutside.x;
}
temp = borderOutside.YMost();
temp1 = temp/dashRect.height;
currRect = dashRect;
if((temp1%2)==0){
adjust = (dashRect.height-(temp%dashRect.height))/2; // adjust back
// draw in the left and right
FillOrInvertRect(aContext, dashRect.x, borderOutside.y,dashRect.width, dashRect.height-adjust,isInvert);
FillOrInvertRect(aContext,dashRect.x,(borderOutside.YMost()-(dashRect.height-adjust)),dashRect.width, dashRect.height-adjust,isInvert);
currRect.y += (dashRect.height-adjust);
temp = temp-= (dashRect.height-adjust);
} else {
adjust = (temp%dashRect.width)/2; // adjust a tad longer
// draw in the left and right
FillOrInvertRect(aContext, dashRect.x, borderOutside.y,dashRect.width, dashRect.height+adjust,isInvert);
FillOrInvertRect(aContext, dashRect.x,(borderOutside.YMost()-(dashRect.height+adjust)),dashRect.width, dashRect.height+adjust,isInvert);
currRect.y += (dashRect.height+adjust);
temp = temp-= (dashRect.height+adjust);
}
if( temp > ywidth)
temp = ywidth;
// get the currRect's x into the view before we start
if( currRect.y < aDirtyRect.y){
temp1 = NSToCoordFloor((float)((aDirtyRect.y-currRect.y)/dashRect.height));
currRect.y += temp1*dashRect.height;
if((temp1%2)==1){
bSolid = PR_TRUE;
}
}
while(currRect.y<temp) {
//draw if necessary
if (bSolid) {
FillOrInvertRect(aContext, currRect,isInvert);
}
bSolid = PRBool(!bSolid);
currRect.y += dashRect.height;
}
}
break;
case NS_SIDE_BOTTOM:
case NS_SIDE_TOP:
bSolid = PR_FALSE;
// This is our dot or dash..
if(whichSide==NS_SIDE_TOP){
dashRect.height = borderInside.y - borderOutside.y;
} else {
dashRect.height = borderOutside.YMost() - borderInside.YMost();
}
if( dashRect.height >0 ) {
dashRect.width = dashRect.height * dashLength;
dashRect.x = borderOutside.x;
if(whichSide == NS_SIDE_BOTTOM){
dashRect.y = borderInside.YMost();
} else {
dashRect.y = borderOutside.y;
}
temp = borderOutside.XMost();
temp1 = temp/dashRect.width;
currRect = dashRect;
if((temp1%2)==0){
adjust = (dashRect.width-(temp%dashRect.width))/2; // even, adjust back
// draw in the left and right
FillOrInvertRect(aContext, borderOutside.x,dashRect.y,dashRect.width-adjust,dashRect.height,isInvert);
FillOrInvertRect(aContext, (borderOutside.XMost()-(dashRect.width-adjust)),dashRect.y,dashRect.width-adjust,dashRect.height,isInvert);
currRect.x += (dashRect.width-adjust);
temp = temp-= (dashRect.width-adjust);
} else {
adjust = (temp%dashRect.width)/2;
// draw in the left and right
FillOrInvertRect(aContext, borderOutside.x,dashRect.y,dashRect.width+adjust,dashRect.height,isInvert);
FillOrInvertRect(aContext, (borderOutside.XMost()-(dashRect.width+adjust)),dashRect.y,dashRect.width+adjust,dashRect.height,isInvert);
currRect.x += (dashRect.width+adjust);
temp = temp-= (dashRect.width+adjust);
}
if( temp > xwidth)
temp = xwidth;
// get the currRect's x into the view before we start
if( currRect.x < aDirtyRect.x){
temp1 = NSToCoordFloor((float)((aDirtyRect.x-currRect.x)/dashRect.width));
currRect.x += temp1*dashRect.width;
if((temp1%2)==1){
bSolid = PR_TRUE;
}
}
while(currRect.x<temp) {
//draw if necessary
if (bSolid) {
FillOrInvertRect(aContext, currRect,isInvert);
}
bSolid = PRBool(!bSolid);
currRect.x += dashRect.width;
}
}
break;
}
}
skippedSide = PR_FALSE;
}
}
/* draw the portions of the border described in aBorderEdges that are dashed.
* a border has 4 edges. Each edge has 1 or more segments.
* "inside edges" are drawn differently than "outside edges" so the shared edges will match up.
* in the case of table collapsing borders, the table edge is the "outside" edge and
* cell edges are always "inside" edges (so adjacent cells have 2 shared "inside" edges.)
* There is a case for each of the four sides. Only the left side is well documented. The others
* are very similar.
*/
// XXX: doesn't do corners or junctions well at all. Just uses logic stolen
// from DrawDashedSides which is insufficient
void nsCSSRendering::DrawDashedSegments(nsIRenderingContext& aContext,
const nsRect& aBounds,
nsBorderEdges * aBorderEdges,
PRIntn aSkipSides,
/* XXX unused */ nsRect* aGap)
{
PRIntn dashLength;
nsRect dashRect, currRect;
PRBool bSolid = PR_TRUE;
float over = 0.0f;
PRBool skippedSide = PR_FALSE;
PRIntn whichSide=0;
// do this just to set up initial condition for loop
// "segment" is the current portion of the edge we are computing
nsBorderEdge * segment = (nsBorderEdge *)(aBorderEdges->mEdges[whichSide].ElementAt(0));
PRUint8 style = segment->mStyle;
for ( ; whichSide < 4; whichSide++)
{
if ((1<<whichSide) & aSkipSides) {
// Skipped side
skippedSide = PR_TRUE;
continue;
}
nscoord x=0; nscoord y=0;
PRInt32 i;
PRInt32 segmentCount = aBorderEdges->mEdges[whichSide].Count();
nsBorderEdges * neighborBorderEdges=nsnull;
PRIntn neighborEdgeCount=0; // keeps track of which inside neighbor is shared with an outside segment
for (i=0; i<segmentCount; i++)
{
bSolid=PR_TRUE;
over = 0.0f;
segment = (nsBorderEdge *)(aBorderEdges->mEdges[whichSide].ElementAt(i));
style = segment->mStyle;
// XXX units for dash & dot?
if (style == NS_STYLE_BORDER_STYLE_DASHED) {
dashLength = DASH_LENGTH;
} else {
dashLength = DOT_LENGTH;
}
aContext.SetColor(segment->mColor);
switch (whichSide) {
case NS_SIDE_LEFT:
{ // draw left segment i
nsBorderEdge * topEdge = (nsBorderEdge *)(aBorderEdges->mEdges[NS_SIDE_TOP].ElementAt(0));
if (0==y)
{ // y is the offset to the top of this segment. 0 means its the topmost left segment
y = aBorderEdges->mMaxBorderWidth.top - topEdge->mWidth;
if (PR_TRUE==aBorderEdges->mOutsideEdge)
y += topEdge->mWidth;
}
// the x offset is the x position offset by the max width of the left edge minus this segment's width
x = aBounds.x + (aBorderEdges->mMaxBorderWidth.left - segment->mWidth);
nscoord height = segment->mLength;
// the space between borderOutside and borderInside inclusive is the segment.
nsRect borderOutside(x, y, aBounds.width, height);
y += segment->mLength; // keep track of the y offset for the next segment
if ((style == NS_STYLE_BORDER_STYLE_DASHED) ||
(style == NS_STYLE_BORDER_STYLE_DOTTED))
{
nsRect borderInside(borderOutside);
nsMargin outsideMargin(segment->mWidth, 0, 0, 0);
borderInside.Deflate(outsideMargin);
nscoord totalLength = segment->mLength; // the computed length of this segment
// outside edges need info from their inside neighbor. The following code keeps track
// of which segment of the inside neighbor's shared edge we should use for this outside segment
if (PR_TRUE==aBorderEdges->mOutsideEdge)
{
if (segment->mInsideNeighbor == neighborBorderEdges)
{
neighborEdgeCount++;
}
else
{
neighborBorderEdges = segment->mInsideNeighbor;
neighborEdgeCount=0;
}
nsBorderEdge * neighborLeft = (nsBorderEdge *)(segment->mInsideNeighbor->mEdges[NS_SIDE_LEFT].ElementAt(neighborEdgeCount));
totalLength = neighborLeft->mLength;
}
dashRect.width = borderInside.x - borderOutside.x;
dashRect.height = nscoord(dashRect.width * dashLength);
dashRect.x = borderOutside.x;
dashRect.y = borderOutside.y + (totalLength/2) - dashRect.height;
if ((PR_TRUE==aBorderEdges->mOutsideEdge) && (0!=i))
dashRect.y -= topEdge->mWidth; // account for the topmost left edge corner with the leftmost top edge
if (0)
{
printf(" L: totalLength = %d, borderOutside.y = %d, midpoint %d, dashRect.y = %d\n",
totalLength, borderOutside.y, borderOutside.y +(totalLength/2), dashRect.y);
}
currRect = dashRect;
// we draw the segment in 2 halves to get the inside and outside edges to line up on the
// centerline of the shared edge.
// draw the top half
while (currRect.YMost() > borderInside.y) {
//clip if necessary
if (currRect.y < borderInside.y) {
over = float(borderInside.y - dashRect.y) /
float(dashRect.height);
currRect.height = currRect.height - (borderInside.y - currRect.y);
currRect.y = borderInside.y;
}
//draw if necessary
if (0)
{
printf("DASHED LEFT: xywh in loop currRect = %d %d %d %d %s\n",
currRect.x, currRect.y, currRect.width, currRect.height, bSolid?"TRUE":"FALSE");
}
if (bSolid) {
aContext.FillRect(currRect);
}
//setup for next iteration
if (over == 0.0f) {
bSolid = PRBool(!bSolid);
}
dashRect.y = dashRect.y - currRect.height;
currRect = dashRect;
}
// draw the bottom half
dashRect.y = borderOutside.y + (totalLength/2) + dashRect.height;
if ((PR_TRUE==aBorderEdges->mOutsideEdge) && (0!=i))
dashRect.y -= topEdge->mWidth;
currRect = dashRect;
bSolid=PR_TRUE;
over = 0.0f;
while (currRect.YMost() < borderInside.YMost()) {
//clip if necessary
if (currRect.y < borderInside.y) {
over = float(borderInside.y - dashRect.y) /
float(dashRect.height);
currRect.height = currRect.height - (borderInside.y - currRect.y);
currRect.y = borderInside.y;
}
//draw if necessary
if (0)
{
printf("DASHED LEFT: xywh in loop currRect = %d %d %d %d %s\n",
currRect.x, currRect.y, currRect.width, currRect.height, bSolid?"TRUE":"FALSE");
}
if (bSolid) {
aContext.FillRect(currRect);
}
//setup for next iteration
if (over == 0.0f) {
bSolid = PRBool(!bSolid);
}
dashRect.y = dashRect.y + currRect.height;
currRect = dashRect;
}
}
}
break;
case NS_SIDE_TOP:
{ // draw top segment i
if (0==x)
{
nsBorderEdge * leftEdge = (nsBorderEdge *)(aBorderEdges->mEdges[NS_SIDE_LEFT].ElementAt(0));
x = aBorderEdges->mMaxBorderWidth.left - leftEdge->mWidth;
}
y = aBounds.y;
if (PR_TRUE==aBorderEdges->mOutsideEdge) // segments of the outside edge are bottom-aligned
y += aBorderEdges->mMaxBorderWidth.top - segment->mWidth;
nsRect borderOutside(x, y, segment->mLength, aBounds.height);
x += segment->mLength;
if ((style == NS_STYLE_BORDER_STYLE_DASHED) ||
(style == NS_STYLE_BORDER_STYLE_DOTTED))
{
nsRect borderInside(borderOutside);
nsBorderEdge * neighbor;
// XXX Adding check to make sure segment->mInsideNeighbor is not null
// so it will do the else part, at this point we are assuming this is an
// ok thing to do (Bug 52130)
if (PR_TRUE==aBorderEdges->mOutsideEdge && segment->mInsideNeighbor)
neighbor = (nsBorderEdge *)(segment->mInsideNeighbor->mEdges[NS_SIDE_LEFT].ElementAt(0));
else
neighbor = (nsBorderEdge *)(aBorderEdges->mEdges[NS_SIDE_LEFT].ElementAt(0));
nsMargin outsideMargin(neighbor->mWidth, segment->mWidth, 0, segment->mWidth);
borderInside.Deflate(outsideMargin);
nscoord firstRectWidth = 0;
if (PR_TRUE==aBorderEdges->mOutsideEdge && 0==i)
{
firstRectWidth = borderInside.x - borderOutside.x;
aContext.FillRect(borderOutside.x, borderOutside.y,
firstRectWidth,
borderInside.y - borderOutside.y);
}
dashRect.height = borderInside.y - borderOutside.y;
dashRect.width = dashRect.height * dashLength;
dashRect.x = borderOutside.x + firstRectWidth;
dashRect.y = borderOutside.y;
currRect = dashRect;
while (currRect.x < borderInside.XMost()) {
//clip if necessary
if (currRect.XMost() > borderInside.XMost()) {
over = float(dashRect.XMost() - borderInside.XMost()) /
float(dashRect.width);
currRect.width = currRect.width -
(currRect.XMost() - borderInside.XMost());
}
//draw if necessary
if (bSolid) {
aContext.FillRect(currRect);
}
//setup for next iteration
if (over == 0.0f) {
bSolid = PRBool(!bSolid);
}
dashRect.x = dashRect.x + currRect.width;
currRect = dashRect;
}
}
}
break;
case NS_SIDE_RIGHT:
{ // draw right segment i
nsBorderEdge * topEdge = (nsBorderEdge *)
(aBorderEdges->mEdges[NS_SIDE_TOP].ElementAt(aBorderEdges->mEdges[NS_SIDE_TOP].Count()-1));
if (0==y)
{
y = aBorderEdges->mMaxBorderWidth.top - topEdge->mWidth;
if (PR_TRUE==aBorderEdges->mOutsideEdge)
y += topEdge->mWidth;
}
nscoord width;
if (PR_TRUE==aBorderEdges->mOutsideEdge)
{
width = aBounds.width - aBorderEdges->mMaxBorderWidth.right;
width += segment->mWidth;
}
else
{
width = aBounds.width;
}
nscoord height = segment->mLength;
nsRect borderOutside(aBounds.x, y, width, height);
y += segment->mLength;
if ((style == NS_STYLE_BORDER_STYLE_DASHED) ||
(style == NS_STYLE_BORDER_STYLE_DOTTED))
{
nsRect borderInside(borderOutside);
nsMargin outsideMargin(segment->mWidth, 0, (segment->mWidth), 0);
borderInside.Deflate(outsideMargin);
nscoord totalLength = segment->mLength;
if (PR_TRUE==aBorderEdges->mOutsideEdge)
{
if (segment->mInsideNeighbor == neighborBorderEdges)
{
neighborEdgeCount++;
}
else
{
neighborBorderEdges = segment->mInsideNeighbor;
neighborEdgeCount=0;
}
nsBorderEdge * neighborRight = (nsBorderEdge *)(segment->mInsideNeighbor->mEdges[NS_SIDE_RIGHT].ElementAt(neighborEdgeCount));
totalLength = neighborRight->mLength;
}
dashRect.width = borderOutside.XMost() - borderInside.XMost();
dashRect.height = nscoord(dashRect.width * dashLength);
dashRect.x = borderInside.XMost();
dashRect.y = borderOutside.y + (totalLength/2) - dashRect.height;
if ((PR_TRUE==aBorderEdges->mOutsideEdge) && (0!=i))
dashRect.y -= topEdge->mWidth;
currRect = dashRect;
// draw the top half
while (currRect.YMost() > borderInside.y) {
//clip if necessary
if (currRect.y < borderInside.y) {
over = float(borderInside.y - dashRect.y) /
float(dashRect.height);
currRect.height = currRect.height - (borderInside.y - currRect.y);
currRect.y = borderInside.y;
}
//draw if necessary
if (bSolid) {
aContext.FillRect(currRect);
}
//setup for next iteration
if (over == 0.0f) {
bSolid = PRBool(!bSolid);
}
dashRect.y = dashRect.y - currRect.height;
currRect = dashRect;
}
// draw the bottom half
dashRect.y = borderOutside.y + (totalLength/2) + dashRect.height;
if ((PR_TRUE==aBorderEdges->mOutsideEdge) && (0!=i))
dashRect.y -= topEdge->mWidth;
currRect = dashRect;
bSolid=PR_TRUE;
over = 0.0f;
while (currRect.YMost() < borderInside.YMost()) {
//clip if necessary
if (currRect.y < borderInside.y) {
over = float(borderInside.y - dashRect.y) /
float(dashRect.height);
currRect.height = currRect.height - (borderInside.y - currRect.y);
currRect.y = borderInside.y;
}
//draw if necessary
if (bSolid) {
aContext.FillRect(currRect);
}
//setup for next iteration
if (over == 0.0f) {
bSolid = PRBool(!bSolid);
}
dashRect.y = dashRect.y + currRect.height;
currRect = dashRect;
}
}
}
break;
case NS_SIDE_BOTTOM:
{ // draw bottom segment i
if (0==x)
{
nsBorderEdge * leftEdge = (nsBorderEdge *)
(aBorderEdges->mEdges[NS_SIDE_LEFT].ElementAt(aBorderEdges->mEdges[NS_SIDE_LEFT].Count()-1));
x = aBorderEdges->mMaxBorderWidth.left - leftEdge->mWidth;
}
y = aBounds.y;
if (PR_TRUE==aBorderEdges->mOutsideEdge) // segments of the outside edge are top-aligned
y -= aBorderEdges->mMaxBorderWidth.bottom - segment->mWidth;
nsRect borderOutside(x, y, segment->mLength, aBounds.height);
x += segment->mLength;
if ((style == NS_STYLE_BORDER_STYLE_DASHED) ||
(style == NS_STYLE_BORDER_STYLE_DOTTED))
{
nsRect borderInside(borderOutside);
nsBorderEdge * neighbor;
if (PR_TRUE==aBorderEdges->mOutsideEdge)
neighbor = (nsBorderEdge *)(segment->mInsideNeighbor->mEdges[NS_SIDE_LEFT].ElementAt(0));
else
neighbor = (nsBorderEdge *)(aBorderEdges->mEdges[NS_SIDE_LEFT].ElementAt(0));
nsMargin outsideMargin(neighbor->mWidth, segment->mWidth, 0, segment->mWidth);
borderInside.Deflate(outsideMargin);
nscoord firstRectWidth = 0;
if (PR_TRUE==aBorderEdges->mOutsideEdge && 0==i)
{
firstRectWidth = borderInside.x - borderOutside.x;
aContext.FillRect(borderOutside.x, borderInside.YMost(),
firstRectWidth,
borderOutside.YMost() - borderInside.YMost());
}
dashRect.height = borderOutside.YMost() - borderInside.YMost();
dashRect.width = nscoord(dashRect.height * dashLength);
dashRect.x = borderOutside.x + firstRectWidth;
dashRect.y = borderInside.YMost();
currRect = dashRect;
while (currRect.x < borderInside.XMost()) {
//clip if necessary
if (currRect.XMost() > borderInside.XMost()) {
over = float(dashRect.XMost() - borderInside.XMost()) /
float(dashRect.width);
currRect.width = currRect.width -
(currRect.XMost() - borderInside.XMost());
}
//draw if necessary
if (bSolid) {
aContext.FillRect(currRect);
}
//setup for next iteration
if (over == 0.0f) {
bSolid = PRBool(!bSolid);
}
dashRect.x = dashRect.x + currRect.width;
currRect = dashRect;
}
}
}
break;
}
}
skippedSide = PR_FALSE;
}
}
nscolor
nsCSSRendering::TransformColor(nscolor aMapColor,PRBool aNoBackGround)
{
PRUint16 hue,sat,value;
nscolor newcolor;
newcolor = aMapColor;
if (PR_TRUE == aNoBackGround){
// convert the RBG to HSV so we can get the lightness (which is the v)
NS_RGB2HSV(newcolor,hue,sat,value);
// The goal here is to send white to black while letting colored
// stuff stay colored... So we adopt the following approach.
// Something with sat = 0 should end up with value = 0. Something
// with a high sat can end up with a high value and it's ok.... At
// the same time, we don't want to make things lighter. Do
// something simple, since it seems to work.
if (value > sat) {
value = sat;
// convert this color back into the RGB color space.
NS_HSV2RGB(newcolor,hue,sat,value);
}
}
return newcolor;
}
// method GetBGColorForHTMLElement
//
// Now here's a *fun* hack: Nav4 uses the BODY element's background color for the
// background color on tables so we need to find that element's
// color and use it... Actually, we can use the HTML element as well.
//
// Traverse from PresContext to PresShell to Document to RootContent. The RootContent is
// then checked to ensure that it is the HTML or BODY element, and if it is, we get
// it's primary frame and from that the style context and from that the color to use.
//
PRBool GetBGColorForHTMLElement( nsPresContext *aPresContext,
const nsStyleBackground *&aBGColor )
{
NS_ASSERTION(aPresContext, "null params not allowed");
PRBool result = PR_FALSE; // assume we did not find the HTML element
nsIPresShell* shell = aPresContext->GetPresShell();
if (shell) {
nsIDocument *doc = shell->GetDocument();
if (doc) {
nsIContent *pContent;
if ((pContent = doc->GetRootContent())) {
// make sure that this is the HTML element
nsIAtom *tag = pContent->Tag();
NS_ASSERTION(tag, "Tag could not be retrieved from root content element");
if (tag == nsHTMLAtoms::html ||
tag == nsHTMLAtoms::body) {
// use this guy's color
nsIFrame *pFrame = nsnull;
if (NS_SUCCEEDED(shell->GetPrimaryFrameFor(pContent, &pFrame)) &&
pFrame) {
nsStyleContext *pContext = pFrame->GetStyleContext();
if (pContext) {
const nsStyleBackground* color = pContext->GetStyleBackground();
if (0 == (color->mBackgroundFlags & NS_STYLE_BG_COLOR_TRANSPARENT)) {
aBGColor = color;
// set the reslt to TRUE to indicate we mapped the color
result = PR_TRUE;
}
}// if context
}// if frame
}// if tag == html or body
#ifdef DEBUG
else {
printf( "Root Content is not HTML or BODY: cannot get bgColor of HTML or BODY\n");
}
#endif
}// if content
}// if doc
} // if shell
return result;
}
// helper macro to determine if the borderstyle 'a' is a MOZ-BG-XXX style
#define MOZ_BG_BORDER(a)\
((a==NS_STYLE_BORDER_STYLE_BG_INSET) || (a==NS_STYLE_BORDER_STYLE_BG_OUTSET)\
|| (a==NS_STYLE_BORDER_STYLE_BG_SOLID))
static
PRBool GetBorderColor(const nsStyleColor* aColor, const nsStyleBorder& aBorder, PRUint8 aSide, nscolor& aColorVal,
nsBorderColors** aCompositeColors = nsnull)
{
PRBool transparent;
PRBool foreground;
if (aCompositeColors) {
aBorder.GetCompositeColors(aSide, aCompositeColors);
if (*aCompositeColors)
return PR_TRUE;
}
aBorder.GetBorderColor(aSide, aColorVal, transparent, foreground);
if (foreground)
aColorVal = aColor->mColor;
return !transparent;
}
// XXX improve this to constrain rendering to the damaged area
void nsCSSRendering::PaintBorder(nsPresContext* aPresContext,
nsIRenderingContext& aRenderingContext,
nsIFrame* aForFrame,
const nsRect& aDirtyRect,
const nsRect& aBorderArea,
const nsStyleBorder& aBorderStyle,
nsStyleContext* aStyleContext,
PRIntn aSkipSides,
nsRect* aGap,
nscoord aHardBorderSize,
PRBool aShouldIgnoreRounded)
{
PRIntn cnt;
nsMargin border;
nsStyleCoord bordStyleRadius[4];
PRInt16 borderRadii[4],i;
float percent;
nsCompatibility compatMode = aPresContext->CompatibilityMode();
PRBool forceSolid;
// Check to see if we have an appearance defined. If so, we let the theme
// renderer draw the border. DO not get the data from aForFrame, since the passed in style context
// may be different! Always use |aStyleContext|!
const nsStyleDisplay* displayData = aStyleContext->GetStyleDisplay();
if (displayData->mAppearance) {
nsITheme *theme = aPresContext->GetTheme();
if (theme && theme->ThemeSupportsWidget(aPresContext, aForFrame, displayData->mAppearance))
return; // Let the theme handle it.
}
// Get our style context's color struct.
const nsStyleColor* ourColor = aStyleContext->GetStyleColor();
// in NavQuirks mode we want to use the parent's context as a starting point
// for determining the background color
const nsStyleBackground* bgColor =
nsCSSRendering::FindNonTransparentBackground(aStyleContext,
compatMode == eCompatibility_NavQuirks ? PR_TRUE : PR_FALSE);
// mozBGColor is used instead of bgColor when the display type is BG_INSET or BG_OUTSET
// or BG_SOLID, and, in quirk mode, it is set to the BODY element's background color
// instead of the nearest ancestor's background color.
const nsStyleBackground* mozBGColor = bgColor;
// now check if we are in Quirks mode and have a border style of BG_INSET or OUTSET
// or BG_SOLID - if so we use the bgColor from the HTML element instead of the
// nearest ancestor
if (compatMode == eCompatibility_NavQuirks) {
PRBool bNeedBodyBGColor = PR_FALSE;
if (aStyleContext) {
for (cnt=0; cnt<4;cnt++) {
bNeedBodyBGColor = MOZ_BG_BORDER(aBorderStyle.GetBorderStyle(cnt));
if (bNeedBodyBGColor) {
break;
}
}
}
if (bNeedBodyBGColor) {
GetBGColorForHTMLElement(aPresContext, mozBGColor);
}
}
if (aHardBorderSize > 0) {
border.SizeTo(aHardBorderSize, aHardBorderSize, aHardBorderSize, aHardBorderSize);
} else {
aBorderStyle.CalcBorderFor(aForFrame, border);
}
if ((0 == border.left) && (0 == border.right) &&
(0 == border.top) && (0 == border.bottom)) {
// Empty border area
return;
}
// get the radius for our border
aBorderStyle.mBorderRadius.GetTop(bordStyleRadius[0]); //topleft
aBorderStyle.mBorderRadius.GetRight(bordStyleRadius[1]); //topright
aBorderStyle.mBorderRadius.GetBottom(bordStyleRadius[2]); //bottomright
aBorderStyle.mBorderRadius.GetLeft(bordStyleRadius[3]); //bottomleft
for(i=0;i<4;i++) {
borderRadii[i] = 0;
switch ( bordStyleRadius[i].GetUnit()) {
case eStyleUnit_Percent:
percent = bordStyleRadius[i].GetPercentValue();
borderRadii[i] = (nscoord)(percent * aBorderArea.width);
break;
case eStyleUnit_Coord:
borderRadii[i] = bordStyleRadius[i].GetCoordValue();
break;
default:
break;
}
}
// rounded version of the outline
// check for any corner that is rounded
for(i=0;i<4;i++){
if(borderRadii[i] > 0 && !aBorderStyle.mBorderColors){
PaintRoundedBorder(aPresContext,aRenderingContext,aForFrame,aDirtyRect,aBorderArea,&aBorderStyle,nsnull,aStyleContext,aSkipSides,borderRadii,aGap,PR_FALSE);
return;
}
}
// Turn off rendering for all of the zero sized sides
if (0 == border.top) aSkipSides |= (1 << NS_SIDE_TOP);
if (0 == border.right) aSkipSides |= (1 << NS_SIDE_RIGHT);
if (0 == border.bottom) aSkipSides |= (1 << NS_SIDE_BOTTOM);
if (0 == border.left) aSkipSides |= (1 << NS_SIDE_LEFT);
// get the inside and outside parts of the border
nsRect outerRect(aBorderArea);
nsRect innerRect(outerRect);
innerRect.Deflate(border);
if (border.left + border.right > aBorderArea.width) {
innerRect.x = outerRect.x;
innerRect.width = outerRect.width;
}
if (border.top + border.bottom > aBorderArea.height) {
innerRect.y = outerRect.y;
innerRect.height = outerRect.height;
}
// If the dirty rect is completely inside the border area (e.g., only the
// content is being painted), then we can skip out now
if (innerRect.Contains(aDirtyRect)) {
return;
}
//see if any sides are dotted or dashed
for (cnt = 0; cnt < 4; cnt++) {
if ((aBorderStyle.GetBorderStyle(cnt) == NS_STYLE_BORDER_STYLE_DOTTED) ||
(aBorderStyle.GetBorderStyle(cnt) == NS_STYLE_BORDER_STYLE_DASHED)) {
break;
}
}
if (cnt < 4) {
DrawDashedSides(cnt, aRenderingContext,aDirtyRect, ourColor, &aBorderStyle,nsnull, PR_FALSE,
outerRect, innerRect, aSkipSides, aGap);
}
// dont clip the borders for composite borders, they use the inner and
// outer rect to compute the diagonale to cross the border radius
nsRect compositeInnerRect(innerRect);
nsRect compositeOuterRect(outerRect);
// Draw all the other sides
if (!aDirtyRect.Contains(outerRect)) {
// Border leaks out of the dirty rectangle - lets clip it but with care
if (innerRect.y < aDirtyRect.y) {
aSkipSides |= (1 << NS_SIDE_TOP);
PRUint32 shortenBy =
PR_MIN(innerRect.height, aDirtyRect.y - innerRect.y);
innerRect.y += shortenBy;
innerRect.height -= shortenBy;
outerRect.y += shortenBy;
outerRect.height -= shortenBy;
}
if (aDirtyRect.YMost() < innerRect.YMost()) {
aSkipSides |= (1 << NS_SIDE_BOTTOM);
PRUint32 shortenBy =
PR_MIN(innerRect.height, innerRect.YMost() - aDirtyRect.YMost());
innerRect.height -= shortenBy;
outerRect.height -= shortenBy;
}
if (innerRect.x < aDirtyRect.x) {
aSkipSides |= (1 << NS_SIDE_LEFT);
PRUint32 shortenBy =
PR_MIN(innerRect.width, aDirtyRect.x - innerRect.x);
innerRect.x += shortenBy;
innerRect.width -= shortenBy;
outerRect.x += shortenBy;
outerRect.width -= shortenBy;
}
if (aDirtyRect.XMost() < innerRect.XMost()) {
aSkipSides |= (1 << NS_SIDE_RIGHT);
PRUint32 shortenBy =
PR_MIN(innerRect.width, innerRect.XMost() - aDirtyRect.XMost());
innerRect.width -= shortenBy;
outerRect.width -= shortenBy;
}
}
/* Get our conversion values */
nscoord twipsPerPixel = aPresContext->IntScaledPixelsToTwips(1);
static PRUint8 sideOrder[] = { NS_SIDE_BOTTOM, NS_SIDE_LEFT, NS_SIDE_TOP, NS_SIDE_RIGHT };
nscolor sideColor;
nsBorderColors* compositeColors = nsnull;
for (cnt = 0; cnt < 4; cnt++) {
PRUint8 side = sideOrder[cnt];
// If a side needs a double border but will be less than two pixels,
// force it to be solid (see bug 1781).
if (aBorderStyle.GetBorderStyle(side) == NS_STYLE_BORDER_STYLE_DOUBLE) {
nscoord widths[] = { border.top, border.right, border.bottom, border.left };
forceSolid = (widths[side]/twipsPerPixel < 2);
} else
forceSolid = PR_FALSE;
if (0 == (aSkipSides & (1<<side))) {
if (GetBorderColor(ourColor, aBorderStyle, side, sideColor, &compositeColors)) {
if (compositeColors)
DrawCompositeSide(aRenderingContext, side, compositeColors, compositeOuterRect,
compositeInnerRect, borderRadii, twipsPerPixel, aGap);
else
DrawSide(aRenderingContext, side,
forceSolid ? NS_STYLE_BORDER_STYLE_SOLID : aBorderStyle.GetBorderStyle(side),
sideColor,
MOZ_BG_BORDER(aBorderStyle.GetBorderStyle(side)) ?
mozBGColor->mBackgroundColor :
bgColor->mBackgroundColor,
outerRect,innerRect, aSkipSides,
twipsPerPixel, aGap);
}
}
}
}
void nsCSSRendering::DrawCompositeSide(nsIRenderingContext& aRenderingContext,
PRIntn aWhichSide,
nsBorderColors* aCompositeColors,
const nsRect& aOuterRect,
const nsRect& aInnerRect,
PRInt16* aBorderRadii,
nscoord twipsPerPixel,
nsRect* aGap)
{
// Loop over each color and at each iteration shrink the length of the
// lines that we draw.
nsRect currOuterRect(aOuterRect);
// XXXdwh This border radius code is rather hacky and will only work for
// small radii, but it will be sufficient to get a major performance
// improvement in themes with small curvature (like Modern).
// Still, this code should be rewritten if/when someone chooses to pick
// up the -moz-border-radius gauntlet.
// Alternatively we could add support for a -moz-border-diagonal property, which is
// what this code actually draws (instead of a curve).
// determine the the number of pixels we need to draw for this side
// and the start and end radii
nscoord shrinkage, startRadius, endRadius;
if (aWhichSide == NS_SIDE_TOP) {
shrinkage = aInnerRect.y - aOuterRect.y;
startRadius = aBorderRadii[0];
endRadius = aBorderRadii[1];
} else if (aWhichSide == NS_SIDE_BOTTOM) {
shrinkage = (aOuterRect.height+aOuterRect.y) - (aInnerRect.height+aInnerRect.y);
startRadius = aBorderRadii[3];
endRadius = aBorderRadii[2];
} else if (aWhichSide == NS_SIDE_RIGHT) {
shrinkage = (aOuterRect.width+aOuterRect.x) - (aInnerRect.width+aInnerRect.x);
startRadius = aBorderRadii[1];
endRadius = aBorderRadii[2];
} else {
NS_ASSERTION(aWhichSide == NS_SIDE_LEFT, "incorrect aWhichSide");
shrinkage = aInnerRect.x - aOuterRect.x;
startRadius = aBorderRadii[0];
endRadius = aBorderRadii[3];
}
while (shrinkage > 0) {
nscoord xshrink = 0;
nscoord yshrink = 0;
nscoord widthshrink = 0;
nscoord heightshrink = 0;
if (startRadius || endRadius) {
if (aWhichSide == NS_SIDE_TOP || aWhichSide == NS_SIDE_BOTTOM) {
xshrink = startRadius;
widthshrink = startRadius + endRadius;
}
else if (aWhichSide == NS_SIDE_LEFT || aWhichSide == NS_SIDE_RIGHT) {
yshrink = startRadius-1;
heightshrink = yshrink + endRadius;
}
}
// subtract any rounded pixels from the outer rect
nsRect newOuterRect(currOuterRect);
newOuterRect.x += xshrink;
newOuterRect.y += yshrink;
newOuterRect.width -= widthshrink;
newOuterRect.height -= heightshrink;
nsRect borderInside(currOuterRect);
// try to subtract one pixel from each side of the outer rect, but only if
// that side has any extra space left to shrink
if (aInnerRect.x > borderInside.x) { // shrink left
borderInside.x += twipsPerPixel;
borderInside.width -= twipsPerPixel;
}
if (borderInside.x+borderInside.width > aInnerRect.x+aInnerRect.width) // shrink right
borderInside.width -= twipsPerPixel;
if (aInnerRect.y > borderInside.y) { // shrink top
borderInside.y += twipsPerPixel;
borderInside.height -= twipsPerPixel;
}
if (borderInside.y+borderInside.height > aInnerRect.y+aInnerRect.height) // shrink bottom
borderInside.height -= twipsPerPixel;
if (!aCompositeColors->mTransparent) {
nsPoint theSide[MAX_POLY_POINTS];
PRInt32 np = MakeSide(theSide, aRenderingContext, aWhichSide, newOuterRect, borderInside, 0,
BORDER_FULL, 1.0f, twipsPerPixel);
NS_ASSERTION(np == 2, "Composite border should always be single pixel!");
aRenderingContext.SetColor(aCompositeColors->mColor);
DrawLine(aRenderingContext, theSide[0].x, theSide[0].y, theSide[1].x, theSide[1].y, aGap);
if (aWhichSide == NS_SIDE_TOP) {
if (startRadius) {
// Connecting line between top/left
nscoord distance = (startRadius+twipsPerPixel)/2;
nscoord remainder = distance%twipsPerPixel;
if (remainder)
distance += twipsPerPixel - remainder;
DrawLine(aRenderingContext,
currOuterRect.x+startRadius,
currOuterRect.y,
currOuterRect.x+startRadius-distance,
currOuterRect.y+distance,
aGap);
}
if (endRadius) {
// Connecting line between top/right
nscoord distance = (endRadius+twipsPerPixel)/2;
nscoord remainder = distance%twipsPerPixel;
if (remainder)
distance += twipsPerPixel - remainder;
DrawLine(aRenderingContext,
currOuterRect.x+currOuterRect.width-endRadius-twipsPerPixel,
currOuterRect.y,
currOuterRect.x+currOuterRect.width-endRadius-twipsPerPixel+distance,
currOuterRect.y+distance,
aGap);
}
}
else if (aWhichSide == NS_SIDE_BOTTOM) {
if (startRadius) {
// Connecting line between bottom/left
nscoord distance = (startRadius+twipsPerPixel)/2;
nscoord remainder = distance%twipsPerPixel;
if (remainder)
distance += twipsPerPixel - remainder;
DrawLine(aRenderingContext,
currOuterRect.x+startRadius,
currOuterRect.y+currOuterRect.height-twipsPerPixel,
currOuterRect.x+startRadius-distance,
currOuterRect.y+currOuterRect.height-twipsPerPixel-distance,
aGap);
}
if (endRadius) {
// Connecting line between bottom/right
nscoord distance = (endRadius+twipsPerPixel)/2;
nscoord remainder = distance%twipsPerPixel;
if (remainder)
distance += twipsPerPixel - remainder;
DrawLine(aRenderingContext,
currOuterRect.x+currOuterRect.width-endRadius-twipsPerPixel,
currOuterRect.y+currOuterRect.height-twipsPerPixel,
currOuterRect.x+currOuterRect.width-endRadius-twipsPerPixel+distance,
currOuterRect.y+currOuterRect.height-twipsPerPixel-distance,
aGap);
}
}
else if (aWhichSide == NS_SIDE_LEFT) {
if (startRadius) {
// Connecting line between left/top
nscoord distance = (startRadius-twipsPerPixel)/2;
nscoord remainder = distance%twipsPerPixel;
if (remainder)
distance -= remainder;
DrawLine(aRenderingContext,
currOuterRect.x+distance,
currOuterRect.y+startRadius-distance,
currOuterRect.x,
currOuterRect.y+startRadius,
aGap);
}
if (endRadius) {
// Connecting line between left/bottom
nscoord distance = (endRadius-twipsPerPixel)/2;
nscoord remainder = distance%twipsPerPixel;
if (remainder)
distance -= remainder;
DrawLine(aRenderingContext,
currOuterRect.x+distance,
currOuterRect.y+currOuterRect.height-twipsPerPixel-endRadius+distance,
currOuterRect.x,
currOuterRect.y+currOuterRect.height-twipsPerPixel-endRadius,
aGap);
}
}
else if (aWhichSide == NS_SIDE_RIGHT) {
if (startRadius) {
// Connecting line between right/top
nscoord distance = (startRadius-twipsPerPixel)/2;
nscoord remainder = distance%twipsPerPixel;
if (remainder)
distance -= remainder;
DrawLine(aRenderingContext,
currOuterRect.x+currOuterRect.width-twipsPerPixel-distance,
currOuterRect.y+startRadius-distance,
currOuterRect.x+currOuterRect.width-twipsPerPixel,
currOuterRect.y+startRadius,
aGap);
}
if (endRadius) {
// Connecting line between right/bottom
nscoord distance = (endRadius-twipsPerPixel)/2;
nscoord remainder = distance%twipsPerPixel;
if (remainder)
distance -= remainder;
DrawLine(aRenderingContext,
currOuterRect.x+currOuterRect.width-twipsPerPixel-distance,
currOuterRect.y+currOuterRect.height-twipsPerPixel-endRadius+distance,
currOuterRect.x+currOuterRect.width-twipsPerPixel,
currOuterRect.y+currOuterRect.height-twipsPerPixel-endRadius,
aGap);
}
}
}
if (aCompositeColors->mNext)
aCompositeColors = aCompositeColors->mNext;
currOuterRect = borderInside;
shrinkage -= twipsPerPixel;
startRadius -= twipsPerPixel;
if (startRadius < 0) startRadius = 0;
endRadius -= twipsPerPixel;
if (endRadius < 0) endRadius = 0;
}
}
// XXX improve this to constrain rendering to the damaged area
void nsCSSRendering::PaintOutline(nsPresContext* aPresContext,
nsIRenderingContext& aRenderingContext,
nsIFrame* aForFrame,
const nsRect& aDirtyRect,
const nsRect& aBorderArea,
const nsStyleBorder& aBorderStyle,
const nsStyleOutline& aOutlineStyle,
nsStyleContext* aStyleContext,
PRIntn aSkipSides,
nsRect* aGap)
{
nsStyleCoord bordStyleRadius[4];
PRInt16 borderRadii[4],i;
float percent;
const nsStyleBackground* bgColor = nsCSSRendering::FindNonTransparentBackground(aStyleContext);
nscoord width, offset;
// Get our style context's color struct.
const nsStyleColor* ourColor = aStyleContext->GetStyleColor();
aOutlineStyle.GetOutlineWidth(width);
if (0 == width) {
// Empty outline
return;
}
// get the radius for our outline
aOutlineStyle.mOutlineRadius.GetTop(bordStyleRadius[0]); //topleft
aOutlineStyle.mOutlineRadius.GetRight(bordStyleRadius[1]); //topright
aOutlineStyle.mOutlineRadius.GetBottom(bordStyleRadius[2]); //bottomright
aOutlineStyle.mOutlineRadius.GetLeft(bordStyleRadius[3]); //bottomleft
for(i=0;i<4;i++) {
borderRadii[i] = 0;
switch ( bordStyleRadius[i].GetUnit()) {
case eStyleUnit_Percent:
percent = bordStyleRadius[i].GetPercentValue();
borderRadii[i] = (nscoord)(percent * aBorderArea.width);
break;
case eStyleUnit_Coord:
borderRadii[i] = bordStyleRadius[i].GetCoordValue();
break;
default:
break;
}
}
nsRect* overflowArea = aForFrame->GetOverflowAreaProperty(PR_FALSE);
if (!overflowArea) {
NS_WARNING("Hmm, outline painting should always find an overflow area here");
return;
}
// get the offset for our outline
aOutlineStyle.GetOutlineOffset(offset);
nsRect outside(*overflowArea);
nsRect inside(outside);
if (width + offset >= 0) {
// the overflow area is exactly the outside edge of the outline
inside.Deflate(width, width);
} else {
// the overflow area is exactly the rectangle containing the frame and its
// children; we can compute the outline directly
inside.Deflate(-offset, -offset);
if (inside.width < 0 || inside.height < 0) {
return; // Protect against negative outline sizes
}
outside = inside;
outside.Inflate(width, width);
}
// rounded version of the border
for(i=0;i<4;i++){
if(borderRadii[i] > 0){
PaintRoundedBorder(aPresContext, aRenderingContext, aForFrame, aDirtyRect,
outside, nsnull, &aOutlineStyle, aStyleContext,
aSkipSides, borderRadii, aGap, PR_TRUE);
return;
}
}
PRUint8 outlineStyle = aOutlineStyle.GetOutlineStyle();
//see if any sides are dotted or dashed
if ((outlineStyle == NS_STYLE_BORDER_STYLE_DOTTED) ||
(outlineStyle == NS_STYLE_BORDER_STYLE_DASHED)) {
DrawDashedSides(0, aRenderingContext, aDirtyRect, ourColor, nsnull, &aOutlineStyle, PR_TRUE,
outside, inside, aSkipSides, aGap);
return;
}
// Draw all the other sides
/* XXX something is misnamed here!!!! */
nscoord twipsPerPixel;/* XXX */
float p2t;/* XXX */
p2t = aPresContext->PixelsToTwips();/* XXX */
twipsPerPixel = (nscoord) p2t;/* XXX */
nscolor outlineColor(NS_RGB(0,0,0)); // default to black in case it is invert color and the platform does not support that
PRBool canDraw = PR_FALSE;
PRBool modeChanged=PR_FALSE;
// see if the outline color is 'invert' or can invert.
if (aOutlineStyle.GetOutlineInvert()) {
canDraw = PR_TRUE;
if( NS_SUCCEEDED(aRenderingContext.SetPenMode(nsPenMode_kInvert)) ) {
modeChanged=PR_TRUE;
}
} else {
canDraw = aOutlineStyle.GetOutlineColor(outlineColor);
}
if (PR_TRUE == canDraw) {
DrawSide(aRenderingContext, NS_SIDE_BOTTOM,
outlineStyle,
outlineColor,
bgColor->mBackgroundColor, outside, inside, aSkipSides,
twipsPerPixel, aGap);
DrawSide(aRenderingContext, NS_SIDE_LEFT,
outlineStyle,
outlineColor,
bgColor->mBackgroundColor,outside, inside,aSkipSides,
twipsPerPixel, aGap);
DrawSide(aRenderingContext, NS_SIDE_TOP,
outlineStyle,
outlineColor,
bgColor->mBackgroundColor,outside, inside,aSkipSides,
twipsPerPixel, aGap);
DrawSide(aRenderingContext, NS_SIDE_RIGHT,
outlineStyle,
outlineColor,
bgColor->mBackgroundColor,outside, inside,aSkipSides,
twipsPerPixel, aGap);
if(modeChanged ) {
aRenderingContext.SetPenMode(nsPenMode_kNone);
}
}
}
/* draw the edges of the border described in aBorderEdges one segment at a time.
* a border has 4 edges. Each edge has 1 or more segments.
* "inside edges" are drawn differently than "outside edges" so the shared edges will match up.
* in the case of table collapsing borders, the table edge is the "outside" edge and
* cell edges are always "inside" edges (so adjacent cells have 2 shared "inside" edges.)
* dashed segments are drawn by DrawDashedSegments().
*/
// XXX: doesn't do corners or junctions well at all. Just uses logic stolen
// from PaintBorder which is insufficient
void nsCSSRendering::PaintBorderEdges(nsPresContext* aPresContext,
nsIRenderingContext& aRenderingContext,
nsIFrame* aForFrame,
const nsRect& aDirtyRect,
const nsRect& aBorderArea,
nsBorderEdges * aBorderEdges,
nsStyleContext* aStyleContext,
PRIntn aSkipSides,
nsRect* aGap)
{
const nsStyleBackground* bgColor = nsCSSRendering::FindNonTransparentBackground(aStyleContext);
if (nsnull==aBorderEdges) { // Empty border segments
return;
}
// Turn off rendering for all of the zero sized sides
if (0 == aBorderEdges->mMaxBorderWidth.top)
aSkipSides |= (1 << NS_SIDE_TOP);
if (0 == aBorderEdges->mMaxBorderWidth.right)
aSkipSides |= (1 << NS_SIDE_RIGHT);
if (0 == aBorderEdges->mMaxBorderWidth.bottom)
aSkipSides |= (1 << NS_SIDE_BOTTOM);
if (0 == aBorderEdges->mMaxBorderWidth.left)
aSkipSides |= (1 << NS_SIDE_LEFT);
// Draw any dashed or dotted segments separately
DrawDashedSegments(aRenderingContext, aBorderArea, aBorderEdges, aSkipSides, aGap);
// Draw all the other sides
nscoord twipsPerPixel;
float p2t;
p2t = aPresContext->PixelsToTwips();
twipsPerPixel = (nscoord) p2t;/* XXX huh!*/
if (0 == (aSkipSides & (1<<NS_SIDE_TOP))) {
PRInt32 segmentCount = aBorderEdges->mEdges[NS_SIDE_TOP].Count();
PRInt32 i;
nsBorderEdge * leftEdge = (nsBorderEdge *)(aBorderEdges->mEdges[NS_SIDE_LEFT].ElementAt(0));
nscoord x = aBorderEdges->mMaxBorderWidth.left - leftEdge->mWidth;
for (i=0; i<segmentCount; i++)
{
nsBorderEdge * borderEdge = (nsBorderEdge *)(aBorderEdges->mEdges[NS_SIDE_TOP].ElementAt(i));
nscoord y = aBorderArea.y;
if (PR_TRUE==aBorderEdges->mOutsideEdge) // segments of the outside edge are bottom-aligned
y += aBorderEdges->mMaxBorderWidth.top - borderEdge->mWidth;
nsRect inside(x, y, borderEdge->mLength, aBorderArea.height);
x += borderEdge->mLength;
nsRect outside(inside);
nsMargin outsideMargin(0, borderEdge->mWidth, 0, 0);
outside.Deflate(outsideMargin);
DrawSide(aRenderingContext, NS_SIDE_TOP,
borderEdge->mStyle,
borderEdge->mColor,
bgColor->mBackgroundColor,
inside, outside,aSkipSides,
twipsPerPixel, aGap);
}
}
if (0 == (aSkipSides & (1<<NS_SIDE_LEFT))) {
PRInt32 segmentCount = aBorderEdges->mEdges[NS_SIDE_LEFT].Count();
PRInt32 i;
nsBorderEdge * topEdge = (nsBorderEdge *)(aBorderEdges->mEdges[NS_SIDE_TOP].ElementAt(0));
nscoord y = aBorderEdges->mMaxBorderWidth.top - topEdge->mWidth;
for (i=0; i<segmentCount; i++)
{
nsBorderEdge * borderEdge = (nsBorderEdge *)(aBorderEdges->mEdges[NS_SIDE_LEFT].ElementAt(i));
nscoord x = aBorderArea.x + (aBorderEdges->mMaxBorderWidth.left - borderEdge->mWidth);
nsRect inside(x, y, aBorderArea.width, borderEdge->mLength);
y += borderEdge->mLength;
nsRect outside(inside);
nsMargin outsideMargin(borderEdge->mWidth, 0, 0, 0);
outside.Deflate(outsideMargin);
DrawSide(aRenderingContext, NS_SIDE_LEFT,
borderEdge->mStyle,
borderEdge->mColor,
bgColor->mBackgroundColor,
inside, outside, aSkipSides,
twipsPerPixel, aGap);
}
}
if (0 == (aSkipSides & (1<<NS_SIDE_BOTTOM))) {
PRInt32 segmentCount = aBorderEdges->mEdges[NS_SIDE_BOTTOM].Count();
PRInt32 i;
nsBorderEdge * leftEdge = (nsBorderEdge *)
(aBorderEdges->mEdges[NS_SIDE_LEFT].ElementAt(aBorderEdges->mEdges[NS_SIDE_LEFT].Count()-1));
nscoord x = aBorderEdges->mMaxBorderWidth.left - leftEdge->mWidth;
for (i=0; i<segmentCount; i++)
{
nsBorderEdge * borderEdge = (nsBorderEdge *)(aBorderEdges->mEdges[NS_SIDE_BOTTOM].ElementAt(i));
nscoord y = aBorderArea.y;
if (PR_TRUE==aBorderEdges->mOutsideEdge) // segments of the outside edge are top-aligned
y -= (aBorderEdges->mMaxBorderWidth.bottom - borderEdge->mWidth);
nsRect inside(x, y, borderEdge->mLength, aBorderArea.height);
x += borderEdge->mLength;
nsRect outside(inside);
nsMargin outsideMargin(0, 0, 0, borderEdge->mWidth);
outside.Deflate(outsideMargin);
DrawSide(aRenderingContext, NS_SIDE_BOTTOM,
borderEdge->mStyle,
borderEdge->mColor,
bgColor->mBackgroundColor,
inside, outside,aSkipSides,
twipsPerPixel, aGap);
}
}
if (0 == (aSkipSides & (1<<NS_SIDE_RIGHT))) {
PRInt32 segmentCount = aBorderEdges->mEdges[NS_SIDE_RIGHT].Count();
PRInt32 i;
nsBorderEdge * topEdge = (nsBorderEdge *)
(aBorderEdges->mEdges[NS_SIDE_TOP].ElementAt(aBorderEdges->mEdges[NS_SIDE_TOP].Count()-1));
nscoord y = aBorderEdges->mMaxBorderWidth.top - topEdge->mWidth;
for (i=0; i<segmentCount; i++)
{
nsBorderEdge * borderEdge = (nsBorderEdge *)(aBorderEdges->mEdges[NS_SIDE_RIGHT].ElementAt(i));
nscoord width;
if (PR_TRUE==aBorderEdges->mOutsideEdge)
{
width = aBorderArea.width - aBorderEdges->mMaxBorderWidth.right;
width += borderEdge->mWidth;
}
else
{
width = aBorderArea.width;
}
nsRect inside(aBorderArea.x, y, width, borderEdge->mLength);
y += borderEdge->mLength;
nsRect outside(inside);
nsMargin outsideMargin(0, 0, (borderEdge->mWidth), 0);
outside.Deflate(outsideMargin);
DrawSide(aRenderingContext, NS_SIDE_RIGHT,
borderEdge->mStyle,
borderEdge->mColor,
bgColor->mBackgroundColor,
inside, outside,aSkipSides,
twipsPerPixel, aGap);
}
}
}
//----------------------------------------------------------------------
// Returns the anchor point to use for the background image. The
// anchor point is the (x, y) location where the first tile should
// be placed
//
// For repeated tiling, the anchor values are normalized wrt to the upper-left
// edge of the bounds, and are always in the range:
// -(aTileWidth - 1) <= anchor.x <= 0
// -(aTileHeight - 1) <= anchor.y <= 0
//
// i.e., they are either 0 or a negative number whose absolute value is
// less than the tile size in that dimension
//
// aOriginBounds is the box to which the tiling position should be relative
// aClipBounds is the box in which the tiling will actually be done
// They should correspond to 'background-origin' and 'background-clip',
// except when painting on the canvas, in which case the origin bounds
// should be the bounds of the root element's frame and the clip bounds
// should be the bounds of the canvas frame.
static void
ComputeBackgroundAnchorPoint(const nsStyleBackground& aColor,
const nsRect& aOriginBounds,
const nsRect& aClipBounds,
nscoord aTileWidth, nscoord aTileHeight,
nsPoint& aResult)
{
nscoord x;
if (NS_STYLE_BG_X_POSITION_LENGTH & aColor.mBackgroundFlags) {
x = aColor.mBackgroundXPosition.mCoord;
}
else if (NS_STYLE_BG_X_POSITION_PERCENT & aColor.mBackgroundFlags) {
PRFloat64 percent = PRFloat64(aColor.mBackgroundXPosition.mFloat);
nscoord tilePos = nscoord(percent * PRFloat64(aTileWidth));
nscoord boxPos = nscoord(percent * PRFloat64(aOriginBounds.width));
x = boxPos - tilePos;
}
else {
x = 0;
}
x += aOriginBounds.x - aClipBounds.x;
if (NS_STYLE_BG_REPEAT_X & aColor.mBackgroundRepeat) {
// When we are tiling in the x direction the loop will run from
// the left edge of the box to the right edge of the box. We need
// to adjust the starting coordinate to lie within the band being
// rendered.
if (x < 0) {
x = -x;
if (x < 0) {
// Some joker gave us max-negative-integer.
x = 0;
}
x %= aTileWidth;
x = -x;
}
else if (x != 0) {
x %= aTileWidth;
if (x > 0) {
x = x - aTileWidth;
}
}
NS_POSTCONDITION((x >= -(aTileWidth - 1)) && (x <= 0), "bad computed anchor value");
}
aResult.x = x;
nscoord y;
if (NS_STYLE_BG_Y_POSITION_LENGTH & aColor.mBackgroundFlags) {
y = aColor.mBackgroundYPosition.mCoord;
}
else if (NS_STYLE_BG_Y_POSITION_PERCENT & aColor.mBackgroundFlags){
PRFloat64 percent = PRFloat64(aColor.mBackgroundYPosition.mFloat);
nscoord tilePos = nscoord(percent * PRFloat64(aTileHeight));
nscoord boxPos = nscoord(percent * PRFloat64(aOriginBounds.height));
y = boxPos - tilePos;
}
else {
y = 0;
}
y += aOriginBounds.y - aClipBounds.y;
if (NS_STYLE_BG_REPEAT_Y & aColor.mBackgroundRepeat) {
// When we are tiling in the y direction the loop will run from
// the top edge of the box to the bottom edge of the box. We need
// to adjust the starting coordinate to lie within the band being
// rendered.
if (y < 0) {
y = -y;
if (y < 0) {
// Some joker gave us max-negative-integer.
y = 0;
}
y %= aTileHeight;
y = -y;
}
else if (y != 0) {
y %= aTileHeight;
if (y > 0) {
y = y - aTileHeight;
}
}
NS_POSTCONDITION((y >= -(aTileHeight - 1)) && (y <= 0), "bad computed anchor value");
}
aResult.y = y;
}
// Returns the root scrollable frame, which is the first child of the root
// frame.
static nsIScrollableFrame*
GetRootScrollableFrame(nsPresContext* aPresContext, nsIFrame* aRootFrame)
{
nsIScrollableFrame* scrollableFrame = nsnull;
if (nsLayoutAtoms::viewportFrame == aRootFrame->GetType()) {
nsIFrame* childFrame = aRootFrame->GetFirstChild(nsnull);
if (childFrame) {
if (nsLayoutAtoms::scrollFrame == childFrame->GetType()) {
// Use this frame, even if we are using GFX frames for the
// viewport, which contains another scroll frame below this
// frame, since the GFX scrollport frame does not implement
// nsIScrollableFrame.
CallQueryInterface(childFrame, &scrollableFrame);
}
}
}
#ifdef DEBUG
else {
NS_WARNING("aRootFrame is not a viewport frame");
}
#endif // DEBUG
return scrollableFrame;
}
const nsStyleBackground*
nsCSSRendering::FindNonTransparentBackground(nsStyleContext* aContext,
PRBool aStartAtParent /*= PR_FALSE*/)
{
NS_ASSERTION(aContext, "Cannot find NonTransparentBackground in a null context" );
const nsStyleBackground* result = nsnull;
nsStyleContext* context = nsnull;
if (aStartAtParent) {
context = aContext->GetParent();
}
if (!context) {
context = aContext;
}
while (context) {
result = context->GetStyleBackground();
if (0 == (result->mBackgroundFlags & NS_STYLE_BG_COLOR_TRANSPARENT))
break;
context = context->GetParent();
}
return result;
}
/**
* |FindBackground| finds the correct style data to use to paint the
* background. It is responsible for handling the following two
* statements in section 14.2 of CSS2:
*
* The background of the box generated by the root element covers the
* entire canvas.
*
* For HTML documents, however, we recommend that authors specify the
* background for the BODY element rather than the HTML element. User
* agents should observe the following precedence rules to fill in the
* background: if the value of the 'background' property for the HTML
* element is different from 'transparent' then use it, else use the
* value of the 'background' property for the BODY element. If the
* resulting value is 'transparent', the rendering is undefined.
*
* Thus, in our implementation, it is responsible for ensuring that:
* + we paint the correct background on the |nsCanvasFrame|,
* |nsRootBoxFrame|, or |nsPageFrame|,
* + we don't paint the background on the root element, and
* + we don't paint the background on the BODY element in *some* cases,
* and for SGML-based HTML documents only.
*
* |FindBackground| returns true if a background should be painted, and
* the resulting style context to use for the background information
* will be filled in to |aBackground|. It fills in a boolean indicating
* whether the frame is the canvas frame to allow PaintBackground to
* ensure that it always paints something non-transparent for the
* canvas.
*/
// Returns nsnull if aFrame is not a canvas frame.
// Otherwise, it returns the frame we should look for the background on.
// This is normally aFrame but if aFrame is the viewport, we need to
// look for the background starting at the scroll root (which shares
// style context with the document root) or the document root itself.
// We need to treat the viewport as canvas because, even though
// it does not actually paint a background, we need to get the right
// background style so we correctly detect transparent documents.
inline nsIFrame*
IsCanvasFrame(nsPresContext* aPresContext, nsIFrame *aFrame)
{
nsIAtom* frameType = aFrame->GetType();
if (frameType == nsLayoutAtoms::canvasFrame ||
frameType == nsLayoutAtoms::rootFrame ||
frameType == nsLayoutAtoms::pageFrame) {
return aFrame;
} else if (frameType == nsLayoutAtoms::viewportFrame) {
nsIFrame* firstChild = aFrame->GetFirstChild(nsnull);
if (firstChild) {
return firstChild;
}
}
return nsnull;
}
inline PRBool
FindCanvasBackground(nsPresContext* aPresContext,
nsIFrame* aForFrame,
const nsStyleBackground** aBackground)
{
// XXXldb What if the root element is positioned, etc.? (We don't
// allow that yet, do we?)
nsIFrame *firstChild = aForFrame->GetFirstChild(nsnull);
if (firstChild) {
const nsStyleBackground* result = firstChild->GetStyleBackground();
// for printing and print preview.. this should be a pageContentFrame
nsStyleContext* parentContext;
if (firstChild->GetType() == nsLayoutAtoms::pageContentFrame) {
// we have to find the background style ourselves.. since the
// pageContentframe does not have content
while(firstChild){
for (nsIFrame* kidFrame = firstChild; nsnull != kidFrame; ) {
parentContext = kidFrame->GetStyleContext();
result = parentContext->GetStyleBackground();
if (!result->IsTransparent()) {
*aBackground = kidFrame->GetStyleBackground();
return PR_TRUE;
} else {
kidFrame = kidFrame->GetNextSibling();
}
}
firstChild = firstChild->GetFirstChild(nsnull);
}
return PR_FALSE; // nothing found for this
}
// Check if we need to do propagation from BODY rather than HTML.
if (result->IsTransparent()) {
nsIContent* content = aForFrame->GetContent();
if (content) {
// Use |GetOwnerDoc| so it works during destruction.
nsIDocument* document = content->GetOwnerDoc();
nsCOMPtr<nsIDOMHTMLDocument> htmlDoc = do_QueryInterface(document);
if (htmlDoc) {
if (!document->IsCaseSensitive()) { // HTML, not XHTML
nsCOMPtr<nsIDOMHTMLElement> body;
htmlDoc->GetBody(getter_AddRefs(body));
nsCOMPtr<nsIContent> bodyContent = do_QueryInterface(body);
// We need to null check the body node (bug 118829) since
// there are cases, thanks to the fix for bug 5569, where we
// will reflow a document with no body. In particular, if a
// SCRIPT element in the head blocks the parser and then has a
// SCRIPT that does "document.location.href = 'foo'", then
// nsParser::Terminate will call |DidBuildModel| methods
// through to the content sink, which will call |StartLayout|
// and thus |InitialReflow| on the pres shell. See bug 119351
// for the ugly details.
if (bodyContent) {
nsIFrame *bodyFrame;
nsresult rv = aPresContext->PresShell()->
GetPrimaryFrameFor(bodyContent, &bodyFrame);
if (NS_SUCCEEDED(rv) && bodyFrame)
result = bodyFrame->GetStyleBackground();
}
}
}
}
}
*aBackground = result;
} else {
// This should always give transparent, so we'll fill it in with the
// default color if needed. This seems to happen a bit while a page is
// being loaded.
*aBackground = aForFrame->GetStyleBackground();
}
return PR_TRUE;
}
inline PRBool
FindElementBackground(nsPresContext* aPresContext,
nsIFrame* aForFrame,
const nsStyleBackground** aBackground)
{
nsIFrame *parentFrame = aForFrame->GetParent();
// XXXldb We shouldn't have to null-check |parentFrame| here.
if (parentFrame && IsCanvasFrame(aPresContext, parentFrame) == parentFrame) {
// Check that we're really the root (rather than in another child list).
nsIFrame *childFrame = parentFrame->GetFirstChild(nsnull);
if (childFrame == aForFrame)
return PR_FALSE; // Background was already drawn for the canvas.
}
*aBackground = aForFrame->GetStyleBackground();
// Return true unless the frame is for a BODY element whose background
// was propagated to the viewport.
if (aForFrame->GetStyleContext()->GetPseudoType())
return PR_TRUE; // A pseudo-element frame.
nsIContent* content = aForFrame->GetContent();
if (!content || !content->IsContentOfType(nsIContent::eHTML))
return PR_TRUE; // not frame for an HTML element
if (!parentFrame)
return PR_TRUE; // no parent to look at
if (content->Tag() != nsHTMLAtoms::body)
return PR_TRUE; // not frame for <BODY> element
// We should only look at the <html> background if we're in an HTML document
nsIDocument* document = content->GetOwnerDoc();
nsCOMPtr<nsIDOMHTMLDocument> htmlDoc = do_QueryInterface(document);
if (!htmlDoc)
return PR_TRUE;
if (document->IsCaseSensitive()) // XHTML, not HTML
return PR_TRUE;
const nsStyleBackground* htmlBG = parentFrame->GetStyleBackground();
return !htmlBG->IsTransparent();
}
PRBool
nsCSSRendering::FindBackground(nsPresContext* aPresContext,
nsIFrame* aForFrame,
const nsStyleBackground** aBackground,
PRBool* aIsCanvas)
{
nsIFrame* canvasFrame = IsCanvasFrame(aPresContext, aForFrame);
*aIsCanvas = canvasFrame != nsnull;
return canvasFrame
? FindCanvasBackground(aPresContext, canvasFrame, aBackground)
: FindElementBackground(aPresContext, aForFrame, aBackground);
}
void
nsCSSRendering::DidPaint()
{
gInlineBGData.Reset();
}
void
nsCSSRendering::PaintBackground(nsPresContext* aPresContext,
nsIRenderingContext& aRenderingContext,
nsIFrame* aForFrame,
const nsRect& aDirtyRect,
const nsRect& aBorderArea,
const nsStyleBorder& aBorder,
const nsStylePadding& aPadding,
PRBool aUsePrintSettings,
nsRect* aBGClipRect)
{
NS_PRECONDITION(aForFrame,
"Frame is expected to be provided to PaintBackground");
PRBool isCanvas;
const nsStyleBackground *color;
if (!FindBackground(aPresContext, aForFrame, &color, &isCanvas)) {
// we don't want to bail out of moz-appearance is set on a root
// node. If it has a parent content node, bail because it's not
// a root, other wise keep going in order to let the theme stuff
// draw the background. The canvas really should be drawing the
// bg, but there's no way to hook that up via css.
if (!aForFrame->GetStyleDisplay()->mAppearance) {
return;
}
nsIContent* content = aForFrame->GetContent();
if (!content || content->GetParent()) {
return;
}
color = aForFrame->GetStyleBackground();
}
if (!isCanvas) {
PaintBackgroundWithSC(aPresContext, aRenderingContext, aForFrame,
aDirtyRect, aBorderArea, *color, aBorder,
aPadding, aUsePrintSettings, aBGClipRect);
return;
}
if (!color)
return;
nsStyleBackground canvasColor(*color);
nsIViewManager* vm = aPresContext->GetViewManager();
if (canvasColor.mBackgroundFlags & NS_STYLE_BG_COLOR_TRANSPARENT) {
nsIView* rootView;
vm->GetRootView(rootView);
if (!rootView->GetParent()) {
PRBool widgetIsTranslucent = PR_FALSE;
if (rootView->HasWidget()) {
rootView->GetWidget()->GetWindowTranslucency(widgetIsTranslucent);
}
if (!widgetIsTranslucent) {
// Ensure that we always paint a color for the root (in case there's
// no background at all or a partly transparent image).
canvasColor.mBackgroundFlags &= ~NS_STYLE_BG_COLOR_TRANSPARENT;
canvasColor.mBackgroundColor = aPresContext->DefaultBackgroundColor();
}
}
}
vm->SetDefaultBackgroundColor(canvasColor.mBackgroundColor);
// Since nsHTMLContainerFrame::CreateViewForFrame might have created
// the view before we knew about the child with the fixed background
// attachment (root or BODY) or the stylesheet specifying that
// attachment, set the BitBlt flag here as well.
if (canvasColor.mBackgroundAttachment == NS_STYLE_BG_ATTACHMENT_FIXED) {
nsIView *view = aForFrame->GetView();
if (view)
vm->SetViewBitBltEnabled(view, PR_FALSE);
}
PaintBackgroundWithSC(aPresContext, aRenderingContext, aForFrame,
aDirtyRect, aBorderArea, canvasColor,
aBorder, aPadding, aUsePrintSettings, aBGClipRect);
}
void
nsCSSRendering::PaintBackgroundWithSC(nsPresContext* aPresContext,
nsIRenderingContext& aRenderingContext,
nsIFrame* aForFrame,
const nsRect& aDirtyRect,
const nsRect& aBorderArea,
const nsStyleBackground& aColor,
const nsStyleBorder& aBorder,
const nsStylePadding& aPadding,
PRBool aUsePrintSettings,
nsRect* aBGClipRect)
{
NS_PRECONDITION(aForFrame,
"Frame is expected to be provided to PaintBackground");
PRBool canDrawBackgroundImage = PR_TRUE;
PRBool canDrawBackgroundColor = PR_TRUE;
if (aUsePrintSettings) {
canDrawBackgroundImage = aPresContext->GetBackgroundImageDraw();
canDrawBackgroundColor = aPresContext->GetBackgroundColorDraw();
}
// Check to see if we have an appearance defined. If so, we let the theme
// renderer draw the background and bail out.
const nsStyleDisplay* displayData = aForFrame->GetStyleDisplay();
if (displayData->mAppearance) {
nsITheme *theme = aPresContext->GetTheme();
if (theme && theme->ThemeSupportsWidget(aPresContext, aForFrame, displayData->mAppearance)) {
theme->DrawWidgetBackground(&aRenderingContext, aForFrame,
displayData->mAppearance, aBorderArea, aDirtyRect);
return;
}
}
nsRect bgClipArea;
if (aBGClipRect) {
bgClipArea = *aBGClipRect;
}
else {
// The background is rendered over the 'background-clip' area.
bgClipArea = aBorderArea;
if (aColor.mBackgroundClip != NS_STYLE_BG_CLIP_BORDER) {
NS_ASSERTION(aColor.mBackgroundClip == NS_STYLE_BG_CLIP_PADDING,
"unknown background-clip value");
bgClipArea.Deflate(aBorder.GetBorder());
}
}
// The actual dirty rect is the intersection of the 'background-clip'
// area and the dirty rect we were given
nsRect dirtyRect;
if (!dirtyRect.IntersectRect(bgClipArea, aDirtyRect)) {
// Nothing to paint
return;
}
// if there is no background image or background images are turned off, try a color.
if (!aColor.mBackgroundImage || !canDrawBackgroundImage) {
PaintBackgroundColor(aPresContext, aRenderingContext, aForFrame, bgClipArea,
aColor, aBorder, aPadding, canDrawBackgroundColor);
return;
}
// We have a background image
// Lookup the image
imgIRequest *req = aPresContext->LoadImage(aColor.mBackgroundImage,
aForFrame);
PRUint32 status = imgIRequest::STATUS_ERROR;
if (req)
req->GetImageStatus(&status);
if (!req || !(status & imgIRequest::STATUS_FRAME_COMPLETE) || !(status & imgIRequest::STATUS_SIZE_AVAILABLE)) {
PaintBackgroundColor(aPresContext, aRenderingContext, aForFrame, bgClipArea,
aColor, aBorder, aPadding, canDrawBackgroundColor);
return;
}
nsCOMPtr<imgIContainer> image;
req->GetImage(getter_AddRefs(image));
nsSize imageSize;
image->GetWidth(&imageSize.width);
image->GetHeight(&imageSize.height);
float p2t;
p2t = aPresContext->PixelsToTwips();
imageSize.width = NSIntPixelsToTwips(imageSize.width, p2t);
imageSize.height = NSIntPixelsToTwips(imageSize.height, p2t);
req = nsnull;
nsRect bgOriginArea;
nsIAtom* frameType = aForFrame->GetType();
if (frameType == nsLayoutAtoms::inlineFrame) {
switch (aColor.mBackgroundInlinePolicy) {
case NS_STYLE_BG_INLINE_POLICY_EACH_BOX:
bgOriginArea = aBorderArea;
break;
case NS_STYLE_BG_INLINE_POLICY_BOUNDING_BOX:
bgOriginArea = gInlineBGData.GetBoundingRect(aForFrame);
break;
default:
NS_ERROR("Unknown background-inline-policy value! "
"Please, teach me what to do.");
case NS_STYLE_BG_INLINE_POLICY_CONTINUOUS:
bgOriginArea = gInlineBGData.GetContinuousRect(aForFrame);
break;
}
}
else {
bgOriginArea = aBorderArea;
}
// Background images are tiled over the 'background-clip' area
// but the origin of the tiling is based on the 'background-origin' area
if (aColor.mBackgroundOrigin != NS_STYLE_BG_ORIGIN_BORDER) {
bgOriginArea.Deflate(aBorder.GetBorder());
if (aColor.mBackgroundOrigin != NS_STYLE_BG_ORIGIN_PADDING) {
nsMargin padding;
// XXX CalcPaddingFor is deprecated, but we need it for percentage padding
aPadding.CalcPaddingFor(aForFrame, padding);
bgOriginArea.Deflate(padding);
NS_ASSERTION(aColor.mBackgroundOrigin == NS_STYLE_BG_ORIGIN_CONTENT,
"unknown background-origin value");
}
}
// Based on the repeat setting, compute how many tiles we should
// lay down for each axis. The value computed is the maximum based
// on the dirty rect before accounting for the background-position.
nscoord tileWidth = imageSize.width;
nscoord tileHeight = imageSize.height;
PRBool needBackgroundColor = !(aColor.mBackgroundFlags &
NS_STYLE_BG_COLOR_TRANSPARENT);
PRIntn repeat = aColor.mBackgroundRepeat;
nscoord xDistance, yDistance;
switch (repeat) {
case NS_STYLE_BG_REPEAT_X:
xDistance = dirtyRect.width;
yDistance = tileHeight;
break;
case NS_STYLE_BG_REPEAT_Y:
xDistance = tileWidth;
yDistance = dirtyRect.height;
break;
case NS_STYLE_BG_REPEAT_XY:
xDistance = dirtyRect.width;
yDistance = dirtyRect.height;
if (needBackgroundColor) {
// If the image is completely opaque, we do not need to paint the
// background color
nsCOMPtr<gfxIImageFrame> gfxImgFrame;
image->GetCurrentFrame(getter_AddRefs(gfxImgFrame));
if (gfxImgFrame) {
gfxImgFrame->GetNeedsBackground(&needBackgroundColor);
/* check for tiling of a image where frame smaller than container */
nsSize iSize;
image->GetWidth(&iSize.width);
image->GetHeight(&iSize.height);
nsRect iframeRect;
gfxImgFrame->GetRect(iframeRect);
if (iSize.width != iframeRect.width ||
iSize.height != iframeRect.height) {
needBackgroundColor = PR_TRUE;
}
}
}
break;
case NS_STYLE_BG_REPEAT_OFF:
default:
NS_ASSERTION(repeat == NS_STYLE_BG_REPEAT_OFF, "unknown background-repeat value");
xDistance = tileWidth;
yDistance = tileHeight;
break;
}
// The background color is rendered over the 'background-clip' area
if (needBackgroundColor) {
PaintBackgroundColor(aPresContext, aRenderingContext, aForFrame, bgClipArea,
aColor, aBorder, aPadding, canDrawBackgroundColor);
}
if ((tileWidth == 0) || (tileHeight == 0) || dirtyRect.IsEmpty()) {
// Nothing left to paint
return;
}
// Compute the anchor point.
//
// When tiling, the anchor coordinate values will be negative offsets
// from the background-origin area.
nsPoint anchor;
if (NS_STYLE_BG_ATTACHMENT_FIXED == aColor.mBackgroundAttachment) {
// If it's a fixed background attachment, then the image is placed
// relative to the viewport
nsIView* viewportView = nsnull;
nsRect viewportArea;
nsIFrame* rootFrame =
aPresContext->PresShell()->FrameManager()->GetRootFrame();
NS_ASSERTION(rootFrame, "no root frame");
if (aPresContext->IsPaginated()) {
nsIFrame* page = nsLayoutUtils::GetPageFrame(aForFrame);
NS_ASSERTION(page, "no page");
rootFrame = page;
}
viewportView = rootFrame->GetView();
NS_ASSERTION(viewportView, "no viewport view");
viewportArea = viewportView->GetBounds();
viewportArea.x = 0;
viewportArea.y = 0;
nsIScrollableFrame* scrollableFrame =
GetRootScrollableFrame(aPresContext, rootFrame);
if (scrollableFrame) {
nsMargin scrollbars = scrollableFrame->GetActualScrollbarSizes();
viewportArea.Deflate(scrollbars);
}
// Get the anchor point
ComputeBackgroundAnchorPoint(aColor, viewportArea, viewportArea, tileWidth, tileHeight, anchor);
// Convert the anchor point to aForFrame's coordinate space
nsPoint offset(0, 0);
nsIView* view = aForFrame->GetClosestView(&offset);
anchor -= offset;
NS_ASSERTION(view, "expected a view");
anchor -= view->GetOffsetTo(viewportView);
} else {
if (frameType == nsLayoutAtoms::canvasFrame) {
// If the frame is the canvas, the image is placed relative to
// the root element's (first) frame (see bug 46446)
nsRect firstRootElementFrameArea;
nsIFrame* firstRootElementFrame = aForFrame->GetFirstChild(nsnull);
NS_ASSERTION(firstRootElementFrame, "A canvas with a background "
"image had no child frame, which is impossible according to CSS. "
"Make sure there isn't a background image specified on the "
"|:viewport| pseudo-element in |html.css|.");
// temporary null check -- see bug 97226
if (firstRootElementFrame) {
firstRootElementFrameArea = firstRootElementFrame->GetRect();
// Take the border out of the frame's rect
const nsStyleBorder* borderStyle = firstRootElementFrame->GetStyleBorder();
firstRootElementFrameArea.Deflate(borderStyle->GetBorder());
// Get the anchor point
ComputeBackgroundAnchorPoint(aColor, firstRootElementFrameArea, bgClipArea, tileWidth, tileHeight, anchor);
} else {
ComputeBackgroundAnchorPoint(aColor, bgOriginArea, bgClipArea, tileWidth, tileHeight, anchor);
}
} else {
// Otherwise, it is the normal case, and the background is
// simply placed relative to the frame's background-clip area
ComputeBackgroundAnchorPoint(aColor, bgOriginArea, bgClipArea, tileWidth, tileHeight, anchor);
}
}
#if (!defined(XP_UNIX) && !defined(XP_BEOS)) || defined(XP_MACOSX)
// Setup clipping so that rendering doesn't leak out of the computed
// dirty rect
aRenderingContext.PushState();
aRenderingContext.SetClipRect(dirtyRect, nsClipCombine_kIntersect);
#endif
// Compute the x and y starting points and limits for tiling
/* An Overview Of The Following Logic
A........ . . . . . . . . . . . . . .
: +---:-------.-------.-------.---- /|\
: | : . . . | nh
:.......: . . . x . . . . . . . . . . \|/
. | . . . .
. | . . ########### .
. . . . . . . . . .#. . . . .#. . . .
. | . . ########### . /|\
. | . . . . | h
. . | . . . . . . . . . . . . . z . . \|/
. | . . . .
|<-----nw------>| |<--w-->|
---- = the background clip area edge. The painting is done within
to this area. If the background is positioned relative to the
viewport ('fixed') then this is the viewport edge.
.... = the primary tile.
. . = the other tiles.
#### = the dirtyRect. This is the minimum region we want to cover.
A = The anchor point. This is the point at which the tile should
start. Always negative or zero.
x = x0 and y0 in the code. The point at which tiling must start
so that the fewest tiles are laid out while completly
covering the dirtyRect area.
z = x1 and y1 in the code. The point at which tiling must end so
that the fewest tiles are laid out while completly covering
the dirtyRect area.
w = the width of the tile (tileWidth).
h = the height of the tile (tileHeight).
n = the number of whole tiles that fit between 'A' and 'x'.
(the vertical n and the horizontal n are different)
Therefore,
x0 = bgClipArea.x + anchor.x + n * tileWidth;
...where n is an integer greater or equal to 0 fitting:
n * tileWidth <=
dirtyRect.x - (bgClipArea.x + anchor.x) <=
(n+1) * tileWidth
...i.e.,
n <= (dirtyRect.x - (bgClipArea.x + anchor.x)) / tileWidth < n + 1
...which, treating the division as an integer divide rounding down, gives:
n = (dirtyRect.x - (bgClipArea.x + anchor.x)) / tileWidth
Substituting into the original expression for x0:
x0 = bgClipArea.x + anchor.x +
((dirtyRect.x - (bgClipArea.x + anchor.x)) / tileWidth) *
tileWidth;
From this x1 is determined,
x1 = x0 + m * tileWidth;
...where m is an integer greater than 0 fitting:
(m - 1) * tileWidth <
dirtyRect.x + dirtyRect.width - x0 <=
m * tileWidth
...i.e.,
m - 1 < (dirtyRect.x + dirtyRect.width - x0) / tileWidth <= m
...which, treating the division as an integer divide, and making it
round up, gives:
m = (dirtyRect.x + dirtyRect.width - x0 + tileWidth - 1) / tileWidth
Substituting into the original expression for x1:
x1 = x0 + ((dirtyRect.x + dirtyRect.width - x0 + tileWidth - 1) /
tileWidth) * tileWidth
The vertical case is analogous. If the background is fixed, then
bgClipArea.x and bgClipArea.y are set to zero when finding the parent
viewport, above.
*/
// first do the horizontal case
nscoord x0, x1;
// For scrolling attachment, the anchor is within the 'background-clip'
// For fixed attachment, the anchor is within the bounds of the nearest
// scrolling ancestor (or the viewport)
x0 = (NS_STYLE_BG_ATTACHMENT_SCROLL == aColor.mBackgroundAttachment) ?
bgClipArea.x : 0;
if (repeat & NS_STYLE_BG_REPEAT_X) {
// When tiling in the x direction, adjust the starting position of the
// tile to account for dirtyRect.x. When tiling in x, the anchor.x value
// will be a negative value used to adjust the starting coordinate.
x0 += anchor.x +
((dirtyRect.x - (bgClipArea.x + anchor.x)) / tileWidth) * tileWidth;
x1 = x0 + ((dirtyRect.x + dirtyRect.width - x0 + tileWidth - 1) / tileWidth) * tileWidth;
}
else {
x0 += anchor.x;
x1 = x0 + tileWidth;
}
// now do all that again with the vertical case
nscoord y0, y1;
// For scrolling attachment, the anchor is within the 'background-clip'
// For fixed attachment, the anchor is within the bounds of the nearest
// scrolling ancestor (or the viewport)
y0 = (NS_STYLE_BG_ATTACHMENT_SCROLL == aColor.mBackgroundAttachment) ?
bgClipArea.y : 0;
if (repeat & NS_STYLE_BG_REPEAT_Y) {
// When tiling in the y direction, adjust the starting position of the
// tile to account for dirtyRect.y. When tiling in y, the anchor.y value
// will be a negative value used to adjust the starting coordinate.
y0 += anchor.y +
((dirtyRect.y - (bgClipArea.y + anchor.y)) / tileHeight) * tileHeight;
y1 = y0 + ((dirtyRect.y + dirtyRect.height - y0 + tileHeight - 1) / tileHeight) * tileHeight;
}
else {
y0 += anchor.y;
y1 = y0 + tileHeight;
}
// Take the intersection again to paint only the required area
nsRect tileRect(x0, y0, (x1 - x0), (y1 - y0));
nsRect drawRect;
if (drawRect.IntersectRect(tileRect, dirtyRect))
aRenderingContext.DrawTile(image, x0, y0, &drawRect);
#if (!defined(XP_UNIX) && !defined(XP_BEOS)) || defined(XP_MACOSX)
// Restore clipping
aRenderingContext.PopState();
#endif
}
void
nsCSSRendering::PaintBackgroundColor(nsPresContext* aPresContext,
nsIRenderingContext& aRenderingContext,
nsIFrame* aForFrame,
const nsRect& aBgClipArea,
const nsStyleBackground& aColor,
const nsStyleBorder& aBorder,
const nsStylePadding& aPadding,
PRBool aCanPaintNonWhite)
{
if (aColor.mBackgroundFlags & NS_STYLE_BG_COLOR_TRANSPARENT) {
// nothing to paint
return;
}
nsStyleCoord bordStyleRadius[4];
PRInt16 borderRadii[4];
nsRect bgClipArea(aBgClipArea);
// get the radius for our border
aBorder.mBorderRadius.GetTop(bordStyleRadius[NS_SIDE_TOP]); // topleft
aBorder.mBorderRadius.GetRight(bordStyleRadius[NS_SIDE_RIGHT]); // topright
aBorder.mBorderRadius.GetBottom(bordStyleRadius[NS_SIDE_BOTTOM]); // bottomright
aBorder.mBorderRadius.GetLeft(bordStyleRadius[NS_SIDE_LEFT]); // bottomleft
PRUint8 side = 0;
for (; side < 4; ++side) {
borderRadii[side] = 0;
switch (bordStyleRadius[side].GetUnit()) {
case eStyleUnit_Percent:
borderRadii[side] = nscoord(bordStyleRadius[side].GetPercentValue() * aBgClipArea.width);
break;
case eStyleUnit_Coord:
borderRadii[side] = bordStyleRadius[side].GetCoordValue();
break;
default:
break;
}
}
// Rounded version of the border
// XXXdwh Composite borders (with multiple colors per side) use their own border radius
// algorithm now, since the current one doesn't work right for small radii.
if (!aBorder.mBorderColors) {
for (side = 0; side < 4; ++side) {
if (borderRadii[side] > 0) {
PaintRoundedBackground(aPresContext, aRenderingContext, aForFrame,
bgClipArea, aColor, aBorder, borderRadii,
aCanPaintNonWhite);
return;
}
}
}
else if (aColor.mBackgroundClip == NS_STYLE_BG_CLIP_BORDER) {
// XXX users of -moz-border-*-colors expect a transparent border-color
// to show the parent's background-color instead of its background-color.
// This seems wrong, but we handle that here by explictly clipping the
// background to the padding area.
bgClipArea.Deflate(aBorder.GetBorder());
}
nscolor color = aColor.mBackgroundColor;
if (!aCanPaintNonWhite) {
color = NS_RGB(255, 255, 255);
}
aRenderingContext.SetColor(color);
aRenderingContext.FillRect(bgClipArea);
}
/** ---------------------------------------------------
* See documentation in nsCSSRendering.h
* @update 3/26/99 dwc
*/
void
nsCSSRendering::PaintRoundedBackground(nsPresContext* aPresContext,
nsIRenderingContext& aRenderingContext,
nsIFrame* aForFrame,
const nsRect& aBgClipArea,
const nsStyleBackground& aColor,
const nsStyleBorder& aBorder,
PRInt16 aTheRadius[4],
PRBool aCanPaintNonWhite)
{
RoundedRect outerPath;
QBCurve cr1,cr2,cr3,cr4;
QBCurve UL,UR,LL,LR;
PRInt32 curIndex,c1Index;
nsFloatPoint thePath[MAXPATHSIZE];
static nsPoint polyPath[MAXPOLYPATHSIZE];
PRInt16 np;
nscoord twipsPerPixel;
float p2t;
// needed for our border thickness
p2t = aPresContext->PixelsToTwips();
twipsPerPixel = NSToCoordRound(p2t);
nscolor color = aColor.mBackgroundColor;
if (!aCanPaintNonWhite) {
color = NS_RGB(255, 255, 255);
}
aRenderingContext.SetColor(color);
// Adjust for background-clip, if necessary
if (aColor.mBackgroundClip != NS_STYLE_BG_CLIP_BORDER) {
NS_ASSERTION(aColor.mBackgroundClip == NS_STYLE_BG_CLIP_PADDING, "unknown background-clip value");
// Get the radius to the outer edge of the padding.
// -moz-border-radius is the radius to the outer edge of the border.
NS_FOR_CSS_SIDES(side) {
aTheRadius[side] -= aBorder.GetBorderWidth(side);
aTheRadius[side] = PR_MAX(aTheRadius[side], 0);
}
}
// set the rounded rect up, and let'er rip
outerPath.Set(aBgClipArea.x,aBgClipArea.y,aBgClipArea.width,aBgClipArea.height,aTheRadius,twipsPerPixel);
outerPath.GetRoundedBorders(UL,UR,LL,LR);
// BUILD THE ENTIRE OUTSIDE PATH
// TOP LINE ----------------------------------------------------------------
UL.MidPointDivide(&cr1,&cr2);
UR.MidPointDivide(&cr3,&cr4);
np=0;
thePath[np++].MoveTo(cr2.mAnc1.x,cr2.mAnc1.y);
thePath[np++].MoveTo(cr2.mCon.x, cr2.mCon.y);
thePath[np++].MoveTo(cr2.mAnc2.x, cr2.mAnc2.y);
thePath[np++].MoveTo(cr3.mAnc1.x, cr3.mAnc1.y);
thePath[np++].MoveTo(cr3.mCon.x, cr3.mCon.y);
thePath[np++].MoveTo(cr3.mAnc2.x, cr3.mAnc2.y);
polyPath[0].x = NSToCoordRound(thePath[0].x);
polyPath[0].y = NSToCoordRound(thePath[0].y);
curIndex = 1;
GetPath(thePath,polyPath,&curIndex,eOutside,c1Index);
// RIGHT LINE ----------------------------------------------------------------
LR.MidPointDivide(&cr2,&cr3);
np=0;
thePath[np++].MoveTo(cr4.mAnc1.x,cr4.mAnc1.y);
thePath[np++].MoveTo(cr4.mCon.x, cr4.mCon.y);
thePath[np++].MoveTo(cr4.mAnc2.x, cr4.mAnc2.y);
thePath[np++].MoveTo(cr2.mAnc1.x, cr2.mAnc1.y);
thePath[np++].MoveTo(cr2.mCon.x, cr2.mCon.y);
thePath[np++].MoveTo(cr2.mAnc2.x, cr2.mAnc2.y);
GetPath(thePath,polyPath,&curIndex,eOutside,c1Index);
// BOTTOM LINE ----------------------------------------------------------------
LL.MidPointDivide(&cr2,&cr4);
np=0;
thePath[np++].MoveTo(cr3.mAnc1.x,cr3.mAnc1.y);
thePath[np++].MoveTo(cr3.mCon.x, cr3.mCon.y);
thePath[np++].MoveTo(cr3.mAnc2.x, cr3.mAnc2.y);
thePath[np++].MoveTo(cr2.mAnc1.x, cr2.mAnc1.y);
thePath[np++].MoveTo(cr2.mCon.x, cr2.mCon.y);
thePath[np++].MoveTo(cr2.mAnc2.x, cr2.mAnc2.y);
GetPath(thePath,polyPath,&curIndex,eOutside,c1Index);
// LEFT LINE ----------------------------------------------------------------
np=0;
thePath[np++].MoveTo(cr4.mAnc1.x,cr4.mAnc1.y);
thePath[np++].MoveTo(cr4.mCon.x, cr4.mCon.y);
thePath[np++].MoveTo(cr4.mAnc2.x, cr4.mAnc2.y);
thePath[np++].MoveTo(cr1.mAnc1.x, cr1.mAnc1.y);
thePath[np++].MoveTo(cr1.mCon.x, cr1.mCon.y);
thePath[np++].MoveTo(cr1.mAnc2.x, cr1.mAnc2.y);
GetPath(thePath,polyPath,&curIndex,eOutside,c1Index);
aRenderingContext.FillPolygon(polyPath,curIndex);
}
/** ---------------------------------------------------
* See documentation in nsCSSRendering.h
* @update 3/26/99 dwc
*/
void
nsCSSRendering::PaintRoundedBorder(nsPresContext* aPresContext,
nsIRenderingContext& aRenderingContext,
nsIFrame* aForFrame,
const nsRect& aDirtyRect,
const nsRect& aBorderArea,
const nsStyleBorder* aBorderStyle,
const nsStyleOutline* aOutlineStyle,
nsStyleContext* aStyleContext,
PRIntn aSkipSides,
PRInt16 aBorderRadius[4],
nsRect* aGap,
PRBool aIsOutline)
{
RoundedRect outerPath;
QBCurve UL,LL,UR,LR;
QBCurve IUL,ILL,IUR,ILR;
QBCurve cr1,cr2,cr3,cr4;
QBCurve Icr1,Icr2,Icr3,Icr4;
nsFloatPoint thePath[MAXPATHSIZE];
PRInt16 np;
nsMargin border;
nscoord twipsPerPixel,qtwips;
float p2t;
NS_ASSERTION((aIsOutline && aOutlineStyle) || (!aIsOutline && aBorderStyle), "null params not allowed");
if (!aIsOutline) {
aBorderStyle->CalcBorderFor(aForFrame, border);
if ((0 == border.left) && (0 == border.right) &&
(0 == border.top) && (0 == border.bottom)) {
return;
}
} else {
nscoord width;
if (!aOutlineStyle->GetOutlineWidth(width)) {
return;
}
border.left = width;
border.right = width;
border.top = width;
border.bottom = width;
}
// needed for our border thickness
p2t = aPresContext->PixelsToTwips();
twipsPerPixel = NSToCoordRound(p2t);
// Base our thickness check on the segment being less than a pixel and 1/2
qtwips = twipsPerPixel >> 2;
//qtwips = twipsPerPixel;
outerPath.Set(aBorderArea.x,aBorderArea.y,aBorderArea.width,aBorderArea.height,aBorderRadius,twipsPerPixel);
outerPath.GetRoundedBorders(UL,UR,LL,LR);
outerPath.CalcInsetCurves(IUL,IUR,ILL,ILR,border);
// TOP LINE -- construct and divide the curves first, then put together our top and bottom paths
UL.MidPointDivide(&cr1,&cr2);
UR.MidPointDivide(&cr3,&cr4);
IUL.MidPointDivide(&Icr1,&Icr2);
IUR.MidPointDivide(&Icr3,&Icr4);
if(0!=border.top){
np=0;
thePath[np++].MoveTo(cr2.mAnc1.x,cr2.mAnc1.y);
thePath[np++].MoveTo(cr2.mCon.x, cr2.mCon.y);
thePath[np++].MoveTo(cr2.mAnc2.x, cr2.mAnc2.y);
thePath[np++].MoveTo(cr3.mAnc1.x, cr3.mAnc1.y);
thePath[np++].MoveTo(cr3.mCon.x, cr3.mCon.y);
thePath[np++].MoveTo(cr3.mAnc2.x, cr3.mAnc2.y);
thePath[np++].MoveTo(Icr3.mAnc2.x,Icr3.mAnc2.y);
thePath[np++].MoveTo(Icr3.mCon.x, Icr3.mCon.y);
thePath[np++].MoveTo(Icr3.mAnc1.x, Icr3.mAnc1.y);
thePath[np++].MoveTo(Icr2.mAnc2.x, Icr2.mAnc2.y);
thePath[np++].MoveTo(Icr2.mCon.x, Icr2.mCon.y);
thePath[np++].MoveTo(Icr2.mAnc1.x, Icr2.mAnc1.y);
RenderSide(thePath,aRenderingContext,aBorderStyle,aOutlineStyle,aStyleContext,NS_SIDE_TOP,border,qtwips, aIsOutline);
}
// RIGHT LINE ----------------------------------------------------------------
LR.MidPointDivide(&cr2,&cr3);
ILR.MidPointDivide(&Icr2,&Icr3);
if(0!=border.right){
np=0;
thePath[np++].MoveTo(cr4.mAnc1.x,cr4.mAnc1.y);
thePath[np++].MoveTo(cr4.mCon.x, cr4.mCon.y);
thePath[np++].MoveTo(cr4.mAnc2.x,cr4.mAnc2.y);
thePath[np++].MoveTo(cr2.mAnc1.x,cr2.mAnc1.y);
thePath[np++].MoveTo(cr2.mCon.x, cr2.mCon.y);
thePath[np++].MoveTo(cr2.mAnc2.x,cr2.mAnc2.y);
thePath[np++].MoveTo(Icr2.mAnc2.x,Icr2.mAnc2.y);
thePath[np++].MoveTo(Icr2.mCon.x, Icr2.mCon.y);
thePath[np++].MoveTo(Icr2.mAnc1.x,Icr2.mAnc1.y);
thePath[np++].MoveTo(Icr4.mAnc2.x,Icr4.mAnc2.y);
thePath[np++].MoveTo(Icr4.mCon.x, Icr4.mCon.y);
thePath[np++].MoveTo(Icr4.mAnc1.x,Icr4.mAnc1.y);
RenderSide(thePath,aRenderingContext,aBorderStyle,aOutlineStyle,aStyleContext,NS_SIDE_RIGHT,border,qtwips, aIsOutline);
}
// bottom line ----------------------------------------------------------------
LL.MidPointDivide(&cr2,&cr4);
ILL.MidPointDivide(&Icr2,&Icr4);
if(0!=border.bottom){
np=0;
thePath[np++].MoveTo(cr3.mAnc1.x,cr3.mAnc1.y);
thePath[np++].MoveTo(cr3.mCon.x, cr3.mCon.y);
thePath[np++].MoveTo(cr3.mAnc2.x, cr3.mAnc2.y);
thePath[np++].MoveTo(cr2.mAnc1.x, cr2.mAnc1.y);
thePath[np++].MoveTo(cr2.mCon.x, cr2.mCon.y);
thePath[np++].MoveTo(cr2.mAnc2.x, cr2.mAnc2.y);
thePath[np++].MoveTo(Icr2.mAnc2.x,Icr2.mAnc2.y);
thePath[np++].MoveTo(Icr2.mCon.x, Icr2.mCon.y);
thePath[np++].MoveTo(Icr2.mAnc1.x, Icr2.mAnc1.y);
thePath[np++].MoveTo(Icr3.mAnc2.x, Icr3.mAnc2.y);
thePath[np++].MoveTo(Icr3.mCon.x, Icr3.mCon.y);
thePath[np++].MoveTo(Icr3.mAnc1.x, Icr3.mAnc1.y);
RenderSide(thePath,aRenderingContext,aBorderStyle,aOutlineStyle,aStyleContext,NS_SIDE_BOTTOM,border,qtwips, aIsOutline);
}
// left line ----------------------------------------------------------------
if(0==border.left)
return;
np=0;
thePath[np++].MoveTo(cr4.mAnc1.x,cr4.mAnc1.y);
thePath[np++].MoveTo(cr4.mCon.x, cr4.mCon.y);
thePath[np++].MoveTo(cr4.mAnc2.x, cr4.mAnc2.y);
thePath[np++].MoveTo(cr1.mAnc1.x, cr1.mAnc1.y);
thePath[np++].MoveTo(cr1.mCon.x, cr1.mCon.y);
thePath[np++].MoveTo(cr1.mAnc2.x, cr1.mAnc2.y);
thePath[np++].MoveTo(Icr1.mAnc2.x,Icr1.mAnc2.y);
thePath[np++].MoveTo(Icr1.mCon.x, Icr1.mCon.y);
thePath[np++].MoveTo(Icr1.mAnc1.x, Icr1.mAnc1.y);
thePath[np++].MoveTo(Icr4.mAnc2.x, Icr4.mAnc2.y);
thePath[np++].MoveTo(Icr4.mCon.x, Icr4.mCon.y);
thePath[np++].MoveTo(Icr4.mAnc1.x, Icr4.mAnc1.y);
RenderSide(thePath,aRenderingContext,aBorderStyle,aOutlineStyle,aStyleContext,NS_SIDE_LEFT,border,qtwips, aIsOutline);
}
/** ---------------------------------------------------
* See documentation in nsCSSRendering.h
* @update 3/26/99 dwc
*/
void
nsCSSRendering::RenderSide(nsFloatPoint aPoints[],nsIRenderingContext& aRenderingContext,
const nsStyleBorder* aBorderStyle,const nsStyleOutline* aOutlineStyle,nsStyleContext* aStyleContext,
PRUint8 aSide,nsMargin &aBorThick,nscoord aTwipsPerPixel,
PRBool aIsOutline)
{
QBCurve thecurve;
nscolor sideColor = NS_RGB(0,0,0);
static nsPoint polypath[MAXPOLYPATHSIZE];
PRInt32 curIndex,c1Index,c2Index,junk;
PRInt8 border_Style;
PRInt16 thickness;
// Get our style context's color struct.
const nsStyleColor* ourColor = aStyleContext->GetStyleColor();
NS_ASSERTION((aIsOutline && aOutlineStyle) || (!aIsOutline && aBorderStyle), "null params not allowed");
// set the style information
if (!aIsOutline) {
if (!GetBorderColor(ourColor, *aBorderStyle, aSide, sideColor)) {
return;
}
} else {
aOutlineStyle->GetOutlineColor(sideColor);
}
aRenderingContext.SetColor ( sideColor );
thickness = 0;
switch(aSide){
case NS_SIDE_LEFT:
thickness = aBorThick.left;
break;
case NS_SIDE_TOP:
thickness = aBorThick.top;
break;
case NS_SIDE_RIGHT:
thickness = aBorThick.right;
break;
case NS_SIDE_BOTTOM:
thickness = aBorThick.bottom;
break;
}
// if the border is thin, just draw it
if (thickness<=aTwipsPerPixel) {
// NOTHING FANCY JUST DRAW OUR OUTSIDE BORDER
thecurve.SetPoints(aPoints[0].x,aPoints[0].y,aPoints[1].x,aPoints[1].y,aPoints[2].x,aPoints[2].y);
thecurve.SubDivide((nsIRenderingContext*)&aRenderingContext,0,0);
aRenderingContext.DrawLine((nscoord)aPoints[2].x,(nscoord)aPoints[2].y,(nscoord)aPoints[3].x,(nscoord)aPoints[3].y);
thecurve.SetPoints(aPoints[3].x,aPoints[3].y,aPoints[4].x,aPoints[4].y,aPoints[5].x,aPoints[5].y);
thecurve.SubDivide((nsIRenderingContext*)&aRenderingContext,0,0);
} else {
if (!aIsOutline) {
border_Style = aBorderStyle->GetBorderStyle(aSide);
} else {
border_Style = aOutlineStyle->GetOutlineStyle();
}
switch (border_Style){
case NS_STYLE_BORDER_STYLE_OUTSET:
case NS_STYLE_BORDER_STYLE_INSET:
case NS_STYLE_BORDER_STYLE_BG_OUTSET:
case NS_STYLE_BORDER_STYLE_BG_INSET:
case NS_STYLE_BORDER_STYLE_BG_SOLID:
{
const nsStyleBackground* bgColor = nsCSSRendering::FindNonTransparentBackground(aStyleContext);
if (border_Style == NS_STYLE_BORDER_STYLE_BG_SOLID) {
nscolor colors[2];
NS_Get3DColors(colors, bgColor->mBackgroundColor);
aRenderingContext.SetColor(colors[0]);
} else {
aRenderingContext.SetColor(MakeBevelColor(aSide, border_Style, bgColor->mBackgroundColor, sideColor,
!MOZ_BG_BORDER(border_Style)));
}
}
case NS_STYLE_BORDER_STYLE_DOTTED:
case NS_STYLE_BORDER_STYLE_DASHED:
// break; XXX This is here until dotted and dashed are supported. It is ok to have
// dotted and dashed render in solid until this style is supported. This code should
// be moved when it is supported so that the above outset and inset will fall into the
// solid code below....
case NS_STYLE_BORDER_STYLE_AUTO:
case NS_STYLE_BORDER_STYLE_SOLID:
polypath[0].x = NSToCoordRound(aPoints[0].x);
polypath[0].y = NSToCoordRound(aPoints[0].y);
curIndex = 1;
GetPath(aPoints,polypath,&curIndex,eOutside,c1Index);
c2Index = curIndex;
polypath[curIndex].x = NSToCoordRound(aPoints[6].x);
polypath[curIndex].y = NSToCoordRound(aPoints[6].y);
curIndex++;
GetPath(aPoints,polypath,&curIndex,eInside,junk);
polypath[curIndex].x = NSToCoordRound(aPoints[0].x);
polypath[curIndex].y = NSToCoordRound(aPoints[0].y);
curIndex++;
aRenderingContext.FillPolygon(polypath,curIndex);
break;
case NS_STYLE_BORDER_STYLE_DOUBLE:
polypath[0].x = NSToCoordRound(aPoints[0].x);
polypath[0].y = NSToCoordRound(aPoints[0].y);
curIndex = 1;
GetPath(aPoints,polypath,&curIndex,eOutside,c1Index);
aRenderingContext.DrawPolyline(polypath,curIndex);
polypath[0].x = NSToCoordRound(aPoints[6].x);
polypath[0].y = NSToCoordRound(aPoints[6].y);
curIndex = 1;
GetPath(aPoints,polypath,&curIndex,eInside,c1Index);
aRenderingContext.DrawPolyline(polypath,curIndex);
break;
case NS_STYLE_BORDER_STYLE_NONE:
case NS_STYLE_BORDER_STYLE_HIDDEN:
break;
case NS_STYLE_BORDER_STYLE_RIDGE:
case NS_STYLE_BORDER_STYLE_GROOVE:
{
const nsStyleBackground* bgColor = nsCSSRendering::FindNonTransparentBackground(aStyleContext);
aRenderingContext.SetColor ( MakeBevelColor (aSide, border_Style, bgColor->mBackgroundColor,sideColor, PR_TRUE));
polypath[0].x = NSToCoordRound(aPoints[0].x);
polypath[0].y = NSToCoordRound(aPoints[0].y);
curIndex = 1;
GetPath(aPoints,polypath,&curIndex,eOutside,c1Index);
polypath[curIndex].x = NSToCoordRound((aPoints[5].x + aPoints[6].x)/2.0f);
polypath[curIndex].y = NSToCoordRound((aPoints[5].y + aPoints[6].y)/2.0f);
curIndex++;
GetPath(aPoints,polypath,&curIndex,eCalcRev,c1Index,.5);
polypath[curIndex].x = NSToCoordRound(aPoints[0].x);
polypath[curIndex].y = NSToCoordRound(aPoints[0].y);
curIndex++;
aRenderingContext.FillPolygon(polypath,curIndex);
aRenderingContext.SetColor ( MakeBevelColor (aSide,
((border_Style == NS_STYLE_BORDER_STYLE_RIDGE) ?
NS_STYLE_BORDER_STYLE_GROOVE :
NS_STYLE_BORDER_STYLE_RIDGE),
bgColor->mBackgroundColor,sideColor, PR_TRUE));
polypath[0].x = NSToCoordRound((aPoints[0].x + aPoints[11].x)/2.0f);
polypath[0].y = NSToCoordRound((aPoints[0].y + aPoints[11].y)/2.0f);
curIndex = 1;
GetPath(aPoints,polypath,&curIndex,eCalc,c1Index,.5);
polypath[curIndex].x = NSToCoordRound(aPoints[6].x) ;
polypath[curIndex].y = NSToCoordRound(aPoints[6].y);
curIndex++;
GetPath(aPoints,polypath,&curIndex,eInside,c1Index);
polypath[curIndex].x = NSToCoordRound(aPoints[0].x);
polypath[curIndex].y = NSToCoordRound(aPoints[0].y);
curIndex++;
aRenderingContext.FillPolygon(polypath,curIndex);
}
break;
default:
break;
}
}
}
/** ---------------------------------------------------
* See documentation in nsCSSRendering.h
* @update 3/26/99 dwc
*/
void
RoundedRect::CalcInsetCurves(QBCurve &aULCurve,QBCurve &aURCurve,QBCurve &aLLCurve,QBCurve &aLRCurve,nsMargin &aBorder)
{
PRInt32 nLeft,nTop,nRight,nBottom;
PRInt32 tLeft,bLeft,tRight,bRight,lTop,rTop,lBottom,rBottom;
PRInt16 adjust=0;
if(mDoRound)
adjust = mRoundness[0]>>3;
nLeft = mLeft + aBorder.left;
tLeft = mLeft + mRoundness[0];
bLeft = mLeft + mRoundness[3];
if(tLeft < nLeft){
tLeft = nLeft;
}
if(bLeft < nLeft){
bLeft = nLeft;
}
nRight = mRight - aBorder.right;
tRight = mRight - mRoundness[1];
bRight = mRight - mRoundness[2];
if(tRight > nRight){
tRight = nRight;
}
if(bRight > nRight){
bRight = nRight;
}
nTop = mTop + aBorder.top;
lTop = mTop + mRoundness[0];
rTop = mTop + mRoundness[1];
if(lTop < nTop){
lTop = nTop;
}
if(rTop < nTop){
rTop = nTop;
}
nBottom = mBottom - aBorder.bottom;
lBottom = mBottom - mRoundness[3];
rBottom = mBottom - mRoundness[2];
if(lBottom > nBottom){
lBottom = nBottom;
}
if(rBottom > nBottom){
rBottom = nBottom;
}
// set the passed in curves to the rounded borders of the rectangle
aULCurve.SetPoints( (float)nLeft,(float)lTop,
(float)nLeft+adjust,(float)nTop+adjust,
(float)tLeft,(float)nTop);
aURCurve.SetPoints( (float)tRight,(float)nTop,
(float)nRight-adjust,(float)nTop+adjust,
(float)nRight,(float)rTop);
aLRCurve.SetPoints( (float)nRight,(float)rBottom,
(float)nRight-adjust,(float)nBottom-adjust,
(float)bRight,(float)nBottom);
aLLCurve.SetPoints( (float)bLeft,(float)nBottom,
(float)nLeft+adjust,(float)nBottom-adjust,
(float)nLeft,(float)lBottom);
}
/** ---------------------------------------------------
* See documentation in nsCSSRendering.h
* @update 4/13/99 dwc
*/
void
RoundedRect::Set(nscoord aLeft,nscoord aTop,PRInt32 aWidth,PRInt32 aHeight,PRInt16 aRadius[4],PRInt16 aNumTwipPerPix)
{
nscoord x,y,width,height;
int i;
// convert this rect to pixel boundaries
x = (aLeft/aNumTwipPerPix)*aNumTwipPerPix;
y = (aTop/aNumTwipPerPix)*aNumTwipPerPix;
width = (aWidth/aNumTwipPerPix)*aNumTwipPerPix;
height = (aHeight/aNumTwipPerPix)*aNumTwipPerPix;
for(i=0;i<4;i++) {
if( (aRadius[i]) > (aWidth>>1) ){
mRoundness[i] = (aWidth>>1);
} else {
mRoundness[i] = aRadius[i];
}
if( mRoundness[i] > (aHeight>>1) )
mRoundness[i] = aHeight>>1;
}
// if we are drawing a circle
mDoRound = PR_FALSE;
if(aHeight==aWidth){
PRBool doRound = PR_TRUE;
for(i=0;i<4;i++){
if(mRoundness[i]<(aWidth>>1)){
doRound = PR_FALSE;
break;
}
}
if(doRound){
mDoRound = PR_TRUE;
for(i=0;i<4;i++){
mRoundness[i] = aWidth>>1;
}
}
}
// important coordinates that the path hits
mLeft = x;
mTop = y;
mRight = x+width;
mBottom = y+height;
}
/** ---------------------------------------------------
* See documentation in nsCSSRendering.h
* @update 4/13/99 dwc
*/
void
RoundedRect::GetRoundedBorders(QBCurve &aULCurve,QBCurve &aURCurve,QBCurve &aLLCurve,QBCurve &aLRCurve)
{
PRInt16 adjust=0;
if(mDoRound)
adjust = mRoundness[0]>>3;
// set the passed in curves to the rounded borders of the rectangle
aULCurve.SetPoints( (float)mLeft,(float)mTop + mRoundness[0],
(float)mLeft+adjust,(float)mTop+adjust,
(float)mLeft+mRoundness[0],(float)mTop);
aURCurve.SetPoints( (float)mRight - mRoundness[1],(float)mTop,
(float)mRight-adjust,(float)mTop+adjust,
(float)mRight,(float)mTop + mRoundness[1]);
aLRCurve.SetPoints( (float)mRight,(float)mBottom - mRoundness[2],
(float)mRight-adjust,(float)mBottom-adjust,
(float)mRight - mRoundness[2],(float)mBottom);
aLLCurve.SetPoints( (float)mLeft + mRoundness[3],(float)mBottom,
(float)mLeft+adjust,(float)mBottom-adjust,
(float)mLeft,(float)mBottom - mRoundness[3]);
}
/** ---------------------------------------------------
* Given a qbezier path, convert it into a polygon path
* @update 3/26/99 dwc
* @param aPoints -- an array of points to use for the path
* @param aPolyPath -- an array of points containing the flattened polygon to use
* @param aCurIndex -- the index that points to the last element of the array
* @param aPathType -- what kind of path that should be returned
* @param aFrac -- the inset amount for a eCalc type path
*/
static void
GetPath(nsFloatPoint aPoints[],nsPoint aPolyPath[],PRInt32 *aCurIndex,ePathTypes aPathType,PRInt32 &aC1Index,float aFrac)
{
QBCurve thecurve;
switch (aPathType) {
case eOutside:
thecurve.SetPoints(aPoints[0].x,aPoints[0].y,aPoints[1].x,aPoints[1].y,aPoints[2].x,aPoints[2].y);
thecurve.SubDivide(nsnull,aPolyPath,aCurIndex);
aC1Index = *aCurIndex;
aPolyPath[*aCurIndex].x = (nscoord)aPoints[3].x;
aPolyPath[*aCurIndex].y = (nscoord)aPoints[3].y;
(*aCurIndex)++;
thecurve.SetPoints(aPoints[3].x,aPoints[3].y,aPoints[4].x,aPoints[4].y,aPoints[5].x,aPoints[5].y);
thecurve.SubDivide(nsnull,aPolyPath,aCurIndex);
break;
case eInside:
thecurve.SetPoints(aPoints[6].x,aPoints[6].y,aPoints[7].x,aPoints[7].y,aPoints[8].x,aPoints[8].y);
thecurve.SubDivide(nsnull,aPolyPath,aCurIndex);
aPolyPath[*aCurIndex].x = (nscoord)aPoints[9].x;
aPolyPath[*aCurIndex].y = (nscoord)aPoints[9].y;
(*aCurIndex)++;
thecurve.SetPoints(aPoints[9].x,aPoints[9].y,aPoints[10].x,aPoints[10].y,aPoints[11].x,aPoints[11].y);
thecurve.SubDivide(nsnull,aPolyPath,aCurIndex);
break;
case eCalc:
thecurve.SetPoints( (aPoints[0].x+aPoints[11].x)/2.0f,(aPoints[0].y+aPoints[11].y)/2.0f,
(aPoints[1].x+aPoints[10].x)/2.0f,(aPoints[1].y+aPoints[10].y)/2.0f,
(aPoints[2].x+aPoints[9].x)/2.0f,(aPoints[2].y+aPoints[9].y)/2.0f);
thecurve.SubDivide(nsnull,aPolyPath,aCurIndex);
aPolyPath[*aCurIndex].x = (nscoord)((aPoints[3].x+aPoints[8].x)/2.0f);
aPolyPath[*aCurIndex].y = (nscoord)((aPoints[3].y+aPoints[8].y)/2.0f);
(*aCurIndex)++;
thecurve.SetPoints( (aPoints[3].x+aPoints[8].x)/2.0f,(aPoints[3].y+aPoints[8].y)/2.0f,
(aPoints[4].x+aPoints[7].x)/2.0f,(aPoints[4].y+aPoints[7].y)/2.0f,
(aPoints[5].x+aPoints[6].x)/2.0f,(aPoints[5].y+aPoints[6].y)/2.0f);
thecurve.SubDivide(nsnull,aPolyPath,aCurIndex);
break;
case eCalcRev:
thecurve.SetPoints( (aPoints[5].x+aPoints[6].x)/2.0f,(aPoints[5].y+aPoints[6].y)/2.0f,
(aPoints[4].x+aPoints[7].x)/2.0f,(aPoints[4].y+aPoints[7].y)/2.0f,
(aPoints[3].x+aPoints[8].x)/2.0f,(aPoints[3].y+aPoints[8].y)/2.0f);
thecurve.SubDivide(nsnull,aPolyPath,aCurIndex);
aPolyPath[*aCurIndex].x = (nscoord)((aPoints[2].x+aPoints[9].x)/2.0f);
aPolyPath[*aCurIndex].y = (nscoord)((aPoints[2].y+aPoints[9].y)/2.0f);
(*aCurIndex)++;
thecurve.SetPoints( (aPoints[2].x+aPoints[9].x)/2.0f,(aPoints[2].y+aPoints[9].y)/2.0f,
(aPoints[1].x+aPoints[10].x)/2.0f,(aPoints[1].y+aPoints[10].y)/2.0f,
(aPoints[0].x+aPoints[11].x)/2.0f,(aPoints[0].y+aPoints[11].y)/2.0f);
thecurve.SubDivide(nsnull,aPolyPath,aCurIndex);
break;
}
}
/** ---------------------------------------------------
* See documentation in nsCSSRendering.h
* @update 4/13/99 dwc
*/
void
QBCurve::SubDivide(nsIRenderingContext *aRenderingContext,nsPoint aPointArray[],PRInt32 *aCurIndex)
{
QBCurve curve1,curve2;
float fx,fy,smag;
// divide the curve into 2 pieces
MidPointDivide(&curve1,&curve2);
fx = (float)fabs(curve1.mAnc2.x - this->mCon.x);
fy = (float)fabs(curve1.mAnc2.y - this->mCon.y);
//smag = fx+fy-(PR_MIN(fx,fy)>>1);
smag = fx*fx + fy*fy;
if (smag>1){
// split the curve again
curve1.SubDivide(aRenderingContext,aPointArray,aCurIndex);
curve2.SubDivide(aRenderingContext,aPointArray,aCurIndex);
}else{
if(aPointArray ) {
// save the points for further processing
aPointArray[*aCurIndex].x = (nscoord)curve1.mAnc2.x;
aPointArray[*aCurIndex].y = (nscoord)curve1.mAnc2.y;
(*aCurIndex)++;
aPointArray[*aCurIndex].x = (nscoord)curve2.mAnc2.x;
aPointArray[*aCurIndex].y = (nscoord)curve2.mAnc2.y;
(*aCurIndex)++;
}else{
// draw the curve
nsTransform2D *aTransform;
aRenderingContext->GetCurrentTransform(aTransform);
aRenderingContext->DrawLine((nscoord)curve1.mAnc1.x,(nscoord)curve1.mAnc1.y,(nscoord)curve1.mAnc2.x,(nscoord)curve1.mAnc2.y);
aRenderingContext->DrawLine((nscoord)curve1.mAnc2.x,(nscoord)curve1.mAnc2.y,(nscoord)curve2.mAnc2.x,(nscoord)curve2.mAnc2.y);
}
}
}
/** ---------------------------------------------------
* See documentation in nsCSSRendering.h
* @update 4/13/99 dwc
*/
void
QBCurve::MidPointDivide(QBCurve *A,QBCurve *B)
{
float c1x,c1y,c2x,c2y;
nsFloatPoint a1;
c1x = (mAnc1.x+mCon.x)/2.0f;
c1y = (mAnc1.y+mCon.y)/2.0f;
c2x = (mAnc2.x+mCon.x)/2.0f;
c2y = (mAnc2.y+mCon.y)/2.0f;
a1.x = (c1x + c2x)/2.0f;
a1.y = (c1y + c2y)/2.0f;
// put the math into our 2 new curves
A->mAnc1 = this->mAnc1;
A->mCon.x = c1x;
A->mCon.y = c1y;
A->mAnc2 = a1;
B->mAnc1 = a1;
B->mCon.x = c2x;
B->mCon.y = c2y;
B->mAnc2 = this->mAnc2;
}
void FillOrInvertRect(nsIRenderingContext& aRC, nscoord aX, nscoord aY, nscoord aWidth, nscoord aHeight, PRBool aInvert)
{
if (aInvert) {
aRC.InvertRect(aX, aY, aWidth, aHeight);
} else {
aRC.FillRect(aX, aY, aWidth, aHeight);
}
}
void FillOrInvertRect(nsIRenderingContext& aRC, const nsRect& aRect, PRBool aInvert)
{
if (aInvert) {
aRC.InvertRect(aRect);
} else {
aRC.FillRect(aRect);
}
}
// Begin table border-collapsing section
// These functions were written to not disrupt the normal ones and yet satisfy some additional requirements
// At some point, all functions should be unified to include the additional functionality that these provide
static nscoord
RoundIntToPixel(nscoord aValue,
nscoord aTwipsPerPixel,
PRBool aRoundDown = PR_FALSE)
{
if (aTwipsPerPixel <= 0)
// We must be rendering to a device that has a resolution greater than Twips!
// In that case, aValue is as accurate as it's going to get.
return aValue;
nscoord halfPixel = NSToCoordRound(aTwipsPerPixel / 2.0f);
nscoord extra = aValue % aTwipsPerPixel;
nscoord finalValue = (!aRoundDown && (extra >= halfPixel)) ? aValue + (aTwipsPerPixel - extra) : aValue - extra;
return finalValue;
}
static nscoord
RoundFloatToPixel(float aValue,
nscoord aTwipsPerPixel,
PRBool aRoundDown = PR_FALSE)
{
return RoundIntToPixel(NSToCoordRound(aValue), aTwipsPerPixel, aRoundDown);
}
static void
SetPoly(const nsRect& aRect,
nsPoint* poly)
{
poly[0].x = aRect.x;
poly[0].y = aRect.y;
poly[1].x = aRect.x + aRect.width;
poly[1].y = aRect.y;
poly[2].x = aRect.x + aRect.width;
poly[2].y = aRect.y + aRect.height;
poly[3].x = aRect.x;
poly[3].y = aRect.y + aRect.height;
poly[4].x = aRect.x;
poly[4].y = aRect.y;
}
static void
DrawSolidBorderSegment(nsIRenderingContext& aContext,
nsRect aRect,
nscoord aTwipsPerPixel,
PRUint8 aStartBevelSide = 0,
nscoord aStartBevelOffset = 0,
PRUint8 aEndBevelSide = 0,
nscoord aEndBevelOffset = 0)
{
if ((aRect.width == aTwipsPerPixel) || (aRect.height == aTwipsPerPixel) ||
((0 == aStartBevelOffset) && (0 == aEndBevelOffset))) {
// simple line or rectangle
if ((NS_SIDE_TOP == aStartBevelSide) || (NS_SIDE_BOTTOM == aStartBevelSide)) {
if (1 == aRect.height)
aContext.DrawLine(aRect.x, aRect.y, aRect.x, aRect.y + aRect.height);
else
aContext.FillRect(aRect);
}
else {
if (1 == aRect.width)
aContext.DrawLine(aRect.x, aRect.y, aRect.x + aRect.width, aRect.y);
else
aContext.FillRect(aRect);
}
}
else {
// polygon with beveling
nsPoint poly[5];
SetPoly(aRect, poly);
switch(aStartBevelSide) {
case NS_SIDE_TOP:
poly[0].x += aStartBevelOffset;
poly[4].x = poly[0].x;
break;
case NS_SIDE_BOTTOM:
poly[3].x += aStartBevelOffset;
break;
case NS_SIDE_RIGHT:
poly[1].y += aStartBevelOffset;
break;
case NS_SIDE_LEFT:
poly[0].y += aStartBevelOffset;
poly[4].y = poly[0].y;
}
switch(aEndBevelSide) {
case NS_SIDE_TOP:
poly[1].x -= aEndBevelOffset;
break;
case NS_SIDE_BOTTOM:
poly[2].x -= aEndBevelOffset;
break;
case NS_SIDE_RIGHT:
poly[2].y -= aEndBevelOffset;
break;
case NS_SIDE_LEFT:
poly[3].y -= aEndBevelOffset;
}
aContext.FillPolygon(poly, 5);
}
}
static void
GetDashInfo(nscoord aBorderLength,
nscoord aDashLength,
nscoord aTwipsPerPixel,
PRInt32& aNumDashSpaces,
nscoord& aStartDashLength,
nscoord& aEndDashLength)
{
aNumDashSpaces = 0;
if (aStartDashLength + aDashLength + aEndDashLength >= aBorderLength) {
aStartDashLength = aBorderLength;
aEndDashLength = 0;
}
else {
aNumDashSpaces = aBorderLength / (2 * aDashLength); // round down
nscoord extra = aBorderLength - aStartDashLength - aEndDashLength - (((2 * aNumDashSpaces) - 1) * aDashLength);
if (extra > 0) {
nscoord half = RoundIntToPixel(extra / 2, aTwipsPerPixel);
aStartDashLength += half;
aEndDashLength += (extra - half);
}
}
}
void
nsCSSRendering::DrawTableBorderSegment(nsIRenderingContext& aContext,
PRUint8 aBorderStyle,
nscolor aBorderColor,
const nsStyleBackground* aBGColor,
const nsRect& aBorder,
float aPixelsToTwips,
PRUint8 aStartBevelSide,
nscoord aStartBevelOffset,
PRUint8 aEndBevelSide,
nscoord aEndBevelOffset)
{
aContext.SetColor (aBorderColor);
PRBool horizontal = ((NS_SIDE_TOP == aStartBevelSide) || (NS_SIDE_BOTTOM == aStartBevelSide));
nscoord twipsPerPixel = NSIntPixelsToTwips(1, aPixelsToTwips);
PRBool ridgeGroove = NS_STYLE_BORDER_STYLE_RIDGE;
if ((twipsPerPixel >= aBorder.width) || (twipsPerPixel >= aBorder.height) ||
(NS_STYLE_BORDER_STYLE_DASHED == aBorderStyle) || (NS_STYLE_BORDER_STYLE_DOTTED == aBorderStyle)) {
// no beveling for 1 pixel border, dash or dot
aStartBevelOffset = 0;
aEndBevelOffset = 0;
}
switch (aBorderStyle) {
case NS_STYLE_BORDER_STYLE_NONE:
case NS_STYLE_BORDER_STYLE_HIDDEN:
//NS_ASSERTION(PR_FALSE, "style of none or hidden");
break;
case NS_STYLE_BORDER_STYLE_DOTTED:
case NS_STYLE_BORDER_STYLE_DASHED:
{
nscoord dashLength = (NS_STYLE_BORDER_STYLE_DASHED == aBorderStyle) ? DASH_LENGTH : DOT_LENGTH;
// make the dash length proportional to the border thickness
dashLength *= (horizontal) ? aBorder.height : aBorder.width;
// make the min dash length for the ends 1/2 the dash length
nscoord minDashLength = (NS_STYLE_BORDER_STYLE_DASHED == aBorderStyle)
? RoundFloatToPixel(((float)dashLength) / 2.0f, twipsPerPixel) : dashLength;
minDashLength = PR_MAX(minDashLength, twipsPerPixel);
nscoord numDashSpaces = 0;
nscoord startDashLength = minDashLength;
nscoord endDashLength = minDashLength;
if (horizontal) {
GetDashInfo(aBorder.width, dashLength, twipsPerPixel, numDashSpaces, startDashLength, endDashLength);
nsRect rect(aBorder.x, aBorder.y, startDashLength, aBorder.height);
DrawSolidBorderSegment(aContext, rect, PR_TRUE);
for (PRInt32 spaceX = 0; spaceX < numDashSpaces; spaceX++) {
rect.x += rect.width + dashLength;
rect.width = (spaceX == (numDashSpaces - 1)) ? endDashLength : dashLength;
DrawSolidBorderSegment(aContext, rect, PR_TRUE);
}
}
else {
GetDashInfo(aBorder.height, dashLength, twipsPerPixel, numDashSpaces, startDashLength, endDashLength);
nsRect rect(aBorder.x, aBorder.y, aBorder.width, startDashLength);
DrawSolidBorderSegment(aContext, rect, PR_FALSE);
for (PRInt32 spaceY = 0; spaceY < numDashSpaces; spaceY++) {
rect.y += rect.height + dashLength;
rect.height = (spaceY == (numDashSpaces - 1)) ? endDashLength : dashLength;
DrawSolidBorderSegment(aContext, rect, PR_FALSE);
}
}
}
break;
case NS_STYLE_BORDER_STYLE_GROOVE:
ridgeGroove = NS_STYLE_BORDER_STYLE_GROOVE; // and fall through to ridge
case NS_STYLE_BORDER_STYLE_RIDGE:
if ((horizontal && (twipsPerPixel >= aBorder.height)) ||
(!horizontal && (twipsPerPixel >= aBorder.width))) {
// a one pixel border
DrawSolidBorderSegment(aContext, aBorder, twipsPerPixel, aStartBevelSide, aStartBevelOffset,
aEndBevelSide, aEndBevelOffset);
}
else {
nscoord startBevel = (aStartBevelOffset > 0)
? RoundFloatToPixel(0.5f * (float)aStartBevelOffset, twipsPerPixel, PR_TRUE) : 0;
nscoord endBevel = (aEndBevelOffset > 0)
? RoundFloatToPixel(0.5f * (float)aEndBevelOffset, twipsPerPixel, PR_TRUE) : 0;
PRUint8 ridgeGrooveSide = (horizontal) ? NS_SIDE_TOP : NS_SIDE_LEFT;
aContext.SetColor (
MakeBevelColor (ridgeGrooveSide, ridgeGroove, aBGColor->mBackgroundColor, aBorderColor, PR_TRUE));
nsRect rect(aBorder);
nscoord half;
if (horizontal) { // top, bottom
half = RoundFloatToPixel(0.5f * (float)aBorder.height, twipsPerPixel);
rect.height = half;
if (NS_SIDE_TOP == aStartBevelSide) {
rect.x += startBevel;
rect.width -= startBevel;
}
if (NS_SIDE_TOP == aEndBevelSide) {
rect.width -= endBevel;
}
DrawSolidBorderSegment(aContext, rect, twipsPerPixel, aStartBevelSide,
startBevel, aEndBevelSide, endBevel);
}
else { // left, right
half = RoundFloatToPixel(0.5f * (float)aBorder.width, twipsPerPixel);
rect.width = half;
if (NS_SIDE_LEFT == aStartBevelSide) {
rect.y += startBevel;
rect.height -= startBevel;
}
if (NS_SIDE_LEFT == aEndBevelSide) {
rect.height -= endBevel;
}
DrawSolidBorderSegment(aContext, rect, twipsPerPixel, aStartBevelSide,
startBevel, aEndBevelSide, endBevel);
}
rect = aBorder;
ridgeGrooveSide = (NS_SIDE_TOP == ridgeGrooveSide) ? NS_SIDE_BOTTOM : NS_SIDE_RIGHT;
aContext.SetColor (
MakeBevelColor (ridgeGrooveSide, ridgeGroove, aBGColor->mBackgroundColor, aBorderColor, PR_TRUE));
if (horizontal) {
rect.y = rect.y + half;
rect.height = aBorder.height - half;
if (NS_SIDE_BOTTOM == aStartBevelSide) {
rect.x += startBevel;
rect.width -= startBevel;
}
if (NS_SIDE_BOTTOM == aEndBevelSide) {
rect.width -= endBevel;
}
DrawSolidBorderSegment(aContext, rect, twipsPerPixel, aStartBevelSide,
startBevel, aEndBevelSide, endBevel);
}
else {
rect.x = rect.x + half;
rect.width = aBorder.width - half;
if (NS_SIDE_RIGHT == aStartBevelSide) {
rect.y += aStartBevelOffset - startBevel;
rect.height -= startBevel;
}
if (NS_SIDE_RIGHT == aEndBevelSide) {
rect.height -= endBevel;
}
DrawSolidBorderSegment(aContext, rect, twipsPerPixel, aStartBevelSide,
startBevel, aEndBevelSide, endBevel);
}
}
break;
case NS_STYLE_BORDER_STYLE_DOUBLE:
if ((aBorder.width > 2) && (aBorder.height > 2)) {
nscoord startBevel = (aStartBevelOffset > 0)
? RoundFloatToPixel(0.333333f * (float)aStartBevelOffset, twipsPerPixel) : 0;
nscoord endBevel = (aEndBevelOffset > 0)
? RoundFloatToPixel(0.333333f * (float)aEndBevelOffset, twipsPerPixel) : 0;
if (horizontal) { // top, bottom
nscoord thirdHeight = RoundFloatToPixel(0.333333f * (float)aBorder.height, twipsPerPixel);
// draw the top line or rect
nsRect topRect(aBorder.x, aBorder.y, aBorder.width, thirdHeight);
if (NS_SIDE_TOP == aStartBevelSide) {
topRect.x += aStartBevelOffset - startBevel;
topRect.width -= aStartBevelOffset - startBevel;
}
if (NS_SIDE_TOP == aEndBevelSide) {
topRect.width -= aEndBevelOffset - endBevel;
}
DrawSolidBorderSegment(aContext, topRect, twipsPerPixel, aStartBevelSide,
startBevel, aEndBevelSide, endBevel);
// draw the botom line or rect
nscoord heightOffset = aBorder.height - thirdHeight;
nsRect bottomRect(aBorder.x, aBorder.y + heightOffset, aBorder.width, aBorder.height - heightOffset);
if (NS_SIDE_BOTTOM == aStartBevelSide) {
bottomRect.x += aStartBevelOffset - startBevel;
bottomRect.width -= aStartBevelOffset - startBevel;
}
if (NS_SIDE_BOTTOM == aEndBevelSide) {
bottomRect.width -= aEndBevelOffset - endBevel;
}
DrawSolidBorderSegment(aContext, bottomRect, twipsPerPixel, aStartBevelSide,
startBevel, aEndBevelSide, endBevel);
}
else { // left, right
nscoord thirdWidth = RoundFloatToPixel(0.333333f * (float)aBorder.width, twipsPerPixel);
nsRect leftRect(aBorder.x, aBorder.y, thirdWidth, aBorder.height);
if (NS_SIDE_LEFT == aStartBevelSide) {
leftRect.y += aStartBevelOffset - startBevel;
leftRect.height -= aStartBevelOffset - startBevel;
}
if (NS_SIDE_LEFT == aEndBevelSide) {
leftRect.height -= aEndBevelOffset - endBevel;
}
DrawSolidBorderSegment(aContext, leftRect, twipsPerPixel, aStartBevelSide,
startBevel, aEndBevelSide, endBevel);
nscoord widthOffset = aBorder.width - thirdWidth;
nsRect rightRect(aBorder.x + widthOffset, aBorder.y, aBorder.width - widthOffset, aBorder.height);
if (NS_SIDE_RIGHT == aStartBevelSide) {
rightRect.y += aStartBevelOffset - startBevel;
rightRect.height -= aStartBevelOffset - startBevel;
}
if (NS_SIDE_RIGHT == aEndBevelSide) {
rightRect.height -= aEndBevelOffset - endBevel;
}
DrawSolidBorderSegment(aContext, rightRect, twipsPerPixel, aStartBevelSide,
startBevel, aEndBevelSide, endBevel);
}
break;
}
// else fall through to solid
case NS_STYLE_BORDER_STYLE_BG_SOLID:
case NS_STYLE_BORDER_STYLE_SOLID:
DrawSolidBorderSegment(aContext, aBorder, twipsPerPixel, aStartBevelSide,
aStartBevelOffset, aEndBevelSide, aEndBevelOffset);
break;
case NS_STYLE_BORDER_STYLE_BG_OUTSET:
case NS_STYLE_BORDER_STYLE_BG_INSET:
case NS_STYLE_BORDER_STYLE_OUTSET:
case NS_STYLE_BORDER_STYLE_INSET:
NS_ASSERTION(PR_FALSE, "inset, outset should have been converted to groove, ridge");
break;
case NS_STYLE_BORDER_STYLE_AUTO:
NS_ASSERTION(PR_FALSE, "Unexpected 'auto' table border");
break;
}
}
// End table border-collapsing section
| 164,690 | 55,349 |
//
// Copyright 2017 Animal Logic
//
// 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 "AL/usd/utils/ALHalf.h"
#include "AL/usd/utils/SIMD.h"
#include "AL/usdmaya/utils/DgNodeHelper.h"
#include "AL/maya/utils/NodeHelper.h"
#include "maya/MDGModifier.h"
#include "maya/MFloatArray.h"
#include "maya/MFloatMatrix.h"
#include "maya/MFnCompoundAttribute.h"
#include "maya/MFnDoubleArrayData.h"
#include "maya/MFnFloatArrayData.h"
#include "maya/MFnMatrixData.h"
#include "maya/MFnMatrixArrayData.h"
#include "maya/MFnNumericAttribute.h"
#include "maya/MFnNumericData.h"
#include "maya/MFnTypedAttribute.h"
#include "maya/MMatrix.h"
#include "maya/MMatrixArray.h"
namespace AL {
namespace usdmaya {
namespace utils {
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setFloat(const MObject node, const MObject attr, float value)
{
const char* const errorString = "float error";
MPlug plug(node, attr);
AL_MAYA_CHECK_ERROR(plug.setValue(value), errorString);
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setAngle(const MObject node, const MObject attr, MAngle value)
{
const char* const errorString = "DgNodeHelper::setAngle";
MPlug plug(node, attr);
AL_MAYA_CHECK_ERROR(plug.setValue(value), errorString);
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setTime(const MObject node, const MObject attr, MTime value)
{
const char* const errorString = "DgNodeHelper::setTime";
MPlug plug(node, attr);
AL_MAYA_CHECK_ERROR(plug.setValue(value), errorString);
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setDistance(const MObject node, const MObject attr, MDistance value)
{
const char* const errorString = "DgNodeHelper::setDistance";
MPlug plug(node, attr);
AL_MAYA_CHECK_ERROR(plug.setValue(value), errorString);
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setDouble(MObject node, MObject attr, double value)
{
const char* const errorString = "double error";
MPlug plug(node, attr);
AL_MAYA_CHECK_ERROR(plug.setValue(value), errorString);
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setBool(MObject node, MObject attr, bool value)
{
const char* const errorString = "int error";
MPlug plug(node, attr);
AL_MAYA_CHECK_ERROR(plug.setValue(value), errorString);
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setInt8(MObject node, MObject attr, int8_t value)
{
const char* const errorString = "int error";
MPlug plug(node, attr);
AL_MAYA_CHECK_ERROR(plug.setChar(value), errorString);
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setInt16(MObject node, MObject attr, int16_t value)
{
const char* const errorString = "int error";
MPlug plug(node, attr);
AL_MAYA_CHECK_ERROR(plug.setShort(value), errorString);
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setInt32(MObject node, MObject attr, int32_t value)
{
const char* const errorString = "int error";
MPlug plug(node, attr);
AL_MAYA_CHECK_ERROR(plug.setValue(value), errorString);
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setInt64(MObject node, MObject attr, int64_t value)
{
const char* const errorString = "int64 error";
MPlug plug(node, attr);
AL_MAYA_CHECK_ERROR(plug.setInt64(value), errorString);
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setVec3(MObject node, MObject attr, float x, float y, float z)
{
const char* const errorString = "vec3f error";
MPlug plug(node, attr);
AL_MAYA_CHECK_ERROR(plug.child(0).setValue(x), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).setValue(y), errorString);
AL_MAYA_CHECK_ERROR(plug.child(2).setValue(z), errorString);
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setVec3(MObject node, MObject attr, double x, double y, double z)
{
const char* const errorString = "vec3d error";
MPlug plug(node, attr);
AL_MAYA_CHECK_ERROR(plug.child(0).setValue(x), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).setValue(y), errorString);
AL_MAYA_CHECK_ERROR(plug.child(2).setValue(z), errorString);
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setVec3(MObject node, MObject attr, MAngle x, MAngle y, MAngle z)
{
const char* const errorString = "vec3d error";
MPlug plug(node, attr);
AL_MAYA_CHECK_ERROR(plug.child(0).setValue(x), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).setValue(y), errorString);
AL_MAYA_CHECK_ERROR(plug.child(2).setValue(z), errorString);
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setBoolArray(MObject node, MObject attribute, const bool* const values, const size_t count)
{
MPlug plug(node, attribute);
if(!plug || !plug.isArray())
return MS::kFailure;
AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized");
for(size_t i = 0; i != count; ++i)
{
plug.elementByLogicalIndex(i).setBool(values[i]);
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setBoolArray(const MObject& node, const MObject& attribute, const std::vector<bool>& values)
{
MPlug plug(node, attribute);
if(!plug || !plug.isArray())
return MS::kFailure;
AL_MAYA_CHECK_ERROR(plug.setNumElements(values.size()), "DgNodeHelper: attribute array could not be resized");
for(size_t i = 0, n = values.size(); i != n; ++i)
{
plug.elementByLogicalIndex(i).setBool(values[i]);
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setInt8Array(MObject node, MObject attribute, const int8_t* const values, const size_t count)
{
MPlug plug(node, attribute);
if(!plug || !plug.isArray())
return MS::kFailure;
AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized");
for(size_t i = 0; i != count; ++i)
{
plug.elementByLogicalIndex(i).setChar(values[i]);
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setInt16Array(MObject node, MObject attribute, const int16_t* const values, const size_t count)
{
MPlug plug(node, attribute);
if(!plug || !plug.isArray())
return MS::kFailure;
AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized");
for(size_t i = 0; i != count; ++i)
{
plug.elementByLogicalIndex(i).setShort(values[i]);
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setInt32Array(MObject node, MObject attribute, const int32_t* const values, const size_t count)
{
MPlug plug(node, attribute);
if(!plug || !plug.isArray())
return MS::kFailure;
AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized");
for(size_t i = 0; i != count; ++i)
{
plug.elementByLogicalIndex(i).setValue(values[i]);
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setInt64Array(MObject node, MObject attribute, const int64_t* const values, const size_t count)
{
MPlug plug(node, attribute);
if(!plug || !plug.isArray())
return MS::kFailure;
AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized");
for(size_t i = 0; i != count; ++i)
{
plug.elementByLogicalIndex(i).setInt64(values[i]);
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setHalfArray(MObject node, MObject attribute, const GfHalf* const values, const size_t count)
{
MPlug plug(node, attribute);
if(!plug || !plug.isArray())
return MS::kFailure;
AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized");
size_t count8 = count & ~0x7ULL;
for(size_t j = 0; j != count8; j += 8)
{
float f[8];
AL::usd::utils::half2float_8f(values + j, f);
plug.elementByLogicalIndex(j + 0).setFloat(f[0]);
plug.elementByLogicalIndex(j + 1).setFloat(f[1]);
plug.elementByLogicalIndex(j + 2).setFloat(f[2]);
plug.elementByLogicalIndex(j + 3).setFloat(f[3]);
plug.elementByLogicalIndex(j + 4).setFloat(f[4]);
plug.elementByLogicalIndex(j + 5).setFloat(f[5]);
plug.elementByLogicalIndex(j + 6).setFloat(f[6]);
plug.elementByLogicalIndex(j + 7).setFloat(f[7]);
}
if(count & 0x4)
{
float f[4];
AL::usd::utils::half2float_4f(values + count8, f);
plug.elementByLogicalIndex(count8 + 0).setFloat(f[0]);
plug.elementByLogicalIndex(count8 + 1).setFloat(f[1]);
plug.elementByLogicalIndex(count8 + 2).setFloat(f[2]);
plug.elementByLogicalIndex(count8 + 3).setFloat(f[3]);
count8 |= 0x4;
}
switch(count & 0x3)
{
case 3: plug.elementByLogicalIndex(count8 + 2).setFloat(AL::usd::utils::half2float_1f(values[count8 + 2]));
case 2: plug.elementByLogicalIndex(count8 + 1).setFloat(AL::usd::utils::half2float_1f(values[count8 + 1]));
case 1: plug.elementByLogicalIndex(count8 + 0).setFloat(AL::usd::utils::half2float_1f(values[count8 + 0]));
default:
break;
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setFloatArray(MObject node, MObject attribute, const float* const values, const size_t count)
{
MPlug plug(node, attribute);
if(!plug)
{
}
else
{
if(!plug.isArray())
{
MStatus status;
MFnFloatArrayData fn;
MFloatArray temp(values, count);
MObject obj = fn.create(temp, &status);
if(status)
{
plug.setValue(obj);
return MS::kSuccess;
}
}
else
{
AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized");
for(size_t i = 0; i != count; ++i)
{
plug.elementByLogicalIndex(i).setFloat(values[i]);
}
}
return MS::kSuccess;
}
return MS::kFailure;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setDoubleArray(MObject node, MObject attribute, const double* const values, const size_t count)
{
MPlug plug(node, attribute);
if(!plug)
{
}
else
{
if(!plug.isArray())
{
MStatus status;
MFnDoubleArrayData fn;
MDoubleArray temp(values, count);
MObject obj = fn.create(temp, &status);
if(status)
{
plug.setValue(obj);
return MS::kSuccess;
}
}
else
{
AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized");
for(size_t i = 0; i != count; ++i)
{
plug.elementByLogicalIndex(i).setDouble(values[i]);
}
}
return MS::kSuccess;
}
return MS::kFailure;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setVec2Array(MObject node, MObject attribute, const int32_t* const values, const size_t count)
{
MPlug plug(node, attribute);
if(!plug || !plug.isArray())
return MS::kFailure;
AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized");
for(size_t i = 0, j = 0; i != count; ++i, j += 2)
{
auto v = plug.elementByLogicalIndex(i);
v.child(0).setInt(values[j]);
v.child(1).setInt(values[j + 1]);
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setVec2Array(MObject node, MObject attribute, const GfHalf* const values, const size_t count)
{
MPlug plug(node, attribute);
if(!plug || !plug.isArray())
return MS::kFailure;
AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized");
size_t count4 = count & ~0x3ULL;
for(size_t i = 0, j = 0; i != count4; i += 4, j += 8)
{
float f[8];
AL::usd::utils::half2float_8f(values + j, f);
auto v0 = plug.elementByLogicalIndex(i + 0);
auto v1 = plug.elementByLogicalIndex(i + 1);
auto v2 = plug.elementByLogicalIndex(i + 2);
auto v3 = plug.elementByLogicalIndex(i + 3);
v0.child(0).setFloat(f[0]);
v0.child(1).setFloat(f[1]);
v1.child(0).setFloat(f[2]);
v1.child(1).setFloat(f[3]);
v2.child(0).setFloat(f[4]);
v2.child(1).setFloat(f[5]);
v3.child(0).setFloat(f[6]);
v3.child(1).setFloat(f[7]);
}
if(count & 0x2)
{
float f[4];
AL::usd::utils::half2float_4f(values + count4 * 2, f);
auto v0 = plug.elementByLogicalIndex(count4 + 0);
auto v1 = plug.elementByLogicalIndex(count4 + 1);
v0.child(0).setFloat(f[0]);
v0.child(1).setFloat(f[1]);
v1.child(0).setFloat(f[2]);
v1.child(1).setFloat(f[3]);
count4 += 2;
}
if(count & 0x1)
{
auto v0 = plug.elementByLogicalIndex(count4);
v0.child(0).setFloat(AL::usd::utils::half2float_1f(values[count4 * 2]));
v0.child(1).setFloat(AL::usd::utils::half2float_1f(values[count4 * 2 + 1]));
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setVec2Array(MObject node, MObject attribute, const float* const values, const size_t count)
{
MPlug plug(node, attribute);
if(!plug || !plug.isArray())
return MS::kFailure;
AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized");
for(size_t i = 0, j = 0; i != count; ++i, j += 2)
{
auto v = plug.elementByLogicalIndex(i);
v.child(0).setFloat(values[j]);
v.child(1).setFloat(values[j + 1]);
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setVec2Array(MObject node, MObject attribute, const double* const values, const size_t count)
{
MPlug plug(node, attribute);
if(!plug || !plug.isArray())
return MS::kFailure;
AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized");
for(size_t i = 0, j = 0; i != count; ++i, j += 2)
{
auto v = plug.elementByLogicalIndex(i);
v.child(0).setDouble(values[j]);
v.child(1).setDouble(values[j + 1]);
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setVec3Array(MObject node, MObject attribute, const int32_t* const values, const size_t count)
{
MPlug plug(node, attribute);
if(!plug || !plug.isArray())
return MS::kFailure;
AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized");
for(size_t i = 0, j = 0; i != count; ++i, j += 3)
{
auto v = plug.elementByLogicalIndex(i);
v.child(0).setInt(values[j]);
v.child(1).setInt(values[j + 1]);
v.child(2).setInt(values[j + 2]);
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setVec3Array(MObject node, MObject attribute, const GfHalf* const values, const size_t count)
{
MPlug plug(node, attribute);
if(!plug || !plug.isArray())
return MS::kFailure;
AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized");
size_t count8 = count & ~0x7ULL;
for(size_t i = 0, j = 0; i != count8; i += 8, j += 24)
{
float f[24];
AL::usd::utils::half2float_8f(values + j, f);
AL::usd::utils::half2float_8f(values + j + 8, f + 8);
AL::usd::utils::half2float_8f(values + j + 16, f + 16);
for(int k = 0; k < 8; ++k)
{
auto v = plug.elementByLogicalIndex(i + k);
v.child(0).setFloat(f[k * 3 + 0]);
v.child(1).setFloat(f[k * 3 + 1]);
v.child(2).setFloat(f[k * 3 + 2]);
}
}
for(size_t i = count8, j = count8 * 3; i != count; ++i, j += 3)
{
float f[4];
GfHalf h[4];
h[0] = values[j];
h[1] = values[j + 1];
h[2] = values[j + 2];
AL::usd::utils::half2float_4f(h, f);
auto v = plug.elementByLogicalIndex(i);
v.child(0).setFloat(f[0]);
v.child(1).setFloat(f[1]);
v.child(2).setFloat(f[2]);
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setVec3Array(MObject node, MObject attribute, const float* const values, const size_t count)
{
MPlug plug(node, attribute);
if(!plug || !plug.isArray())
return MS::kFailure;
AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized");
for(size_t i = 0, j = 0; i != count; ++i, j += 3)
{
auto v = plug.elementByLogicalIndex(i);
v.child(0).setFloat(values[j]);
v.child(1).setFloat(values[j + 1]);
v.child(2).setFloat(values[j + 2]);
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setVec3Array(MObject node, MObject attribute, const double* const values, const size_t count)
{
MPlug plug(node, attribute);
if(!plug || !plug.isArray())
return MS::kFailure;
AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized");
for(size_t i = 0, j = 0; i != count; ++i, j += 3)
{
auto v = plug.elementByLogicalIndex(i);
v.child(0).setDouble(values[j]);
v.child(1).setDouble(values[j + 1]);
v.child(2).setDouble(values[j + 2]);
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setVec4Array(MObject node, MObject attribute, const GfHalf* const values, const size_t count)
{
MPlug plug(node, attribute);
if(!plug || !plug.isArray())
{
return MS::kFailure;
}
AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized");
size_t count2 = count & ~0x1ULL;
for(size_t i = 0, j = 0; i != count2; i += 2, j += 8)
{
float f[8];
AL::usd::utils::half2float_8f(values + j, f);
auto v0 = plug.elementByLogicalIndex(i);
auto v1 = plug.elementByLogicalIndex(i + 1);
v0.child(0).setFloat(f[0]);
v0.child(1).setFloat(f[1]);
v0.child(2).setFloat(f[2]);
v0.child(3).setFloat(f[3]);
v1.child(0).setFloat(f[4]);
v1.child(1).setFloat(f[5]);
v1.child(2).setFloat(f[6]);
v1.child(3).setFloat(f[7]);
}
if(count & 0x1)
{
float f[4];
AL::usd::utils::half2float_4f(values + count2 * 4, f);
auto v0 = plug.elementByLogicalIndex(count2);
v0.child(0).setFloat(f[0]);
v0.child(1).setFloat(f[1]);
v0.child(2).setFloat(f[2]);
v0.child(3).setFloat(f[3]);
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setVec4Array(MObject node, MObject attribute, const int* const values, const size_t count)
{
MPlug plug(node, attribute);
if(!plug || !plug.isArray())
return MS::kFailure;
AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized");
for(size_t i = 0, j = 0; i != count; ++i, j += 4)
{
auto v = plug.elementByLogicalIndex(i);
v.child(0).setInt(values[j]);
v.child(1).setInt(values[j + 1]);
v.child(2).setInt(values[j + 2]);
v.child(3).setInt(values[j + 3]);
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setVec4Array(MObject node, MObject attribute, const float* const values, const size_t count)
{
MPlug plug(node, attribute);
if(!plug || !plug.isArray())
return MS::kFailure;
AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized");
for(size_t i = 0, j = 0; i != count; ++i, j += 4)
{
auto v = plug.elementByLogicalIndex(i);
v.child(0).setFloat(values[j]);
v.child(1).setFloat(values[j + 1]);
v.child(2).setFloat(values[j + 2]);
v.child(3).setFloat(values[j + 3]);
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setVec4Array(MObject node, MObject attribute, const double* const values, const size_t count)
{
MPlug plug(node, attribute);
if(!plug || !plug.isArray())
return MS::kFailure;
AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized");
for(size_t i = 0, j = 0; i != count; ++i, j += 4)
{
auto v = plug.elementByLogicalIndex(i);
v.child(0).setDouble(values[j]);
v.child(1).setDouble(values[j + 1]);
v.child(2).setDouble(values[j + 2]);
v.child(3).setDouble(values[j + 3]);
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setMatrix4x4Array(MObject node, MObject attribute, const double* const values, const size_t count)
{
MPlug plug(node, attribute);
if(!plug)
return MS::kFailure;
if(!plug.isArray())
{
MStatus status;
MMatrixArray arrayData;
arrayData.setLength(count);
memcpy(&arrayData[0], values, sizeof(MMatrix) * count);
MFnMatrixArrayData fn;
MObject data = fn.create(arrayData, &status);
AL_MAYA_CHECK_ERROR2(status, MString("Count not set array value"));
status = plug.setValue(data);
AL_MAYA_CHECK_ERROR2(status, MString("Count not set array value"));
}
else
{
// Yes this is horrible. It would appear that as of Maya 2017, setting the contents of matrix array attributes doesn't work.
// Well, at least for dynamic attributes. Using an array builder inside a compute method would be one way
char tempStr[1024] = {0};
for(uint32_t i = 0; i < 16 * count; i += 16)
{
sprintf(tempStr, "setAttr \"%s[%d]\" -type \"matrix\" %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf;", plug.name().asChar(),
(i >> 4),
values[i + 0],
values[i + 1],
values[i + 2],
values[i + 3],
values[i + 4],
values[i + 5],
values[i + 6],
values[i + 7],
values[i + 8],
values[i + 9],
values[i + 10],
values[i + 11],
values[i + 12],
values[i + 13],
values[i + 14],
values[i + 15] );
MGlobal::executeCommand(tempStr);
}
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setMatrix4x4Array(MObject node, MObject attribute, const float* const values, const size_t count)
{
MPlug plug(node, attribute);
if(!plug)
return MS::kFailure;
if(!plug.isArray())
{
MStatus status;
MMatrixArray arrayData;
arrayData.setLength(count);
double* ptr = &arrayData[0].matrix[0][0];
for(size_t i = 0, j = 0; i != count; ++i, j += 16)
{
double* const dptr = ptr + j;
const float* const fptr = values + j;
#if AL_UTILS_ENABLE_SIMD
# if __AVX__
const f256 d0 = loadu8f(fptr);
const f256 d1 = loadu8f(fptr + 8);
storeu4d(dptr , cvt4f_to_4d(extract4f(d0, 0)));
storeu4d(dptr + 4, cvt4f_to_4d(extract4f(d0, 1)));
storeu4d(dptr + 8, cvt4f_to_4d(extract4f(d1, 0)));
storeu4d(dptr + 12, cvt4f_to_4d(extract4f(d1, 1)));
# else
const f128 d0 = loadu4f(fptr);
const f128 d1 = loadu4f(fptr + 4);
const f128 d2 = loadu4f(fptr + 8);
const f128 d3 = loadu4f(fptr + 12);
storeu2d(dptr , cvt2f_to_2d(d0));
storeu2d(dptr + 2, cvt2f_to_2d(movehl4f(d0, d0)));
storeu2d(dptr + 4, cvt2f_to_2d(d1));
storeu2d(dptr + 6, cvt2f_to_2d(movehl4f(d1, d1)));
storeu2d(dptr + 8, cvt2f_to_2d(d2));
storeu2d(dptr + 10, cvt2f_to_2d(movehl4f(d2, d2)));
storeu2d(dptr + 12, cvt2f_to_2d(d3));
storeu2d(dptr + 14, cvt2f_to_2d(movehl4f(d3, d3)));
# endif
#else
for(int k = 0; k < 16; ++k)
{
dptr[k] = fptr[k];
}
#endif
}
MFnMatrixArrayData fn;
MObject data = fn.create(arrayData, &status);
AL_MAYA_CHECK_ERROR2(status, MString("Count not set array value"));
status = plug.setValue(data);
AL_MAYA_CHECK_ERROR2(status, MString("Count not set array value"));
}
else
{
// I can't seem to create a multi of arrays within the Maya API (without using an array data builder within a compute).
char tempStr[2048] = {0};
for(uint32_t i = 0; i < 16 * count; i += 16)
{
sprintf(tempStr, "setAttr \"%s[%d]\" -type \"matrix\" %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f;", plug.name().asChar(),
(i >> 4),
values[i + 0],
values[i + 1],
values[i + 2],
values[i + 3],
values[i + 4],
values[i + 5],
values[i + 6],
values[i + 7],
values[i + 8],
values[i + 9],
values[i + 10],
values[i + 11],
values[i + 12],
values[i + 13],
values[i + 14],
values[i + 15] );
MGlobal::executeCommand(tempStr);
}
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setTimeArray(MObject node, MObject attribute, const float* const values, const size_t count, MTime::Unit unit)
{
// determine how much we need to modify the
const MTime mod(1.0, unit);
const float unitConversion = float(mod.as(MTime::k6000FPS));
MPlug plug(node, attribute);
if(!plug || !plug.isArray())
return MS::kFailure;
AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized");
#if AL_UTILS_ENABLE_SIMD
const f128 unitConversion128 = splat4f(unitConversion);
const size_t count4 = count & ~3ULL;
size_t i = 0;
for(; i < count4; i += 4)
{
MPlug v0 = plug.elementByLogicalIndex(i);
MPlug v1 = plug.elementByLogicalIndex(i + 1);
MPlug v2 = plug.elementByLogicalIndex(i + 2);
MPlug v3 = plug.elementByLogicalIndex(i + 3);
const f128 temp = mul4f(unitConversion128, loadu4f(values + i));
ALIGN16(float tempf[4]);
store4f(tempf, temp);
v0.setFloat(tempf[0]);
v1.setFloat(tempf[1]);
v2.setFloat(tempf[2]);
v3.setFloat(tempf[3]);
}
switch(count & 3)
{
case 3: plug.elementByLogicalIndex(i + 2).setFloat(unitConversion * values[i + 2]);
case 2: plug.elementByLogicalIndex(i + 1).setFloat(unitConversion * values[i + 1]);
case 1: plug.elementByLogicalIndex(i ).setFloat(unitConversion * values[i ]);
default: break;
}
#else
for(size_t i = 0; i < count; ++i)
{
plug.elementByLogicalIndex(i).setFloat(unitConversion * values[i]);
}
#endif
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setAngleArray(MObject node, MObject attribute, const float* const values, const size_t count, MAngle::Unit unit)
{
// determine how much we need to modify the
const MAngle mod(1.0, unit);
const float unitConversion = float(mod.as(MAngle::internalUnit()));
MPlug plug(node, attribute);
if(!plug || !plug.isArray())
return MS::kFailure;
AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized");
#if AL_UTILS_ENABLE_SIMD
const f128 unitConversion128 = splat4f(unitConversion);
const size_t count4 = count & ~3ULL;
size_t i = 0;
for(; i < count4; i += 4)
{
MPlug v0 = plug.elementByLogicalIndex(i);
MPlug v1 = plug.elementByLogicalIndex(i + 1);
MPlug v2 = plug.elementByLogicalIndex(i + 2);
MPlug v3 = plug.elementByLogicalIndex(i + 3);
const f128 temp = mul4f(unitConversion128, loadu4f(values + i));
ALIGN16(float tempf[4]);
store4f(tempf, temp);
v0.setFloat(tempf[0]);
v1.setFloat(tempf[1]);
v2.setFloat(tempf[2]);
v3.setFloat(tempf[3]);
}
switch(count & 3)
{
case 3: plug.elementByLogicalIndex(i + 2).setFloat(unitConversion * values[i + 2]);
case 2: plug.elementByLogicalIndex(i + 1).setFloat(unitConversion * values[i + 1]);
case 1: plug.elementByLogicalIndex(i ).setFloat(unitConversion * values[i]);
default: break;
}
#else
for(size_t i = 0; i < count; ++i)
{
plug.elementByLogicalIndex(i).setFloat(unitConversion * values[i]);
}
#endif
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setDistanceArray(MObject node, MObject attribute, const float* const values, const size_t count, MDistance::Unit unit)
{
// determine how much we need to modify the
const MDistance mod(1.0, unit);
const float unitConversion = float(mod.as(MDistance::internalUnit()));
MPlug plug(node, attribute);
if(!plug || !plug.isArray())
return MS::kFailure;
AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized");
#if AL_UTILS_ENABLE_SIMD
const f128 unitConversion128 = splat4f(unitConversion);
const size_t count4 = count & ~3ULL;
size_t i = 0;
for(; i < count4; i += 4)
{
MPlug v0 = plug.elementByLogicalIndex(i);
MPlug v1 = plug.elementByLogicalIndex(i + 1);
MPlug v2 = plug.elementByLogicalIndex(i + 2);
MPlug v3 = plug.elementByLogicalIndex(i + 3);
const f128 temp = mul4f(unitConversion128, loadu4f(values + i));
ALIGN16(float tempf[4]);
store4f(tempf, temp);
v0.setFloat(tempf[0]);
v1.setFloat(tempf[1]);
v2.setFloat(tempf[2]);
v3.setFloat(tempf[3]);
}
switch(count & 0x3)
{
case 3: plug.elementByLogicalIndex(i + 2).setFloat(unitConversion * values[i + 2]);
case 2: plug.elementByLogicalIndex(i + 1).setFloat(unitConversion * values[i + 1]);
case 1: plug.elementByLogicalIndex(i ).setFloat(unitConversion * values[i]);
default: break;
}
#else
for(size_t i = 0; i < count; ++i)
{
plug.elementByLogicalIndex(i).setFloat(unitConversion * values[i]);
}
#endif
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setUsdBoolArray(const MObject& node, const MObject& attribute, const VtArray<bool>& values)
{
MPlug plug(node, attribute);
if(!plug || !plug.isArray())
return MS::kFailure;
AL_MAYA_CHECK_ERROR(plug.setNumElements(values.size()), "DgNodeTranslator: attribute array could not be resized");
for(size_t i = 0, n = values.size(); i != n; ++i)
{
plug.elementByLogicalIndex(i).setBool(values[i]);
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setAngleAnim(MObject node, MObject attr, const UsdGeomXformOp op)
{
MStatus status;
const char* const errorString = "DgNodeHelper::setAngleAnim";
MPlug plug(node, attr);
MFnAnimCurve fnCurve;
fnCurve.create(plug, NULL, &status);
AL_MAYA_CHECK_ERROR(status, errorString);
std::vector<double> times;
op.GetTimeSamples(×);
const float conversionFactor = 0.0174533f;
float value = 0;
for(auto const& timeValue: times)
{
const bool retValue = op.GetAs<float>(&value, timeValue);
if (!retValue) continue;
MTime tm(timeValue, MTime::kFilm);
switch (fnCurve.animCurveType())
{
case MFnAnimCurve::kAnimCurveTL:
case MFnAnimCurve::kAnimCurveTA:
case MFnAnimCurve::kAnimCurveTU:
{
fnCurve.addKey(tm, value * conversionFactor, MFnAnimCurve::kTangentGlobal, MFnAnimCurve::kTangentGlobal, NULL, &status);
AL_MAYA_CHECK_ERROR(status, errorString);
break;
}
default:
{
std::cout << "[DgNodeHelper::setAngleAnim] Unexpected anim curve type: " << fnCurve.animCurveType() << std::endl;
break;
}
}
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setFloatAttrAnim(const MObject node, const MObject attr, UsdAttribute usdAttr,
double conversionFactor)
{
if (!usdAttr.GetNumTimeSamples())
{
return MS::kFailure;
}
const char* const errorString = "DgNodeTranslator::setFloatAttrAnim";
MStatus status;
MPlug plug(node, attr);
MPlug srcPlug;
MFnAnimCurve fnCurve;
MDGModifier dgmod;
srcPlug = plug.source(&status);
AL_MAYA_CHECK_ERROR(status, errorString);
if(!srcPlug.isNull())
{
std::cout << "[DgNodeTranslator::setFloatAttrAnim] disconnecting curve! = " << srcPlug.name().asChar() << std::endl;
dgmod.disconnect(srcPlug, plug);
dgmod.doIt();
}
fnCurve.create(plug, NULL, &status);
AL_MAYA_CHECK_ERROR(status, errorString);
std::vector<double> times;
usdAttr.GetTimeSamples(×);
float value;
for(auto const& timeValue: times)
{
const bool retValue = usdAttr.Get(&value, timeValue);
if(!retValue) continue;
MTime tm(timeValue, MTime::kFilm);
switch(fnCurve.animCurveType())
{
case MFnAnimCurve::kAnimCurveTL:
case MFnAnimCurve::kAnimCurveTA:
case MFnAnimCurve::kAnimCurveTU:
{
fnCurve.addKey(tm, value * conversionFactor, MFnAnimCurve::kTangentGlobal, MFnAnimCurve::kTangentGlobal, NULL, &status);
AL_MAYA_CHECK_ERROR(status, errorString);
break;
}
default:
{
std::cout << "[DgNodeTranslator::setFloatAttrAnim] OTHER ANIM CURVE TYPE! = " << fnCurve.animCurveType() << std::endl;
break;
}
}
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setVisAttrAnim(const MObject node, const MObject attr, const UsdAttribute &usdAttr)
{
if (!usdAttr.GetNumTimeSamples())
{
return MS::kFailure;
}
const char* const errorString = "DgNodeTranslator::setVisAttrAnim";
MStatus status;
MPlug plug(node, attr);
MPlug srcPlug;
MFnAnimCurve fnCurve;
MDGModifier dgmod;
srcPlug = plug.source(&status);
AL_MAYA_CHECK_ERROR(status, errorString);
if(!srcPlug.isNull())
{
std::cout << "[DgNodeTranslator::setVisAttrAnim] disconnecting curve! = " << srcPlug.name().asChar() << std::endl;
dgmod.disconnect(srcPlug, plug);
dgmod.doIt();
}
fnCurve.create(plug, NULL, &status);
AL_MAYA_CHECK_ERROR(status, errorString);
std::vector<double> times;
usdAttr.GetTimeSamples(×);
TfToken value;
for(auto const& timeValue: times)
{
const bool retValue = usdAttr.Get<TfToken>(&value, timeValue);
if(!retValue) continue;
MTime tm(timeValue, MTime::kFilm);
fnCurve.addKey(tm, (value == UsdGeomTokens->invisible) ? 0 : 1, MFnAnimCurve::kTangentGlobal, MFnAnimCurve::kTangentGlobal, NULL, &status);
AL_MAYA_CHECK_ERROR(status, errorString);
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getBoolArray(const MObject& node, const MObject& attr, std::vector<bool>& values)
{
//
// Handle the oddity that is std::vector<bool>
//
MPlug plug(node, attr);
if(!plug || !plug.isArray())
return MS::kFailure;
uint32_t num = plug.numElements();
values.resize(num);
for(uint32_t i = 0; i < num; ++i)
{
values[i] = plug.elementByLogicalIndex(i).asBool();
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getBoolArray(MObject node, MObject attribute, bool* const values, const size_t count)
{
MPlug plug(node, attribute);
if(!plug || !plug.isArray())
return MS::kFailure;
uint32_t num = plug.numElements();
if(num != count)
{
MGlobal::displayError("array is sized incorrectly");
return MS::kFailure;
}
#if AL_UTILS_ENABLE_SIMD
uint32_t count16 = count & ~0xF;
for(uint32_t i = 0; i < count16; i += 16)
{
ALIGN16(bool temp[16]);
temp[0] = plug.elementByLogicalIndex(i).asBool();
temp[1] = plug.elementByLogicalIndex(i + 1).asBool();
temp[2] = plug.elementByLogicalIndex(i + 2).asBool();
temp[3] = plug.elementByLogicalIndex(i + 3).asBool();
temp[4] = plug.elementByLogicalIndex(i + 4).asBool();
temp[5] = plug.elementByLogicalIndex(i + 5).asBool();
temp[6] = plug.elementByLogicalIndex(i + 6).asBool();
temp[7] = plug.elementByLogicalIndex(i + 7).asBool();
temp[8] = plug.elementByLogicalIndex(i + 8).asBool();
temp[9] = plug.elementByLogicalIndex(i + 9).asBool();
temp[10] = plug.elementByLogicalIndex(i + 10).asBool();
temp[11] = plug.elementByLogicalIndex(i + 11).asBool();
temp[12] = plug.elementByLogicalIndex(i + 12).asBool();
temp[13] = plug.elementByLogicalIndex(i + 13).asBool();
temp[14] = plug.elementByLogicalIndex(i + 14).asBool();
temp[15] = plug.elementByLogicalIndex(i + 15).asBool();
storeu4i(values + i, load4i(temp));
}
for(uint32_t i = count16; i < num; ++i)
{
values[i] = plug.elementByLogicalIndex(i).asBool();
}
#else
for(uint32_t i = 0; i < num; ++i)
{
values[i] = plug.elementByLogicalIndex(i).asBool();
}
#endif
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getInt64Array(MObject node, MObject attribute, int64_t* const values, const size_t count)
{
MPlug plug(node, attribute);
if(!plug || !plug.isArray())
return MS::kFailure;
uint32_t num = plug.numElements();
if(num != count)
{
MGlobal::displayError(plug.name() + ", error array is sized incorrectly");
return MS::kFailure;
}
#if AL_UTILS_ENABLE_SIMD
#ifdef __AVX__
uint32_t count4 = count & ~0x3;
uint32_t i = 0;
for(; i < count4; i += 4)
{
ALIGN32(int64_t temp[4]);
temp[0] = plug.elementByLogicalIndex(i).asInt64();
temp[1] = plug.elementByLogicalIndex(i + 1).asInt64();
temp[2] = plug.elementByLogicalIndex(i + 2).asInt64();
temp[3] = plug.elementByLogicalIndex(i + 3).asInt64();
storeu8i(values + i, load8i(temp));
}
if(count & 0x2)
{
ALIGN16(int64_t temp[2]);
temp[0] = plug.elementByLogicalIndex(i).asInt64();
temp[1] = plug.elementByLogicalIndex(i + 1).asInt64();
storeu4i(values + i, load4i(temp));
i += 2;
}
#else
uint32_t count2 = count & ~0x1;
uint32_t i = 0;
for(; i < count2; i += 2)
{
ALIGN16(int64_t temp[2]);
temp[0] = plug.elementByLogicalIndex(i).asInt64();
temp[1] = plug.elementByLogicalIndex(i + 1).asInt64();
storeu4i(values + i, load4i(temp));
}
#endif
if(count & 1)
{
values[i] = plug.elementByLogicalIndex(i).asInt64();
}
#else
for(uint32_t i = 0; i < num; ++i)
{
values[i] = plug.elementByLogicalIndex(i).asInt64();
}
#endif
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getInt32Array(MObject node, MObject attribute, int32_t* const values, const size_t count)
{
MPlug plug(node, attribute);
if(!plug || !plug.isArray())
return MS::kFailure;
uint32_t num = plug.numElements();
if(num != count)
{
MGlobal::displayError("array is sized incorrectly");
return MS::kFailure;
}
#if AL_UTILS_ENABLE_SIMD
#ifdef __AVX__
uint32_t count8 = count & ~0x7;
uint32_t i = 0;
for(; i < count8; i += 8)
{
ALIGN32(int32_t temp[8]);
temp[0] = plug.elementByLogicalIndex(i).asInt();
temp[1] = plug.elementByLogicalIndex(i + 1).asInt();
temp[2] = plug.elementByLogicalIndex(i + 2).asInt();
temp[3] = plug.elementByLogicalIndex(i + 3).asInt();
temp[4] = plug.elementByLogicalIndex(i + 4).asInt();
temp[5] = plug.elementByLogicalIndex(i + 5).asInt();
temp[6] = plug.elementByLogicalIndex(i + 6).asInt();
temp[7] = plug.elementByLogicalIndex(i + 7).asInt();
storeu8i(values + i, load8i(temp));
}
if(count & 0x4)
{
ALIGN16(int32_t temp[4]);
temp[0] = plug.elementByLogicalIndex(i).asInt();
temp[1] = plug.elementByLogicalIndex(i + 1).asInt();
temp[2] = plug.elementByLogicalIndex(i + 2).asInt();
temp[3] = plug.elementByLogicalIndex(i + 3).asInt();
storeu4i(values + i, load4i(temp));
i += 4;
}
#else
uint32_t count4 = count & ~0x3;
uint32_t i = 0;
for(; i < count4; i += 4)
{
ALIGN16(int32_t temp[4]);
temp[0] = plug.elementByLogicalIndex(i).asInt();
temp[1] = plug.elementByLogicalIndex(i + 1).asInt();
temp[2] = plug.elementByLogicalIndex(i + 2).asInt();
temp[3] = plug.elementByLogicalIndex(i + 3).asInt();
storeu4i(values + i, load4i(temp));
}
#endif
switch(count & 3)
{
case 3: values[i + 2] = plug.elementByLogicalIndex(i + 2).asInt();
case 2: values[i + 1] = plug.elementByLogicalIndex(i + 1).asInt();
case 1: values[i] = plug.elementByLogicalIndex(i).asInt();
default: break;
}
#else
for(uint32_t i = 0; i < num; ++i)
{
values[i] = plug.elementByLogicalIndex(i).asInt();
}
#endif
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getInt8Array(MObject node, MObject attribute, int8_t* const values, const size_t count)
{
MPlug plug(node, attribute);
if(!plug || !plug.isArray())
return MS::kFailure;
uint32_t num = plug.numElements();
if(num != count)
{
MGlobal::displayError("array is sized incorrectly");
return MS::kFailure;
}
for(uint32_t i = 0; i < num; ++i)
{
values[i] = plug.elementByLogicalIndex(i).asChar();
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getInt16Array(MObject node, MObject attribute, int16_t* const values, const size_t count)
{
MPlug plug(node, attribute);
if(!plug || !plug.isArray())
return MS::kFailure;
uint32_t num = plug.numElements();
if(num != count)
{
MGlobal::displayError("array is sized incorrectly");
return MS::kFailure;
}
for(uint32_t i = 0; i < num; ++i)
{
values[i] = plug.elementByLogicalIndex(i).asShort();
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getFloatArray(MObject node, MObject attribute, float* const values, const size_t count)
{
MPlug plug(node, attribute);
if(!plug || !plug.isArray())
return MS::kFailure;
uint32_t num = plug.numElements();
if(num != count)
{
MGlobal::displayError("array is sized incorrectly");
return MS::kFailure;
}
#if AL_UTILS_ENABLE_SIMD
#ifdef __AVX__
uint32_t count8 = count & ~0x7;
uint32_t i = 0;
for(; i < count8; i += 8)
{
ALIGN32(float temp[8]);
temp[0] = plug.elementByLogicalIndex(i).asFloat();
temp[1] = plug.elementByLogicalIndex(i + 1).asFloat();
temp[2] = plug.elementByLogicalIndex(i + 2).asFloat();
temp[3] = plug.elementByLogicalIndex(i + 3).asFloat();
temp[4] = plug.elementByLogicalIndex(i + 4).asFloat();
temp[5] = plug.elementByLogicalIndex(i + 5).asFloat();
temp[6] = plug.elementByLogicalIndex(i + 6).asFloat();
temp[7] = plug.elementByLogicalIndex(i + 7).asFloat();
storeu8f(values + i, load8f(temp));
}
if(count & 0x4)
{
ALIGN16(float temp[4]);
temp[0] = plug.elementByLogicalIndex(i).asFloat();
temp[1] = plug.elementByLogicalIndex(i + 1).asFloat();
temp[2] = plug.elementByLogicalIndex(i + 2).asFloat();
temp[3] = plug.elementByLogicalIndex(i + 3).asFloat();
storeu4f(values + i, load4f(temp));
i += 4;
}
#else
uint32_t count4 = count & ~0x3;
uint32_t i = 0;
for(; i < count4; i += 4)
{
ALIGN16(float temp[4]);
temp[0] = plug.elementByLogicalIndex(i).asFloat();
temp[1] = plug.elementByLogicalIndex(i + 1).asFloat();
temp[2] = plug.elementByLogicalIndex(i + 2).asFloat();
temp[3] = plug.elementByLogicalIndex(i + 3).asFloat();
storeu4f(values + i, load4f(temp));
}
#endif
switch(count & 3)
{
case 3: values[i + 2] = plug.elementByLogicalIndex(i + 2).asFloat();
case 2: values[i + 1] = plug.elementByLogicalIndex(i + 1).asFloat();
case 1: values[i] = plug.elementByLogicalIndex(i).asFloat();
default: break;
}
#else
for(uint32_t i = 0; i < num; ++i)
{
values[i] = plug.elementByLogicalIndex(i).asFloat();
}
#endif
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getHalfArray(MObject node, MObject attribute, GfHalf* const values, const size_t count)
{
MPlug plug(node, attribute);
if(!plug || !plug.isArray())
return MS::kFailure;
uint32_t num = plug.numElements();
if(num != count)
{
MGlobal::displayError("array is sized incorrectly");
return MS::kFailure;
}
size_t count8 = count & ~0x7ULL;
for(uint32_t i = 0; i < count8; i += 8)
{
float f[8];
f[0] = plug.elementByLogicalIndex(i + 0).asFloat();
f[1] = plug.elementByLogicalIndex(i + 1).asFloat();
f[2] = plug.elementByLogicalIndex(i + 2).asFloat();
f[3] = plug.elementByLogicalIndex(i + 3).asFloat();
f[4] = plug.elementByLogicalIndex(i + 4).asFloat();
f[5] = plug.elementByLogicalIndex(i + 5).asFloat();
f[6] = plug.elementByLogicalIndex(i + 6).asFloat();
f[7] = plug.elementByLogicalIndex(i + 7).asFloat();
AL::usd::utils::float2half_8f(f, values + i);
}
if(count & 0x4)
{
float f[4];
f[0] = plug.elementByLogicalIndex(count8 + 0).asFloat();
f[1] = plug.elementByLogicalIndex(count8 + 1).asFloat();
f[2] = plug.elementByLogicalIndex(count8 + 2).asFloat();
f[3] = plug.elementByLogicalIndex(count8 + 3).asFloat();
AL::usd::utils::float2half_4f(f, values + count8);
count8 += 4;
}
switch(count & 0x3)
{
case 3: values[count8 + 2] = AL::usd::utils::float2half_1f(plug.elementByLogicalIndex(count8 + 2).asFloat());
case 2: values[count8 + 1] = AL::usd::utils::float2half_1f(plug.elementByLogicalIndex(count8 + 1).asFloat());
case 1: values[count8 + 0] = AL::usd::utils::float2half_1f(plug.elementByLogicalIndex(count8 + 0).asFloat());
default: break;
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getDoubleArray(MObject node, MObject attribute, double* const values, const size_t count)
{
MPlug plug(node, attribute);
if(!plug || !plug.isArray())
return MS::kFailure;
uint32_t num = plug.numElements();
if(num != count)
{
MGlobal::displayError("array is sized incorrectly");
return MS::kFailure;
}
#if AL_UTILS_ENABLE_SIMD
#ifdef __AVX__
uint32_t count8 = count & ~0x7;
uint32_t i = 0;
for(; i < count8; i += 8)
{
ALIGN32(double temp[8]);
temp[0] = plug.elementByLogicalIndex(i).asDouble();
temp[1] = plug.elementByLogicalIndex(i + 1).asDouble();
temp[2] = plug.elementByLogicalIndex(i + 2).asDouble();
temp[3] = plug.elementByLogicalIndex(i + 3).asDouble();
temp[4] = plug.elementByLogicalIndex(i + 4).asDouble();
temp[5] = plug.elementByLogicalIndex(i + 5).asDouble();
temp[6] = plug.elementByLogicalIndex(i + 6).asDouble();
temp[7] = plug.elementByLogicalIndex(i + 7).asDouble();
storeu4d(values + i, load4d(temp));
storeu4d(values + i + 4, load4d(temp + 4));
}
if(count & 0x4)
{
ALIGN16(double temp[4]);
temp[0] = plug.elementByLogicalIndex(i).asDouble();
temp[1] = plug.elementByLogicalIndex(i + 1).asDouble();
temp[2] = plug.elementByLogicalIndex(i + 2).asDouble();
temp[3] = plug.elementByLogicalIndex(i + 3).asDouble();
storeu4d(values + i, load4d(temp));
i += 4;
}
#else
uint32_t count4 = count & ~0x3;
uint32_t i = 0;
for(; i < count4; i += 4)
{
ALIGN16(double temp[4]);
temp[0] = plug.elementByLogicalIndex(i).asDouble();
temp[1] = plug.elementByLogicalIndex(i + 1).asDouble();
temp[2] = plug.elementByLogicalIndex(i + 2).asDouble();
temp[3] = plug.elementByLogicalIndex(i + 3).asDouble();
storeu2d(values + i, load2d(temp));
storeu2d(values + i + 2, load2d(temp + 2));
}
#endif
switch(count & 3)
{
case 3: values[i + 2] = plug.elementByLogicalIndex(i + 2).asDouble();
case 2: values[i + 1] = plug.elementByLogicalIndex(i + 1).asDouble();
case 1: values[i] = plug.elementByLogicalIndex(i).asDouble();
default: break;
}
#else
for(uint32_t i = 0; i < num; ++i)
{
values[i] = plug.elementByLogicalIndex(i).asDouble();
}
#endif
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getVec2Array(MObject node, MObject attribute, double* const values, const size_t count)
{
MPlug plug(node, attribute);
if(!plug || !plug.isArray())
return MS::kFailure;
uint32_t num = plug.numElements();
if(num != count)
{
MGlobal::displayError("array is sized incorrectly");
return MS::kFailure;
}
#if AL_UTILS_ENABLE_SIMD
#ifdef __AVX__
uint32_t count2 = count & ~0x1;
uint32_t i = 0;
for(; i < count2; i += 2)
{
ALIGN32(double temp[4]);
temp[0] = plug.elementByLogicalIndex(i).child(0).asDouble();
temp[1] = plug.elementByLogicalIndex(i).child(1).asDouble();
temp[2] = plug.elementByLogicalIndex(i + 1).child(0).asDouble();
temp[3] = plug.elementByLogicalIndex(i + 1).child(1).asDouble();
storeu4d(values + i * 2, load4d(temp));
}
if(count & 1)
{
ALIGN16(double temp[2]);
temp[0] = plug.elementByLogicalIndex(i).child(0).asDouble();
temp[1] = plug.elementByLogicalIndex(i).child(1).asDouble();
storeu2d(values + i * 2, load2d(temp));
}
#else
uint32_t i = 0;
for(; i < count; ++i)
{
ALIGN16(double temp[2]);
temp[0] = plug.elementByLogicalIndex(i).child(0).asDouble();
temp[1] = plug.elementByLogicalIndex(i).child(1).asDouble();
storeu2d(values + i * 2, load2d(temp));
}
#endif
#else
for(uint32_t i = 0, j = 0; i < num; ++i, j += 2)
{
values[j] = plug.elementByLogicalIndex(i).child(0).asDouble();
values[j + 1] = plug.elementByLogicalIndex(i).child(1).asDouble();
}
#endif
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getVec2Array(MObject node, MObject attribute, float* const values, const size_t count)
{
MPlug plug(node, attribute);
if(!plug || !plug.isArray())
return MS::kFailure;
uint32_t num = plug.numElements();
if(num != count)
{
MGlobal::displayError("array is sized incorrectly");
return MS::kFailure;
}
#if AL_UTILS_ENABLE_SIMD
#ifdef __AVX__
uint32_t count4 = count & ~0x3;
uint32_t i = 0;
for(; i < count4; i += 4)
{
ALIGN32(float temp[8]);
temp[0] = plug.elementByLogicalIndex(i).child(0).asFloat();
temp[1] = plug.elementByLogicalIndex(i).child(1).asFloat();
temp[2] = plug.elementByLogicalIndex(i + 1).child(0).asFloat();
temp[3] = plug.elementByLogicalIndex(i + 1).child(1).asFloat();
temp[4] = plug.elementByLogicalIndex(i + 2).child(0).asFloat();
temp[5] = plug.elementByLogicalIndex(i + 2).child(1).asFloat();
temp[6] = plug.elementByLogicalIndex(i + 3).child(0).asFloat();
temp[7] = plug.elementByLogicalIndex(i + 3).child(1).asFloat();
storeu8f(values + i * 2, load8f(temp));
}
if(count & 0x2)
{
ALIGN16(float temp[4]);
temp[0] = plug.elementByLogicalIndex(i).child(0).asFloat();
temp[1] = plug.elementByLogicalIndex(i).child(1).asFloat();
temp[2] = plug.elementByLogicalIndex(i + 1).child(0).asFloat();
temp[3] = plug.elementByLogicalIndex(i + 1).child(1).asFloat();
storeu4f(values + i * 2, load4f(temp));
i += 2;
}
#else
uint32_t count2 = count & ~0x1;
uint32_t i = 0;
for(; i < count2; i += 2)
{
ALIGN16(float temp[4]);
temp[0] = plug.elementByLogicalIndex(i).child(0).asFloat();
temp[1] = plug.elementByLogicalIndex(i).child(1).asFloat();
temp[2] = plug.elementByLogicalIndex(i + 1).child(0).asFloat();
temp[3] = plug.elementByLogicalIndex(i + 1).child(1).asFloat();
storeu4f(values + i * 2, load4f(temp));
}
#endif
switch(count & 1)
{
case 1: values[i * 2] = plug.elementByLogicalIndex(i).child(0).asFloat();
values[i * 2 + 1] = plug.elementByLogicalIndex(i).child(1).asFloat();
default: break;
}
#else
for(uint32_t i = 0, j = 0; i < num; ++i, j += 2)
{
values[j] = plug.elementByLogicalIndex(i).child(0).asFloat();
values[j + 1] = plug.elementByLogicalIndex(i).child(1).asFloat();
}
#endif
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getVec2Array(MObject node, MObject attribute, GfHalf* const values, const size_t count)
{
MPlug plug(node, attribute);
if(!plug || !plug.isArray())
return MS::kFailure;
uint32_t num = plug.numElements();
if(num != count)
{
MGlobal::displayError("array is sized incorrectly");
return MS::kFailure;
}
for(uint32_t i = 0, j = 0; i < num; ++i, j += 2)
{
values[j] = plug.elementByLogicalIndex(i).child(0).asFloat();
values[j + 1] = plug.elementByLogicalIndex(i).child(1).asFloat();
}
size_t count4 = count & ~0x3FULL;
for(uint32_t i = 0, j = 0; i < count4; i += 4, j += 8)
{
float f[8];
auto v0 = plug.elementByLogicalIndex(i + 0);
auto v1 = plug.elementByLogicalIndex(i + 1);
auto v2 = plug.elementByLogicalIndex(i + 2);
auto v3 = plug.elementByLogicalIndex(i + 3);
f[0] = v0.child(0).asFloat();
f[1] = v0.child(1).asFloat();
f[2] = v1.child(0).asFloat();
f[3] = v1.child(1).asFloat();
f[4] = v2.child(0).asFloat();
f[5] = v2.child(1).asFloat();
f[6] = v3.child(0).asFloat();
f[7] = v3.child(1).asFloat();
AL::usd::utils::float2half_8f(f, values + j);
}
if(count & 0x2)
{
float f[4];
auto v0 = plug.elementByLogicalIndex(count4 + 0);
auto v1 = plug.elementByLogicalIndex(count4 + 1);
f[0] = v0.child(0).asFloat();
f[1] = v0.child(1).asFloat();
f[2] = v1.child(0).asFloat();
f[3] = v1.child(1).asFloat();
AL::usd::utils::float2half_4f(f, values + count4 * 2);
count4 += 2;
}
if(count & 0x1)
{
auto v = plug.elementByLogicalIndex(count4);
values[count4 * 2 + 0] = AL::usd::utils::float2half_1f(v.child(0).asFloat());
values[count4 * 2 + 1] = AL::usd::utils::float2half_1f(v.child(1).asFloat());
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getVec2Array(MObject node, MObject attribute, int32_t* const values, const size_t count)
{
MPlug plug(node, attribute);
if(!plug || !plug.isArray())
return MS::kFailure;
uint32_t num = plug.numElements();
if(num != count)
{
MGlobal::displayError("array is sized incorrectly");
return MS::kFailure;
}
#if AL_UTILS_ENABLE_SIMD
#ifdef __AVX__
uint32_t count4 = count & ~0x3;
uint32_t i = 0;
for(; i < count4; i += 4)
{
ALIGN32(int32_t temp[8]);
temp[0] = plug.elementByLogicalIndex(i).child(0).asInt();
temp[1] = plug.elementByLogicalIndex(i).child(1).asInt();
temp[2] = plug.elementByLogicalIndex(i + 1).child(0).asInt();
temp[3] = plug.elementByLogicalIndex(i + 1).child(1).asInt();
temp[4] = plug.elementByLogicalIndex(i + 2).child(0).asInt();
temp[5] = plug.elementByLogicalIndex(i + 2).child(1).asInt();
temp[6] = plug.elementByLogicalIndex(i + 3).child(0).asInt();
temp[7] = plug.elementByLogicalIndex(i + 3).child(1).asInt();
storeu8i(values + i * 2, load8i(temp));
}
if(count & 0x2)
{
ALIGN16(int32_t temp[4]);
temp[0] = plug.elementByLogicalIndex(i).child(0).asInt();
temp[1] = plug.elementByLogicalIndex(i).child(1).asInt();
temp[2] = plug.elementByLogicalIndex(i + 1).child(0).asInt();
temp[3] = plug.elementByLogicalIndex(i + 1).child(1).asInt();
storeu4i(values + i * 2, load4i(temp));
i += 2;
}
#else
uint32_t count2 = count & ~0x1;
uint32_t i = 0;
for(; i < count2; i += 2)
{
ALIGN16(int32_t temp[4]);
temp[0] = plug.elementByLogicalIndex(i).child(0).asInt();
temp[1] = plug.elementByLogicalIndex(i).child(1).asInt();
temp[2] = plug.elementByLogicalIndex(i + 1).child(0).asInt();
temp[3] = plug.elementByLogicalIndex(i + 1).child(1).asInt();
storeu4i(values + i * 2, load4i(temp));
}
#endif
if(count & 1)
{
values[i * 2] = plug.elementByLogicalIndex(i).child(0).asInt();
values[i * 2 + 1] = plug.elementByLogicalIndex(i).child(1).asInt();
}
#else
for(uint32_t i = 0, j = 0; i < num; ++i, j += 2)
{
values[j] = plug.elementByLogicalIndex(i).child(0).asInt();
values[j + 1] = plug.elementByLogicalIndex(i).child(1).asInt();
}
#endif
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getVec3Array(MObject node, MObject attribute, float* const values, const size_t count)
{
MPlug plug(node, attribute);
if(!plug || !plug.isArray())
return MS::kFailure;
uint32_t num = plug.numElements();
if(num != count)
{
MGlobal::displayError("array is sized incorrectly");
return MS::kFailure;
}
#if AL_UTILS_ENABLE_SIMD
#ifdef __AVX__
uint32_t count8 = count & ~0x7;
uint32_t i = 0;
for(; i < count8; i += 8)
{
ALIGN32(float temp[24]);
const MPlug c0 = plug.elementByLogicalIndex(i );
const MPlug c1 = plug.elementByLogicalIndex(i + 1);
const MPlug c2 = plug.elementByLogicalIndex(i + 2);
const MPlug c3 = plug.elementByLogicalIndex(i + 3);
const MPlug c4 = plug.elementByLogicalIndex(i + 4);
const MPlug c5 = plug.elementByLogicalIndex(i + 5);
const MPlug c6 = plug.elementByLogicalIndex(i + 6);
const MPlug c7 = plug.elementByLogicalIndex(i + 7);
temp[ 0] = c0.child(0).asFloat();
temp[ 1] = c0.child(1).asFloat();
temp[ 2] = c0.child(2).asFloat();
temp[ 3] = c1.child(0).asFloat();
temp[ 4] = c1.child(1).asFloat();
temp[ 5] = c1.child(2).asFloat();
temp[ 6] = c2.child(0).asFloat();
temp[ 7] = c2.child(1).asFloat();
temp[ 8] = c2.child(2).asFloat();
temp[ 9] = c3.child(0).asFloat();
temp[10] = c3.child(1).asFloat();
temp[11] = c3.child(2).asFloat();
temp[12] = c4.child(0).asFloat();
temp[13] = c4.child(1).asFloat();
temp[14] = c4.child(2).asFloat();
temp[15] = c5.child(0).asFloat();
temp[16] = c5.child(1).asFloat();
temp[17] = c5.child(2).asFloat();
temp[18] = c6.child(0).asFloat();
temp[19] = c6.child(1).asFloat();
temp[20] = c6.child(2).asFloat();
temp[21] = c7.child(0).asFloat();
temp[22] = c7.child(1).asFloat();
temp[23] = c7.child(2).asFloat();
float* optr = values + (i * 3);
storeu8f(optr, load8f(temp));
storeu8f(optr + 8, load8f(temp + 8));
storeu8f(optr + 16, load8f(temp + 16));
}
if(count & 0x4)
{
ALIGN32(float temp[12]);
const MPlug c0 = plug.elementByLogicalIndex(i );
const MPlug c1 = plug.elementByLogicalIndex(i + 1);
const MPlug c2 = plug.elementByLogicalIndex(i + 2);
const MPlug c3 = plug.elementByLogicalIndex(i + 3);
temp[ 0] = c0.child(0).asFloat();
temp[ 1] = c0.child(1).asFloat();
temp[ 2] = c0.child(2).asFloat();
temp[ 3] = c1.child(0).asFloat();
temp[ 4] = c1.child(1).asFloat();
temp[ 5] = c1.child(2).asFloat();
temp[ 6] = c2.child(0).asFloat();
temp[ 7] = c2.child(1).asFloat();
temp[ 8] = c2.child(2).asFloat();
temp[ 9] = c3.child(0).asFloat();
temp[10] = c3.child(1).asFloat();
temp[11] = c3.child(2).asFloat();
float* optr = values + (i * 3);
storeu8f(optr, load8f(temp));
storeu4f(optr + 8, load4f(temp + 8));
i += 4;
}
#else
uint32_t count4 = count & ~0x3;
uint32_t i = 0;
for(; i < count4; i += 4)
{
ALIGN16(float temp[12]);
const MPlug c0 = plug.elementByLogicalIndex(i );
const MPlug c1 = plug.elementByLogicalIndex(i + 1);
const MPlug c2 = plug.elementByLogicalIndex(i + 2);
const MPlug c3 = plug.elementByLogicalIndex(i + 3);
temp[ 0] = c0.child(0).asFloat();
temp[ 1] = c0.child(1).asFloat();
temp[ 2] = c0.child(2).asFloat();
temp[ 3] = c1.child(0).asFloat();
temp[ 4] = c1.child(1).asFloat();
temp[ 5] = c1.child(2).asFloat();
temp[ 6] = c2.child(0).asFloat();
temp[ 7] = c2.child(1).asFloat();
temp[ 8] = c2.child(2).asFloat();
temp[ 9] = c3.child(0).asFloat();
temp[10] = c3.child(1).asFloat();
temp[11] = c3.child(2).asFloat();
float* optr = values + (i * 3);
storeu4f(optr + 0, load4f(temp + 0));
storeu4f(optr + 4, load4f(temp + 4));
storeu4f(optr + 8, load4f(temp + 8));
}
#endif
float* optr = values + (i * 3);
MPlug elem;
switch(count & 3)
{
case 3: elem = plug.elementByLogicalIndex(i + 2);
optr[6] = elem.child(0).asFloat();
optr[7] = elem.child(1).asFloat();
optr[8] = elem.child(2).asFloat();
case 2: elem = plug.elementByLogicalIndex(i + 1);
optr[3] = elem.child(0).asFloat();
optr[4] = elem.child(1).asFloat();
optr[5] = elem.child(2).asFloat();
case 1: elem = plug.elementByLogicalIndex(i);
optr[0] = elem.child(0).asFloat();
optr[1] = elem.child(1).asFloat();
optr[2] = elem.child(2).asFloat();
default: break;
}
#else
for(uint32_t i = 0, j = 0; i < num; ++i, j += 3)
{
MPlug elem = plug.elementByLogicalIndex(i);
values[j ] = elem.child(0).asFloat();
values[j + 1] = elem.child(1).asFloat();
values[j + 2] = elem.child(2).asFloat();
}
#endif
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getVec3Array(MObject node, MObject attribute, double* const values, const size_t count)
{
MPlug plug(node, attribute);
if(!plug || !plug.isArray())
return MS::kFailure;
uint32_t num = plug.numElements();
if(num != count)
{
MGlobal::displayError("array is sized incorrectly");
return MS::kFailure;
}
#if AL_UTILS_ENABLE_SIMD
#ifdef __AVX__
uint32_t count4 = count & ~0x3;
uint32_t i = 0;
for(; i < count4; i += 4)
{
ALIGN32(double temp[12]);
const MPlug c0 = plug.elementByLogicalIndex(i );
const MPlug c1 = plug.elementByLogicalIndex(i + 1);
const MPlug c2 = plug.elementByLogicalIndex(i + 2);
const MPlug c3 = plug.elementByLogicalIndex(i + 3);
temp[ 0] = c0.child(0).asDouble();
temp[ 1] = c0.child(1).asDouble();
temp[ 2] = c0.child(2).asDouble();
temp[ 3] = c1.child(0).asDouble();
temp[ 4] = c1.child(1).asDouble();
temp[ 5] = c1.child(2).asDouble();
temp[ 6] = c2.child(0).asDouble();
temp[ 7] = c2.child(1).asDouble();
temp[ 8] = c2.child(2).asDouble();
temp[ 9] = c3.child(0).asDouble();
temp[10] = c3.child(1).asDouble();
temp[11] = c3.child(2).asDouble();
double* optr = values + (i * 3);
storeu4d(optr, load4d(temp));
storeu4d(optr + 4, load4d(temp + 4));
storeu4d(optr + 8, load4d(temp + 8));
}
if(count & 0x2)
{
ALIGN32(double temp[6]);
const MPlug c0 = plug.elementByLogicalIndex(i );
const MPlug c1 = plug.elementByLogicalIndex(i + 1);
temp[ 0] = c0.child(0).asDouble();
temp[ 1] = c0.child(1).asDouble();
temp[ 2] = c0.child(2).asDouble();
temp[ 3] = c1.child(0).asDouble();
temp[ 4] = c1.child(1).asDouble();
temp[ 5] = c1.child(2).asDouble();
double* optr = values + (i * 3);
storeu4d(optr, load4d(temp));
storeu2d(optr + 4, load2d(temp + 4));
i += 2;
}
#else
uint32_t count2 = count & ~0x1;
uint32_t i = 0;
for(; i < count2; i += 2)
{
ALIGN16(double temp[6]);
const MPlug c0 = plug.elementByLogicalIndex(i );
const MPlug c1 = plug.elementByLogicalIndex(i + 1);
temp[ 0] = c0.child(0).asDouble();
temp[ 1] = c0.child(1).asDouble();
temp[ 2] = c0.child(2).asDouble();
temp[ 3] = c1.child(0).asDouble();
temp[ 4] = c1.child(1).asDouble();
temp[ 5] = c1.child(2).asDouble();
double* optr = values + (i * 3);
storeu2d(optr + 0, load2d(temp + 0));
storeu2d(optr + 2, load2d(temp + 2));
storeu2d(optr + 4, load2d(temp + 4));
}
#endif
if(count & 1)
{
double* optr = values + (i * 3);
MPlug elem = plug.elementByLogicalIndex(i);
optr[0] = elem.child(0).asDouble();
optr[1] = elem.child(1).asDouble();
optr[2] = elem.child(2).asDouble();
}
#else
for(uint32_t i = 0, j = 0; i < num; ++i, j += 3)
{
MPlug elem = plug.elementByLogicalIndex(i);
values[j ] = elem.child(0).asFloat();
values[j + 1] = elem.child(1).asFloat();
values[j + 2] = elem.child(2).asFloat();
}
#endif
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getVec3Array(MObject node, MObject attribute, GfHalf* const values, const size_t count)
{
MPlug plug(node, attribute);
if(!plug || !plug.isArray())
return MS::kFailure;
uint32_t num = plug.numElements();
if(num != count)
{
MGlobal::displayError("array is sized incorrectly");
return MS::kFailure;
}
size_t count8 = count & ~0x7ULL;
for(uint32_t i = 0, j = 0; i < count8; i += 8, j += 24)
{
float r[24];
MPlug v0 = plug.elementByLogicalIndex(i + 0);
MPlug v1 = plug.elementByLogicalIndex(i + 1);
MPlug v2 = plug.elementByLogicalIndex(i + 2);
MPlug v3 = plug.elementByLogicalIndex(i + 3);
MPlug v4 = plug.elementByLogicalIndex(i + 4);
MPlug v5 = plug.elementByLogicalIndex(i + 5);
MPlug v6 = plug.elementByLogicalIndex(i + 6);
MPlug v7 = plug.elementByLogicalIndex(i + 7);
r[ 0] = v0.child(0).asFloat();
r[ 1] = v0.child(1).asFloat();
r[ 2] = v0.child(2).asFloat();
r[ 3] = v1.child(0).asFloat();
r[ 4] = v1.child(1).asFloat();
r[ 5] = v1.child(2).asFloat();
r[ 6] = v2.child(0).asFloat();
r[ 7] = v2.child(1).asFloat();
r[ 8] = v2.child(2).asFloat();
r[ 9] = v3.child(0).asFloat();
r[10] = v3.child(1).asFloat();
r[11] = v3.child(2).asFloat();
r[12] = v4.child(0).asFloat();
r[13] = v4.child(1).asFloat();
r[14] = v4.child(2).asFloat();
r[15] = v5.child(0).asFloat();
r[16] = v5.child(1).asFloat();
r[17] = v5.child(2).asFloat();
r[18] = v6.child(0).asFloat();
r[19] = v6.child(1).asFloat();
r[20] = v6.child(2).asFloat();
r[21] = v7.child(0).asFloat();
r[22] = v7.child(1).asFloat();
r[23] = v7.child(2).asFloat();
AL::usd::utils::float2half_8f(r, values + j);
AL::usd::utils::float2half_8f(r + 8, values + j + 8);
AL::usd::utils::float2half_8f(r + 16, values + j + 16);
}
for(uint32_t i = count8, j = count8 * 3; i < count; ++i, j += 3)
{
float v[4];
GfHalf h[4];
MPlug elem = plug.elementByLogicalIndex(i);
v[0] = elem.child(0).asFloat();
v[1] = elem.child(1).asFloat();
v[2] = elem.child(2).asFloat();
AL::usd::utils::float2half_4f(v, h);
values[j + 0] = h[0];
values[j + 1] = h[1];
values[j + 2] = h[2];
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getVec3Array(MObject node, MObject attribute, int32_t* const values, const size_t count)
{
MPlug plug(node, attribute);
if(!plug || !plug.isArray())
return MS::kFailure;
uint32_t num = plug.numElements();
if(num != count)
{
MGlobal::displayError("array is sized incorrectly");
return MS::kFailure;
}
#if AL_UTILS_ENABLE_SIMD
#ifdef __AVX__
uint32_t count8 = count & ~0x7;
uint32_t i = 0;
for(; i < count8; i += 8)
{
ALIGN32(int32_t temp[24]);
const MPlug c0 = plug.elementByLogicalIndex(i );
const MPlug c1 = plug.elementByLogicalIndex(i + 1);
const MPlug c2 = plug.elementByLogicalIndex(i + 2);
const MPlug c3 = plug.elementByLogicalIndex(i + 3);
const MPlug c4 = plug.elementByLogicalIndex(i + 4);
const MPlug c5 = plug.elementByLogicalIndex(i + 5);
const MPlug c6 = plug.elementByLogicalIndex(i + 6);
const MPlug c7 = plug.elementByLogicalIndex(i + 7);
temp[ 0] = c0.child(0).asInt();
temp[ 1] = c0.child(1).asInt();
temp[ 2] = c0.child(2).asInt();
temp[ 3] = c1.child(0).asInt();
temp[ 4] = c1.child(1).asInt();
temp[ 5] = c1.child(2).asInt();
temp[ 6] = c2.child(0).asInt();
temp[ 7] = c2.child(1).asInt();
temp[ 8] = c2.child(2).asInt();
temp[ 9] = c3.child(0).asInt();
temp[10] = c3.child(1).asInt();
temp[11] = c3.child(2).asInt();
temp[12] = c4.child(0).asInt();
temp[13] = c4.child(1).asInt();
temp[14] = c4.child(2).asInt();
temp[15] = c5.child(0).asInt();
temp[16] = c5.child(1).asInt();
temp[17] = c5.child(2).asInt();
temp[18] = c6.child(0).asInt();
temp[19] = c6.child(1).asInt();
temp[20] = c6.child(2).asInt();
temp[21] = c7.child(0).asInt();
temp[22] = c7.child(1).asInt();
temp[23] = c7.child(2).asInt();
int32_t* optr = values + (i * 3);
storeu8i(optr + 0, load8i(temp + 0));
storeu8i(optr + 8, load8i(temp + 8));
storeu8i(optr + 16, load8i(temp + 16));
}
if(count & 0x4)
{
ALIGN32(int32_t temp[12]);
const MPlug c0 = plug.elementByLogicalIndex(i );
const MPlug c1 = plug.elementByLogicalIndex(i + 1);
const MPlug c2 = plug.elementByLogicalIndex(i + 2);
const MPlug c3 = plug.elementByLogicalIndex(i + 3);
temp[ 0] = c0.child(0).asInt();
temp[ 1] = c0.child(1).asInt();
temp[ 2] = c0.child(2).asInt();
temp[ 3] = c1.child(0).asInt();
temp[ 4] = c1.child(1).asInt();
temp[ 5] = c1.child(2).asInt();
temp[ 6] = c2.child(0).asInt();
temp[ 7] = c2.child(1).asInt();
temp[ 8] = c2.child(2).asInt();
temp[ 9] = c3.child(0).asInt();
temp[10] = c3.child(1).asInt();
temp[11] = c3.child(2).asInt();
int32_t* optr = values + (i * 3);
storeu8i(optr + 0, load8i(temp + 0));
storeu4i(optr + 8, load4i(temp + 8));
i += 4;
}
#else
uint32_t count4 = count & ~0x3;
uint32_t i = 0;
for(; i < count4; i += 4)
{
ALIGN16(int32_t temp[12]);
const MPlug c0 = plug.elementByLogicalIndex(i );
const MPlug c1 = plug.elementByLogicalIndex(i + 1);
const MPlug c2 = plug.elementByLogicalIndex(i + 2);
const MPlug c3 = plug.elementByLogicalIndex(i + 3);
temp[ 0] = c0.child(0).asInt();
temp[ 1] = c0.child(1).asInt();
temp[ 2] = c0.child(2).asInt();
temp[ 3] = c1.child(0).asInt();
temp[ 4] = c1.child(1).asInt();
temp[ 5] = c1.child(2).asInt();
temp[ 6] = c2.child(0).asInt();
temp[ 7] = c2.child(1).asInt();
temp[ 8] = c2.child(2).asInt();
temp[ 9] = c3.child(0).asInt();
temp[10] = c3.child(1).asInt();
temp[11] = c3.child(2).asInt();
int32_t* optr = values + (i * 3);
storeu4i(optr + 0, load4i(temp + 0));
storeu4i(optr + 4, load4i(temp + 4));
storeu4i(optr + 8, load4i(temp + 8));
}
#endif
int32_t* optr = values + (i * 3);
MPlug elem;
switch(count & 3)
{
case 3: elem = plug.elementByLogicalIndex(i + 2);
optr[6] = elem.child(0).asInt();
optr[7] = elem.child(1).asInt();
optr[8] = elem.child(2).asInt();
case 2: elem = plug.elementByLogicalIndex(i + 1);
optr[3] = elem.child(0).asInt();
optr[4] = elem.child(1).asInt();
optr[5] = elem.child(2).asInt();
case 1: elem = plug.elementByLogicalIndex(i);
optr[0] = elem.child(0).asInt();
optr[1] = elem.child(1).asInt();
optr[2] = elem.child(2).asInt();
default: break;
}
#else
for(uint32_t i = 0, j = 0; i < num; ++i, j += 3)
{
MPlug elem = plug.elementByLogicalIndex(i);
values[j ] = elem.child(0).asInt();
values[j + 1] = elem.child(1).asInt();
values[j + 2] = elem.child(2).asInt();
}
#endif
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getVec4Array(MObject node, MObject attribute, int32_t* const values, const size_t count)
{
MPlug plug(node, attribute);
if(!plug || !plug.isArray())
return MS::kFailure;
uint32_t num = plug.numElements();
if(num != count)
{
MGlobal::displayError("array is sized incorrectly");
return MS::kFailure;
}
size_t count2 = count & ~1;
size_t i = 0, j = 0;
for(; i < count2; i += 2, j += 8)
{
ALIGN32(int32_t temp[8]);
MPlug elem0 = plug.elementByLogicalIndex(i);
MPlug elem1 = plug.elementByLogicalIndex(i + 1);
temp[0] = elem0.child(0).asInt();
temp[1] = elem0.child(1).asInt();
temp[2] = elem0.child(2).asInt();
temp[3] = elem0.child(3).asInt();
temp[4] = elem1.child(0).asInt();
temp[5] = elem1.child(1).asInt();
temp[6] = elem1.child(2).asInt();
temp[7] = elem1.child(3).asInt();
#if AL_UTILS_ENABLE_SIMD
# ifdef __AVX__
storeu8i(values + j, load8i(temp));
# else
storeu4i(values + j, load4i(temp));
storeu4i(values + j + 4, load4i(temp + 4));
# endif
#else
values[j + 0] = temp[0];
values[j + 1] = temp[1];
values[j + 2] = temp[2];
values[j + 3] = temp[3];
values[j + 4] = temp[4];
values[j + 5] = temp[5];
values[j + 6] = temp[6];
values[j + 7] = temp[7];
#endif
}
if(count & 1)
{
ALIGN16(int32_t temp[4]);
MPlug elem0 = plug.elementByLogicalIndex(i);
temp[0] = elem0.child(0).asInt();
temp[1] = elem0.child(1).asInt();
temp[2] = elem0.child(2).asInt();
temp[3] = elem0.child(3).asInt();
#if AL_UTILS_ENABLE_SIMD
storeu4i(values + j, load4i(temp));
#else
values[j + 0] = temp[0];
values[j + 1] = temp[1];
values[j + 2] = temp[2];
values[j + 3] = temp[3];
#endif
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getVec4Array(MObject node, MObject attribute, float* const values, const size_t count)
{
MPlug plug(node, attribute);
if(!plug || !plug.isArray())
return MS::kFailure;
uint32_t num = plug.numElements();
if(num != count)
{
MGlobal::displayError("array is sized incorrectly");
return MS::kFailure;
}
size_t count2 = count & ~1;
size_t i = 0, j = 0;
for(; i < count2; i += 2, j += 8)
{
ALIGN32(float temp[8]);
MPlug elem0 = plug.elementByLogicalIndex(i);
MPlug elem1 = plug.elementByLogicalIndex(i + 1);
temp[0] = elem0.child(0).asFloat();
temp[1] = elem0.child(1).asFloat();
temp[2] = elem0.child(2).asFloat();
temp[3] = elem0.child(3).asFloat();
temp[4] = elem1.child(0).asFloat();
temp[5] = elem1.child(1).asFloat();
temp[6] = elem1.child(2).asFloat();
temp[7] = elem1.child(3).asFloat();
#if AL_UTILS_ENABLE_SIMD
# ifdef __AVX__
storeu8f(values + j, load8f(temp));
# else
storeu4f(values + j, load4f(temp));
storeu4f(values + j + 4, load4f(temp + 4));
# endif
#else
values[j + 0] = temp[0];
values[j + 1] = temp[1];
values[j + 2] = temp[2];
values[j + 3] = temp[3];
values[j + 4] = temp[4];
values[j + 5] = temp[5];
values[j + 6] = temp[6];
values[j + 7] = temp[7];
#endif
}
if(count & 1)
{
ALIGN16(float temp[4]);
MPlug elem0 = plug.elementByLogicalIndex(i);
temp[0] = elem0.child(0).asFloat();
temp[1] = elem0.child(1).asFloat();
temp[2] = elem0.child(2).asFloat();
temp[3] = elem0.child(3).asFloat();
#if AL_UTILS_ENABLE_SIMD
storeu4f(values + j, load4f(temp));
#else
values[j + 0] = temp[0];
values[j + 1] = temp[1];
values[j + 2] = temp[2];
values[j + 3] = temp[3];
#endif
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getVec4Array(MObject node, MObject attribute, double* const values, const size_t count)
{
MPlug plug(node, attribute);
if(!plug || !plug.isArray())
return MS::kFailure;
uint32_t num = plug.numElements();
if(num != count)
{
MGlobal::displayError("array is sized incorrectly");
return MS::kFailure;
}
for(uint32_t i = 0, j = 0; i < num; ++i, j += 4)
{
ALIGN32(double temp[4]);
MPlug elem = plug.elementByLogicalIndex(i);
temp[0] = elem.child(0).asDouble();
temp[1] = elem.child(1).asDouble();
temp[2] = elem.child(2).asDouble();
temp[3] = elem.child(3).asDouble();
#if AL_UTILS_ENABLE_SIMD
# ifdef __AVX__
storeu4d(values + j, load4d(temp));
# else
storeu2d(values + j, load2d(temp));
storeu2d(values + j + 2, load2d(temp + 2));
# endif
#else
values[j + 0] = temp[0];
values[j + 1] = temp[1];
values[j + 2] = temp[2];
values[j + 3] = temp[3];
#endif
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getVec4Array(MObject node, MObject attribute, GfHalf* const values, const size_t count)
{
MPlug plug(node, attribute);
if(!plug || !plug.isArray())
return MS::kFailure;
uint32_t num = plug.numElements();
if(num != count)
{
MGlobal::displayError("array is sized incorrectly");
return MS::kFailure;
}
size_t count2 = count & ~0x1ULL;
for(uint32_t i = 0, j = 0; i < count2; i += 2, j += 8)
{
MPlug v0 = plug.elementByLogicalIndex(i + 0);
MPlug v1 = plug.elementByLogicalIndex(i + 1);
float f[8];
f[0] = v0.child(0).asFloat();
f[1] = v0.child(1).asFloat();
f[2] = v0.child(2).asFloat();
f[3] = v0.child(3).asFloat();
f[4] = v1.child(0).asFloat();
f[5] = v1.child(1).asFloat();
f[6] = v1.child(2).asFloat();
f[7] = v1.child(3).asFloat();
AL::usd::utils::float2half_8f(f, values + j);
}
if(count & 0x1)
{
MPlug v0 = plug.elementByLogicalIndex(count2);
float f[4];
f[0] = v0.child(0).asFloat();
f[1] = v0.child(1).asFloat();
f[2] = v0.child(2).asFloat();
f[3] = v0.child(3).asFloat();
AL::usd::utils::float2half_4f(f, values + count2 * 4);
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getQuatArray(MObject node, MObject attr, GfHalf* const values, const size_t count)
{
return getVec4Array(node, attr, values, count);
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getQuatArray(MObject node, MObject attr, float* const values, const size_t count)
{
return getVec4Array(node, attr, values, count);
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getQuatArray(MObject node, MObject attr, double* const values, const size_t count)
{
return getVec4Array(node, attr, values, count);
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getMatrix2x2Array(MObject node, MObject attribute, double* const values, const size_t count)
{
const char* const errorString = "getMatrix2x2Array error";
MPlug arrayPlug(node, attribute);
for(uint32_t i = 0; i < count; ++i)
{
double* const str = values + i * 4;
MPlug plug = arrayPlug.elementByLogicalIndex(i);
AL_MAYA_CHECK_ERROR(plug.child(0).child(0).getValue(str[0]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(0).child(1).getValue(str[1]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).child(0).getValue(str[2]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).child(1).getValue(str[3]), errorString);
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getMatrix2x2Array(MObject node, MObject attribute, float* const values, const size_t count)
{
const char* const errorString = "getMatrix2x2Array error";
MPlug arrayPlug(node, attribute);
for(uint32_t i = 0; i < count; ++i)
{
float* const str = values + i * 4;
MPlug plug = arrayPlug.elementByLogicalIndex(i);
AL_MAYA_CHECK_ERROR(plug.child(0).child(0).getValue(str[0]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(0).child(1).getValue(str[1]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).child(0).getValue(str[2]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).child(1).getValue(str[3]), errorString);
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getMatrix3x3Array(MObject node, MObject attribute, double* const values, const size_t count)
{
const char* const errorString = "getMatrix3x3Array error";
MPlug arrayPlug(node, attribute);
for(uint32_t i = 0; i < count; ++i)
{
double* const str = values + i * 9;
MPlug plug = arrayPlug.elementByLogicalIndex(i);
AL_MAYA_CHECK_ERROR(plug.child(0).child(0).getValue(str[0]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(0).child(1).getValue(str[1]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(0).child(2).getValue(str[2]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).child(0).getValue(str[3]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).child(1).getValue(str[4]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).child(2).getValue(str[5]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(2).child(0).getValue(str[6]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(2).child(1).getValue(str[7]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(2).child(2).getValue(str[8]), errorString);
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getMatrix3x3Array(MObject node, MObject attribute, float* const values, const size_t count)
{
const char* const errorString = "getMatrix3x3Array error";
MPlug arrayPlug(node, attribute);
for(uint32_t i = 0; i < count; ++i)
{
float* const str = values + i * 9;
MPlug plug = arrayPlug.elementByLogicalIndex(i);
AL_MAYA_CHECK_ERROR(plug.child(0).child(0).getValue(str[0]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(0).child(1).getValue(str[1]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(0).child(2).getValue(str[2]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).child(0).getValue(str[3]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).child(1).getValue(str[4]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).child(2).getValue(str[5]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(2).child(0).getValue(str[6]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(2).child(1).getValue(str[7]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(2).child(2).getValue(str[8]), errorString);
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getMatrix4x4Array(MObject node, MObject attribute, float* const values, const size_t count)
{
MPlug plug(node, attribute);
if(!plug)
return MS::kFailure;
if(plug.isArray())
{
uint32_t num = plug.numElements();
if(num != count)
{
MGlobal::displayError("array is sized incorrectly");
return MS::kFailure;
}
MFnMatrixData fn;
MObject elementValue;
for(uint32_t i = 0, j = 0; i < count; ++i, j += 16)
{
plug.elementByLogicalIndex(i).getValue(elementValue);
fn.setObject(elementValue);
const MMatrix& m = fn.matrix();
#if AL_UTILS_ENABLE_SIMD
# ifdef __AVX__
const f128 m0 = cvt4d_to_4f(loadu4d(&m.matrix[0][0]));
const f128 m1 = cvt4d_to_4f(loadu4d(&m.matrix[1][0]));
const f128 m2 = cvt4d_to_4f(loadu4d(&m.matrix[2][0]));
const f128 m3 = cvt4d_to_4f(loadu4d(&m.matrix[3][0]));
# else
const f128 m0a = cvt2d_to_2f(loadu2d(&m.matrix[0][0]));
const f128 m0b = cvt2d_to_2f(loadu2d(&m.matrix[0][2]));
const f128 m1a = cvt2d_to_2f(loadu2d(&m.matrix[1][0]));
const f128 m1b = cvt2d_to_2f(loadu2d(&m.matrix[1][2]));
const f128 m2a = cvt2d_to_2f(loadu2d(&m.matrix[2][0]));
const f128 m2b = cvt2d_to_2f(loadu2d(&m.matrix[2][2]));
const f128 m3a = cvt2d_to_2f(loadu2d(&m.matrix[3][0]));
const f128 m3b = cvt2d_to_2f(loadu2d(&m.matrix[3][2]));
const f128 m0 = movelh4f(m0a, m0b);
const f128 m1 = movelh4f(m1a, m1b);
const f128 m2 = movelh4f(m2a, m2b);
const f128 m3 = movelh4f(m3a, m3b);
# endif
float* optr = values + j;
storeu4f(optr, m0);
storeu4f(optr + 4, m1);
storeu4f(optr + 8, m2);
storeu4f(optr + 12, m3);
#else
float* optr = values + j;
optr[0] = m.matrix[0][0];
optr[1] = m.matrix[0][1];
optr[2] = m.matrix[0][2];
optr[3] = m.matrix[0][3];
optr[4] = m.matrix[1][0];
optr[5] = m.matrix[1][1];
optr[6] = m.matrix[1][2];
optr[7] = m.matrix[1][3];
optr[8] = m.matrix[2][0];
optr[9] = m.matrix[2][1];
optr[10] = m.matrix[2][2];
optr[11] = m.matrix[2][3];
optr[12] = m.matrix[3][0];
optr[13] = m.matrix[3][1];
optr[14] = m.matrix[3][2];
optr[15] = m.matrix[3][3];
#endif
}
}
else
{
MObject value;
plug.getValue(value);
MFnMatrixArrayData fn(value);
for(uint32_t i = 0, n = fn.length(); i < n; ++i)
{
float* optr = values + i * 16;
double* iptr = &fn[i].matrix[0][0];
#if AL_UTILS_ENABLE_SIMD
# ifdef __AVX__
const f128 m0 = cvt4d_to_4f(loadu4d(iptr));
const f128 m1 = cvt4d_to_4f(loadu4d(iptr + 4));
const f128 m2 = cvt4d_to_4f(loadu4d(iptr + 8));
const f128 m3 = cvt4d_to_4f(loadu4d(iptr + 12));
# else
const f128 m0a = cvt2d_to_2f(loadu2d(iptr));
const f128 m0b = cvt2d_to_2f(loadu2d(iptr + 2));
const f128 m1a = cvt2d_to_2f(loadu2d(iptr + 4));
const f128 m1b = cvt2d_to_2f(loadu2d(iptr + 6));
const f128 m2a = cvt2d_to_2f(loadu2d(iptr + 8));
const f128 m2b = cvt2d_to_2f(loadu2d(iptr + 10));
const f128 m3a = cvt2d_to_2f(loadu2d(iptr + 12));
const f128 m3b = cvt2d_to_2f(loadu2d(iptr + 14));
const f128 m0 = movelh4f(m0a, m0b);
const f128 m1 = movelh4f(m1a, m1b);
const f128 m2 = movelh4f(m2a, m2b);
const f128 m3 = movelh4f(m3a, m3b);
# endif
storeu4f(optr, m0);
storeu4f(optr + 4, m1);
storeu4f(optr + 8, m2);
storeu4f(optr + 12, m3);
#else
for(int k = 0; k < 16; ++k)
{
optr[k] = iptr[k];
}
#endif
}
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getMatrix4x4Array(MObject node, MObject attribute, double* const values, const size_t count)
{
MPlug plug(node, attribute);
if(!plug)
return MS::kFailure;
if(plug.isArray())
{
uint32_t num = plug.numElements();
if(num != count)
{
MGlobal::displayError("array is sized incorrectly");
return MS::kFailure;
}
MFnMatrixData fn;
MObject elementValue;
for(uint32_t i = 0, j = 0; i < count; ++i, j += 16)
{
plug.elementByLogicalIndex(i).getValue(elementValue);
fn.setObject(elementValue);
const MMatrix& m = fn.matrix();
#if AL_UTILS_ENABLE_SIMD
# ifdef __AVX__
double* optr = values + j;
storeu4d(optr + 0, loadu4d(&m.matrix[0][0]));
storeu4d(optr + 4, loadu4d(&m.matrix[1][0]));
storeu4d(optr + 8, loadu4d(&m.matrix[2][0]));
storeu4d(optr + 12, loadu4d(&m.matrix[3][0]));
# else
double* optr = values + j;
storeu2d(optr + 0, loadu2d(&m.matrix[0][0]));
storeu2d(optr + 2, loadu2d(&m.matrix[0][2]));
storeu2d(optr + 4, loadu2d(&m.matrix[1][0]));
storeu2d(optr + 6, loadu2d(&m.matrix[1][2]));
storeu2d(optr + 8, loadu2d(&m.matrix[2][0]));
storeu2d(optr + 10, loadu2d(&m.matrix[2][2]));
storeu2d(optr + 12, loadu2d(&m.matrix[3][0]));
storeu2d(optr + 14, loadu2d(&m.matrix[3][2]));
# endif
#else
double* optr = values + j;
optr[0] = m.matrix[0][0];
optr[1] = m.matrix[0][1];
optr[2] = m.matrix[0][2];
optr[3] = m.matrix[0][3];
optr[4] = m.matrix[1][0];
optr[5] = m.matrix[1][1];
optr[6] = m.matrix[1][2];
optr[7] = m.matrix[1][3];
optr[8] = m.matrix[2][0];
optr[9] = m.matrix[2][1];
optr[10] = m.matrix[2][2];
optr[11] = m.matrix[2][3];
optr[12] = m.matrix[3][0];
optr[13] = m.matrix[3][1];
optr[14] = m.matrix[3][2];
optr[15] = m.matrix[3][3];
#endif
}
}
else
{
MObject value;
plug.getValue(value);
MFnMatrixArrayData fn(value);
for(uint32_t i = 0, n = fn.length(); i < n; ++i)
{
double* optr = values + i * 16;
double* iptr = &fn[i].matrix[0][0];
#if AL_UTILS_ENABLE_SIMD
# ifdef __AVX__
storeu4d(optr, loadu4d(iptr));
storeu4d(optr + 4, loadu4d(iptr + 4));
storeu4d(optr + 8, loadu4d(iptr + 8));
storeu4d(optr + 12, loadu4d(iptr + 12));
# else
storeu2d(optr , loadu2d(iptr));
storeu2d(optr + 2, loadu2d(iptr + 2));
storeu2d(optr + 4, loadu2d(iptr + 4));
storeu2d(optr + 6, loadu2d(iptr + 6));
storeu2d(optr + 8, loadu2d(iptr + 8));
storeu2d(optr + 10, loadu2d(iptr + 10));
storeu2d(optr + 12, loadu2d(iptr + 12));
storeu2d(optr + 14, loadu2d(iptr + 14));
# endif
#else
for(uint32_t k = 0; k < 16; ++k)
{
optr[k] = iptr[k];
}
#endif
}
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getTimeArray(MObject node, MObject attribute, float* const values, const size_t count, MTime::Unit unit)
{
const MTime mod(1.0, MTime::k6000FPS);
const float unitConversion = float(mod.as(unit));
MPlug plug(node, attribute);
if(!plug || !plug.isArray())
return MS::kFailure;
uint32_t num = plug.numElements();
if(num != count)
{
MGlobal::displayError("array is sized incorrectly");
return MS::kFailure;
}
#if AL_UTILS_ENABLE_SIMD
#if defined(__AVX__) && ENABLE_SOME_AVX_ROUTINES
const f256 unitConversion256 = splat8f(unitConversion);
const f128 unitConversion128 = splat4f(unitConversion);
uint32_t count8 = count & ~0x7;
uint32_t i = 0;
for(; i < count8; i += 8)
{
ALIGN32(float temp[8]);
temp[0] = plug.elementByLogicalIndex(i).asFloat();
temp[1] = plug.elementByLogicalIndex(i + 1).asFloat();
temp[2] = plug.elementByLogicalIndex(i + 2).asFloat();
temp[3] = plug.elementByLogicalIndex(i + 3).asFloat();
temp[4] = plug.elementByLogicalIndex(i + 4).asFloat();
temp[5] = plug.elementByLogicalIndex(i + 5).asFloat();
temp[6] = plug.elementByLogicalIndex(i + 6).asFloat();
temp[7] = plug.elementByLogicalIndex(i + 7).asFloat();
storeu8f(values + i, mul8f(unitConversion256, load8f(temp)));
}
if(count & 0x4)
{
ALIGN16(float temp[4]);
temp[0] = plug.elementByLogicalIndex(i).asFloat();
temp[1] = plug.elementByLogicalIndex(i + 1).asFloat();
temp[2] = plug.elementByLogicalIndex(i + 2).asFloat();
temp[3] = plug.elementByLogicalIndex(i + 3).asFloat();
storeu4f(values + i, mul4f(unitConversion128, load4f(temp)));
i += 4;
}
#else
const f128 unitConversion128 = splat4f(unitConversion);
uint32_t count4 = count & ~0x3;
uint32_t i = 0;
for(; i < count4; i += 4)
{
ALIGN16(float temp[4]);
temp[0] = plug.elementByLogicalIndex(i).asFloat();
temp[1] = plug.elementByLogicalIndex(i + 1).asFloat();
temp[2] = plug.elementByLogicalIndex(i + 2).asFloat();
temp[3] = plug.elementByLogicalIndex(i + 3).asFloat();
storeu4f(values + i, mul4f(unitConversion128, load4f(temp)));
}
#endif
switch(count & 3)
{
case 3: values[i + 2] = unitConversion * plug.elementByLogicalIndex(i + 2).asFloat();
case 2: values[i + 1] = unitConversion * plug.elementByLogicalIndex(i + 1).asFloat();
case 1: values[i ] = unitConversion * plug.elementByLogicalIndex(i ).asFloat();
default: break;
}
#else
for(uint32_t i = 0; i < num; ++i)
{
values[i] = unitConversion * plug.elementByLogicalIndex(i).asFloat();
}
#endif
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getAngleArray(MObject node, MObject attribute, float* const values, const size_t count, MAngle::Unit unit)
{
const MAngle mod(1.0, MAngle::internalUnit());
const float unitConversion = float(mod.as(unit));
MPlug plug(node, attribute);
if(!plug || !plug.isArray())
return MS::kFailure;
uint32_t num = plug.numElements();
if(num != count)
{
MGlobal::displayError("array is sized incorrectly");
return MS::kFailure;
}
#if AL_UTILS_ENABLE_SIMD
#if defined(__AVX__) && ENABLE_SOME_AVX_ROUTINES
const f256 unitConversion256 = splat8f(unitConversion);
const f128 unitConversion128 = splat4f(unitConversion);
uint32_t count8 = count & ~0x7;
uint32_t i = 0;
for(; i < count8; i += 8)
{
ALIGN32(float temp[8]);
temp[0] = plug.elementByLogicalIndex(i).asFloat();
temp[1] = plug.elementByLogicalIndex(i + 1).asFloat();
temp[2] = plug.elementByLogicalIndex(i + 2).asFloat();
temp[3] = plug.elementByLogicalIndex(i + 3).asFloat();
temp[4] = plug.elementByLogicalIndex(i + 4).asFloat();
temp[5] = plug.elementByLogicalIndex(i + 5).asFloat();
temp[6] = plug.elementByLogicalIndex(i + 6).asFloat();
temp[7] = plug.elementByLogicalIndex(i + 7).asFloat();
storeu8f(values + i, mul8f(unitConversion256, load8f(temp)));
}
if(count & 0x4)
{
ALIGN16(float temp[4]);
temp[0] = plug.elementByLogicalIndex(i).asFloat();
temp[1] = plug.elementByLogicalIndex(i + 1).asFloat();
temp[2] = plug.elementByLogicalIndex(i + 2).asFloat();
temp[3] = plug.elementByLogicalIndex(i + 3).asFloat();
storeu4f(values + i, mul4f(unitConversion128, load4f(temp)));
i += 4;
}
#else
const f128 unitConversion128 = splat4f(unitConversion);
uint32_t count4 = count & ~0x3;
uint32_t i = 0;
for(; i < count4; i += 4)
{
ALIGN16(float temp[4]);
temp[0] = plug.elementByLogicalIndex(i).asFloat();
temp[1] = plug.elementByLogicalIndex(i + 1).asFloat();
temp[2] = plug.elementByLogicalIndex(i + 2).asFloat();
temp[3] = plug.elementByLogicalIndex(i + 3).asFloat();
storeu4f(values + i, mul4f(unitConversion128, load4f(temp)));
}
#endif
switch(count & 3)
{
case 3: values[i + 2] = unitConversion * plug.elementByLogicalIndex(i + 2).asFloat();
case 2: values[i + 1] = unitConversion * plug.elementByLogicalIndex(i + 1).asFloat();
case 1: values[i] = unitConversion * plug.elementByLogicalIndex(i).asFloat();
default: break;
}
#else
for(uint32_t i = 0; i < num; ++i)
{
values[i] = unitConversion * plug.elementByLogicalIndex(i).asFloat();
}
#endif
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getDistanceArray(MObject node, MObject attribute, float* const values, const size_t count, MDistance::Unit unit)
{
const MDistance mod(1.0, MDistance::internalUnit());
const float unitConversion = float(mod.as(unit));
MPlug plug(node, attribute);
if(!plug || !plug.isArray())
return MS::kFailure;
uint32_t num = plug.numElements();
if(num != count)
{
MGlobal::displayError("array is sized incorrectly");
return MS::kFailure;
}
#if AL_UTILS_ENABLE_SIMD
#if defined(__AVX__) && ENABLE_SOME_AVX_ROUTINES
const f256 unitConversion256 = splat8f(unitConversion);
const f128 unitConversion128 = splat4f(unitConversion);
uint32_t count8 = count & ~0x7;
uint32_t i = 0;
for(; i < count8; i += 8)
{
ALIGN32(float temp[8]);
temp[0] = plug.elementByLogicalIndex(i).asFloat();
temp[1] = plug.elementByLogicalIndex(i + 1).asFloat();
temp[2] = plug.elementByLogicalIndex(i + 2).asFloat();
temp[3] = plug.elementByLogicalIndex(i + 3).asFloat();
temp[4] = plug.elementByLogicalIndex(i + 4).asFloat();
temp[5] = plug.elementByLogicalIndex(i + 5).asFloat();
temp[6] = plug.elementByLogicalIndex(i + 6).asFloat();
temp[7] = plug.elementByLogicalIndex(i + 7).asFloat();
storeu8f(values + i, mul8f(unitConversion256, load8f(temp)));
}
if(count & 0x4)
{
ALIGN16(float temp[4]);
temp[0] = plug.elementByLogicalIndex(i).asFloat();
temp[1] = plug.elementByLogicalIndex(i + 1).asFloat();
temp[2] = plug.elementByLogicalIndex(i + 2).asFloat();
temp[3] = plug.elementByLogicalIndex(i + 3).asFloat();
storeu4f(values + i, mul4f(unitConversion128, load4f(temp)));
i += 4;
}
#else
const f128 unitConversion128 = splat4f(unitConversion);
uint32_t count4 = count & ~0x3;
uint32_t i = 0;
for(; i < count4; i += 4)
{
ALIGN16(float temp[4]);
temp[0] = plug.elementByLogicalIndex(i).asFloat();
temp[1] = plug.elementByLogicalIndex(i + 1).asFloat();
temp[2] = plug.elementByLogicalIndex(i + 2).asFloat();
temp[3] = plug.elementByLogicalIndex(i + 3).asFloat();
storeu4f(values + i, mul4f(unitConversion128, load4f(temp)));
}
#endif
switch(count & 3)
{
case 3: values[i + 2] = unitConversion * plug.elementByLogicalIndex(i + 2).asFloat();
case 2: values[i + 1] = unitConversion * plug.elementByLogicalIndex(i + 1).asFloat();
case 1: values[i] = unitConversion * plug.elementByLogicalIndex(i).asFloat();
default: break;
}
#else
for(uint32_t i = 0; i < num; ++i)
{
values[i] = unitConversion * plug.elementByLogicalIndex(i).asFloat();
}
#endif
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setString(MObject node, MObject attr, const std::string& str)
{
return setString(node, attr, str.c_str());
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setVec2(MObject node, MObject attr, const int* const xy)
{
const char* const errorString = "vec2i error";
MPlug plug(node, attr);
AL_MAYA_CHECK_ERROR(plug.child(0).setValue(xy[0]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).setValue(xy[1]), errorString);
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setVec2(MObject node, MObject attr, const float* const xy)
{
const char* const errorString = "vec2f error";
MPlug plug(node, attr);
AL_MAYA_CHECK_ERROR(plug.child(0).setValue(xy[0]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).setValue(xy[1]), errorString);
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setVec2(MObject node, MObject attr, const GfHalf* const xy)
{
const char* const errorString = "vec2h error";
MPlug plug(node, attr);
AL_MAYA_CHECK_ERROR(plug.child(0).setValue(AL::usd::utils::float2half_1f(xy[0])), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).setValue(AL::usd::utils::float2half_1f(xy[1])), errorString);
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setVec2(MObject node, MObject attr, const double* const xy)
{
const char* const errorString = "vec2d error";
MPlug plug(node, attr);
AL_MAYA_CHECK_ERROR(plug.child(0).setValue(xy[0]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).setValue(xy[1]), errorString);
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setVec3(MObject node, MObject attr, const int* const xyz)
{
const char* const errorString = "vec3i error";
MPlug plug(node, attr);
AL_MAYA_CHECK_ERROR(plug.child(0).setValue(xyz[0]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).setValue(xyz[1]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(2).setValue(xyz[2]), errorString);
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setVec3(MObject node, MObject attr, const float* const xyz)
{
const char* const errorString = "vec3f error";
MPlug plug(node, attr);
AL_MAYA_CHECK_ERROR(plug.child(0).setValue(xyz[0]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).setValue(xyz[1]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(2).setValue(xyz[2]), errorString);
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setVec3(MObject node, MObject attr, const GfHalf* const xyz)
{
const char* const errorString = "vec3h error";
MPlug plug(node, attr);
AL_MAYA_CHECK_ERROR(plug.child(0).setValue(AL::usd::utils::float2half_1f(xyz[0])), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).setValue(AL::usd::utils::float2half_1f(xyz[1])), errorString);
AL_MAYA_CHECK_ERROR(plug.child(2).setValue(AL::usd::utils::float2half_1f(xyz[2])), errorString);
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setVec3(MObject node, MObject attr, const double* const xyz)
{
const char* const errorString = "vec3d error";
MPlug plug(node, attr);
AL_MAYA_CHECK_ERROR(plug.child(0).setValue(xyz[0]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).setValue(xyz[1]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(2).setValue(xyz[2]), errorString);
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setVec4(MObject node, MObject attr, const int* const xyzw)
{
const char* const errorString = "vec4i error";
MPlug plug(node, attr);
AL_MAYA_CHECK_ERROR(plug.child(0).setValue(xyzw[0]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).setValue(xyzw[1]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(2).setValue(xyzw[2]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(3).setValue(xyzw[3]), errorString);
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setVec4(MObject node, MObject attr, const float* const xyzw)
{
const char* const errorString = "vec4f error";
MPlug plug(node, attr);
AL_MAYA_CHECK_ERROR(plug.child(0).setValue(xyzw[0]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).setValue(xyzw[1]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(2).setValue(xyzw[2]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(3).setValue(xyzw[3]), errorString);
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setVec4(MObject node, MObject attr, const double* const xyzw)
{
const char* const errorString = "vec4d error";
MPlug plug(node, attr);
AL_MAYA_CHECK_ERROR(plug.child(0).setValue(xyzw[0]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).setValue(xyzw[1]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(2).setValue(xyzw[2]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(3).setValue(xyzw[3]), errorString);
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setVec4(MObject node, MObject attr, const GfHalf* const xyzw)
{
const char* const errorString = "vec4h error";
MPlug plug(node, attr);
AL_MAYA_CHECK_ERROR(plug.child(0).setValue(AL::usd::utils::float2half_1f(xyzw[0])), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).setValue(AL::usd::utils::float2half_1f(xyzw[1])), errorString);
AL_MAYA_CHECK_ERROR(plug.child(2).setValue(AL::usd::utils::float2half_1f(xyzw[2])), errorString);
AL_MAYA_CHECK_ERROR(plug.child(3).setValue(AL::usd::utils::float2half_1f(xyzw[3])), errorString);
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setQuat(MObject node, MObject attr, const float* const xyzw)
{
const char* const errorString = "quatf error";
MPlug plug(node, attr);
AL_MAYA_CHECK_ERROR(plug.child(0).setValue(xyzw[0]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).setValue(xyzw[1]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(2).setValue(xyzw[2]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(3).setValue(xyzw[3]), errorString);
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setQuat(MObject node, MObject attr, const double* const xyzw)
{
const char* const errorString = "quatd error";
MPlug plug(node, attr);
AL_MAYA_CHECK_ERROR(plug.child(0).setValue(xyzw[0]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).setValue(xyzw[1]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(2).setValue(xyzw[2]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(3).setValue(xyzw[3]), errorString);
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setQuat(MObject node, MObject attr, const GfHalf* const xyzw)
{
const char* const errorString = "quath error";
MPlug plug(node, attr);
AL_MAYA_CHECK_ERROR(plug.child(0).setValue(AL::usd::utils::float2half_1f(xyzw[0])), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).setValue(AL::usd::utils::float2half_1f(xyzw[1])), errorString);
AL_MAYA_CHECK_ERROR(plug.child(2).setValue(AL::usd::utils::float2half_1f(xyzw[2])), errorString);
AL_MAYA_CHECK_ERROR(plug.child(3).setValue(AL::usd::utils::float2half_1f(xyzw[3])), errorString);
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setString(MObject node, MObject attr, const char* const str)
{
const char* const errorString = "string error";
MPlug plug(node, attr);
AL_MAYA_CHECK_ERROR(plug.setString(str), errorString);
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setMatrix4x4(MObject node, MObject attr, const double* const str)
{
const char* const errorString = "matrix4x4 error - unimplemented";
MPlug plug(node, attr);
MFnMatrixData fn;
typedef double hack[4];
MObject data = fn.create(MMatrix((const hack*)str));
AL_MAYA_CHECK_ERROR(plug.setValue(data), errorString);
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setMatrix4x4(MObject node, MObject attr, const float* const ptr)
{
const char* const errorString = "matrix4x4 error - unimplemented";
MPlug plug(node, attr);
MFnMatrixData fn;
MMatrix m;
#if AL_UTILS_ENABLE_SIMD
# if __AVX__
const f256 d0 = loadu8f(ptr);
const f256 d1 = loadu8f(ptr + 8);
storeu4d(&m.matrix[0][0], cvt4f_to_4d(extract4f(d0, 0)));
storeu4d(&m.matrix[1][0], cvt4f_to_4d(extract4f(d0, 1)));
storeu4d(&m.matrix[2][0], cvt4f_to_4d(extract4f(d1, 0)));
storeu4d(&m.matrix[3][0], cvt4f_to_4d(extract4f(d1, 1)));
# else
const f128 d0 = loadu4f(ptr);
const f128 d1 = loadu4f(ptr + 4);
const f128 d2 = loadu4f(ptr + 8);
const f128 d3 = loadu4f(ptr + 12);
storeu2d(&m.matrix[0][0], cvt2f_to_2d(d0));
storeu2d(&m.matrix[0][2], cvt2f_to_2d(movehl4f(d0, d0)));
storeu2d(&m.matrix[1][0], cvt2f_to_2d(d1));
storeu2d(&m.matrix[1][2], cvt2f_to_2d(movehl4f(d1, d1)));
storeu2d(&m.matrix[2][0], cvt2f_to_2d(d2));
storeu2d(&m.matrix[2][2], cvt2f_to_2d(movehl4f(d2, d2)));
storeu2d(&m.matrix[3][0], cvt2f_to_2d(d3));
storeu2d(&m.matrix[3][2], cvt2f_to_2d(movehl4f(d3, d3)));
# endif
#else
m[0][0] = ptr[0]; m[0][1] = ptr[1]; m[0][2] = ptr[2]; m[0][3] = ptr[3];
m[1][0] = ptr[4]; m[1][1] = ptr[5]; m[1][2] = ptr[6]; m[1][3] = ptr[7];
m[2][0] = ptr[8]; m[2][1] = ptr[9]; m[2][2] = ptr[10]; m[2][3] = ptr[11];
m[3][0] = ptr[12]; m[3][1] = ptr[13]; m[3][2] = ptr[14]; m[3][3] = ptr[15];
#endif
MObject data = fn.create(m);
AL_MAYA_CHECK_ERROR(plug.setValue(data), errorString);
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setMatrix3x3(MObject node, MObject attr, const double* const str)
{
const char* const errorString = "matrix3x3 error";
MPlug plug(node, attr);
AL_MAYA_CHECK_ERROR(plug.child(0).child(0).setValue(str[0]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(0).child(1).setValue(str[1]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(0).child(2).setValue(str[2]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).child(0).setValue(str[3]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).child(1).setValue(str[4]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).child(2).setValue(str[5]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(2).child(0).setValue(str[6]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(2).child(1).setValue(str[7]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(2).child(2).setValue(str[8]), errorString);
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setMatrix3x3(MObject node, MObject attr, const float* const str)
{
const char* const errorString = "matrix3x3 error";
MPlug plug(node, attr);
AL_MAYA_CHECK_ERROR(plug.child(0).child(0).setValue(str[0]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(0).child(1).setValue(str[1]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(0).child(2).setValue(str[2]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).child(0).setValue(str[3]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).child(1).setValue(str[4]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).child(2).setValue(str[5]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(2).child(0).setValue(str[6]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(2).child(1).setValue(str[7]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(2).child(2).setValue(str[8]), errorString);
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setMatrix2x2(MObject node, MObject attr, const double* const str)
{
const char* const errorString = "matrix2x2 error";
MPlug plug(node, attr);
AL_MAYA_CHECK_ERROR(plug.child(0).child(0).setValue(str[0]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(0).child(1).setValue(str[1]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).child(0).setValue(str[2]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).child(1).setValue(str[3]), errorString);
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setMatrix2x2(MObject node, MObject attr, const float* const str)
{
const char* const errorString = "matrix2x2 error";
MPlug plug(node, attr);
AL_MAYA_CHECK_ERROR(plug.child(0).child(0).setValue(str[0]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(0).child(1).setValue(str[1]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).child(0).setValue(str[2]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).child(1).setValue(str[3]), errorString);
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setMatrix2x2Array(MObject node, MObject attribute, const double* const values, const size_t count)
{
const char* const errorString = "setMatrix2x2Array error";
MPlug arrayPlug(node, attribute);
arrayPlug.setNumElements(count);
for(uint32_t i = 0; i < count; ++i)
{
const double* const str = values + i * 4;
MPlug plug = arrayPlug.elementByLogicalIndex(i);
AL_MAYA_CHECK_ERROR(plug.child(0).child(0).setValue(str[0]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(0).child(1).setValue(str[1]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).child(0).setValue(str[2]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).child(1).setValue(str[3]), errorString);
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setMatrix2x2Array(MObject node, MObject attribute, const float* const values, const size_t count)
{
const char* const errorString = "setMatrix2x2Array error";
MPlug arrayPlug(node, attribute);
arrayPlug.setNumElements(count);
for(uint32_t i = 0; i < count; ++i)
{
const float* const str = values + i * 4;
MPlug plug = arrayPlug.elementByLogicalIndex(i);
AL_MAYA_CHECK_ERROR(plug.child(0).child(0).setValue(str[0]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(0).child(1).setValue(str[1]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).child(0).setValue(str[2]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).child(1).setValue(str[3]), errorString);
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setMatrix3x3Array(MObject node, MObject attribute, const double* const values, const size_t count)
{
const char* const errorString = "setMatrix3x3Array error";
MPlug arrayPlug(node, attribute);
arrayPlug.setNumElements(count);
for(uint32_t i = 0; i < count; ++i)
{
const double* const str = values + i * 9;
MPlug plug = arrayPlug.elementByLogicalIndex(i);
AL_MAYA_CHECK_ERROR(plug.child(0).child(0).setValue(str[0]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(0).child(1).setValue(str[1]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(0).child(2).setValue(str[2]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).child(0).setValue(str[3]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).child(1).setValue(str[4]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).child(2).setValue(str[5]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(2).child(0).setValue(str[6]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(2).child(1).setValue(str[7]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(2).child(2).setValue(str[8]), errorString);
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setMatrix3x3Array(MObject node, MObject attribute, const float* const values, const size_t count)
{
const char* const errorString = "setMatrix3x3Array error";
MPlug arrayPlug(node, attribute);
arrayPlug.setNumElements(count);
for(uint32_t i = 0; i < count; ++i)
{
const float* const str = values + i * 9;
MPlug plug = arrayPlug.elementByLogicalIndex(i);
AL_MAYA_CHECK_ERROR(plug.child(0).child(0).setValue(str[0]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(0).child(1).setValue(str[1]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(0).child(2).setValue(str[2]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).child(0).setValue(str[3]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).child(1).setValue(str[4]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).child(2).setValue(str[5]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(2).child(0).setValue(str[6]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(2).child(1).setValue(str[7]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(2).child(2).setValue(str[8]), errorString);
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setStringArray(MObject node, MObject attribute, const std::string* const values, const size_t count)
{
const char* const errorString = "DgNodeHelper::setStringArray error";
MPlug plug(node, attribute);
if(!plug)
{
MGlobal::displayError(errorString);
return MS::kFailure;
}
plug.setNumElements(count);
for(uint32_t i = 0; i < count; ++i)
{
MPlug elem = plug.elementByLogicalIndex(i);
elem.setString(MString(values[i].c_str(), values[i].size()));
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setQuatArray(MObject node, MObject attr, const GfHalf* const values, const size_t count)
{
return setVec4Array(node, attr, values, count);
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setQuatArray(MObject node, MObject attr, const float* const values, const size_t count)
{
return setVec4Array(node, attr, values, count);
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setQuatArray(MObject node, MObject attr, const double* const values, const size_t count)
{
return setVec4Array(node, attr, values, count);
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getFloat(MObject node, MObject attr, float& value)
{
const char* const errorString = "DgNodeHelper::getFloat error";
MPlug plug(node, attr);
if(!plug)
{
MGlobal::displayError(errorString);
return MS::kFailure;
}
return plug.getValue(value);
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getDouble(MObject node, MObject attr, double& value)
{
const char* const errorString = "DgNodeHelper::getDouble error";
MPlug plug(node, attr);
if(!plug)
{
MGlobal::displayError(errorString);
return MS::kFailure;
}
return plug.getValue(value);
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getTime(MObject node, MObject attr, MTime& value)
{
const char* const errorString = "DgNodeHelper::getTime error";
MPlug plug(node, attr);
if(!plug)
{
MGlobal::displayError(errorString);
return MS::kFailure;
}
return plug.getValue(value);
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getDistance(MObject node, MObject attr, MDistance& value)
{
const char* const errorString = "DgNodeHelper::getDistance error";
MPlug plug(node, attr);
if(!plug)
{
MGlobal::displayError(errorString);
return MS::kFailure;
}
return plug.getValue(value);
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getAngle(MObject node, MObject attr, MAngle& value)
{
const char* const errorString = "DgNodeHelper::getAngle error";
MPlug plug(node, attr);
if(!plug)
{
MGlobal::displayError(errorString);
return MS::kFailure;
}
return plug.getValue(value);
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getBool(MObject node, MObject attr, bool& value)
{
const char* const errorString = "DgNodeHelper::getBool error";
MPlug plug(node, attr);
if(!plug)
{
MGlobal::displayError(errorString);
return MS::kFailure;
}
return plug.getValue(value);
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getInt8(MObject node, MObject attr, int8_t& value)
{
const char* const errorString = "DgNodeHelper::getInt32 error";
MPlug plug(node, attr);
if(!plug)
{
MGlobal::displayError(errorString);
return MS::kFailure;
}
char c;
MStatus status = plug.getValue(c);
value = c;
return status;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getInt16(MObject node, MObject attr, int16_t& value)
{
const char* const errorString = "DgNodeHelper::getInt32 error";
MPlug plug(node, attr);
if(!plug)
{
MGlobal::displayError(errorString);
return MS::kFailure;
}
return plug.getValue(value);
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getInt32(MObject node, MObject attr, int32_t& value)
{
const char* const errorString = "DgNodeHelper::getInt32 error";
MPlug plug(node, attr);
if(!plug)
{
MGlobal::displayError(errorString);
return MS::kFailure;
}
return plug.getValue(value);
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getInt64(MObject node, MObject attr, int64_t& value)
{
const char* const errorString = "DgNodeHelper::getInt32 error";
MPlug plug(node, attr);
if(!plug)
{
MGlobal::displayError(errorString);
return MS::kFailure;
}
MStatus status;
#if MAYA_API_VERSION >= 201800
value = plug.asInt64(&status);
#else
value = plug.asInt64(MDGContext::fsNormal, &status);
#endif
return status;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getMatrix2x2(MObject node, MObject attr, float* const str)
{
const char* const errorString = "DgNodeHelper::getMatrix2x2 error";
MPlug plug(node, attr);
if(!plug)
{
MGlobal::displayError(errorString);
return MS::kFailure;
}
AL_MAYA_CHECK_ERROR(plug.child(0).child(0).getValue(str[0]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(0).child(1).getValue(str[1]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).child(0).getValue(str[2]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).child(1).getValue(str[3]), errorString);
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getMatrix3x3(MObject node, MObject attr, float* const str)
{
const char* const errorString = "getMatrix3x3 error";
MPlug plug(node, attr);
if(!plug)
{
MGlobal::displayError(errorString);
return MS::kFailure;
}
AL_MAYA_CHECK_ERROR(plug.child(0).child(0).getValue(str[0]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(0).child(1).getValue(str[1]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(0).child(2).getValue(str[2]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).child(0).getValue(str[3]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).child(1).getValue(str[4]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).child(2).getValue(str[5]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(2).child(0).getValue(str[6]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(2).child(1).getValue(str[7]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(2).child(2).getValue(str[8]), errorString);
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getMatrix4x4(MObject node, MObject attr, float* const values)
{
const char* const errorString = "DgNodeHelper::getMatrix4x4 error";
MPlug plug(node, attr);
if(!plug)
{
MGlobal::displayError(errorString);
return MS::kFailure;
}
MObject data;
AL_MAYA_CHECK_ERROR(plug.getValue(data), errorString);
MFnMatrixData fn(data);
const MMatrix& mat = fn.matrix();
#if AL_UTILS_ENABLE_SIMD
# ifdef __AVX__
const f128 r0 = cvt4d_to_4f(loadu4d(&mat.matrix[0][0]));
const f128 r1 = cvt4d_to_4f(loadu4d(&mat.matrix[1][0]));
const f128 r2 = cvt4d_to_4f(loadu4d(&mat.matrix[2][0]));
const f128 r3 = cvt4d_to_4f(loadu4d(&mat.matrix[3][0]));
# else
const f128 r0 = movelh4f(
cvt2d_to_2f(loadu2d(&mat.matrix[0][0])),
cvt2d_to_2f(loadu2d(&mat.matrix[0][2])));
const f128 r1 = movelh4f(
cvt2d_to_2f(loadu2d(&mat.matrix[1][0])),
cvt2d_to_2f(loadu2d(&mat.matrix[1][2])));
const f128 r2 = movelh4f(
cvt2d_to_2f(loadu2d(&mat.matrix[2][0])),
cvt2d_to_2f(loadu2d(&mat.matrix[2][2])));
const f128 r3 = movelh4f(
cvt2d_to_2f(loadu2d(&mat.matrix[3][0])),
cvt2d_to_2f(loadu2d(&mat.matrix[3][2])));
# endif
storeu4f(values, r0);
storeu4f(values + 4, r1);
storeu4f(values + 8, r2);
storeu4f(values + 12, r3);
#else
values[0] = mat.matrix[0][0];
values[1] = mat.matrix[0][1];
values[2] = mat.matrix[0][2];
values[3] = mat.matrix[0][3];
values[4] = mat.matrix[1][0];
values[5] = mat.matrix[1][1];
values[6] = mat.matrix[1][2];
values[7] = mat.matrix[1][3];
values[8] = mat.matrix[2][0];
values[9] = mat.matrix[2][1];
values[10] = mat.matrix[2][2];
values[11] = mat.matrix[2][3];
values[12] = mat.matrix[3][0];
values[13] = mat.matrix[3][1];
values[14] = mat.matrix[3][2];
values[15] = mat.matrix[3][3];
#endif
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getMatrix2x2(MObject node, MObject attr, double* const str)
{
const char* const errorString = "DgNodeHelper::getMatrix2x2 error";
MPlug plug(node, attr);
if(!plug)
{
MGlobal::displayError(errorString);
return MS::kFailure;
}
AL_MAYA_CHECK_ERROR(plug.child(0).child(0).getValue(str[0]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(0).child(1).getValue(str[1]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).child(0).getValue(str[2]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).child(1).getValue(str[3]), errorString);
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getMatrix3x3(MObject node, MObject attr, double* const str)
{
const char* const errorString = "DgNodeHelper::getMatrix3x3 error";
MPlug plug(node, attr);
if(!plug)
{
MGlobal::displayError(errorString);
return MS::kFailure;
}
AL_MAYA_CHECK_ERROR(plug.child(0).child(0).getValue(str[0]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(0).child(1).getValue(str[1]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(0).child(2).getValue(str[2]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).child(0).getValue(str[3]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).child(1).getValue(str[4]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).child(2).getValue(str[5]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(2).child(0).getValue(str[6]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(2).child(1).getValue(str[7]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(2).child(2).getValue(str[8]), errorString);
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getMatrix4x4(MObject node, MObject attr, double* const values)
{
const char* const errorString = "DgNodeHelper::getMatrix4x4 error";
MPlug plug(node, attr);
if(!plug)
{
MGlobal::displayError(errorString);
return MS::kFailure;
}
MObject data;
AL_MAYA_CHECK_ERROR(plug.getValue(data), errorString);
MFnMatrixData fn(data);
const MMatrix& mat = fn.matrix();
#if AL_UTILS_ENABLE_SIMD
# ifdef __AVX__
const d256 r0 = loadu4d(&mat.matrix[0][0]);
const d256 r1 = loadu4d(&mat.matrix[1][0]);
const d256 r2 = loadu4d(&mat.matrix[2][0]);
const d256 r3 = loadu4d(&mat.matrix[3][0]);
storeu4d(values, r0);
storeu4d(values + 4, r1);
storeu4d(values + 8, r2);
storeu4d(values + 12, r3);
# else
const d128 r0a = loadu2d(&mat.matrix[0][0]);
const d128 r0b = loadu2d(&mat.matrix[0][2]);
const d128 r1a = loadu2d(&mat.matrix[1][0]);
const d128 r1b = loadu2d(&mat.matrix[1][2]);
const d128 r2a = loadu2d(&mat.matrix[2][0]);
const d128 r2b = loadu2d(&mat.matrix[2][2]);
const d128 r3a = loadu2d(&mat.matrix[3][0]);
const d128 r3b = loadu2d(&mat.matrix[3][2]);
storeu2d(values, r0a);
storeu2d(values + 2, r0b);
storeu2d(values + 4, r1a);
storeu2d(values + 6, r1b);
storeu2d(values + 8, r2a);
storeu2d(values + 10, r2b);
storeu2d(values + 12, r3a);
storeu2d(values + 14, r3b);
# endif
#else
values[0] = mat.matrix[0][0];
values[1] = mat.matrix[0][1];
values[2] = mat.matrix[0][2];
values[3] = mat.matrix[0][3];
values[4] = mat.matrix[1][0];
values[5] = mat.matrix[1][1];
values[6] = mat.matrix[1][2];
values[7] = mat.matrix[1][3];
values[8] = mat.matrix[2][0];
values[9] = mat.matrix[2][1];
values[10] = mat.matrix[2][2];
values[11] = mat.matrix[2][3];
values[12] = mat.matrix[3][0];
values[13] = mat.matrix[3][1];
values[14] = mat.matrix[3][2];
values[15] = mat.matrix[3][3];
#endif
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getString(MObject node, MObject attr, std::string& str)
{
const char* const errorString = "DgNodeHelper::getString error";
MPlug plug(node, attr);
if(!plug)
{
MGlobal::displayError(errorString);
return MS::kFailure;
}
MString value;
AL_MAYA_CHECK_ERROR(plug.getValue(value), errorString);
str.assign(value.asChar(), value.asChar() + value.length());
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getVec2(MObject node, MObject attr, int* xy)
{
const char* const errorString = "DgNodeHelper::getVec2 error";
MPlug plug(node, attr);
if(!plug)
{
MGlobal::displayError(errorString);
return MS::kFailure;
}
AL_MAYA_CHECK_ERROR(plug.child(0).getValue(xy[0]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).getValue(xy[1]), errorString);
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getVec2(MObject node, MObject attr, float* xy)
{
const char* const errorString = "DgNodeHelper::getVec2 error";
MPlug plug(node, attr);
if(!plug)
{
MGlobal::displayError(errorString);
return MS::kFailure;
}
AL_MAYA_CHECK_ERROR(plug.child(0).getValue(xy[0]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).getValue(xy[1]), errorString);
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getVec2(MObject node, MObject attr, double* xy)
{
const char* const errorString = "DgNodeHelper::getVec2 error";
MPlug plug(node, attr);
if(!plug)
{
MGlobal::displayError(errorString);
return MS::kFailure;
}
AL_MAYA_CHECK_ERROR(plug.child(0).getValue(xy[0]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).getValue(xy[1]), errorString);
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getVec2(MObject node, MObject attr, GfHalf* xy)
{
float fxy[2];
MStatus status = getVec2(node, attr, fxy);
xy[0] = AL::usd::utils::float2half_1f(fxy[0]);
xy[1] = AL::usd::utils::float2half_1f(fxy[1]);
return status;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getVec3(MObject node, MObject attr, int* xyz)
{
const char* const errorString = "DgNodeHelper::getVec3 error";
MPlug plug(node, attr);
if(!plug)
{
MGlobal::displayError(errorString);
return MS::kFailure;
}
AL_MAYA_CHECK_ERROR(plug.child(0).getValue(xyz[0]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).getValue(xyz[1]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(2).getValue(xyz[2]), errorString);
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getVec3(MObject node, MObject attr, float* xyz)
{
const char* const errorString = "DgNodeHelper::getVec3 error";
MPlug plug(node, attr);
if(!plug)
{
MGlobal::displayError(errorString);
return MS::kFailure;
}
AL_MAYA_CHECK_ERROR(plug.child(0).getValue(xyz[0]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).getValue(xyz[1]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(2).getValue(xyz[2]), errorString);
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getVec3(MObject node, MObject attr, double* xyz)
{
const char* const errorString = "DgNodeHelper::getVec3 error";
MPlug plug(node, attr);
if(!plug)
{
MGlobal::displayError(errorString);
return MS::kFailure;
}
AL_MAYA_CHECK_ERROR(plug.child(0).getValue(xyz[0]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).getValue(xyz[1]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(2).getValue(xyz[2]), errorString);
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getVec3(MObject node, MObject attr, GfHalf* xyz)
{
float fxyz[4];
GfHalf xyzw[4];
MStatus status = getVec3(node, attr, fxyz);
AL::usd::utils::float2half_4f(fxyz, xyzw);
xyz[0] = xyzw[0];
xyz[1] = xyzw[1];
xyz[2] = xyzw[2];
return status;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getVec4(MObject node, MObject attr, int* xyzw)
{
const char* const errorString = "DgNodeHelper::getVec4 error";
MPlug plug(node, attr);
if(!plug)
{
MGlobal::displayError(errorString);
return MS::kFailure;
}
AL_MAYA_CHECK_ERROR(plug.child(0).getValue(xyzw[0]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).getValue(xyzw[1]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(2).getValue(xyzw[2]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(3).getValue(xyzw[3]), errorString);
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getVec4(MObject node, MObject attr, float* xyzw)
{
const char* const errorString = "DgNodeHelper::getVec4 error";
MPlug plug(node, attr);
if(!plug)
{
MGlobal::displayError(errorString);
return MS::kFailure;
}
AL_MAYA_CHECK_ERROR(plug.child(0).getValue(xyzw[0]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).getValue(xyzw[1]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(2).getValue(xyzw[2]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(3).getValue(xyzw[3]), errorString);
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getVec4(MObject node, MObject attr, double* xyzw)
{
const char* const errorString = "DgNodeHelper::getVec4 error";
MPlug plug(node, attr);
if(!plug)
{
MGlobal::displayError(errorString);
return MS::kFailure;
}
AL_MAYA_CHECK_ERROR(plug.child(0).getValue(xyzw[0]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(1).getValue(xyzw[1]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(2).getValue(xyzw[2]), errorString);
AL_MAYA_CHECK_ERROR(plug.child(3).getValue(xyzw[3]), errorString);
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getVec4(MObject node, MObject attr, GfHalf* xyzw)
{
float fxyzw[4];
MStatus status = getVec4(node, attr, fxyzw);
AL::usd::utils::float2half_4f(fxyzw, xyzw);
return status;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getQuat(MObject node, MObject attr, float* xyzw)
{
return getVec4(node, attr, xyzw);
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getQuat(MObject node, MObject attr, double* xyzw)
{
return getVec4(node, attr, xyzw);
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getQuat(MObject node, MObject attr, GfHalf* xyzw)
{
return getVec4(node, attr, xyzw);
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getUsdBoolArray(const MObject& node, const MObject& attr, VtArray<bool>& values)
{
//
// Handle the oddity that is std::vector<bool>
//
MPlug plug(node, attr);
if(!plug || !plug.isArray())
return MS::kFailure;
uint32_t num = plug.numElements();
values.resize(num);
for(uint32_t i = 0; i < num; ++i)
{
values[i] = plug.elementByLogicalIndex(i).asBool();
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::getStringArray(MObject node, MObject attr, std::string* const values, const size_t count)
{
const char* const errorString = "DgNodeHelper::getStringArray";
MPlug plug(node, attr);
if(!plug)
{
MGlobal::displayError(errorString);
return MS::kFailure;
}
if(count != plug.numElements())
{
return MS::kFailure;
}
for(size_t i = 0; i < count; ++i)
{
const MString& str = plug.elementByLogicalIndex(i).asString();
values[i].assign(str.asChar(), str.length());
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::addStringValue(MObject node, const char* const attrName, const char* const stringValue)
{
MFnTypedAttribute fnT;
MObject attribute = fnT.create(attrName, attrName, MFnData::kString);
fnT.setArray(false);
fnT.setReadable(true);
fnT.setWritable(true);
MFnDependencyNode fn(node);
if(fn.addAttribute(attribute))
{
MPlug plug(node, attribute);
plug.setValue(stringValue);
return MS::kSuccess;
}
return MS::kFailure;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setMatrix4x4(MObject node, MObject attr, const MFloatMatrix& value)
{ return setMatrix4x4(node, attr, &value[0][0]); }
MStatus DgNodeHelper::setMatrix4x4(MObject node, MObject attr, const MMatrix& value)
{ return setMatrix4x4(node, attr, &value[0][0]); }
MStatus DgNodeHelper::getMatrix4x4(MObject node, MObject attr, MFloatMatrix& value)
{ return getMatrix4x4(node, attr, &value[0][0]); }
MStatus DgNodeHelper::getMatrix4x4(MObject node, MObject attr, MMatrix& value)
{ return getMatrix4x4(node, attr, &value[0][0]); }
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::copyBool(MObject node, MObject attr, const UsdAttribute& value)
{
if(value.IsAuthored() && value.HasValue())
{
bool data;
value.Get<bool> (&data);
return setBool(node, attr, data);
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::copyFloat(MObject node, MObject attr, const UsdAttribute& value)
{
if(value.IsAuthored() && value.HasValue())
{
float data;
value.Get<float> (&data);
return setFloat(node, attr, data);
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::copyDouble(MObject node, MObject attr, const UsdAttribute& value)
{
if(value.IsAuthored() && value.HasValue())
{
double data;
value.Get<double> (&data);
return setDouble(node, attr, data);
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::copyInt(MObject node, MObject attr, const UsdAttribute& value)
{
if(value.IsAuthored() && value.HasValue())
{
int data;
value.Get<int> (&data);
return setBool(node, attr, data);
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::copyVec3(MObject node, MObject attr, const UsdAttribute& value)
{
if(value.IsAuthored() && value.HasValue())
{
int data;
value.Get<int> (&data);
return setBool(node, attr, data);
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::addDynamicAttribute(MObject node, const UsdAttribute& usdAttr)
{
const SdfValueTypeName typeName = usdAttr.GetTypeName();
const bool isArray = typeName.IsArray();
const UsdDataType dataType = getAttributeType(usdAttr);
MObject attribute = MObject::kNullObj;
const char* attrName = usdAttr.GetName().GetString().c_str();
const uint32_t flags = (isArray ? AL::maya::utils::NodeHelper::kArray : 0) | AL::maya::utils::NodeHelper::kReadable |
AL::maya::utils::NodeHelper::kWritable | AL::maya::utils::NodeHelper::kStorable |
AL::maya::utils::NodeHelper::kConnectable;
switch(dataType)
{
case UsdDataType::kAsset:
{
return MS::kSuccess;
}
break;
case UsdDataType::kBool:
{
AL::maya::utils::NodeHelper::addBoolAttr(node, attrName, attrName, false, flags, &attribute);
}
break;
case UsdDataType::kUChar:
{
AL::maya::utils::NodeHelper::addInt8Attr(node, attrName, attrName, 0, flags, &attribute);
}
break;
case UsdDataType::kInt:
case UsdDataType::kUInt:
{
AL::maya::utils::NodeHelper::addInt32Attr(node, attrName, attrName, 0, flags, &attribute);
}
break;
case UsdDataType::kInt64:
case UsdDataType::kUInt64:
{
AL::maya::utils::NodeHelper::addInt64Attr(node, attrName, attrName, 0, flags, &attribute);
}
break;
case UsdDataType::kHalf:
case UsdDataType::kFloat:
{
AL::maya::utils::NodeHelper::addFloatAttr(node, attrName, attrName, 0, flags, &attribute);
}
break;
case UsdDataType::kDouble:
{
AL::maya::utils::NodeHelper::addDoubleAttr(node, attrName, attrName, 0, flags, &attribute);
}
break;
case UsdDataType::kString:
{
AL::maya::utils::NodeHelper::addStringAttr(node, attrName, attrName, flags, true, &attribute);
}
break;
case UsdDataType::kMatrix2d:
{
const float defValue[2][2] = {{0, 0}, {0, 0}};
AL::maya::utils::NodeHelper::addMatrix2x2Attr(node, attrName, attrName, defValue, flags, &attribute);
}
break;
case UsdDataType::kMatrix3d:
{
const float defValue[3][3] = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}};
AL::maya::utils::NodeHelper::addMatrix3x3Attr(node, attrName, attrName, defValue, flags, &attribute);
}
break;
case UsdDataType::kMatrix4d:
{
AL::maya::utils::NodeHelper::addMatrixAttr(node, attrName, attrName, MMatrix(), flags, &attribute);
}
break;
case UsdDataType::kQuatd:
{
AL::maya::utils::NodeHelper::addVec4dAttr(node, attrName, attrName, flags, &attribute);
}
break;
case UsdDataType::kQuatf:
case UsdDataType::kQuath:
{
AL::maya::utils::NodeHelper::addVec4fAttr(node, attrName, attrName, flags, &attribute);
}
break;
case UsdDataType::kVec2d:
{
AL::maya::utils::NodeHelper::addVec2dAttr(node, attrName, attrName, flags, &attribute);
}
break;
case UsdDataType::kVec2f:
case UsdDataType::kVec2h:
{
AL::maya::utils::NodeHelper::addVec2fAttr(node, attrName, attrName, flags, &attribute);
}
break;
case UsdDataType::kVec2i:
{
AL::maya::utils::NodeHelper::addVec2iAttr(node, attrName, attrName, flags, &attribute);
}
break;
case UsdDataType::kVec3d:
{
AL::maya::utils::NodeHelper::addVec3dAttr(node, attrName, attrName, flags, &attribute);
}
break;
case UsdDataType::kVec3f:
case UsdDataType::kVec3h:
{
AL::maya::utils::NodeHelper::addVec3fAttr(node, attrName, attrName, flags, &attribute);
}
break;
case UsdDataType::kVec3i:
{
AL::maya::utils::NodeHelper::addVec3iAttr(node, attrName, attrName, flags, &attribute);
}
break;
case UsdDataType::kVec4d:
{
AL::maya::utils::NodeHelper::addVec4dAttr(node, attrName, attrName, flags, &attribute);
}
break;
case UsdDataType::kVec4f:
case UsdDataType::kVec4h:
{
AL::maya::utils::NodeHelper::addVec4fAttr(node, attrName, attrName, flags, &attribute);
}
break;
case UsdDataType::kVec4i:
{
AL::maya::utils::NodeHelper::addVec4iAttr(node, attrName, attrName, flags, &attribute);
}
break;
default:
MGlobal::displayError("DgNodeTranslator::addDynamicAttribute - unsupported USD data type");
return MS::kFailure;
}
if(isArray)
{
return setArrayMayaValue(node, attribute, usdAttr, dataType);
}
return setSingleMayaValue(node, attribute, usdAttr, dataType);
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setMayaValue(MObject node, MObject attr, const UsdAttribute& usdAttr)
{
const SdfValueTypeName typeName = usdAttr.GetTypeName();
UsdDataType dataType = getAttributeType(usdAttr);
if(typeName.IsArray())
{
return setArrayMayaValue(node, attr, usdAttr, dataType);
}
return setSingleMayaValue(node, attr, usdAttr, dataType);
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setArrayMayaValue(MObject node, MObject attr, const UsdAttribute& usdAttr, const UsdDataType type)
{
switch(type)
{
case UsdDataType::kBool:
{
VtArray<bool> value;
usdAttr.Get(&value);
return setUsdBoolArray(node, attr, value);
}
case UsdDataType::kUChar:
{
VtArray<unsigned char> value;
usdAttr.Get(&value);
return setInt8Array(node, attr, (const int8_t*)value.cdata(), value.size());
}
case UsdDataType::kInt:
{
VtArray<int32_t> value;
usdAttr.Get(&value);
return setInt32Array(node, attr, (const int32_t*)value.cdata(), value.size());
}
case UsdDataType::kUInt:
{
VtArray<uint32_t> value;
usdAttr.Get(&value);
return setInt32Array(node, attr, (const int32_t*)value.cdata(), value.size());
}
case UsdDataType::kInt64:
{
VtArray<int64_t> value;
usdAttr.Get(&value);
return setInt64Array(node, attr, (const int64_t*)value.cdata(), value.size());
}
case UsdDataType::kUInt64:
{
VtArray<uint64_t> value;
usdAttr.Get(&value);
return setInt64Array(node, attr, (const int64_t*)value.cdata(), value.size());
}
case UsdDataType::kHalf:
{
VtArray<GfHalf> value;
usdAttr.Get(&value);
return setHalfArray(node, attr, (const GfHalf*)value.cdata(), value.size());
}
case UsdDataType::kFloat:
{
VtArray<float> value;
usdAttr.Get(&value);
return setFloatArray(node, attr, (const float*)value.cdata(), value.size());
}
case UsdDataType::kDouble:
{
VtArray<double> value;
usdAttr.Get(&value);
return setDoubleArray(node, attr, (const double*)value.cdata(), value.size());
}
case UsdDataType::kString:
{
VtArray<std::string> value;
usdAttr.Get(&value);
return setStringArray(node, attr, (const std::string*)value.cdata(), value.size());
}
case UsdDataType::kMatrix2d:
{
VtArray<GfMatrix2d> value;
usdAttr.Get(&value);
return setMatrix2x2Array(node, attr, (const double*)value.cdata(), value.size());
}
case UsdDataType::kMatrix3d:
{
VtArray<GfMatrix3d> value;
usdAttr.Get(&value);
return setMatrix3x3Array(node, attr, (const double*)value.cdata(), value.size());
}
case UsdDataType::kMatrix4d:
{
VtArray<GfMatrix4d> value;
usdAttr.Get(&value);
return setMatrix4x4Array(node, attr, (const double*)value.cdata(), value.size());
}
case UsdDataType::kQuatd:
{
VtArray<GfQuatd> value;
usdAttr.Get(&value);
return setQuatArray(node, attr, (const double*)value.cdata(), value.size());
}
case UsdDataType::kQuatf:
{
VtArray<GfQuatf> value;
usdAttr.Get(&value);
return setQuatArray(node, attr, (const float*)value.cdata(), value.size());
}
case UsdDataType::kQuath:
{
VtArray<GfQuath> value;
usdAttr.Get(&value);
return setQuatArray(node, attr, (const GfHalf*)value.cdata(), value.size());
}
case UsdDataType::kVec2d:
{
VtArray<GfVec2d> value;
usdAttr.Get(&value);
return setVec2Array(node, attr, (const double*)value.cdata(), value.size());
}
case UsdDataType::kVec2f:
{
VtArray<GfVec2f> value;
usdAttr.Get(&value);
return setVec2Array(node, attr, (const float*)value.cdata(), value.size());
}
case UsdDataType::kVec2h:
{
VtArray<GfVec2h> value;
usdAttr.Get(&value);
return setVec2Array(node, attr, (const GfHalf*)value.cdata(), value.size());
}
case UsdDataType::kVec2i:
{
VtArray<GfVec2i> value;
usdAttr.Get(&value);
return setVec2Array(node, attr, (const int32_t*)value.cdata(), value.size());
}
case UsdDataType::kVec3d:
{
VtArray<GfVec3d> value;
usdAttr.Get(&value);
return setVec3Array(node, attr, (const double*)value.cdata(), value.size());
}
case UsdDataType::kVec3f:
{
VtArray<GfVec3f> value;
usdAttr.Get(&value);
return setVec3Array(node, attr, (const float*)value.cdata(), value.size());
}
case UsdDataType::kVec3h:
{
VtArray<GfVec3h> value;
usdAttr.Get(&value);
return setVec3Array(node, attr, (const GfHalf*)value.cdata(), value.size());
}
case UsdDataType::kVec3i:
{
VtArray<GfVec3i> value;
usdAttr.Get(&value);
return setVec3Array(node, attr, (const int32_t*)value.cdata(), value.size());
}
case UsdDataType::kVec4d:
{
VtArray<GfVec4d> value;
usdAttr.Get(&value);
return setVec4Array(node, attr, (const double*)value.cdata(), value.size());
}
case UsdDataType::kVec4f:
{
VtArray<GfVec4f> value;
usdAttr.Get(&value);
return setVec4Array(node, attr, (const float*)value.cdata(), value.size());
}
case UsdDataType::kVec4h:
{
VtArray<GfVec4h> value;
usdAttr.Get(&value);
return setVec4Array(node, attr, (const GfHalf*)value.cdata(), value.size());
}
case UsdDataType::kVec4i:
{
VtArray<GfVec4i> value;
usdAttr.Get(&value);
return setVec4Array(node, attr, (const int32_t*)value.cdata(), value.size());
}
default:
MGlobal::displayError("DgNodeTranslator::setArrayMayaValue - unsupported USD data type");
break;
}
return MS::kFailure;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::setSingleMayaValue(MObject node, MObject attr, const UsdAttribute& usdAttr, const UsdDataType type)
{
switch(type)
{
case UsdDataType::kBool:
{
bool value;
usdAttr.Get<bool>(&value);
return setBool(node, attr, value);
}
case UsdDataType::kUChar:
{
unsigned char value;
usdAttr.Get<unsigned char>(&value);
return setInt8(node, attr, value);
}
case UsdDataType::kInt:
{
int32_t value;
usdAttr.Get<int32_t>(&value);
return setInt32(node, attr, value);
}
case UsdDataType::kUInt:
{
uint32_t value;
usdAttr.Get<uint32_t>(&value);
return setInt32(node, attr, value);
}
case UsdDataType::kInt64:
{
int64_t value;
usdAttr.Get<int64_t>(&value);
return setInt64(node, attr, value);
}
case UsdDataType::kUInt64:
{
uint64_t value;
usdAttr.Get<uint64_t>(&value);
return setInt64(node, attr, value);
}
case UsdDataType::kHalf:
{
GfHalf value;
usdAttr.Get<GfHalf>(&value);
return setFloat(node, attr, value);
}
case UsdDataType::kFloat:
{
float value;
usdAttr.Get<float>(&value);
return setFloat(node, attr, value);
}
case UsdDataType::kDouble:
{
double value;
usdAttr.Get<double>(&value);
return setDouble(node, attr, value);
}
case UsdDataType::kString:
{
std::string value;
usdAttr.Get<std::string>(&value);
return setString(node, attr, value.c_str());
}
case UsdDataType::kMatrix2d:
{
GfMatrix2d value;
usdAttr.Get<GfMatrix2d>(&value);
return setMatrix2x2(node, attr, value.GetArray());
}
case UsdDataType::kMatrix3d:
{
GfMatrix3d value;
usdAttr.Get<GfMatrix3d>(&value);
return setMatrix3x3(node, attr, value.GetArray());
}
case UsdDataType::kMatrix4d:
{
GfMatrix4d value;
usdAttr.Get<GfMatrix4d>(&value);
return setMatrix4x4(node, attr, value.GetArray());
}
case UsdDataType::kQuatd:
{
GfQuatd value;
usdAttr.Get<GfQuatd>(&value);
return setQuat(node, attr, reinterpret_cast<const double*>(&value));
}
case UsdDataType::kQuatf:
{
GfQuatf value;
usdAttr.Get<GfQuatf>(&value);
return setQuat(node, attr, reinterpret_cast<const float*>(&value));
}
case UsdDataType::kQuath:
{
GfQuath value;
usdAttr.Get<GfQuath>(&value);
float xyzw[4];
xyzw[0] = value.GetImaginary()[0];
xyzw[1] = value.GetImaginary()[1];
xyzw[2] = value.GetImaginary()[2];
xyzw[3] = value.GetReal();
return setQuat(node, attr, xyzw);
}
case UsdDataType::kVec2d:
{
GfVec2d value;
usdAttr.Get<GfVec2d>(&value);
return setVec2(node, attr, reinterpret_cast<const double*>(&value));
}
case UsdDataType::kVec2f:
{
GfVec2f value;
usdAttr.Get<GfVec2f>(&value);
return setVec2(node, attr, reinterpret_cast<const float*>(&value));
}
case UsdDataType::kVec2h:
{
GfVec2h value;
usdAttr.Get<GfVec2h>(&value);
float data[2];
data[0] = value[0];
data[1] = value[1];
return setVec2(node, attr, data);
}
case UsdDataType::kVec2i:
{
GfVec2i value;
usdAttr.Get<GfVec2i>(&value);
return setVec2(node, attr, reinterpret_cast<const int32_t*>(&value));
}
case UsdDataType::kVec3d:
{
GfVec3d value;
usdAttr.Get<GfVec3d>(&value);
return setVec3(node, attr, reinterpret_cast<const double*>(&value));
}
case UsdDataType::kVec3f:
{
GfVec3f value;
usdAttr.Get<GfVec3f>(&value);
return setVec3(node, attr, reinterpret_cast<const float*>(&value));
}
case UsdDataType::kVec3h:
{
GfVec3h value;
usdAttr.Get<GfVec3h>(&value);
return setVec3(node, attr, value[0], value[1], value[2]);
}
case UsdDataType::kVec3i:
{
GfVec3i value;
usdAttr.Get<GfVec3i>(&value);
return setVec3(node, attr, reinterpret_cast<const int32_t*>(&value));
}
case UsdDataType::kVec4d:
{
GfVec4d value;
usdAttr.Get<GfVec4d>(&value);
return setVec4(node, attr, reinterpret_cast<const double*>(&value));
}
case UsdDataType::kVec4f:
{
GfVec4f value;
usdAttr.Get<GfVec4f>(&value);
return setVec4(node, attr, reinterpret_cast<const float*>(&value));
}
case UsdDataType::kVec4h:
{
GfVec4h value;
usdAttr.Get<GfVec4h>(&value);
float xyzw[4];
xyzw[0] = value[0];
xyzw[1] = value[1];
xyzw[2] = value[2];
xyzw[3] = value[3];
return setVec4(node, attr, xyzw);
}
case UsdDataType::kVec4i:
{
GfVec4i value;
usdAttr.Get<GfVec4i>(&value);
return setVec4(node, attr, reinterpret_cast<const int32_t*>(&value));
}
default:
MGlobal::displayError("DgNodeTranslator::setArrayMayaValue - unsupported USD data type");
break;
}
return MS::kFailure;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::convertSpecialValueToUSDAttribute(const MPlug& plug, UsdAttribute& usdAttr)
{
// now we start some hard-coded special attribute value type conversion, no better way found:
// interpolateBoundary: This property comes from alembic, in maya it is boolean type:
if(usdAttr.GetName() == UsdGeomTokens->interpolateBoundary)
{
if(plug.asBool())
usdAttr.Set(UsdGeomTokens->edgeAndCorner);
else
usdAttr.Set(UsdGeomTokens->edgeOnly);
return MS::kSuccess;
}
// more special type conversion rules might come here..
return MS::kFailure;
}
//----------------------------------------------------------------------------------------------------------------------
MStatus DgNodeHelper::copyDynamicAttributes(MObject node, UsdPrim& prim)
{
MFnDependencyNode fn(node);
uint32_t numAttributes = fn.attributeCount();
for(uint32_t i = 0; i < numAttributes; ++i)
{
MObject attribute = fn.attribute(i);
MPlug plug(node, attribute);
// skip child attributes (only export from highest level)
if(plug.isChild())
continue;
bool isDynamic = plug.isDynamic();
if(isDynamic)
{
TfToken attributeName = TfToken(plug.partialName(false, false, false, false, false, true).asChar());
// first test if the attribute happen to come with the prim by nature and we have a mapping rule for it:
if(prim.HasAttribute(attributeName))
{
UsdAttribute usdAttr = prim.GetAttribute(attributeName);
// if the conversion works, we are done:
if(convertSpecialValueToUSDAttribute(plug, usdAttr))
{
continue;
}
// if not, then we count on CreateAttribute codes below since that will return the USDAttribute if
// already exists and hopefully the type conversions below will work.
}
bool isArray = plug.isArray();
switch(attribute.apiType())
{
case MFn::kAttribute2Double:
{
if(!isArray)
{
UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Double2);
GfVec2d m;
getVec2(node, attribute, (double*)&m);
usdAttr.Set(m);
usdAttr.SetCustom(true);
}
else
{
UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Double2Array);
VtArray<GfVec2d> m;
m.resize(plug.numElements());
getVec2Array(node, attribute, (double*)m.data(), m.size());
usdAttr.Set(m);
usdAttr.SetCustom(true);
}
}
break;
case MFn::kAttribute2Float:
{
if(!isArray)
{
UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Float2);
GfVec2f m;
getVec2(node, attribute, (float*)&m);
usdAttr.Set(m);
usdAttr.SetCustom(true);
}
else
{
UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Float2Array);
VtArray<GfVec2f> m;
m.resize(plug.numElements());
getVec2Array(node, attribute, (float*)m.data(), m.size());
usdAttr.Set(m);
usdAttr.SetCustom(true);
}
}
break;
case MFn::kAttribute2Int:
case MFn::kAttribute2Short:
{
if(!isArray)
{
UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Int2);
GfVec2i m;
getVec2(node, attribute, (int32_t*)&m);
usdAttr.Set(m);
usdAttr.SetCustom(true);
}
else
{
UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Int2Array);
VtArray<GfVec2i> m;
m.resize(plug.numElements());
getVec2Array(node, attribute, (int32_t*)m.data(), m.size());
usdAttr.Set(m);
usdAttr.SetCustom(true);
}
}
break;
case MFn::kAttribute3Double:
{
if(!isArray)
{
UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Double3);
GfVec3d m;
getVec3(node, attribute, (double*)&m);
usdAttr.Set(m);
usdAttr.SetCustom(true);
}
else
{
UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Double3Array);
VtArray<GfVec3d> m;
m.resize(plug.numElements());
getVec3Array(node, attribute, (double*)m.data(), m.size());
usdAttr.Set(m);
usdAttr.SetCustom(true);
}
}
break;
case MFn::kAttribute3Float:
{
if(!isArray)
{
UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Float3);
GfVec3f m;
getVec3(node, attribute, (float*)&m);
usdAttr.Set(m);
usdAttr.SetCustom(true);
}
else
{
UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Float3Array);
VtArray<GfVec3f> m;
m.resize(plug.numElements());
getVec3Array(node, attribute, (float*)m.data(), m.size());
usdAttr.Set(m);
usdAttr.SetCustom(true);
}
}
break;
case MFn::kAttribute3Long:
case MFn::kAttribute3Short:
{
if(!isArray)
{
UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Int3);
GfVec3i m;
getVec3(node, attribute, (int32_t*)&m);
usdAttr.Set(m);
usdAttr.SetCustom(true);
}
else
{
UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Int3Array);
VtArray<GfVec3i> m;
m.resize(plug.numElements());
getVec3Array(node, attribute, (int32_t*)m.data(), m.size());
usdAttr.Set(m);
usdAttr.SetCustom(true);
}
}
break;
case MFn::kAttribute4Double:
{
if(!isArray)
{
UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Double4);
GfVec4d m;
getVec4(node, attribute, (double*)&m);
usdAttr.Set(m);
usdAttr.SetCustom(true);
}
else
{
UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Double4Array);
VtArray<GfVec4d> m;
m.resize(plug.numElements());
getVec4Array(node, attribute, (double*)m.data(), m.size());
usdAttr.Set(m);
usdAttr.SetCustom(true);
}
}
break;
case MFn::kNumericAttribute:
{
MFnNumericAttribute fn(attribute);
switch(fn.unitType())
{
case MFnNumericData::kBoolean:
{
if(!isArray)
{
UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Bool);
bool value;
getBool(node, attribute, value);
usdAttr.Set(value);
usdAttr.SetCustom(true);
}
else
{
UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->BoolArray);
VtArray<bool> m;
m.resize(plug.numElements());
getUsdBoolArray(node, attribute, m);
usdAttr.Set(m);
usdAttr.SetCustom(true);
}
}
break;
case MFnNumericData::kFloat:
{
if(!isArray)
{
UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Float);
float value;
getFloat(node, attribute, value);
usdAttr.Set(value);
usdAttr.SetCustom(true);
}
else
{
UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->FloatArray);
VtArray<float> m;
m.resize(plug.numElements());
getFloatArray(node, attribute, (float*)m.data(), m.size());
usdAttr.Set(m);
usdAttr.SetCustom(true);
}
}
break;
case MFnNumericData::kDouble:
{
if(!isArray)
{
UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Double);
double value;
getDouble(node, attribute, value);
usdAttr.Set(value);
usdAttr.SetCustom(true);
}
else
{
UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->DoubleArray);
VtArray<double> m;
m.resize(plug.numElements());
getDoubleArray(node, attribute, (double*)m.data(), m.size());
usdAttr.Set(m);
usdAttr.SetCustom(true);
}
}
break;
case MFnNumericData::kInt:
case MFnNumericData::kShort:
{
if(!isArray)
{
UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Int);
int32_t value;
getInt32(node, attribute, value);
usdAttr.Set(value);
usdAttr.SetCustom(true);
}
else
{
UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->IntArray);
VtArray<int> m;
m.resize(plug.numElements());
getInt32Array(node, attribute, (int32_t*)m.data(), m.size());
usdAttr.Set(m);
usdAttr.SetCustom(true);
}
}
break;
case MFnNumericData::kInt64:
{
if(!isArray)
{
UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Int64);
int64_t value;
getInt64(node, attribute, value);
usdAttr.Set(value);
usdAttr.SetCustom(true);
}
else
{
UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Int64Array);
VtArray<int64_t> m;
m.resize(plug.numElements());
getInt64Array(node, attribute, (int64_t*)m.data(), m.size());
usdAttr.Set(m);
usdAttr.SetCustom(true);
}
}
break;
case MFnNumericData::kByte:
case MFnNumericData::kChar:
{
if(!isArray)
{
UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->UChar);
int16_t value;
getInt16(node, attribute, value);
usdAttr.Set(uint8_t(value));
usdAttr.SetCustom(true);
}
else
{
UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->UCharArray);
VtArray<uint8_t> m;
m.resize(plug.numElements());
getInt8Array(node, attribute, (int8_t*)m.data(), m.size());
usdAttr.Set(m);
usdAttr.SetCustom(true);
}
}
break;
default:
{
std::cout << "Unhandled numeric attribute: " << fn.name().asChar() << " " << fn.unitType() << std::endl;
}
break;
}
}
break;
case MFn::kDoubleAngleAttribute:
{
if(!isArray)
{
UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Double);
double value;
getDouble(node, attribute, value);
usdAttr.Set(value);
usdAttr.SetCustom(true);
}
else
{
UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->DoubleArray);
VtArray<double> value;
value.resize(plug.numElements());
getDoubleArray(node, attribute, (double*)value.data(), value.size());
usdAttr.Set(value);
usdAttr.SetCustom(true);
}
}
break;
case MFn::kFloatAngleAttribute:
{
if(!isArray)
{
UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Float);
float value;
getFloat(node, attribute, value);
usdAttr.Set(value);
usdAttr.SetCustom(true);
}
else
{
UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->FloatArray);
VtArray<float> value;
value.resize(plug.numElements());
getFloatArray(node, attribute, (float*)value.data(), value.size());
usdAttr.Set(value);
usdAttr.SetCustom(true);
}
}
break;
case MFn::kDoubleLinearAttribute:
{
if(!isArray)
{
UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Double);
double value;
getDouble(node, attribute, value);
usdAttr.Set(value);
usdAttr.SetCustom(true);
}
else
{
UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->DoubleArray);
VtArray<double> value;
value.resize(plug.numElements());
getDoubleArray(node, attribute, (double*)value.data(), value.size());
usdAttr.Set(value);
usdAttr.SetCustom(true);
}
}
break;
case MFn::kFloatLinearAttribute:
{
if(!isArray)
{
UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Float);
float value;
getFloat(node, attribute, value);
usdAttr.Set(value);
usdAttr.SetCustom(true);
}
else
{
UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->FloatArray);
VtArray<float> value;
value.resize(plug.numElements());
getFloatArray(node, attribute, (float*)value.data(), value.size());
usdAttr.Set(value);
usdAttr.SetCustom(true);
}
}
break;
case MFn::kTimeAttribute:
{
if(!isArray)
{
UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Double);
double value;
getDouble(node, attribute, value);
usdAttr.Set(value);
usdAttr.SetCustom(true);
}
else
{
UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->DoubleArray);
VtArray<double> value;
value.resize(plug.numElements());
getDoubleArray(node, attribute, (double*)value.data(), value.size());
usdAttr.Set(value);
usdAttr.SetCustom(true);
}
}
break;
case MFn::kEnumAttribute:
{
if(!isArray)
{
UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Int);
int32_t value;
getInt32(node, attribute, value);
usdAttr.Set(value);
usdAttr.SetCustom(true);
}
else
{
UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->IntArray);
VtArray<int> m;
m.resize(plug.numElements());
getInt32Array(node, attribute, (int32_t*)m.data(), m.size());
usdAttr.Set(m);
usdAttr.SetCustom(true);
}
}
break;
case MFn::kTypedAttribute:
{
MFnTypedAttribute fnTyped(plug.attribute());
MFnData::Type type = fnTyped.attrType();
switch(type)
{
case MFnData::kString:
{
if(!isArray)
{
UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->String);
std::string value;
getString(node, attribute, value);
usdAttr.Set(value);
usdAttr.SetCustom(true);
}
else
{
UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->StringArray);
VtArray<std::string> value;
value.resize(plug.numElements());
getStringArray(node, attribute, (std::string*)value.data(), value.size());
usdAttr.Set(value);
usdAttr.SetCustom(true);
}
}
break;
case MFnData::kMatrixArray:
{
MFnMatrixArrayData fnData(plug.asMObject());
UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Matrix4dArray);
VtArray<GfMatrix4d> m;
m.assign((const GfMatrix4d*)&fnData.array()[0], ((const GfMatrix4d*)&fnData.array()[0]) + fnData.array().length());
usdAttr.Set(m);
usdAttr.SetCustom(true);
}
break;
default:
{
std::cout << "Unhandled typed attribute: " << fn.name().asChar() << " " << fn.typeName().asChar() << std::endl;
}
break;
}
}
break;
case MFn::kCompoundAttribute:
{
MFnCompoundAttribute fnCompound(plug.attribute());
{
if(fnCompound.numChildren() == 2)
{
MObject x = fnCompound.child(0);
MObject y = fnCompound.child(1);
if(x.apiType() == MFn::kCompoundAttribute &&
y.apiType() == MFn::kCompoundAttribute)
{
MFnCompoundAttribute fnCompoundX(x);
MFnCompoundAttribute fnCompoundY(y);
if(fnCompoundX.numChildren() == 2 && fnCompoundY.numChildren() == 2)
{
MObject xx = fnCompoundX.child(0);
MObject xy = fnCompoundX.child(1);
MObject yx = fnCompoundY.child(0);
MObject yy = fnCompoundY.child(1);
if(xx.apiType() == MFn::kNumericAttribute &&
xy.apiType() == MFn::kNumericAttribute &&
yx.apiType() == MFn::kNumericAttribute &&
yy.apiType() == MFn::kNumericAttribute)
{
if(!isArray)
{
UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Matrix2d);
GfMatrix2d value;
getMatrix2x2(node, attribute, (double*)&value);
usdAttr.Set(value);
usdAttr.SetCustom(true);
}
else
{
UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Matrix2dArray);
VtArray<GfMatrix2d> value;
value.resize(plug.numElements());
getMatrix2x2Array(node, attribute, (double*)value.data(), plug.numElements());
usdAttr.Set(value);
usdAttr.SetCustom(true);
}
}
}
}
}
else
if(fnCompound.numChildren() == 3)
{
MObject x = fnCompound.child(0);
MObject y = fnCompound.child(1);
MObject z = fnCompound.child(2);
if(x.apiType() == MFn::kCompoundAttribute &&
y.apiType() == MFn::kCompoundAttribute &&
z.apiType() == MFn::kCompoundAttribute)
{
MFnCompoundAttribute fnCompoundX(x);
MFnCompoundAttribute fnCompoundY(y);
MFnCompoundAttribute fnCompoundZ(z);
if(fnCompoundX.numChildren() == 3 && fnCompoundY.numChildren() == 3 && fnCompoundZ.numChildren() == 3)
{
MObject xx = fnCompoundX.child(0);
MObject xy = fnCompoundX.child(1);
MObject xz = fnCompoundX.child(2);
MObject yx = fnCompoundY.child(0);
MObject yy = fnCompoundY.child(1);
MObject yz = fnCompoundY.child(2);
MObject zx = fnCompoundZ.child(0);
MObject zy = fnCompoundZ.child(1);
MObject zz = fnCompoundZ.child(2);
if(xx.apiType() == MFn::kNumericAttribute &&
xy.apiType() == MFn::kNumericAttribute &&
xz.apiType() == MFn::kNumericAttribute &&
yx.apiType() == MFn::kNumericAttribute &&
yy.apiType() == MFn::kNumericAttribute &&
yz.apiType() == MFn::kNumericAttribute &&
zx.apiType() == MFn::kNumericAttribute &&
zy.apiType() == MFn::kNumericAttribute &&
zz.apiType() == MFn::kNumericAttribute)
{
if(!isArray)
{
UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Matrix3d);
GfMatrix3d value;
getMatrix3x3(node, attribute, (double*)&value);
usdAttr.Set(value);
usdAttr.SetCustom(true);
}
else
{
UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Matrix3dArray);
VtArray<GfMatrix3d> value;
value.resize(plug.numElements());
getMatrix3x3Array(node, attribute, (double*)value.data(), plug.numElements());
usdAttr.Set(value);
usdAttr.SetCustom(true);
}
}
}
}
}
else
if(fnCompound.numChildren() == 4)
{
MObject x = fnCompound.child(0);
MObject y = fnCompound.child(1);
MObject z = fnCompound.child(2);
MObject w = fnCompound.child(3);
if(x.apiType() == MFn::kNumericAttribute &&
y.apiType() == MFn::kNumericAttribute &&
z.apiType() == MFn::kNumericAttribute &&
w.apiType() == MFn::kNumericAttribute)
{
MFnNumericAttribute fnx(x);
MFnNumericAttribute fny(y);
MFnNumericAttribute fnz(z);
MFnNumericAttribute fnw(w);
MFnNumericData::Type typex = fnx.unitType();
MFnNumericData::Type typey = fny.unitType();
MFnNumericData::Type typez = fnz.unitType();
MFnNumericData::Type typew = fnw.unitType();
if(typex == typey && typex == typez && typex == typew)
{
switch(typex)
{
case MFnNumericData::kInt:
{
if(!isArray)
{
UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Int4);
GfVec4i value;
getVec4(node, attribute, (int32_t*)&value);
usdAttr.Set(value);
usdAttr.SetCustom(true);
}
else
{
UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Int4Array);
VtArray<GfVec4i> value;
value.resize(plug.numElements());
getVec4Array(node, attribute, (int32_t*)value.data(), value.size());
usdAttr.Set(value);
usdAttr.SetCustom(true);
}
}
break;
case MFnNumericData::kFloat:
{
if(!isArray)
{
UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Float4);
GfVec4f value;
getVec4(node, attribute, (float*)&value);
usdAttr.Set(value);
usdAttr.SetCustom(true);
}
else
{
UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Float4Array);
VtArray<GfVec4f> value;
value.resize(plug.numElements());
getVec4Array(node, attribute, (float*)value.data(), value.size());
usdAttr.Set(value);
usdAttr.SetCustom(true);
}
}
break;
case MFnNumericData::kDouble:
{
if(!isArray)
{
UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Double4);
GfVec4d value;
getVec4(node, attribute, (double*)&value);
usdAttr.Set(value);
usdAttr.SetCustom(true);
}
else
{
UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Double4Array);
VtArray<GfVec4d> value;
value.resize(plug.numElements());
getVec4Array(node, attribute, (double*)value.data(), value.size());
usdAttr.Set(value);
usdAttr.SetCustom(true);
}
}
break;
default: break;
}
}
}
}
}
}
break;
case MFn::kFloatMatrixAttribute:
case MFn::kMatrixAttribute:
{
if(!isArray)
{
UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Matrix4d);
GfMatrix4d m;
getMatrix4x4(node, attribute, (double*)&m);
usdAttr.Set(m);
usdAttr.SetCustom(true);
}
else
{
UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Matrix4dArray);
VtArray<GfMatrix4d> value;
value.resize(plug.numElements());
getMatrix4x4Array(node, attribute, (double*)value.data(), value.size());
usdAttr.Set(value);
usdAttr.SetCustom(true);
}
}
break;
default: break;
}
}
}
return MS::kSuccess;
}
//----------------------------------------------------------------------------------------------------------------------
void DgNodeHelper::copySimpleValue(const MPlug& plug, UsdAttribute& usdAttr, const UsdTimeCode& timeCode)
{
MObject node = plug.node();
MObject attribute = plug.attribute();
bool isArray = plug.isArray();
switch(getAttributeType(usdAttr))
{
case UsdDataType::kUChar:
if(!isArray)
{
int8_t value;
getInt8(node, attribute, value);
usdAttr.Set(uint8_t(value), timeCode);
}
else
{
VtArray<uint8_t> m;
m.resize(plug.numElements());
getInt8Array(node, attribute, (int8_t*)m.data(), m.size());
usdAttr.Set(m, timeCode);
}
break;
case UsdDataType::kInt:
if(!isArray)
{
int32_t value;
getInt32(node, attribute, value);
usdAttr.Set(value, timeCode);
}
else
{
VtArray<int32_t> m;
m.resize(plug.numElements());
getInt32Array(node, attribute, (int32_t*)m.data(), m.size());
usdAttr.Set(m, timeCode);
}
break;
case UsdDataType::kUInt:
if(!isArray)
{
int32_t value;
getInt32(node, attribute, value);
usdAttr.Set(uint32_t(value), timeCode);
}
else
{
VtArray<uint32_t> m;
m.resize(plug.numElements());
getInt32Array(node, attribute, (int32_t*)m.data(), m.size());
usdAttr.Set(m, timeCode);
}
break;
case UsdDataType::kInt64:
if(!isArray)
{
int64_t value;
getInt64(node, attribute, value);
usdAttr.Set(value, timeCode);
}
else
{
VtArray<int64_t> m;
m.resize(plug.numElements());
getInt64Array(node, attribute, (int64_t*)m.data(), m.size());
usdAttr.Set(m, timeCode);
}
break;
case UsdDataType::kUInt64:
if(!isArray)
{
int64_t value;
getInt64(node, attribute, value);
usdAttr.Set(value, timeCode);
}
else
{
VtArray<int64_t> m;
m.resize(plug.numElements());
getInt64Array(node, attribute, (int64_t*)m.data(), m.size());
usdAttr.Set(m, timeCode);
}
break;
case UsdDataType::kFloat:
if(!isArray)
{
float value;
getFloat(node, attribute, value);
usdAttr.Set(value, timeCode);
}
else
{
VtArray<float> m;
m.resize(plug.numElements());
getFloatArray(node, attribute, (float*)m.data(), m.size());
usdAttr.Set(m, timeCode);
}
break;
case UsdDataType::kDouble:
if(!isArray)
{
double value;
getDouble(node, attribute, value);
usdAttr.Set(value, timeCode);
}
else
{
VtArray<double> m;
m.resize(plug.numElements());
getDoubleArray(node, attribute, (double*)m.data(), m.size());
usdAttr.Set(m, timeCode);
}
break;
case UsdDataType::kHalf:
if(!isArray)
{
GfHalf value;
getHalf(node, attribute, value);
usdAttr.Set(value, timeCode);
}
else
{
VtArray<GfHalf> m;
m.resize(plug.numElements());
getHalfArray(node, attribute, (GfHalf*)m.data(), m.size());
usdAttr.Set(m, timeCode);
}
break;
default:
break;
}
}
//----------------------------------------------------------------------------------------------------------------------
void DgNodeHelper::copyAttributeValue(const MPlug& plug, UsdAttribute& usdAttr, const UsdTimeCode& timeCode)
{
MObject node = plug.node();
MObject attribute = plug.attribute();
bool isArray = plug.isArray();
switch(attribute.apiType())
{
case MFn::kAttribute2Double:
case MFn::kAttribute2Float:
case MFn::kAttribute2Int:
case MFn::kAttribute2Short:
{
switch(getAttributeType(usdAttr))
{
case UsdDataType::kVec2d:
if(!isArray)
{
GfVec2d m;
getVec2(node, attribute, (double*)&m);
usdAttr.Set(m, timeCode);
}
else
{
VtArray<GfVec2d> m;
m.resize(plug.numElements());
getVec2Array(node, attribute, (double*)m.data(), m.size());
usdAttr.Set(m, timeCode);
}
break;
case UsdDataType::kVec2f:
if(!isArray)
{
GfVec2f m;
getVec2(node, attribute, (float*)&m);
usdAttr.Set(m, timeCode);
}
else
{
VtArray<GfVec2f> m;
m.resize(plug.numElements());
getVec2Array(node, attribute, (float*)m.data(), m.size());
usdAttr.Set(m, timeCode);
}
break;
case UsdDataType::kVec2i:
if(!isArray)
{
GfVec2i m;
getVec2(node, attribute, (int*)&m);
usdAttr.Set(m, timeCode);
}
else
{
VtArray<GfVec2i> m;
m.resize(plug.numElements());
getVec2Array(node, attribute, (int*)m.data(), m.size());
usdAttr.Set(m, timeCode);
}
break;
case UsdDataType::kVec2h:
if(!isArray)
{
GfVec2h m;
getVec2(node, attribute, (GfHalf*)&m);
usdAttr.Set(m, timeCode);
}
else
{
VtArray<GfVec2h> m;
m.resize(plug.numElements());
getVec2Array(node, attribute, (GfHalf*)m.data(), m.size());
usdAttr.Set(m, timeCode);
}
break;
default:
break;
}
}
break;
case MFn::kAttribute3Double:
case MFn::kAttribute3Float:
case MFn::kAttribute3Long:
case MFn::kAttribute3Short:
{
switch(getAttributeType(usdAttr))
{
case UsdDataType::kVec3d:
if(!isArray)
{
GfVec3d m;
getVec3(node, attribute, (double*)&m);
usdAttr.Set(m, timeCode);
}
else
{
VtArray<GfVec3d> m;
m.resize(plug.numElements());
getVec3Array(node, attribute, (double*)m.data(), m.size());
usdAttr.Set(m, timeCode);
}
break;
case UsdDataType::kVec3f:
if(!isArray)
{
GfVec3f m;
getVec3(node, attribute, (float*)&m);
usdAttr.Set(m, timeCode);
}
else
{
VtArray<GfVec3f> m;
m.resize(plug.numElements());
getVec3Array(node, attribute, (float*)m.data(), m.size());
usdAttr.Set(m, timeCode);
}
break;
case UsdDataType::kVec3i:
if(!isArray)
{
GfVec3i m;
getVec3(node, attribute, (int*)&m);
usdAttr.Set(m, timeCode);
}
else
{
VtArray<GfVec3i> m;
m.resize(plug.numElements());
getVec3Array(node, attribute, (int*)m.data(), m.size());
usdAttr.Set(m, timeCode);
}
break;
case UsdDataType::kVec3h:
if(!isArray)
{
GfVec3h m;
getVec3(node, attribute, (GfHalf*)&m);
usdAttr.Set(m, timeCode);
}
else
{
VtArray<GfVec3h> m;
m.resize(plug.numElements());
getVec3Array(node, attribute, (GfHalf*)m.data(), m.size());
usdAttr.Set(m, timeCode);
}
break;
default:
break;
}
}
break;
case MFn::kAttribute4Double:
{
switch(getAttributeType(usdAttr))
{
case UsdDataType::kVec4d:
if(!isArray)
{
GfVec4d m;
getVec4(node, attribute, (double*)&m);
usdAttr.Set(m, timeCode);
}
else
{
VtArray<GfVec4d> m;
m.resize(plug.numElements());
getVec4Array(node, attribute, (double*)m.data(), m.size());
usdAttr.Set(m, timeCode);
}
break;
case UsdDataType::kVec4f:
if(!isArray)
{
GfVec4f m;
getVec4(node, attribute, (float*)&m);
usdAttr.Set(m, timeCode);
}
else
{
VtArray<GfVec4f> m;
m.resize(plug.numElements());
getVec4Array(node, attribute, (float*)m.data(), m.size());
usdAttr.Set(m, timeCode);
}
break;
case UsdDataType::kVec4i:
if(!isArray)
{
GfVec4i m;
getVec4(node, attribute, (int*)&m);
usdAttr.Set(m, timeCode);
}
else
{
VtArray<GfVec4i> m;
m.resize(plug.numElements());
getVec4Array(node, attribute, (int*)m.data(), m.size());
usdAttr.Set(m, timeCode);
}
break;
case UsdDataType::kVec4h:
if(!isArray)
{
GfVec4h m;
getVec4(node, attribute, (GfHalf*)&m);
usdAttr.Set(m, timeCode);
}
else
{
VtArray<GfVec4h> m;
m.resize(plug.numElements());
getVec4Array(node, attribute, (GfHalf*)m.data(), m.size());
usdAttr.Set(m, timeCode);
}
break;
default:
break;
}
}
break;
case MFn::kNumericAttribute:
{
MFnNumericAttribute fn(attribute);
switch(fn.unitType())
{
case MFnNumericData::kBoolean:
{
if(!isArray)
{
bool value;
getBool(node, attribute, value);
usdAttr.Set(value, timeCode);
}
else
{
VtArray<bool> m;
m.resize(plug.numElements());
getUsdBoolArray(node, attribute, m);
usdAttr.Set(m, timeCode);
}
}
break;
case MFnNumericData::kFloat:
case MFnNumericData::kDouble:
case MFnNumericData::kInt:
case MFnNumericData::kShort:
case MFnNumericData::kInt64:
case MFnNumericData::kByte:
case MFnNumericData::kChar:
{
copySimpleValue(plug, usdAttr, timeCode);
}
break;
default:
{
}
break;
}
}
break;
case MFn::kTimeAttribute:
case MFn::kFloatAngleAttribute:
case MFn::kDoubleAngleAttribute:
case MFn::kDoubleLinearAttribute:
case MFn::kFloatLinearAttribute:
{
copySimpleValue(plug, usdAttr, timeCode);
}
break;
case MFn::kEnumAttribute:
{
switch(getAttributeType(usdAttr))
{
case UsdDataType::kInt:
{
if(!isArray)
{
int32_t value;
getInt32(node, attribute, value);
usdAttr.Set(value, timeCode);
}
else
{
VtArray<int> m;
m.resize(plug.numElements());
getInt32Array(node, attribute, m.data(), m.size());
usdAttr.Set(m, timeCode);
}
}
}
}
break;
case MFn::kTypedAttribute:
{
MFnTypedAttribute fnTyped(plug.attribute());
MFnData::Type type = fnTyped.attrType();
switch(type)
{
case MFnData::kString:
{
std::string value;
getString(node, attribute, value);
usdAttr.Set(value, timeCode);
}
break;
case MFnData::kMatrixArray:
{
MFnMatrixArrayData fnData(plug.asMObject());
VtArray<GfMatrix4d> m;
m.assign((const GfMatrix4d*)&fnData.array()[0], ((const GfMatrix4d*)&fnData.array()[0]) + fnData.array().length());
usdAttr.Set(m, timeCode);
}
break;
default:
{
}
break;
}
}
break;
case MFn::kCompoundAttribute:
{
MFnCompoundAttribute fnCompound(plug.attribute());
{
if(fnCompound.numChildren() == 2)
{
MObject x = fnCompound.child(0);
MObject y = fnCompound.child(1);
if(x.apiType() == MFn::kCompoundAttribute &&
y.apiType() == MFn::kCompoundAttribute)
{
MFnCompoundAttribute fnCompoundX(x);
MFnCompoundAttribute fnCompoundY(y);
if(fnCompoundX.numChildren() == 2 && fnCompoundY.numChildren() == 2)
{
MObject xx = fnCompoundX.child(0);
MObject xy = fnCompoundX.child(1);
MObject yx = fnCompoundY.child(0);
MObject yy = fnCompoundY.child(1);
if(xx.apiType() == MFn::kNumericAttribute &&
xy.apiType() == MFn::kNumericAttribute &&
yx.apiType() == MFn::kNumericAttribute &&
yy.apiType() == MFn::kNumericAttribute)
{
if(!isArray)
{
GfMatrix2d value;
getMatrix2x2(node, attribute, (double*)&value);
usdAttr.Set(value, timeCode);
}
else
{
VtArray<GfMatrix2d> value;
value.resize(plug.numElements());
getMatrix2x2Array(node, attribute, (double*)value.data(), plug.numElements());
usdAttr.Set(value, timeCode);
}
}
}
}
}
else
if(fnCompound.numChildren() == 3)
{
MObject x = fnCompound.child(0);
MObject y = fnCompound.child(1);
MObject z = fnCompound.child(2);
if(x.apiType() == MFn::kCompoundAttribute &&
y.apiType() == MFn::kCompoundAttribute &&
z.apiType() == MFn::kCompoundAttribute)
{
MFnCompoundAttribute fnCompoundX(x);
MFnCompoundAttribute fnCompoundY(y);
MFnCompoundAttribute fnCompoundZ(z);
if(fnCompoundX.numChildren() == 3 && fnCompoundY.numChildren() == 3 && fnCompoundZ.numChildren() == 3)
{
MObject xx = fnCompoundX.child(0);
MObject xy = fnCompoundX.child(1);
MObject xz = fnCompoundX.child(2);
MObject yx = fnCompoundY.child(0);
MObject yy = fnCompoundY.child(1);
MObject yz = fnCompoundY.child(2);
MObject zx = fnCompoundZ.child(0);
MObject zy = fnCompoundZ.child(1);
MObject zz = fnCompoundZ.child(2);
if(xx.apiType() == MFn::kNumericAttribute &&
xy.apiType() == MFn::kNumericAttribute &&
xz.apiType() == MFn::kNumericAttribute &&
yx.apiType() == MFn::kNumericAttribute &&
yy.apiType() == MFn::kNumericAttribute &&
yz.apiType() == MFn::kNumericAttribute &&
zx.apiType() == MFn::kNumericAttribute &&
zy.apiType() == MFn::kNumericAttribute &&
zz.apiType() == MFn::kNumericAttribute)
{
if(!isArray)
{
GfMatrix3d value;
getMatrix3x3(node, attribute, (double*)&value);
usdAttr.Set(value, timeCode);
}
else
{
VtArray<GfMatrix3d> value;
value.resize(plug.numElements());
getMatrix3x3Array(node, attribute, (double*)value.data(), plug.numElements());
usdAttr.Set(value, timeCode);
}
}
}
}
}
else
if(fnCompound.numChildren() == 4)
{
MObject x = fnCompound.child(0);
MObject y = fnCompound.child(1);
MObject z = fnCompound.child(2);
MObject w = fnCompound.child(3);
if(x.apiType() == MFn::kNumericAttribute &&
y.apiType() == MFn::kNumericAttribute &&
z.apiType() == MFn::kNumericAttribute &&
w.apiType() == MFn::kNumericAttribute)
{
MFnNumericAttribute fnx(x);
MFnNumericAttribute fny(y);
MFnNumericAttribute fnz(z);
MFnNumericAttribute fnw(w);
MFnNumericData::Type typex = fnx.unitType();
MFnNumericData::Type typey = fny.unitType();
MFnNumericData::Type typez = fnz.unitType();
MFnNumericData::Type typew = fnw.unitType();
if(typex == typey && typex == typez && typex == typew)
{
switch(typex)
{
case MFnNumericData::kInt:
{
if(!isArray)
{
GfVec4i value;
getVec4(node, attribute, (int32_t*)&value);
usdAttr.Set(value, timeCode);
}
else
{
VtArray<GfVec4i> value;
value.resize(plug.numElements());
getVec4Array(node, attribute, (int32_t*)value.data(), value.size());
usdAttr.Set(value, timeCode);
}
}
break;
case MFnNumericData::kFloat:
{
if(!isArray)
{
GfVec4f value;
getVec4(node, attribute, (float*)&value);
usdAttr.Set(value, timeCode);
}
else
{
VtArray<GfVec4f> value;
value.resize(plug.numElements());
getVec4Array(node, attribute, (float*)value.data(), value.size());
usdAttr.Set(value, timeCode);
}
}
break;
case MFnNumericData::kDouble:
{
if(!isArray)
{
GfVec4d value;
getVec4(node, attribute, (double*)&value);
usdAttr.Set(value, timeCode);
}
else
{
VtArray<GfVec4d> value;
value.resize(plug.numElements());
getVec4Array(node, attribute, (double*)value.data(), value.size());
usdAttr.Set(value, timeCode);
}
}
break;
default: break;
}
}
}
}
}
}
break;
case MFn::kFloatMatrixAttribute:
case MFn::kMatrixAttribute:
{
if(!isArray)
{
GfMatrix4d m;
getMatrix4x4(node, attribute, (double*)&m);
usdAttr.Set(m, timeCode);
}
else
{
VtArray<GfMatrix4d> value;
value.resize(plug.numElements());
getMatrix4x4Array(node, attribute, (double*)value.data(), value.size());
usdAttr.Set(value, timeCode);
}
}
break;
default: break;
}
}
//----------------------------------------------------------------------------------------------------------------------
void DgNodeHelper::copySimpleValue(const MPlug& plug, UsdAttribute& usdAttr, const float scale, const UsdTimeCode& timeCode)
{
MObject node = plug.node();
MObject attribute = plug.attribute();
bool isArray = plug.isArray();
switch(getAttributeType(usdAttr))
{
case UsdDataType::kFloat:
if(!isArray)
{
float value;
getFloat(node, attribute, value);
usdAttr.Set(value * scale, timeCode);
}
else
{
VtArray<float> m;
m.resize(plug.numElements());
getFloatArray(node, attribute, (float*)m.data(), m.size());
for(auto it = m.begin(), e = m.end(); it != e; ++it)
{
*it *= scale;
}
usdAttr.Set(m, timeCode);
}
break;
case UsdDataType::kDouble:
if(!isArray)
{
double value;
getDouble(node, attribute, value);
usdAttr.Set(value * scale, timeCode);
}
else
{
VtArray<double> m;
m.resize(plug.numElements());
getDoubleArray(node, attribute, (double*)m.data(), m.size());
double temp = scale;
for(auto it = m.begin(), e = m.end(); it != e; ++it)
{
*it *= temp;
}
usdAttr.Set(m, timeCode);
}
break;
default:
break;
}
}
//----------------------------------------------------------------------------------------------------------------------
void DgNodeHelper::copyAttributeValue(const MPlug& plug, UsdAttribute& usdAttr, const float scale, const UsdTimeCode& timeCode)
{
MObject node = plug.node();
MObject attribute = plug.attribute();
bool isArray = plug.isArray();
switch(attribute.apiType())
{
case MFn::kAttribute2Double:
case MFn::kAttribute2Float:
case MFn::kAttribute2Int:
case MFn::kAttribute2Short:
{
switch(getAttributeType(usdAttr))
{
case UsdDataType::kVec2d:
if(!isArray)
{
GfVec2d m;
getVec2(node, attribute, (double*)&m);
m *= scale;
usdAttr.Set(m, timeCode);
}
else
{
VtArray<GfVec2d> m;
m.resize(plug.numElements());
getVec2Array(node, attribute, (double*)m.data(), m.size());
double temp = scale;
for(auto it = m.begin(), e = m.end(); it != e; ++it)
{
*it *= temp;
}
usdAttr.Set(m, timeCode);
}
break;
case UsdDataType::kVec2f:
if(!isArray)
{
GfVec2f m;
getVec2(node, attribute, (float*)&m);
m *= scale;
usdAttr.Set(m, timeCode);
}
else
{
VtArray<GfVec2f> m;
m.resize(plug.numElements());
getVec2Array(node, attribute, (float*)m.data(), m.size());
for(auto it = m.begin(), e = m.end(); it != e; ++it)
{
*it *= scale;
}
usdAttr.Set(m, timeCode);
}
break;
default:
break;
}
}
break;
case MFn::kAttribute3Double:
case MFn::kAttribute3Float:
case MFn::kAttribute3Long:
case MFn::kAttribute3Short:
{
switch(getAttributeType(usdAttr))
{
case UsdDataType::kVec3d:
if(!isArray)
{
GfVec3d m;
getVec3(node, attribute, (double*)&m);
m *= scale;
usdAttr.Set(m, timeCode);
}
else
{
VtArray<GfVec3d> m;
m.resize(plug.numElements());
getVec3Array(node, attribute, (double*)m.data(), m.size());
double temp = scale;
for(auto it = m.begin(), e = m.end(); it != e; ++it)
{
*it *= temp;
}
usdAttr.Set(m, timeCode);
}
break;
case UsdDataType::kVec3f:
if(!isArray)
{
GfVec3f m;
getVec3(node, attribute, (float*)&m);
m *= scale;
usdAttr.Set(m, timeCode);
}
else
{
VtArray<GfVec3f> m;
m.resize(plug.numElements());
getVec3Array(node, attribute, (float*)m.data(), m.size());
for(auto it = m.begin(), e = m.end(); it != e; ++it)
{
*it *= scale;
}
usdAttr.Set(m, timeCode);
}
break;
default:
break;
}
}
break;
case MFn::kAttribute4Double:
{
switch(getAttributeType(usdAttr))
{
case UsdDataType::kVec4d:
if(!isArray)
{
GfVec4d m;
getVec4(node, attribute, (double*)&m);
m *= scale;
usdAttr.Set(m, timeCode);
}
else
{
VtArray<GfVec4d> m;
m.resize(plug.numElements());
getVec4Array(node, attribute, (double*)m.data(), m.size());
double temp = scale;
for(auto it = m.begin(), e = m.end(); it != e; ++it)
{
*it *= temp;
}
usdAttr.Set(m, timeCode);
}
break;
case UsdDataType::kVec4f:
if(!isArray)
{
GfVec4f m;
getVec4(node, attribute, (float*)&m);
m *= scale;
usdAttr.Set(m, timeCode);
}
else
{
VtArray<GfVec4f> m;
m.resize(plug.numElements());
getVec4Array(node, attribute, (float*)m.data(), m.size());
for(auto it = m.begin(), e = m.end(); it != e; ++it)
{
*it *= scale;
}
usdAttr.Set(m, timeCode);
}
break;
default:
break;
}
}
break;
case MFn::kNumericAttribute:
{
MFnNumericAttribute fn(attribute);
switch(fn.unitType())
{
case MFnNumericData::kFloat:
case MFnNumericData::kDouble:
case MFnNumericData::kInt:
case MFnNumericData::kShort:
case MFnNumericData::kInt64:
case MFnNumericData::kByte:
case MFnNumericData::kChar:
{
copySimpleValue(plug, usdAttr, scale, timeCode);
}
break;
default:
{
}
break;
}
}
break;
case MFn::kTimeAttribute:
case MFn::kFloatAngleAttribute:
case MFn::kDoubleAngleAttribute:
case MFn::kDoubleLinearAttribute:
case MFn::kFloatLinearAttribute:
{
copySimpleValue(plug, usdAttr, scale, timeCode);
}
break;
default: break;
}
}
//----------------------------------------------------------------------------------------------------------------------
} // utils
} // usdmaya
} // AL
//----------------------------------------------------------------------------------------------------------------------
| 215,503 | 76,855 |
/*
* Copyright (C) 2020 Frank Mertens.
*
* Distribution and use is allowed under the terms of the zlib license
* (see cc/LICENSE-zlib).
*
*/
#include <cc/Application>
#include <cc/TimeMaster>
#include <cc/PlatformPlugin>
#include <cc/PosGuard>
#include <cc/InputControl>
#include <cc/Process>
#include <cc/Bmp>
#include <cc/stdio>
namespace cc {
void Application::State::notifyTimer(const Timer &timer)
{
if (!timer) return;
if (timer.interval() > 0) {
TimeMaster{}.ack();
}
timer.me().timeout_.emit();
}
Application::State::State()
{
textInputArea.onChanged([this]{
if (focusControl())
setTextInputArea(textInputArea());
});
focusControl.onChanged([this]{
if (focusControlSaved_) stopTextInput();
focusControlSaved_ = focusControl();
if (focusControl()) {
startTextInput(focusControl().window());
textInputArea([this]{
if (!focusControl()) return Rect{};
Rect a = focusControl().me().textInputArea();
return Rect{focusControl().mapToGlobal(a.pos()), a.size()};
});
setTextInputArea(textInputArea());
}
else
textInputArea = Rect{};
});
cursorControl.onChanged([this]{
if (cursorControl()) {
cursor([this]{
return cursorControl() ? cursorControl().cursor() : Cursor{};
});
}
else {
cursor = Cursor{};
}
});
cursor.onChanged([this]{
if (cursor()) setCursor(cursor());
else unsetCursor();
});
}
bool Application::State::feedFingerEvent(const Window &window, FingerEvent &event)
{
if (cursorControl()) cursorControl = Control{};
if (hoverControl()) hoverControl = Control{};
showCursor(false);
Point eventPos = window.size() * event.pos();
Control topControl = window.findControl(eventPos);
if (topControl) {
topControl->pointerPos = topControl.mapToLocal(eventPos);
}
if (event.action() == PointerAction::Moved)
;
else if (event.action() == PointerAction::Pressed)
{
if (!pressedControl()) {
pressedControl = topControl;
}
}
else if (event.action() == PointerAction::Released)
{
if (focusControl() != pressedControl()) {
focusControl = Control{};
}
}
bool eaten = false;
if (pressedControl())
{
eaten = pressedControl()->feedFingerEvent(event);
if (event.action() == PointerAction::Released)
{
PosGuard guard{event, pressedControl().mapToLocal(eventPos)};
if (
pressedControl()->onPointerClicked(event) ||
pressedControl()->onFingerClicked(event)
) {
eaten = true;
}
pressedControl = Control{};
}
}
if (!eaten) {
eaten = window.view()->feedFingerEvent(event);
}
return eaten;
}
bool Application::State::feedMouseEvent(const Window &window, MouseEvent &event)
{
Control topControl = window.findControl(event.pos());
if (topControl) {
topControl->pointerPos = topControl.mapToLocal(event.pos());
}
if (event.action() == PointerAction::Moved)
{
hoverControl = topControl;
}
else if (event.action() == PointerAction::Pressed)
{
if (!pressedControl()) {
pressedControl = topControl;
if (topControl) captureMouse(true);
}
hoverControl = Control{};
}
else if (event.action() == PointerAction::Released)
{
if (focusControl() != pressedControl()) {
focusControl = Control{};
}
hoverControl = topControl;
}
bool eaten = false;
if (pressedControl())
{
eaten = pressedControl()->feedMouseEvent(event);
if (event.action() == PointerAction::Released)
{
PosGuard guard{event, pressedControl().mapToLocal(event.pos())};
if (
pressedControl()->onPointerClicked(event) ||
pressedControl()->onMouseClicked(event)
) {
eaten = true;
}
pressedControl = Control{};
captureMouse(false);
}
}
if (!eaten) {
eaten = window.view()->feedMouseEvent(event);
}
cursorControl = topControl;
showCursor(true);
return eaten;
}
bool Application::State::feedWheelEvent(const Window &window, WheelEvent &event)
{
bool eaten = false;
if (hoverControl()) eaten = hoverControl().me().feedWheelEvent(event);
if (!eaten) eaten = window.view().me().feedWheelEvent(event);
return eaten;
}
bool Application::State::feedKeyEvent(const Window &window, KeyEvent &event)
{
if (
event.scanCode() == ScanCode::Key_ScrollLock &&
event.action() == KeyAction::Pressed
) {
takeScreenshot(window);
return true;
}
if (focusControl()) {
return focusControl().me().feedKeyEvent(event);
}
if (
event.scanCode() == ScanCode::Key_Tab &&
event.action() == KeyAction::Pressed &&
!(event.modifiers() & KeyModifier::Shift) &&
!(event.modifiers() & KeyModifier::Alt) &&
!(event.modifiers() & KeyModifier::Control)
) {
List<InputControl> inputControls;
window.view().collectVisible<InputControl>(&inputControls);
if (inputControls.count() > 0) {
inputControls.mutableAt(0).focus(true);
}
}
return true;
}
bool Application::State::feedExposedEvent(const Window &window)
{
return window.view().me().feedExposedEvent();
}
bool Application::State::feedEnterEvent(const Window &window)
{
return window.view().me().feedEnterEvent();
}
bool Application::State::feedLeaveEvent(const Window &window)
{
hoverControl = Control{};
return window.view().me().feedLeaveEvent();
}
bool Application::State::feedTextEditingEvent(const String &text, int start, int length)
{
if (focusControl()) {
focusControl().me().onTextEdited(text, start, length);
return true;
}
return false;
}
bool Application::State::feedTextInputEvent(const String &text)
{
if (focusControl()) {
focusControl().me().onTextInput(text);
return true;
}
return false;
}
void Application::State::takeScreenshot(const Window &window)
{
View view = window.view();
Image image{view.size()};
String path = Format{"%%.bmp"}.arg(fixed(System::now(), 0));
view.renderTo(image);
Bmp::save(path, image);
ferr() << "Written screenshot to file://" << Process::cwd() << "/" << path << nl;
}
void Application::State::disengage(const View &view)
{
if (view.isParentOf(hoverControl())) {
hoverControl(Control{});
}
if (view.isParentOf(pressedControl())) {
pressedControl(Control{});
}
if (view.isParentOf(focusControl())) {
focusControl(Control{});
}
if (view.isParentOf(cursorControl())) {
cursorControl(Control{});
}
if (view.isParentOf(focusControlSaved_)) {
focusControlSaved_ = Control{};
}
}
Application::Application()
{
*this = platform().application();
}
Application::Application(int argc, char *argv[])
{
*this = platform().application();
me().init(argc, argv);
}
FontSmoothing Application::fontSmoothing() const
{
if (me().fontSmoothing_ == FontSmoothing::Default)
return DisplayManager{}.defaultFontSmoothing();
return me().fontSmoothing_;
}
bool Application::pointerIsDragged(const PointerEvent &event, Point dragStart) const
{
double minDragDistance = event.is<MouseEvent>() ? minMouseDragDistance() : minFingerDragDistance();
return (event.pos() - dragStart).absPow2() >= minDragDistance * minDragDistance;
}
void Application::postEvent(Fun<void()> &&doNext)
{
me().postEvent(move(doNext));
}
Application app()
{
return platform().application();
}
} // namespace cc
| 8,072 | 2,381 |
#ifndef COIO_CPU_AFFINITY
#define COIO_CPU_AFFINITY
#include <sched.h>
#include <sys/syscall.h>
#include <unistd.h>
namespace coio {
static inline bool reset_cpu_affinity(int cpuno) {
cpu_set_t mask;
CPU_ZERO(&mask);
CPU_SET(cpuno, &mask);
auto tid = syscall(SYS_gettid);
return sched_setaffinity(tid, sizeof(mask), &mask) != -1;
}
} // namespace coio
#endif | 374 | 163 |
// Copyright 2019 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "biod/ec_command.h"
using testing::_;
using testing::InvokeWithoutArgs;
using testing::Return;
namespace biod {
namespace {
constexpr int kDummyFd = 0;
constexpr int kIoctlFailureRetVal = -1;
template <typename O, typename I>
class MockEcCommand : public EcCommand<O, I> {
public:
using EcCommand<O, I>::EcCommand;
~MockEcCommand() override = default;
using Data = typename EcCommand<O, I>::Data;
MOCK_METHOD(int, ioctl, (int fd, uint32_t request, Data* data));
};
class MockFpModeCommand : public MockEcCommand<struct ec_params_fp_mode,
struct ec_response_fp_mode> {
public:
MockFpModeCommand() : MockEcCommand(EC_CMD_FP_MODE, 0, {.mode = 1}) {}
};
// ioctl behavior for EC commands:
// returns sizeof(EC response) (>=0) on success, -1 on failure
// cmd.result is error code from EC (EC_RES_SUCCESS, etc)
TEST(EcCommand, Run_Success) {
MockFpModeCommand mock;
EXPECT_CALL(mock, ioctl).WillOnce(Return(mock.RespSize()));
EXPECT_TRUE(mock.Run(kDummyFd));
}
TEST(EcCommand, Run_IoctlFailure) {
MockFpModeCommand mock;
EXPECT_CALL(mock, ioctl).WillOnce(Return(kIoctlFailureRetVal));
EXPECT_FALSE(mock.Run(kDummyFd));
}
TEST(EcCommand, Run_CommandFailure) {
MockFpModeCommand mock;
EXPECT_CALL(mock, ioctl)
.WillOnce([](int, uint32_t, MockFpModeCommand::Data* data) {
// Test the case where the ioctl itself succeeds, the but the EC
// command did not. In this case, "result" will be set, but the
// response size will not match the command's response size.
data->cmd.result = EC_RES_ACCESS_DENIED;
return 0;
});
EXPECT_FALSE(mock.Run(kDummyFd));
}
TEST(EcCommand, ConstReq) {
const MockFpModeCommand mock;
EXPECT_TRUE(mock.Req());
}
TEST(EcCommand, ConstResp) {
const MockFpModeCommand mock;
EXPECT_TRUE(mock.Resp());
}
TEST(EcCommand, Run_CheckResult_Success) {
constexpr int kExpectedResult = 42;
MockFpModeCommand mock;
EXPECT_CALL(mock, ioctl)
.WillOnce([](int, uint32_t, MockFpModeCommand::Data* data) {
data->cmd.result = kExpectedResult;
return data->cmd.insize;
});
EXPECT_TRUE(mock.Run(kDummyFd));
EXPECT_EQ(mock.Result(), kExpectedResult);
}
TEST(EcCommand, Run_CheckResult_Failure) {
MockFpModeCommand mock;
EXPECT_CALL(mock, ioctl)
.WillOnce([](int, uint32_t, MockFpModeCommand::Data* data) {
// Note that it's not expected that the result would be set by the
// kernel driver in this case, but we want to be defensive against
// the behavior in case there is an instance where it does.
data->cmd.result = EC_RES_ERROR;
return kIoctlFailureRetVal;
});
EXPECT_FALSE(mock.Run(kDummyFd));
EXPECT_EQ(mock.Result(), kEcCommandUninitializedResult);
}
TEST(EcCommand, RunWithMultipleAttempts_Success) {
constexpr int kNumAttempts = 2;
MockFpModeCommand mock;
EXPECT_CALL(mock, ioctl)
.Times(kNumAttempts)
// First ioctl() fails
.WillOnce(InvokeWithoutArgs([]() {
errno = ETIMEDOUT;
return kIoctlFailureRetVal;
}))
// Second ioctl() succeeds
.WillOnce(Return(mock.RespSize()));
EXPECT_TRUE(mock.RunWithMultipleAttempts(kDummyFd, kNumAttempts));
}
TEST(EcCommand, RunWithMultipleAttempts_Timeout_Failure) {
constexpr int kNumAttempts = 2;
MockFpModeCommand mock;
EXPECT_CALL(mock, ioctl)
.Times(kNumAttempts)
// All calls to ioctl() timeout
.WillRepeatedly(InvokeWithoutArgs([]() {
errno = ETIMEDOUT;
return kIoctlFailureRetVal;
}));
EXPECT_FALSE(mock.RunWithMultipleAttempts(kDummyFd, kNumAttempts));
}
TEST(EcCommand, RunWithMultipleAttempts_ErrorNotTimeout_Failure) {
constexpr int kNumAttempts = 2;
MockFpModeCommand mock;
EXPECT_CALL(mock, ioctl)
// Errors other than timeout should cause immediate failure even when
// attempting retries.
.Times(1)
.WillOnce(InvokeWithoutArgs([]() {
errno = EINVAL;
return kIoctlFailureRetVal;
}));
EXPECT_FALSE(mock.RunWithMultipleAttempts(kDummyFd, kNumAttempts));
}
} // namespace
} // namespace biod
| 4,395 | 1,587 |
// boost/detail/bitmask.hpp ------------------------------------------------//
// Copyright Beman Dawes 2006
// Distributed under the Boost Software License, Version 1.0
// http://www.boost.org/LICENSE_1_0.txt
// Usage: enum foo { a=1, b=2, c=4 };
// BOOST_BITMASK( foo )
//
// void f( foo arg );
// ...
// f( a | c );
//
// See [bitmask.types] in the C++ standard for the formal specification
#ifndef BOOST_BITMASK_HPP
#define BOOST_BITMASK_HPP
#include <boost/config.hpp>
#include <boost/cstdint.hpp>
#define BOOST_BITMASK(Bitmask) \
\
inline BOOST_CONSTEXPR Bitmask operator| (Bitmask x , Bitmask y ) \
{ return static_cast<Bitmask>( static_cast<boost::int_least32_t>(x) \
| static_cast<boost::int_least32_t>(y)); } \
\
inline BOOST_CONSTEXPR Bitmask operator& (Bitmask x , Bitmask y ) \
{ return static_cast<Bitmask>( static_cast<boost::int_least32_t>(x) \
& static_cast<boost::int_least32_t>(y)); } \
\
inline BOOST_CONSTEXPR Bitmask operator^ (Bitmask x , Bitmask y ) \
{ return static_cast<Bitmask>( static_cast<boost::int_least32_t>(x) \
^ static_cast<boost::int_least32_t>(y)); } \
\
inline BOOST_CONSTEXPR Bitmask operator~ (Bitmask x ) \
{ return static_cast<Bitmask>(~static_cast<boost::int_least32_t>(x)); } \
\
inline Bitmask & operator&=(Bitmask& x , Bitmask y) \
{ x = x & y ; return x ; } \
\
inline Bitmask & operator|=(Bitmask& x , Bitmask y) \
{ x = x | y ; return x ; } \
\
inline Bitmask & operator^=(Bitmask& x , Bitmask y) \
{ x = x ^ y ; return x ; } \
\
/* Boost extensions to [bitmask.types] */ \
\
inline BOOST_CONSTEXPR bool operator!(Bitmask x) \
{ return !static_cast<int>(x); } \
\
inline BOOST_CONSTEXPR bool bitmask_set(Bitmask x) \
{ return !!x; }
#endif // BOOST_BITMASK_HPP
| 3,091 | 850 |
#include "AliAnalysisTaskEventCutsValidation.h"
// ROOT includes
#include <TChain.h>
#include <TH2F.h>
#include <TList.h>
// ALIROOT includes
#include "AliAODEvent.h"
#include "AliAODHeader.h"
#include "AliAODTrack.h"
#include "AliESDEvent.h"
#include "AliESDtrack.h"
#include "AliVEvent.h"
///\cond CLASSIMP
ClassImp(AliAnalysisTaskEventCutsValidation);
///\endcond
/// Standard and default constructor of the class.
///
/// \param taskname Name of the task
/// \param partname Name of the analysed particle
///
AliAnalysisTaskEventCutsValidation::AliAnalysisTaskEventCutsValidation(bool storeCuts, TString taskname) :
AliAnalysisTaskSE(taskname.Data()),
fEventCut(false),
fList(nullptr),
fStoreCuts(storeCuts)
{
DefineInput(0, TChain::Class());
DefineOutput(1, TList::Class());
if (storeCuts) DefineOutput(2, AliEventCuts::Class());
}
/// Standard destructor
///
AliAnalysisTaskEventCutsValidation::~AliAnalysisTaskEventCutsValidation() {
if (fList) delete fList;
}
/// This function creates all the histograms and all the objects in general used during the analysis
/// \return void
///
void AliAnalysisTaskEventCutsValidation::UserCreateOutputObjects() {
fList = new TList();
fList->SetOwner(true);
fEventCut.AddQAplotsToList(fList,true);
PostData(1,fList);
if (fStoreCuts) PostData(2,&fEventCut);
}
/// This is the function that is evaluated for each event. The analysis code stays here.
///
/// \param options Deprecated parameter
/// \return void
///
void AliAnalysisTaskEventCutsValidation::UserExec(Option_t *) {
AliVEvent* ev = InputEvent();
fEventCut.AcceptEvent(ev);
PostData(1,fList);
if (fStoreCuts) PostData(2,&fEventCut);
return;
}
/// Merge the output. Called once at the end of the query.
///
/// \return void
///
void AliAnalysisTaskEventCutsValidation::Terminate(Option_t *) {
return;
}
| 1,857 | 648 |
#include "linetestviewer.h"
#ifdef LINETEST
#include "tapp.h"
#include "viewerdraw.h"
#include "timagecache.h"
#include "tgl.h"
#include "trop.h"
#include "toonz/txsheethandle.h"
#include "toonz/tframehandle.h"
#include "toonz/tcolumnhandle.h"
#include "toonz/txshlevelhandle.h"
#include "toonz/tobjecthandle.h"
#include "toonz/txshsimplelevel.h"
#include "toonz/stage2.h"
#include "toonz/stagevisitor.h"
#include "toonz/tonionskinmaskhandle.h"
#include "toonz/imagemanager.h"
#include "toonz/tstageobjecttree.h"
#include "toonz/childstack.h"
#include "toonz/dpiscale.h"
#include "toonz/toonzscene.h"
#include "toonz/sceneproperties.h"
#include "toonz/tcamera.h"
#include "tools/toolhandle.h"
#include "tools/cursormanager.h"
#include "tools/toolcommandids.h"
#include "toonzqt/menubarcommand.h"
#include "toonzqt/imageutils.h"
#include <QPainter>
#include <QPaintEvent>
#include <QApplication>
#include <QInputContext>
#include <QMenu>
#ifndef USE_QPAINTER
GLshort vertices[] = {
0, 1, 0,
0, 0, 0,
1, 0, 0,
1, 1, 0};
GLshort coords[] = {
0, 1,
0, 0,
1, 0,
1, 1};
// function pointers for PBO Extension
// Windows needs to get function pointers from ICD OpenGL drivers,
// because opengl32.dll does not support extensions higher than v1.1.
#ifdef _WIN32
PFNGLGENBUFFERSARBPROC pglGenBuffersARB = 0; // VBO Name Generation Procedure
PFNGLBINDBUFFERARBPROC pglBindBufferARB = 0; // VBO Bind Procedure
PFNGLBUFFERDATAARBPROC pglBufferDataARB = 0; // VBO Data Loading Procedure
PFNGLBUFFERSUBDATAARBPROC pglBufferSubDataARB = 0; // VBO Sub Data Loading Procedure
PFNGLDELETEBUFFERSARBPROC pglDeleteBuffersARB = 0; // VBO Deletion Procedure
PFNGLGETBUFFERPARAMETERIVARBPROC pglGetBufferParameterivARB = 0; // return various parameters of VBO
PFNGLMAPBUFFERARBPROC pglMapBufferARB = 0; // map VBO procedure
PFNGLUNMAPBUFFERARBPROC pglUnmapBufferARB = 0; // unmap VBO procedure
#define glGenBuffersARB pglGenBuffersARB
#define glBindBufferARB pglBindBufferARB
#define glBufferDataARB pglBufferDataARB
#define glBufferSubDataARB pglBufferSubDataARB
#define glDeleteBuffersARB pglDeleteBuffersARB
#define glGetBufferParameterivARB pglGetBufferParameterivARB
#define glMapBufferARB pglMapBufferARB
#define glUnmapBufferARB pglUnmapBufferARB
#endif
#endif //USE_QPAINTER
//-----------------------------------------------------------------------------
namespace
{
//-----------------------------------------------------------------------------
void initToonzEvent(TMouseEvent &toonzEvent, QMouseEvent *event,
int widgetHeight, double pressure, bool isTablet)
{
toonzEvent.m_pos = TPoint(event->pos().x(), widgetHeight - 1 - event->pos().y());
toonzEvent.setModifiers(event->modifiers() & Qt::ShiftModifier,
event->modifiers() & Qt::AltModifier,
event->modifiers() & Qt::CtrlModifier);
if (isTablet)
toonzEvent.m_pressure = (int)(255 * pressure);
else
toonzEvent.m_pressure = 255;
}
//-----------------------------------------------------------------------------
class ViewerZoomer : public ImageUtils::ShortcutZoomer
{
public:
ViewerZoomer(QWidget *parent) : ShortcutZoomer(parent) {}
void zoom(bool zoomin, bool resetZoom)
{
if (resetZoom)
((LineTestViewer *)getWidget())->resetView();
else
((LineTestViewer *)getWidget())->zoomQt(zoomin, resetZoom);
}
void fit()
{
//((LineTestViewer*)getWidget())->fitToCamera();
}
void setActualPixelSize()
{
//((LineTestViewer*)getWidget())->setActualPixelSize();
}
};
//-----------------------------------------------------------------------------
} //namespace
//-----------------------------------------------------------------------------
// definito - per ora - in tapp.cpp
extern string updateToolEnableStatus(TTool *tool);
//=============================================================================
// LineTestViewer
//-----------------------------------------------------------------------------
LineTestViewer::LineTestViewer(QWidget *parent)
#ifdef USE_QPAINTER
: QWidget(parent)
#else
: QGLWidget(parent)
//, m_pboSupported(false)
#endif //USE_QPAINTER
,
m_pos(), m_mouseButton(Qt::NoButton), m_viewAffine()
{
m_viewAffine = getNormalZoomScale();
setMouseTracking(true);
}
//-----------------------------------------------------------------------------
LineTestViewer::~LineTestViewer()
{
//#ifndef USE_QPAINTER
// clean up PBO
//if(m_pboSupported)
// glDeleteBuffersARB(1, &m_pboId);
//#endif //USE_QPAINTER
}
//-----------------------------------------------------------------------------
TPointD LineTestViewer::winToWorld(const QPoint &pos) const
{
// coordinate window (origine in alto a sinistra) -> coordinate colonna (origine al centro dell'immagine)
TPointD pp(pos.x() - width() * 0.5, -pos.y() + height() * 0.5);
return getViewMatrix().inv() * pp;
}
//-----------------------------------------------------------------------------
TPointD LineTestViewer::winToWorld(const TPoint &winPos) const
{
return winToWorld(QPoint(winPos.x, height() - winPos.y));
}
//-----------------------------------------------------------------------------
void LineTestViewer::resetInputMethod()
{
qApp->inputContext()->reset();
}
//-----------------------------------------------------------------------------
TAffine LineTestViewer::getViewMatrix() const
{
int frame = TApp::instance()->getCurrentFrame()->getFrame();
TXsheet *xsh = TApp::instance()->getCurrentXsheet()->getXsheet();
TAffine aff = xsh->getCameraAff(frame);
return m_viewAffine * aff.inv();
}
//-----------------------------------------------------------------------------
#ifdef USE_QPAINTER
void LineTestViewer::paintEvent(QPaintEvent *)
{
QPainter p(this);
p.begin(this);
p.resetMatrix();
TApp *app = TApp::instance();
ToonzScene *scene = app->getCurrentScene()->getScene();
p.fillRect(visibleRegion().boundingRect(), QBrush(QColor(Qt::white)));
TPixel32 cameraBgColor = scene->getProperties()->getBgColor();
TPixel32 viewerBgColor = scene->getProperties()->getViewerBgColor();
p.fillRect(visibleRegion().boundingRect(), QBrush(QColor(viewerBgColor.r, viewerBgColor.g, viewerBgColor.b, viewerBgColor.m)));
int h = height();
int w = width();
TDimension viewerSize(w, h);
TRect clipRect(viewerSize);
clipRect -= TPoint(viewerSize.lx * 0.5, viewerSize.ly * 0.5);
TAffine viewAff = getViewMatrix();
Stage::RasterPainter stagePainter(viewerSize, viewAff, clipRect, 0, true);
TFrameHandle *frameHandle = app->getCurrentFrame();
if (app->getCurrentFrame()->isEditingLevel()) {
Stage::visit(stagePainter,
app->getCurrentLevel()->getLevel(),
app->getCurrentFrame()->getFid(),
OnionSkinMask(),
frameHandle->isPlaying());
} else {
int xsheetLevel = 0;
TXsheet *xsh = app->getCurrentXsheet()->getXsheet();
int frame = app->getCurrentFrame()->getFrame();
Stage::VisitArgs args;
args.scene = scene;
args.xsh = xsh;
args.row = frame;
args.currentColumnIndex = app->getCurrentColumn()->getColumnIndex();
OnionSkinMask osm = app->getCurrentOnionSkin()->getOnionSkinMask();
args.osm = &osm;
args.xsheetLevel = xsheetLevel;
args.isPlaying = frameHandle->isPlaying();
args.onlyVisible = true;
args.checkPreviewVisibility = true;
Stage::visit(stagePainter, args);
}
//Draw camera rect and mask
TRectD rect = ViewerDraw::getCameraRect();
TXsheet *xsh = app->getCurrentXsheet()->getXsheet();
TStageObjectId cameraId = xsh->getStageObjectTree()->getCurrentCameraId();
int row = app->getCurrentFrame()->getFrameIndex();
double cameraZ = xsh->getZ(cameraId, row);
TAffine aff = xsh->getPlacement(cameraId, row) * TScale((1000 + cameraZ) / 1000);
aff = TAffine(1, 0, 0, 0, -1, viewerSize.ly) * TTranslation(viewerSize.lx * 0.5, viewerSize.ly * 0.5) * viewAff * aff;
QMatrix matrix(aff.a11, aff.a21, aff.a12, aff.a22, aff.a13, aff.a23);
QPolygon cameraPolygon(QRect(rect.getP00().x, rect.getP00().y, rect.getLx(), rect.getLy()));
cameraPolygon = cameraPolygon * matrix;
p.fillRect(cameraPolygon.boundingRect(), QBrush(QColor(cameraBgColor.r, cameraBgColor.g, cameraBgColor.b, cameraBgColor.m)));
stagePainter.drawRasterImages(p, cameraPolygon);
p.end();
}
#else
//-----------------------------------------------------------------------------
void LineTestViewer::initializeGL()
{
glClearColor(1.0f, 1.0f, 1.0f, 0.0f);
glPixelStorei(GL_UNPACK_ALIGNMENT, 4); // 4-byte pixel alignment
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_TEXTURE_2D);
//checkPBOSupport();
// Generater pbuffer
//if(m_pboSupported)
// glGenBuffersARB(1, &m_pboId);
}
//-----------------------------------------------------------------------------
void LineTestViewer::resizeGL(int width, int height)
{
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, width, 0, height, -1, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
// To maintain pixel accuracy
glTranslated(0.375, 0.375, 0.0);
}
//-----------------------------------------------------------------------------
//#include "tstopwatch.h"
void LineTestViewer::paintRaster(TRasterP ras)
{
//TStopWatch timer;
//TStopWatch timer2;
//timer.start();
//timer2.start();
int w = ras->getLx();
int h = ras->getLy();
vertices[1] = h;
vertices[6] = w;
vertices[9] = w;
vertices[10] = h;
int dataSize = w * h * 4;
//timer.stop();
//timer2.stop();
//qDebug("time 1: %d",timer.getTotalTime());
//timer.start(true);
//timer2.start();
/****************************************************************************************
ATTENZIONE!!! Qeesto codice potrebbe dare problemi!!!!!
quando si utilizzano le texture le loro dimensioni dovrebbero essere potenze di dur...
le nuove schede grafiche sembrerebbero funzionare lo stesso ma le vecchie a volte danno problemi!!!
Inoltre non viene fatto il controllo se le dimenzioni dei raster da disegnare superano le dimenzioni
supportate dalla scheda grafica... se cio' accade bisognerebbe spezzare il raster in due...
Questo codice sembra essere meolto veloce (cosa di cui abbiamo bisogno) ma puo' dare seri problemi!!!!
*****************************************************************************************/
ras->lock();
int pixelSize = ras->getPixelSize();
glGenTextures(1, &m_textureId);
glBindTexture(GL_TEXTURE_2D, m_textureId);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
if (pixelSize == 4)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, GL_BGRA, GL_UNSIGNED_BYTE, (GLvoid *)0);
else if (pixelSize == 1) {
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE8, w, h, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, (GLvoid *)0);
} else
return;
//if(m_pboSupported)
// {
// // bind PBO to update pixel values
// glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, m_pboId);
// // map the buffer object into client's memory
// // Note that glMapBufferARB() causes sync issue.
// // If GPU is working with this buffer, glMapBufferARB() will wait(stall)
// // for GPU to finish its job. To avoid waiting (stall), you can call
// // first glBufferDataARB() with NULL pointer before glMapBufferARB().
// // If you do that, the previous data in PBO will be discarded and
// // glMapBufferARB() returns a new allocated pointer immediately
// // even if GPU is still working with the previous data.
// glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, dataSize, 0, GL_STREAM_DRAW_ARB);
// GLubyte* ptr = (GLubyte*)glMapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, GL_WRITE_ONLY_ARB);
// if(ptr)
// {
// ras->lock();
// memcpy( ptr, ras->getRawData(), dataSize);
// glUnmapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB); // release pointer to mapping buffer
// ras->unlock();
// }
// // it is good idea to release PBOs with ID 0 after use.
// // Once bound with 0, all pixel operations behave normal ways.
// //glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0);
//
// // bind the texture and PBO
// glBindTexture(GL_TEXTURE_2D, m_textureId);
// glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, m_pboId);
// // copy pixels from PBO to texture object
// // Use offset instead of ponter.
// glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h, GL_BGRA, GL_UNSIGNED_BYTE, 0);
// }
// else
// {
// start to copy pixels from system memory to textrure object
glBindTexture(GL_TEXTURE_2D, m_textureId);
if (pixelSize == 4)
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h, GL_BGRA, GL_UNSIGNED_BYTE, (GLvoid *)ras->getRawData());
else if (pixelSize == 1)
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h, GL_LUMINANCE, GL_UNSIGNED_BYTE, (GLvoid *)ras->getRawData());
else
return;
ras->unlock();
// }
glEnable(GL_BLEND);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glVertexPointer(3, GL_SHORT, 0, vertices);
glTexCoordPointer(2, GL_SHORT, 0, &coords);
glDrawArrays(GL_QUADS, 0, 4);
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisable(GL_BLEND);
// clean up texture
glDeleteTextures(1, &m_textureId);
//timer.stop();
//timer2.stop();
//qDebug("time 2: %d",timer.getTotalTime());
//qDebug("total time: %d",timer2.getTotalTime());
}
//-----------------------------------------------------------------------------
void LineTestViewer::paintGL()
{
TApp *app = TApp::instance();
ToonzScene *scene = app->getCurrentScene()->getScene();
TPixel32 cameraBgColor = scene->getProperties()->getBgColor();
TPixel32 viewerBgColor = scene->getProperties()->getViewerBgColor();
glClearColor(viewerBgColor.r / 255.0, viewerBgColor.g / 255.0, viewerBgColor.b / 255.0, viewerBgColor.m / 255.0);
glClear(GL_COLOR_BUFFER_BIT);
int h = height();
int w = width();
TDimension viewerSize(w, h);
TRect clipRect(viewerSize);
//clipRect -= TPoint(viewerSize.lx*0.5,viewerSize.ly*0.5);
TAffine viewAff = getViewMatrix();
Stage::RasterPainter stagePainter(viewerSize, viewAff, clipRect, 0, true);
TFrameHandle *frameHandle = app->getCurrentFrame();
int frame = frameHandle->getFrame();
if (app->getCurrentFrame()->isEditingLevel()) {
Stage::visit(stagePainter,
app->getCurrentLevel()->getLevel(),
frameHandle->getFid(),
OnionSkinMask(),
frameHandle->isPlaying());
} else {
int xsheetLevel = 0;
TXsheet *xsh = app->getCurrentXsheet()->getXsheet();
Stage::VisitArgs args;
args.scene = scene;
args.xsh = xsh;
args.row = frame;
args.currentColumnIndex = app->getCurrentColumn()->getColumnIndex();
OnionSkinMask osm = app->getCurrentOnionSkin()->getOnionSkinMask();
args.osm = &osm;
args.xsheetLevel = xsheetLevel;
args.isPlaying = frameHandle->isPlaying();
args.onlyVisible = true;
args.checkPreviewVisibility = true;
Stage::visit(stagePainter, args);
}
//Draw camera rect and mask
TRectD cameraRect = ViewerDraw::getCameraRect();
TXsheet *xsh = app->getCurrentXsheet()->getXsheet();
TStageObjectId cameraId = xsh->getStageObjectTree()->getCurrentCameraId();
int row = frameHandle->getFrameIndex();
double cameraZ = xsh->getZ(cameraId, row);
TAffine aff = xsh->getPlacement(cameraId, row) * TScale((1000 + cameraZ) / 1000);
aff = TTranslation(viewerSize.lx * 0.5, viewerSize.ly * 0.5) * viewAff * aff;
QMatrix matrix(aff.a11, aff.a21, aff.a12, aff.a22, aff.a13, aff.a23);
QPolygon cameraPolygon(QRect(cameraRect.getP00().x, cameraRect.getP00().y, cameraRect.getLx(), cameraRect.getLy()));
cameraPolygon = cameraPolygon * matrix;
tglColor(cameraBgColor);
glBegin(GL_POLYGON);
glVertex2d(cameraPolygon.at(0).x(), cameraPolygon.at(0).y());
glVertex2d(cameraPolygon.at(1).x(), cameraPolygon.at(1).y());
glVertex2d(cameraPolygon.at(2).x(), cameraPolygon.at(2).y());
glVertex2d(cameraPolygon.at(3).x(), cameraPolygon.at(3).y());
glEnd();
tglColor(TPixel::White);
int nodesSize = stagePainter.getNodesCount();
if (nodesSize == 0)
return;
int cameraWidth = cameraPolygon.at(2).x() - cameraPolygon.at(0).x();
int cameraHeight = cameraPolygon.at(2).y() - cameraPolygon.at(0).y();
int i;
GLfloat mat[4][4];
QMatrix mtx;
//GLubyte *pbo;
//TRaster32P pboRaster;
//if(m_pboSupported)
//{
// glGenTextures(1, &m_textureId);
// glBindTexture(GL_TEXTURE_2D, m_textureId);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
// glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, cameraWidth, cameraHeight, 0, GL_BGRA, GL_UNSIGNED_BYTE, (GLvoid*)0);
// glBindTexture(GL_TEXTURE_2D, m_textureId);
// glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, m_pboId);
// // copy pixels from PBO to texture object
// // Use offset instead of ponter.
// glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, cameraWidth, cameraHeight, GL_BGRA, GL_UNSIGNED_BYTE, 0);
// // bind PBO to update pixel values
// glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, m_pboId);
// // map the buffer object into client's memory
// // Note that glMapBufferARB() causes sync issue.
// // If GPU is working with this buffer, glMapBufferARB() will wait(stall)
// // for GPU to finish its job. To avoid waiting (stall), you can call
// // first glBufferDataARB() with NULL pointer before glMapBufferARB().
// // If you do that, the previous data in PBO will be discarded and
// // glMapBufferARB() returns a new allocated pointer immediately
// // even if GPU is still working with the previous data.
// glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, cameraWidth * cameraHeight * 4, 0, GL_STREAM_DRAW_ARB);
// pbo = (GLubyte*)glMapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, GL_WRITE_ONLY_ARB);
// pboRaster = TRaster32P(cameraWidth, cameraHeight,cameraWidth, (TPixelRGBM32*) pbo, false);
// pboRaster->fill(TPixel32::Green);
//}
glScissor(cameraPolygon.at(0).x(), cameraPolygon.at(0).y(), cameraWidth, cameraHeight);
glEnable(GL_SCISSOR_TEST);
//if(!m_pboSupported)
glPushMatrix();
for (i = 0; i < nodesSize; i++) {
TRasterP ras = stagePainter.getRaster(i, mtx);
if (!ras.getPointer())
continue;
//if(!m_pboSupported)
//{
//Matrix tranformation
mat[0][0] = mtx.m11();
mat[0][1] = mtx.m12();
mat[0][2] = 0;
mat[0][3] = 0;
mat[1][0] = mtx.m21();
mat[1][1] = mtx.m22();
mat[1][2] = 0;
mat[1][3] = 0;
mat[2][0] = 0;
mat[2][1] = 0;
mat[2][2] = 1;
mat[2][3] = 0;
mat[3][0] = mtx.dx();
mat[3][1] = mtx.dy();
mat[3][2] = 0;
mat[3][3] = 1;
//Draw Raster
// CASO NON PBO
glLoadMatrixf(&mat[0][0]);
paintRaster(ras);
//}
//else
//{
// TAffine aff;// (mtx.m11(),mtx.m12(),mtx.dx(),mtx.m21(),mtx.m22(),mtx.dy());
// //TRop::quickPut(pboRaster, ras, aff);
//}
}
//if(!m_pboSupported)
glPopMatrix();
// Convert PBO to texture and draw it
//if(m_pboSupported)
//{
// glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0);
// vertices[0] = cameraPolygon.at(0).x();
// vertices[1] = cameraPolygon.at(0).y() + cameraHeight;
// vertices[3] = cameraPolygon.at(0).x();
// vertices[4] = cameraPolygon.at(0).y();
// vertices[6] = cameraPolygon.at(0).x() + cameraWidth;
// vertices[7] = cameraPolygon.at(0).y();
// vertices[9] = cameraPolygon.at(0).x() + cameraWidth;
// vertices[10] = cameraPolygon.at(0).y() + cameraHeight;
// glBindTexture(GL_TEXTURE_2D, m_textureId);
// glEnable(GL_BLEND);
// glEnableClientState(GL_VERTEX_ARRAY);
// glEnableClientState(GL_TEXTURE_COORD_ARRAY);
// glVertexPointer(3, GL_SHORT, 0, vertices);
// glTexCoordPointer(2,GL_SHORT,0,&coords);
// glDrawArrays(GL_QUADS, 0, 4);
// glDisableClientState(GL_VERTEX_ARRAY);
// glDisableClientState(GL_TEXTURE_COORD_ARRAY);
// glDisable(GL_BLEND);
// // clean up texture
// glDeleteTextures(1, &m_textureId);
//}
glDisable(GL_SCISSOR_TEST);
stagePainter.clearNodes();
}
#endif //USE_QPAINTER
//-----------------------------------------------------------------------------
void LineTestViewer::showEvent(QShowEvent *)
{
TApp *app = TApp::instance();
bool ret = true;
ret = ret && connect(TApp::instance()->getCurrentObject(), SIGNAL(objectSwitched()), this, SLOT(update()));
ret = ret && connect(TApp::instance()->getCurrentObject(), SIGNAL(objectChanged(bool)), this, SLOT(update()));
ret = ret && connect(TApp::instance()->getCurrentOnionSkin(), SIGNAL(onionSkinMaskChanged()), this, SLOT(update()));
ret = ret && connect(TApp::instance()->getCurrentLevel(), SIGNAL(xshLevelChanged()), this, SLOT(update()));
TFrameHandle *frameHandle = app->getCurrentFrame();
ret = ret && connect(frameHandle, SIGNAL(frameSwitched()), this, SLOT(update()));
TXsheetHandle *xsheetHandle = app->getCurrentXsheet();
ret = ret && connect(xsheetHandle, SIGNAL(xsheetChanged()), this, SLOT(update()));
ret = ret && connect(xsheetHandle, SIGNAL(xsheetSwitched()), this, SLOT(update()));
TSceneHandle *sceneHandle = app->getCurrentScene();
ret = ret && connect(sceneHandle, SIGNAL(sceneSwitched()), this, SLOT(onSceneSwitched()));
ret = ret && connect(sceneHandle, SIGNAL(sceneChanged()), this, SLOT(update()));
ret = ret && connect(TApp::instance()->getCurrentOnionSkin(), SIGNAL(onionSkinMaskChanged()), this, SLOT(update()));
assert(ret);
}
//-----------------------------------------------------------------------------
void LineTestViewer::hideEvent(QHideEvent *e)
{
TApp *app = TApp::instance();
disconnect(TApp::instance()->getCurrentObject(), SIGNAL(objectSwitched()), this, SLOT(update()));
disconnect(TApp::instance()->getCurrentObject(), SIGNAL(objectChanged(bool)), this, SLOT(update()));
disconnect(TApp::instance()->getCurrentOnionSkin(), SIGNAL(onionSkinMaskChanged()), this, SLOT(update()));
disconnect(TApp::instance()->getCurrentLevel(), SIGNAL(xshLevelChanged()), this, SLOT(update()));
TFrameHandle *frameHandle = app->getCurrentFrame();
disconnect(frameHandle, SIGNAL(frameSwitched()), this, SLOT(update()));
TXsheetHandle *xsheetHandle = app->getCurrentXsheet();
disconnect(xsheetHandle, SIGNAL(xsheetChanged()), this, SLOT(update()));
disconnect(xsheetHandle, SIGNAL(xsheetSwitched()), this, SLOT(update()));
TSceneHandle *sceneHandle = app->getCurrentScene();
disconnect(sceneHandle, SIGNAL(sceneSwitched()), this, SLOT(onSceneSwitched()));
disconnect(sceneHandle, SIGNAL(sceneChanged()), this, SLOT(update()));
disconnect(TApp::instance()->getCurrentOnionSkin(), SIGNAL(onionSkinMaskChanged()), this, SLOT(update()));
QWidget::hideEvent(e);
}
//-----------------------------------------------------------------------------
void LineTestViewer::leaveEvent(QEvent *)
{
//update();
QApplication::restoreOverrideCursor();
}
//-----------------------------------------------------------------------------
void LineTestViewer::enterEvent(QEvent *)
{
QApplication::setOverrideCursor(Qt::ForbiddenCursor);
//update();
setFocus();
}
//-----------------------------------------------------------------------------
void LineTestViewer::mouseMoveEvent(QMouseEvent *event)
{
if (m_mouseButton == Qt::MidButton) {
//panning
QPoint curPos = event->pos();
panQt(curPos - m_pos);
m_pos = curPos;
return;
}
}
//-----------------------------------------------------------------------------
void LineTestViewer::mousePressEvent(QMouseEvent *event)
{
m_pos = event->pos();
m_mouseButton = event->button();
}
//-----------------------------------------------------------------------------
void LineTestViewer::mouseReleaseEvent(QMouseEvent *event)
{
m_pos = QPoint(0, 0);
m_mouseButton = Qt::NoButton;
}
//-----------------------------------------------------------------------------
void LineTestViewer::wheelEvent(QWheelEvent *e)
{
if (e->orientation() == Qt::Horizontal)
return;
int delta = e->delta() > 0 ? 120 : -120;
zoomQt(e->pos(), exp(0.001 * delta));
}
//-----------------------------------------------------------------------------
// delta.x: right panning, pixel; delta.y: down panning, pixel
void LineTestViewer::panQt(const QPoint &delta)
{
if (delta == QPoint())
return;
m_viewAffine = TTranslation(delta.x(), -delta.y()) * m_viewAffine;
update();
}
//-----------------------------------------------------------------------------
void LineTestViewer::contextMenuEvent(QContextMenuEvent *event)
{
QMenu *menu = new QMenu(this);
QAction *act = menu->addAction("Reset View");
act->setShortcut(QKeySequence(CommandManager::instance()->getKeyFromId(T_ZoomReset)));
connect(act, SIGNAL(triggered()), this, SLOT(resetView()));
menu->exec(event->globalPos());
}
//-----------------------------------------------------------------------------
void LineTestViewer::keyPressEvent(QKeyEvent *event)
{
ViewerZoomer(this).exec(event);
}
//-----------------------------------------------------------------------------
// center: window coordinate, pixels, topleft origin
void LineTestViewer::zoomQt(const QPoint ¢er, double factor)
{
if (factor == 1.0)
return;
TPointD delta(center.x() - width() * 0.5, -center.y() + height() * 0.5);
double scale2 = fabs(m_viewAffine.det());
if ((scale2 < 100000 || factor < 1) && (scale2 > 0.001 * 0.05 || factor > 1))
m_viewAffine = TTranslation(delta) * TScale(factor) * TTranslation(-delta) * m_viewAffine;
update();
emit onZoomChanged();
}
//-----------------------------------------------------------------------------
void LineTestViewer::zoomQt(bool forward, bool reset)
{
int i;
double normalZoom = sqrt(getNormalZoomScale().det());
double scale2 = m_viewAffine.det();
if (reset || ((scale2 < 256 || !forward) && (scale2 > 0.001 * 0.05 || forward))) {
double oldZoomScale = sqrt(scale2);
double zoomScale = reset ? 1 : ImageUtils::getQuantizedZoomFactor(oldZoomScale / normalZoom, forward);
m_viewAffine = TScale(zoomScale * normalZoom / oldZoomScale) * m_viewAffine;
}
update();
emit onZoomChanged();
}
//-----------------------------------------------------------------------------
void LineTestViewer::onFrameSwitched()
{
update();
}
//-----------------------------------------------------------------------------
void LineTestViewer::onXsheetChanged()
{
update();
}
//-----------------------------------------------------------------------------
void LineTestViewer::onSceneSwitched()
{
resetView();
}
//-----------------------------------------------------------------------------
void LineTestViewer::resetView()
{
m_viewAffine = getNormalZoomScale();
update();
emit onZoomChanged();
}
//-----------------------------------------------------------------------------
void LineTestViewer::onButtonPressed(FlipConsole::EGadget button)
{
switch (button) {
CASE FlipConsole::eFilledRaster:
{
TXshSimpleLevel::m_fillFullColorRaster = !TXshSimpleLevel::m_fillFullColorRaster;
update();
}
DEFAULT:;
}
}
//-----------------------------------------------------------------------------
TAffine LineTestViewer::getNormalZoomScale()
{
TApp *app = TApp::instance();
const double inch = Stage::inch;
TCamera *camera = app->getCurrentScene()->getScene()->getCurrentCamera();
double size;
int res;
if (camera->isXPrevalence()) {
size = camera->getSize().lx;
res = camera->getRes().lx;
} else {
size = camera->getSize().ly;
res = camera->getRes().ly;
}
TScale cameraScale(inch * size / res);
return cameraScale.inv();
}
#endif
| 27,548 | 10,323 |
/*******************************************************************************
* Copyright (C) 2021 Intel Corporation
*
* SPDX-License-Identifier: MIT
******************************************************************************/
#include <core/view.hpp>
#include <dml/detail/ml/result.hpp>
namespace dml::detail::ml
{
detail::execution_status get_status(completion_record &record) noexcept
{
return static_cast<execution_status>(0b111111 & core::any_completion_record(record).status());
}
detail::result_t get_result(completion_record &record) noexcept
{
return core::any_completion_record(record).result();
}
detail::transfer_size_t get_bytes_completed(completion_record &record) noexcept
{
return core::any_completion_record(record).bytes_completed();
}
detail::transfer_size_t get_delta_record_size(completion_record &record) noexcept
{
return core::make_view<core::operation::create_delta>(record).delta_record_size();
}
detail::transfer_size_t get_crc_value(completion_record &record) noexcept
{
return core::make_view<core::operation::crc>(record).crc_value();
}
} // namespace dml::detail::ml
| 1,216 | 367 |
/**
* \file QryIdecTouRef1NFile.cpp
* job handler for job QryIdecTouRef1NFile (implementation)
* \author Alexander Wirthmueller
* \date created: 30 Dec 2017
* \date modified: 30 Dec 2017
*/
#ifdef IDECCMBD
#include <Ideccmbd.h>
#else
#include <Idecd.h>
#endif
#include "QryIdecTouRef1NFile.h"
#include "QryIdecTouRef1NFile_blks.cpp"
/******************************************************************************
class QryIdecTouRef1NFile
******************************************************************************/
QryIdecTouRef1NFile::QryIdecTouRef1NFile(
XchgIdec* xchg
, DbsIdec* dbsidec
, const ubigint jrefSup
, const uint ixIdecVLocale
) : JobIdec(xchg, VecIdecVJob::QRYIDECTOUREF1NFILE, jrefSup, ixIdecVLocale) {
jref = xchg->addJob(this);
// IP constructor.cust1 --- INSERT
xchg->addStmgr(jref, Stub::VecVNonetype::SHORT);
ixIdecVQrystate = VecIdecVQrystate::OOD;
// IP constructor.cust2 --- INSERT
rerun(dbsidec);
xchg->addClstn(VecIdecVCall::CALLIDECSTUBCHG, jref, Clstn::VecVJobmask::SPEC, jref, Arg(), Clstn::VecVJactype::LOCK);
// IP constructor.cust3 --- INSERT
// IP constructor.spec3 --- INSERT
};
QryIdecTouRef1NFile::~QryIdecTouRef1NFile() {
// IP destructor.spec --- INSERT
// IP destructor.cust --- INSERT
xchg->removeJobByJref(jref);
};
// IP cust --- INSERT
void QryIdecTouRef1NFile::refreshJnum() {
ubigint preRefSel = xchg->getRefPreset(VecIdecVPreset::PREIDECREFSEL, jref);
stgiac.jnum = getJnumByRef(preRefSel);
};
void QryIdecTouRef1NFile::rerun(
DbsIdec* dbsidec
, const bool call
) {
string sqlstr;
uint cnt;
ubigint preRefTou = xchg->getRefPreset(VecIdecVPreset::PREIDECREFTOU, jref);
xchg->removeClstns(VecIdecVCall::CALLIDECFILMOD_RETREUEQ, jref);
dbsidec->tblidecqselect->removeRstByJref(jref);
dbsidec->tblidecqtouref1nfile->removeRstByJref(jref);
sqlstr = "SELECT COUNT(TblIdecMFile.ref)";
sqlstr += " FROM TblIdecMFile";
sqlstr += " WHERE TblIdecMFile.refIxVTbl = " + to_string(VecIdecVMFileRefTbl::TOU);
sqlstr += " AND TblIdecMFile.refUref = " + to_string(preRefTou) + "";
dbsidec->loadUintBySQL(sqlstr, cnt);
statshr.ntot = cnt;
statshr.nload = 0;
if (stgiac.jnumFirstload > cnt) {
if (cnt >= stgiac.nload) stgiac.jnumFirstload = cnt-stgiac.nload+1;
else stgiac.jnumFirstload = 1;
};
sqlstr = "INSERT INTO TblIdecQTouRef1NFile(jref, jnum, ref)";
sqlstr += " SELECT " + to_string(jref) + ", 0, TblIdecMFile.ref";
sqlstr += " FROM TblIdecMFile";
sqlstr += " WHERE TblIdecMFile.refIxVTbl = " + to_string(VecIdecVMFileRefTbl::TOU);
sqlstr += " AND TblIdecMFile.refUref = " + to_string(preRefTou) + "";
sqlstr += " ORDER BY Filename ASC";
sqlstr += " LIMIT " + to_string(stgiac.nload) + " OFFSET " + to_string(stgiac.jnumFirstload-1);
dbsidec->executeQuery(sqlstr);
sqlstr = "UPDATE TblIdecQTouRef1NFile SET jnum = qref WHERE jref = " + to_string(jref);
dbsidec->executeQuery(sqlstr);
ixIdecVQrystate = VecIdecVQrystate::UTD;
statshr.jnumFirstload = stgiac.jnumFirstload;
fetch(dbsidec);
if (call) xchg->triggerCall(dbsidec, VecIdecVCall::CALLIDECSTATCHG, jref);
xchg->addIxRefClstn(VecIdecVCall::CALLIDECFILMOD_RETREUEQ, jref, Clstn::VecVJobmask::ALL, 0, VecIdecVMFileRefTbl::TOU, preRefTou, Clstn::VecVJactype::LOCK);
};
void QryIdecTouRef1NFile::fetch(
DbsIdec* dbsidec
) {
string sqlstr;
StmgrIdec* stmgr = NULL;
Stcch* stcch = NULL;
IdecQTouRef1NFile* rec = NULL;
dbsidec->tblidecqtouref1nfile->loadRstByJref(jref, false, rst);
statshr.nload = rst.nodes.size();
stmgr = xchg->getStmgrByJref(jref);
if (stmgr) {
stmgr->begin();
stcch = stmgr->stcch;
stcch->clear();
for (unsigned int i=0;i<rst.nodes.size();i++) {
rec = rst.nodes[i];
rec->jnum = statshr.jnumFirstload + i;
rec->stubRef = StubIdec::getStubFilStd(dbsidec, rec->ref, ixIdecVLocale, Stub::VecVNonetype::SHORT, stcch);
};
stmgr->commit();
stmgr->unlockAccess("QryIdecTouRef1NFile", "fetch");
};
refreshJnum();
};
uint QryIdecTouRef1NFile::getJnumByRef(
const ubigint ref
) {
uint retval = 0;
IdecQTouRef1NFile* rec = NULL;
for (unsigned int i=0;i<rst.nodes.size();i++) {
rec = rst.nodes[i];
if (rec->ref == ref) {
retval = rec->jnum;
break;
};
};
return retval;
};
ubigint QryIdecTouRef1NFile::getRefByJnum(
const uint jnum
) {
uint ref = 0;
IdecQTouRef1NFile* rec = getRecByJnum(jnum);
if (rec) ref = rec->ref;
return ref;
};
IdecQTouRef1NFile* QryIdecTouRef1NFile::getRecByJnum(
const uint jnum
) {
IdecQTouRef1NFile* rec = NULL;
for (unsigned int i=0;i<rst.nodes.size();i++) {
rec = rst.nodes[i];
if (rec->jnum == jnum) break;
};
if (rec) if (rec->jnum != jnum) rec = NULL;
return rec;
};
void QryIdecTouRef1NFile::handleRequest(
DbsIdec* dbsidec
, ReqIdec* req
) {
if (req->ixVBasetype == ReqIdec::VecVBasetype::CMD) {
reqCmd = req;
if (req->cmd == "cmdset") {
cout << "\trerun" << endl;
cout << "\tshow" << endl;
} else if (req->cmd == "rerun") {
req->retain = handleRerun(dbsidec);
} else if (req->cmd == "show") {
req->retain = handleShow(dbsidec);
} else {
cout << "\tinvalid command!" << endl;
};
if (!req->retain) reqCmd = NULL;
} else if (req->ixVBasetype == ReqIdec::VecVBasetype::REGULAR) {
};
};
bool QryIdecTouRef1NFile::handleRerun(
DbsIdec* dbsidec
) {
bool retval = false;
string input;
cout << "\tjnumFirstload (" << stgiac.jnumFirstload << "): ";
cin >> input;
stgiac.jnumFirstload = atol(input.c_str());
cout << "\tnload (" << stgiac.nload << "): ";
cin >> input;
stgiac.nload = atol(input.c_str());
rerun(dbsidec);
return retval;
};
bool QryIdecTouRef1NFile::handleShow(
DbsIdec* dbsidec
) {
bool retval = false;
IdecQTouRef1NFile* rec = NULL;
// header row
cout << "\tqref";
cout << "\tjref";
cout << "\tjnum";
cout << "\tref";
cout << "\tstubRef";
cout << endl;
// record rows
for (unsigned int i=0;i<rst.nodes.size();i++) {
rec = rst.nodes[i];
cout << "\t" << rec->qref;
cout << "\t" << rec->jref;
cout << "\t" << rec->jnum;
cout << "\t" << rec->ref;
cout << "\t" << rec->stubRef;
cout << endl;
};
return retval;
};
void QryIdecTouRef1NFile::handleCall(
DbsIdec* dbsidec
, Call* call
) {
if (call->ixVCall == VecIdecVCall::CALLIDECSTUBCHG) {
call->abort = handleCallIdecStubChg(dbsidec, call->jref);
} else if (call->ixVCall == VecIdecVCall::CALLIDECFILMOD_RETREUEQ) {
call->abort = handleCallIdecFilMod_retReuEq(dbsidec, call->jref, call->argInv.ix, call->argInv.ref);
};
};
bool QryIdecTouRef1NFile::handleCallIdecStubChg(
DbsIdec* dbsidec
, const ubigint jrefTrig
) {
bool retval = false;
if (ixIdecVQrystate == VecIdecVQrystate::UTD) {
ixIdecVQrystate = VecIdecVQrystate::SLM;
xchg->triggerCall(dbsidec, VecIdecVCall::CALLIDECSTATCHG, jref);
};
return retval;
};
bool QryIdecTouRef1NFile::handleCallIdecFilMod_retReuEq(
DbsIdec* dbsidec
, const ubigint jrefTrig
, const uint ixInv
, const ubigint refInv
) {
bool retval = false;
if (ixIdecVQrystate != VecIdecVQrystate::OOD) {
ixIdecVQrystate = VecIdecVQrystate::OOD;
xchg->triggerCall(dbsidec, VecIdecVCall::CALLIDECSTATCHG, jref);
};
return retval;
};
| 7,220 | 3,371 |
#include "util/Scheduler.h"
#include "util/Config.h"
#include <logging/Journal.h>
#include <gsl/gsl>
TilingScheduler::~TilingScheduler() {}
FixedThreadsScheduler::FixedThreadsScheduler(FixedThreadsSchedulerArgs args)
: _read_executor(args.read_threads)
, _indexing_executor(args.indexing_threads)
{
if (!global_config().is_journaling_enabled)
return;
_read_executor_observer =
_read_executor.make_observer<tf::ExecutorObserver>();
_indexing_executor_observer =
_indexing_executor.make_observer<tf::ExecutorObserver>();
}
FixedThreadsScheduler::~FixedThreadsScheduler()
{
if (!_read_executor_observer)
return;
auto read_trace = _read_executor_observer->dump();
auto indexing_trace = _indexing_executor_observer->dump();
auto read_journal = logging::JournalStore::global()
.new_journal("executor_read_trace")
.with_flat_type<std::string>()
.as_text(global_config().journal_directory)
.into_unique_files()
.build();
read_journal->add_record(std::move(read_trace));
auto indexing_journal = logging::JournalStore::global()
.new_journal("executor_indexing_trace")
.with_flat_type<std::string>()
.as_text(global_config().journal_directory)
.into_unique_files()
.build();
indexing_journal->add_record(std::move(indexing_trace));
}
std::future<void>
FixedThreadsScheduler::execute_tiling_iteration(tf::Taskflow& read_graph,
tf::Taskflow& index_graph)
{
auto read_future = _read_executor.run(read_graph).share();
auto index_future = _indexing_executor.run(index_graph).share();
return std::async(std::launch::deferred,
[wait_for_read = std::move(read_future),
wait_for_index = std::move(index_future)]() mutable {
wait_for_read.wait();
wait_for_index.wait();
});
}
std::pair<uint32_t, uint32_t>
FixedThreadsScheduler::get_read_and_index_concurrency(uint32_t remaining_files)
{
return { _read_executor.num_workers(), _indexing_executor.num_workers() };
}
AdaptiveScheduler::AdaptiveScheduler(
uint32_t num_threads,
ThroughputSampler& read_throughput_sampler,
ThroughputSampler& indexing_throughput_sampler)
: _num_read_threads(1)
, _num_index_threads(std::max(1u, num_threads - 1))
, _executor(
_num_read_threads +
_num_index_threads) // Important to use the sum of read+index threads,
// instead of num_threads, because num_threads can be
// <= 1 but we need at least two threads!
, _read_throughput_sampler(read_throughput_sampler)
, _indexing_throughput_sampler(indexing_throughput_sampler)
{
if (global_config().is_journaling_enabled) {
_executor_observer = _executor.make_observer<tf::ExecutorObserver>();
}
}
AdaptiveScheduler::~AdaptiveScheduler()
{
if (!_executor_observer)
return;
auto trace = _executor_observer->dump();
auto journal = logging::JournalStore::global()
.new_journal("executor_adaptive_trace")
.with_flat_type<std::string>()
.as_text(global_config().journal_directory)
.into_unique_files()
.build();
journal->add_record(std::move(trace));
}
std::future<void>
AdaptiveScheduler::execute_tiling_iteration(tf::Taskflow& read_graph,
tf::Taskflow& index_graph)
{
auto read_future = _executor.run(read_graph).share();
auto index_future = _executor.run(index_graph).share();
return std::async(std::launch::deferred,
[this,
wait_for_read = std::move(read_future),
wait_for_index = std::move(index_future)]() mutable {
wait_for_read.wait();
wait_for_index.wait();
});
}
std::pair<uint32_t, uint32_t>
AdaptiveScheduler::get_read_and_index_concurrency(uint32_t remaining_files)
{
// The main question that this function answers is: Should we use more or less
// read threads, or keep the count the same? For this, we solve the equation
// following set of equations: 1) R*tr = I*ti 2) R + I = max_threads
//
// R = number of read threads
// tr = throughput of a single read thread in points/s
// I = number of index threads
// ti = throughput of a single index thread in points/s
const auto read_throughput_per_thread =
_read_throughput_sampler.get_throughput_per_second() / _num_read_threads;
const auto index_throughput_per_thread =
_indexing_throughput_sampler.get_throughput_per_second() /
_num_index_threads;
const auto total_thread_count =
gsl::narrow_cast<uint32_t>(_executor.num_workers());
_num_read_threads = std::min(_num_read_threads, remaining_files);
_num_index_threads = total_thread_count - _num_read_threads;
// Any of the throughputs can be zero (e.g. on the first and last iteration).
// In this case we can't calculate a meaningful new thread distribution
if (read_throughput_per_thread == 0 || index_throughput_per_thread == 0) {
return { _num_read_threads, _num_index_threads };
}
const auto exact_index_threads =
total_thread_count /
(1 + (index_throughput_per_thread / read_throughput_per_thread));
const auto exact_read_threads = total_thread_count - exact_index_threads;
const auto rounded_read_threads = std::ceil(exact_read_threads);
const auto max_read_threads =
std::min(total_thread_count - 1, remaining_files);
_num_read_threads = gsl::narrow_cast<uint32_t>(
std::min<double>(max_read_threads, rounded_read_threads));
_num_index_threads = total_thread_count - _num_read_threads;
return { _num_read_threads, _num_index_threads };
} | 6,008 | 1,927 |
#include "CondFormats/DataRecord/interface/EcalPFSeedingThresholdsRcd.h"
#include "CondFormats/EcalObjects/interface/EcalPFSeedingThresholds.h"
#include "RecoParticleFlow/PFClusterProducer/interface/RecHitTopologicalCleanerBase.h"
class ECALPFSeedCleaner : public RecHitTopologicalCleanerBase {
public:
ECALPFSeedCleaner(const edm::ParameterSet& conf, edm::ConsumesCollector& cc);
ECALPFSeedCleaner(const ECALPFSeedCleaner&) = delete;
ECALPFSeedCleaner& operator=(const ECALPFSeedCleaner&) = delete;
void update(const edm::EventSetup&) override;
void clean(const edm::Handle<reco::PFRecHitCollection>& input, std::vector<bool>& mask) override;
private:
edm::ESHandle<EcalPFSeedingThresholds> ths_;
edm::ESGetToken<EcalPFSeedingThresholds, EcalPFSeedingThresholdsRcd> thsToken_;
};
DEFINE_EDM_PLUGIN(RecHitTopologicalCleanerFactory, ECALPFSeedCleaner, "ECALPFSeedCleaner");
ECALPFSeedCleaner::ECALPFSeedCleaner(const edm::ParameterSet& conf, edm::ConsumesCollector& cc)
: RecHitTopologicalCleanerBase(conf, cc), thsToken_(cc.esConsumes<edm::Transition::BeginLuminosityBlock>()) {}
void ECALPFSeedCleaner::update(const edm::EventSetup& iSetup) { ths_ = iSetup.getHandle(thsToken_); }
void ECALPFSeedCleaner::clean(const edm::Handle<reco::PFRecHitCollection>& input, std::vector<bool>& mask) {
//need to run over energy sorted rechits, as this is order used in seeding step
// this can cause ambiguity, isn't it better to index by detid ?
auto const& hits = *input;
std::vector<unsigned> ordered_hits(hits.size());
for (unsigned i = 0; i < hits.size(); ++i)
ordered_hits[i] = i;
std::sort(ordered_hits.begin(), ordered_hits.end(), [&](unsigned i, unsigned j) {
return hits[i].energy() > hits[j].energy();
});
for (const auto& idx : ordered_hits) {
if (!mask[idx])
continue; // is it useful ?
const reco::PFRecHit& rechit = hits[idx];
float threshold = (*ths_)[rechit.detId()];
if (rechit.energy() < threshold)
mask[idx] = false;
} // rechit loop
}
| 2,031 | 758 |
#pragma once
#include "Spike/Synapses/Synapses.hpp"
namespace Backend {
namespace Dummy {
class Synapses : public virtual ::Backend::Synapses {
public:
~Synapses() override = default;
void prepare() override;
void reset_state() override;
void copy_to_frontend() override;
void copy_to_backend() override;
};
} // namespace Dummy
} // namespace Backend
| 403 | 126 |
#include "LeetCodeLib.h"
class Solution {
public:
// iterative approach
int calculate(string s) {
int result = 0;
int sign = 1;
stack<int> st;
for (int i = 0; i < s.size(); i++) {
// get the number from string
if (s[i] >= '0') {
int num = 0;
while (i < s.size() && s[i] >= '0') {
num *= 10;
num += int(s[i]) - '0';
i++;
}
i--;
result += num * sign;
} else if (s[i] == '+') {
sign = 1;
} else if (s[i] == '-') {
sign = -1;
} else if (s[i] == '(') {
st.push(result);
st.push(sign);
result = 0;
sign = 1;
} else if (s[i] == ')') {
sign = st.top();
st.pop();
result *= sign;
result += st.top();
st.pop();
}
}
return result;
}
// prev own approach
// #define LEFT_PARA_VALUE -999999 /* -999999 represents '('*/
// stack<int> reverse, order;
// int calculate(string s) {
// int result = 0;
//
// for (int i = 0; i < s.size(); ++i) {
// if (s[i] == ' ') {
// continue;
// }
// if(s[i]=='('){
// reverse.push(LEFT_PARA_VALUE);
// continue;
// }
// if (s[i] == ')') {
// while (reverse.top() != LEFT_PARA_VALUE/*represents '('*/) {
// order.push(reverse.top());
// reverse.pop();
// }
// reverse.pop();// get rid of "("
// result = calculatePara();
// reverse.push(result);
// } else {
// // check each input is a num or not
// if (isdigit(s[i])) {
// string numString = s.substr(i, 20);
// int num = stoi(numString);
// reverse.push(num);
// i += to_string(num).size() - 1;
// } else {
// reverse.push((s[i]));
// }
// }
// }
//
// // handle all nums in ()
// if (reverse.empty()) {
// return result;
// } else {
// while (!reverse.empty()) {
// order.push(reverse.top());
// reverse.pop();
// }
// return calculatePara();
// }
// }
//
// int calculatePara() {
// if(order.empty()){
// cout<<"Problem in order stack"<<endl;
// return 0;
// }
// int result = (order.top()), right;
// int op;
// order.pop();
// // do operations on each num
// while (!order.empty()) {
// op = order.top();
// order.pop();
// right = order.top();
// order.pop();
// if (op == '+') {
// result = result + right;
// } else {
// result = result - right;
// }
// }
// return result;
// }
};
string stringToString(string input) {
assert(input.length() >= 2);
string result;
for (int i = 1; i < input.length() - 1; i++) {
char currentChar = input[i];
if (input[i] == '\\') {
char nextChar = input[i + 1];
switch (nextChar) {
case '\"':
result.push_back('\"');
break;
case '/' :
result.push_back('/');
break;
case '\\':
result.push_back('\\');
break;
case 'b' :
result.push_back('\b');
break;
case 'f' :
result.push_back('\f');
break;
case 'r' :
result.push_back('\r');
break;
case 'n' :
result.push_back('\n');
break;
case 't' :
result.push_back('\t');
break;
default:
break;
}
i++;
} else {
result.push_back(currentChar);
}
}
return result;
}
int main() {
string line;
while (getline(cin, line)) {
string s = stringToString(line);
int ret = Solution().calculate(s);
string out = to_string(ret);
cout << out << endl;
}
return 0;
}
/*
* testcase
* "1 + 1"=2
* "(1+(4+5+2)-3)+(6+8)"=23
* */ | 3,451 | 1,750 |
//@type greedy, DP
//@result 12964986 2015-09-11 22:53:08 zetta217 534B - Covered Path GNU C++ Accepted 15 ms 0 KB
// I don't use DP
#include <iostream>
using namespace std;
int main() {
int begin(0);
int end(0);
while (cin >> begin >> end) {
if (begin > end) {
int temp = begin;
begin = end;
end = temp;
}
int time(0);
int change(0);
cin >> time >> change;
int current(begin);
int distance(begin);
for (int i = 1; i + 1 < time; ++ i) {
current = current + change;
if (current > end && current - change * (time - 1 - i) > end) {
current = end + change * (time - 1 - i);
}
distance += current;
//cout << "test " << i << " " << current << " " << distance << endl;
}
cout << distance + end << endl;
}
return 0;
} | 794 | 349 |
/*****
* TFractalViewerWindow.c
*
* The window methods for the application.
*
* TFractalViewerWindow inherits its Draw method from TWindow.
* TMandelbrot, TJulia, and others override DrawShape to draw their own kind of CGI.
*
*****/
#include <Packages.h> // for NumToString prototype
#include "TFractalViewerWindow.h"
#include <stdlib.h>
#include "Utils.h"
/****
* TFractalViewerWindow constructor
*
* Create a bullseye window. This constructor relies
* on the TWindow constructor to place the window in
* in attractive place. Then it appends a number to the
* window title.
*
****/
TFractalViewerWindow::TFractalViewerWindow(void)
{
Str15 numStr;
Str255 title;
long windowNumber;
// Set the title of the window to be
// the title in the resource
// plus the window counter.
// The window counter is a class variable
// declared in the TWindow class.
GetWindowTitle(title);
windowNumber = GetWindowNumber();
NumToString(GetWindowNumber(), numStr);
concat(title, numStr);
SetWindowTitle(title);
}
/****
* Hit
*
* Handle a mouse down in the window.
* Bullseye window just force a refresh.
*
****/
void TFractalViewerWindow::Hit(Point where)
{
RefreshWindow(false); // preserve the scroll bars
}
/****
* GetStyle
* SetStyle
*
* Get and set the color style
*
****/
short TFractalViewerWindow::GetStyle()
{
return style;
}
void TFractalViewerWindow::SetStyle(short w)
{
style = w;
RefreshWindow(true);
}
short TFractalViewerWindow::GetDrawMode()
{
return drawMode;
}
void TFractalViewerWindow::SetDrawMode(short m)
{
if (drawMode != m) {
drawMode = m;
RefreshWindow(true);
}
}
/****
* Draw
*
* Draw the bullseye figures.
* Repeatedly call DrawShape with a smaller drawing area.
* The drawing area gets smaller by 2 * the width.
*
****/
void TFractalViewerWindow::Draw(void)
{
RgnHandle saveClip = NewRgn();
PenState pen;
Rect drawingRect;
GetPenState(&pen);
GetClip(saveClip);
inherited::Draw();
GetWindowRect(&drawingRect, false); // Don't draw in the scroll
// bar areas. Note that it's
// ok to pass the address of
// drawingRect because
// GetWindowRect won't move
// memory.
sTop = drawingRect.top;
sLeft = drawingRect.left;
DrawShape(&drawingRect);
SetClip(saveClip);
DisposeRgn(saveClip);
SetPenState(&pen);
}
/****
* DrawShape methods
*
* These are the DrawShape methods for
* TBullWindow: does nothing
* TCircleBull: Circles
* TSquareBull: Squares
* TPlasma: "Triangles"
*
* All the DrawShape methods take a drawingRect
* as a parameter. The pen width
* is already set to the appropriate width.
*
****/
void TFractalViewerWindow::DrawShape(Rect *drawingRect)
{
}
//
// ZOOM CONTENT
//
void TFractalViewerWindow::ZoomContent(short z)
{
RefreshWindow(false); // preserve the scroll bars
}
| 2,928 | 1,070 |
#include <cstring>
#include <stdexcept>
#include "common.hpp"
class TestHandler123 : public osmium::handler::Handler {
public:
TestHandler123() :
osmium::handler::Handler() {
}
void way(const osmium::Way& way) const {
if (way.id() == 123800) {
REQUIRE(way.version() == 1);
REQUIRE(way.nodes().size() == 2);
REQUIRE(way.nodes()[0] != way.nodes()[1]);
REQUIRE(way.nodes()[0].location() == way.nodes()[1].location());
} else {
throw std::runtime_error{"Unknown ID"};
}
}
}; // class TestHandler123
TEST_CASE("123") {
osmium::io::Reader reader{dirname + "/1/123/data.osm"};
index_pos_type index_pos;
index_neg_type index_neg;
location_handler_type location_handler{index_pos, index_neg};
location_handler.ignore_errors();
CheckBasicsHandler check_basics_handler{123, 2, 1, 0};
CheckWKTHandler check_wkt_handler{dirname, 123};
TestHandler123 test_handler;
osmium::apply(reader, location_handler, check_basics_handler, check_wkt_handler, test_handler);
}
| 1,105 | 407 |
// Copyright (c) 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/test/chromedriver/chrome/chrome_desktop_impl.h"
#include <stddef.h>
#include <utility>
#include "base/files/file_path.h"
#include "base/logging.h"
#include "base/posix/eintr_wrapper.h"
#include "base/process/kill.h"
#include "base/strings/string_util.h"
#include "base/sys_info.h"
#include "base/threading/platform_thread.h"
#include "base/time/time.h"
#include "build/build_config.h"
#include "chrome/test/chromedriver/chrome/automation_extension.h"
#include "chrome/test/chromedriver/chrome/devtools_client.h"
#include "chrome/test/chromedriver/chrome/devtools_event_listener.h"
#include "chrome/test/chromedriver/chrome/devtools_http_client.h"
#include "chrome/test/chromedriver/chrome/status.h"
#include "chrome/test/chromedriver/chrome/web_view_impl.h"
#include "chrome/test/chromedriver/net/timeout.h"
#if defined(OS_POSIX)
#include <errno.h>
#include <signal.h>
#include <sys/wait.h>
#include <unistd.h>
#endif
namespace {
// Enables wifi and data only, not airplane mode.
const int kDefaultConnectionType = 6;
bool KillProcess(const base::Process& process, bool kill_gracefully) {
#if defined(OS_POSIX)
if (!kill_gracefully) {
kill(process.Pid(), SIGKILL);
base::TimeTicks deadline =
base::TimeTicks::Now() + base::TimeDelta::FromSeconds(30);
while (base::TimeTicks::Now() < deadline) {
pid_t pid = HANDLE_EINTR(waitpid(process.Pid(), NULL, WNOHANG));
if (pid == process.Pid())
return true;
if (pid == -1) {
if (errno == ECHILD) {
// The wait may fail with ECHILD if another process also waited for
// the same pid, causing the process state to get cleaned up.
return true;
}
LOG(WARNING) << "Error waiting for process " << process.Pid();
}
base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(50));
}
return false;
}
#endif
if (!process.Terminate(0, true)) {
int exit_code;
return base::GetTerminationStatus(process.Handle(), &exit_code) !=
base::TERMINATION_STATUS_STILL_RUNNING;
}
return true;
}
} // namespace
ChromeDesktopImpl::ChromeDesktopImpl(
std::unique_ptr<DevToolsHttpClient> http_client,
std::unique_ptr<DevToolsClient> websocket_client,
std::vector<std::unique_ptr<DevToolsEventListener>>
devtools_event_listeners,
std::string page_load_strategy,
base::Process process,
const base::CommandLine& command,
base::ScopedTempDir* user_data_dir,
base::ScopedTempDir* extension_dir,
bool network_emulation_enabled)
: ChromeImpl(std::move(http_client),
std::move(websocket_client),
std::move(devtools_event_listeners),
page_load_strategy),
process_(std::move(process)),
command_(command),
network_connection_enabled_(network_emulation_enabled),
network_connection_(kDefaultConnectionType) {
if (user_data_dir->IsValid())
CHECK(user_data_dir_.Set(user_data_dir->Take()));
if (extension_dir->IsValid())
CHECK(extension_dir_.Set(extension_dir->Take()));
}
ChromeDesktopImpl::~ChromeDesktopImpl() {
if (!quit_) {
base::FilePath user_data_dir = user_data_dir_.Take();
base::FilePath extension_dir = extension_dir_.Take();
LOG(WARNING) << "chrome quit unexpectedly, leaving behind temporary "
"directories for debugging:";
if (user_data_dir_.IsValid())
LOG(WARNING) << "chrome user data directory: " << user_data_dir.value();
if (extension_dir_.IsValid())
LOG(WARNING) << "chromedriver automation extension directory: "
<< extension_dir.value();
}
}
Status ChromeDesktopImpl::WaitForPageToLoad(
const std::string& url,
const base::TimeDelta& timeout_raw,
std::unique_ptr<WebView>* web_view,
bool w3c_compliant) {
Timeout timeout(timeout_raw);
std::string id;
WebViewInfo::Type type = WebViewInfo::Type::kPage;
while (timeout.GetRemainingTime() > base::TimeDelta()) {
WebViewsInfo views_info;
Status status = devtools_http_client_->GetWebViewsInfo(&views_info);
if (status.IsError())
return status;
for (size_t i = 0; i < views_info.GetSize(); ++i) {
const WebViewInfo& view_info = views_info.Get(i);
if (base::StartsWith(view_info.url, url, base::CompareCase::SENSITIVE)) {
id = view_info.id;
type = view_info.type;
break;
}
}
if (!id.empty())
break;
base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(100));
}
if (id.empty())
return Status(kUnknownError, "page could not be found: " + url);
const DeviceMetrics* device_metrics = devtools_http_client_->device_metrics();
if (type == WebViewInfo::Type::kApp ||
type == WebViewInfo::Type::kBackgroundPage) {
// Apps and extensions don't work on Android, so it doesn't make sense to
// provide override device metrics in mobile emulation mode, and can also
// potentially crash the renderer, for more details see:
// https://code.google.com/p/chromedriver/issues/detail?id=1205
device_metrics = nullptr;
}
std::unique_ptr<WebView> web_view_tmp(
new WebViewImpl(id, w3c_compliant, devtools_http_client_->browser_info(),
devtools_http_client_->CreateClient(id), device_metrics,
page_load_strategy()));
Status status = web_view_tmp->ConnectIfNecessary();
if (status.IsError())
return status;
status = web_view_tmp->WaitForPendingNavigations(
std::string(), timeout, false);
if (status.IsOk())
*web_view = std::move(web_view_tmp);
return status;
}
Status ChromeDesktopImpl::GetAutomationExtension(
AutomationExtension** extension,
bool w3c_compliant) {
if (!automation_extension_) {
std::unique_ptr<WebView> web_view;
Status status = WaitForPageToLoad(
"chrome-extension://aapnijgdinlhnhlmodcfapnahmbfebeb/"
"_generated_background_page.html",
base::TimeDelta::FromSeconds(10),
&web_view,
w3c_compliant);
if (status.IsError())
return Status(kUnknownError, "cannot get automation extension", status);
automation_extension_.reset(new AutomationExtension(std::move(web_view)));
}
*extension = automation_extension_.get();
return Status(kOk);
}
Status ChromeDesktopImpl::GetAsDesktop(ChromeDesktopImpl** desktop) {
*desktop = this;
return Status(kOk);
}
std::string ChromeDesktopImpl::GetOperatingSystemName() {
return base::SysInfo::OperatingSystemName();
}
bool ChromeDesktopImpl::IsMobileEmulationEnabled() const {
return devtools_http_client_->device_metrics() != NULL;
}
bool ChromeDesktopImpl::HasTouchScreen() const {
return IsMobileEmulationEnabled();
}
bool ChromeDesktopImpl::IsNetworkConnectionEnabled() const {
return network_connection_enabled_;
}
Status ChromeDesktopImpl::QuitImpl() {
Status status = devtools_websocket_client_->ConnectIfNecessary();
if (status.IsOk()) {
status = devtools_websocket_client_->SendCommandAndIgnoreResponse(
"Browser.close", base::DictionaryValue());
if (status.IsOk() && process_.WaitForExitWithTimeout(
base::TimeDelta::FromSeconds(10), nullptr))
return status;
}
// If the Chrome session uses a custom user data directory, try sending a
// SIGTERM signal before SIGKILL, so that Chrome has a chance to write
// everything back out to the user data directory and exit cleanly. If we're
// using a temporary user data directory, we're going to delete the temporary
// directory anyway, so just send SIGKILL immediately.
bool kill_gracefully = !user_data_dir_.IsValid();
// If the Chrome session is being run with --log-net-log, send SIGTERM first
// to allow Chrome to write out all the net logs to the log path.
kill_gracefully |= command_.HasSwitch("log-net-log");
if (!KillProcess(process_, kill_gracefully))
return Status(kUnknownError, "cannot kill Chrome");
return Status(kOk);
}
const base::CommandLine& ChromeDesktopImpl::command() const {
return command_;
}
int ChromeDesktopImpl::GetNetworkConnection() const {
return network_connection_;
}
void ChromeDesktopImpl::SetNetworkConnection(
int network_connection) {
network_connection_ = network_connection;
}
Status ChromeDesktopImpl::GetWindowPosition(const std::string& target_id,
int* x,
int* y) {
Window window;
Status status = GetWindow(target_id, &window);
if (status.IsError())
return status;
*x = window.left;
*y = window.top;
return Status(kOk);
}
Status ChromeDesktopImpl::GetWindowSize(const std::string& target_id,
int* width,
int* height) {
Window window;
Status status = GetWindow(target_id, &window);
if (status.IsError())
return status;
*width = window.width;
*height = window.height;
return Status(kOk);
}
Status ChromeDesktopImpl::SetWindowRect(const std::string& target_id,
const base::DictionaryValue& params) {
Window window;
Status status = GetWindow(target_id, &window);
if (status.IsError())
return status;
auto bounds = std::make_unique<base::DictionaryValue>();
// fully exit fullscreen
if (window.state != "normal") {
auto bounds = std::make_unique<base::DictionaryValue>();
bounds->SetString("windowState", "normal");
status = SetWindowBounds(window.id, std::move(bounds));
if (status.IsError())
return status;
}
// window position
int x = 0;
int y = 0;
if (params.GetInteger("x", &x) && params.GetInteger("y", &y)) {
bounds->SetInteger("left", x);
bounds->SetInteger("top", y);
}
// window size
int width = 0;
int height = 0;
if (params.GetInteger("width", &width) &&
params.GetInteger("height", &height)) {
bounds->SetInteger("width", width);
bounds->SetInteger("height", height);
}
return SetWindowBounds(window.id, std::move(bounds));
}
Status ChromeDesktopImpl::SetWindowPosition(const std::string& target_id,
int x,
int y) {
Window window;
Status status = GetWindow(target_id, &window);
if (status.IsError())
return status;
if (window.state != "normal") {
// restore window to normal first to allow position change.
auto bounds = std::make_unique<base::DictionaryValue>();
bounds->SetString("windowState", "normal");
status = SetWindowBounds(window.id, std::move(bounds));
if (status.IsError())
return status;
}
auto bounds = std::make_unique<base::DictionaryValue>();
bounds->SetInteger("left", x);
bounds->SetInteger("top", y);
return SetWindowBounds(window.id, std::move(bounds));
}
Status ChromeDesktopImpl::SetWindowSize(const std::string& target_id,
int width,
int height) {
Window window;
Status status = GetWindow(target_id, &window);
if (status.IsError())
return status;
if (window.state != "normal") {
// restore window to normal first to allow size change.
auto bounds = std::make_unique<base::DictionaryValue>();
bounds->SetString("windowState", "normal");
status = SetWindowBounds(window.id, std::move(bounds));
if (status.IsError())
return status;
}
auto bounds = std::make_unique<base::DictionaryValue>();
bounds->SetInteger("width", width);
bounds->SetInteger("height", height);
return SetWindowBounds(window.id, std::move(bounds));
}
Status ChromeDesktopImpl::MaximizeWindow(const std::string& target_id) {
Window window;
Status status = GetWindow(target_id, &window);
if (status.IsError())
return status;
if (window.state == "maximized")
return Status(kOk);
if (window.state != "normal") {
// always restore window to normal first, since chrome ui doesn't allow
// maximizing a minimized or fullscreen window.
auto bounds = std::make_unique<base::DictionaryValue>();
bounds->SetString("windowState", "normal");
status = SetWindowBounds(window.id, std::move(bounds));
if (status.IsError())
return status;
}
auto bounds = std::make_unique<base::DictionaryValue>();
bounds->SetString("windowState", "maximized");
return SetWindowBounds(window.id, std::move(bounds));
}
Status ChromeDesktopImpl::MinimizeWindow(const std::string& target_id) {
Window window;
Status status = GetWindow(target_id, &window);
if (status.IsError())
return status;
if (window.state == "minimized")
return Status(kOk);
if (window.state != "normal") {
// restore window to normal first
auto bounds = std::make_unique<base::DictionaryValue>();
bounds->SetString("windowState", "normal");
status = SetWindowBounds(window.id, std::move(bounds));
if (status.IsError())
return status;
}
auto bounds = std::make_unique<base::DictionaryValue>();
bounds->SetString("windowState", "minimized");
return SetWindowBounds(window.id, std::move(bounds));
}
Status ChromeDesktopImpl::FullScreenWindow(const std::string& target_id) {
Window window;
Status status = GetWindow(target_id, &window);
if (status.IsError())
return status;
if (window.state == "fullscreen")
return Status(kOk);
if (window.state != "normal") {
auto bounds = std::make_unique<base::DictionaryValue>();
bounds->SetString("windowState", "normal");
status = SetWindowBounds(window.id, std::move(bounds));
if (status.IsError())
return status;
}
auto bounds = std::make_unique<base::DictionaryValue>();
bounds->SetString("windowState", "fullscreen");
return SetWindowBounds(window.id, std::move(bounds));
}
Status ChromeDesktopImpl::ParseWindowBounds(
std::unique_ptr<base::DictionaryValue> params,
Window* window) {
const base::Value* value = nullptr;
const base::DictionaryValue* bounds_dict = nullptr;
if (!params->Get("bounds", &value) || !value->GetAsDictionary(&bounds_dict))
return Status(kUnknownError, "no window bounds in response");
if (!bounds_dict->GetString("windowState", &window->state))
return Status(kUnknownError, "no window state in window bounds");
if (!bounds_dict->GetInteger("left", &window->left))
return Status(kUnknownError, "no left offset in window bounds");
if (!bounds_dict->GetInteger("top", &window->top))
return Status(kUnknownError, "no top offset in window bounds");
if (!bounds_dict->GetInteger("width", &window->width))
return Status(kUnknownError, "no width in window bounds");
if (!bounds_dict->GetInteger("height", &window->height))
return Status(kUnknownError, "no height in window bounds");
return Status(kOk);
}
Status ChromeDesktopImpl::ParseWindow(
std::unique_ptr<base::DictionaryValue> params,
Window* window) {
if (!params->GetInteger("windowId", &window->id))
return Status(kUnknownError, "no window id in response");
return ParseWindowBounds(std::move(params), window);
}
Status ChromeDesktopImpl::GetWindow(const std::string& target_id,
Window* window) {
Status status = devtools_websocket_client_->ConnectIfNecessary();
if (status.IsError())
return status;
base::DictionaryValue params;
params.SetString("targetId", target_id);
std::unique_ptr<base::DictionaryValue> result;
status = devtools_websocket_client_->SendCommandAndGetResult(
"Browser.getWindowForTarget", params, &result);
if (status.IsError())
return status;
return ParseWindow(std::move(result), window);
}
Status ChromeDesktopImpl::GetWindowBounds(int window_id, Window* window) {
Status status = devtools_websocket_client_->ConnectIfNecessary();
if (status.IsError())
return status;
base::DictionaryValue params;
params.SetInteger("windowId", window_id);
std::unique_ptr<base::DictionaryValue> result;
status = devtools_websocket_client_->SendCommandAndGetResult(
"Browser.getWindowBounds", params, &result);
if (status.IsError())
return status;
return ParseWindowBounds(std::move(result), window);
}
Status ChromeDesktopImpl::SetWindowBounds(
int window_id,
std::unique_ptr<base::DictionaryValue> bounds) {
Status status = devtools_websocket_client_->ConnectIfNecessary();
if (status.IsError())
return status;
base::DictionaryValue params;
params.SetInteger("windowId", window_id);
params.Set("bounds", bounds->CreateDeepCopy());
status = devtools_websocket_client_->SendCommand("Browser.setWindowBounds",
params);
if (status.IsError())
return status;
base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(100));
std::string state;
if (!bounds->GetString("windowState", &state))
return Status(kOk);
Window window;
status = GetWindowBounds(window_id, &window);
if (status.IsError())
return status;
if (window.state != state)
return Status(kUnknownError, "failed to change window state to " + state +
", current state is " + window.state);
return Status(kOk);
}
| 17,392 | 5,278 |
/*=========================================================================
*
* Copyright David Doria 2012 daviddoria@gmail.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.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 DilatedVarianceDifferenceAcceptanceVisitor_HPP
#define DilatedVarianceDifferenceAcceptanceVisitor_HPP
#include <boost/graph/graph_traits.hpp>
// Parent class
#include "Visitors/AcceptanceVisitors/AcceptanceVisitorParent.h"
// Custom
#include <Mask/Mask.h>
#include <ITKHelpers/ITKHelpers.h>
// ITK
#include "itkImage.h"
#include "itkImageRegion.h"
/**
*/
template <typename TGraph, typename TImage>
struct DilatedVarianceDifferenceAcceptanceVisitor : public AcceptanceVisitorParent<TGraph>
{
TImage* Image;
Mask* MaskImage;
const unsigned int HalfWidth;
unsigned int NumberOfFinishedVertices = 0;
float DifferenceThreshold;
typedef typename boost::graph_traits<TGraph>::vertex_descriptor VertexDescriptorType;
DilatedVarianceDifferenceAcceptanceVisitor(TImage* const image, Mask* const mask,
const unsigned int halfWidth, const float differenceThreshold = 100) :
Image(image), MaskImage(mask), HalfWidth(halfWidth), DifferenceThreshold(differenceThreshold)
{
}
bool AcceptMatch(VertexDescriptorType target, VertexDescriptorType source, float& computedEnergy) const override
{
//std::cout << "DilatedVarianceDifferenceAcceptanceVisitor::AcceptMatch" << std::endl;
itk::Index<2> targetPixel = ITKHelpers::CreateIndex(target);
itk::ImageRegion<2> targetRegion = ITKHelpers::GetRegionInRadiusAroundPixel(targetPixel, HalfWidth);
itk::Index<2> sourcePixel = ITKHelpers::CreateIndex(source);
itk::ImageRegion<2> sourceRegion = ITKHelpers::GetRegionInRadiusAroundPixel(sourcePixel, HalfWidth);
//std::cout << "Extracting target region mask..." << std::endl;
Mask::Pointer targetRegionMask = Mask::New();
ITKHelpers::ExtractRegion(MaskImage, targetRegion, targetRegionMask.GetPointer());
//std::cout << "There are " << ITKHelpers::CountPixelsWithValue(targetRegionMask.GetPointer(), targetRegionMask->GetHoleValue()) << " hole pixels in the target region." << std::endl;
//std::cout << "Dilating target region mask..." << std::endl;
Mask::Pointer dilatedTargetRegionMask = Mask::New();
ITKHelpers::DilateImage(targetRegionMask.GetPointer(), dilatedTargetRegionMask.GetPointer(), 6);
//std::cout << "There are " << ITKHelpers::CountPixelsWithValue(dilatedTargetRegionMask.GetPointer(), dilatedTargetRegionMask->GetHoleValue()) << " dilated hole pixels in the target region." << std::endl;
// Separate so that only the newly dilated part of the hole remains
//std::cout << "XORing dilated target mask with target mask..." << std::endl;
typedef itk::Image<bool, 2> BoolImage;
BoolImage::Pointer rindImage = BoolImage::New(); // "rind" like an "orange rind"
ITKHelpers::XORRegions(targetRegionMask.GetPointer(), targetRegionMask->GetLargestPossibleRegion(),
dilatedTargetRegionMask.GetPointer(), dilatedTargetRegionMask->GetLargestPossibleRegion(), rindImage.GetPointer());
//std::cout << "There are " << ITKHelpers::CountPixelsWithValue(rindImage.GetPointer(), true) << " XORed hole pixels in the target region." << std::endl;
std::vector<itk::Index<2> > rindPixels = ITKHelpers::GetPixelsWithValue(rindImage.GetPointer(), rindImage->GetLargestPossibleRegion(), true);
//std::cout << "There are " << rindPixels.size() << " rindPixels." << std::endl;
std::vector<itk::Offset<2> > rindOffsets = ITKHelpers::IndicesToOffsets(rindPixels, ITKHelpers::ZeroIndex());
//std::cout << "There are " << rindOffsets.size() << " rindOffsets." << std::endl;
//std::cout << "Computing variances..." << std::endl;
// Compute the variance of the rind pixels in the target region
std::vector<itk::Index<2> > targetRindPixels = ITKHelpers::OffsetsToIndices(rindOffsets, targetRegion.GetIndex());
//std::cout << "There are " << targetRindPixels.size() << " targetRindPixels." << std::endl;
//std::cout << "Computing target variances..." << std::endl;
typename TImage::PixelType targetRegionSourcePixelVariance = ITKHelpers::VarianceOfPixelsAtIndices(Image, targetRindPixels);
//std::cout << "targetRegionSourcePixelVariance: " << targetRegionSourcePixelVariance << std::endl;
// Compute the variance of the rind pixels in the source region
std::vector<itk::Index<2> > sourceRindPixels = ITKHelpers::OffsetsToIndices(rindOffsets, sourceRegion.GetIndex());
//std::cout << "There are " << sourceRindPixels.size() << " targetRindPixels." << std::endl;
//std::cout << "Computing source variances..." << std::endl;
typename TImage::PixelType sourceRegionTargetPixelVariance = ITKHelpers::VarianceOfPixelsAtIndices(Image, sourceRindPixels);
//std::cout << "sourceRegionTargetPixelVariance: " << sourceRegionTargetPixelVariance << std::endl;
// Compute the difference
computedEnergy = (targetRegionSourcePixelVariance - sourceRegionTargetPixelVariance).GetNorm();
std::cout << "DilatedVarianceDifferenceAcceptanceVisitor Energy: " << computedEnergy << std::endl;
if(computedEnergy < DifferenceThreshold)
{
std::cout << "DilatedVarianceDifferenceAcceptanceVisitor: Match accepted (less than " << DifferenceThreshold << ")" << std::endl;
return true;
}
else
{
std::cout << "DilatedVarianceDifferenceAcceptanceVisitor: Match rejected (greater than " << DifferenceThreshold << ")" << std::endl;
return false;
}
};
};
#endif
| 6,223 | 1,900 |
/*
* See header for notes.
*/
#include "vfd_task.h"
#include "board_defs.h"
#include "catch_errors.h"
#include "packet_utils.h"
#include "string.h" // memcpy
#include "vfd_defs.h"
VfdTask::VfdTask( //
const char* name,
UartTasks& uart,
Writable& target,
TaskUtilitiesArg& utilArg,
UBaseType_t priority)
: uart{ uart }
, target{ target }
, util{ utilArg }
, task{ name, funcWrapper, this, priority }
, bus{ uart, responseDelayMs, target, packet, util }
{}
void VfdTask::func()
{
// Assuming sequential address, including broadcast address (0)
// Todo - more flexible address configuration
const uint8_t numNodes = 3; // node 1, 2, and broadcast
// const uint8_t numNodes = 6; // nodes 1-5, and broadcast
uint16_t lastFrequency[numNodes];
for (int i = 0; i < numNodes; i++) {
lastFrequency[i] = -1; // invalid, max of 4000
}
uint16_t setFrequency[numNodes] = { 0 };
// Which address we're focusing on updating.
// Address 0 is broadcast, which does not get any responses.
uint8_t focus = 0;
util.watchdogRegisterTask();
while (1) {
util.watchdogKick();
// Collect all incoming host commands before deciding what modbus commands to send
while (msgbuf.read(&packet, sizeof(packet), 0)) {
switch (packet.id) {
case PacketID::VfdSetFrequency: {
uint8_t node = packet.body.vfdSetFrequency.node;
uint16_t freq = packet.body.vfdSetFrequency.frequency;
util.logln( //
"%s got command to set vfd %u frequency to %u.%u Hz",
pcTaskGetName(task.handle),
node,
freq / 10,
freq % 10);
if (node < numNodes) {
setFrequency[node] = freq;
} else {
util.logln( //
"%s got invalid address %u, exceeds %u",
pcTaskGetName(task.handle),
node,
numNodes - 1);
}
break;
}
default:
util.logln( //
"%s doesn't know what to do with packet id: %s",
pcTaskGetName(task.handle),
packetIdToString(packet.id));
critical();
break;
}
}
// For each address in round-robbin fashion,
// create a modbus "Request" packet to send.
// If there's a new frequency setpoint, send that,
// otherwise request status.
focus += 1;
focus %= numNodes;
if (setFrequency[focus] != lastFrequency[focus]) {
// Write frequency value
bus.outPkt->nodeAddress = focus;
bus.outPkt->command = FunctionCode::WriteSingleRegister;
bus.outPkt->writeSingleRegisterRequest.registerAddress = frequencyRegAddress;
bus.outPkt->writeSingleRegisterRequest.data = setFrequency[focus];
} else {
// Don't broadcast status request. Won't get a response.
if (focus == 0) {
continue;
}
// Read status registers
bus.outPkt->nodeAddress = focus;
bus.outPkt->command = FunctionCode::ReadMultipleRegisters;
bus.outPkt->readMultipleRegistersRequest.startingAddress = statusRegAddress;
bus.outPkt->readMultipleRegistersRequest.numRegisters = statusRegNum;
}
// Set origin for all outgoing reporting packets.
// Note that this packet is reused by modbus driver.
packet.origin = PacketOrigin::TargetToHost;
uint32_t respLen = bus.sendRequest();
// Special handling for broadcast messages
if (respLen == 1 && bus.outPkt->nodeAddress == 0) {
// If frequency setpoint update
if (bus.outPkt->command == FunctionCode::WriteSingleRegister && //
__builtin_bswap16(bus.outPkt->writeSingleRegisterRequest.registerAddress) == frequencyRegAddress) {
// Only update last frequency setpoint if write succeeded.
// Otherwise, will attempt retransmission next lap.
// For broadcast, failure could be due to a bad echo.
lastFrequency[focus] = setFrequency[focus];
} else {
error("Unexpected modbus broadcast");
}
// Successful non-broadcast requests
} else if (respLen) {
switch (bus.inPkt->command) {
case FunctionCode::ReadMultipleRegisters: {
// The requested register is not returned in the response,
// and the outgoing request packet inverted endianness, so
// need to reverse that conversion.
uint16_t regAddr = __builtin_bswap16(bus.outPkt->readMultipleRegistersRequest.startingAddress);
switch (regAddr) {
case statusRegAddress:
// Response size is already verified by modbus driver.
// Form packet for reporting
setPacketIdAndLength(packet, PacketID::VfdStatus);
packet.body.vfdStatus.nodeAddress = bus.inPkt->nodeAddress;
memcpy(&packet.body.vfdStatus.payload, bus.inPkt->readMultipleRegistersResponse.payload, sizeof(VfdStatus::payload));
// Report result of modbus request
util.write(target, &packet, packet.length);
break;
default: //
util.logln("Unexpected multi-reg modbus read response at address 0x%x", regAddr);
break;
}
break;
}
case FunctionCode::WriteSingleRegister: {
uint16_t regAddr = bus.inPkt->writeSingleRegisterResponse.registerAddress;
switch (regAddr) {
case frequencyRegAddress:
util.logln( //
"node %u: wrote frequency %u, %u.%u Hz",
bus.inPkt->nodeAddress,
bus.inPkt->writeSingleRegisterResponse.data,
bus.inPkt->writeSingleRegisterResponse.data / 10,
bus.inPkt->writeSingleRegisterResponse.data % 10);
// Only update last frequency setpoint if write succeeded.
// Otherwise, will attempt retransmission next lap.
lastFrequency[focus] = setFrequency[focus];
break;
default: //
util.logln("Unexpected single-reg modbus write response at address 0x%x", regAddr);
break;
}
}
case FunctionCode::WriteMultipleRegisters: // not expecting anything for this yet
case FunctionCode::Exception: // error bit convenience
default: //
util.logln( //
"node %u unexpected modbus response command 0x%x - possible exception",
bus.outPkt->nodeAddress,
bus.inPkt->command);
VfdErrorDbgPinHigh();
VfdErrorDbgPinLow();
VfdErrorDbgPinHigh();
// Hold to allow capture by low sample rate scope
osDelay(1);
VfdErrorDbgPinLow();
break;
}
bus.shiftOutConsumedBytes(respLen);
} else {
util.logln("node %u: Unsuccessful modbus request", bus.outPkt->nodeAddress);
VfdErrorDbgPinHigh();
// Hold to allow capture by low sample rate scope
osDelay(1);
VfdErrorDbgPinLow();
}
}
}
size_t VfdTask::write(const void* buf, size_t len, TickType_t ticks)
{
return msgbuf.write(buf, len, ticks);
}
| 7,145 | 2,124 |
#include <exodus/library.h>
libraryinit()
function main(in x, in y, in x2, in y2, in readwrite, io buffer) {
//TODO implement if screen handling required
//VIDEO.RW(0,0,@CRTWIDE-1,@CRTHIGH-1,'R',startBUFFER)
//eg to copy a whole screen sized 80x25, use 0,0,79,24
//R=Read, W=Write
//evade warning "usused"
false and x and y and x2 and y2 and readwrite;
if (readwrite=="R") {
buffer="";
} else if (readwrite=="W") {
}
return 0;
}
libraryexit()
| 463 | 206 |
#include <iostream>
#include <string>
#include <SDL2/SDL.h>
#include <QApplication>
#include <QMessageBox>
#include <QDebug>
#include "editor.h"
#include "yaml.h"
#include "map_game.h"
#include "yaml.h"
#include "inventory.h"
#include "inventory_editor.h"
#define EXIT_PADDING 5
#define EXIT_ICON_SIDE 20
#define SAVE_PADDING 10
#define SAVE_ICON_SIDE 60
Editor::Editor(YAML::Node map, std::string mn, std::string bgn, std::string bgp) :
bg_name(bgn),
bg_path(bgp),
map_name(mn),
mapNode(YAML::Clone(map)),
staticNode(mapNode["static"]),
mapGame(mapNode),
editorWindow(staticNode, 0, 0, true, true),
camera(editorWindow.getScreenWidth(),
editorWindow.getScreenHeight(),
editorWindow.getBgWidth(),
editorWindow.getBgHeight()),
renderer(editorWindow.getRenderer()),
editorInventory(renderer,
mapNode["static"]["teams_amount"].as<int>(),
mapNode["static"]["worms_health"].as<int>()) {
this->teamsAmount = mapNode["static"]["teams_amount"].as<int>();
this->wormsHealth = mapNode["static"]["worms_health"].as<int>();
this->editorInventory.toggleOpen();
this->mapGame.setRenderer(this->renderer);
this->mapGame.initializeStates();
this->mapGame.createMapToSave();
this->exitTexture.loadFromFile(gPath.PATH_EXIT_ICON, this->renderer);
this->exitTexture.setX(this->editorWindow.getScreenWidth() - EXIT_PADDING - EXIT_ICON_SIDE);
this->exitTexture.setY(EXIT_PADDING);
this->saveTexture.loadFromFile(gPath.PATH_SAVE_ICON, this->renderer);
this->saveTexture.setX(this->editorWindow.getScreenWidth() - SAVE_PADDING - SAVE_ICON_SIDE);
this->saveTexture.setY(EXIT_PADDING + EXIT_ICON_SIDE + SAVE_PADDING);
this->unsaved_changes = false;
this->notice.setScreenWidth(this->editorWindow.getScreenWidth());
this->notice.setScreenHeight(this->editorWindow.getScreenHeight());
}
int Editor::start(void) {
bool quit = false;
SDL_Event e;
while (!quit) {
int camX = camera.getX(), camY = camera.getY();
while (SDL_PollEvent(&e) != 0) {
if (e.type == SDL_QUIT) {
quit = true;
editorWindow.hide();
validMap = mapGame.hasWorms();
if (!validMap) {
QMessageBox msgBox;
msgBox.setWindowTitle("Mapa inválido.");
msgBox.setText("El mapa debe tener al menos un worm de cada team." "¿Desea continuar editando el mapa?");
msgBox.setStandardButtons(QMessageBox::Yes);
msgBox.addButton(QMessageBox::No);
msgBox.setDefaultButton(QMessageBox::Yes);
if(msgBox.exec() == QMessageBox::Yes) {
editorWindow.show();
quit = false;
}
}
}
if (e.type == SDL_KEYDOWN) {
if (e.key.keysym.sym == SDLK_z && (e.key.keysym.mod & KMOD_CTRL)) {
mapGame.setPreviousState(editorInventory);
}
if (e.key.keysym.sym == SDLK_y && (e.key.keysym.mod & KMOD_CTRL)) {
mapGame.setNextState(editorInventory);
}
}
if (e.type == SDL_MOUSEBUTTONDOWN) {
int mouseX, mouseY;
SDL_GetMouseState(&mouseX, &mouseY);
if (e.button.button == SDL_BUTTON_LEFT) {
if (
mouseX > this->saveTexture.getX() &&
mouseX < this->saveTexture.getX() + SAVE_ICON_SIDE &&
mouseY > this->saveTexture.getY() &&
mouseY < this->saveTexture.getY() + SAVE_ICON_SIDE
) {
if (!this->unsaved_changes) {
std::cout << "No hay cambios sin guardar." << std::endl;
this->notice.showFlashNotice(this->renderer, "No hay cambios sin guardar.");
continue;
}
validMap = mapGame.hasWorms();
if (!validMap) {
std::cout << "El mapa debe tener al menos un worm de cada team." << std::endl;
this->notice.showFlashError(this->renderer, "El mapa debe tener al menos un worm de cada team.");
continue;
}
mapGame.saveAs(this->map_name, this->bg_name, this->bg_path);
this->unsaved_changes = false;
std::cout << "Mapa guardado." << std::endl;
this->notice.showFlashNotice(this->renderer, "Mapa guardado en /usr/etc/worms/maps/" + this->map_name);
} else if (
mouseX > this->exitTexture.getX() &&
mouseX < this->exitTexture.getX() + EXIT_ICON_SIDE &&
mouseY > this->exitTexture.getY() &&
mouseY < this->exitTexture.getY() + EXIT_ICON_SIDE) {
quit = true;
editorWindow.hide();
validMap = mapGame.hasWorms();
if (!validMap) {
QMessageBox msgBox;
msgBox.setWindowTitle("Mapa inválido.");
msgBox.setText("El mapa debe tener al menos un worm de cada team." "¿Desea continuar editando el mapa?");
msgBox.setStandardButtons(QMessageBox::Yes);
msgBox.addButton(QMessageBox::No);
msgBox.setDefaultButton(QMessageBox::Yes);
if(msgBox.exec() == QMessageBox::Yes) {
editorWindow.show();
quit = false;
continue;
}
}
if (this->unsaved_changes) {
QMessageBox msgBox;
msgBox.setWindowTitle("Guardar antes de salir.");
msgBox.setText("Hay cambios sin guardar. Desea guardar el mapa antes de salir?");
msgBox.setStandardButtons(QMessageBox::Yes);
msgBox.addButton(QMessageBox::No);
msgBox.setDefaultButton(QMessageBox::Yes);
if(msgBox.exec() == QMessageBox::Yes) {
mapGame.saveAs(this->map_name, this->bg_name, this->bg_path);
this->unsaved_changes = false;
continue;
}
}
} else {
editorInventory.handleEvent(renderer, e, mapGame, camX, camY);
this->unsaved_changes = true;
}
}
} else {
editorInventory.handleEvent(renderer, e, mapGame, camX, camY);
}
}
SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0x00, 0x00);
SDL_RenderClear(renderer);
camera.updateCameraPosition();
editorWindow.render(camera);
mapGame.render(renderer, camX, camY);
editorInventory.renderSelectedInMouse(renderer);
editorWindow.renderWater(camera);
editorInventory.render(renderer);
notice.render(renderer);
this->saveTexture.render(this->renderer, this->saveTexture.getX(), this->saveTexture.getY(), SAVE_ICON_SIDE, SAVE_ICON_SIDE);
this->exitTexture.render(this->renderer, this->exitTexture.getX(), this->exitTexture.getY(), EXIT_ICON_SIDE, EXIT_ICON_SIDE);
SDL_RenderPresent(renderer);
SDL_Delay(50); // Para no usar al mango el CPU
}
if (validMap && this->unsaved_changes) {
QMessageBox msgBox;
msgBox.setWindowTitle("Fin de edición");
msgBox.setText("¿Desea guardar el mapa?");
msgBox.setStandardButtons(QMessageBox::Yes);
msgBox.addButton(QMessageBox::No);
msgBox.setDefaultButton(QMessageBox::Yes);
if(msgBox.exec() == QMessageBox::Yes) {
mapGame.saveAs(this->map_name, this->bg_name, this->bg_path);
this->unsaved_changes = false;
return 0;
}
}
return -1;
}
| 6,887 | 2,939 |
/*
* Copyright (c) 2019 SK Telecom Co., Ltd. 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 "base/nugu_log.h"
#include "capability_manager.hh"
#include "wakeup_handler.hh"
namespace NuguCore {
WakeupHandler::WakeupHandler(const std::string& model_path)
: wakeup_detector(std::unique_ptr<WakeupDetector>(new WakeupDetector(WakeupDetector::Attribute { "", "", "", model_path })))
, uniq(0)
{
wakeup_detector->setListener(this);
}
WakeupHandler::~WakeupHandler()
{
}
void WakeupHandler::setListener(IWakeupListener* listener)
{
this->listener = listener;
}
bool WakeupHandler::startWakeup()
{
std::string id = "id#" + std::to_string(uniq++);
setWakeupId(id);
return wakeup_detector->startWakeup(id);
}
void WakeupHandler::stopWakeup()
{
wakeup_detector->stopWakeup();
}
void WakeupHandler::onWakeupState(WakeupState state, const std::string& id, float noise, float speech)
{
if (request_wakeup_id != id) {
nugu_warn("[id: %s] ignore [id: %s]'s state %d", request_wakeup_id.c_str(), id.c_str(), state);
return;
}
switch (state) {
case WakeupState::FAIL:
nugu_dbg("[id: %s] WakeupState::FAIL", id.c_str());
if (listener)
listener->onWakeupState(WakeupDetectState::WAKEUP_FAIL, noise, speech);
break;
case WakeupState::DETECTING:
nugu_dbg("[id: %s] WakeupState::DETECTING", id.c_str());
if (listener)
listener->onWakeupState(WakeupDetectState::WAKEUP_DETECTING, noise, speech);
break;
case WakeupState::DETECTED:
nugu_dbg("[id: %s] WakeupState::DETECTED", id.c_str());
if (listener)
listener->onWakeupState(WakeupDetectState::WAKEUP_DETECTED, noise, speech);
break;
case WakeupState::DONE:
nugu_dbg("[id: %s] WakeupState::DONE", id.c_str());
break;
}
}
void WakeupHandler::setWakeupId(const std::string& id)
{
request_wakeup_id = id;
nugu_dbg("startListening with new id(%s)", request_wakeup_id.c_str());
}
} // NuguCore
| 2,589 | 954 |
// C++ program to illustrate If statement
#include<iostream>
using namespace std;
int main()
{
int i = 10;
if (i > 15)
{
cout<<"10 is less than 15";
}
cout<<"I am Not in if";
}
| 197 | 93 |
//Language: GNU C++
//HACK ME, PLEASE! ^_^
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
#include <vector>
#include <set>
#include <utility>
#include <math.h>
#include <cstdlib>
#include <memory.h>
#include <queue>
#define pb push_back
#define i64 long long
#define mp make_pair
#define pii pair <int,int>
#define vi vector <int>
#define vii vector <pii>
#define f first
#define s second
#define foran(i,a,b) for (int i=a;i<(int)b;i++)
#define forn(i,n) for (int i=0;i<(int)n;i++)
#define ford(i,n) for (int i=(int)n-1;i>=0;i--)
const double eps = 1e-9;
const int int_inf = 2000000000;
const i64 i64_inf = 1000000000000000000LL;
const double pi = acos(-1.0);
using namespace std;
struct p
{
int x,y;
p() {};
};
struct tr
{
p a,b;
tr(int x1=0,int y1=0,int x2=0,int y2=0) { a.x=x1; a.y=y1; b.x=x2; b.y=y2; };
};
int dest(tr F, tr S)
{
if (F.a.x == F.b.x && S.a.x == S.b.x)
{
int y = F.a.y; int yy = F.b.y;
int y1 = S.a.y; int yy1 = S.b.y;
if ( min(y,yy) > max(y1,yy1) || min(y1,yy1) > max(y,yy))
{
if (y1 < yy1) swap(y1,yy1);
if (y < yy) swap(y,yy);
int dx = abs(F.a.x - S.b.x);
int dy = min(abs(yy1 - y),abs(y1-yy));
return dx * dx + dy * dy;
} else return (F.a.x - S.a.x) * (F.a.x - S.a.x);
} else
if (F.a.y == F.b.y && S.a.y == S.b.y)
{
int x = F.a.x; int xx = F.b.x;
int x1 = S.a.x; int xx1 = S.b.x;
if ( min(x,xx) > max(x1,xx1) || min(x1,xx1) > max(x,xx))
{
if (x1 < xx1) swap(x1,xx1);
if (x < xx) swap(x,xx);
int dy = abs(F.a.y - S.b.y);
int dx = min(abs(xx1 - x), abs(x1-xx));
return dx * dx + dy * dy;
} else return (F.a.y - S.a.y) * (F.a.y - S.a.y);
} else
{
if (F.a.y == F.b.y) swap(F,S);
int y = F.b.y;
int y1 = F.a.y;
int x = S.a.x;
int x1 = S.b.x;
if (y1 < y) swap(y,y1);
if (x1 < x) swap(x,x1);
if (S.a.y <= y1 && S.a.y >= y) return min( (x - F.b.x)*(x - F.b.x), (x1 - F.b.x)*(x1 - F.b.x) );
if (F.a.x >= x && F.a.x <= x1) return min( (y1 - S.a.y)*(y1 - S.a.y), (y - S.a.y) * (y - S.a.y) );
if (abs(x - F.a.x) > abs(x1 - F.a.x)) swap(x,x1);
if (abs(y - S.a.y) < abs(y1 - S.a.y)) swap(y,y1);
int dx = F.a.x - x;
int dy = y1 - S.a.y;
return dx * dx + dy * dy;
}
}
int n;
int a,aa,b;
p A; p B;
tr c[1100];
int d[1050];
int main() {
cin >> a >> b;
aa = a;
a = a * a;
cin >> A.x >> A.y >> B.x >> B.y;
cin >> n;
forn(i,n)
scanf("%d%d%d%d",&c[i].a.x,&c[i].a.y,&c[i].b.x,&c[i].b.y);
if ( (A.x - B.x)*(A.x - B.x) + (A.y - B.y)*(A.y - B.y) <= a)
{
int de = (A.x - B.x)*(A.x - B.x) + (A.y - B.y)*(A.y - B.y);
printf("%.8lf",(double)sqrt((double)de));
return 0;
}
forn(i,n)
if (dest(tr(A.x,A.y,A.x,A.y),c[i]) <= a) d[i] = 1; else d[i] = int_inf;
queue <int> q;
forn(i,n) if (d[i] < int_inf) q.push(i);
double res = int_inf;
while (!q.empty())
{
int j = q.front();
q.pop();
if (dest(tr(B.x,B.y,B.x,B.y),c[j]) <= a)
res = min(res,(double)d[j]*(aa+b) + (double)sqrt((double)dest(tr(B.x,B.y,B.x,B.y),c[j])));
forn(i,n)
if (dest(c[i],c[j]) <= a && i != j && d[i] > d[j] + 1) q.push(i), d[i] = d[j] + 1;
}
if (res == int_inf) { cout << "-1"; return 0; }
printf("%.8lf",(double)res);
return 0;
} | 3,652 | 1,874 |
#include <iostream>
#include <vector>
#include "binary_tree.h"
using namespace std;
class Solution {
public:
TreeNode* bstFromPreorder(vector<int>& preorder) {
if (preorder.size() == 0) return nullptr;
TreeNode* root = new TreeNode {preorder[0]};
for (int i = 1; i < preorder.size(); i++) {
TreeNode *parent = nullptr;
TreeNode *child = root;
// TreeNode *child = root;
int val = preorder[i];
while (child) {
parent = child;
if (child->val < val) {
child = child->right;
} else {
child = child->left;
}
}
if (parent->val < val) {
parent->right = new TreeNode {val};
} else {
parent->left = new TreeNode {val};
}
}
return root;
}
};
int main() {
vector<int> v {8, 5, 1, 7, 10, 12};
TreeNode* root = Solution().bstFromPreorder(v);
prettyPrintTree(root);
} | 1,089 | 320 |
// Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// 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 ReaderProxyData.cpp
*
*/
#include <fastrtps/rtps/builtin/data/ReaderProxyData.h>
#include <fastrtps/rtps/common/CDRMessage_t.h>
#include <fastrtps/log/Log.h>
namespace eprosima {
namespace fastrtps{
namespace rtps {
ReaderProxyData::ReaderProxyData() :
m_expectsInlineQos(false),
m_userDefinedId(0),
m_isAlive(true),
m_topicKind(NO_KEY)
{
}
ReaderProxyData::~ReaderProxyData()
{
logInfo(RTPS_PROXY_DATA,"ReaderProxyData destructor: "<< this->m_guid;);
}
ReaderProxyData::ReaderProxyData(const ReaderProxyData& readerInfo) :
m_expectsInlineQos(readerInfo.m_expectsInlineQos),
m_guid(readerInfo.m_guid),
m_unicastLocatorList(readerInfo.m_unicastLocatorList),
m_multicastLocatorList(readerInfo.m_multicastLocatorList),
m_key(readerInfo.m_key),
m_RTPSParticipantKey(readerInfo.m_RTPSParticipantKey),
m_typeName(readerInfo.m_typeName),
m_topicName(readerInfo.m_topicName),
m_userDefinedId(readerInfo.m_userDefinedId),
m_isAlive(readerInfo.m_isAlive),
m_topicKind(readerInfo.m_topicKind)
{
m_qos.setQos(readerInfo.m_qos, true);
}
ReaderProxyData& ReaderProxyData::operator=(const ReaderProxyData& readerInfo)
{
m_expectsInlineQos = readerInfo.m_expectsInlineQos;
m_guid = readerInfo.m_guid;
m_unicastLocatorList = readerInfo.m_unicastLocatorList;
m_multicastLocatorList = readerInfo.m_multicastLocatorList;
m_key = readerInfo.m_key;
m_RTPSParticipantKey = readerInfo.m_RTPSParticipantKey;
m_typeName = readerInfo.m_typeName;
m_topicName = readerInfo.m_topicName;
m_userDefinedId = readerInfo.m_userDefinedId;
m_isAlive = readerInfo.m_isAlive;
m_expectsInlineQos = readerInfo.m_expectsInlineQos;
m_topicKind = readerInfo.m_topicKind;
m_qos.setQos(readerInfo.m_qos, true);
return *this;
}
ParameterList_t ReaderProxyData::toParameterList()
{
ParameterList_t parameter_list;
for(LocatorListIterator lit = m_unicastLocatorList.begin();
lit!=m_unicastLocatorList.end();++lit)
{
ParameterLocator_t* p = new ParameterLocator_t(PID_UNICAST_LOCATOR,PARAMETER_LOCATOR_LENGTH,*lit);
parameter_list.m_parameters.push_back((Parameter_t*)p);
}
for(LocatorListIterator lit = m_multicastLocatorList.begin();
lit!=m_multicastLocatorList.end();++lit)
{
ParameterLocator_t* p = new ParameterLocator_t(PID_MULTICAST_LOCATOR,PARAMETER_LOCATOR_LENGTH,*lit);
parameter_list.m_parameters.push_back((Parameter_t*)p);
}
{
ParameterBool_t * p = new ParameterBool_t(PID_EXPECTS_INLINE_QOS,PARAMETER_BOOL_LENGTH,m_expectsInlineQos);
parameter_list.m_parameters.push_back((Parameter_t*)p);
}
{
ParameterGuid_t* p = new ParameterGuid_t(PID_PARTICIPANT_GUID,PARAMETER_GUID_LENGTH,m_RTPSParticipantKey);
parameter_list.m_parameters.push_back((Parameter_t*)p);
}
{
ParameterString_t * p = new ParameterString_t(PID_TOPIC_NAME,0,m_topicName);
parameter_list.m_parameters.push_back((Parameter_t*)p);
}
{
ParameterString_t * p = new ParameterString_t(PID_TYPE_NAME,0,m_typeName);
parameter_list.m_parameters.push_back((Parameter_t*)p);
}
{
ParameterKey_t * p = new ParameterKey_t(PID_KEY_HASH,16,m_key);
parameter_list.m_parameters.push_back((Parameter_t*)p);
}
{
ParameterGuid_t * p = new ParameterGuid_t(PID_ENDPOINT_GUID,16,m_guid);
parameter_list.m_parameters.push_back((Parameter_t*)p);
}
{
ParameterProtocolVersion_t* p = new ParameterProtocolVersion_t(PID_PROTOCOL_VERSION,4);
parameter_list.m_parameters.push_back((Parameter_t*)p);
}
{
ParameterVendorId_t*p = new ParameterVendorId_t(PID_VENDORID,4);
parameter_list.m_parameters.push_back((Parameter_t*)p);
}
if(m_qos.m_durability.sendAlways() || m_qos.m_durability.hasChanged)
{
DurabilityQosPolicy*p = new DurabilityQosPolicy();
*p = m_qos.m_durability;
parameter_list.m_parameters.push_back((Parameter_t*)p);
}
if(m_qos.m_durabilityService.sendAlways() || m_qos.m_durabilityService.hasChanged)
{
DurabilityServiceQosPolicy*p = new DurabilityServiceQosPolicy();
*p = m_qos.m_durabilityService;
parameter_list.m_parameters.push_back((Parameter_t*)p);
}
if(m_qos.m_deadline.sendAlways() || m_qos.m_deadline.hasChanged)
{
DeadlineQosPolicy*p = new DeadlineQosPolicy();
*p = m_qos.m_deadline;
parameter_list.m_parameters.push_back((Parameter_t*)p);
}
if(m_qos.m_latencyBudget.sendAlways() || m_qos.m_latencyBudget.hasChanged)
{
LatencyBudgetQosPolicy*p = new LatencyBudgetQosPolicy();
*p = m_qos.m_latencyBudget;
parameter_list.m_parameters.push_back((Parameter_t*)p);
}
if(m_qos.m_liveliness.sendAlways() || m_qos.m_liveliness.hasChanged)
{
LivelinessQosPolicy*p = new LivelinessQosPolicy();
*p = m_qos.m_liveliness;
parameter_list.m_parameters.push_back((Parameter_t*)p);
}
if(m_qos.m_reliability.sendAlways() || m_qos.m_reliability.hasChanged)
{
ReliabilityQosPolicy*p = new ReliabilityQosPolicy();
*p = m_qos.m_reliability;
parameter_list.m_parameters.push_back((Parameter_t*)p);
}
if(m_qos.m_lifespan.sendAlways() || m_qos.m_lifespan.hasChanged)
{
LifespanQosPolicy*p = new LifespanQosPolicy();
*p = m_qos.m_lifespan;
parameter_list.m_parameters.push_back((Parameter_t*)p);
}
if(m_qos.m_userData.sendAlways() || m_qos.m_userData.hasChanged)
{
UserDataQosPolicy*p = new UserDataQosPolicy();
*p = m_qos.m_userData;
parameter_list.m_parameters.push_back((Parameter_t*)p);
}
if(m_qos.m_timeBasedFilter.sendAlways() || m_qos.m_timeBasedFilter.hasChanged)
{
TimeBasedFilterQosPolicy*p = new TimeBasedFilterQosPolicy();
*p = m_qos.m_timeBasedFilter;
parameter_list.m_parameters.push_back((Parameter_t*)p);
}
if(m_qos.m_ownership.sendAlways() || m_qos.m_ownership.hasChanged)
{
OwnershipQosPolicy*p = new OwnershipQosPolicy();
*p = m_qos.m_ownership;
parameter_list.m_parameters.push_back((Parameter_t*)p);
}
if(m_qos.m_destinationOrder.sendAlways() || m_qos.m_destinationOrder.hasChanged)
{
DestinationOrderQosPolicy*p = new DestinationOrderQosPolicy();
*p = m_qos.m_destinationOrder;
parameter_list.m_parameters.push_back((Parameter_t*)p);
}
if(m_qos.m_presentation.sendAlways() || m_qos.m_presentation.hasChanged)
{
PresentationQosPolicy*p = new PresentationQosPolicy();
*p = m_qos.m_presentation;
parameter_list.m_parameters.push_back((Parameter_t*)p);
}
if(m_qos.m_partition.sendAlways() || m_qos.m_partition.hasChanged)
{
PartitionQosPolicy*p = new PartitionQosPolicy();
*p = m_qos.m_partition;
parameter_list.m_parameters.push_back((Parameter_t*)p);
}
if(m_qos.m_topicData.sendAlways() || m_qos.m_topicData.hasChanged)
{
TopicDataQosPolicy*p = new TopicDataQosPolicy();
*p = m_qos.m_topicData;
parameter_list.m_parameters.push_back((Parameter_t*)p);
}
if(m_qos.m_groupData.sendAlways() || m_qos.m_groupData.hasChanged)
{
GroupDataQosPolicy*p = new GroupDataQosPolicy();
*p = m_qos.m_groupData;
parameter_list.m_parameters.push_back((Parameter_t*)p);
}
if(m_qos.m_timeBasedFilter.sendAlways() || m_qos.m_timeBasedFilter.hasChanged)
{
TimeBasedFilterQosPolicy*p = new TimeBasedFilterQosPolicy();
*p = m_qos.m_timeBasedFilter;
parameter_list.m_parameters.push_back((Parameter_t*)p);
}
logInfo(RTPS_PROXY_DATA,"DiscoveredReaderData converted to ParameterList with " << parameter_list.m_parameters.size()<< " parameters");
return parameter_list;
}
bool ReaderProxyData::readFromCDRMessage(CDRMessage_t* msg)
{
ParameterList_t parameter_list;
if(ParameterList::readParameterListfromCDRMsg(msg, ¶meter_list, NULL, true)>0)
{
for(std::vector<Parameter_t*>::iterator it = parameter_list.m_parameters.begin();
it!=parameter_list.m_parameters.end();++it)
{
switch((*it)->Pid)
{
case PID_DURABILITY:
{
DurabilityQosPolicy * p = (DurabilityQosPolicy*)(*it);
m_qos.m_durability = *p;
break;
}
case PID_DURABILITY_SERVICE:
{
DurabilityServiceQosPolicy * p = (DurabilityServiceQosPolicy*)(*it);
m_qos.m_durabilityService = *p;
break;
}
case PID_DEADLINE:
{
DeadlineQosPolicy * p = (DeadlineQosPolicy*)(*it);
m_qos.m_deadline = *p;
break;
}
case PID_LATENCY_BUDGET:
{
LatencyBudgetQosPolicy * p = (LatencyBudgetQosPolicy*)(*it);
m_qos.m_latencyBudget = *p;
break;
}
case PID_LIVELINESS:
{
LivelinessQosPolicy * p = (LivelinessQosPolicy*)(*it);
m_qos.m_liveliness = *p;
break;
}
case PID_RELIABILITY:
{
ReliabilityQosPolicy * p = (ReliabilityQosPolicy*)(*it);
m_qos.m_reliability = *p;
break;
}
case PID_LIFESPAN:
{
LifespanQosPolicy * p = (LifespanQosPolicy*)(*it);
m_qos.m_lifespan = *p;
break;
}
case PID_USER_DATA:
{
UserDataQosPolicy * p = (UserDataQosPolicy*)(*it);
m_qos.m_userData = *p;
break;
}
case PID_TIME_BASED_FILTER:
{
TimeBasedFilterQosPolicy * p = (TimeBasedFilterQosPolicy*)(*it);
m_qos.m_timeBasedFilter = *p;
break;
}
case PID_OWNERSHIP:
{
OwnershipQosPolicy * p = (OwnershipQosPolicy*)(*it);
m_qos.m_ownership = *p;
break;
}
case PID_DESTINATION_ORDER:
{
DestinationOrderQosPolicy * p = (DestinationOrderQosPolicy*)(*it);
m_qos.m_destinationOrder = *p;
break;
}
case PID_PRESENTATION:
{
PresentationQosPolicy * p = (PresentationQosPolicy*)(*it);
m_qos.m_presentation = *p;
break;
}
case PID_PARTITION:
{
PartitionQosPolicy * p = (PartitionQosPolicy*)(*it);
m_qos.m_partition = *p;
break;
}
case PID_TOPIC_DATA:
{
TopicDataQosPolicy * p = (TopicDataQosPolicy*)(*it);
m_qos.m_topicData = *p;
break;
}
case PID_GROUP_DATA:
{
GroupDataQosPolicy * p = (GroupDataQosPolicy*)(*it);
m_qos.m_groupData = *p;
break;
}
case PID_TOPIC_NAME:
{
ParameterString_t*p = (ParameterString_t*)(*it);
m_topicName = std::string(p->getName());
break;
}
case PID_TYPE_NAME:
{
ParameterString_t*p = (ParameterString_t*)(*it);
m_typeName = std::string(p->getName());
break;
}
case PID_PARTICIPANT_GUID:
{
ParameterGuid_t * p = (ParameterGuid_t*)(*it);
for(uint8_t i = 0; i < 16; ++i)
{
if(i < 12)
m_RTPSParticipantKey.value[i] = p->guid.guidPrefix.value[i];
else
m_RTPSParticipantKey.value[i] = p->guid.entityId.value[i - 12];
}
break;
}
case PID_ENDPOINT_GUID:
{
ParameterGuid_t * p = (ParameterGuid_t*)(*it);
m_guid = p->guid;
for(uint8_t i=0;i<16;++i)
{
if(i<12)
m_key.value[i] = p->guid.guidPrefix.value[i];
else
m_key.value[i] = p->guid.entityId.value[i - 12];
}
break;
}
case PID_UNICAST_LOCATOR:
{
ParameterLocator_t* p = (ParameterLocator_t*)(*it);
m_unicastLocatorList.push_back(p->locator);
break;
}
case PID_MULTICAST_LOCATOR:
{
ParameterLocator_t* p = (ParameterLocator_t*)(*it);
m_multicastLocatorList.push_back(p->locator);
break;
}
case PID_EXPECTS_INLINE_QOS:
{
ParameterBool_t*p =(ParameterBool_t*)(*it);
m_expectsInlineQos = p->value;
break;
}
case PID_KEY_HASH:
{
ParameterKey_t*p=(ParameterKey_t*)(*it);
m_key = p->key;
iHandle2GUID(m_guid,m_key);
break;
}
default:
{
//logInfo(RTPS_PROXY_DATA,"Parameter with ID: " <<(uint16_t)(*it)->Pid << " NOT CONSIDERED");
break;
}
}
}
if(m_guid.entityId.value[3] == 0x04)
m_topicKind = NO_KEY;
else if(m_guid.entityId.value[3] == 0x07)
m_topicKind = WITH_KEY;
return true;
}
return false;
}
void ReaderProxyData::clear()
{
m_expectsInlineQos = false;
m_guid = c_Guid_Unknown;
m_unicastLocatorList.clear();
m_multicastLocatorList.clear();
m_key = InstanceHandle_t();
m_RTPSParticipantKey = InstanceHandle_t();
m_typeName = "";
m_topicName = "";
m_userDefinedId = 0;
m_qos = ReaderQos();
m_isAlive = true;
m_topicKind = NO_KEY;
}
void ReaderProxyData::update(ReaderProxyData* rdata)
{
m_unicastLocatorList = rdata->m_unicastLocatorList;
m_multicastLocatorList = rdata->m_multicastLocatorList;
m_qos.setQos(rdata->m_qos,false);
m_isAlive = rdata->m_isAlive;
m_expectsInlineQos = rdata->m_expectsInlineQos;
}
void ReaderProxyData::copy(ReaderProxyData* rdata)
{
m_guid = rdata->m_guid;
m_unicastLocatorList = rdata->m_unicastLocatorList;
m_multicastLocatorList = rdata->m_multicastLocatorList;
m_key = rdata->m_key;
m_RTPSParticipantKey = rdata->m_RTPSParticipantKey;
m_typeName = rdata->m_typeName;
m_topicName = rdata->m_topicName;
m_userDefinedId = rdata->m_userDefinedId;
m_qos = rdata->m_qos;
//cout << "COPYING DATA: expects inlineQOS : " << rdata->m_expectsInlineQos << endl;
m_expectsInlineQos = rdata->m_expectsInlineQos;
m_isAlive = rdata->m_isAlive;
m_topicKind = rdata->m_topicKind;
}
RemoteReaderAttributes ReaderProxyData::toRemoteReaderAttributes() const
{
RemoteReaderAttributes remoteAtt;
remoteAtt.guid = m_guid;
remoteAtt.expectsInlineQos = this->m_expectsInlineQos;
remoteAtt.endpoint.durabilityKind = m_qos.m_durability.durabilityKind();
remoteAtt.endpoint.endpointKind = READER;
remoteAtt.endpoint.topicKind = m_topicKind;
remoteAtt.endpoint.reliabilityKind = m_qos.m_reliability.kind == RELIABLE_RELIABILITY_QOS ? RELIABLE : BEST_EFFORT;
remoteAtt.endpoint.unicastLocatorList = this->m_unicastLocatorList;
remoteAtt.endpoint.multicastLocatorList = this->m_multicastLocatorList;
return remoteAtt;
}
}
} /* namespace rtps */
} /* namespace eprosima */
| 17,829 | 5,989 |
#include "p4unit.h"
#include <boost/log/attributes/constant.hpp>
#include <boost/log/sinks/syslog_backend.hpp>
#include <boost/tokenizer.hpp>
#include <fstream>
#include <sstream>
#include "../p4l/lexer.h"
namespace {
boost::log::sources::severity_logger<int> _logger(boost::log::keywords::severity = boost::log::sinks::syslog::debug);
std::string::size_type get_position_index(const std::string& content, const Position& position)
{
const std::string newline(1, '\n');
std::string::size_type index = 0;
for (auto it = 0U; it != position._line; ++it)
{
auto next_index = content.find_first_of(newline, index);
if (next_index == std::string::npos)
{
BOOST_LOG_SEV(_logger, boost::log::sinks::syslog::error) << "has " << it + 1 << " lines, but changes requested on line " << position._line;
return std::string::npos;
}
index = next_index + 1;
}
auto line_end_index = content.find_first_of(newline, index);
if (line_end_index == std::string::npos)
{
line_end_index = content.size();
}
if (index + position._character < line_end_index)
{
return index + position._character;
}
BOOST_LOG_SEV(_logger, boost::log::sinks::syslog::error) << "line " << position._line << " is shorter than " << position._character << " characters";
return std::string::npos;
}
} // namespace
#if 0
bool Symbol_collector::preorder(const IR::Node* node)
{
if (!node->is<Util::IHasSourceInfo>())
{
return false;
}
if (auto ctxt = getContext())
{
Range range;
const char* file = "";
if (auto info = node->getSourceInfo())
{
range.set(info);
file = info.getSourceFile().c_str();
}
auto unit = _temp_path == file ? _unit_path.c_str() : file;
Location location{unit, range};
BOOST_LOG(_logger)
<< ctxt->depth
<< " " << node->node_type_name()
<< " " << node->toString()
<< " " << location;
// definitions
if (node->is<IR::Type_Header>() || node->is<IR::Type_HeaderUnion>() || node->is<IR::Type_Struct>() || node->is<IR::Type_Extern>() || node->is<IR::Type_Enum>())
{
std::ostringstream definition;
definition << node;
auto name = node->to<IR::IDeclaration>()->getName().toString().c_str();
_definitions.emplace(name, definition.str());
BOOST_LOG(_logger) << "Header or Struct: \"" << name << "\"\n" << definition.str();
}
else if (node->is<IR::Type_Typedef>())
{
auto name = node->to<IR::IDeclaration>()->getName().toString().c_str();
std::ostringstream definition;
definition << "typedef " << node->to<IR::Type_Typedef>()->type << " " << name << ";";
_definitions.emplace(name, definition.str());
BOOST_LOG(_logger) << "Typedef:\"" << name << "\"\n" << definition.str();
}
// highlights
if (_unit_path == unit)
{
if (node->is<IR::Parameter>() || node->is<IR::PathExpression>())
{
auto name = node->toString().c_str();
auto it = _highlights.find(name);
if (it == _highlights.end())
{
it = _highlights.emplace(std::piecewise_construct, std::forward_as_tuple(name), std::forward_as_tuple()).first;
}
it->second.emplace_back(range, DOCUMENT_HIGHLIGHT_KIND::Text);
_locations[unit].emplace(std::make_pair(range, name));
}
}
// locations of types, but need locations for all other interesting items as well
if (node->is<IR::Type_Name>())
{
_locations[unit].emplace(std::make_pair(range, node->toString().c_str()));
}
else if (ctxt->depth == _max_depth
&& node->is<IR::IDeclaration>()
&& !node->is<IR::Type_Control>()
&& !node->is<IR::Type_Parser>())
{
boost::optional<std::string> container;
if (!_container.empty())
{
container.emplace(_container.back());
}
auto name = node->to<IR::IDeclaration>()->getName().toString().c_str();
_indexes[name] = _symbols.size();
_symbols.emplace_back(name, get_symbol_kind(node), location, container);
if (node->is<IR::Type_Header>()
|| node->is<IR::Type_Struct>()
|| node->is<IR::P4Control>()
|| node->is<IR::P4Parser>())
{
_container.push_back(name);
++_max_depth;
}
}
}
return true;
}
void Symbol_collector::postorder(const IR::Node* node)
{
if (auto ctxt = getContext())
{
BOOST_LOG(_logger) << "exit from " << ctxt->depth << " " << node->node_type_name();
if (ctxt->depth < _max_depth)
{
--_max_depth;
_container.pop_back();
}
}
}
SYMBOL_KIND Symbol_collector::get_symbol_kind(const IR::Node* node)
{
if (node->is<IR::Declaration_Constant>())
{
return SYMBOL_KIND::Constant;
}
if (node->is<IR::Type_Header>() ||
node->is<IR::Type_Struct>())
{
return SYMBOL_KIND::Class;
}
if (node->is<IR::P4Parser>() ||
node->is<IR::P4Control>())
{
return SYMBOL_KIND::Class;
}
if (node->is<IR::Type_Typedef>())
{
return SYMBOL_KIND::Interface;
}
if (node->is<IR::Declaration_Instance>())
{
return SYMBOL_KIND::Variable;
}
if (node->is<IR::StructField>())
{
return SYMBOL_KIND::Field;
}
if (node->is<IR::ParserState>() ||
node->is<IR::P4Action>() ||
node->is<IR::P4Table>())
{
return SYMBOL_KIND::Method;
}
return SYMBOL_KIND::Null;
}
#endif
P4_file::P4_file(const std::string &command, const std::string &unit_path, const std::string& text)
: _command(std::make_unique<char[]>(command.size() + 1))
, _unit_path(unit_path)
, _source_code(text)
, _changed(true)
{
_logger.add_attribute("Tag", boost::log::attributes::constant<std::string>("P4UNIT"));
BOOST_LOG(_logger) << "constructor started.";
boost::char_separator<char> separator(" ");
boost::tokenizer<boost::char_separator<char>> tokens(command, separator);
auto arg = _command.get();
for (auto it = tokens.begin(); it != tokens.end(); ++it)
{
BOOST_LOG(_logger) << "process token " << *it;
auto size = it->size() + 1;
strncpy(arg, it->c_str(), size);
_argv.emplace_back(arg);
arg += size;
}
compile();
BOOST_LOG(_logger) << "constructed.";
}
void P4_file::change_source_code(const std::vector<Text_document_content_change_event>& content_changes)
{
_changed = true;
for (auto& it : content_changes)
{
if (!it._range)
{
_source_code = it._text;
BOOST_LOG(_logger) << "replaced entire source code with new content.";
}
else
{
const auto start = get_position_index(_source_code, it._range->_start);
const auto end = get_position_index(_source_code, it._range->_end);
if (start != std::string::npos && end != std::string::npos &&
start <= end && (!it._range_length || *it._range_length == end - start))
{
std::string content;
content.reserve(start + it._text.size() + _source_code.size() - end);
content = _source_code.substr(0, start);
content += it._text;
content += _source_code.substr(end);
_source_code = std::move(content);
BOOST_LOG(_logger) << "applied content change in range " << *it._range;
}
else
{
BOOST_LOG_SEV(_logger, boost::log::sinks::syslog::error) << "ignore invalid content change in range " << *it._range;
}
}
}
}
std::vector<Symbol_information>& P4_file::get_symbols()
{
if (_changed)
{
compile();
}
return _symbols;
}
boost::optional<std::string> P4_file::get_hover(const Location& location)
{
BOOST_LOG(_logger) << "search hover for " << location;
for (const auto& it : _locations[location._uri])
{
BOOST_LOG(_logger) << "check location " << it.first;
if (it.first & location._range)
{
auto def = _definitions.find(it.second);
if (def != _definitions.end())
{
return def->second;
}
return boost::none;
}
}
return boost::none;
}
boost::optional<std::vector<Text_document_highlight>> P4_file::get_highlights(const Location& location)
{
BOOST_LOG(_logger) << "search highlight for " << location;
for (const auto& it : _locations[location._uri])
{
BOOST_LOG(_logger) << "check location " << it.first;
if (it.first & location._range)
{
return _highlights[it.second];
}
}
return boost::none;
}
void P4_file::compile()
{
using token_type = p4l::p4lex_token<>;
using lexer_type = p4l::p4lex_iterator<token_type>;
using context_type = boost::wave::context<std::string::iterator, lexer_type>;
context_type::token_type current_token;
context_type ctx(_source_code.begin(), _source_code.end(), _unit_path.c_str());
ctx.set_language(boost::wave::support_cpp0x);
ctx.set_language(boost::wave::enable_preserve_comments(ctx.get_language()));
ctx.set_language(boost::wave::enable_prefer_pp_numbers(ctx.get_language()));
ctx.set_language(boost::wave::enable_emit_contnewlines(ctx.get_language()));
auto token = ctx.begin();
while (token != ctx.end()) {
try {
++token;
} catch (boost::wave::cpp_exception const& e) {
std::cerr << e.file_name() << "(" << e.line_no() << "): " << e.description() << std::endl;
} catch (std::exception const& e) {
std::cerr << current_token.get_position().get_file() << "(" << current_token.get_position().get_line() << "): " << "unexpected exception: " << e.what() << std::endl;
} catch (...) {
std::cerr << current_token.get_position().get_file() << "(" << current_token.get_position().get_line() << "): " << "unexpected exception." << std::endl;
}
}
#if 0
p4c_options.process(_argv.size(), _argv.data());
BOOST_LOG(_logger) << "processed options, number of errors " << ::errorCount();
auto temp_file_path = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path("%%%%-%%%%-%%%%-%%%%.p4");
p4c_options.file = temp_file_path.native();
std::ofstream ofs(p4c_options.file);
ofs << _source_code;
ofs.close();
BOOST_LOG(_logger) << "wrote document \"" << _unit_path << "\" to a temporary file \"" << p4c_options.file << "\"";
_program.reset(P4::parseP4File(p4c_options));
auto error_count = ::errorCount();
BOOST_LOG(_logger) << "compiled p4 source file, number of errors " << error_count;
auto existed = remove(temp_file_path);
BOOST_LOG(_logger) << "removed temporary file " << temp_file_path << " " << existed;
if (_program && error_count == 0)
{
_definitions.clear();
_highlights.clear();
_locations.clear();
_indexes.clear();
_symbols.clear();
Collected_data output{_symbols, _definitions, _highlights, _locations, _indexes};
Outline outline(p4c_options, _unit_path, output);
outline.process(_program);
_changed = false;
}
#endif
}
| 10,180 | 4,009 |
#include<stdio.h>
int fun(int n)
{
if(n == 0)
return 1;
else
return n*fun(n-1);
}
int main()
{
int a = 1;
int b = 2;
a = fun(b);
return a;
} | 168 | 92 |
/*
Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "qwebiconimageprovider_p.h"
#include "QtWebContext.h"
#include "QtWebIconDatabaseClient.h"
#include <QtCore/QUrl>
#include <QtGui/QImage>
#include <wtf/text/WTFString.h>
using namespace WebKit;
QWebIconImageProvider::QWebIconImageProvider()
: QDeclarativeImageProvider(QDeclarativeImageProvider::Image)
{
}
QWebIconImageProvider::~QWebIconImageProvider()
{
}
QImage QWebIconImageProvider::requestImage(const QString& id, QSize* size, const QSize& requestedSize)
{
QString decodedIconUrl = id;
decodedIconUrl.remove(0, decodedIconUrl.indexOf('#') + 1);
String pageURL = QString::fromUtf8(QUrl(decodedIconUrl).toEncoded());
// The string identifier has the leading image://webicon/ already stripped, so we just
// need to truncate from the first slash to get the context id.
QString contextIDAsString = id;
contextIDAsString.truncate(contextIDAsString.indexOf(QLatin1Char('/')));
bool ok = false;
uint64_t contextId = contextIDAsString.toUInt(&ok);
if (!ok)
return QImage();
QtWebContext* context = QtWebContext::contextByID(contextId);
if (!context)
return QImage();
QtWebIconDatabaseClient* iconDatabase = context->iconDatabase();
QImage icon = requestedSize.isValid() ? iconDatabase->iconImageForPageURL(pageURL, requestedSize) : iconDatabase->iconImageForPageURL(pageURL);
ASSERT(!icon.isNull());
if (size)
*size = icon.size();
return icon;
}
| 2,336 | 728 |
// Copyright (c) 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 "remoting/host/screen_resolution.h"
#include <limits>
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace remoting {
TEST(ScreenResolutionTest, Empty) {
ScreenResolution resolution;
EXPECT_TRUE(resolution.IsEmpty());
resolution.dimensions_.set(-1, 0);
EXPECT_TRUE(resolution.IsEmpty());
resolution.dimensions_.set(0, -1);
EXPECT_TRUE(resolution.IsEmpty());
resolution.dimensions_.set(-1, -1);
EXPECT_TRUE(resolution.IsEmpty());
resolution.dpi_.set(-1, 0);
EXPECT_TRUE(resolution.IsEmpty());
resolution.dpi_.set(0, -1);
EXPECT_TRUE(resolution.IsEmpty());
resolution.dpi_.set(-1, -1);
EXPECT_TRUE(resolution.IsEmpty());
}
TEST(ScreenResolutionTest, Invalid) {
ScreenResolution resolution;
EXPECT_TRUE(resolution.IsValid());
resolution.dimensions_.set(-1, 0);
EXPECT_FALSE(resolution.IsValid());
resolution.dimensions_.set(0, -1);
EXPECT_FALSE(resolution.IsValid());
resolution.dimensions_.set(-1, -1);
EXPECT_FALSE(resolution.IsValid());
resolution.dpi_.set(-1, 0);
EXPECT_FALSE(resolution.IsValid());
resolution.dpi_.set(0, -1);
EXPECT_FALSE(resolution.IsValid());
resolution.dpi_.set(-1, -1);
EXPECT_FALSE(resolution.IsValid());
}
TEST(ScreenResolutionTest, Scaling) {
ScreenResolution resolution(
SkISize::Make(100, 100), SkIPoint::Make(10, 10));
EXPECT_EQ(resolution.ScaleDimensionsToDpi(SkIPoint::Make(5, 5)),
SkISize::Make(50, 50));
EXPECT_EQ(resolution.ScaleDimensionsToDpi(SkIPoint::Make(20, 20)),
SkISize::Make(200, 200));
}
TEST(ScreenResolutionTest, ScalingSaturation) {
ScreenResolution resolution(
SkISize::Make(10000000, 1000000), SkIPoint::Make(1, 1));
EXPECT_EQ(resolution.ScaleDimensionsToDpi(SkIPoint::Make(1000000, 1000000)),
SkISize::Make(std::numeric_limits<int32>::max(),
std::numeric_limits<int32>::max()));
}
} // namespace remoting
| 2,150 | 838 |
//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "rtklib.h"
#include "convopt.h"
#include "codeopt.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TCodeOptDialog *CodeOptDialog;
//---------------------------------------------------------------------------
__fastcall TCodeOptDialog::TCodeOptDialog(TComponent* Owner)
: TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TCodeOptDialog::FormShow(TObject *Sender)
{
char mask[7][64]={""};
for (int i=0;i<7;i++) strcpy(mask[i],ConvOptDialog->CodeMask[i].c_str());
G01->Checked=mask[0][ 0]=='1';
G02->Checked=mask[0][ 1]=='1';
G03->Checked=mask[0][ 2]=='1';
G04->Checked=mask[0][ 3]=='1';
G05->Checked=mask[0][ 4]=='1';
G06->Checked=mask[0][ 5]=='1';
G07->Checked=mask[0][ 6]=='1';
G08->Checked=mask[0][ 7]=='1';
G14->Checked=mask[0][13]=='1';
G15->Checked=mask[0][14]=='1';
G16->Checked=mask[0][15]=='1';
G17->Checked=mask[0][16]=='1';
G18->Checked=mask[0][17]=='1';
G19->Checked=mask[0][18]=='1';
G20->Checked=mask[0][19]=='1';
G21->Checked=mask[0][20]=='1';
G22->Checked=mask[0][21]=='1';
G23->Checked=mask[0][22]=='1';
G24->Checked=mask[0][23]=='1';
G25->Checked=mask[0][24]=='1';
G26->Checked=mask[0][25]=='1';
R01->Checked=mask[1][ 0]=='1';
R02->Checked=mask[1][ 1]=='1';
R14->Checked=mask[1][13]=='1';
R19->Checked=mask[1][18]=='1';
R44->Checked=mask[1][43]=='1';
R45->Checked=mask[1][44]=='1';
R46->Checked=mask[1][45]=='1';
E01->Checked=mask[2][ 0]=='1';
E10->Checked=mask[2][ 9]=='1';
E11->Checked=mask[2][10]=='1';
E12->Checked=mask[2][11]=='1';
E13->Checked=mask[2][12]=='1';
E24->Checked=mask[2][23]=='1';
E25->Checked=mask[2][24]=='1';
E26->Checked=mask[2][25]=='1';
E27->Checked=mask[2][26]=='1';
E28->Checked=mask[2][27]=='1';
E29->Checked=mask[2][28]=='1';
E30->Checked=mask[2][29]=='1';
E31->Checked=mask[2][30]=='1';
E32->Checked=mask[2][31]=='1';
E33->Checked=mask[2][32]=='1';
E34->Checked=mask[2][33]=='1';
E37->Checked=mask[2][36]=='1';
E38->Checked=mask[2][37]=='1';
E39->Checked=mask[2][38]=='1';
J01->Checked=mask[3][ 0]=='1';
J07->Checked=mask[3][ 6]=='1';
J08->Checked=mask[3][ 7]=='1';
J13->Checked=mask[3][12]=='1';
J12->Checked=mask[3][11]=='1';
J16->Checked=mask[3][15]=='1';
J17->Checked=mask[3][16]=='1';
J18->Checked=mask[3][17]=='1';
J24->Checked=mask[3][23]=='1';
J25->Checked=mask[3][24]=='1';
J26->Checked=mask[3][25]=='1';
J35->Checked=mask[3][34]=='1';
J36->Checked=mask[3][35]=='1';
J33->Checked=mask[3][32]=='1';
C40->Checked=mask[5][39]=='1';
C41->Checked=mask[5][40]=='1';
C12->Checked=mask[5][11]=='1';
C27->Checked=mask[5][26]=='1';
C28->Checked=mask[5][27]=='1';
C29->Checked=mask[5][28]=='1';
C42->Checked=mask[5][41]=='1';
C43->Checked=mask[5][42]=='1';
C33->Checked=mask[5][32]=='1';
I49->Checked=mask[6][48]=='1';
I50->Checked=mask[6][49]=='1';
I51->Checked=mask[6][50]=='1';
I26->Checked=mask[6][25]=='1';
I52->Checked=mask[6][51]=='1';
I53->Checked=mask[6][52]=='1';
I54->Checked=mask[6][53]=='1';
I55->Checked=mask[6][54]=='1';
S01->Checked=mask[4][ 0]=='1';
S24->Checked=mask[4][23]=='1';
S25->Checked=mask[4][24]=='1';
S26->Checked=mask[4][25]=='1';
UpdateEnable();
}
//---------------------------------------------------------------------------
void __fastcall TCodeOptDialog::BtnOkClick(TObject *Sender)
{
char mask[7][64]={""};
for (int i=0;i<7;i++) for (int j=0;j<MAXCODE;j++) mask[i][j]='0';
if (G01->Checked) mask[0][ 0]='1';
if (G02->Checked) mask[0][ 1]='1';
if (G03->Checked) mask[0][ 2]='1';
if (G04->Checked) mask[0][ 3]='1';
if (G05->Checked) mask[0][ 4]='1';
if (G06->Checked) mask[0][ 5]='1';
if (G07->Checked) mask[0][ 6]='1';
if (G08->Checked) mask[0][ 7]='1';
if (G14->Checked) mask[0][13]='1';
if (G15->Checked) mask[0][14]='1';
if (G16->Checked) mask[0][15]='1';
if (G17->Checked) mask[0][16]='1';
if (G18->Checked) mask[0][17]='1';
if (G19->Checked) mask[0][18]='1';
if (G20->Checked) mask[0][19]='1';
if (G21->Checked) mask[0][20]='1';
if (G22->Checked) mask[0][21]='1';
if (G23->Checked) mask[0][22]='1';
if (G24->Checked) mask[0][23]='1';
if (G25->Checked) mask[0][24]='1';
if (G26->Checked) mask[0][25]='1';
if (R01->Checked) mask[1][ 0]='1';
if (R02->Checked) mask[1][ 1]='1';
if (R14->Checked) mask[1][13]='1';
if (R19->Checked) mask[1][18]='1';
if (R44->Checked) mask[1][43]='1';
if (R45->Checked) mask[1][44]='1';
if (R46->Checked) mask[1][45]='1';
if (E01->Checked) mask[2][ 0]='1';
if (E10->Checked) mask[2][ 9]='1';
if (E11->Checked) mask[2][10]='1';
if (E12->Checked) mask[2][11]='1';
if (E13->Checked) mask[2][12]='1';
if (E24->Checked) mask[2][23]='1';
if (E25->Checked) mask[2][24]='1';
if (E26->Checked) mask[2][25]='1';
if (E27->Checked) mask[2][26]='1';
if (E28->Checked) mask[2][27]='1';
if (E29->Checked) mask[2][28]='1';
if (E30->Checked) mask[2][29]='1';
if (E31->Checked) mask[2][30]='1';
if (E32->Checked) mask[2][31]='1';
if (E33->Checked) mask[2][32]='1';
if (E34->Checked) mask[2][33]='1';
if (E37->Checked) mask[2][36]='1';
if (E38->Checked) mask[2][37]='1';
if (E39->Checked) mask[2][38]='1';
if (J01->Checked) mask[3][ 0]='1';
if (J07->Checked) mask[3][ 6]='1';
if (J08->Checked) mask[3][ 7]='1';
if (J13->Checked) mask[3][12]='1';
if (J12->Checked) mask[3][11]='1';
if (J16->Checked) mask[3][15]='1';
if (J17->Checked) mask[3][16]='1';
if (J18->Checked) mask[3][17]='1';
if (J24->Checked) mask[3][23]='1';
if (J25->Checked) mask[3][24]='1';
if (J26->Checked) mask[3][25]='1';
if (J35->Checked) mask[3][34]='1';
if (J36->Checked) mask[3][35]='1';
if (J33->Checked) mask[3][32]='1';
if (C40->Checked) mask[5][39]='1';
if (C41->Checked) mask[5][40]='1';
if (C12->Checked) mask[5][11]='1';
if (C27->Checked) mask[5][26]='1';
if (C28->Checked) mask[5][27]='1';
if (C29->Checked) mask[5][28]='1';
if (C42->Checked) mask[5][41]='1';
if (C43->Checked) mask[5][42]='1';
if (C33->Checked) mask[5][32]='1';
if (I49->Checked) mask[6][48]='1';
if (I50->Checked) mask[6][49]='1';
if (I51->Checked) mask[6][50]='1';
if (I26->Checked) mask[6][25]='1';
if (I52->Checked) mask[6][51]='1';
if (I53->Checked) mask[6][52]='1';
if (I54->Checked) mask[6][53]='1';
if (I55->Checked) mask[6][54]='1';
if (S01->Checked) mask[4][ 0]='1';
if (S24->Checked) mask[4][23]='1';
if (S25->Checked) mask[4][24]='1';
if (S26->Checked) mask[4][25]='1';
for (int i=0;i<7;i++) ConvOptDialog->CodeMask[i]=mask[i];
}
//---------------------------------------------------------------------------
void __fastcall TCodeOptDialog::BtnSetAllClick(TObject *Sender)
{
int set=BtnSetAll->Caption=="Set All";
G01->Checked=set;
G02->Checked=set;
G03->Checked=set;
G04->Checked=set;
G05->Checked=set;
G06->Checked=set;
G07->Checked=set;
G08->Checked=set;
G14->Checked=set;
G15->Checked=set;
G16->Checked=set;
G17->Checked=set;
G18->Checked=set;
G19->Checked=set;
G20->Checked=set;
G21->Checked=set;
G22->Checked=set;
G23->Checked=set;
G24->Checked=set;
G25->Checked=set;
G26->Checked=set;
R01->Checked=set;
R02->Checked=set;
R14->Checked=set;
R19->Checked=set;
R44->Checked=set;
R45->Checked=set;
R46->Checked=set;
E01->Checked=set;
E10->Checked=set;
E11->Checked=set;
E12->Checked=set;
E13->Checked=set;
E24->Checked=set;
E25->Checked=set;
E26->Checked=set;
E27->Checked=set;
E28->Checked=set;
E29->Checked=set;
E30->Checked=set;
E31->Checked=set;
E32->Checked=set;
E33->Checked=set;
E34->Checked=set;
E37->Checked=set;
E38->Checked=set;
E39->Checked=set;
J01->Checked=set;
J07->Checked=set;
J08->Checked=set;
J13->Checked=set;
J12->Checked=set;
J16->Checked=set;
J17->Checked=set;
J18->Checked=set;
J24->Checked=set;
J25->Checked=set;
J26->Checked=set;
J35->Checked=set;
J36->Checked=set;
J33->Checked=set;
C40->Checked=set;
C41->Checked=set;
C12->Checked=set;
C27->Checked=set;
C28->Checked=set;
C29->Checked=set;
C42->Checked=set;
C43->Checked=set;
C33->Checked=set;
I49->Checked=set;
I50->Checked=set;
I51->Checked=set;
I26->Checked=set;
I52->Checked=set;
I53->Checked=set;
I54->Checked=set;
I55->Checked=set;
S01->Checked=set;
S24->Checked=set;
S25->Checked=set;
S26->Checked=set;
BtnSetAll->Caption=BtnSetAll->Caption=="Set All"?"Unset All":"Set All";
}
//---------------------------------------------------------------------------
void __fastcall TCodeOptDialog::UpdateEnable(void)
{
G01->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L1);
G02->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L1);
G03->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L1);
G04->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L1);
G05->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L1);
G06->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L1);
G07->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L1);
G08->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L1);
G14->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L2);
G15->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L2);
G16->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L2);
G17->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L2);
G18->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L2);
G19->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L2);
G20->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L2);
G21->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L2);
G22->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L2);
G23->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L2);
G24->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L5);
G25->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L5);
G26->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L5);
R01->Enabled=(NavSys&SYS_GLO)&&(FreqType&FREQTYPE_L1);
R02->Enabled=(NavSys&SYS_GLO)&&(FreqType&FREQTYPE_L1);
R14->Enabled=(NavSys&SYS_GLO)&&(FreqType&FREQTYPE_L2);
R19->Enabled=(NavSys&SYS_GLO)&&(FreqType&FREQTYPE_L2);
R44->Enabled=(NavSys&SYS_GLO)&&(FreqType&FREQTYPE_L5);
R45->Enabled=(NavSys&SYS_GLO)&&(FreqType&FREQTYPE_L5);
R46->Enabled=(NavSys&SYS_GLO)&&(FreqType&FREQTYPE_L5);
E01->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_L1);
E10->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_L1);
E11->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_L1);
E12->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_L1);
E13->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_L1);
E24->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_L5);
E25->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_L5);
E26->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_L5);
E27->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_L2);
E28->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_L2);
E29->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_L2);
E30->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_E6);
E31->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_E6);
E32->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_E6);
E33->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_E6);
E34->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_E6);
E37->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_E5ab);
E38->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_E5ab);
E39->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_E5ab);
J01->Enabled=(NavSys&SYS_QZS)&&(FreqType&FREQTYPE_L1);
J07->Enabled=(NavSys&SYS_QZS)&&(FreqType&FREQTYPE_L1);
J08->Enabled=(NavSys&SYS_QZS)&&(FreqType&FREQTYPE_L1);
J13->Enabled=(NavSys&SYS_QZS)&&(FreqType&FREQTYPE_L1);
J12->Enabled=(NavSys&SYS_QZS)&&(FreqType&FREQTYPE_L1);
J16->Enabled=(NavSys&SYS_QZS)&&(FreqType&FREQTYPE_L2);
J17->Enabled=(NavSys&SYS_QZS)&&(FreqType&FREQTYPE_L2);
J18->Enabled=(NavSys&SYS_QZS)&&(FreqType&FREQTYPE_L2);
J24->Enabled=(NavSys&SYS_QZS)&&(FreqType&FREQTYPE_L2);
J25->Enabled=(NavSys&SYS_QZS)&&(FreqType&FREQTYPE_L2);
J26->Enabled=(NavSys&SYS_QZS)&&(FreqType&FREQTYPE_L2);
J35->Enabled=(NavSys&SYS_QZS)&&(FreqType&FREQTYPE_E6);
J36->Enabled=(NavSys&SYS_QZS)&&(FreqType&FREQTYPE_E6);
J33->Enabled=(NavSys&SYS_QZS)&&(FreqType&FREQTYPE_E6);
C40->Enabled=(NavSys&SYS_CMP)&&(FreqType&FREQTYPE_L1);
C41->Enabled=(NavSys&SYS_CMP)&&(FreqType&FREQTYPE_L1);
C12->Enabled=(NavSys&SYS_CMP)&&(FreqType&FREQTYPE_L1);
C27->Enabled=(NavSys&SYS_CMP)&&(FreqType&FREQTYPE_L2);
C28->Enabled=(NavSys&SYS_CMP)&&(FreqType&FREQTYPE_L2);
C29->Enabled=(NavSys&SYS_CMP)&&(FreqType&FREQTYPE_L2);
C42->Enabled=(NavSys&SYS_CMP)&&(FreqType&FREQTYPE_E6);
C43->Enabled=(NavSys&SYS_CMP)&&(FreqType&FREQTYPE_E6);
C33->Enabled=(NavSys&SYS_CMP)&&(FreqType&FREQTYPE_E6);
I49->Enabled=(NavSys&SYS_IRN)&&(FreqType&FREQTYPE_L5);
I50->Enabled=(NavSys&SYS_IRN)&&(FreqType&FREQTYPE_L5);
I51->Enabled=(NavSys&SYS_IRN)&&(FreqType&FREQTYPE_L5);
I26->Enabled=(NavSys&SYS_IRN)&&(FreqType&FREQTYPE_L5);
I52->Enabled=(NavSys&SYS_IRN)&&(FreqType&FREQTYPE_S);
I53->Enabled=(NavSys&SYS_IRN)&&(FreqType&FREQTYPE_S);
I54->Enabled=(NavSys&SYS_IRN)&&(FreqType&FREQTYPE_S);
I55->Enabled=(NavSys&SYS_IRN)&&(FreqType&FREQTYPE_S);
S01->Enabled=(NavSys&SYS_SBS)&&(FreqType&FREQTYPE_L1);
S24->Enabled=(NavSys&SYS_SBS)&&(FreqType&FREQTYPE_L5);
S25->Enabled=(NavSys&SYS_SBS)&&(FreqType&FREQTYPE_L5);
S26->Enabled=(NavSys&SYS_SBS)&&(FreqType&FREQTYPE_L5);
}
//---------------------------------------------------------------------------
| 13,250 | 7,099 |