text string | size int64 | token_count int64 |
|---|---|---|
/*
* Author: Thomas Ingleby <thomas.c.ingleby@intel.com>
* Copyright (c) 2014 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#pragma once
#include "common.h"
#include <string>
namespace mraa {
/**
* @file
* @brief C++ API to common functions of MRAA
*
* This file defines the C++ interface for libmraa common functions
*/
/**
* Get libmraa version.
*
* @return libmraa version (e.g. v0.4.0-20-gb408207)
*/
std::string getVersion()
{
std::string ret = mraa_get_version();
return ret;
}
/**
* This function attempts to set the mraa process to a given priority and the
* scheduler to SCHED_RR. Highest * priority is typically 99 and minimum is 0.
* This function * will set to MAX if * priority is > MAX. Function will return
* -1 on failure.
*
* @param priority Value from typically 0 to 99
* @return The priority value set
*/
int setPriority(const unsigned int priority)
{
return mraa_set_priority(priority);
}
/**
* Get platform type, board must be initialised.
*
* @return mraa_platform_t Platform type enum
*/
mraa_platform_t getPlatformType()
{
return mraa_get_platform_type();
}
/**
* Print a textual representation of the mraa_result_t
*
* @param result the result to print
*/
void printError(mraa_result_t result)
{
mraa_result_print(result);
}
/**
* Checks if a pin is able to use the passed in mode.
*
* @param pin Physical Pin to be checked.
* @param mode the mode to be tested.
* @return boolean if the mode is supported, 0=false.
*/
bool pinModeTest(int pin, mraa_pinmodes_t mode)
{
return (bool) mraa_pin_mode_test(pin,mode);
}
}
| 2,661 | 896 |
#include "messageprovider.h"
MessageProvider::MessageProvider(QObject *parent) : QObject(parent)
{
_socket = new QTcpSocket(this);
connect(_socket, &QIODevice::readyRead, this, &MessageProvider::processMessage);
connect(_socket, &QAbstractSocket::disconnected,
[=](){emit this->disconnected();});
connect(_socket, &QAbstractSocket::connected,
[=](){emit this->connected();});
connect(_socket, QOverload<QAbstractSocket::SocketError>::of(&QAbstractSocket::error),
this, &MessageProvider::socketError);
//_stream.setDevice(_socket);
//_stream.setVersion(QDataStream::Qt_5_12);
}
void MessageProvider::connectToSrv(QString addr, qint16 port)
{
_socket->connectToHost(addr, port);
}
void MessageProvider::disconnectFromSrv()
{
_socket->disconnectFromHost();
}
void MessageProvider::setShip(QPoint point)
{
char cmd[3];
cmd[0] = SIG_SETUP_CELL;
cmd[1] = point.x();
cmd[2] = point.y();
write(cmd, 3);
}
void MessageProvider::ready()
{
char cmd[1];
cmd[0] = SIG_READY;
write(cmd, 1);
}
void MessageProvider::shot(QPoint point)
{
char cmd[3];
cmd[0] = SIG_SHOT;
cmd[1] = point.x();
cmd[2] = point.y();
write(cmd, 3);
}
void MessageProvider::nameResponse(QString name)
{
char cmdbuf[128];
cmdbuf[0] = SIG_RESPONSE_NAME;
cmdbuf[1] = char(name.length());
for(int i = 0; i < name.length(); ++i)
{
cmdbuf[i+2] = name.toStdString()[i];
}
write(cmdbuf, 2+name.length());
}
void MessageProvider::processMessage()
{
const int maxBufSize = 5*100*2; //5 bytes per cell repeated 100 times(full area)
char buf[maxBufSize];
int size = read(buf);
char* command = buf;
qDebug() << "received msg size: " << size;
while(command < (buf+size))
switch(*(command))
{
case SIG_REQUEST_NAME:
{
qDebug() << "DEBUG: name request";
emit sigNameRequest();
command+=1;
break;
}
case SIG_SHARE_NAME:
{
qDebug() << "DEBUG: name share" << buf+2;
int nameLen = command[1];
int temp = command[2 + nameLen];
command[2 + nameLen] = '\0';
QString name(command+2);
command[2 + nameLen] = temp;
emit sigShareName(name);
command += (2+nameLen);
break;
}
case SIG_SET_CELL:
{
qDebug() << "DEBUG: set cell";
GameArea::CellType t;
qDebug() << "DEBUG: received cell type is : " <<
"X: " << static_cast<int>(command[1]) <<
" y: " << static_cast<int>(command[2]) <<
" wnemy: " << static_cast<int>(command[3]) <<
static_cast<int>(command[4]);
switch(command[4])
{
case CELL_SEA:
t = GameArea::Sea;
break;
case CELL_SHIP:
t = GameArea::Ship;
break;
case CELL_SEA_SHOTED:
t = GameArea::ShotSea;
break;
case CELL_SHIP_WOUNDED:
t = GameArea::ShotShip;
break;
case CELL_SHIP_KILLED:
t = GameArea::KilledShip;
break;
}
if(command[3] == OWN)
emit sigOwnCellUpdate(QPoint(command[1], command[2]), t);
else if(command[3] == ENEMY)
emit sigEnemyCellUpdate(QPoint(command[1], command[2]), t);
command += 5;
break;
}
case SIG_GAME_STARTED:
{
qDebug() << "DEBUG: game started";
command += 1;
break;
}
case SIG_FIRE:
{
qDebug() << "DEBUG: fire";
emit sigYouTurn();
command += 1;
break;
}
case SIG_ERR_SHIPS_INCORRECT:
{
emit sigShipPlacementIncorrect();
emit externalMsg(tr("Ship placement incorrect"));
command += 1;
break;
}
case SIG_SHIP_PLACEMENT_OK:
{
emit sigShipPlacementOk();
command += 1;
break;
}
case SIG_NOT_READY:
{
emit sigNotReady();
command+=1;
break;
}
case SIG_WIN:
{
emit sigWin();
emit externalMsg("You win!");
command += 1;
break;
}
case SIG_LOSE:
{
emit sigLose();
emit externalMsg("You lose =(");
command += 1;
break;
}
default: qDebug() << "DEBUG: Unknown command"; return;
}
}
void MessageProvider::socketError(QAbstractSocket::SocketError err)
{
switch (err) {
case QAbstractSocket::HostNotFoundError:
emit externalMsg(tr("The host was not found"));
break;
case QAbstractSocket::ConnectionRefusedError:
emit externalMsg(tr("Connection was refused by destination host"));
break;
case QAbstractSocket::RemoteHostClosedError:
emit externalMsg(tr("Host closed"));
//emit disconnected();
break;
}
}
void MessageProvider::write(char* msg, int len)
{
_socket->write(msg, len);
}
int MessageProvider::read(char* msgPtr)
{
int len = _socket->bytesAvailable();
_socket->read(msgPtr, 128);
return len;
}
| 5,114 | 1,746 |
/*
* Copyright (C) 2021 mod.io Pty Ltd. <https://mod.io>
*
* This file is part of the mod.io UE4 Plugin.
*
* Distributed under the MIT License. (See accompanying file LICENSE or
* view online at <https://github.com/modio/modio-ue4/blob/main/LICENSE>)
*
*/
#include "ModioSubsystem.h"
#include "Engine/Engine.h"
#include "Internal/Convert/AuthParams.h"
#include "Internal/Convert/ErrorCode.h"
#include "Internal/Convert/FilterParams.h"
#include "Internal/Convert/InitializeOptions.h"
#include "Internal/Convert/List.h"
#include "Internal/Convert/ModCollectionEntry.h"
#include "Internal/Convert/ModDependency.h"
#include "Internal/Convert/ModInfo.h"
#include "Internal/Convert/ModInfoList.h"
#include "Internal/Convert/ModManagementEvent.h"
#include "Internal/Convert/ModProgressInfo.h"
#include "Internal/Convert/ModTagInfo.h"
#include "Internal/Convert/ModTagOptions.h"
#include "Internal/Convert/Rating.h"
#include "Internal/Convert/ReportParams.h"
#include "Internal/Convert/Terms.h"
#include "Internal/Convert/User.h"
#include "Internal/ModioConvert.h"
#include "ModioSettings.h"
#include <map>
template<typename DestKey, typename DestValue, typename SourceKey, typename SourceValue>
TMap<DestKey, DestValue> ToUnreal(std::map<SourceKey, SourceValue>&& OriginalMap);
template<typename Dest, typename Source>
TOptional<Dest> ToUnrealOptional(Source Original);
template<typename Dest, typename Source>
Dest ToBP(Source Original);
void UModioSubsystem::Initialize(FSubsystemCollectionBase& Collection)
{
Super::Initialize(Collection);
if (const UModioSettings* Settings = GetDefault<UModioSettings>())
{
SetLogLevel(Settings->LogLevel);
}
ImageCache = MakeUnique<FModioImageCache>();
}
void UModioSubsystem::Deinitialize()
{
ImageCache.Release();
Super::Deinitialize();
}
bool UModioSubsystem::ShouldCreateSubsystem(UObject* Outer) const
{
// @todo: Add hooks here where the user can decide where the subsystem is valid
return true;
}
void UModioSubsystem::InitializeAsync(const FModioInitializeOptions& Options, FOnErrorOnlyDelegateFast OnInitComplete)
{
Modio::InitializeAsync(ToModio(Options), [this, OnInitComplete](Modio::ErrorCode ec) {
InvalidateUserSubscriptionCache();
OnInitComplete.ExecuteIfBound(ToUnreal(ec));
});
}
void UModioSubsystem::K2_InitializeAsync(const FModioInitializeOptions& InitializeOptions,
FOnErrorOnlyDelegate InitCallback)
{
InitializeAsync(InitializeOptions, FOnErrorOnlyDelegateFast::CreateLambda(
[InitCallback](FModioErrorCode ec) { InitCallback.ExecuteIfBound(ec); }));
}
void UModioSubsystem::ListAllModsAsync(const FModioFilterParams& Filter, FOnListAllModsDelegateFast Callback)
{
Modio::ListAllModsAsync(ToModio(Filter),
[Callback](Modio::ErrorCode ec, Modio::Optional<Modio::ModInfoList> Result) {
Callback.ExecuteIfBound(ec, ToUnrealOptional<FModioModInfoList>(Result));
});
}
void UModioSubsystem::SubscribeToModAsync(FModioModID ModToSubscribeTo, FOnErrorOnlyDelegateFast OnSubscribeComplete)
{
Modio::SubscribeToModAsync(ToModio(ModToSubscribeTo), [this, OnSubscribeComplete](Modio::ErrorCode ec) {
InvalidateUserSubscriptionCache();
OnSubscribeComplete.ExecuteIfBound(ToUnreal(ec));
});
}
void UModioSubsystem::UnsubscribeFromModAsync(FModioModID ModToUnsubscribeFrom,
FOnErrorOnlyDelegateFast OnUnsubscribeComplete)
{
Modio::UnsubscribeFromModAsync(ToModio(ModToUnsubscribeFrom), [this, OnUnsubscribeComplete](Modio::ErrorCode ec) {
InvalidateUserSubscriptionCache();
OnUnsubscribeComplete.ExecuteIfBound(ToUnreal(ec));
});
}
void UModioSubsystem::FetchExternalUpdatesAsync(FOnErrorOnlyDelegateFast OnFetchDone)
{
Modio::FetchExternalUpdatesAsync([this, OnFetchDone](Modio::ErrorCode ec) {
InvalidateUserSubscriptionCache();
OnFetchDone.ExecuteIfBound(ToUnreal(ec));
});
}
void UModioSubsystem::EnableModManagement(FOnModManagementDelegateFast Callback)
{
Modio::EnableModManagement([this, Callback](Modio::ModManagementEvent Event) {
// @todo: For some smarter caching, look at the event and see if we should invalidate the cache
InvalidateUserInstallationCache();
Callback.ExecuteIfBound(ToUnreal(Event));
});
}
void UModioSubsystem::K2_ListAllModsAsync(const FModioFilterParams& Filter, FOnListAllModsDelegate Callback)
{
ListAllModsAsync(Filter, FOnListAllModsDelegateFast::CreateLambda(
[Callback](FModioErrorCode ec, TOptional<FModioModInfoList> ModList) {
Callback.ExecuteIfBound(ec, ToBP<FModioOptionalModInfoList>(ModList));
}));
}
void UModioSubsystem::K2_SubscribeToModAsync(FModioModID ModToSubscribeTo, FOnErrorOnlyDelegate OnSubscribeComplete)
{
SubscribeToModAsync(ModToSubscribeTo,
FOnErrorOnlyDelegateFast::CreateLambda(
[OnSubscribeComplete](FModioErrorCode ec) { OnSubscribeComplete.ExecuteIfBound(ec); }));
}
void UModioSubsystem::K2_UnsubscribeFromModAsync(FModioModID ModToUnsubscribeFrom,
FOnErrorOnlyDelegate OnUnsubscribeComplete)
{
UnsubscribeFromModAsync(ModToUnsubscribeFrom,
FOnErrorOnlyDelegateFast::CreateLambda([OnUnsubscribeComplete](FModioErrorCode ec) {
OnUnsubscribeComplete.ExecuteIfBound(ec);
}));
}
void UModioSubsystem::K2_FetchExternalUpdatesAsync(FOnErrorOnlyDelegate OnFetchDone)
{
FetchExternalUpdatesAsync(
FOnErrorOnlyDelegateFast::CreateLambda([OnFetchDone](FModioErrorCode ec) { OnFetchDone.ExecuteIfBound(ec); }));
}
void UModioSubsystem::K2_EnableModManagement(FOnModManagementDelegate Callback)
{
EnableModManagement(FOnModManagementDelegateFast::CreateLambda(
[Callback](FModioModManagementEvent Event) { Callback.ExecuteIfBound(Event); }));
}
void UModioSubsystem::DisableModManagement()
{
Modio::DisableModManagement();
}
void UModioSubsystem::ShutdownAsync(FOnErrorOnlyDelegateFast OnShutdownComplete)
{
Modio::ShutdownAsync([this, OnShutdownComplete](Modio::ErrorCode ec) {
InvalidateUserSubscriptionCache();
OnShutdownComplete.ExecuteIfBound(ToUnreal(ec));
});
}
void UModioSubsystem::K2_ShutdownAsync(FOnErrorOnlyDelegate OnShutdownComplete)
{
ShutdownAsync(FOnErrorOnlyDelegateFast::CreateLambda(
[OnShutdownComplete](FModioErrorCode ec) { OnShutdownComplete.ExecuteIfBound(ec); }));
}
void UModioSubsystem::RunPendingHandlers()
{
InvalidateUserSubscriptionCache();
Modio::RunPendingHandlers();
}
void UModioSubsystem::SetLogLevel(EModioLogLevel UnrealLogLevel)
{
Modio::SetLogLevel(ToModio(UnrealLogLevel));
}
bool UModioSubsystem::IsModManagementBusy()
{
return Modio::IsModManagementBusy();
}
TOptional<FModioModProgressInfo> UModioSubsystem::QueryCurrentModUpdate()
{
return ToUnrealOptional<FModioModProgressInfo>(Modio::QueryCurrentModUpdate());
}
FModioOptionalModProgressInfo UModioSubsystem::K2_QueryCurrentModUpdate()
{
return ToBP<FModioOptionalModProgressInfo>(QueryCurrentModUpdate());
}
const TMap<FModioModID, FModioModCollectionEntry>& UModioSubsystem::QueryUserSubscriptions()
{
if (!CachedUserSubscriptions)
{
CachedUserSubscriptions = ToUnreal<FModioModID, FModioModCollectionEntry>(Modio::QueryUserSubscriptions());
}
return CachedUserSubscriptions.GetValue();
}
const TMap<FModioModID, FModioModCollectionEntry>& UModioSubsystem::QueryUserInstallations(bool bIncludeOutdatedMods)
{
TOptional<TMap<FModioModID, FModioModCollectionEntry>>& UserInstallation =
bIncludeOutdatedMods ? CachedUserInstallationWithOutdatedMods : CachedUserInstallationWithoutOutdatedMods;
if (!UserInstallation)
{
UserInstallation =
ToUnreal<FModioModID, FModioModCollectionEntry>(Modio::QueryUserInstallations(bIncludeOutdatedMods));
}
return UserInstallation.GetValue();
}
TOptional<FModioUser> UModioSubsystem::QueryUserProfile()
{
return ToUnrealOptional<FModioUser>(Modio::QueryUserProfile());
}
FModioOptionalUser UModioSubsystem::K2_QueryUserProfile()
{
return ToBP<FModioOptionalUser>(QueryUserProfile());
}
void UModioSubsystem::GetModInfoAsync(FModioModID ModId, FOnGetModInfoDelegateFast Callback)
{
Modio::GetModInfoAsync(ToModio(ModId), [Callback](Modio::ErrorCode ec, Modio::Optional<Modio::ModInfo> ModInfo) {
Callback.ExecuteIfBound(ec, ToUnrealOptional<FModioModInfo>(ModInfo));
});
}
void UModioSubsystem::K2_GetModInfoAsync(FModioModID ModId, FOnGetModInfoDelegate Callback)
{
GetModInfoAsync(ModId, FOnGetModInfoDelegateFast::CreateLambda(
[Callback](FModioErrorCode ec, TOptional<FModioModInfo> ModInfo) {
Callback.ExecuteIfBound(ec, ToBP<FModioOptionalModInfo>(ModInfo));
}));
}
void UModioSubsystem::GetModMediaAsync(FModioModID ModId, EModioAvatarSize AvatarSize, FOnGetMediaDelegateFast Callback)
{
Modio::GetModMediaAsync(ToModio(ModId), ToModio(AvatarSize),
[Callback](Modio::ErrorCode ec, Modio::Optional<Modio::filesystem::path> Path) {
// Manually calling ToUnreal on the path and assigning to the member of FModioImage
// because we already have a Modio::filesystem::path -> FString overload of ToUnreal
// TODO: @modio-ue4 Potentially refactor ToUnreal(Modio::filesystem::path) as a template
// function returning type T so we can be explicit about the expected type
if (Path)
{
FModioImage Out;
Out.ImagePath = ToUnreal(Path.value());
Callback.ExecuteIfBound(ec, Out);
}
else
{
Callback.ExecuteIfBound(ec, {});
}
});
}
void UModioSubsystem::GetModMediaAsync(FModioModID ModId, EModioGallerySize GallerySize, int32 Index,
FOnGetMediaDelegateFast Callback)
{
Modio::GetModMediaAsync(ToModio(ModId), ToModio(GallerySize), Index,
[Callback](Modio::ErrorCode ec, Modio::Optional<Modio::filesystem::path> Path) {
// Manually calling ToUnreal on the path and assigning to the member of FModioImage
// because we already have a Modio::filesystem::path -> FString overload of ToUnreal
// TODO: @modio-ue4 Potentially refactor ToUnreal(Modio::filesystem::path) as a template
// function returning type T so we can be explicit about the expected type
if (Path)
{
FModioImage Out;
Out.ImagePath = ToUnreal(Path.value());
Callback.ExecuteIfBound(ec, Out);
}
else
{
Callback.ExecuteIfBound(ec, {});
}
});
}
void UModioSubsystem::GetModMediaAsync(FModioModID ModId, EModioLogoSize LogoSize, FOnGetMediaDelegateFast Callback)
{
Modio::GetModMediaAsync(ToModio(ModId), ToModio(LogoSize),
[Callback](Modio::ErrorCode ec, Modio::Optional<Modio::filesystem::path> Path) {
// Manually calling ToUnreal on the path and assigning to the member of FModioImage
// because we already have a Modio::filesystem::path -> FString overload of ToUnreal
// TODO: @modio-ue4 Potentially refactor ToUnreal(Modio::filesystem::path) as a template
// function returning type T so we can be explicit about the expected type
if (Path)
{
FModioImage Out;
Out.ImagePath = ToUnreal(Path.value());
Callback.ExecuteIfBound(ec, Out);
}
else
{
Callback.ExecuteIfBound(ec, {});
}
});
}
void UModioSubsystem::K2_GetModMediaAvatarAsync(FModioModID ModId, EModioAvatarSize AvatarSize,
FOnGetMediaDelegate Callback)
{
GetModMediaAsync(
ModId, AvatarSize,
FOnGetMediaDelegateFast::CreateLambda([Callback](FModioErrorCode ec, TOptional<FModioImage> Media) {
Callback.ExecuteIfBound(ec, ToBP<FModioOptionalImage>(Media));
}));
}
void UModioSubsystem::K2_GetModMediaGalleryImageAsync(FModioModID ModId, EModioGallerySize GallerySize, int32 Index,
FOnGetMediaDelegate Callback)
{
GetModMediaAsync(
ModId, GallerySize, Index,
FOnGetMediaDelegateFast::CreateLambda([Callback](FModioErrorCode ec, TOptional<FModioImage> Media) {
Callback.ExecuteIfBound(ec, ToBP<FModioOptionalImage>(Media));
}));
}
void UModioSubsystem::K2_GetModMediaLogoAsync(FModioModID ModId, EModioLogoSize LogoSize, FOnGetMediaDelegate Callback)
{
GetModMediaAsync(
ModId, LogoSize,
FOnGetMediaDelegateFast::CreateLambda([Callback](FModioErrorCode ec, TOptional<FModioImage> Media) {
Callback.ExecuteIfBound(ec, ToBP<FModioOptionalImage>(Media));
}));
}
void UModioSubsystem::GetModTagOptionsAsync(FOnGetModTagOptionsDelegateFast Callback)
{
if (CachedModTags)
{
Callback.ExecuteIfBound({}, CachedModTags);
return;
}
Modio::GetModTagOptionsAsync(
[this, Callback](Modio::ErrorCode ec, Modio::Optional<Modio::ModTagOptions> ModTagOptions) {
CachedModTags = ToUnrealOptional<FModioModTagOptions>(ModTagOptions);
Callback.ExecuteIfBound(ec, ToUnrealOptional<FModioModTagOptions>(ModTagOptions));
});
}
void UModioSubsystem::K2_GetModTagOptionsAsync(FOnGetModTagOptionsDelegate Callback)
{
GetModTagOptionsAsync(FOnGetModTagOptionsDelegateFast::CreateLambda(
[Callback](FModioErrorCode ec, TOptional<FModioModTagOptions> ModTagOptions) {
Callback.ExecuteIfBound(ec, ToBP<FModioOptionalModTagOptions>(ModTagOptions));
}));
}
void UModioSubsystem::RequestEmailAuthCodeAsync(const FModioEmailAddress& EmailAddress,
FOnErrorOnlyDelegateFast Callback)
{
Modio::RequestEmailAuthCodeAsync(ToModio(EmailAddress),
[Callback](Modio::ErrorCode ec) { Callback.ExecuteIfBound(ToUnreal(ec)); });
}
void UModioSubsystem::K2_RequestEmailAuthCodeAsync(const FModioEmailAddress& EmailAddress,
FOnErrorOnlyDelegate Callback)
{
RequestEmailAuthCodeAsync(EmailAddress, FOnErrorOnlyDelegateFast::CreateLambda(
[Callback](FModioErrorCode ec) { Callback.ExecuteIfBound(ec); }));
}
void UModioSubsystem::AuthenticateUserEmailAsync(const FModioEmailAuthCode& AuthenticationCode,
FOnErrorOnlyDelegateFast Callback)
{
Modio::AuthenticateUserEmailAsync(ToModio(AuthenticationCode),
[Callback](FModioErrorCode ec) { Callback.ExecuteIfBound(ec); });
}
void UModioSubsystem::K2_AuthenticateUserEmailAsync(const FModioEmailAuthCode& AuthenticationCode,
FOnErrorOnlyDelegate Callback)
{
AuthenticateUserEmailAsync(
AuthenticationCode,
FOnErrorOnlyDelegateFast::CreateLambda([Callback](FModioErrorCode ec) { Callback.ExecuteIfBound(ec); }));
}
void UModioSubsystem::AuthenticateUserExternalAsync(const FModioAuthenticationParams& User,
EModioAuthenticationProvider Provider,
FOnErrorOnlyDelegateFast Callback)
{
Modio::AuthenticateUserExternalAsync(ToModio(User), ToModio(Provider),
[Callback](Modio::ErrorCode ec) { Callback.ExecuteIfBound(ec); });
}
void UModioSubsystem::K2_AuthenticateUserExternalAsync(const FModioAuthenticationParams& User,
EModioAuthenticationProvider Provider,
FOnErrorOnlyDelegate Callback)
{
AuthenticateUserExternalAsync(
User, Provider,
FOnErrorOnlyDelegateFast::CreateLambda([Callback](FModioErrorCode ec) { Callback.ExecuteIfBound(ec); }));
}
void UModioSubsystem::GetTermsOfUseAsync(EModioAuthenticationProvider Provider, EModioLanguage Locale,
FOnGetTermsOfUseDelegateFast Callback)
{
Modio::GetTermsOfUseAsync(ToModio(Provider), ToModio(Locale),
[Callback](Modio::ErrorCode ec, Modio::Optional<Modio::Terms> Terms) {
Callback.ExecuteIfBound(ec, ToUnrealOptional<FModioTerms>(Terms));
});
}
void UModioSubsystem::K2_GetTermsOfUseAsync(EModioAuthenticationProvider Provider, EModioLanguage Locale,
FOnGetTermsOfUseDelegate Callback)
{
GetTermsOfUseAsync(
Provider, Locale,
FOnGetTermsOfUseDelegateFast::CreateLambda([Callback](FModioErrorCode ec, TOptional<FModioTerms> Terms) {
Callback.ExecuteIfBound(ec, ToBP<FModioOptionalTerms>(Terms));
}));
}
void UModioSubsystem::ClearUserDataAsync(FOnErrorOnlyDelegateFast Callback)
{
Modio::ClearUserDataAsync([Callback](Modio::ErrorCode ec) { Callback.ExecuteIfBound(ToUnreal(ec)); });
}
void UModioSubsystem::K2_ClearUserDataAsync(FOnErrorOnlyDelegate Callback)
{
ClearUserDataAsync(
FOnErrorOnlyDelegateFast::CreateLambda([Callback](FModioErrorCode ec) { Callback.ExecuteIfBound(ec); }));
}
void UModioSubsystem::GetUserMediaAsync(EModioAvatarSize AvatarSize, FOnGetMediaDelegateFast Callback)
{
Modio::GetUserMediaAsync(ToModio(AvatarSize),
[Callback](Modio::ErrorCode ec, Modio::Optional<Modio::filesystem::path> Media) {
// Manually calling ToUnreal on the path and assigning to the member of FModioImage
// because we already have a Modio::filesystem::path -> FString overload of ToUnreal
// TODO: @modio-ue4 Potentially refactor ToUnreal(Modio::filesystem::path) as a
// template function returning type T so we can be explicit about the expected type
if (Media)
{
FModioImage Out;
Out.ImagePath = ToUnreal(Media.value());
Callback.ExecuteIfBound(ec, Out);
}
else
{
Callback.ExecuteIfBound(ec, {});
}
});
}
void UModioSubsystem::K2_GetUserMediaAvatarAsync(EModioAvatarSize AvatarSize, FOnGetMediaDelegate Callback)
{
GetUserMediaAsync(AvatarSize, FOnGetMediaDelegateFast::CreateLambda(
[Callback](FModioErrorCode ec, TOptional<FModioImage> ModioMedia) {
Callback.ExecuteIfBound(ec, ToBP<FModioOptionalImage>(ModioMedia));
}));
}
void UModioSubsystem::InvalidateUserSubscriptionCache()
{
CachedUserSubscriptions.Reset();
}
void UModioSubsystem::InvalidateUserInstallationCache()
{
CachedUserInstallationWithOutdatedMods.Reset();
CachedUserInstallationWithoutOutdatedMods.Reset();
}
FModioImageCache& UModioSubsystem::GetImageCache() const
{
return *ImageCache;
}
TArray<FModioValidationError> UModioSubsystem::GetLastValidationError()
{
TArray<FModioValidationError> Errors;
for (const auto& Error : Modio::GetLastValidationError())
{
Errors.Add(FModioValidationError {ToUnreal(Error.Field), ToUnreal(Error.Error)});
}
return Errors;
}
TMap<FModioModID, FModioModCollectionEntry> UModioSubsystem::QuerySystemInstallations()
{
return ToUnreal<FModioModID, FModioModCollectionEntry>(Modio::QuerySystemInstallations());
}
void UModioSubsystem::ForceUninstallModAsync(FModioModID ModToRemove, FOnErrorOnlyDelegate Callback)
{
Modio::ForceUninstallModAsync(ToModio(ModToRemove),
[Callback](FModioErrorCode ec) { Callback.ExecuteIfBound(ec); });
}
void UModioSubsystem::SubmitModRatingAsync(FModioModID Mod, EModioRating Rating, FOnErrorOnlyDelegateFast Callback)
{
Modio::SubmitModRatingAsync(ToModio(Mod), ToModio(Rating),
[Callback](FModioErrorCode ec) { Callback.ExecuteIfBound(ec); });
}
void UModioSubsystem::K2_SubmitModRatingAsync(FModioModID Mod, EModioRating Rating, FOnErrorOnlyDelegate Callback)
{
SubmitModRatingAsync(Mod, Rating, FOnErrorOnlyDelegateFast::CreateLambda([Callback](FModioErrorCode ec) {
Callback.ExecuteIfBound(ec);
}));
}
void UModioSubsystem::ReportContentAsync(FModioReportParams Report, FOnErrorOnlyDelegateFast Callback)
{
Modio::ReportContentAsync(ToModio(Report), [Callback](FModioErrorCode ec) { Callback.ExecuteIfBound(ec); });
}
void UModioSubsystem::K2_ReportContentAsync(FModioReportParams Report, FOnErrorOnlyDelegate Callback)
{
ReportContentAsync(Report, FOnErrorOnlyDelegateFast::CreateLambda(
[Callback](FModioErrorCode ec) { Callback.ExecuteIfBound(ec); }));
}
void UModioSubsystem::GetModDependenciesAsync(FModioModID ModID, FOnGetModDependenciesDelegateFast Callback)
{
Modio::GetModDependenciesAsync(
ToModio(ModID), [Callback](Modio::ErrorCode ec, Modio::Optional<Modio::ModDependencyList> Dependencies) {
if (Dependencies)
{
FModioModDependencyList Out;
Out.InternalList = ToUnreal<FModioModDependency>(Dependencies->GetRawList());
Out.PagedResult = FModioPagedResult(Dependencies.value());
Callback.ExecuteIfBound(ec, Out);
}
else
{
Callback.ExecuteIfBound(ec, {});
}
});
}
MODIO_API void UModioSubsystem::K2_GetModDependenciesAsync(FModioModID ModID, FOnGetModDependenciesDelegate Callback)
{
GetModDependenciesAsync(ModID, FOnGetModDependenciesDelegateFast::CreateLambda(
[Callback](FModioErrorCode ec, TOptional<FModioModDependencyList> Dependencies) {
Callback.ExecuteIfBound(
ec, FModioOptionalModDependencyList(MoveTempIfPossible(Dependencies)));
}));
}
/// File scope implementations
#pragma region Implementation
template<typename DestKey, typename DestValue, typename SourceKey, typename SourceValue>
TMap<DestKey, DestValue> ToUnreal(std::map<SourceKey, SourceValue>&& OriginalMap)
{
TMap<DestKey, DestValue> Result;
Result.Reserve(OriginalMap.size());
for (auto& It : OriginalMap)
{
Result.Add(ToUnreal(It.first), ToUnreal(It.second));
}
return Result;
}
template<typename Dest, typename Source>
TOptional<Dest> ToUnrealOptional(Source Original)
{
TOptional<Dest> DestinationOptional = {};
if (Original)
{
DestinationOptional = ToUnreal(Original.value());
}
return DestinationOptional;
}
template<typename Dest, typename Source>
Dest ToBP(Source Original)
{
Dest Result = {MoveTempIfPossible(Original)};
return Result;
}
#pragma endregion
| 21,223 | 7,834 |
/// \file fon9/Subr.hpp
/// \author fonwinz@gmail.com
#ifndef __fon9_Subr_hpp__
#define __fon9_Subr_hpp__
#include "fon9/DummyMutex.hpp"
#include "fon9/MustLock.hpp"
#include "fon9/SortedVector.hpp"
namespace fon9 {
/// Subject/Subscriber 註冊取得的 ID, 用來取消註冊時使用.
/// - 此ID的編碼方式為: 在新的訂閱者註冊時, 為目前最後一個ID+1, 如果現在沒有任何訂閱者則使用1.
/// - 所以如果最後一個訂閱者為 0xffffffff... 則無法再註冊新的訂閱者, 此時註冊就會失敗傳回 nullptr
using SubConn = struct SubId*;
fon9_WARN_DISABLE_PADDING;
/// 提供給 Subject 儲存訂閱者的容器.
template <class SubscriberT>
class SubrMap : private SortedVector<SubConn, SubscriberT> {
using base = SortedVector<SubConn, SubscriberT>;
unsigned FirstReserve_;
public:
using typename base::size_type;
using typename base::iterator;
using typename base::difference_type;
using typename base::value_type;
/// \param firstReserve 當加入第一個元素時的預分配資料量,0表示使用預設值.
/// - 第一個 subr 註冊時, 表示此 Subject 是讓人感興趣的.
/// - 可以預期, 接下來可能還會有別人訂閱.
/// - 預先分配 **一小塊** 可能的空間, 可大幅改進後續訂閱者的處理速度.
/// - 在 x64 系統裡: 如果 SubscriberT=Object*; 加上 SubId; 每個 T 占用 sizeof(void*)*2 = 16;
/// - 所以如果 firstReserve=64, 則加入第一個 subr 時大約占用 16 bytes * 64 items = 1024 bytes.
SubrMap(unsigned firstReserve) : FirstReserve_{firstReserve} {
}
using base::begin;
using base::end;
using base::erase;
using base::size;
using base::empty;
using base::sindex;
using base::clear;
/// 使用 SortedVector::find(SubConn id) 進行二元搜尋.
iterator find(SubConn id) {
return base::find(id);
}
/// 使用 std::find(subr) 線性搜尋, subr 必須提供 `==` 操作.
template <class SubscriberT2>
iterator find(const SubscriberT2& subr) {
return std::find_if(this->begin(), this->end(), [&subr](const value_type& i) {
return(i.second == subr);
});
}
/// 移除全部相同的 subr, 傳回移除的數量.
template <class SubscriberT2>
size_type remove(const SubscriberT2& subr, size_type ibegin, size_type iend) {
return this->remove_if(ibegin, iend, [&subr](const value_type& i) -> bool {
return(i.second == subr);
});
}
/// 在尾端建立一個 Subscriber.
/// \return 傳回nullptr表示失敗, 請參閱 \ref SubConn
template <class... ArgsT>
SubConn emplace_back(ArgsT&&... args) {
SubConn id;
if (fon9_LIKELY(!this->empty())) {
SubConn lastid = this->back().first;
id = reinterpret_cast<SubConn>(reinterpret_cast<uintptr_t>(lastid) + 1);
if (fon9_UNLIKELY(id < lastid))
return nullptr;
}
else {
id = reinterpret_cast<SubConn>(1);
if (this->FirstReserve_)
this->reserve(this->FirstReserve_);
}
base::emplace_back(id, std::forward<ArgsT>(args)...);
return id;
}
};
/// 事件訂閱機制: 訂閱事件的主題.
/// \tparam SubscriberT 訂閱者型別, 必須配合 Publish(args...) 的參數, 提供 SubscriberT(args...) 呼叫.
/// 針對 thread safe 的議題, 可考慮 std::function + shared_ptr + weak_ptr.
/// \tparam MutexT 預設使用 std::recursive_mutex: 允許在收到訊息的時候, 在同一個 thread 直接取消訂閱!
/// \tparam ContainerT 儲存訂閱者的容器: 預設使用 SubrMap; 請參考 SubrMap 的介面.
template < class SubscriberT
, class MutexT = std::recursive_mutex
, template <class T/*SubscriberT*/> class ContainerT = SubrMap
>
class Subject {
fon9_NON_COPY_NON_MOVE(Subject);
using ContainerImpl = ContainerT<SubscriberT>;
using Container = MustLock<ContainerImpl, MutexT>;
using Locker = typename Container::Locker;
using ConstLocker = typename Container::ConstLocker;
using iterator = typename ContainerImpl::iterator;
using size_type = typename ContainerImpl::size_type;
using difference_type = typename ContainerImpl::difference_type;
Container Subrs_;
size_type NextEmitIdx_{};
size_type EraseIterator(Locker& subrs, iterator ifind) {
if (ifind == subrs->end())
return 0;
size_type idx = static_cast<size_type>(ifind - subrs->begin());
if (idx < this->NextEmitIdx_)
--this->NextEmitIdx_;
subrs->erase(ifind);
return 1;
}
public:
using Subscriber = SubscriberT;
/// \copydoc SubrMap::SubrMap
explicit Subject(unsigned firstReserve = 32) : Subrs_{firstReserve} {
}
/// 直接在尾端註冊一個新的訂閱者.
/// - 註冊時不會檢查是否已經有相同訂閱者, 也就是: 同一個訂閱者, 可以註冊多次, 此時同一次發行流程, 會收到多次訂閱的事件.
/// - 使用 SubscriberT{args...} 直接在尾端建立訂閱者.
/// - 如果 SubscriberT 不支援 `operator==(const SubscriberT& subr)`, 則傳回值是唯一可以取消訂閱的依據.
///
/// \return 傳回值是取消訂閱時的依據, 傳回 nullptr 表示無法註冊, 原因請參閱 \ref SubConn 的說明.
template <class... ArgsT>
SubConn Subscribe(ArgsT&&... args) {
Locker subrs(this->Subrs_);
return subrs->emplace_back(std::forward<ArgsT>(args)...);
}
/// 訂閱時, 在返回前就先設定好 conn, 避免底下情況:
/// - conn = subj.Subscribe(...); 在返回後, 設定 conn 之前,
/// 就在其他 thread 觸發了 subj.Publish();
/// 而在訂閱者處理時用到了 conn, 此時的 conn 不正確.
template <class... ArgsT>
void Subscribe(SubConn* conn, ArgsT&&... args) {
Locker subrs(this->Subrs_);
*conn = subrs->emplace_back(std::forward<ArgsT>(args)...);
}
/// 取消訂閱.
/// - 若 MutexT = std::recursive_mutex 則: 可以在收到訊息的時候, 在同一個 thread 之中取消訂閱!
/// - 若 MutexT = std::mutex 則: 在收到訊息的時候, 在同一個 thread 之中取消訂閱: 會死結!
///
/// \param connection 是 Subscribe() 的傳回值.
/// \return 傳回實際移除的數量: 0 or 1
size_type Unsubscribe(SubConn connection) {
if (!connection)
return 0;
Locker subrs(this->Subrs_);
return this->EraseIterator(subrs, subrs->find(connection));
}
/// 取消訂閱, 並清除 *connection;
size_type Unsubscribe(SubConn* connection) {
if (SubConn c = *connection) {
*connection = SubConn{};
return this->Unsubscribe(c);
}
return 0;
}
/// 取消訂閱, 並將 Subscriber 取出.
bool MoveOutSubscriber(SubConn connection, SubscriberT& subr) {
return this->MoveOutSubscriber(&connection, subr);
}
bool MoveOutSubscriber(SubConn* pConnection, SubscriberT& subr) {
Locker subrs(this->Subrs_);
auto ifind = subrs->find(*pConnection);
*pConnection = SubConn{};
if (ifind == subrs->end())
return false;
subr = std::move(ifind->second);
this->EraseIterator(subrs, ifind);
return true;
}
/// 取消訂閱.
/// \param subr SubscriberT 必須支援: bool operator==(const SubscriberT&) const;
/// \return 傳回實際移除的數量: 0 or 1
size_type Unsubscribe(const SubscriberT& subr) {
Locker subrs(this->Subrs_);
return this->EraseIterator(subrs, subrs->find(subr));
}
size_type UnsubscribeAll(const SubscriberT& subr) {
Locker subrs(this->Subrs_);
size_type count = subrs->remove(subr, this->NextEmitIdx_, subrs->size());
if (this->NextEmitIdx_ > 0) {
if (size_type count2 = subrs->remove(subr, 0, this->NextEmitIdx_)) {
this->NextEmitIdx_ -= count2;
count += count2;
}
}
return count;
}
/// - 在發行訊息的過程, 會 **全程鎖住容器**.
/// - 這裡會呼叫 subr(std::forward<ArgsT>(args)...);
/// - 在收到發行訊息時:
/// - 若 MutexT = std::mutex; 則禁止在同一個 thread: 重複發行 or 取消註冊 or 新增註冊. 如果您這樣做, 會立即進入鎖死狀態!
/// - 若 MutexT = std::recursive_mutex:
/// - 可允許: 重複發行 or 取消註冊 or 新增註冊.
/// - 請避免: 在重複發行時, 又取消註冊. 因為原本的發行流程, 可能會有訂閱者遺漏訊息, 例:
/// - Pub(msgA): Subr1(idx=0), Subr2(idx=1), Subr3(idx=2), Subr4(idx=3)
/// - 在 Subr2 收到 msgA 時(msgA.NextIdx=2), Pub(msgB), 當 Subr1 收到 msgB 時, 取消註冊 Subr1.
/// - 此時剩下 Subr2(idx=0), Subr3(idx=1), Subr4(idx=2)
/// - 接下來 msgB 的流程: Subr2, Subr3, Subr4; msgB 發行結束.
/// - 返回 msgA(msgA.NextIdx=2) 繼續流程: Subr4; **此時遺漏了 Subr3**
template <class... ArgsT>
void Publish(ArgsT&&... args) {
struct Combiner {
bool operator()(SubscriberT& subr, ArgsT&&... args) {
subr(std::forward<ArgsT>(args)...);
return true;
}
} combiner;
Combine(combiner, std::forward<ArgsT>(args)...);
}
/// 透過 combiner 合併訊息發行結果.
/// 若 combiner(SubscriberT& subr, ArgsT&&... args) 傳回 false 則中斷發行.
template <class CombinerT, class... ArgsT>
void Combine(CombinerT& combiner, ArgsT&&... args) {
Locker subrs(this->Subrs_);
struct ResetIdx {
size_type prv;
size_type* idx;
ResetIdx(size_type* i) : prv{*i}, idx{i} {
*i = 0;
}
~ResetIdx() { *idx = prv; }
} resetIdx{&this->NextEmitIdx_};
while (this->NextEmitIdx_ < subrs->size()) {
if (!combiner(subrs->sindex(this->NextEmitIdx_++).second, std::forward<ArgsT>(args)...))
break;
}
}
/// 是否沒有訂閱者?
/// 若 MutexT = std::mutex 則: 在收到訊息的時候, 在同一個 thread 之中呼叫: 會死結!
bool IsEmpty() const {
ConstLocker subrs(this->Subrs_);
return subrs->empty();
}
/// 訂閱者數量.
size_type GetSubscriberCount() const {
ConstLocker subrs(this->Subrs_);
return subrs->size();
}
void Clear() {
Locker subrs(this->Subrs_);
return subrs->clear();
}
/// 鎖定後就暫時不會發行訊息.
ConstLocker Lock() const {
return ConstLocker{this->Subrs_};
}
};
/// 不支援 thread safe 的 Subject: 使用 fon9::DummyMutex.
template <class SubscriberT, template <class T> class SubrContainerT = SubrMap>
using UnsafeSubject = Subject<SubscriberT, DummyMutex, SubrContainerT>;
/// - 輔助 Subject 提供 Obj* 當作 Subscriber 使用.
/// \code
/// struct CbObj {
/// virtual void operator()() = 0;
/// };
/// using Subr = fon9::ObjCallback<CbObj>;
/// using Subj = fon9::Subject<Subr>;
/// \endcode
/// - 提供 Obj* 呼叫 Obj::operator() 的包裝.
/// - 提供 operator==(); operator!=() 判斷是否指向同一個 Obj
template <class Obj>
struct ObjCallback {
Obj* Obj_;
ObjCallback(Obj* obj) : Obj_{obj} {
}
bool operator==(const ObjCallback& r) const {
return this->Obj_ == r.Obj_;
}
bool operator!=(const ObjCallback& r) const {
return this->Obj_ == r.Obj_;
}
template <class... ArgsT>
auto operator()(ArgsT&&... args) const -> decltype((*this->Obj_)(std::forward<ArgsT>(args)...)) {
return (*this->Obj_)(std::forward<ArgsT>(args)...);
}
};
fon9_WARN_POP;
} // namespaces
#endif//__fon9_Subr_hpp__
| 10,021 | 4,900 |
#ifndef SoftWire_RegisterAllocator_hpp
#define SoftWire_RegisterAllocator_hpp
#include "Assembler.hpp"
namespace SoftWire
{
class RegisterAllocator : public Assembler
{
protected:
struct AllocationData
{
AllocationData()
{
free();
}
void free()
{
reference = 0;
priority = 0;
partial = 0;
copyInstruction = 0;
loadInstruction = 0;
spillInstruction = 0;
}
OperandREF reference;
unsigned int priority;
int partial; // Number of bytes used, 0/1/2 for general-purpose, 0/4 for SSE, 0 means all
Encoding *copyInstruction;
Encoding *loadInstruction;
Encoding *spillInstruction;
};
struct Allocation : AllocationData
{
Allocation()
{
free();
}
void free()
{
AllocationData::free();
spill.free();
modified = false;
}
AllocationData spill;
bool modified;
};
struct State
{
Allocation ERX[8];
Allocation MM[8];
Allocation XMM[8];
};
public:
RegisterAllocator();
virtual ~RegisterAllocator();
// Register allocation
const OperandREG8 r8(const OperandREF &ref, bool copy = true);
const OperandR_M8 m8(const OperandREF &ref);
const OperandREG16 r16(const OperandREF &ref, bool copy = true);
const OperandR_M16 m16(const OperandREF &ref);
OperandREG32 r32(const OperandREF &ref, bool copy = true, int partial = 0);
OperandR_M32 m32(const OperandREF &ref, int partial = 0);
void free(const OperandREG32 &r32);
void spill(const OperandREG32 &r32);
OperandMMREG r64(const OperandREF &ref, bool copy = true);
OperandR_M64 m64(const OperandREF &ref);
void free(const OperandMMREG &r64);
void spill(const OperandMMREG &r64);
OperandXMMREG r128(const OperandREF &ref, bool copy = true, bool ss = false);
OperandR_M128 m128(const OperandREF &ref, bool ss = false);
void free(const OperandXMMREG &r128);
void spill(const OperandXMMREG &r128);
OperandXMMREG rSS(const OperandREF &ref, bool copy = true, bool ss = true);
OperandXMM32 mSS(const OperandREF &ref, bool ss = true);
void free(const OperandREF &ref);
void spill(const OperandREF &ref);
void freeAll();
void spillAll();
void spillMMX(); // Specifically for using FPU after MMX
void spillMMXcept(const OperandMMREG &r64); // Empty MMX state but leave one associated
const State capture(); // Capture register allocation state
void restore(const State &state); // Restore state to minimize spills
// Temporarily exclude register from allocation (spill, then prioritize)
void exclude(const OperandREG32 &r32);
using Assembler::mov;
Encoding *mov(OperandREG32 r32i, OperandREG32 r32j);
Encoding *mov(OperandREG32 r32, OperandMEM32 m32);
Encoding *mov(OperandREG32 r32, OperandR_M32 r_m32);
using Assembler::movq;
Encoding *movq(OperandMMREG r64i, OperandMMREG r64j);
Encoding *movq(OperandMMREG r64, OperandMEM64 m64);
Encoding *movq(OperandMMREG r64, OperandR_M64 r_m64);
using Assembler::movaps;
Encoding *movaps(OperandXMMREG r128i, OperandXMMREG r128j);
Encoding *movaps(OperandXMMREG r128, OperandMEM128 m128);
Encoding *movaps(OperandXMMREG r128, OperandR_M128 r_m128);
// Automatically emit emms when all MMX registers freed
void enableAutoEMMS(); // Default off
void disableAutoEMMS();
// Optimization flags
static void enableCopyPropagation(); // Default on
static void disableCopyPropagation();
static void enableLoadElimination(); // Default on
static void disableLoadElimination();
static void enableSpillElimination(); // Default on
static void disableSpillElimination();
static void enableMinimalRestore(); // Default on
static void disableMinimalRestore();
static void enableDropUnmodified(); // Default on
static void disableDropUnmodified();
protected:
Encoding *x86(int instructionID, const Operand &firstOperand, const Operand &secondOperand, const Operand &thirdOperand);
// Current allocation data
static Allocation ERX[8];
static Allocation MM[8];
static Allocation XMM[8];
private:
void markModified(const Operand &op);
void markReferenced(const Operand &op);
OperandREG32 allocate32(int i, const OperandREF &ref, bool copy, int partial);
OperandREG32 prioritize32(int i);
void free32(int i);
Encoding *spill32(int i);
void swap32(int i, int j);
OperandMMREG allocate64(int i, const OperandREF &ref, bool copy);
OperandMMREG prioritize64(int i);
void free64(int i);
Encoding *spill64(int i);
void swap64(int i, int j);
OperandXMMREG allocate128(int i, const OperandREF &ref, bool copy, bool ss);
OperandXMMREG prioritize128(int i);
void free128(int i);
Encoding *spill128(int i);
void swap128(int i, int j);
static bool autoEMMS;
static bool copyPropagation;
static bool loadElimination;
static bool spillElimination;
static bool minimalRestore;
static bool dropUnmodified;
};
}
#endif // SoftWire_RegisterAllocator_hpp
| 5,141 | 2,056 |
#include <core/EConfigure.hpp>
#include <fstream>
namespace slc {
EConfigure::EConfigure() {}
EConfigure::~EConfigure() {}
bool EConfigure::loadFile(EString file) {
if(file.isEmpty()) return false;
std::ifstream reader;
reader.open(file.toStdChars(),std::ios::ate);
if(!reader.is_open())
return false;
std::string s;
while(getline(reader,s))
{
EString::format("%s",s.c_str());
}
reader.close();
return true;
}
EString EConfigure::readString(EString path, const EString val) {
if(path.isEmpty())
return val;
EString res;
return res;
}
} | 707 | 227 |
////////////////////////////////////////////////////////////////////////////
//
// This file is part of SNC
//
// Copyright (c) 2014-2021, Richard Barnett
//
// 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 "SNCPythonGlue.h"
#include "SNCPythonMainConsole.h"
#include "SNCPythonMainWindow.h"
#include "SNCPythonClient.h"
#include "SNCUtils.h"
#include <qmutex.h>
QMutex lockSNCPython;
SNCPythonGlue::SNCPythonGlue()
{
m_main = NULL;
m_connected = false;
m_directoryRequested = false;
}
SNCPythonGlue::~SNCPythonGlue()
{
if (m_main != NULL)
stopLib();
}
void SNCPythonGlue::startLib(const char *productType, int& argc, char **argv, bool showWindow)
{
m_argc = argc;
m_argv = argv;
m_daemonMode = SNCUtils::checkDaemonModeFlag(m_argc, m_argv);
if (SNCUtils::checkConsoleModeFlag(m_argc, m_argv)) {
QCoreApplication a(m_argc, m_argv);
SNCUtils::loadStandardSettings(productType, a.arguments());
m_main = new SNCPythonMainConsole(&a, this);
a.exec();
} else {
QApplication a(m_argc, m_argv);
SNCUtils::loadStandardSettings(productType, a.arguments());
m_main = new SNCPythonMainWindow(this);
if (showWindow)
((SNCPythonMainWindow *)m_main)->show();
a.exec();
}
}
void SNCPythonGlue::stopLib()
{
m_main->stopRunning();
m_main = NULL;
}
void SNCPythonGlue::setWindowTitle(char *title)
{
m_main->setWindowTitle(title);
}
void SNCPythonGlue::displayImage(unsigned char *image, int length,
int width, int height, char *timestamp)
{
m_main->displayImage(QByteArray((const char *)image, length), width, height, timestamp);
}
void SNCPythonGlue::displayJpegImage(unsigned char *image, int length, char *timestamp)
{
m_main->displayJpegImage(QByteArray((const char *)image, length), timestamp);
}
char *SNCPythonGlue::getAppName()
{
static char name[256];
strcpy(name, qPrintable(SNCUtils::getAppName()));
return name;
}
void SNCPythonGlue::setConnected(bool state)
{
QMutexLocker lock(&lockSNCPython);
m_connected = state;
}
bool SNCPythonGlue::isConnected()
{
QMutexLocker lock(&lockSNCPython);
return m_connected;
}
bool SNCPythonGlue::requestDirectory()
{
QMutexLocker lock(&lockSNCPython);
if (!m_connected)
return false;
m_directoryRequested = true;
return true;
}
bool SNCPythonGlue::isDirectoryRequested()
{
QMutexLocker lock(&lockSNCPython);
bool ret = m_directoryRequested;
m_directoryRequested = false;
return ret;
}
char *SNCPythonGlue::lookupMulticastSources(const char *sourceName)
{
return m_main->getClient()->lookupSources(sourceName, SERVICETYPE_MULTICAST);
}
int SNCPythonGlue::addMulticastSourceService(const char *servicePath)
{
return m_main->getClient()->clientAddService(servicePath, SERVICETYPE_MULTICAST, true);
}
int SNCPythonGlue::addMulticastSinkService(const char *servicePath)
{
return m_main->getClient()->clientAddService(servicePath, SERVICETYPE_MULTICAST, false);
}
char *SNCPythonGlue::lookupE2ESources(const char *sourceType)
{
return m_main->getClient()->lookupSources(sourceType, SERVICETYPE_E2E);
}
int SNCPythonGlue::addE2ESourceService(const char *servicePath)
{
return m_main->getClient()->clientAddService(servicePath, SERVICETYPE_E2E, true);
}
int SNCPythonGlue::addE2ESinkService(const char *servicePath)
{
return m_main->getClient()->clientAddService(servicePath, SERVICETYPE_E2E, false);
}
bool SNCPythonGlue::removeService(int servicePort)
{
return m_main->getClient()->clientRemoveService(servicePort);
}
bool SNCPythonGlue::isClearToSend(int servicePort)
{
return m_main->getClient()->clientClearToSend(servicePort);
}
bool SNCPythonGlue::isServiceActive(int servicePort)
{
return m_main->getClient()->clientIsServiceActive(servicePort);
}
bool SNCPythonGlue::sendAVData(int servicePort, unsigned char *videoData, int videoLength,
unsigned char *audioData, int audioLength)
{
return m_main->sendAVData(servicePort, videoData, videoLength, audioData, audioLength);
}
bool SNCPythonGlue::sendJpegAVData(int servicePort, unsigned char *videoData, int videoLength,
unsigned char *audioData, int audioLength)
{
return m_main->sendJpegAVData(servicePort, videoData, videoLength, audioData, audioLength);
}
bool SNCPythonGlue::getAVData(int servicePort, long long *timestamp, unsigned char **videoData, int *videoLength,
unsigned char **audioData, int *audioLength)
{
return m_main->getClient()->getAVData(servicePort, timestamp, videoData, videoLength, audioData, audioLength);
}
bool SNCPythonGlue::getVideoData(int servicePort, long long *timestamp, unsigned char **videoData, int *videoLength,
int *width, int *height, int *rate)
{
return m_main->getClient()->getVideoData(servicePort, timestamp, videoData, videoLength, width, height, rate);
}
bool SNCPythonGlue::sendVideoData(int servicePort, long long timestamp, unsigned char *videoData, int videoLength,
int width, int height, int rate)
{
return m_main->sendVideoData(servicePort, timestamp, videoData, videoLength, width, height, rate);
}
void SNCPythonGlue::setVideoParams(int width, int height, int rate)
{
m_main->getClient()->setVideoParams(width, height, rate);
}
void SNCPythonGlue::setAudioParams(int rate, int size, int channels)
{
m_main->getClient()->setVideoParams(rate, size, channels);
}
bool SNCPythonGlue::getSensorData(int servicePort, long long *timestamp, unsigned char **jsonData, int *jsonLength)
{
return m_main->getClient()->getSensorData(servicePort, timestamp, jsonData, jsonLength);
}
bool SNCPythonGlue::sendSensorData(int servicePort, unsigned char *data, int dataLength)
{
return m_main->sendSensorData(servicePort, data, dataLength);
}
bool SNCPythonGlue::sendMulticastData(int servicePort, unsigned char *data, int dataLength)
{
return m_main->sendMulticastData(servicePort, data, dataLength);
}
bool SNCPythonGlue::sendE2EData(int servicePort, unsigned char *data, int dataLength)
{
return m_main->sendE2EData(servicePort, data, dataLength);
}
bool SNCPythonGlue::getMulticastData(int servicePort, unsigned char **data, int *dataLength)
{
return m_main->getClient()->getGenericData(servicePort, data, dataLength);
}
bool SNCPythonGlue::getE2EData(int servicePort, unsigned char **data, int *dataLength)
{
return m_main->getClient()->getGenericData(servicePort, data, dataLength);
}
bool SNCPythonGlue::vidCapOpen(int cameraNum, int width, int height, int rate)
{
return m_main->vidCapOpen(cameraNum, width, height, rate);
}
bool SNCPythonGlue::vidCapClose(int cameraNum)
{
return m_main->vidCapClose(cameraNum);
}
bool SNCPythonGlue::vidCapGetFrame(int cameraNum, unsigned char** frame, int& length, bool& jpeg,
int& width, int& height, int& rate)
{
QByteArray qframe;
*frame = NULL;
if (!m_main->vidCapGetFrame(cameraNum, qframe, jpeg, width, height, rate))
return false;
*frame = (unsigned char *)malloc(qframe.length());
memcpy(*frame, qframe.data(), qframe.length());
length = qframe.length();
return true;
}
| 8,360 | 2,773 |
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2009-2012. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/interprocess for documentation.
//
//////////////////////////////////////////////////////////////////////////////
#ifndef BOOST_INTERPROCESS_WINDOWS_INTERMODULE_SINGLETON_HPP
#define BOOST_INTERPROCESS_WINDOWS_INTERMODULE_SINGLETON_HPP
#ifndef BOOST_CONFIG_HPP
# include <boost/config.hpp>
#endif
#
#if defined(BOOST_HAS_PRAGMA_ONCE)
#pragma once
#endif
#include <boost/interprocess/detail/config_begin.hpp>
#include <boost/interprocess/detail/workaround.hpp>
#include <boost/container/string.hpp>
#if !defined(BOOST_INTERPROCESS_WINDOWS)
#error "This header can't be included from non-windows operating systems"
#endif
#include <boost/assert.hpp>
#include <boost/interprocess/detail/intermodule_singleton_common.hpp>
#include <boost/interprocess/sync/windows/winapi_semaphore_wrapper.hpp>
#include <boost/interprocess/sync/windows/winapi_mutex_wrapper.hpp>
#include <boost/interprocess/sync/scoped_lock.hpp>
#include <boost/cstdint.hpp>
#include <string>
#include <boost/container/map.hpp>
namespace boost{
namespace interprocess{
namespace ipcdetail{
namespace intermodule_singleton_helpers {
//This global map will be implemented using 3 sync primitives:
//
//1) A named mutex that will implement global mutual exclusion between
// threads from different modules/dlls
//
//2) A semaphore that will act as a global counter for modules attached to the global map
// so that the global map can be destroyed when the last module is detached.
//
//3) A semaphore that will be hacked to hold the address of a heap-allocated map in the
// max and current semaphore count.
class windows_semaphore_based_map
{
typedef boost::container::map<boost::container::string, ref_count_ptr> map_type;
public:
windows_semaphore_based_map()
{
map_type *m = new map_type;
boost::uint32_t initial_count = 0;
boost::uint32_t max_count = 0;
//Windows user address space sizes:
//32 bit windows: [32 bit processes] 2GB or 3GB (31/32 bits)
//64 bit windows: [32 bit processes] 2GB or 4GB (31/32 bits)
// [64 bit processes] 2GB or 8TB (31/43 bits)
//
//Windows semaphores use 'long' parameters (32 bits in LLP64 data model) and
//those values can't be negative, so we have 31 bits to store something
//in max_count and initial count parameters.
//Also, max count must be bigger than 0 and bigger or equal than initial count.
if(sizeof(void*) == sizeof(boost::uint32_t)){
//This means that for 32 bit processes, a semaphore count (31 usable bits) is
//enough to store 4 byte aligned memory (4GB -> 32 bits - 2 bits = 30 bits).
//The max count will hold the pointer value and current semaphore count
//will be zero.
//
//Relying in UB with a cast through union, but all known windows compilers
//accept this (C11 also accepts this).
union caster_union
{
void *addr;
boost::uint32_t addr_uint32;
} caster;
caster.addr = m;
//memory is at least 4 byte aligned in windows
BOOST_ASSERT((caster.addr_uint32 & boost::uint32_t(3)) == 0);
max_count = caster.addr_uint32 >> 2;
}
else if(sizeof(void*) == sizeof(boost::uint64_t)){
//Relying in UB with a cast through union, but all known windows compilers
//accept this (C11 accepts this).
union caster_union
{
void *addr;
boost::uint64_t addr_uint64;
} caster;
caster.addr = m;
//We'll encode the address using 30 bits in each 32 bit high and low parts.
//High part will be the sem max count, low part will be the sem initial count.
//(restrictions: max count > 0, initial count >= 0 and max count >= initial count):
//
// - Low part will be shifted two times (4 byte alignment) so that top
// two bits are cleared (the top one for sign, the next one to
// assure low part value is always less than the high part value.
// - The top bit of the high part will be cleared and the next bit will be 1
// (so high part is always bigger than low part due to the quasi-top bit).
//
// This means that the addresses we can store must be 4 byte aligned
// and less than 1 ExbiBytes ( 2^60 bytes, ~1 ExaByte). User-level address space in Windows 64
// is much less than this (8TB, 2^43 bytes): "1 EByte (or it was 640K?) ought to be enough for anybody" ;-).
caster.addr = m;
BOOST_ASSERT((caster.addr_uint64 & boost::uint64_t(3)) == 0);
max_count = boost::uint32_t(caster.addr_uint64 >> 32);
initial_count = boost::uint32_t(caster.addr_uint64);
initial_count = initial_count/4;
//Make sure top two bits are zero
BOOST_ASSERT((max_count & boost::uint32_t(0xC0000000)) == 0);
//Set quasi-top bit
max_count |= boost::uint32_t(0x40000000);
}
bool created = false;
const permissions & perm = permissions();
std::string pid_creation_time, name;
get_pid_creation_time_str(pid_creation_time);
name = "bipc_gmap_sem_lock_";
name += pid_creation_time;
bool success = m_mtx_lock.open_or_create(name.c_str(), perm);
name = "bipc_gmap_sem_count_";
name += pid_creation_time;
scoped_lock<winapi_mutex_wrapper> lck(m_mtx_lock);
{
success = success && m_sem_count.open_or_create
( name.c_str(), static_cast<long>(0), winapi_semaphore_wrapper::MaxCount, perm, created);
name = "bipc_gmap_sem_map_";
name += pid_creation_time;
success = success && m_sem_map.open_or_create
(name.c_str(), initial_count, max_count, perm, created);
if(!success){
delete m;
//winapi_xxx wrappers do the cleanup...
throw int(0);
}
if(!created){
delete m;
}
else{
BOOST_ASSERT(&get_map_unlocked() == m);
}
m_sem_count.post();
}
}
map_type &get_map_unlocked()
{
if(sizeof(void*) == sizeof(boost::uint32_t)){
union caster_union
{
void *addr;
boost::uint32_t addr_uint32;
} caster;
caster.addr = 0;
caster.addr_uint32 = m_sem_map.limit();
caster.addr_uint32 = caster.addr_uint32 << 2;
return *static_cast<map_type*>(caster.addr);
}
else{
union caster_union
{
void *addr;
boost::uint64_t addr_uint64;
} caster;
boost::uint32_t max_count(m_sem_map.limit()), initial_count(m_sem_map.value());
//Clear quasi-top bit
max_count &= boost::uint32_t(0xBFFFFFFF);
caster.addr_uint64 = max_count;
caster.addr_uint64 = caster.addr_uint64 << 32;
caster.addr_uint64 |= boost::uint64_t(initial_count) << 2;
return *static_cast<map_type*>(caster.addr);
}
}
ref_count_ptr *find(const char *name)
{
scoped_lock<winapi_mutex_wrapper> lck(m_mtx_lock);
map_type &map = this->get_map_unlocked();
map_type::iterator it = map.find(boost::container::string(name));
if(it != map.end()){
return &it->second;
}
else{
return 0;
}
}
ref_count_ptr * insert(const char *name, const ref_count_ptr &ref)
{
scoped_lock<winapi_mutex_wrapper> lck(m_mtx_lock);
map_type &map = this->get_map_unlocked();
map_type::iterator it = map.insert(map_type::value_type(boost::container::string(name), ref)).first;
return &it->second;
}
bool erase(const char *name)
{
scoped_lock<winapi_mutex_wrapper> lck(m_mtx_lock);
map_type &map = this->get_map_unlocked();
return map.erase(boost::container::string(name)) != 0;
}
template<class F>
void atomic_func(F &f)
{
scoped_lock<winapi_mutex_wrapper> lck(m_mtx_lock);
f();
}
~windows_semaphore_based_map()
{
scoped_lock<winapi_mutex_wrapper> lck(m_mtx_lock);
m_sem_count.wait();
if(0 == m_sem_count.value()){
map_type &map = this->get_map_unlocked();
BOOST_ASSERT(map.empty());
delete ↦
}
//First close sems to protect this with the external mutex
m_sem_map.close();
m_sem_count.close();
//Once scoped_lock unlocks the mutex, the destructor will close the handle...
}
private:
winapi_mutex_wrapper m_mtx_lock;
winapi_semaphore_wrapper m_sem_map;
winapi_semaphore_wrapper m_sem_count;
};
template<>
struct thread_safe_global_map_dependant<windows_semaphore_based_map>
{
static void apply_gmem_erase_logic(const char *, const char *){}
static bool remove_old_gmem()
{ return true; }
struct lock_file_logic
{
lock_file_logic(windows_semaphore_based_map &)
: retry_with_new_map(false)
{}
void operator()(void){}
bool retry() const { return retry_with_new_map; }
private:
const bool retry_with_new_map;
};
static void construct_map(void *addr)
{
::new (addr)windows_semaphore_based_map;
}
struct unlink_map_logic
{
unlink_map_logic(windows_semaphore_based_map &)
{}
void operator()(){}
};
static ref_count_ptr *find(windows_semaphore_based_map &map, const char *name)
{
return map.find(name);
}
static ref_count_ptr * insert(windows_semaphore_based_map &map, const char *name, const ref_count_ptr &ref)
{
return map.insert(name, ref);
}
static bool erase(windows_semaphore_based_map &map, const char *name)
{
return map.erase(name);
}
template<class F>
static void atomic_func(windows_semaphore_based_map &map, F &f)
{
map.atomic_func(f);
}
};
} //namespace intermodule_singleton_helpers {
template<typename C, bool LazyInit = true, bool Phoenix = false>
class windows_intermodule_singleton
: public intermodule_singleton_impl
< C
, LazyInit
, Phoenix
, intermodule_singleton_helpers::windows_semaphore_based_map
>
{};
} //namespace ipcdetail{
} //namespace interprocess{
} //namespace boost{
#include <boost/interprocess/detail/config_end.hpp>
#endif //#ifndef BOOST_INTERPROCESS_WINDOWS_INTERMODULE_SINGLETON_HPP
| 11,059 | 3,722 |
/*
* Copyright (c) 2017, 2020, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
#ifndef SHARE_JVMCI_JVMCI_HPP
#define SHARE_JVMCI_JVMCI_HPP
#include "compiler/compiler_globals.hpp"
#include "compiler/compilerDefinitions.hpp"
#include "utilities/exceptions.hpp"
class BoolObjectClosure;
class constantPoolHandle;
class JavaThread;
class JVMCIEnv;
class JVMCIRuntime;
class Metadata;
class MetadataHandleBlock;
class OopClosure;
class OopStorage;
template <size_t>
class FormatStringEventLog;
typedef FormatStringEventLog<256> StringEventLog;
struct _jmetadata;
typedef struct _jmetadata *jmetadata;
class JVMCI : public AllStatic {
friend class JVMCIRuntime;
friend class JVMCIEnv;
private:
// Access to the HotSpotJVMCIRuntime used by the CompileBroker.
static JVMCIRuntime* _compiler_runtime;
// True when at least one JVMCIRuntime::initialize_HotSpotJVMCIRuntime()
// execution has completed successfully.
static volatile bool _is_initialized;
// True once boxing cache classes are guaranteed to be initialized.
static bool _box_caches_initialized;
// Handle created when loading the JVMCI shared library with os::dll_load.
// Must hold JVMCI_lock when initializing.
static void* _shared_library_handle;
// Argument to os::dll_load when loading JVMCI shared library
static char* _shared_library_path;
// Records whether JVMCI::shutdown has been called.
static volatile bool _in_shutdown;
// Access to the HotSpot heap based JVMCIRuntime
static JVMCIRuntime* _java_runtime;
// The file descriptor to which fatal_log() writes. Initialized on
// first call to fatal_log().
static volatile int _fatal_log_fd;
// The path of the file underlying _fatal_log_fd if it is a normal file.
static const char* _fatal_log_filename;
// Native thread id of thread that will initialize _fatal_log_fd.
static volatile intx _fatal_log_init_thread;
// JVMCI event log (shows up in hs_err crash logs).
static StringEventLog* _events;
static StringEventLog* _verbose_events;
enum {
max_EventLog_level = 4
};
// Gets the Thread* value for the current thread or NULL if it's not available.
static Thread* current_thread_or_null();
public:
enum CodeInstallResult {
ok,
dependencies_failed,
cache_full,
nmethod_reclaimed, // code cache sweeper reclaimed nmethod in between its creation and being marked "in_use"
code_too_large,
first_permanent_bailout = code_too_large
};
// Gets the handle to the loaded JVMCI shared library, loading it
// first if not yet loaded and `load` is true. The path from
// which the library is loaded is returned in `path`. If
// `load` is true then JVMCI_lock must be locked.
static void* get_shared_library(char*& path, bool load);
// Logs the fatal crash data in `buf` to the appropriate stream.
static void fatal_log(const char* buf, size_t count);
// Gets the name of the opened JVMCI shared library crash data file or NULL
// if this file has not been created.
static const char* fatal_log_filename() { return _fatal_log_filename; }
static void do_unloading(bool unloading_occurred);
static void metadata_do(void f(Metadata*));
static void shutdown();
// Returns whether JVMCI::shutdown has been called.
static bool in_shutdown();
static bool is_compiler_initialized();
/**
* Determines if the VM is sufficiently booted to initialize JVMCI.
*/
static bool can_initialize_JVMCI();
static void initialize_globals();
static void initialize_compiler(TRAPS);
// Ensures the boxing cache classes (e.g., java.lang.Integer.IntegerCache) are initialized.
static void ensure_box_caches_initialized(TRAPS);
// Increments a value indicating some JVMCI compilation activity
// happened on `thread` if it is a CompilerThread.
// Returns `thread`.
static JavaThread* compilation_tick(JavaThread* thread);
static JVMCIRuntime* compiler_runtime() { return _compiler_runtime; }
// Gets the single runtime for JVMCI on the Java heap. This is the only
// JVMCI runtime available when !UseJVMCINativeLibrary.
static JVMCIRuntime* java_runtime() { return _java_runtime; }
// Appends an event to the JVMCI event log if JVMCIEventLogLevel >= `level`
static void vlog(int level, const char* format, va_list ap) ATTRIBUTE_PRINTF(2, 0);
// Traces an event to tty if JVMCITraceLevel >= `level`
static void vtrace(int level, const char* format, va_list ap) ATTRIBUTE_PRINTF(2, 0);
public:
// Log/trace a JVMCI event
static void event(int level, const char* format, ...) ATTRIBUTE_PRINTF(2, 3);
static void event1(const char* format, ...) ATTRIBUTE_PRINTF(1, 2);
static void event2(const char* format, ...) ATTRIBUTE_PRINTF(1, 2);
static void event3(const char* format, ...) ATTRIBUTE_PRINTF(1, 2);
static void event4(const char* format, ...) ATTRIBUTE_PRINTF(1, 2);
};
// JVMCI event macros.
#define JVMCI_event_1 if (JVMCITraceLevel < 1 && JVMCIEventLogLevel < 1) ; else ::JVMCI::event1
#define JVMCI_event_2 if (JVMCITraceLevel < 2 && JVMCIEventLogLevel < 2) ; else ::JVMCI::event2
#define JVMCI_event_3 if (JVMCITraceLevel < 3 && JVMCIEventLogLevel < 3) ; else ::JVMCI::event3
#define JVMCI_event_4 if (JVMCITraceLevel < 4 && JVMCIEventLogLevel < 4) ; else ::JVMCI::event4
#endif // SHARE_JVMCI_JVMCI_HPP
| 6,301 | 2,029 |
#ifndef _OP_SOCKET_DGRAM_CHANNEL_HPP_
#define _OP_SOCKET_DGRAM_CHANNEL_HPP_
#include <atomic>
#include <netinet/in.h>
#include "framework/memory/offset_ptr.hpp"
#include "socket/api.hpp"
namespace openperf::socket {
struct dgram_ipv4_addr
{
uint32_t addr;
};
struct dgram_ipv6_addr
{
uint32_t addr[4];
/* LWIP_IPV6_SCOPES adds zone field in lwpip ip6_addr_t */
uint8_t zone;
};
/* Congruent to lwIP ip_addr_t; otherwise we'd use a variant */
struct dgram_ip_addr
{
enum class type : uint8_t { IPv4 = 0, IPv6 = 6 };
union
{
dgram_ipv6_addr ip6;
dgram_ipv4_addr ip4;
} u_addr;
type type;
};
/* Congruent to struct sockaddr_ll */
struct dgram_sockaddr_ll
{
uint16_t family;
uint16_t protocol;
int ifindex;
uint16_t hatype;
uint8_t pkttype;
uint8_t halen;
std::array<uint8_t, 8> addr;
};
using dgram_channel_addr =
std::variant<sockaddr_in, sockaddr_in6, dgram_sockaddr_ll>;
/*
* Static tag for sanity checking random pointers are actually descriptors.
* Can be removed once we're sure this works :)
*/
static constexpr uint64_t descriptor_tag = 0xABCCDDDEEEEE;
/* Each datagram in the buffer is pre-pended with the following descriptor */
struct dgram_channel_descriptor
{
uint64_t tag = descriptor_tag;
std::optional<dgram_channel_addr> address;
uint16_t length;
};
/*
* The datagram channel uses the same approach as the stream
* channel. But because we're dealing with packets of data,
* we pre-pend each write to the buffer with a fixed size header.
* This header allows the reader to determine the address for the
* payload and the actual size of the data which follows.
*
* Additionally, just like the stream channel, we maintain two
* individual buffers, one for transmit and one for receive,
* and we used eventfd's to signal between client and server
* when necessary.
*/
#define DGRAM_CHANNEL_MEMBERS \
struct alignas(cache_line_size) \
{ \
buffer tx_buffer; \
api::socket_fd_pair client_fds; \
std::atomic_uint64_t tx_q_write_idx; \
std::atomic_uint64_t rx_q_read_idx; \
std::atomic_uint64_t tx_fd_write_idx; \
std::atomic_uint64_t rx_fd_read_idx; \
std::atomic_int socket_flags; \
}; \
struct alignas(cache_line_size) \
{ \
buffer rx_buffer; \
api::socket_fd_pair server_fds; \
std::atomic_uint64_t tx_q_read_idx; \
std::atomic_uint64_t rx_q_write_idx; \
std::atomic_uint64_t tx_fd_read_idx; \
std::atomic_uint64_t rx_fd_write_idx; \
void* allocator; \
};
struct dgram_channel
{
DGRAM_CHANNEL_MEMBERS
};
} // namespace openperf::socket
#endif /* _OP_SOCKET_DGRAM_CHANNEL_HPP_ */
| 3,659 | 1,099 |
/*!
* @copyright
* Copyright (c) 2015-2019 Intel Corporation
*
* @copyright
* 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
*
* @copyright
* http://www.apache.org/licenses/LICENSE-2.0
*
* @copyright
* 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 app.hpp
*
* @brief Declares App class wrapping main program logic.
* */
#pragma once
#include "psme/eventing/eventing_server.hpp"
#include "psme/registration/registration_server.hpp"
#include "psme/rest/rest_server.hpp"
#include "psme/rest/model/watcher.hpp"
#include "psme/rest/eventing/event_service.hpp"
#include "psme/rest/security/session/session_service.hpp"
#include "net/network_change_notifier.hpp"
#include <memory>
namespace jsonrpc {
class HttpServer;
}
namespace ssdp {
class SsdpService;
}
/*! Psme namespace */
namespace psme {
/*! Application namespace */
namespace app {
/*!
* @brief Application class wrapping main program logic.
*
* Responsible for application initialization and execution.
*/
class App final {
public:
/*!
* @brief Constructor
* @param argc number of arguments passed to program
* @param argv array with program arguments
*/
App(int argc, const char** argv);
/*!
* @brief Destructor
*
* Responsible for resource cleanup. Stops any running servers.
*/
~App();
/*!
* @brief Starts servers initialized in init method
* and waits for interrupt signal.
*/
void run();
private:
/*!
* @brief Initialization method
*
* Responsible for initialization of loggers, registration server,
* eventing server and rest server. Does not start the mentioned servers.
*/
void init();
void init_database();
void init_logger();
void init_network_change_notifier();
void init_ssdp_service();
void init_registration_server();
void init_eventing_server();
void init_rest_event_service();
void init_rest_session_service();
void init_rest_server();
void init_registries();
void cleanup();
void statics_cleanup();
void wait_for_termination();
const json::Json& m_configuration;
std::unique_ptr<psme::app::eventing::EventingServer> m_eventing_server{};
std::unique_ptr<psme::app::registration::RegistrationServer> m_registration_server{};
std::unique_ptr<psme::rest::server::RestServer> m_rest_server{};
std::unique_ptr<psme::rest::eventing::EventService> m_rest_event_service{};
std::unique_ptr<psme::rest::security::session::SessionService> m_rest_session_service{};
std::unique_ptr<net::NetworkChangeNotifier> m_network_change_notifier{};
std::shared_ptr<ssdp::SsdpService> m_ssdp_service{};
std::unique_ptr<rest::model::Watcher> m_model_watcher{};
};
}
}
| 3,170 | 996 |
/* AFE Firmware for smarthome devices, More info: https://afe.smartnydom.pl/ */
#include "AFE-I2C-Scanner.h"
#ifdef AFE_CONFIG_HARDWARE_I2C
AFEI2CScanner::AFEI2CScanner() {};
void AFEI2CScanner::begin(TwoWire *_WirePort) {
AFEDataAccess Data;
WirePort = _WirePort;
}
#ifdef DEBUG
void AFEI2CScanner::scanAll() {
uint8_t numberOfDeficesFound = 0;
boolean searchStatus;
Serial << endl
<< endl
<< F("------------------ I2C Scanner ------------------");
for (uint8_t address = 1; address < 127; address++) {
searchStatus = scan(address);
if (searchStatus)
numberOfDeficesFound++;
}
if (numberOfDeficesFound == 0) {
Serial << endl << F("No I2C devices found");
} else {
Serial << endl << F("Scanning completed");
}
Serial << endl
<< F("---------------------------------------------------") << endl;
}
#endif
boolean AFEI2CScanner::scan(byte address) {
byte status;
WirePort->beginTransmission(address);
status = WirePort->endTransmission();
if (status == 0) {
#ifdef DEBUG
Serial << endl << F(" - Sensor Found [0x");
if (address < 16) {
Serial << F("0");
}
Serial << _HEX(address) << F("] : ") << getName(address);
#endif
return true;
} else {
return false;
}
}
const char *AFEI2CScanner::getName(byte deviceAddress) {
/* WARN: Description can't be longer than 70chars, used by addDeviceI2CAddressSelectionItem in AFE-Site-Gnerator.h */
if (deviceAddress == 0x00)
return "AS3935";
else if (deviceAddress == 0x01)
return "AS3935";
else if (deviceAddress == 0x02)
return "AS3935";
else if (deviceAddress == 0x03)
return "AS3935";
else if (deviceAddress == 0x0A)
return "SGTL5000";
else if (deviceAddress == 0x0B)
return "SMBusBattery?";
else if (deviceAddress == 0x0C)
return "AK8963";
else if (deviceAddress == 0x10)
return "CS4272";
else if (deviceAddress == 0x11)
return "Si4713";
else if (deviceAddress == 0x13)
return "VCNL4000,AK4558";
else if (deviceAddress == 0x18)
return "LIS331DLH";
else if (deviceAddress == 0x19)
return "LSM303,LIS331DLH";
else if (deviceAddress == 0x1A)
return "WM8731";
else if (deviceAddress == 0x1C)
return "LIS3MDL";
else if (deviceAddress == 0x1D)
return "LSM303D,LSM9DS0,ADXL345,MMA7455L,LSM9DS1,LIS3DSH";
else if (deviceAddress == 0x1E)
return "LSM303D,HMC5883L,FXOS8700,LIS3DSH";
else if (deviceAddress == 0x20)
//return "MCP23017,MCP23008,PCF8574,FXAS21002,SoilMoisture";
return "MCP23017";
else if (deviceAddress == 0x21)
//return "MCP23017,MCP23008,PCF8574";
return "MCP23017";
else if (deviceAddress == 0x22)
//return "MCP23017,MCP23008,PCF8574";
return "MCP23017";
else if (deviceAddress == 0x23)
return "BH1750, MCP23017";
//return "BH1750,MCP23017,MCP23008,PCF8574";
else if (deviceAddress == 0x24)
//return "MCP23017,MCP23008,PCF8574";
return "MCP23017,PN532";
else if (deviceAddress == 0x25)
//return "MCP23017,MCP23008,PCF8574";
return "MCP23017";
else if (deviceAddress == 0x26)
//return "MCP23017,MCP23008,PCF8574";
return "MCP23017";
else if (deviceAddress == 0x27)
//return "MCP23017,MCP23008,PCF8574,LCD16x2,DigoleDisplay";
return "MCP23017";
else if (deviceAddress == 0x28)
return "BNO055,EM7180,CAP1188";
else if (deviceAddress == 0x29)
return "TSL2561,VL6180,TSL2561,TSL2591,BNO055,CAP1188";
else if (deviceAddress == 0x2A)
return "SGTL5000,CAP1188";
else if (deviceAddress == 0x2B)
return "CAP1188";
else if (deviceAddress == 0x2C)
return "MCP44XX ePot";
else if (deviceAddress == 0x2D)
return "MCP44XX ePot";
else if (deviceAddress == 0x2E)
return "MCP44XX ePot";
else if (deviceAddress == 0x2F)
return "MCP44XX ePot";
else if (deviceAddress == 0x38)
return "RA8875,FT6206";
else if (deviceAddress == 0x39)
return "TSL2561";
else if (deviceAddress == 0x3C)
return "SSD1306,DigisparkOLED";
else if (deviceAddress == 0x3D)
return "SSD1306";
else if (deviceAddress == 0x40)
return "PCA9685,Si7021";
else if (deviceAddress == 0x41)
return "STMPE610,PCA9685";
else if (deviceAddress == 0x42)
return "PCA9685";
else if (deviceAddress == 0x43)
return "PCA9685";
else if (deviceAddress == 0x44)
return "PCA9685";
else if (deviceAddress == 0x45)
return "PCA9685";
else if (deviceAddress == 0x46)
return "PCA9685";
else if (deviceAddress == 0x47)
return "PCA9685";
else if (deviceAddress == 0x48)
return "ADS1115,PN532,TMP102,PCF8591";
else if (deviceAddress == 0x49)
return "ADS1115,TSL2561,PCF8591";
else if (deviceAddress == 0x4A)
return "ADS1115";
else if (deviceAddress == 0x4B)
return "ADS1115,TMP102";
else if (deviceAddress == 0x50)
return "EEPROM";
else if (deviceAddress == 0x51)
return "EEPROM";
else if (deviceAddress == 0x52)
return "Nunchuk,EEPROM";
else if (deviceAddress == 0x53)
return "ADXL345,EEPROM";
else if (deviceAddress == 0x54)
return "EEPROM";
else if (deviceAddress == 0x55)
return "EEPROM";
else if (deviceAddress == 0x56)
return "EEPROM";
else if (deviceAddress == 0x57)
return "EEPROM";
else if (deviceAddress == 0x58)
return "TPA2016,MAX21100";
else if (deviceAddress == 0x5A)
return "MPR121";
else if (deviceAddress == 0x5C)
return "BH1750";
else if (deviceAddress == 0x60)
return "MPL3115,MCP4725,MCP4728,TEA5767,Si5351";
else if (deviceAddress == 0x61)
return "MCP4725,AtlasEzoDO";
else if (deviceAddress == 0x62)
return "LidarLite,MCP4725,AtlasEzoORP";
else if (deviceAddress == 0x63)
return "MCP4725,AtlasEzoPH";
else if (deviceAddress == 0x64)
return "AtlasEzoEC";
else if (deviceAddress == 0x66)
return "AtlasEzoRTD";
else if (deviceAddress == 0x68)
return "DS1307,DS3231,MPU6050,MPU9050,MPU9250,ITG3200,ITG3701,"
"LSM9DS0,L3G4200D";
else if (deviceAddress == 0x69)
return "MPU6050,MPU9050,MPU9250,ITG3701,L3G4200D";
else if (deviceAddress == 0x6A)
return "LSM9DS1";
else if (deviceAddress == 0x6B)
return "LSM9DS0";
else if (deviceAddress == 0x70)
return "AdafruitLED";
else if (deviceAddress == 0x71)
return "SFE7SEG,AdafruitLED";
else if (deviceAddress == 0x72)
return "AdafruitLED";
else if (deviceAddress == 0x73)
return "AdafruitLED";
else if (deviceAddress == 0x76)
return "BMx280";
//return "BMx280,MS5607,MS5611,MS5637";
else if (deviceAddress == 0x77)
//return "BMx085,BMx180,BMx280,BMx680,MS5611";
return "BMx085,BMx180,BMx280,BMx680";
else
return "UNKNOWN";
}
#endif // AFE_CONFIG_HARDWARE_I2C | 6,725 | 3,109 |
/*
* Copyright (c) 2003 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Steve Reinhardt
* Ron Dreslinski
* Ali Saidi
*/
/**
* @file
* Definitions of page table.
*/
#include <fstream>
#include <map>
#include <string>
#include "base/bitfield.hh"
#include "base/intmath.hh"
#include "base/trace.hh"
#include "config/the_isa.hh"
#include "debug/MMU.hh"
#include "mem/page_table.hh"
#include "sim/faults.hh"
#include "sim/sim_object.hh"
using namespace std;
using namespace TheISA;
PageTable::PageTable(const std::string &__name, uint64_t _pid, Addr _pageSize)
: pageSize(_pageSize), offsetMask(mask(floorLog2(_pageSize))),
pid(_pid), _name(__name)
{
assert(isPowerOf2(pageSize));
pTableCache[0].valid = false;
pTableCache[1].valid = false;
pTableCache[2].valid = false;
}
PageTable::~PageTable()
{
}
void
PageTable::map(Addr vaddr, Addr paddr, int64_t size, bool clobber)
{
// starting address must be page aligned
assert(pageOffset(vaddr) == 0);
DPRINTF(MMU, "Allocating Page: %#x-%#x\n", vaddr, vaddr+ size);
for (; size > 0; size -= pageSize, vaddr += pageSize, paddr += pageSize) {
if (!clobber && (pTable.find(vaddr) != pTable.end())) {
// already mapped
fatal("PageTable::allocate: address 0x%x already mapped", vaddr);
}
pTable[vaddr] = TheISA::TlbEntry(pid, vaddr, paddr);
eraseCacheEntry(vaddr);
updateCache(vaddr, pTable[vaddr]);
}
}
void
PageTable::remap(Addr vaddr, int64_t size, Addr new_vaddr)
{
assert(pageOffset(vaddr) == 0);
assert(pageOffset(new_vaddr) == 0);
DPRINTF(MMU, "moving pages from vaddr %08p to %08p, size = %d\n", vaddr,
new_vaddr, size);
for (; size > 0; size -= pageSize, vaddr += pageSize, new_vaddr += pageSize) {
assert(pTable.find(vaddr) != pTable.end());
pTable[new_vaddr] = pTable[vaddr];
pTable.erase(vaddr);
eraseCacheEntry(vaddr);
pTable[new_vaddr].updateVaddr(new_vaddr);
updateCache(new_vaddr, pTable[new_vaddr]);
}
}
void
PageTable::unmap(Addr vaddr, int64_t size)
{
assert(pageOffset(vaddr) == 0);
DPRINTF(MMU, "Unmapping page: %#x-%#x\n", vaddr, vaddr+ size);
for (; size > 0; size -= pageSize, vaddr += pageSize) {
assert(pTable.find(vaddr) != pTable.end());
pTable.erase(vaddr);
eraseCacheEntry(vaddr);
}
}
bool
PageTable::isUnmapped(Addr vaddr, int64_t size)
{
// starting address must be page aligned
assert(pageOffset(vaddr) == 0);
for (; size > 0; size -= pageSize, vaddr += pageSize) {
if (pTable.find(vaddr) != pTable.end()) {
return false;
}
}
return true;
}
bool
PageTable::lookup(Addr vaddr, TheISA::TlbEntry &entry)
{
Addr page_addr = pageAlign(vaddr);
if (pTableCache[0].valid && pTableCache[0].vaddr == page_addr) {
entry = pTableCache[0].entry;
return true;
}
if (pTableCache[1].valid && pTableCache[1].vaddr == page_addr) {
entry = pTableCache[1].entry;
return true;
}
if (pTableCache[2].valid && pTableCache[2].vaddr == page_addr) {
entry = pTableCache[2].entry;
return true;
}
PTableItr iter = pTable.find(page_addr);
if (iter == pTable.end()) {
return false;
}
updateCache(page_addr, iter->second);
entry = iter->second;
return true;
}
bool
PageTable::translate(Addr vaddr, Addr &paddr)
{
TheISA::TlbEntry entry;
if (!lookup(vaddr, entry)) {
DPRINTF(MMU, "Couldn't Translate: %#x\n", vaddr);
return false;
}
paddr = pageOffset(vaddr) + entry.pageStart();
DPRINTF(MMU, "Translating: %#x->%#x\n", vaddr, paddr);
return true;
}
Fault
PageTable::translate(RequestPtr req)
{
Addr paddr;
assert(pageAlign(req->getVaddr() + req->getSize() - 1)
== pageAlign(req->getVaddr()));
if (!translate(req->getVaddr(), paddr)) {
return Fault(new GenericPageTableFault(req->getVaddr()));
}
req->setPaddr(paddr);
if ((paddr & (pageSize - 1)) + req->getSize() > pageSize) {
panic("Request spans page boundaries!\n");
return NoFault;
}
return NoFault;
}
void
PageTable::serialize(std::ostream &os)
{
paramOut(os, "ptable.size", pTable.size());
PTable::size_type count = 0;
PTableItr iter = pTable.begin();
PTableItr end = pTable.end();
while (iter != end) {
os << "\n[" << csprintf("%s.Entry%d", name(), count) << "]\n";
paramOut(os, "vaddr", iter->first);
iter->second.serialize(os);
++iter;
++count;
}
assert(count == pTable.size());
}
void
PageTable::unserialize(Checkpoint *cp, const std::string §ion)
{
int i = 0, count;
paramIn(cp, section, "ptable.size", count);
pTable.clear();
while (i < count) {
TheISA::TlbEntry *entry;
Addr vaddr;
paramIn(cp, csprintf("%s.Entry%d", name(), i), "vaddr", vaddr);
entry = new TheISA::TlbEntry();
entry->unserialize(cp, csprintf("%s.Entry%d", name(), i));
pTable[vaddr] = *entry;
delete entry;
++i;
}
}
| 6,712 | 2,429 |
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <initializer_list>
#include "tensorflow/lite/c/builtin_op_data.h"
#include "tensorflow/lite/c/common.h"
#include "tensorflow/lite/micro/kernels/kernel_runner.h"
#include "tensorflow/lite/micro/test_helpers.h"
#include "tensorflow/lite/micro/testing/micro_test.h"
namespace tflite {
namespace testing {
namespace {
void TestConcatenateTwoInputs(const int* input1_dims_data,
const float* input1_data,
const int* input2_dims_data,
const float* input2_data, int axis,
const int* output_dims_data,
const float* expected_output_data,
float* output_data) {
TfLiteIntArray* input1_dims = IntArrayFromInts(input1_dims_data);
TfLiteIntArray* input2_dims = IntArrayFromInts(input2_dims_data);
TfLiteIntArray* output_dims = IntArrayFromInts(output_dims_data);
constexpr int input_size = 2;
constexpr int output_size = 1;
constexpr int tensors_size = input_size + output_size;
TfLiteTensor tensors[tensors_size] = {CreateTensor(input1_data, input1_dims),
CreateTensor(input2_data, input2_dims),
CreateTensor(output_data, output_dims)};
int inputs_array_data[] = {2, 0, 1};
TfLiteIntArray* inputs_array = IntArrayFromInts(inputs_array_data);
int outputs_array_data[] = {1, 2};
TfLiteIntArray* outputs_array = IntArrayFromInts(outputs_array_data);
TfLiteConcatenationParams builtin_data = {
.axis = axis,
.activation = kTfLiteActNone // Only activation supported in this impl
};
const TfLiteRegistration registration =
tflite::ops::micro::Register_CONCATENATION();
micro::KernelRunner runner(
registration, tensors, tensors_size, inputs_array, outputs_array,
reinterpret_cast<void*>(&builtin_data), micro_test::reporter);
TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, runner.InitAndPrepare());
TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, runner.Invoke());
const int output_dims_count = ElementCount(*output_dims);
for (int i = 0; i < output_dims_count; ++i) {
TF_LITE_MICRO_EXPECT_NEAR(expected_output_data[i], output_data[i], 1e-5f);
}
}
void TestConcatenateQuantizedTwoInputs(
const int* input1_dims_data, const uint8_t* input1_data,
const int* input2_dims_data, const uint8_t* input2_data,
const float input_scale, const int input_zero_point, int axis,
const int* output_dims_data, const uint8_t* expected_output_data,
const float output_scale, const int output_zero_point,
uint8_t* output_data) {
TfLiteIntArray* input1_dims = IntArrayFromInts(input1_dims_data);
TfLiteIntArray* input2_dims = IntArrayFromInts(input2_dims_data);
TfLiteIntArray* output_dims = IntArrayFromInts(output_dims_data);
constexpr int input_size = 2;
constexpr int output_size = 1;
constexpr int tensors_size = input_size + output_size;
TfLiteTensor tensors[tensors_size] = {
CreateQuantizedTensor(input1_data, input1_dims, input_scale,
input_zero_point),
CreateQuantizedTensor(input2_data, input2_dims, input_scale,
input_zero_point),
CreateQuantizedTensor(output_data, output_dims, output_scale,
output_zero_point)};
int inputs_array_data[] = {2, 0, 1};
TfLiteIntArray* inputs_array = IntArrayFromInts(inputs_array_data);
int outputs_array_data[] = {1, 2};
TfLiteIntArray* outputs_array = IntArrayFromInts(outputs_array_data);
TfLiteConcatenationParams builtin_data = {
.axis = axis,
.activation = kTfLiteActNone // Only activation supported in this impl
};
const TfLiteRegistration registration =
tflite::ops::micro::Register_CONCATENATION();
micro::KernelRunner runner(
registration, tensors, tensors_size, inputs_array, outputs_array,
reinterpret_cast<void*>(&builtin_data), micro_test::reporter);
TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, runner.InitAndPrepare());
TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, runner.Invoke());
const int output_dims_count = ElementCount(*output_dims);
for (int i = 0; i < output_dims_count; ++i) {
TF_LITE_MICRO_EXPECT_EQ(expected_output_data[i], output_data[i]);
}
}
} // namespace
} // namespace testing
} // namespace tflite
TF_LITE_MICRO_TESTS_BEGIN
TF_LITE_MICRO_TEST(TwoInputsAllAxesCombinations) {
// Concatenate the same two input tensors along all possible axes.
const int input_shape[] = {2, 2, 3};
const float input1_value[] = {1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f};
const float input2_value[] = {7.0f, 8.0f, 9.0f, 10.0f, 11.0f, 12.0f};
// expected output when concatenating on axis 0
const int output_shape_axis0[] = {2, 4, 3};
const float output_value_axis0[] = {1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f,
7.0f, 8.0f, 9.0f, 10.0f, 11.0f, 12.0f};
// expected output when concatenating on axis 1
const int output_shape_axis1[] = {2, 2, 6};
const float output_value_axis1[] = {1.0f, 2.0f, 3.0f, 7.0f, 8.0f, 9.0f,
4.0f, 5.0f, 6.0f, 10.0f, 11.0f, 12.0f};
float output_data[12];
// Axis = 0
tflite::testing::TestConcatenateTwoInputs(
input_shape, input1_value, input_shape, input2_value, /* axis */ 0,
output_shape_axis0, output_value_axis0, output_data);
// Axis = -2 (equivalent to axis = 0)
tflite::testing::TestConcatenateTwoInputs(
input_shape, input1_value, input_shape, input2_value, /* axis */ -2,
output_shape_axis0, output_value_axis0, output_data);
// Axis = 1
tflite::testing::TestConcatenateTwoInputs(
input_shape, input1_value, input_shape, input2_value, /* axis */ 1,
output_shape_axis1, output_value_axis1, output_data);
// Axis = -1 (equivalent to axis = 1)
tflite::testing::TestConcatenateTwoInputs(
input_shape, input1_value, input_shape, input2_value, /* axis */ -1,
output_shape_axis1, output_value_axis1, output_data);
}
TF_LITE_MICRO_TEST(TwoInputsQuantizedUint8) {
const int axis = 2;
const int input_shape[] = {3, 2, 1, 2};
const int output_shape[] = {3, 2, 1, 4};
const float input_scale = 0.1f;
const int input_zero_point = 127;
const float output_scale = 0.1f;
const int output_zero_point = 127;
const uint8_t input1_values[] = {137, 157, 167, 197};
const uint8_t input2_values[] = {138, 158, 168, 198};
const uint8_t output_value[] = {
137, 157, 138, 158, 167, 197, 168, 198,
};
uint8_t output_data[8];
tflite::testing::TestConcatenateQuantizedTwoInputs(
input_shape, input1_values, input_shape, input2_values, input_scale,
input_zero_point, axis, output_shape, output_value, output_scale,
output_zero_point, output_data);
}
TF_LITE_MICRO_TEST(ThreeDimensionalTwoInputsDifferentShapes) {
const int axis = 1;
const int input1_shape[] = {3, 2, 1, 2};
const int input2_shape[] = {3, 2, 3, 2};
const int output_shape[] = {3, 2, 4, 2};
const float input1_values[] = {1.0f, 3.0f, 4.0f, 7.0f};
const float input2_values[] = {1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f,
7.0f, 8.0f, 9.0f, 10.0f, 11.0f, 12.0f};
const float output_values[] = {1.0f, 3.0f, 1.0f, 2.0f, 3.0f, 4.0f,
5.0f, 6.0f, 4.0f, 7.0f, 7.0f, 8.0f,
9.0f, 10.0f, 11.0f, 12.0f};
float output_data[16];
tflite::testing::TestConcatenateTwoInputs(
input1_shape, input1_values, input2_shape, input2_values, axis,
output_shape, output_values, output_data);
}
TF_LITE_MICRO_TESTS_END
| 8,323 | 3,232 |
// Copyright 2018 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 "ash/assistant/assistant_alarm_timer_controller_impl.h"
#include <cmath>
#include <utility>
#include "ash/assistant/assistant_controller_impl.h"
#include "ash/assistant/assistant_notification_controller_impl.h"
#include "ash/assistant/util/deep_link_util.h"
#include "ash/strings/grit/ash_strings.h"
#include "base/bind.h"
#include "base/i18n/message_formatter.h"
#include "base/strings/utf_string_conversions.h"
#include "base/time/time.h"
#include "chromeos/services/assistant/public/cpp/assistant_service.h"
#include "chromeos/services/assistant/public/cpp/features.h"
#include "chromeos/services/libassistant/public/cpp/assistant_notification.h"
#include "chromeos/services/libassistant/public/cpp/assistant_timer.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/receiver.h"
#include "third_party/icu/source/common/unicode/utypes.h"
#include "third_party/icu/source/i18n/unicode/measfmt.h"
#include "third_party/icu/source/i18n/unicode/measunit.h"
#include "third_party/icu/source/i18n/unicode/measure.h"
#include "ui/base/l10n/l10n_util.h"
namespace ash {
namespace {
using assistant::util::AlarmTimerAction;
using chromeos::assistant::AssistantNotification;
using chromeos::assistant::AssistantNotificationButton;
using chromeos::assistant::AssistantNotificationPriority;
using chromeos::assistant::AssistantTimer;
using chromeos::assistant::AssistantTimerState;
// Grouping key and ID prefix for timer notifications.
constexpr char kTimerNotificationGroupingKey[] = "assistant/timer";
constexpr char kTimerNotificationIdPrefix[] = "assistant/timer";
// Helpers ---------------------------------------------------------------------
std::string ToFormattedTimeString(base::TimeDelta time,
UMeasureFormatWidth width) {
DCHECK(width == UMEASFMT_WIDTH_NARROW || width == UMEASFMT_WIDTH_NUMERIC);
// Method aliases to prevent line-wrapping below.
const auto createHour = icu::MeasureUnit::createHour;
const auto createMinute = icu::MeasureUnit::createMinute;
const auto createSecond = icu::MeasureUnit::createSecond;
// We round |total_seconds| to the nearest full second since we don't display
// our time string w/ millisecond granularity and because this method is
// called very near to full second boundaries. Otherwise, values like 4.99 sec
// would be displayed to the user as "0:04" instead of the expected "0:05".
const int64_t total_seconds = std::abs(std::round(time.InSecondsF()));
// Calculate time in hours/minutes/seconds.
const int32_t hours = total_seconds / 3600;
const int32_t minutes = (total_seconds - hours * 3600) / 60;
const int32_t seconds = total_seconds % 60;
// Success of the ICU APIs is tracked by |status|.
UErrorCode status = U_ZERO_ERROR;
// Create our distinct |measures| to be formatted.
std::vector<icu::Measure> measures;
// We only show |hours| if necessary.
if (hours)
measures.emplace_back(hours, createHour(status), status);
// We only show |minutes| if necessary or if using numeric format |width|.
if (minutes || width == UMEASFMT_WIDTH_NUMERIC)
measures.emplace_back(minutes, createMinute(status), status);
// We only show |seconds| if necessary or if using numeric format |width|.
if (seconds || width == UMEASFMT_WIDTH_NUMERIC)
measures.emplace_back(seconds, createSecond(status), status);
// Format our |measures| into a |unicode_message|.
icu::UnicodeString unicode_message;
icu::FieldPosition field_position = icu::FieldPosition::DONT_CARE;
icu::MeasureFormat measure_format(icu::Locale::getDefault(), width, status);
measure_format.formatMeasures(measures.data(), measures.size(),
unicode_message, field_position, status);
std::string formatted_time;
if (U_SUCCESS(status)) {
// If formatting was successful, convert our |unicode_message| into UTF-8.
unicode_message.toUTF8String(formatted_time);
} else {
// If something went wrong formatting w/ ICU, fall back to I18N messages.
LOG(ERROR) << "Error formatting time string: " << status;
formatted_time =
base::UTF16ToUTF8(base::i18n::MessageFormatter::FormatWithNumberedArgs(
l10n_util::GetStringUTF16(
width == UMEASFMT_WIDTH_NARROW
? IDS_ASSISTANT_TIMER_NOTIFICATION_FORMATTED_TIME_NARROW_FALLBACK
: IDS_ASSISTANT_TIMER_NOTIFICATION_FORMATTED_TIME_NUMERIC_FALLBACK),
hours, minutes, seconds));
}
// If necessary, negate the amount of time remaining.
if (time.InSeconds() < 0) {
formatted_time =
base::UTF16ToUTF8(base::i18n::MessageFormatter::FormatWithNumberedArgs(
l10n_util::GetStringUTF16(
IDS_ASSISTANT_TIMER_NOTIFICATION_FORMATTED_TIME_NEGATE),
formatted_time));
}
return formatted_time;
}
// Returns a string representation of the original duration for a given |timer|.
std::string ToOriginalDurationString(const AssistantTimer& timer) {
return ToFormattedTimeString(timer.original_duration, UMEASFMT_WIDTH_NARROW);
}
// Returns a string representation of the remaining time for the given |timer|.
std::string ToRemainingTimeString(const AssistantTimer& timer) {
return ToFormattedTimeString(timer.remaining_time, UMEASFMT_WIDTH_NUMERIC);
}
// Creates a notification ID for the given |timer|. It is guaranteed that this
// method will always return the same notification ID given the same timer.
std::string CreateTimerNotificationId(const AssistantTimer& timer) {
return std::string(kTimerNotificationIdPrefix) + timer.id;
}
// Creates a notification title for the given |timer|.
std::string CreateTimerNotificationTitle(const AssistantTimer& timer) {
return ToRemainingTimeString(timer);
}
// Creates a notification message for the given |timer|.
std::string CreateTimerNotificationMessage(const AssistantTimer& timer) {
if (timer.label.empty()) {
return base::UTF16ToUTF8(
base::i18n::MessageFormatter::FormatWithNumberedArgs(
l10n_util::GetStringUTF16(
timer.state == AssistantTimerState::kFired
? IDS_ASSISTANT_TIMER_NOTIFICATION_MESSAGE_WHEN_FIRED
: IDS_ASSISTANT_TIMER_NOTIFICATION_MESSAGE),
ToOriginalDurationString(timer)));
}
return base::UTF16ToUTF8(base::i18n::MessageFormatter::FormatWithNumberedArgs(
l10n_util::GetStringUTF16(
timer.state == AssistantTimerState::kFired
? IDS_ASSISTANT_TIMER_NOTIFICATION_MESSAGE_WHEN_FIRED_WITH_LABEL
: IDS_ASSISTANT_TIMER_NOTIFICATION_MESSAGE_WITH_LABEL),
ToOriginalDurationString(timer), timer.label));
}
// Creates notification buttons for the given |timer|.
std::vector<AssistantNotificationButton> CreateTimerNotificationButtons(
const AssistantTimer& timer) {
std::vector<AssistantNotificationButton> buttons;
if (timer.state != AssistantTimerState::kFired) {
if (timer.state == AssistantTimerState::kPaused) {
// "RESUME" button.
buttons.push_back({l10n_util::GetStringUTF8(
IDS_ASSISTANT_TIMER_NOTIFICATION_RESUME_BUTTON),
assistant::util::CreateAlarmTimerDeepLink(
AlarmTimerAction::kResumeTimer, timer.id)
.value(),
/*remove_notification_on_click=*/false});
} else {
// "PAUSE" button.
buttons.push_back({l10n_util::GetStringUTF8(
IDS_ASSISTANT_TIMER_NOTIFICATION_PAUSE_BUTTON),
assistant::util::CreateAlarmTimerDeepLink(
AlarmTimerAction::kPauseTimer, timer.id)
.value(),
/*remove_notification_on_click=*/false});
}
}
if (timer.state == AssistantTimerState::kFired) {
// "STOP" button.
buttons.push_back(
{l10n_util::GetStringUTF8(IDS_ASSISTANT_TIMER_NOTIFICATION_STOP_BUTTON),
assistant::util::CreateAlarmTimerDeepLink(
AlarmTimerAction::kRemoveAlarmOrTimer, timer.id)
.value(),
/*remove_notification_on_click=*/true});
// "ADD 1 MIN" button.
buttons.push_back(
{l10n_util::GetStringUTF8(
IDS_ASSISTANT_TIMER_NOTIFICATION_ADD_1_MIN_BUTTON),
assistant::util::CreateAlarmTimerDeepLink(
AlarmTimerAction::kAddTimeToTimer, timer.id, base::Minutes(1))
.value(),
/*remove_notification_on_click=*/false});
} else {
// "CANCEL" button.
buttons.push_back({l10n_util::GetStringUTF8(
IDS_ASSISTANT_TIMER_NOTIFICATION_CANCEL_BUTTON),
assistant::util::CreateAlarmTimerDeepLink(
AlarmTimerAction::kRemoveAlarmOrTimer, timer.id)
.value(),
/*remove_notification_on_click=*/true});
}
return buttons;
}
// Creates a timer notification priority for the given |timer|.
AssistantNotificationPriority CreateTimerNotificationPriority(
const AssistantTimer& timer) {
// In timers v2, a notification for a |kFired| timer is |kHigh| priority.
// This will cause the notification to pop up to the user.
if (timer.state == AssistantTimerState::kFired)
return AssistantNotificationPriority::kHigh;
// If the notification has lived for at least |kPopupThreshold|, drop the
// priority to |kLow| so that the notification will not pop up to the user.
constexpr base::TimeDelta kPopupThreshold = base::Seconds(6);
const base::TimeDelta lifetime =
base::Time::Now() - timer.creation_time.value_or(base::Time::Now());
if (lifetime >= kPopupThreshold)
return AssistantNotificationPriority::kLow;
// Otherwise, the notification is |kDefault| priority. This means that it
// may or may not pop up to the user, depending on the presence of other
// notifications.
return AssistantNotificationPriority::kDefault;
}
// Creates a notification for the given |timer|.
AssistantNotification CreateTimerNotification(
const AssistantTimer& timer,
const AssistantNotification* existing_notification = nullptr) {
AssistantNotification notification;
notification.title = CreateTimerNotificationTitle(timer);
notification.message = CreateTimerNotificationMessage(timer);
notification.buttons = CreateTimerNotificationButtons(timer);
notification.client_id = CreateTimerNotificationId(timer);
notification.grouping_key = kTimerNotificationGroupingKey;
notification.priority = CreateTimerNotificationPriority(timer);
notification.remove_on_click = false;
notification.is_pinned = true;
// If we are creating a notification to replace an |existing_notification| and
// our new notification has higher priority, we want the system to "renotify"
// the user of the notification change. This will cause the new notification
// to popup to the user even if it was previously marked as read.
if (existing_notification &&
notification.priority > existing_notification->priority) {
notification.renotify = true;
}
return notification;
}
// Returns whether an |update| from LibAssistant to the specified |original|
// timer is allowed. Updates are always allowed in v1, only conditionally in v2.
bool ShouldAllowUpdateFromLibAssistant(const AssistantTimer& original,
const AssistantTimer& update) {
// If |id| is not equal, then |update| does refer to the |original| timer.
DCHECK_EQ(original.id, update.id);
// In v2, updates are only allowed from LibAssistant if they are significant.
// We may receive an update due to a state change in another timer, and we'd
// want to discard the update to this timer to avoid introducing UI jank by
// updating its notification outside of its regular tick interval. In v2, we
// also update timer state from |kScheduled| to |kFired| ourselves to work
// around latency in receiving the event from LibAssistant. When we do so, we
// expect to later receive the state change from LibAssistant but discard it.
return !original.IsEqualInLibAssistantTo(update);
}
} // namespace
// AssistantAlarmTimerControllerImpl ------------------------------------------
AssistantAlarmTimerControllerImpl::AssistantAlarmTimerControllerImpl(
AssistantControllerImpl* assistant_controller)
: assistant_controller_(assistant_controller) {
model_.AddObserver(this);
assistant_controller_observation_.Observe(AssistantController::Get());
}
AssistantAlarmTimerControllerImpl::~AssistantAlarmTimerControllerImpl() {
model_.RemoveObserver(this);
}
void AssistantAlarmTimerControllerImpl::SetAssistant(
chromeos::assistant::Assistant* assistant) {
assistant_ = assistant;
}
const AssistantAlarmTimerModel* AssistantAlarmTimerControllerImpl::GetModel()
const {
return &model_;
}
void AssistantAlarmTimerControllerImpl::OnTimerStateChanged(
const std::vector<AssistantTimer>& new_or_updated_timers) {
// First we remove all old timers that no longer exist.
for (const auto* old_timer : model_.GetAllTimers()) {
if (std::none_of(new_or_updated_timers.begin(), new_or_updated_timers.end(),
[&old_timer](const auto& new_or_updated_timer) {
return old_timer->id == new_or_updated_timer.id;
})) {
model_.RemoveTimer(old_timer->id);
}
}
// Then we add any new timers and update existing ones (if allowed).
for (const auto& new_or_updated_timer : new_or_updated_timers) {
const auto* original_timer = model_.GetTimerById(new_or_updated_timer.id);
const bool is_new_timer = original_timer == nullptr;
if (is_new_timer || ShouldAllowUpdateFromLibAssistant(
*original_timer, new_or_updated_timer)) {
model_.AddOrUpdateTimer(std::move(new_or_updated_timer));
}
}
}
void AssistantAlarmTimerControllerImpl::OnAssistantControllerConstructed() {
AssistantState::Get()->AddObserver(this);
}
void AssistantAlarmTimerControllerImpl::OnAssistantControllerDestroying() {
AssistantState::Get()->RemoveObserver(this);
}
void AssistantAlarmTimerControllerImpl::OnDeepLinkReceived(
assistant::util::DeepLinkType type,
const std::map<std::string, std::string>& params) {
using assistant::util::DeepLinkParam;
using assistant::util::DeepLinkType;
if (type != DeepLinkType::kAlarmTimer)
return;
const absl::optional<AlarmTimerAction>& action =
assistant::util::GetDeepLinkParamAsAlarmTimerAction(params);
if (!action.has_value())
return;
const absl::optional<std::string>& alarm_timer_id =
assistant::util::GetDeepLinkParam(params, DeepLinkParam::kId);
if (!alarm_timer_id.has_value())
return;
// Duration is optional. Only used for adding time to timer.
const absl::optional<base::TimeDelta>& duration =
assistant::util::GetDeepLinkParamAsTimeDelta(params,
DeepLinkParam::kDurationMs);
PerformAlarmTimerAction(action.value(), alarm_timer_id.value(), duration);
}
void AssistantAlarmTimerControllerImpl::OnAssistantStatusChanged(
chromeos::assistant::AssistantStatus status) {
// If LibAssistant is no longer running we need to clear our cache to
// accurately reflect LibAssistant alarm/timer state.
if (status == chromeos::assistant::AssistantStatus::NOT_READY)
model_.RemoveAllTimers();
}
void AssistantAlarmTimerControllerImpl::OnTimerAdded(
const AssistantTimer& timer) {
// Schedule the next tick of |timer|.
ScheduleNextTick(timer);
// Create a notification for the added alarm/timer.
assistant_controller_->notification_controller()->AddOrUpdateNotification(
CreateTimerNotification(timer));
}
void AssistantAlarmTimerControllerImpl::OnTimerUpdated(
const AssistantTimer& timer) {
// Schedule the next tick of |timer|.
ScheduleNextTick(timer);
auto* notification_controller =
assistant_controller_->notification_controller();
const auto* existing_notification =
notification_controller->model()->GetNotificationById(
CreateTimerNotificationId(timer));
// When a |timer| is updated we need to update the corresponding notification
// unless it has already been dismissed by the user.
if (existing_notification) {
notification_controller->AddOrUpdateNotification(
CreateTimerNotification(timer, existing_notification));
}
}
void AssistantAlarmTimerControllerImpl::OnTimerRemoved(
const AssistantTimer& timer) {
// Clean up the ticker for |timer|, if one exists.
tickers_.erase(timer.id);
// Remove any notification associated w/ |timer|.
assistant_controller_->notification_controller()->RemoveNotificationById(
CreateTimerNotificationId(timer), /*from_server=*/false);
}
void AssistantAlarmTimerControllerImpl::PerformAlarmTimerAction(
const AlarmTimerAction& action,
const std::string& alarm_timer_id,
const absl::optional<base::TimeDelta>& duration) {
DCHECK(assistant_);
switch (action) {
case AlarmTimerAction::kAddTimeToTimer:
if (!duration.has_value()) {
LOG(ERROR) << "Ignoring add time to timer action duration.";
return;
}
assistant_->AddTimeToTimer(alarm_timer_id, duration.value());
break;
case AlarmTimerAction::kPauseTimer:
DCHECK(!duration.has_value());
assistant_->PauseTimer(alarm_timer_id);
break;
case AlarmTimerAction::kRemoveAlarmOrTimer:
DCHECK(!duration.has_value());
assistant_->RemoveAlarmOrTimer(alarm_timer_id);
break;
case AlarmTimerAction::kResumeTimer:
DCHECK(!duration.has_value());
assistant_->ResumeTimer(alarm_timer_id);
break;
}
}
void AssistantAlarmTimerControllerImpl::ScheduleNextTick(
const AssistantTimer& timer) {
auto& ticker = tickers_[timer.id];
if (ticker.IsRunning())
return;
// The next tick of |timer| should occur at its next full second of remaining
// time. Here we are calculating the number of milliseconds to that next full
// second.
int millis_to_next_full_sec = timer.remaining_time.InMilliseconds() % 1000;
// If |timer| has already fired, |millis_to_next_full_sec| will be negative.
// In this case, we take the inverse of the value to get the correct number of
// milliseconds to the next full second of remaining time.
if (millis_to_next_full_sec < 0)
millis_to_next_full_sec = 1000 + millis_to_next_full_sec;
// If we are exactly at the boundary of a full second, we want to make sure
// we wait until the next second to perform the next tick. Otherwise we'll end
// up w/ a superfluous tick that is unnecessary.
if (millis_to_next_full_sec == 0)
millis_to_next_full_sec = 1000;
// NOTE: We pass a copy of |timer.id| here as |timer| may no longer exist
// when Tick() is called due to the possibility of the |model_| being updated
// via a call to OnTimerStateChanged(), such as might happen if a timer is
// created, paused, resumed, or removed by LibAssistant.
ticker.Start(FROM_HERE, base::Milliseconds(millis_to_next_full_sec),
base::BindOnce(&AssistantAlarmTimerControllerImpl::Tick,
base::Unretained(this), timer.id));
}
void AssistantAlarmTimerControllerImpl::Tick(const std::string& timer_id) {
const auto* timer = model_.GetTimerById(timer_id);
DCHECK(timer);
// We don't tick paused timers. Once the |timer| resumes, ticking will resume.
if (timer->state == AssistantTimerState::kPaused)
return;
// Update |timer| to reflect the new amount of |remaining_time|.
AssistantTimer updated_timer(*timer);
updated_timer.remaining_time = updated_timer.fire_time - base::Time::Now();
// If there is no remaining time left on the timer, we ensure that our timer
// is marked as |kFired|. Since LibAssistant may be a bit slow to notify us of
// the change in state, we set the value ourselves to eliminate UI jank.
// NOTE: We use the rounded value of |remaining_time| since that's what we are
// displaying to the user and otherwise would be out of sync for ticks
// occurring at full second boundary values.
if (std::round(updated_timer.remaining_time.InSecondsF()) <= 0.f)
updated_timer.state = AssistantTimerState::kFired;
model_.AddOrUpdateTimer(std::move(updated_timer));
}
} // namespace ash
| 20,626 | 6,180 |
/*
* Copyright 2012 The LibYuv Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "libyuv/basic_types.h"
#include "libyuv/row.h"
#ifdef __cplusplus
namespace libyuv {
extern "C" {
#endif
// This module is for GCC MIPS DSPR2
#if !defined(LIBYUV_DISABLE_MIPS) && defined(__mips_dsp) && \
(__mips_dsp_rev >= 2) && (_MIPS_SIM == _MIPS_SIM_ABI32)
void ScaleRowDown2_DSPR2(const uint8* src_ptr,
ptrdiff_t src_stride,
uint8* dst,
int dst_width) {
__asm__ __volatile__(
".set push \n"
".set noreorder \n"
"srl $t9, %[dst_width], 4 \n" // iterations -> by 16
"beqz $t9, 2f \n"
" nop \n"
"1: \n"
"lw $t0, 0(%[src_ptr]) \n" // |3|2|1|0|
"lw $t1, 4(%[src_ptr]) \n" // |7|6|5|4|
"lw $t2, 8(%[src_ptr]) \n" // |11|10|9|8|
"lw $t3, 12(%[src_ptr]) \n" // |15|14|13|12|
"lw $t4, 16(%[src_ptr]) \n" // |19|18|17|16|
"lw $t5, 20(%[src_ptr]) \n" // |23|22|21|20|
"lw $t6, 24(%[src_ptr]) \n" // |27|26|25|24|
"lw $t7, 28(%[src_ptr]) \n" // |31|30|29|28|
// TODO(fbarchard): Use odd pixels instead of even.
"precr.qb.ph $t8, $t1, $t0 \n" // |6|4|2|0|
"precr.qb.ph $t0, $t3, $t2 \n" // |14|12|10|8|
"precr.qb.ph $t1, $t5, $t4 \n" // |22|20|18|16|
"precr.qb.ph $t2, $t7, $t6 \n" // |30|28|26|24|
"addiu %[src_ptr], %[src_ptr], 32 \n"
"addiu $t9, $t9, -1 \n"
"sw $t8, 0(%[dst]) \n"
"sw $t0, 4(%[dst]) \n"
"sw $t1, 8(%[dst]) \n"
"sw $t2, 12(%[dst]) \n"
"bgtz $t9, 1b \n"
" addiu %[dst], %[dst], 16 \n"
"2: \n"
"andi $t9, %[dst_width], 0xf \n" // residue
"beqz $t9, 3f \n"
" nop \n"
"21: \n"
"lbu $t0, 0(%[src_ptr]) \n"
"addiu %[src_ptr], %[src_ptr], 2 \n"
"addiu $t9, $t9, -1 \n"
"sb $t0, 0(%[dst]) \n"
"bgtz $t9, 21b \n"
" addiu %[dst], %[dst], 1 \n"
"3: \n"
".set pop \n"
: [src_ptr] "+r"(src_ptr), [dst] "+r"(dst)
: [dst_width] "r"(dst_width)
: "t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7", "t8", "t9");
}
void ScaleRowDown2Box_DSPR2(const uint8* src_ptr,
ptrdiff_t src_stride,
uint8* dst,
int dst_width) {
const uint8* t = src_ptr + src_stride;
__asm__ __volatile__(
".set push \n"
".set noreorder \n"
"srl $t9, %[dst_width], 3 \n" // iterations -> step 8
"bltz $t9, 2f \n"
" nop \n"
"1: \n"
"lw $t0, 0(%[src_ptr]) \n" // |3|2|1|0|
"lw $t1, 4(%[src_ptr]) \n" // |7|6|5|4|
"lw $t2, 8(%[src_ptr]) \n" // |11|10|9|8|
"lw $t3, 12(%[src_ptr]) \n" // |15|14|13|12|
"lw $t4, 0(%[t]) \n" // |19|18|17|16|
"lw $t5, 4(%[t]) \n" // |23|22|21|20|
"lw $t6, 8(%[t]) \n" // |27|26|25|24|
"lw $t7, 12(%[t]) \n" // |31|30|29|28|
"addiu $t9, $t9, -1 \n"
"srl $t8, $t0, 16 \n" // |X|X|3|2|
"ins $t0, $t4, 16, 16 \n" // |17|16|1|0|
"ins $t4, $t8, 0, 16 \n" // |19|18|3|2|
"raddu.w.qb $t0, $t0 \n" // |17+16+1+0|
"raddu.w.qb $t4, $t4 \n" // |19+18+3+2|
"shra_r.w $t0, $t0, 2 \n" // |t0+2|>>2
"shra_r.w $t4, $t4, 2 \n" // |t4+2|>>2
"srl $t8, $t1, 16 \n" // |X|X|7|6|
"ins $t1, $t5, 16, 16 \n" // |21|20|5|4|
"ins $t5, $t8, 0, 16 \n" // |22|23|7|6|
"raddu.w.qb $t1, $t1 \n" // |21+20+5+4|
"raddu.w.qb $t5, $t5 \n" // |23+22+7+6|
"shra_r.w $t1, $t1, 2 \n" // |t1+2|>>2
"shra_r.w $t5, $t5, 2 \n" // |t5+2|>>2
"srl $t8, $t2, 16 \n" // |X|X|11|10|
"ins $t2, $t6, 16, 16 \n" // |25|24|9|8|
"ins $t6, $t8, 0, 16 \n" // |27|26|11|10|
"raddu.w.qb $t2, $t2 \n" // |25+24+9+8|
"raddu.w.qb $t6, $t6 \n" // |27+26+11+10|
"shra_r.w $t2, $t2, 2 \n" // |t2+2|>>2
"shra_r.w $t6, $t6, 2 \n" // |t5+2|>>2
"srl $t8, $t3, 16 \n" // |X|X|15|14|
"ins $t3, $t7, 16, 16 \n" // |29|28|13|12|
"ins $t7, $t8, 0, 16 \n" // |31|30|15|14|
"raddu.w.qb $t3, $t3 \n" // |29+28+13+12|
"raddu.w.qb $t7, $t7 \n" // |31+30+15+14|
"shra_r.w $t3, $t3, 2 \n" // |t3+2|>>2
"shra_r.w $t7, $t7, 2 \n" // |t7+2|>>2
"addiu %[src_ptr], %[src_ptr], 16 \n"
"addiu %[t], %[t], 16 \n"
"sb $t0, 0(%[dst]) \n"
"sb $t4, 1(%[dst]) \n"
"sb $t1, 2(%[dst]) \n"
"sb $t5, 3(%[dst]) \n"
"sb $t2, 4(%[dst]) \n"
"sb $t6, 5(%[dst]) \n"
"sb $t3, 6(%[dst]) \n"
"sb $t7, 7(%[dst]) \n"
"bgtz $t9, 1b \n"
" addiu %[dst], %[dst], 8 \n"
"2: \n"
"andi $t9, %[dst_width], 0x7 \n" // x = residue
"beqz $t9, 3f \n"
" nop \n"
"21: \n"
"lwr $t1, 0(%[src_ptr]) \n"
"lwl $t1, 3(%[src_ptr]) \n"
"lwr $t2, 0(%[t]) \n"
"lwl $t2, 3(%[t]) \n"
"srl $t8, $t1, 16 \n"
"ins $t1, $t2, 16, 16 \n"
"ins $t2, $t8, 0, 16 \n"
"raddu.w.qb $t1, $t1 \n"
"raddu.w.qb $t2, $t2 \n"
"shra_r.w $t1, $t1, 2 \n"
"shra_r.w $t2, $t2, 2 \n"
"sb $t1, 0(%[dst]) \n"
"sb $t2, 1(%[dst]) \n"
"addiu %[src_ptr], %[src_ptr], 4 \n"
"addiu $t9, $t9, -2 \n"
"addiu %[t], %[t], 4 \n"
"bgtz $t9, 21b \n"
" addiu %[dst], %[dst], 2 \n"
"3: \n"
".set pop \n"
: [src_ptr] "+r"(src_ptr), [dst] "+r"(dst), [t] "+r"(t)
: [dst_width] "r"(dst_width)
: "t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7", "t8", "t9");
}
void ScaleRowDown4_DSPR2(const uint8* src_ptr,
ptrdiff_t src_stride,
uint8* dst,
int dst_width) {
__asm__ __volatile__(
".set push \n"
".set noreorder \n"
"srl $t9, %[dst_width], 3 \n"
"beqz $t9, 2f \n"
" nop \n"
"1: \n"
"lw $t1, 0(%[src_ptr]) \n" // |3|2|1|0|
"lw $t2, 4(%[src_ptr]) \n" // |7|6|5|4|
"lw $t3, 8(%[src_ptr]) \n" // |11|10|9|8|
"lw $t4, 12(%[src_ptr]) \n" // |15|14|13|12|
"lw $t5, 16(%[src_ptr]) \n" // |19|18|17|16|
"lw $t6, 20(%[src_ptr]) \n" // |23|22|21|20|
"lw $t7, 24(%[src_ptr]) \n" // |27|26|25|24|
"lw $t8, 28(%[src_ptr]) \n" // |31|30|29|28|
"precr.qb.ph $t1, $t2, $t1 \n" // |6|4|2|0|
"precr.qb.ph $t2, $t4, $t3 \n" // |14|12|10|8|
"precr.qb.ph $t5, $t6, $t5 \n" // |22|20|18|16|
"precr.qb.ph $t6, $t8, $t7 \n" // |30|28|26|24|
"precr.qb.ph $t1, $t2, $t1 \n" // |12|8|4|0|
"precr.qb.ph $t5, $t6, $t5 \n" // |28|24|20|16|
"addiu %[src_ptr], %[src_ptr], 32 \n"
"addiu $t9, $t9, -1 \n"
"sw $t1, 0(%[dst]) \n"
"sw $t5, 4(%[dst]) \n"
"bgtz $t9, 1b \n"
" addiu %[dst], %[dst], 8 \n"
"2: \n"
"andi $t9, %[dst_width], 7 \n" // residue
"beqz $t9, 3f \n"
" nop \n"
"21: \n"
"lbu $t1, 0(%[src_ptr]) \n"
"addiu %[src_ptr], %[src_ptr], 4 \n"
"addiu $t9, $t9, -1 \n"
"sb $t1, 0(%[dst]) \n"
"bgtz $t9, 21b \n"
" addiu %[dst], %[dst], 1 \n"
"3: \n"
".set pop \n"
: [src_ptr] "+r"(src_ptr), [dst] "+r"(dst)
: [dst_width] "r"(dst_width)
: "t1", "t2", "t3", "t4", "t5", "t6", "t7", "t8", "t9");
}
void ScaleRowDown4Box_DSPR2(const uint8* src_ptr,
ptrdiff_t src_stride,
uint8* dst,
int dst_width) {
intptr_t stride = src_stride;
const uint8* s1 = src_ptr + stride;
const uint8* s2 = s1 + stride;
const uint8* s3 = s2 + stride;
__asm__ __volatile__(
".set push \n"
".set noreorder \n"
"srl $t9, %[dst_width], 1 \n"
"andi $t8, %[dst_width], 1 \n"
"1: \n"
"lw $t0, 0(%[src_ptr]) \n" // |3|2|1|0|
"lw $t1, 0(%[s1]) \n" // |7|6|5|4|
"lw $t2, 0(%[s2]) \n" // |11|10|9|8|
"lw $t3, 0(%[s3]) \n" // |15|14|13|12|
"lw $t4, 4(%[src_ptr]) \n" // |19|18|17|16|
"lw $t5, 4(%[s1]) \n" // |23|22|21|20|
"lw $t6, 4(%[s2]) \n" // |27|26|25|24|
"lw $t7, 4(%[s3]) \n" // |31|30|29|28|
"raddu.w.qb $t0, $t0 \n" // |3 + 2 + 1 + 0|
"raddu.w.qb $t1, $t1 \n" // |7 + 6 + 5 + 4|
"raddu.w.qb $t2, $t2 \n" // |11 + 10 + 9 + 8|
"raddu.w.qb $t3, $t3 \n" // |15 + 14 + 13 + 12|
"raddu.w.qb $t4, $t4 \n" // |19 + 18 + 17 + 16|
"raddu.w.qb $t5, $t5 \n" // |23 + 22 + 21 + 20|
"raddu.w.qb $t6, $t6 \n" // |27 + 26 + 25 + 24|
"raddu.w.qb $t7, $t7 \n" // |31 + 30 + 29 + 28|
"add $t0, $t0, $t1 \n"
"add $t1, $t2, $t3 \n"
"add $t0, $t0, $t1 \n"
"add $t4, $t4, $t5 \n"
"add $t6, $t6, $t7 \n"
"add $t4, $t4, $t6 \n"
"shra_r.w $t0, $t0, 4 \n"
"shra_r.w $t4, $t4, 4 \n"
"sb $t0, 0(%[dst]) \n"
"sb $t4, 1(%[dst]) \n"
"addiu %[src_ptr], %[src_ptr], 8 \n"
"addiu %[s1], %[s1], 8 \n"
"addiu %[s2], %[s2], 8 \n"
"addiu %[s3], %[s3], 8 \n"
"addiu $t9, $t9, -1 \n"
"bgtz $t9, 1b \n"
" addiu %[dst], %[dst], 2 \n"
"beqz $t8, 2f \n"
" nop \n"
"lw $t0, 0(%[src_ptr]) \n" // |3|2|1|0|
"lw $t1, 0(%[s1]) \n" // |7|6|5|4|
"lw $t2, 0(%[s2]) \n" // |11|10|9|8|
"lw $t3, 0(%[s3]) \n" // |15|14|13|12|
"raddu.w.qb $t0, $t0 \n" // |3 + 2 + 1 + 0|
"raddu.w.qb $t1, $t1 \n" // |7 + 6 + 5 + 4|
"raddu.w.qb $t2, $t2 \n" // |11 + 10 + 9 + 8|
"raddu.w.qb $t3, $t3 \n" // |15 + 14 + 13 + 12|
"add $t0, $t0, $t1 \n"
"add $t1, $t2, $t3 \n"
"add $t0, $t0, $t1 \n"
"shra_r.w $t0, $t0, 4 \n"
"sb $t0, 0(%[dst]) \n"
"2: \n"
".set pop \n"
: [src_ptr] "+r"(src_ptr), [dst] "+r"(dst), [s1] "+r"(s1), [s2] "+r"(s2),
[s3] "+r"(s3)
: [dst_width] "r"(dst_width)
: "t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7", "t8", "t9");
}
void ScaleRowDown34_DSPR2(const uint8* src_ptr,
ptrdiff_t src_stride,
uint8* dst,
int dst_width) {
__asm__ __volatile__(
".set push \n"
".set noreorder \n"
"1: \n"
"lw $t1, 0(%[src_ptr]) \n" // |3|2|1|0|
"lw $t2, 4(%[src_ptr]) \n" // |7|6|5|4|
"lw $t3, 8(%[src_ptr]) \n" // |11|10|9|8|
"lw $t4, 12(%[src_ptr]) \n" // |15|14|13|12|
"lw $t5, 16(%[src_ptr]) \n" // |19|18|17|16|
"lw $t6, 20(%[src_ptr]) \n" // |23|22|21|20|
"lw $t7, 24(%[src_ptr]) \n" // |27|26|25|24|
"lw $t8, 28(%[src_ptr]) \n" // |31|30|29|28|
"precrq.qb.ph $t0, $t2, $t4 \n" // |7|5|15|13|
"precrq.qb.ph $t9, $t6, $t8 \n" // |23|21|31|30|
"addiu %[dst_width], %[dst_width], -24 \n"
"ins $t1, $t1, 8, 16 \n" // |3|1|0|X|
"ins $t4, $t0, 8, 16 \n" // |X|15|13|12|
"ins $t5, $t5, 8, 16 \n" // |19|17|16|X|
"ins $t8, $t9, 8, 16 \n" // |X|31|29|28|
"addiu %[src_ptr], %[src_ptr], 32 \n"
"packrl.ph $t0, $t3, $t0 \n" // |9|8|7|5|
"packrl.ph $t9, $t7, $t9 \n" // |25|24|23|21|
"prepend $t1, $t2, 8 \n" // |4|3|1|0|
"prepend $t3, $t4, 24 \n" // |15|13|12|11|
"prepend $t5, $t6, 8 \n" // |20|19|17|16|
"prepend $t7, $t8, 24 \n" // |31|29|28|27|
"sw $t1, 0(%[dst]) \n"
"sw $t0, 4(%[dst]) \n"
"sw $t3, 8(%[dst]) \n"
"sw $t5, 12(%[dst]) \n"
"sw $t9, 16(%[dst]) \n"
"sw $t7, 20(%[dst]) \n"
"bnez %[dst_width], 1b \n"
" addiu %[dst], %[dst], 24 \n"
".set pop \n"
: [src_ptr] "+r"(src_ptr), [dst] "+r"(dst), [dst_width] "+r"(dst_width)
:
: "t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7", "t8", "t9");
}
void ScaleRowDown34_0_Box_DSPR2(const uint8* src_ptr,
ptrdiff_t src_stride,
uint8* d,
int dst_width) {
__asm__ __volatile__(
".set push \n"
".set noreorder \n"
"repl.ph $t3, 3 \n" // 0x00030003
"1: \n"
"lw $t0, 0(%[src_ptr]) \n" // |S3|S2|S1|S0|
"lwx $t1, %[src_stride](%[src_ptr]) \n" // |T3|T2|T1|T0|
"rotr $t2, $t0, 8 \n" // |S0|S3|S2|S1|
"rotr $t6, $t1, 8 \n" // |T0|T3|T2|T1|
"muleu_s.ph.qbl $t4, $t2, $t3 \n" // |S0*3|S3*3|
"muleu_s.ph.qbl $t5, $t6, $t3 \n" // |T0*3|T3*3|
"andi $t0, $t2, 0xFFFF \n" // |0|0|S2|S1|
"andi $t1, $t6, 0xFFFF \n" // |0|0|T2|T1|
"raddu.w.qb $t0, $t0 \n"
"raddu.w.qb $t1, $t1 \n"
"shra_r.w $t0, $t0, 1 \n"
"shra_r.w $t1, $t1, 1 \n"
"preceu.ph.qbr $t2, $t2 \n" // |0|S2|0|S1|
"preceu.ph.qbr $t6, $t6 \n" // |0|T2|0|T1|
"rotr $t2, $t2, 16 \n" // |0|S1|0|S2|
"rotr $t6, $t6, 16 \n" // |0|T1|0|T2|
"addu.ph $t2, $t2, $t4 \n"
"addu.ph $t6, $t6, $t5 \n"
"sll $t5, $t0, 1 \n"
"add $t0, $t5, $t0 \n"
"shra_r.ph $t2, $t2, 2 \n"
"shra_r.ph $t6, $t6, 2 \n"
"shll.ph $t4, $t2, 1 \n"
"addq.ph $t4, $t4, $t2 \n"
"addu $t0, $t0, $t1 \n"
"addiu %[src_ptr], %[src_ptr], 4 \n"
"shra_r.w $t0, $t0, 2 \n"
"addu.ph $t6, $t6, $t4 \n"
"shra_r.ph $t6, $t6, 2 \n"
"srl $t1, $t6, 16 \n"
"addiu %[dst_width], %[dst_width], -3 \n"
"sb $t1, 0(%[d]) \n"
"sb $t0, 1(%[d]) \n"
"sb $t6, 2(%[d]) \n"
"bgtz %[dst_width], 1b \n"
" addiu %[d], %[d], 3 \n"
"3: \n"
".set pop \n"
: [src_ptr] "+r"(src_ptr), [src_stride] "+r"(src_stride), [d] "+r"(d),
[dst_width] "+r"(dst_width)
:
: "t0", "t1", "t2", "t3", "t4", "t5", "t6");
}
void ScaleRowDown34_1_Box_DSPR2(const uint8* src_ptr,
ptrdiff_t src_stride,
uint8* d,
int dst_width) {
__asm__ __volatile__(
".set push \n"
".set noreorder \n"
"repl.ph $t2, 3 \n" // 0x00030003
"1: \n"
"lw $t0, 0(%[src_ptr]) \n" // |S3|S2|S1|S0|
"lwx $t1, %[src_stride](%[src_ptr]) \n" // |T3|T2|T1|T0|
"rotr $t4, $t0, 8 \n" // |S0|S3|S2|S1|
"rotr $t6, $t1, 8 \n" // |T0|T3|T2|T1|
"muleu_s.ph.qbl $t3, $t4, $t2 \n" // |S0*3|S3*3|
"muleu_s.ph.qbl $t5, $t6, $t2 \n" // |T0*3|T3*3|
"andi $t0, $t4, 0xFFFF \n" // |0|0|S2|S1|
"andi $t1, $t6, 0xFFFF \n" // |0|0|T2|T1|
"raddu.w.qb $t0, $t0 \n"
"raddu.w.qb $t1, $t1 \n"
"shra_r.w $t0, $t0, 1 \n"
"shra_r.w $t1, $t1, 1 \n"
"preceu.ph.qbr $t4, $t4 \n" // |0|S2|0|S1|
"preceu.ph.qbr $t6, $t6 \n" // |0|T2|0|T1|
"rotr $t4, $t4, 16 \n" // |0|S1|0|S2|
"rotr $t6, $t6, 16 \n" // |0|T1|0|T2|
"addu.ph $t4, $t4, $t3 \n"
"addu.ph $t6, $t6, $t5 \n"
"shra_r.ph $t6, $t6, 2 \n"
"shra_r.ph $t4, $t4, 2 \n"
"addu.ph $t6, $t6, $t4 \n"
"addiu %[src_ptr], %[src_ptr], 4 \n"
"shra_r.ph $t6, $t6, 1 \n"
"addu $t0, $t0, $t1 \n"
"addiu %[dst_width], %[dst_width], -3 \n"
"shra_r.w $t0, $t0, 1 \n"
"srl $t1, $t6, 16 \n"
"sb $t1, 0(%[d]) \n"
"sb $t0, 1(%[d]) \n"
"sb $t6, 2(%[d]) \n"
"bgtz %[dst_width], 1b \n"
" addiu %[d], %[d], 3 \n"
"3: \n"
".set pop \n"
: [src_ptr] "+r"(src_ptr), [src_stride] "+r"(src_stride), [d] "+r"(d),
[dst_width] "+r"(dst_width)
:
: "t0", "t1", "t2", "t3", "t4", "t5", "t6");
}
void ScaleRowDown38_DSPR2(const uint8* src_ptr,
ptrdiff_t src_stride,
uint8* dst,
int dst_width) {
__asm__ __volatile__(
".set push \n"
".set noreorder \n"
"1: \n"
"lw $t0, 0(%[src_ptr]) \n" // |3|2|1|0|
"lw $t1, 4(%[src_ptr]) \n" // |7|6|5|4|
"lw $t2, 8(%[src_ptr]) \n" // |11|10|9|8|
"lw $t3, 12(%[src_ptr]) \n" // |15|14|13|12|
"lw $t4, 16(%[src_ptr]) \n" // |19|18|17|16|
"lw $t5, 20(%[src_ptr]) \n" // |23|22|21|20|
"lw $t6, 24(%[src_ptr]) \n" // |27|26|25|24|
"lw $t7, 28(%[src_ptr]) \n" // |31|30|29|28|
"wsbh $t0, $t0 \n" // |2|3|0|1|
"wsbh $t6, $t6 \n" // |26|27|24|25|
"srl $t0, $t0, 8 \n" // |X|2|3|0|
"srl $t3, $t3, 16 \n" // |X|X|15|14|
"srl $t5, $t5, 16 \n" // |X|X|23|22|
"srl $t7, $t7, 16 \n" // |X|X|31|30|
"ins $t1, $t2, 24, 8 \n" // |8|6|5|4|
"ins $t6, $t5, 0, 8 \n" // |26|27|24|22|
"ins $t1, $t0, 0, 16 \n" // |8|6|3|0|
"ins $t6, $t7, 24, 8 \n" // |30|27|24|22|
"prepend $t2, $t3, 24 \n" // |X|15|14|11|
"ins $t4, $t4, 16, 8 \n" // |19|16|17|X|
"ins $t4, $t2, 0, 16 \n" // |19|16|14|11|
"addiu %[src_ptr], %[src_ptr], 32 \n"
"addiu %[dst_width], %[dst_width], -12 \n"
"addiu $t8,%[dst_width], -12 \n"
"sw $t1, 0(%[dst]) \n"
"sw $t4, 4(%[dst]) \n"
"sw $t6, 8(%[dst]) \n"
"bgez $t8, 1b \n"
" addiu %[dst], %[dst], 12 \n"
".set pop \n"
: [src_ptr] "+r"(src_ptr), [dst] "+r"(dst), [dst_width] "+r"(dst_width)
:
: "t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7", "t8");
}
void ScaleRowDown38_2_Box_DSPR2(const uint8* src_ptr,
ptrdiff_t src_stride,
uint8* dst_ptr,
int dst_width) {
intptr_t stride = src_stride;
const uint8* t = src_ptr + stride;
const int c = 0x2AAA;
__asm__ __volatile__(
".set push \n"
".set noreorder \n"
"1: \n"
"lw $t0, 0(%[src_ptr]) \n" // |S3|S2|S1|S0|
"lw $t1, 4(%[src_ptr]) \n" // |S7|S6|S5|S4|
"lw $t2, 0(%[t]) \n" // |T3|T2|T1|T0|
"lw $t3, 4(%[t]) \n" // |T7|T6|T5|T4|
"rotr $t1, $t1, 16 \n" // |S5|S4|S7|S6|
"packrl.ph $t4, $t1, $t3 \n" // |S7|S6|T7|T6|
"packrl.ph $t5, $t3, $t1 \n" // |T5|T4|S5|S4|
"raddu.w.qb $t4, $t4 \n" // S7+S6+T7+T6
"raddu.w.qb $t5, $t5 \n" // T5+T4+S5+S4
"precrq.qb.ph $t6, $t0, $t2 \n" // |S3|S1|T3|T1|
"precrq.qb.ph $t6, $t6, $t6 \n" // |S3|T3|S3|T3|
"srl $t4, $t4, 2 \n" // t4 / 4
"srl $t6, $t6, 16 \n" // |0|0|S3|T3|
"raddu.w.qb $t6, $t6 \n" // 0+0+S3+T3
"addu $t6, $t5, $t6 \n"
"mul $t6, $t6, %[c] \n" // t6 * 0x2AAA
"sll $t0, $t0, 8 \n" // |S2|S1|S0|0|
"sll $t2, $t2, 8 \n" // |T2|T1|T0|0|
"raddu.w.qb $t0, $t0 \n" // S2+S1+S0+0
"raddu.w.qb $t2, $t2 \n" // T2+T1+T0+0
"addu $t0, $t0, $t2 \n"
"mul $t0, $t0, %[c] \n" // t0 * 0x2AAA
"addiu %[src_ptr], %[src_ptr], 8 \n"
"addiu %[t], %[t], 8 \n"
"addiu %[dst_width], %[dst_width], -3 \n"
"addiu %[dst_ptr], %[dst_ptr], 3 \n"
"srl $t6, $t6, 16 \n"
"srl $t0, $t0, 16 \n"
"sb $t4, -1(%[dst_ptr]) \n"
"sb $t6, -2(%[dst_ptr]) \n"
"bgtz %[dst_width], 1b \n"
" sb $t0, -3(%[dst_ptr]) \n"
".set pop \n"
: [src_ptr] "+r"(src_ptr), [dst_ptr] "+r"(dst_ptr), [t] "+r"(t),
[dst_width] "+r"(dst_width)
: [c] "r"(c)
: "t0", "t1", "t2", "t3", "t4", "t5", "t6");
}
void ScaleRowDown38_3_Box_DSPR2(const uint8* src_ptr,
ptrdiff_t src_stride,
uint8* dst_ptr,
int dst_width) {
intptr_t stride = src_stride;
const uint8* s1 = src_ptr + stride;
stride += stride;
const uint8* s2 = src_ptr + stride;
const int c1 = 0x1C71;
const int c2 = 0x2AAA;
__asm__ __volatile__(
".set push \n"
".set noreorder \n"
"1: \n"
"lw $t0, 0(%[src_ptr]) \n" // |S3|S2|S1|S0|
"lw $t1, 4(%[src_ptr]) \n" // |S7|S6|S5|S4|
"lw $t2, 0(%[s1]) \n" // |T3|T2|T1|T0|
"lw $t3, 4(%[s1]) \n" // |T7|T6|T5|T4|
"lw $t4, 0(%[s2]) \n" // |R3|R2|R1|R0|
"lw $t5, 4(%[s2]) \n" // |R7|R6|R5|R4|
"rotr $t1, $t1, 16 \n" // |S5|S4|S7|S6|
"packrl.ph $t6, $t1, $t3 \n" // |S7|S6|T7|T6|
"raddu.w.qb $t6, $t6 \n" // S7+S6+T7+T6
"packrl.ph $t7, $t3, $t1 \n" // |T5|T4|S5|S4|
"raddu.w.qb $t7, $t7 \n" // T5+T4+S5+S4
"sll $t8, $t5, 16 \n" // |R5|R4|0|0|
"raddu.w.qb $t8, $t8 \n" // R5+R4
"addu $t7, $t7, $t8 \n"
"srl $t8, $t5, 16 \n" // |0|0|R7|R6|
"raddu.w.qb $t8, $t8 \n" // R7 + R6
"addu $t6, $t6, $t8 \n"
"mul $t6, $t6, %[c2] \n" // t6 * 0x2AAA
"precrq.qb.ph $t8, $t0, $t2 \n" // |S3|S1|T3|T1|
"precrq.qb.ph $t8, $t8, $t4 \n" // |S3|T3|R3|R1|
"srl $t8, $t8, 8 \n" // |0|S3|T3|R3|
"raddu.w.qb $t8, $t8 \n" // S3 + T3 + R3
"addu $t7, $t7, $t8 \n"
"mul $t7, $t7, %[c1] \n" // t7 * 0x1C71
"sll $t0, $t0, 8 \n" // |S2|S1|S0|0|
"sll $t2, $t2, 8 \n" // |T2|T1|T0|0|
"sll $t4, $t4, 8 \n" // |R2|R1|R0|0|
"raddu.w.qb $t0, $t0 \n"
"raddu.w.qb $t2, $t2 \n"
"raddu.w.qb $t4, $t4 \n"
"addu $t0, $t0, $t2 \n"
"addu $t0, $t0, $t4 \n"
"mul $t0, $t0, %[c1] \n" // t0 * 0x1C71
"addiu %[src_ptr], %[src_ptr], 8 \n"
"addiu %[s1], %[s1], 8 \n"
"addiu %[s2], %[s2], 8 \n"
"addiu %[dst_width], %[dst_width], -3 \n"
"addiu %[dst_ptr], %[dst_ptr], 3 \n"
"srl $t6, $t6, 16 \n"
"srl $t7, $t7, 16 \n"
"srl $t0, $t0, 16 \n"
"sb $t6, -1(%[dst_ptr]) \n"
"sb $t7, -2(%[dst_ptr]) \n"
"bgtz %[dst_width], 1b \n"
" sb $t0, -3(%[dst_ptr]) \n"
".set pop \n"
: [src_ptr] "+r"(src_ptr), [dst_ptr] "+r"(dst_ptr), [s1] "+r"(s1),
[s2] "+r"(s2), [dst_width] "+r"(dst_width)
: [c1] "r"(c1), [c2] "r"(c2)
: "t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7", "t8");
}
#endif // defined(__mips_dsp) && (__mips_dsp_rev >= 2)
#ifdef __cplusplus
} // extern "C"
} // namespace libyuv
#endif
| 34,615 | 14,162 |
// Copyright (c) 2015-2018 Daniel Cooke
// Use of this source code is governed by the MIT license that can be found in the LICENSE file.
#ifndef indel_mutation_model_hpp
#define indel_mutation_model_hpp
#include <vector>
#include <cstdint>
#include "core/types/haplotype.hpp"
#include "core/types/variant.hpp"
namespace octopus {
class IndelMutationModel
{
public:
struct Parameters
{
double indel_mutation_rate;
unsigned max_period = 10, max_periodicity = 20;
double max_open_probability = 1.0, max_extend_probability = 1.0;
};
struct ContextIndelModel
{
using Probability = double;
using ProbabilityVector = std::vector<Probability>;
ProbabilityVector gap_open, gap_extend;
};
IndelMutationModel() = delete;
IndelMutationModel(Parameters params);
IndelMutationModel(const IndelMutationModel&) = default;
IndelMutationModel& operator=(const IndelMutationModel&) = default;
IndelMutationModel(IndelMutationModel&&) = default;
IndelMutationModel& operator=(IndelMutationModel&&) = default;
~IndelMutationModel() = default;
ContextIndelModel evaluate(const Haplotype& haplotype) const;
private:
struct ModelCell { double open, extend; };
using RepeatModel = std::vector<std::vector<ModelCell>>;
Parameters params_;
RepeatModel indel_repeat_model_;
};
IndelMutationModel::ContextIndelModel make_indel_model(const Haplotype& context, IndelMutationModel::Parameters params);
} // namespace octopus
#endif
| 1,600 | 524 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "media/filters/audio_file_reader.h"
#include <stddef.h>
#include <cmath>
#include <vector>
#include "base/bind.h"
#include "base/callback.h"
#include "base/logging.h"
#include "base/numerics/safe_math.h"
#include "base/time/time.h"
#include "media/base/audio_bus.h"
#include "media/base/audio_sample_types.h"
#include "media/ffmpeg/ffmpeg_common.h"
#include "media/ffmpeg/ffmpeg_decoding_loop.h"
namespace media {
// AAC(M4A) decoding specific constants.
static const int kAACPrimingFrameCount = 2112;
static const int kAACRemainderFrameCount = 519;
AudioFileReader::AudioFileReader(FFmpegURLProtocol* protocol)
: stream_index_(0),
protocol_(protocol),
audio_codec_(kUnknownAudioCodec),
channels_(0),
sample_rate_(0),
av_sample_format_(0) {}
AudioFileReader::~AudioFileReader() {
Close();
}
bool AudioFileReader::Open() {
return OpenDemuxer() && OpenDecoder();
}
bool AudioFileReader::OpenDemuxer() {
glue_.reset(new FFmpegGlue(protocol_));
AVFormatContext* format_context = glue_->format_context();
// Open FFmpeg AVFormatContext.
if (!glue_->OpenContext()) {
DLOG(WARNING) << "AudioFileReader::Open() : error in avformat_open_input()";
return false;
}
const int result = avformat_find_stream_info(format_context, NULL);
if (result < 0) {
DLOG(WARNING)
<< "AudioFileReader::Open() : error in avformat_find_stream_info()";
return false;
}
// Calling avformat_find_stream_info can uncover new streams. We wait till now
// to find the first audio stream, if any.
codec_context_.reset();
bool found_stream = false;
for (size_t i = 0; i < format_context->nb_streams; ++i) {
if (format_context->streams[i]->codecpar->codec_type ==
AVMEDIA_TYPE_AUDIO) {
stream_index_ = i;
found_stream = true;
break;
}
}
if (!found_stream)
return false;
// Get the codec context.
codec_context_ =
AVStreamToAVCodecContext(format_context->streams[stream_index_]);
if (!codec_context_)
return false;
DCHECK_EQ(codec_context_->codec_type, AVMEDIA_TYPE_AUDIO);
return true;
}
bool AudioFileReader::OpenDecoder() {
AVCodec* codec = avcodec_find_decoder(codec_context_->codec_id);
if (codec) {
// MP3 decodes to S16P which we don't support, tell it to use S16 instead.
if (codec_context_->sample_fmt == AV_SAMPLE_FMT_S16P)
codec_context_->request_sample_fmt = AV_SAMPLE_FMT_S16;
const int result = avcodec_open2(codec_context_.get(), codec, nullptr);
if (result < 0) {
DLOG(WARNING) << "AudioFileReader::Open() : could not open codec -"
<< " result: " << result;
return false;
}
// Ensure avcodec_open2() respected our format request.
if (codec_context_->sample_fmt == AV_SAMPLE_FMT_S16P) {
DLOG(ERROR) << "AudioFileReader::Open() : unable to configure a"
<< " supported sample format - "
<< codec_context_->sample_fmt;
return false;
}
} else {
DLOG(WARNING) << "AudioFileReader::Open() : could not find codec.";
return false;
}
// Verify the channel layout is supported by Chrome. Acts as a sanity check
// against invalid files. See http://crbug.com/171962
if (ChannelLayoutToChromeChannelLayout(codec_context_->channel_layout,
codec_context_->channels) ==
CHANNEL_LAYOUT_UNSUPPORTED) {
return false;
}
// Store initial values to guard against midstream configuration changes.
channels_ = codec_context_->channels;
audio_codec_ = CodecIDToAudioCodec(codec_context_->codec_id);
sample_rate_ = codec_context_->sample_rate;
av_sample_format_ = codec_context_->sample_fmt;
return true;
}
bool AudioFileReader::HasKnownDuration() const {
return glue_->format_context()->duration != AV_NOPTS_VALUE;
}
void AudioFileReader::Close() {
codec_context_.reset();
glue_.reset();
}
int AudioFileReader::Read(
std::vector<std::unique_ptr<AudioBus>>* decoded_audio_packets,
int packets_to_read) {
DCHECK(glue_ && codec_context_)
<< "AudioFileReader::Read() : reader is not opened!";
FFmpegDecodingLoop decode_loop(codec_context_.get());
int total_frames = 0;
auto frame_ready_cb =
base::BindRepeating(&AudioFileReader::OnNewFrame, base::Unretained(this),
&total_frames, decoded_audio_packets);
AVPacket packet;
int packets_read = 0;
while (packets_read++ < packets_to_read && ReadPacket(&packet)) {
const auto status = decode_loop.DecodePacket(&packet, frame_ready_cb);
av_packet_unref(&packet);
if (status != FFmpegDecodingLoop::DecodeStatus::kOkay)
break;
}
return total_frames;
}
base::TimeDelta AudioFileReader::GetDuration() const {
const AVRational av_time_base = {1, AV_TIME_BASE};
DCHECK_NE(glue_->format_context()->duration, AV_NOPTS_VALUE);
base::CheckedNumeric<int64_t> estimated_duration_us =
glue_->format_context()->duration;
if (audio_codec_ == kCodecAAC) {
// For certain AAC-encoded files, FFMPEG's estimated frame count might not
// be sufficient to capture the entire audio content that we want. This is
// especially noticeable for short files (< 10ms) resulting in silence
// throughout the decoded buffer. Thus we add the priming frames and the
// remainder frames to the estimation.
// (See: crbug.com/513178)
estimated_duration_us += ceil(
1000000.0 *
static_cast<double>(kAACPrimingFrameCount + kAACRemainderFrameCount) /
sample_rate());
} else {
// Add one microsecond to avoid rounding-down errors which can occur when
// |duration| has been calculated from an exact number of sample-frames.
// One microsecond is much less than the time of a single sample-frame
// at any real-world sample-rate.
estimated_duration_us += 1;
}
return ConvertFromTimeBase(av_time_base, estimated_duration_us.ValueOrDie());
}
int AudioFileReader::GetNumberOfFrames() const {
return base::ClampCeil(GetDuration().InSecondsF() * sample_rate());
}
bool AudioFileReader::OpenDemuxerForTesting() {
return OpenDemuxer();
}
bool AudioFileReader::ReadPacketForTesting(AVPacket* output_packet) {
return ReadPacket(output_packet);
}
bool AudioFileReader::ReadPacket(AVPacket* output_packet) {
while (av_read_frame(glue_->format_context(), output_packet) >= 0) {
// Skip packets from other streams.
if (output_packet->stream_index != stream_index_) {
av_packet_unref(output_packet);
continue;
}
return true;
}
return false;
}
bool AudioFileReader::OnNewFrame(
int* total_frames,
std::vector<std::unique_ptr<AudioBus>>* decoded_audio_packets,
AVFrame* frame) {
int frames_read = frame->nb_samples;
if (frames_read < 0)
return false;
const int channels = frame->channels;
if (frame->sample_rate != sample_rate_ || channels != channels_ ||
frame->format != av_sample_format_) {
DLOG(ERROR) << "Unsupported midstream configuration change!"
<< " Sample Rate: " << frame->sample_rate << " vs "
<< sample_rate_ << ", Channels: " << channels << " vs "
<< channels_ << ", Sample Format: " << frame->format << " vs "
<< av_sample_format_;
// This is an unrecoverable error, so bail out. We'll return
// whatever we've decoded up to this point.
return false;
}
// AAC decoding doesn't properly trim the last packet in a stream, so if we
// have duration information, use it to set the correct length to avoid extra
// silence from being output. In the case where we are also discarding some
// portion of the packet (as indicated by a negative pts), we further want to
// adjust the duration downward by however much exists before zero.
if (audio_codec_ == kCodecAAC && frame->pkt_duration) {
const base::TimeDelta pkt_duration = ConvertFromTimeBase(
glue_->format_context()->streams[stream_index_]->time_base,
frame->pkt_duration + std::min(static_cast<int64_t>(0), frame->pts));
const base::TimeDelta frame_duration = base::TimeDelta::FromSecondsD(
frames_read / static_cast<double>(sample_rate_));
if (pkt_duration < frame_duration && pkt_duration > base::TimeDelta()) {
const int new_frames_read =
base::ClampFloor(frames_read * (pkt_duration / frame_duration));
DVLOG(2) << "Shrinking AAC frame from " << frames_read << " to "
<< new_frames_read << " based on packet duration.";
frames_read = new_frames_read;
// The above process may delete the entire packet.
if (!frames_read)
return true;
}
}
// Deinterleave each channel and convert to 32bit floating-point with
// nominal range -1.0 -> +1.0. If the output is already in float planar
// format, just copy it into the AudioBus.
decoded_audio_packets->emplace_back(AudioBus::Create(channels, frames_read));
AudioBus* audio_bus = decoded_audio_packets->back().get();
if (codec_context_->sample_fmt == AV_SAMPLE_FMT_FLT) {
audio_bus->FromInterleaved<Float32SampleTypeTraits>(
reinterpret_cast<float*>(frame->data[0]), frames_read);
} else if (codec_context_->sample_fmt == AV_SAMPLE_FMT_FLTP) {
for (int ch = 0; ch < audio_bus->channels(); ++ch) {
memcpy(audio_bus->channel(ch), frame->extended_data[ch],
sizeof(float) * frames_read);
}
} else {
audio_bus->FromInterleaved(
frame->data[0], frames_read,
av_get_bytes_per_sample(codec_context_->sample_fmt));
}
(*total_frames) += frames_read;
return true;
}
bool AudioFileReader::SeekForTesting(base::TimeDelta seek_time) {
// Use the AVStream's time_base, since |codec_context_| does not have
// time_base populated until after OpenDecoder().
return av_seek_frame(
glue_->format_context(), stream_index_,
ConvertToTimeBase(GetAVStreamForTesting()->time_base, seek_time),
AVSEEK_FLAG_BACKWARD) >= 0;
}
const AVStream* AudioFileReader::GetAVStreamForTesting() const {
return glue_->format_context()->streams[stream_index_];
}
} // namespace media
| 10,357 | 3,439 |
#include <mainwindow.h>
#include <QApplication>
#include <cstring>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
bool debug = argc > 1 && strcmp(argv[1], "-d") == 0;
MainWindow w(debug);
w.show();
return a.exec();
}
| 261 | 103 |
#include "Fraction.h"
#include <sstream>
Fraction::Fraction()
{
m_nom = new int(0);
m_denom = new int(1);
}
Fraction::Fraction(int value) {
m_nom = new int(value);
m_denom = new int(1);
}
Fraction::Fraction(int nom, int denom)
{
m_nom = new int(nom);
m_denom = new int(denom);
makeDenominatorPositive();
}
Fraction::Fraction(const Fraction& f)
{
m_nom = new int(*f.m_nom);
m_denom = new int(*f.m_denom);
}
Fraction::~Fraction()
{
delete m_nom;
delete m_denom;
}
void Fraction::makeDenominatorPositive()
{
if (*m_denom < 0) {
*m_nom = -*m_nom;
*m_denom = -*m_denom;
}
}
int Fraction::getNom() const
{
return *m_nom;
}
int Fraction::getDenom() const
{
return *m_denom;
}
void Fraction::setNom(int nom)
{
*m_nom = nom;
}
bool Fraction::setDenom(int denom)
{
if (denom == 0)
return false;
*m_denom = denom;
makeDenominatorPositive();
return true;
}
std::string Fraction::ToString() const
{
std::stringstream ss;
ss << *m_nom << '/' << *m_denom;
return ss.str();
}
| 1,088 | 460 |
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <utility>
#include "absl/algorithm/container.h"
#include "tensorflow/compiler/xla/literal_util.h"
#include "tensorflow/compiler/xla/service/gather_expander.h"
#include "tensorflow/compiler/xla/service/hlo_creation_utils.h"
#include "tensorflow/compiler/xla/service/hlo_instruction.h"
#include "tensorflow/compiler/xla/service/while_util.h"
#include "tensorflow/compiler/xla/statusor.h"
#include "tensorflow/compiler/xla/util.h"
namespace xla {
static StatusOr<HloInstruction*> TransposeIndexVectorDimToLast(
HloInstruction* start_indices, int64 index_vector_dim) {
const Shape& start_indices_shape = start_indices->shape();
if (start_indices_shape.dimensions_size() == index_vector_dim) {
return start_indices;
}
if (index_vector_dim == (start_indices_shape.dimensions_size() - 1)) {
return start_indices;
}
std::vector<int64> permutation;
permutation.reserve(start_indices_shape.dimensions_size());
for (int64 i = 0, e = start_indices_shape.dimensions_size(); i < e; i++) {
if (i != index_vector_dim) {
permutation.push_back(i);
}
}
permutation.push_back(index_vector_dim);
return MakeTransposeHlo(start_indices, permutation);
}
// Canonicalizes the start_indices tensors so that we only have deal with some
// specific cases in the while loop that does the heavy lifting.
//
// See the "High Level Algorithm" section for a broader picture.
static StatusOr<HloInstruction*> CanonicalizeGatherIndices(
HloInstruction* start_indices, int64 index_vector_dim) {
// Transpose the non-index-vector dimensions to the front.
TF_ASSIGN_OR_RETURN(
HloInstruction * transposed_start_indices,
TransposeIndexVectorDimToLast(start_indices, index_vector_dim));
bool indices_are_scalar =
index_vector_dim == start_indices->shape().dimensions_size();
// The number of dimensions in start_indices that are index dimensions.
const int64 index_dims_in_start_indices = indices_are_scalar ? 0 : 1;
// If there is only one index (i.e. start_indices has rank 1 and this gather
// is really just a dynamic slice) add a leading degenerate dimension for
// uniformity. Otherwise create a "collapsed" leading dimension that subsumes
// all of the non-index-vector dimensions.
const Shape& shape = transposed_start_indices->shape();
if (shape.dimensions_size() == index_dims_in_start_indices) {
return PrependDegenerateDims(transposed_start_indices, 1);
} else {
// Collapse all but the dimensions (0 or 1) in start_indices containing the
// index vectors.
return CollapseFirstNDims(
transposed_start_indices,
shape.dimensions_size() - index_dims_in_start_indices);
}
}
// Expands out or contracts away the gather dimensions in the accumulator
// produced by the while loop.
static StatusOr<HloInstruction*> AdjustBatchDimsInAccumulator(
const Shape& start_indices_shape, HloInstruction* accumulator,
int64 index_vector_dim) {
std::vector<int64> batch_dim_bounds;
batch_dim_bounds.reserve(start_indices_shape.dimensions_size());
for (int64 i = 0, e = start_indices_shape.dimensions_size(); i < e; i++) {
if (i != index_vector_dim) {
batch_dim_bounds.push_back(start_indices_shape.dimensions(i));
}
}
if (batch_dim_bounds.empty()) {
// If batch_dim_bounds is empty we must be lowering a (effectively)
// dynamic-slice. In that case, there is a leading degenerate gather
// dimension that we added to make this special case play well with the
// general while loop which we need to remove now.
return ElideDegenerateDims(accumulator, {0});
}
return ExpandFirstDimIntoNDims(accumulator, batch_dim_bounds);
}
// Expand an index vector from the start_indices tensor into a vector that can
// be used to dynamic-slice out of the gather operand.
static StatusOr<HloInstruction*> ExpandIndexVectorIntoOperandSpace(
HloInstruction* index_vector, const GatherDimensionNumbers& dim_numbers,
int64 operand_rank) {
HloComputation* computation = index_vector->parent();
const Shape& index_shape = index_vector->shape();
HloInstruction* zero =
computation->AddInstruction(HloInstruction::CreateConstant(
LiteralUtil::CreateFromDimensions(index_shape.element_type(), {1})));
// We extract out individual components from the smaller index and concatenate
// them (interspersing zeros as needed) into the larger index.
std::vector<HloInstruction*> expanded_index_components;
for (int i = 0; i < operand_rank; i++) {
int64 index_vector_dim_index = FindIndex(dim_numbers.start_index_map(), i);
if (index_vector_dim_index != dim_numbers.start_index_map_size()) {
TF_ASSIGN_OR_RETURN(
HloInstruction * component_to_concat,
MakeSliceHlo(index_vector, /*start_indices=*/{index_vector_dim_index},
/*limit_indices=*/{index_vector_dim_index + 1},
/*strides=*/{1}));
expanded_index_components.push_back(component_to_concat);
} else {
expanded_index_components.push_back(zero);
}
}
return MakeConcatHlo(expanded_index_components, /*dimension=*/0);
}
// This generates the body of the while that implements the main data movement
// behavior of gather using dynamic-slice and dynamic-update-slice.
static StatusOr<std::vector<HloInstruction*>> GatherLoopBody(
const HloInstruction& gather, HloInstruction* induction_var,
const std::vector<HloInstruction*>& incoming_loop_state) {
const GatherDimensionNumbers& dim_numbers = gather.gather_dimension_numbers();
CHECK_EQ(incoming_loop_state.size(), 3);
HloInstruction* const operand = incoming_loop_state[0];
HloInstruction* const start_indices = incoming_loop_state[1];
HloInstruction* const output_accumulator = incoming_loop_state[2];
bool has_scalar_indices = start_indices->shape().dimensions_size() == 1;
CHECK_EQ(has_scalar_indices,
dim_numbers.index_vector_dim() ==
gather.operand(1)->shape().dimensions_size());
TF_ASSIGN_OR_RETURN(
HloInstruction * induction_var_as_vector,
MakeBroadcastHlo(induction_var, /*broadcast_dimensions=*/{},
/*result_shape_bounds=*/{1}));
HloInstruction* index_vector;
if (has_scalar_indices) {
// In this case start_indices has rank 1 and induction_var_as_vector (of
// shape {1}) is an index into this rank 1 tensor.
TF_ASSIGN_OR_RETURN(
index_vector,
MakeDynamicSliceHlo(start_indices, induction_var_as_vector, {1}));
} else {
// In this case start_indices has rank 2 and induction_var_as_vector (of
// shape {1}) is an index into just the first dimension of this rank 2
// tensor.
TF_ASSIGN_OR_RETURN(
HloInstruction * index_into_start_indices,
PadVectorWithZeros(induction_var_as_vector,
/*zeros_to_prepend=*/0, /*zeros_to_append=*/1));
int64 index_vector_size = start_indices->shape().dimensions(1);
TF_ASSIGN_OR_RETURN(
HloInstruction * index_vector_2d,
MakeDynamicSliceHlo(start_indices, index_into_start_indices,
{1, index_vector_size}));
TF_ASSIGN_OR_RETURN(index_vector,
ElideDegenerateDims(index_vector_2d, {0}));
}
TF_ASSIGN_OR_RETURN(
HloInstruction * gathered_slice_start,
ExpandIndexVectorIntoOperandSpace(index_vector, dim_numbers,
operand->shape().dimensions_size()));
TF_ASSIGN_OR_RETURN(HloInstruction * gathered_slice,
MakeDynamicSliceHlo(operand, gathered_slice_start,
gather.gather_slice_sizes()));
TF_ASSIGN_OR_RETURN(
HloInstruction* const gathered_slice_with_dims_collapsed,
ElideDegenerateDims(gathered_slice,
AsInt64Slice(dim_numbers.collapsed_slice_dims())));
TF_ASSIGN_OR_RETURN(
HloInstruction* const gathered_slice_for_update,
PrependDegenerateDims(gathered_slice_with_dims_collapsed, 1));
TF_ASSIGN_OR_RETURN(
HloInstruction* const index_vector_into_accumulator,
PadVectorWithZeros(
induction_var_as_vector, /*zeros_to_prepend=*/0,
/*zeros_to_append=*/
gathered_slice_with_dims_collapsed->shape().dimensions_size()));
TF_ASSIGN_OR_RETURN(
HloInstruction* const updated_accumulator,
MakeDynamicUpdateSliceHlo(output_accumulator, gathered_slice_for_update,
index_vector_into_accumulator));
// New loop state -- only the accumulator has changed. The
// WhileUtil::MakeCountedLoop functions takes care of the induction variable
// and the while loop exit condition.
return StatusOr<std::vector<HloInstruction*>>{
{operand, start_indices, updated_accumulator}};
}
static StatusOr<HloInstruction*> CreateGatherLoopAccumulatorInitValue(
HloComputation* computation, PrimitiveType element_type,
absl::Span<const int64> slice_sizes, int64 gather_loop_trip_count,
const GatherDimensionNumbers& dim_numbers) {
std::vector<int64> accumulator_state_shape_dims;
accumulator_state_shape_dims.reserve(1 + slice_sizes.size());
accumulator_state_shape_dims.push_back(gather_loop_trip_count);
for (int64 i = 0; i < slice_sizes.size(); i++) {
if (!absl::c_binary_search(dim_numbers.collapsed_slice_dims(), i)) {
accumulator_state_shape_dims.push_back(slice_sizes[i]);
}
}
return BroadcastZeros(computation, element_type,
accumulator_state_shape_dims);
}
// `accumulator` is almost the tensor the gather operation would have produced,
// except that it has the dimensions in the wrong order -- the batch dimensions
// are the major dimensions and the offset dimensions are the minor dimensions.
// Fix this up with a transpose.
static StatusOr<HloInstruction*> PermuteBatchAndOffsetDims(
HloInstruction* accumulator, absl::Span<const int64> offset_dims,
int64 output_rank) {
std::vector<int64> permutation;
permutation.reserve(output_rank);
int64 batch_idx_counter = 0;
int64 offset_idx_counter = output_rank - offset_dims.size();
for (int64 i = 0; i < output_rank; i++) {
bool is_offset_dim = absl::c_binary_search(offset_dims, i);
if (is_offset_dim) {
permutation.push_back(offset_idx_counter++);
} else {
permutation.push_back(batch_idx_counter++);
}
}
return MakeTransposeHlo(accumulator, permutation);
}
// High Level Algorithm
//
// We follow the following steps in sequence:
//
// 1. We canonicalize the start_indices tensor such that it has rank
// 2 (i.e. is a matrix) where each row is an index vector into the
// operand.
// 2. We iterate over the set of indices in the canonicalized
// start_indices tensor using a while loop, accumulating slices
// of the operand tensor into an accumulator using
// DynamicUpdateSlice.
// 3. The accumulator result from the while loop from (2) is then
// reshaped to split out all the individual gather dimensions and
// then transposed to give the final result.
//
// As an example, if we started with the following operation:
//
// HloModule TensorFlowGatherMultipleBatchDims
//
// ENTRY main {
// operand = s32[3,3] parameter(0)
// indices = s32[2,2] parameter(1)
// ROOT gather = s32[2,3,2] gather(operand, indices),
// offset_dims={1},
// collapsed_slice_dims={1},
// start_index_map={1},
// index_vector_dim=2,
// slice_sizes={3, 1}
// }
//
// We'd first reshape indices to s32[4,1], where each row is an index
// into operand. We'd then run a loop to slice out 4 tensors of shape
// [3,1] out of operand into an accumulator of shape [4,3,1]. We then
// reshape this result to [2,2,3] and finally transpose it to [2,3,2].
StatusOr<HloInstruction*> GatherExpander::ExpandGather(
HloInstruction* gather_instr) {
CHECK(!ShapeUtil::IsZeroElementArray(gather_instr->shape()));
HloComputation* computation = gather_instr->parent();
HloInstruction* operand = gather_instr->mutable_operand(0);
HloInstruction* start_indices = gather_instr->mutable_operand(1);
const Shape& start_indices_shape = start_indices->shape();
const Shape& output_shape = gather_instr->shape();
int64 output_rank = output_shape.dimensions_size();
const GatherDimensionNumbers& dim_numbers =
gather_instr->gather_dimension_numbers();
int64 gather_loop_trip_count = 1;
for (int64 i = 0, e = start_indices_shape.dimensions_size(); i < e; i++) {
if (i != dim_numbers.index_vector_dim()) {
gather_loop_trip_count *= start_indices_shape.dimensions(i);
}
}
if (!IsInt32(gather_loop_trip_count)) {
return Unimplemented(
"Gather operations with more than 2147483647 gather indices are not "
"supported. This error occurred for %s.",
gather_instr->ToString());
}
TF_ASSIGN_OR_RETURN(
HloInstruction * canonical_start_indices,
CanonicalizeGatherIndices(start_indices, dim_numbers.index_vector_dim()));
CHECK_EQ(gather_loop_trip_count,
canonical_start_indices->shape().dimensions(0));
TF_ASSIGN_OR_RETURN(
HloInstruction * accumulator_init,
CreateGatherLoopAccumulatorInitValue(
computation, output_shape.element_type(),
gather_instr->gather_slice_sizes(), gather_loop_trip_count,
gather_instr->gather_dimension_numbers()));
StatusOr<std::vector<HloInstruction*>> gather_loop_result_or_error =
WhileUtil::MakeCountedLoop(
computation, gather_loop_trip_count,
{operand, canonical_start_indices, accumulator_init},
[&](HloInstruction* indvar,
const std::vector<HloInstruction*>& loop_state) {
return GatherLoopBody(*gather_instr, indvar, loop_state);
});
TF_ASSIGN_OR_RETURN(std::vector<HloInstruction*> gather_loop_result,
gather_loop_result_or_error);
HloInstruction* accumulator_result = gather_loop_result.back();
TF_ASSIGN_OR_RETURN(
HloInstruction* const accumulator_with_batch_dims_decanonicalized,
AdjustBatchDimsInAccumulator(start_indices->shape(), accumulator_result,
dim_numbers.index_vector_dim()));
return PermuteBatchAndOffsetDims(accumulator_with_batch_dims_decanonicalized,
AsInt64Slice(dim_numbers.offset_dims()),
output_rank);
}
StatusOr<bool> GatherExpander::Run(HloModule* module) {
auto is_nontrivial_gather = [](HloInstruction* inst) {
return inst->opcode() == HloOpcode::kGather &&
// Avoid expanding gather ops that produce zero sized tensors,
// instead punt these to ZeroSizedHloElimination.
!ShapeUtil::IsZeroElementArray(inst->shape());
};
std::vector<HloInstruction*> gather_instrs;
for (HloComputation* computation : module->MakeNonfusionComputations()) {
absl::c_copy_if(computation->instructions(),
std::back_inserter(gather_instrs), is_nontrivial_gather);
}
for (HloInstruction* inst : gather_instrs) {
TF_ASSIGN_OR_RETURN(HloInstruction * expanded_root, ExpandGather(inst));
TF_RETURN_IF_ERROR(inst->parent()->ReplaceInstruction(inst, expanded_root));
}
return !gather_instrs.empty();
}
} // namespace xla
| 16,042 | 5,226 |
/*
* Copyright (C) 2021 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "shared/source/execution_environment/execution_environment.h"
#include "shared/source/os_interface/linux/local_memory_helper.h"
#include "shared/source/os_interface/linux/memory_info_impl.h"
#include "shared/test/common/helpers/debug_manager_state_restore.h"
#include "shared/test/common/helpers/default_hw_info.h"
#include "opencl/test/unit_test/os_interface/linux/drm_mock_exp.h"
#include "opencl/test/unit_test/os_interface/linux/drm_mock_prod_dg1.h"
#include "test.h"
using namespace NEO;
using LocalMemoryHelperTestsDg1 = ::testing::Test;
DG1TEST_F(LocalMemoryHelperTestsDg1, givenDg1WhenCreateGemExtThenReturnCorrectValue) {
auto executionEnvironment = std::make_unique<ExecutionEnvironment>();
executionEnvironment->prepareRootDeviceEnvironments(1);
auto drm = std::make_unique<DrmMockExp>(*executionEnvironment->rootDeviceEnvironments[0]);
drm_i915_memory_region_info regionInfo[2] = {};
regionInfo[0].region = {I915_MEMORY_CLASS_SYSTEM, 0};
regionInfo[0].probed_size = 8 * GB;
regionInfo[1].region = {I915_MEMORY_CLASS_DEVICE, 0};
regionInfo[1].probed_size = 16 * GB;
auto localMemHelper = LocalMemoryHelper::get(defaultHwInfo->platform.eProductFamily);
uint32_t handle = 0;
auto ret = localMemHelper->createGemExt(drm.get(), ®ionInfo[1], 1, 1024, handle);
EXPECT_EQ(0u, ret);
EXPECT_EQ(1u, handle);
EXPECT_EQ(1u, drm->numRegions);
EXPECT_EQ(1024u, drm->createExt.size);
EXPECT_EQ(I915_MEMORY_CLASS_DEVICE, drm->memRegions.memory_class);
}
DG1TEST_F(LocalMemoryHelperTestsDg1, givenDg1WithDrmTipWhenCreateGemExtWithDebugFlagThenPrintDebugInfo) {
DebugManagerStateRestore stateRestore;
DebugManager.flags.PrintBOCreateDestroyResult.set(true);
auto executionEnvironment = std::make_unique<ExecutionEnvironment>();
executionEnvironment->prepareRootDeviceEnvironments(1);
auto drm = std::make_unique<DrmMockExp>(*executionEnvironment->rootDeviceEnvironments[0]);
drm_i915_memory_region_info regionInfo[2] = {};
regionInfo[0].region = {I915_MEMORY_CLASS_SYSTEM, 0};
regionInfo[1].region = {I915_MEMORY_CLASS_DEVICE, 0};
testing::internal::CaptureStdout();
auto localMemHelper = LocalMemoryHelper::get(defaultHwInfo->platform.eProductFamily);
uint32_t handle = 0;
auto ret = localMemHelper->createGemExt(drm.get(), ®ionInfo[1], 1, 1024, handle);
std::string output = testing::internal::GetCapturedStdout();
std::string expectedOutput("Performing GEM_CREATE_EXT with { size: 1024, memory class: 1, memory instance: 0 }\nGEM_CREATE_EXT with EXT_MEMORY_REGIONS has returned: 0 BO-1 with size: 1024\n");
EXPECT_EQ(expectedOutput, output);
EXPECT_EQ(1u, drm->ioctlCallsCount);
EXPECT_EQ(0u, ret);
}
DG1TEST_F(LocalMemoryHelperTestsDg1, givenDg1WhenCreateGemExtWithDebugFlagThenPrintDebugInfo) {
DebugManagerStateRestore stateRestore;
DebugManager.flags.PrintBOCreateDestroyResult.set(true);
auto executionEnvironment = std::make_unique<ExecutionEnvironment>();
executionEnvironment->prepareRootDeviceEnvironments(1);
auto drm = std::make_unique<DrmMockProdDg1>(*executionEnvironment->rootDeviceEnvironments[0]);
drm_i915_memory_region_info regionInfo[2] = {};
regionInfo[0].region = {I915_MEMORY_CLASS_SYSTEM, 0};
regionInfo[1].region = {I915_MEMORY_CLASS_DEVICE, 0};
testing::internal::CaptureStdout();
auto localMemHelper = LocalMemoryHelper::get(defaultHwInfo->platform.eProductFamily);
uint32_t handle = 0;
auto ret = localMemHelper->createGemExt(drm.get(), ®ionInfo[1], 1, 1024, handle);
std::string output = testing::internal::GetCapturedStdout();
std::string expectedOutput("Performing GEM_CREATE_EXT with { size: 1024, memory class: 1, memory instance: 0 }\nGEM_CREATE_EXT with EXT_SETPARAM has returned: 0 BO-1 with size: 1024\n");
EXPECT_EQ(expectedOutput, output);
EXPECT_EQ(2u, drm->ioctlCallsCount);
EXPECT_EQ(0u, ret);
}
DG1TEST_F(LocalMemoryHelperTestsDg1, givenDg1AndMemoryRegionQuerySupportedWhenQueryingMemoryInfoThenMemoryInfoIsCreatedWithRegions) {
auto executionEnvironment = std::make_unique<ExecutionEnvironment>();
executionEnvironment->prepareRootDeviceEnvironments(1);
auto drm = std::make_unique<DrmMockProdDg1>(*executionEnvironment->rootDeviceEnvironments[0]);
ASSERT_NE(nullptr, drm);
drm->queryMemoryInfo();
EXPECT_EQ(2u, drm->ioctlCallsCount);
auto memoryInfo = static_cast<MemoryInfoImpl *>(drm->getMemoryInfo());
ASSERT_NE(nullptr, memoryInfo);
EXPECT_EQ(2u, memoryInfo->getDrmRegionInfos().size());
}
| 4,696 | 1,697 |
#include "StdAfx.h"
class ManagedFileInterface : public Rocket::Core::FileInterface
{
public:
typedef size_t (*OpenCb)(String path HANDLE_ARG);
typedef void(*CloseCb)(Rocket::Core::FileHandle file HANDLE_ARG);
typedef size_t(*ReadCb)(void* buffer, size_t size, Rocket::Core::FileHandle file HANDLE_ARG);
typedef bool(*SeekCb)(Rocket::Core::FileHandle file, long offset, int origin HANDLE_ARG);
typedef size_t(*TellCb)(Rocket::Core::FileHandle file HANDLE_ARG);
typedef void (*ReleaseCb)(HANDLE_FIRST_ARG);
ManagedFileInterface(OpenCb open, CloseCb close, ReadCb read, SeekCb seek, TellCb tell, ReleaseCb release HANDLE_ARG)
:open(open),
close(close),
read(read),
seek(seek),
tell(tell),
release(release)
ASSIGN_HANDLE_INITIALIZER
{
}
virtual ~ManagedFileInterface()
{
}
virtual Rocket::Core::FileHandle Open(const Rocket::Core::String& path)
{
return open(path.CString() PASS_HANDLE_ARG);
}
virtual void Close(Rocket::Core::FileHandle file)
{
close(file PASS_HANDLE_ARG);
}
virtual size_t Read(void* buffer, size_t size, Rocket::Core::FileHandle file)
{
return read(buffer, size, file PASS_HANDLE_ARG);
}
virtual bool Seek(Rocket::Core::FileHandle file, long offset, int origin)
{
return seek(file, offset, origin PASS_HANDLE_ARG);
}
virtual size_t Tell(Rocket::Core::FileHandle file)
{
return tell(file PASS_HANDLE_ARG);
}
virtual void Release()
{
release(PASS_HANDLE);
}
private:
OpenCb open;
CloseCb close;
ReadCb read;
SeekCb seek;
TellCb tell;
ReleaseCb release;
HANDLE_INSTANCE
};
extern "C" _AnomalousExport ManagedFileInterface* ManagedFileInterface_Create(ManagedFileInterface::OpenCb open, ManagedFileInterface::CloseCb close, ManagedFileInterface::ReadCb read, ManagedFileInterface::SeekCb seek, ManagedFileInterface::TellCb tell, ManagedFileInterface::ReleaseCb release HANDLE_ARG)
{
return new ManagedFileInterface(open, close, read, seek, tell, release PASS_HANDLE_ARG);
}
extern "C" _AnomalousExport void ManagedFileInterface_Delete(ManagedFileInterface* fileInterface)
{
delete fileInterface;
} | 2,166 | 831 |
/*
Name: K32_load
Copyright: Copyright (C) SIL International.
Documentation:
Description:
Create Date: 14 Sep 2006
Modified Date: 25 Oct 2016
Authors: mcdurdin
Related Files:
Dependencies:
Bugs:
Todo:
Notes:
History: 14 Sep 2006 - mcdurdin - Support unencrypted keyboards for any internal Keyman product
19 Jun 2007 - mcdurdin - Load ICO files and convert to BMP (for TIP)
11 Mar 2009 - mcdurdin - I1894 - Fix threading bugs introduced in I1888
11 Dec 2009 - mcdurdin - I934 - x64 - Initial version
12 Mar 2010 - mcdurdin - I934 - x64 - Complete
12 Mar 2010 - mcdurdin - I2229 - Remove hints and warnings
04 May 2010 - mcdurdin - I2351 - Robustness - verify _td return value
25 May 2010 - mcdurdin - I1632 - Keyboard Options
02 Dec 2011 - mcdurdin - I3160 - Hotkeys can fail to activate keyboards when multiple OEM products are running
04 Nov 2012 - mcdurdin - I3522 - V9.0 - Merge of I3160 - Hotkeys can fail to activate keyboards when multiple OEM products are running
16 Apr 2014 - mcdurdin - I4169 - V9.0 - Mnemonic layouts should be recompiled to positional based on user-selected base keyboard
06 Feb 2015 - mcdurdin - I4552 - V9.0 - Add mnemonic recompile option to ignore deadkeys
25 Oct 2016 - mcdurdin - I5136 - Remove additional product references from Keyman Engine
*/
#include "pch.h"
HBITMAP LoadBitmapFile(LPBYTE data, DWORD sz);
BOOL VerifyKeyboard(LPBYTE filebase, DWORD sz);
#ifdef _WIN64
LPKEYBOARD CopyKeyboard(PBYTE bufp, PBYTE base, DWORD dwFileSize);
#else
LPKEYBOARD FixupKeyboard(PBYTE bufp, PBYTE base, DWORD dwFileSize);
#endif
HBITMAP LoadBitmapFileEx(PBYTE filebase);
BOOL GetKeyboardFileName(LPSTR kbname, LPSTR buf, int nbuf)
{
PKEYMAN64THREADDATA _td = ThreadGlobals();
if(!_td) return FALSE;
if(_td->ForceFileName[0])
{
strncpy_s(buf, nbuf, _td->ForceFileName, nbuf);
buf[nbuf-1] = 0;
return TRUE;
}
int n = 0;
RegistryReadOnly *reg = Reg_GetKeymanInstalledKeyboard(kbname);
if(!reg) return FALSE;
__try
{
// We need to test if the user is in deadkey conversion mode // I4552
if(Globals::get_MnemonicDeadkeyConversionMode() && reg->ValueExists(REGSZ_KeymanFile_MnemonicOverride_Deadkey)) {
n = reg->ReadString(REGSZ_KeymanFile_MnemonicOverride_Deadkey, buf, nbuf);
}
else if(reg->ValueExists(REGSZ_KeymanFile_MnemonicOverride)) { // I4169
n = reg->ReadString(REGSZ_KeymanFile_MnemonicOverride, buf, nbuf);
} else {
n = reg->ReadString(REGSZ_KeymanFile, buf, nbuf);
}
}
__finally
{
delete reg;
}
return n;
}
BOOL LoadlpKeyboard(int i)
{
PKEYMAN64THREADDATA _td = ThreadGlobals();
if(!_td) return FALSE;
if(_td->lpKeyboards[i].Keyboard) return TRUE;
if(_td->lpActiveKeyboard == &_td->lpKeyboards[i]) _td->lpActiveKeyboard = NULL; // I822 TSF not working
char buf[256];
if(!GetKeyboardFileName(_td->lpKeyboards[i].Name, buf, 256)) return FALSE;
if(!LoadKeyboard(buf, &_td->lpKeyboards[i].Keyboard)) return FALSE; // I5136
LoadDLLs(&_td->lpKeyboards[i]);
LoadKeyboardOptions(&_td->lpKeyboards[i]);
return TRUE;
}
/*
* Instead of performing a straightforward calculation of the 32 bit
* CRC using a series of logical operations, this program uses the
* faster table lookup method. This routine is called once when the
* program starts up to build the table which will be used later
* when calculating the CRC values.
*/
#define CRC32_POLYNOMIAL 0xEDB88320L
unsigned long CRCTable[256];
void BuildCRCTable(void)
{
static BOOL TableBuilt = FALSE;
int i;
int j;
unsigned long crc;
if(!TableBuilt)
{
for(i = 0; i <= 255; i++)
{
crc = i;
for(j = 8; j > 0; j--)
if(crc & 1) crc = (crc >> 1) ^ CRC32_POLYNOMIAL; else crc >>= 1;
CRCTable[i] = crc;
}
}
}
/*
* This routine calculates the CRC for a block of data using the
* table lookup method. It accepts an original value for the crc,
* and returns the updated value.
*/
unsigned long CalculateBufferCRC(unsigned long count, BYTE *p)
{
unsigned long temp1;
unsigned long temp2;
unsigned long crc = 0xFFFFFFFFL;
BuildCRCTable();
while (count-- != 0)
{
temp1 = ( crc >> 8 ) & 0x00FFFFFFL;
temp2 = CRCTable[((int) crc ^ *p++) & 0xff];
crc = temp1 ^ temp2;
}
return crc;
}
//#define Err(s)
void Err(char *s)
{
SendDebugMessageFormat(0, sdmLoad, 0, "LoadKeyboard: %s", s);
}
BOOL LoadKeyboard(LPSTR fileName, LPKEYBOARD *lpKeyboard)
{
DWORD sz;
LPBYTE buf;
HANDLE hFile;
LPKEYBOARD kbp;
PBYTE filebase;
if(!fileName || !lpKeyboard)
{
Err("Bad Filename");
return FALSE;
}
hFile = CreateFile(fileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
if(hFile == INVALID_HANDLE_VALUE)
{
Err("Could not open file");
return FALSE;
}
sz = GetFileSize(hFile, NULL);
#ifdef _WIN64
buf = new BYTE[sz*3];
#else
buf = new BYTE[sz];
#endif
if(!buf)
{
CloseHandle(hFile);
Err("Not allocmem");
return FALSE;
}
#ifdef _WIN64
filebase = buf + sz*2;
#else
filebase = buf;
#endif
ReadFile(hFile, filebase, sz, &sz, NULL);
CloseHandle(hFile);
PKEYMAN64THREADDATA _td = ThreadGlobals();
if(!_td) return FALSE;
if(*LPDWORD(filebase) != FILEID_COMPILED)
{
delete buf;
Err("Invalid file");
return FALSE;
}
if(!VerifyKeyboard(filebase, sz)) return FALSE;
#ifdef _WIN64
kbp = CopyKeyboard(buf, filebase, sz);
#else
kbp = FixupKeyboard(buf, filebase, sz);
#endif
if(!kbp) return FALSE;
if(kbp->dwIdentifier != FILEID_COMPILED) { delete buf; Err("errNotFileID"); return FALSE; }
kbp->hBitmap = LoadBitmapFileEx(filebase);
*lpKeyboard = kbp;
return TRUE;
}
// These next two structs represent how the icon information is stored
// in an ICO file.
typedef struct
{
BYTE bWidth; // Width of the image
BYTE bHeight; // Height of the image (times 2)
BYTE bColorCount; // Number of colors in image (0 if >=8bpp)
BYTE bReserved; // Reserved
WORD wPlanes; // Color Planes
WORD wBitCount; // Bits per pixel
DWORD dwBytesInRes; // how many bytes in this resource?
DWORD dwImageOffset; // where in the file is this image
} ICONDIRENTRY, *LPICONDIRENTRY;
typedef struct
{
WORD idReserved; // Reserved
WORD idType; // resource type (1 for icons)
WORD idCount; // how many images?
ICONDIRENTRY idEntries[1]; // the entries for each image
} ICONDIR, *LPICONDIR;
// The following two structs are for the use of this program in
// manipulating icons. They are more closely tied to the operation
// of this program than the structures listed above. One of the
// main differences is that they provide a pointer to the DIB
// information of the masks.
typedef struct
{
UINT Width, Height, Colors; // Width, Height and bpp
LPBYTE lpBits; // ptr to DIB bits
DWORD dwNumBytes; // how many bytes?
LPBITMAPINFO lpbi; // ptr to header
LPBYTE lpXOR; // ptr to XOR image bits
LPBYTE lpAND; // ptr to AND image bits
} ICONIMAGE, *LPICONIMAGE;
typedef struct
{
UINT nNumImages; // How many images?
ICONIMAGE IconImages[1]; // Image entries
} ICONRESOURCE, *LPICONRESOURCE;
/****************************************************************************/
LPICONRESOURCE ReadIconFromICOFile( PBYTE buf, int sz );
void FreeIconResource(LPICONRESOURCE lpIR);
HICON MakeIconFromResource( LPICONIMAGE lpIcon );
HBITMAP LoadBitmapFile(LPBYTE data, DWORD sz)
{
BITMAPFILEHEADER *bmfh;
BITMAPINFO *bmi;
HBITMAP hBitmap, hBitmap2, hOldBmp1, hOldBmp2;
HDC hDC, hSrcDC, hSrcDC2;
LPICONRESOURCE lpir = NULL;
bmfh = (BITMAPFILEHEADER *) data;
if(bmfh->bfType == 0x4D42)
{
SendDebugMessageFormat(0, sdmLoad, 0, "LoadKeyboard: Bitmap found");
bmi = (BITMAPINFO *) (data + sizeof(BITMAPFILEHEADER));
hDC = GetDC(GetDesktopWindow());
hSrcDC = CreateCompatibleDC(hDC);
hSrcDC2 = CreateCompatibleDC(hDC);
hBitmap = CreateDIBitmap(hDC, &bmi->bmiHeader, CBM_INIT, data + bmfh->bfOffBits, bmi, DIB_RGB_COLORS);
hBitmap2 = CreateCompatibleBitmap(hDC, 16, 16);
ReleaseDC(GetDesktopWindow(), hDC);
hOldBmp1 = (HBITMAP) SelectObject(hSrcDC, hBitmap);
hOldBmp2 = (HBITMAP) SelectObject(hSrcDC2, hBitmap2);
BitBlt(hSrcDC2, 0, 0, 16, 16, hSrcDC, 0, 0, SRCCOPY);
SelectObject(hSrcDC, hOldBmp1);
SelectObject(hSrcDC2, hOldBmp2);
DeleteDC(hSrcDC);
DeleteDC(hSrcDC2);
DeleteObject(hBitmap);
}
else
{
SendDebugMessageFormat(0, sdmLoad, 0, "LoadKeyboard: Icon found");
lpir = ReadIconFromICOFile(data, sz);
if(!lpir)
{
SendDebugMessageFormat(0, sdmLoad, 0, "LoadKeyboard: icon not loaded");
return 0;
}
if(lpir->nNumImages == 0)
{
FreeIconResource(lpir);
return 0;
}
HICON hIcon = MakeIconFromResource(&lpir->IconImages[0]);
//HICON hIcon = CreateIcon(GetModuleHandle(LIBRARY_NAME), lpir->IconImages[0].Width, lpir->IconImages[0].Height,
// 1, lpir->IconImages[0].Colors, lpir->IconImages[0].lpAND, lpir->IconImages[0].lpXOR);
FreeIconResource(lpir);
if(hIcon == 0)
{
DebugLastError("MakeIconFromResource");
return 0;
}
hDC = GetDC(GetDesktopWindow());
hBitmap2 = CreateCompatibleBitmap(hDC, 16, 16);
hSrcDC = CreateCompatibleDC(hDC);
ReleaseDC(GetDesktopWindow(), hDC);
hOldBmp2 = (HBITMAP) SelectObject(hSrcDC, hBitmap2);
DrawIconEx(hSrcDC, 0, 0, hIcon, 16, 16, 0, NULL, DI_NORMAL);
SelectObject(hSrcDC, hOldBmp2);
DeleteDC(hSrcDC);
DestroyIcon(hIcon);
}
return hBitmap2;
}
/****************************************************************************
*
* FUNCTION: ReadICOHeader
*
* PURPOSE: Reads the header from an ICO file
*
* PARAMS: HANDLE hFile - handle to the file
*
* RETURNS: UINT - Number of images in file, -1 for failure
*
* History:
* July '95 - Created
*
\****************************************************************************/
UINT ReadICOHeader( PBYTE buf )
{
if(*(PWORD)(buf) != 0) return (UINT)-1;
if(*(PWORD)(buf+2) != 1) return (UINT)-1;
return *(PWORD)(buf+4);
}
/* End ReadICOHeader() ****************************************************/
/****************************************************************************
*
* FUNCTION: DIBNumColors
*
* PURPOSE: Calculates the number of entries in the color table.
*
* PARAMS: LPSTR lpbi - pointer to the CF_DIB memory block
*
* RETURNS: WORD - Number of entries in the color table.
*
* History:
* July '95 - Copied <g>
*
\****************************************************************************/
WORD DIBNumColors( LPSTR lpbi )
{
WORD wBitCount;
DWORD dwClrUsed;
dwClrUsed = ((LPBITMAPINFOHEADER) lpbi)->biClrUsed;
if (dwClrUsed)
return (WORD) dwClrUsed;
wBitCount = ((LPBITMAPINFOHEADER) lpbi)->biBitCount;
switch (wBitCount)
{
case 1: return 2;
case 4: return 16;
case 8: return 256;
}
return 0;
}
/* End DIBNumColors() ******************************************************/
/****************************************************************************
*
* FUNCTION: PaletteSize
*
* PURPOSE: Calculates the number of bytes in the color table.
*
* PARAMS: LPSTR lpbi - pointer to the CF_DIB memory block
*
* RETURNS: WORD - number of bytes in the color table
*
*
* History:
* July '95 - Copied <g>
*
\****************************************************************************/
WORD PaletteSize( LPSTR lpbi )
{
return ( DIBNumColors( lpbi ) * sizeof( RGBQUAD ) );
}
/* End PaletteSize() ********************************************************/
/****************************************************************************
*
* FUNCTION: FindDIBits
*
* PURPOSE: Locate the image bits in a CF_DIB format DIB.
*
* PARAMS: LPSTR lpbi - pointer to the CF_DIB memory block
*
* RETURNS: LPSTR - pointer to the image bits
*
* History:
* July '95 - Copied <g>
*
\****************************************************************************/
LPSTR FindDIBBits( LPSTR lpbi )
{
return ( lpbi + *(LPDWORD)lpbi + PaletteSize( lpbi ) );
}
/* End FindDIBits() *********************************************************/
// How wide, in bytes, would this many bits be, DWORD aligned?
#define WIDTHBYTES(bits) ((((bits) + 31)>>5)<<2)
/****************************************************************************
*
* FUNCTION: BytesPerLine
*
* PURPOSE: Calculates the number of bytes in one scan line.
*
* PARAMS: LPBITMAPINFOHEADER lpBMIH - pointer to the BITMAPINFOHEADER
* that begins the CF_DIB block
*
* RETURNS: DWORD - number of bytes in one scan line (DWORD aligned)
*
* History:
* July '95 - Created
*
\****************************************************************************/
DWORD BytesPerLine( LPBITMAPINFOHEADER lpBMIH )
{
return WIDTHBYTES(lpBMIH->biWidth * lpBMIH->biPlanes * lpBMIH->biBitCount);
}
/* End BytesPerLine() ********************************************************/
/****************************************************************************
*
* FUNCTION: AdjustIconImagePointers
*
* PURPOSE: Adjusts internal pointers in icon resource struct
*
* PARAMS: LPICONIMAGE lpImage - the resource to handle
*
* RETURNS: BOOL - TRUE for success, FALSE for failure
*
* History:
* July '95 - Created
*
\****************************************************************************/
BOOL AdjustIconImagePointers( LPICONIMAGE lpImage )
{
// Sanity check
if( lpImage==NULL )
return FALSE;
// BITMAPINFO is at beginning of bits
lpImage->lpbi = (LPBITMAPINFO)lpImage->lpBits;
// Width - simple enough
lpImage->Width = lpImage->lpbi->bmiHeader.biWidth;
// Icons are stored in funky format where height is doubled - account for it
lpImage->Height = (lpImage->lpbi->bmiHeader.biHeight)/2;
// How many colors?
lpImage->Colors = lpImage->lpbi->bmiHeader.biPlanes * lpImage->lpbi->bmiHeader.biBitCount;
// XOR bits follow the header and color table
lpImage->lpXOR = (LPBYTE) FindDIBBits((LPSTR)lpImage->lpbi);
// AND bits follow the XOR bits
lpImage->lpAND = lpImage->lpXOR + (lpImage->Height*BytesPerLine((LPBITMAPINFOHEADER)(lpImage->lpbi)));
return TRUE;
}
/* End AdjustIconImagePointers() *******************************************/
/****************************************************************************
*
* FUNCTION: ReadIconFromICOFile
*
* PURPOSE: Reads an Icon Resource from an ICO file
*
* PARAMS: LPCTSTR szFileName - Name of the ICO file
*
* RETURNS: LPICONRESOURCE - pointer to the resource, NULL for failure
*
* History:
* July '95 - Created
*
\****************************************************************************/
LPICONRESOURCE ReadIconFromICOFile( PBYTE buf, int sz )
{
UNREFERENCED_PARAMETER(sz);
LPICONRESOURCE lpIR = NULL, lpNew = NULL;
HANDLE hFile = NULL;
//LPRESOURCEPOSINFO lpRPI = NULL;
UINT i;
LPICONDIRENTRY lpIDE = NULL;
// Allocate memory for the resource structure
if( (lpIR = (LPICONRESOURCE) malloc( sizeof(ICONRESOURCE) )) == NULL )
{
SendDebugMessageFormat(0, sdmLoad, 0, "Error Allocating Memory");
return NULL;
}
// Read in the header
if( (lpIR->nNumImages = ReadICOHeader(buf)) == (UINT)-1 )
{
SendDebugMessageFormat(0, sdmLoad, 0, "Error Reading File Header");
free( lpIR );
return NULL;
}
// Adjust the size of the struct to account for the images
if( (lpNew = (LPICONRESOURCE) realloc( lpIR, sizeof(ICONRESOURCE) + ((lpIR->nNumImages-1) * sizeof(ICONIMAGE)) )) == NULL )
{
SendDebugMessageFormat(0, sdmLoad, 0, "Error Allocating Memory");
CloseHandle( hFile );
free( lpIR );
return NULL;
}
lpIR = lpNew;
// Store the original name
// Allocate enough memory for the icon directory entries
if( (lpIDE = (LPICONDIRENTRY) malloc( lpIR->nNumImages * sizeof( ICONDIRENTRY ) ) ) == NULL )
{
SendDebugMessageFormat(0, sdmLoad, 0, "Error Allocating Memory");
free( lpIR );
return NULL;
}
memcpy(lpIDE, buf + 6, lpIR->nNumImages * sizeof( ICONDIRENTRY ));
// Loop through and read in each image
for( i = 0; i < lpIR->nNumImages; i++ )
{
// Allocate memory for the resource
if( (lpIR->IconImages[i].lpBits = (LPBYTE) malloc(lpIDE[i].dwBytesInRes)) == NULL )
{
SendDebugMessageFormat(0, sdmLoad, 0, "Error Allocating Memory");
free( lpIR );
free( lpIDE );
return NULL;
}
lpIR->IconImages[i].dwNumBytes = lpIDE[i].dwBytesInRes;
// Seek to beginning of this image
memcpy(lpIR->IconImages[i].lpBits, buf + lpIDE[i].dwImageOffset, lpIDE[i].dwBytesInRes);
// Set the internal pointers appropriately
if( ! AdjustIconImagePointers( &(lpIR->IconImages[i]) ) )
{
SendDebugMessageFormat(0, sdmLoad, 0, "Error Converting to Internal Format");
free( lpIDE );
free( lpIR );
return NULL;
}
}
// Clean up
free( lpIDE );
//free( lpRPI );
return lpIR;
}
/* End ReadIconFromICOFile() **********************************************/
void FreeIconResource(LPICONRESOURCE lpIR)
{
for( UINT i = 0; i < lpIR->nNumImages; i++ )
// Allocate memory for the resource
free(lpIR->IconImages[i].lpBits);
free( lpIR );
}
/****************************************************************************
*
* FUNCTION: MakeIconFromResource
*
* PURPOSE: Makes an HICON from an icon resource
*
* PARAMS: LPICONIMAGE lpIcon - pointer to the icon resource
*
* RETURNS: HICON - handle to the new icon, NULL for failure
*
* History:
* July '95 - Created
*
\****************************************************************************/
HICON MakeIconFromResource( LPICONIMAGE lpIcon )
{
HICON hIcon = NULL;
// Sanity Check
if( lpIcon == NULL )
return NULL;
if( lpIcon->lpBits == NULL )
return NULL;
// Let the OS do the real work :)
hIcon = CreateIconFromResourceEx( lpIcon->lpBits, lpIcon->dwNumBytes, TRUE, 0x00030000,
(*(LPBITMAPINFOHEADER)(lpIcon->lpBits)).biWidth, (*(LPBITMAPINFOHEADER)(lpIcon->lpBits)).biHeight/2, 0 );
// It failed, odds are good we're on NT so try the non-Ex way
if( hIcon == NULL )
{
// We would break on NT if we try with a 16bpp image
if(lpIcon->lpbi->bmiHeader.biBitCount != 16)
{
hIcon = CreateIconFromResource( lpIcon->lpBits, lpIcon->dwNumBytes, TRUE, 0x00030000 );
}
}
return hIcon;
}
/* End MakeIconFromResource() **********************************************/
PWCHAR StringOffset(PBYTE base, DWORD offset)
{
if(offset == 0) return NULL;
return (PWCHAR)(base + offset);
}
#ifdef _WIN64
/**
CopyKeyboard will copy the data read into bufp from x86-sized structures into x64-sized structures starting at base
* We know the base is dwFileSize * 3
* After this function finishes, we still need to keep the original data
*/
LPKEYBOARD CopyKeyboard(PBYTE bufp, PBYTE base, DWORD dwFileSize)
{
UNREFERENCED_PARAMETER(dwFileSize);
PCOMP_KEYBOARD ckbp = (PCOMP_KEYBOARD) base;
/* Copy keyboard structure */
LPKEYBOARD kbp = (LPKEYBOARD) bufp;
bufp += sizeof(KEYBOARD);
kbp->dwIdentifier = ckbp->dwIdentifier;
kbp->dwFileVersion = ckbp->dwFileVersion;
kbp->dwCheckSum = ckbp->dwCheckSum;
kbp->xxkbdlayout = ckbp->KeyboardID;
kbp->IsRegistered = ckbp->IsRegistered;
kbp->version = ckbp->version;
kbp->cxStoreArray = ckbp->cxStoreArray;
kbp->cxGroupArray = ckbp->cxGroupArray;
kbp->StartGroup[0] = ckbp->StartGroup[0];
kbp->StartGroup[1] = ckbp->StartGroup[1];
kbp->dwFlags = ckbp->dwFlags;
kbp->dwHotKey = ckbp->dwHotKey;
kbp->hBitmap = 0; // will be built later
kbp->dpStoreArray = (LPSTORE) bufp;
bufp += sizeof(STORE) * kbp->cxStoreArray;
kbp->dpGroupArray = (LPGROUP) bufp;
bufp += sizeof(GROUP) * kbp->cxGroupArray;
PCOMP_STORE csp;
LPSTORE sp;
DWORD i;
for(
csp = (PCOMP_STORE)(base + ckbp->dpStoreArray), sp = kbp->dpStoreArray, i = 0;
i < kbp->cxStoreArray;
i++, sp++, csp++)
{
sp->dwSystemID = csp->dwSystemID;
sp->dpName = StringOffset(base, csp->dpName);
sp->dpString = StringOffset(base, csp->dpString);
}
PCOMP_GROUP cgp;
LPGROUP gp;
for(
cgp = (PCOMP_GROUP)(base + ckbp->dpGroupArray), gp = kbp->dpGroupArray, i = 0;
i < kbp->cxGroupArray;
i++, gp++, cgp++)
{
gp->dpName = (PWCHAR)(base + cgp->dpName);
gp->dpKeyArray = (LPKEY) bufp;
gp->cxKeyArray = cgp->cxKeyArray;
bufp += sizeof(KEY) * gp->cxKeyArray;
gp->dpMatch = StringOffset(base, cgp->dpMatch);
gp->dpNoMatch = StringOffset(base, cgp->dpNoMatch);
gp->fUsingKeys = cgp->fUsingKeys;
PCOMP_KEY ckp;
LPKEY kp;
DWORD j;
for(
ckp = (PCOMP_KEY)(base + cgp->dpKeyArray), kp = gp->dpKeyArray, j = 0;
j < gp->cxKeyArray;
j++, kp++, ckp++)
{
kp->Key = ckp->Key;
kp->Line = ckp->Line;
kp->ShiftFlags = ckp->ShiftFlags;
kp->dpOutput = StringOffset(base, ckp->dpOutput);
kp->dpContext = StringOffset(base, ckp->dpContext);
}
}
return kbp;
}
#else
LPKEYBOARD FixupKeyboard(PBYTE bufp, PBYTE base, DWORD dwFileSize)
{
UNREFERENCED_PARAMETER(dwFileSize);
DWORD i, j;
PCOMP_KEYBOARD ckbp = (PCOMP_KEYBOARD) base;
PCOMP_GROUP cgp;
PCOMP_STORE csp;
PCOMP_KEY ckp;
LPKEYBOARD kbp = (LPKEYBOARD) bufp;
LPSTORE sp;
LPGROUP gp;
LPKEY kp;
kbp->dpStoreArray = (LPSTORE) (base + ckbp->dpStoreArray);
kbp->dpGroupArray = (LPGROUP) (base + ckbp->dpGroupArray);
/*if( ckbp->dwBitmapSize > 0 )
kbp->hBitmap = LoadBitmapFile((buf + ckbp->dpBitmapOffset), ckbp->dwBitmapSize);
else
kbp->hBitmap = NULL;
*/
for(sp = kbp->dpStoreArray, csp = (PCOMP_STORE) sp, i = 0; i < kbp->cxStoreArray; i++, sp++, csp++)
{
sp->dpName = StringOffset(base, csp->dpName);
sp->dpString = StringOffset(base, csp->dpString);
}
for(gp = kbp->dpGroupArray, cgp = (PCOMP_GROUP) gp, i = 0; i < kbp->cxGroupArray; i++, gp++, cgp++)
{
gp->dpName = StringOffset(base, cgp->dpName);
gp->dpKeyArray = (LPKEY) (base + cgp->dpKeyArray);
if(cgp->dpMatch != NULL) gp->dpMatch = (PWSTR) (base + cgp->dpMatch);
if(cgp->dpNoMatch != NULL) gp->dpNoMatch = (PWSTR) (base + cgp->dpNoMatch);
for(kp = gp->dpKeyArray, ckp = (PCOMP_KEY) kp, j = 0; j < gp->cxKeyArray; j++, kp++, ckp++)
{
kp->dpOutput = (PWSTR) (base + ckp->dpOutput);
kp->dpContext = (PWSTR) (base + ckp->dpContext);
}
}
return kbp;
}
#endif
HBITMAP LoadBitmapFileEx(PBYTE filebase)
{
PCOMP_KEYBOARD ckbp = (PCOMP_KEYBOARD) filebase;
if( ckbp->dwBitmapSize > 0 )
return LoadBitmapFile(filebase + ckbp->dpBitmapOffset, ckbp->dwBitmapSize);
else
return NULL;
}
BOOL VerifyChecksum(LPBYTE buf, DWORD sz)
{
DWORD tempcs;
PCOMP_KEYBOARD ckbp;
ckbp = (PCOMP_KEYBOARD) buf;
tempcs = ckbp->dwCheckSum;
ckbp->dwCheckSum = 0;
return tempcs == CalculateBufferCRC(sz, buf);
}
BOOL VerifyKeyboard(LPBYTE filebase, DWORD sz)
{
DWORD i;
PCOMP_KEYBOARD ckbp = (PCOMP_KEYBOARD) filebase;
PCOMP_STORE csp;
/* Check file version */
if(ckbp->dwFileVersion < VERSION_MIN ||
ckbp->dwFileVersion > VERSION_MAX)
{
/* Old or new version -- identify the desired program version */
if(VerifyChecksum(filebase, sz))
{
for(csp = (PCOMP_STORE)(filebase + ckbp->dpStoreArray), i = 0; i < ckbp->cxStoreArray; i++, csp++)
if(csp->dwSystemID == TSS_COMPILEDVERSION)
{
char buf2[256];
if(csp->dpString == 0)
wsprintf(buf2, "errWrongFileVersion:NULL");
else
wsprintf(buf2, "errWrongFileVersion:%10.10ls", StringOffset(filebase, csp->dpString));
Err(buf2);
return FALSE;
}
}
Err("errWrongFileVersion");
return FALSE;
}
if(!VerifyChecksum(filebase, sz)) { Err("errBadChecksum"); return FALSE; }
return TRUE;
}
| 24,833 | 9,260 |
/****************************************************************************
* Copyright (C) from 2009 to Present EPAM Systems.
*
* This file is part of Indigo toolkit.
*
* 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 "molecule/molecule_tautomer_utils.h"
using namespace indigo;
bool MoleculeTautomerUtils::_isRepMetal(int elem)
{
static const int list[] = {ELEM_Li, ELEM_Na, ELEM_K, ELEM_Rb, ELEM_Cs, ELEM_Be, ELEM_Mg, ELEM_Ca, ELEM_Sr, ELEM_Ba};
for (int i = 0; i < (int)NELEM(list); i++)
if (elem == list[i])
return true;
return false;
}
// Count potential hydrogens (+, - charges or metal bonds)
void MoleculeTautomerUtils::countHReplacements(BaseMolecule& m, Array<int>& h_rep_count)
{
h_rep_count.clear_resize(m.vertexEnd());
for (int i : m.vertices())
{
const Vertex& vertex = m.getVertex(i);
h_rep_count[i] = 0;
for (int bond_idx : vertex.neighbors())
{
if (_isRepMetal(m.getAtomNumber(vertex.neiVertex(bond_idx))))
{
int bond_type = m.getBondOrder(vertex.neiEdge(bond_idx));
if (bond_type != BOND_AROMATIC)
h_rep_count[i] += bond_type;
}
}
// + or - charge also count as potential hydrogens
int charge = m.getAtomCharge(i);
if (charge != CHARGE_UNKNOWN)
h_rep_count[i] += abs(charge);
}
}
// If core_2 != 0 highlights g1 too
void MoleculeTautomerUtils::highlightChains(BaseMolecule& g1, BaseMolecule& g2, const Array<int>& chains_2, const int* core_2)
{
int i;
for (i = g2.vertexBegin(); i < g2.vertexEnd(); i = g2.vertexNext(i))
{
if (chains_2[i] > 0 || (core_2 != 0 && core_2[i] >= 0))
g2.highlightAtom(i);
}
for (i = g2.edgeBegin(); i < g2.edgeEnd(); i = g2.edgeNext(i))
{
const Edge& edge = g2.getEdge(i);
// zeroed bond?
if (g2.getBondOrder(i) == -1 && g2.possibleBondOrder(i, BOND_SINGLE))
continue;
if (chains_2[edge.beg] > 0 && chains_2[edge.end] > 0 && abs(chains_2[edge.beg] - chains_2[edge.end]) == 1)
g2.highlightBond(i);
else if (core_2 != 0 && core_2[edge.beg] >= 0 && core_2[edge.end] >= 0)
{
if (g1.findEdgeIndex(core_2[edge.beg], core_2[edge.end]) != -1)
g2.highlightBond(i);
}
}
}
| 2,990 | 1,091 |
/***************************************************************************
* Copyright 2019 HYUNWOO O
*
* 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 <iostream>
#include "TableIndexer.hpp"
#include "TableSearcher.hpp"
#define MAX_QUERY_SIZE 1000
int main() {
HashMap hashMap;
TableIndexer tableIndexer;
tableIndexer.createIndex("../resources/amazon_jobs.csv", hashMap);
TableSearcher tableSearcher;
while (true) {
std::cout << "Input queries: (type 'exitsearch' to exit) ";
char temp[MAX_QUERY_SIZE];
std::cin.getline(temp, MAX_QUERY_SIZE, '\n');
std::string searchQuery(temp);
if (searchQuery == "exitsearch") {
std::cout << "===== Shut down search engine... =====\n";
break;
}
tableSearcher.search(searchQuery, hashMap);
}
return 0;
}
| 1,493 | 431 |
#pragma once
#include <mcpe\BlockPos.hpp>
#include <mcpe\Block.hpp>
#include <mcpe\Dimension.hpp>
class LevelChunk {
public:
Level getLevel() const;
Dimension getDimension() const;
Block getBlock(ChunkBlockPos const&) const;
ChunkLocalHeight getHeightRange() const;
ChunkPos* getPosition() const;
}; | 324 | 108 |
/*
*
* (C) 2003 by Argonne National Laboratory.
* See COPYRIGHT in top-level directory.
*/
#include <sstmac/replacements/mpi/mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "mpitest.h"
namespace probe_intercomm{
/**
static char MTEST_Descrip[] = "Test MPI_Probe() for an intercomm";
*/
#define MAX_DATA_LEN 100
int probe_intercomm( int argc, char *argv[] )
{
int errs = 0, recvlen, isLeft;
MPI_Status status;
int rank, size;
MPI_Comm intercomm;
char buf[MAX_DATA_LEN];
const char *test_str = "test";
MTest_Init( &argc, &argv );
MPI_Comm_rank( MPI_COMM_WORLD, &rank );
MPI_Comm_size( MPI_COMM_WORLD, &size );
if (size < 2) {
fprintf( stderr, "This test requires at least two processes." );
MPI_Abort( MPI_COMM_WORLD, 1 );
}
while (MTestGetIntercomm( &intercomm, &isLeft, 2 )) {
if (intercomm == MPI_COMM_NULL) continue;
MPI_Comm_rank(intercomm, &rank);
/** 0 ranks on each side communicate, everyone else does nothing */
if(rank == 0) {
if (isLeft) {
recvlen = -1;
MPI_Probe(0, 0, intercomm, &status);
MPI_Get_count(&status, MPI_CHAR, &recvlen);
if (recvlen != (strlen(test_str) + 1)) {
printf(" Error: recvlen (%d) != strlen(\"%s\")+1 (%d)\n", recvlen, test_str, (int)strlen(test_str) + 1);
++errs;
}
buf[0] = '\0';
MPI_Recv(buf, recvlen, MPI_CHAR, 0, 0, intercomm, &status);
if (strcmp(test_str,buf)) {
printf(" Error: strcmp(test_str,buf)!=0\n");
++errs;
}
}
else {
strncpy(buf, test_str, 5);
MPI_Send(buf, strlen(buf)+1, MPI_CHAR, 0, 0, intercomm);
}
}
MTestFreeComm(&intercomm);
}
MTest_Finalize( errs );
MPI_Finalize();
return 0;
}
}
| 2,007 | 755 |
/*
-------------------------------------------------------------------------
CxxTest: A lightweight C++ unit testing library.
Copyright (c) 2008 Sandia Corporation.
This software is distributed under the LGPL License v2.1
For more information, see the COPYING file in the top CxxTest directory.
Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------
*/
#ifndef __cxxtest__LinkedList_cpp__
#define __cxxtest__LinkedList_cpp__
#include <cxxtest/LinkedList.h>
namespace CxxTest
{
List GlobalFixture::_list = { 0, 0 };
List RealSuiteDescription::_suites = { 0, 0 };
void List::initialize()
{
_head = _tail = 0;
}
Link *List::head()
{
Link *l = _head;
while ( l && !l->active() )
l = l->next();
return l;
}
const Link *List::head() const
{
Link *l = _head;
while ( l && !l->active() )
l = l->next();
return l;
}
Link *List::tail()
{
Link *l = _tail;
while ( l && !l->active() )
l = l->prev();
return l;
}
const Link *List::tail() const
{
Link *l = _tail;
while ( l && !l->active() )
l = l->prev();
return l;
}
bool List::empty() const
{
return (_head == 0);
}
unsigned List::size() const
{
unsigned count = 0;
for ( const Link *l = head(); l != 0; l = l->next() )
++ count;
return count;
}
Link *List::nth( unsigned n )
{
Link *l = head();
while ( n -- )
l = l->next();
return l;
}
void List::activateAll()
{
for ( Link *l = _head; l != 0; l = l->justNext() )
l->setActive( true );
}
void List::leaveOnly( const Link &link )
{
for ( Link *l = head(); l != 0; l = l->next() )
if ( l != &link )
l->setActive( false );
}
Link::Link() :
_next( 0 ),
_prev( 0 ),
_active( true )
{
}
Link::~Link()
{
}
bool Link::active() const
{
return _active;
}
void Link::setActive( bool value )
{
_active = value;
}
Link * Link::justNext()
{
return _next;
}
Link * Link::justPrev()
{
return _prev;
}
Link * Link::next()
{
Link *l = _next;
while ( l && !l->_active )
l = l->_next;
return l;
}
Link * Link::prev()
{
Link *l = _prev;
while ( l && !l->_active )
l = l->_prev;
return l;
}
const Link * Link::next() const
{
Link *l = _next;
while ( l && !l->_active )
l = l->_next;
return l;
}
const Link * Link::prev() const
{
Link *l = _prev;
while ( l && !l->_active )
l = l->_prev;
return l;
}
void Link::attach( List &l )
{
if ( l._tail )
l._tail->_next = this;
_prev = l._tail;
_next = 0;
if ( l._head == 0 )
l._head = this;
l._tail = this;
}
void Link::detach( List &l )
{
if ( _prev )
_prev->_next = _next;
else
l._head = _next;
if ( _next )
_next->_prev = _prev;
else
l._tail = _prev;
}
}
#endif // __cxxtest__LinkedList_cpp__
| 3,660 | 1,202 |
using namespace System;
using namespace System::Globalization;
void ShowZeroPlaceholder()
{
// <Snippet1>
double value;
value = 123;
Console::WriteLine(value.ToString("00000"));
Console::WriteLine(String::Format("{0:00000}", value));
// Displays 00123
value = 1.2;
Console::WriteLine(value.ToString("0.00", CultureInfo::InvariantCulture));
Console::WriteLine(String::Format(CultureInfo::InvariantCulture,
"{0:0.00}", value));
// Displays 1.20
Console::WriteLine(value.ToString("00.00", CultureInfo::InvariantCulture));
Console::WriteLine(String::Format(CultureInfo::InvariantCulture,
"{0:00.00}", value));
// Displays 01.20
CultureInfo^ daDK = CultureInfo::CreateSpecificCulture("da-DK");
Console::WriteLine(value.ToString("00.00", daDK));
Console::WriteLine(String::Format(daDK, "{0:00.00}", value));
// Displays 01,20
value = .56;
Console::WriteLine(value.ToString("0.0", CultureInfo::InvariantCulture));
Console::WriteLine(String::Format(CultureInfo::InvariantCulture,
"{0:0.0}", value));
// Displays 0.6
value = 1234567890;
Console::WriteLine(value.ToString("0,0", CultureInfo::InvariantCulture));
Console::WriteLine(String::Format(CultureInfo::InvariantCulture,
"{0:0,0}", value));
// Displays 1,234,567,890
CultureInfo^ elGR = CultureInfo::CreateSpecificCulture("el-GR");
Console::WriteLine(value.ToString("0,0", elGR));
Console::WriteLine(String::Format(elGR, "{0:0,0}", value));
// Displays 1.234.567.890
value = 1234567890.123456;
Console::WriteLine(value.ToString("0,0.0", CultureInfo::InvariantCulture));
Console::WriteLine(String::Format(CultureInfo::InvariantCulture,
"{0:0,0.0}", value));
// Displays 1,234,567,890.1
value = 1234.567890;
Console::WriteLine(value.ToString("0,0.00", CultureInfo::InvariantCulture));
Console::WriteLine(String::Format(CultureInfo::InvariantCulture,
"{0:0,0.00}", value));
// Displays 1,234.57
// </Snippet1>
}
void ShowDigitPlaceholder()
{
// <Snippet2>
double value;
value = 1.2;
Console::WriteLine(value.ToString("#.##", CultureInfo::InvariantCulture));
Console::WriteLine(String::Format(CultureInfo::InvariantCulture,
"{0:#.##}", value));
// Displays 1.2
value = 123;
Console::WriteLine(value.ToString("#####"));
Console::WriteLine(String::Format("{0:#####}", value));
// Displays 123
value = 123456;
Console::WriteLine(value.ToString("[##-##-##]"));
Console::WriteLine(String::Format("{0:[##-##-##]}", value));
// Displays [12-34-56]
value = 1234567890;
Console::WriteLine(value.ToString("#"));
Console::WriteLine(String::Format("{0:#}", value));
// Displays 1234567890
Console::WriteLine(value.ToString("(###) ###-####"));
Console::WriteLine(String::Format("{0:(###) ###-####}", value));
// Displays (123) 456-7890
// </Snippet2>
}
void ShowDecimalPoint()
{
// <Snippet3>
double value;
value = 1.2;
Console::WriteLine(value.ToString("0.00", CultureInfo::InvariantCulture));
Console::WriteLine(String::Format(CultureInfo::InvariantCulture,
"{0:0.00}", value));
// Displays 1.20
Console::WriteLine(value.ToString("00.00", CultureInfo::InvariantCulture));
Console::WriteLine(String::Format(CultureInfo::InvariantCulture,
"{0:00.00}", value));
// Displays 01.20
Console::WriteLine(value.ToString("00.00",
CultureInfo::CreateSpecificCulture("da-DK")));
Console::WriteLine(String::Format(CultureInfo::CreateSpecificCulture("da-DK"),
"{0:00.00}", value));
// Displays 01,20
value = .086;
Console::WriteLine(value.ToString("#0.##%", CultureInfo::InvariantCulture));
Console::WriteLine(String::Format(CultureInfo::InvariantCulture,
"{0:#0.##%}", value));
// Displays 8.6%
value = 86000;
Console::WriteLine(value.ToString("0.###E+0", CultureInfo::InvariantCulture));
Console::WriteLine(String::Format(CultureInfo::InvariantCulture,
"{0:0.###E+0}", value));
// Displays 8.6E+4
// </Snippet3>
}
void ShowThousandSpecifier()
{
// <Snippet4>
double value = 1234567890;
Console::WriteLine(value.ToString("#,#", CultureInfo::InvariantCulture));
Console::WriteLine(String::Format(CultureInfo::InvariantCulture,
"{0:#,#}", value));
// Displays 1,234,567,890
Console::WriteLine(value.ToString("#,##0,,", CultureInfo::InvariantCulture));
Console::WriteLine(String::Format(CultureInfo::InvariantCulture,
"{0:#,##0,,}", value));
// Displays 1,235
// </Snippet4>
}
void ShowScalingSpecifier()
{
// <Snippet5>
double value = 1234567890;
Console::WriteLine(value.ToString("#,,", CultureInfo::InvariantCulture));
Console::WriteLine(String::Format(CultureInfo::InvariantCulture,
"{0:#,,}", value));
// Displays 1235
Console::WriteLine(value.ToString("#,,,", CultureInfo::InvariantCulture));
Console::WriteLine(String::Format(CultureInfo::InvariantCulture,
"{0:#,,,}", value));
// Displays 1
Console::WriteLine(value.ToString("#,##0,,", CultureInfo::InvariantCulture));
Console::WriteLine(String::Format(CultureInfo::InvariantCulture,
"{0:#,##0,,}", value));
// Displays 1,235
// </Snippet5>
}
void ShowPercentagePlaceholder()
{
// <Snippet6>
double value = .086;
Console::WriteLine(value.ToString("#0.##%", CultureInfo::InvariantCulture));
Console::WriteLine(String::Format(CultureInfo::InvariantCulture,
"{0:#0.##%}", value));
// Displays 8.6%
// </Snippet6>
}
void ShowScientificNotation()
{
// <Snippet7>
double value = 86000;
Console::WriteLine(value.ToString("0.###E+0", CultureInfo::InvariantCulture));
Console::WriteLine(String::Format(CultureInfo::InvariantCulture,
"{0:0.###E+0}", value));
// Displays 8.6E+4
Console::WriteLine(value.ToString("0.###E+000", CultureInfo::InvariantCulture));
Console::WriteLine(String::Format(CultureInfo::InvariantCulture,
"{0:0.###E+000}", value));
// Displays 8.6E+004
Console::WriteLine(value.ToString("0.###E-000", CultureInfo::InvariantCulture));
Console::WriteLine(String::Format(CultureInfo::InvariantCulture,
"{0:0.###E-000}", value));
// Displays 8.6E004
// </Snippet7>
}
void ShowSectionSpecifier()
{
// <Snippet8>
double posValue = 1234;
double negValue = -1234;
double zeroValue = 0;
String^ fmt2 = "##;(##)";
String^ fmt3 = "##;(##);**Zero**";
Console::WriteLine(posValue.ToString(fmt2));
Console::WriteLine(String::Format("{0:" + fmt2 + "}", posValue));
// Displays 1234
Console::WriteLine(negValue.ToString(fmt2));
Console::WriteLine(String::Format("{0:" + fmt2 + "}", negValue));
// Displays (1234)
Console::WriteLine(zeroValue.ToString(fmt3));
Console::WriteLine(String::Format("{0:" + fmt3 + "}", zeroValue));
// Displays **Zero**
// </Snippet8>
}
void ShowPerMillePlaceholder()
{
// <Snippet9>
double value = .00354;
String^ perMilleFmt = "#0.## " + '\u2030';
Console::WriteLine(value.ToString(perMilleFmt, CultureInfo::InvariantCulture));
Console::WriteLine(String::Format(CultureInfo::InvariantCulture,
"{0:" + perMilleFmt + "}", value));
// Displays 3.54‰
// </Snippet9>
}
void main()
{
Console::WriteLine("Zero Placeholder:");
ShowZeroPlaceholder();
Console::WriteLine();
Console::WriteLine("Digit Placeholder:");
ShowDigitPlaceholder();
Console::WriteLine();
Console::WriteLine("Decimal Point:");
ShowDecimalPoint();
Console::WriteLine();
Console::WriteLine("Thousand Specifier:");
ShowThousandSpecifier();
Console::WriteLine();
Console::WriteLine("Scaling Specifier:");
ShowScalingSpecifier();
Console::WriteLine();
Console::WriteLine("Percentage Placeholder:");
ShowPercentagePlaceholder();
Console::WriteLine();
Console::WriteLine("Scientific Notation:");
ShowScientificNotation();
Console::WriteLine();
Console::WriteLine("Section Specifier:");
ShowSectionSpecifier();
Console::WriteLine();
Console::WriteLine("Per Mille Placeholder:");
ShowPerMillePlaceholder();
}
| 9,131 | 2,963 |
// @@@LICENSE
//
// Copyright (c) 2010-2013 LG Electronics, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// LICENSE@@@
#include "protocol/StoreResponseParser.h"
StoreResponseParser::StoreResponseParser(ImapSession& session, DoneSignal::SlotRef doneSlot)
: ImapResponseParser(session, doneSlot),
m_responsesLeft(0)
{
}
StoreResponseParser::~StoreResponseParser()
{
}
void StoreResponseParser::HandleResponse(ImapStatusCode status, const std::string& response)
{
// FIXME handle errors
m_responsesLeft--;
}
void StoreResponseParser::AddExpectedResponse()
{
m_responsesLeft++;
}
void StoreResponseParser::Done()
{
if(m_responsesLeft < 1 || m_status == STATUS_EXCEPTION)
m_doneSignal.fire();
}
| 1,226 | 399 |
#include <stdafx.h>
#include "Sandbox.h"
#include "Scripting.h"
Sandbox::Sandbox(Scripting* apScripting, sol::environment aBaseEnvironment, const std::filesystem::path& acRootPath)
: m_pScripting(apScripting)
, m_env(apScripting->GetState().Get(), sol::create)
, m_path(acRootPath)
{
// copy base environment, do not set it as fallback, as it may cause globals to bleed into other things!
for (const auto& cKV : aBaseEnvironment)
m_env[cKV.first].set(cKV.second.as<sol::object>());
}
sol::protected_function_result Sandbox::ExecuteFile(const std::string& acPath) const
{
return m_pScripting->GetState().Get().script_file(acPath, m_env);
}
sol::protected_function_result Sandbox::ExecuteString(const std::string& acString) const
{
return m_pScripting->GetState().Get().script(acString, m_env);
}
sol::environment& Sandbox::GetEnvironment()
{
return m_env;
}
const std::filesystem::path& Sandbox::GetRootPath() const
{
return m_path;
}
| 984 | 338 |
#define __USE_MINGW_ANSI_STDIO 0
#include<bits/stdc++.h>
using namespace std;
#define PI acos(-1)
#define pb push_back
#define fi first
#define se second
#define TASK "commuting"
#define sz(a) (int)(a).size()
#define all(c) (c).begin(), (c).end()
#define TIMESTAMP fprintf(stderr, "Execution time: %.3lf s.\n", (double)clock()/CLOCKS_PER_SEC)
typedef long long ll;
typedef long double ld;
typedef vector <int> vi;
typedef vector <ll> vll;
typedef pair <int, int> pii;
typedef vector <vi> vvi;
typedef vector <pii> vpii;
typedef vector <string> vs;
const int MAXN = 2e5 + 9;
const int MOD = (int)(1e9 + 7);
const int INF = 1e9;
int gg[MAXN], rr[MAXN];
int n;
int ans[MAXN];
int T[MAXN];
int cnt = 0;
int tmp[MAXN], posTmp;
mt19937_64 rnd(chrono::high_resolution_clock::now().time_since_epoch().count());
void input() {
cin >> n;
for(int i = 1; i <= n; i++) {
int x;
cin >> x;
gg[i] = x;
rr[x] = i;
}
}
void go(int pos) {
if(pos == n + 1) {
cnt++;
bool ok = 1;
for(int i = 1; i <= n; i++)
if(T[i] < ans[i])
ok = 0;
else if(ok && ans[i] < T[i]) {
return;
}
for(int i = 1; i <= n; i++) {
if(gg[T[i]] != T[gg[i]])
return;
}
if(!ok) {
cout << " found " << endl;
cout << " input " << endl;
for(int i = 1; i <= n; i++)
cout << gg[i] << ' ';
cout << endl;
cout << " ans " << endl;
for(int i = 1; i <= n; i++)
cout << ans[i] << ' ';
cout << endl;
cout << " bettter ans " << endl;
for(int i = 1; i <= n; i++)
cout << T[i] << ' ';
cout << endl;
cout << " checking " << endl;
for(int i = 1; i <= n; i++)
cout << gg[T[i]] - T[gg[i]] << ' ';
cout << endl;
exit(0);
}
return;
}
for(int i = 1; i <= n; i++) {
T[pos] = i;
go(pos + 1);
}
}
void solve() {
memset(ans, -1, sizeof(ans));
vi cycles(n + 1, INF);
vi used(n + 1, 0);
for(int i = 1; i <= n; i++) {
if(used[i]) continue;
posTmp = 0;
tmp[posTmp++] = gg[i];
int v = gg[gg[i]];
while(v != gg[i]) {
used[v] = 1;
tmp[posTmp++] = v;
v = gg[v];
}
int curMin = *min_element(tmp, tmp + posTmp);
cycles[posTmp] = min(cycles[posTmp], curMin);
}
for(int i = 1; i <= n; i++) {
if(ans[i] != -1) continue;
posTmp = 0;
tmp[posTmp++] = gg[i];
int v = gg[gg[i]];
while(v != gg[i]) {
tmp[posTmp++] = v;
v = gg[v];
}
int cur = INF;
cerr << i << ' ' << posTmp << endl;
TIMESTAMP;
for(int j = 1; j <= posTmp; j++)
if(posTmp % j == 0)
cur = min(cur, cycles[j]);
for(int j = 0; j < posTmp; j++) {
ans[rr[tmp[j]]] = cur;
cur = gg[cur];
}
}
for(int i = 1; i <= n; i++)
assert(ans[gg[i]] == gg[ans[i]]);
//go(1);
for(int i = 1; i <= n; i++) cout << ans[i] << ' ';
cout << endl;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
#ifdef LOCAL
freopen("xxx.in", "r", stdin);
freopen("xxx.out", "w", stdout);
#else
freopen(TASK".in", "r", stdin);
freopen(TASK".out", "w", stdout);
#endif
input();
solve();
#ifdef LOCAL
TIMESTAMP;
#endif
return 0;
} | 3,031 | 1,571 |
// Handles challenges / current battles
// Copyright David Stone 2020.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <tm/constant_generation.hpp>
| 266 | 95 |
/*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkColorPriv.h"
#include "SkColorSpace_Base.h"
#include "SkColorSpaceXform.h"
#include "SkOpts.h"
static inline bool compute_gamut_xform(SkMatrix44* srcToDst, const SkMatrix44& srcToXYZ,
const SkMatrix44& dstToXYZ) {
if (!dstToXYZ.invert(srcToDst)) {
return false;
}
srcToDst->postConcat(srcToXYZ);
return true;
}
std::unique_ptr<SkColorSpaceXform> SkColorSpaceXform::New(const sk_sp<SkColorSpace>& srcSpace,
const sk_sp<SkColorSpace>& dstSpace) {
if (!srcSpace || !dstSpace) {
// Invalid input
return nullptr;
}
if (as_CSB(dstSpace)->colorLUT()) {
// It would be really weird for a dst profile to have a color LUT. I don't think
// we need to support this.
return nullptr;
}
SkMatrix44 srcToDst(SkMatrix44::kUninitialized_Constructor);
if (!compute_gamut_xform(&srcToDst, srcSpace->xyz(), dstSpace->xyz())) {
return nullptr;
}
if (0.0f == srcToDst.getFloat(3, 0) &&
0.0f == srcToDst.getFloat(3, 1) &&
0.0f == srcToDst.getFloat(3, 2) &&
!as_CSB(srcSpace)->colorLUT())
{
switch (srcSpace->gammaNamed()) {
case SkColorSpace::kSRGB_GammaNamed:
if (SkColorSpace::kSRGB_GammaNamed == dstSpace->gammaNamed()) {
return std::unique_ptr<SkColorSpaceXform>(
new SkFastXform<SkColorSpace::kSRGB_GammaNamed,
SkColorSpace::kSRGB_GammaNamed>(srcToDst));
} else if (SkColorSpace::k2Dot2Curve_GammaNamed == dstSpace->gammaNamed()) {
return std::unique_ptr<SkColorSpaceXform>(
new SkFastXform<SkColorSpace::kSRGB_GammaNamed,
SkColorSpace::k2Dot2Curve_GammaNamed>(srcToDst));
}
break;
case SkColorSpace::k2Dot2Curve_GammaNamed:
if (SkColorSpace::kSRGB_GammaNamed == dstSpace->gammaNamed()) {
return std::unique_ptr<SkColorSpaceXform>(
new SkFastXform<SkColorSpace::k2Dot2Curve_GammaNamed,
SkColorSpace::kSRGB_GammaNamed>(srcToDst));
} else if (SkColorSpace::k2Dot2Curve_GammaNamed == dstSpace->gammaNamed()) {
return std::unique_ptr<SkColorSpaceXform>(
new SkFastXform<SkColorSpace::k2Dot2Curve_GammaNamed,
SkColorSpace::k2Dot2Curve_GammaNamed>(srcToDst));
}
break;
default:
break;
}
}
return std::unique_ptr<SkColorSpaceXform>(new SkDefaultXform(srcSpace, srcToDst, dstSpace));
}
///////////////////////////////////////////////////////////////////////////////////////////////////
static void build_src_to_dst(float srcToDstArray[12], const SkMatrix44& srcToDstMatrix) {
// Build the following row major matrix:
// rX gX bX 0
// rY gY bY 0
// rZ gZ bZ 0
// Swap R and B if necessary to make sure that we output SkPMColor order.
#ifdef SK_PMCOLOR_IS_BGRA
srcToDstArray[0] = srcToDstMatrix.getFloat(0, 2);
srcToDstArray[1] = srcToDstMatrix.getFloat(0, 1);
srcToDstArray[2] = srcToDstMatrix.getFloat(0, 0);
srcToDstArray[3] = 0.0f;
srcToDstArray[4] = srcToDstMatrix.getFloat(1, 2);
srcToDstArray[5] = srcToDstMatrix.getFloat(1, 1);
srcToDstArray[6] = srcToDstMatrix.getFloat(1, 0);
srcToDstArray[7] = 0.0f;
srcToDstArray[8] = srcToDstMatrix.getFloat(2, 2);
srcToDstArray[9] = srcToDstMatrix.getFloat(2, 1);
srcToDstArray[10] = srcToDstMatrix.getFloat(2, 0);
srcToDstArray[11] = 0.0f;
#else
srcToDstArray[0] = srcToDstMatrix.getFloat(0, 0);
srcToDstArray[1] = srcToDstMatrix.getFloat(0, 1);
srcToDstArray[2] = srcToDstMatrix.getFloat(0, 2);
srcToDstArray[3] = 0.0f;
srcToDstArray[4] = srcToDstMatrix.getFloat(1, 0);
srcToDstArray[5] = srcToDstMatrix.getFloat(1, 1);
srcToDstArray[6] = srcToDstMatrix.getFloat(1, 2);
srcToDstArray[7] = 0.0f;
srcToDstArray[8] = srcToDstMatrix.getFloat(2, 0);
srcToDstArray[9] = srcToDstMatrix.getFloat(2, 1);
srcToDstArray[10] = srcToDstMatrix.getFloat(2, 2);
srcToDstArray[11] = 0.0f;
#endif
}
template <SkColorSpace::GammaNamed Src, SkColorSpace::GammaNamed Dst>
SkFastXform<Src, Dst>::SkFastXform(const SkMatrix44& srcToDst)
{
build_src_to_dst(fSrcToDst, srcToDst);
}
template <>
void SkFastXform<SkColorSpace::kSRGB_GammaNamed, SkColorSpace::kSRGB_GammaNamed>
::xform_RGB1_8888(uint32_t* dst, const uint32_t* src, uint32_t len) const
{
SkOpts::color_xform_RGB1_srgb_to_srgb(dst, src, len, fSrcToDst);
}
template <>
void SkFastXform<SkColorSpace::kSRGB_GammaNamed, SkColorSpace::k2Dot2Curve_GammaNamed>
::xform_RGB1_8888(uint32_t* dst, const uint32_t* src, uint32_t len) const
{
SkOpts::color_xform_RGB1_srgb_to_2dot2(dst, src, len, fSrcToDst);
}
template <>
void SkFastXform<SkColorSpace::k2Dot2Curve_GammaNamed, SkColorSpace::kSRGB_GammaNamed>
::xform_RGB1_8888(uint32_t* dst, const uint32_t* src, uint32_t len) const
{
SkOpts::color_xform_RGB1_2dot2_to_srgb(dst, src, len, fSrcToDst);
}
template <>
void SkFastXform<SkColorSpace::k2Dot2Curve_GammaNamed, SkColorSpace::k2Dot2Curve_GammaNamed>
::xform_RGB1_8888(uint32_t* dst, const uint32_t* src, uint32_t len) const
{
SkOpts::color_xform_RGB1_2dot2_to_2dot2(dst, src, len, fSrcToDst);
}
///////////////////////////////////////////////////////////////////////////////////////////////////
extern const float sk_linear_from_srgb[256] = {
0.000000000000000000f, 0.000303526983548838f, 0.000607053967097675f, 0.000910580950646513f,
0.001214107934195350f, 0.001517634917744190f, 0.001821161901293030f, 0.002124688884841860f,
0.002428215868390700f, 0.002731742851939540f, 0.003034518678424960f, 0.003346535763899160f,
0.003676507324047440f, 0.004024717018496310f, 0.004391442037410290f, 0.004776953480693730f,
0.005181516702338390f, 0.005605391624202720f, 0.006048833022857060f, 0.006512090792594470f,
0.006995410187265390f, 0.007499032043226180f, 0.008023192985384990f, 0.008568125618069310f,
0.009134058702220790f, 0.009721217320237850f, 0.010329823029626900f, 0.010960094006488200f,
0.011612245179743900f, 0.012286488356915900f, 0.012983032342173000f, 0.013702083047289700f,
0.014443843596092500f, 0.015208514422912700f, 0.015996293365509600f, 0.016807375752887400f,
0.017641954488384100f, 0.018500220128379700f, 0.019382360956935700f, 0.020288563056652400f,
0.021219010376003600f, 0.022173884793387400f, 0.023153366178110400f, 0.024157632448504800f,
0.025186859627361600f, 0.026241221894849900f, 0.027320891639074900f, 0.028426039504420800f,
0.029556834437808800f, 0.030713443732993600f, 0.031896033073011500f, 0.033104766570885100f,
0.034339806808682200f, 0.035601314875020300f, 0.036889450401100000f, 0.038204371595346500f,
0.039546235276732800f, 0.040915196906853200f, 0.042311410620809700f, 0.043735029256973500f,
0.045186204385675500f, 0.046665086336880100f, 0.048171824226889400f, 0.049706565984127200f,
0.051269458374043200f, 0.052860647023180200f, 0.054480276442442400f, 0.056128490049600100f,
0.057805430191067200f, 0.059511238162981200f, 0.061246054231617600f, 0.063010017653167700f,
0.064803266692905800f, 0.066625938643772900f, 0.068478169844400200f, 0.070360095696595900f,
0.072271850682317500f, 0.074213568380149600f, 0.076185381481307900f, 0.078187421805186300f,
0.080219820314468300f, 0.082282707129814800f, 0.084376211544148800f, 0.086500462036549800f,
0.088655586285772900f, 0.090841711183407700f, 0.093058962846687500f, 0.095307466630964700f,
0.097587347141862500f, 0.099898728247113900f, 0.102241733088101000f, 0.104616484091104000f,
0.107023102978268000f, 0.109461710778299000f, 0.111932427836906000f, 0.114435373826974000f,
0.116970667758511000f, 0.119538427988346000f, 0.122138772229602000f, 0.124771817560950000f,
0.127437680435647000f, 0.130136476690364000f, 0.132868321553818000f, 0.135633329655206000f,
0.138431615032452000f, 0.141263291140272000f, 0.144128470858058000f, 0.147027266497595000f,
0.149959789810609000f, 0.152926151996150000f, 0.155926463707827000f, 0.158960835060880000f,
0.162029375639111000f, 0.165132194501668000f, 0.168269400189691000f, 0.171441100732823000f,
0.174647403655585000f, 0.177888415983629000f, 0.181164244249860000f, 0.184474994500441000f,
0.187820772300678000f, 0.191201682740791000f, 0.194617830441576000f, 0.198069319559949000f,
0.201556253794397000f, 0.205078736390317000f, 0.208636870145256000f, 0.212230757414055000f,
0.215860500113899000f, 0.219526199729269000f, 0.223227957316809000f, 0.226965873510098000f,
0.230740048524349000f, 0.234550582161005000f, 0.238397573812271000f, 0.242281122465555000f,
0.246201326707835000f, 0.250158284729953000f, 0.254152094330827000f, 0.258182852921596000f,
0.262250657529696000f, 0.266355604802862000f, 0.270497791013066000f, 0.274677312060385000f,
0.278894263476810000f, 0.283148740429992000f, 0.287440837726918000f, 0.291770649817536000f,
0.296138270798321000f, 0.300543794415777000f, 0.304987314069886000f, 0.309468922817509000f,
0.313988713375718000f, 0.318546778125092000f, 0.323143209112951000f, 0.327778098056542000f,
0.332451536346179000f, 0.337163615048330000f, 0.341914424908661000f, 0.346704056355030000f,
0.351532599500439000f, 0.356400144145944000f, 0.361306779783510000f, 0.366252595598840000f,
0.371237680474149000f, 0.376262122990906000f, 0.381326011432530000f, 0.386429433787049000f,
0.391572477749723000f, 0.396755230725627000f, 0.401977779832196000f, 0.407240211901737000f,
0.412542613483904000f, 0.417885070848138000f, 0.423267669986072000f, 0.428690496613907000f,
0.434153636174749000f, 0.439657173840919000f, 0.445201194516228000f, 0.450785782838223000f,
0.456411023180405000f, 0.462076999654407000f, 0.467783796112159000f, 0.473531496148010000f,
0.479320183100827000f, 0.485149940056070000f, 0.491020849847836000f, 0.496932995060870000f,
0.502886458032569000f, 0.508881320854934000f, 0.514917665376521000f, 0.520995573204354000f,
0.527115125705813000f, 0.533276404010505000f, 0.539479489012107000f, 0.545724461370187000f,
0.552011401512000000f, 0.558340389634268000f, 0.564711505704929000f, 0.571124829464873000f,
0.577580440429651000f, 0.584078417891164000f, 0.590618840919337000f, 0.597201788363763000f,
0.603827338855338000f, 0.610495570807865000f, 0.617206562419651000f, 0.623960391675076000f,
0.630757136346147000f, 0.637596873994033000f, 0.644479681970582000f, 0.651405637419824000f,
0.658374817279448000f, 0.665387298282272000f, 0.672443156957688000f, 0.679542469633094000f,
0.686685312435314000f, 0.693871761291990000f, 0.701101891932973000f, 0.708375779891687000f,
0.715693500506481000f, 0.723055128921969000f, 0.730460740090354000f, 0.737910408772731000f,
0.745404209540387000f, 0.752942216776078000f, 0.760524504675292000f, 0.768151147247507000f,
0.775822218317423000f, 0.783537791526194000f, 0.791297940332630000f, 0.799102738014409000f,
0.806952257669252000f, 0.814846572216101000f, 0.822785754396284000f, 0.830769876774655000f,
0.838799011740740000f, 0.846873231509858000f, 0.854992608124234000f, 0.863157213454102000f,
0.871367119198797000f, 0.879622396887832000f, 0.887923117881966000f, 0.896269353374266000f,
0.904661174391149000f, 0.913098651793419000f, 0.921581856277295000f, 0.930110858375424000f,
0.938685728457888000f, 0.947306536733200000f, 0.955973353249286000f, 0.964686247894465000f,
0.973445290398413000f, 0.982250550333117000f, 0.991102097113830000f, 1.000000000000000000f,
};
extern const float sk_linear_from_2dot2[256] = {
0.000000000000000000f, 0.000005077051900662f, 0.000023328004666099f, 0.000056921765712193f,
0.000107187362341244f, 0.000175123977503027f, 0.000261543754548491f, 0.000367136269815943f,
0.000492503787191433f, 0.000638182842167022f, 0.000804658499513058f, 0.000992374304074325f,
0.001201739522438400f, 0.001433134589671860f, 0.001686915316789280f, 0.001963416213396470f,
0.002262953160706430f, 0.002585825596234170f, 0.002932318323938360f, 0.003302703032003640f,
0.003697239578900130f, 0.004116177093282750f, 0.004559754922526020f, 0.005028203456855540f,
0.005521744850239660f, 0.006040593654849810f, 0.006584957382581690f, 0.007155037004573030f,
0.007751027397660610f, 0.008373117745148580f, 0.009021491898012130f, 0.009696328701658230f,
0.010397802292555300f, 0.011126082368383200f, 0.011881334434813700f, 0.012663720031582100f,
0.013473396940142600f, 0.014310519374884100f, 0.015175238159625200f, 0.016067700890886900f,
0.016988052089250000f, 0.017936433339950200f, 0.018912983423721500f, 0.019917838438785700f,
0.020951131914781100f, 0.022012994919336500f, 0.023103556157921400f, 0.024222942067534200f,
0.025371276904734600f, 0.026548682828472900f, 0.027755279978126000f, 0.028991186547107800f,
0.030256518852388700f, 0.031551391400226400f, 0.032875916948383800f, 0.034230206565082000f,
0.035614369684918800f, 0.037028514161960200f, 0.038472746320194600f, 0.039947171001525600f,
0.041451891611462500f, 0.042987010162657100f, 0.044552627316421400f, 0.046148842422351000f,
0.047775753556170600f, 0.049433457555908000f, 0.051122050056493400f, 0.052841625522879000f,
0.054592277281760300f, 0.056374097551979800f, 0.058187177473685400f, 0.060031607136313200f,
0.061907475605455800f, 0.063814870948677200f, 0.065753880260330100f, 0.067724589685424300f,
0.069727084442598800f, 0.071761448846239100f, 0.073827766327784600f, 0.075926119456264800f,
0.078056589958101900f, 0.080219258736215100f, 0.082414205888459200f, 0.084641510725429500f,
0.086901251787660300f, 0.089193506862247800f, 0.091518352998919500f, 0.093875866525577800f,
0.096266123063339700f, 0.098689197541094500f, 0.101145164209600000f, 0.103634096655137000f,
0.106156067812744000f, 0.108711149979039000f, 0.111299414824660000f, 0.113920933406333000f,
0.116575776178572000f, 0.119264013005047000f, 0.121985713169619000f, 0.124740945387051000f,
0.127529777813422000f, 0.130352278056244000f, 0.133208513184300000f, 0.136098549737202000f,
0.139022453734703000f, 0.141980290685736000f, 0.144972125597231000f, 0.147998022982685000f,
0.151058046870511000f, 0.154152260812165000f, 0.157280727890073000f, 0.160443510725344000f,
0.163640671485290000f, 0.166872271890766000f, 0.170138373223312000f, 0.173439036332135000f,
0.176774321640903000f, 0.180144289154390000f, 0.183548998464951000f, 0.186988508758844000f,
0.190462878822409000f, 0.193972167048093000f, 0.197516431440340000f, 0.201095729621346000f,
0.204710118836677000f, 0.208359655960767000f, 0.212044397502288000f, 0.215764399609395000f,
0.219519718074868000f, 0.223310408341127000f, 0.227136525505149000f, 0.230998124323267000f,
0.234895259215880000f, 0.238827984272048000f, 0.242796353254002000f, 0.246800419601550000f,
0.250840236436400000f, 0.254915856566385000f, 0.259027332489606000f, 0.263174716398492000f,
0.267358060183772000f, 0.271577415438375000f, 0.275832833461245000f, 0.280124365261085000f,
0.284452061560024000f, 0.288815972797219000f, 0.293216149132375000f, 0.297652640449211000f,
0.302125496358853000f, 0.306634766203158000f, 0.311180499057984000f, 0.315762743736397000f,
0.320381548791810000f, 0.325036962521076000f, 0.329729032967515000f, 0.334457807923889000f,
0.339223334935327000f, 0.344025661302187000f, 0.348864834082879000f, 0.353740900096629000f,
0.358653905926199000f, 0.363603897920553000f, 0.368590922197487000f, 0.373615024646202000f,
0.378676250929840000f, 0.383774646487975000f, 0.388910256539059000f, 0.394083126082829000f,
0.399293299902674000f, 0.404540822567962000f, 0.409825738436323000f, 0.415148091655907000f,
0.420507926167587000f, 0.425905285707146000f, 0.431340213807410000f, 0.436812753800359000f,
0.442322948819202000f, 0.447870841800410000f, 0.453456475485731000f, 0.459079892424160000f,
0.464741134973889000f, 0.470440245304218000f, 0.476177265397440000f, 0.481952237050698000f,
0.487765201877811000f, 0.493616201311074000f, 0.499505276603030000f, 0.505432468828216000f,
0.511397818884880000f, 0.517401367496673000f, 0.523443155214325000f, 0.529523222417277000f,
0.535641609315311000f, 0.541798355950137000f, 0.547993502196972000f, 0.554227087766085000f,
0.560499152204328000f, 0.566809734896638000f, 0.573158875067523000f, 0.579546611782525000f,
0.585972983949661000f, 0.592438030320847000f, 0.598941789493296000f, 0.605484299910907000f,
0.612065599865624000f, 0.618685727498780000f, 0.625344720802427000f, 0.632042617620641000f,
0.638779455650817000f, 0.645555272444935000f, 0.652370105410821000f, 0.659223991813387000f,
0.666116968775851000f, 0.673049073280942000f, 0.680020342172095000f, 0.687030812154625000f,
0.694080519796882000f, 0.701169501531402000f, 0.708297793656032000f, 0.715465432335048000f,
0.722672453600255000f, 0.729918893352071000f, 0.737204787360605000f, 0.744530171266715000f,
0.751895080583051000f, 0.759299550695091000f, 0.766743616862161000f, 0.774227314218442000f,
0.781750677773962000f, 0.789313742415586000f, 0.796916542907978000f, 0.804559113894567000f,
0.812241489898490000f, 0.819963705323528000f, 0.827725794455034000f, 0.835527791460841000f,
0.843369730392169000f, 0.851251645184515000f, 0.859173569658532000f, 0.867135537520905000f,
0.875137582365205000f, 0.883179737672745000f, 0.891262036813419000f, 0.899384513046529000f,
0.907547199521614000f, 0.915750129279253000f, 0.923993335251873000f, 0.932276850264543000f,
0.940600707035753000f, 0.948964938178195000f, 0.957369576199527000f, 0.965814653503130000f,
0.974300202388861000f, 0.982826255053791000f, 0.991392843592940000f, 1.000000000000000000f,
};
static void build_table_linear_from_gamma(float* outTable, float exponent) {
for (float x = 0.0f; x <= 1.0f; x += (1.0f/255.0f)) {
*outTable++ = powf(x, exponent);
}
}
// Interpolating lookup in a variably sized table.
static float interp_lut(float input, const float* table, int tableSize) {
float index = input * (tableSize - 1);
float diff = index - sk_float_floor2int(index);
return table[(int) sk_float_floor2int(index)] * (1.0f - diff) +
table[(int) sk_float_ceil2int(index)] * diff;
}
// outTable is always 256 entries, inTable may be larger or smaller.
static void build_table_linear_from_gamma(float* outTable, const float* inTable,
int inTableSize) {
if (256 == inTableSize) {
memcpy(outTable, inTable, sizeof(float) * 256);
return;
}
for (float x = 0.0f; x <= 1.0f; x += (1.0f/255.0f)) {
*outTable++ = interp_lut(x, inTable, inTableSize);
}
}
static void build_table_linear_from_gamma(float* outTable, float g, float a, float b, float c,
float d, float e, float f) {
// Y = (aX + b)^g + c for X >= d
// Y = eX + f otherwise
for (float x = 0.0f; x <= 1.0f; x += (1.0f/255.0f)) {
if (x >= d) {
*outTable++ = powf(a * x + b, g) + c;
} else {
*outTable++ = e * x + f;
}
}
}
static constexpr uint8_t linear_to_srgb[1024] = {
0, 3, 6, 10, 13, 15, 18, 20, 22, 23, 25, 27, 28, 30, 31, 32, 34, 35,
36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 49, 50, 51, 52,
53, 53, 54, 55, 56, 56, 57, 58, 58, 59, 60, 61, 61, 62, 62, 63, 64, 64,
65, 66, 66, 67, 67, 68, 68, 69, 70, 70, 71, 71, 72, 72, 73, 73, 74, 74,
75, 76, 76, 77, 77, 78, 78, 79, 79, 79, 80, 80, 81, 81, 82, 82, 83, 83,
84, 84, 85, 85, 85, 86, 86, 87, 87, 88, 88, 88, 89, 89, 90, 90, 91, 91,
91, 92, 92, 93, 93, 93, 94, 94, 95, 95, 95, 96, 96, 97, 97, 97, 98, 98,
98, 99, 99, 99, 100, 100, 101, 101, 101, 102, 102, 102, 103, 103, 103, 104, 104, 104,
105, 105, 106, 106, 106, 107, 107, 107, 108, 108, 108, 109, 109, 109, 110, 110, 110, 110,
111, 111, 111, 112, 112, 112, 113, 113, 113, 114, 114, 114, 115, 115, 115, 115, 116, 116,
116, 117, 117, 117, 118, 118, 118, 118, 119, 119, 119, 120, 120, 120, 121, 121, 121, 121,
122, 122, 122, 123, 123, 123, 123, 124, 124, 124, 125, 125, 125, 125, 126, 126, 126, 126,
127, 127, 127, 128, 128, 128, 128, 129, 129, 129, 129, 130, 130, 130, 130, 131, 131, 131,
131, 132, 132, 132, 133, 133, 133, 133, 134, 134, 134, 134, 135, 135, 135, 135, 136, 136,
136, 136, 137, 137, 137, 137, 138, 138, 138, 138, 138, 139, 139, 139, 139, 140, 140, 140,
140, 141, 141, 141, 141, 142, 142, 142, 142, 143, 143, 143, 143, 143, 144, 144, 144, 144,
145, 145, 145, 145, 146, 146, 146, 146, 146, 147, 147, 147, 147, 148, 148, 148, 148, 148,
149, 149, 149, 149, 150, 150, 150, 150, 150, 151, 151, 151, 151, 152, 152, 152, 152, 152,
153, 153, 153, 153, 153, 154, 154, 154, 154, 155, 155, 155, 155, 155, 156, 156, 156, 156,
156, 157, 157, 157, 157, 157, 158, 158, 158, 158, 158, 159, 159, 159, 159, 159, 160, 160,
160, 160, 160, 161, 161, 161, 161, 161, 162, 162, 162, 162, 162, 163, 163, 163, 163, 163,
164, 164, 164, 164, 164, 165, 165, 165, 165, 165, 166, 166, 166, 166, 166, 167, 167, 167,
167, 167, 168, 168, 168, 168, 168, 168, 169, 169, 169, 169, 169, 170, 170, 170, 170, 170,
171, 171, 171, 171, 171, 171, 172, 172, 172, 172, 172, 173, 173, 173, 173, 173, 173, 174,
174, 174, 174, 174, 175, 175, 175, 175, 175, 175, 176, 176, 176, 176, 176, 177, 177, 177,
177, 177, 177, 178, 178, 178, 178, 178, 178, 179, 179, 179, 179, 179, 179, 180, 180, 180,
180, 180, 181, 181, 181, 181, 181, 181, 182, 182, 182, 182, 182, 182, 183, 183, 183, 183,
183, 183, 184, 184, 184, 184, 184, 184, 185, 185, 185, 185, 185, 185, 186, 186, 186, 186,
186, 186, 187, 187, 187, 187, 187, 187, 188, 188, 188, 188, 188, 188, 189, 189, 189, 189,
189, 189, 190, 190, 190, 190, 190, 190, 191, 191, 191, 191, 191, 191, 191, 192, 192, 192,
192, 192, 192, 193, 193, 193, 193, 193, 193, 194, 194, 194, 194, 194, 194, 194, 195, 195,
195, 195, 195, 195, 196, 196, 196, 196, 196, 196, 197, 197, 197, 197, 197, 197, 197, 198,
198, 198, 198, 198, 198, 199, 199, 199, 199, 199, 199, 199, 200, 200, 200, 200, 200, 200,
200, 201, 201, 201, 201, 201, 201, 202, 202, 202, 202, 202, 202, 202, 203, 203, 203, 203,
203, 203, 203, 204, 204, 204, 204, 204, 204, 204, 205, 205, 205, 205, 205, 205, 206, 206,
206, 206, 206, 206, 206, 207, 207, 207, 207, 207, 207, 207, 208, 208, 208, 208, 208, 208,
208, 209, 209, 209, 209, 209, 209, 209, 210, 210, 210, 210, 210, 210, 210, 211, 211, 211,
211, 211, 211, 211, 212, 212, 212, 212, 212, 212, 212, 212, 213, 213, 213, 213, 213, 213,
213, 214, 214, 214, 214, 214, 214, 214, 215, 215, 215, 215, 215, 215, 215, 216, 216, 216,
216, 216, 216, 216, 216, 217, 217, 217, 217, 217, 217, 217, 218, 218, 218, 218, 218, 218,
218, 219, 219, 219, 219, 219, 219, 219, 219, 220, 220, 220, 220, 220, 220, 220, 221, 221,
221, 221, 221, 221, 221, 221, 222, 222, 222, 222, 222, 222, 222, 222, 223, 223, 223, 223,
223, 223, 223, 224, 224, 224, 224, 224, 224, 224, 224, 225, 225, 225, 225, 225, 225, 225,
225, 226, 226, 226, 226, 226, 226, 226, 227, 227, 227, 227, 227, 227, 227, 227, 228, 228,
228, 228, 228, 228, 228, 228, 229, 229, 229, 229, 229, 229, 229, 229, 230, 230, 230, 230,
230, 230, 230, 230, 231, 231, 231, 231, 231, 231, 231, 231, 232, 232, 232, 232, 232, 232,
232, 232, 233, 233, 233, 233, 233, 233, 233, 233, 234, 234, 234, 234, 234, 234, 234, 234,
235, 235, 235, 235, 235, 235, 235, 235, 236, 236, 236, 236, 236, 236, 236, 236, 236, 237,
237, 237, 237, 237, 237, 237, 237, 238, 238, 238, 238, 238, 238, 238, 238, 239, 239, 239,
239, 239, 239, 239, 239, 239, 240, 240, 240, 240, 240, 240, 240, 240, 241, 241, 241, 241,
241, 241, 241, 241, 241, 242, 242, 242, 242, 242, 242, 242, 242, 243, 243, 243, 243, 243,
243, 243, 243, 243, 244, 244, 244, 244, 244, 244, 244, 244, 245, 245, 245, 245, 245, 245,
245, 245, 245, 246, 246, 246, 246, 246, 246, 246, 246, 246, 247, 247, 247, 247, 247, 247,
247, 247, 248, 248, 248, 248, 248, 248, 248, 248, 248, 249, 249, 249, 249, 249, 249, 249,
249, 249, 250, 250, 250, 250, 250, 250, 250, 250, 250, 251, 251, 251, 251, 251, 251, 251,
251, 251, 252, 252, 252, 252, 252, 252, 252, 252, 252, 253, 253, 253, 253, 253, 253, 253,
253, 253, 254, 254, 254, 254, 254, 254, 254, 254, 254, 255, 255, 255, 255, 255
};
static constexpr uint8_t linear_to_2dot2[1024] = {
0, 11, 15, 18, 21, 23, 25, 26, 28, 30, 31, 32, 34, 35, 36, 37, 39, 40,
41, 42, 43, 44, 45, 45, 46, 47, 48, 49, 50, 50, 51, 52, 53, 54, 54, 55,
56, 56, 57, 58, 58, 59, 60, 60, 61, 62, 62, 63, 63, 64, 65, 65, 66, 66,
67, 68, 68, 69, 69, 70, 70, 71, 71, 72, 72, 73, 73, 74, 74, 75, 75, 76,
76, 77, 77, 78, 78, 79, 79, 80, 80, 81, 81, 81, 82, 82, 83, 83, 84, 84,
84, 85, 85, 86, 86, 87, 87, 87, 88, 88, 89, 89, 89, 90, 90, 91, 91, 91,
92, 92, 93, 93, 93, 94, 94, 94, 95, 95, 96, 96, 96, 97, 97, 97, 98, 98,
98, 99, 99, 99, 100, 100, 101, 101, 101, 102, 102, 102, 103, 103, 103, 104, 104, 104,
105, 105, 105, 106, 106, 106, 107, 107, 107, 108, 108, 108, 108, 109, 109, 109, 110, 110,
110, 111, 111, 111, 112, 112, 112, 112, 113, 113, 113, 114, 114, 114, 115, 115, 115, 115,
116, 116, 116, 117, 117, 117, 117, 118, 118, 118, 119, 119, 119, 119, 120, 120, 120, 121,
121, 121, 121, 122, 122, 122, 123, 123, 123, 123, 124, 124, 124, 124, 125, 125, 125, 125,
126, 126, 126, 127, 127, 127, 127, 128, 128, 128, 128, 129, 129, 129, 129, 130, 130, 130,
130, 131, 131, 131, 131, 132, 132, 132, 132, 133, 133, 133, 133, 134, 134, 134, 134, 135,
135, 135, 135, 136, 136, 136, 136, 137, 137, 137, 137, 138, 138, 138, 138, 138, 139, 139,
139, 139, 140, 140, 140, 140, 141, 141, 141, 141, 142, 142, 142, 142, 142, 143, 143, 143,
143, 144, 144, 144, 144, 144, 145, 145, 145, 145, 146, 146, 146, 146, 146, 147, 147, 147,
147, 148, 148, 148, 148, 148, 149, 149, 149, 149, 149, 150, 150, 150, 150, 151, 151, 151,
151, 151, 152, 152, 152, 152, 152, 153, 153, 153, 153, 154, 154, 154, 154, 154, 155, 155,
155, 155, 155, 156, 156, 156, 156, 156, 157, 157, 157, 157, 157, 158, 158, 158, 158, 158,
159, 159, 159, 159, 159, 160, 160, 160, 160, 160, 161, 161, 161, 161, 161, 162, 162, 162,
162, 162, 163, 163, 163, 163, 163, 164, 164, 164, 164, 164, 165, 165, 165, 165, 165, 165,
166, 166, 166, 166, 166, 167, 167, 167, 167, 167, 168, 168, 168, 168, 168, 168, 169, 169,
169, 169, 169, 170, 170, 170, 170, 170, 171, 171, 171, 171, 171, 171, 172, 172, 172, 172,
172, 173, 173, 173, 173, 173, 173, 174, 174, 174, 174, 174, 174, 175, 175, 175, 175, 175,
176, 176, 176, 176, 176, 176, 177, 177, 177, 177, 177, 177, 178, 178, 178, 178, 178, 179,
179, 179, 179, 179, 179, 180, 180, 180, 180, 180, 180, 181, 181, 181, 181, 181, 181, 182,
182, 182, 182, 182, 182, 183, 183, 183, 183, 183, 183, 184, 184, 184, 184, 184, 185, 185,
185, 185, 185, 185, 186, 186, 186, 186, 186, 186, 186, 187, 187, 187, 187, 187, 187, 188,
188, 188, 188, 188, 188, 189, 189, 189, 189, 189, 189, 190, 190, 190, 190, 190, 190, 191,
191, 191, 191, 191, 191, 192, 192, 192, 192, 192, 192, 192, 193, 193, 193, 193, 193, 193,
194, 194, 194, 194, 194, 194, 195, 195, 195, 195, 195, 195, 195, 196, 196, 196, 196, 196,
196, 197, 197, 197, 197, 197, 197, 197, 198, 198, 198, 198, 198, 198, 199, 199, 199, 199,
199, 199, 199, 200, 200, 200, 200, 200, 200, 201, 201, 201, 201, 201, 201, 201, 202, 202,
202, 202, 202, 202, 202, 203, 203, 203, 203, 203, 203, 204, 204, 204, 204, 204, 204, 204,
205, 205, 205, 205, 205, 205, 205, 206, 206, 206, 206, 206, 206, 206, 207, 207, 207, 207,
207, 207, 207, 208, 208, 208, 208, 208, 208, 209, 209, 209, 209, 209, 209, 209, 210, 210,
210, 210, 210, 210, 210, 211, 211, 211, 211, 211, 211, 211, 212, 212, 212, 212, 212, 212,
212, 213, 213, 213, 213, 213, 213, 213, 213, 214, 214, 214, 214, 214, 214, 214, 215, 215,
215, 215, 215, 215, 215, 216, 216, 216, 216, 216, 216, 216, 217, 217, 217, 217, 217, 217,
217, 218, 218, 218, 218, 218, 218, 218, 218, 219, 219, 219, 219, 219, 219, 219, 220, 220,
220, 220, 220, 220, 220, 221, 221, 221, 221, 221, 221, 221, 221, 222, 222, 222, 222, 222,
222, 222, 223, 223, 223, 223, 223, 223, 223, 223, 224, 224, 224, 224, 224, 224, 224, 225,
225, 225, 225, 225, 225, 225, 225, 226, 226, 226, 226, 226, 226, 226, 226, 227, 227, 227,
227, 227, 227, 227, 228, 228, 228, 228, 228, 228, 228, 228, 229, 229, 229, 229, 229, 229,
229, 229, 230, 230, 230, 230, 230, 230, 230, 230, 231, 231, 231, 231, 231, 231, 231, 232,
232, 232, 232, 232, 232, 232, 232, 233, 233, 233, 233, 233, 233, 233, 233, 234, 234, 234,
234, 234, 234, 234, 234, 235, 235, 235, 235, 235, 235, 235, 235, 236, 236, 236, 236, 236,
236, 236, 236, 237, 237, 237, 237, 237, 237, 237, 237, 238, 238, 238, 238, 238, 238, 238,
238, 238, 239, 239, 239, 239, 239, 239, 239, 239, 240, 240, 240, 240, 240, 240, 240, 240,
241, 241, 241, 241, 241, 241, 241, 241, 242, 242, 242, 242, 242, 242, 242, 242, 243, 243,
243, 243, 243, 243, 243, 243, 243, 244, 244, 244, 244, 244, 244, 244, 244, 245, 245, 245,
245, 245, 245, 245, 245, 245, 246, 246, 246, 246, 246, 246, 246, 246, 247, 247, 247, 247,
247, 247, 247, 247, 248, 248, 248, 248, 248, 248, 248, 248, 248, 249, 249, 249, 249, 249,
249, 249, 249, 249, 250, 250, 250, 250, 250, 250, 250, 250, 251, 251, 251, 251, 251, 251,
251, 251, 251, 252, 252, 252, 252, 252, 252, 252, 252, 252, 253, 253, 253, 253, 253, 253,
253, 253, 254, 254, 254, 254, 254, 254, 254, 254, 254, 255, 255, 255, 255, 255,
};
// Expand range from 0-1 to 0-255, then convert.
static uint8_t clamp_normalized_float_to_byte(float v) {
// The ordering of the logic is a little strange here in order
// to make sure we convert NaNs to 0.
v = v * 255.0f;
if (v >= 254.5f) {
return 255;
} else if (v >= 0.5f) {
return (uint8_t) (v + 0.5f);
} else {
return 0;
}
}
static void build_table_linear_to_gamma(uint8_t* outTable, int outTableSize, float exponent) {
float toGammaExp = 1.0f / exponent;
for (int i = 0; i < outTableSize; i++) {
float x = ((float) i) * (1.0f / ((float) (outTableSize - 1)));
outTable[i] = clamp_normalized_float_to_byte(powf(x, toGammaExp));
}
}
// Inverse table lookup. Ex: what index corresponds to the input value? This will
// have strange results when the table is non-increasing. But any sane gamma
// function will be increasing.
static float inverse_interp_lut(float input, float* table, int tableSize) {
if (input <= table[0]) {
return table[0];
} else if (input >= table[tableSize - 1]) {
return 1.0f;
}
for (int i = 1; i < tableSize; i++) {
if (table[i] >= input) {
// We are guaranteed that input is greater than table[i - 1].
float diff = input - table[i - 1];
float distance = table[i] - table[i - 1];
float index = (i - 1) + diff / distance;
return index / (tableSize - 1);
}
}
// Should be unreachable, since we'll return before the loop if input is
// larger than the last entry.
SkASSERT(false);
return 0.0f;
}
static void build_table_linear_to_gamma(uint8_t* outTable, int outTableSize, float* inTable,
int inTableSize) {
for (int i = 0; i < outTableSize; i++) {
float x = ((float) i) * (1.0f / ((float) (outTableSize - 1)));
float y = inverse_interp_lut(x, inTable, inTableSize);
outTable[i] = clamp_normalized_float_to_byte(y);
}
}
static float inverse_parametric(float x, float g, float a, float b, float c, float d, float e,
float f) {
// We need to take the inverse of the following piecewise function.
// Y = (aX + b)^g + c for X >= d
// Y = eX + f otherwise
// Assume that the gamma function is continuous, or this won't make much sense anyway.
// Plug in |d| to the first equation to calculate the new piecewise interval.
// Then simply use the inverse of the original functions.
float interval = e * d + f;
if (x < interval) {
// X = (Y - F) / E
if (0.0f == e) {
// The gamma curve for this segment is constant, so the inverse is undefined.
// Since this is the lower segment, guess zero.
return 0.0f;
}
return (x - f) / e;
}
// X = ((Y - C)^(1 / G) - B) / A
if (0.0f == a || 0.0f == g) {
// The gamma curve for this segment is constant, so the inverse is undefined.
// Since this is the upper segment, guess one.
return 1.0f;
}
return (powf(x - c, 1.0f / g) - b) / a;
}
static void build_table_linear_to_gamma(uint8_t* outTable, int outTableSize, float g, float a,
float b, float c, float d, float e, float f) {
for (int i = 0; i < outTableSize; i++) {
float x = ((float) i) * (1.0f / ((float) (outTableSize - 1)));
float y = inverse_parametric(x, g, a, b, c, d, e, f);
outTable[i] = clamp_normalized_float_to_byte(y);
}
}
SkDefaultXform::SkDefaultXform(const sk_sp<SkColorSpace>& srcSpace, const SkMatrix44& srcToDst,
const sk_sp<SkColorSpace>& dstSpace)
: fColorLUT(sk_ref_sp((SkColorLookUpTable*) as_CSB(srcSpace)->colorLUT()))
, fSrcToDst(srcToDst)
{
// Build tables to transform src gamma to linear.
switch (srcSpace->gammaNamed()) {
case SkColorSpace::kSRGB_GammaNamed:
fSrcGammaTables[0] = fSrcGammaTables[1] = fSrcGammaTables[2] = sk_linear_from_srgb;
break;
case SkColorSpace::k2Dot2Curve_GammaNamed:
fSrcGammaTables[0] = fSrcGammaTables[1] = fSrcGammaTables[2] = sk_linear_from_2dot2;
break;
case SkColorSpace::kLinear_GammaNamed:
build_table_linear_from_gamma(fSrcGammaTableStorage, 1.0f);
fSrcGammaTables[0] = fSrcGammaTables[1] = fSrcGammaTables[2] = fSrcGammaTableStorage;
break;
default: {
const SkGammas* gammas = as_CSB(srcSpace)->gammas();
SkASSERT(gammas);
for (int i = 0; i < 3; i++) {
const SkGammaCurve& curve = (*gammas)[i];
if (i > 0) {
// Check if this curve matches the first curve. In this case, we can
// share the same table pointer. Logically, this should almost always
// be true. I've never seen a profile where all three gamma curves
// didn't match. But it is possible that they won't.
// TODO (msarett):
// This comparison won't catch the case where each gamma curve has a
// pointer to its own look-up table, but the tables actually match.
// Should we perform a deep compare of gamma tables here? Or should
// we catch this when parsing the profile? Or should we not worry
// about a bit of redundant work?
if (curve.quickEquals((*gammas)[0])) {
fSrcGammaTables[i] = fSrcGammaTables[0];
continue;
}
}
if (curve.isNamed()) {
switch (curve.fNamed) {
case SkColorSpace::kSRGB_GammaNamed:
fSrcGammaTables[i] = sk_linear_from_srgb;
break;
case SkColorSpace::k2Dot2Curve_GammaNamed:
fSrcGammaTables[i] = sk_linear_from_2dot2;
break;
case SkColorSpace::kLinear_GammaNamed:
build_table_linear_from_gamma(&fSrcGammaTableStorage[i * 256], 1.0f);
fSrcGammaTables[i] = &fSrcGammaTableStorage[i * 256];
break;
default:
SkASSERT(false);
break;
}
} else if (curve.isValue()) {
build_table_linear_from_gamma(&fSrcGammaTableStorage[i * 256], curve.fValue);
fSrcGammaTables[i] = &fSrcGammaTableStorage[i * 256];
} else if (curve.isTable()) {
build_table_linear_from_gamma(&fSrcGammaTableStorage[i * 256],
curve.fTable.get(), curve.fTableSize);
fSrcGammaTables[i] = &fSrcGammaTableStorage[i * 256];
} else {
SkASSERT(curve.isParametric());
build_table_linear_from_gamma(&fSrcGammaTableStorage[i * 256], curve.fG,
curve.fA, curve.fB, curve.fC, curve.fD, curve.fE,
curve.fF);
fSrcGammaTables[i] = &fSrcGammaTableStorage[i * 256];
}
}
}
}
// Build tables to transform linear to dst gamma.
switch (dstSpace->gammaNamed()) {
case SkColorSpace::kSRGB_GammaNamed:
fDstGammaTables[0] = fDstGammaTables[1] = fDstGammaTables[2] = linear_to_srgb;
break;
case SkColorSpace::k2Dot2Curve_GammaNamed:
fDstGammaTables[0] = fDstGammaTables[1] = fDstGammaTables[2] = linear_to_2dot2;
break;
case SkColorSpace::kLinear_GammaNamed:
build_table_linear_to_gamma(fDstGammaTableStorage, kDstGammaTableSize, 1.0f);
fDstGammaTables[0] = fDstGammaTables[1] = fDstGammaTables[2] = fDstGammaTableStorage;
break;
default: {
const SkGammas* gammas = as_CSB(dstSpace)->gammas();
SkASSERT(gammas);
for (int i = 0; i < 3; i++) {
const SkGammaCurve& curve = (*gammas)[i];
if (i > 0) {
// Check if this curve matches the first curve. In this case, we can
// share the same table pointer. Logically, this should almost always
// be true. I've never seen a profile where all three gamma curves
// didn't match. But it is possible that they won't.
// TODO (msarett):
// This comparison won't catch the case where each gamma curve has a
// pointer to its own look-up table (but the tables actually match).
// Should we perform a deep compare of gamma tables here? Or should
// we catch this when parsing the profile? Or should we not worry
// about a bit of redundant work?
if (curve.quickEquals((*gammas)[0])) {
fDstGammaTables[i] = fDstGammaTables[0];
continue;
}
}
if (curve.isNamed()) {
switch (curve.fNamed) {
case SkColorSpace::kSRGB_GammaNamed:
fDstGammaTables[i] = linear_to_srgb;
break;
case SkColorSpace::k2Dot2Curve_GammaNamed:
fDstGammaTables[i] = linear_to_2dot2;
break;
case SkColorSpace::kLinear_GammaNamed:
build_table_linear_to_gamma(
&fDstGammaTableStorage[i * kDstGammaTableSize],
kDstGammaTableSize, 1.0f);
fDstGammaTables[i] = &fDstGammaTableStorage[i * kDstGammaTableSize];
break;
default:
SkASSERT(false);
break;
}
} else if (curve.isValue()) {
build_table_linear_to_gamma(&fDstGammaTableStorage[i * kDstGammaTableSize],
kDstGammaTableSize, curve.fValue);
fDstGammaTables[i] = &fDstGammaTableStorage[i * kDstGammaTableSize];
} else if (curve.isTable()) {
build_table_linear_to_gamma(&fDstGammaTableStorage[i * kDstGammaTableSize],
kDstGammaTableSize, curve.fTable.get(),
curve.fTableSize);
fDstGammaTables[i] = &fDstGammaTableStorage[i * kDstGammaTableSize];
} else {
SkASSERT(curve.isParametric());
build_table_linear_to_gamma(&fDstGammaTableStorage[i * kDstGammaTableSize],
kDstGammaTableSize, curve.fG, curve.fA, curve.fB,
curve.fC, curve.fD, curve.fE, curve.fF);
fDstGammaTables[i] = &fDstGammaTableStorage[i * kDstGammaTableSize];
}
}
}
}
}
static float byte_to_float(uint8_t byte) {
return ((float) byte) * (1.0f / 255.0f);
}
// Clamp to the 0-1 range.
static float clamp_normalized_float(float v) {
if (v > 1.0f) {
return 1.0f;
} else if ((v < 0.0f) || (v != v)) {
return 0.0f;
} else {
return v;
}
}
static void interp_3d_clut(float dst[3], float src[3], const SkColorLookUpTable* colorLUT) {
// Call the src components x, y, and z.
uint8_t maxX = colorLUT->fGridPoints[0] - 1;
uint8_t maxY = colorLUT->fGridPoints[1] - 1;
uint8_t maxZ = colorLUT->fGridPoints[2] - 1;
// An approximate index into each of the three dimensions of the table.
float x = src[0] * maxX;
float y = src[1] * maxY;
float z = src[2] * maxZ;
// This gives us the low index for our interpolation.
int ix = sk_float_floor2int(x);
int iy = sk_float_floor2int(y);
int iz = sk_float_floor2int(z);
// Make sure the low index is not also the max index.
ix = (maxX == ix) ? ix - 1 : ix;
iy = (maxY == iy) ? iy - 1 : iy;
iz = (maxZ == iz) ? iz - 1 : iz;
// Weighting factors for the interpolation.
float diffX = x - ix;
float diffY = y - iy;
float diffZ = z - iz;
// Constants to help us navigate the 3D table.
// Ex: Assume x = a, y = b, z = c.
// table[a * n001 + b * n010 + c * n100] logically equals table[a][b][c].
const int n000 = 0;
const int n001 = 3 * colorLUT->fGridPoints[1] * colorLUT->fGridPoints[2];
const int n010 = 3 * colorLUT->fGridPoints[2];
const int n011 = n001 + n010;
const int n100 = 3;
const int n101 = n100 + n001;
const int n110 = n100 + n010;
const int n111 = n110 + n001;
// Base ptr into the table.
float* ptr = &colorLUT->fTable[ix*n001 + iy*n010 + iz*n100];
// The code below performs a tetrahedral interpolation for each of the three
// dst components. Once the tetrahedron containing the interpolation point is
// identified, the interpolation is a weighted sum of grid values at the
// vertices of the tetrahedron. The claim is that tetrahedral interpolation
// provides a more accurate color conversion.
// blogs.mathworks.com/steve/2006/11/24/tetrahedral-interpolation-for-colorspace-conversion/
//
// I have one test image, and visually I can't tell the difference between
// tetrahedral and trilinear interpolation. In terms of computation, the
// tetrahedral code requires more branches but less computation. The
// SampleICC library provides an option for the client to choose either
// tetrahedral or trilinear.
for (int i = 0; i < 3; i++) {
if (diffZ < diffY) {
if (diffZ < diffX) {
dst[i] = (ptr[n000] + diffZ * (ptr[n110] - ptr[n010]) +
diffY * (ptr[n010] - ptr[n000]) +
diffX * (ptr[n111] - ptr[n110]));
} else if (diffY < diffX) {
dst[i] = (ptr[n000] + diffZ * (ptr[n111] - ptr[n011]) +
diffY * (ptr[n011] - ptr[n001]) +
diffX * (ptr[n001] - ptr[n000]));
} else {
dst[i] = (ptr[n000] + diffZ * (ptr[n111] - ptr[n011]) +
diffY * (ptr[n010] - ptr[n000]) +
diffX * (ptr[n011] - ptr[n010]));
}
} else {
if (diffZ < diffX) {
dst[i] = (ptr[n000] + diffZ * (ptr[n101] - ptr[n001]) +
diffY * (ptr[n111] - ptr[n101]) +
diffX * (ptr[n001] - ptr[n000]));
} else if (diffY < diffX) {
dst[i] = (ptr[n000] + diffZ * (ptr[n100] - ptr[n000]) +
diffY * (ptr[n111] - ptr[n101]) +
diffX * (ptr[n101] - ptr[n100]));
} else {
dst[i] = (ptr[n000] + diffZ * (ptr[n100] - ptr[n000]) +
diffY * (ptr[n110] - ptr[n100]) +
diffX * (ptr[n111] - ptr[n110]));
}
}
// Increment the table ptr in order to handle the next component.
// Note that this is the how table is designed: all of nXXX
// variables are multiples of 3 because there are 3 output
// components.
ptr++;
}
}
void SkDefaultXform::xform_RGB1_8888(uint32_t* dst, const uint32_t* src, uint32_t len) const {
while (len-- > 0) {
uint8_t r = (*src >> 0) & 0xFF,
g = (*src >> 8) & 0xFF,
b = (*src >> 16) & 0xFF;
if (fColorLUT) {
float in[3];
float out[3];
in[0] = byte_to_float(r);
in[1] = byte_to_float(g);
in[2] = byte_to_float(b);
interp_3d_clut(out, in, fColorLUT.get());
r = sk_float_round2int(255.0f * clamp_normalized_float(out[0]));
g = sk_float_round2int(255.0f * clamp_normalized_float(out[1]));
b = sk_float_round2int(255.0f * clamp_normalized_float(out[2]));
}
// Convert to linear.
float srcFloats[3];
srcFloats[0] = fSrcGammaTables[0][r];
srcFloats[1] = fSrcGammaTables[1][g];
srcFloats[2] = fSrcGammaTables[2][b];
// Convert to dst gamut.
float dstFloats[3];
dstFloats[0] = srcFloats[0] * fSrcToDst.getFloat(0, 0) +
srcFloats[1] * fSrcToDst.getFloat(1, 0) +
srcFloats[2] * fSrcToDst.getFloat(2, 0) + fSrcToDst.getFloat(3, 0);
dstFloats[1] = srcFloats[0] * fSrcToDst.getFloat(0, 1) +
srcFloats[1] * fSrcToDst.getFloat(1, 1) +
srcFloats[2] * fSrcToDst.getFloat(2, 1) + fSrcToDst.getFloat(3, 1);
dstFloats[2] = srcFloats[0] * fSrcToDst.getFloat(0, 2) +
srcFloats[1] * fSrcToDst.getFloat(1, 2) +
srcFloats[2] * fSrcToDst.getFloat(2, 2) + fSrcToDst.getFloat(3, 2);
// Clamp to 0-1.
dstFloats[0] = clamp_normalized_float(dstFloats[0]);
dstFloats[1] = clamp_normalized_float(dstFloats[1]);
dstFloats[2] = clamp_normalized_float(dstFloats[2]);
// Convert to dst gamma.
r = fDstGammaTables[0][sk_float_round2int((kDstGammaTableSize - 1) * dstFloats[0])];
g = fDstGammaTables[1][sk_float_round2int((kDstGammaTableSize - 1) * dstFloats[1])];
b = fDstGammaTables[2][sk_float_round2int((kDstGammaTableSize - 1) * dstFloats[2])];
*dst = SkPackARGB32NoCheck(0xFF, r, g, b);
dst++;
src++;
}
}
| 49,799 | 30,848 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "gtest/gtest.h"
#include "test/providers/provider_test_utils.h"
namespace onnxruntime {
namespace test {
static void scatter_without_axis_tests(const char* op_name, int op_version) {
OpTester test(op_name, op_version);
std::vector<float> input;
input.resize(3 * 3);
std::fill(input.begin(), input.end(), .0f);
test.AddInput<float>("data", {3, 3}, input);
test.AddInput<int64_t>("indices", {2, 3},
{1, 0, 2,
0, 2, 1});
test.AddInput<float>("updates", {2, 3},
{1.0f, 1.1f, 1.2f,
2.0f, 2.1f, 2.2f});
test.AddOutput<float>("y", {3, 3},
{2.0f, 1.1f, 0.0f,
1.0f, 0.0f, 2.2f,
0.0f, 2.1f, 1.2f});
test.Run();
}
TEST(Scatter, WithoutAxis) {
scatter_without_axis_tests("Scatter", 9);
scatter_without_axis_tests("ScatterElements", 11);
}
static void scatter_with_axis_tests(const char* op_name, int op_version) {
OpTester test(op_name, op_version);
test.AddAttribute<int64_t>("axis", 1);
test.AddInput<float>("data", {1, 5}, {1.0f, 2.0f, 3.0f, 4.0f, 5.0f});
test.AddInput<int64_t>("indices", {1, 2}, {1, 3});
test.AddInput<float>("updates", {1, 2}, {1.1f, 2.1f});
test.AddOutput<float>("y", {1, 5}, {1.0f, 1.1f, 3.0f, 2.1f, 5.0f});
test.Run();
}
TEST(Scatter, WithAxis) {
scatter_with_axis_tests("Scatter", 9);
scatter_with_axis_tests("ScatterElements", 11);
}
static void scatter_three_dim_with_axis_0(const char* op_name, int op_version) {
OpTester test(op_name, op_version);
test.AddAttribute<int64_t>("axis", 0);
test.AddInput<int64_t>("data", {1, 3, 3},
{1, 2, 3,
4, 5, 6,
7, 8, 9});
// Because axis 0 is only 1 dimension it should be all zeros
test.AddInput<int64_t>("indices", {1, 3, 3},
{0, 0, 0,
0, 0, 0,
0, 0, 0});
test.AddInput<int64_t>("updates", {1, 3, 3},
{11, 12, 13,
14, 15, 16,
17, 18, 19});
test.AddOutput<int64_t>("y", {1, 3, 3},
{11, 12, 13,
14, 15, 16,
17, 18, 19});
test.Run();
}
TEST(Scatter, ThreeDimsWithAxis_0) {
scatter_three_dim_with_axis_0("Scatter", 9);
scatter_three_dim_with_axis_0("ScatterElements", 11);
}
static void scatter_three_dim_with_axis_negative_2(const char* op_name, int op_version) {
OpTester test(op_name, op_version);
test.AddAttribute<int64_t>("axis", -2);
test.AddInput<int64_t>("data", {2, 2, 2},
{1, 2, 3, 4, 5, 6, 7, 8});
test.AddInput<int64_t>("indices", {2, 1, 2},
{0, 1, 1, 0});
test.AddInput<int64_t>("updates", {2, 1, 2},
{11, 12, 13, 14});
test.AddOutput<int64_t>("y", {2, 2, 2},
{11, 2, 3, 12, 5, 14, 13, 8});
test.Run();
}
TEST(Scatter, ThreeDimsWithAxisNegative_2) {
scatter_three_dim_with_axis_negative_2("Scatter", 9);
scatter_three_dim_with_axis_negative_2("ScatterElements", 11);
}
static void scatter_three_dim_with_axis_2(const char* op_name, int op_version) {
OpTester test(op_name, op_version);
test.AddAttribute<int64_t>("axis", 2);
test.AddInput<int64_t>("data", {1, 3, 3},
{1, 2, 3,
4, 5, 6,
7, 8, 9});
test.AddInput<int64_t>("indices", {1, 3, 3},
{2, 1, 0,
2, 1, 0,
2, 1, 0});
test.AddInput<int64_t>("updates", {1, 3, 3},
{11, 12, 13,
14, 15, 16,
17, 18, 19});
test.AddOutput<int64_t>("y", {1, 3, 3},
{13, 12, 11,
16, 15, 14,
19, 18, 17});
test.Run();
}
TEST(Scatter, ThreeDimsWithAxis_2) {
scatter_three_dim_with_axis_2("Scatter", 9);
scatter_three_dim_with_axis_2("ScatterElements", 11);
}
static void scatter_string(const char* op_name, int op_version) {
OpTester test(op_name, op_version);
test.AddAttribute<int64_t>("axis", 1);
test.AddInput<std::string>("data", {1, 5}, {"1.0f", "2.0f", "3.0f", "4.0f", "5.0f"});
test.AddInput<int64_t>("indices", {1, 2}, {1, 3});
test.AddInput<std::string>("updates", {1, 2}, {"1.1f", "2.1f"});
test.AddOutput<std::string>("y", {1, 5}, {"1.0f", "1.1f", "3.0f", "2.1f", "5.0f"});
test.Run();
}
TEST(Scatter, String) {
scatter_string("Scatter", 9);
scatter_string("ScatterElements", 11);
}
static void scatter_negative_axis(const char* op_name, int op_version) {
OpTester test(op_name, op_version);
test.AddAttribute<int64_t>("axis", -1);
test.AddInput<float>("data", {1, 5}, {1.0f, 2.0f, 3.0f, 4.0f, 5.0f});
test.AddInput<int64_t>("indices", {1, 2}, {1, 3});
test.AddInput<float>("updates", {1, 2}, {1.1f, 2.1f});
test.AddOutput<float>("y", {1, 5}, {1.0f, 1.1f, 3.0f, 2.1f, 5.0f});
#if defined(OPENVINO_CONFIG_MYRIAD) || defined(OPENVINO_CONFIG_VAD_M) //TBD temporarily disabling for openvino
test.Run(OpTester::ExpectResult::kExpectSuccess, "", {kOpenVINOExecutionProvider});
#else
test.Run();
#endif
}
TEST(Scatter, NegativeAxis) {
scatter_negative_axis("Scatter", 9);
scatter_negative_axis("ScatterElements", 11);
}
static void scatter_indices_updates_dont_match(const char* op_name, int op_version) {
OpTester test(op_name, op_version);
test.AddAttribute<int64_t>("axis", 1);
test.AddInput<float>("data", {1, 5}, {1.0f, 2.0f, 3.0f, 4.0f, 5.0f});
test.AddInput<int64_t>("indices", {1, 3}, {1, 3, 3});
test.AddInput<float>("updates", {1, 2}, {1.1f, 2.1f});
test.AddOutput<float>("y", {1, 5}, {1.0f, 1.1f, 3.0f, 2.1f, 5.0f});
test.Run(OpTester::ExpectResult::kExpectFailure, "Indices vs updates dimensions differs at position=1 3 vs 2");
}
TEST(Scatter, IndicesUpdatesDontMatch) {
scatter_indices_updates_dont_match("Scatter", 9);
scatter_indices_updates_dont_match("ScatterElements", 11);
}
static void scatter_valid_index(const char* op_name, int op_version) {
OpTester test(op_name, op_version);
test.AddAttribute<int64_t>("axis", 0);
test.AddInput<float>("data", {4, 2, 1}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f});
test.AddInput<int64_t>("indices", {1, 1, 1}, {3});
test.AddInput<float>("updates", {1, 1, 1}, {5.0f});
test.AddOutput<float>("y", {4, 2, 1}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 5.0f, 0.0f});
test.Run();
}
TEST(Scatter, ValidAxis) {
scatter_valid_index("Scatter", 9);
scatter_valid_index("ScatterElements", 11);
}
static void scatter_invalid_index(const char* op_name, int op_version) {
OpTester test(op_name, op_version);
test.AddAttribute<int64_t>("axis", 0);
test.AddInput<float>("data", {4, 2, 1}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f});
test.AddInput<int64_t>("indices", {1, 1, 1}, {4});
test.AddInput<float>("updates", {1, 1, 1}, {5.0f});
test.AddOutput<float>("y", {4, 2, 1}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 5.0f, 0.0f});
test.Run(OpTester::ExpectResult::kExpectFailure,
"indices element out of data bounds, idx=4 must be within the inclusive range [-4,3]",
{kCudaExecutionProvider});
}
TEST(Scatter, InvalidIndex) {
scatter_invalid_index("Scatter", 9);
scatter_invalid_index("ScatterElements", 11);
}
static void scatter_valid_negative_index(const char* op_name, int op_version) {
OpTester test(op_name, op_version);
test.AddAttribute<int64_t>("axis", 0);
test.AddInput<float>("data", {4, 2, 1}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f});
test.AddInput<int64_t>("indices", {1, 1, 1}, {-1});
test.AddInput<float>("updates", {1, 1, 1}, {5.0f});
test.AddOutput<float>("y", {4, 2, 1}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 5.0f, 0.0f});
#if defined(OPENVINO_CONFIG_MYRIAD) || defined(OPENVINO_CONFIG_VAD_M) //TBD temporarily disabling for openvino
test.Run(OpTester::ExpectResult::kExpectSuccess, "", {kOpenVINOExecutionProvider});
#else
test.Run();
#endif
}
TEST(Scatter, ValidNegativeIndex) {
scatter_valid_negative_index("Scatter", 9);
scatter_valid_negative_index("ScatterElements", 11);
}
static void scatter_bool_with_axis_tests(const char* op_name, int op_version) {
OpTester test(op_name, op_version);
test.AddAttribute<int64_t>("axis", 1);
test.AddInput<bool>("data", {1, 5}, {false, false, false, true, false});
test.AddInput<int64_t>("indices", {1, 2}, {1, 3});
test.AddInput<bool>("updates", {1, 2}, {true, false});
test.AddOutput<bool>("y", {1, 5}, {false, true, false, false, false});
test.Run();
}
TEST(Scatter, BoolInputWithAxis) {
scatter_bool_with_axis_tests("Scatter", 9);
scatter_bool_with_axis_tests("ScatterElements", 11);
}
static void scatter_same_updates_tests(const char* op_name, int op_version) {
OpTester test(op_name, op_version);
std::vector<float> input;
input.resize(3 * 3);
std::fill(input.begin(), input.end(), .0f);
test.AddInput<float>("data", {3, 3}, input);
test.AddInput<int64_t>("indices", {1, 2},
{1, 1}, /*is_initializer*/ true);
test.AddInput<float>("updates", {1, 2},
{2.0f, 2.0f});
test.AddOutput<float>("y", {3, 3},
{0.0f, 0.0f, 0.0f,
2.0f, 2.0f, 0.0f,
0.0f, 0.0f, 0.0f});
test.Run();
}
TEST(Scatter, SameUpdateWithoutAxis) {
scatter_same_updates_tests("Scatter", 9);
scatter_same_updates_tests("ScatterElements", 11);
}
} // namespace test
} // namespace onnxruntime
| 9,838 | 4,364 |
//
// Downloader.cpp
//
// Created by Nissim Hadar on 1 Mar 2018.
// Copyright 2013 High Fidelity, Inc.
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
#include "Downloader.h"
#include <QtWidgets/QMessageBox>
Downloader::Downloader(QUrl fileURL, QObject *parent) : QObject(parent) {
connect(
&_networkAccessManager, SIGNAL (finished(QNetworkReply*)),
this, SLOT (fileDownloaded(QNetworkReply*))
);
QNetworkRequest request(fileURL);
_networkAccessManager.get(request);
}
void Downloader::fileDownloaded(QNetworkReply* reply) {
QNetworkReply::NetworkError error = reply->error();
if (error != QNetworkReply::NetworkError::NoError) {
QMessageBox::information(0, "Test Aborted", "Failed to download file: " + reply->errorString());
return;
}
_downloadedData = reply->readAll();
//emit a signal
reply->deleteLater();
emit downloaded();
}
QByteArray Downloader::downloadedData() const {
return _downloadedData;
} | 1,098 | 364 |
/**
Accelerated C++, Exercise 10-3, 10_3.cpp
Write a test program to verify that the median function operates correctly.
Ensure that calling median does not change the order of the elements in the container.
*/
#include "stdafx.h"
#include "10_3.h"
#include "10_2.h"
#include <vector>
using std::vector;
#include <iostream>
using std::cout;
using std::endl;
using std::ostream;
template<class T>
ostream& print_vector(const vector<T> v, ostream& os)
{
if (v.size() > 0)
{
os << v[0];
for (vector<T>::size_type i = 1; i < v.size(); i++)
os << ", " << v[i];
os << endl;
}
return os;
}
int ex10_3()
{
vector<double> v_double = { 12.5, 5.25, 25.7, 16.3, 1.26 };
print_vector(v_double, cout);
cout << median<double, vector<double>::iterator>(v_double.begin(), v_double.end()) << endl;
print_vector(v_double, cout);
return 0;
} | 871 | 355 |
#include "queue.h"
Queue::Queue() {
first = 0;
last = 0;
size = 0;
}
void Queue::addElem(PCB* pcb) {
if (first == 0) {
first = new Elem(pcb);
last = first;
} else {
Elem* temp = new Elem(pcb);
last->next = temp;
last = temp;
}
size++;
}
PCB* Queue::getElem() {
if (first == 0) return 0;
PCB* ret = 0;
if (first->next != 0) {
ret = first->data;
Elem* temp = first;
first = first->next;
delete temp;
} else {
ret = first->data;
delete first;
first = last = 0;
}
size--;
return ret;
}
int Queue::getSize() {
return size;
}
Queue::~Queue() {
Elem* temp = first;
Elem* prev = 0;
while (temp != 0) {
prev = temp;
temp = temp->next;
delete prev;
}
first = last = 0;
size = 0;
}
| 781 | 362 |
// 10298 - Power Strings
#include <cstdio>
#define N 1000001
int main()
{
int i, j;
int b[N];
char str[N];
while(scanf("%s", str), str[0] != '.')
{
// KMP algorithm
i = 0; j = -1; b[0] = -1;
while(str[i])
{
while(j >= 0 && str[i] != str[j]) j = b[j];
i++; j++;
b[i] = j;
}
if(i % (i - j)) printf("1\n");
else printf("%d\n", i / (i - j));
}
return 0;
}
| 389 | 223 |
// Copyright 2013 The Flutter 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 <future>
#define FML_USED_ON_EMBEDDER
#include "flutter/shell/common/shell_test.h"
#include "flutter/flow/layers/layer_tree.h"
#include "flutter/flow/layers/transform_layer.h"
#include "flutter/fml/make_copyable.h"
#include "flutter/fml/mapping.h"
#include "flutter/runtime/dart_vm.h"
#include "flutter/shell/gpu/gpu_surface_gl.h"
#include "flutter/testing/testing.h"
namespace flutter {
namespace testing {
ShellTest::ShellTest()
: native_resolver_(std::make_shared<TestDartNativeResolver>()) {}
ShellTest::~ShellTest() = default;
void ShellTest::SendEnginePlatformMessage(
Shell* shell,
fml::RefPtr<PlatformMessage> message) {
fml::AutoResetWaitableEvent latch;
fml::TaskRunner::RunNowOrPostTask(
shell->GetTaskRunners().GetPlatformTaskRunner(),
[shell, &latch, message = std::move(message)]() {
if (auto engine = shell->weak_engine_) {
engine->HandlePlatformMessage(std::move(message));
}
latch.Signal();
});
latch.Wait();
}
void ShellTest::SetSnapshotsAndAssets(Settings& settings) {
if (!assets_dir_.is_valid()) {
return;
}
settings.assets_dir = assets_dir_.get();
// In JIT execution, all snapshots are present within the binary itself and
// don't need to be explicitly suppiled by the embedder.
if (DartVM::IsRunningPrecompiledCode()) {
settings.vm_snapshot_data = [this]() {
return fml::FileMapping::CreateReadOnly(assets_dir_, "vm_snapshot_data");
};
settings.isolate_snapshot_data = [this]() {
return fml::FileMapping::CreateReadOnly(assets_dir_,
"isolate_snapshot_data");
};
if (DartVM::IsRunningPrecompiledCode()) {
settings.vm_snapshot_instr = [this]() {
return fml::FileMapping::CreateReadExecute(assets_dir_,
"vm_snapshot_instr");
};
settings.isolate_snapshot_instr = [this]() {
return fml::FileMapping::CreateReadExecute(assets_dir_,
"isolate_snapshot_instr");
};
}
} else {
settings.application_kernels = [this]() {
std::vector<std::unique_ptr<const fml::Mapping>> kernel_mappings;
kernel_mappings.emplace_back(
fml::FileMapping::CreateReadOnly(assets_dir_, "kernel_blob.bin"));
return kernel_mappings;
};
}
}
void ShellTest::PlatformViewNotifyCreated(Shell* shell) {
fml::AutoResetWaitableEvent latch;
fml::TaskRunner::RunNowOrPostTask(
shell->GetTaskRunners().GetPlatformTaskRunner(), [shell, &latch]() {
shell->GetPlatformView()->NotifyCreated();
latch.Signal();
});
latch.Wait();
}
void ShellTest::RunEngine(Shell* shell, RunConfiguration configuration) {
fml::AutoResetWaitableEvent latch;
fml::TaskRunner::RunNowOrPostTask(
shell->GetTaskRunners().GetPlatformTaskRunner(),
[shell, &latch, &configuration]() {
shell->RunEngine(std::move(configuration),
[&latch](Engine::RunStatus run_status) {
ASSERT_EQ(run_status, Engine::RunStatus::Success);
latch.Signal();
});
});
latch.Wait();
}
void ShellTest::RestartEngine(Shell* shell, RunConfiguration configuration) {
std::promise<bool> restarted;
fml::TaskRunner::RunNowOrPostTask(
shell->GetTaskRunners().GetUITaskRunner(),
[shell, &restarted, &configuration]() {
restarted.set_value(shell->engine_->Restart(std::move(configuration)));
});
ASSERT_TRUE(restarted.get_future().get());
}
void ShellTest::VSyncFlush(Shell* shell, bool& will_draw_new_frame) {
fml::AutoResetWaitableEvent latch;
shell->GetTaskRunners().GetPlatformTaskRunner()->PostTask(
[shell, &will_draw_new_frame, &latch] {
// The following UI task ensures that all previous UI tasks are flushed.
fml::AutoResetWaitableEvent ui_latch;
shell->GetTaskRunners().GetUITaskRunner()->PostTask(
[&ui_latch, &will_draw_new_frame]() {
will_draw_new_frame = true;
ui_latch.Signal();
});
ShellTestPlatformView* test_platform_view =
static_cast<ShellTestPlatformView*>(shell->GetPlatformView().get());
do {
test_platform_view->SimulateVSync();
} while (ui_latch.WaitWithTimeout(fml::TimeDelta::FromMilliseconds(1)));
latch.Signal();
});
latch.Wait();
}
void ShellTest::PumpOneFrame(Shell* shell,
double width,
double height,
LayerTreeBuilder builder) {
// Set viewport to nonempty, and call Animator::BeginFrame to make the layer
// tree pipeline nonempty. Without either of this, the layer tree below
// won't be rasterized.
fml::AutoResetWaitableEvent latch;
shell->GetTaskRunners().GetUITaskRunner()->PostTask(
[&latch, engine = shell->weak_engine_, width, height]() {
engine->SetViewportMetrics(
{1, width, height, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0});
engine->animator_->BeginFrame(fml::TimePoint::Now(),
fml::TimePoint::Now());
latch.Signal();
});
latch.Wait();
latch.Reset();
// Call |Render| to rasterize a layer tree and trigger |OnFrameRasterized|
fml::WeakPtr<RuntimeDelegate> runtime_delegate = shell->weak_engine_;
shell->GetTaskRunners().GetUITaskRunner()->PostTask(
[&latch, runtime_delegate, &builder]() {
auto layer_tree = std::make_unique<LayerTree>();
SkMatrix identity;
identity.setIdentity();
auto root_layer = std::make_shared<TransformLayer>(identity);
layer_tree->set_root_layer(root_layer);
if (builder) {
builder(root_layer);
}
runtime_delegate->Render(std::move(layer_tree));
latch.Signal();
});
latch.Wait();
}
void ShellTest::DispatchFakePointerData(Shell* shell) {
auto packet = std::make_unique<PointerDataPacket>(1);
DispatchPointerData(shell, std::move(packet));
}
void ShellTest::DispatchPointerData(Shell* shell,
std::unique_ptr<PointerDataPacket> packet) {
fml::AutoResetWaitableEvent latch;
shell->GetTaskRunners().GetPlatformTaskRunner()->PostTask(
[&latch, shell, &packet]() {
// Goes through PlatformView to ensure packet is corrected converted.
shell->GetPlatformView()->DispatchPointerDataPacket(std::move(packet));
latch.Signal();
});
latch.Wait();
}
int ShellTest::UnreportedTimingsCount(Shell* shell) {
return shell->unreported_timings_.size();
}
void ShellTest::SetNeedsReportTimings(Shell* shell, bool value) {
shell->SetNeedsReportTimings(value);
}
bool ShellTest::GetNeedsReportTimings(Shell* shell) {
return shell->needs_report_timings_;
}
std::shared_ptr<txt::FontCollection> ShellTest::GetFontCollection(
Shell* shell) {
return shell->weak_engine_->GetFontCollection().GetFontCollection();
}
Settings ShellTest::CreateSettingsForFixture() {
Settings settings;
settings.leak_vm = false;
settings.task_observer_add = [](intptr_t key, fml::closure handler) {
fml::MessageLoop::GetCurrent().AddTaskObserver(key, handler);
};
settings.task_observer_remove = [](intptr_t key) {
fml::MessageLoop::GetCurrent().RemoveTaskObserver(key);
};
settings.isolate_create_callback = [this]() {
native_resolver_->SetNativeResolverForIsolate();
};
SetSnapshotsAndAssets(settings);
return settings;
}
TaskRunners ShellTest::GetTaskRunnersForFixture() {
return {
"test",
thread_host_->platform_thread->GetTaskRunner(), // platform
thread_host_->gpu_thread->GetTaskRunner(), // gpu
thread_host_->ui_thread->GetTaskRunner(), // ui
thread_host_->io_thread->GetTaskRunner() // io
};
}
std::unique_ptr<Shell> ShellTest::CreateShell(Settings settings,
bool simulate_vsync) {
return CreateShell(std::move(settings), GetTaskRunnersForFixture(),
simulate_vsync);
}
std::unique_ptr<Shell> ShellTest::CreateShell(Settings settings,
TaskRunners task_runners,
bool simulate_vsync) {
return Shell::Create(
task_runners, settings,
[simulate_vsync](Shell& shell) {
return std::make_unique<ShellTestPlatformView>(
shell, shell.GetTaskRunners(), simulate_vsync);
},
[](Shell& shell) {
return std::make_unique<Rasterizer>(shell, shell.GetTaskRunners());
});
}
void ShellTest::DestroyShell(std::unique_ptr<Shell> shell) {
DestroyShell(std::move(shell), GetTaskRunnersForFixture());
}
void ShellTest::DestroyShell(std::unique_ptr<Shell> shell,
TaskRunners task_runners) {
fml::AutoResetWaitableEvent latch;
fml::TaskRunner::RunNowOrPostTask(task_runners.GetPlatformTaskRunner(),
[&shell, &latch]() mutable {
shell.reset();
latch.Signal();
});
latch.Wait();
}
// |testing::ThreadTest|
void ShellTest::SetUp() {
ThreadTest::SetUp();
assets_dir_ =
fml::OpenDirectory(GetFixturesPath(), false, fml::FilePermission::kRead);
thread_host_ = std::make_unique<ThreadHost>(
"io.flutter.test." + GetCurrentTestName() + ".",
ThreadHost::Type::Platform | ThreadHost::Type::IO | ThreadHost::Type::UI |
ThreadHost::Type::GPU);
}
// |testing::ThreadTest|
void ShellTest::TearDown() {
ThreadTest::TearDown();
assets_dir_.reset();
thread_host_.reset();
}
void ShellTest::AddNativeCallback(std::string name,
Dart_NativeFunction callback) {
native_resolver_->AddNativeCallback(std::move(name), callback);
}
void ShellTestVsyncClock::SimulateVSync() {
std::scoped_lock lock(mutex_);
if (vsync_issued_ >= vsync_promised_.size()) {
vsync_promised_.emplace_back();
}
FML_CHECK(vsync_issued_ < vsync_promised_.size());
vsync_promised_[vsync_issued_].set_value(vsync_issued_);
vsync_issued_ += 1;
}
std::future<int> ShellTestVsyncClock::NextVSync() {
std::scoped_lock lock(mutex_);
vsync_promised_.emplace_back();
return vsync_promised_.back().get_future();
}
void ShellTestVsyncWaiter::AwaitVSync() {
FML_DCHECK(task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread());
auto vsync_future = clock_.NextVSync();
auto async_wait = std::async([&vsync_future, this]() {
vsync_future.wait();
// Post the `FireCallback` to the Platform thread so earlier Platform tasks
// (specifically, the `VSyncFlush` call) will be finished before
// `FireCallback` is executed. This is only needed for our unit tests.
//
// Without this, the repeated VSYNC signals in `VSyncFlush` may start both
// the current frame in the UI thread and the next frame in the secondary
// callback (both of them are waiting for VSYNCs). That breaks the unit
// test's assumption that each frame's VSYNC must be issued by different
// `VSyncFlush` call (which resets the `will_draw_new_frame` bit).
//
// For example, HandlesActualIphoneXsInputEvents will fail without this.
task_runners_.GetPlatformTaskRunner()->PostTask([this]() {
FireCallback(fml::TimePoint::Now(), fml::TimePoint::Now());
});
});
}
ShellTestPlatformView::ShellTestPlatformView(PlatformView::Delegate& delegate,
TaskRunners task_runners,
bool simulate_vsync)
: PlatformView(delegate, std::move(task_runners)),
gl_surface_(SkISize::Make(800, 600)),
simulate_vsync_(simulate_vsync) {}
ShellTestPlatformView::~ShellTestPlatformView() = default;
std::unique_ptr<VsyncWaiter> ShellTestPlatformView::CreateVSyncWaiter() {
return simulate_vsync_ ? std::make_unique<ShellTestVsyncWaiter>(task_runners_,
vsync_clock_)
: PlatformView::CreateVSyncWaiter();
}
void ShellTestPlatformView::SimulateVSync() {
vsync_clock_.SimulateVSync();
}
// |PlatformView|
std::unique_ptr<Surface> ShellTestPlatformView::CreateRenderingSurface() {
return std::make_unique<GPUSurfaceGL>(this, true);
}
// |PlatformView|
PointerDataDispatcherMaker ShellTestPlatformView::GetDispatcherMaker() {
return [](DefaultPointerDataDispatcher::Delegate& delegate) {
return std::make_unique<SmoothPointerDataDispatcher>(delegate);
};
}
// |GPUSurfaceGLDelegate|
bool ShellTestPlatformView::GLContextMakeCurrent() {
return gl_surface_.MakeCurrent();
}
// |GPUSurfaceGLDelegate|
bool ShellTestPlatformView::GLContextClearCurrent() {
return gl_surface_.ClearCurrent();
}
// |GPUSurfaceGLDelegate|
bool ShellTestPlatformView::GLContextPresent() {
return gl_surface_.Present();
}
// |GPUSurfaceGLDelegate|
intptr_t ShellTestPlatformView::GLContextFBO() const {
return gl_surface_.GetFramebuffer();
}
// |GPUSurfaceGLDelegate|
GPUSurfaceGLDelegate::GLProcResolver ShellTestPlatformView::GetGLProcResolver()
const {
return [surface = &gl_surface_](const char* name) -> void* {
return surface->GetProcAddress(name);
};
}
// |GPUSurfaceGLDelegate|
ExternalViewEmbedder* ShellTestPlatformView::GetExternalViewEmbedder() {
return nullptr;
}
} // namespace testing
} // namespace flutter
| 13,787 | 4,282 |
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System::Reflection
namespace System::Reflection {
// Forward declaring type: MemberInfo
class MemberInfo;
}
// Completed forward declares
// Type namespace: System
namespace System {
// Forward declaring type: __Filters
class __Filters;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::System::__Filters);
DEFINE_IL2CPP_ARG_TYPE(::System::__Filters*, "System", "__Filters");
// Type namespace: System
namespace System {
// Size: 0x10
#pragma pack(push, 1)
// Autogenerated type: System.__Filters
// [TokenAttribute] Offset: FFFFFFFF
class __Filters : public ::Il2CppObject {
public:
// Get static field: static readonly System.__Filters Instance
static ::System::__Filters* _get_Instance();
// Set static field: static readonly System.__Filters Instance
static void _set_Instance(::System::__Filters* value);
// static private System.Void .cctor()
// Offset: 0x298CE34
static void _cctor();
// System.Boolean FilterAttribute(System.Reflection.MemberInfo m, System.Object filterCriteria)
// Offset: 0x298C794
bool FilterAttribute(::System::Reflection::MemberInfo* m, ::Il2CppObject* filterCriteria);
// System.Boolean FilterName(System.Reflection.MemberInfo m, System.Object filterCriteria)
// Offset: 0x298CAEC
bool FilterName(::System::Reflection::MemberInfo* m, ::Il2CppObject* filterCriteria);
// System.Boolean FilterIgnoreCase(System.Reflection.MemberInfo m, System.Object filterCriteria)
// Offset: 0x298CC84
bool FilterIgnoreCase(::System::Reflection::MemberInfo* m, ::Il2CppObject* filterCriteria);
// public System.Void .ctor()
// Offset: 0x298CE2C
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static __Filters* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::__Filters::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<__Filters*, creationType>()));
}
}; // System.__Filters
#pragma pack(pop)
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: System::__Filters::_cctor
// Il2CppName: .cctor
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)()>(&System::__Filters::_cctor)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::__Filters*), ".cctor", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::__Filters::FilterAttribute
// Il2CppName: FilterAttribute
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::__Filters::*)(::System::Reflection::MemberInfo*, ::Il2CppObject*)>(&System::__Filters::FilterAttribute)> {
static const MethodInfo* get() {
static auto* m = &::il2cpp_utils::GetClassFromName("System.Reflection", "MemberInfo")->byval_arg;
static auto* filterCriteria = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::__Filters*), "FilterAttribute", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{m, filterCriteria});
}
};
// Writing MetadataGetter for method: System::__Filters::FilterName
// Il2CppName: FilterName
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::__Filters::*)(::System::Reflection::MemberInfo*, ::Il2CppObject*)>(&System::__Filters::FilterName)> {
static const MethodInfo* get() {
static auto* m = &::il2cpp_utils::GetClassFromName("System.Reflection", "MemberInfo")->byval_arg;
static auto* filterCriteria = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::__Filters*), "FilterName", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{m, filterCriteria});
}
};
// Writing MetadataGetter for method: System::__Filters::FilterIgnoreCase
// Il2CppName: FilterIgnoreCase
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::__Filters::*)(::System::Reflection::MemberInfo*, ::Il2CppObject*)>(&System::__Filters::FilterIgnoreCase)> {
static const MethodInfo* get() {
static auto* m = &::il2cpp_utils::GetClassFromName("System.Reflection", "MemberInfo")->byval_arg;
static auto* filterCriteria = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::__Filters*), "FilterIgnoreCase", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{m, filterCriteria});
}
};
// Writing MetadataGetter for method: System::__Filters::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
| 5,630 | 1,864 |
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin >> n;
for(int i=0;i<n;i++)
{
string s;
cin >> s;
if(s.length()>10)
{
stringstream ss;
int l;
l=s.length()-2;
ss << s[0] << l << s[s.length()-1];
cout << ss.str() << endl;
}
else
cout << s << endl;
}
return 0;
}
| 423 | 158 |
#include "Object.h"
Object::Object()
{
}
void Object::render(){
SDL_RenderCopy(texture->getRenderer(), texture->getTexture(), &sprite, &location);
}
/** \brief Sets the texture to the character
*
* \param Texture* _texture: The texture which you want to set to character
*
*/
void Object::setTexture(Texture* _texture){
texture = _texture;
}
Object::~Object()
{
}
| 371 | 129 |
#include "Handler.h"
#include "ServerHandler.h"
using namespace ThorsAnvil::Nisse::Core::Service;
TimerHandler::TimerHandler(Server& parent, double timeOut, std::function<void()>&& action)
: HandlerNonSuspendable(parent, -1, EV_PERSIST, timeOut)
, action(std::move(action))
{}
short TimerHandler::eventActivate(LibSocketId /*sockId*/, short /*eventType*/)
{
action();
return 0;
}
#ifdef COVERAGE_TEST
/*
* This code is only compiled into the unit tests for code coverage purposes
* It is not part of the live code.
*/
#include "ServerHandler.tpp"
#include "test/Action.h"
#include "ThorsNisseCoreSocket/Socket.h"
template ThorsAnvil::Nisse::Core::Service::ServerHandler<Action, void>::ServerHandler(ThorsAnvil::Nisse::Core::Service::Server&, ThorsAnvil::Nisse::Core::Socket::ServerSocket&&);
template ThorsAnvil::Nisse::Core::Service::ServerHandler<ActionUnReg, void>::ServerHandler(ThorsAnvil::Nisse::Core::Service::Server&, ThorsAnvil::Nisse::Core::Socket::ServerSocket&&);
template ThorsAnvil::Nisse::Core::Service::ServerHandler<TestHandler, std::tuple<bool, bool, bool> >::ServerHandler(ThorsAnvil::Nisse::Core::Service::Server&, ThorsAnvil::Nisse::Core::Socket::ServerSocket&&, std::tuple<bool, bool, bool>&);
template ThorsAnvil::Nisse::Core::Service::ServerHandler<InHandlerTest, std::tuple<bool, std::function<void (ThorsAnvil::Nisse::Core::Service::Server&)> > >::ServerHandler(ThorsAnvil::Nisse::Core::Service::Server&, ThorsAnvil::Nisse::Core::Socket::ServerSocket&&, std::tuple<bool, std::function<void (ThorsAnvil::Nisse::Core::Service::Server&)> >&);
#endif
| 1,597 | 520 |
#include "stdafx.h"
#include "RESTAPICore/RouteAccess/EpochTimeService.h"
#include <chrono>
#include <thread>
using namespace testing;
namespace systelab { namespace rest_api_core { namespace unit_test {
class EpochTimeServiceTest : public Test
{
protected:
rest_api_core::EpochTimeService m_service;
};
TEST_F(EpochTimeServiceTest, testGetCurrentEpochTimeReturnsGreaterOrEqualTimeOnSecondCall)
{
time_t currentTime1 = m_service.getCurrentEpochTime();
time_t currentTime2 = m_service.getCurrentEpochTime();
ASSERT_GE(currentTime2, currentTime1);
}
TEST_F(EpochTimeServiceTest, testGetCurrentTimeEpochReturnsTime2SecondsGreaterAfterWaiting2Seconds)
{
time_t currentTime1 = m_service.getCurrentEpochTime();
std::this_thread::sleep_for(std::chrono::seconds(2));
time_t currentTime2 = m_service.getCurrentEpochTime();
ASSERT_GE(difftime(currentTime2, currentTime1), 2);
}
}}}
| 907 | 340 |
/*
* RejudgeJobBase.cpp
*
* Created on: 2018年11月20日
* Author: peter
*/
#include "RejudgeJobBase.hpp"
#include "logger.hpp"
#ifndef MYSQLPP_MYSQL_HEADERS_BURIED
# define MYSQLPP_MYSQL_HEADERS_BURIED
#endif
#include <mysql++/transaction.h>
#include <mysql_conn_factory.hpp>
extern std::ofstream log_fp;
RejudgeJobBase::RejudgeJobBase(int jobType, ojv4::s_id_type s_id, kerbal::redis_v2::connection & redis_conn) :
UpdateJobBase(jobType, s_id, redis_conn), rejudge_time(mysqlpp::DateTime::now())
{
LOG_DEBUG(jobType, s_id, log_fp, BOOST_CURRENT_FUNCTION);
}
void RejudgeJobBase::handle()
{
LOG_DEBUG(jobType, s_id, log_fp, BOOST_CURRENT_FUNCTION);
std::exception_ptr move_solution_exception = nullptr;
std::exception_ptr update_solution_exception = nullptr;
std::exception_ptr update_compile_error_info_exception = nullptr;
std::exception_ptr update_user_exception = nullptr;
std::exception_ptr update_problem_exception = nullptr;
std::exception_ptr update_user_problem_exception = nullptr;
std::exception_ptr update_user_problem_status_exception = nullptr;
std::exception_ptr commit_exception = nullptr;
// 本次更新任务的 mysql 连接
auto mysql_conn_handle = sync_fetch_mysql_conn();
mysqlpp::Connection & mysql_conn = *mysql_conn_handle;
mysqlpp::Transaction trans(mysql_conn);
try {
this->move_orig_solution_to_rejudge_solution(mysql_conn);
} catch (const std::exception & e) {
move_solution_exception = std::current_exception();
EXCEPT_FATAL(jobType, s_id, log_fp, "Move original solution failed!", e);
//DO NOT THROW
}
if (move_solution_exception == nullptr) {
try {
this->update_solution(mysql_conn);
} catch (const std::exception & e) {
move_solution_exception = std::current_exception();
EXCEPT_FATAL(jobType, s_id, log_fp, "Update solution failed!", e);
//DO NOT THROW
}
if (update_solution_exception == nullptr) {
try {
this->update_compile_info(mysql_conn);
} catch (const std::exception & e) {
update_compile_error_info_exception = std::current_exception();
EXCEPT_FATAL(jobType, s_id, log_fp, "Update compile error info failed!", e);
//DO NOT THROW
}
try {
this->update_user(mysql_conn);
} catch (const std::exception & e) {
update_user_exception = std::current_exception();
EXCEPT_FATAL(jobType, s_id, log_fp, "Update user failed!", e);
//DO NOT THROW
}
try {
this->update_problem(mysql_conn);
} catch (const std::exception & e) {
update_problem_exception = std::current_exception();
EXCEPT_FATAL(jobType, s_id, log_fp, "Update problem failed!", e);
//DO NOT THROW
}
try {
this->update_user_problem(mysql_conn);
} catch (const std::exception & e) {
update_user_problem_exception = std::current_exception();
EXCEPT_FATAL(jobType, s_id, log_fp, "Update user problem failed!", e);
//DO NOT THROW
}
// try {
// this->update_user_problem_status(mysql_conn);
// } catch (const std::exception & e) {
// update_user_problem_status_exception = std::current_exception();
// EXCEPT_FATAL(jobType, s_id, log_fp, "Update user problem status failed!", e);
// //DO NOT THROW
// }
try {
this->send_rejudge_notification(mysql_conn);
} catch (const std::exception & e){
EXCEPT_WARNING(jobType, s_id, log_fp, "Send rejudge notification failed!", e);
//DO NOT THROW
}
}
try {
trans.commit();
} catch (const std::exception & e) {
EXCEPT_FATAL(jobType, s_id, log_fp, "MySQL commit failed!", e);
commit_exception = std::current_exception();
//DO NOT THROW
} catch (...) {
UNKNOWN_EXCEPT_FATAL(jobType, s_id, log_fp, "MySQL commit failed!");
commit_exception = std::current_exception();
//DO NOT THROW
}
}
this->clear_redis_info();
}
void RejudgeJobBase::clear_redis_info() noexcept try
{
this->UpdateJobBase::clear_this_jobs_info_in_redis();
auto redis_conn_handler = sync_fetch_redis_conn();
kerbal::redis_v2::operation opt(*redis_conn_handler);
try {
boost::format judge_status_templ("judge_status:%d:%d");
if (opt.del((judge_status_templ % jobType % s_id).str()) == false) {
LOG_WARNING(jobType, s_id, log_fp, "Doesn't delete judge_status actually!");
}
} catch (const std::exception & e) {
LOG_WARNING(jobType, s_id, log_fp, "Exception occurred while deleting judge_status!");
//DO NOT THROW
}
try {
boost::format similarity_details("similarity_details:%d:%d");
if (opt.del((similarity_details % jobType % s_id).str()) == false) {
// LOG_WARNING(jobType, s_id, log_fp, "Doesn't delete similarity_details actually!");
}
} catch (const std::exception & e) {
LOG_WARNING(jobType, s_id, log_fp, "Exception occurred while deleting similarity_details!");
//DO NOT THROW
}
try {
boost::format job_info("job_info:%d:%d");
if (opt.del((job_info % jobType % s_id).str()) == false) {
// LOG_WARNING(jobType, s_id, log_fp, "Doesn't delete job_info actually!");
}
} catch (const std::exception & e) {
LOG_WARNING(jobType, s_id, log_fp, "Exception occurred while deleting job_info!");
//DO NOT THROW
}
} catch (...) {
UNKNOWN_EXCEPT_FATAL(jobType, s_id, log_fp, "Clear this jobs info in redis failed!");
}
| 5,182 | 2,064 |
/*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/runtime/vm/jit/stack-overflow.h"
#include "hphp/runtime/base/exceptions.h"
#include "hphp/runtime/base/typed-value.h"
#include "hphp/runtime/vm/bytecode.h"
#include "hphp/runtime/vm/func.h"
#include "hphp/runtime/vm/hhbc.h"
#include "hphp/runtime/vm/hhbc-codec.h"
#include "hphp/runtime/vm/unit.h"
#include "hphp/runtime/vm/unwind.h"
#include "hphp/runtime/vm/vm-regs.h"
#include "hphp/runtime/vm/jit/translator-inline.h"
#include "hphp/util/assertions.h"
namespace HPHP { namespace jit {
///////////////////////////////////////////////////////////////////////////////
bool checkCalleeStackOverflow(const TypedValue* calleeFP, const Func* callee) {
auto const limit = callee->maxStackCells() + kStackCheckPadding;
const void* const needed_top = calleeFP - limit;
const void* const lower_limit =
static_cast<char*>(vmRegsUnsafe().stack.getStackLowAddress()) +
Stack::sSurprisePageSize;
return needed_top < lower_limit;
}
void handleStackOverflow(ActRec* calleeAR) {
// We didn't finish setting up the prologue, so let the unwinder know that
// locals are already freed so it doesn't try to decref the garbage. Do not
// bother decrefing numArgs, as we are going to fail the request anyway.
calleeAR->setLocalsDecRefd();
// sync_regstate in unwind-itanium.cpp doesn't have enough context to properly
// sync registers, so do it here. Sync them to correspond to the state on
// function entry. This is not really true, but it's good enough for unwinder.
auto& unsafeRegs = vmRegsUnsafe();
unsafeRegs.fp = calleeAR;
unsafeRegs.pc = calleeAR->func()->getEntry();
unsafeRegs.stack.top() =
reinterpret_cast<TypedValue*>(calleeAR) - calleeAR->func()->numSlotsInFrame();
unsafeRegs.jitReturnAddr = nullptr;
tl_regState = VMRegState::CLEAN;
throw_stack_overflow();
}
void handlePossibleStackOverflow(ActRec* calleeAR) {
assert_native_stack_aligned();
// If it's not an overflow, it was probably a surprise flag trip. But we
// can't assert that it is because background threads are allowed to clear
// surprise bits concurrently, so it could be cleared again by now.
auto const calleeFP = reinterpret_cast<const TypedValue*>(calleeAR);
if (!checkCalleeStackOverflow(calleeFP, calleeAR->func())) return;
/*
* Stack overflows in this situation are a slightly different case than
* handleStackOverflow:
*
* A function prologue already did all the work to prepare to enter the
* function, but then it found out it didn't have enough room on the stack.
* It may even have written uninits deeper than the stack base (but we limit
* it to sSurprisePageSize, so it's harmless).
*
* Most importantly, it might have pulled args /off/ the eval stack and
* shoved them into an array for a variadic capture param. We need to get
* things into an appropriate state for handleStackOverflow to be able to
* synchronize things to throw from the PC of the caller's FCall.
*
* We don't actually need to make sure the stack is the right depth for the
* FCall: the unwinder will expect to see a pre-live ActRec (and we'll set it
* up so it will), but it doesn't care how many args (or what types of args)
* are below it on the stack.
*
* So, all that boils down to this: we set calleeAR->m_numArgs to indicate
* how many things are actually on the stack (so handleStackOverflow knows
* what to set the vmsp to)---we just set it to the function's numLocals,
* which might mean decreffing some uninits unnecessarily, but that's ok.
*/
calleeAR->setNumArgs(calleeAR->m_func->numLocals());
handleStackOverflow(calleeAR);
}
///////////////////////////////////////////////////////////////////////////////
}}
| 4,734 | 1,403 |
#include <frovedis.hpp>
#include <frovedis/ml/graph/graph.hpp>
#include <boost/program_options.hpp>
using namespace boost;
using namespace frovedis;
using namespace std;
template <class T>
void call_bfs(const std::string& data_p,
const std::string& out_p,
bool if_prep,
size_t source_vertex,
int opt_level,
double threshold,
size_t depth_limit) {
graph<T> gr;
time_spent t(INFO);
if(if_prep) gr = read_edgelist<T>(data_p);
else {
auto mat = make_crs_matrix_load<T>(data_p);
gr = graph<T>(mat);
}
t.show("data loading time: ");
auto res = gr.bfs(source_vertex, opt_level, threshold, depth_limit);
t.show("bfs computation time: ");
res.save(out_p);
res.debug_print(5);
}
int main(int argc, char* argv[]){
frovedis::use_frovedis use(argc, argv);
using namespace boost::program_options;
options_description opt("option");
opt.add_options()
("help,h", "produce help message")
("input,i" , value<std::string>(), "input data path containing either edgelist or adjacency matrix data")
("dtype,t" , value<std::string>(), "input data type (int, float or double) [default: int]")
("output,o" , value<std::string>(), "output data path to save cc results")
("source,s", value<size_t>(), "source vertex id [1 ~ nvert] (default: 1)")
("opt-level", value<int>(), "optimization level 0, 1 or 2 (default: 1)")
("hyb-threshold", value<double>(), "threshold value for hybrid optimization [0.0 ~ 1.0] (default: 0.4)")
("depth-limit", value<size_t>(), "depth limit to which tree is to be traversed (default: Max depth)")
("verbose", "set loglevel to DEBUG")
("verbose2", "set loglevel to TRACE")
("prepare,p" , "whether to generate the CRS matrix from original edgelist file ");
variables_map argmap;
store(command_line_parser(argc,argv).options(opt).allow_unregistered().
run(), argmap);
notify(argmap);
bool if_prep = 0; // true if prepare data from raw dataset
std::string data_p, out_p, dtype = "int";
size_t source_vertex = 1;
int opt_level = 1;
double threshold = 0.4;
size_t depth_limit = std::numeric_limits<size_t>::max();
if(argmap.count("help")){
std::cerr << opt << std::endl;
exit(1);
}
if(argmap.count("input")){
data_p = argmap["input"].as<std::string>();
} else {
std::cerr << "input path is not specified" << std::endl;
std::cerr << opt << std::endl;
exit(1);
}
if(argmap.count("output")){
out_p = argmap["output"].as<std::string>();
} else {
std::cerr << "output path is not specified" << std::endl;
std::cerr << opt << std::endl;
exit(1);
}
if(argmap.count("prepare")){
if_prep = true;
}
if(argmap.count("dtype")){
dtype = argmap["dtype"].as<std::string>();
}
if(argmap.count("source")){
source_vertex = argmap["source"].as<size_t>();
}
if(argmap.count("opt-level")){
opt_level = argmap["opt-level"].as<int>();
}
if(argmap.count("hyb-threshold")){
threshold = argmap["hyb-threshold"].as<double>();
}
if(argmap.count("depth-limit")){
depth_limit = argmap["depth-limit"].as<size_t>();
}
if(argmap.count("verbose")){
set_loglevel(DEBUG);
}
if(argmap.count("verbose2")){
set_loglevel(TRACE);
}
try {
if (dtype == "int") {
call_bfs<int>(data_p, out_p, if_prep, source_vertex,
opt_level, threshold, depth_limit);
}
else if (dtype == "float") {
call_bfs<float>(data_p, out_p, if_prep, source_vertex,
opt_level, threshold, depth_limit);
}
else if (dtype == "double") {
call_bfs<double>(data_p, out_p, if_prep, source_vertex,
opt_level, threshold, depth_limit);
}
else {
std::cerr << "Supported dtypes are only int, float and double!\n";
std::cerr << opt << std::endl;
exit(1);
}
}
catch (std::exception& e) {
std::cout << "exception caught: " << e.what() << std::endl;
}
return 0;
}
| 4,347 | 1,482 |
/* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "2D.h"
#include "PathAnalysis.h"
#include "PathHelpers.h"
namespace mozilla {
namespace gfx {
static float CubicRoot(float aValue) {
if (aValue < 0.0) {
return -CubicRoot(-aValue);
}
else {
return powf(aValue, 1.0f / 3.0f);
}
}
struct BezierControlPoints
{
BezierControlPoints() {}
BezierControlPoints(const Point &aCP1, const Point &aCP2,
const Point &aCP3, const Point &aCP4)
: mCP1(aCP1), mCP2(aCP2), mCP3(aCP3), mCP4(aCP4)
{
}
Point mCP1, mCP2, mCP3, mCP4;
};
void
FlattenBezier(const BezierControlPoints &aPoints,
PathSink *aSink, Float aTolerance);
Path::Path()
{
}
Path::~Path()
{
}
Float
Path::ComputeLength()
{
EnsureFlattenedPath();
return mFlattenedPath->ComputeLength();
}
Point
Path::ComputePointAtLength(Float aLength, Point* aTangent)
{
EnsureFlattenedPath();
return mFlattenedPath->ComputePointAtLength(aLength, aTangent);
}
void
Path::EnsureFlattenedPath()
{
if (!mFlattenedPath) {
mFlattenedPath = new FlattenedPath();
StreamToSink(mFlattenedPath);
}
}
// This is the maximum deviation we allow (with an additional ~20% margin of
// error) of the approximation from the actual Bezier curve.
const Float kFlatteningTolerance = 0.0001f;
void
FlattenedPath::MoveTo(const Point &aPoint)
{
MOZ_ASSERT(!mCalculatedLength);
FlatPathOp op;
op.mType = FlatPathOp::OP_MOVETO;
op.mPoint = aPoint;
mPathOps.push_back(op);
mLastMove = aPoint;
}
void
FlattenedPath::LineTo(const Point &aPoint)
{
MOZ_ASSERT(!mCalculatedLength);
FlatPathOp op;
op.mType = FlatPathOp::OP_LINETO;
op.mPoint = aPoint;
mPathOps.push_back(op);
}
void
FlattenedPath::BezierTo(const Point &aCP1,
const Point &aCP2,
const Point &aCP3)
{
MOZ_ASSERT(!mCalculatedLength);
FlattenBezier(BezierControlPoints(CurrentPoint(), aCP1, aCP2, aCP3), this, kFlatteningTolerance);
}
void
FlattenedPath::QuadraticBezierTo(const Point &aCP1,
const Point &aCP2)
{
MOZ_ASSERT(!mCalculatedLength);
// We need to elevate the degree of this quadratic B�zier to cubic, so we're
// going to add an intermediate control point, and recompute control point 1.
// The first and last control points remain the same.
// This formula can be found on http://fontforge.sourceforge.net/bezier.html
Point CP0 = CurrentPoint();
Point CP1 = (CP0 + aCP1 * 2.0) / 3.0;
Point CP2 = (aCP2 + aCP1 * 2.0) / 3.0;
Point CP3 = aCP2;
BezierTo(CP1, CP2, CP3);
}
void
FlattenedPath::Close()
{
MOZ_ASSERT(!mCalculatedLength);
LineTo(mLastMove);
}
void
FlattenedPath::Arc(const Point &aOrigin, float aRadius, float aStartAngle,
float aEndAngle, bool aAntiClockwise)
{
ArcToBezier(this, aOrigin, Size(aRadius, aRadius), aStartAngle, aEndAngle, aAntiClockwise);
}
Float
FlattenedPath::ComputeLength()
{
if (!mCalculatedLength) {
Point currentPoint;
for (uint32_t i = 0; i < mPathOps.size(); i++) {
if (mPathOps[i].mType == FlatPathOp::OP_MOVETO) {
currentPoint = mPathOps[i].mPoint;
} else {
mCachedLength += Distance(currentPoint, mPathOps[i].mPoint);
currentPoint = mPathOps[i].mPoint;
}
}
mCalculatedLength = true;
}
return mCachedLength;
}
Point
FlattenedPath::ComputePointAtLength(Float aLength, Point *aTangent)
{
// We track the last point that -wasn't- in the same place as the current
// point so if we pass the edge of the path with a bunch of zero length
// paths we still get the correct tangent vector.
Point lastPointSinceMove;
Point currentPoint;
for (uint32_t i = 0; i < mPathOps.size(); i++) {
if (mPathOps[i].mType == FlatPathOp::OP_MOVETO) {
if (Distance(currentPoint, mPathOps[i].mPoint)) {
lastPointSinceMove = currentPoint;
}
currentPoint = mPathOps[i].mPoint;
} else {
Float segmentLength = Distance(currentPoint, mPathOps[i].mPoint);
if (segmentLength) {
lastPointSinceMove = currentPoint;
if (segmentLength > aLength) {
Point currentVector = mPathOps[i].mPoint - currentPoint;
Point tangent = currentVector / segmentLength;
if (aTangent) {
*aTangent = tangent;
}
return currentPoint + tangent * aLength;
}
}
aLength -= segmentLength;
currentPoint = mPathOps[i].mPoint;
}
}
Point currentVector = currentPoint - lastPointSinceMove;
if (aTangent) {
if (hypotf(currentVector.x, currentVector.y)) {
*aTangent = currentVector / hypotf(currentVector.x, currentVector.y);
} else {
*aTangent = Point();
}
}
return currentPoint;
}
// This function explicitly permits aControlPoints to refer to the same object
// as either of the other arguments.
static void
SplitBezier(const BezierControlPoints &aControlPoints,
BezierControlPoints *aFirstSegmentControlPoints,
BezierControlPoints *aSecondSegmentControlPoints,
Float t)
{
MOZ_ASSERT(aSecondSegmentControlPoints);
*aSecondSegmentControlPoints = aControlPoints;
Point cp1a = aControlPoints.mCP1 + (aControlPoints.mCP2 - aControlPoints.mCP1) * t;
Point cp2a = aControlPoints.mCP2 + (aControlPoints.mCP3 - aControlPoints.mCP2) * t;
Point cp1aa = cp1a + (cp2a - cp1a) * t;
Point cp3a = aControlPoints.mCP3 + (aControlPoints.mCP4 - aControlPoints.mCP3) * t;
Point cp2aa = cp2a + (cp3a - cp2a) * t;
Point cp1aaa = cp1aa + (cp2aa - cp1aa) * t;
aSecondSegmentControlPoints->mCP4 = aControlPoints.mCP4;
if(aFirstSegmentControlPoints) {
aFirstSegmentControlPoints->mCP1 = aControlPoints.mCP1;
aFirstSegmentControlPoints->mCP2 = cp1a;
aFirstSegmentControlPoints->mCP3 = cp1aa;
aFirstSegmentControlPoints->mCP4 = cp1aaa;
}
aSecondSegmentControlPoints->mCP1 = cp1aaa;
aSecondSegmentControlPoints->mCP2 = cp2aa;
aSecondSegmentControlPoints->mCP3 = cp3a;
}
static void
FlattenBezierCurveSegment(const BezierControlPoints &aControlPoints,
PathSink *aSink,
Float aTolerance)
{
/* The algorithm implemented here is based on:
* http://cis.usouthal.edu/~hain/general/Publications/Bezier/Bezier%20Offset%20Curves.pdf
*
* The basic premise is that for a small t the third order term in the
* equation of a cubic bezier curve is insignificantly small. This can
* then be approximated by a quadratic equation for which the maximum
* difference from a linear approximation can be much more easily determined.
*/
BezierControlPoints currentCP = aControlPoints;
Float t = 0;
while (t < 1.0f) {
Point cp21 = currentCP.mCP2 - currentCP.mCP3;
Point cp31 = currentCP.mCP3 - currentCP.mCP1;
/* To remove divisions and check for divide-by-zero, this is optimized from:
* Float s3 = (cp31.x * cp21.y - cp31.y * cp21.x) / hypotf(cp21.x, cp21.y);
* t = 2 * Float(sqrt(aTolerance / (3. * std::abs(s3))));
*/
Float cp21x31 = cp31.x * cp21.y - cp31.y * cp21.x;
Float h = hypotf(cp21.x, cp21.y);
if (cp21x31 * h == 0) {
break;
}
Float s3inv = h / cp21x31;
t = 2 * Float(sqrt(aTolerance * std::abs(s3inv) / 3.));
if (t >= 1.0f) {
break;
}
Point prevCP2, prevCP3, nextCP1, nextCP2, nextCP3;
SplitBezier(currentCP, nullptr, ¤tCP, t);
aSink->LineTo(currentCP.mCP1);
}
aSink->LineTo(currentCP.mCP4);
}
static inline void
FindInflectionApproximationRange(BezierControlPoints aControlPoints,
Float *aMin, Float *aMax, Float aT,
Float aTolerance)
{
SplitBezier(aControlPoints, nullptr, &aControlPoints, aT);
Point cp21 = aControlPoints.mCP2 - aControlPoints.mCP1;
Point cp41 = aControlPoints.mCP4 - aControlPoints.mCP1;
if (cp21.x == 0.f && cp21.y == 0.f) {
// In this case s3 becomes lim[n->0] (cp41.x * n) / n - (cp41.y * n) / n = cp41.x - cp41.y.
// Use the absolute value so that Min and Max will correspond with the
// minimum and maximum of the range.
*aMin = aT - CubicRoot(std::abs(aTolerance / (cp41.x - cp41.y)));
*aMax = aT + CubicRoot(std::abs(aTolerance / (cp41.x - cp41.y)));
return;
}
Float s3 = (cp41.x * cp21.y - cp41.y * cp21.x) / hypotf(cp21.x, cp21.y);
if (s3 == 0) {
// This means within the precision we have it can be approximated
// infinitely by a linear segment. Deal with this by specifying the
// approximation range as extending beyond the entire curve.
*aMin = -1.0f;
*aMax = 2.0f;
return;
}
Float tf = CubicRoot(std::abs(aTolerance / s3));
*aMin = aT - tf * (1 - aT);
*aMax = aT + tf * (1 - aT);
}
/* Find the inflection points of a bezier curve. Will return false if the
* curve is degenerate in such a way that it is best approximated by a straight
* line.
*
* The below algorithm was written by Jeff Muizelaar <jmuizelaar@mozilla.com>, explanation follows:
*
* The lower inflection point is returned in aT1, the higher one in aT2. In the
* case of a single inflection point this will be in aT1.
*
* The method is inspired by the algorithm in "analysis of in?ection points for planar cubic bezier curve"
*
* Here are some differences between this algorithm and versions discussed elsewhere in the literature:
*
* zhang et. al compute a0, d0 and e0 incrementally using the follow formula:
*
* Point a0 = CP2 - CP1
* Point a1 = CP3 - CP2
* Point a2 = CP4 - CP1
*
* Point d0 = a1 - a0
* Point d1 = a2 - a1
* Point e0 = d1 - d0
*
* this avoids any multiplications and may or may not be faster than the approach take below.
*
* "fast, precise flattening of cubic bezier path and ofset curves" by hain et. al
* Point a = CP1 + 3 * CP2 - 3 * CP3 + CP4
* Point b = 3 * CP1 - 6 * CP2 + 3 * CP3
* Point c = -3 * CP1 + 3 * CP2
* Point d = CP1
* the a, b, c, d can be expressed in terms of a0, d0 and e0 defined above as:
* c = 3 * a0
* b = 3 * d0
* a = e0
*
*
* a = 3a = a.y * b.x - a.x * b.y
* b = 3b = a.y * c.x - a.x * c.y
* c = 9c = b.y * c.x - b.x * c.y
*
* The additional multiples of 3 cancel each other out as show below:
*
* x = (-b + sqrt(b * b - 4 * a * c)) / (2 * a)
* x = (-3 * b + sqrt(3 * b * 3 * b - 4 * a * 3 * 9 * c / 3)) / (2 * 3 * a)
* x = 3 * (-b + sqrt(b * b - 4 * a * c)) / (2 * 3 * a)
* x = (-b + sqrt(b * b - 4 * a * c)) / (2 * a)
*
* I haven't looked into whether the formulation of the quadratic formula in
* hain has any numerical advantages over the one used below.
*/
static inline void
FindInflectionPoints(const BezierControlPoints &aControlPoints,
Float *aT1, Float *aT2, uint32_t *aCount)
{
// Find inflection points.
// See www.faculty.idc.ac.il/arik/quality/appendixa.html for an explanation
// of this approach.
Point A = aControlPoints.mCP2 - aControlPoints.mCP1;
Point B = aControlPoints.mCP3 - (aControlPoints.mCP2 * 2) + aControlPoints.mCP1;
Point C = aControlPoints.mCP4 - (aControlPoints.mCP3 * 3) + (aControlPoints.mCP2 * 3) - aControlPoints.mCP1;
Float a = Float(B.x) * C.y - Float(B.y) * C.x;
Float b = Float(A.x) * C.y - Float(A.y) * C.x;
Float c = Float(A.x) * B.y - Float(A.y) * B.x;
if (a == 0) {
// Not a quadratic equation.
if (b == 0) {
// Instead of a linear acceleration change we have a constant
// acceleration change. This means the equation has no solution
// and there are no inflection points, unless the constant is 0.
// In that case the curve is a straight line, essentially that means
// the easiest way to deal with is is by saying there's an inflection
// point at t == 0. The inflection point approximation range found will
// automatically extend into infinity.
if (c == 0) {
*aCount = 1;
*aT1 = 0;
return;
}
*aCount = 0;
return;
}
*aT1 = -c / b;
*aCount = 1;
return;
} else {
Float discriminant = b * b - 4 * a * c;
if (discriminant < 0) {
// No inflection points.
*aCount = 0;
} else if (discriminant == 0) {
*aCount = 1;
*aT1 = -b / (2 * a);
} else {
/* Use the following formula for computing the roots:
*
* q = -1/2 * (b + sign(b) * sqrt(b^2 - 4ac))
* t1 = q / a
* t2 = c / q
*/
Float q = sqrtf(discriminant);
if (b < 0) {
q = b - q;
} else {
q = b + q;
}
q *= Float(-1./2);
*aT1 = q / a;
*aT2 = c / q;
if (*aT1 > *aT2) {
std::swap(*aT1, *aT2);
}
*aCount = 2;
}
}
return;
}
void
FlattenBezier(const BezierControlPoints &aControlPoints,
PathSink *aSink, Float aTolerance)
{
Float t1;
Float t2;
uint32_t count;
FindInflectionPoints(aControlPoints, &t1, &t2, &count);
// Check that at least one of the inflection points is inside [0..1]
if (count == 0 || ((t1 < 0 || t1 > 1.0) && (count == 1 || (t2 < 0 || t2 > 1.0))) ) {
FlattenBezierCurveSegment(aControlPoints, aSink, aTolerance);
return;
}
Float t1min = t1, t1max = t1, t2min = t2, t2max = t2;
BezierControlPoints remainingCP = aControlPoints;
// For both inflection points, calulate the range where they can be linearly
// approximated if they are positioned within [0,1]
if (count > 0 && t1 >= 0 && t1 < 1.0) {
FindInflectionApproximationRange(aControlPoints, &t1min, &t1max, t1, aTolerance);
}
if (count > 1 && t2 >= 0 && t2 < 1.0) {
FindInflectionApproximationRange(aControlPoints, &t2min, &t2max, t2, aTolerance);
}
BezierControlPoints nextCPs = aControlPoints;
BezierControlPoints prevCPs;
// Process ranges. [t1min, t1max] and [t2min, t2max] are approximated by line
// segments.
if (count == 1 && t1min <= 0 && t1max >= 1.0) {
// The whole range can be approximated by a line segment.
aSink->LineTo(aControlPoints.mCP4);
return;
}
if (t1min > 0) {
// Flatten the Bezier up until the first inflection point's approximation
// point.
SplitBezier(aControlPoints, &prevCPs,
&remainingCP, t1min);
FlattenBezierCurveSegment(prevCPs, aSink, aTolerance);
}
if (t1max >= 0 && t1max < 1.0 && (count == 1 || t2min > t1max)) {
// The second inflection point's approximation range begins after the end
// of the first, approximate the first inflection point by a line and
// subsequently flatten up until the end or the next inflection point.
SplitBezier(aControlPoints, nullptr, &nextCPs, t1max);
aSink->LineTo(nextCPs.mCP1);
if (count == 1 || (count > 1 && t2min >= 1.0)) {
// No more inflection points to deal with, flatten the rest of the curve.
FlattenBezierCurveSegment(nextCPs, aSink, aTolerance);
}
} else if (count > 1 && t2min > 1.0) {
// We've already concluded t2min <= t1max, so if this is true the
// approximation range for the first inflection point runs past the
// end of the curve, draw a line to the end and we're done.
aSink->LineTo(aControlPoints.mCP4);
return;
}
if (count > 1 && t2min < 1.0 && t2max > 0) {
if (t2min > 0 && t2min < t1max) {
// In this case the t2 approximation range starts inside the t1
// approximation range.
SplitBezier(aControlPoints, nullptr, &nextCPs, t1max);
aSink->LineTo(nextCPs.mCP1);
} else if (t2min > 0 && t1max > 0) {
SplitBezier(aControlPoints, nullptr, &nextCPs, t1max);
// Find a control points describing the portion of the curve between t1max and t2min.
Float t2mina = (t2min - t1max) / (1 - t1max);
SplitBezier(nextCPs, &prevCPs, &nextCPs, t2mina);
FlattenBezierCurveSegment(prevCPs, aSink, aTolerance);
} else if (t2min > 0) {
// We have nothing interesting before t2min, find that bit and flatten it.
SplitBezier(aControlPoints, &prevCPs, &nextCPs, t2min);
FlattenBezierCurveSegment(prevCPs, aSink, aTolerance);
}
if (t2max < 1.0) {
// Flatten the portion of the curve after t2max
SplitBezier(aControlPoints, nullptr, &nextCPs, t2max);
// Draw a line to the start, this is the approximation between t2min and
// t2max.
aSink->LineTo(nextCPs.mCP1);
FlattenBezierCurveSegment(nextCPs, aSink, aTolerance);
} else {
// Our approximation range extends beyond the end of the curve.
aSink->LineTo(aControlPoints.mCP4);
return;
}
}
}
} // namespace gfx
} // namespace mozilla
| 16,845 | 6,300 |
#include "FileSystem/OsFileSync.h"
#include "Log/Log.h"
#include <exception>
namespace Rocket {
int32_t OsFileSync::Initialize(const std::string& path, const std::string& file_name, FileOperateMode mode) {
mode_ = mode;
file_.file_path = path;
file_.file_name = file_name;
file_.full_name = path + file_name;
return Initialize(file_.full_name.data(), mode_);
}
int32_t OsFileSync::Initialize(const std::string& path, FileOperateMode mode) {
mode_ = mode;
file_.full_name = path;
switch(mode_) {
case FileOperateMode::READ_BINARY: file_.file_pointer = (void*)fopen(file_.full_name.data(), "rb"); break;
case FileOperateMode::WRITE_BINARY: file_.file_pointer = (void*)fopen(file_.full_name.data(), "wb"); break;
case FileOperateMode::READ_TEXT: file_.file_pointer = (void*)fopen(file_.full_name.data(), "r"); break;
case FileOperateMode::WRITE_TEXT: file_.file_pointer = (void*)fopen(file_.full_name.data(), "w"); break;
default: break;
};
SeekToEnd();
file_.total_size = Tell();
Seek(0);
initialized_ = true;
RK_TRACE(File, "Open File {} Success", file_.full_name);
if(file_.file_pointer == nullptr)
return 1;
else
return 0;
}
void OsFileSync::Finalize() {
if(file_.file_pointer != nullptr)
fclose((FILE*)file_.file_pointer);
if(file_.extra_file_info != nullptr)
delete file_.extra_file_info;
initialized_ = false;
}
std::size_t OsFileSync::Read(FileBuffer& buffer, std::size_t length) {
if(mode_ == FileOperateMode::READ_BINARY) {
buffer.size = length;
buffer.buffer = new uint8_t[length];
auto result = fread(buffer.buffer, buffer.size, 1, (FILE*)file_.file_pointer);
if(result == 1)
return length;
else
return 0;
}
else if(mode_ == FileOperateMode::READ_TEXT) {
buffer.size = length + 1;
buffer.buffer = new uint8_t[length + 1];
auto result = fread(buffer.buffer, buffer.size, 1, (FILE*)file_.file_pointer);
static_cast<char*>(buffer.buffer)[length] = '\0';
if(result == 0)
return buffer.size;
else
return 0;
}
else {
return 0;
}
}
std::size_t OsFileSync::ReadAll(FileBuffer& buffer) {
if(mode_ == FileOperateMode::READ_BINARY || mode_ == FileOperateMode::READ_TEXT)
return Read(buffer, file_.total_size);
else
return 0;
}
std::size_t OsFileSync::Write(FileBuffer& buffer, std::size_t length) {
std::size_t real_length = 0;
if(length == 0 || length > buffer.size)
real_length = buffer.size;
else
real_length = length;
auto result = fwrite(buffer.buffer, real_length, 1, (FILE*)file_.file_pointer);
if(result == 1)
return length;
else
return 0;
}
std::size_t OsFileSync::WriteAll(FileBuffer& buffer) {
auto result = fwrite(buffer.buffer, buffer.size, 1, (FILE*)file_.file_pointer);
if(result == 1)
return buffer.size;
else
return 0;
}
void OsFileSync::Seek(std::size_t position) {
auto result = fseek((FILE*)file_.file_pointer, position, SEEK_SET);
if(result != 0) {
RK_ERROR(File, "{} File Seek {} Error", file_.full_name, position);
throw std::runtime_error("File Seek Error");
}
}
void OsFileSync::SeekToEnd(void) {
auto result = fseek((FILE*)file_.file_pointer, 0, SEEK_END);
if(result != 0) {
RK_ERROR(File, "{} File Seek End Error", file_.full_name);
throw std::runtime_error("File Seek End Error");
}
}
void OsFileSync::Skip(std::size_t bytes) {
auto result = fseek((FILE*)file_.file_pointer, bytes, SEEK_CUR);
if(result != 0) {
RK_ERROR(File, "{} File Skip {} Error", file_.full_name);
throw std::runtime_error("File Skip Error");
}
}
std::size_t OsFileSync::Tell(void) const {
std::size_t result = ftell((FILE*)file_.file_pointer);
return result;
}
}
| 4,437 | 1,402 |
#include "lnk4archive.h"
#include "../log.h"
#include "uncompressedstream.h"
#include "vfs.h"
#include "../util.h"
#include <SDL_endian.h>
namespace Impacto {
namespace Io {
struct Lnk4MetaEntry : FileMeta {
int64_t Offset;
};
Lnk4Archive::~Lnk4Archive() {
if (TOC) delete[] TOC;
}
IoError Lnk4Archive::Open(FileMeta* file, InputStream** outStream) {
Lnk4MetaEntry* entry = (Lnk4MetaEntry*)file;
IoError err = UncompressedStream::Create(BaseStream, entry->Offset,
entry->Size, outStream);
if (err != IoError_OK) {
ImpLog(LL_Error, LC_IO,
"LNK4 file open failed for file \"%s\" in archive \"%s\"\n",
entry->FileName.c_str(), BaseStream->Meta.FileName.c_str());
}
return err;
}
IoError Lnk4Archive::Create(InputStream* stream, VfsArchive** outArchive) {
ImpLog(LL_Trace, LC_IO, "Trying to mount \"%s\" as LNK4\n",
stream->Meta.FileName.c_str());
Lnk4Archive* result = 0;
uint32_t* rawToc = 0;
uint32_t offsetBlockSize = 2048;
uint32_t blockSize = 1024;
uint32_t const magic = 0x4C4E4B34;
uint32_t const tocOffset = 8;
uint32_t maxFileCount;
uint32_t fileCount;
uint32_t dataOffset;
char fileName[6];
if (ReadBE<uint32_t>(stream) != magic) {
ImpLog(LL_Trace, LC_IO, "Not LNK4\n");
goto fail;
}
dataOffset = ReadLE<uint32_t>(stream);
if (dataOffset < tocOffset) {
ImpLog(LL_Error, LC_IO, "LNK4 header too short\n");
goto fail;
}
maxFileCount = (dataOffset - tocOffset) / 8;
rawToc = (uint32_t*)ImpStackAlloc(dataOffset - tocOffset);
if (stream->Read(rawToc, dataOffset - tocOffset) != dataOffset - tocOffset)
goto fail;
fileCount = 0;
for (uint32_t* it = rawToc; it < rawToc + (maxFileCount * 2); it += 2) {
// first file starts at 0
if (SDL_SwapLE32(*it) == 0 && it != rawToc) break;
fileCount++;
}
result = new Lnk4Archive;
result->BaseStream = stream;
result->NamesToIds.reserve(fileCount);
result->IdsToFiles.reserve(fileCount);
result->TOC = new Lnk4MetaEntry[fileCount];
for (uint32_t i = 0; i < fileCount; i++) {
snprintf(fileName, 6, "%05i", i);
result->TOC[i].FileName = fileName;
result->TOC[i].Id = i;
result->TOC[i].Offset =
SDL_SwapLE32(rawToc[i * 2]) * offsetBlockSize + dataOffset;
result->TOC[i].Size = SDL_SwapLE32(rawToc[i * 2 + 1]) * blockSize;
result->IdsToFiles[i] = &result->TOC[i];
result->NamesToIds[result->TOC[i].FileName] = i;
}
ImpStackFree(rawToc);
result->IsInit = true;
*outArchive = result;
return IoError_OK;
fail:
stream->Seek(0, RW_SEEK_SET);
if (result) delete result;
if (rawToc) ImpStackFree(rawToc);
return IoError_Fail;
}
} // namespace Io
} // namespace Impacto | 2,756 | 1,145 |
#include "Environment/Template.hpp"
#include "Environment/TemplateInstance.hpp"
#include "Environment/ArgumentVariable.hpp"
#include "Environment/ASTCallNode.hpp"
#include "Environment/ASTSemanticAnalyzer.hpp"
#include "Environment/SSATemplate.hpp"
#include "Environment/BootstrapTypeRegistration.hpp"
#include "Environment/StringUtilities.hpp"
namespace Sysmel
{
namespace Environment
{
static BootstrapTypeRegistration<Template> templateTypeRegistration;
bool Template::isTemplate() const
{
return true;
}
void Template::recordChildProgramEntityDefinition(const ProgramEntityPtr &newChild)
{
children.push_back(newChild);
newChild->setParentProgramEntity(selfFromThis());
}
AnyValuePtr Template::getName() const
{
return name;
}
void Template::setName(const AnyValuePtr &newName)
{
name = newName;
}
SSAValuePtr Template::asSSAValueRequiredInPosition(const ASTSourcePositionPtr &)
{
if(!ssaTemplate)
{
ssaTemplate = basicMakeObject<SSATemplate> ();
ssaTemplate->setName(getValidName());
ssaTemplate->setExternalLanguageMode(externalLanguageMode);
ssaTemplate->setVisibility(visibility);
ssaTemplate->setDllLinkageMode(dllLinkageMode);
auto ssaParent = getParentProgramEntity()->asProgramEntitySSAValue();
if(ssaParent)
{
sysmelAssert(ssaParent->isSSAProgramEntity());
ssaParent.staticAs<SSAProgramEntity>()->addChild(ssaTemplate);
}
}
return ssaTemplate;
}
void Template::setDeclarationNode(const ASTNodePtr &node)
{
declarationPosition = node->sourcePosition;
declarationNode = node;
}
void Template::addDefinition(const ASTNodePtr &node, const ASTNodePtr &bodyNode, const ASTAnalysisEnvironmentPtr &bodyEnvironment)
{
definitionFragments.push_back({
node->sourcePosition,
node,
bodyNode,
bodyEnvironment
});
}
void Template::setArgumentTypes(const TypePtrList &argumentTypes)
{
arguments.reserve(argumentTypes.size());
for(const auto &type : argumentTypes)
{
auto argument = basicMakeObject<ArgumentVariable> ();
recordChildProgramEntityDefinition(argument);
argument->setType(type);
arguments.push_back(argument);
}
}
void Template::setArgumentDeclarationNode(size_t index, const ASTArgumentDefinitionNodePtr &argumentNode)
{
sysmelAssert(index < arguments.size());
arguments[index]->setArgumentDeclarationNode(argumentNode);
}
void Template::setArgumentDefinitionNode(size_t index, const ASTArgumentDefinitionNodePtr &argumentNode)
{
sysmelAssert(index < arguments.size());
arguments[index]->setArgumentDefinitionNode(argumentNode);
}
TemplateInstancePtr Template::getOrCreateTemplateInstanceWithArguments(const AnyValuePtrList &instanceArguments)
{
sysmelAssert(instanceArguments.size() == arguments.size());
auto it = instanceCache.find(instanceArguments);
if(it != instanceCache.end())
return it->second;
auto instance = basicMakeObject<TemplateInstance> ();
instanceCache.insert({instanceArguments, instance});
// TODO: Record this on a module specific program entity if needed.
recordChildProgramEntityDefinition(instance);
for(size_t i = 0; i < instanceArguments.size(); ++i)
instance->addArgumentBinding(arguments[i]->getName(), instanceArguments[i]);
for(auto &fragment : definitionFragments)
instance->evaluateDefinitionFragment(fragment);
return instance;
}
AnyValuePtr Template::getOrCreateTemplateInstanceValueWithArguments(const AnyValuePtrList &instanceArguments)
{
return getOrCreateTemplateInstanceWithArguments(instanceArguments)->getValue();
}
ASTNodePtr Template::analyzeCallNode(const ASTCallNodePtr &callNode, const ASTSemanticAnalyzerPtr &semanticAnalyzer)
{
if(callNode->arguments.size() != arguments.size())
return semanticAnalyzer->recordSemanticErrorInNode(callNode, formatString("Template {0} expects {1} arguments instead of the {2} provided arguments.",
{printString(), castToString(arguments.size()), castToString(callNode->arguments.size())}));
if(definitionFragments.empty())
return semanticAnalyzer->recordSemanticErrorInNode(callNode, formatString("Cannot instance template {0} without a definition body.", {printString()}));
auto templateInstanceNode = semanticAnalyzer->guardCompileTimeEvaluationForNode(callNode, [&](){
AnyValuePtrList instanceArguments;
instanceArguments.reserve(arguments.size());
bool hasError = false;
ASTNodePtr errorNode;
for(size_t i = 0; i < arguments.size(); ++i)
{
auto expectedType = arguments[i]->getValueType();
auto argumentNode = semanticAnalyzer->analyzeNodeIfNeededWithExpectedType(callNode->arguments[i], expectedType);
if(argumentNode->isASTErrorNode())
{
if(!hasError)
errorNode = argumentNode;
hasError = true;
continue;
}
auto argumentValue = semanticAnalyzer->evaluateInCompileTime(argumentNode);
if(validAnyValue(argumentValue)->isCompilationErrorValue())
{
if(!hasError)
errorNode = semanticAnalyzer->recordSemanticErrorInNode(callNode, "Failed to evaluate template instance argument.");
hasError = true;
continue;
}
instanceArguments.push_back(argumentValue);
}
if(hasError)
{
sysmelAssert(errorNode);
return errorNode;
}
return validAnyValue(getOrCreateTemplateInstanceValueWithArguments(instanceArguments))->asASTNodeRequiredInPosition(callNode->sourcePosition);
});
return semanticAnalyzer->analyzeNodeIfNeededWithCurrentExpectedType(templateInstanceNode);
}
} // End of namespace Environment
} // End of namespace Sysmel | 5,968 | 1,569 |
// -*- C++ -*-
//
// $Id: Acceptor_Registry.inl 73791 2006-07-27 20:54:56Z wotte $
TAO_BEGIN_VERSIONED_NAMESPACE_DECL
ACE_INLINE TAO_AcceptorSetIterator
TAO_Acceptor_Registry::begin (void)
{
return this->acceptors_;
}
ACE_INLINE TAO_AcceptorSetIterator
TAO_Acceptor_Registry::end (void)
{
return this->acceptors_ + this->size_;
}
TAO_END_VERSIONED_NAMESPACE_DECL
| 371 | 171 |
/*
* refit/scan/legacy.c
*
* Copyright (c) 2006-2010 Christoph Pfisterer
* 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 Christoph Pfisterer nor the names of the
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <Platform.h> // Only use angled for Platform, else, xcode project won't compile
#include "entry_scan.h"
#include "../refit/screen.h"
#include "../refit/menu.h"
#include "../gui/REFIT_MENU_SCREEN.h"
#include "../gui/REFIT_MAINMENU_SCREEN.h"
#include "../Platform/Volumes.h"
#include "../libeg/XTheme.h"
#include "../include/OSFlags.h"
#ifndef DEBUG_ALL
#define DEBUG_SCAN_LEGACY 1
#else
#define DEBUG_SCAN_LEGACY DEBUG_ALL
#endif
#if DEBUG_SCAN_LEGACY == 0
#define DBG(...)
#else
#define DBG(...) DebugLog(DEBUG_SCAN_LEGACY, __VA_ARGS__)
#endif
//the function is not in the class and deals always with MainMenu
//I made args as pointers to have an ability to call with NULL
XBool AddLegacyEntry(IN const XStringW& FullTitle, IN const XStringW& _LoaderTitle, IN REFIT_VOLUME *Volume, IN const XIcon* Image, IN const XIcon* DriveImage, IN char32_t Hotkey, IN XBool CustomEntry)
{
LEGACY_ENTRY *Entry, *SubEntry;
REFIT_MENU_SCREEN *SubScreen;
XStringW VolDesc;
CHAR16 ShortcutLetter = 0;
// INTN i;
DBG(" AddLegacyEntry:\n");
DBG(" FullTitle=%ls\n", FullTitle.wc_str());
DBG(" LoaderTitle=%ls\n", _LoaderTitle.wc_str());
DBG(" Volume->LegacyOS->Name=%ls\n", Volume->LegacyOS->Name.wc_str());
if (Volume == NULL) {
return false;
}
// Ignore this loader if it's device path is already present in another loader
for (UINTN i = 0; i < MainMenu.Entries.size(); ++i) {
REFIT_ABSTRACT_MENU_ENTRY& MainEntry = MainMenu.Entries[i];
// DBG("entry %lld\n", i);
// Only want legacy
if (MainEntry.getLEGACY_ENTRY()) {
if ( MainEntry.getLEGACY_ENTRY()->DevicePathString.isEqualIC(Volume->DevicePathString) ) {
return true;
}
}
}
XStringW LoaderTitle;
if ( _LoaderTitle.isEmpty() ) {
LoaderTitle = Volume->LegacyOS->Name;
}else{
LoaderTitle = _LoaderTitle;
}
XStringW LTitle;
if (LoaderTitle.isEmpty()) {
if (Volume->LegacyOS->Name.notEmpty()) {
LTitle.takeValueFrom(Volume->LegacyOS->Name);
if (Volume->LegacyOS->Name[0] == 'W' || Volume->LegacyOS->Name[0] == 'L')
ShortcutLetter = (wchar_t)Volume->LegacyOS->Name[0]; // cast safe because value is 'W' or 'L'
} else
LTitle = L"Legacy OS"_XSW;
} else
LTitle = LoaderTitle;
if (Volume->VolName.notEmpty())
VolDesc = Volume->VolName;
else
VolDesc.takeValueFrom((Volume->DiskKind == DISK_KIND_OPTICAL) ? L"CD" : L"HD");
//DBG("VolDesc=%ls\n", VolDesc);
// prepare the menu entry
Entry = new LEGACY_ENTRY;
if ( FullTitle.notEmpty() ) {
Entry->Title = FullTitle;
} else {
if (ThemeX.BootCampStyle) {
Entry->Title = LTitle;
} else {
Entry->Title.SWPrintf("Boot %ls from %ls", LoaderTitle.wc_str(), VolDesc.wc_str());
}
}
DBG(" Entry->Title=%ls\n", Entry->Title.wc_str());
Entry->Row = 0;
Entry->ShortcutLetter = (Hotkey == 0) ? ShortcutLetter : Hotkey;
if ( Image && !Image->isEmpty() ) {
Entry->Image = *Image;
} else {
Entry->Image = ThemeX.LoadOSIcon(Volume->LegacyOS->IconName);
if (Entry->Image.Image.isEmpty()) {
Entry->Image = ThemeX.GetIcon("os_win"_XS8); //we have no legacy.png
}
}
// DBG("IconName=%ls\n", Volume->LegacyOS->IconName);
Entry->DriveImage = (DriveImage != NULL) ? *DriveImage : ScanVolumeDefaultIcon(Volume, Volume->LegacyOS->Type, Volume->DevicePath);
// DBG("HideBadges=%d Volume=%ls\n", GlobalConfig.HideBadges, Volume->VolName);
// DBG("Title=%ls OSName=%ls OSIconName=%ls\n", LoaderTitle, Volume->OSName, Volume->OSIconName);
//actions
Entry->AtClick = ActionSelect;
Entry->AtDoubleClick = ActionEnter;
Entry->AtRightClick = ActionDetails;
if (ThemeX.HideBadges & HDBADGES_SHOW) {
if (ThemeX.HideBadges & HDBADGES_SWAP) { //will be scaled later
Entry->BadgeImage.Image = XImage(Entry->DriveImage.Image, 0); //ThemeX.BadgeScale/16.f); //0 accepted
} else {
Entry->BadgeImage.Image = XImage(Entry->Image.Image, 0); //ThemeX.BadgeScale/16.f);
}
}
Entry->Volume = Volume;
Entry->DevicePathString = Volume->DevicePathString;
// Entry->LoadOptions = (Volume->DiskKind == DISK_KIND_OPTICAL) ? "CD"_XS8 : ((Volume->DiskKind == DISK_KIND_EXTERNAL) ? "USB"_XS8 : "HD"_XS8);
Entry->LoadOptions.setEmpty();
Entry->LoadOptions.Add((Volume->DiskKind == DISK_KIND_OPTICAL) ? "CD" : ((Volume->DiskKind == DISK_KIND_EXTERNAL) ? "USB" : "HD"));
// If this isn't a custom entry make sure it's not hidden by a custom entry
if (!CustomEntry) {
for (size_t CustomIndex = 0 ; CustomIndex < GlobalConfig.CustomLegacyEntries.size() ; ++CustomIndex ) {
CUSTOM_LEGACY_ENTRY& Custom = GlobalConfig.CustomLegacyEntries[CustomIndex];
if ( Custom.settings.Disabled || OSFLAG_ISSET(Custom.getFlags(), OSFLAG_DISABLED) || Custom.settings.Hidden ) {
if (Custom.settings.Volume.notEmpty()) {
if ( !Volume->DevicePathString.contains(Custom.settings.Volume) && !Volume->VolName.contains(Custom.settings.Volume) ) {
if (Custom.settings.Type != 0) {
if (Custom.settings.Type == Volume->LegacyOS->Type) {
Entry->Hidden = true;
}
} else {
Entry->Hidden = true;
}
}
} else if (Custom.settings.Type != 0) {
if (Custom.settings.Type == Volume->LegacyOS->Type) {
Entry->Hidden = true;
}
}
}
}
}
// create the submenu
SubScreen = new REFIT_MENU_SCREEN;
// SubScreen->Title = L"Boot Options for "_XSW + LoaderTitle + L" on "_XSW + VolDesc;
SubScreen->Title.SWPrintf("Boot Options for %ls on %ls", LoaderTitle.wc_str(), VolDesc.wc_str());
SubScreen->TitleImage = Entry->Image; //it is XIcon
SubScreen->ID = SCREEN_BOOT;
SubScreen->GetAnime();
// default entry
SubEntry = new LEGACY_ENTRY;
SubEntry->Title = L"Boot "_XSW + LoaderTitle;
// SubEntry->Tag = TAG_LEGACY;
SubEntry->Volume = Entry->Volume;
SubEntry->DevicePathString = Entry->DevicePathString;
SubEntry->LoadOptions = Entry->LoadOptions;
SubEntry->AtClick = ActionEnter;
SubScreen->AddMenuEntry(SubEntry, true);
SubScreen->AddMenuEntry(&MenuEntryReturn, false);
Entry->SubScreen = SubScreen;
MainMenu.AddMenuEntry(Entry, true);
// DBG(" added '%ls' OSType=%d Icon=%ls\n", Entry->Title, Volume->LegacyOS->Type, Volume->LegacyOS->IconName);
return true;
}
void ScanLegacy(void)
{
UINTN VolumeIndex, VolumeIndex2;
XBool ShowVolume, HideIfOthersFound;
REFIT_VOLUME *Volume;
DBG("Scanning legacy ...\n");
for (VolumeIndex = 0; VolumeIndex < Volumes.size(); VolumeIndex++) {
Volume = &Volumes[VolumeIndex];
// DBG("test VI=%d\n", VolumeIndex);
if ((Volume->BootType != BOOTING_BY_PBR) &&
(Volume->BootType != BOOTING_BY_MBR) &&
(Volume->BootType != BOOTING_BY_CD)) {
// DBG(" not legacy\n");
continue;
}
// DBG("%2d: '%ls' (%ls)", VolumeIndex, Volume->VolName, Volume->LegacyOS->IconName);
#if 0 // REFIT_DEBUG > 0
DBG(" %d %ls\n %d %d %ls %d %ls\n",
VolumeIndex, FileDevicePathToStr(Volume->DevicePath),
Volume->DiskKind, Volume->MbrPartitionIndex,
Volume->IsAppleLegacy ? L"AL" : L"--", Volume->HasBootCode,
Volume->VolName ? Volume->VolName : L"(no name)");
#endif
// skip volume if its kind is configured as disabled
/* if ((Volume->DiskKind == DISK_KIND_OPTICAL && (GlobalConfig.DisableFlags & VOLTYPE_OPTICAL)) ||
(Volume->DiskKind == DISK_KIND_EXTERNAL && (GlobalConfig.DisableFlags & VOLTYPE_EXTERNAL)) ||
(Volume->DiskKind == DISK_KIND_INTERNAL && (GlobalConfig.DisableFlags & VOLTYPE_INTERNAL)) ||
(Volume->DiskKind == DISK_KIND_FIREWIRE && (GlobalConfig.DisableFlags & VOLTYPE_FIREWIRE))) */
if (((1ull<<Volume->DiskKind) & GlobalConfig.DisableFlags) != 0)
{
// DBG(" hidden\n");
continue;
}
// DBG("not hidden\n");
ShowVolume = false;
HideIfOthersFound = false;
if (Volume->IsAppleLegacy) {
ShowVolume = true;
HideIfOthersFound = true;
} else if (Volume->HasBootCode) {
ShowVolume = true;
// DBG("Volume %d will be shown BlockIo=%X WholeIo=%X\n",
// VolumeIndex, Volume->BlockIO, Volume->WholeDiskBlockIO);
if ((Volume->WholeDiskBlockIO == 0) &&
Volume->BlockIOOffset == 0 /* &&
Volume->OSName == NULL */)
// this is a whole disk (MBR) entry; hide if we have entries for partitions
HideIfOthersFound = true;
// DBG("Hide it!\n");
}
if (HideIfOthersFound) {
// check for other bootable entries on the same disk
//if PBR exists then Hide MBR
for (VolumeIndex2 = 0; VolumeIndex2 < Volumes.size(); VolumeIndex2++) {
// DBG("what to hide %d\n", VolumeIndex2);
if (VolumeIndex2 != VolumeIndex &&
Volumes[VolumeIndex2].HasBootCode &&
Volumes[VolumeIndex2].WholeDiskBlockIO == Volume->BlockIO){
ShowVolume = false;
// DBG("PBR volume at index %d\n", VolumeIndex2);
break;
}
}
}
if (ShowVolume && (!Volume->Hidden)){
// DBG(" add legacy\n");
if (!AddLegacyEntry(L""_XSW, L""_XSW, Volume, NULL, NULL, 0, false)) {
DBG("...entry not added\n");
};
} else {
DBG(" hidden\n");
}
}
}
// Add custom legacy
void AddCustomLegacy(void)
{
UINTN VolumeIndex, VolumeIndex2;
XBool ShowVolume, HideIfOthersFound;
REFIT_VOLUME *Volume;
XIcon MainIcon;
XIcon DriveIcon;
// DBG("Custom legacy start\n");
if (GlobalConfig.CustomLegacyEntries.notEmpty()) {
DbgHeader("AddCustomLegacy");
}
// Traverse the custom entries
for (size_t i = 0 ; i < GlobalConfig.CustomLegacyEntries.size() ; ++i ) {
CUSTOM_LEGACY_ENTRY& Custom = GlobalConfig.CustomLegacyEntries[i];
if (Custom.settings.Disabled || OSFLAG_ISSET(Custom.getFlags(), OSFLAG_DISABLED)) {
DBG("Custom legacy %zu skipped because it is disabled.\n", i);
continue;
}
// if (!gSettings.ShowHiddenEntries && OSFLAG_ISSET(Custom.Flags, OSFLAG_HIDDEN)) {
// DBG("Custom legacy %llu skipped because it is hidden.\n", i);
// continue;
// }
if (Custom.settings.Volume.notEmpty()) {
DBG("Custom legacy %zu matching \"%ls\" ...\n", i, Custom.settings.Volume.wc_str());
}
for (VolumeIndex = 0; VolumeIndex < Volumes.size(); ++VolumeIndex) {
Volume = &Volumes[VolumeIndex];
DBG(" Checking volume \"%ls\" (%ls) ... ", Volume->VolName.wc_str(), Volume->DevicePathString.wc_str());
// skip volume if its kind is configured as disabled
if (((1ull<<Volume->DiskKind) & GlobalConfig.DisableFlags) != 0)
{
DBG("skipped because media is disabled\n");
continue;
}
if (Custom.settings.VolumeType != 0) {
if (((1ull<<Volume->DiskKind) & Custom.settings.VolumeType) == 0) {
DBG("skipped because media is ignored\n");
continue;
}
}
if ((Volume->BootType != BOOTING_BY_PBR) &&
(Volume->BootType != BOOTING_BY_MBR) &&
(Volume->BootType != BOOTING_BY_CD)) {
DBG("skipped because volume is not legacy bootable\n");
continue;
}
ShowVolume = false;
HideIfOthersFound = false;
if (Volume->IsAppleLegacy) {
ShowVolume = true;
HideIfOthersFound = true;
} else if (Volume->HasBootCode) {
ShowVolume = true;
if ((Volume->WholeDiskBlockIO == 0) &&
Volume->BlockIOOffset == 0) {
// this is a whole disk (MBR) entry; hide if we have entries for partitions
HideIfOthersFound = true;
}
}
if (HideIfOthersFound) {
// check for other bootable entries on the same disk
//if PBR exists then Hide MBR
for (VolumeIndex2 = 0; VolumeIndex2 < Volumes.size(); VolumeIndex2++) {
if (VolumeIndex2 != VolumeIndex &&
Volumes[VolumeIndex2].HasBootCode &&
Volumes[VolumeIndex2].WholeDiskBlockIO == Volume->BlockIO) {
ShowVolume = false;
break;
}
}
}
if ( !ShowVolume ) {
DBG("skipped because volume ShowVolume==false\n");
continue;
}
if ( Volume->Hidden ) {
DBG("skipped because volume is hidden\n");
continue;
}
// Check for exact volume matches
if (Custom.settings.Volume.notEmpty()) {
if ((StrStr(Volume->DevicePathString.wc_str(), Custom.settings.Volume.wc_str()) == NULL) &&
((Volume->VolName.isEmpty()) || (StrStr(Volume->VolName.wc_str(), Custom.settings.Volume.wc_str()) == NULL))) {
DBG("skipped\n");
continue;
}
// Check if the volume should be of certain os type
if ((Custom.settings.Type != 0) && (Custom.settings.Type != Volume->LegacyOS->Type)) {
DBG("skipped because wrong type\n");
continue;
}
} else if ((Custom.settings.Type != 0) && (Custom.settings.Type != Volume->LegacyOS->Type)) {
DBG("skipped because wrong type\n");
continue;
}
// Change to custom image if needed
MainIcon = Custom.Image;
if (MainIcon.Image.isEmpty()) {
MainIcon.Image.LoadXImage(&ThemeX.getThemeDir(), Custom.settings.ImagePath);
}
// Change to custom drive image if needed
DriveIcon = Custom.DriveImage;
if (DriveIcon.Image.isEmpty()) {
DriveIcon.Image.LoadXImage(&ThemeX.getThemeDir(), Custom.settings.DriveImagePath);
}
// Create a legacy entry for this volume
DBG("\n");
if (AddLegacyEntry(Custom.settings.FullTitle, Custom.settings.Title, Volume, &MainIcon, &DriveIcon, Custom.settings.Hotkey, true))
{
// DBG("match!\n");
}
}
}
//DBG("Custom legacy end\n");
}
| 16,130 | 5,491 |
#include "decoration.hpp"
#include <spdlog/spdlog.h>
#include "protocols/wl/surface.hpp"
namespace Awning::Protocols::KDE::Decoration
{
const struct org_kde_kwin_server_decoration_interface interface = {
.release = Interface::Release,
.request_mode = Interface::Request_Mode,
};
std::unordered_map<wl_resource*,Instance> instances;
namespace Interface
{
void Release(struct wl_client *client, struct wl_resource *resource)
{
}
void Request_Mode(struct wl_client *client, struct wl_resource *resource, uint32_t mode)
{
auto surface = instances[resource].surface;
WL::Surface::instances[surface].window->Frame(mode == ORG_KDE_KWIN_SERVER_DECORATION_MANAGER_MODE_SERVER);
org_kde_kwin_server_decoration_send_mode(resource, mode);
}
}
wl_resource* Create(struct wl_client* wl_client, uint32_t version, uint32_t id, wl_resource* surface)
{
struct wl_resource* resource = wl_resource_create(wl_client, &org_kde_kwin_server_decoration_interface, version, id);
if (resource == nullptr) {
wl_client_post_no_memory(wl_client);
return resource;
}
wl_resource_set_implementation(resource, &interface, nullptr, Destroy);
instances[resource].surface = surface;
return resource;
}
void Destroy(struct wl_resource* resource)
{
}
}
namespace Awning::Protocols::KDE::Decoration_Manager
{
const struct org_kde_kwin_server_decoration_manager_interface interface = {
.create = Interface::Create,
};
namespace Interface
{
void Create(struct wl_client *client, struct wl_resource *resource, uint32_t id, struct wl_resource *surface)
{
Decoration::Create(client, 1, id, surface);
}
}
void Bind(struct wl_client* wl_client, void* data, uint32_t version, uint32_t id)
{
struct wl_resource* resource = wl_resource_create(wl_client, &org_kde_kwin_server_decoration_manager_interface, version, id);
if (resource == nullptr) {
wl_client_post_no_memory(wl_client);
return;
}
wl_resource_set_implementation(resource, &interface, data, nullptr);
org_kde_kwin_server_decoration_manager_send_default_mode(resource, ORG_KDE_KWIN_SERVER_DECORATION_MANAGER_MODE_SERVER);
}
wl_global* Add(struct wl_display* display, void* data)
{
return wl_global_create(display, &org_kde_kwin_server_decoration_manager_interface, 1, data, Bind);
}
} | 2,308 | 885 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/renderer/dom_storage/webstoragearea_impl.h"
#include "base/lazy_instance.h"
#include "base/metrics/histogram.h"
#include "base/time.h"
#include "base/utf_string_conversions.h"
#include "content/common/dom_storage_messages.h"
#include "content/renderer/dom_storage/dom_storage_dispatcher.h"
#include "content/renderer/render_thread_impl.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebURL.h"
#include "webkit/dom_storage/dom_storage_cached_area.h"
using dom_storage::DomStorageCachedArea;
using WebKit::WebString;
using WebKit::WebURL;
namespace content {
namespace {
typedef IDMap<WebStorageAreaImpl> AreaImplMap;
base::LazyInstance<AreaImplMap>::Leaky
g_all_areas_map = LAZY_INSTANCE_INITIALIZER;
DomStorageDispatcher* dispatcher() {
return RenderThreadImpl::current()->dom_storage_dispatcher();
}
} // namespace
// static
WebStorageAreaImpl* WebStorageAreaImpl::FromConnectionId(int id) {
return g_all_areas_map.Pointer()->Lookup(id);
}
WebStorageAreaImpl::WebStorageAreaImpl(
int64 namespace_id, const GURL& origin)
: ALLOW_THIS_IN_INITIALIZER_LIST(
connection_id_(g_all_areas_map.Pointer()->Add(this))),
cached_area_(dispatcher()->
OpenCachedArea(connection_id_, namespace_id, origin)) {
}
WebStorageAreaImpl::~WebStorageAreaImpl() {
g_all_areas_map.Pointer()->Remove(connection_id_);
if (dispatcher())
dispatcher()->CloseCachedArea(connection_id_, cached_area_);
}
unsigned WebStorageAreaImpl::length() {
return cached_area_->GetLength(connection_id_);
}
WebString WebStorageAreaImpl::key(unsigned index) {
return cached_area_->GetKey(connection_id_, index);
}
WebString WebStorageAreaImpl::getItem(const WebString& key) {
return cached_area_->GetItem(connection_id_, key);
}
void WebStorageAreaImpl::setItem(
const WebString& key, const WebString& value, const WebURL& page_url,
WebStorageArea::Result& result) {
if (!cached_area_->SetItem(connection_id_, key, value, page_url))
result = ResultBlockedByQuota;
else
result = ResultOK;
}
void WebStorageAreaImpl::removeItem(
const WebString& key, const WebURL& page_url) {
cached_area_->RemoveItem(connection_id_, key, page_url);
}
void WebStorageAreaImpl::clear(const WebURL& page_url) {
cached_area_->Clear(connection_id_, page_url);
}
size_t WebStorageAreaImpl::memoryBytesUsedByCache() const {
return cached_area_->MemoryBytesUsedByCache();
}
} // namespace content
| 2,642 | 885 |
#ifndef network_cpp
#define network_cpp
#include<bits/stdc++.h>
#include "customer.cpp"
#include "utilities.cpp"
using namespace std;
namespace Network
{
string sms_otp(string name,string number)
{
string processed_name;
for(int i=0;i<name.size() && name[i]!=' ';i++)
processed_name.push_back(name[i]);
string otp=Utilities::generate_otp();
string command="python3 sms_otp.py "+number+" "+otp+" "+processed_name;
cout<<"> Sending OTP.............\n";
system(command.c_str());
fstream file(".junk");
int status;
file>>status;
if(status==-1)
{
cout<<"> OTP Sending Faliure. Please Check Your Network And Try Later.\n";
string empty;
return empty;
}
cout<<"> OTP Sent Success\n";
return otp;
}
string mail_otp(string name,string email)
{
string processed_name;
for(int i=0;i<name.size() && name[i]!=' ';i++)
processed_name.push_back(name[i]);
string otp=Utilities::generate_otp();
string command="python3 mail_otp.py "+email+" "+otp+" "+processed_name;
cout<<"> Sending OTP.............\n";
system(command.c_str());
fstream file(".junk");
int status;
file>>status;
if(status==-1)
{
cout<<"> OTP Sending Faliure. Please Check Your Network And Try Later.\n";
string empty;
return empty;
}
cout<<"> OTP Sent Success\n";
return otp;
}
};
#endif | 1,415 | 488 |
#include "pch.h"
static void* GetModulePointer(HANDLE hProcess, const wchar_t* sDllPath) {
Utils::Win32Handle<> th32(CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, GetProcessId(hProcess)));
MODULEENTRY32W mod{ sizeof MODULEENTRY32W };
if (!Module32FirstW(th32, &mod))
return nullptr;
do {
if (_wcsicmp(mod.szExePath, sDllPath) == 0)
return mod.modBaseAddr;
} while (Module32NextW(th32, &mod));
return nullptr;
}
static std::wstring GetProcessExecutablePath(HANDLE hProcess) {
std::wstring sPath(PATHCCH_MAX_CCH, L'\0');
while (true) {
auto length = static_cast<DWORD>(sPath.size());
QueryFullProcessImageNameW(hProcess, 0, &sPath[0], &length);
if (length < sPath.size() - 1) {
sPath.resize(length);
break;
}
}
return sPath;
}
static int CallRemoteFunction(HANDLE hProcess, void* rpfn, void* rpParam) {
Utils::Win32Handle<> hLoadLibraryThread(CreateRemoteThread(hProcess, nullptr, 0, reinterpret_cast<LPTHREAD_START_ROUTINE>(rpfn), rpParam, 0, nullptr));
WaitForSingleObject(hLoadLibraryThread, INFINITE);
DWORD exitCode;
GetExitCodeThread(hLoadLibraryThread, &exitCode);
return exitCode;
}
static int InjectDll(HANDLE hProcess, const wchar_t* pszDllPath) {
const size_t nDllPathLength = wcslen(pszDllPath) + 1;
if (GetModulePointer(hProcess, pszDllPath))
return 0;
const auto nNumberOfBytes = nDllPathLength * sizeof pszDllPath[0];
void* rpszDllPath = VirtualAllocEx(hProcess, nullptr, nNumberOfBytes, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
if (!rpszDllPath)
return -1;
if (!WriteProcessMemory(hProcess, rpszDllPath, pszDllPath, nNumberOfBytes, nullptr)) {
VirtualFreeEx(hProcess, rpszDllPath, 0, MEM_RELEASE);
return -1;
}
const auto exitCode = CallRemoteFunction(hProcess, LoadLibraryW, rpszDllPath);
VirtualFreeEx(hProcess, rpszDllPath, 0, MEM_RELEASE);
return exitCode;
}
BOOL SetPrivilege(HANDLE hToken, LPCTSTR Privilege, BOOL bEnablePrivilege) {
TOKEN_PRIVILEGES tp;
LUID luid;
TOKEN_PRIVILEGES tpPrevious;
DWORD cbPrevious = sizeof(TOKEN_PRIVILEGES);
if (!LookupPrivilegeValue(NULL, Privilege, &luid)) return FALSE;
//
// first pass. get current privilege setting
//
tp.PrivilegeCount = 1;
tp.Privileges[0].Luid = luid;
tp.Privileges[0].Attributes = 0;
AdjustTokenPrivileges(
hToken,
FALSE,
&tp,
sizeof(TOKEN_PRIVILEGES),
&tpPrevious,
&cbPrevious
);
if (GetLastError() != ERROR_SUCCESS) return FALSE;
//
// second pass. set privilege based on previous setting
//
tpPrevious.PrivilegeCount = 1;
tpPrevious.Privileges[0].Luid = luid;
if (bEnablePrivilege)
tpPrevious.Privileges[0].Attributes |= (SE_PRIVILEGE_ENABLED);
else
tpPrevious.Privileges[0].Attributes ^= (SE_PRIVILEGE_ENABLED & tpPrevious.Privileges[0].Attributes);
AdjustTokenPrivileges(
hToken, FALSE, &tpPrevious, cbPrevious, NULL, NULL);
if (GetLastError() != ERROR_SUCCESS) return FALSE;
return TRUE;
}
const char* AddDebugPrivilege() {
Utils::Win32Handle<> token;
{
HANDLE hToken;
if (!OpenThreadToken(GetCurrentThread(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, FALSE, &hToken)) {
if (GetLastError() == ERROR_NO_TOKEN) {
if (!ImpersonateSelf(SecurityImpersonation))
return "ImpersonateSelf";
if (!OpenThreadToken(GetCurrentThread(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, FALSE, &hToken)) {
return "OpenThreadToken2";
}
} else
return "OpenThreadToken1";
}
token = hToken;
}
if (!SetPrivilege(token, SE_DEBUG_NAME, TRUE))
return "SetPrivilege";
return nullptr;
}
void* FindModuleAddress(HANDLE hProcess, const wchar_t* szDllPath) {
HMODULE hMods[1024];
DWORD cbNeeded;
unsigned int i;
bool skip = false;
if (EnumProcessModules(hProcess, hMods, sizeof(hMods), &cbNeeded)) {
for (i = 0; i < (cbNeeded / sizeof(HMODULE)); i++) {
WCHAR szModName[MAX_PATH];
if (GetModuleFileNameExW(hProcess, hMods[i], szModName, MAX_PATH)) {
if (wcsncmp(szModName, szDllPath, MAX_PATH) == 0)
return hMods[i];
}
}
}
return nullptr;
}
extern "C" __declspec(dllimport) int __stdcall LoadXivAlexander(void* lpReserved);
extern "C" __declspec(dllimport) int __stdcall UnloadXivAlexander(void* lpReserved);
int WINAPI wWinMain(
_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nShowCmd
) {
struct {
bool noask = false;
bool noerror = false;
} params;
int nArgs;
LPWSTR *szArgList = CommandLineToArgvW(lpCmdLine, &nArgs);
if (nArgs > 1) {
for (int i = 1; i < nArgs; i++) {
if (wcsncmp(L"/noask", szArgList[i], 6) == 0)
params.noask = true;
if (wcsncmp(L"/noerror", szArgList[i], 8) == 0)
params.noerror = true;
}
}
LocalFree(szArgList);
DWORD pid;
HWND hwnd = nullptr;
wchar_t szDllPath[PATHCCH_MAX_CCH] = { 0 };
GetModuleFileNameW(nullptr, szDllPath, _countof(szDllPath));
PathCchRemoveFileSpec(szDllPath, _countof(szDllPath));
PathCchAppend(szDllPath, _countof(szDllPath), L"XivAlexander.dll");
const auto szDebugPrivError = AddDebugPrivilege();
const std::wstring ProcessName(L"ffxiv_dx11.exe");
bool found = false;
while (hwnd = FindWindowExW(nullptr, hwnd, L"FFXIVGAME", nullptr)) {
GetWindowThreadProcessId(hwnd, &pid);
std::wstring sExePath;
try {
{
Utils::Win32Handle<> hProcess(OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid));
sExePath = GetProcessExecutablePath(hProcess);
}
if (sExePath.length() < ProcessName.length() || (0 != sExePath.compare(sExePath.length() - ProcessName.length(), ProcessName.length(), ProcessName)))
continue;
found = true;
void* rpModule;
{
Utils::Win32Handle<> hProcess(OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, false, pid));
rpModule = FindModuleAddress(hProcess, szDllPath);
}
std::wstring msg;
UINT nMsgType;
if (rpModule) {
msg = Utils::FormatString(
L"XivAlexander detected in FFXIV Process (%d:%s)\n"
L"Press Yes to try loading again if it hasn't loaded properly,\n"
L"Press No to skip,\n"
L"Press Cancel to unload.\n"
L"\n"
L"Note: your anti-virus software will probably classify DLL injection as a malicious action, "
L"and you will have to add both XivAlexanderLoader.exe and XivAlexander.dll to exceptions.",
static_cast<int>(pid), sExePath.c_str());
nMsgType = (MB_YESNOCANCEL | MB_ICONQUESTION | MB_DEFBUTTON1);
} else {
msg = Utils::FormatString(
L"FFXIV Process found (%d:%s)\n"
L"Continue loading XivAlexander into this process?\n"
L"\n"
L"Note: your anti-virus software will probably classify DLL injection as a malicious action, "
L"and you will have to add both XivAlexanderLoader.exe and XivAlexander.dll to exceptions.",
static_cast<int>(pid), sExePath.c_str());
nMsgType = (MB_YESNO | MB_DEFBUTTON1);
}
int response = params.noask ? IDYES : MessageBoxW(nullptr, msg.c_str(), L"XivAlexander Loader", nMsgType);
if (response == IDNO)
continue;
{
Utils::Win32Handle<> hProcess(OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_CREATE_THREAD | PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE, false, pid));
rpModule = FindModuleAddress(hProcess, szDllPath);
if (response == IDCANCEL && !rpModule)
continue;
if (!rpModule) {
InjectDll(hProcess, szDllPath);
rpModule = FindModuleAddress(hProcess, szDllPath);
}
DWORD loadResult = 0;
if (response == IDYES) {
loadResult = CallRemoteFunction(hProcess, LoadXivAlexander, nullptr);
if (loadResult != 0) {
response = IDCANCEL;
}
}
if (response == IDCANCEL) {
if (CallRemoteFunction(hProcess, UnloadXivAlexander, nullptr)) {
CallRemoteFunction(hProcess, FreeLibrary, rpModule);
}
}
if (loadResult)
throw std::exception(Utils::FormatString("Failed to start the addon: %d", loadResult).c_str());
}
} catch (std::exception& e) {
if (!params.noerror)
MessageBoxW(nullptr, Utils::FromUtf8(Utils::FormatString("PID %d: %s\nDebug Privilege: %s", pid, e.what(), szDebugPrivError ? szDebugPrivError : "OK")).c_str(), L"Error", MB_OK | MB_ICONERROR);
}
}
if (!found) {
if (!params.noerror)
MessageBoxW(nullptr, L"ffxiv_dx11.exe not found", L"Error", MB_OK | MB_ICONERROR);
}
return 0;
} | 8,236 | 3,539 |
/* Copyright 2017 - 2021 R. Thomas
* Copyright 2017 - 2021 Quarkslab
*
* 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 <numeric>
#include <iomanip>
#include <sstream>
#include "LIEF/PE/hash.hpp"
#include "LIEF/PE/Structures.hpp"
#include "LIEF/PE/EnumToString.hpp"
#include "LIEF/PE/CodeIntegrity.hpp"
namespace LIEF {
namespace PE {
CodeIntegrity::~CodeIntegrity() = default;
CodeIntegrity& CodeIntegrity::operator=(const CodeIntegrity&) = default;
CodeIntegrity::CodeIntegrity(const CodeIntegrity&) = default;
CodeIntegrity::CodeIntegrity() :
flags_{0},
catalog_{0},
catalog_offset_{0},
reserved_{0}
{}
CodeIntegrity::CodeIntegrity(const pe_code_integrity *header) :
flags_{header->Flags},
catalog_{header->Catalog},
catalog_offset_{header->CatalogOffset},
reserved_{header->Reserved}
{}
uint16_t CodeIntegrity::flags() const {
return this->flags_;
}
uint16_t CodeIntegrity::catalog() const {
return this->catalog_;
}
uint32_t CodeIntegrity::catalog_offset() const {
return this->catalog_offset_;
}
uint32_t CodeIntegrity::reserved() const {
return this->reserved_;
}
void CodeIntegrity::flags(uint16_t flags) {
this->flags_ = flags;
}
void CodeIntegrity::catalog(uint16_t catalog) {
this->catalog_ = catalog;
}
void CodeIntegrity::catalog_offset(uint32_t catalog_offset) {
this->catalog_offset_ = catalog_offset;
}
void CodeIntegrity::reserved(uint32_t reserved) {
this->reserved_ = reserved;
}
void CodeIntegrity::accept(LIEF::Visitor& visitor) const {
visitor.visit(*this);
}
bool CodeIntegrity::operator==(const CodeIntegrity& rhs) const {
size_t hash_lhs = Hash::hash(*this);
size_t hash_rhs = Hash::hash(rhs);
return hash_lhs == hash_rhs;
}
bool CodeIntegrity::operator!=(const CodeIntegrity& rhs) const {
return not (*this == rhs);
}
std::ostream& operator<<(std::ostream& os, const CodeIntegrity& entry) {
os << std::hex << std::left << std::showbase;
os << std::setw(CodeIntegrity::PRINT_WIDTH) << std::setfill(' ') << "Flags:" << std::hex << entry.flags() << std::endl;
os << std::setw(CodeIntegrity::PRINT_WIDTH) << std::setfill(' ') << "Catalog:" << std::hex << entry.catalog() << std::endl;
os << std::setw(CodeIntegrity::PRINT_WIDTH) << std::setfill(' ') << "Catalog offset:" << std::hex << entry.catalog_offset() << std::endl;
os << std::setw(CodeIntegrity::PRINT_WIDTH) << std::setfill(' ') << "Reserved:" << std::hex << entry.reserved() << std::endl;
return os;
}
}
}
| 3,029 | 1,029 |
#include "FBPostProcessor.hh"
#include "RawFrame.hh"
#include "StretchScalerOutput.hh"
#include "ScalerOutput.hh"
#include "RenderSettings.hh"
#include "Scaler.hh"
#include "ScalerFactory.hh"
#include "SDLOutputSurface.hh"
#include "aligned.hh"
#include "checked_cast.hh"
#include "random.hh"
#include "xrange.hh"
#include <algorithm>
#include <cassert>
#include <cmath>
#include <cstdint>
#include <cstddef>
#include <numeric>
#ifdef __SSE2__
#include <emmintrin.h>
#endif
namespace openmsx {
constexpr unsigned NOISE_SHIFT = 8192;
constexpr unsigned NOISE_BUF_SIZE = 2 * NOISE_SHIFT;
ALIGNAS_SSE static signed char noiseBuf[NOISE_BUF_SIZE];
template<typename Pixel>
void FBPostProcessor<Pixel>::preCalcNoise(float factor)
{
// We skip noise drawing if the factor is 0, so there is no point in
// initializing the random data in that case.
if (factor == 0.0f) return;
// for 32bpp groups of 4 consecutive noiseBuf elements (starting at
// 4 element boundaries) must have the same value. Later optimizations
// depend on it.
float scale[4];
if (sizeof(Pixel) == 4) {
// 32bpp
// TODO ATM we compensate for big endian here. A better
// alternative is to turn noiseBuf into an array of ints (it's
// now bytes) and in the 16bpp code extract R,G,B components
// from those ints
const auto p = Pixel(OPENMSX_BIGENDIAN ? 0x00010203
: 0x03020100);
// TODO we can also fill the array with 'factor' and only set
// 'alpha' to 0.0. But PixelOperations doesn't offer a simple
// way to get the position of the alpha byte (yet).
scale[0] = scale[1] = scale[2] = scale[3] = 0.0f;
scale[pixelOps.red (p)] = factor;
scale[pixelOps.green(p)] = factor;
scale[pixelOps.blue (p)] = factor;
} else {
// 16bpp
scale[0] = (pixelOps.getMaxRed() / 255.0f) * factor;
scale[1] = (pixelOps.getMaxGreen() / 255.0f) * factor;
scale[2] = (pixelOps.getMaxBlue() / 255.0f) * factor;
scale[3] = 0.0f;
}
auto& generator = global_urng(); // fast (non-cryptographic) random numbers
std::normal_distribution<float> distribution(0.0f, 1.0f);
for (unsigned i = 0; i < NOISE_BUF_SIZE; i += 4) {
float r = distribution(generator);
noiseBuf[i + 0] = std::clamp(int(roundf(r * scale[0])), -128, 127);
noiseBuf[i + 1] = std::clamp(int(roundf(r * scale[1])), -128, 127);
noiseBuf[i + 2] = std::clamp(int(roundf(r * scale[2])), -128, 127);
noiseBuf[i + 3] = std::clamp(int(roundf(r * scale[3])), -128, 127);
}
}
#ifdef __SSE2__
static inline void drawNoiseLineSse2(uint32_t* buf_, signed char* noise, size_t width)
{
// To each of the RGBA color components (a value in range [0..255]) we
// want to add a signed noise value (in range [-128..127]) and also clip
// the result to the range [0..255]. There is no SSE instruction that
// directly performs this operation. But we can:
// - subtract 128 from the RGBA component to get a signed byte
// - perform the addition with signed saturation
// - add 128 to the result to get back to the unsigned byte range
// For 8-bit values the following 3 expressions are equivalent:
// x + 128 == x - 128 == x ^ 128
// So the expression becomes:
// signed_add_sat(value ^ 128, noise) ^ 128
// The following loop does just that, though it processes 64 bytes per
// iteration.
ptrdiff_t x = width * sizeof(uint32_t);
assert((x & 63) == 0);
assert((uintptr_t(buf_) & 15) == 0);
char* buf = reinterpret_cast<char*>(buf_) + x;
char* nse = reinterpret_cast<char*>(noise) + x;
x = -x;
__m128i b7 = _mm_set1_epi8(-128); // 0x80
do {
__m128i i0 = _mm_load_si128(reinterpret_cast<__m128i*>(buf + x + 0));
__m128i i1 = _mm_load_si128(reinterpret_cast<__m128i*>(buf + x + 16));
__m128i i2 = _mm_load_si128(reinterpret_cast<__m128i*>(buf + x + 32));
__m128i i3 = _mm_load_si128(reinterpret_cast<__m128i*>(buf + x + 48));
__m128i n0 = _mm_load_si128(reinterpret_cast<__m128i*>(nse + x + 0));
__m128i n1 = _mm_load_si128(reinterpret_cast<__m128i*>(nse + x + 16));
__m128i n2 = _mm_load_si128(reinterpret_cast<__m128i*>(nse + x + 32));
__m128i n3 = _mm_load_si128(reinterpret_cast<__m128i*>(nse + x + 48));
__m128i o0 = _mm_xor_si128(_mm_adds_epi8(_mm_xor_si128(i0, b7), n0), b7);
__m128i o1 = _mm_xor_si128(_mm_adds_epi8(_mm_xor_si128(i1, b7), n1), b7);
__m128i o2 = _mm_xor_si128(_mm_adds_epi8(_mm_xor_si128(i2, b7), n2), b7);
__m128i o3 = _mm_xor_si128(_mm_adds_epi8(_mm_xor_si128(i3, b7), n3), b7);
_mm_store_si128(reinterpret_cast<__m128i*>(buf + x + 0), o0);
_mm_store_si128(reinterpret_cast<__m128i*>(buf + x + 16), o1);
_mm_store_si128(reinterpret_cast<__m128i*>(buf + x + 32), o2);
_mm_store_si128(reinterpret_cast<__m128i*>(buf + x + 48), o3);
x += 4 * sizeof(__m128i);
} while (x < 0);
}
#endif
/** Add noise to the given pixel.
* @param p contains 4 8-bit unsigned components, so components have range [0, 255]
* @param n contains 4 8-bit signed components, so components have range [-128, 127]
* @result per component result of clip<0, 255>(p + n)
*/
static constexpr uint32_t addNoise4(uint32_t p, uint32_t n)
{
// unclipped result (lower 8 bits of each component)
// alternative:
// uint32_t s20 = ((p & 0x00FF00FF) + (n & 0x00FF00FF)) & 0x00FF00FF;
// uint32_t s31 = ((p & 0xFF00FF00) + (n & 0xFF00FF00)) & 0xFF00FF00;
// uint32_t s = s20 | s31;
uint32_t s0 = p + n; // carry spills to neighbors
uint32_t ci = (p ^ n ^ s0) & 0x01010100; // carry-in bits of prev sum
uint32_t s = s0 - ci; // subtract carry bits again
// Underflow of a component happens ONLY
// WHEN input component is in range [0, 127]
// AND noise component is negative
// AND result component is in range [128, 255]
// Overflow of a component happens ONLY
// WHEN input component in in range [128, 255]
// AND noise component is positive
// AND result component is in range [0, 127]
// Create a mask per component containing 00 for no under/overflow,
// FF for under/overflow
// ((~p & n & s) | (p & ~n & ~s)) == ((p ^ n) & (p ^ s))
uint32_t t = (p ^ n) & (p ^ s) & 0x80808080;
uint32_t u1 = t & s; // underflow (alternative: u1 = t & n)
// alternative1: uint32_t u2 = u1 | (u1 >> 1);
// uint32_t u4 = u2 | (u2 >> 2);
// uint32_t u8 = u4 | (u4 >> 4);
// alternative2: uint32_t u8 = (u1 >> 7) * 0xFF;
uint32_t u8 = (u1 << 1) - (u1 >> 7);
uint32_t o1 = t & p; // overflow
uint32_t o8 = (o1 << 1) - (o1 >> 7);
// clip result
return (s & (~u8)) | o8;
}
template<typename Pixel>
void FBPostProcessor<Pixel>::drawNoiseLine(
Pixel* buf, signed char* noise, size_t width)
{
#ifdef __SSE2__
if (sizeof(Pixel) == 4) {
// cast to avoid compilation error in case of 16bpp (even
// though this code is dead in that case).
auto* buf32 = reinterpret_cast<uint32_t*>(buf);
drawNoiseLineSse2(buf32, noise, width);
return;
}
#endif
// c++ version
if (sizeof(Pixel) == 4) {
// optimized version for 32bpp
auto* noise4 = reinterpret_cast<uint32_t*>(noise);
for (auto i : xrange(width)) {
buf[i] = addNoise4(buf[i], noise4[i]);
}
} else {
int mr = pixelOps.getMaxRed();
int mg = pixelOps.getMaxGreen();
int mb = pixelOps.getMaxBlue();
for (auto i : xrange(width)) {
Pixel p = buf[i];
int r = pixelOps.red(p);
int g = pixelOps.green(p);
int b = pixelOps.blue(p);
r += noise[4 * i + 0];
g += noise[4 * i + 1];
b += noise[4 * i + 2];
r = std::min(std::max(r, 0), mr);
g = std::min(std::max(g, 0), mg);
b = std::min(std::max(b, 0), mb);
buf[i] = pixelOps.combine(r, g, b);
}
}
}
template<typename Pixel>
void FBPostProcessor<Pixel>::drawNoise(OutputSurface& output_)
{
if (renderSettings.getNoise() == 0.0f) return;
auto& output = checked_cast<SDLOutputSurface&>(output_);
auto [w, h] = output.getLogicalSize();
auto pixelAccess = output.getDirectPixelAccess();
for (auto y : xrange(h)) {
auto* buf = pixelAccess.getLinePtr<Pixel>(y);
drawNoiseLine(buf, &noiseBuf[noiseShift[y]], w);
}
}
template<typename Pixel>
void FBPostProcessor<Pixel>::update(const Setting& setting) noexcept
{
VideoLayer::update(setting);
auto& noiseSetting = renderSettings.getNoiseSetting();
if (&setting == &noiseSetting) {
preCalcNoise(noiseSetting.getDouble());
}
}
template<typename Pixel>
FBPostProcessor<Pixel>::FBPostProcessor(MSXMotherBoard& motherBoard_,
Display& display_, OutputSurface& screen_, const std::string& videoSource,
unsigned maxWidth_, unsigned height_, bool canDoInterlace_)
: PostProcessor(
motherBoard_, display_, screen_, videoSource, maxWidth_, height_,
canDoInterlace_)
, noiseShift(screen.getLogicalHeight())
, pixelOps(screen.getPixelFormat())
{
scaleAlgorithm = RenderSettings::NO_SCALER;
scaleFactor = unsigned(-1);
stretchWidth = unsigned(-1);
auto& noiseSetting = renderSettings.getNoiseSetting();
noiseSetting.attach(*this);
preCalcNoise(noiseSetting.getDouble());
assert((screen.getLogicalWidth() * sizeof(Pixel)) < NOISE_SHIFT);
}
template<typename Pixel>
FBPostProcessor<Pixel>::~FBPostProcessor()
{
renderSettings.getNoiseSetting().detach(*this);
}
template<typename Pixel>
void FBPostProcessor<Pixel>::paint(OutputSurface& output_)
{
auto& output = checked_cast<SDLOutputSurface&>(output_);
if (renderSettings.getInterleaveBlackFrame()) {
interleaveCount ^= 1;
if (interleaveCount) {
output.clearScreen();
return;
}
}
if (!paintFrame) return;
// New scaler algorithm selected? Or different horizontal stretch?
auto algo = renderSettings.getScaleAlgorithm();
unsigned factor = renderSettings.getScaleFactor();
unsigned inWidth = lrintf(renderSettings.getHorizontalStretch());
if ((scaleAlgorithm != algo) || (scaleFactor != factor) ||
(inWidth != stretchWidth) || (lastOutput != &output)) {
scaleAlgorithm = algo;
scaleFactor = factor;
stretchWidth = inWidth;
lastOutput = &output;
currScaler = ScalerFactory<Pixel>::createScaler(
PixelOperations<Pixel>(output.getPixelFormat()),
renderSettings);
stretchScaler = StretchScalerOutputFactory<Pixel>::create(
output, pixelOps, inWidth);
}
// Scale image.
const unsigned srcHeight = paintFrame->getHeight();
const unsigned dstHeight = output.getLogicalHeight();
unsigned g = std::gcd(srcHeight, dstHeight);
unsigned srcStep = srcHeight / g;
unsigned dstStep = dstHeight / g;
// TODO: Store all MSX lines in RawFrame and only scale the ones that fit
// on the PC screen, as a preparation for resizable output window.
unsigned srcStartY = 0;
unsigned dstStartY = 0;
while (dstStartY < dstHeight) {
// Currently this is true because the source frame height
// is always >= dstHeight/(dstStep/srcStep).
assert(srcStartY < srcHeight);
// get region with equal lineWidth
unsigned lineWidth = getLineWidth(paintFrame, srcStartY, srcStep);
unsigned srcEndY = srcStartY + srcStep;
unsigned dstEndY = dstStartY + dstStep;
while ((srcEndY < srcHeight) && (dstEndY < dstHeight) &&
(getLineWidth(paintFrame, srcEndY, srcStep) == lineWidth)) {
srcEndY += srcStep;
dstEndY += dstStep;
}
// fill region
//fprintf(stderr, "post processing lines %d-%d: %d\n",
// srcStartY, srcEndY, lineWidth);
currScaler->scaleImage(
*paintFrame, superImposeVideoFrame,
srcStartY, srcEndY, lineWidth, // source
*stretchScaler, dstStartY, dstEndY); // dest
// next region
srcStartY = srcEndY;
dstStartY = dstEndY;
}
drawNoise(output);
output.flushFrameBuffer();
}
template<typename Pixel>
std::unique_ptr<RawFrame> FBPostProcessor<Pixel>::rotateFrames(
std::unique_ptr<RawFrame> finishedFrame, EmuTime::param time)
{
auto& generator = global_urng(); // fast (non-cryptographic) random numbers
std::uniform_int_distribution<int> distribution(0, NOISE_SHIFT / 16 - 1);
for (auto y : xrange(screen.getLogicalHeight())) {
noiseShift[y] = distribution(generator) * 16;
}
return PostProcessor::rotateFrames(std::move(finishedFrame), time);
}
// Force template instantiation.
#if HAVE_16BPP
template class FBPostProcessor<uint16_t>;
#endif
#if HAVE_32BPP
template class FBPostProcessor<uint32_t>;
#endif
} // namespace openmsx
| 12,218 | 5,060 |
#include "Basic2DGenericPFlowPositionCalc.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "FWCore/Utilities/interface/isFinite.h"
#include <cmath>
#include "CommonTools/Utils/interface/DynArray.h"
#include<iterator>
#include <boost/function_output_iterator.hpp>
#include "vdt/vdtMath.h"
namespace {
inline
bool isBarrel(int cell_layer){
return (cell_layer == PFLayer::HCAL_BARREL1 ||
cell_layer == PFLayer::HCAL_BARREL2 ||
cell_layer == PFLayer::ECAL_BARREL);
}
}
void Basic2DGenericPFlowPositionCalc::
calculateAndSetPosition(reco::PFCluster& cluster) {
calculateAndSetPositionActual(cluster);
}
void Basic2DGenericPFlowPositionCalc::
calculateAndSetPositions(reco::PFClusterCollection& clusters) {
for( reco::PFCluster& cluster : clusters ) {
calculateAndSetPositionActual(cluster);
}
}
void Basic2DGenericPFlowPositionCalc::
calculateAndSetPositionActual(reco::PFCluster& cluster) const {
if( !cluster.seed() ) {
throw cms::Exception("ClusterWithNoSeed")
<< " Found a cluster with no seed: " << cluster;
}
double cl_energy = 0;
double cl_time = 0;
double cl_timeweight=0.0;
double max_e = 0.0;
PFLayer::Layer max_e_layer = PFLayer::NONE;
// find the seed and max layer and also calculate time
//Michalis : Even if we dont use timing in clustering here we should fill
//the time information for the cluster. This should use the timing resolution(1/E)
//so the weight should be fraction*E^2
//calculate a simplistic depth now. The log weighted will be done
//in different stage
auto const recHitCollection = &(*cluster.recHitFractions()[0].recHitRef()) - cluster.recHitFractions()[0].recHitRef().key();
auto nhits = cluster.recHitFractions().size();
struct LHit{ reco::PFRecHit const * hit; float energy; float fraction;};
declareDynArray(LHit,nhits,hits);
for(auto i=0U; i<nhits; ++i) {
auto const & hf = cluster.recHitFractions()[i];
auto k = hf.recHitRef().key();
auto p = recHitCollection+k;
hits[i]= {p,(*p).energy(), float(hf.fraction())};
}
bool resGiven = bool(_timeResolutionCalcBarrel) & bool(_timeResolutionCalcEndcap);
LHit mySeed={nullptr};
for( auto const & rhf : hits ) {
const reco::PFRecHit & refhit = *rhf.hit;
if( refhit.detId() == cluster.seed() ) mySeed = rhf;
const auto rh_fraction = rhf.fraction;
const auto rh_rawenergy = rhf.energy;
const auto rh_energy = rh_rawenergy * rh_fraction;
#ifdef PF_DEBUG
if UNLIKELY( edm::isNotFinite(rh_energy) ) {
throw cms::Exception("PFClusterAlgo")
<<"rechit " << refhit.detId() << " has a NaN energy... "
<< "The input of the particle flow clustering seems to be corrupted.";
}
#endif
cl_energy += rh_energy;
// If time resolution is given, calculated weighted average
if ( resGiven ) {
double res2 = 1.e-4;
int cell_layer = (int)refhit.layer();
res2 = isBarrel(cell_layer) ? 1./_timeResolutionCalcBarrel->timeResolution2(rh_rawenergy) :
1./_timeResolutionCalcEndcap->timeResolution2(rh_rawenergy);
cl_time += rh_fraction*refhit.time()*res2;
cl_timeweight += rh_fraction*res2;
}
else { // assume resolution = 1/E**2
const double rh_rawenergy2 = rh_rawenergy*rh_rawenergy;
cl_timeweight+=rh_rawenergy2*rh_fraction;
cl_time += rh_rawenergy2*rh_fraction*refhit.time();
}
if( rh_energy > max_e ) {
max_e = rh_energy;
max_e_layer = refhit.layer();
}
}
cluster.setEnergy(cl_energy);
cluster.setTime(cl_time/cl_timeweight);
if (resGiven) {
cluster.setTimeError(std::sqrt(1.0f/float(cl_timeweight)));
}
cluster.setLayer(max_e_layer);
// calculate the position
double depth = 0.0;
double position_norm = 0.0;
double x(0.0),y(0.0),z(0.0);
if( nullptr != mySeed.hit ) {
auto seedNeighbours = mySeed.hit->neighbours();
switch( _posCalcNCrystals ) {
case 5:
seedNeighbours = mySeed.hit->neighbours4();
break;
case 9:
seedNeighbours = mySeed.hit->neighbours8();
break;
default:
break;
}
auto compute = [&](LHit const& rhf) {
const reco::PFRecHit & refhit = *rhf.hit;
int cell_layer = (int)refhit.layer();
float threshold=0;
for (unsigned int j=0; j<(std::get<2>(_logWeightDenom)).size(); ++j) {
// barrel is detecor type1
int detectorEnum=std::get<0>(_logWeightDenom)[j];
int depth=std::get<1>(_logWeightDenom)[j];
if( ( cell_layer == PFLayer::HCAL_BARREL1 && detectorEnum==1 && refhit.depth()== depth)
|| ( cell_layer == PFLayer::HCAL_ENDCAP && detectorEnum==2 && refhit.depth()== depth)
|| detectorEnum==0
) threshold=std::get<2>(_logWeightDenom)[j];
}
const auto rh_energy = rhf.energy * rhf.fraction;
const auto norm = ( rhf.fraction < _minFractionInCalc ?
0.0f :
std::max(0.0f,vdt::fast_logf(rh_energy*threshold)) );
const auto rhpos_xyz = refhit.position()*norm;
x += rhpos_xyz.x();
y += rhpos_xyz.y();
z += rhpos_xyz.z();
depth += refhit.depth()*norm;
position_norm += norm;
};
if(_posCalcNCrystals != -1) // sorted to make neighbour search faster (maybe)
std::sort(hits.begin(),hits.end(),[](LHit const& a, LHit const& b) { return a.hit<b.hit;});
if(_posCalcNCrystals == -1)
for( auto const & rhf : hits ) compute(rhf);
else { // only seed and its neighbours
compute(mySeed);
// search seedNeighbours to find energy fraction in cluster (sic)
unInitDynArray(reco::PFRecHit const *,seedNeighbours.size(),nei);
for(auto k : seedNeighbours){
nei.push_back(recHitCollection+k);
}
std::sort(nei.begin(),nei.end());
struct LHitLess {
auto operator()(LHit const &a, reco::PFRecHit const * b) const {return a.hit<b;}
auto operator()(reco::PFRecHit const * b, LHit const &a) const {return b<a.hit;}
};
std::set_intersection(hits.begin(),hits.end(),nei.begin(),nei.end(),
boost::make_function_output_iterator(compute),
LHitLess()
);
}
} else {
throw cms::Exception("Basic2DGenerticPFlowPositionCalc")
<< "Cluster seed hit is null, something is wrong with PFlow RecHit!";
}
if( position_norm < _minAllowedNorm ) {
edm::LogError("WeirdClusterNormalization")
<< "PFCluster too far from seeding cell: set position to (0,0,0).";
cluster.setPosition(math::XYZPoint(0,0,0));
cluster.calculatePositionREP();
} else {
const double norm_inverse = 1.0/position_norm;
x *= norm_inverse;
y *= norm_inverse;
z *= norm_inverse;
depth *= norm_inverse;
cluster.setPosition(math::XYZPoint(x,y,z));
cluster.setDepth(depth);
cluster.calculatePositionREP();
}
}
| 6,827 | 2,544 |
/* ****************************************************************** **
** OpenSees - Open System for Earthquake Engineering Simulation **
** Pacific Earthquake Engineering Research Center **
** **
** **
** (C) Copyright 1999, The Regents of the University of California **
** All Rights Reserved. **
** **
** Commercial use of this program without express permission of the **
** University of California, Berkeley, is strictly prohibited. See **
** file 'COPYRIGHT' in main directory for information on usage and **
** redistribution, and for a DISCLAIMER OF ALL WARRANTIES. **
** **
** ****************************************************************** */
// $Revision: 1.7 $
// $Date: 2008-10-20 22:23:03 $
// $Source: /usr/local/cvs/OpenSees/SRC/material/nD/J2PlaneStrain.cpp,v $
// Written: Ed "C++" Love
//
// J2PlaneStrain isotropic hardening material class
//
// Elastic Model
// sigma = K*trace(epsilion_elastic) + (2*G)*dev(epsilon_elastic)
//
// Yield Function
// phi(sigma,q) = || dev(sigma) || - sqrt(2/3)*q(xi)
//
// Saturation Isotropic Hardening with linear term
// q(xi) = simga_infty + (sigma_0 - sigma_infty)*exp(-delta*xi) + H*xi
//
// Flow Rules
// \dot{epsilon_p} = gamma * d_phi/d_sigma
// \dot{xi} = -gamma * d_phi/d_q
//
// Linear Viscosity
// gamma = phi / eta ( if phi > 0 )
//
// Backward Euler Integration Routine
// Yield condition enforced at time n+1
//
// Send strains in following format :
//
// strain_vec = { eps_00
// eps_11
// 2 eps_01 } <--- note the 2
//
// set eta := 0 for rate independent case
//
#include <J2PlaneStrain.h>
#include <Channel.h>
#include <FEM_ObjectBroker.h>
//static vectors and matrices
Vector J2PlaneStrain :: strain_vec(3) ;
Vector J2PlaneStrain :: stress_vec(3) ;
Matrix J2PlaneStrain :: tangent_matrix(3,3) ;
//null constructor
J2PlaneStrain :: J2PlaneStrain( ) :
J2Plasticity( )
{ }
//full constructor
J2PlaneStrain ::
J2PlaneStrain( int tag,
double K,
double G,
double yield0,
double yield_infty,
double d,
double H,
double viscosity,
double rho) :
J2Plasticity( tag, ND_TAG_J2PlaneStrain,
K, G, yield0, yield_infty, d, H, viscosity, rho )
{
}
//elastic constructor
J2PlaneStrain ::
J2PlaneStrain( int tag,
double K,
double G ) :
J2Plasticity( tag, ND_TAG_J2PlaneStrain, K, G )
{
}
//destructor
J2PlaneStrain :: ~J2PlaneStrain( )
{
}
//make a clone of this material
NDMaterial* J2PlaneStrain :: getCopy( )
{
J2PlaneStrain *clone;
clone = new J2PlaneStrain() ; //new instance of this class
*clone = *this ; //asignment to make copy
return clone ;
}
//send back type of material
const char* J2PlaneStrain :: getType( ) const
{
return "PlaneStrain" ;
}
//send back order of strain in vector form
int J2PlaneStrain :: getOrder( ) const
{
return 3 ;
}
//get the strain and integrate plasticity equations
int J2PlaneStrain :: setTrialStrain( const Vector &strain_from_element)
{
strain.Zero( ) ;
strain(0,0) = strain_from_element(0) ;
strain(1,1) = strain_from_element(1) ;
strain(0,1) = 0.50 * strain_from_element(2) ;
strain(1,0) = strain(0,1) ;
this->plastic_integrator( ) ;
return 0 ;
}
//unused trial strain functions
int J2PlaneStrain :: setTrialStrain( const Vector &v, const Vector &r )
{
return this->setTrialStrain( v ) ;
}
int J2PlaneStrain :: setTrialStrainIncr( const Vector &v )
{
static Vector newStrain(3);
newStrain(0) = strain(0,0) + v(0);
newStrain(1) = strain(1,1) + v(1);
newStrain(2) = 2.0 * strain(0,1) + v(2);
return this->setTrialStrain(newStrain);
}
int J2PlaneStrain :: setTrialStrainIncr( const Vector &v, const Vector &r )
{
return this->setTrialStrainIncr(v);
}
//send back the strain
const Vector& J2PlaneStrain :: getStrain( )
{
strain_vec(0) = strain(0,0) ;
strain_vec(1) = strain(1,1) ;
strain_vec(2) = 2.0 * strain(0,1) ;
return strain_vec ;
}
//send back the stress
const Vector& J2PlaneStrain :: getStress( )
{
stress_vec(0) = stress(0,0) ;
stress_vec(1) = stress(1,1) ;
stress_vec(2) = stress(0,1) ;
return stress_vec ;
}
//send back the tangent
const Matrix& J2PlaneStrain :: getTangent( )
{
// matrix to tensor mapping
// Matrix Tensor
// ------- -------
// 0 0 0
// 1 1 1
// 2 0 1 ( or 1 0 )
//
tangent_matrix(0,0) = tangent [0][0] [0][0] ;
tangent_matrix(1,1) = tangent [1][1] [1][1] ;
tangent_matrix(2,2) = tangent [0][1] [0][1] ;
tangent_matrix(0,1) = tangent [0][0] [1][1] ;
tangent_matrix(1,0) = tangent [1][1] [0][0] ;
tangent_matrix(0,2) = tangent [0][0] [0][1] ;
tangent_matrix(2,0) = tangent [0][1] [0][0] ;
tangent_matrix(1,2) = tangent [1][1] [0][1] ;
tangent_matrix(2,1) = tangent [0][1] [1][1] ;
return tangent_matrix ;
}
//send back the tangent
const Matrix& J2PlaneStrain :: getInitialTangent( )
{
// matrix to tensor mapping
// Matrix Tensor
// ------- -------
// 0 0 0
// 1 1 1
// 2 0 1 ( or 1 0 )
//
this->doInitialTangent();
tangent_matrix(0,0) = initialTangent [0][0] [0][0] ;
tangent_matrix(1,1) = initialTangent [1][1] [1][1] ;
tangent_matrix(2,2) = initialTangent [0][1] [0][1] ;
tangent_matrix(0,1) = initialTangent [0][0] [1][1] ;
tangent_matrix(1,0) = initialTangent [1][1] [0][0] ;
tangent_matrix(0,2) = initialTangent [0][0] [0][1] ;
tangent_matrix(2,0) = initialTangent [0][1] [0][0] ;
tangent_matrix(1,2) = initialTangent [1][1] [0][1] ;
tangent_matrix(2,1) = initialTangent [0][1] [1][1] ;
return tangent_matrix ;
}
int
J2PlaneStrain::commitState( )
{
epsilon_p_n = epsilon_p_nplus1;
xi_n = xi_nplus1;
return 0;
}
int
J2PlaneStrain::revertToLastCommit( ) {
return 0;
}
int
J2PlaneStrain::revertToStart( )
{
this->zero( ) ;
return 0;
}
int
J2PlaneStrain::sendSelf (int commitTag, Channel &theChannel)
{
// we place all the data needed to define material and it's state
// int a vector object
static Vector data(19);
int cnt = 0;
data(cnt++) = this->getTag();
data(cnt++) = bulk;
data(cnt++) = shear;
data(cnt++) = sigma_0;
data(cnt++) = sigma_infty;
data(cnt++) = delta;
data(cnt++) = Hard;
data(cnt++) = eta;
data(cnt++) = rho;
data(cnt++) = xi_n;
// data(cnt++) = commitEps22;
for (int i=0; i<3; i++)
for (int j=0; j<3; j++)
data(cnt++) = epsilon_p_n(i,j);
// send the vector object to the channel
if (theChannel.sendVector(this->getDbTag(), commitTag, data) < 0) {
opserr << "J2PlaneStrain::sendSelf - failed to send vector to channel\n";
return -1;
}
return 0;
}
int
J2PlaneStrain::recvSelf (int commitTag, Channel &theChannel,
FEM_ObjectBroker &theBroker)
{
// recv the vector object from the channel which defines material param and state
static Vector data(19);
if (theChannel.recvVector(this->getDbTag(), commitTag, data) < 0) {
opserr << "J2PlaneStrain::recvSelf - failed to sned vectorto channel\n";
return -1;
}
// set the material parameters and state variables
int cnt = 0;
this->setTag(data(cnt++));
bulk = data(cnt++);
shear = data(cnt++);
sigma_0 = data(cnt++);
sigma_infty = data(cnt++);
delta = data(cnt++);
Hard = data(cnt++);
eta = data(cnt++);
rho = data(cnt++);
xi_n = data(cnt++);
for (int i=0; i<3; i++)
for (int j=0; j<3; j++)
epsilon_p_n(i,j) = data(cnt++);
epsilon_p_nplus1 = epsilon_p_n;
xi_nplus1 = xi_n;
return 0;
}
| 8,223 | 3,231 |
//
// Location.cpp
// PinballWarping
//
// Created by Eric on 6/10/15.
//
//
#include "Location.h"
| 103 | 49 |
/*
Bad Question Description:
https://leetcode.com/problems/bag-of-tokens/discuss/197856/Bad-descriptions!
Description Rewrite:
You have a bag of tokens, from which you can take whichever token you want, and after you take one,
you can't put it back to the bag, meaning you can use every token at most once.
You start the game with P power and 0 point.
For every tokens[i], you can use it in either way:
- plus tokens[i] powers, and minus 1 point;
- or, minus tokens[i] powers, and plus 1 point.
(meaning you exchange your powers to get 1 point, or exchange your point to get more powers)
But you have to make sure that during the process, both your powers>=0 and points>=0, otherwise you would have to stop playing the game.
And you can use just some of the tokens (don't have to use all of them).
Your target is to get the maximum points possible.
*/
//2020
class Solution {
public:
int bagOfTokensScore(vector<int>& tokens, int P) {
sort(tokens.begin(), tokens.end());
int point = 0;
for(int i = 0, j = tokens.size()-1; i<=j;){
if(tokens[i] <= P){
point++;
P -= tokens[i++];
}
else if(i!=j && point > 0){ //i != j, 若只剩下一个点,不用了
point--;
P+= tokens[j--];
}
else{
break;
}
}
return point;
}
};
class Solution {
public:
int bagOfTokensScore(vector<int>& tokens, int P) {
sort(tokens.begin(), tokens.end());
int res = 0, points = 0, i = 0, j = tokens.size() - 1;
while (i <= j) {
if (P >= tokens[i]) {
P -= tokens[i++];
res = max(res, ++points);
} else if (points > 0) {
points--;
P += tokens[j--];
} else {
break;
}
}
return res;
}
};
class Solution {
public:
int bagOfTokensScore(vector<int>& tokens, int P) {
sort(tokens.begin(), tokens.end());
return helper(tokens, 0, tokens.size()-1, P, 0);
}
int helper(vector<int>& tokens, int i, int j, int p, int points){
if(i > j) return points;
int res = points;
if(tokens[i] <= p)
res = max(res, helper(tokens, i+1, j, p-tokens[i], points+1));
else if(points >= 1)
res = max(res, helper(tokens, i, j-1, p+tokens[j], points-1));
return res;
}
};
class Solution {
public:
int bagOfTokensScore(vector<int>& tokens, int P) {
int N = tokens.size();
if (!N) return 0;
sort(tokens.begin(), tokens.end());
if (P < tokens[0]) return 0;
int l = 0, h = N-1;
int points = 0;
while (l <= h) {
if (P < tokens[l] && points) {
P += tokens[h--]; points--;
}
if (P < tokens[l])
return points;
P -= tokens[l++];
points++;
}
return points;
}
}; | 3,102 | 1,000 |
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2014-2021, Lawrence Livermore National Security, LLC.
// Produced at the Lawrence Livermore National Laboratory.
// Written by the LBANN Research Team (B. Van Essen, et al.) listed in
// the CONTRIBUTORS file. <lbann-dev@llnl.gov>
//
// LLNL-CODE-697807.
// All rights reserved.
//
// This file is part of LBANN: Livermore Big Artificial Neural Network
// Toolkit. For details, see http://software.llnl.gov/LBANN or
// https://github.com/LLNL/LBANN.
//
// Licensed under the Apache License, Version 2.0 (the "Licensee"); 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.
//
// lbann_proto.cpp - prototext application
////////////////////////////////////////////////////////////////////////////////
#include "lbann/lbann.hpp"
#include "lbann/proto/proto_common.hpp"
#include <lbann.pb.h>
#include <reader.pb.h>
#include <string>
using namespace lbann;
int mini_batch_size = 128;
void test_is_shuffled(const generic_data_reader &reader, bool is_shuffled, const char *msg = nullptr);
int main(int argc, char *argv[]) {
world_comm_ptr comm = initialize(argc, argv);
// Initialize the general RNGs and the data sequence RNGs
int random_seed = lbann_default_random_seed;
init_random(random_seed);
init_data_seq_random(random_seed);
const bool master = comm->am_world_master();
try {
// Initialize options db (this parses the command line)
auto& arg_parser = global_argument_parser();
construct_all_options();
arg_parser.add_flag("fn", {"--fn"}, "TODO");
arg_parser.parse(argc, argv);
if (arg_parser.help_requested() or argc == 1) {
if (master)
std::cout << arg_parser << std::endl;
return EXIT_SUCCESS;
}
//read data_reader prototext file
if (arg_parser.get<std::string>("fn") == "") {
std::cerr << __FILE__ << " " << __LINE__ << " :: "
<< "you must run with: --fn=<string> where <string> is\n"
<< "a data_reader prototext filePathName\n";
return EXIT_FAILURE;
}
lbann_data::LbannPB pb;
std::string reader_fn = arg_parser.get<std::string>("fn");
read_prototext_file(reader_fn.c_str(), pb, master);
const lbann_data::DataReader & d_reader = pb.data_reader();
int size = d_reader.reader_size();
for (int j=0; j<size; j++) {
const lbann_data::Reader& readme = d_reader.reader(j);
if (readme.role() == "train") {
bool shuffle = true;
auto reader = std::make_unique<mnist_reader>(shuffle);
if (readme.data_filename() != "") { reader->set_data_filename( readme.data_filename() ); }
if (readme.label_filename() != "") { reader->set_label_filename( readme.label_filename() ); }
if (readme.data_filedir() != "") { reader->set_file_dir( readme.data_filedir() ); }
reader->load();
test_is_shuffled(*reader, true, "TEST #1");
//test: indices should not be shuffled; same as previous, except we call
// shuffle(true);
shuffle = false;
reader = std::make_unique<mnist_reader>(shuffle);
if (readme.data_filename() != "") { reader->set_data_filename( readme.data_filename() ); }
if (readme.label_filename() != "") { reader->set_label_filename( readme.label_filename() ); }
if (readme.data_filedir() != "") { reader->set_file_dir( readme.data_filedir() ); }
reader->set_shuffle(shuffle);
reader->load();
test_is_shuffled(*reader, false, "TEST #2");
//test: indices should not be shuffled, due to ctor argument
shuffle = false;
reader = std::make_unique<mnist_reader>(shuffle);
if (readme.data_filename() != "") { reader->set_data_filename( readme.data_filename() ); }
if (readme.label_filename() != "") { reader->set_label_filename( readme.label_filename() ); }
if (readme.data_filedir() != "") { reader->set_file_dir( readme.data_filedir() ); }
reader->load();
test_is_shuffled(*reader, false, "TEST #3");
//test: set_shuffled_indices; indices should not be shuffled
shuffle = true;
reader = std::make_unique<mnist_reader>(shuffle);
if (readme.data_filename() != "") { reader->set_data_filename( readme.data_filename() ); }
if (readme.label_filename() != "") { reader->set_label_filename( readme.label_filename() ); }
if (readme.data_filedir() != "") { reader->set_file_dir( readme.data_filedir() ); }
reader->load();
//at this point the indices should be shuffled (same as first test)
test_is_shuffled(*reader, true, "TEST #4");
std::vector<int> indices(mini_batch_size);
std::iota(indices.begin(), indices.end(), 0);
reader->set_shuffled_indices(indices);
test_is_shuffled(*reader, false, "TEST #5");
break;
}
}
} catch (lbann_exception& e) {
e.print_report();
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
void test_is_shuffled(const generic_data_reader &reader, bool is_shuffled, const char *msg) {
const std::vector<int> &indices = reader.get_shuffled_indices();
std::cerr << "\nstarting test_is_suffled; mini_batch_size: " << mini_batch_size
<< " indices.size(): " << indices.size();
if (msg) {
std::cout << " :: " << msg;
}
std::cout << std::endl;
bool yes = false; //if true true: indices are actaully shuffled
for (int h=0; h<mini_batch_size; h++) {
if (indices[h] != h) {
yes = true;
}
}
std::cout << "testing for is_shuffled = " << is_shuffled << " test shows the shuffled is actually "
<< yes << " :: ";
if (yes == is_shuffled) {
std::cout << "PASSED!\n";
} else {
std::cout << "FAILED!\n";
}
}
| 6,210 | 2,066 |
#include "Ext.h"
#include "preprocessor/llvm_includes_start.h"
#include <llvm/IR/IntrinsicInst.h>
#include "preprocessor/llvm_includes_end.h"
#include "RuntimeManager.h"
#include "Memory.h"
#include "Type.h"
#include "Endianness.h"
namespace dev
{
namespace vap
{
namespace jit
{
Ext::Ext(RuntimeManager& _runtimeManager, Memory& _memoryMan):
RuntimeHelper(_runtimeManager),
m_memoryMan(_memoryMan)
{
m_funcs = decltype(m_funcs)();
m_argAllocas = decltype(m_argAllocas)();
m_size = m_builder.CreateAlloca(Type::Size, nullptr, "env.size");
}
using FuncDesc = std::tuple<char const*, llvm::FunctionType*>;
llvm::FunctionType* getFunctionType(llvm::Type* _returnType, std::initializer_list<llvm::Type*> const& _argsTypes)
{
return llvm::FunctionType::get(_returnType, llvm::ArrayRef<llvm::Type*>{_argsTypes.begin(), _argsTypes.size()}, false);
}
std::array<FuncDesc, sizeOf<EnvFunc>::value> const& getEnvFuncDescs()
{
static std::array<FuncDesc, sizeOf<EnvFunc>::value> descs{{
FuncDesc{"env_sload", getFunctionType(Type::Void, {Type::EnvPtr, Type::WordPtr, Type::WordPtr})},
FuncDesc{"env_sstore", getFunctionType(Type::Void, {Type::EnvPtr, Type::WordPtr, Type::WordPtr})},
FuncDesc{"env_sha3", getFunctionType(Type::Void, {Type::BytePtr, Type::Size, Type::WordPtr})},
FuncDesc{"env_balance", getFunctionType(Type::Void, {Type::EnvPtr, Type::WordPtr, Type::WordPtr})},
FuncDesc{"env_create", getFunctionType(Type::Void, {Type::EnvPtr, Type::GasPtr, Type::WordPtr, Type::BytePtr, Type::Size, Type::WordPtr})},
FuncDesc{"env_call", getFunctionType(Type::Bool, {Type::EnvPtr, Type::GasPtr, Type::Gas, Type::WordPtr, Type::WordPtr, Type::WordPtr, Type::WordPtr, Type::WordPtr, Type::BytePtr, Type::Size, Type::BytePtr, Type::Size})},
FuncDesc{"env_log", getFunctionType(Type::Void, {Type::EnvPtr, Type::BytePtr, Type::Size, Type::WordPtr, Type::WordPtr, Type::WordPtr, Type::WordPtr})},
FuncDesc{"env_blockhash", getFunctionType(Type::Void, {Type::EnvPtr, Type::WordPtr, Type::WordPtr})},
FuncDesc{"env_extcode", getFunctionType(Type::BytePtr, {Type::EnvPtr, Type::WordPtr, Type::Size->getPointerTo()})},
}};
return descs;
}
llvm::Function* createFunc(EnvFunc _id, llvm::Module* _module)
{
auto&& desc = getEnvFuncDescs()[static_cast<size_t>(_id)];
return llvm::Function::Create(std::get<1>(desc), llvm::Function::ExternalLinkage, std::get<0>(desc), _module);
}
llvm::Value* Ext::getArgAlloca()
{
auto& a = m_argAllocas[m_argCounter];
if (!a)
{
InsertPointGuard g{m_builder};
auto allocaIt = getMainFunction()->front().begin();
auto allocaPtr = &(*allocaIt);
std::advance(allocaIt, m_argCounter); // Skip already created allocas
m_builder.SetInsertPoint(allocaPtr);
a = m_builder.CreateAlloca(Type::Word, nullptr, {"a.", std::to_string(m_argCounter)});
}
++m_argCounter;
return a;
}
llvm::Value* Ext::byPtr(llvm::Value* _value)
{
auto a = getArgAlloca();
m_builder.CreateStore(_value, a);
return a;
}
llvm::CallInst* Ext::createCall(EnvFunc _funcId, std::initializer_list<llvm::Value*> const& _args)
{
auto& func = m_funcs[static_cast<size_t>(_funcId)];
if (!func)
func = createFunc(_funcId, getModule());
m_argCounter = 0;
return m_builder.CreateCall(func, {_args.begin(), _args.size()});
}
llvm::Value* Ext::sload(llvm::Value* _index)
{
auto ret = getArgAlloca();
createCall(EnvFunc::sload, {getRuntimeManager().getEnvPtr(), byPtr(_index), ret}); // Uses native endianness
return m_builder.CreateLoad(ret);
}
void Ext::sstore(llvm::Value* _index, llvm::Value* _value)
{
createCall(EnvFunc::sstore, {getRuntimeManager().getEnvPtr(), byPtr(_index), byPtr(_value)}); // Uses native endianness
}
llvm::Value* Ext::calldataload(llvm::Value* _idx)
{
auto ret = getArgAlloca();
auto result = m_builder.CreateBitCast(ret, Type::BytePtr);
auto callDataSize = getRuntimeManager().getCallDataSize();
auto callDataSize64 = m_builder.CreateTrunc(callDataSize, Type::Size);
auto idxValid = m_builder.CreateICmpULT(_idx, callDataSize);
auto idx = m_builder.CreateTrunc(m_builder.CreateSelect(idxValid, _idx, callDataSize), Type::Size, "idx");
auto end = m_builder.CreateNUWAdd(idx, m_builder.getInt64(32));
end = m_builder.CreateSelect(m_builder.CreateICmpULE(end, callDataSize64), end, callDataSize64);
auto copySize = m_builder.CreateNUWSub(end, idx);
auto padSize = m_builder.CreateNUWSub(m_builder.getInt64(32), copySize);
auto dataBegin = m_builder.CreateGEP(Type::Byte, getRuntimeManager().getCallData(), idx);
m_builder.CreateMemCpy(result, dataBegin, copySize, 1);
auto pad = m_builder.CreateGEP(Type::Byte, result, copySize);
m_builder.CreateMemSet(pad, m_builder.getInt8(0), padSize, 1);
m_argCounter = 0; // Release args allocas. TODO: This is a bad design
return Endianness::toNative(m_builder, m_builder.CreateLoad(ret));
}
llvm::Value* Ext::balance(llvm::Value* _address)
{
auto address = Endianness::toBE(m_builder, _address);
auto ret = getArgAlloca();
createCall(EnvFunc::balance, {getRuntimeManager().getEnvPtr(), byPtr(address), ret});
return m_builder.CreateLoad(ret);
}
llvm::Value* Ext::blockHash(llvm::Value* _number)
{
auto hash = getArgAlloca();
createCall(EnvFunc::blockhash, {getRuntimeManager().getEnvPtr(), byPtr(_number), hash});
hash = m_builder.CreateLoad(hash);
return Endianness::toNative(m_builder, hash);
}
llvm::Value* Ext::create(llvm::Value* _endowment, llvm::Value* _initOff, llvm::Value* _initSize)
{
auto ret = getArgAlloca();
auto begin = m_memoryMan.getBytePtr(_initOff);
auto size = m_builder.CreateTrunc(_initSize, Type::Size, "size");
createCall(EnvFunc::create, {getRuntimeManager().getEnvPtr(), getRuntimeManager().getGasPtr(), byPtr(_endowment), begin, size, ret});
llvm::Value* address = m_builder.CreateLoad(ret);
address = Endianness::toNative(m_builder, address);
return address;
}
llvm::Value* Ext::call(llvm::Value* _callGas, llvm::Value* _senderAddress, llvm::Value* _receiveAddress, llvm::Value* _codeAddress, llvm::Value* _valueTransfer, llvm::Value* _apparentValue, llvm::Value* _inOff, llvm::Value* _inSize, llvm::Value* _outOff, llvm::Value* _outSize)
{
auto senderAddress = Endianness::toBE(m_builder, _senderAddress);
auto receiveAddress = Endianness::toBE(m_builder, _receiveAddress);
auto inBeg = m_memoryMan.getBytePtr(_inOff);
auto inSize = m_builder.CreateTrunc(_inSize, Type::Size, "in.size");
auto outBeg = m_memoryMan.getBytePtr(_outOff);
auto outSize = m_builder.CreateTrunc(_outSize, Type::Size, "out.size");
auto codeAddress = Endianness::toBE(m_builder, _codeAddress);
auto callGas = m_builder.CreateSelect(
m_builder.CreateICmpULE(_callGas, m_builder.CreateZExt(Constant::gasMax, Type::Word)),
m_builder.CreateTrunc(_callGas, Type::Gas),
Constant::gasMax);
auto ret = createCall(EnvFunc::call, {getRuntimeManager().getEnvPtr(), getRuntimeManager().getGasPtr(), callGas, byPtr(senderAddress), byPtr(receiveAddress), byPtr(codeAddress), byPtr(_valueTransfer), byPtr(_apparentValue), inBeg, inSize, outBeg, outSize});
return m_builder.CreateZExt(ret, Type::Word, "ret");
}
llvm::Value* Ext::sha3(llvm::Value* _inOff, llvm::Value* _inSize)
{
auto begin = m_memoryMan.getBytePtr(_inOff);
auto size = m_builder.CreateTrunc(_inSize, Type::Size, "size");
auto ret = getArgAlloca();
createCall(EnvFunc::sha3, {begin, size, ret});
llvm::Value* hash = m_builder.CreateLoad(ret);
hash = Endianness::toNative(m_builder, hash);
return hash;
}
MemoryRef Ext::extcode(llvm::Value* _addr)
{
auto addr = Endianness::toBE(m_builder, _addr);
auto code = createCall(EnvFunc::extcode, {getRuntimeManager().getEnvPtr(), byPtr(addr), m_size});
auto codeSize = m_builder.CreateLoad(m_size);
auto codeSize256 = m_builder.CreateZExt(codeSize, Type::Word);
return {code, codeSize256};
}
void Ext::log(llvm::Value* _memIdx, llvm::Value* _numBytes, std::array<llvm::Value*,4> const& _topics)
{
auto begin = m_memoryMan.getBytePtr(_memIdx);
auto size = m_builder.CreateTrunc(_numBytes, Type::Size, "size");
llvm::Value* args[] = {getRuntimeManager().getEnvPtr(), begin, size, getArgAlloca(), getArgAlloca(), getArgAlloca(), getArgAlloca()};
auto topicArgPtr = &args[3];
for (auto&& topic : _topics)
{
if (topic)
m_builder.CreateStore(Endianness::toBE(m_builder, topic), *topicArgPtr);
else
*topicArgPtr = llvm::ConstantPointerNull::get(Type::WordPtr);
++topicArgPtr;
}
createCall(EnvFunc::log, {args[0], args[1], args[2], args[3], args[4], args[5], args[6]}); // TODO: use std::initializer_list<>
}
}
}
}
| 8,509 | 3,179 |
// file : evolution/add-index/driver.cxx
// copyright : Copyright (c) 2009-2015 Code Synthesis Tools CC
// license : GNU GPL v2; see accompanying LICENSE file
// Test adding a new index.
//
#include <memory> // std::auto_ptr
#include <cassert>
#include <iostream>
#include <odb/database.hxx>
#include <odb/transaction.hxx>
#include <odb/schema-catalog.hxx>
#include <common/common.hxx>
#include "test2.hxx"
#include "test3.hxx"
#include "test2-odb.hxx"
#include "test3-odb.hxx"
using namespace std;
using namespace odb::core;
int
main (int argc, char* argv[])
{
try
{
auto_ptr<database> db (create_database (argc, argv, false));
bool embedded (schema_catalog::exists (*db));
// 1 - base version
// 2 - migration
// 3 - current version
//
unsigned short pass (*argv[argc - 1] - '0');
switch (pass)
{
case 1:
{
using namespace v2;
if (embedded)
{
transaction t (db->begin ());
schema_catalog::drop_schema (*db);
schema_catalog::create_schema (*db, "", false);
schema_catalog::migrate_schema (*db, 2);
t.commit ();
}
object o0 (0);
o0.num = 123;
object o1 (1);
o1.num = 234;
object o2 (2);
o2.num = 234;
// Duplicates are ok.
//
{
transaction t (db->begin ());
db->persist (o0);
db->persist (o1);
db->persist (o2);
t.commit ();
}
break;
}
case 2:
{
using namespace v3;
if (embedded)
{
transaction t (db->begin ());
schema_catalog::migrate_schema_pre (*db, 3);
t.commit ();
}
object o3 (3);
o3.num = 234;
// Duplicates are still ok but we need to remove them before the
// post migration step.
//
{
transaction t (db->begin ());
db->persist (o3);
t.commit ();
}
{
typedef odb::query<object> query;
typedef odb::result<object> result;
transaction t (db->begin ());
result r (db->query<object> (
"ORDER BY" + query::num + "," + query::id));
unsigned long prev (0);
for (result::iterator i (r.begin ()); i != r.end (); ++i)
{
if (i->num == prev)
db->erase (*i);
prev = i->num;
}
t.commit ();
}
if (embedded)
{
transaction t (db->begin ());
schema_catalog::migrate_schema_post (*db, 3);
t.commit ();
}
break;
}
case 3:
{
using namespace v3;
{
transaction t (db->begin ());
auto_ptr<object> p0 (db->load<object> (0));
auto_ptr<object> p1 (db->load<object> (1));
assert (p0->num == 123);
assert (p1->num == 234);
t.commit ();
}
try
{
object o2 (2);
o2.num = 234;
transaction t (db->begin ());
db->persist (o2);
assert (false);
}
catch (const odb::exception& ) {}
break;
}
default:
{
cerr << "unknown pass number '" << argv[argc - 1] << "'" << endl;
return 1;
}
}
}
catch (const odb::exception& e)
{
cerr << e.what () << endl;
return 1;
}
}
| 3,478 | 1,158 |
// Copyright 2011-2020 Wason Technology, LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifdef ROBOTRACONTEUR_CORE_USE_STDAFX
#include "stdafx.h"
#endif
#include "Discovery_private.h"
#include "Subscription_private.h"
#include <boost/foreach.hpp>
#include <boost/range/adaptors.hpp>
#include <boost/range/algorithm.hpp>
#include <boost/algorithm/string.hpp>
namespace RobotRaconteur
{
ServiceInfo2::ServiceInfo2()
{
}
ServiceInfo2::ServiceInfo2(const RobotRaconteurServiceIndex::ServiceInfo &info, const RobotRaconteurServiceIndex::NodeInfo &ninfo)
{
Name = info.Name;
RootObjectType = info.RootObjectType;
if (info.RootObjectImplements)
{
BOOST_FOREACH(RR_INTRUSIVE_PTR<RobotRaconteur::RRArray<char> >& e, *info.RootObjectImplements | boost::adaptors::map_values)
{
RootObjectImplements.push_back(RRArrayToString(e));
}
}
if (info.ConnectionURL)
{
BOOST_FOREACH(RR_INTRUSIVE_PTR<RobotRaconteur::RRArray<char> >& e, *info.ConnectionURL | boost::adaptors::map_values)
{
ConnectionURL.push_back(RRArrayToString(e));
}
}
Attributes = info.Attributes->GetStorageContainer();
NodeID = RobotRaconteur::NodeID(RRArrayToArray<uint8_t, 16>(ninfo.NodeID));
NodeName = ninfo.NodeName;
}
namespace detail
{
Discovery_updatediscoverednodes::Discovery_updatediscoverednodes(RR_SHARED_PTR<RobotRaconteurNode> node)
{
active_count = 0;
searching = true;
this->node = node;
}
void Discovery_updatediscoverednodes::timeout_timer_callback(const TimerEvent& e)
{
boost::mutex::scoped_lock lock(work_lock);
if (!e.stopped)
{
{
//boost::mutex::scoped_lock lock(searching_lock);
if (!searching) return;
searching = false;
}
{
boost::mutex::scoped_lock lock(timeout_timer_lock);
try
{
if (timeout_timer) timeout_timer->Stop();
}
catch (std::exception&) {}
timeout_timer.reset();
}
ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "UpdateDiscoveredNodes timed out, returning current results");
detail::InvokeHandler(node, handler);
}
}
void Discovery_updatediscoverednodes::getdetectednodes_callback(RR_SHARED_PTR<std::vector<NodeDiscoveryInfo> > ret, int32_t key)
{
boost::mutex::scoped_lock lock(work_lock);
bool c;
{
//boost::mutex::scoped_lock lock(searching_lock);
c = searching;
}
if (!c) return;
BOOST_FOREACH(NodeDiscoveryInfo& e, *ret)
{
node->NodeDetected(e);
}
bool done = false;
{
boost::mutex::scoped_lock lock(active_lock);
active.remove(key);
if (active.size() == 0) done = true;
}
if (done)
{
{
//boost::mutex::scoped_lock lock(searching_lock);
c = searching;
searching = false;
}
if (!c) return;
{
boost::mutex::scoped_lock lock(timeout_timer_lock);
try
{
if (timeout_timer) timeout_timer->Stop();
}
catch (std::exception&) {}
timeout_timer.reset();
}
ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "UpdateDiscoveredNodes completed successfully");
detail::InvokeHandler(node, handler);
}
}
void Discovery_updatediscoverednodes::UpdateDiscoveredNodes(const std::vector<std::string>& schemes, const std::vector<RR_SHARED_PTR<Transport> >& transports, RR_MOVE_ARG(boost::function<void()>) handler, int32_t timeout)
{
ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "Begin UpdateDiscoveredNodes");
boost::mutex::scoped_lock lock(work_lock);
this->handler = handler;
this->schemes = schemes;
searching = true;
if (timeout != RR_TIMEOUT_INFINITE)
{
timeout_timer = node->CreateTimer(boost::posix_time::milliseconds(timeout), boost::bind(&Discovery_updatediscoverednodes::timeout_timer_callback, shared_from_this(), RR_BOOST_PLACEHOLDERS(_1)), true);
timeout_timer->Start();
}
{
boost::mutex::scoped_lock lock(active_lock);
int32_t timeout1 = timeout;
if (timeout1 > 0)
{
timeout1 = (3 * timeout) / 4;
}
BOOST_FOREACH(const RR_SHARED_PTR<Transport>& e, transports)
{
int32_t key = active_count++;
try
{
ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "Begin GetDetectedNodes for transport " << e->GetUrlSchemeString());
boost::function<void(RR_SHARED_PTR<std::vector<NodeDiscoveryInfo> >)> h = boost::bind(&Discovery_updatediscoverednodes::getdetectednodes_callback, shared_from_this(), RR_BOOST_PLACEHOLDERS(_1), key);
e->AsyncGetDetectedNodes(schemes, h, timeout1);
}
catch (std::exception& exp)
{
ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "Begin GetDetectedNodes failed for transport " << e->GetUrlSchemeString() << ": " << exp.what());
}
active.push_back(key);
}
}
bool done = false;
{
boost::mutex::scoped_lock lock(active_lock);
if (active.size() == 0) done = true;
}
if (done)
{
ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "No transports available for node discovery");
detail::InvokeHandler(node, handler);
}
}
Discovery_findservicebytype::Discovery_findservicebytype(RR_SHARED_PTR<RobotRaconteurNode> node)
{
active_count = 0;
searching = true;
ret = RR_MAKE_SHARED<std::vector<ServiceInfo2> >();
this->node = node;
}
void Discovery_findservicebytype::handle_error(const int32_t& key, RR_SHARED_PTR<RobotRaconteurException> err)
{
boost::recursive_mutex::scoped_lock lock2(work_lock);
{
//boost::mutex::scoped_lock lock(searching_lock);
if (!searching) return;
}
ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "FindServiceByType candidate failed: " << err->what());
{
boost::mutex::scoped_lock lock(active_lock);
active.remove(key);
errors.push_back(err);
if (active.size() != 0) return;
}
//All activities have completed, assume failure
{
//boost::mutex::scoped_lock lock(searching_lock);
searching = false;
}
{
boost::mutex::scoped_lock lock(timeout_timer_lock);
try
{
if (timeout_timer) timeout_timer->Stop();
}
catch (std::exception&) {}
timeout_timer.reset();
}
boost::mutex::scoped_lock lock(ret_lock);
ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "FindServiceByType last candidate failed, returning " << ret->size() << " discovered services");
detail::InvokeHandler(node, handler, ret);
}
void Discovery_findservicebytype::timeout_timer_callback(const TimerEvent& e)
{
boost::recursive_mutex::scoped_lock lock2(work_lock);
if (!e.stopped)
{
{
//boost::mutex::scoped_lock lock(searching_lock);
if (!searching) return;
searching = false;
}
{
boost::mutex::scoped_lock lock(timeout_timer_lock);
try
{
if (timeout_timer) timeout_timer->Stop();
}
catch (std::exception&) {}
timeout_timer.reset();
}
boost::mutex::scoped_lock lock(ret_lock);
ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "FindServiceByType timed out, returning " << ret->size() << " discovered services");
detail::InvokeHandler(node, handler, ret);
}
}
void Discovery_findservicebytype::rr_empty_handler()
{
}
void Discovery_findservicebytype::serviceinfo_callback(RR_INTRUSIVE_PTR<MessageEntry> ret1, RR_SHARED_PTR<RobotRaconteurException> err, RR_SHARED_PTR<ServiceStub> client, std::string url, uint32_t key)
{
boost::recursive_mutex::scoped_lock lock2(work_lock);
if (err)
{
ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "FindServiceByType getting ServiceInfo2 from " << url << " failed: " << err->what());
try
{
node->AsyncDisconnectService(client, &Discovery_findservicebytype::rr_empty_handler);
}
catch (std::exception&)
{
}
handle_error(key, err);
return;
}
bool c;
{
//boost::mutex::scoped_lock lock(searching_lock);
c = searching;
}
if (!c)
{
try
{
node->AsyncDisconnectService(client, &Discovery_findservicebytype::rr_empty_handler);
}
catch (std::exception&)
{
}
}
else
{
try
{
RR_SHARED_PTR<RobotRaconteurServiceIndex::NodeInfo> n = RR_MAKE_SHARED<RobotRaconteurServiceIndex::NodeInfo>();
n->NodeID = ArrayToRRArray<uint8_t>(rr_cast<ServiceStub>(client)->GetContext()->GetRemoteNodeID().ToByteArray());
n->NodeName = rr_cast<ServiceStub>(client)->GetContext()->GetRemoteNodeName();
try
{
node->AsyncDisconnectService(client, &Discovery_findservicebytype::rr_empty_handler);
}
catch (std::exception&)
{
}
boost::smatch url_result;
boost::regex reg("^([^:]+)://(.*)$");
boost::regex_search(url, url_result, reg);
if (url_result.size() < 3) throw InvalidArgumentException("Malformed URL");
std::string scheme = url_result[1];
if (ret1->Error == RobotRaconteur::MessageErrorType_None)
{
RR_INTRUSIVE_PTR<RobotRaconteur::MessageElement> me = ret1->FindElement("return");
RR_INTRUSIVE_PTR<RobotRaconteur::RRMap<int32_t, RobotRaconteurServiceIndex::ServiceInfo> > ret = RobotRaconteur::rr_cast<RobotRaconteur::RRMap<int32_t, RobotRaconteurServiceIndex::ServiceInfo > >((node->UnpackMapType<int32_t, RobotRaconteurServiceIndex::ServiceInfo >(me->CastData<RobotRaconteur::MessageElementNestedElementList >())));
if (ret)
{
BOOST_FOREACH(RR_INTRUSIVE_PTR<RobotRaconteurServiceIndex::ServiceInfo>& ii, *ret | boost::adaptors::map_values)
{
if (!ii) continue;
if (ii->RootObjectType == servicetype)
{
boost::mutex::scoped_lock lock(ret_lock);
ServiceInfo2 si(*ii, *n);
//TODO: what is this?
BOOST_FOREACH(std::string& iii, si.ConnectionURL)
{
/*if (!boost::starts_with(*iii, scheme + "://"))
{
boost::smatch url_result2;
boost::regex_search(*iii, url_result2, reg);
if (url_result2.size() < 3) continue;
*iii = scheme + "://" + url_result2[2];
}*/
}
this->ret->push_back(si);
}
else
{
BOOST_FOREACH(RR_INTRUSIVE_PTR<RRArray<char> >& impl, *ii->RootObjectImplements | boost::adaptors::map_values)
{
if (RRArrayToString(impl) == servicetype)
{
boost::mutex::scoped_lock lock(ret_lock);
ServiceInfo2 si(*ii, *n);
//TODO: What is this?
BOOST_FOREACH(std::string &iii, si.ConnectionURL)
{
/*if (!boost::starts_with(*iii, scheme + "://"))
{
boost::smatch url_result2;
boost::regex_search(*iii, url_result2, reg);
if (url_result2.size() < 3) continue;
*iii = scheme + "://" + url_result2[2];
}*/
}
this->ret->push_back(si);
break;
}
}
}
}
}
ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "FindServiceByType getting ServiceInfo2 from " << url << " completed successfully");
}
else
{
ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "FindServiceByType getting ServiceInfo2 from " << url << " failed: " << ret1->Error);
}
bool done = false;
{
boost::mutex::scoped_lock lock(active_lock);
active.remove(key);
done = active.empty();
}
if (done)
{
bool c2;
{
//boost::mutex::scoped_lock lock(searching_lock);
c2 = searching;
searching = false;
}
if (c2)
{
{
boost::mutex::scoped_lock lock(timeout_timer_lock);
try
{
if (timeout_timer) timeout_timer->Stop();
}
catch (std::exception&) {}
timeout_timer.reset();
}
boost::mutex::scoped_lock lock(ret_lock);
ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "FindServiceByType completed successfully with " << this->ret->size() << " discovered services");
detail::InvokeHandler(node, handler, this->ret);
}
}
}
catch (std::exception& err2)
{
ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "FindServiceByType getting ServiceInfo2 from " << url << " failed: " << err2.what());
handle_error(key, RobotRaconteurExceptionUtil::ExceptionToSharedPtr(err2, MessageErrorType_ConnectionError));
}
}
}
void Discovery_findservicebytype::connect_callback(RR_SHARED_PTR<RRObject> client, RR_SHARED_PTR<RobotRaconteurException> err, std::string url, uint32_t key)
{
boost::recursive_mutex::scoped_lock lock2(work_lock);
if (err)
{
ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "FindServiceByType connecting to " << url << " failed: " << err->what());
handle_error(key, err);
return;
}
bool c;
{
//boost::mutex::scoped_lock lock(searching_lock);
c = searching;
}
if (!c)
{
try
{
node->AsyncDisconnectService(client, &Discovery_findservicebytype::rr_empty_handler);
}
catch (std::exception&)
{
}
}
else
{
try
{
ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "FindServiceByType connectted to " << url << ", begin getting ServiceInfo2");
int32_t key2;
{
boost::mutex::scoped_lock lock(active_lock);
active_count++;
key2 = active_count;
RR_SHARED_PTR<ServiceStub> client3 = rr_cast<ServiceStub>(client);
RR_INTRUSIVE_PTR<RobotRaconteur::MessageEntry> rr_req = RobotRaconteur::CreateMessageEntry(RobotRaconteur::MessageEntryType_FunctionCallReq, "GetLocalNodeServices");
client3->AsyncProcessRequest(rr_req, boost::bind(&Discovery_findservicebytype::serviceinfo_callback, shared_from_this(), RR_BOOST_PLACEHOLDERS(_1), RR_BOOST_PLACEHOLDERS(_2), client3, url, key2), 5000);
active.push_back(key2);
active.remove(key);
}
}
catch (std::exception& err2)
{
ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "FindServiceByType begin getting ServiceInfo2 from url " << url << " failed: " << err2.what());
try
{
node->AsyncDisconnectService(client, &Discovery_findservicebytype::rr_empty_handler);
}
catch (std::exception&)
{
}
handle_error(key, RobotRaconteurExceptionUtil::ExceptionToSharedPtr(err2, MessageErrorType_ConnectionError));
}
}
}
void Discovery_findservicebytype::find2()
{
boost::recursive_mutex::scoped_lock lock2(work_lock);
std::list<std::vector<std::string> > urls;
std::vector<NodeDiscoveryInfo> n1 = node->GetDetectedNodes();
BOOST_FOREACH(NodeDiscoveryInfo& ee, n1)
{
try
{
std::vector<std::string> urls1 = std::vector<std::string>();
BOOST_FOREACH(NodeDiscoveryInfoURL& url, ee.URLs)
{
BOOST_FOREACH(const std::string& e, schemes)
{
std::string t2 = (e + "://");
if (boost::starts_with(url.URL, t2))
{
urls1.push_back(url.URL);
break;
}
}
}
if (!urls1.empty()) urls.push_back(urls1);
}
catch (std::exception& exp) {
ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "FindServiceByType error processing NodeDiscoveryInfo for NodeID " << ee.NodeID.ToString() << ": " << exp.what() );
}
}
if (urls.empty())
{
ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "FindServiceByType could not find any candidate URLs");
RR_SHARED_PTR<std::vector<ServiceInfo2> > ret = RR_MAKE_SHARED<std::vector<ServiceInfo2> >();
detail::PostHandler(node,handler, ret,true);
return;
}
if (timeout_timer) timeout_timer->Start();
BOOST_FOREACH(std::vector<std::string>& e, urls)
{
try
{
int32_t key;
{
boost::mutex::scoped_lock lock(active_lock);
active_count++;
key = active_count;
ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "FindServiceByType connecting to node using candidate URLs " << boost::join(e,", "));
node->AsyncConnectService(e, "", (RR_INTRUSIVE_PTR<RRMap<std::string, RRValue> >()), NULL, "", boost::bind(&Discovery_findservicebytype::connect_callback, shared_from_this(), RR_BOOST_PLACEHOLDERS(_1), RR_BOOST_PLACEHOLDERS(_2), e.front(), key), timeout);
active.push_back(key);
}
}
catch (std::exception& exp2)
{
ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "FindServiceByType connecting to node using candidate URLs " << boost::join(e,", ")
<< " failed: " << exp2.what());
}
}
}
void Discovery_findservicebytype::AsyncFindServiceByType(boost::string_ref servicetype, const std::vector<std::string>& schemes, RR_MOVE_ARG(boost::function<void(RR_SHARED_PTR<std::vector<ServiceInfo2> >)>) handler, int32_t timeout)
{
ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "Begin FindServiceByType for type \"" << servicetype << "\" with schemes " << boost::join(schemes, ", "));
boost::recursive_mutex::scoped_lock lock2(work_lock);
this->handler = handler;
this->schemes = schemes;
this->timeout = timeout;
this->servicetype = RR_MOVE(servicetype.to_string());
if (timeout != RR_TIMEOUT_INFINITE)
{
timeout_timer = node->CreateTimer(boost::posix_time::milliseconds(timeout), boost::bind(&Discovery_findservicebytype::timeout_timer_callback, shared_from_this(), RR_BOOST_PLACEHOLDERS(_1)), true);
//timeout_timer->Start();
}
ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "FindServiceByType begin update detected nodes");
//int32_t timeout2=(timeout==RR_TIMEOUT_INFINITE) ? RR_TIMEOUT_INFINITE : timeout/4;
node->AsyncUpdateDetectedNodes(schemes, boost::bind(&Discovery_findservicebytype::find2, shared_from_this()), timeout / 4);
}
//class Discovery_updateserviceinfo
Discovery_updateserviceinfo::Discovery_updateserviceinfo(RR_WEAK_PTR<RobotRaconteurNode> node)
{
this->node = node;
retry_count = 0;
backoff = 0;
}
void Discovery_updateserviceinfo::handle_error(RR_SHARED_PTR<RobotRaconteurException> err)
{
RR_SHARED_PTR<RobotRaconteurNode> n = node.lock();
if (!n) return;
if (client)
{
try
{
n->AsyncDisconnectService(client, boost::bind(&Discovery_updateserviceinfo::rr_empty_handler));
}
catch (std::exception&) {}
}
client.reset();
retry_count++;
if (retry_count < 3)
{
ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "UpdateServiceInfo for remote node " << this->remote_nodeid.ToString() << " failed, retrying: " << err->what());
//Restart the process 3 times
backoff = n->GetRandomInt(0, 500);
RR_SHARED_PTR<Timer> t = n->CreateTimer(boost::posix_time::milliseconds(backoff),
boost::bind(&Discovery_updateserviceinfo::backoff_timer_handler, shared_from_this(), RR_BOOST_PLACEHOLDERS(_1)),
true);
t->Start();
timeout_timer = t;
return;
}
ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "UpdateServiceInfo for remote node " << this->remote_nodeid.ToString() << " failed, out of retries: " << err->what());
boost::function<void(RR_SHARED_PTR<Discovery_nodestorage>, RR_SHARED_PTR<std::vector<ServiceInfo2> >, boost::string_ref, RR_SHARED_PTR<RobotRaconteurException>)> handler2 = handler;
handler.clear();
{
boost::mutex::scoped_lock lock2(storage->this_lock);
if (storage->updater.lock() == shared_from_this())
{
storage->updater.reset();
}
}
if (!handler2) return;
RobotRaconteurNode::TryPostToThreadPool(node, boost::bind(handler2, storage, RR_SHARED_PTR<std::vector<ServiceInfo2> >(), service_nonce, err), true);
}
void Discovery_updateserviceinfo::rr_empty_handler()
{
}
static std::vector<std::string> Discovery_updateserviceinfo_convertmap(RR_INTRUSIVE_PTR<RRMap<int32_t, RRArray<char> > > d)
{
RR_NULL_CHECK(d);
std::vector<std::string> o;
o.reserve(d->size());
BOOST_FOREACH(RR_INTRUSIVE_PTR<RRArray<char> > d2, *d | boost::adaptors::map_values)
{
o.push_back(RRArrayToString(d2));
}
return o;
}
void Discovery_updateserviceinfo::serviceinfo_handler(RR_INTRUSIVE_PTR<MessageEntry> ret1, RR_SHARED_PTR<RobotRaconteurException> err)
{
boost::mutex::scoped_lock lock(this_lock);
if (err)
{
ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "UpdateServiceInfo getting ServiceInfo2 for remote node " << this->remote_nodeid.ToString() << " failed: " << err->what());
handle_error(err);
return;
}
RR_SHARED_PTR<RobotRaconteurNode> n = node.lock();
if (!n)
{
handle_error(RR_MAKE_SHARED<ServiceException>("Node has been released"));
return;
}
try
{
if (n)
{
n->AsyncDisconnectService(client, boost::bind(&Discovery_updateserviceinfo::rr_empty_handler));
}
}
catch (std::exception&) {}
if (!ret1)
{
ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "UpdateServiceInfo for remote node " << this->remote_nodeid.ToString() << " failed: Invalid return");
handle_error(RR_MAKE_SHARED<ServiceException>("Invalid return"));
return;
}
if (ret1->Error != MessageErrorType_None)
{
ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "UpdateServiceInfo getting ServiceInfo2 for remote node " << this->remote_nodeid.ToString() << " failed: " << ret1->Error);
handle_error(RobotRaconteurExceptionUtil::MessageEntryToException(ret1));
return;
};
RR_SHARED_PTR<std::vector<ServiceInfo2> > o = RR_MAKE_SHARED<std::vector<ServiceInfo2> >();
try
{
RR_INTRUSIVE_PTR<RobotRaconteur::MessageElement> me = ret1->FindElement("return");
// Limit size to protect from memory leak attacks
if (me->ElementSize > 64*1024)
{
ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "UpdateServiceInfo dropping response from remote node " << this->remote_nodeid.ToString() << " to prevent overflow");
handle_error(RR_MAKE_SHARED<ServiceException>("Return from remote node too large"));
return;
}
RR_INTRUSIVE_PTR<RobotRaconteur::RRMap<int32_t, RobotRaconteurServiceIndex::ServiceInfo> > ret = RobotRaconteur::rr_cast<RobotRaconteur::RRMap<int32_t, RobotRaconteurServiceIndex::ServiceInfo> >((n->UnpackMapType<int32_t, RobotRaconteurServiceIndex::ServiceInfo>(me->CastDataToNestedList())));
if (ret)
{
BOOST_FOREACH(RR_INTRUSIVE_PTR<RobotRaconteurServiceIndex::ServiceInfo>& e, *ret | boost::adaptors::map_values)
{
ServiceInfo2 o1;
o1.NodeID = remote_nodeid;
o1.NodeName = remote_nodename;
o1.Name = e->Name;
o1.ConnectionURL = Discovery_updateserviceinfo_convertmap(e->ConnectionURL);
o1.RootObjectType = e->RootObjectType;
o1.RootObjectImplements = Discovery_updateserviceinfo_convertmap(e->RootObjectImplements);
o1.Attributes = e->Attributes->GetStorageContainer();
o->push_back(o1);
}
}
}
catch (RobotRaconteurException& err)
{
ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "UpdateServiceInfo getting ServiceInfo2 for remote node " << this->remote_nodeid.ToString() << " failed: " << err.what());
handle_error(RobotRaconteurExceptionUtil::DownCastException(err));
return;
}
catch (std::exception& err)
{
ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "UpdateServiceInfo getting ServiceInfo2 for remote node " << this->remote_nodeid.ToString() << " failed: " << err.what());
handle_error(RR_MAKE_SHARED<ServiceException>(err.what()));
return;
}
boost::function<void(RR_SHARED_PTR<Discovery_nodestorage>, RR_SHARED_PTR<std::vector<ServiceInfo2> >, boost::string_ref, RR_SHARED_PTR<RobotRaconteurException>)> handler2 = handler;
handler.clear();
lock.unlock();
{
boost::mutex::scoped_lock lock2(storage->this_lock);
if (storage->updater.lock() == shared_from_this())
{
storage->updater.reset();
}
}
ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "UpdateServiceInfo getting ServiceInfo2 for remote node " << this->remote_nodeid.ToString() << " completed successfully");
if (!handler2) return;
RobotRaconteurNode::TryPostToThreadPool(node, boost::bind(handler2, storage, o, service_nonce, RR_SHARED_PTR<RobotRaconteurException>()), true);
}
void Discovery_updateserviceinfo::connect_handler(RR_SHARED_PTR<RRObject> client, RR_SHARED_PTR<RobotRaconteurException> err)
{
boost::mutex::scoped_lock lock(this_lock);
if (err)
{
ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "UpdateServiceInfo connect for remote node " << this->remote_nodeid.ToString() << " failed: " << err->what());
handle_error(err);
return;
}
RR_SHARED_PTR<RobotRaconteurNode> n = node.lock();
if (!n)
{
handle_error(RR_MAKE_SHARED<ConnectionException>("Node has been released"));
return;
}
this->client = client;
try
{
ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "UpdateServiceInfo connected to remote node " << this->remote_nodeid.ToString() << ", begin getting ServiceInfo2");
RR_SHARED_PTR<ServiceStub> client3 = rr_cast<ServiceStub>(client);
remote_nodeid=client3->GetContext()->GetRemoteNodeID();
remote_nodename = client3->GetContext()->GetRemoteNodeName();
if (remote_nodeid != storage->info->NodeID
|| (!storage->info->NodeName.empty() && remote_nodename != storage->info->NodeName))
{
//Very unlikely unless a node is on the fritz
try
{
handle_error(RR_MAKE_SHARED <ConnectionException>("Node identification mismatch"));
return;
}
catch (std::exception&) {}
}
RR_INTRUSIVE_PTR<RobotRaconteur::MessageEntry> rr_req = RobotRaconteur::CreateMessageEntry(RobotRaconteur::MessageEntryType_FunctionCallReq, "GetLocalNodeServices");
client3->AsyncProcessRequest(rr_req, boost::bind(&Discovery_updateserviceinfo::serviceinfo_handler, shared_from_this(), RR_BOOST_PLACEHOLDERS(_1), RR_BOOST_PLACEHOLDERS(_2)),5000);
}
catch (RobotRaconteurException& err)
{
ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "UpdateServiceInfo connect for remote node " << this->remote_nodeid.ToString() << " failed: " << err.what());
handle_error(RobotRaconteurExceptionUtil::DownCastException(err));
return;
}
catch (std::exception& err)
{
ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "UpdateServiceInfo connect for remote node " << this->remote_nodeid.ToString() << " failed: " << err.what());
handle_error(RR_MAKE_SHARED<ServiceException>(err.what()));
return;
}
}
void Discovery_updateserviceinfo::backoff_timer_handler(const TimerEvent& evt)
{
boost::mutex::scoped_lock lock(this_lock);
timeout_timer.reset();
RR_SHARED_PTR<RobotRaconteurNode> n = node.lock();
if (!n)
{
handle_error(RR_MAKE_SHARED<ConnectionException>("Node has been released"));
return;
}
std::vector<std::string> urls;
{
boost::mutex::scoped_lock lock(storage->this_lock);
urls.reserve(storage->info->URLs.size());
BOOST_FOREACH(NodeDiscoveryInfoURL& u, storage->info->URLs)
{
urls.push_back(u.URL);
}
}
try
{
ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "UpdateServiceInfo connecting to remote node " << this->remote_nodeid.ToString()
<< " using candidate URLs " << boost::join(urls,", "));
n->AsyncConnectService(urls, "", RR_INTRUSIVE_PTR<RRMap<std::string, RRValue> >(), NULL, "",
boost::bind(&Discovery_updateserviceinfo::connect_handler, shared_from_this(), RR_BOOST_PLACEHOLDERS(_1), RR_BOOST_PLACEHOLDERS(_2)), 15000);
}
catch (RobotRaconteurException& err)
{
ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "UpdateServiceInfo connecting to remote node " <<
this->remote_nodeid.ToString() << " using candidate URLs " << boost::join(urls,", ") << " failed: " << err.what());
handle_error(RobotRaconteurExceptionUtil::DownCastException(err));
return;
}
catch (std::exception& err)
{
ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "UpdateServiceInfo connecting to remote node " <<
this->remote_nodeid.ToString() << " using candidate URLs " << boost::join(urls,", ") << " failed: " << err.what());
handle_error(RR_MAKE_SHARED<ServiceException>(err.what()));
return;
}
}
void Discovery_updateserviceinfo::AsyncUpdateServiceInfo(RR_SHARED_PTR<Discovery_nodestorage> storage, boost::string_ref service_nonce, RR_MOVE_ARG(boost::function<void(RR_SHARED_PTR<Discovery_nodestorage>, RR_SHARED_PTR<std::vector<ServiceInfo2> >, boost::string_ref, RR_SHARED_PTR<RobotRaconteurException>)>) handler, int32_t extra_backoff)
{
this->storage = storage;
this->handler = handler;
this->retry_count = 0;
this->service_nonce = RR_MOVE(service_nonce.to_string());
RR_SHARED_PTR<RobotRaconteurNode> n = node.lock();
if (!n) return;
backoff = n->GetRandomInt(100, 600) + extra_backoff;
RR_SHARED_PTR<Timer> t = n->CreateTimer(boost::posix_time::milliseconds(backoff),
boost::bind(&Discovery_updateserviceinfo::backoff_timer_handler, shared_from_this(), RR_BOOST_PLACEHOLDERS(_1)),
true);
t->Start();
timeout_timer = t;
ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "Begin UpdateServiceInfo to remote node " <<
this->remote_nodeid.ToString() << " using " << backoff << " ms backoff");
}
//class Discovery
Discovery::Discovery(RR_SHARED_PTR<RobotRaconteurNode> node)
{
max_DiscoveredNodes.data() = 4096;
this->node = node;
ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "Discovery created");
}
std::vector<NodeDiscoveryInfo> Discovery::GetDetectedNodes()
{
std::vector<NodeDiscoveryInfo> o;
boost::mutex::scoped_lock lock(m_DiscoveredNodes_lock);
BOOST_FOREACH(RR_SHARED_PTR<Discovery_nodestorage>& o1, m_DiscoveredNodes | boost::adaptors::map_values)
{
boost::mutex::scoped_lock lock2(o1->this_lock);
o.push_back(*o1->info);
}
ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "GetDetectedNodes returning " << o.size() << " detected nodes");
return o;
}
NodeInfo2 Discovery::GetDetectedNodeCacheInfo(const RobotRaconteur::NodeID& nodeid)
{
NodeInfo2 nodeinfo2;
bool res = TryGetDetectedNodeCacheInfo(nodeid, nodeinfo2);
if (!res)
{
ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "Node " << nodeid.ToString() << "not in node cache");
throw NodeNotFoundException("Node " + nodeid.ToString() + "not in node cache");
}
return nodeinfo2;
}
bool Discovery::TryGetDetectedNodeCacheInfo(const RobotRaconteur::NodeID& nodeid, NodeInfo2& nodeinfo2)
{
boost::mutex::scoped_lock lock(m_DiscoveredNodes_lock);
std::map<std::string, RR_SHARED_PTR<Discovery_nodestorage> >::iterator e1 = m_DiscoveredNodes.find(nodeid.ToString());
if (e1 == m_DiscoveredNodes.end())
{
ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "TryGetDetectedNodeCacheInfo node " << nodeid.ToString() << " not found");
return false;
}
ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "TryGetDetectedNodeCacheInfo node " << nodeid.ToString() << " returning " << nodeinfo2.ConnectionURL.size() << " urls");
nodeinfo2.NodeID = e1->second->info->NodeID;
nodeinfo2.NodeName = e1->second->info->NodeName;
nodeinfo2.ConnectionURL.clear();
BOOST_FOREACH(NodeDiscoveryInfoURL u, e1->second->info->URLs)
{
nodeinfo2.ConnectionURL.push_back(u.URL);
}
return true;
}
static std::string Discovery_log_NodeDiscoveryInfoURLs_url_field(const NodeDiscoveryInfoURL& url)
{
return url.URL;
}
static std::string Discovery_log_NodeDiscoveryInfoURLs(const std::vector<NodeDiscoveryInfoURL>& urls)
{
return boost::join(urls | boost::adaptors::transformed(&Discovery_log_NodeDiscoveryInfoURLs_url_field), ", ");
}
void Discovery::NodeDetected(const NodeDiscoveryInfo& info)
{
if (info.NodeID.IsAnyNode()) return;
RR_SHARED_PTR<RobotRaconteurNode> n = node.lock();
if (!n) return;
ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "Node detected NodeID " << info.NodeID.ToString() << " NodeName " << info.NodeName
<< " URLs " << Discovery_log_NodeDiscoveryInfoURLs(info.URLs));
if (info.ServiceStateNonce.size() > 32)
{
ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "Node detected NodeID " << info.NodeID.ToString() << " invalid ServiceStateNonce");
return;
}
try
{
boost::mutex::scoped_lock lock(m_DiscoveredNodes_lock);
if (info.NodeName.size() > 128)
{
ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "Node detected NodeID " << info.NodeID.ToString() << " invalid NodeName");
return;
}
std::string id = info.NodeID.ToString();
std::map<std::string, RR_SHARED_PTR<Discovery_nodestorage> >::iterator e1 = m_DiscoveredNodes.find(id);
if (e1 == m_DiscoveredNodes.end())
{
if (m_DiscoveredNodes.size() >= max_DiscoveredNodes)
{
ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "Detected node NodeID " << info.NodeID.ToString()
<< " dropped due to full node cache");
return;
}
RR_SHARED_PTR<NodeDiscoveryInfo> info2 = RR_MAKE_SHARED<NodeDiscoveryInfo>(info);
for (std::vector<NodeDiscoveryInfoURL>::iterator e = info2->URLs.begin(); e != info2->URLs.end();)
{
bool valid = true;
if (e->URL.size() > 256)
{
valid = false;
}
if (valid)
{
try
{
ParseConnectionURLResult u = ParseConnectionURL(e->URL);
if (u.nodeid != info.NodeID)
{
valid = false;
}
}
catch (std::exception& exp2)
{
ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "Node detected NodeID " << info.NodeID.ToString() << " provides invalid URL: " << e->URL << ": " << exp2.what());
valid = false;
}
}
if (valid)
{
ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "Node detected NodeID " << info.NodeID.ToString() << " accepting candidate URL " << e->URL);
e++;
}
else
{
ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "Node detected NodeID " << info.NodeID.ToString() << " rejecting candidate URL " << e->URL);
e = info2->URLs.erase(e);
}
}
if (info2->URLs.size() == 0)
{
ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "Node detected NodeID " << info.NodeID.ToString() << " did not find any valid candidate URLs");
return;
}
RR_SHARED_PTR<Discovery_nodestorage> storage = RR_MAKE_SHARED<Discovery_nodestorage>();
storage->info = info2;
RR_SHARED_PTR<Discovery_updateserviceinfo> update = RR_MAKE_SHARED<Discovery_updateserviceinfo>(node);
storage->updater = update;
storage->recent_service_nonce.push_back(info2->ServiceStateNonce);
storage->retry_window_start = n->NowNodeTime();
m_DiscoveredNodes.insert(std::make_pair(id, storage));
if (!subscriptions.empty())
{
ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "Node detected NodeID " << info.NodeID.ToString() << " updating service info");
update->AsyncUpdateServiceInfo(storage, info2->ServiceStateNonce, boost::bind(&Discovery::EndUpdateServiceInfo, shared_from_this(), RR_BOOST_PLACEHOLDERS(_1), RR_BOOST_PLACEHOLDERS(_2), RR_BOOST_PLACEHOLDERS(_3), RR_BOOST_PLACEHOLDERS(_4)));
}
return;
}
else
{
boost::mutex::scoped_lock lock2(e1->second->this_lock);
RR_SHARED_PTR<NodeDiscoveryInfo>& i = e1->second->info;
BOOST_FOREACH(const NodeDiscoveryInfoURL& e, info.URLs)
{
bool found = false;
BOOST_FOREACH(NodeDiscoveryInfoURL& ee, i->URLs)
{
if (e.URL == ee.URL)
{
if (e.LastAnnounceTime > ee.LastAnnounceTime)
{
ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "Node detected NodeID " << info.NodeID.ToString()
<< " updating last announce time for candidate URL " << e.URL);
ee.LastAnnounceTime = e.LastAnnounceTime;
}
found = true;
}
}
if (!found)
{
if (e.URL.size() > 256)
{
continue;
}
try
{
ParseConnectionURLResult u = ParseConnectionURL(e.URL);
if (u.nodeid != info.NodeID)
{
continue;
}
}
catch (std::exception& exp2)
{
ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "Node detected NodeID " << info.NodeID.ToString() << " provides invalid URL: " << e.URL << ": " << exp2.what());
continue;
}
ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "Node detected NodeID " << info.NodeID.ToString() << " accepting candidate URL " << e.URL);
i->URLs.push_back(e);
}
}
if (i->ServiceStateNonce != info.ServiceStateNonce && !info.ServiceStateNonce.empty())
{
ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "Node detected NodeID " << info.NodeID.ToString() << " updating ServiceStateNonce");
i->ServiceStateNonce = info.ServiceStateNonce;
}
if (!info.ServiceStateNonce.empty())
{
if (boost::range::find(e1->second->recent_service_nonce, info.ServiceStateNonce) != e1->second->recent_service_nonce.end())
{
return;
}
else
{
e1->second->recent_service_nonce.push_back(info.ServiceStateNonce);
if (e1->second->recent_service_nonce.size() > 16)
{
e1->second->recent_service_nonce.pop_front();
}
}
}
if (!subscriptions.empty())
{
if (((i->ServiceStateNonce != e1->second->last_update_nonce) || i->ServiceStateNonce.empty())
&& !e1->second->updater.lock())
{
ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "Node detected NodeID " << info.NodeID.ToString()
<< " updating service info due to change in ServiceStateNonce");
RetryUpdateServiceInfo(e1->second);
}
}
}
}
catch (std::exception& exp)
{
ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "Node detected NodeID " << info.NodeID.ToString() << " failed: " << exp.what());
}
}
void Discovery::EndUpdateServiceInfo(RR_SHARED_PTR<Discovery_nodestorage> storage, RR_SHARED_PTR<std::vector<ServiceInfo2> > info, boost::string_ref nonce, RR_SHARED_PTR<RobotRaconteurException> err)
{
RR_SHARED_PTR<RobotRaconteurNode> n = node.lock();
if (!n) return;
if (!info) return;
boost::mutex::scoped_lock lock(m_DiscoveredNodes_lock);
boost::mutex::scoped_lock lock2(storage->this_lock);
storage->services = info;
storage->last_update_nonce = RR_MOVE(nonce.to_string());
storage->last_update_time = n->NowNodeTime();
if (storage->last_update_nonce != storage->info->ServiceStateNonce)
{
//We missed an update, do another refresh but delay 5 seconds to prevent flooding
if (!storage->updater.lock())
{
ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "ServiceStateNonce for " << storage->info->NodeID.ToString() <<
" changed during update, retry");
RetryUpdateServiceInfo(storage);
}
}
else
{
storage->retry_count.data() = 0;
}
BOOST_FOREACH(RR_WEAK_PTR<IServiceSubscription> s, subscriptions)
{
RR_SHARED_PTR<IServiceSubscription> s1 = s.lock();
if (!s1) continue;
s1->NodeUpdated(storage);
}
RobotRaconteurNode::TryPostToThreadPool(node, boost::bind(&RobotRaconteurNode::FireNodeDetected, n, storage->info, storage->services));
}
void Discovery::RetryUpdateServiceInfo(RR_SHARED_PTR<Discovery_nodestorage> storage)
{
//If updater is running, return
if (storage->updater.lock()) return;
ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "UpdateServiceInfo retry requested for " << storage->info->NodeID.ToString());
RR_SHARED_PTR<RobotRaconteurNode> n = node.lock();
if (!n) return;
boost::posix_time::ptime now = n->NowNodeTime();
if (now > storage->retry_window_start + boost::posix_time::seconds(60))
{
storage->retry_window_start = now;
storage->retry_count.data() = 0;
}
uint32_t retry_count = storage->retry_count.data()++;
//Add progressive backoffs to prevent flooding
uint32_t backoff = n->GetRandomInt<uint32_t>(100,600);
if (retry_count > 3)
backoff = n->GetRandomInt<uint32_t>(2000, 2500);
if (retry_count > 5)
backoff = n->GetRandomInt<uint32_t>(4500, 5500);
if (retry_count > 8)
backoff = n->GetRandomInt<uint32_t>(9000, 11000);
if (retry_count > 12)
backoff = n->GetRandomInt<uint32_t>(25000, 35000);
//If nonce isn't in use, add 15 seconds to delay
if (storage->info->ServiceStateNonce.empty() && storage->last_update_nonce.empty()
&& !storage->last_update_time.is_not_a_date_time())
{
backoff += 15000;
}
ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "UpdateServiceInfo retry requested for " << storage->info->NodeID.ToString()
<< " using backoff " << backoff << " ms for retry " << retry_count);
RR_SHARED_PTR<Discovery_updateserviceinfo> update = RR_MAKE_SHARED<Discovery_updateserviceinfo>(node);
storage->updater = update;
update->AsyncUpdateServiceInfo(storage, storage->info->ServiceStateNonce, boost::bind(&Discovery::EndUpdateServiceInfo, shared_from_this(), RR_BOOST_PLACEHOLDERS(_1), RR_BOOST_PLACEHOLDERS(_2), RR_BOOST_PLACEHOLDERS(_3), RR_BOOST_PLACEHOLDERS(_4)), backoff);
}
void Discovery::UpdateDetectedNodes(const std::vector<std::string>& schemes)
{
ROBOTRACONTEUR_ASSERT_MULTITHREADED(node);
RR_SHARED_PTR<detail::sync_async_handler<void> > t = RR_MAKE_SHARED<detail::sync_async_handler<void> >();
boost::function<void()> h = boost::bind(&detail::sync_async_handler<void>::operator(), t);
AsyncUpdateDetectedNodes(schemes, h);
t->end_void();
}
void Discovery::AsyncUpdateDetectedNodes(const std::vector<std::string>& schemes, boost::function<void()>& handler, int32_t timeout)
{
RR_SHARED_PTR<RobotRaconteurNode> n = node.lock();
if (!n) throw InvalidOperationException("Node has been released");
ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "UpdateDetectedNodes requested for schemes " << boost::join(schemes,", "));
std::vector<RR_SHARED_PTR<Transport> > t;
{
boost::mutex::scoped_lock lock(n->transports_lock);
boost::copy(n->transports | boost::adaptors::map_values, std::back_inserter(t));
}
RR_SHARED_PTR<Discovery_updatediscoverednodes> d = RR_MAKE_SHARED<Discovery_updatediscoverednodes>(n);
d->UpdateDiscoveredNodes(schemes, t, RR_MOVE(handler), timeout);
}
void Discovery::NodeAnnouncePacketReceived(boost::string_ref packet)
{
RR_SHARED_PTR<RobotRaconteurNode> n = node.lock();
if (!n) return;
try
{
std::string seed = "Robot Raconteur Node Discovery Packet";
if (packet.substr(0, seed.length()) == seed)
{
std::vector<std::string> lines;
boost::split(lines, packet, boost::is_from_range('\n', '\n'));
std::vector<std::string> idline;
boost::split(idline, lines.at(1), boost::is_from_range(',', ','));
RobotRaconteur::NodeID nodeid(idline.at(0));
std::string nodename;
if (idline.size() > 1)
{
nodename = idline.at(1);
}
std::string url = lines.at(2);
//If the URL or nodename is excessively long, just ignore it
if (url.size() > 256)
{
ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "Parsing discovery text packet failed: invalid URL");
return;
}
if (nodename.size() > 128)
{
nodename.clear();
}
try
{
ParseConnectionURLResult u = ParseConnectionURL(url);
if (u.nodeid != nodeid)
{
ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "Parsing discovery text packet failed: invalid URL");
return;
}
}
catch (ConnectionException& exp2)
{
ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "Parsing discovery text packet URL failed: " << exp2.what());
return;
}
std::string services_nonce;
try
{
for (size_t i = 3; i < lines.size(); i++)
{
std::string& l = lines.at(i);
boost::trim(l);
if (l.empty()) continue;
boost::regex r("^\\s*([\\w+\\.\\-]+)\\s*\\:\\s*(.*)\\s*$");
boost::smatch r_match;
if (!boost::regex_match(l, r_match, r))
{
continue;
}
std::string attr_name = boost::trim_copy(r_match[1].str());
std::string attr_value = boost::trim_copy(r_match[2].str());
if (attr_name == "ServiceStateNonce" && attr_value.size() < 32)
{
services_nonce = attr_value;
}
}
}
catch (std::exception& exp2)
{
ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "Parsing discovery text packet attributes failed: " << exp2.what());
}
NodeDiscoveryInfo info;
info.NodeID = nodeid;
info.NodeName = nodename;
NodeDiscoveryInfoURL url1;
url1.LastAnnounceTime = n->NowNodeTime();
url1.URL = url;
info.URLs.push_back(url1);
info.ServiceStateNonce = services_nonce;
ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "Parsing discovery text packet successful for node " << info.NodeID.ToString());
NodeDetected(info);
}
else
{
ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "Invalid discovery text packet received");
}
}
catch (std::exception& exp)
{
ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "Parsing discovery text packet failed: " << exp.what());
};
//Console.WriteLine(packet);
}
void Discovery::CleanDiscoveredNodes()
{
RR_SHARED_PTR<RobotRaconteurNode> n = node.lock();
if (!n) return;
{
boost::mutex::scoped_lock lock(m_DiscoveredNodes_lock);
boost::posix_time::ptime now = n->NowNodeTime();
std::vector<std::string> keys;
boost::copy(m_DiscoveredNodes | boost::adaptors::map_keys, std::back_inserter(keys));
BOOST_FOREACH(std::string& e, keys)
{
try
{
std::vector<NodeDiscoveryInfoURL> newurls = std::vector<NodeDiscoveryInfoURL>();
std::map<std::string, RR_SHARED_PTR<Discovery_nodestorage> >::iterator e1 = m_DiscoveredNodes.find(e);
if (e1 == m_DiscoveredNodes.end()) continue;
boost::mutex::scoped_lock lock2(e1->second->this_lock);
std::vector<NodeDiscoveryInfoURL> urls = e1->second->info->URLs;
BOOST_FOREACH(NodeDiscoveryInfoURL& u, urls)
{
int64_t time = (now - u.LastAnnounceTime).total_milliseconds();
if (time < 60000)
{
newurls.push_back(u);
}
}
e1->second->info->URLs = newurls;
if (newurls.empty())
{
ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "Discovery lost node " << e1->second->info->NodeID.ToString());
RR_SHARED_PTR<Discovery_nodestorage> e2 = e1->second;
BOOST_FOREACH(RR_WEAK_PTR<IServiceSubscription> s, subscriptions)
{
RR_SHARED_PTR<IServiceSubscription> s1 = s.lock();
if (!s1) continue;
try
{
s1->NodeLost(e2);
}
catch (std::exception&) {}
}
lock2.unlock();
m_DiscoveredNodes.erase(e1);
RobotRaconteurNode::TryPostToThreadPool(node, boost::bind(&RobotRaconteurNode::FireNodeLost, n, e2->info));
}
}
catch (std::exception& exp2)
{
ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "Error cleaning node " << e << ": " << exp2.what());
}
}
}
}
uint32_t Discovery::GetNodeDiscoveryMaxCacheCount()
{
boost::mutex::scoped_lock lock(m_DiscoveredNodes_lock);
return max_DiscoveredNodes;
}
void Discovery::SetNodeDiscoveryMaxCacheCount(uint32_t count)
{
boost::mutex::scoped_lock lock(m_DiscoveredNodes_lock);
max_DiscoveredNodes.data() = count;
ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "NodeDiscoveryMaxCacheCount set to " << count);
}
void Discovery::AsyncFindServiceByType(boost::string_ref servicetype, const std::vector<std::string>& transportschemes, boost::function<void(RR_SHARED_PTR<std::vector<ServiceInfo2> >) >& handler, int32_t timeout)
{
RR_SHARED_PTR<RobotRaconteurNode> n = node.lock();
if (!n) throw InvalidOperationException("Node has been released");
std::list<std::vector<std::string> > all_urls;
std::vector<ServiceInfo2> services;
std::vector<std::string> nodeids;
{
boost::mutex::scoped_lock lock(m_DiscoveredNodes_lock);
boost::copy(m_DiscoveredNodes | boost::adaptors::map_keys, std::back_inserter(nodeids));
}
for (size_t i = 0; i < nodeids.size(); i++)
{
boost::mutex::scoped_lock lock(m_DiscoveredNodes_lock);
try
{
std::vector<std::string> urls = std::vector<std::string>();
std::map<std::string, RR_SHARED_PTR<Discovery_nodestorage> >::iterator e1 = m_DiscoveredNodes.find(nodeids.at(i));
if (e1 == m_DiscoveredNodes.end()) continue;
boost::mutex::scoped_lock lock2(e1->second->this_lock);
BOOST_FOREACH(NodeDiscoveryInfoURL& url, e1->second->info->URLs)
{
BOOST_FOREACH(const std::string& e, transportschemes)
{
std::string t2 = (e + "://");
if (boost::starts_with(url.URL, t2))
{
urls.push_back(url.URL);
break;
}
}
}
if (!urls.empty()) all_urls.push_back(urls);
}
catch (std::exception& exp)
{
ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "Error searching for candidate URLs for FindServiceByType: " << exp.what());
}
}
RR_SHARED_PTR<Discovery_findservicebytype> f = RR_MAKE_SHARED<Discovery_findservicebytype>(n);
f->AsyncFindServiceByType(servicetype, transportschemes, RR_MOVE(handler), timeout);
}
std::vector<ServiceInfo2> Discovery::FindServiceByType(boost::string_ref servicetype, const std::vector<std::string>& transportschemes)
{
ROBOTRACONTEUR_ASSERT_MULTITHREADED(node);
RR_SHARED_PTR<detail::sync_async_handler<std::vector<ServiceInfo2> > > t = RR_MAKE_SHARED<detail::sync_async_handler<std::vector<ServiceInfo2> > >();
boost::function< void(RR_SHARED_PTR<std::vector<ServiceInfo2> >) > h = boost::bind(&detail::sync_async_handler<std::vector<ServiceInfo2> >::operator(), t, RR_BOOST_PLACEHOLDERS(_1), RR_SHARED_PTR<RobotRaconteurException>());
AsyncFindServiceByType(servicetype, transportschemes, h);
return *t->end();
}
std::vector<NodeInfo2> Discovery::FindNodeByID(const RobotRaconteur::NodeID& id, const std::vector<std::string>& transportschemes)
{
ROBOTRACONTEUR_ASSERT_MULTITHREADED(node);
RR_SHARED_PTR<detail::sync_async_handler<std::vector<NodeInfo2> > > n = RR_MAKE_SHARED<detail::sync_async_handler<std::vector<NodeInfo2> > >();
boost::function< void(RR_SHARED_PTR<std::vector<NodeInfo2> >) > h = boost::bind(&detail::sync_async_handler<std::vector<NodeInfo2> >::operator(), n, RR_BOOST_PLACEHOLDERS(_1), RR_SHARED_PTR<RobotRaconteurException>());
AsyncFindNodeByID(id, transportschemes, h);
return *n->end();
}
void Discovery::AsyncFindNodeByID(const RobotRaconteur::NodeID& id, const std::vector<std::string>& transportschemes, boost::function< void(RR_SHARED_PTR<std::vector<NodeInfo2> >) >& handler, int32_t timeout)
{
ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "Begin AsyncFindNodeByID for remote node " << id.ToString());
RobotRaconteur::NodeID id1 = id;
boost::function<void()> h = boost::bind(&Discovery::EndAsyncFindNodeByID, shared_from_this(), id1, transportschemes, handler);
AsyncUpdateDetectedNodes(transportschemes, h, timeout);
}
void Discovery::EndAsyncFindNodeByID(RobotRaconteur::NodeID id, std::vector<std::string> transportschemes, boost::function< void(RR_SHARED_PTR<std::vector<NodeInfo2> >) >& handler)
{
ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "AsyncFindNodeByID for remote node " << id.ToString() << " update complete");
RR_SHARED_PTR<std::vector<NodeInfo2> > ret = RR_MAKE_SHARED<std::vector<NodeInfo2> >();
std::string sid = id.ToString();
{
boost::mutex::scoped_lock lock(m_DiscoveredNodes_lock);
std::map<std::string, RR_SHARED_PTR<Discovery_nodestorage> >::iterator e1 = m_DiscoveredNodes.find(sid);
if (e1 != m_DiscoveredNodes.end())
{
boost::mutex::scoped_lock lock2(e1->second->this_lock);
RR_SHARED_PTR<NodeDiscoveryInfo> ni = e1->second->info;
NodeInfo2 n;
n.NodeID = NodeID(sid);
n.NodeName = ni->NodeName;
BOOST_FOREACH(NodeDiscoveryInfoURL& url, ni->URLs)
{
BOOST_FOREACH(std::string& e, transportschemes)
{
try
{
ParseConnectionURLResult u = ParseConnectionURL(url.URL);
if (u.scheme == e)
{
std::string short_url;
if (u.port == -1)
{
short_url = u.scheme + "://" + u.host + u.path + "?nodeid=" + boost::replace_all_copy(boost::replace_all_copy(u.nodeid.ToString(), "{", ""), "}", "");
}
else
{
short_url = u.scheme + "://" + u.host + ":" + boost::lexical_cast<std::string>(u.port) + u.path + "?nodeid=" + boost::replace_all_copy(boost::replace_all_copy(u.nodeid.ToString(), "{", ""), "}", "");
}
n.ConnectionURL.push_back(short_url);
break;
}
}
catch (std::exception& exp2)
{
ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "AsyncFindNodeByID for remote node " << id.ToString()
<< " failed processing candidate: " << exp2.what());
}
}
}
if (!n.ConnectionURL.empty())
{
ret->push_back(n);
}
}
}
ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "AsyncFindNodeByID for remote node " << id.ToString()
<< " completed successfully with " << ret->size() << " candidates");
detail::InvokeHandler(node, handler, ret);
}
std::vector<NodeInfo2> Discovery::FindNodeByName(boost::string_ref name, const std::vector<std::string>& transportschemes)
{
ROBOTRACONTEUR_ASSERT_MULTITHREADED(node);
RR_SHARED_PTR<detail::sync_async_handler<std::vector<NodeInfo2> > > n = RR_MAKE_SHARED<detail::sync_async_handler<std::vector<NodeInfo2> > >();
boost::function< void(RR_SHARED_PTR<std::vector<NodeInfo2> >) > h = boost::bind(&detail::sync_async_handler<std::vector<NodeInfo2> >::operator(), n, RR_BOOST_PLACEHOLDERS(_1), RR_SHARED_PTR<RobotRaconteurException>());
AsyncFindNodeByName(name, transportschemes, h);
return *n->end();
}
void Discovery::AsyncFindNodeByName(boost::string_ref name, const std::vector<std::string>& transportschemes, boost::function< void(RR_SHARED_PTR<std::vector<NodeInfo2> >) >& handler, int32_t timeout)
{
ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "Begin AsyncFindNodeByName for remote node \"" << name << "\"");
boost::function<void()> h = boost::bind(&Discovery::EndAsyncFindNodeByName, shared_from_this(), name.to_string(), transportschemes, handler);
AsyncUpdateDetectedNodes(transportschemes, h, timeout);
}
void Discovery::EndAsyncFindNodeByName(std::string name, std::vector<std::string> transportschemes, boost::function< void(RR_SHARED_PTR<std::vector<NodeInfo2> >) >& handler)
{
ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "AsyncFindNodeByName for remote node \"" << name << "\" update complete");
RR_SHARED_PTR<std::vector<NodeInfo2> > ret = RR_MAKE_SHARED<std::vector<NodeInfo2> >();
{
boost::mutex::scoped_lock lock(m_DiscoveredNodes_lock);
BOOST_FOREACH(RR_SHARED_PTR<Discovery_nodestorage>& e, m_DiscoveredNodes | boost::adaptors::map_values)
{
boost::mutex::scoped_lock lock2(e->this_lock);
if (e->info->NodeName == name)
{
NodeInfo2 n;
n.NodeID = e->info->NodeID;
n.NodeName = e->info->NodeName;
BOOST_FOREACH(NodeDiscoveryInfoURL& url, e->info->URLs)
{
BOOST_FOREACH(std::string& e, transportschemes)
{
try
{
ParseConnectionURLResult u = ParseConnectionURL(url.URL);
if (u.scheme == e)
{
std::string short_url;
if (u.port == -1)
{
short_url = u.scheme + "://" + u.host + u.path + "?nodeid=" + boost::replace_all_copy(boost::replace_all_copy(u.nodeid.ToString(), "{", ""), "}", "");
}
else
{
short_url = u.scheme + "://" + u.host + ":" + boost::lexical_cast<std::string>(u.port) + u.path + "?nodeid=" + boost::replace_all_copy(boost::replace_all_copy(u.nodeid.ToString(), "{", ""), "}", "");
}
n.ConnectionURL.push_back(short_url);
break;
}
}
catch (std::exception& exp2)
{
ROBOTRACONTEUR_LOG_DEBUG_COMPONENT(node, Discovery, -1, "AsyncFindNodeByID for remote node \"" << name
<< "\" failed processing candidate: " << exp2.what());
}
}
}
if (!n.ConnectionURL.empty())
{
ret->push_back(n);
}
}
}
}
ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "AsyncFindNodeByID for remote node \"" << name
<< "\" completed successfully with " << ret->size() << " candidates");
detail::InvokeHandler(node, handler, ret);
}
RR_SHARED_PTR<RobotRaconteurNode> Discovery::GetNode()
{
RR_SHARED_PTR<RobotRaconteurNode> n = node.lock();
if (!n) throw InvalidOperationException("Node has been released");
return n;
}
RR_SHARED_PTR<ServiceSubscription> Discovery::SubscribeService(const std::vector<std::string>& url, boost::string_ref username, RR_INTRUSIVE_PTR<RRMap<std::string,RRValue> > credentials, boost::string_ref objecttype)
{
RR_SHARED_PTR<ServiceSubscription> s = RR_MAKE_SHARED<ServiceSubscription>(shared_from_this());
s->InitServiceURL(url,username,credentials,objecttype);
return s;
}
RR_SHARED_PTR<ServiceSubscription> Discovery::SubscribeServiceByType(const std::vector<std::string>& service_types, RR_SHARED_PTR<ServiceSubscriptionFilter> filter)
{
RR_SHARED_PTR<ServiceSubscription> s = RR_MAKE_SHARED<ServiceSubscription>(shared_from_this());
DoSubscribe(service_types, filter, s);
return s;
}
RR_SHARED_PTR<ServiceInfo2Subscription> Discovery::SubscribeServiceInfo2(const std::vector<std::string>& service_types, RR_SHARED_PTR<ServiceSubscriptionFilter> filter)
{
RR_SHARED_PTR<ServiceInfo2Subscription> s = RR_MAKE_SHARED<ServiceInfo2Subscription>(shared_from_this());
DoSubscribe(service_types, filter, s);
return s;
}
void Discovery::DoSubscribe(const std::vector<std::string>& service_types, RR_SHARED_PTR<ServiceSubscriptionFilter> filter, RR_SHARED_PTR<IServiceSubscription> s)
{
ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "Begin DoSubscribe for service types " << boost::join(service_types, ", "));
boost::mutex::scoped_lock lock(m_DiscoveredNodes_lock);
subscriptions.push_back(s);
s->Init(service_types, filter);
std::vector<RR_SHARED_PTR<Discovery_nodestorage> > storage;
boost::range::copy(m_DiscoveredNodes | boost::adaptors::map_values, std::back_inserter(storage));
lock.unlock();
BOOST_FOREACH(RR_SHARED_PTR<Discovery_nodestorage>& n, storage)
{
boost::mutex::scoped_lock(n->this_lock);
if (n->last_update_nonce != n->info->ServiceStateNonce || n->info->ServiceStateNonce.empty())
{
try
{
ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "Subscription requesting update for node " << n->info->NodeID.ToString());
RetryUpdateServiceInfo(n);
}
catch (std::exception& exp)
{
RobotRaconteurNode::TryHandleException(node, &exp);
}
}
s->NodeUpdated(n);
}
}
void Discovery::SubscriptionClosed(RR_SHARED_PTR<IServiceSubscription> subscription)
{
boost::mutex::scoped_lock lock(m_DiscoveredNodes_lock);
ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "Subscription closed");
for (std::list<RR_WEAK_PTR<IServiceSubscription> >::iterator e = subscriptions.begin(); e != subscriptions.end(); )
{
RR_SHARED_PTR<IServiceSubscription> s = e->lock();
if (!s)
{
e = subscriptions.erase(e);
continue;
}
if (s == subscription)
{
e = subscriptions.erase(e);
}
else
{
e++;
}
}
}
void Discovery::Shutdown()
{
std::list<RR_WEAK_PTR<IServiceSubscription> > subscriptions1;
{
boost::mutex::scoped_lock lock(m_DiscoveredNodes_lock);
is_shutdown.data() = true;
subscriptions = RR_MOVE(subscriptions1);
}
BOOST_FOREACH(RR_WEAK_PTR<IServiceSubscription>& s, subscriptions1)
{
RR_SHARED_PTR<IServiceSubscription> s1 = s.lock();
if (s1)
{
s1->Close();
}
}
ROBOTRACONTEUR_LOG_TRACE_COMPONENT(node, Discovery, -1, "Discovery shut down");
}
}
}
| 61,772 | 27,806 |
#include "./stack_two_queues.hpp"
#include <queue>
using std::queue;
void stack_two_queues::pop() {
if (q1.empty()) {
return;
}
while (q1.size() != 1) {
q2.push(q1.front());
q1.pop();
}
q1.pop();
queue<int> temp = q1;
q1 = q2;
q2 = temp;
}
void stack_two_queues::push(int num) { q1.push(num); }
int stack_two_queues::top() {
while (q1.size() != 1) {
q2.push(q1.front());
q1.pop();
}
int top_item = q1.front();
q2.push(top_item);
queue<int> temp = q1;
q1 = q2;
q2 = temp;
return top_item;
}
| 552 | 266 |
#include "thriftlink_server.h"
#include "userdef_server.h"
#include <Windows.h>
#include "stdio.h"
#pragma comment(lib, "user32.lib")
bool inject_dll(HMODULE &hmodule, HHOOK &hhook, int target_threadid);
void eject_dll(HMODULE &hmodule, HHOOK &hhook);
BOOL CtrlHandler( DWORD fdwCtrlType ) ;
bool _break_loop = false;
int main(int argc, char **argv) {
if (argc==3 && _stricmp(argv[1], "hook")==0){
int threadid = atoi(argv[2]);
HMODULE hmodule = NULL;
HHOOK hhook = NULL;
// Inject dlls
if (!inject_dll(hmodule, hhook, threadid)){
printf("Injection failed.\n");
return 1;
}
// Set Ctrl handler.
if( !SetConsoleCtrlHandler( (PHANDLER_ROUTINE) CtrlHandler, TRUE ) ) {
printf("Could not set control handler.\n");
return 1;
}
printf("Press CTRL+C to stop.\n");
// Message handler is required for 32bit/64bit platform cross supporting.
MSG msg;
bool runThread = true;
while(runThread) {
// Keep pumping...
PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE);
TranslateMessage(&msg);
DispatchMessage(&msg);
if (_break_loop) break;
Sleep(10);
}
eject_dll(hmodule, hhook);
return 0;
}
else if ((argc==2||argc==3) && _stricmp(argv[1], "server")==0) {
int port = 3900;
if (argc==3) atoi(argv[2]);
thrift_server_start(port);
return 0;
}
printf("Usage:\n");
printf(" %s hook thread_id\n", argv[0]);
printf(" %s server [port_number]\n", argv[0]);
return 1;
}
//
// This sample demonstrate how to inject dll by SetWindowsHookEx.
// You can inject apifwrd.dll to destination process simply by AppInit_DLLs registry key or
// implement your own method like CreateRemoteThread, ...
//
bool inject_dll(HMODULE &hmodule, HHOOK &hhook, int target_threadid)
{
// Already hooked.
if (hhook!=NULL) return true;
// Load library
if (hmodule==NULL) {
hmodule = LoadLibraryW(L"apifwrd.dll");
if (hmodule==NULL) return false;
}
// apifwrd.dll is ready to support SetWindowsHookEx() way.
HOOKPROC addr = (HOOKPROC) GetProcAddress(hmodule, "HelperHookProcForSetWindowsHookEx");
if (addr==NULL) {
FreeLibrary(hmodule);
return false;
}
// Install hook
hhook = SetWindowsHookEx(WH_CBT, addr, hmodule, target_threadid);
if (hhook==NULL) {
FreeLibrary(hmodule);
return false;
}
return true;
}
void eject_dll(HMODULE &hmodule, HHOOK &hhook)
{
if (hhook) {
UnhookWindowsHookEx(hhook);
hhook = NULL;
}
if (hmodule) {
FreeLibrary(hmodule);
hmodule = NULL;
}
return;
}
BOOL CtrlHandler( DWORD fdwCtrlType )
{
switch( fdwCtrlType )
{
// Handle the CTRL-C signal.
case CTRL_C_EVENT:
case CTRL_CLOSE_EVENT:
case CTRL_BREAK_EVENT:
case CTRL_LOGOFF_EVENT:
case CTRL_SHUTDOWN_EVENT:
_break_loop = true;
break;
default:
return FALSE;
}
return TRUE;
} | 3,181 | 1,131 |
/*
Copyright (c) 2015 - 2021 Advanced Micro Devices, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/* HIT_START
* BUILD: %t %s ../../src/test_common.cpp ../../src/timer.cpp
* TEST: %t
* HIT_END
*/
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <complex>
#include "timer.h"
#include "test_common.h"
// Quiet pesky warnings
#ifdef WIN_OS
#define SNPRINTF sprintf_s
#else
#define SNPRINTF snprintf
#endif
#define NUM_SIZES 9
//4KB, 8KB, 64KB, 256KB, 1 MB, 4MB, 16 MB, 16MB+10
static const unsigned int Sizes[NUM_SIZES] = {4096, 8192, 65536, 262144, 524288, 1048576, 4194304, 16777216, 16777216+10};
static const unsigned int Iterations[2] = {1, 1000};
#define BUF_TYPES 4
// 16 ways to combine 4 different buffer types
#define NUM_SUBTESTS (BUF_TYPES*BUF_TYPES)
#define CHECK_RESULT(test, msg) \
if ((test)) \
{ \
printf("\n%s\n", msg); \
abort(); \
}
void setData(void *ptr, unsigned int size, char value)
{
char *ptr2 = (char *)ptr;
for (unsigned int i = 0; i < size ; i++)
{
ptr2[i] = value;
}
}
void checkData(void *ptr, unsigned int size, char value)
{
char *ptr2 = (char *)ptr;
for (unsigned int i = 0; i < size; i++)
{
if (ptr2[i] != value)
{
printf("Data validation failed at %d! Got 0x%08x\n", i, ptr2[i]);
printf("Expected 0x%08x\n", value);
CHECK_RESULT(true, "Data validation failed!");
break;
}
}
}
int main(int argc, char* argv[]) {
HipTest::parseStandardArguments(argc, argv, true);
hipError_t err = hipSuccess;
hipDeviceProp_t props = {0};
hipGetDeviceProperties(&props, p_gpuDevice);
CHECK_RESULT(err != hipSuccess, "hipGetDeviceProperties failed" );
printf("Set device to %d : %s\n", p_gpuDevice, props.name);
printf("Legend: unp - unpinned(malloc), hM - hipMalloc(device)\n");
printf(" hHR - hipHostRegister(pinned), hHM - hipHostMalloc(prePinned)\n");
err = hipSetDevice(p_gpuDevice);
CHECK_RESULT(err != hipSuccess, "hipSetDevice failed" );
unsigned int bufSize_;
bool hostMalloc[2] = {false};
bool hostRegister[2] = {false};
bool unpinnedMalloc[2] = {false};
unsigned int numIter;
void *memptr[2] = {NULL};
void *alignedmemptr[2] = {NULL};
void* srcBuffer = NULL;
void* dstBuffer = NULL;
int numTests = (p_tests == -1) ? (NUM_SIZES*NUM_SUBTESTS*2 - 1) : p_tests;
int test = (p_tests == -1) ? 0 : p_tests;
for(;test <= numTests; test++)
{
unsigned int srcTest = (test / NUM_SIZES) % BUF_TYPES;
unsigned int dstTest = (test / (NUM_SIZES*BUF_TYPES)) % BUF_TYPES;
bufSize_ = Sizes[test % NUM_SIZES];
hostMalloc[0] = hostMalloc[1] = false;
hostRegister[0] = hostRegister[1] = false;
unpinnedMalloc[0] = unpinnedMalloc[1] = false;
srcBuffer = dstBuffer = 0;
memptr[0] = memptr[1] = NULL;
alignedmemptr[0] = alignedmemptr[1] = NULL;
if (srcTest == 3)
{
hostRegister[0] = true;
}
else if (srcTest == 2)
{
hostMalloc[0] = true;
}
else if (srcTest == 1)
{
unpinnedMalloc[0] = true;
}
if (dstTest == 1)
{
unpinnedMalloc[1] = true;
}
else if (dstTest == 2)
{
hostMalloc[1] = true;
}
else if (dstTest == 3)
{
hostRegister[1] = true;
}
numIter = Iterations[test / (NUM_SIZES * NUM_SUBTESTS)];
if (hostMalloc[0])
{
err = hipHostMalloc((void**)&srcBuffer, bufSize_, 0);
setData(srcBuffer, bufSize_, 0xd0);
CHECK_RESULT(err != hipSuccess, "hipHostMalloc failed");
}
else if (hostRegister[0])
{
memptr[0] = malloc(bufSize_ + 4096);
alignedmemptr[0] = (void*)(((size_t)memptr[0] + 4095) & ~4095);
srcBuffer = alignedmemptr[0];
setData(srcBuffer, bufSize_, 0xd0);
err = hipHostRegister(srcBuffer, bufSize_, 0);
CHECK_RESULT(err != hipSuccess, "hipHostRegister failed");
}
else if (unpinnedMalloc[0])
{
memptr[0] = malloc(bufSize_ + 4096);
alignedmemptr[0] = (void*)(((size_t)memptr[0] + 4095) & ~4095);
srcBuffer = alignedmemptr[0];
setData(srcBuffer, bufSize_, 0xd0);
}
else
{
err = hipMalloc(&srcBuffer, bufSize_);
CHECK_RESULT(err != hipSuccess, "hipMalloc failed");
err = hipMemset(srcBuffer, 0xd0, bufSize_);
CHECK_RESULT(err != hipSuccess, "hipMemset failed");
}
if (hostMalloc[1])
{
err = hipHostMalloc((void**)&dstBuffer, bufSize_, 0);
CHECK_RESULT(err != hipSuccess, "hipHostMalloc failed");
}
else if (hostRegister[1])
{
memptr[1] = malloc(bufSize_ + 4096);
alignedmemptr[1] = (void*)(((size_t)memptr[1] + 4095) & ~4095);
dstBuffer = alignedmemptr[1];
err = hipHostRegister(dstBuffer, bufSize_, 0);
CHECK_RESULT(err != hipSuccess, "hipHostRegister failed");
}
else if (unpinnedMalloc[1])
{
memptr[1] = malloc(bufSize_ + 4096);
alignedmemptr[1] = (void*)(((size_t)memptr[1] + 4095) & ~4095);
dstBuffer = alignedmemptr[1];
}
else
{
err = hipMalloc(&dstBuffer, bufSize_);
CHECK_RESULT(err != hipSuccess, "hipMalloc failed");
}
CPerfCounter timer;
//warm up
err = hipMemcpy(dstBuffer, srcBuffer, bufSize_, hipMemcpyDefault);
CHECK_RESULT(err, "hipMemcpy failed");
timer.Reset();
timer.Start();
for (unsigned int i = 0; i < numIter; i++)
{
err = hipMemcpyAsync(dstBuffer, srcBuffer, bufSize_, hipMemcpyDefault, NULL);
CHECK_RESULT(err, "hipMemcpyAsync failed");
}
err = hipDeviceSynchronize();
CHECK_RESULT(err, "hipDeviceSynchronize failed");
timer.Stop();
double sec = timer.GetElapsedTime();
// Buffer copy bandwidth in GB/s
double perf = ((double)bufSize_*numIter*(double)(1e-09)) / sec;
const char *strSrc = NULL;
const char *strDst = NULL;
if (hostMalloc[0])
strSrc = "hHM";
else if (hostRegister[0])
strSrc = "hHR";
else if (unpinnedMalloc[0])
strSrc = "unp";
else
strSrc = "hM";
if (hostMalloc[1])
strDst = "hHM";
else if (hostRegister[1])
strDst = "hHR";
else if (unpinnedMalloc[1])
strDst = "unp";
else
strDst = "hM";
// Double results when src and dst are both on device
if ((!hostMalloc[0] && !hostRegister[0] && !unpinnedMalloc[0]) &&
(!hostMalloc[1] && !hostRegister[1] && !unpinnedMalloc[1]))
perf *= 2.0;
// Double results when src and dst are both in sysmem
if ((hostMalloc[0] || hostRegister[0] || unpinnedMalloc[0]) &&
(hostMalloc[1] || hostRegister[1] || unpinnedMalloc[1]))
perf *= 2.0;
char buf[256];
SNPRINTF(buf, sizeof(buf), "HIPPerfBufferCopySpeed[%d]\t(%8d bytes)\ts:%s d:%s\ti:%4d\t(GB/s) perf\t%f",
test, bufSize_, strSrc, strDst, numIter, (float)perf);
printf("%s\n", buf);
// Verification
void* temp = malloc(bufSize_ + 4096);
void* chkBuf = (void*)(((size_t)temp + 4095) & ~4095);
err = hipMemcpy(chkBuf, dstBuffer, bufSize_, hipMemcpyDefault);
CHECK_RESULT(err, "hipMemcpy failed");
checkData(chkBuf, bufSize_, 0xd0);
free(temp);
//Free src
if (hostMalloc[0])
{
hipHostFree(srcBuffer);
}
else if (hostRegister[0])
{
hipHostUnregister(srcBuffer);
free(memptr[0]);
}
else if (unpinnedMalloc[0])
{
free(memptr[0]);
}
else
{
hipFree(srcBuffer);
}
//Free dst
if (hostMalloc[1])
{
hipHostFree(dstBuffer);
}
else if (hostRegister[1])
{
hipHostUnregister(dstBuffer);
free(memptr[1]);
}
else if (unpinnedMalloc[1])
{
free(memptr[1]);
}
else
{
hipFree(dstBuffer);
}
}
passed();
}
| 9,777 | 3,433 |
#ifndef _COMMAND_LINE_ARGUMENTS_HPP_
#define _COMMAND_LINE_ARGUMENTS_HPP_
extern "C" {
#include <inttypes.h>
};
#include <string>
#include <stdexcept>
#include <sstream>
#include <limits>
/* Exceptions
*
*/
struct not_enough_arguments_error : public std::runtime_error
{
not_enough_arguments_error();
};
struct excess_argument_error : public std::runtime_error
{
excess_argument_error(const std::string &value);
};
struct missing_argument_value_error : public std::runtime_error
{
missing_argument_value_error(const std::string &argument);
};
struct unsupported_option_error : public std::runtime_error
{
unsupported_option_error(const std::string &option);
};
/* String to value conversion functions.
*
*/
template <typename T> void coerce_command_line_argument(T *arg, const std::string &value);
/* Get arguments
*
*/
template <typename T>
void get_command_line_argument(T *arg, int*i, int argc, const char **argv);
template <>
void get_command_line_argument(std::string *arg, int *i, int argc, const char **argv);
template <typename T>
void
get_command_line_argument(T *arg, int *i, int argc, const char **argv)
{
std::string string_value;
int previous_value = *i;
try {
get_command_line_argument(&string_value, i, argc, argv);
coerce_command_line_argument(arg, string_value);
} catch (...) {
*i = previous_value;
throw;
}
}
/* Command Line Argument for general values.
*
*/
template <class T>
class CommandLineArgument
{
public:
CommandLineArgument() : is_assigned(false) {}
CommandLineArgument &operator=(const T &argument) {
is_assigned = true;
value = argument;
return *this;
}
CommandLineArgument &operator=(const std::string &string) {
coerce_command_line_argument(&value, string);
is_assigned = true;
return *this;
}
T &operator*() {
if (!isAssigned())
throw std::runtime_error("Cannot obtain reference to value of expected command line argument as no value has been assigned.");
return value;
}
T *operator->() {
if (!isAssigned())
throw std::runtime_error("Cannot obtain pointer to value of expected command line argument as no value has been assigned.");
return &value;
}
bool isAssigned() const {
return is_assigned;
}
private:
bool is_assigned;
T value;
};
/* Command Line Argument for strings.
*
*/
template <>
class CommandLineArgument<std::string>
{
public:
CommandLineArgument() : is_assigned(false) {}
CommandLineArgument &operator=(const std::string &argument) {
is_assigned = true;
value = argument;
return *this;
}
std::string &operator*() {
if (!isAssigned())
throw std::runtime_error("Cannot obtain reference to value of expected command line argument as no value has been assigned.");
return value;
}
const std::string &operator*() const {
if (!isAssigned())
throw std::runtime_error("Cannot obtain reference to value of expected command line argument as no value has been assigned.");
return value;
}
std::string *operator->() {
if (!isAssigned())
throw std::runtime_error("Cannot obtain pointer to value of expected command line argument as no value has been assigned.");
return &value;
}
const std::string *operator->() const {
if (!isAssigned())
throw std::runtime_error("Cannot obtain pointer to value of expected command line argument as no value has been assigned.");
return &value;
}
bool isAssigned() const {
return is_assigned;
}
private:
bool is_assigned;
std::string value;
};
/**
** HAVE_ARGUMENT_P and HAVE_ARGUMENTS_P.
**/
template <typename T>
bool have_argument_p(const CommandLineArgument<T> &argument)
{
return argument.isAssigned();
}
template <typename T>
bool have_arguments_p(const CommandLineArgument<T> &argument)
{
return have_argument_p(argument);
}
template <typename T, typename... Rest>
bool have_arguments_p(const CommandLineArgument<T> &argument, const CommandLineArgument<Rest> & ... others)
{
return true
&& have_argument_p(argument)
&& have_arguments_p(others...);
}
/**
** ASSIGN_ARGUMENT
**/
template <typename V, typename T>
bool assign_argument(const V &value, CommandLineArgument<T> &argument)
{
if (have_argument_p(argument))
return false;
else {
argument = value;
return true;
}
}
template <typename V, typename T1, typename... Rest>
bool assign_argument(const V &value, CommandLineArgument<T1> &argument1, CommandLineArgument<Rest> & ... others)
{
return false
|| assign_argument(value, argument1)
|| assign_argument(value, others...);
}
/* Command line option test. */
bool command_line_option_p(const std::string &value);
/* Number conversions. */
template <typename T>
struct CoerceToNumberFunctor;
template <>
struct CoerceToNumberFunctor<intmax_t> : public std::binary_function<const char *, char **, intmax_t>
{
CoerceToNumberFunctor() : base(10) {}
CoerceToNumberFunctor(int _base) : base(_base) {}
result_type operator()(const char *string, char **endptr) const {
return strtoimax(string, endptr, base);
}
int base;
};
template <>
struct CoerceToNumberFunctor<uintmax_t> : public std::binary_function<const char *, char **, uintmax_t>
{
CoerceToNumberFunctor() : base(10) {}
CoerceToNumberFunctor(int _base) : base(_base) {}
result_type operator()(const char *string, char **endptr) const {
return strtoumax(string, endptr, base);
}
int base;
};
template <>
struct CoerceToNumberFunctor<double> : public std::binary_function<const char *, char **, double>
{
result_type operator()(const char *string, char **endptr) const {
return strtod(string, endptr);
}
};
template <typename T, bool IsEnum, bool IsInteger, bool IsSigned>
struct CoerceToNumberFunctorSelector;
template <typename T>
struct CoerceToNumberFunctorSelector<T, false, true, true>
{
typedef CoerceToNumberFunctor<intmax_t> functor_type;
};
template <typename T>
struct CoerceToNumberFunctorSelector<T, false, true, false>
{
typedef CoerceToNumberFunctor<uintmax_t> functor_type;
};
template <typename T>
struct CoerceToNumberFunctorSelector<T, false, false, true>
{
typedef CoerceToNumberFunctor<double> functor_type;
};
template <typename T, bool V>
struct CoerceToNumberFunctorSelector<T, true, false, V>
{
typedef typename std::underlying_type<T>::type underlying_type;
static const bool is_enum = std::is_enum<T>::value;
static const bool is_integer = std::is_integral<T>::value;
static const bool is_signed = std::is_signed<T>::value;
typedef
typename CoerceToNumberFunctorSelector<underlying_type, is_enum, is_integer, is_signed>::functor_type
functor_type;
};
template <typename T>
void
coerce_command_line_argument(T *arg, const std::string &string_value)
{
static const bool is_enum = std::is_enum<T>::value;
static const bool is_integer = std::is_integral<T>::value;
static const bool is_signed = std::is_signed<T>::value;
typedef typename CoerceToNumberFunctorSelector<T, is_enum, is_integer, is_signed>::functor_type functor_type;
functor_type functor;
const char *data = string_value.c_str();
const char *data_end = data + string_value.size();
char *end;
typename functor_type::result_type value = functor(data, &end);
std::numeric_limits<T> limits;
if ((end == data_end) && (limits.lowest() <= value) && (value <= limits.max()))
*arg = static_cast<T>(value);
else
throw std::runtime_error(std::string("Unable to convert value ") + string_value + " to the specified number type.");
}
#endif
| 7,586 | 2,481 |
/* Copyright (c) 2019, Acme Robotics, Ethan Quist, Corbyn Yhap
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <gtest/gtest.h>
#include <algorithm>
#include "InverseKinematics.hpp"
#include "RevoluteJoint.hpp"
bool AreSame(double a, double b) {
double error = fabs(a - b);
double epsilon = 0.00001;
return error < epsilon;
}
TEST(InverseKinematics, checkContract) {
InverseKinematicAcmeArm IKsolver;
std::vector<JointPtr> result;
// Using the Coordinates from the Paper
Eigen::Matrix4d T = Eigen::Matrix4d::Identity();
// Transform Matrix - Position
T.block<3, 1>(0, 3) = Eigen::Vector3d(2.0, 0.0, 2.5);
result = IKsolver.computeIK(T);
JointPtr tQ1(new RevoluteJoint(0));
JointPtr tQ2(new RevoluteJoint(0));
JointPtr tQ3(new RevoluteJoint(0));
JointPtr tQ4(new RevoluteJoint(1.5708));
JointPtr tQ5(new RevoluteJoint(1.5708));
JointPtr tQ6(new RevoluteJoint(-1.5708));
std::vector<JointPtr> expected;
expected.push_back(tQ1);
expected.push_back(tQ2);
expected.push_back(tQ3);
expected.push_back(tQ4);
expected.push_back(tQ5);
expected.push_back(tQ6);
// Test the number of joints that were output
ASSERT_EQ(expected.size(), result.size());
// Test Each element in each matches (in order)
JointPtr result1 = result[0];
double r1 = result1->getConfig();
double q1 = tQ1->getConfig();
bool joint_angle1 = AreSame(r1, q1);
ASSERT_EQ(joint_angle1, true);
JointPtr result2 = result[1];
double r2 = result2->getConfig();
double q2 = tQ2->getConfig();
bool joint_angle2 = AreSame(r2, q2);
ASSERT_EQ(joint_angle2, true);
JointPtr result3 = result[2];
double r3 = result3->getConfig();
double q3 = tQ3->getConfig();
bool joint_angle3 = AreSame(r3, q3);
ASSERT_EQ(joint_angle3, true);
JointPtr result4 = result[3];
double r4 = result4->getConfig();
double q4 = tQ4->getConfig();
bool joint_angle4 = AreSame(r4, q4);
ASSERT_EQ(joint_angle4, true);
JointPtr result5 = result[4];
double r5 = result5->getConfig();
double q5 = tQ5->getConfig();
bool joint_angle5 = AreSame(r5, q5);
ASSERT_EQ(joint_angle5, true);
JointPtr result6 = result[5];
double r6 = result6->getConfig();
double q6 = tQ6->getConfig();
bool joint_angle6 = AreSame(r6, q6);
ASSERT_EQ(joint_angle6, true);
}
| 3,766 | 1,443 |
#include <cassert>
#include <cstring>
#include <numeric>
#include <optional>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/uio.h>
#include "socket/server/icmp_socket.hpp"
#include "socket/server/lwip_utils.hpp"
#include "socket/server/raw_socket.hpp"
#include "lwip/icmp.h"
#include "lwip/icmp6.h"
#include "lwip/memp.h"
#include "lwip/raw.h"
#include "socket/server/compat/linux/icmp.h"
#include "socket/server/compat/linux/icmp6.h"
namespace openperf::socket::server {
/*
* XXX: Uses LwIP functions that reference global variables instead of parsing
* the pbuf, however this signature is used in case that ever needs to change.
*/
static uint8_t icmp_type(const pbuf*)
{
return (ip_current_is_v6() ? ICMPH_TYPE(
static_cast<const icmp6_hdr*>(ip_next_header_ptr()))
: ICMPH_TYPE(static_cast<const icmp_echo_hdr*>(
ip_next_header_ptr())));
}
/* RAW receive function; payload should point to IP header */
static uint8_t
icmp_receive_raw(void* arg, raw_pcb*, pbuf* p, const ip_addr_t* addr)
{
assert(addr != nullptr);
auto sock = reinterpret_cast<icmp_socket*>(arg);
if (sock->is_filtered(icmp_type(p))) {
/* packet not handled by socket so return 0 to allow
* icmp_input()/icmp6_input() to handle it
*/
return 0;
}
auto channel = std::get<dgram_channel*>(sock->channel());
return (channel->send(p, reinterpret_cast<const dgram_ip_addr*>(addr), 0));
}
/* DGRAM receive functions; payload should point to ICMP(v6) header */
static uint8_t
icmp_receive_dgram(void* arg, raw_pcb*, pbuf* p, const ip_addr_t* addr)
{
assert(addr != nullptr);
auto sock = reinterpret_cast<icmp_socket*>(arg);
if (sock->is_filtered(icmp_type(p))) {
/* packet not handled by socket so return 0 to allow
* icmp_input()/icmp6_input() to handle it
*/
return 0;
}
/*
* Drop the IP header so that the payload points to the ICMP/ICMPv6 header.
* XXX: ip_current_header_tot_len uses a global variable inside LwIP.
*/
pbuf_remove_header(p, ip_current_header_tot_len());
auto channel = std::get<dgram_channel*>(sock->channel());
return (channel->send(p, reinterpret_cast<const dgram_ip_addr*>(addr), 0));
}
static raw_recv_fn get_receive_function(int type)
{
switch (type) {
case SOCK_DGRAM:
return (icmp_receive_dgram);
case SOCK_RAW:
return (icmp_receive_raw);
default:
throw std::runtime_error("Invalid icmp socket type: "
+ std::to_string(type));
}
}
icmp_socket::icmp_socket(openperf::socket::server::allocator& allocator,
enum lwip_ip_addr_type ip_type,
int flags,
int protocol)
: raw_socket(
allocator, ip_type, flags, protocol, get_receive_function(flags & 0xff))
, m_filter(0)
{
if (protocol == IPPROTO_ICMPV6) {
/* ICMPv6 packets should always have checksum calculated by the stack as
* per RFC 3542 chapter 3.1 */
m_pcb->chksum_reqd = 1;
m_pcb->chksum_offset = 2;
/* Default to just echo reply to avoid issues with NDP */
m_filter.set();
m_filter[ICMP6_TYPE_EREP] = false;
}
}
icmp_socket& icmp_socket::operator=(icmp_socket&& other) noexcept
{
if (this != &other) { m_filter = other.m_filter; }
return (*this);
}
icmp_socket::icmp_socket(icmp_socket&& other) noexcept
: raw_socket(std::move(other))
, m_filter(other.m_filter)
{}
tl::expected<socklen_t, int>
icmp_socket::do_getsockopt(const raw_pcb* pcb,
const api::request_getsockopt& getsockopt)
{
switch (getsockopt.level) {
case SOL_RAW:
switch (getsockopt.optname) {
case LINUX_ICMP_FILTER: {
if (pcb->protocol != IPPROTO_ICMP)
return (tl::make_unexpected(EOPNOTSUPP));
auto filter =
linux_icmp_filter{static_cast<uint32_t>(m_filter.to_ulong())};
auto result =
copy_out(getsockopt.id.pid,
getsockopt.optval,
&filter,
std::min(static_cast<unsigned>(sizeof(filter)),
getsockopt.optlen));
if (!result) return (tl::make_unexpected(result.error()));
return (sizeof(filter));
}
default:
return (tl::make_unexpected(ENOPROTOOPT));
}
case IPPROTO_ICMPV6:
return (do_icmp6_getsockopt(pcb, getsockopt));
default:
return raw_socket::do_getsockopt(pcb, getsockopt);
}
}
tl::expected<void, int>
icmp_socket::do_setsockopt(raw_pcb* pcb,
const api::request_setsockopt& setsockopt)
{
switch (setsockopt.level) {
case SOL_RAW:
switch (setsockopt.optname) {
case LINUX_ICMP_FILTER: {
if (pcb->protocol != IPPROTO_ICMP)
return (tl::make_unexpected(EOPNOTSUPP));
auto filter = linux_icmp_filter{0};
auto opt = copy_in(reinterpret_cast<char*>(&filter),
setsockopt.id.pid,
reinterpret_cast<const char*>(setsockopt.optval),
sizeof(filter),
setsockopt.optlen);
if (!opt) return (tl::make_unexpected(opt.error()));
m_filter = icmp_filter(filter.data);
return {};
}
default:
return (tl::make_unexpected(ENOPROTOOPT));
}
case SOL_SOCKET:
return (do_sock_setsockopt(reinterpret_cast<ip_pcb*>(pcb), setsockopt));
case IPPROTO_IP:
return (do_ip_setsockopt(reinterpret_cast<ip_pcb*>(pcb), setsockopt));
case IPPROTO_IPV6:
return (do_ip6_setsockopt(reinterpret_cast<ip_pcb*>(pcb), setsockopt));
case IPPROTO_ICMPV6:
return (do_icmp6_setsockopt(pcb, setsockopt));
default:
return (tl::make_unexpected(ENOPROTOOPT));
}
}
bool icmp_socket::is_filtered(uint8_t type) const
{
return (m_filter.test(type));
}
tl::expected<socklen_t, int>
icmp_socket::do_icmp6_getsockopt(const raw_pcb* pcb,
const api::request_getsockopt& getsockopt)
{
assert(getsockopt.level == IPPROTO_ICMPV6);
switch (getsockopt.optname) {
case LINUX_ICMP6_FILTER: {
if (pcb->protocol != IPPROTO_ICMPV6)
return (tl::make_unexpected(EOPNOTSUPP));
auto filter = linux_icmp6_filter{0};
for (size_t i = 0; i < m_filter.size(); ++i) {
if (m_filter[i]) LINUX_ICMP6_FILTER_SETBLOCK(i, &filter);
}
auto result = copy_out(
getsockopt.id.pid,
getsockopt.optval,
&filter,
std::min(static_cast<unsigned>(sizeof(filter)), getsockopt.optlen));
if (!result) return (tl::make_unexpected(result.error()));
return (sizeof(filter));
}
default:
return (tl::make_unexpected(ENOPROTOOPT));
}
}
tl::expected<void, int>
icmp_socket::do_icmp6_setsockopt(raw_pcb* pcb,
const api::request_setsockopt& setsockopt)
{
assert(setsockopt.level == IPPROTO_ICMPV6);
switch (setsockopt.optname) {
case LINUX_ICMP6_FILTER: {
if (pcb->protocol != IPPROTO_ICMPV6)
return (tl::make_unexpected(EOPNOTSUPP));
auto filter = linux_icmp6_filter{0};
auto opt = copy_in(reinterpret_cast<char*>(&filter),
setsockopt.id.pid,
reinterpret_cast<const char*>(setsockopt.optval),
sizeof(filter),
setsockopt.optlen);
if (!opt) return (tl::make_unexpected(opt.error()));
for (size_t i = 0; i < m_filter.size(); ++i) {
m_filter[i] = LINUX_ICMP6_FILTER_WILLBLOCK(i, &filter);
}
return {};
}
default:
return (tl::make_unexpected(ENOPROTOOPT));
}
}
} // namespace openperf::socket::server
| 8,154 | 2,778 |
// Copyright (C) 2018-2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include <map>
#include <memory>
#include <string>
#include <algorithm>
#include <vector>
#include <ie_layouts.h>
#include <ie_iextension.h>
#include <ie_blob.h>
#include <ngraph/op/op.hpp>
#include <ngraph/node.hpp>
#include <ngraph/opsets/opset.hpp>
#define CUSTOM_RELU_TYPE "CustomReLU"
class CustomReLUImpl : public InferenceEngine::ILayerExecImpl {
public:
explicit CustomReLUImpl(const std::shared_ptr<ngraph::Node>& node) : _node(node) {}
InferenceEngine::StatusCode getSupportedConfigurations(std::vector<InferenceEngine::LayerConfig>& conf,
InferenceEngine::ResponseDesc* /*resp*/) noexcept override {
InferenceEngine::LayerConfig layerConfig;
layerConfig.dynBatchSupport = true;
if (_node->outputs().size() != 1 && _node->inputs().size() != 1)
return InferenceEngine::GENERAL_ERROR;
InferenceEngine::DataConfig cfg;
cfg.constant = false;
cfg.inPlace = 0;
InferenceEngine::SizeVector order;
auto partialShape = _node->get_output_partial_shape(0);
if (partialShape.is_dynamic())
return InferenceEngine::GENERAL_ERROR;
auto shape = _node->get_output_shape(0);
for (size_t i = 0; i < shape.size(); i++) {
order.push_back(i);
}
cfg.desc = InferenceEngine::TensorDesc(InferenceEngine::Precision::FP32,
shape, {shape, order});
layerConfig.outConfs.push_back(cfg);
layerConfig.inConfs.push_back(cfg);
conf.push_back(layerConfig);
return InferenceEngine::OK;
}
InferenceEngine::StatusCode
init(InferenceEngine::LayerConfig& /*config*/, InferenceEngine::ResponseDesc* /*resp*/) noexcept override {
return InferenceEngine::StatusCode::OK;
}
InferenceEngine::StatusCode
execute(std::vector<InferenceEngine::Blob::Ptr>& inputs, std::vector<InferenceEngine::Blob::Ptr>& outputs,
InferenceEngine::ResponseDesc* /*resp*/) noexcept override {
static bool wasCalled = false;
if (!wasCalled) {
std::cout << "Running " + std::string(CUSTOM_RELU_TYPE) + " kernel for the first time (next messages won't be printed)"
<< std::endl;
wasCalled = true;
}
for (size_t i = 0; i < inputs.size(); i++) {
InferenceEngine::MemoryBlob::CPtr minput = InferenceEngine::as<InferenceEngine::MemoryBlob>(inputs[i]);
InferenceEngine::MemoryBlob::Ptr moutput = InferenceEngine::as<InferenceEngine::MemoryBlob>(outputs[i]);
if (!moutput || !minput) {
return InferenceEngine::StatusCode::PARAMETER_MISMATCH;
}
// locked memory holder should be alive all time while access to its buffer happens
auto minputHolder = minput->rmap();
auto moutputHolder = moutput->wmap();
auto inputData = minputHolder.as<const float *>();
auto outputData = moutputHolder.as<float *>();
for (size_t j = 0; j < minput->size(); j++) {
outputData[j] = inputData[j] < 0 ? 0 : inputData[j];
}
}
return InferenceEngine::StatusCode::OK;
}
private:
const std::shared_ptr<ngraph::Node> _node;
};
class CustomReluOp: public ngraph::op::Op {
public:
static constexpr ngraph::NodeTypeInfo type_info{CUSTOM_RELU_TYPE, 0};
const ngraph::NodeTypeInfo& get_type_info() const override { return type_info; }
CustomReluOp() = default;
explicit CustomReluOp(const ngraph::Output<ngraph::Node>& arg): Op({arg}) {
constructor_validate_and_infer_types();
}
void validate_and_infer_types() override {
auto input_shape = get_input_partial_shape(0).to_shape();
ngraph::Shape output_shape(input_shape);
for (size_t i = 0; i < input_shape.size(); ++i) {
output_shape[i] = input_shape[i];
}
set_output_type(0, get_input_element_type(0), ngraph::PartialShape(output_shape));
}
std::shared_ptr<ngraph::Node> copy_with_new_args(const ngraph::NodeVector& new_args) const override {
if (new_args.size() != 1) {
throw ngraph::ngraph_error("Incorrect number of new arguments");
}
return std::make_shared<CustomReluOp>(new_args.at(0));
}
bool visit_attributes(ngraph::AttributeVisitor& visitor) override {
return true;
}
};
constexpr ngraph::NodeTypeInfo CustomReluOp::type_info;
class InPlaceExtension : public InferenceEngine::IExtension {
public:
InPlaceExtension() {
impls[CUSTOM_RELU_TYPE] = [](const std::shared_ptr<ngraph::Node>& node) -> InferenceEngine::ILayerImpl::Ptr {
return std::make_shared<CustomReLUImpl>(node);
};
}
void GetVersion(const InferenceEngine::Version*& versionInfo) const noexcept override {}
void Unload() noexcept override {}
void Release() noexcept override {}
std::vector<std::string> getImplTypes(const std::shared_ptr<ngraph::Node>& node) override {
if (impls.find(node->description()) == impls.end())
return {};
return {"CPU"};
}
InferenceEngine::ILayerImpl::Ptr getImplementation(const std::shared_ptr<ngraph::Node>& node, const std::string& implType) override {
if (impls.find(node->description()) == impls.end() || implType != "CPU")
return nullptr;
return impls[node->description()](node);
}
std::map<std::string, ngraph::OpSet> getOpSets() override {
static std::map<std::string, ngraph::OpSet> opsets;
if (opsets.empty()) {
ngraph::OpSet opset;
opset.insert<CustomReluOp>();
opsets["experimental"] = opset;
}
return opsets;
}
private:
std::map<std::string, std::function<InferenceEngine::ILayerImpl::Ptr(const std::shared_ptr<ngraph::Node>)>> impls;
};
| 6,069 | 1,878 |
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <cstring>
#include <string.h>
#include <stdio.h>
#include <cmath>
#include <limits>
#include <assert.h>
#include <stdint.h>
#include "il2cpp-class-internals.h"
#include "codegen/il2cpp-codegen.h"
#include "il2cpp-object-internals.h"
// System.Action`1<UnityEngine.AsyncOperation>
struct Action_1_t1617499438;
// System.Byte[]
struct ByteU5BU5D_t4116647657;
// System.Char[]
struct CharU5BU5D_t3528271667;
// System.Collections.Generic.List`1<System.Byte[]>
struct List_1_t1293755103;
// System.Collections.Generic.List`1<System.String>
struct List_1_t3319525431;
// System.Object[]
struct ObjectU5BU5D_t2843939325;
// System.Reflection.Assembly
struct Assembly_t;
// System.String
struct String_t;
// System.Text.DecoderFallback
struct DecoderFallback_t3123823036;
// System.Text.EncoderFallback
struct EncoderFallback_t1188251036;
// System.Text.Encoding
struct Encoding_t1523322056;
// System.Uri
struct Uri_t100236324;
// System.Void
struct Void_t1185182177;
// UnityEngine.AssetBundle
struct AssetBundle_t1153907252;
// UnityEngine.CustomYieldInstruction
struct CustomYieldInstruction_t1895667560;
// UnityEngine.Networking.CertificateHandler
struct CertificateHandler_t2739891000;
// UnityEngine.Networking.DownloadHandler
struct DownloadHandler_t2937767557;
// UnityEngine.Networking.DownloadHandlerAssetBundle
struct DownloadHandlerAssetBundle_t197128434;
// UnityEngine.Networking.UnityWebRequest
struct UnityWebRequest_t463507806;
// UnityEngine.Networking.UnityWebRequestAsyncOperation
struct UnityWebRequestAsyncOperation_t3852015985;
// UnityEngine.Networking.UploadHandler
struct UploadHandler_t2993558019;
// UnityEngine.Object
struct Object_t631007953;
// UnityEngine.WWW
struct WWW_t3688466362;
// UnityEngine.WWWForm
struct WWWForm_t4064702195;
extern RuntimeClass* ByteU5BU5D_t4116647657_il2cpp_TypeInfo_var;
extern RuntimeClass* Debug_t3317548046_il2cpp_TypeInfo_var;
extern RuntimeClass* DownloadHandlerAssetBundle_t197128434_il2cpp_TypeInfo_var;
extern RuntimeClass* Int64_t3736567304_il2cpp_TypeInfo_var;
extern RuntimeClass* Object_t631007953_il2cpp_TypeInfo_var;
extern RuntimeClass* String_t_il2cpp_TypeInfo_var;
extern RuntimeClass* WWW_t3688466362_il2cpp_TypeInfo_var;
extern String_t* _stringLiteral1060465165;
extern String_t* _stringLiteral106317971;
extern String_t* _stringLiteral1073086928;
extern String_t* _stringLiteral1091611732;
extern String_t* _stringLiteral1138636386;
extern String_t* _stringLiteral1542497020;
extern String_t* _stringLiteral1659593328;
extern String_t* _stringLiteral1814237603;
extern String_t* _stringLiteral1973828197;
extern String_t* _stringLiteral2002596717;
extern String_t* _stringLiteral2030167956;
extern String_t* _stringLiteral2117271536;
extern String_t* _stringLiteral2178748878;
extern String_t* _stringLiteral2201204884;
extern String_t* _stringLiteral2343474426;
extern String_t* _stringLiteral2487325543;
extern String_t* _stringLiteral2791739693;
extern String_t* _stringLiteral3090824594;
extern String_t* _stringLiteral3244775435;
extern String_t* _stringLiteral3363965078;
extern String_t* _stringLiteral3457136609;
extern String_t* _stringLiteral3476706848;
extern String_t* _stringLiteral3545044340;
extern String_t* _stringLiteral356324127;
extern String_t* _stringLiteral3604523934;
extern String_t* _stringLiteral3739562776;
extern String_t* _stringLiteral380657706;
extern String_t* _stringLiteral3842069051;
extern String_t* _stringLiteral3860885797;
extern String_t* _stringLiteral3899005722;
extern String_t* _stringLiteral3911804090;
extern String_t* _stringLiteral4002396095;
extern String_t* _stringLiteral4054833267;
extern String_t* _stringLiteral4140321389;
extern String_t* _stringLiteral4233297459;
extern String_t* _stringLiteral4277434149;
extern String_t* _stringLiteral461727106;
extern String_t* _stringLiteral560819067;
extern String_t* _stringLiteral573727993;
extern String_t* _stringLiteral624401215;
extern String_t* _stringLiteral757602046;
extern String_t* _stringLiteral858510039;
extern const uint32_t WWW_GetStatusCodeName_m3580893459_MetadataUsageId;
extern const uint32_t WWW_LoadFromCacheOrDownload_m4247140216_MetadataUsageId;
extern const uint32_t WWW_WaitUntilDoneIfPossible_m2855479680_MetadataUsageId;
extern const uint32_t WWW_get_assetBundle_m3753667806_MetadataUsageId;
extern const uint32_t WWW_get_bytes_m3061182897_MetadataUsageId;
extern const uint32_t WWW_get_error_m3055313367_MetadataUsageId;
extern const uint32_t WWW_get_text_m898164367_MetadataUsageId;
struct CertificateHandler_t2739891000_marshaled_com;
struct DownloadHandler_t2937767557_marshaled_com;
struct UnityWebRequest_t463507806_marshaled_com;
struct UnityWebRequest_t463507806_marshaled_pinvoke;
struct UploadHandler_t2993558019_marshaled_com;
struct ByteU5BU5D_t4116647657;
#ifndef U3CMODULEU3E_T692745538_H
#define U3CMODULEU3E_T692745538_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// <Module>
struct U3CModuleU3E_t692745538
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // U3CMODULEU3E_T692745538_H
#ifndef RUNTIMEOBJECT_H
#define RUNTIMEOBJECT_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Object
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // RUNTIMEOBJECT_H
struct Il2CppArrayBounds;
#ifndef RUNTIMEARRAY_H
#define RUNTIMEARRAY_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Array
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // RUNTIMEARRAY_H
#ifndef STRING_T_H
#define STRING_T_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.String
struct String_t : public RuntimeObject
{
public:
// System.Int32 System.String::length
int32_t ___length_0;
// System.Char System.String::start_char
Il2CppChar ___start_char_1;
public:
inline static int32_t get_offset_of_length_0() { return static_cast<int32_t>(offsetof(String_t, ___length_0)); }
inline int32_t get_length_0() const { return ___length_0; }
inline int32_t* get_address_of_length_0() { return &___length_0; }
inline void set_length_0(int32_t value)
{
___length_0 = value;
}
inline static int32_t get_offset_of_start_char_1() { return static_cast<int32_t>(offsetof(String_t, ___start_char_1)); }
inline Il2CppChar get_start_char_1() const { return ___start_char_1; }
inline Il2CppChar* get_address_of_start_char_1() { return &___start_char_1; }
inline void set_start_char_1(Il2CppChar value)
{
___start_char_1 = value;
}
};
struct String_t_StaticFields
{
public:
// System.String System.String::Empty
String_t* ___Empty_2;
// System.Char[] System.String::WhiteChars
CharU5BU5D_t3528271667* ___WhiteChars_3;
public:
inline static int32_t get_offset_of_Empty_2() { return static_cast<int32_t>(offsetof(String_t_StaticFields, ___Empty_2)); }
inline String_t* get_Empty_2() const { return ___Empty_2; }
inline String_t** get_address_of_Empty_2() { return &___Empty_2; }
inline void set_Empty_2(String_t* value)
{
___Empty_2 = value;
Il2CppCodeGenWriteBarrier((&___Empty_2), value);
}
inline static int32_t get_offset_of_WhiteChars_3() { return static_cast<int32_t>(offsetof(String_t_StaticFields, ___WhiteChars_3)); }
inline CharU5BU5D_t3528271667* get_WhiteChars_3() const { return ___WhiteChars_3; }
inline CharU5BU5D_t3528271667** get_address_of_WhiteChars_3() { return &___WhiteChars_3; }
inline void set_WhiteChars_3(CharU5BU5D_t3528271667* value)
{
___WhiteChars_3 = value;
Il2CppCodeGenWriteBarrier((&___WhiteChars_3), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // STRING_T_H
#ifndef ENCODING_T1523322056_H
#define ENCODING_T1523322056_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Text.Encoding
struct Encoding_t1523322056 : public RuntimeObject
{
public:
// System.Int32 System.Text.Encoding::codePage
int32_t ___codePage_0;
// System.Int32 System.Text.Encoding::windows_code_page
int32_t ___windows_code_page_1;
// System.Boolean System.Text.Encoding::is_readonly
bool ___is_readonly_2;
// System.Text.DecoderFallback System.Text.Encoding::decoder_fallback
DecoderFallback_t3123823036 * ___decoder_fallback_3;
// System.Text.EncoderFallback System.Text.Encoding::encoder_fallback
EncoderFallback_t1188251036 * ___encoder_fallback_4;
// System.String System.Text.Encoding::body_name
String_t* ___body_name_8;
// System.String System.Text.Encoding::encoding_name
String_t* ___encoding_name_9;
// System.String System.Text.Encoding::header_name
String_t* ___header_name_10;
// System.Boolean System.Text.Encoding::is_mail_news_display
bool ___is_mail_news_display_11;
// System.Boolean System.Text.Encoding::is_mail_news_save
bool ___is_mail_news_save_12;
// System.Boolean System.Text.Encoding::is_browser_save
bool ___is_browser_save_13;
// System.Boolean System.Text.Encoding::is_browser_display
bool ___is_browser_display_14;
// System.String System.Text.Encoding::web_name
String_t* ___web_name_15;
public:
inline static int32_t get_offset_of_codePage_0() { return static_cast<int32_t>(offsetof(Encoding_t1523322056, ___codePage_0)); }
inline int32_t get_codePage_0() const { return ___codePage_0; }
inline int32_t* get_address_of_codePage_0() { return &___codePage_0; }
inline void set_codePage_0(int32_t value)
{
___codePage_0 = value;
}
inline static int32_t get_offset_of_windows_code_page_1() { return static_cast<int32_t>(offsetof(Encoding_t1523322056, ___windows_code_page_1)); }
inline int32_t get_windows_code_page_1() const { return ___windows_code_page_1; }
inline int32_t* get_address_of_windows_code_page_1() { return &___windows_code_page_1; }
inline void set_windows_code_page_1(int32_t value)
{
___windows_code_page_1 = value;
}
inline static int32_t get_offset_of_is_readonly_2() { return static_cast<int32_t>(offsetof(Encoding_t1523322056, ___is_readonly_2)); }
inline bool get_is_readonly_2() const { return ___is_readonly_2; }
inline bool* get_address_of_is_readonly_2() { return &___is_readonly_2; }
inline void set_is_readonly_2(bool value)
{
___is_readonly_2 = value;
}
inline static int32_t get_offset_of_decoder_fallback_3() { return static_cast<int32_t>(offsetof(Encoding_t1523322056, ___decoder_fallback_3)); }
inline DecoderFallback_t3123823036 * get_decoder_fallback_3() const { return ___decoder_fallback_3; }
inline DecoderFallback_t3123823036 ** get_address_of_decoder_fallback_3() { return &___decoder_fallback_3; }
inline void set_decoder_fallback_3(DecoderFallback_t3123823036 * value)
{
___decoder_fallback_3 = value;
Il2CppCodeGenWriteBarrier((&___decoder_fallback_3), value);
}
inline static int32_t get_offset_of_encoder_fallback_4() { return static_cast<int32_t>(offsetof(Encoding_t1523322056, ___encoder_fallback_4)); }
inline EncoderFallback_t1188251036 * get_encoder_fallback_4() const { return ___encoder_fallback_4; }
inline EncoderFallback_t1188251036 ** get_address_of_encoder_fallback_4() { return &___encoder_fallback_4; }
inline void set_encoder_fallback_4(EncoderFallback_t1188251036 * value)
{
___encoder_fallback_4 = value;
Il2CppCodeGenWriteBarrier((&___encoder_fallback_4), value);
}
inline static int32_t get_offset_of_body_name_8() { return static_cast<int32_t>(offsetof(Encoding_t1523322056, ___body_name_8)); }
inline String_t* get_body_name_8() const { return ___body_name_8; }
inline String_t** get_address_of_body_name_8() { return &___body_name_8; }
inline void set_body_name_8(String_t* value)
{
___body_name_8 = value;
Il2CppCodeGenWriteBarrier((&___body_name_8), value);
}
inline static int32_t get_offset_of_encoding_name_9() { return static_cast<int32_t>(offsetof(Encoding_t1523322056, ___encoding_name_9)); }
inline String_t* get_encoding_name_9() const { return ___encoding_name_9; }
inline String_t** get_address_of_encoding_name_9() { return &___encoding_name_9; }
inline void set_encoding_name_9(String_t* value)
{
___encoding_name_9 = value;
Il2CppCodeGenWriteBarrier((&___encoding_name_9), value);
}
inline static int32_t get_offset_of_header_name_10() { return static_cast<int32_t>(offsetof(Encoding_t1523322056, ___header_name_10)); }
inline String_t* get_header_name_10() const { return ___header_name_10; }
inline String_t** get_address_of_header_name_10() { return &___header_name_10; }
inline void set_header_name_10(String_t* value)
{
___header_name_10 = value;
Il2CppCodeGenWriteBarrier((&___header_name_10), value);
}
inline static int32_t get_offset_of_is_mail_news_display_11() { return static_cast<int32_t>(offsetof(Encoding_t1523322056, ___is_mail_news_display_11)); }
inline bool get_is_mail_news_display_11() const { return ___is_mail_news_display_11; }
inline bool* get_address_of_is_mail_news_display_11() { return &___is_mail_news_display_11; }
inline void set_is_mail_news_display_11(bool value)
{
___is_mail_news_display_11 = value;
}
inline static int32_t get_offset_of_is_mail_news_save_12() { return static_cast<int32_t>(offsetof(Encoding_t1523322056, ___is_mail_news_save_12)); }
inline bool get_is_mail_news_save_12() const { return ___is_mail_news_save_12; }
inline bool* get_address_of_is_mail_news_save_12() { return &___is_mail_news_save_12; }
inline void set_is_mail_news_save_12(bool value)
{
___is_mail_news_save_12 = value;
}
inline static int32_t get_offset_of_is_browser_save_13() { return static_cast<int32_t>(offsetof(Encoding_t1523322056, ___is_browser_save_13)); }
inline bool get_is_browser_save_13() const { return ___is_browser_save_13; }
inline bool* get_address_of_is_browser_save_13() { return &___is_browser_save_13; }
inline void set_is_browser_save_13(bool value)
{
___is_browser_save_13 = value;
}
inline static int32_t get_offset_of_is_browser_display_14() { return static_cast<int32_t>(offsetof(Encoding_t1523322056, ___is_browser_display_14)); }
inline bool get_is_browser_display_14() const { return ___is_browser_display_14; }
inline bool* get_address_of_is_browser_display_14() { return &___is_browser_display_14; }
inline void set_is_browser_display_14(bool value)
{
___is_browser_display_14 = value;
}
inline static int32_t get_offset_of_web_name_15() { return static_cast<int32_t>(offsetof(Encoding_t1523322056, ___web_name_15)); }
inline String_t* get_web_name_15() const { return ___web_name_15; }
inline String_t** get_address_of_web_name_15() { return &___web_name_15; }
inline void set_web_name_15(String_t* value)
{
___web_name_15 = value;
Il2CppCodeGenWriteBarrier((&___web_name_15), value);
}
};
struct Encoding_t1523322056_StaticFields
{
public:
// System.Reflection.Assembly System.Text.Encoding::i18nAssembly
Assembly_t * ___i18nAssembly_5;
// System.Boolean System.Text.Encoding::i18nDisabled
bool ___i18nDisabled_6;
// System.Object[] System.Text.Encoding::encodings
ObjectU5BU5D_t2843939325* ___encodings_7;
// System.Text.Encoding modreq(System.Runtime.CompilerServices.IsVolatile) System.Text.Encoding::asciiEncoding
Encoding_t1523322056 * ___asciiEncoding_16;
// System.Text.Encoding modreq(System.Runtime.CompilerServices.IsVolatile) System.Text.Encoding::bigEndianEncoding
Encoding_t1523322056 * ___bigEndianEncoding_17;
// System.Text.Encoding modreq(System.Runtime.CompilerServices.IsVolatile) System.Text.Encoding::defaultEncoding
Encoding_t1523322056 * ___defaultEncoding_18;
// System.Text.Encoding modreq(System.Runtime.CompilerServices.IsVolatile) System.Text.Encoding::utf7Encoding
Encoding_t1523322056 * ___utf7Encoding_19;
// System.Text.Encoding modreq(System.Runtime.CompilerServices.IsVolatile) System.Text.Encoding::utf8EncodingWithMarkers
Encoding_t1523322056 * ___utf8EncodingWithMarkers_20;
// System.Text.Encoding modreq(System.Runtime.CompilerServices.IsVolatile) System.Text.Encoding::utf8EncodingWithoutMarkers
Encoding_t1523322056 * ___utf8EncodingWithoutMarkers_21;
// System.Text.Encoding modreq(System.Runtime.CompilerServices.IsVolatile) System.Text.Encoding::unicodeEncoding
Encoding_t1523322056 * ___unicodeEncoding_22;
// System.Text.Encoding modreq(System.Runtime.CompilerServices.IsVolatile) System.Text.Encoding::isoLatin1Encoding
Encoding_t1523322056 * ___isoLatin1Encoding_23;
// System.Text.Encoding modreq(System.Runtime.CompilerServices.IsVolatile) System.Text.Encoding::utf8EncodingUnsafe
Encoding_t1523322056 * ___utf8EncodingUnsafe_24;
// System.Text.Encoding modreq(System.Runtime.CompilerServices.IsVolatile) System.Text.Encoding::utf32Encoding
Encoding_t1523322056 * ___utf32Encoding_25;
// System.Text.Encoding modreq(System.Runtime.CompilerServices.IsVolatile) System.Text.Encoding::bigEndianUTF32Encoding
Encoding_t1523322056 * ___bigEndianUTF32Encoding_26;
// System.Object System.Text.Encoding::lockobj
RuntimeObject * ___lockobj_27;
public:
inline static int32_t get_offset_of_i18nAssembly_5() { return static_cast<int32_t>(offsetof(Encoding_t1523322056_StaticFields, ___i18nAssembly_5)); }
inline Assembly_t * get_i18nAssembly_5() const { return ___i18nAssembly_5; }
inline Assembly_t ** get_address_of_i18nAssembly_5() { return &___i18nAssembly_5; }
inline void set_i18nAssembly_5(Assembly_t * value)
{
___i18nAssembly_5 = value;
Il2CppCodeGenWriteBarrier((&___i18nAssembly_5), value);
}
inline static int32_t get_offset_of_i18nDisabled_6() { return static_cast<int32_t>(offsetof(Encoding_t1523322056_StaticFields, ___i18nDisabled_6)); }
inline bool get_i18nDisabled_6() const { return ___i18nDisabled_6; }
inline bool* get_address_of_i18nDisabled_6() { return &___i18nDisabled_6; }
inline void set_i18nDisabled_6(bool value)
{
___i18nDisabled_6 = value;
}
inline static int32_t get_offset_of_encodings_7() { return static_cast<int32_t>(offsetof(Encoding_t1523322056_StaticFields, ___encodings_7)); }
inline ObjectU5BU5D_t2843939325* get_encodings_7() const { return ___encodings_7; }
inline ObjectU5BU5D_t2843939325** get_address_of_encodings_7() { return &___encodings_7; }
inline void set_encodings_7(ObjectU5BU5D_t2843939325* value)
{
___encodings_7 = value;
Il2CppCodeGenWriteBarrier((&___encodings_7), value);
}
inline static int32_t get_offset_of_asciiEncoding_16() { return static_cast<int32_t>(offsetof(Encoding_t1523322056_StaticFields, ___asciiEncoding_16)); }
inline Encoding_t1523322056 * get_asciiEncoding_16() const { return ___asciiEncoding_16; }
inline Encoding_t1523322056 ** get_address_of_asciiEncoding_16() { return &___asciiEncoding_16; }
inline void set_asciiEncoding_16(Encoding_t1523322056 * value)
{
___asciiEncoding_16 = value;
Il2CppCodeGenWriteBarrier((&___asciiEncoding_16), value);
}
inline static int32_t get_offset_of_bigEndianEncoding_17() { return static_cast<int32_t>(offsetof(Encoding_t1523322056_StaticFields, ___bigEndianEncoding_17)); }
inline Encoding_t1523322056 * get_bigEndianEncoding_17() const { return ___bigEndianEncoding_17; }
inline Encoding_t1523322056 ** get_address_of_bigEndianEncoding_17() { return &___bigEndianEncoding_17; }
inline void set_bigEndianEncoding_17(Encoding_t1523322056 * value)
{
___bigEndianEncoding_17 = value;
Il2CppCodeGenWriteBarrier((&___bigEndianEncoding_17), value);
}
inline static int32_t get_offset_of_defaultEncoding_18() { return static_cast<int32_t>(offsetof(Encoding_t1523322056_StaticFields, ___defaultEncoding_18)); }
inline Encoding_t1523322056 * get_defaultEncoding_18() const { return ___defaultEncoding_18; }
inline Encoding_t1523322056 ** get_address_of_defaultEncoding_18() { return &___defaultEncoding_18; }
inline void set_defaultEncoding_18(Encoding_t1523322056 * value)
{
___defaultEncoding_18 = value;
Il2CppCodeGenWriteBarrier((&___defaultEncoding_18), value);
}
inline static int32_t get_offset_of_utf7Encoding_19() { return static_cast<int32_t>(offsetof(Encoding_t1523322056_StaticFields, ___utf7Encoding_19)); }
inline Encoding_t1523322056 * get_utf7Encoding_19() const { return ___utf7Encoding_19; }
inline Encoding_t1523322056 ** get_address_of_utf7Encoding_19() { return &___utf7Encoding_19; }
inline void set_utf7Encoding_19(Encoding_t1523322056 * value)
{
___utf7Encoding_19 = value;
Il2CppCodeGenWriteBarrier((&___utf7Encoding_19), value);
}
inline static int32_t get_offset_of_utf8EncodingWithMarkers_20() { return static_cast<int32_t>(offsetof(Encoding_t1523322056_StaticFields, ___utf8EncodingWithMarkers_20)); }
inline Encoding_t1523322056 * get_utf8EncodingWithMarkers_20() const { return ___utf8EncodingWithMarkers_20; }
inline Encoding_t1523322056 ** get_address_of_utf8EncodingWithMarkers_20() { return &___utf8EncodingWithMarkers_20; }
inline void set_utf8EncodingWithMarkers_20(Encoding_t1523322056 * value)
{
___utf8EncodingWithMarkers_20 = value;
Il2CppCodeGenWriteBarrier((&___utf8EncodingWithMarkers_20), value);
}
inline static int32_t get_offset_of_utf8EncodingWithoutMarkers_21() { return static_cast<int32_t>(offsetof(Encoding_t1523322056_StaticFields, ___utf8EncodingWithoutMarkers_21)); }
inline Encoding_t1523322056 * get_utf8EncodingWithoutMarkers_21() const { return ___utf8EncodingWithoutMarkers_21; }
inline Encoding_t1523322056 ** get_address_of_utf8EncodingWithoutMarkers_21() { return &___utf8EncodingWithoutMarkers_21; }
inline void set_utf8EncodingWithoutMarkers_21(Encoding_t1523322056 * value)
{
___utf8EncodingWithoutMarkers_21 = value;
Il2CppCodeGenWriteBarrier((&___utf8EncodingWithoutMarkers_21), value);
}
inline static int32_t get_offset_of_unicodeEncoding_22() { return static_cast<int32_t>(offsetof(Encoding_t1523322056_StaticFields, ___unicodeEncoding_22)); }
inline Encoding_t1523322056 * get_unicodeEncoding_22() const { return ___unicodeEncoding_22; }
inline Encoding_t1523322056 ** get_address_of_unicodeEncoding_22() { return &___unicodeEncoding_22; }
inline void set_unicodeEncoding_22(Encoding_t1523322056 * value)
{
___unicodeEncoding_22 = value;
Il2CppCodeGenWriteBarrier((&___unicodeEncoding_22), value);
}
inline static int32_t get_offset_of_isoLatin1Encoding_23() { return static_cast<int32_t>(offsetof(Encoding_t1523322056_StaticFields, ___isoLatin1Encoding_23)); }
inline Encoding_t1523322056 * get_isoLatin1Encoding_23() const { return ___isoLatin1Encoding_23; }
inline Encoding_t1523322056 ** get_address_of_isoLatin1Encoding_23() { return &___isoLatin1Encoding_23; }
inline void set_isoLatin1Encoding_23(Encoding_t1523322056 * value)
{
___isoLatin1Encoding_23 = value;
Il2CppCodeGenWriteBarrier((&___isoLatin1Encoding_23), value);
}
inline static int32_t get_offset_of_utf8EncodingUnsafe_24() { return static_cast<int32_t>(offsetof(Encoding_t1523322056_StaticFields, ___utf8EncodingUnsafe_24)); }
inline Encoding_t1523322056 * get_utf8EncodingUnsafe_24() const { return ___utf8EncodingUnsafe_24; }
inline Encoding_t1523322056 ** get_address_of_utf8EncodingUnsafe_24() { return &___utf8EncodingUnsafe_24; }
inline void set_utf8EncodingUnsafe_24(Encoding_t1523322056 * value)
{
___utf8EncodingUnsafe_24 = value;
Il2CppCodeGenWriteBarrier((&___utf8EncodingUnsafe_24), value);
}
inline static int32_t get_offset_of_utf32Encoding_25() { return static_cast<int32_t>(offsetof(Encoding_t1523322056_StaticFields, ___utf32Encoding_25)); }
inline Encoding_t1523322056 * get_utf32Encoding_25() const { return ___utf32Encoding_25; }
inline Encoding_t1523322056 ** get_address_of_utf32Encoding_25() { return &___utf32Encoding_25; }
inline void set_utf32Encoding_25(Encoding_t1523322056 * value)
{
___utf32Encoding_25 = value;
Il2CppCodeGenWriteBarrier((&___utf32Encoding_25), value);
}
inline static int32_t get_offset_of_bigEndianUTF32Encoding_26() { return static_cast<int32_t>(offsetof(Encoding_t1523322056_StaticFields, ___bigEndianUTF32Encoding_26)); }
inline Encoding_t1523322056 * get_bigEndianUTF32Encoding_26() const { return ___bigEndianUTF32Encoding_26; }
inline Encoding_t1523322056 ** get_address_of_bigEndianUTF32Encoding_26() { return &___bigEndianUTF32Encoding_26; }
inline void set_bigEndianUTF32Encoding_26(Encoding_t1523322056 * value)
{
___bigEndianUTF32Encoding_26 = value;
Il2CppCodeGenWriteBarrier((&___bigEndianUTF32Encoding_26), value);
}
inline static int32_t get_offset_of_lockobj_27() { return static_cast<int32_t>(offsetof(Encoding_t1523322056_StaticFields, ___lockobj_27)); }
inline RuntimeObject * get_lockobj_27() const { return ___lockobj_27; }
inline RuntimeObject ** get_address_of_lockobj_27() { return &___lockobj_27; }
inline void set_lockobj_27(RuntimeObject * value)
{
___lockobj_27 = value;
Il2CppCodeGenWriteBarrier((&___lockobj_27), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // ENCODING_T1523322056_H
#ifndef VALUETYPE_T3640485471_H
#define VALUETYPE_T3640485471_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ValueType
struct ValueType_t3640485471 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of System.ValueType
struct ValueType_t3640485471_marshaled_pinvoke
{
};
// Native definition for COM marshalling of System.ValueType
struct ValueType_t3640485471_marshaled_com
{
};
#endif // VALUETYPE_T3640485471_H
#ifndef CUSTOMYIELDINSTRUCTION_T1895667560_H
#define CUSTOMYIELDINSTRUCTION_T1895667560_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.CustomYieldInstruction
struct CustomYieldInstruction_t1895667560 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // CUSTOMYIELDINSTRUCTION_T1895667560_H
#ifndef WWWFORM_T4064702195_H
#define WWWFORM_T4064702195_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.WWWForm
struct WWWForm_t4064702195 : public RuntimeObject
{
public:
// System.Collections.Generic.List`1<System.Byte[]> UnityEngine.WWWForm::formData
List_1_t1293755103 * ___formData_0;
// System.Collections.Generic.List`1<System.String> UnityEngine.WWWForm::fieldNames
List_1_t3319525431 * ___fieldNames_1;
// System.Collections.Generic.List`1<System.String> UnityEngine.WWWForm::fileNames
List_1_t3319525431 * ___fileNames_2;
// System.Collections.Generic.List`1<System.String> UnityEngine.WWWForm::types
List_1_t3319525431 * ___types_3;
// System.Byte[] UnityEngine.WWWForm::boundary
ByteU5BU5D_t4116647657* ___boundary_4;
// System.Boolean UnityEngine.WWWForm::containsFiles
bool ___containsFiles_5;
public:
inline static int32_t get_offset_of_formData_0() { return static_cast<int32_t>(offsetof(WWWForm_t4064702195, ___formData_0)); }
inline List_1_t1293755103 * get_formData_0() const { return ___formData_0; }
inline List_1_t1293755103 ** get_address_of_formData_0() { return &___formData_0; }
inline void set_formData_0(List_1_t1293755103 * value)
{
___formData_0 = value;
Il2CppCodeGenWriteBarrier((&___formData_0), value);
}
inline static int32_t get_offset_of_fieldNames_1() { return static_cast<int32_t>(offsetof(WWWForm_t4064702195, ___fieldNames_1)); }
inline List_1_t3319525431 * get_fieldNames_1() const { return ___fieldNames_1; }
inline List_1_t3319525431 ** get_address_of_fieldNames_1() { return &___fieldNames_1; }
inline void set_fieldNames_1(List_1_t3319525431 * value)
{
___fieldNames_1 = value;
Il2CppCodeGenWriteBarrier((&___fieldNames_1), value);
}
inline static int32_t get_offset_of_fileNames_2() { return static_cast<int32_t>(offsetof(WWWForm_t4064702195, ___fileNames_2)); }
inline List_1_t3319525431 * get_fileNames_2() const { return ___fileNames_2; }
inline List_1_t3319525431 ** get_address_of_fileNames_2() { return &___fileNames_2; }
inline void set_fileNames_2(List_1_t3319525431 * value)
{
___fileNames_2 = value;
Il2CppCodeGenWriteBarrier((&___fileNames_2), value);
}
inline static int32_t get_offset_of_types_3() { return static_cast<int32_t>(offsetof(WWWForm_t4064702195, ___types_3)); }
inline List_1_t3319525431 * get_types_3() const { return ___types_3; }
inline List_1_t3319525431 ** get_address_of_types_3() { return &___types_3; }
inline void set_types_3(List_1_t3319525431 * value)
{
___types_3 = value;
Il2CppCodeGenWriteBarrier((&___types_3), value);
}
inline static int32_t get_offset_of_boundary_4() { return static_cast<int32_t>(offsetof(WWWForm_t4064702195, ___boundary_4)); }
inline ByteU5BU5D_t4116647657* get_boundary_4() const { return ___boundary_4; }
inline ByteU5BU5D_t4116647657** get_address_of_boundary_4() { return &___boundary_4; }
inline void set_boundary_4(ByteU5BU5D_t4116647657* value)
{
___boundary_4 = value;
Il2CppCodeGenWriteBarrier((&___boundary_4), value);
}
inline static int32_t get_offset_of_containsFiles_5() { return static_cast<int32_t>(offsetof(WWWForm_t4064702195, ___containsFiles_5)); }
inline bool get_containsFiles_5() const { return ___containsFiles_5; }
inline bool* get_address_of_containsFiles_5() { return &___containsFiles_5; }
inline void set_containsFiles_5(bool value)
{
___containsFiles_5 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // WWWFORM_T4064702195_H
#ifndef YIELDINSTRUCTION_T403091072_H
#define YIELDINSTRUCTION_T403091072_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.YieldInstruction
struct YieldInstruction_t403091072 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of UnityEngine.YieldInstruction
struct YieldInstruction_t403091072_marshaled_pinvoke
{
};
// Native definition for COM marshalling of UnityEngine.YieldInstruction
struct YieldInstruction_t403091072_marshaled_com
{
};
#endif // YIELDINSTRUCTION_T403091072_H
#ifndef BOOLEAN_T97287965_H
#define BOOLEAN_T97287965_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Boolean
struct Boolean_t97287965
{
public:
// System.Boolean System.Boolean::m_value
bool ___m_value_2;
public:
inline static int32_t get_offset_of_m_value_2() { return static_cast<int32_t>(offsetof(Boolean_t97287965, ___m_value_2)); }
inline bool get_m_value_2() const { return ___m_value_2; }
inline bool* get_address_of_m_value_2() { return &___m_value_2; }
inline void set_m_value_2(bool value)
{
___m_value_2 = value;
}
};
struct Boolean_t97287965_StaticFields
{
public:
// System.String System.Boolean::FalseString
String_t* ___FalseString_0;
// System.String System.Boolean::TrueString
String_t* ___TrueString_1;
public:
inline static int32_t get_offset_of_FalseString_0() { return static_cast<int32_t>(offsetof(Boolean_t97287965_StaticFields, ___FalseString_0)); }
inline String_t* get_FalseString_0() const { return ___FalseString_0; }
inline String_t** get_address_of_FalseString_0() { return &___FalseString_0; }
inline void set_FalseString_0(String_t* value)
{
___FalseString_0 = value;
Il2CppCodeGenWriteBarrier((&___FalseString_0), value);
}
inline static int32_t get_offset_of_TrueString_1() { return static_cast<int32_t>(offsetof(Boolean_t97287965_StaticFields, ___TrueString_1)); }
inline String_t* get_TrueString_1() const { return ___TrueString_1; }
inline String_t** get_address_of_TrueString_1() { return &___TrueString_1; }
inline void set_TrueString_1(String_t* value)
{
___TrueString_1 = value;
Il2CppCodeGenWriteBarrier((&___TrueString_1), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // BOOLEAN_T97287965_H
#ifndef BYTE_T1134296376_H
#define BYTE_T1134296376_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Byte
struct Byte_t1134296376
{
public:
// System.Byte System.Byte::m_value
uint8_t ___m_value_2;
public:
inline static int32_t get_offset_of_m_value_2() { return static_cast<int32_t>(offsetof(Byte_t1134296376, ___m_value_2)); }
inline uint8_t get_m_value_2() const { return ___m_value_2; }
inline uint8_t* get_address_of_m_value_2() { return &___m_value_2; }
inline void set_m_value_2(uint8_t value)
{
___m_value_2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // BYTE_T1134296376_H
#ifndef ENUM_T4135868527_H
#define ENUM_T4135868527_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Enum
struct Enum_t4135868527 : public ValueType_t3640485471
{
public:
public:
};
struct Enum_t4135868527_StaticFields
{
public:
// System.Char[] System.Enum::split_char
CharU5BU5D_t3528271667* ___split_char_0;
public:
inline static int32_t get_offset_of_split_char_0() { return static_cast<int32_t>(offsetof(Enum_t4135868527_StaticFields, ___split_char_0)); }
inline CharU5BU5D_t3528271667* get_split_char_0() const { return ___split_char_0; }
inline CharU5BU5D_t3528271667** get_address_of_split_char_0() { return &___split_char_0; }
inline void set_split_char_0(CharU5BU5D_t3528271667* value)
{
___split_char_0 = value;
Il2CppCodeGenWriteBarrier((&___split_char_0), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of System.Enum
struct Enum_t4135868527_marshaled_pinvoke
{
};
// Native definition for COM marshalling of System.Enum
struct Enum_t4135868527_marshaled_com
{
};
#endif // ENUM_T4135868527_H
#ifndef INT32_T2950945753_H
#define INT32_T2950945753_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Int32
struct Int32_t2950945753
{
public:
// System.Int32 System.Int32::m_value
int32_t ___m_value_2;
public:
inline static int32_t get_offset_of_m_value_2() { return static_cast<int32_t>(offsetof(Int32_t2950945753, ___m_value_2)); }
inline int32_t get_m_value_2() const { return ___m_value_2; }
inline int32_t* get_address_of_m_value_2() { return &___m_value_2; }
inline void set_m_value_2(int32_t value)
{
___m_value_2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // INT32_T2950945753_H
#ifndef INT64_T3736567304_H
#define INT64_T3736567304_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Int64
struct Int64_t3736567304
{
public:
// System.Int64 System.Int64::m_value
int64_t ___m_value_0;
public:
inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(Int64_t3736567304, ___m_value_0)); }
inline int64_t get_m_value_0() const { return ___m_value_0; }
inline int64_t* get_address_of_m_value_0() { return &___m_value_0; }
inline void set_m_value_0(int64_t value)
{
___m_value_0 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // INT64_T3736567304_H
#ifndef INTPTR_T_H
#define INTPTR_T_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.IntPtr
struct IntPtr_t
{
public:
// System.Void* System.IntPtr::m_value
void* ___m_value_0;
public:
inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(IntPtr_t, ___m_value_0)); }
inline void* get_m_value_0() const { return ___m_value_0; }
inline void** get_address_of_m_value_0() { return &___m_value_0; }
inline void set_m_value_0(void* value)
{
___m_value_0 = value;
}
};
struct IntPtr_t_StaticFields
{
public:
// System.IntPtr System.IntPtr::Zero
intptr_t ___Zero_1;
public:
inline static int32_t get_offset_of_Zero_1() { return static_cast<int32_t>(offsetof(IntPtr_t_StaticFields, ___Zero_1)); }
inline intptr_t get_Zero_1() const { return ___Zero_1; }
inline intptr_t* get_address_of_Zero_1() { return &___Zero_1; }
inline void set_Zero_1(intptr_t value)
{
___Zero_1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // INTPTR_T_H
#ifndef UINT32_T2560061978_H
#define UINT32_T2560061978_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.UInt32
struct UInt32_t2560061978
{
public:
// System.UInt32 System.UInt32::m_value
uint32_t ___m_value_0;
public:
inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(UInt32_t2560061978, ___m_value_0)); }
inline uint32_t get_m_value_0() const { return ___m_value_0; }
inline uint32_t* get_address_of_m_value_0() { return &___m_value_0; }
inline void set_m_value_0(uint32_t value)
{
___m_value_0 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // UINT32_T2560061978_H
#ifndef VOID_T1185182177_H
#define VOID_T1185182177_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Void
struct Void_t1185182177
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // VOID_T1185182177_H
#ifndef HASH128_T2357739769_H
#define HASH128_T2357739769_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.Hash128
struct Hash128_t2357739769
{
public:
// System.UInt32 UnityEngine.Hash128::m_u32_0
uint32_t ___m_u32_0_0;
// System.UInt32 UnityEngine.Hash128::m_u32_1
uint32_t ___m_u32_1_1;
// System.UInt32 UnityEngine.Hash128::m_u32_2
uint32_t ___m_u32_2_2;
// System.UInt32 UnityEngine.Hash128::m_u32_3
uint32_t ___m_u32_3_3;
public:
inline static int32_t get_offset_of_m_u32_0_0() { return static_cast<int32_t>(offsetof(Hash128_t2357739769, ___m_u32_0_0)); }
inline uint32_t get_m_u32_0_0() const { return ___m_u32_0_0; }
inline uint32_t* get_address_of_m_u32_0_0() { return &___m_u32_0_0; }
inline void set_m_u32_0_0(uint32_t value)
{
___m_u32_0_0 = value;
}
inline static int32_t get_offset_of_m_u32_1_1() { return static_cast<int32_t>(offsetof(Hash128_t2357739769, ___m_u32_1_1)); }
inline uint32_t get_m_u32_1_1() const { return ___m_u32_1_1; }
inline uint32_t* get_address_of_m_u32_1_1() { return &___m_u32_1_1; }
inline void set_m_u32_1_1(uint32_t value)
{
___m_u32_1_1 = value;
}
inline static int32_t get_offset_of_m_u32_2_2() { return static_cast<int32_t>(offsetof(Hash128_t2357739769, ___m_u32_2_2)); }
inline uint32_t get_m_u32_2_2() const { return ___m_u32_2_2; }
inline uint32_t* get_address_of_m_u32_2_2() { return &___m_u32_2_2; }
inline void set_m_u32_2_2(uint32_t value)
{
___m_u32_2_2 = value;
}
inline static int32_t get_offset_of_m_u32_3_3() { return static_cast<int32_t>(offsetof(Hash128_t2357739769, ___m_u32_3_3)); }
inline uint32_t get_m_u32_3_3() const { return ___m_u32_3_3; }
inline uint32_t* get_address_of_m_u32_3_3() { return &___m_u32_3_3; }
inline void set_m_u32_3_3(uint32_t value)
{
___m_u32_3_3 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // HASH128_T2357739769_H
#ifndef WWW_T3688466362_H
#define WWW_T3688466362_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.WWW
struct WWW_t3688466362 : public CustomYieldInstruction_t1895667560
{
public:
// UnityEngine.Networking.UnityWebRequest UnityEngine.WWW::_uwr
UnityWebRequest_t463507806 * ____uwr_0;
// UnityEngine.AssetBundle UnityEngine.WWW::_assetBundle
AssetBundle_t1153907252 * ____assetBundle_1;
public:
inline static int32_t get_offset_of__uwr_0() { return static_cast<int32_t>(offsetof(WWW_t3688466362, ____uwr_0)); }
inline UnityWebRequest_t463507806 * get__uwr_0() const { return ____uwr_0; }
inline UnityWebRequest_t463507806 ** get_address_of__uwr_0() { return &____uwr_0; }
inline void set__uwr_0(UnityWebRequest_t463507806 * value)
{
____uwr_0 = value;
Il2CppCodeGenWriteBarrier((&____uwr_0), value);
}
inline static int32_t get_offset_of__assetBundle_1() { return static_cast<int32_t>(offsetof(WWW_t3688466362, ____assetBundle_1)); }
inline AssetBundle_t1153907252 * get__assetBundle_1() const { return ____assetBundle_1; }
inline AssetBundle_t1153907252 ** get_address_of__assetBundle_1() { return &____assetBundle_1; }
inline void set__assetBundle_1(AssetBundle_t1153907252 * value)
{
____assetBundle_1 = value;
Il2CppCodeGenWriteBarrier((&____assetBundle_1), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // WWW_T3688466362_H
#ifndef STRINGCOMPARISON_T3657712135_H
#define STRINGCOMPARISON_T3657712135_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.StringComparison
struct StringComparison_t3657712135
{
public:
// System.Int32 System.StringComparison::value__
int32_t ___value___1;
public:
inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(StringComparison_t3657712135, ___value___1)); }
inline int32_t get_value___1() const { return ___value___1; }
inline int32_t* get_address_of_value___1() { return &___value___1; }
inline void set_value___1(int32_t value)
{
___value___1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // STRINGCOMPARISON_T3657712135_H
#ifndef ASYNCOPERATION_T1445031843_H
#define ASYNCOPERATION_T1445031843_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.AsyncOperation
struct AsyncOperation_t1445031843 : public YieldInstruction_t403091072
{
public:
// System.IntPtr UnityEngine.AsyncOperation::m_Ptr
intptr_t ___m_Ptr_0;
// System.Action`1<UnityEngine.AsyncOperation> UnityEngine.AsyncOperation::m_completeCallback
Action_1_t1617499438 * ___m_completeCallback_1;
public:
inline static int32_t get_offset_of_m_Ptr_0() { return static_cast<int32_t>(offsetof(AsyncOperation_t1445031843, ___m_Ptr_0)); }
inline intptr_t get_m_Ptr_0() const { return ___m_Ptr_0; }
inline intptr_t* get_address_of_m_Ptr_0() { return &___m_Ptr_0; }
inline void set_m_Ptr_0(intptr_t value)
{
___m_Ptr_0 = value;
}
inline static int32_t get_offset_of_m_completeCallback_1() { return static_cast<int32_t>(offsetof(AsyncOperation_t1445031843, ___m_completeCallback_1)); }
inline Action_1_t1617499438 * get_m_completeCallback_1() const { return ___m_completeCallback_1; }
inline Action_1_t1617499438 ** get_address_of_m_completeCallback_1() { return &___m_completeCallback_1; }
inline void set_m_completeCallback_1(Action_1_t1617499438 * value)
{
___m_completeCallback_1 = value;
Il2CppCodeGenWriteBarrier((&___m_completeCallback_1), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of UnityEngine.AsyncOperation
struct AsyncOperation_t1445031843_marshaled_pinvoke : public YieldInstruction_t403091072_marshaled_pinvoke
{
intptr_t ___m_Ptr_0;
Il2CppMethodPointer ___m_completeCallback_1;
};
// Native definition for COM marshalling of UnityEngine.AsyncOperation
struct AsyncOperation_t1445031843_marshaled_com : public YieldInstruction_t403091072_marshaled_com
{
intptr_t ___m_Ptr_0;
Il2CppMethodPointer ___m_completeCallback_1;
};
#endif // ASYNCOPERATION_T1445031843_H
#ifndef CACHEDASSETBUNDLE_T2205819908_H
#define CACHEDASSETBUNDLE_T2205819908_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.CachedAssetBundle
struct CachedAssetBundle_t2205819908
{
public:
// System.String UnityEngine.CachedAssetBundle::m_Name
String_t* ___m_Name_0;
// UnityEngine.Hash128 UnityEngine.CachedAssetBundle::m_Hash
Hash128_t2357739769 ___m_Hash_1;
public:
inline static int32_t get_offset_of_m_Name_0() { return static_cast<int32_t>(offsetof(CachedAssetBundle_t2205819908, ___m_Name_0)); }
inline String_t* get_m_Name_0() const { return ___m_Name_0; }
inline String_t** get_address_of_m_Name_0() { return &___m_Name_0; }
inline void set_m_Name_0(String_t* value)
{
___m_Name_0 = value;
Il2CppCodeGenWriteBarrier((&___m_Name_0), value);
}
inline static int32_t get_offset_of_m_Hash_1() { return static_cast<int32_t>(offsetof(CachedAssetBundle_t2205819908, ___m_Hash_1)); }
inline Hash128_t2357739769 get_m_Hash_1() const { return ___m_Hash_1; }
inline Hash128_t2357739769 * get_address_of_m_Hash_1() { return &___m_Hash_1; }
inline void set_m_Hash_1(Hash128_t2357739769 value)
{
___m_Hash_1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of UnityEngine.CachedAssetBundle
struct CachedAssetBundle_t2205819908_marshaled_pinvoke
{
char* ___m_Name_0;
Hash128_t2357739769 ___m_Hash_1;
};
// Native definition for COM marshalling of UnityEngine.CachedAssetBundle
struct CachedAssetBundle_t2205819908_marshaled_com
{
Il2CppChar* ___m_Name_0;
Hash128_t2357739769 ___m_Hash_1;
};
#endif // CACHEDASSETBUNDLE_T2205819908_H
#ifndef CERTIFICATEHANDLER_T2739891000_H
#define CERTIFICATEHANDLER_T2739891000_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.Networking.CertificateHandler
struct CertificateHandler_t2739891000 : public RuntimeObject
{
public:
// System.IntPtr UnityEngine.Networking.CertificateHandler::m_Ptr
intptr_t ___m_Ptr_0;
public:
inline static int32_t get_offset_of_m_Ptr_0() { return static_cast<int32_t>(offsetof(CertificateHandler_t2739891000, ___m_Ptr_0)); }
inline intptr_t get_m_Ptr_0() const { return ___m_Ptr_0; }
inline intptr_t* get_address_of_m_Ptr_0() { return &___m_Ptr_0; }
inline void set_m_Ptr_0(intptr_t value)
{
___m_Ptr_0 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of UnityEngine.Networking.CertificateHandler
struct CertificateHandler_t2739891000_marshaled_pinvoke
{
intptr_t ___m_Ptr_0;
};
// Native definition for COM marshalling of UnityEngine.Networking.CertificateHandler
struct CertificateHandler_t2739891000_marshaled_com
{
intptr_t ___m_Ptr_0;
};
#endif // CERTIFICATEHANDLER_T2739891000_H
#ifndef DOWNLOADHANDLER_T2937767557_H
#define DOWNLOADHANDLER_T2937767557_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.Networking.DownloadHandler
struct DownloadHandler_t2937767557 : public RuntimeObject
{
public:
// System.IntPtr UnityEngine.Networking.DownloadHandler::m_Ptr
intptr_t ___m_Ptr_0;
public:
inline static int32_t get_offset_of_m_Ptr_0() { return static_cast<int32_t>(offsetof(DownloadHandler_t2937767557, ___m_Ptr_0)); }
inline intptr_t get_m_Ptr_0() const { return ___m_Ptr_0; }
inline intptr_t* get_address_of_m_Ptr_0() { return &___m_Ptr_0; }
inline void set_m_Ptr_0(intptr_t value)
{
___m_Ptr_0 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of UnityEngine.Networking.DownloadHandler
struct DownloadHandler_t2937767557_marshaled_pinvoke
{
intptr_t ___m_Ptr_0;
};
// Native definition for COM marshalling of UnityEngine.Networking.DownloadHandler
struct DownloadHandler_t2937767557_marshaled_com
{
intptr_t ___m_Ptr_0;
};
#endif // DOWNLOADHANDLER_T2937767557_H
#ifndef UPLOADHANDLER_T2993558019_H
#define UPLOADHANDLER_T2993558019_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.Networking.UploadHandler
struct UploadHandler_t2993558019 : public RuntimeObject
{
public:
// System.IntPtr UnityEngine.Networking.UploadHandler::m_Ptr
intptr_t ___m_Ptr_0;
public:
inline static int32_t get_offset_of_m_Ptr_0() { return static_cast<int32_t>(offsetof(UploadHandler_t2993558019, ___m_Ptr_0)); }
inline intptr_t get_m_Ptr_0() const { return ___m_Ptr_0; }
inline intptr_t* get_address_of_m_Ptr_0() { return &___m_Ptr_0; }
inline void set_m_Ptr_0(intptr_t value)
{
___m_Ptr_0 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of UnityEngine.Networking.UploadHandler
struct UploadHandler_t2993558019_marshaled_pinvoke
{
intptr_t ___m_Ptr_0;
};
// Native definition for COM marshalling of UnityEngine.Networking.UploadHandler
struct UploadHandler_t2993558019_marshaled_com
{
intptr_t ___m_Ptr_0;
};
#endif // UPLOADHANDLER_T2993558019_H
#ifndef OBJECT_T631007953_H
#define OBJECT_T631007953_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.Object
struct Object_t631007953 : public RuntimeObject
{
public:
// System.IntPtr UnityEngine.Object::m_CachedPtr
intptr_t ___m_CachedPtr_0;
public:
inline static int32_t get_offset_of_m_CachedPtr_0() { return static_cast<int32_t>(offsetof(Object_t631007953, ___m_CachedPtr_0)); }
inline intptr_t get_m_CachedPtr_0() const { return ___m_CachedPtr_0; }
inline intptr_t* get_address_of_m_CachedPtr_0() { return &___m_CachedPtr_0; }
inline void set_m_CachedPtr_0(intptr_t value)
{
___m_CachedPtr_0 = value;
}
};
struct Object_t631007953_StaticFields
{
public:
// System.Int32 UnityEngine.Object::OffsetOfInstanceIDInCPlusPlusObject
int32_t ___OffsetOfInstanceIDInCPlusPlusObject_1;
public:
inline static int32_t get_offset_of_OffsetOfInstanceIDInCPlusPlusObject_1() { return static_cast<int32_t>(offsetof(Object_t631007953_StaticFields, ___OffsetOfInstanceIDInCPlusPlusObject_1)); }
inline int32_t get_OffsetOfInstanceIDInCPlusPlusObject_1() const { return ___OffsetOfInstanceIDInCPlusPlusObject_1; }
inline int32_t* get_address_of_OffsetOfInstanceIDInCPlusPlusObject_1() { return &___OffsetOfInstanceIDInCPlusPlusObject_1; }
inline void set_OffsetOfInstanceIDInCPlusPlusObject_1(int32_t value)
{
___OffsetOfInstanceIDInCPlusPlusObject_1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of UnityEngine.Object
struct Object_t631007953_marshaled_pinvoke
{
intptr_t ___m_CachedPtr_0;
};
// Native definition for COM marshalling of UnityEngine.Object
struct Object_t631007953_marshaled_com
{
intptr_t ___m_CachedPtr_0;
};
#endif // OBJECT_T631007953_H
#ifndef ASSETBUNDLE_T1153907252_H
#define ASSETBUNDLE_T1153907252_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.AssetBundle
struct AssetBundle_t1153907252 : public Object_t631007953
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // ASSETBUNDLE_T1153907252_H
#ifndef DOWNLOADHANDLERASSETBUNDLE_T197128434_H
#define DOWNLOADHANDLERASSETBUNDLE_T197128434_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.Networking.DownloadHandlerAssetBundle
struct DownloadHandlerAssetBundle_t197128434 : public DownloadHandler_t2937767557
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of UnityEngine.Networking.DownloadHandlerAssetBundle
struct DownloadHandlerAssetBundle_t197128434_marshaled_pinvoke : public DownloadHandler_t2937767557_marshaled_pinvoke
{
};
// Native definition for COM marshalling of UnityEngine.Networking.DownloadHandlerAssetBundle
struct DownloadHandlerAssetBundle_t197128434_marshaled_com : public DownloadHandler_t2937767557_marshaled_com
{
};
#endif // DOWNLOADHANDLERASSETBUNDLE_T197128434_H
#ifndef UNITYWEBREQUEST_T463507806_H
#define UNITYWEBREQUEST_T463507806_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.Networking.UnityWebRequest
struct UnityWebRequest_t463507806 : public RuntimeObject
{
public:
// System.IntPtr UnityEngine.Networking.UnityWebRequest::m_Ptr
intptr_t ___m_Ptr_0;
// UnityEngine.Networking.DownloadHandler UnityEngine.Networking.UnityWebRequest::m_DownloadHandler
DownloadHandler_t2937767557 * ___m_DownloadHandler_1;
// UnityEngine.Networking.UploadHandler UnityEngine.Networking.UnityWebRequest::m_UploadHandler
UploadHandler_t2993558019 * ___m_UploadHandler_2;
// UnityEngine.Networking.CertificateHandler UnityEngine.Networking.UnityWebRequest::m_CertificateHandler
CertificateHandler_t2739891000 * ___m_CertificateHandler_3;
// System.Uri UnityEngine.Networking.UnityWebRequest::m_Uri
Uri_t100236324 * ___m_Uri_4;
// System.Boolean UnityEngine.Networking.UnityWebRequest::<disposeCertificateHandlerOnDispose>k__BackingField
bool ___U3CdisposeCertificateHandlerOnDisposeU3Ek__BackingField_5;
// System.Boolean UnityEngine.Networking.UnityWebRequest::<disposeDownloadHandlerOnDispose>k__BackingField
bool ___U3CdisposeDownloadHandlerOnDisposeU3Ek__BackingField_6;
// System.Boolean UnityEngine.Networking.UnityWebRequest::<disposeUploadHandlerOnDispose>k__BackingField
bool ___U3CdisposeUploadHandlerOnDisposeU3Ek__BackingField_7;
public:
inline static int32_t get_offset_of_m_Ptr_0() { return static_cast<int32_t>(offsetof(UnityWebRequest_t463507806, ___m_Ptr_0)); }
inline intptr_t get_m_Ptr_0() const { return ___m_Ptr_0; }
inline intptr_t* get_address_of_m_Ptr_0() { return &___m_Ptr_0; }
inline void set_m_Ptr_0(intptr_t value)
{
___m_Ptr_0 = value;
}
inline static int32_t get_offset_of_m_DownloadHandler_1() { return static_cast<int32_t>(offsetof(UnityWebRequest_t463507806, ___m_DownloadHandler_1)); }
inline DownloadHandler_t2937767557 * get_m_DownloadHandler_1() const { return ___m_DownloadHandler_1; }
inline DownloadHandler_t2937767557 ** get_address_of_m_DownloadHandler_1() { return &___m_DownloadHandler_1; }
inline void set_m_DownloadHandler_1(DownloadHandler_t2937767557 * value)
{
___m_DownloadHandler_1 = value;
Il2CppCodeGenWriteBarrier((&___m_DownloadHandler_1), value);
}
inline static int32_t get_offset_of_m_UploadHandler_2() { return static_cast<int32_t>(offsetof(UnityWebRequest_t463507806, ___m_UploadHandler_2)); }
inline UploadHandler_t2993558019 * get_m_UploadHandler_2() const { return ___m_UploadHandler_2; }
inline UploadHandler_t2993558019 ** get_address_of_m_UploadHandler_2() { return &___m_UploadHandler_2; }
inline void set_m_UploadHandler_2(UploadHandler_t2993558019 * value)
{
___m_UploadHandler_2 = value;
Il2CppCodeGenWriteBarrier((&___m_UploadHandler_2), value);
}
inline static int32_t get_offset_of_m_CertificateHandler_3() { return static_cast<int32_t>(offsetof(UnityWebRequest_t463507806, ___m_CertificateHandler_3)); }
inline CertificateHandler_t2739891000 * get_m_CertificateHandler_3() const { return ___m_CertificateHandler_3; }
inline CertificateHandler_t2739891000 ** get_address_of_m_CertificateHandler_3() { return &___m_CertificateHandler_3; }
inline void set_m_CertificateHandler_3(CertificateHandler_t2739891000 * value)
{
___m_CertificateHandler_3 = value;
Il2CppCodeGenWriteBarrier((&___m_CertificateHandler_3), value);
}
inline static int32_t get_offset_of_m_Uri_4() { return static_cast<int32_t>(offsetof(UnityWebRequest_t463507806, ___m_Uri_4)); }
inline Uri_t100236324 * get_m_Uri_4() const { return ___m_Uri_4; }
inline Uri_t100236324 ** get_address_of_m_Uri_4() { return &___m_Uri_4; }
inline void set_m_Uri_4(Uri_t100236324 * value)
{
___m_Uri_4 = value;
Il2CppCodeGenWriteBarrier((&___m_Uri_4), value);
}
inline static int32_t get_offset_of_U3CdisposeCertificateHandlerOnDisposeU3Ek__BackingField_5() { return static_cast<int32_t>(offsetof(UnityWebRequest_t463507806, ___U3CdisposeCertificateHandlerOnDisposeU3Ek__BackingField_5)); }
inline bool get_U3CdisposeCertificateHandlerOnDisposeU3Ek__BackingField_5() const { return ___U3CdisposeCertificateHandlerOnDisposeU3Ek__BackingField_5; }
inline bool* get_address_of_U3CdisposeCertificateHandlerOnDisposeU3Ek__BackingField_5() { return &___U3CdisposeCertificateHandlerOnDisposeU3Ek__BackingField_5; }
inline void set_U3CdisposeCertificateHandlerOnDisposeU3Ek__BackingField_5(bool value)
{
___U3CdisposeCertificateHandlerOnDisposeU3Ek__BackingField_5 = value;
}
inline static int32_t get_offset_of_U3CdisposeDownloadHandlerOnDisposeU3Ek__BackingField_6() { return static_cast<int32_t>(offsetof(UnityWebRequest_t463507806, ___U3CdisposeDownloadHandlerOnDisposeU3Ek__BackingField_6)); }
inline bool get_U3CdisposeDownloadHandlerOnDisposeU3Ek__BackingField_6() const { return ___U3CdisposeDownloadHandlerOnDisposeU3Ek__BackingField_6; }
inline bool* get_address_of_U3CdisposeDownloadHandlerOnDisposeU3Ek__BackingField_6() { return &___U3CdisposeDownloadHandlerOnDisposeU3Ek__BackingField_6; }
inline void set_U3CdisposeDownloadHandlerOnDisposeU3Ek__BackingField_6(bool value)
{
___U3CdisposeDownloadHandlerOnDisposeU3Ek__BackingField_6 = value;
}
inline static int32_t get_offset_of_U3CdisposeUploadHandlerOnDisposeU3Ek__BackingField_7() { return static_cast<int32_t>(offsetof(UnityWebRequest_t463507806, ___U3CdisposeUploadHandlerOnDisposeU3Ek__BackingField_7)); }
inline bool get_U3CdisposeUploadHandlerOnDisposeU3Ek__BackingField_7() const { return ___U3CdisposeUploadHandlerOnDisposeU3Ek__BackingField_7; }
inline bool* get_address_of_U3CdisposeUploadHandlerOnDisposeU3Ek__BackingField_7() { return &___U3CdisposeUploadHandlerOnDisposeU3Ek__BackingField_7; }
inline void set_U3CdisposeUploadHandlerOnDisposeU3Ek__BackingField_7(bool value)
{
___U3CdisposeUploadHandlerOnDisposeU3Ek__BackingField_7 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of UnityEngine.Networking.UnityWebRequest
struct UnityWebRequest_t463507806_marshaled_pinvoke
{
intptr_t ___m_Ptr_0;
DownloadHandler_t2937767557_marshaled_pinvoke ___m_DownloadHandler_1;
UploadHandler_t2993558019_marshaled_pinvoke ___m_UploadHandler_2;
CertificateHandler_t2739891000_marshaled_pinvoke ___m_CertificateHandler_3;
Uri_t100236324 * ___m_Uri_4;
int32_t ___U3CdisposeCertificateHandlerOnDisposeU3Ek__BackingField_5;
int32_t ___U3CdisposeDownloadHandlerOnDisposeU3Ek__BackingField_6;
int32_t ___U3CdisposeUploadHandlerOnDisposeU3Ek__BackingField_7;
};
// Native definition for COM marshalling of UnityEngine.Networking.UnityWebRequest
struct UnityWebRequest_t463507806_marshaled_com
{
intptr_t ___m_Ptr_0;
DownloadHandler_t2937767557_marshaled_com* ___m_DownloadHandler_1;
UploadHandler_t2993558019_marshaled_com* ___m_UploadHandler_2;
CertificateHandler_t2739891000_marshaled_com* ___m_CertificateHandler_3;
Uri_t100236324 * ___m_Uri_4;
int32_t ___U3CdisposeCertificateHandlerOnDisposeU3Ek__BackingField_5;
int32_t ___U3CdisposeDownloadHandlerOnDisposeU3Ek__BackingField_6;
int32_t ___U3CdisposeUploadHandlerOnDisposeU3Ek__BackingField_7;
};
#endif // UNITYWEBREQUEST_T463507806_H
#ifndef UNITYWEBREQUESTASYNCOPERATION_T3852015985_H
#define UNITYWEBREQUESTASYNCOPERATION_T3852015985_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.Networking.UnityWebRequestAsyncOperation
struct UnityWebRequestAsyncOperation_t3852015985 : public AsyncOperation_t1445031843
{
public:
// UnityEngine.Networking.UnityWebRequest UnityEngine.Networking.UnityWebRequestAsyncOperation::<webRequest>k__BackingField
UnityWebRequest_t463507806 * ___U3CwebRequestU3Ek__BackingField_2;
public:
inline static int32_t get_offset_of_U3CwebRequestU3Ek__BackingField_2() { return static_cast<int32_t>(offsetof(UnityWebRequestAsyncOperation_t3852015985, ___U3CwebRequestU3Ek__BackingField_2)); }
inline UnityWebRequest_t463507806 * get_U3CwebRequestU3Ek__BackingField_2() const { return ___U3CwebRequestU3Ek__BackingField_2; }
inline UnityWebRequest_t463507806 ** get_address_of_U3CwebRequestU3Ek__BackingField_2() { return &___U3CwebRequestU3Ek__BackingField_2; }
inline void set_U3CwebRequestU3Ek__BackingField_2(UnityWebRequest_t463507806 * value)
{
___U3CwebRequestU3Ek__BackingField_2 = value;
Il2CppCodeGenWriteBarrier((&___U3CwebRequestU3Ek__BackingField_2), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of UnityEngine.Networking.UnityWebRequestAsyncOperation
struct UnityWebRequestAsyncOperation_t3852015985_marshaled_pinvoke : public AsyncOperation_t1445031843_marshaled_pinvoke
{
UnityWebRequest_t463507806_marshaled_pinvoke* ___U3CwebRequestU3Ek__BackingField_2;
};
// Native definition for COM marshalling of UnityEngine.Networking.UnityWebRequestAsyncOperation
struct UnityWebRequestAsyncOperation_t3852015985_marshaled_com : public AsyncOperation_t1445031843_marshaled_com
{
UnityWebRequest_t463507806_marshaled_com* ___U3CwebRequestU3Ek__BackingField_2;
};
#endif // UNITYWEBREQUESTASYNCOPERATION_T3852015985_H
// System.Byte[]
struct ByteU5BU5D_t4116647657 : public RuntimeArray
{
public:
ALIGN_FIELD (8) uint8_t m_Items[1];
public:
inline uint8_t GetAt(il2cpp_array_size_t index) const
{
IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length);
return m_Items[index];
}
inline uint8_t* GetAddressAt(il2cpp_array_size_t index)
{
IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length);
return m_Items + index;
}
inline void SetAt(il2cpp_array_size_t index, uint8_t value)
{
IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length);
m_Items[index] = value;
}
inline uint8_t GetAtUnchecked(il2cpp_array_size_t index) const
{
return m_Items[index];
}
inline uint8_t* GetAddressAtUnchecked(il2cpp_array_size_t index)
{
return m_Items + index;
}
inline void SetAtUnchecked(il2cpp_array_size_t index, uint8_t value)
{
m_Items[index] = value;
}
};
// System.Void UnityEngine.CustomYieldInstruction::.ctor()
extern "C" IL2CPP_METHOD_ATTR void CustomYieldInstruction__ctor_m3408208142 (CustomYieldInstruction_t1895667560 * __this, const RuntimeMethod* method);
// UnityEngine.Networking.UnityWebRequest UnityEngine.Networking.UnityWebRequest::Get(System.String)
extern "C" IL2CPP_METHOD_ATTR UnityWebRequest_t463507806 * UnityWebRequest_Get_m996521828 (RuntimeObject * __this /* static, unused */, String_t* p0, const RuntimeMethod* method);
// UnityEngine.Networking.UnityWebRequestAsyncOperation UnityEngine.Networking.UnityWebRequest::SendWebRequest()
extern "C" IL2CPP_METHOD_ATTR UnityWebRequestAsyncOperation_t3852015985 * UnityWebRequest_SendWebRequest_m489860187 (UnityWebRequest_t463507806 * __this, const RuntimeMethod* method);
// UnityEngine.Networking.UnityWebRequest UnityEngine.Networking.UnityWebRequest::Post(System.String,UnityEngine.WWWForm)
extern "C" IL2CPP_METHOD_ATTR UnityWebRequest_t463507806 * UnityWebRequest_Post_m4193475377 (RuntimeObject * __this /* static, unused */, String_t* p0, WWWForm_t4064702195 * p1, const RuntimeMethod* method);
// System.Void UnityEngine.Networking.UnityWebRequest::set_chunkedTransfer(System.Boolean)
extern "C" IL2CPP_METHOD_ATTR void UnityWebRequest_set_chunkedTransfer_m1735705240 (UnityWebRequest_t463507806 * __this, bool p0, const RuntimeMethod* method);
// System.Void UnityEngine.CachedAssetBundle::.ctor(System.String,UnityEngine.Hash128)
extern "C" IL2CPP_METHOD_ATTR void CachedAssetBundle__ctor_m1886503626 (CachedAssetBundle_t2205819908 * __this, String_t* p0, Hash128_t2357739769 p1, const RuntimeMethod* method);
// UnityEngine.Networking.UnityWebRequest UnityEngine.Networking.UnityWebRequestAssetBundle::GetAssetBundle(System.String,UnityEngine.CachedAssetBundle,System.UInt32)
extern "C" IL2CPP_METHOD_ATTR UnityWebRequest_t463507806 * UnityWebRequestAssetBundle_GetAssetBundle_m1528696577 (RuntimeObject * __this /* static, unused */, String_t* p0, CachedAssetBundle_t2205819908 p1, uint32_t p2, const RuntimeMethod* method);
// System.String UnityEngine.Networking.UnityWebRequest::EscapeURL(System.String,System.Text.Encoding)
extern "C" IL2CPP_METHOD_ATTR String_t* UnityWebRequest_EscapeURL_m1351912812 (RuntimeObject * __this /* static, unused */, String_t* p0, Encoding_t1523322056 * p1, const RuntimeMethod* method);
// UnityEngine.WWW UnityEngine.WWW::LoadFromCacheOrDownload(System.String,System.Int32,System.UInt32)
extern "C" IL2CPP_METHOD_ATTR WWW_t3688466362 * WWW_LoadFromCacheOrDownload_m3958223827 (RuntimeObject * __this /* static, unused */, String_t* ___url0, int32_t ___version1, uint32_t ___crc2, const RuntimeMethod* method);
// System.Void UnityEngine.Hash128::.ctor(System.UInt32,System.UInt32,System.UInt32,System.UInt32)
extern "C" IL2CPP_METHOD_ATTR void Hash128__ctor_m2348731757 (Hash128_t2357739769 * __this, uint32_t p0, uint32_t p1, uint32_t p2, uint32_t p3, const RuntimeMethod* method);
// UnityEngine.WWW UnityEngine.WWW::LoadFromCacheOrDownload(System.String,UnityEngine.Hash128,System.UInt32)
extern "C" IL2CPP_METHOD_ATTR WWW_t3688466362 * WWW_LoadFromCacheOrDownload_m4247140216 (RuntimeObject * __this /* static, unused */, String_t* ___url0, Hash128_t2357739769 ___hash1, uint32_t ___crc2, const RuntimeMethod* method);
// System.Void UnityEngine.WWW::.ctor(System.String,System.String,UnityEngine.Hash128,System.UInt32)
extern "C" IL2CPP_METHOD_ATTR void WWW__ctor_m3488013117 (WWW_t3688466362 * __this, String_t* ___url0, String_t* ___name1, Hash128_t2357739769 ___hash2, uint32_t ___crc3, const RuntimeMethod* method);
// System.Boolean UnityEngine.Object::op_Equality(UnityEngine.Object,UnityEngine.Object)
extern "C" IL2CPP_METHOD_ATTR bool Object_op_Equality_m1810815630 (RuntimeObject * __this /* static, unused */, Object_t631007953 * p0, Object_t631007953 * p1, const RuntimeMethod* method);
// System.Boolean UnityEngine.WWW::WaitUntilDoneIfPossible()
extern "C" IL2CPP_METHOD_ATTR bool WWW_WaitUntilDoneIfPossible_m2855479680 (WWW_t3688466362 * __this, const RuntimeMethod* method);
// System.Boolean UnityEngine.Networking.UnityWebRequest::get_isNetworkError()
extern "C" IL2CPP_METHOD_ATTR bool UnityWebRequest_get_isNetworkError_m1231611882 (UnityWebRequest_t463507806 * __this, const RuntimeMethod* method);
// UnityEngine.Networking.DownloadHandler UnityEngine.Networking.UnityWebRequest::get_downloadHandler()
extern "C" IL2CPP_METHOD_ATTR DownloadHandler_t2937767557 * UnityWebRequest_get_downloadHandler_m534911913 (UnityWebRequest_t463507806 * __this, const RuntimeMethod* method);
// UnityEngine.AssetBundle UnityEngine.Networking.DownloadHandlerAssetBundle::get_assetBundle()
extern "C" IL2CPP_METHOD_ATTR AssetBundle_t1153907252 * DownloadHandlerAssetBundle_get_assetBundle_m3640693480 (DownloadHandlerAssetBundle_t197128434 * __this, const RuntimeMethod* method);
// System.Byte[] UnityEngine.WWW::get_bytes()
extern "C" IL2CPP_METHOD_ATTR ByteU5BU5D_t4116647657* WWW_get_bytes_m3061182897 (WWW_t3688466362 * __this, const RuntimeMethod* method);
// UnityEngine.AssetBundle UnityEngine.AssetBundle::LoadFromMemory(System.Byte[])
extern "C" IL2CPP_METHOD_ATTR AssetBundle_t1153907252 * AssetBundle_LoadFromMemory_m336091660 (RuntimeObject * __this /* static, unused */, ByteU5BU5D_t4116647657* p0, const RuntimeMethod* method);
// System.Byte[] UnityEngine.Networking.DownloadHandler::get_data()
extern "C" IL2CPP_METHOD_ATTR ByteU5BU5D_t4116647657* DownloadHandler_get_data_m1669096410 (DownloadHandler_t2937767557 * __this, const RuntimeMethod* method);
// System.Boolean UnityEngine.Networking.UnityWebRequest::get_isDone()
extern "C" IL2CPP_METHOD_ATTR bool UnityWebRequest_get_isDone_m1752128881 (UnityWebRequest_t463507806 * __this, const RuntimeMethod* method);
// System.String UnityEngine.Networking.UnityWebRequest::get_error()
extern "C" IL2CPP_METHOD_ATTR String_t* UnityWebRequest_get_error_m1613086199 (UnityWebRequest_t463507806 * __this, const RuntimeMethod* method);
// System.Int64 UnityEngine.Networking.UnityWebRequest::get_responseCode()
extern "C" IL2CPP_METHOD_ATTR int64_t UnityWebRequest_get_responseCode_m1090830473 (UnityWebRequest_t463507806 * __this, const RuntimeMethod* method);
// System.String UnityEngine.WWW::GetStatusCodeName(System.Int64)
extern "C" IL2CPP_METHOD_ATTR String_t* WWW_GetStatusCodeName_m3580893459 (WWW_t3688466362 * __this, int64_t ___statusCode0, const RuntimeMethod* method);
// System.String System.String::Format(System.String,System.Object,System.Object)
extern "C" IL2CPP_METHOD_ATTR String_t* String_Format_m2556382932 (RuntimeObject * __this /* static, unused */, String_t* p0, RuntimeObject * p1, RuntimeObject * p2, const RuntimeMethod* method);
// System.String UnityEngine.Networking.DownloadHandler::get_text()
extern "C" IL2CPP_METHOD_ATTR String_t* DownloadHandler_get_text_m2427232382 (DownloadHandler_t2937767557 * __this, const RuntimeMethod* method);
// System.String UnityEngine.Networking.UnityWebRequest::get_url()
extern "C" IL2CPP_METHOD_ATTR String_t* UnityWebRequest_get_url_m2568598920 (UnityWebRequest_t463507806 * __this, const RuntimeMethod* method);
// System.Void UnityEngine.Networking.UnityWebRequest::Dispose()
extern "C" IL2CPP_METHOD_ATTR void UnityWebRequest_Dispose_m3261105905 (UnityWebRequest_t463507806 * __this, const RuntimeMethod* method);
// System.String UnityEngine.WWW::get_url()
extern "C" IL2CPP_METHOD_ATTR String_t* WWW_get_url_m3672399347 (WWW_t3688466362 * __this, const RuntimeMethod* method);
// System.Boolean System.String::StartsWith(System.String,System.StringComparison)
extern "C" IL2CPP_METHOD_ATTR bool String_StartsWith_m2640722675 (String_t* __this, String_t* p0, int32_t p1, const RuntimeMethod* method);
// System.Void UnityEngine.Debug::LogError(System.Object)
extern "C" IL2CPP_METHOD_ATTR void Debug_LogError_m2850623458 (RuntimeObject * __this /* static, unused */, RuntimeObject * p0, const RuntimeMethod* method);
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Void UnityEngine.WWW::.ctor(System.String)
extern "C" IL2CPP_METHOD_ATTR void WWW__ctor_m2915079343 (WWW_t3688466362 * __this, String_t* ___url0, const RuntimeMethod* method)
{
{
CustomYieldInstruction__ctor_m3408208142(__this, /*hidden argument*/NULL);
String_t* L_0 = ___url0;
UnityWebRequest_t463507806 * L_1 = UnityWebRequest_Get_m996521828(NULL /*static, unused*/, L_0, /*hidden argument*/NULL);
__this->set__uwr_0(L_1);
UnityWebRequest_t463507806 * L_2 = __this->get__uwr_0();
NullCheck(L_2);
UnityWebRequest_SendWebRequest_m489860187(L_2, /*hidden argument*/NULL);
return;
}
}
// System.Void UnityEngine.WWW::.ctor(System.String,UnityEngine.WWWForm)
extern "C" IL2CPP_METHOD_ATTR void WWW__ctor_m1562165 (WWW_t3688466362 * __this, String_t* ___url0, WWWForm_t4064702195 * ___form1, const RuntimeMethod* method)
{
{
CustomYieldInstruction__ctor_m3408208142(__this, /*hidden argument*/NULL);
String_t* L_0 = ___url0;
WWWForm_t4064702195 * L_1 = ___form1;
UnityWebRequest_t463507806 * L_2 = UnityWebRequest_Post_m4193475377(NULL /*static, unused*/, L_0, L_1, /*hidden argument*/NULL);
__this->set__uwr_0(L_2);
UnityWebRequest_t463507806 * L_3 = __this->get__uwr_0();
NullCheck(L_3);
UnityWebRequest_set_chunkedTransfer_m1735705240(L_3, (bool)0, /*hidden argument*/NULL);
UnityWebRequest_t463507806 * L_4 = __this->get__uwr_0();
NullCheck(L_4);
UnityWebRequest_SendWebRequest_m489860187(L_4, /*hidden argument*/NULL);
return;
}
}
// System.Void UnityEngine.WWW::.ctor(System.String,System.String,UnityEngine.Hash128,System.UInt32)
extern "C" IL2CPP_METHOD_ATTR void WWW__ctor_m3488013117 (WWW_t3688466362 * __this, String_t* ___url0, String_t* ___name1, Hash128_t2357739769 ___hash2, uint32_t ___crc3, const RuntimeMethod* method)
{
{
CustomYieldInstruction__ctor_m3408208142(__this, /*hidden argument*/NULL);
String_t* L_0 = ___url0;
String_t* L_1 = ___name1;
Hash128_t2357739769 L_2 = ___hash2;
CachedAssetBundle_t2205819908 L_3;
memset(&L_3, 0, sizeof(L_3));
CachedAssetBundle__ctor_m1886503626((&L_3), L_1, L_2, /*hidden argument*/NULL);
uint32_t L_4 = ___crc3;
UnityWebRequest_t463507806 * L_5 = UnityWebRequestAssetBundle_GetAssetBundle_m1528696577(NULL /*static, unused*/, L_0, L_3, L_4, /*hidden argument*/NULL);
__this->set__uwr_0(L_5);
UnityWebRequest_t463507806 * L_6 = __this->get__uwr_0();
NullCheck(L_6);
UnityWebRequest_SendWebRequest_m489860187(L_6, /*hidden argument*/NULL);
return;
}
}
// System.String UnityEngine.WWW::EscapeURL(System.String,System.Text.Encoding)
extern "C" IL2CPP_METHOD_ATTR String_t* WWW_EscapeURL_m2044390713 (RuntimeObject * __this /* static, unused */, String_t* ___s0, Encoding_t1523322056 * ___e1, const RuntimeMethod* method)
{
String_t* V_0 = NULL;
{
String_t* L_0 = ___s0;
Encoding_t1523322056 * L_1 = ___e1;
String_t* L_2 = UnityWebRequest_EscapeURL_m1351912812(NULL /*static, unused*/, L_0, L_1, /*hidden argument*/NULL);
V_0 = L_2;
goto IL_000e;
}
IL_000e:
{
String_t* L_3 = V_0;
return L_3;
}
}
// UnityEngine.WWW UnityEngine.WWW::LoadFromCacheOrDownload(System.String,System.Int32)
extern "C" IL2CPP_METHOD_ATTR WWW_t3688466362 * WWW_LoadFromCacheOrDownload_m1915063972 (RuntimeObject * __this /* static, unused */, String_t* ___url0, int32_t ___version1, const RuntimeMethod* method)
{
WWW_t3688466362 * V_0 = NULL;
{
String_t* L_0 = ___url0;
int32_t L_1 = ___version1;
WWW_t3688466362 * L_2 = WWW_LoadFromCacheOrDownload_m3958223827(NULL /*static, unused*/, L_0, L_1, 0, /*hidden argument*/NULL);
V_0 = L_2;
goto IL_000f;
}
IL_000f:
{
WWW_t3688466362 * L_3 = V_0;
return L_3;
}
}
// UnityEngine.WWW UnityEngine.WWW::LoadFromCacheOrDownload(System.String,System.Int32,System.UInt32)
extern "C" IL2CPP_METHOD_ATTR WWW_t3688466362 * WWW_LoadFromCacheOrDownload_m3958223827 (RuntimeObject * __this /* static, unused */, String_t* ___url0, int32_t ___version1, uint32_t ___crc2, const RuntimeMethod* method)
{
Hash128_t2357739769 V_0;
memset(&V_0, 0, sizeof(V_0));
WWW_t3688466362 * V_1 = NULL;
{
int32_t L_0 = ___version1;
Hash128__ctor_m2348731757((Hash128_t2357739769 *)(&V_0), 0, 0, 0, L_0, /*hidden argument*/NULL);
String_t* L_1 = ___url0;
Hash128_t2357739769 L_2 = V_0;
uint32_t L_3 = ___crc2;
WWW_t3688466362 * L_4 = WWW_LoadFromCacheOrDownload_m4247140216(NULL /*static, unused*/, L_1, L_2, L_3, /*hidden argument*/NULL);
V_1 = L_4;
goto IL_001a;
}
IL_001a:
{
WWW_t3688466362 * L_5 = V_1;
return L_5;
}
}
// UnityEngine.WWW UnityEngine.WWW::LoadFromCacheOrDownload(System.String,UnityEngine.Hash128,System.UInt32)
extern "C" IL2CPP_METHOD_ATTR WWW_t3688466362 * WWW_LoadFromCacheOrDownload_m4247140216 (RuntimeObject * __this /* static, unused */, String_t* ___url0, Hash128_t2357739769 ___hash1, uint32_t ___crc2, const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_method (WWW_LoadFromCacheOrDownload_m4247140216_MetadataUsageId);
s_Il2CppMethodInitialized = true;
}
WWW_t3688466362 * V_0 = NULL;
{
String_t* L_0 = ___url0;
Hash128_t2357739769 L_1 = ___hash1;
uint32_t L_2 = ___crc2;
WWW_t3688466362 * L_3 = (WWW_t3688466362 *)il2cpp_codegen_object_new(WWW_t3688466362_il2cpp_TypeInfo_var);
WWW__ctor_m3488013117(L_3, L_0, _stringLiteral757602046, L_1, L_2, /*hidden argument*/NULL);
V_0 = L_3;
goto IL_0014;
}
IL_0014:
{
WWW_t3688466362 * L_4 = V_0;
return L_4;
}
}
// UnityEngine.AssetBundle UnityEngine.WWW::get_assetBundle()
extern "C" IL2CPP_METHOD_ATTR AssetBundle_t1153907252 * WWW_get_assetBundle_m3753667806 (WWW_t3688466362 * __this, const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_method (WWW_get_assetBundle_m3753667806_MetadataUsageId);
s_Il2CppMethodInitialized = true;
}
AssetBundle_t1153907252 * V_0 = NULL;
DownloadHandlerAssetBundle_t197128434 * V_1 = NULL;
ByteU5BU5D_t4116647657* V_2 = NULL;
{
AssetBundle_t1153907252 * L_0 = __this->get__assetBundle_1();
IL2CPP_RUNTIME_CLASS_INIT(Object_t631007953_il2cpp_TypeInfo_var);
bool L_1 = Object_op_Equality_m1810815630(NULL /*static, unused*/, L_0, (Object_t631007953 *)NULL, /*hidden argument*/NULL);
if (!L_1)
{
goto IL_0087;
}
}
{
bool L_2 = WWW_WaitUntilDoneIfPossible_m2855479680(__this, /*hidden argument*/NULL);
if (L_2)
{
goto IL_0025;
}
}
{
V_0 = (AssetBundle_t1153907252 *)NULL;
goto IL_0093;
}
IL_0025:
{
UnityWebRequest_t463507806 * L_3 = __this->get__uwr_0();
NullCheck(L_3);
bool L_4 = UnityWebRequest_get_isNetworkError_m1231611882(L_3, /*hidden argument*/NULL);
if (!L_4)
{
goto IL_003c;
}
}
{
V_0 = (AssetBundle_t1153907252 *)NULL;
goto IL_0093;
}
IL_003c:
{
UnityWebRequest_t463507806 * L_5 = __this->get__uwr_0();
NullCheck(L_5);
DownloadHandler_t2937767557 * L_6 = UnityWebRequest_get_downloadHandler_m534911913(L_5, /*hidden argument*/NULL);
V_1 = ((DownloadHandlerAssetBundle_t197128434 *)IsInstSealed((RuntimeObject*)L_6, DownloadHandlerAssetBundle_t197128434_il2cpp_TypeInfo_var));
DownloadHandlerAssetBundle_t197128434 * L_7 = V_1;
if (!L_7)
{
goto IL_0064;
}
}
{
DownloadHandlerAssetBundle_t197128434 * L_8 = V_1;
NullCheck(L_8);
AssetBundle_t1153907252 * L_9 = DownloadHandlerAssetBundle_get_assetBundle_m3640693480(L_8, /*hidden argument*/NULL);
__this->set__assetBundle_1(L_9);
goto IL_0086;
}
IL_0064:
{
ByteU5BU5D_t4116647657* L_10 = WWW_get_bytes_m3061182897(__this, /*hidden argument*/NULL);
V_2 = L_10;
ByteU5BU5D_t4116647657* L_11 = V_2;
if (L_11)
{
goto IL_0079;
}
}
{
V_0 = (AssetBundle_t1153907252 *)NULL;
goto IL_0093;
}
IL_0079:
{
ByteU5BU5D_t4116647657* L_12 = V_2;
AssetBundle_t1153907252 * L_13 = AssetBundle_LoadFromMemory_m336091660(NULL /*static, unused*/, L_12, /*hidden argument*/NULL);
__this->set__assetBundle_1(L_13);
}
IL_0086:
{
}
IL_0087:
{
AssetBundle_t1153907252 * L_14 = __this->get__assetBundle_1();
V_0 = L_14;
goto IL_0093;
}
IL_0093:
{
AssetBundle_t1153907252 * L_15 = V_0;
return L_15;
}
}
// System.Byte[] UnityEngine.WWW::get_bytes()
extern "C" IL2CPP_METHOD_ATTR ByteU5BU5D_t4116647657* WWW_get_bytes_m3061182897 (WWW_t3688466362 * __this, const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_method (WWW_get_bytes_m3061182897_MetadataUsageId);
s_Il2CppMethodInitialized = true;
}
ByteU5BU5D_t4116647657* V_0 = NULL;
DownloadHandler_t2937767557 * V_1 = NULL;
{
bool L_0 = WWW_WaitUntilDoneIfPossible_m2855479680(__this, /*hidden argument*/NULL);
if (L_0)
{
goto IL_0018;
}
}
{
ByteU5BU5D_t4116647657* L_1 = (ByteU5BU5D_t4116647657*)SZArrayNew(ByteU5BU5D_t4116647657_il2cpp_TypeInfo_var, (uint32_t)0);
V_0 = L_1;
goto IL_005e;
}
IL_0018:
{
UnityWebRequest_t463507806 * L_2 = __this->get__uwr_0();
NullCheck(L_2);
bool L_3 = UnityWebRequest_get_isNetworkError_m1231611882(L_2, /*hidden argument*/NULL);
if (!L_3)
{
goto IL_0034;
}
}
{
ByteU5BU5D_t4116647657* L_4 = (ByteU5BU5D_t4116647657*)SZArrayNew(ByteU5BU5D_t4116647657_il2cpp_TypeInfo_var, (uint32_t)0);
V_0 = L_4;
goto IL_005e;
}
IL_0034:
{
UnityWebRequest_t463507806 * L_5 = __this->get__uwr_0();
NullCheck(L_5);
DownloadHandler_t2937767557 * L_6 = UnityWebRequest_get_downloadHandler_m534911913(L_5, /*hidden argument*/NULL);
V_1 = L_6;
DownloadHandler_t2937767557 * L_7 = V_1;
if (L_7)
{
goto IL_0052;
}
}
{
ByteU5BU5D_t4116647657* L_8 = (ByteU5BU5D_t4116647657*)SZArrayNew(ByteU5BU5D_t4116647657_il2cpp_TypeInfo_var, (uint32_t)0);
V_0 = L_8;
goto IL_005e;
}
IL_0052:
{
DownloadHandler_t2937767557 * L_9 = V_1;
NullCheck(L_9);
ByteU5BU5D_t4116647657* L_10 = DownloadHandler_get_data_m1669096410(L_9, /*hidden argument*/NULL);
V_0 = L_10;
goto IL_005e;
}
IL_005e:
{
ByteU5BU5D_t4116647657* L_11 = V_0;
return L_11;
}
}
// System.String UnityEngine.WWW::get_error()
extern "C" IL2CPP_METHOD_ATTR String_t* WWW_get_error_m3055313367 (WWW_t3688466362 * __this, const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_method (WWW_get_error_m3055313367_MetadataUsageId);
s_Il2CppMethodInitialized = true;
}
String_t* V_0 = NULL;
{
UnityWebRequest_t463507806 * L_0 = __this->get__uwr_0();
NullCheck(L_0);
bool L_1 = UnityWebRequest_get_isDone_m1752128881(L_0, /*hidden argument*/NULL);
if (L_1)
{
goto IL_0018;
}
}
{
V_0 = (String_t*)NULL;
goto IL_0087;
}
IL_0018:
{
UnityWebRequest_t463507806 * L_2 = __this->get__uwr_0();
NullCheck(L_2);
bool L_3 = UnityWebRequest_get_isNetworkError_m1231611882(L_2, /*hidden argument*/NULL);
if (!L_3)
{
goto IL_0039;
}
}
{
UnityWebRequest_t463507806 * L_4 = __this->get__uwr_0();
NullCheck(L_4);
String_t* L_5 = UnityWebRequest_get_error_m1613086199(L_4, /*hidden argument*/NULL);
V_0 = L_5;
goto IL_0087;
}
IL_0039:
{
UnityWebRequest_t463507806 * L_6 = __this->get__uwr_0();
NullCheck(L_6);
int64_t L_7 = UnityWebRequest_get_responseCode_m1090830473(L_6, /*hidden argument*/NULL);
if ((((int64_t)L_7) < ((int64_t)(((int64_t)((int64_t)((int32_t)400)))))))
{
goto IL_0080;
}
}
{
UnityWebRequest_t463507806 * L_8 = __this->get__uwr_0();
NullCheck(L_8);
int64_t L_9 = UnityWebRequest_get_responseCode_m1090830473(L_8, /*hidden argument*/NULL);
int64_t L_10 = L_9;
RuntimeObject * L_11 = Box(Int64_t3736567304_il2cpp_TypeInfo_var, &L_10);
UnityWebRequest_t463507806 * L_12 = __this->get__uwr_0();
NullCheck(L_12);
int64_t L_13 = UnityWebRequest_get_responseCode_m1090830473(L_12, /*hidden argument*/NULL);
String_t* L_14 = WWW_GetStatusCodeName_m3580893459(__this, L_13, /*hidden argument*/NULL);
IL2CPP_RUNTIME_CLASS_INIT(String_t_il2cpp_TypeInfo_var);
String_t* L_15 = String_Format_m2556382932(NULL /*static, unused*/, _stringLiteral380657706, L_11, L_14, /*hidden argument*/NULL);
V_0 = L_15;
goto IL_0087;
}
IL_0080:
{
V_0 = (String_t*)NULL;
goto IL_0087;
}
IL_0087:
{
String_t* L_16 = V_0;
return L_16;
}
}
// System.Boolean UnityEngine.WWW::get_isDone()
extern "C" IL2CPP_METHOD_ATTR bool WWW_get_isDone_m3426350689 (WWW_t3688466362 * __this, const RuntimeMethod* method)
{
bool V_0 = false;
{
UnityWebRequest_t463507806 * L_0 = __this->get__uwr_0();
NullCheck(L_0);
bool L_1 = UnityWebRequest_get_isDone_m1752128881(L_0, /*hidden argument*/NULL);
V_0 = L_1;
goto IL_0012;
}
IL_0012:
{
bool L_2 = V_0;
return L_2;
}
}
// System.String UnityEngine.WWW::get_text()
extern "C" IL2CPP_METHOD_ATTR String_t* WWW_get_text_m898164367 (WWW_t3688466362 * __this, const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_method (WWW_get_text_m898164367_MetadataUsageId);
s_Il2CppMethodInitialized = true;
}
String_t* V_0 = NULL;
DownloadHandler_t2937767557 * V_1 = NULL;
{
bool L_0 = WWW_WaitUntilDoneIfPossible_m2855479680(__this, /*hidden argument*/NULL);
if (L_0)
{
goto IL_0017;
}
}
{
V_0 = _stringLiteral757602046;
goto IL_005b;
}
IL_0017:
{
UnityWebRequest_t463507806 * L_1 = __this->get__uwr_0();
NullCheck(L_1);
bool L_2 = UnityWebRequest_get_isNetworkError_m1231611882(L_1, /*hidden argument*/NULL);
if (!L_2)
{
goto IL_0032;
}
}
{
V_0 = _stringLiteral757602046;
goto IL_005b;
}
IL_0032:
{
UnityWebRequest_t463507806 * L_3 = __this->get__uwr_0();
NullCheck(L_3);
DownloadHandler_t2937767557 * L_4 = UnityWebRequest_get_downloadHandler_m534911913(L_3, /*hidden argument*/NULL);
V_1 = L_4;
DownloadHandler_t2937767557 * L_5 = V_1;
if (L_5)
{
goto IL_004f;
}
}
{
V_0 = _stringLiteral757602046;
goto IL_005b;
}
IL_004f:
{
DownloadHandler_t2937767557 * L_6 = V_1;
NullCheck(L_6);
String_t* L_7 = DownloadHandler_get_text_m2427232382(L_6, /*hidden argument*/NULL);
V_0 = L_7;
goto IL_005b;
}
IL_005b:
{
String_t* L_8 = V_0;
return L_8;
}
}
// System.String UnityEngine.WWW::get_url()
extern "C" IL2CPP_METHOD_ATTR String_t* WWW_get_url_m3672399347 (WWW_t3688466362 * __this, const RuntimeMethod* method)
{
String_t* V_0 = NULL;
{
UnityWebRequest_t463507806 * L_0 = __this->get__uwr_0();
NullCheck(L_0);
String_t* L_1 = UnityWebRequest_get_url_m2568598920(L_0, /*hidden argument*/NULL);
V_0 = L_1;
goto IL_0012;
}
IL_0012:
{
String_t* L_2 = V_0;
return L_2;
}
}
// System.Boolean UnityEngine.WWW::get_keepWaiting()
extern "C" IL2CPP_METHOD_ATTR bool WWW_get_keepWaiting_m1438015190 (WWW_t3688466362 * __this, const RuntimeMethod* method)
{
bool V_0 = false;
{
UnityWebRequest_t463507806 * L_0 = __this->get__uwr_0();
NullCheck(L_0);
bool L_1 = UnityWebRequest_get_isDone_m1752128881(L_0, /*hidden argument*/NULL);
V_0 = (bool)((((int32_t)L_1) == ((int32_t)0))? 1 : 0);
goto IL_0015;
}
IL_0015:
{
bool L_2 = V_0;
return L_2;
}
}
// System.Void UnityEngine.WWW::Dispose()
extern "C" IL2CPP_METHOD_ATTR void WWW_Dispose_m2256148703 (WWW_t3688466362 * __this, const RuntimeMethod* method)
{
{
UnityWebRequest_t463507806 * L_0 = __this->get__uwr_0();
NullCheck(L_0);
UnityWebRequest_Dispose_m3261105905(L_0, /*hidden argument*/NULL);
return;
}
}
// System.Boolean UnityEngine.WWW::WaitUntilDoneIfPossible()
extern "C" IL2CPP_METHOD_ATTR bool WWW_WaitUntilDoneIfPossible_m2855479680 (WWW_t3688466362 * __this, const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_method (WWW_WaitUntilDoneIfPossible_m2855479680_MetadataUsageId);
s_Il2CppMethodInitialized = true;
}
bool V_0 = false;
{
UnityWebRequest_t463507806 * L_0 = __this->get__uwr_0();
NullCheck(L_0);
bool L_1 = UnityWebRequest_get_isDone_m1752128881(L_0, /*hidden argument*/NULL);
if (!L_1)
{
goto IL_0018;
}
}
{
V_0 = (bool)1;
goto IL_005f;
}
IL_0018:
{
String_t* L_2 = WWW_get_url_m3672399347(__this, /*hidden argument*/NULL);
NullCheck(L_2);
bool L_3 = String_StartsWith_m2640722675(L_2, _stringLiteral4054833267, 5, /*hidden argument*/NULL);
if (!L_3)
{
goto IL_004d;
}
}
{
goto IL_0036;
}
IL_0034:
{
}
IL_0036:
{
UnityWebRequest_t463507806 * L_4 = __this->get__uwr_0();
NullCheck(L_4);
bool L_5 = UnityWebRequest_get_isDone_m1752128881(L_4, /*hidden argument*/NULL);
if (!L_5)
{
goto IL_0034;
}
}
{
V_0 = (bool)1;
goto IL_005f;
}
IL_004d:
{
IL2CPP_RUNTIME_CLASS_INIT(Debug_t3317548046_il2cpp_TypeInfo_var);
Debug_LogError_m2850623458(NULL /*static, unused*/, _stringLiteral1973828197, /*hidden argument*/NULL);
V_0 = (bool)0;
goto IL_005f;
}
IL_005f:
{
bool L_6 = V_0;
return L_6;
}
}
// System.String UnityEngine.WWW::GetStatusCodeName(System.Int64)
extern "C" IL2CPP_METHOD_ATTR String_t* WWW_GetStatusCodeName_m3580893459 (WWW_t3688466362 * __this, int64_t ___statusCode0, const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_method (WWW_GetStatusCodeName_m3580893459_MetadataUsageId);
s_Il2CppMethodInitialized = true;
}
String_t* V_0 = NULL;
{
int64_t L_0 = ___statusCode0;
if ((((int64_t)L_0) < ((int64_t)(((int64_t)((int64_t)((int32_t)400)))))))
{
goto IL_006b;
}
}
{
int64_t L_1 = ___statusCode0;
if ((((int64_t)L_1) > ((int64_t)(((int64_t)((int64_t)((int32_t)416)))))))
{
goto IL_006b;
}
}
{
int64_t L_2 = ___statusCode0;
switch ((((int32_t)((int32_t)((int64_t)il2cpp_codegen_subtract((int64_t)L_2, (int64_t)(((int64_t)((int64_t)((int32_t)400))))))))))
{
case 0:
{
goto IL_01d9;
}
case 1:
{
goto IL_01e4;
}
case 2:
{
goto IL_01ef;
}
case 3:
{
goto IL_01fa;
}
case 4:
{
goto IL_0205;
}
case 5:
{
goto IL_0210;
}
case 6:
{
goto IL_021b;
}
case 7:
{
goto IL_0226;
}
case 8:
{
goto IL_0231;
}
case 9:
{
goto IL_023c;
}
case 10:
{
goto IL_0247;
}
case 11:
{
goto IL_0252;
}
case 12:
{
goto IL_025d;
}
case 13:
{
goto IL_0268;
}
case 14:
{
goto IL_0273;
}
case 15:
{
goto IL_027e;
}
case 16:
{
goto IL_0289;
}
}
}
IL_006b:
{
int64_t L_3 = ___statusCode0;
if ((((int64_t)L_3) < ((int64_t)(((int64_t)((int64_t)((int32_t)200)))))))
{
goto IL_00ad;
}
}
{
int64_t L_4 = ___statusCode0;
if ((((int64_t)L_4) > ((int64_t)(((int64_t)((int64_t)((int32_t)206)))))))
{
goto IL_00ad;
}
}
{
int64_t L_5 = ___statusCode0;
switch ((((int32_t)((int32_t)((int64_t)il2cpp_codegen_subtract((int64_t)L_5, (int64_t)(((int64_t)((int64_t)((int32_t)200))))))))))
{
case 0:
{
goto IL_013f;
}
case 1:
{
goto IL_014a;
}
case 2:
{
goto IL_0155;
}
case 3:
{
goto IL_0160;
}
case 4:
{
goto IL_016b;
}
case 5:
{
goto IL_0176;
}
case 6:
{
goto IL_0181;
}
}
}
IL_00ad:
{
int64_t L_6 = ___statusCode0;
if ((((int64_t)L_6) < ((int64_t)(((int64_t)((int64_t)((int32_t)300)))))))
{
goto IL_00f3;
}
}
{
int64_t L_7 = ___statusCode0;
if ((((int64_t)L_7) > ((int64_t)(((int64_t)((int64_t)((int32_t)307)))))))
{
goto IL_00f3;
}
}
{
int64_t L_8 = ___statusCode0;
switch ((((int32_t)((int32_t)((int64_t)il2cpp_codegen_subtract((int64_t)L_8, (int64_t)(((int64_t)((int64_t)((int32_t)300))))))))))
{
case 0:
{
goto IL_018c;
}
case 1:
{
goto IL_0197;
}
case 2:
{
goto IL_01a2;
}
case 3:
{
goto IL_01ad;
}
case 4:
{
goto IL_01b8;
}
case 5:
{
goto IL_01c3;
}
case 6:
{
goto IL_00f3;
}
case 7:
{
goto IL_01ce;
}
}
}
IL_00f3:
{
int64_t L_9 = ___statusCode0;
if ((((int64_t)L_9) < ((int64_t)(((int64_t)((int64_t)((int32_t)500)))))))
{
goto IL_0131;
}
}
{
int64_t L_10 = ___statusCode0;
if ((((int64_t)L_10) > ((int64_t)(((int64_t)((int64_t)((int32_t)505)))))))
{
goto IL_0131;
}
}
{
int64_t L_11 = ___statusCode0;
switch ((((int32_t)((int32_t)((int64_t)il2cpp_codegen_subtract((int64_t)L_11, (int64_t)(((int64_t)((int64_t)((int32_t)500))))))))))
{
case 0:
{
goto IL_029f;
}
case 1:
{
goto IL_02aa;
}
case 2:
{
goto IL_02b5;
}
case 3:
{
goto IL_02c0;
}
case 4:
{
goto IL_02cb;
}
case 5:
{
goto IL_02d6;
}
}
}
IL_0131:
{
int64_t L_12 = ___statusCode0;
if ((((int64_t)L_12) == ((int64_t)(((int64_t)((int64_t)((int32_t)41)))))))
{
goto IL_0294;
}
}
{
goto IL_02e1;
}
IL_013f:
{
V_0 = _stringLiteral3457136609;
goto IL_02ec;
}
IL_014a:
{
V_0 = _stringLiteral3911804090;
goto IL_02ec;
}
IL_0155:
{
V_0 = _stringLiteral2487325543;
goto IL_02ec;
}
IL_0160:
{
V_0 = _stringLiteral3860885797;
goto IL_02ec;
}
IL_016b:
{
V_0 = _stringLiteral3476706848;
goto IL_02ec;
}
IL_0176:
{
V_0 = _stringLiteral560819067;
goto IL_02ec;
}
IL_0181:
{
V_0 = _stringLiteral2030167956;
goto IL_02ec;
}
IL_018c:
{
V_0 = _stringLiteral1814237603;
goto IL_02ec;
}
IL_0197:
{
V_0 = _stringLiteral4140321389;
goto IL_02ec;
}
IL_01a2:
{
V_0 = _stringLiteral2002596717;
goto IL_02ec;
}
IL_01ad:
{
V_0 = _stringLiteral1659593328;
goto IL_02ec;
}
IL_01b8:
{
V_0 = _stringLiteral4277434149;
goto IL_02ec;
}
IL_01c3:
{
V_0 = _stringLiteral3090824594;
goto IL_02ec;
}
IL_01ce:
{
V_0 = _stringLiteral3842069051;
goto IL_02ec;
}
IL_01d9:
{
V_0 = _stringLiteral4233297459;
goto IL_02ec;
}
IL_01e4:
{
V_0 = _stringLiteral3545044340;
goto IL_02ec;
}
IL_01ef:
{
V_0 = _stringLiteral573727993;
goto IL_02ec;
}
IL_01fa:
{
V_0 = _stringLiteral2117271536;
goto IL_02ec;
}
IL_0205:
{
V_0 = _stringLiteral2178748878;
goto IL_02ec;
}
IL_0210:
{
V_0 = _stringLiteral106317971;
goto IL_02ec;
}
IL_021b:
{
V_0 = _stringLiteral461727106;
goto IL_02ec;
}
IL_0226:
{
V_0 = _stringLiteral1542497020;
goto IL_02ec;
}
IL_0231:
{
V_0 = _stringLiteral2343474426;
goto IL_02ec;
}
IL_023c:
{
V_0 = _stringLiteral1138636386;
goto IL_02ec;
}
IL_0247:
{
V_0 = _stringLiteral2791739693;
goto IL_02ec;
}
IL_0252:
{
V_0 = _stringLiteral1091611732;
goto IL_02ec;
}
IL_025d:
{
V_0 = _stringLiteral356324127;
goto IL_02ec;
}
IL_0268:
{
V_0 = _stringLiteral624401215;
goto IL_02ec;
}
IL_0273:
{
V_0 = _stringLiteral1073086928;
goto IL_02ec;
}
IL_027e:
{
V_0 = _stringLiteral1060465165;
goto IL_02ec;
}
IL_0289:
{
V_0 = _stringLiteral3739562776;
goto IL_02ec;
}
IL_0294:
{
V_0 = _stringLiteral3244775435;
goto IL_02ec;
}
IL_029f:
{
V_0 = _stringLiteral3899005722;
goto IL_02ec;
}
IL_02aa:
{
V_0 = _stringLiteral4002396095;
goto IL_02ec;
}
IL_02b5:
{
V_0 = _stringLiteral3604523934;
goto IL_02ec;
}
IL_02c0:
{
V_0 = _stringLiteral2201204884;
goto IL_02ec;
}
IL_02cb:
{
V_0 = _stringLiteral3363965078;
goto IL_02ec;
}
IL_02d6:
{
V_0 = _stringLiteral858510039;
goto IL_02ec;
}
IL_02e1:
{
V_0 = _stringLiteral757602046;
goto IL_02ec;
}
IL_02ec:
{
String_t* L_13 = V_0;
return L_13;
}
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| 95,371 | 44,825 |
#include "canonical_pdbs.h"
#include "dominance_pruning.h"
#include "pattern_database.h"
#include <algorithm>
#include <cassert>
#include <iostream>
#include <limits>
using namespace std;
namespace pdbs {
CanonicalPDBs::CanonicalPDBs(
shared_ptr<PDBCollection> pattern_databases,
shared_ptr<MaxAdditivePDBSubsets> max_additive_subsets_,
bool dominance_pruning)
: max_additive_subsets(max_additive_subsets_) {
assert(max_additive_subsets);
if (dominance_pruning) {
max_additive_subsets = prune_dominated_subsets(
*pattern_databases, *max_additive_subsets);
}
}
int CanonicalPDBs::get_value(const State &state) const {
// If we have an empty collection, then max_additive_subsets = { \emptyset }.
assert(!max_additive_subsets->empty());
int max_h = 0;
for (const auto &subset : *max_additive_subsets) {
int subset_h = 0;
for (const shared_ptr<PatternDatabase> &pdb : subset) {
/* Experiments showed that it is faster to recompute the
h values than to cache them in an unordered_map. */
int h = pdb->get_value(state);
if (h == numeric_limits<int>::max())
return numeric_limits<int>::max();
subset_h += h;
}
max_h = max(max_h, subset_h);
}
return max_h;
}
}
| 1,342 | 449 |
//
// Utility.cpp
//
// $Id: //poco/Main/Data/SQLite/src/Utility.cpp#5 $
//
// Library: SQLite
// Package: SQLite
// Module: Utility
//
// Implementation of Utility
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// 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, including
// the above license grant, this restriction and the following disclaimer,
// 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.
//
// 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Data/SQLite/Utility.h"
#include "Poco/Data/SQLite/SQLiteException.h"
#include "Poco/NumberFormatter.h"
#include "Poco/String.h"
#include "Poco/Any.h"
#include "Poco/Exception.h"
#if defined(POCO_UNBUNDLED)
#include <sqlite3.h>
#else
#include "sqlite3.h"
#endif
namespace Poco {
namespace Data {
namespace SQLite {
const int Utility::THREAD_MODE_SINGLE = SQLITE_CONFIG_SINGLETHREAD;
const int Utility::THREAD_MODE_MULTI = SQLITE_CONFIG_MULTITHREAD;
const int Utility::THREAD_MODE_SERIAL = SQLITE_CONFIG_SERIALIZED;
int Utility::_threadMode =
#if (SQLITE_THREADSAFE == 0)
SQLITE_CONFIG_SINGLETHREAD;
#elif (SQLITE_THREADSAFE == 1)
SQLITE_CONFIG_SERIALIZED;
#elif (SQLITE_THREADSAFE == 2)
SQLITE_CONFIG_MULTITHREAD;
#endif
const int Utility::OPERATION_INSERT = SQLITE_INSERT;
const int Utility::OPERATION_DELETE = SQLITE_DELETE;
const int Utility::OPERATION_UPDATE = SQLITE_UPDATE;
const std::string Utility::SQLITE_DATE_FORMAT = "%Y-%m-%d";
const std::string Utility::SQLITE_TIME_FORMAT = "%H:%M:%S";
Utility::TypeMap Utility::_types;
Poco::Mutex Utility::_mutex;
Utility::Utility()
{
Poco::Mutex::ScopedLock l(_mutex);
if (_types.empty())
{
_types.insert(TypeMap::value_type("", MetaColumn::FDT_STRING));
_types.insert(TypeMap::value_type("BOOL", MetaColumn::FDT_BOOL));
_types.insert(TypeMap::value_type("BOOLEAN", MetaColumn::FDT_BOOL));
_types.insert(TypeMap::value_type("BIT", MetaColumn::FDT_BOOL));
_types.insert(TypeMap::value_type("UINT8", MetaColumn::FDT_UINT8));
_types.insert(TypeMap::value_type("UTINY", MetaColumn::FDT_UINT8));
_types.insert(TypeMap::value_type("UINTEGER8", MetaColumn::FDT_UINT8));
_types.insert(TypeMap::value_type("INT8", MetaColumn::FDT_INT8));
_types.insert(TypeMap::value_type("TINY", MetaColumn::FDT_INT8));
_types.insert(TypeMap::value_type("INTEGER8", MetaColumn::FDT_INT8));
_types.insert(TypeMap::value_type("UINT16", MetaColumn::FDT_UINT16));
_types.insert(TypeMap::value_type("USHORT", MetaColumn::FDT_UINT16));
_types.insert(TypeMap::value_type("UINTEGER16", MetaColumn::FDT_UINT16));
_types.insert(TypeMap::value_type("INT16", MetaColumn::FDT_INT16));
_types.insert(TypeMap::value_type("SHORT", MetaColumn::FDT_INT16));
_types.insert(TypeMap::value_type("INTEGER16", MetaColumn::FDT_INT16));
_types.insert(TypeMap::value_type("UINT", MetaColumn::FDT_UINT32));
_types.insert(TypeMap::value_type("UINT32", MetaColumn::FDT_UINT32));
_types.insert(TypeMap::value_type("UINTEGER32", MetaColumn::FDT_UINT32));
_types.insert(TypeMap::value_type("INT", MetaColumn::FDT_INT32));
_types.insert(TypeMap::value_type("INT32", MetaColumn::FDT_INT32));
_types.insert(TypeMap::value_type("INTEGER", MetaColumn::FDT_INT32));
_types.insert(TypeMap::value_type("INTEGER32", MetaColumn::FDT_INT32));
_types.insert(TypeMap::value_type("UINT64", MetaColumn::FDT_UINT64));
_types.insert(TypeMap::value_type("ULONG", MetaColumn::FDT_INT64));
_types.insert(TypeMap::value_type("UINTEGER64", MetaColumn::FDT_UINT64));
_types.insert(TypeMap::value_type("INT64", MetaColumn::FDT_INT64));
_types.insert(TypeMap::value_type("LONG", MetaColumn::FDT_INT64));
_types.insert(TypeMap::value_type("INTEGER64", MetaColumn::FDT_INT64));
_types.insert(TypeMap::value_type("COUNTER", MetaColumn::FDT_UINT64));
_types.insert(TypeMap::value_type("AUTOINCREMENT", MetaColumn::FDT_UINT64));
_types.insert(TypeMap::value_type("REAL", MetaColumn::FDT_DOUBLE));
_types.insert(TypeMap::value_type("FLOA", MetaColumn::FDT_DOUBLE));
_types.insert(TypeMap::value_type("FLOAT", MetaColumn::FDT_DOUBLE));
_types.insert(TypeMap::value_type("DOUB", MetaColumn::FDT_DOUBLE));
_types.insert(TypeMap::value_type("DOUBLE", MetaColumn::FDT_DOUBLE));
_types.insert(TypeMap::value_type("CHAR", MetaColumn::FDT_STRING));
_types.insert(TypeMap::value_type("CLOB", MetaColumn::FDT_STRING));
_types.insert(TypeMap::value_type("TEXT", MetaColumn::FDT_STRING));
_types.insert(TypeMap::value_type("VARCHAR", MetaColumn::FDT_STRING));
_types.insert(TypeMap::value_type("NCHAR", MetaColumn::FDT_STRING));
_types.insert(TypeMap::value_type("NCLOB", MetaColumn::FDT_STRING));
_types.insert(TypeMap::value_type("NTEXT", MetaColumn::FDT_STRING));
_types.insert(TypeMap::value_type("NVARCHAR", MetaColumn::FDT_STRING));
_types.insert(TypeMap::value_type("BLOB", MetaColumn::FDT_BLOB));
_types.insert(TypeMap::value_type("DATE", MetaColumn::FDT_DATE));
_types.insert(TypeMap::value_type("TIME", MetaColumn::FDT_TIME));
_types.insert(TypeMap::value_type("DATETIME", MetaColumn::FDT_TIMESTAMP));
_types.insert(TypeMap::value_type("TIMESTAMP", MetaColumn::FDT_TIMESTAMP));
}
}
std::string Utility::lastError(sqlite3* pDB)
{
return std::string(sqlite3_errmsg(pDB));
}
MetaColumn::ColumnDataType Utility::getColumnType(sqlite3_stmt* pStmt, std::size_t pos)
{
poco_assert_dbg (pStmt);
static Utility u;
const char* pc = sqlite3_column_decltype(pStmt, (int) pos);
std::string sqliteType = pc ? pc : "";
Poco::toUpperInPlace(sqliteType);
sqliteType = sqliteType.substr(0, sqliteType.find_first_of(" ("));
TypeMap::const_iterator it = _types.find(Poco::trimInPlace(sqliteType));
if (_types.end() == it) throw Poco::NotFoundException();
return it->second;
}
void Utility::throwException(int rc, const std::string& addErrMsg)
{
switch (rc)
{
case SQLITE_OK:
break;
case SQLITE_ERROR:
throw InvalidSQLStatementException(std::string("SQL error or missing database"), addErrMsg);
case SQLITE_INTERNAL:
throw InternalDBErrorException(std::string("An internal logic error in SQLite"), addErrMsg);
case SQLITE_PERM:
throw DBAccessDeniedException(std::string("Access permission denied"), addErrMsg);
case SQLITE_ABORT:
throw ExecutionAbortedException(std::string("Callback routine requested an abort"), addErrMsg);
case SQLITE_BUSY:
throw DBLockedException(std::string("The database file is locked"), addErrMsg);
case SQLITE_LOCKED:
throw TableLockedException(std::string("A table in the database is locked"), addErrMsg);
case SQLITE_NOMEM:
throw NoMemoryException(std::string("A malloc() failed"), addErrMsg);
case SQLITE_READONLY:
throw ReadOnlyException(std::string("Attempt to write a readonly database"), addErrMsg);
case SQLITE_INTERRUPT:
throw InterruptException(std::string("Operation terminated by sqlite_interrupt()"), addErrMsg);
case SQLITE_IOERR:
throw IOErrorException(std::string("Some kind of disk I/O error occurred"), addErrMsg);
case SQLITE_CORRUPT:
throw CorruptImageException(std::string("The database disk image is malformed"), addErrMsg);
case SQLITE_NOTFOUND:
throw TableNotFoundException(std::string("Table or record not found"), addErrMsg);
case SQLITE_FULL:
throw DatabaseFullException(std::string("Insertion failed because database is full"), addErrMsg);
case SQLITE_CANTOPEN:
throw CantOpenDBFileException(std::string("Unable to open the database file"), addErrMsg);
case SQLITE_PROTOCOL:
throw LockProtocolException(std::string("Database lock protocol error"), addErrMsg);
case SQLITE_EMPTY:
throw InternalDBErrorException(std::string("(Internal Only) Database table is empty"), addErrMsg);
case SQLITE_SCHEMA:
throw SchemaDiffersException(std::string("The database schema changed"), addErrMsg);
case SQLITE_TOOBIG:
throw RowTooBigException(std::string("Too much data for one row of a table"), addErrMsg);
case SQLITE_CONSTRAINT:
throw ConstraintViolationException(std::string("Abort due to constraint violation"), addErrMsg);
case SQLITE_MISMATCH:
throw DataTypeMismatchException(std::string("Data type mismatch"), addErrMsg);
case SQLITE_MISUSE:
throw InvalidLibraryUseException(std::string("Library used incorrectly"), addErrMsg);
case SQLITE_NOLFS:
throw OSFeaturesMissingException(std::string("Uses OS features not supported on host"), addErrMsg);
case SQLITE_AUTH:
throw AuthorizationDeniedException(std::string("Authorization denied"), addErrMsg);
case SQLITE_FORMAT:
throw CorruptImageException(std::string("Auxiliary database format error"), addErrMsg);
case SQLITE_NOTADB:
throw CorruptImageException(std::string("File opened that is not a database file"), addErrMsg);
case SQLITE_RANGE:
throw InvalidSQLStatementException(std::string("Bind Parameter out of range (Access of invalid position 0? bind starts with 1!)"), addErrMsg);
case SQLITE_ROW:
break; // sqlite_step() has another row ready
case SQLITE_DONE:
break; // sqlite_step() has finished executing
default:
throw SQLiteException(std::string("Unknown error code: ") + Poco::NumberFormatter::format(rc), addErrMsg);
}
}
bool Utility::fileToMemory(sqlite3* pInMemory, const std::string& fileName)
{
int rc;
sqlite3* pFile;
sqlite3_backup* pBackup;
rc = sqlite3_open(fileName.c_str(), &pFile);
if(rc == SQLITE_OK )
{
pBackup = sqlite3_backup_init(pInMemory, "main", pFile, "main");
if( pBackup )
{
sqlite3_backup_step(pBackup, -1);
sqlite3_backup_finish(pBackup);
}
rc = sqlite3_errcode(pFile);
}
sqlite3_close(pFile);
return SQLITE_OK == rc;
}
bool Utility::memoryToFile(const std::string& fileName, sqlite3* pInMemory)
{
int rc;
sqlite3* pFile;
sqlite3_backup* pBackup;
rc = sqlite3_open(fileName.c_str(), &pFile);
if(rc == SQLITE_OK )
{
pBackup = sqlite3_backup_init(pFile, "main", pInMemory, "main");
if( pBackup )
{
sqlite3_backup_step(pBackup, -1);
sqlite3_backup_finish(pBackup);
}
rc = sqlite3_errcode(pFile);
}
sqlite3_close(pFile);
return SQLITE_OK == rc;
}
bool Utility::isThreadSafe()
{
return 0 != sqlite3_threadsafe();
}
int Utility::getThreadMode()
{
return _threadMode;
}
bool Utility::setThreadMode(int mode)
{
#if (SQLITE_THREADSAFE != 0)
if (SQLITE_OK == sqlite3_shutdown())
{
if (SQLITE_OK == sqlite3_config(mode))
{
_threadMode = mode;
if (SQLITE_OK == sqlite3_initialize())
return true;
}
sqlite3_initialize();
}
return false;
#else
return false;
#endif
}
void* Utility::eventHookRegister(sqlite3* pDB, UpdateCallbackType callbackFn, void* pParam)
{
typedef void(*pF)(void*, int, const char*, const char*, sqlite3_int64);
return sqlite3_update_hook(pDB, reinterpret_cast<pF>(callbackFn), pParam);
}
void* Utility::eventHookRegister(sqlite3* pDB, CommitCallbackType callbackFn, void* pParam)
{
return sqlite3_commit_hook(pDB, callbackFn, pParam);
}
void* Utility::eventHookRegister(sqlite3* pDB, RollbackCallbackType callbackFn, void* pParam)
{
return sqlite3_rollback_hook(pDB, callbackFn, pParam);
}
} } } // namespace Poco::Data::SQLite
| 12,163 | 4,455 |
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Written (W) 2012 Sergey Lisitsyn
* Copyright (C) 2012 Sergey Lisitsyn
*/
#include <shogun/preprocessor/SumOne.h>
#include <shogun/preprocessor/DensePreprocessor.h>
#include <shogun/mathematics/Math.h>
#include <shogun/features/Features.h>
using namespace shogun;
CSumOne::CSumOne()
: CDensePreprocessor<float64_t>()
{
}
CSumOne::~CSumOne()
{
}
/// initialize preprocessor from features
bool CSumOne::init(CFeatures* features)
{
ASSERT(features->get_feature_class()==C_DENSE)
ASSERT(features->get_feature_type()==F_DREAL)
return true;
}
/// clean up allocated memory
void CSumOne::cleanup()
{
}
/// initialize preprocessor from file
bool CSumOne::load(FILE* f)
{
SG_SET_LOCALE_C;
SG_RESET_LOCALE;
return false;
}
/// save preprocessor init-data to file
bool CSumOne::save(FILE* f)
{
SG_SET_LOCALE_C;
SG_RESET_LOCALE;
return false;
}
/// apply preproc on feature matrix
/// result in feature matrix
/// return pointer to feature_matrix, i.e. f->get_feature_matrix();
SGMatrix<float64_t> CSumOne::apply_to_feature_matrix(CFeatures* features)
{
SGMatrix<float64_t> feature_matrix=((CDenseFeatures<float64_t>*)features)->get_feature_matrix();
for (int32_t i=0; i<feature_matrix.num_cols; i++)
{
float64_t* vec= &(feature_matrix.matrix[i*feature_matrix.num_rows]);
float64_t sum = SGVector<float64_t>::sum(vec,feature_matrix.num_rows);
SGVector<float64_t>::scale_vector(1.0/sum, vec, feature_matrix.num_rows);
}
return feature_matrix;
}
/// apply preproc on single feature vector
/// result in feature matrix
SGVector<float64_t> CSumOne::apply_to_feature_vector(SGVector<float64_t> vector)
{
float64_t* normed_vec = SG_MALLOC(float64_t, vector.vlen);
float64_t sum = SGVector<float64_t>::sum(vector.vector, vector.vlen);
for (int32_t i=0; i<vector.vlen; i++)
normed_vec[i]=vector.vector[i]/sum;
return SGVector<float64_t>(normed_vec,vector.vlen);
}
| 2,146 | 831 |
/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, Rice University
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Rice University nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Ioan Sucan */
#include "ompl/control/SpaceInformation.h"
#include "ompl/control/SimpleDirectedControlSampler.h"
#include "ompl/control/SteeredControlSampler.h"
#include "ompl/util/Exception.h"
#include <cassert>
#include <utility>
#include <limits>
ompl::control::SpaceInformation::SpaceInformation(
const base::StateSpacePtr &stateSpace, ControlSpacePtr controlSpace)
: base::SpaceInformation(stateSpace), controlSpace_(std::move(controlSpace))
{
declareParams();
}
void ompl::control::SpaceInformation::declareParams()
{
params_.declareParam<unsigned int>("min_control_duration",
[this](unsigned int n) { setMinControlDuration(n); },
[this] { return getMinControlDuration(); });
params_.declareParam<unsigned int>("max_control_duration",
[this](unsigned int n) { setMaxControlDuration(n); },
[this] { return getMaxControlDuration(); });
params_.declareParam<double>("propagation_step_size",
[this](double s) { setPropagationStepSize(s); },
[this] { return getPropagationStepSize(); });
}
void ompl::control::SpaceInformation::setup()
{
base::SpaceInformation::setup();
declareParams(); // calling base::SpaceInformation::setup() clears the params
if (!statePropagator_)
throw Exception("State propagator not defined");
if (minSteps_ > maxSteps_)
throw Exception("The minimum number of steps cannot be larger than the maximum number of steps");
if (minSteps_ == 0 && maxSteps_ == 0)
{
minSteps_ = 1;
maxSteps_ = 10;
OMPL_WARN("Assuming propagation will always have between %d and %d steps", minSteps_, maxSteps_);
}
if (minSteps_ < 1)
throw Exception("The minimum number of steps must be at least 1");
if (stepSize_ < std::numeric_limits<double>::epsilon())
{
stepSize_ = getStateValidityCheckingResolution() * getMaximumExtent();
if (stepSize_ < std::numeric_limits<double>::epsilon())
throw Exception("The propagation step size must be larger than 0");
OMPL_WARN("The propagation step size is assumed to be %f", stepSize_);
}
controlSpace_->setup();
if (controlSpace_->getDimension() <= 0)
throw Exception("The dimension of the control space we plan in must be > 0");
}
ompl::control::DirectedControlSamplerPtr ompl::control::SpaceInformation::allocDirectedControlSampler() const
{
if (dcsa_)
return dcsa_(this);
if (statePropagator_->canSteer())
return std::make_shared<SteeredControlSampler>(this);
else
return std::make_shared<SimpleDirectedControlSampler>(this);
}
void ompl::control::SpaceInformation::setDirectedControlSamplerAllocator(const DirectedControlSamplerAllocator &dcsa)
{
dcsa_ = dcsa;
setup_ = false;
}
void ompl::control::SpaceInformation::clearDirectedSamplerAllocator()
{
dcsa_ = DirectedControlSamplerAllocator();
setup_ = false;
}
void ompl::control::SpaceInformation::setStatePropagator(const StatePropagatorFn &fn)
{
class FnStatePropagator : public StatePropagator
{
public:
FnStatePropagator(SpaceInformation *si, StatePropagatorFn fn) : StatePropagator(si), fn_(std::move(fn))
{
}
void propagate(const base::State *state, const Control *control, const double duration,
base::State *result) const override
{
fn_(state, control, duration, result);
}
protected:
StatePropagatorFn fn_;
};
setStatePropagator(std::make_shared<FnStatePropagator>(this, fn));
}
void ompl::control::SpaceInformation::setStatePropagator(const StatePropagatorPtr &sp)
{
statePropagator_ = sp;
}
bool ompl::control::SpaceInformation::canPropagateBackward() const
{
return statePropagator_->canPropagateBackward();
}
void ompl::control::SpaceInformation::propagate(const base::State *state, const Control *control, int steps,
base::State *result) const
{
if (steps == 0)
{
if (result != state)
copyState(result, state);
}
else
{
double signedStepSize = steps > 0 ? stepSize_ : -stepSize_;
steps = abs(steps);
statePropagator_->propagate(state, control, signedStepSize, result);
for (int i = 1; i < steps; ++i)
statePropagator_->propagate(result, control, signedStepSize, result);
}
}
unsigned int ompl::control::SpaceInformation::propagateWhileValid(const base::State *state, const Control *control,
int steps, base::State *result) const
{
if (steps == 0)
{
if (result != state)
copyState(result, state);
return 0;
}
double signedStepSize = steps > 0 ? stepSize_ : -stepSize_;
steps = abs(steps);
// perform the first step of propagation
statePropagator_->propagate(state, control, signedStepSize, result);
// if we found a valid state after one step, we can go on
if (isValid(result))
{
base::State *temp1 = result;
base::State *temp2 = allocState();
base::State *toDelete = temp2;
unsigned int r = steps;
// for the remaining number of steps
for (int i = 1; i < steps; ++i)
{
statePropagator_->propagate(temp1, control, signedStepSize, temp2);
if (isValid(temp2))
std::swap(temp1, temp2);
else
{
// the last valid state is temp1;
r = i;
break;
}
}
// if we finished the for-loop without finding an invalid state, the last valid state is temp1
// make sure result contains that information
if (result != temp1)
copyState(result, temp1);
// free the temporary memory
freeState(toDelete);
return r;
}
// if the first propagation step produced an invalid step, return 0 steps
// the last valid state is the starting one (assumed to be valid)
if (result != state)
copyState(result, state);
return 0;
}
void ompl::control::SpaceInformation::propagate(const base::State *state, const Control *control, int steps,
std::vector<base::State *> &result, bool alloc) const
{
double signedStepSize = steps > 0 ? stepSize_ : -stepSize_;
steps = abs(steps);
if (alloc)
{
result.resize(steps);
for (auto &i : result)
i = allocState();
}
else
{
if (result.empty())
return;
steps = std::min(steps, (int)result.size());
}
int st = 0;
if (st < steps)
{
statePropagator_->propagate(state, control, signedStepSize, result[st]);
++st;
while (st < steps)
{
statePropagator_->propagate(result[st - 1], control, signedStepSize, result[st]);
++st;
}
}
}
unsigned int ompl::control::SpaceInformation::propagateWhileValid(const base::State *state, const Control *control,
int steps, std::vector<base::State *> &result,
bool alloc) const
{
double signedStepSize = steps > 0 ? stepSize_ : -stepSize_;
steps = abs(steps);
if (alloc)
result.resize(steps);
else
{
if (result.empty())
return 0;
steps = std::min(steps, (int)result.size());
}
int st = 0;
if (st < steps)
{
if (alloc)
result[st] = allocState();
statePropagator_->propagate(state, control, signedStepSize, result[st]);
if (isValid(result[st]))
{
++st;
while (st < steps)
{
if (alloc)
result[st] = allocState();
statePropagator_->propagate(result[st - 1], control, signedStepSize, result[st]);
if (!isValid(result[st]))
{
if (alloc)
{
freeState(result[st]);
result.resize(st);
}
break;
}
++st;
}
}
else
{
if (alloc)
{
freeState(result[st]);
result.resize(st);
}
}
}
return st;
}
void ompl::control::SpaceInformation::printSettings(std::ostream &out) const
{
base::SpaceInformation::printSettings(out);
out << " - control space:" << std::endl;
controlSpace_->printSettings(out);
out << " - can propagate backward: " << (canPropagateBackward() ? "yes" : "no") << std::endl;
out << " - propagation step size: " << stepSize_ << std::endl;
out << " - propagation duration: [" << minSteps_ << ", " << maxSteps_ << "]" << std::endl;
}
| 10,956 | 3,205 |
/// \file
// Range v3 library
//
// Copyright Eric Niebler 2013-present
//
// Use, modification and distribution is subject to the
// Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// Project home: https://github.com/ericniebler/range-v3
//
#ifndef RANGES_V3_VIEW_UNIQUE_HPP
#define RANGES_V3_VIEW_UNIQUE_HPP
#include <utility>
#include <meta/meta.hpp>
#include <range/v3/range_fwd.hpp>
#include <range/v3/functional/bind_back.hpp>
#include <range/v3/functional/not_fn.hpp>
#include <range/v3/utility/static_const.hpp>
#include <range/v3/view/adjacent_filter.hpp>
#include <range/v3/view/all.hpp>
#include <range/v3/view/view.hpp>
namespace ranges
{
/// \addtogroup group-views
/// @{
namespace views
{
struct unique_fn
{
private:
friend view_access;
template<typename C>
static constexpr auto CPP_fun(bind)(unique_fn unique, C pred)( //
requires(!range<C>))
{
return bind_back(unique, std::move(pred));
}
public:
template<typename Rng, typename C = equal_to>
constexpr auto operator()(Rng && rng, C pred = {}) const
-> CPP_ret(adjacent_filter_view<all_t<Rng>, logical_negate<C>>)( //
requires viewable_range<Rng> && forward_range<Rng> &&
indirect_relation<C, iterator_t<Rng>>)
{
return {all(static_cast<Rng &&>(rng)), not_fn(pred)};
}
};
/// \relates unique_fn
/// \ingroup group-views
RANGES_INLINE_VARIABLE(view<unique_fn>, unique)
} // namespace views
/// @}
} // namespace ranges
#endif
| 1,797 | 620 |
/*
* ClusteringProjector.h
*
* Created on: 07.01.2013
* Author: Christian Staudt (christian.staudt@kit.edu)
*/
#ifndef NETWORKIT_COARSENING_CLUSTERING_PROJECTOR_HPP_
#define NETWORKIT_COARSENING_CLUSTERING_PROJECTOR_HPP_
#include <networkit/graph/Graph.hpp>
#include <networkit/structures/Partition.hpp>
namespace NetworKit {
/**
* @ingroup coarsening
*/
class ClusteringProjector {
public:
/**
* DEPRECATED
*
* Given
* @param[in] Gcoarse
* @param[in] Gfine
* @param[in] fineToCoarse
* @param[in] zetaCoarse a clustering of the coarse graph
*
* , project the clustering back to the fine graph to create a clustering of the fine graph.
* @param[out] a clustering of the fine graph
**/
//virtual Partition projectBack(Graph& Gcoarse, Graph& Gfine, std::vector<node>& fineToCoarse, Partition& zetaCoarse);
/**
* Given
* @param[in] Gcoarse
* @param[in] Gfine
* @param[in] fineToCoarse
* @param[in] zetaCoarse a clustering of the coarse graph
*
* , project the clustering back to the fine graph to create a clustering of the fine graph.
* @param[out] a clustering of the fine graph
**/
virtual Partition projectBack(const Graph& Gcoarse, const Graph& Gfine, const std::vector<node>& fineToCoarse, const Partition& zetaCoarse);
/**
* Project a clustering \zeta^{i} of the coarse graph G^{i} back to
* the finest graph G^{0}, using the hierarchy of fine->coarse maps
*/
virtual Partition projectBackToFinest(const Partition& zetaCoarse, const std::vector<std::vector<node> >& maps, const Graph& Gfinest);
/**
* Assuming that the coarse graph resulted from contracting and represents a clustering of the finest graph
*
* @param[in] Gcoarse coarse graph
* @param[in] Gfinest finest graph
* @param[in] maps hierarchy of maps M^{i->i+1} mapping nodes in finer graph to supernodes in coarser graph
*/
virtual Partition projectCoarseGraphToFinestClustering(const Graph& Gcoarse, const Graph& Gfinest, const std::vector<std::vector<node> >& maps);
};
} /* namespace NetworKit */
#endif // NETWORKIT_COARSENING_CLUSTERING_PROJECTOR_HPP_
| 2,261 | 826 |
#ifdef _WIN32
#include "Timer.h"
#include <Windows.h>
using namespace Eleusis;
using namespace std;
static std::map<void*, Timer*> _activeTimers;
void CALLBACK _timerProc(_In_ HWND hwnd, _In_ UINT uMsg, _In_ UINT_PTR idEvent, _In_ DWORD dwTime)
{
auto l_timerIter = _activeTimers.find(reinterpret_cast<void*>(idEvent));
if (l_timerIter == _activeTimers.end())
return;
Timer* l_timer = l_timerIter->second;
if (l_timer->repetition_get() == TimerRepetition::Once)
l_timer->stop();
if (l_timer->enabled_get())
raiseEvent l_timer->elapsed(l_timer, nullptr);
}
Timer::Timer(unsigned int duration, TimerRepetition repetition) :
_duration(duration),
_repetition(repetition)
{
}
Timer::~Timer()
{
stop();
}
void Timer::start()
{
if (_timerID == 0)
{
_timerID = reinterpret_cast<void*>(SetTimer(nullptr, 0, _duration, _timerProc));
_activeTimers[_timerID] = this;
}
else
{
SetTimer(nullptr, reinterpret_cast<UINT_PTR>(_timerID), _duration, _timerProc);
}
raiseEvent started(this, nullptr);
}
void Timer::stop()
{
if (_timerID == 0) return;
KillTimer(nullptr, reinterpret_cast<UINT_PTR>(_timerID));
_activeTimers.erase(_timerID);
_timerID = 0;
}
void Timer::duration_set(unsigned int duration)
{
_duration = duration;
if (_timerID != 0)
SetTimer(nullptr, reinterpret_cast<UINT_PTR>(_timerID), _duration, _timerProc);
}
unsigned int Timer::duration_get()
{
return _duration;
}
void Timer::repetition_set(TimerRepetition repetition)
{
_repetition = repetition;
}
TimerRepetition Timer::repetition_get()
{
return _repetition;
}
void Timer::enabled_set(bool enable)
{
_enabled = enable;
}
bool Timer::enabled_get()
{
return _enabled;
}
#endif | 1,809 | 669 |
/*************************************************************************
* *
* Tokamak Physics Engine, Copyright (C) 2002-2007 David Lam. *
* All rights reserved. Email: david@tokamakphysics.com *
* Web: www.tokamakphysics.com *
* *
* 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 files *
* LICENSE.TXT for more details. *
* *
*************************************************************************/
#include "math/ne_type.h"
#include "math/ne_debug.h"
#include "tokamak.h"
#include "containers.h"
#include "scenery.h"
#include "collision.h"
#include "constraint.h"
#include "rigidbody.h"
#ifdef _WIN32
#include <windows.h>
#endif
#include "stack.h"
#include "simulator.h"
#include "message.h"
#include "stdio.h"
#define CAST_THIS(a, b) a& b = reinterpret_cast<a&>(*this);
#ifdef TOKAMAK_COMPILE_DLL
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
#endif
/****************************************************************************
*
* neGeometry::SetBoxSize
*
****************************************************************************/
void neGeometry::SetBoxSize(f32 width, f32 height, f32 depth)
{
CAST_THIS(TConvex, con);
con.SetBoxSize(width, height, depth);
}
/****************************************************************************
*
* neGeometry::SetBoxSize
*
****************************************************************************/
void neGeometry::SetBoxSize(const neV3 & boxSize)
{
CAST_THIS(TConvex, con);
con.SetBoxSize(boxSize[0], boxSize[1], boxSize[2]);
}
/****************************************************************************
*
* neGeometry::SetCylinder
*
****************************************************************************/
void neGeometry::SetCylinder(f32 diameter, f32 height)
{
CAST_THIS(TConvex, con);
con.type = TConvex::CYLINDER;
con.as.cylinder.radius = diameter * 0.5f;
con.as.cylinder.radiusSq = con.as.cylinder.radius * con.as.cylinder.radius;
con.as.cylinder.halfHeight = height * 0.5f;
}
/****************************************************************************
*
* neGeometry::GetCylinder
*
****************************************************************************/
neBool neGeometry::GetCylinder(f32 & diameter, f32 & height) // return false if geometry is not a cylinder
{
CAST_THIS(TConvex, con);
if (con.type != TConvex::CYLINDER)
return false;
diameter = con.CylinderRadius() * 2.0f;
height = con.CylinderHalfHeight() * 2.0f;
return true;
}
/****************************************************************************
*
* neGeometry::SetConvexMesh
*
****************************************************************************/
void neGeometry::SetConvexMesh(neByte * convexData)
{
CAST_THIS(TConvex, con);
con.SetConvexMesh(convexData);
}
/****************************************************************************
*
* neGeometry::GetConvexMesh
*
****************************************************************************/
neBool neGeometry::GetConvexMesh(neByte *& convexData)
{
CAST_THIS(TConvex, con);
if (con.type != TConvex::CONVEXDCD)
return false;
convexData = con.as.convexDCD.convexData;
return true;
}
/****************************************************************************
*
* neGeometry::SetTransform
*
****************************************************************************/
void neGeometry::SetTransform(neT3 & t)
{
CAST_THIS(TConvex, con);
con.SetTransform(t);
}
/****************************************************************************
*
* neGeometry::SetMaterialIndex
*
****************************************************************************/
void neGeometry::SetMaterialIndex(s32 index)
{
CAST_THIS(TConvex, con);
con.SetMaterialId(index);
}
/****************************************************************************
*
* neGeometry::GetMaterialIndex
*
****************************************************************************/
s32 neGeometry::GetMaterialIndex()
{
CAST_THIS(TConvex, con);
return con.matIndex;
}
/****************************************************************************
*
* neGeometry::GetTransform
*
****************************************************************************/
neT3 neGeometry::GetTransform()
{
CAST_THIS(TConvex, con);
return con.c2p;
}
/****************************************************************************
*
* neGeometry::SetUserData
*
****************************************************************************/
void neGeometry::SetUserData(u32 userData)
{
CAST_THIS(TConvex, con);
con.userData = userData;
}
/****************************************************************************
*
* neGeometry::GetUserData
*
****************************************************************************/
u32 neGeometry::GetUserData()
{
CAST_THIS(TConvex, con);
return con.userData;
}
/****************************************************************************
*
* neGeometry::GetBoxSize
*
****************************************************************************/
neBool neGeometry::GetBoxSize(neV3 & boxSize) // return false if geometry is not a box
{
CAST_THIS(TConvex, con);
if (con.type != TConvex::BOX)
return false;
boxSize = con.as.box.boxSize * 2.0f;
return true;
}
/****************************************************************************
*
* neGeometry::SetSphereDiameter
*
****************************************************************************/
void neGeometry::SetSphereDiameter(f32 diameter)
{
CAST_THIS(TConvex, con);
con.type = TConvex::SPHERE;
con.as.sphere.radius = diameter * 0.5f;
con.as.sphere.radiusSq = con.as.sphere.radius * con.as.sphere.radius;
}
/****************************************************************************
*
* neGeometry::GetSphereDiameter
*
****************************************************************************/
neBool neGeometry::GetSphereDiameter(f32 & diameter) // return false if geometry is not a sphere
{
CAST_THIS(TConvex, con);
if (con.type != TConvex::SPHERE)
return false;
diameter = con.Radius() * 2.0f;
return true;
}
/****************************************************************************
*
* neGeometry::SetBreakFlag
*
****************************************************************************/
void neGeometry::SetBreakageFlag(neBreakFlag flag)
{
CAST_THIS(TConvex, con);
con.breakInfo.flag = flag;
}
/****************************************************************************
*
* neGeometry::GetBreakFlag
*
****************************************************************************/
neGeometry::neBreakFlag neGeometry::GetBreakageFlag()
{
CAST_THIS(TConvex, con);
return con.breakInfo.flag;
}
/****************************************************************************
*
* neGeometry::SetBreakageMass
*
****************************************************************************/
void neGeometry::SetBreakageMass(f32 mass)
{
CAST_THIS(TConvex, con);
con.breakInfo.mass = mass;
}
/****************************************************************************
*
* neGeometry::GetBreakageMass
*
****************************************************************************/
f32 neGeometry::GetBreakageMass()
{
CAST_THIS(TConvex, con);
return con.breakInfo.mass;
}
/****************************************************************************
*
* neGeometry::SetBreakageInertiaTensor
*
****************************************************************************/
void neGeometry::SetBreakageInertiaTensor(const neV3 & tensor)
{
CAST_THIS(TConvex, con);
con.breakInfo.inertiaTensor = tensor;
}
/****************************************************************************
*
* neGeometry::GetBreakageInertiaTensor
*
****************************************************************************/
neV3 neGeometry::GetBreakageInertiaTensor()
{
CAST_THIS(TConvex, con);
return con.breakInfo.inertiaTensor;
}
/****************************************************************************
*
* neGeometry::SetBreakageMagnitude
*
****************************************************************************/
void neGeometry::SetBreakageMagnitude(f32 mag)
{
CAST_THIS(TConvex, con);
con.breakInfo.breakMagnitude = mag;
}
/****************************************************************************
*
* neGeometry::GetBreakageMagnitude
*
****************************************************************************/
f32 neGeometry::GetBreakageMagnitude()
{
CAST_THIS(TConvex, con);
return con.breakInfo.breakMagnitude;
}
/****************************************************************************
*
* neGeometry::SetBreakageAbsorption
*
****************************************************************************/
void neGeometry::SetBreakageAbsorption(f32 absorb)
{
CAST_THIS(TConvex, con);
con.breakInfo.breakAbsorb = absorb;
}
void neGeometry::SetBreakagePlane(const neV3 & planeNormal)
{
CAST_THIS(TConvex, con);
con.breakInfo.breakPlane = planeNormal;
}
neV3 neGeometry::GetBreakagePlane()
{
CAST_THIS(TConvex, con);
return con.breakInfo.breakPlane;
}
/****************************************************************************
*
* neGeometry::GetBreakageAbsorption
*
****************************************************************************/
f32 neGeometry::GetBreakageAbsorption()
{
CAST_THIS(TConvex, con);
return con.breakInfo.breakAbsorb;
}
/****************************************************************************
*
* neGeometry::SetBreakNeighbourRadius
*
****************************************************************************/
void neGeometry::SetBreakageNeighbourRadius(f32 radius)
{
CAST_THIS(TConvex, con);
con.breakInfo.neighbourRadius = radius;
}
/****************************************************************************
*
* neGeometry::GetBreakNeighbourRadius
*
****************************************************************************/
f32 neGeometry::GetBreakageNeighbourRadius()
{
CAST_THIS(TConvex, con);
return con.breakInfo.neighbourRadius;
}
/****************************************************************************
*
* neAnimatedBody::GetPos
*
****************************************************************************/
neV3 neAnimatedBody::GetPos()
{
CAST_THIS(neCollisionBody_, cb);
return cb.b2w.pos;
}
/****************************************************************************
*
* neAnimatedBody::SetPos
*
****************************************************************************/
void neAnimatedBody::SetPos(const neV3 & p)
{
CAST_THIS(neCollisionBody_, cb);
cb.b2w.pos = p;
cb.UpdateAABB();
cb.moved = true;
}
/****************************************************************************
*
* neAnimatedBody::GetRotationM3
*
****************************************************************************/
neM3 neAnimatedBody::GetRotationM3()
{
CAST_THIS(neCollisionBody_, cb);
return cb.b2w.rot;
}
/****************************************************************************
*
* neAnimatedBody::GetRotationQ
*
****************************************************************************/
neQ neAnimatedBody::GetRotationQ()
{
CAST_THIS(neCollisionBody_, cb);
neQ q;
q.SetupFromMatrix3(cb.b2w.rot);
return q;
}
/****************************************************************************
*
* neAnimatedBody::SetRotation
*
****************************************************************************/
void neAnimatedBody::SetRotation(const neM3 & m)
{
CAST_THIS(neCollisionBody_, cb);
cb.b2w.rot = m;
cb.moved = true;
}
/****************************************************************************
*
* neAnimatedBody::SetRotation
*
****************************************************************************/
void neAnimatedBody::SetRotation(const neQ & q)
{
CAST_THIS(neCollisionBody_, cb);
cb.b2w.rot = q.BuildMatrix3();
cb.moved = true;
}
/****************************************************************************
*
* neAnimatedBody::GetTransform
*
****************************************************************************/
neT3 neAnimatedBody::GetTransform()
{
CAST_THIS(neCollisionBody_, cb);
return cb.b2w;
}
/****************************************************************************
*
* neAnimatedBody::SetCollisionID
*
****************************************************************************/
void neAnimatedBody::SetCollisionID(s32 cid)
{
CAST_THIS(neCollisionBody_, cb);
cb.cid = cid;
}
/****************************************************************************
*
* neAnimatedBody::GetCollisionID
*
****************************************************************************/
s32 neAnimatedBody::GetCollisionID()
{
CAST_THIS(neCollisionBody_, cb);
return cb.cid;
}
/****************************************************************************
*
* neAnimatedBody::SetUserData
*
****************************************************************************/
void neAnimatedBody::SetUserData(u32 cookies)
{
CAST_THIS(neCollisionBody_, cb);
cb.cookies = cookies;
}
/****************************************************************************
*
* neAnimatedBody::GetUserData
*
****************************************************************************/
u32 neAnimatedBody::GetUserData()
{
CAST_THIS(neCollisionBody_, cb);
return cb.cookies;
}
/****************************************************************************
*
* neAnimatedBody::GetGeometryCount
*
****************************************************************************/
s32 neAnimatedBody::GetGeometryCount()
{
CAST_THIS(neCollisionBody_, cb);
return cb.col.convexCount;
}
/****************************************************************************
*
* neAnimatedBody::GetGeometry
*
****************************************************************************/
/*
neGeometry * neAnimatedBody::GetGeometry(s32 index)
{
CAST_THIS(neCollisionBody_, cb);
return reinterpret_cast<neGeometry*>(cb.GetConvex(index));
}
*/
/****************************************************************************
*
* neAnimatedBody::SetGeometry
*
****************************************************************************/
/*
void neAnimatedBody::SetGeometry(s32 geometryCount, neGeometry * geometryArray)
{
CAST_THIS(neCollisionBody_, cb);
//todo
}
*/
/****************************************************************************
*
* neAnimatedBody::UpdateBoundingInfo
*
****************************************************************************/
void neAnimatedBody::UpdateBoundingInfo()
{
CAST_THIS(neRigidBodyBase, rb);
rb.RecalcBB();
}
/****************************************************************************
*
* neAnimatedBody::CollideConnected
*
****************************************************************************/
void neAnimatedBody::CollideConnected(neBool yes)
{
CAST_THIS(neRigidBodyBase, rb);
rb.CollideConnected(yes);
}
/****************************************************************************
*
* neAnimatedBody::IsCollideConnected
*
****************************************************************************/
neBool neAnimatedBody::CollideConnected()
{
CAST_THIS(neRigidBodyBase, rb);
return rb.CollideConnected();
}
/****************************************************************************
*
* neAnimatedBody::CollideDirectlyConnected
*
****************************************************************************/
void neAnimatedBody::CollideDirectlyConnected(neBool yes)
{
CAST_THIS(neRigidBodyBase, rb);
rb.isCollideDirectlyConnected = yes;
}
/****************************************************************************
*
* neAnimatedBody::CollideDirectlyConnected
*
****************************************************************************/
neBool neAnimatedBody::CollideDirectlyConnected()
{
CAST_THIS(neRigidBodyBase, rb);
return rb.isCollideDirectlyConnected;
}
/****************************************************************************
*
* neAnimatedBody::AddGeometry
*
****************************************************************************/
neGeometry * neAnimatedBody::AddGeometry()
{
CAST_THIS(neCollisionBody_, ab);
TConvex * g = ab.AddGeometry();
return reinterpret_cast<neGeometry *>(g);
}
/****************************************************************************
*
* neAnimatedBody::RemoveGeometry
*
****************************************************************************/
neBool neAnimatedBody::RemoveGeometry(neGeometry * g)
{
CAST_THIS(neCollisionBody_, ab);
if (!ab.col.convex)
return false;
TConvexItem * gi = (TConvexItem *)ab.col.convex;
while (gi)
{
TConvex * convex = reinterpret_cast<TConvex *>(gi);
gi = gi->next;
if (convex == reinterpret_cast<TConvex *>(g))
{
if (ab.col.convex == convex)
{
ab.col.convex = (TConvex*)gi;
}
ab.sim->geometryHeap.Dealloc(convex, 1);
ab.col.convexCount--;
if (ab.col.convexCount == 0)
{
ab.col.convex = NULL;
if (ab.IsInRegion() && !ab.isCustomCD)
ab.sim->region.RemoveBody(&ab);
}
return true;
}
}
return false;
}
/****************************************************************************
*
* neAnimatedBody::BeginIterateGeometry
*
****************************************************************************/
void neAnimatedBody::BeginIterateGeometry()
{
CAST_THIS(neCollisionBody_, ab);
ab.BeginIterateGeometry();
}
/****************************************************************************
*
* neAnimatedBody::GetNextGeometry
*
****************************************************************************/
neGeometry * neAnimatedBody::GetNextGeometry()
{
CAST_THIS(neCollisionBody_, ab);
return reinterpret_cast<neGeometry *>(ab.GetNextGeometry());
}
/****************************************************************************
*
* neAnimatedBody::BreakGeometry
*
****************************************************************************/
neRigidBody * neAnimatedBody::BreakGeometry(neGeometry * g)
{
CAST_THIS(neCollisionBody_, ab);
neRigidBody_ * newBody = ab.sim->CreateRigidBodyFromConvex((TConvex*)g, &ab);
return (neRigidBody *)newBody;
}
/****************************************************************************
*
* neAnimatedBody::UseCustomCollisionDetection
*
****************************************************************************/
void neAnimatedBody::UseCustomCollisionDetection(neBool yes, const neT3 * obb, f32 boundingRadius)
{
CAST_THIS(neCollisionBody_, ab);
if (yes)
{
ab.obb = *obb;
ab.col.boundingRadius = boundingRadius;
ab.isCustomCD = yes;
if (ab.isActive && !ab.IsInRegion())
{
ab.sim->region.AddBody(&ab, NULL);
}
}
else
{
ab.isCustomCD = yes;
this->UpdateBoundingInfo();
if (ab.IsInRegion() && GetGeometryCount() == 0)
{
ab.sim->region.RemoveBody(&ab);
}
}
}
/****************************************************************************
*
* neAnimatedBody::UseCustomCollisionDetection
*
****************************************************************************/
neBool neAnimatedBody::UseCustomCollisionDetection()
{
CAST_THIS(neCollisionBody_, ab);
return ab.isCustomCD;
}
/****************************************************************************
*
* neAnimatedBody::AddSensor
*
****************************************************************************/
neSensor * neAnimatedBody::AddSensor()
{
CAST_THIS(neRigidBodyBase, ab);
neSensor_ * s = ab.AddSensor();
return reinterpret_cast<neSensor *>(s);
}
/****************************************************************************
*
* neAnimatedBody::RemoveSensor
*
****************************************************************************/
neBool neAnimatedBody::RemoveSensor(neSensor * s)
{
CAST_THIS(neRigidBodyBase, ab);
if (!ab.sensors)
return false;
neSensorItem * si = (neSensorItem *)ab.sensors;
while (si)
{
neSensor_ * sensor = (neSensor_ *) si;
si = si->next;
if (sensor == reinterpret_cast<neSensor_*>(s))
{
//reinterpret_cast<neSensorItem *>(s)->Remove();
ab.sim->sensorHeap.Dealloc(sensor, 1);
return true;
}
}
return false;
}
/****************************************************************************
*
* neAnimatedBody::BeginIterateSensor
*
****************************************************************************/
void neAnimatedBody::BeginIterateSensor()
{
CAST_THIS(neRigidBodyBase, ab);
ab.BeginIterateSensor();
}
/****************************************************************************
*
* neAnimatedBody::GetNextSensor
*
****************************************************************************/
neSensor * neAnimatedBody::GetNextSensor()
{
CAST_THIS(neRigidBodyBase, ab);
return reinterpret_cast<neSensor *>(ab.GetNextSensor());
}
/****************************************************************************
*
* neAnimatedBody::Active
*
****************************************************************************/
void neAnimatedBody::Active(neBool yes, neRigidBody * hint)
{
CAST_THIS(neRigidBodyBase, ab);
ab.Active(yes, (neRigidBodyBase *)hint);
}
/****************************************************************************
*
* neAnimatedBody::Active
*
****************************************************************************/
void neAnimatedBody::Active(neBool yes, neAnimatedBody * hint)
{
CAST_THIS(neRigidBodyBase, ab);
ab.Active(yes, (neRigidBodyBase *)hint);
}
/****************************************************************************
*
* neAnimatedBody::IsActive
*
****************************************************************************/
neBool neAnimatedBody::Active()
{
CAST_THIS(neRigidBodyBase, ab);
return ab.isActive;
}
/****************************************************************************
*
* neRigidBody::GetMass
*
****************************************************************************/
f32 neRigidBody::GetMass()
{
CAST_THIS(neRigidBody_, rb);
return rb.mass;
}
/****************************************************************************
*
* neRigidBody::SetMass
*
****************************************************************************/
void neRigidBody::SetMass(f32 mass)
{
CAST_THIS(neRigidBody_, rb);
ASSERT(neIsFinite(mass));
rb.mass = mass;
rb.oneOnMass = 1.0f / mass;
}
/****************************************************************************
*
* neRigidBody::SetInertiaTensor
*
****************************************************************************/
void neRigidBody::SetInertiaTensor(const neM3 & tensor)
{
CAST_THIS(neRigidBody_, rb);
rb.Ibody = tensor;
rb.IbodyInv.SetInvert(tensor);
//ASSERT(tensor.Invert(rb.IbodyInv));
}
/****************************************************************************
*
* neRigidBody::SetInertiaTensor
*
****************************************************************************/
void neRigidBody::SetInertiaTensor(const neV3 & tensor)
{
CAST_THIS(neRigidBody_, rb);
neM3 i;
i.SetIdentity();
i[0][0] = tensor[0];
i[1][1] = tensor[1];
i[2][2] = tensor[2];
rb.Ibody = i;
rb.IbodyInv.SetInvert(rb.Ibody);
}
/****************************************************************************
*
* neRigidBody::SetCollisionID
*
****************************************************************************/
void neRigidBody::SetCollisionID(s32 cid)
{
CAST_THIS(neRigidBodyBase, rb);
rb.cid = cid;
}
/****************************************************************************
*
* neRigidBody::GetCollisionID
*
****************************************************************************/
s32 neRigidBody::GetCollisionID()
{
CAST_THIS(neRigidBodyBase, rb);
return rb.cid;
}
/****************************************************************************
*
* neRigidBody::SetUserData
*
****************************************************************************/
void neRigidBody::SetUserData(u32 cookies)
{
CAST_THIS(neRigidBodyBase, rb);
rb.cookies = cookies;
}
/****************************************************************************
*
* neRigidBody::GetUserData
*
****************************************************************************/
u32 neRigidBody::GetUserData()
{
CAST_THIS(neRigidBodyBase, rb);
return rb.cookies;
}
/****************************************************************************
*
* neRigidBody::GetGeometryCount
*
****************************************************************************/
s32 neRigidBody::GetGeometryCount()
{
CAST_THIS(neRigidBodyBase, rb);
return rb.col.convexCount;
}
void neRigidBody::SetLinearDamping(f32 damp)
{
CAST_THIS(neRigidBody_, rb);
rb.linearDamp = neAbs(damp);
}
f32 neRigidBody::GetLinearDamping()
{
CAST_THIS(neRigidBody_, rb);
return rb.linearDamp;
}
void neRigidBody::SetAngularDamping(f32 damp)
{
CAST_THIS(neRigidBody_, rb);
rb.angularDamp = neAbs(damp);
}
f32 neRigidBody::GetAngularDamping()
{
CAST_THIS(neRigidBody_, rb);
return rb.angularDamp;
}
void neRigidBody::SetSleepingParameter(f32 sleepingParam)
{
CAST_THIS(neRigidBody_, rb);
rb.sleepingParam = sleepingParam;
}
f32 neRigidBody::GetSleepingParameter()
{
CAST_THIS(neRigidBody_, rb);
return rb.sleepingParam;
}
/****************************************************************************
*
* neRigidBody::GetGeometry
*
****************************************************************************/
/*
neGeometry * neRigidBody::GetGeometry(s32 index)
{
CAST_THIS(neRigidBodyBase, rb);
return reinterpret_cast<neGeometry*>(rb.GetConvex(index));
}
*/
/****************************************************************************
*
* neRigidBody::SetGeometry
*
****************************************************************************/
/*
void neRigidBody::SetGeometry(s32 geometryCount, neGeometry * geometryArray)
{
//todo
}
*/
/****************************************************************************
*
* neRigidBody::GetPos
*
****************************************************************************/
neV3 neRigidBody::GetPos()
{
CAST_THIS(neRigidBody_, rb);
return rb.GetPos();
}
/****************************************************************************
*
* neRigidBody::SetPos
*
****************************************************************************/
void neRigidBody::SetPos(const neV3 & p)
{
CAST_THIS(neRigidBody_, rb);
rb.SetPos(p);
rb.WakeUp();
}
/****************************************************************************
*
* neRigidBody::GetRotationM3
*
****************************************************************************/
neM3 neRigidBody::GetRotationM3()
{
CAST_THIS(neRigidBody_, rb);
return rb.State().rot();
}
/****************************************************************************
*
* neRigidBody::GetRotationQ
*
****************************************************************************/
neQ neRigidBody::GetRotationQ()
{
CAST_THIS(neRigidBody_, rb);
return rb.State().q;
}
/****************************************************************************
*
* neRigidBody::SetRotation
*
****************************************************************************/
void neRigidBody::SetRotation(const neM3 & m)
{
ASSERT(m.IsOrthogonalNormal());
CAST_THIS(neRigidBody_, rb);
rb.State().rot() = m;
rb.State().q.SetupFromMatrix3(m);
rb.WakeUp();
}
/****************************************************************************
*
* neRigidBody::SetRotation
*
****************************************************************************/
void neRigidBody::SetRotation(const neQ & q)
{
CAST_THIS(neRigidBody_, rb);
rb.State().q = q;
rb.State().rot() = q.BuildMatrix3();
rb.WakeUp();
}
/****************************************************************************
*
* neRigidBody::GetTransform
*
****************************************************************************/
neT3 neRigidBody::GetTransform()
{
CAST_THIS(neRigidBody_, rb);
rb.State().b2w.rot[0].v[3] = 0.0f;
rb.State().b2w.rot[1].v[3] = 0.0f;
rb.State().b2w.rot[2].v[3] = 0.0f;
rb.State().b2w.pos.v[3] = 1.0f;
return rb.State().b2w;
}
/****************************************************************************
*
* neRigidBody::GetVelocity
*
****************************************************************************/
neV3 neRigidBody::GetVelocity()
{
CAST_THIS(neRigidBody_, rb);
return rb.Derive().linearVel;
}
/****************************************************************************
*
* neRigidBody::SetVelocity
*
****************************************************************************/
void neRigidBody::SetVelocity(const neV3 & v)
{
CAST_THIS(neRigidBody_, rb);
rb.Derive().linearVel = v;
rb.WakeUpAllJoint();
}
/****************************************************************************
*
* neRigidBody::GetAngularVelocity
*
****************************************************************************/
neV3 neRigidBody::GetAngularVelocity()
{
CAST_THIS(neRigidBody_, rb);
return rb.Derive().angularVel;
}
/****************************************************************************
*
* neRigidBody::GetAngularMomentum
*
****************************************************************************/
neV3 neRigidBody::GetAngularMomentum()
{
CAST_THIS(neRigidBody_, rb);
return rb.State().angularMom;
}
/****************************************************************************
*
* neRigidBody::SetAngularMomemtum
*
****************************************************************************/
void neRigidBody::SetAngularMomentum(const neV3& am)
{
CAST_THIS(neRigidBody_, rb);
rb.SetAngMom(am);
rb.WakeUpAllJoint();
}
/****************************************************************************
*
* neRigidBody::GetVelocityAtPoint
*
****************************************************************************/
neV3 neRigidBody::GetVelocityAtPoint(const neV3 & pt)
{
CAST_THIS(neRigidBody_, rb);
return rb.VelocityAtPoint(pt);
}
/****************************************************************************
*
* neRigidBody::UpdateBoundingInfo
*
****************************************************************************/
void neRigidBody::UpdateBoundingInfo()
{
CAST_THIS(neRigidBodyBase, rb);
rb.RecalcBB();
}
/****************************************************************************
*
* neRigidBody::UpdateInertiaTensor
*
****************************************************************************/
void neRigidBody::UpdateInertiaTensor()
{
CAST_THIS(neRigidBody_, rb);
rb.RecalcInertiaTensor();
}
/****************************************************************************
*
* neRigidBody::SetForce
*
****************************************************************************/
void neRigidBody::SetForce(const neV3 & force, const neV3 & pos)
{
CAST_THIS(neRigidBody_, rb);
if (force.IsConsiderZero())
{
rb.force = force;
rb.torque = ((pos - rb.GetPos()).Cross(force));
return;
}
rb.force = force;
rb.torque = ((pos - rb.GetPos()).Cross(force));
rb.WakeUp();
}
/****************************************************************************
*
* neRigidBody::SetForce
*
****************************************************************************/
void neRigidBody::SetTorque(const neV3 & torque)
{
CAST_THIS(neRigidBody_, rb);
if (torque.IsConsiderZero())
{
rb.torque = torque;
return;
}
rb.torque = torque;
rb.WakeUp();
}
/****************************************************************************
*
* neRigidBody::ApplyForceCOG
*
****************************************************************************/
void neRigidBody::SetForce(const neV3 & force)
{
CAST_THIS(neRigidBody_, rb);
if (force.IsConsiderZero())
{
rb.force = force;
return;
}
rb.force = force;
rb.WakeUp();
}
neV3 neRigidBody::GetForce()
{
CAST_THIS(neRigidBody_, rb);
return rb.force;
}
neV3 neRigidBody::GetTorque()
{
CAST_THIS(neRigidBody_, rb);
return rb.torque;
}
/****************************************************************************
*
* neRigidBody::AddImpulse
*
****************************************************************************/
void neRigidBody::ApplyImpulse(const neV3 & impulse)
{
CAST_THIS(neRigidBody_, rb);
neV3 dv = impulse * rb.oneOnMass;
rb.Derive().linearVel += dv;
//rb.WakeUp();
rb.WakeUpAllJoint();
}
/****************************************************************************
*
* neRigidBody::AddImpulseWithTwist
*
****************************************************************************/
void neRigidBody::ApplyImpulse(const neV3 & impulse, const neV3 & pos)
{
CAST_THIS(neRigidBody_, rb);
neV3 dv = impulse * rb.oneOnMass;
neV3 da = (pos - rb.GetPos()).Cross(impulse);
rb.Derive().linearVel += dv;
neV3 newAM = rb.State().angularMom + da;
rb.SetAngMom(newAM);
rb.WakeUp();
}
/****************************************************************************
*
* neRigidBody::ApplyTwist
*
****************************************************************************/
void neRigidBody::ApplyTwist(const neV3 & twist)
{
CAST_THIS(neRigidBody_, rb);
neV3 newAM = twist;
rb.SetAngMom(newAM);
rb.WakeUp();
}
/****************************************************************************
*
* neRigidBody::AddController
*
****************************************************************************/
neRigidBodyController * neRigidBody::AddController(neRigidBodyControllerCallback * controller, s32 period)
{
CAST_THIS(neRigidBody_, rb);
return (neRigidBodyController *)rb.AddController(controller, period);
}
/****************************************************************************
*
* neRigidBody::RemoveController
*
****************************************************************************/
neBool neRigidBody::RemoveController(neRigidBodyController * rbController)
{
CAST_THIS(neRigidBody_, rb);
if (!rb.controllers)
return false;
neControllerItem * ci = (neControllerItem *)rb.controllers;
while (ci)
{
neController * con = reinterpret_cast<neController *>(ci);
ci = ci->next;
if (con == reinterpret_cast<neController *>(rbController))
{
//reinterpret_cast<neControllerItem *>(con)->Remove();
rb.sim->controllerHeap.Dealloc(con, 1);
return true;
}
}
return false;
}
/****************************************************************************
*
* neRigidBody::BeginIterateController
*
****************************************************************************/
void neRigidBody::BeginIterateController()
{
CAST_THIS(neRigidBody_, rb);
rb.BeginIterateController();
}
/****************************************************************************
*
* neRigidBody::GetNextController
*
****************************************************************************/
neRigidBodyController * neRigidBody::GetNextController()
{
CAST_THIS(neRigidBody_, rb);
return (neRigidBodyController *)rb.GetNextController();
}
/****************************************************************************
*
* neRigidBody::GravityEnable
*
****************************************************************************/
void neRigidBody::GravityEnable(neBool yes)
{
CAST_THIS(neRigidBody_, rb);
rb.GravityEnable(yes);
}
/****************************************************************************
*
* neRigidBody::GravityEnable
*
****************************************************************************/
neBool neRigidBody::GravityEnable()
{
CAST_THIS(neRigidBody_, rb);
return rb.gravityOn;
}
/****************************************************************************
*
* neRigidBody::CollideConnected
*
****************************************************************************/
void neRigidBody::CollideConnected(neBool yes)
{
CAST_THIS(neRigidBody_, rb);
rb.CollideConnected(yes);
}
/****************************************************************************
*
* neRigidBody::CollideConnected
*
****************************************************************************/
neBool neRigidBody::CollideConnected()
{
CAST_THIS(neRigidBody_, rb);
return rb.CollideConnected();
}
/****************************************************************************
*
* neRigidBody::CollideDirectlyConnected
*
****************************************************************************/
void neRigidBody::CollideDirectlyConnected(neBool yes)
{
CAST_THIS(neRigidBody_, rb);
rb.isCollideDirectlyConnected = yes;
}
/****************************************************************************
*
* neRigidBody::CollideConnected
*
****************************************************************************/
neBool neRigidBody::CollideDirectlyConnected()
{
CAST_THIS(neRigidBody_, rb);
return rb.isCollideDirectlyConnected;
}
/****************************************************************************
*
* neRigidBody::AddGeometry
*
****************************************************************************/
neGeometry * neRigidBody::AddGeometry()
{
CAST_THIS(neRigidBody_, rb);
TConvex * g = rb.AddGeometry();
return reinterpret_cast<neGeometry *>(g);
}
/****************************************************************************
*
* neRigidBody::RemoveGeometry
*
****************************************************************************/
neBool neRigidBody::RemoveGeometry(neGeometry * g)
{
CAST_THIS(neRigidBody_, rb);
if (!rb.col.convex)
return false;
TConvexItem * gi = (TConvexItem *)rb.col.convex;
while (gi)
{
TConvex * convex = reinterpret_cast<TConvex *>(gi);
gi = gi->next;
if (convex == reinterpret_cast<TConvex *>(g))
{
if (rb.col.convex == convex)
{
rb.col.convex = (TConvex*)gi;
}
rb.sim->geometryHeap.Dealloc(convex, 1);
rb.col.convexCount--;
if (rb.col.convexCount == 0)
{
rb.col.convex = NULL;
if (rb.IsInRegion() && !rb.isCustomCD)
rb.sim->region.RemoveBody(&rb);
}
return true;
}
}
return false;
}
/****************************************************************************
*
* neRigidBody::BeginIterateGeometry
*
****************************************************************************/
void neRigidBody::BeginIterateGeometry()
{
CAST_THIS(neRigidBody_, rb);
rb.BeginIterateGeometry();
}
/****************************************************************************
*
* neRigidBody::GetNextGeometry
*
****************************************************************************/
neGeometry * neRigidBody::GetNextGeometry()
{
CAST_THIS(neRigidBody_, rb);
return reinterpret_cast<neGeometry *>(rb.GetNextGeometry());
}
/****************************************************************************
*
* neRigidBody::BreakGeometry
*
****************************************************************************/
neRigidBody * neRigidBody::BreakGeometry(neGeometry * g)
{
CAST_THIS(neRigidBody_, rb);
neRigidBody_ * newBody = rb.sim->CreateRigidBodyFromConvex((TConvex*)g, &rb);
return (neRigidBody *)newBody;
}
/****************************************************************************
*
* neRigidBody::UseCustomCollisionDetection
*
****************************************************************************/
void neRigidBody::UseCustomCollisionDetection(neBool yes, const neT3 * obb, f32 boundingRadius)
{
CAST_THIS(neRigidBody_, rb);
if (yes)
{
rb.obb = *obb;
rb.col.boundingRadius = boundingRadius;
rb.isCustomCD = yes;
if (rb.isActive && !rb.IsInRegion())
{
rb.sim->region.AddBody(&rb, NULL);
}
}
else
{
rb.isCustomCD = yes;
this->UpdateBoundingInfo();
if (rb.IsInRegion() && GetGeometryCount() == 0)
{
rb.sim->region.RemoveBody(&rb);
}
}
}
/****************************************************************************
*
* neRigidBody::UseCustomCollisionDetection
*
****************************************************************************/
neBool neRigidBody::UseCustomCollisionDetection()
{
CAST_THIS(neRigidBody_, rb);
return rb.isCustomCD;
}
/****************************************************************************
*
* neRigidBody::AddSensor
*
****************************************************************************/
neSensor * neRigidBody::AddSensor()
{
CAST_THIS(neRigidBody_, rb);
neSensor_ * s = rb.AddSensor();
return reinterpret_cast<neSensor *>(s);
}
/****************************************************************************
*
* neRigidBody::RemoveSensor
*
****************************************************************************/
neBool neRigidBody::RemoveSensor(neSensor * s)
{
CAST_THIS(neRigidBody_, rb);
if (!rb.sensors)
return false;
neSensorItem * si = (neSensorItem *)rb.sensors;
while (si)
{
neSensor_ * sensor = reinterpret_cast<neSensor_ *>(si);
si = si->next;
if (sensor == reinterpret_cast<neSensor_ *>(s))
{
//reinterpret_cast<neSensorItem *>(s)->Remove();
rb.sim->sensorHeap.Dealloc(sensor, 1);
return true;
}
}
return false;
}
/****************************************************************************
*
* neRigidBody::BeginIterateSensor
*
****************************************************************************/
void neRigidBody::BeginIterateSensor()
{
CAST_THIS(neRigidBody_, rb);
rb.BeginIterateSensor();
}
/****************************************************************************
*
* neRigidBody::GetNextSensor
*
****************************************************************************/
neSensor * neRigidBody::GetNextSensor()
{
CAST_THIS(neRigidBody_, rb);
return reinterpret_cast<neSensor *>(rb.GetNextSensor());
}
/****************************************************************************
*
* neRigidBody::Active
*
****************************************************************************/
void neRigidBody::Active(neBool yes, neRigidBody * hint)
{
CAST_THIS(neRigidBodyBase, ab);
ab.Active(yes, (neRigidBodyBase *)hint);
}
/****************************************************************************
*
* neRigidBody::Active
*
****************************************************************************/
void neRigidBody::Active(neBool yes, neAnimatedBody * hint)
{
CAST_THIS(neRigidBodyBase, ab);
ab.Active(yes, (neRigidBodyBase *)hint);
}
/****************************************************************************
*
* neAnimatedBody::IsActive
*
****************************************************************************/
neBool neRigidBody::Active()
{
CAST_THIS(neRigidBodyBase, ab);
return ab.isActive;
}
neBool neRigidBody::IsIdle()
{
CAST_THIS(neRigidBody_, rb);
return (rb.status == neRigidBody_::NE_RBSTATUS_IDLE);
}
/****************************************************************************
*
* neSimulator::CreateSimulator
*
****************************************************************************/
neSimulator * neSimulator::CreateSimulator(const neSimulatorSizeInfo & sizeInfo, neAllocatorAbstract * alloc, const neV3 * grav)
{
neFixedTimeStepSimulator * s = new neFixedTimeStepSimulator(sizeInfo, alloc, grav);
return reinterpret_cast<neSimulator*>(s);
}
/****************************************************************************
*
* neSimulator::DestroySimulator(neSimulator * sim);
*
****************************************************************************/
void neSimulator::DestroySimulator(neSimulator * sim)
{
neFixedTimeStepSimulator * s = reinterpret_cast<neFixedTimeStepSimulator *>(sim);
delete s;
}
/****************************************************************************
*
* neSimulator::Gravity
*
****************************************************************************/
neV3 neSimulator::Gravity()
{
CAST_THIS(neFixedTimeStepSimulator, sim);
return sim.gravity;
}
/****************************************************************************
*
* neSimulator::Gravity
*
****************************************************************************/
void neSimulator::Gravity(const neV3 & g)
{
CAST_THIS(neFixedTimeStepSimulator, sim);
sim.SetGravity(g);
/*
sim.gravity = g;
sim.gravityVector = g;
sim.gravityVector.Normalize();
*/
}
/****************************************************************************
*
* neSimulator::CreateRigidBody
*
****************************************************************************/
neRigidBody * neSimulator::CreateRigidBody()
{
CAST_THIS(neFixedTimeStepSimulator, sim);
neRigidBody_ * ret = sim.CreateRigidBody();
return reinterpret_cast<neRigidBody *>(ret);
}
/****************************************************************************
*
* neSimulator::CreateRigidParticle
*
****************************************************************************/
neRigidBody * neSimulator::CreateRigidParticle()
{
CAST_THIS(neFixedTimeStepSimulator, sim);
neRigidBody_ * ret = sim.CreateRigidBody(true);
return reinterpret_cast<neRigidBody *>(ret);
}
/****************************************************************************
*
* neSimulator::CreateCollisionBody()
*
****************************************************************************/
neAnimatedBody * neSimulator::CreateAnimatedBody()
{
CAST_THIS(neFixedTimeStepSimulator, sim);
neCollisionBody_ * ret = sim.CreateCollisionBody();
return reinterpret_cast<neAnimatedBody *>(ret);
}
/****************************************************************************
*
* neSimulator::FreeBody
*
****************************************************************************/
void neSimulator::FreeRigidBody(neRigidBody * body)
{
CAST_THIS(neFixedTimeStepSimulator, sim);
sim.Free(reinterpret_cast<neRigidBody_*>(body));
}
/****************************************************************************
*
* neSimulator::FreeCollisionBody
*
****************************************************************************/
void neSimulator::FreeAnimatedBody(neAnimatedBody * body)
{
CAST_THIS(neFixedTimeStepSimulator, sim);
sim.Free(reinterpret_cast<neRigidBody_*>(body));
}
/****************************************************************************
*
* neSimulator::GetCollisionTable
*
****************************************************************************/
neCollisionTable * neSimulator::GetCollisionTable()
{
CAST_THIS(neFixedTimeStepSimulator, sim);
return (neCollisionTable *)(&sim.colTable);
}
/****************************************************************************
*
* neSimulator::GetMaterial
*
****************************************************************************/
bool neSimulator::SetMaterial(s32 index, f32 friction, f32 restitution)
{
CAST_THIS(neFixedTimeStepSimulator, sim);
return sim.SetMaterial(index, friction, restitution, 0.0f);
}
/****************************************************************************
*
* neSimulator::GetMaterial
*
****************************************************************************/
bool neSimulator::GetMaterial(s32 index, f32& friction, f32& restitution)
{
CAST_THIS(neFixedTimeStepSimulator, sim);
f32 density;
return sim.GetMaterial(index, friction, restitution, density);
}
/****************************************************************************
*
* neSimulator::Advance
*
****************************************************************************/
void neSimulator::Advance(f32 sec, s32 step, nePerformanceReport * perfReport)
{
CAST_THIS(neFixedTimeStepSimulator, sim);
sim.Advance(sec, step, perfReport);
}
void neSimulator::Advance(f32 sec, f32 minTimeStep, f32 maxTimeStep, nePerformanceReport * perfReport)
{
CAST_THIS(neFixedTimeStepSimulator, sim);
sim.Advance(sec, minTimeStep, maxTimeStep, perfReport);
}
/****************************************************************************
*
* neSimulator::SetTerrainMesh
*
****************************************************************************/
void neSimulator::SetTerrainMesh(neTriangleMesh * tris)
{
CAST_THIS(neFixedTimeStepSimulator, sim);
sim.SetTerrainMesh(tris);
}
void neSimulator::FreeTerrainMesh()
{
CAST_THIS(neFixedTimeStepSimulator, sim);
sim.FreeTerrainMesh();
}
/****************************************************************************
*
* neSimulator::CreateJoint
*
****************************************************************************/
neJoint * neSimulator::CreateJoint(neRigidBody * bodyA)
{
CAST_THIS(neFixedTimeStepSimulator, sim);
if (!bodyA)
return NULL;
_neConstraint * constr = sim.constraintHeap.Alloc(1); // 1 means make it solo
if (!constr)
{
sprintf(sim.logBuffer, MSG_CONSTRAINT_FULL);
sim.LogOutput(neSimulator::LOG_OUTPUT_LEVEL_ONE);
return NULL;
}
constr->Reset();
constr->sim = ∼
constr->bodyA = (neRigidBody_*)bodyA;
neRigidBody_ * ba = (neRigidBody_*)bodyA;
ba->constraintCollection.Add(&constr->bodyAHandle);
return reinterpret_cast<neJoint*>(constr);
}
/****************************************************************************
*
* neSimulator::CreateJoint
*
****************************************************************************/
neJoint * neSimulator::CreateJoint(neRigidBody * bodyA, neRigidBody * bodyB)
{
CAST_THIS(neFixedTimeStepSimulator, sim);
if (!bodyA)
return NULL;
if (!bodyB)
return NULL;
_neConstraint * constr = sim.constraintHeap.Alloc(1); // 1 means make it solo
if (!constr)
{
sprintf(sim.logBuffer, MSG_CONSTRAINT_FULL);
sim.LogOutput(neSimulator::LOG_OUTPUT_LEVEL_ONE);
return NULL;
}
constr->Reset();
constr->sim = ∼
constr->bodyA = (neRigidBody_*)bodyA;
neRigidBody_ * ba = (neRigidBody_*)bodyA;
ba->constraintCollection.Add(&constr->bodyAHandle);
constr->bodyB = (neRigidBodyBase*)bodyB;
neRigidBody_ * bb = (neRigidBody_*)bodyB;
bb->constraintCollection.Add(&constr->bodyBHandle);
return reinterpret_cast<neJoint*>(constr);
}
/****************************************************************************
*
* neSimulator::CreateJoint
*
****************************************************************************/
neJoint * neSimulator::CreateJoint(neRigidBody * bodyA, neAnimatedBody * bodyB)
{
CAST_THIS(neFixedTimeStepSimulator, sim);
if (!bodyA)
return NULL;
if (!bodyB)
return NULL;
_neConstraint * constr = sim.constraintHeap.Alloc(1); // 1 means make it solo
if (!constr)
{
sprintf(sim.logBuffer, MSG_CONSTRAINT_FULL);
sim.LogOutput(neSimulator::LOG_OUTPUT_LEVEL_ONE);
return NULL;
}
constr->Reset();
constr->sim = ∼
constr->bodyA = (neRigidBody_*)bodyA;
neRigidBody_ * ba = (neRigidBody_*)bodyA;
ba->constraintCollection.Add(&constr->bodyAHandle);
constr->bodyB = (neRigidBodyBase*)bodyB;
neRigidBodyBase * bb = (neRigidBodyBase*)bodyB;
bb->constraintCollection.Add(&constr->bodyBHandle);
return reinterpret_cast<neJoint*>(constr);
}
/****************************************************************************
*
* neSimulator::FreeJoint
*
****************************************************************************/
void neSimulator::FreeJoint(neJoint * constraint)
{
CAST_THIS(neFixedTimeStepSimulator, sim);
_neConstraint * c = (_neConstraint *)constraint;
ASSERT(sim.constraintHeap.CheckBelongAndInUse(c));
if (c->bodyA)
{
c->bodyA->constraintCollection.Remove(&c->bodyAHandle);
if (c->bodyB)
c->bodyB->constraintCollection.Remove(&c->bodyBHandle);
neConstraintHeader * h = c->bodyA->GetConstraintHeader();
if (h)
{
h->Remove(c);
h->flag = neConstraintHeader::FLAG_NEED_REORG;
}
sim.constraintHeap.Dealloc(c, 1);
if (c->bodyA->constraintCollection.count == 0)
c->bodyA->RemoveConstraintHeader();
if (c->bodyB &&
c->bodyB->constraintCollection.count == 0)
c->bodyB->RemoveConstraintHeader();
}
else
{
sim.constraintHeap.Dealloc(c, 1);
}
}
/****************************************************************************
*
* neSimulator::SetCollisionCallback
*
****************************************************************************/
void neSimulator::SetCollisionCallback(neCollisionCallback * fn)
{
CAST_THIS(neFixedTimeStepSimulator, sim);
sim.SetCollisionCallback(fn);
}
/****************************************************************************
*
* neSimulator::GetCollisionCallback
*
****************************************************************************/
neCollisionCallback * neSimulator::GetCollisionCallback()
{
CAST_THIS(neFixedTimeStepSimulator, sim);
return sim.collisionCallback;
}
/****************************************************************************
*
* neSimulator::SetBreakageCallback
*
****************************************************************************/
void neSimulator::SetBreakageCallback(neBreakageCallback * cb)
{
CAST_THIS(neFixedTimeStepSimulator, sim);
sim.breakageCallback = cb;
}
/****************************************************************************
*
* neSimulator::GetBreakageCallback
*
****************************************************************************/
neBreakageCallback * neSimulator::GetBreakageCallback()
{
CAST_THIS(neFixedTimeStepSimulator, sim);
return sim.breakageCallback;
}
/****************************************************************************
*
* neSimulator::SetTerrainTriangleQueryCallback
*
****************************************************************************/
void neSimulator::SetTerrainTriangleQueryCallback(neTerrainTriangleQueryCallback * cb)
{
CAST_THIS(neFixedTimeStepSimulator, sim);
sim.terrainQueryCallback = cb;
}
/****************************************************************************
*
* neSimulator::GetTerrainTriangleQueryCallback
*
****************************************************************************/
neTerrainTriangleQueryCallback * neSimulator::GetTerrainTriangleQueryCallback()
{
CAST_THIS(neFixedTimeStepSimulator, sim);
return sim.terrainQueryCallback;
}
/****************************************************************************
*
* neSimulator::SetCustomCDRB2RBCallback
*
****************************************************************************/
void neSimulator::SetCustomCDRB2RBCallback(neCustomCDRB2RBCallback * cb)
{
CAST_THIS(neFixedTimeStepSimulator, sim);
sim.customCDRB2RBCallback = cb;
}
/****************************************************************************
*
* neSimulator::GetCustomCDRB2RBCallback
*
****************************************************************************/
neCustomCDRB2RBCallback * neSimulator::GetCustomCDRB2RBCallback()
{
CAST_THIS(neFixedTimeStepSimulator, sim);
return sim.customCDRB2RBCallback;
}
/****************************************************************************
*
* neSimulator::SetCustomCDRB2ABCallback
*
****************************************************************************/
void neSimulator::SetCustomCDRB2ABCallback(neCustomCDRB2ABCallback * cb)
{
CAST_THIS(neFixedTimeStepSimulator, sim);
sim.customCDRB2ABCallback = cb;
}
/****************************************************************************
*
* neSimulator::GetCustomCDRB2ABCallback
*
****************************************************************************/
neCustomCDRB2ABCallback * neSimulator::GetCustomCDRB2ABCallback()
{
CAST_THIS(neFixedTimeStepSimulator, sim);
return sim.customCDRB2ABCallback;
}
/****************************************************************************
*
* neSimulator::SetLogOutputCallback
*
****************************************************************************/
void neSimulator::SetLogOutputCallback(neLogOutputCallback * fn)
{
CAST_THIS(neFixedTimeStepSimulator, sim);
sim.SetLogOutputCallback(fn);
}
/*
f32 neSimulator::GetMagicNumber()
{
CAST_THIS(neFixedTimeStepSimulator, sim);
return sim.magicNumber;
}
*/
/****************************************************************************
*
* neSimulator::GetLogOutputCallback
*
****************************************************************************/
neLogOutputCallback * neSimulator::GetLogOutputCallback()
{
CAST_THIS(neFixedTimeStepSimulator, sim);
return sim.logCallback;
}
/****************************************************************************
*
* neSimulator::SetLogOutputLevel
*
****************************************************************************/
void neSimulator::SetLogOutputLevel(LOG_OUTPUT_LEVEL lvl)
{
CAST_THIS(neFixedTimeStepSimulator, sim);
sim.SetLogOutputLevel(lvl);
}
/****************************************************************************
*
* neSimulator::GetCurrentSizeInfo
*
****************************************************************************/
neSimulatorSizeInfo neSimulator::GetCurrentSizeInfo()
{
CAST_THIS(neFixedTimeStepSimulator, sim);
neSimulatorSizeInfo ret;
ret.rigidBodiesCount = sim.rigidBodyHeap.GetUsedCount();
ret.animatedBodiesCount = sim.collisionBodyHeap.GetUsedCount();
ret.rigidParticleCount = sim.rigidParticleHeap.GetUsedCount();
ret.controllersCount = sim.controllerHeap.GetUsedCount();
ret.overlappedPairsCount = sim.region.overlappedPairs.GetUsedCount();
ret.geometriesCount = sim.geometryHeap.GetUsedCount();
ret.constraintsCount = sim.constraintHeap.GetUsedCount();
ret.constraintSetsCount = sim.constraintHeaders.GetUsedCount();
// ret.constraintBufferSize = sim.miniConstraintHeap.GetUsedCount();
ret.sensorsCount = sim.sensorHeap.GetUsedCount();
ret.terrainNodesStartCount = sim.region.terrainTree.nodes.GetUsedCount();
ret.terrainNodesGrowByCount = sim.sizeInfo.terrainNodesGrowByCount;
return ret;
}
/****************************************************************************
*
* neSimulator::GetStartSizeInfo
*
****************************************************************************/
neSimulatorSizeInfo neSimulator::GetStartSizeInfo()
{
CAST_THIS(neFixedTimeStepSimulator, sim);
return sim.sizeInfo;
}
/****************************************************************************
*
* neSimulator::GetMemoryUsage
*
****************************************************************************/
void neSimulator::GetMemoryAllocated(s32 & memoryAllocated)
{
CAST_THIS(neFixedTimeStepSimulator, sim);
sim.GetMemoryAllocated(memoryAllocated);
}
/****************************************************************************
*
* neJoint::SetType
*
****************************************************************************/
void neJoint::SetType(ConstraintType t)
{
CAST_THIS(_neConstraint, c);
c.SetType(t);
}
/****************************************************************************
*
* neJoint::GetType
*
****************************************************************************/
neJoint::ConstraintType neJoint::GetType()
{
CAST_THIS(_neConstraint, c);
return c.type;
}
/****************************************************************************
*
* neJoint::GetRigidBodyA
*
****************************************************************************/
neRigidBody * neJoint::GetRigidBodyA()
{
CAST_THIS(_neConstraint, c);
return reinterpret_cast<neRigidBody *>(c.bodyA);
}
/****************************************************************************
*
* neJoint::GetRigidBodyB
*
****************************************************************************/
neRigidBody * neJoint::GetRigidBodyB()
{
CAST_THIS(_neConstraint, c);
if (!c.bodyB)
return NULL;
if (c.bodyB->AsCollisionBody())
return NULL;
return reinterpret_cast<neRigidBody *>(c.bodyB);
}
/****************************************************************************
*
* neJoint::GetAnimatedBodyB
*
****************************************************************************/
neAnimatedBody * neJoint::GetAnimatedBodyB()
{
CAST_THIS(_neConstraint, c);
if (!c.bodyB)
return NULL;
if (c.bodyB->AsRigidBody())
return NULL;
return reinterpret_cast<neAnimatedBody *>(c.bodyB);
}
/****************************************************************************
*
* neJoint::SetJointFrameA
*
****************************************************************************/
void neJoint::SetJointFrameA(const neT3 & frameA)
{
CAST_THIS(_neConstraint, c);
c.frameA = frameA;
}
/****************************************************************************
*
* neJoint::SetJointFrameB
*
****************************************************************************/
void neJoint::SetJointFrameB(const neT3 & frameB)
{
CAST_THIS(_neConstraint, c);
c.frameB = frameB;
}
void neJoint::SetJointFrameWorld(const neT3 & frame)
{
CAST_THIS(_neConstraint, c);
neT3 w2b;
w2b = c.bodyA->GetB2W().FastInverse();
c.frameA = w2b * frame;
if (!c.bodyB)
{
c.frameB = frame;
return;
}
w2b = c.bodyB->GetB2W().FastInverse();
c.frameB = w2b * frame;
}
/****************************************************************************
*
* neJoint::GetJointFrameA
*
****************************************************************************/
neT3 neJoint::GetJointFrameA()
{
CAST_THIS(_neConstraint, c);
if (!c.bodyA)
{
return c.frameA;
}
neT3 ret;
ret = c.bodyA->State().b2w * c.frameA;
return ret;
}
/****************************************************************************
*
* neJoint::GetJointFrameB
*
****************************************************************************/
neT3 neJoint::GetJointFrameB()
{
CAST_THIS(_neConstraint, c);
if (!c.bodyB)
{
return c.frameB;
}
neT3 ret;
neCollisionBody_ * cb = c.bodyB->AsCollisionBody();
if (cb)
{
ret = cb->b2w * c.frameB;
}
else
{
neRigidBody_ * rb = c.bodyB->AsRigidBody();
ret = rb->State().b2w * c.frameB;
}
return ret;
}
/****************************************************************************
*
* neJoint::SetJointLength
*
****************************************************************************/
void neJoint::SetJointLength(f32 length)
{
CAST_THIS(_neConstraint, c);
c.jointLength = length;
}
/****************************************************************************
*
* neJoint::GetJointLength
*
****************************************************************************/
f32 neJoint::GetJointLength()
{
CAST_THIS(_neConstraint, c);
return c.jointLength;
}
/****************************************************************************
*
* neJoint::Enable
*
****************************************************************************/
void neJoint::Enable(neBool yes)
{
CAST_THIS(_neConstraint, c);
c.Enable(yes);
}
/****************************************************************************
*
* neJoint::IsEnable
*
****************************************************************************/
neBool neJoint::Enable()
{
CAST_THIS(_neConstraint, c);
return c.enable;
}
/****************************************************************************
*
* neJoint::InfiniteMassB
*
****************************************************************************/
/*
void neJoint::InfiniteMassB(neBool yes)
{
CAST_THIS(_neConstraint, c);
c.InfiniteMassB(yes);
}
*/
/****************************************************************************
*
* neJoint::SetDampingFactor
*
****************************************************************************/
void neJoint::SetDampingFactor(f32 damp)
{
CAST_THIS(_neConstraint, c);
c.jointDampingFactor = damp;
}
/****************************************************************************
*
* neJoint::GetDampingFactor
*
****************************************************************************/
f32 neJoint::GetDampingFactor()
{
CAST_THIS(_neConstraint, c);
return c.jointDampingFactor;
}
/****************************************************************************
*
* neJoint::SetEpsilon
*
****************************************************************************/
void neJoint::SetEpsilon(f32 t)
{
CAST_THIS(_neConstraint, c);
c.accuracy = t;
}
/****************************************************************************
*
* neJoint::GetEpsilon
*
****************************************************************************/
f32 neJoint::GetEpsilon()
{
CAST_THIS(_neConstraint, c);
if (c.accuracy <= 0.0f)
return DEFAULT_CONSTRAINT_EPSILON;
return c.accuracy;
}
/****************************************************************************
*
* neJoint::SetIteration2
*
****************************************************************************/
void neJoint::SetIteration(s32 i)
{
CAST_THIS(_neConstraint, c);
c.iteration = i;
}
/****************************************************************************
*
* neJoint::GetIteration2
*
****************************************************************************/
s32 neJoint::GetIteration()
{
CAST_THIS(_neConstraint, c);
return c.iteration;
}
/****************************************************************************
*
* neJoint::GetUpperLimit
*
****************************************************************************/
f32 neJoint::GetUpperLimit()
{
CAST_THIS(_neConstraint, c);
return c.limitStates[0].upperLimit;
}
/****************************************************************************
*
* neJoint::SetUpperLimit
*
****************************************************************************/
void neJoint::SetUpperLimit(f32 upperLimit)
{
CAST_THIS(_neConstraint, c);
c.limitStates[0].upperLimit = upperLimit;
}
/****************************************************************************
*
* neJoint::GetLowerLimit
*
****************************************************************************/
f32 neJoint::GetLowerLimit()
{
CAST_THIS(_neConstraint, c);
return c.limitStates[0].lowerLimit;
}
/****************************************************************************
*
* neJoint::SetLowerLimit
*
****************************************************************************/
void neJoint::SetLowerLimit(f32 lowerLimit)
{
CAST_THIS(_neConstraint, c);
c.limitStates[0].lowerLimit = lowerLimit;
}
/****************************************************************************
*
* neJoint::IsEnableLimit
*
****************************************************************************/
neBool neJoint::EnableLimit()
{
CAST_THIS(_neConstraint, c);
return c.limitStates[0].enableLimit;
}
/****************************************************************************
*
* neJoint::EnableLimite
*
****************************************************************************/
void neJoint::EnableLimit(neBool yes)
{
CAST_THIS(_neConstraint, c);
c.limitStates[0].enableLimit = yes;
}
/****************************************************************************
*
* neJoint::GetUpperLimit2
*
****************************************************************************/
f32 neJoint::GetUpperLimit2()
{
CAST_THIS(_neConstraint, c);
return c.limitStates[1].upperLimit;
}
/****************************************************************************
*
* neJoint::SetUpperLimit2
*
****************************************************************************/
void neJoint::SetUpperLimit2(f32 upperLimit)
{
CAST_THIS(_neConstraint, c);
c.limitStates[1].upperLimit = upperLimit;
}
/****************************************************************************
*
* neJoint::GetLowerLimit2
*
****************************************************************************/
f32 neJoint::GetLowerLimit2()
{
CAST_THIS(_neConstraint, c);
return c.limitStates[1].lowerLimit;
}
/****************************************************************************
*
* neJoint::SetLowerLimit2
*
****************************************************************************/
void neJoint::SetLowerLimit2(f32 lowerLimit)
{
CAST_THIS(_neConstraint, c);
c.limitStates[1].lowerLimit = lowerLimit;
}
/****************************************************************************
*
* neJoint::IsEnableLimit2
*
****************************************************************************/
neBool neJoint::EnableLimit2()
{
CAST_THIS(_neConstraint, c);
return c.limitStates[1].enableLimit;
}
/****************************************************************************
*
* neJoint::EnableMotor
*
****************************************************************************/
neBool neJoint::EnableMotor()
{
CAST_THIS(_neConstraint, c);
return c.motors[0].enable;
}
/****************************************************************************
*
* neJoint::EnableMotor
*
****************************************************************************/
void neJoint::EnableMotor(neBool yes)
{
CAST_THIS(_neConstraint, c);
c.motors[0].enable = yes;
}
/****************************************************************************
*
* neJoint::SetMotor
*
****************************************************************************/
void neJoint::SetMotor(MotorType motorType, f32 desireValue, f32 maxForce)
{
CAST_THIS(_neConstraint, c);
c.motors[0].motorType = motorType;
c.motors[0].desireVelocity = desireValue;
c.motors[0].maxForce = neAbs(maxForce);
}
/****************************************************************************
*
* neJoint::GetMotor
*
****************************************************************************/
void neJoint::GetMotor(MotorType & motorType, f32 & desireValue, f32 & maxForce)
{
CAST_THIS(_neConstraint, c);
motorType = c.motors[0].motorType;
desireValue = c.motors[0].desireVelocity;
maxForce = c.motors[0].maxForce;
}
/****************************************************************************
*
* neJoint::EnableMotor2
*
****************************************************************************/
neBool neJoint::EnableMotor2()
{
CAST_THIS(_neConstraint, c);
return c.motors[1].enable;
}
/****************************************************************************
*
* neJoint::EnableMotor2
*
****************************************************************************/
void neJoint::EnableMotor2(neBool yes)
{
CAST_THIS(_neConstraint, c);
c.motors[1].enable = yes;
}
/****************************************************************************
*
* neJoint::SetMotor2
*
****************************************************************************/
void neJoint::SetMotor2(MotorType motorType, f32 desireValue, f32 maxForce)
{
CAST_THIS(_neConstraint, c);
c.motors[1].motorType = motorType;
c.motors[1].desireVelocity = desireValue;
c.motors[1].maxForce = neAbs(maxForce);
}
/****************************************************************************
*
* neJoint::GetMotor2
*
****************************************************************************/
void neJoint::GetMotor2(MotorType & motorType, f32 & desireValue, f32 & maxForce)
{
CAST_THIS(_neConstraint, c);
motorType = c.motors[1].motorType;
desireValue = c.motors[1].desireVelocity;
maxForce = c.motors[1].maxForce;
}
/****************************************************************************
*
* neJoint::EnableLimite
*
****************************************************************************/
void neJoint::EnableLimit2(neBool yes)
{
CAST_THIS(_neConstraint, c);
c.limitStates[1].enableLimit = yes;
}
/****************************************************************************
*
* neJoint::AddController
*
****************************************************************************/
neJointController * neJoint::AddController(neJointControllerCallback * controller, s32 period)
{
CAST_THIS(_neConstraint, c);
return (neJointController *)c.AddController(controller, period);
}
/****************************************************************************
*
* neJoint::RemoveController
*
****************************************************************************/
neBool neJoint::RemoveController(neJointController * jController)
{
CAST_THIS(_neConstraint, c);
if (!c.controllers)
return false;
neControllerItem * ci = (neControllerItem *)c.controllers;
while (ci)
{
neController * con = reinterpret_cast<neController *>(ci);
ci = ci->next;
if (con == reinterpret_cast<neController *>(jController))
{
//reinterpret_cast<neControllerItem *>(con)->Remove();
c.sim->controllerHeap.Dealloc(con, 1);
return true;
}
}
return false;
}
/****************************************************************************
*
* neJoint::BeginIterateController
*
****************************************************************************/
void neJoint::BeginIterateController()
{
CAST_THIS(_neConstraint, c);
c.BeginIterateController();
}
/****************************************************************************
*
* neJoint::GetNextController
*
****************************************************************************/
neJointController * neJoint::GetNextController()
{
CAST_THIS(_neConstraint, c);
return (neJointController *)c.GetNextController();
}
/****************************************************************************
*
* neJoint::SetBSPoints
*
****************************************************************************/
/*
neBool neJoint::SetBSPoints(const neV3 & pointA, const neV3 & pointB)
{
CAST_THIS(_neConstraint, c);
if (c.type != NE_Constraint_BALLSOCKET)
return false;
c.cpointsA[0].PtBody() = pointA;
c.cpointsB[0].PtBody() = pointB;
return true;
}
*/
/****************************************************************************
*
* neJoint::SetHingePoints
*
****************************************************************************/
/*
neBool neJoint::SetHingePoints(const neV3 & pointA1, const neV3 & pointA2,
const neV3 & pointB1, const neV3 & pointB2)
{
CAST_THIS(_neConstraint, c);
if (c.type != NE_Constraint_HINGE)
return false;
c.cpointsA[0].PtBody() = pointA1;
c.cpointsA[1].PtBody() = pointA2;
c.cpointsB[0].PtBody() = pointB1;
c.cpointsB[1].PtBody() = pointB2;
return true;
}
*/
/****************************************************************************
*
* neSensor::SetLineSensor
*
****************************************************************************/
void neSensor::SetLineSensor(const neV3 & pos, const neV3 & lineVector)
{
CAST_THIS(neSensor_, sensor);
sensor.pos = pos;
sensor.dir = lineVector;
sensor.dirNormal = lineVector;
sensor.dirNormal.Normalize();
sensor.length = lineVector.Length();
}
/****************************************************************************
*
* neSensor::SetUserData
*
****************************************************************************/
void neSensor::SetUserData(u32 cookies)
{
CAST_THIS(neSensor_, sensor);
sensor.cookies = cookies;
}
/****************************************************************************
*
* neSensor::GetUserData
*
****************************************************************************/
u32 neSensor::GetUserData()
{
CAST_THIS(neSensor_, sensor);
return sensor.cookies;
}
/****************************************************************************
*
* neSensor::GetLineNormal
*
****************************************************************************/
neV3 neSensor::GetLineVector()
{
CAST_THIS(neSensor_, sensor);
return sensor.dir;
}
/****************************************************************************
*
* neSensor::GetLineNormal
*
****************************************************************************/
neV3 neSensor::GetLineUnitVector()
{
CAST_THIS(neSensor_, sensor);
return sensor.dirNormal ;
}
/****************************************************************************
*
* neSensor::GetLinePos
*
****************************************************************************/
neV3 neSensor::GetLinePos()
{
CAST_THIS(neSensor_, sensor);
return sensor.pos;
}
/****************************************************************************
*
* neSensor::GetDetectDepth
*
****************************************************************************/
f32 neSensor::GetDetectDepth()
{
CAST_THIS(neSensor_, sensor);
return sensor.depth;
}
/****************************************************************************
*
* neSensor::GetDetectNormal
*
****************************************************************************/
neV3 neSensor::GetDetectNormal()
{
CAST_THIS(neSensor_, sensor);
return sensor.normal;
}
/****************************************************************************
*
* neSensor::GetDetectContactPoint
*
****************************************************************************/
neV3 neSensor::GetDetectContactPoint()
{
CAST_THIS(neSensor_, sensor);
return sensor.contactPoint;
}
/****************************************************************************
*
* neSensor::GetDetectRigidBody
*
****************************************************************************/
neRigidBody * neSensor::GetDetectRigidBody()
{
CAST_THIS(neSensor_, sensor);
if (!sensor.body)
return NULL;
if (sensor.body->AsCollisionBody())
return NULL;
return (neRigidBody *)sensor.body;
}
/****************************************************************************
*
* neSensor::GetDetectAnimatedBody
*
****************************************************************************/
neAnimatedBody * neSensor::GetDetectAnimatedBody()
{
CAST_THIS(neSensor_, sensor);
if (!sensor.body)
return NULL;
if (sensor.body->AsRigidBody())
return NULL;
return (neAnimatedBody *)sensor.body;
}
/****************************************************************************
*
* neSensor::
*
****************************************************************************/
s32 neSensor::GetDetectMaterial()
{
CAST_THIS(neSensor_, sensor);
return sensor.materialID;
}
/****************************************************************************
*
* neRigidBodyController::
*
****************************************************************************/
neRigidBody * neRigidBodyController::GetRigidBody()
{
CAST_THIS(neController, c);
return (neRigidBody *)c.rb;
}
/****************************************************************************
*
* neRigidBodyController::
*
****************************************************************************/
neV3 neRigidBodyController::GetControllerForce()
{
CAST_THIS(neController, c);
return c.forceA;
}
/****************************************************************************
*
* neRigidBodyController::
*
****************************************************************************/
neV3 neRigidBodyController::GetControllerTorque()
{
CAST_THIS(neController, c);
return c.torqueA;
}
/****************************************************************************
*
* neRigidBodyController::
*
****************************************************************************/
void neRigidBodyController::SetControllerForce(const neV3 & force)
{
CAST_THIS(neController, c);
c.forceA = force;
}
/****************************************************************************
*
* neRigidBodyController::
*
****************************************************************************/
void neRigidBodyController::SetControllerForceWithTorque(const neV3 & force, const neV3 & pos)
{
CAST_THIS(neController, c);
c.forceA = force;
c.torqueA = ((pos - c.rb->GetPos()).Cross(force));
}
/****************************************************************************
*
* neRigidBodyController::
*
****************************************************************************/
void neRigidBodyController::SetControllerTorque(const neV3 & torque)
{
CAST_THIS(neController, c);
c.torqueA = torque;
}
/****************************************************************************
*
* neJointController::
*
****************************************************************************/
neJoint * neJointController::GetJoint()
{
CAST_THIS(neController, c);
return (neJoint *)c.constraint;
}
/****************************************************************************
*
* neJointController::
*
****************************************************************************/
neV3 neJointController::GetControllerForceBodyA()
{
CAST_THIS(neController, c);
return c.forceA;
}
/****************************************************************************
*
* neJointController::
*
****************************************************************************/
neV3 neJointController::GetControllerForceBodyB()
{
CAST_THIS(neController, c);
return c.forceB;
}
/****************************************************************************
*
* neJointController::
*
****************************************************************************/
neV3 neJointController::GetControllerTorqueBodyA()
{
CAST_THIS(neController, c);
return c.torqueA;
}
/****************************************************************************
*
* neJointController::
*
****************************************************************************/
neV3 neJointController::GetControllerTorqueBodyB()
{
CAST_THIS(neController, c);
return c.torqueB;
}
/****************************************************************************
*
* neJointController::
*
****************************************************************************/
void neJointController::SetControllerForceBodyA(const neV3 & force)
{
CAST_THIS(neController, c);
c.forceA = force;
}
/****************************************************************************
*
* neJointController::
*
****************************************************************************/
void neJointController::SetControllerForceWithTorqueBodyA(const neV3 & force, const neV3 & pos)
{
CAST_THIS(neController, c);
c.forceA = force;
c.torqueA = ((pos - c.constraint->bodyA->GetPos()).Cross(force));
}
/****************************************************************************
*
* neJointController::
*
****************************************************************************/
void neJointController::SetControllerForceWithTorqueBodyB(const neV3 & force, const neV3 & pos)
{
CAST_THIS(neController, c);
c.forceB = force;
if (c.constraint->bodyB &&
!c.constraint->bodyB->AsCollisionBody())
{
neRigidBody_ * rb = (neRigidBody_*)c.constraint->bodyB;
c.torqueB = ((pos - rb->GetPos()).Cross(force));
}
}
/****************************************************************************
*
* neJointController::
*
****************************************************************************/
void neJointController::SetControllerForceBodyB(const neV3 & force)
{
CAST_THIS(neController, c);
c.forceB = force;
}
/****************************************************************************
*
* neJointController::
*
****************************************************************************/
void neJointController::SetControllerTorqueBodyA(const neV3 & torque)
{
CAST_THIS(neController, c);
c.torqueA = torque;
}
/****************************************************************************
*
* neJointController::
*
****************************************************************************/
void neJointController::SetControllerTorqueBodyB(const neV3 & torque)
{
CAST_THIS(neController, c);
c.torqueB = torque;
}
/****************************************************************************
*
* neCollisionTable::Set
*
****************************************************************************/
void neCollisionTable::Set(s32 collisionID1, s32 collisionID2, neReponseBitFlag response)
{
CAST_THIS(neCollisionTable_, ct);
ct.Set(collisionID1, collisionID2, response);
}
/****************************************************************************
*
* neCollisionTable::Get
*
****************************************************************************/
neCollisionTable::neReponseBitFlag neCollisionTable::Get(s32 collisionID1, s32 collisionID2)
{
CAST_THIS(neCollisionTable_, ct);
ASSERT(collisionID1 < NE_COLLISION_TABLE_MAX);
ASSERT(collisionID2 < NE_COLLISION_TABLE_MAX);
if (collisionID1 < NE_COLLISION_TABLE_MAX && collisionID2 < NE_COLLISION_TABLE_MAX)
{
return ct.table[collisionID1][collisionID2];
}
else
{
return RESPONSE_IGNORE;
}
}
/****************************************************************************
*
* neCollisionTable::GetMaxCollisionID
*
****************************************************************************/
s32 neCollisionTable::GetMaxCollisionID()
{
return NE_COLLISION_TABLE_MAX;
}
/****************************************************************************
*
* Helper functions
*
****************************************************************************/
/****************************************************************************
*
* BoxInertiaTensor
*
****************************************************************************/
neV3 neBoxInertiaTensor(const neV3 & boxSize, f32 mass)
{
return neBoxInertiaTensor(boxSize[0], boxSize[1], boxSize[2], mass);
}
neV3 neBoxInertiaTensor(f32 width, f32 height, f32 depth, f32 mass)
{
neV3 ret;
f32 maxdim = width;
if (height > maxdim)
maxdim = height;
if (depth > maxdim)
maxdim = depth;
#if 0
f32 xsq = width;
f32 ysq = height;
f32 zsq = depth;
#else
f32 xsq = maxdim;
f32 ysq = maxdim;
f32 zsq = maxdim;
#endif
xsq *= xsq;
ysq *= ysq;
zsq *= zsq;
ret[0] = (ysq + zsq) * mass / 3.0f;
ret[1] = (xsq + zsq) * mass / 3.0f;
ret[2] = (xsq + ysq) * mass / 3.0f;
return ret;
}
neV3 neSphereInertiaTensor(f32 diameter, f32 mass)
{
f32 radius = diameter * 0.5f;
f32 value = 2.0f / 5.0f * mass * radius * radius;
neV3 ret;
ret.Set(value);
return ret;
}
neV3 neCylinderInertiaTensor(f32 diameter, f32 height, f32 mass)
{
// if (height > diameter)
// {
// diameter = height;
// }
f32 radius = diameter * 0.5f;
f32 radiusSq = radius * radius;
f32 Ixz = 1.0f / 12.0f * mass * height * height + 0.25f * mass * radiusSq;
f32 Iyy = 0.5f * mass * radiusSq;
neV3 ret;
ret.Set(Ixz, Iyy, Ixz);
return ret;
}
/*
neBool IsEnableLimit();
void EnableLimit(neBool yes);
f32 GetUpperLimit();
void SetUpperLimit(f32 upperLimit);
f32 GetLowerLimit();
void SetLowerLimit(f32 lowerLimit);
*/ | 90,628 | 28,627 |
// Copyright 2020 Tier IV, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2009, Willow Garage, 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:
*
* * 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 Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* $Id: voxel_grid.cpp 35876 2011-02-09 01:04:36Z rusu $
*
*/
#include "pointcloud_preprocessor/downsample_filter/voxel_grid_downsample_filter_nodelet.hpp"
#include <pcl/kdtree/kdtree_flann.h>
#include <pcl/search/kdtree.h>
#include <pcl/segmentation/segment_differences.h>
#include <vector>
namespace pointcloud_preprocessor
{
VoxelGridDownsampleFilterComponent::VoxelGridDownsampleFilterComponent(
const rclcpp::NodeOptions & options)
: Filter("VoxelGridDownsampleFilter", options)
{
// set initial parameters
{
voxel_size_x_ = static_cast<double>(declare_parameter("voxel_size_x", 0.3));
voxel_size_y_ = static_cast<double>(declare_parameter("voxel_size_y", 0.3));
voxel_size_z_ = static_cast<double>(declare_parameter("voxel_size_z", 0.1));
}
using std::placeholders::_1;
set_param_res_ = this->add_on_set_parameters_callback(
std::bind(&VoxelGridDownsampleFilterComponent::paramCallback, this, _1));
}
void VoxelGridDownsampleFilterComponent::filter(
const PointCloud2ConstPtr & input, const IndicesPtr & /*indices*/, PointCloud2 & output)
{
std::scoped_lock lock(mutex_);
pcl::PointCloud<pcl::PointXYZ>::Ptr pcl_input(new pcl::PointCloud<pcl::PointXYZ>);
pcl::PointCloud<pcl::PointXYZ>::Ptr pcl_output(new pcl::PointCloud<pcl::PointXYZ>);
pcl::fromROSMsg(*input, *pcl_input);
pcl_output->points.reserve(pcl_input->points.size());
pcl::VoxelGrid<pcl::PointXYZ> filter;
filter.setInputCloud(pcl_input);
// filter.setSaveLeafLayout(true);
filter.setLeafSize(voxel_size_x_, voxel_size_y_, voxel_size_z_);
filter.filter(*pcl_output);
pcl::toROSMsg(*pcl_output, output);
output.header = input->header;
}
rcl_interfaces::msg::SetParametersResult VoxelGridDownsampleFilterComponent::paramCallback(
const std::vector<rclcpp::Parameter> & p)
{
std::scoped_lock lock(mutex_);
if (get_param(p, "voxel_size_x", voxel_size_x_)) {
RCLCPP_DEBUG(get_logger(), "Setting new distance threshold to: %f.", voxel_size_x_);
}
if (get_param(p, "voxel_size_y", voxel_size_y_)) {
RCLCPP_DEBUG(get_logger(), "Setting new distance threshold to: %f.", voxel_size_y_);
}
if (get_param(p, "voxel_size_z", voxel_size_z_)) {
RCLCPP_DEBUG(get_logger(), "Setting new distance threshold to: %f.", voxel_size_z_);
}
rcl_interfaces::msg::SetParametersResult result;
result.successful = true;
result.reason = "success";
return result;
}
} // namespace pointcloud_preprocessor
#include <rclcpp_components/register_node_macro.hpp>
RCLCPP_COMPONENTS_REGISTER_NODE(pointcloud_preprocessor::VoxelGridDownsampleFilterComponent)
| 4,851 | 1,762 |
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file
#include "catch.hpp"
#include "SceneTrackStatic.h"
#include "TestCommon.h"
#include "tinydir/tinydir.h"
#include "TestCRC.h"
typedef uint8_t u8;
typedef uint16_t u16;
typedef uint32_t u32;
typedef uint64_t u64;
typedef int8_t s8;
typedef int16_t s16;
typedef int32_t s32;
typedef int64_t s64;
typedef float f32;
typedef double f64;
typedef u8 stByte;
struct SoundClass
{
u32 type;
u32 speaker;
u32 volume;
u32 length;
};
struct SpeakerClass
{
u32 type;
u32 position;
};
typedef u32 Speaker;
typedef u32 Sound;
SCENARIO("Events")
{
u32 recording = stCreateRecording();
stAppendSaveRecording("events.st", ST_FORMAT_BINARY, 2);
SoundClass soundClass;
soundClass.type = stCreateObjectType(ST_FREQUENCY_EVENT);
soundClass.speaker = stAddObjectTypeComponent(soundClass.type, ST_KIND_PARENT, ST_TYPE_UINT32, 1);
soundClass.volume = stAddObjectTypeComponent(soundClass.type, ST_KIND_INTENSITY, ST_TYPE_FLOAT32, 1);
soundClass.length = stAddObjectTypeComponent(soundClass.type, ST_KIND_LENGTH, ST_TYPE_FLOAT32, 1);
SpeakerClass speakerClass;
speakerClass.type = stCreateObjectType(ST_FREQUENCY_DYNAMIC);
speakerClass.position = stAddObjectTypeComponent(speakerClass.type, ST_KIND_POSITION, ST_TYPE_FLOAT32, 3);
Speaker speaker = stCreateObject(speakerClass.type);
stSetValue_3_float32(speaker, speakerClass.position, 3.0f, 4.0f, 5.0f);
Sound sound1 = stCreateObject(soundClass.type);
stSetValue_uint32(sound1, soundClass.speaker, speaker);
stSubmit(1.0f);
Sound sound2 = stCreateObject(soundClass.type);
stSetValue_uint32(sound2, soundClass.speaker, speaker);
stSubmit(1.0f);
stCloseRecording(recording);
}
| 1,822 | 755 |
//Copyright (c) 2016 Artem A. Mavrin and other contributors
#include "DialogueSystemPrivatePCH.h"
#include "BTComposite_Context.h"
UBTComposite_Context::UBTComposite_Context(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer)
{
NodeName = "Context";
ExecutionMode = EContextExecutionMode::CE_Sequence;
OnNextChild.BindUObject(this, &UBTComposite_Context::GetNextChildHandler);
}
bool UBTComposite_Context::VerifyExecution(EBTNodeResult::Type LastResult) const
{
if (ExecutionMode == EContextExecutionMode::CE_Sequence)
return LastResult == EBTNodeResult::Succeeded;
else return LastResult == EBTNodeResult::Failed;
}
int32 UBTComposite_Context::GetNextChildHandler(struct FBehaviorTreeSearchData& SearchData, int32 PrevChild, EBTNodeResult::Type LastResult) const
{
int32 NextChildIdx = BTSpecialChild::ReturnToParent;
if (PrevChild == BTSpecialChild::NotInitialized)
{
NextChildIdx = 0;
}
else if (VerifyExecution(LastResult) && (PrevChild + 1) < GetChildrenNum())
{
NextChildIdx = PrevChild + 1;
}
return NextChildIdx;
}
#if WITH_EDITOR
FName UBTComposite_Context::GetNodeIconName() const
{
return FName("BTEditor.Graph.BTNode.Decorator.DoesPathExist.Icon");
}
#endif
FString UBTComposite_Context::GetStaticDescription() const
{
FString Description = "";
Description += (ExecutionMode == EContextExecutionMode::CE_Sequence) ? TEXT("Sequence \n\n") : TEXT("Selector \n\n");
for (const FBTDialogueParameter& DialogueParameter : DialogueParameters)
Description += DialogueParameter.StringKey + " : " + DialogueParameter.BlackboardKey.SelectedKeyName.ToString() + TEXT(" \n");
return Description;
}
void UBTComposite_Context::PushArguments(FFormatNamedArguments& DialogueArguments, UBlackboardComponent * Blackboard) const
{
for (const FBTDialogueParameter& DialogueParameter : DialogueParameters)
DialogueParameter.PushArgument(DialogueArguments, Blackboard);
}
| 1,929 | 651 |
#include "mp2v_hdr.h"
#include "misc.hpp"
bool write_sequence_header(bitstream_writer_c* m_bs, sequence_header_t &sh) {
m_bs->align();
m_bs->write_bits(START_CODE(sequence_header_code), 32);
m_bs->write_bits(sh.horizontal_size_value, 12);
m_bs->write_bits(sh.vertical_size_value, 12);
m_bs->write_bits(sh.aspect_ratio_information, 4);
m_bs->write_bits(sh.frame_rate_code, 4);
m_bs->write_bits(sh.bit_rate_value, 18);
m_bs->one_bit();
m_bs->write_bits(sh.vbv_buffer_size_value, 10);
m_bs->write_bits(sh.constrained_parameters_flag, 1);
m_bs->write_bits(sh.load_intra_quantiser_matrix, 1);
if (sh.load_intra_quantiser_matrix)
local_write_array<uint8_t, 64>(m_bs, sh.intra_quantiser_matrix);
m_bs->write_bits(sh.load_non_intra_quantiser_matrix, 1);
if (sh.load_non_intra_quantiser_matrix)
local_write_array<uint8_t, 64>(m_bs, sh.non_intra_quantiser_matrix);
return true;
}
bool write_sequence_extension(bitstream_writer_c* m_bs, sequence_extension_t &sext) {
m_bs->align();
m_bs->write_bits(START_CODE(extension_start_code), 32);
m_bs->write_bits(sequence_extension_id, 4);
m_bs->write_bits(sext.profile_and_level_indication, 8);
m_bs->write_bits(sext.progressive_sequence, 1);
m_bs->write_bits(sext.chroma_format, 2);
m_bs->write_bits(sext.horizontal_size_extension, 2);
m_bs->write_bits(sext.vertical_size_extension, 2);
m_bs->write_bits(sext.bit_rate_extension, 12);
m_bs->one_bit();
m_bs->write_bits(sext.vbv_buffer_size_extension, 8);
m_bs->write_bits(sext.low_delay, 1);
m_bs->write_bits(sext.frame_rate_extension_n, 2);
m_bs->write_bits(sext.frame_rate_extension_d, 5);
return true;
}
bool write_sequence_display_extension(bitstream_writer_c* m_bs, sequence_display_extension_t & sdext) {
m_bs->align();
m_bs->write_bits(START_CODE(extension_start_code), 32);
m_bs->write_bits(sequence_display_extension_id, 4);
m_bs->write_bits(sdext.video_format, 3);
m_bs->write_bits(sdext.colour_description, 1);
if (sdext.colour_description) {
m_bs->write_bits(sdext.colour_primaries, 8);
m_bs->write_bits(sdext.transfer_characteristics, 8);
m_bs->write_bits(sdext.matrix_coefficients, 8);
}
m_bs->write_bits(sdext.display_horizontal_size, 14);
m_bs->one_bit();
m_bs->write_bits(sdext.display_vertical_size, 14);
return true;
}
bool write_sequence_scalable_extension(bitstream_writer_c* m_bs, sequence_scalable_extension_t &ssext) {
m_bs->align();
m_bs->write_bits(START_CODE(extension_start_code), 32);
m_bs->write_bits(sequence_scalable_extension_id, 4);
m_bs->write_bits(ssext.scalable_mode, 2);
m_bs->write_bits(ssext.layer_id, 4);
if (ssext.scalable_mode == scalable_mode_spatial_scalability) {
m_bs->write_bits(ssext.lower_layer_prediction_horizontal_size, 14);
m_bs->one_bit();
m_bs->write_bits(ssext.lower_layer_prediction_vertical_size, 14);
m_bs->write_bits(ssext.horizontal_subsampling_factor_m, 5);
m_bs->write_bits(ssext.horizontal_subsampling_factor_n, 5);
m_bs->write_bits(ssext.vertical_subsampling_factor_m, 5);
m_bs->write_bits(ssext.vertical_subsampling_factor_n, 5);
}
if (ssext.scalable_mode == scalable_mode_temporal_scalability) {
m_bs->write_bits(ssext.picture_mux_enable, 1);
if (ssext.picture_mux_enable)
m_bs->write_bits(ssext.mux_to_progressive_sequence, 1);
m_bs->write_bits(ssext.picture_mux_order, 3);
m_bs->write_bits(ssext.picture_mux_factor, 3);
}
return true;
}
bool write_group_of_pictures_header(bitstream_writer_c* m_bs, group_of_pictures_header_t &gph) {
m_bs->align();
m_bs->write_bits(START_CODE(group_start_code), 32);
m_bs->write_bits(gph.time_code, 25);
m_bs->write_bits(gph.closed_gop, 1);
m_bs->write_bits(gph.broken_link, 1);
return true;
}
bool write_picture_header(bitstream_writer_c* m_bs, picture_header_t & ph) {
m_bs->align();
m_bs->write_bits(START_CODE(picture_start_code), 32);
m_bs->write_bits(ph.temporal_reference, 10);
m_bs->write_bits(ph.picture_coding_type, 3);
m_bs->write_bits(ph.vbv_delay, 16);
if (ph.picture_coding_type == 2 || ph.picture_coding_type == 3) {
m_bs->write_bits(ph.full_pel_forward_vector, 1);
m_bs->write_bits(ph.forward_f_code, 3);
}
if (ph.picture_coding_type == 3) {
m_bs->write_bits(ph.full_pel_backward_vector, 1);
m_bs->write_bits(ph.backward_f_code, 3);
}
m_bs->zero_bit(); // skip all extra_information_picture
return true;
}
bool write_picture_coding_extension(bitstream_writer_c* m_bs, picture_coding_extension_t &pcext) {
m_bs->align();
m_bs->write_bits(START_CODE(extension_start_code), 32);
m_bs->write_bits(picture_coding_extension_id, 4);
m_bs->write_bits(pcext.f_code[0][0], 4);
m_bs->write_bits(pcext.f_code[0][1], 4);
m_bs->write_bits(pcext.f_code[1][0], 4);
m_bs->write_bits(pcext.f_code[1][1], 4);
m_bs->write_bits(pcext.intra_dc_precision, 2);
m_bs->write_bits(pcext.picture_structure, 2);
m_bs->write_bits(pcext.top_field_first, 1);
m_bs->write_bits(pcext.frame_pred_frame_dct, 1);
m_bs->write_bits(pcext.concealment_motion_vectors, 1);
m_bs->write_bits(pcext.q_scale_type, 1);
m_bs->write_bits(pcext.intra_vlc_format, 1);
m_bs->write_bits(pcext.alternate_scan, 1);
m_bs->write_bits(pcext.repeat_first_field, 1);
m_bs->write_bits(pcext.chroma_420_type, 1);
m_bs->write_bits(pcext.progressive_frame, 1);
m_bs->write_bits(pcext.composite_display_flag, 1);
if (pcext.composite_display_flag) {
m_bs->write_bits(pcext.v_axis, 1);
m_bs->write_bits(pcext.field_sequence, 3);
m_bs->write_bits(pcext.sub_carrier, 1);
m_bs->write_bits(pcext.burst_amplitude, 7);
m_bs->write_bits(pcext.sub_carrier_phase, 8);
}
return true;
}
bool write_quant_matrix_extension(bitstream_writer_c* m_bs, quant_matrix_extension_t &qmext) {
m_bs->align();
m_bs->write_bits(START_CODE(extension_start_code), 32);
m_bs->write_bits(quant_matrix_extension_id, 4);
m_bs->write_bits(qmext.load_intra_quantiser_matrix, 1);
if (qmext.load_intra_quantiser_matrix)
local_write_array<uint8_t, 64>(m_bs, qmext.intra_quantiser_matrix);
m_bs->write_bits(qmext.load_non_intra_quantiser_matrix, 1);
if (qmext.load_non_intra_quantiser_matrix)
local_write_array<uint8_t, 64>(m_bs, qmext.non_intra_quantiser_matrix);
m_bs->write_bits(qmext.load_chroma_intra_quantiser_matrix, 1);
if (qmext.load_chroma_intra_quantiser_matrix)
local_write_array<uint8_t, 64>(m_bs, qmext.chroma_intra_quantiser_matrix);
m_bs->write_bits(qmext.load_chroma_non_intra_quantiser_matrix, 1);
if (qmext.load_chroma_non_intra_quantiser_matrix)
local_write_array<uint8_t, 64>(m_bs, qmext.chroma_non_intra_quantiser_matrix);
return true;
}
bool write_picture_display_extension(bitstream_writer_c* m_bs, picture_display_extension_t &pdext, sequence_extension_t &sext, picture_coding_extension_t &pcext) {
/* calculta number_of_frame_centre_offsets */
int number_of_frame_centre_offsets;
if (sext.progressive_sequence == 1) {
if (pcext.repeat_first_field == 1) {
if (pcext.top_field_first == 1)
number_of_frame_centre_offsets = 3;
else
number_of_frame_centre_offsets = 2;
}
else
number_of_frame_centre_offsets = 1;
}
else {
if (pcext.picture_structure == picture_structure_topfield || pcext.picture_structure == picture_structure_botfield)
number_of_frame_centre_offsets = 1;
else {
if (pcext.repeat_first_field == 1)
number_of_frame_centre_offsets = 3;
else
number_of_frame_centre_offsets = 2;
}
}
m_bs->align();
m_bs->write_bits(START_CODE(extension_start_code), 32);
m_bs->write_bits(picture_display_extension_id, 4);
for (int i = 0; i < number_of_frame_centre_offsets; i++) {
m_bs->write_bits(pdext.frame_centre_horizontal_offset[i], 16);
m_bs->one_bit();
m_bs->write_bits(pdext.frame_centre_vertical_offset[i], 16);
m_bs->one_bit();
}
return true;
}
bool write_picture_temporal_scalable_extension(bitstream_writer_c* m_bs, picture_temporal_scalable_extension_t& ptsext) {
m_bs->align();
m_bs->write_bits(START_CODE(extension_start_code), 32);
m_bs->write_bits(picture_temporal_scalable_extension_id, 4);
m_bs->write_bits(ptsext.reference_select_code, 2);
m_bs->write_bits(ptsext.forward_temporal_reference, 10);
m_bs->one_bit();
m_bs->write_bits(ptsext.backward_temporal_reference, 10);
return true;
}
bool write_picture_spatial_scalable_extension(bitstream_writer_c* m_bs, picture_spatial_scalable_extension_t& pssext) {
m_bs->align();
m_bs->write_bits(START_CODE(extension_start_code), 32);
m_bs->write_bits(picture_spatial_scalable_extension_id, 4);
m_bs->write_bits(pssext.lower_layer_temporal_reference, 10);
m_bs->one_bit();
m_bs->write_bits(pssext.lower_layer_horizontal_offset, 15);
m_bs->one_bit();
m_bs->write_bits(pssext.lower_layer_vertical_offset, 15);
m_bs->write_bits(pssext.spatial_temporal_weight_code_table_index, 2);
m_bs->write_bits(pssext.lower_layer_progressive_frame, 1);
m_bs->write_bits(pssext.lower_layer_deinterlaced_field_select, 1);
return true;
}
bool write_copyright_extension(bitstream_writer_c* m_bs, copyright_extension_t& crext) {
m_bs->align();
m_bs->write_bits(START_CODE(extension_start_code), 32);
m_bs->write_bits(copiright_extension_id, 4);
m_bs->write_bits(crext.copyright_flag, 1);
m_bs->write_bits(crext.copyright_identifier, 8);
m_bs->write_bits(crext.original_or_copy, 1);
m_bs->write_bits(crext.reserved, 7);
m_bs->one_bit();
m_bs->write_bits(crext.copyright_number_1, 20);
m_bs->one_bit();
m_bs->write_bits(crext.copyright_number_2, 22);
m_bs->one_bit();
m_bs->write_bits(crext.copyright_number_3, 22);
return true;
}
| 10,251 | 4,252 |
//----------------------------------------------------------------------------
// ObjectWindows
// Copyright (c) 1995, 1996 by Borland International, All Rights Reserved
//
//----------------------------------------------------------------------------
#include <owl/pch.h>
#if !defined(OWL_TIMEGADG_H)
# include <owl/timegadg.h>
#endif
#include <owl/time.h>
#include <owl/pointer.h>
namespace owl {
OWL_DIAGINFO;
//
/// Constructor for TTimeGadget.
//
TTimeGadget::TTimeGadget(TGetTimeFunc timeFunc, int id, TBorderStyle border,
TAlign align, uint numChars, LPCTSTR text,
TFont* font)
:
TTextGadget(id, border, align, numChars, text, font),
TimeFunc(timeFunc)
{
SetShrinkWrap(false, true);
}
//
/// String-aware overload
//
TTimeGadget::TTimeGadget(
TGetTimeFunc timeFunc,
int id,
TBorderStyle border,
TAlign align,
uint numChars,
const tstring& text,
TFont* font
)
: TTextGadget(id, border, align, numChars, text, font),
TimeFunc(timeFunc)
{
SetShrinkWrap(false, true);
}
//
/// Overriden from TGadget to inform gadget window to setup a timer
//
void
TTimeGadget::Created()
{
TGadget::Created();
GetGadgetWindow()->EnableTimer();
}
//
/// Overridden from TGadget to display the current time.
//
bool
TTimeGadget::IdleAction(long count)
{
TGadget::IdleAction(count);
tstring newTime;
TimeFunc(newTime);
SetText(newTime.c_str());
// NOTE: Don't return true to drain system. Let GadgetWindow Timer
// message indirectly trigger IdleAction.
//
return false;
}
//
/// Retrieves the current time.
//
void
TTimeGadget::GetTTime(tstring& newTime)
{
TTime time;
newTime = time.AsString();
}
//
// Win32 specific
//
//
/// Retrieves the system time using the Win32 API.
//
void
TTimeGadget::GetSystemTime(tstring& newTime)
{
TAPointer<tchar> dateBuffer(new tchar[100]);
TAPointer<tchar> timeBuffer(new tchar[100]);
LCID lcid = ::GetUserDefaultLCID();
SYSTEMTIME systemTime;
::GetSystemTime(&systemTime);
if (::GetTimeFormat(lcid, LOCALE_NOUSEROVERRIDE, &systemTime, 0, timeBuffer, 100)) {
if (::GetDateFormat(lcid, LOCALE_NOUSEROVERRIDE, &systemTime, 0, dateBuffer, 100)) {
newTime += dateBuffer;
newTime += _T(" ");
newTime += timeBuffer;
}
}
}
//
/// Retrieves the local time using the Win32 API
//
void
TTimeGadget::GetLocalTime(tstring& newTime)
{
TAPointer<tchar> dateBuffer(new tchar[100]);
TAPointer<tchar> timeBuffer(new tchar[100]);
LCID lcid = ::GetUserDefaultLCID();
SYSTEMTIME systemTime;
::GetLocalTime(&systemTime);
if (::GetTimeFormat(lcid, LOCALE_NOUSEROVERRIDE, &systemTime, 0, timeBuffer, 100)) {
if (::GetDateFormat(lcid, LOCALE_NOUSEROVERRIDE, &systemTime, 0, dateBuffer, 100)) {
newTime += dateBuffer;
newTime += _T(" ");
newTime += timeBuffer;
}
}
}
} // OWL namespace
/* ========================================================================== */
| 2,969 | 1,097 |
/*******************************************************************************
* disp_sdl.cpp
*
* Written by Christoph Hormann <chris_hormann@gmx.de>
*
* SDL (Simple direct media layer) based render display system
*
* from Persistence of Vision Ray Tracer ('POV-Ray') version 3.7.
* Copyright 2003-2009 Persistence of Vision Raytracer Pty. Ltd.
* ---------------------------------------------------------------------------
* NOTICE: This source code file is provided so that users may experiment
* with enhancements to POV-Ray and to port the software to platforms other
* than those supported by the POV-Ray developers. There are strict rules
* regarding how you are permitted to use this file. These rules are contained
* in the distribution and derivative versions licenses which should have been
* provided with this file.
*
* These licences may be found online, linked from the end-user license
* agreement that is located at http://www.povray.org/povlegal.html
* ---------------------------------------------------------------------------
* POV-Ray is based on the popular DKB raytracer version 2.12.
* DKBTrace was originally written by David K. Buck.
* DKBTrace Ver 2.0-2.12 were written by David K. Buck & Aaron A. Collins.
* ---------------------------------------------------------------------------
* $File: //depot/povray/smp/unix/disp_sdl.cpp $
* $Revision: #19 $
* $Change: 5604 $
* $DateTime: 2012/01/28 15:37:41 $
* $Author: jgrimbert $
*******************************************************************************/
/*********************************************************************************
* NOTICE
*
* This file is part of a BETA-TEST version of POV-Ray version 3.7. It is not
* final code. Use of this source file is governed by both the standard POV-Ray
* licences referred to in the copyright header block above this notice, and the
* following additional restrictions numbered 1 through 4 below:
*
* 1. This source file may not be re-distributed without the written permission
* of Persistence of Vision Raytracer Pty. Ltd.
*
* 2. This notice may not be altered or removed.
*
* 3. Binaries generated from this source file by individuals for their own
* personal use may not be re-distributed without the written permission
* of Persistence of Vision Raytracer Pty. Ltd. Such personal-use binaries
* are not required to have a timeout, and thus permission is granted in
* these circumstances only to disable the timeout code contained within
* the beta software.
*
* 4. Binaries generated from this source file for use within an organizational
* unit (such as, but not limited to, a company or university) may not be
* distributed beyond the local organizational unit in which they were made,
* unless written permission is obtained from Persistence of Vision Raytracer
* Pty. Ltd. Additionally, the timeout code implemented within the beta may
* not be disabled or otherwise bypassed in any manner.
*
* The following text is not part of the above conditions and is provided for
* informational purposes only.
*
* The purpose of the no-redistribution clause is to attempt to keep the
* circulating copies of the beta source fresh. The only authorized distribution
* point for the source code is the POV-Ray website and Perforce server, where
* the code will be kept up to date with recent fixes. Additionally the beta
* timeout code mentioned above has been a standard part of POV-Ray betas since
* version 1.0, and is intended to reduce bug reports from old betas as well as
* keep any circulating beta binaries relatively fresh.
*
* All said, however, the POV-Ray developers are open to any reasonable request
* for variations to the above conditions and will consider them on a case-by-case
* basis.
*
* Additionally, the developers request your co-operation in fixing bugs and
* generally improving the program. If submitting a bug-fix, please ensure that
* you quote the revision number of the file shown above in the copyright header
* (see the '$Revision:' field). This ensures that it is possible to determine
* what specific copy of the file you are working with. The developers also would
* like to make it known that until POV-Ray 3.7 is out of beta, they would prefer
* to emphasize the provision of bug fixes over the addition of new features.
*
* Persons wishing to enhance this source are requested to take the above into
* account. It is also strongly suggested that such enhancements are started with
* a recent copy of the source.
*
* The source code page (see http://www.povray.org/beta/source/) sets out the
* conditions under which the developers are willing to accept contributions back
* into the primary source tree. Please refer to those conditions prior to making
* any changes to this source, if you wish to submit those changes for inclusion
* with POV-Ray.
*
*********************************************************************************/
#include "config.h"
#ifdef HAVE_LIBSDL
#include "disp_sdl.h"
#include <algorithm>
// this must be the last file included
#include "syspovdebug.h"
namespace pov_frontend
{
using namespace std;
using namespace vfe;
using namespace vfePlatform;
extern boost::shared_ptr<Display> gDisplay;
const UnixOptionsProcessor::Option_Info UnixSDLDisplay::Options[] =
{
// command line/povray.conf/environment options of this display mode can be added here
// section name, option name, default, has_param, command line parameter, environment variable name, help text
UnixOptionsProcessor::Option_Info("display", "scaled", "on", false, "", "POV_DISPLAY_SCALED", "scale render view to fit screen"),
UnixOptionsProcessor::Option_Info("", "", "", false, "", "", "") // has to be last
};
bool UnixSDLDisplay::Register(vfeUnixSession *session)
{
session->GetUnixOptions()->Register(Options);
// TODO: correct display detection
return true;
}
UnixSDLDisplay::UnixSDLDisplay(unsigned int w, unsigned int h, GammaCurvePtr gamma, vfeSession *session, bool visible) :
UnixDisplay(w, h, gamma, session, visible)
{
m_valid = false;
m_display_scaled = false;
m_display_scale = 1.;
m_screen = NULL;
m_display = NULL;
}
UnixSDLDisplay::~UnixSDLDisplay()
{
Close();
}
void UnixSDLDisplay::Initialise()
{
if (m_VisibleOnCreation)
Show();
}
void UnixSDLDisplay::Hide()
{
}
bool UnixSDLDisplay::TakeOver(UnixDisplay *display)
{
UnixSDLDisplay *p = dynamic_cast<UnixSDLDisplay *>(display);
if (p == NULL)
return false;
if ((GetWidth() != p->GetWidth()) || (GetHeight() != p->GetHeight()))
return false;
m_valid = p->m_valid;
m_display_scaled = p->m_display_scaled;
m_display_scale = p->m_display_scale;
m_screen = p->m_screen;
m_display = p->m_display;
if (m_display_scaled)
{
int width = GetWidth();
int height = GetHeight();
// allocate a new pixel counters, dropping influence of previous picture
m_PxCount.clear(); // not useful, vector was created empty, just to be sure
m_PxCount.reserve(width*height); // we need that, and the loop!
for(vector<unsigned char>::iterator iter = m_PxCount.begin(); iter != m_PxCount.end(); iter++)
(*iter) = 0;
}
return true;
}
void UnixSDLDisplay::Close()
{
if (!m_valid)
return;
// FIXME: should handle this correctly for the last frame
// SDL_FreeSurface(m_display);
// SDL_Quit();
m_PxCount.clear();
m_valid = false;
}
void UnixSDLDisplay::SetCaption(bool paused)
{
if (!m_valid)
return;
boost::format f;
if (m_display_scaled)
f = boost::format(PACKAGE_NAME " " VERSION_BASE " SDL display (scaled at %.0f%%)%s")
% (m_display_scale*100)
% (paused ? " [paused]" : "");
else
f = boost::format(PACKAGE_NAME " " VERSION_BASE " SDL display%s")
% (paused ? " [paused]" : "");
// FIXME: SDL_WM_SetCaption() causes locks on some distros, see http://bugs.povray.org/23
// FIXME: SDL_WM_SetCaption(f.str().c_str(), PACKAGE_NAME);
}
void UnixSDLDisplay::Show()
{
if (gDisplay.get() != this)
gDisplay = m_Session->GetDisplay();
if (!m_valid)
{
// Initialize SDL
if ( SDL_Init(SDL_INIT_VIDEO) != 0 )
{
fprintf(stderr, "Couldn't initialize SDL: %s.\n", SDL_GetError());
return;
}
int desired_bpp = 0;
Uint32 video_flags = 0;
int width = GetWidth();
int height = GetHeight();
vfeUnixSession *UxSession = dynamic_cast<vfeUnixSession *>(m_Session);
if (UxSession->GetUnixOptions()->isOptionSet("display", "scaled"))
// determine maximum display area (wrong and ugly)
{
SDL_Rect **modes = SDL_ListModes(NULL, SDL_FULLSCREEN);
if (modes != NULL)
{
width = min(modes[0]->w - 10, width);
height = min(modes[0]->h - 80, height);
}
}
// calculate display area
float AspectRatio = float(width)/float(height);
float AspectRatio_Full = float(GetWidth())/float(GetHeight());
if (AspectRatio > AspectRatio_Full)
width = int(AspectRatio_Full*float(height));
else if (AspectRatio != AspectRatio_Full)
height = int(float(width)/AspectRatio_Full);
// Initialize the display
m_screen = SDL_SetVideoMode(width, height, desired_bpp, video_flags);
if ( m_screen == NULL )
{
fprintf(stderr, "Couldn't set %dx%dx%d video mode: %s\n", width, height, desired_bpp, SDL_GetError());
return;
}
SDL_Surface *temp = SDL_CreateRGBSurface(SDL_SWSURFACE, width, height, 32, 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF);
if ( temp == NULL )
{
fprintf(stderr, "Couldn't create render display surface: %s\n", SDL_GetError());
return;
}
m_display = SDL_DisplayFormat(temp);
SDL_FreeSurface(temp);
if ( m_display == NULL )
{
fprintf(stderr, "Couldn't convert bar surface: %s\n", SDL_GetError());
return;
}
m_PxCount.clear();
m_PxCount.reserve(width*height);
for(vector<unsigned char>::iterator iter = m_PxCount.begin(); iter != m_PxCount.end(); iter++)
(*iter) = 0;
m_update_rect.x = 0;
m_update_rect.y = 0;
m_update_rect.w = width;
m_update_rect.h = height;
m_screen_rect.x = 0;
m_screen_rect.y = 0;
m_screen_rect.w = width;
m_screen_rect.h = height;
m_valid = true;
m_PxCnt = UpdateInterval;
if ((width == GetWidth()) && (height == GetHeight()))
{
m_display_scaled = false;
m_display_scale = 1.;
}
else
{
m_display_scaled = true;
m_display_scale = float(width) / GetWidth();
}
SetCaption(false);
}
}
inline void UnixSDLDisplay::SetPixel(unsigned int x, unsigned int y, const RGBA8& colour)
{
Uint8 *p = (Uint8 *) m_display->pixels + y * m_display->pitch + x * m_display->format->BytesPerPixel;
Uint32 sdl_col = SDL_MapRGBA(m_display->format, colour.red, colour.green, colour.blue, colour.alpha);
switch (m_display->format->BytesPerPixel)
{
case 1:
*p = sdl_col;
break;
case 2:
*(Uint16 *) p = sdl_col;
break;
case 3:
if (SDL_BYTEORDER == SDL_BIG_ENDIAN)
{
p[0] = (sdl_col >> 16) & 0xFF;
p[1] = (sdl_col >> 8) & 0xFF;
p[2] = sdl_col & 0xFF;
}
else
{
p[0] = sdl_col & 0xFF;
p[1] = (sdl_col >> 8) & 0xFF;
p[2] = (sdl_col >> 16) & 0xFF;
}
break;
case 4:
*(Uint32 *) p = sdl_col;
break;
}
}
inline void UnixSDLDisplay::SetPixelScaled(unsigned int x, unsigned int y, const RGBA8& colour)
{
unsigned int ix = x * m_display_scale;
unsigned int iy = y * m_display_scale;
Uint8 *p = (Uint8 *) m_display->pixels + iy * m_display->pitch + ix * m_display->format->BytesPerPixel;
Uint8 r, g, b, a;
Uint32 old = *(Uint32 *) p;
SDL_GetRGBA(old, m_display->format, &r, &g, &b, &a);
unsigned int ofs = ix + iy * m_display->w;
r = (r*m_PxCount[ofs] + colour.red ) / (m_PxCount[ofs]+1);
g = (g*m_PxCount[ofs] + colour.green) / (m_PxCount[ofs]+1);
b = (b*m_PxCount[ofs] + colour.blue ) / (m_PxCount[ofs]+1);
a = (a*m_PxCount[ofs] + colour.alpha) / (m_PxCount[ofs]+1);
Uint32 sdl_col = SDL_MapRGBA(m_display->format, r, g, b, a);
switch (m_display->format->BytesPerPixel)
{
case 1:
*p = sdl_col;
break;
case 2:
*(Uint16 *) p = sdl_col;
break;
case 3:
if (SDL_BYTEORDER == SDL_BIG_ENDIAN)
{
p[0] = (sdl_col >> 16) & 0xFF;
p[1] = (sdl_col >> 8) & 0xFF;
p[2] = sdl_col & 0xFF;
}
else
{
p[0] = sdl_col & 0xFF;
p[1] = (sdl_col >> 8) & 0xFF;
p[2] = (sdl_col >> 16) & 0xFF;
}
break;
case 4:
*(Uint32 *) p = sdl_col;
break;
}
++m_PxCount[ofs];
}
void UnixSDLDisplay::UpdateCoord(unsigned int x, unsigned int y)
{
unsigned int rx2 = m_update_rect.x + m_update_rect.w;
unsigned int ry2 = m_update_rect.y + m_update_rect.h;
m_update_rect.x = min((unsigned int)m_update_rect.x, x);
m_update_rect.y = min((unsigned int)m_update_rect.y, y);
rx2 = max(rx2, x);
ry2 = max(ry2, y);
m_update_rect.w = rx2 - m_update_rect.x;
m_update_rect.h = ry2 - m_update_rect.y;
}
void UnixSDLDisplay::UpdateCoord(unsigned int x1, unsigned int y1, unsigned int x2, unsigned int y2)
{
unsigned int rx2 = m_update_rect.x + m_update_rect.w;
unsigned int ry2 = m_update_rect.y + m_update_rect.h;
m_update_rect.x = min((unsigned int)m_update_rect.x, x1);
m_update_rect.y = min((unsigned int)m_update_rect.y, y1);
rx2 = max(rx2, x2);
ry2 = max(ry2, y2);
m_update_rect.w = rx2 - m_update_rect.x;
m_update_rect.h = ry2 - m_update_rect.y;
}
void UnixSDLDisplay::UpdateCoordScaled(unsigned int x, unsigned int y)
{
UpdateCoord(static_cast<unsigned int>(x * m_display_scale), static_cast<unsigned int>(y * m_display_scale));
}
void UnixSDLDisplay::UpdateCoordScaled(unsigned int x1, unsigned int y1, unsigned int x2, unsigned int y2)
{
UpdateCoord(static_cast<unsigned int>(x1 * m_display_scale), static_cast<unsigned int>(y1 * m_display_scale),
static_cast<unsigned int>(x2 * m_display_scale), static_cast<unsigned int>(y2 * m_display_scale));
}
void UnixSDLDisplay::DrawPixel(unsigned int x, unsigned int y, const RGBA8& colour)
{
if (!m_valid || x >= GetWidth() || y >= GetHeight())
return;
if (SDL_MUSTLOCK(m_display) && SDL_LockSurface(m_display) < 0)
return;
if (m_display_scaled)
{
SetPixelScaled(x, y, colour);
UpdateCoordScaled(x, y);
}
else
{
SetPixel(x, y, colour);
UpdateCoord(x, y);
}
m_PxCnt++;
if (SDL_MUSTLOCK(m_display))
SDL_UnlockSurface(m_display);
}
void UnixSDLDisplay::DrawRectangleFrame(unsigned int x1, unsigned int y1, unsigned int x2, unsigned int y2, const RGBA8& colour)
{
if (!m_valid)
return;
int ix1 = min(x1, GetWidth()-1);
int ix2 = min(x2, GetWidth()-1);
int iy1 = min(y1, GetHeight()-1);
int iy2 = min(y2, GetHeight()-1);
if (SDL_MUSTLOCK(m_display) && SDL_LockSurface(m_display) < 0)
return;
if (m_display_scaled)
{
for(unsigned int x = ix1; x <= ix2; x++)
{
SetPixelScaled(x, iy1, colour);
SetPixelScaled(x, iy2, colour);
}
for(unsigned int y = iy1; y <= iy2; y++)
{
SetPixelScaled(ix1, y, colour);
SetPixelScaled(ix2, y, colour);
}
UpdateCoordScaled(ix1, iy1, ix2, iy2);
}
else
{
for(unsigned int x = ix1; x <= ix2; x++)
{
SetPixel(x, iy1, colour);
SetPixel(x, iy2, colour);
}
for(unsigned int y = iy1; y <= iy2; y++)
{
SetPixel(ix1, y, colour);
SetPixel(ix2, y, colour);
}
UpdateCoord(ix1, iy1, ix2, iy2);
}
if (SDL_MUSTLOCK(m_display))
SDL_UnlockSurface(m_display);
m_PxCnt = UpdateInterval;
}
void UnixSDLDisplay::DrawFilledRectangle(unsigned int x1, unsigned int y1, unsigned int x2, unsigned int y2, const RGBA8& colour)
{
if (!m_valid)
return;
unsigned int ix1 = min(x1, GetWidth()-1);
unsigned int ix2 = min(x2, GetWidth()-1);
unsigned int iy1 = min(y1, GetHeight()-1);
unsigned int iy2 = min(y2, GetHeight()-1);
if (m_display_scaled)
{
ix1 *= m_display_scale;
iy1 *= m_display_scale;
ix2 *= m_display_scale;
iy2 *= m_display_scale;
}
UpdateCoord(ix1, iy1, ix2, iy2);
Uint32 sdl_col = SDL_MapRGBA(m_display->format, colour.red, colour.green, colour.blue, colour.alpha);
SDL_Rect tempRect;
tempRect.x = ix1;
tempRect.y = iy1;
tempRect.w = ix2 - ix1 + 1;
tempRect.h = iy2 - iy1 + 1;
SDL_FillRect(m_display, &tempRect, sdl_col);
m_PxCnt = UpdateInterval;
}
void UnixSDLDisplay::DrawPixelBlock(unsigned int x1, unsigned int y1, unsigned int x2, unsigned int y2, const RGBA8 *colour)
{
if (!m_valid)
return;
unsigned int ix1 = min(x1, GetWidth()-1);
unsigned int ix2 = min(x2, GetWidth()-1);
unsigned int iy1 = min(y1, GetHeight()-1);
unsigned int iy2 = min(y2, GetHeight()-1);
if (SDL_MUSTLOCK(m_display) && SDL_LockSurface(m_display) < 0)
return;
if (m_display_scaled)
{
for(unsigned int y = iy1, i = 0; y <= iy2; y++)
for(unsigned int x = ix1; x <= ix2; x++, i++)
SetPixelScaled(x, y, colour[i]);
UpdateCoordScaled(ix1, iy1, ix2, iy2);
}
else
{
for(unsigned int y = y1, i = 0; y <= iy2; y++)
for(unsigned int x = ix1; x <= ix2; x++, i++)
SetPixel(x, y, colour[i]);
UpdateCoord(ix1, iy1, ix2, iy2);
}
if (SDL_MUSTLOCK(m_display))
SDL_UnlockSurface(m_display);
m_PxCnt = UpdateInterval;
}
void UnixSDLDisplay::Clear()
{
for(vector<unsigned char>::iterator iter = m_PxCount.begin(); iter != m_PxCount.end(); iter++)
(*iter) = 0;
m_update_rect.x = 0;
m_update_rect.y = 0;
m_update_rect.w = m_display->w;
m_update_rect.h = m_display->h;
SDL_FillRect(m_display, &m_update_rect, (Uint32)0);
m_PxCnt = UpdateInterval;
}
void UnixSDLDisplay::UpdateScreen(bool Force = false)
{
if (!m_valid)
return;
if (Force || m_PxCnt >= UpdateInterval)
{
SDL_BlitSurface(m_display, &m_update_rect, m_screen, &m_update_rect);
SDL_UpdateRect(m_screen, m_update_rect.x, m_update_rect.y, m_update_rect.w, m_update_rect.h);
m_PxCnt = 0;
}
}
void UnixSDLDisplay::PauseWhenDoneNotifyStart()
{
if (!m_valid)
return;
fprintf(stderr, "Press a key or click the display to continue...");
SetCaption(true);
}
void UnixSDLDisplay::PauseWhenDoneNotifyEnd()
{
if (!m_valid)
return;
SetCaption(false);
fprintf(stderr, "\n\n");
}
bool UnixSDLDisplay::PauseWhenDoneResumeIsRequested()
{
if (!m_valid)
return true;
SDL_Event event;
bool do_quit = false;
if (SDL_PollEvent(&event))
{
switch (event.type)
{
case SDL_KEYDOWN:
if ( event.key.keysym.sym == SDLK_q || event.key.keysym.sym == SDLK_RETURN || event.key.keysym.sym == SDLK_KP_ENTER )
do_quit = true;
break;
case SDL_MOUSEBUTTONDOWN:
do_quit = true;
break;
}
}
return do_quit;
}
bool UnixSDLDisplay::HandleEvents()
{
if (!m_valid)
return false;
SDL_Event event;
bool do_quit = false;
while (SDL_PollEvent(&event))
{
switch (event.type)
{
case SDL_KEYDOWN:
if ( event.key.keysym.sym == SDLK_q )
do_quit = true;
else if ( event.key.keysym.sym == SDLK_p )
{
if (!m_Session->IsPausable())
break;
if (m_Session->Paused())
{
if (m_Session->Resume())
SetCaption(false);
}
else
{
if (m_Session->Pause())
SetCaption(true);
}
}
break;
case SDL_QUIT:
do_quit = true;
break;
}
if (do_quit)
break;
}
return do_quit;
}
}
#endif /* HAVE_LIBSDL */
| 19,610 | 8,157 |
#include <vector>
#include "caffe/layers/tile_layer.hpp"
#include "caffe/util/math_functions.hpp"
namespace caffe {
template <typename Dtype>
__global__ void Tile(const int nthreads, const Dtype* bottom_data,
const int tile_size, const int num_tiles, const int bottom_tile_axis,
Dtype* top_data) {
HIP_KERNEL_LOOP(index, nthreads) {
const int d = index % tile_size;
const int b = (index / tile_size / num_tiles) % bottom_tile_axis;
const int n = index / tile_size / num_tiles / bottom_tile_axis;
const int bottom_index = (n * bottom_tile_axis + b) * tile_size + d;
top_data[index] = bottom_data[bottom_index];
}
}
template <typename Dtype>
void TileLayer<Dtype>::Forward_gpu(
const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) {
const Dtype* bottom_data = bottom[0]->gpu_data();
Dtype* top_data = top[0]->mutable_gpu_data();
const int bottom_tile_axis = bottom[0]->shape(axis_);
const int nthreads = top[0]->count();
hipLaunchKernelGGL(Tile<Dtype>, //) NOLINT_NEXT_LINE(whitespace/operators)
dim3(CAFFE_GET_BLOCKS(nthreads)), dim3(CAFFE_HIP_NUM_THREADS), 0, 0,
nthreads, bottom_data, inner_dim_, tiles_, bottom_tile_axis, top_data);
}
template <typename Dtype>
__global__ void TileBackward(const int nthreads, const Dtype* top_diff,
const int tile_size, const int num_tiles, const int bottom_tile_axis,
Dtype* bottom_diff) {
HIP_KERNEL_LOOP(index, nthreads) {
const int d = index % tile_size;
const int b = (index / tile_size) % bottom_tile_axis;
const int n = index / tile_size / bottom_tile_axis;
bottom_diff[index] = 0;
int top_index = (n * num_tiles * bottom_tile_axis + b) * tile_size + d;
for (int t = 0; t < num_tiles; ++t) {
bottom_diff[index] += top_diff[top_index];
top_index += bottom_tile_axis * tile_size;
}
}
}
template <typename Dtype>
void TileLayer<Dtype>::Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) {
if (!propagate_down[0]) { return; }
const Dtype* top_diff = top[0]->gpu_diff();
Dtype* bottom_diff = bottom[0]->mutable_gpu_diff();
const int bottom_tile_axis = bottom[0]->shape(axis_);
const int tile_size = inner_dim_ / bottom_tile_axis;
const int nthreads = bottom[0]->count();
hipLaunchKernelGGL(TileBackward<Dtype>, // NOLINT_NEXT_LINE(whitespace/operators)
dim3(CAFFE_GET_BLOCKS(nthreads)), dim3(CAFFE_HIP_NUM_THREADS), 0, 0,
nthreads, top_diff, tile_size, tiles_, bottom_tile_axis, bottom_diff);
}
INSTANTIATE_LAYER_GPU_FUNCS(TileLayer);
} // namespace caffe
| 2,630 | 1,013 |
// RUN: %clang_cc1 -std=c++11 -fsyntax-only -Wno-nullability-declspec %s -verify
#if __has_feature(nullability)
#else
# error nullability feature should be defined
#endif
typedef decltype(nullptr) nullptr_t;
class X {
};
// Nullability applies to all pointer types.
typedef int (X::* _Nonnull member_function_type_1)(int);
typedef int X::* _Nonnull member_data_type_1;
typedef nullptr_t _Nonnull nonnull_nullptr_t; // expected-error{{nullability specifier '_Nonnull' cannot be applied to non-pointer type 'nullptr_t'}}
// Nullability can move into member pointers (this is suppressing a warning).
typedef _Nonnull int (X::* member_function_type_2)(int);
typedef int (X::* _Nonnull member_function_type_3)(int);
typedef _Nonnull int X::* member_data_type_2;
// Adding non-null via a template.
template<typename T>
struct AddNonNull {
typedef _Nonnull T type; // expected-error{{nullability specifier '_Nonnull' cannot be applied to non-pointer type 'int'}}
// expected-error@-1{{nullability specifier '_Nonnull' cannot be applied to non-pointer type 'nullptr_t'}}
};
typedef AddNonNull<int *>::type nonnull_int_ptr_1;
typedef AddNonNull<int * _Nullable>::type nonnull_int_ptr_2; // FIXME: check that it was overridden
typedef AddNonNull<nullptr_t>::type nonnull_int_ptr_3; // expected-note{{in instantiation of template class}}
typedef AddNonNull<int>::type nonnull_non_pointer_1; // expected-note{{in instantiation of template class 'AddNonNull<int>' requested here}}
// Non-null checking within a template.
template<typename T>
struct AddNonNull2 {
typedef _Nonnull AddNonNull<T> invalid1; // expected-error{{nullability specifier '_Nonnull' cannot be applied to non-pointer type 'AddNonNull<T>'}}
typedef _Nonnull AddNonNull2 invalid2; // expected-error{{nullability specifier '_Nonnull' cannot be applied to non-pointer type 'AddNonNull2<T>'}}
typedef _Nonnull AddNonNull2<T> invalid3; // expected-error{{nullability specifier '_Nonnull' cannot be applied to non-pointer type 'AddNonNull2<T>'}}
typedef _Nonnull typename AddNonNull<T>::type okay1;
// Don't move past a dependent type even if we know that nullability
// cannot apply to that specific dependent type.
typedef _Nonnull AddNonNull<T> (*invalid4); // expected-error{{nullability specifier '_Nonnull' cannot be applied to non-pointer type 'AddNonNull<T>'}}
};
// Check passing null to a _Nonnull argument.
void (*accepts_nonnull_1)(_Nonnull int *ptr);
void (*& accepts_nonnull_2)(_Nonnull int *ptr) = accepts_nonnull_1;
void (X::* accepts_nonnull_3)(_Nonnull int *ptr);
void accepts_nonnull_4(_Nonnull int *ptr);
void (&accepts_nonnull_5)(_Nonnull int *ptr) = accepts_nonnull_4;
void test_accepts_nonnull_null_pointer_literal(X *x) {
accepts_nonnull_1(0); // expected-warning{{null passed to a callee that requires a non-null argument}}
accepts_nonnull_2(0); // expected-warning{{null passed to a callee that requires a non-null argument}}
(x->*accepts_nonnull_3)(0); // expected-warning{{null passed to a callee that requires a non-null argument}}
accepts_nonnull_4(0); // expected-warning{{null passed to a callee that requires a non-null argument}}
accepts_nonnull_5(0); // expected-warning{{null passed to a callee that requires a non-null argument}}
}
template<void FP(_Nonnull int*)>
void test_accepts_nonnull_null_pointer_literal_template() {
FP(0); // expected-warning{{null passed to a callee that requires a non-null argument}}
}
template void test_accepts_nonnull_null_pointer_literal_template<&accepts_nonnull_4>(); // expected-note{{instantiation of function template specialization}}
| 3,608 | 1,192 |
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/modules/webgl/oes_draw_buffers_indexed.h"
namespace blink {
OESDrawBuffersIndexed::OESDrawBuffersIndexed(WebGLRenderingContextBase* context)
: WebGLExtension(context) {
context->ExtensionsUtil()->EnsureExtensionEnabled(
"GL_OES_draw_buffers_indexed");
}
WebGLExtensionName OESDrawBuffersIndexed::GetName() const {
return kOESDrawBuffersIndexed;
}
bool OESDrawBuffersIndexed::Supported(WebGLRenderingContextBase* context) {
return context->ExtensionsUtil()->SupportsExtension(
"GL_OES_draw_buffers_indexed");
}
const char* OESDrawBuffersIndexed::ExtensionName() {
return "OES_draw_buffers_indexed";
}
void OESDrawBuffersIndexed::enableiOES(GLenum target, GLuint index) {
WebGLExtensionScopedContext scoped(this);
if (scoped.IsLost())
return;
scoped.Context()->ContextGL()->EnableiOES(target, index);
}
void OESDrawBuffersIndexed::disableiOES(GLenum target, GLuint index) {
WebGLExtensionScopedContext scoped(this);
if (scoped.IsLost())
return;
scoped.Context()->ContextGL()->DisableiOES(target, index);
}
void OESDrawBuffersIndexed::blendEquationiOES(GLuint buf, GLenum mode) {
WebGLExtensionScopedContext scoped(this);
if (scoped.IsLost())
return;
scoped.Context()->ContextGL()->BlendEquationiOES(buf, mode);
}
void OESDrawBuffersIndexed::blendEquationSeparateiOES(GLuint buf,
GLenum modeRGB,
GLenum modeAlpha) {
WebGLExtensionScopedContext scoped(this);
if (scoped.IsLost())
return;
scoped.Context()->ContextGL()->BlendEquationSeparateiOES(buf, modeRGB,
modeAlpha);
}
void OESDrawBuffersIndexed::blendFunciOES(GLuint buf, GLenum src, GLenum dst) {
WebGLExtensionScopedContext scoped(this);
if (scoped.IsLost())
return;
scoped.Context()->ContextGL()->BlendFunciOES(buf, src, dst);
}
void OESDrawBuffersIndexed::blendFuncSeparateiOES(GLuint buf,
GLenum srcRGB,
GLenum dstRGB,
GLenum srcAlpha,
GLenum dstAlpha) {
WebGLExtensionScopedContext scoped(this);
if (scoped.IsLost())
return;
scoped.Context()->ContextGL()->BlendFuncSeparateiOES(buf, srcRGB, dstRGB,
srcAlpha, dstAlpha);
}
void OESDrawBuffersIndexed::colorMaskiOES(GLuint buf,
GLboolean r,
GLboolean g,
GLboolean b,
GLboolean a) {
WebGLExtensionScopedContext scoped(this);
if (scoped.IsLost())
return;
scoped.Context()->ContextGL()->ColorMaskiOES(buf, r, g, b, a);
}
GLboolean OESDrawBuffersIndexed::isEnablediOES(GLenum target, GLuint index) {
WebGLExtensionScopedContext scoped(this);
if (scoped.IsLost())
return 0;
return scoped.Context()->ContextGL()->IsEnablediOES(target, index);
}
} // namespace blink
| 3,377 | 1,071 |
#include "std.h"
#include "compile.h"
#include "wildcard.h"
#include "process.h"
#include "env.h"
namespace compile {
Target::Target(const Path &wd, const Config &config) :
wd(wd),
config(config),
includes(wd, config),
compileVariants(config.getArray("compile")),
buildDir(wd + Path(config.getVars("buildDir"))),
intermediateExt(config.getVars("intermediateExt")),
pchHeader(config.getVars("pch")),
pchFile(buildDir + Path(config.getVars("pchFile"))),
combinedPch(config.getBool("pchCompileCombined")),
appendExt(config.getBool("appendExt", false)),
absolutePath(config.getBool("absolutePath", false)) {
buildDir.makeDir();
linkOutput = config.getBool("linkOutput", false);
forwardDeps = config.getBool("forwardDeps", false);
if (absolutePath) {
vector<String> inc = this->config.getArray("include");
this->config.clear("include");
for (nat i = 0; i < inc.size(); i++) {
this->config.add("include", toS(Path(inc[i]).makeAbsolute(wd)));
}
}
// Add file extensions. We don't bother with uniqueness here, and let the ExtCache deal with that.
validExts = config.getArray("ext");
vector<String> ign = config.getArray("ignore");
for (nat i = 0; i < ign.size(); i++)
ignore << Wildcard(ign[i]);
// Create build directory if it is not already created.
buildDir.createDir();
// Load cached data if possible.
includes.ignore(config.getArray("noIncludes"));
if (!force) {
includes.load(buildDir + "includes");
commands.load(buildDir + "commands");
}
}
Target::~Target() {
// We do this in "save", since if we execute the binary, the destructor will not be executed.
// includes.save(buildDir + "includes");
}
void Target::clean() {
DEBUG("Cleaning " << buildDir.makeRelative(wd) << "...", NORMAL);
buildDir.recursiveDelete();
Path e = wd + Path(config.getVars("execDir"));
e.makeDir();
DEBUG("Cleaning " << e.makeRelative(wd) << "...", NORMAL);
e.recursiveDelete();
}
bool Target::find() {
DEBUG("Finding dependencies for target in " << wd, INFO);
toCompile.clear();
ExtCache cache(validExts);
CompileQueue q;
String outputName = config.getVars("output");
// Compile pre-compiled header first.
String pchStr = config.getVars("pch");
if (!pchStr.empty()) {
if (!addFile(q, cache, pchStr, true)) {
PLN("Failed to find an implementation file for the precompiled header.");
PLN("Make sure to create both a header file '" << pchStr << "' and a corresponding implementation file.");
return false;
}
}
// Add initial files.
addFiles(q, cache, config.getArray("input"));
// Process files...
while (q.any()) {
Compile now = q.pop();
if (ignored(toS(now.makeRelative(wd))))
continue;
if (!now.isPch && !now.autoFound && outputName.empty())
outputName = now.title();
// Check if 'now' is inside the working directory.
if (!now.isChild(wd)) {
// No need to follow further!
DEBUG("Ignoring file outside of working directory: " << now.makeRelative(wd), VERBOSE);
continue;
}
toCompile << now;
// Add all other files we need.
IncludeInfo info = includes.info(now);
// Check so that any pch file is included first.
if (!info.ignored && !pchStr.empty() && pchStr != info.firstInclude) {
PLN(now << ":1: Precompiled header " << pchStr << " not used.");
PLN("The precompiled header " << pchStr << " must be included first in each implementation file.");
PLN("You need to use '#include \"" << pchStr << "\"' (exactly like that), and use 'include=./'.");
return false;
}
for (IncludeInfo::PathSet::const_iterator i = info.includes.begin(); i != info.includes.end(); ++i) {
DEBUG(now << " depends on " << *i, VERBOSE);
addFile(q, cache, *i);
// Is this a reference to another sub-project?
if (!i->isChild(wd)) {
Path parentRel = i->makeRelative(wd.parent());
if (parentRel.first() != "..") {
dependsOn << parentRel.first();
}
}
}
}
if (toCompile.empty()) {
PLN("No input files.");
return false;
}
// Try to add the files which should be created by the pre-build step (if any).
addPreBuildFiles(q, config.getArray("preBuildCreates"));
while (q.any()) {
Compile now = q.pop();
DEBUG("Adding file created by pre-build step currently not existing: " << now.makeRelative(wd), INFO);
toCompile << now;
}
if (outputName.empty())
outputName = wd.title();
Path execDir = wd + Path(config.getVars("execDir"));
execDir.createDir();
output = execDir + Path(outputName).titleNoExt();
output.makeExt(config.getStr("execExt"));
return true;
}
// Save command line on exit.
class SaveOnExit : public ProcessCallback {
public:
SaveOnExit(Commands *to, const String &file, const String &command) : to(to), key(file), command(command) {}
// Save to.
Commands *to;
// Source file used as key.
String key;
// Command line.
String command;
virtual void exited(int result) {
if (result == 0)
to->set(key, command);
}
};
Process *Target::saveShellProcess(const String &file, const String &command, const Path &cwd, const Env *env) {
Process *p = shellProcess(command, cwd, env);
p->callback = new SaveOnExit(&commands, file, command);
return p;
}
bool Target::compile() {
nat threads = to<nat>(config.getStr("maxThreads", "1"));
// Force serial execution?
if (!config.getBool("parallel", true))
threads = 1;
DEBUG("Using max " << threads << " threads.", VERBOSE);
ProcGroup group(threads, outputState);
DEBUG("Compiling target in " << wd, INFO);
Env env(config);
// Run pre-compile steps.
{
map<String, String> stepData;
stepData["output"] = toS(output.makeRelative(wd));
if (!runSteps("preBuild", group, env, stepData))
return false;
}
map<String, String> data;
data["file"] = "";
data["output"] = "";
data["pchFile"] = toS(pchFile.makeRelative(wd));
TimeCache timeCache;
Timestamp latestModified(0);
ostringstream intermediateFiles;
for (nat i = 0; i < toCompile.size(); i++) {
const Compile &src = toCompile[i];
Path output = src.makeRelative(wd).makeAbsolute(buildDir);
if (appendExt) {
String t = output.titleNoExt() + "_" + output.ext() + "." + intermediateExt;
output.makeTitle(t);
} else {
output.makeExt(intermediateExt);
}
output.parent().createDir();
String file = toS(src.makeRelative(wd));
String out = toS(output.makeRelative(wd));
if (i > 0)
intermediateFiles << ' ';
intermediateFiles << out;
if (ignored(file))
continue;
Timestamp lastModified = includes.info(src).lastModified(timeCache);
bool pchValid = true;
if (src.isPch) {
// Note: This implies that pchFile exists as well.
pchValid = pchFile.mTime() >= lastModified;
}
bool skip = !force // Never skip a file if the force flag is set.
&& pchValid // If the pch is invalid, don't skip.
&& output.mTime() >= lastModified; // If the output exists and is new enough, we can skip.
if (!combinedPch && src.isPch) {
String cmd = config.getStr("pchCompile");
Path pchPath = Path(pchHeader).makeAbsolute(wd);
String pchFile = toS(pchPath.makeRelative(wd));
data["file"] = preparePath(pchPath);
data["output"] = data["pchFile"];
cmd = config.expandVars(cmd, data);
if (skip && commands.check(pchFile, cmd)) {
DEBUG("Skipping header " << file << "...", INFO);
} else {
DEBUG("Compiling header " << file << "...", NORMAL);
DEBUG("Command line: " << cmd, INFO);
if (!group.spawn(saveShellProcess(pchFile, cmd, wd, &env))) {
return false;
}
// Wait for it to complete...
if (!group.wait()) {
return false;
}
}
}
String cmd;
if (combinedPch && src.isPch)
cmd = config.getStr("pchCompile");
else
cmd = chooseCompile(file);
if (cmd == "") {
PLN("No suitable compile command-line for " << file);
return false;
}
data["file"] = preparePath(src);
data["output"] = out;
cmd = config.expandVars(cmd, data);
if (skip && commands.check(file, cmd)) {
DEBUG("Skipping " << file << "...", INFO);
DEBUG("Source modified: " << lastModified << ", output modified " << output.mTime(), DEBUG);
} else {
DEBUG("Compiling " << file << "...", NORMAL);
DEBUG("Command line: " << cmd, INFO);
if (!group.spawn(saveShellProcess(file, cmd, wd, &env)))
return false;
// If it is a pch, wait for it to finish.
if (src.isPch) {
if (!group.wait())
return false;
}
}
// Update 'last modified'. We always want to do this, even if we did not need to compile the file.
if (i == 0)
latestModified = lastModified;
else
latestModified = max(latestModified, lastModified);
}
// Wait for compilation to terminate.
if (!group.wait())
return false;
vector<String> libs = config.getArray("localLibrary");
for (nat i = 0; i < libs.size(); i++) {
Path libPath(libs[i]);
if (libPath.exists()) {
latestModified = max(latestModified, libPath.mTime());
} else {
WARNING("Local library " << libPath << " not found. Use 'library' for system libraries.");
}
}
// Link the output.
bool skipLink = !force && output.mTime() >= latestModified;
String finalOutput = toS(output.makeRelative(wd));
data["files"] = intermediateFiles.str();
data["output"] = finalOutput;
vector<String> linkCmds = config.getArray("link");
std::ostringstream allCmds;
for (nat i = 0; i < linkCmds.size(); i++) {
linkCmds[i] = config.expandVars(linkCmds[i], data);
if (i > 0)
allCmds << ";";
allCmds << linkCmds[i];
}
if (skipLink && commands.check(finalOutput, allCmds.str())) {
DEBUG("Skipping linking.", INFO);
DEBUG("Output modified " << output.mTime() << ", input modified " << latestModified, DEBUG);
return true;
}
DEBUG("Linking " << output.title() << "...", NORMAL);
for (nat i = 0; i < linkCmds.size(); i++) {
const String &cmd = linkCmds[i];
DEBUG("Command line: " << cmd, INFO);
if (!group.spawn(shellProcess(cmd, wd, &env)))
return false;
if (!group.wait())
return false;
}
commands.set(finalOutput, allCmds.str());
{
// Run post-build steps.
map<String, String> stepData;
stepData["output"] = data["output"];
if (!runSteps("postBuild", group, env, stepData))
return false;
}
return true;
}
String Target::preparePath(const Path &file) {
if (absolutePath) {
return toS(file.makeAbsolute(wd));
} else {
return toS(file.makeRelative(wd));
}
}
bool Target::ignored(const String &file) {
for (nat j = 0; j < ignore.size(); j++) {
if (ignore[j].matches(file)) {
DEBUG("Ignoring " << file << " as per " << ignore[j], INFO);
return true;
}
}
return false;
}
bool Target::runSteps(const String &key, ProcGroup &group, const Env &env, const map<String, String> &options) {
vector<String> steps = config.getArray(key);
for (nat i = 0; i < steps.size(); i++) {
String expanded = config.expandVars(steps[i], options);
DEBUG("Running " << expanded, INFO);
if (!group.spawn(shellProcess(expanded, wd, &env))) {
PLN("Failed running " << key << ": " << expanded);
return false;
}
if (!group.wait()) {
PLN("Failed running " << key << ": " << expanded);
return false;
}
}
return true;
}
void Target::save() const {
includes.save(buildDir + "includes");
commands.save(buildDir + "commands");
}
int Target::execute(const vector<String> ¶ms) const {
if (!config.getBool("execute"))
return 0;
Path execPath = wd;
if (config.has("execPath")) {
execPath = Path(config.getStr("execPath")).makeAbsolute(wd);
}
DEBUG("Executing " << output.makeRelative(execPath) << " " << join(params) << " in " << execPath, INFO);
return exec(output, params, execPath, null);
}
void Target::addLib(const Path &p) {
config.add("localLibrary", toS(p));
}
vector<Path> Target::findExt(const Path &path, ExtCache &cache) {
// Earlier implementation did way too many queries for files, and has therefore been optimized.
// for (nat i = 0; i < validExts.size(); i++) {
// path.makeExt(validExts[i]);
// if (path.exists())
// return true;
// }
const vector<String> &exts = cache.find(path);
vector<Path> result;
for (nat i = 0; i < exts.size(); i++) {
result.push_back(path);
result.back().makeExt(exts[i]);
}
if (!appendExt && result.size() > 1) {
WARNING("Multiple files with the same name scheduled for compilation.");
PLN("This leads to a name collision in the temporary files, leading to");
PLN("incorrect compilation, and probably also linker errors.");
PLN("If you intend to compile all files below, add 'appendExt=yes' to this target.");
PLN("Colliding files:\n" << join(result, "\n"));
}
return result;
}
void Target::addFiles(CompileQueue &to, ExtCache &cache, const vector<String> &src) {
for (nat i = 0; i < src.size(); i++) {
addFile(to, cache, src[i], false);
}
}
void Target::addFilesRecursive(CompileQueue &to, const Path &at) {
vector<Path> children = at.children();
for (nat i = 0; i < children.size(); i++) {
if (children[i].isDir()) {
DEBUG("Found directory " << children[i], DEBUG);
addFilesRecursive(to, children[i]);
} else {
DEBUG("Found file " << children[i], DEBUG);
if (std::find(validExts.begin(), validExts.end(), children[i].ext()) != validExts.end()) {
DEBUG("Adding file " << children[i], VERBOSE);
to << Compile(children[i], false, true);
}
}
}
}
bool Target::addFile(CompileQueue &to, ExtCache &cache, const String &src, bool pch) {
if (src.empty())
return false;
if (src == "*") {
addFilesRecursive(to, wd);
return true;
}
Path path(src);
path = path.makeAbsolute(wd);
vector<Path> exts = findExt(path, cache);
if (exts.empty()) {
WARNING("The file " << src << " does not exist with any of the extensions " << join(validExts));
return false;
}
for (nat i = 0; i < exts.size(); i++) {
to.push(Compile(exts[i], pch, false));
}
return true;
}
void Target::addFile(CompileQueue &to, ExtCache &cache, const Path &header) {
vector<Path> exts = findExt(header, cache);
// No big deal if no cpp file is found for every h file.
for (nat i = 0; i < exts.size(); i++) {
to.push(Compile(exts[i], false, true));
}
}
void Target::addPreBuildFiles(CompileQueue &to, const vector<String> &src) {
for (nat i = 0; i < src.size(); i++)
addPreBuildFile(to, src[i]);
}
void Target::addPreBuildFile(CompileQueue &to, const String &src) {
Path path = Path(src).makeAbsolute(wd);
to.push(Compile(path, false, true));
}
String Target::chooseCompile(const String &file) {
for (nat i = compileVariants.size(); i > 0; i--) {
const String &variant = compileVariants[i - 1];
nat colon = variant.find(':');
if (colon == String::npos) {
WARNING("Compile variable without telling what filetypes it is for: " << variant);
continue;
}
Wildcard w(variant.substr(0, colon));
if (w.matches(file))
return variant.substr(colon + 1);
DEBUG("No match for " << file << " using " << variant, INFO);
}
return "";
}
}
| 15,269 | 5,966 |
#include "../common/common.hpp"
#include <edyn/sys/integrate_linvel.hpp>
TEST(integrate_linvel, test) {
entt::registry registry;
auto e0 = registry.create();
auto e1 = registry.create();
auto e2 = registry.create();
auto& p0 = registry.emplace<edyn::position>(e0, 2.f, 3.f, 4.f);
const auto p0_0 = p0;
auto& p1 = registry.emplace<edyn::position>(e1, -2.f, -3.f, -5.1f);
const auto p1_0 = p1;
registry.emplace<edyn::linvel>(e1, -0.33f, -0.5f, -0.1f);
registry.emplace<edyn::linvel>(e2, -0.12f, -0.99f, 0.12f);
// Only dynamic entities have their position updated.
registry.emplace<edyn::dynamic_tag>(e0);
registry.emplace<edyn::dynamic_tag>(e1);
registry.emplace<edyn::dynamic_tag>(e2);
const edyn::scalar dt = 0.1666f;
const size_t n = 3;
for (size_t i = 0; i < n; ++i) {
edyn::integrate_linvel(registry, dt);
}
auto& p0_1 = registry.get<edyn::position>(e0);
auto& p1_1 = registry.get<edyn::position>(e1);
auto& v1 = registry.get<edyn::linvel>(e1);
ASSERT_EQ(p0_1, p0_0); // e0 has no velocity, thus unchanged
ASSERT_SCALAR_EQ(p1_1.x, (p1_0 + v1 * dt * n).x);
ASSERT_SCALAR_EQ(p1_1.y, (p1_0 + v1 * dt * n).y);
ASSERT_SCALAR_EQ(p1_1.z, (p1_0 + v1 * dt * n).z);
} | 1,278 | 580 |
#include <iostream>
#include <cstring>
using namespace std;
struct stringy
{
char *str;
int ct;
};
void set(stringy &stry, char *str);
void show(const stringy &stry, int times = 1);
void show(const char *str, int times = 1);
int main()
{
stringy beany;
char testing[] = "Reality isn't what it uesd to be.";
set(beany, testing);
show(beany);
show(beany, 2);
testing[0] = 'D';
testing[1] = 'u';
show(testing);
show(testing, 3);
show("Done");
return 0;
}
void set(stringy &stry, char *str)
{
int len = strlen(str);
char *copy = new char[len];
strcpy(copy, str);
stry.ct = len;
stry.str = copy;
}
void show(const stringy &stry, int times)
{
for (int i = 0; i < times; i++)
{
cout << stry.str << endl;
}
}
void show(const char *str, int times)
{
for (int i = 0; i < times; i++)
{
cout << str << endl;
}
}
| 922 | 367 |
/*
* Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include "AVSCommon/Utils/MediaPlayer/MediaPlayerObserverInterface.h"
#include "AVSCommon/Utils/MediaPlayer/MockMediaPlayer.h"
namespace alexaClientSDK {
namespace avsCommon {
namespace utils {
namespace mediaPlayer {
namespace test {
using namespace testing;
const static std::chrono::milliseconds WAIT_LOOP_INTERVAL{1};
std::shared_ptr<NiceMock<MockMediaPlayer>> MockMediaPlayer::create() {
auto result = std::make_shared<NiceMock<MockMediaPlayer>>();
ON_CALL(*result.get(), attachmentSetSource(_, _))
.WillByDefault(InvokeWithoutArgs(result.get(), &MockMediaPlayer::mockSetSource));
ON_CALL(*result.get(), urlSetSource(_))
.WillByDefault(InvokeWithoutArgs(result.get(), &MockMediaPlayer::mockSetSource));
ON_CALL(*result.get(), streamSetSource(_, _))
.WillByDefault(InvokeWithoutArgs(result.get(), &MockMediaPlayer::mockSetSource));
ON_CALL(*result.get(), play(_)).WillByDefault(Invoke(result.get(), &MockMediaPlayer::mockPlay));
ON_CALL(*result.get(), stop(_)).WillByDefault(Invoke(result.get(), &MockMediaPlayer::mockStop));
ON_CALL(*result.get(), pause(_)).WillByDefault(Invoke(result.get(), &MockMediaPlayer::mockPause));
ON_CALL(*result.get(), resume(_)).WillByDefault(Invoke(result.get(), &MockMediaPlayer::mockResume));
ON_CALL(*result.get(), getOffset(_)).WillByDefault(Invoke(result.get(), &MockMediaPlayer::mockGetOffset));
return result;
}
MockMediaPlayer::MockMediaPlayer() : RequiresShutdown{"MockMediaPlayer"}, m_playerObserver{nullptr} {
// Create a 'source' for sourceId = 0
mockSetSource();
}
MediaPlayerInterface::SourceId MockMediaPlayer::setSource(
std::shared_ptr<avsCommon::avs::attachment::AttachmentReader> attachmentReader,
const avsCommon::utils::AudioFormat* audioFormat) {
return attachmentSetSource(attachmentReader, audioFormat);
}
MediaPlayerInterface::SourceId MockMediaPlayer::setSource(
const std::string& url,
std::chrono::milliseconds offset,
bool repeat) {
return urlSetSource(url);
}
MediaPlayerInterface::SourceId MockMediaPlayer::setSource(std::shared_ptr<std::istream> stream, bool repeat) {
return streamSetSource(stream, repeat);
}
void MockMediaPlayer::setObserver(std::shared_ptr<MediaPlayerObserverInterface> playerObserver) {
m_playerObserver = playerObserver;
}
std::shared_ptr<MediaPlayerObserverInterface> MockMediaPlayer::getObserver() const {
return m_playerObserver;
}
void MockMediaPlayer::doShutdown() {
std::lock_guard<std::mutex> lock(m_mutex);
m_playerObserver.reset();
m_sources.clear();
}
MediaPlayerInterface::SourceId MockMediaPlayer::mockSetSource() {
std::lock_guard<std::mutex> lock(m_mutex);
SourceId result = m_sources.size();
m_sources.emplace_back(std::make_shared<Source>(this, result));
return result;
}
bool MockMediaPlayer::mockPlay(SourceId sourceId) {
auto source = getCurrentSource(sourceId);
if (!source) {
return false;
}
EXPECT_TRUE(source->stopwatch.start());
source->started.trigger();
return true;
}
bool MockMediaPlayer::mockPause(SourceId sourceId) {
auto source = getCurrentSource(sourceId);
if (!source) {
return false;
}
// Ideally we would EXPECT_TRUE on pause(), however ACSDK-734 doesn't guarantee that will be okay.
source->stopwatch.pause();
source->resumed.resetStateReached();
source->paused.trigger();
return true;
}
bool MockMediaPlayer::mockResume(SourceId sourceId) {
auto source = getCurrentSource(sourceId);
if (!source) {
return false;
}
EXPECT_TRUE(source->stopwatch.resume());
source->paused.resetStateReached();
source->resumed.trigger();
return true;
}
bool MockMediaPlayer::mockStop(SourceId sourceId) {
auto source = getCurrentSource(sourceId);
if (!source) {
return false;
}
source->stopwatch.stop();
source->stopped.trigger();
return true;
}
bool MockMediaPlayer::mockFinished(SourceId sourceId) {
auto source = getCurrentSource(sourceId);
if (!source) {
return false;
}
source->stopwatch.stop();
source->finished.trigger();
return true;
}
bool MockMediaPlayer::mockError(SourceId sourceId) {
auto source = getCurrentSource(sourceId);
if (!source) {
return false;
}
source->stopwatch.stop();
source->error.trigger();
return true;
}
bool MockMediaPlayer::mockSetOffset(SourceId sourceId, std::chrono::milliseconds offset) {
auto source = getCurrentSource(sourceId);
if (!source) {
return false;
}
std::lock_guard<std::mutex> lock(m_mutex);
source->offset = offset;
return true;
}
std::chrono::milliseconds MockMediaPlayer::mockGetOffset(SourceId sourceId) {
auto source = getCurrentSource(sourceId);
if (!source) {
return MEDIA_PLAYER_INVALID_OFFSET;
}
return source->stopwatch.getElapsed() + source->offset;
}
bool MockMediaPlayer::waitUntilNextSetSource(const std::chrono::milliseconds timeout) {
auto originalSourceId = getCurrentSourceId();
auto timeLimit = std::chrono::steady_clock::now() + timeout;
while (std::chrono::steady_clock::now() < timeLimit) {
if (getCurrentSourceId() != originalSourceId) {
return true;
}
std::this_thread::sleep_for(WAIT_LOOP_INTERVAL);
}
return false;
}
bool MockMediaPlayer::waitUntilPlaybackStarted(std::chrono::milliseconds timeout) {
return m_sources[getCurrentSourceId()]->started.wait(timeout);
}
bool MockMediaPlayer::waitUntilPlaybackPaused(std::chrono::milliseconds timeout) {
return m_sources[getCurrentSourceId()]->paused.wait(timeout);
}
bool MockMediaPlayer::waitUntilPlaybackResumed(std::chrono::milliseconds timeout) {
return m_sources[getCurrentSourceId()]->resumed.wait(timeout);
}
bool MockMediaPlayer::waitUntilPlaybackStopped(std::chrono::milliseconds timeout) {
return m_sources[getCurrentSourceId()]->stopped.wait(timeout);
}
bool MockMediaPlayer::waitUntilPlaybackFinished(std::chrono::milliseconds timeout) {
return m_sources[getCurrentSourceId()]->finished.wait(timeout);
}
bool MockMediaPlayer::waitUntilPlaybackError(std::chrono::milliseconds timeout) {
return m_sources[getCurrentSourceId()]->error.wait(timeout);
}
MediaPlayerInterface::SourceId MockMediaPlayer::getCurrentSourceId() {
std::unique_lock<std::mutex> lock(m_mutex);
return m_sources.size() - 1;
}
MockMediaPlayer::SourceState::SourceState(
Source* source,
const std::string& name,
std::function<void(std::shared_ptr<observer>, SourceId)> notifyFunction) :
m_source{source},
m_name{name},
m_notifyFunction{notifyFunction},
m_stateReached{false},
m_shutdown{false} {
}
MockMediaPlayer::SourceState::~SourceState() {
{
std::lock_guard<std::mutex> lock(m_mutex);
m_shutdown = true;
}
m_wake.notify_all();
if (m_thread.joinable()) {
m_thread.join();
}
}
void MockMediaPlayer::SourceState::trigger() {
std::lock_guard<std::mutex> lock(m_mutex);
if (m_stateReached) {
return;
}
m_thread = std::thread(&MockMediaPlayer::SourceState::notify, this, DEFAULT_TIME);
m_stateReached = true;
m_wake.notify_all();
}
void MockMediaPlayer::SourceState::notify(const std::chrono::milliseconds timeout) {
std::unique_lock<std::mutex> lock(m_mutex);
auto observer = m_source->mockMediaPlayer->m_playerObserver;
if (!m_wake.wait_for(lock, timeout, [this]() { return (m_stateReached || m_shutdown); })) {
if (observer) {
lock.unlock();
observer->onPlaybackError(
m_source->sourceId, ErrorType::MEDIA_ERROR_UNKNOWN, m_name + ": wait to notify timed out");
}
return;
}
if (observer) {
m_notifyFunction(observer, m_source->sourceId);
}
return;
}
bool MockMediaPlayer::SourceState::wait(const std::chrono::milliseconds timeout) {
std::unique_lock<std::mutex> lock(m_mutex);
if (!m_wake.wait_for(lock, timeout, [this]() { return (m_stateReached || m_shutdown); })) {
return false;
}
return m_stateReached;
}
void MockMediaPlayer::SourceState::resetStateReached() {
if (m_thread.joinable()) {
m_thread.join();
}
std::unique_lock<std::mutex> lock(m_mutex);
m_stateReached = false;
}
static void notifyPlaybackStarted(
std::shared_ptr<MediaPlayerObserverInterface> observer,
MediaPlayerInterface::SourceId sourceId) {
observer->onPlaybackStarted(sourceId);
}
static void notifyPlaybackPaused(
std::shared_ptr<MediaPlayerObserverInterface> observer,
MediaPlayerInterface::SourceId sourceId) {
observer->onPlaybackPaused(sourceId);
}
static void notifyPlaybackResumed(
std::shared_ptr<MediaPlayerObserverInterface> observer,
MediaPlayerInterface::SourceId sourceId) {
observer->onPlaybackResumed(sourceId);
}
static void notifyPlaybackStopped(
std::shared_ptr<MediaPlayerObserverInterface> observer,
MediaPlayerInterface::SourceId sourceId) {
observer->onPlaybackStopped(sourceId);
}
static void notifyPlaybackFinished(
std::shared_ptr<MediaPlayerObserverInterface> observer,
MediaPlayerInterface::SourceId sourceId) {
observer->onPlaybackFinished(sourceId);
}
static void notifyPlaybackError(
std::shared_ptr<MediaPlayerObserverInterface> observer,
MediaPlayerInterface::SourceId sourceId) {
observer->onPlaybackError(sourceId, ErrorType::MEDIA_ERROR_INTERNAL_SERVER_ERROR, "mock error");
}
MockMediaPlayer::Source::Source(MockMediaPlayer* player, SourceId id) :
mockMediaPlayer{player},
sourceId{id},
offset{MEDIA_PLAYER_INVALID_OFFSET},
started{this, "started", notifyPlaybackStarted},
paused{this, "paused", notifyPlaybackPaused},
resumed{this, "resumed", notifyPlaybackResumed},
stopped{this, "stopped", notifyPlaybackStopped},
finished{this, "finished", notifyPlaybackFinished},
error{this, "error", notifyPlaybackError} {
}
std::shared_ptr<MockMediaPlayer::Source> MockMediaPlayer::getCurrentSource(SourceId sourceId) {
if (ERROR == sourceId || sourceId != getCurrentSourceId()) {
return nullptr;
}
return m_sources[static_cast<size_t>(sourceId)];
}
} // namespace test
} // namespace mediaPlayer
} // namespace utils
} // namespace avsCommon
} // namespace alexaClientSDK
| 11,056 | 3,430 |
// Copyright (c) 2013-2017, Matt Godbolt
// 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.
//
// 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.
#include "seasocks/StringUtil.h"
#include <cctype>
#include <cerrno>
#include <cstddef>
#include <cstdio>
#include <cstring>
namespace seasocks {
char* skipWhitespace(char* str) {
while (isspace(*str)) ++str;
return str;
}
char* skipNonWhitespace(char* str) {
while (*str && !isspace(*str)) {
++str;
}
return str;
}
char* shift(char*& str) {
if (str == nullptr) {
return nullptr;
}
char* startOfWord = skipWhitespace(str);
if (*startOfWord == 0) {
str = startOfWord;
return nullptr;
}
char* endOfWord = skipNonWhitespace(startOfWord);
if (*endOfWord != 0) {
*endOfWord++ = 0;
}
str = endOfWord;
return startOfWord;
}
std::string trimWhitespace(const std::string& str) {
auto* start = str.c_str();
while (isspace(*start)) ++start;
auto* end = &str.back();
while (end >= start && isspace(*end)) --end;
return std::string(start, end - start + 1);
}
std::string getLastError(){
char errbuf[1024];
return strerror_r(errno, errbuf, sizeof(errbuf));
}
std::string formatAddress(const sockaddr_in& address) {
char ipBuffer[24];
sprintf(ipBuffer,
"%d.%d.%d.%d:%d",
(address.sin_addr.s_addr >> 0) & 0xff,
(address.sin_addr.s_addr >> 8) & 0xff,
(address.sin_addr.s_addr >> 16) & 0xff,
(address.sin_addr.s_addr >> 24) & 0xff,
htons(address.sin_port));
return ipBuffer;
}
std::vector<std::string> split(const std::string& input, char splitChar) {
if (input.empty()) return std::vector<std::string>();
std::vector<std::string> result;
size_t pos = 0;
size_t newPos;
while ((newPos = input.find(splitChar, pos)) != std::string::npos) {
result.push_back(input.substr(pos, newPos - pos));
pos = newPos + 1;
}
result.push_back(input.substr(pos));
return result;
}
void replace(std::string& string, const std::string& find,
const std::string& replace) {
size_t pos = 0;
const size_t findLen = find.length();
const size_t replaceLen = replace.length();
while ((pos = string.find(find, pos)) != std::string::npos) {
string = string.substr(0, pos) + replace + string.substr(pos + findLen);
pos += replaceLen;
}
}
bool caseInsensitiveSame(const std::string &lhs, const std::string &rhs) {
return strcasecmp(lhs.c_str(), rhs.c_str()) == 0;
}
std::string webtime(time_t time) {
struct tm tm;
gmtime_r(&time, &tm);
char buf[1024];
// Wed, 20 Apr 2011 17:31:28 GMT
strftime(buf, sizeof(buf)-1, "%a, %d %b %Y %H:%M:%S %Z", &tm);
return buf;
}
std::string now() {
return webtime(time(nullptr));
}
}
| 4,085 | 1,508 |
// Copyright (c) 1999-2018 David Muse
// See the file COPYING for more information
#include <sqlrelay/sqlrserver.h>
#include <rudiments/domnode.h>
#include <rudiments/stdio.h>
//#define DEBUG_MESSAGES 1
#include <rudiments/debugprint.h>
#include <config.h>
#ifndef SQLRELAY_ENABLE_SHARED
extern "C" {
#include "sqlrquerydeclarations.cpp"
}
#endif
class sqlrqueryplugin {
public:
sqlrquery *qr;
dynamiclib *dl;
};
class sqlrqueriesprivate {
friend class sqlrqueries;
private:
sqlrservercontroller *_cont;
singlylinkedlist< sqlrqueryplugin * > _llist;
};
sqlrqueries::sqlrqueries(sqlrservercontroller *cont) {
debugFunction();
pvt=new sqlrqueriesprivate;
pvt->_cont=cont;
}
sqlrqueries::~sqlrqueries() {
debugFunction();
unload();
delete pvt;
}
bool sqlrqueries::load(domnode *parameters) {
debugFunction();
unload();
// run through the query list
for (domnode *query=parameters->getFirstTagChild();
!query->isNullNode(); query=query->getNextTagSibling()) {
debugPrintf("loading query ...\n");
// load query
loadQuery(query);
}
return true;
}
void sqlrqueries::unload() {
debugFunction();
for (listnode< sqlrqueryplugin * > *node=
pvt->_llist.getFirst();
node; node=node->getNext()) {
sqlrqueryplugin *sqlrlp=node->getValue();
delete sqlrlp->qr;
delete sqlrlp->dl;
delete sqlrlp;
}
pvt->_llist.clear();
}
void sqlrqueries::loadQuery(domnode *query) {
debugFunction();
// ignore non-queries
if (charstring::compare(query->getName(),"query")) {
return;
}
// get the query name
const char *module=query->getAttributeValue("module");
if (!charstring::length(module)) {
// try "file", that's what it used to be called
module=query->getAttributeValue("file");
if (!charstring::length(module)) {
return;
}
}
debugPrintf("loading query: %s\n",module);
#ifdef SQLRELAY_ENABLE_SHARED
// load the query module
stringbuffer modulename;
modulename.append(pvt->_cont->getPaths()->getLibExecDir());
modulename.append(SQLR);
modulename.append("query_");
modulename.append(module)->append(".")->append(SQLRELAY_MODULESUFFIX);
dynamiclib *dl=new dynamiclib();
if (!dl->open(modulename.getString(),true,true)) {
stdoutput.printf("failed to load query module: %s\n",module);
char *error=dl->getError();
stdoutput.printf("%s\n",(error)?error:"");
delete[] error;
delete dl;
return;
}
// load the query itself
stringbuffer functionname;
functionname.append("new_sqlrquery_")->append(module);
sqlrquery *(*newQuery)(sqlrservercontroller *,
sqlrqueries *,
domnode *)=
(sqlrquery *(*)(sqlrservercontroller *,
sqlrqueries *,
domnode *))
dl->getSymbol(functionname.getString());
if (!newQuery) {
stdoutput.printf("failed to load query: %s\n",module);
char *error=dl->getError();
stdoutput.printf("%s\n",(error)?error:"");
delete[] error;
dl->close();
delete dl;
return;
}
sqlrquery *qr=(*newQuery)(pvt->_cont,this,query);
#else
dynamiclib *dl=NULL;
sqlrquery *qr;
#include "sqlrqueryassignments.cpp"
{
qr=NULL;
}
#endif
// add the plugin to the list
sqlrqueryplugin *sqlrlp=new sqlrqueryplugin;
sqlrlp->qr=qr;
sqlrlp->dl=dl;
pvt->_llist.append(sqlrlp);
}
sqlrquerycursor *sqlrqueries::match(sqlrserverconnection *sqlrcon,
const char *querystring,
uint32_t querylength,
uint16_t id) {
debugFunction();
for (listnode< sqlrqueryplugin * > *node=
pvt->_llist.getFirst();
node; node=node->getNext()) {
sqlrquery *qr=node->getValue()->qr;
if (qr->match(querystring,querylength)) {
return qr->newCursor(sqlrcon,id);
}
}
return NULL;
}
void sqlrqueries::endTransaction(bool commit) {
for (listnode< sqlrqueryplugin * > *node=
pvt->_llist.getFirst();
node; node=node->getNext()) {
node->getValue()->qr->endTransaction(commit);
}
}
void sqlrqueries::endSession() {
for (listnode< sqlrqueryplugin * > *node=
pvt->_llist.getFirst();
node; node=node->getNext()) {
node->getValue()->qr->endSession();
}
}
| 4,026 | 1,641 |